New contributed modules org-mac-iCal.el by Christopher Suckling
[org-mode.git] / lisp / org.el
blob1eb5e74e670261e9695232de0b95585592daa305
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.27trans
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.27trans"
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 jira Add a jira:ticket protocol to Org" org-jira)
197 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
198 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
199 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
200 (const :tag "C mtags: Support for muse-like tags" org-mtags)
201 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
202 (const :tag "C R: Computation using the R language" org-R)
203 (const :tag "C registry: A registry for Org links" org-registry)
204 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
205 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
206 (const :tag "C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
207 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
208 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
209 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
211 (defcustom org-support-shift-select nil
212 "Non-nil means, make shift-cursor commands select text when possible.
214 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
215 selecting a region, or enlarge thusly regions started in this way.
216 In Org-mode, in special contexts, these same keys are used for other
217 purposes, important enough to compete with shift selection. Org tries
218 to balance these needs by supporting `shift-select-mode' outside these
219 special contexts, under control of this variable.
221 The default of this variable is nil, to avoid confusing behavior. Shifted
222 cursor keys will then execute Org commands in the following contexts:
223 - on a headline, changing TODO state (left/right) and priority (up/down)
224 - on a time stamp, changing the time
225 - in a plain list item, changing the bullet type
226 - in a property definition line, switching between allowed values
227 - in the BEGIN line of a clock table (changing the time block).
228 Outside these contexts, the commands will throw an error.
230 When this variable is t and the cursor is not in a special context,
231 Org-mode will support shift-selection for making and enlarging regions.
232 To make this more effective, the bullet cycling will no longer happen
233 anywhere in an item line, but only if the cursor is exactly on the bullet.
235 If you set this variable to the symbol `always', then the keys
236 will not be special in headlines, property lines, and item lines, to make
237 shift selection work there as well. If this is what you want, you can
238 use the following alternative commands: `C-c C-t' and `C-c ,' to
239 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
240 TODO sets, `C-c -' to cycle item bullet types, and properties can be
241 edited by hand or in column view.
243 However, when the cursor is on a timestamp, shift-cursor commands
244 will still edit the time stamp - this is just too good to give up.
246 XEmacs user should have this variable set to nil, because shift-select-mode
247 is Emacs 23 only."
248 :group 'org
249 :type '(choice
250 (const :tag "Never" nil)
251 (const :tag "When outside special context" t)
252 (const :tag "Everywhere except timestamps" always)))
254 (defgroup org-startup nil
255 "Options concerning startup of Org-mode."
256 :tag "Org Startup"
257 :group 'org)
259 (defcustom org-startup-folded t
260 "Non-nil means, entering Org-mode will switch to OVERVIEW.
261 This can also be configured on a per-file basis by adding one of
262 the following lines anywhere in the buffer:
264 #+STARTUP: fold
265 #+STARTUP: nofold
266 #+STARTUP: content"
267 :group 'org-startup
268 :type '(choice
269 (const :tag "nofold: show all" nil)
270 (const :tag "fold: overview" t)
271 (const :tag "content: all headlines" content)))
273 (defcustom org-startup-truncated t
274 "Non-nil means, entering Org-mode will set `truncate-lines'.
275 This is useful since some lines containing links can be very long and
276 uninteresting. Also tables look terrible when wrapped."
277 :group 'org-startup
278 :type 'boolean)
280 (defcustom org-startup-align-all-tables nil
281 "Non-nil means, align all tables when visiting a file.
282 This is useful when the column width in tables is forced with <N> cookies
283 in table fields. Such tables will look correct only after the first re-align.
284 This can also be configured on a per-file basis by adding one of
285 the following lines anywhere in the buffer:
286 #+STARTUP: align
287 #+STARTUP: noalign"
288 :group 'org-startup
289 :type 'boolean)
291 (defcustom org-insert-mode-line-in-empty-file nil
292 "Non-nil means insert the first line setting Org-mode in empty files.
293 When the function `org-mode' is called interactively in an empty file, this
294 normally means that the file name does not automatically trigger Org-mode.
295 To ensure that the file will always be in Org-mode in the future, a
296 line enforcing Org-mode will be inserted into the buffer, if this option
297 has been set."
298 :group 'org-startup
299 :type 'boolean)
301 (defcustom org-replace-disputed-keys nil
302 "Non-nil means use alternative key bindings for some keys.
303 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
304 These keys are also used by other packages like shift-selection-mode'
305 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
306 If you want to use Org-mode together with one of these other modes,
307 or more generally if you would like to move some Org-mode commands to
308 other keys, set this variable and configure the keys with the variable
309 `org-disputed-keys'.
311 This option is only relevant at load-time of Org-mode, and must be set
312 *before* org.el is loaded. Changing it requires a restart of Emacs to
313 become effective."
314 :group 'org-startup
315 :type 'boolean)
317 (defcustom org-use-extra-keys nil
318 "Non-nil means use extra key sequence definitions for certain
319 commands. This happens automatically if you run XEmacs or if
320 window-system is nil. This variable lets you do the same
321 manually. You must set it before loading org.
323 Example: on Carbon Emacs 22 running graphically, with an external
324 keyboard on a Powerbook, the default way of setting M-left might
325 not work for either Alt or ESC. Setting this variable will make
326 it work for ESC."
327 :group 'org-startup
328 :type 'boolean)
330 (if (fboundp 'defvaralias)
331 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
333 (defcustom org-disputed-keys
334 '(([(shift up)] . [(meta p)])
335 ([(shift down)] . [(meta n)])
336 ([(shift left)] . [(meta -)])
337 ([(shift right)] . [(meta +)])
338 ([(control shift right)] . [(meta shift +)])
339 ([(control shift left)] . [(meta shift -)]))
340 "Keys for which Org-mode and other modes compete.
341 This is an alist, cars are the default keys, second element specifies
342 the alternative to use when `org-replace-disputed-keys' is t.
344 Keys can be specified in any syntax supported by `define-key'.
345 The value of this option takes effect only at Org-mode's startup,
346 therefore you'll have to restart Emacs to apply it after changing."
347 :group 'org-startup
348 :type 'alist)
350 (defun org-key (key)
351 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
352 Or return the original if not disputed."
353 (if org-replace-disputed-keys
354 (let* ((nkey (key-description key))
355 (x (org-find-if (lambda (x)
356 (equal (key-description (car x)) nkey))
357 org-disputed-keys)))
358 (if x (cdr x) key))
359 key))
361 (defun org-find-if (predicate seq)
362 (catch 'exit
363 (while seq
364 (if (funcall predicate (car seq))
365 (throw 'exit (car seq))
366 (pop seq)))))
368 (defun org-defkey (keymap key def)
369 "Define a key, possibly translated, as returned by `org-key'."
370 (define-key keymap (org-key key) def))
372 (defcustom org-ellipsis nil
373 "The ellipsis to use in the Org-mode outline.
374 When nil, just use the standard three dots. When a string, use that instead,
375 When a face, use the standard 3 dots, but with the specified face.
376 The change affects only Org-mode (which will then use its own display table).
377 Changing this requires executing `M-x org-mode' in a buffer to become
378 effective."
379 :group 'org-startup
380 :type '(choice (const :tag "Default" nil)
381 (face :tag "Face" :value org-warning)
382 (string :tag "String" :value "...#")))
384 (defvar org-display-table nil
385 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
387 (defgroup org-keywords nil
388 "Keywords in Org-mode."
389 :tag "Org Keywords"
390 :group 'org)
392 (defcustom org-deadline-string "DEADLINE:"
393 "String to mark deadline entries.
394 A deadline is this string, followed by a time stamp. Should be a word,
395 terminated by a colon. You can insert a schedule keyword and
396 a timestamp with \\[org-deadline].
397 Changes become only effective after restarting Emacs."
398 :group 'org-keywords
399 :type 'string)
401 (defcustom org-scheduled-string "SCHEDULED:"
402 "String to mark scheduled TODO entries.
403 A schedule is this string, followed by a time stamp. Should be a word,
404 terminated by a colon. You can insert a schedule keyword and
405 a timestamp with \\[org-schedule].
406 Changes become only effective after restarting Emacs."
407 :group 'org-keywords
408 :type 'string)
410 (defcustom org-closed-string "CLOSED:"
411 "String used as the prefix for timestamps logging closing a TODO entry."
412 :group 'org-keywords
413 :type 'string)
415 (defcustom org-clock-string "CLOCK:"
416 "String used as prefix for timestamps clocking work hours on an item."
417 :group 'org-keywords
418 :type 'string)
420 (defcustom org-comment-string "COMMENT"
421 "Entries starting with this keyword will never be exported.
422 An entry can be toggled between COMMENT and normal with
423 \\[org-toggle-comment].
424 Changes become only effective after restarting Emacs."
425 :group 'org-keywords
426 :type 'string)
428 (defcustom org-quote-string "QUOTE"
429 "Entries starting with this keyword will be exported in fixed-width font.
430 Quoting applies only to the text in the entry following the headline, and does
431 not extend beyond the next headline, even if that is lower level.
432 An entry can be toggled between QUOTE and normal with
433 \\[org-toggle-fixed-width-section]."
434 :group 'org-keywords
435 :type 'string)
437 (defconst org-repeat-re
438 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
439 "Regular expression for specifying repeated events.
440 After a match, group 1 contains the repeat expression.")
442 (defgroup org-structure nil
443 "Options concerning the general structure of Org-mode files."
444 :tag "Org Structure"
445 :group 'org)
447 (defgroup org-reveal-location nil
448 "Options about how to make context of a location visible."
449 :tag "Org Reveal Location"
450 :group 'org-structure)
452 (defconst org-context-choice
453 '(choice
454 (const :tag "Always" t)
455 (const :tag "Never" nil)
456 (repeat :greedy t :tag "Individual contexts"
457 (cons
458 (choice :tag "Context"
459 (const agenda)
460 (const org-goto)
461 (const occur-tree)
462 (const tags-tree)
463 (const link-search)
464 (const mark-goto)
465 (const bookmark-jump)
466 (const isearch)
467 (const default))
468 (boolean))))
469 "Contexts for the reveal options.")
471 (defcustom org-show-hierarchy-above '((default . t))
472 "Non-nil means, show full hierarchy when revealing a location.
473 Org-mode often shows locations in an org-mode file which might have
474 been invisible before. When this is set, the hierarchy of headings
475 above the exposed location is shown.
476 Turning this off for example for sparse trees makes them very compact.
477 Instead of t, this can also be an alist specifying this option for different
478 contexts. Valid contexts are
479 agenda when exposing an entry from the agenda
480 org-goto when using the command `org-goto' on key C-c C-j
481 occur-tree when using the command `org-occur' on key C-c /
482 tags-tree when constructing a sparse tree based on tags matches
483 link-search when exposing search matches associated with a link
484 mark-goto when exposing the jump goal of a mark
485 bookmark-jump when exposing a bookmark location
486 isearch when exiting from an incremental search
487 default default for all contexts not set explicitly"
488 :group 'org-reveal-location
489 :type org-context-choice)
491 (defcustom org-show-following-heading '((default . nil))
492 "Non-nil means, show following heading when revealing a location.
493 Org-mode often shows locations in an org-mode file which might have
494 been invisible before. When this is set, the heading following the
495 match is shown.
496 Turning this off for example for sparse trees makes them very compact,
497 but makes it harder to edit the location of the match. In such a case,
498 use the command \\[org-reveal] to show more context.
499 Instead of t, this can also be an alist specifying this option for different
500 contexts. See `org-show-hierarchy-above' for valid contexts."
501 :group 'org-reveal-location
502 :type org-context-choice)
504 (defcustom org-show-siblings '((default . nil) (isearch t))
505 "Non-nil means, show all sibling heading when revealing a location.
506 Org-mode often shows locations in an org-mode file which might have
507 been invisible before. When this is set, the sibling of the current entry
508 heading are all made visible. If `org-show-hierarchy-above' is t,
509 the same happens on each level of the hierarchy above the current entry.
511 By default this is on for the isearch context, off for all other contexts.
512 Turning this off for example for sparse trees makes them very compact,
513 but makes it harder to edit the location of the match. In such a case,
514 use the command \\[org-reveal] to show more context.
515 Instead of t, this can also be an alist specifying this option for different
516 contexts. See `org-show-hierarchy-above' for valid contexts."
517 :group 'org-reveal-location
518 :type org-context-choice)
520 (defcustom org-show-entry-below '((default . nil))
521 "Non-nil means, show the entry below a headline when revealing a location.
522 Org-mode often shows locations in an org-mode file which might have
523 been invisible before. When this is set, the text below the headline that is
524 exposed is also shown.
526 By default this is off for all contexts.
527 Instead of t, this can also be an alist specifying this option for different
528 contexts. See `org-show-hierarchy-above' for valid contexts."
529 :group 'org-reveal-location
530 :type org-context-choice)
532 (defcustom org-indirect-buffer-display 'other-window
533 "How should indirect tree buffers be displayed?
534 This applies to indirect buffers created with the commands
535 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
536 Valid values are:
537 current-window Display in the current window
538 other-window Just display in another window.
539 dedicated-frame Create one new frame, and re-use it each time.
540 new-frame Make a new frame each time. Note that in this case
541 previously-made indirect buffers are kept, and you need to
542 kill these buffers yourself."
543 :group 'org-structure
544 :group 'org-agenda-windows
545 :type '(choice
546 (const :tag "In current window" current-window)
547 (const :tag "In current frame, other window" other-window)
548 (const :tag "Each time a new frame" new-frame)
549 (const :tag "One dedicated frame" dedicated-frame)))
551 (defgroup org-cycle nil
552 "Options concerning visibility cycling in Org-mode."
553 :tag "Org Cycle"
554 :group 'org-structure)
556 (defcustom org-cycle-max-level nil
557 "Maximum level which should still be subject to visibility cycling.
558 Levels higher than this will, for cycling, be treated as text, not a headline.
559 When `org-odd-levels-only' is set, a value of N in this variable actually
560 means 2N-1 stars as the limiting headline.
561 When nil, cycle all levels.
562 Note that the limiting level of cycling is also influenced by
563 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
564 `org-inlinetask-min-level' is, cycling will be limited to levels one less
565 than its value."
566 :group 'org-cycle
567 :type '(choice
568 (const :tag "No limit" nil)
569 (integer :tag "Maximum level")))
571 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
572 "Names of drawers. Drawers are not opened by cycling on the headline above.
573 Drawers only open with a TAB on the drawer line itself. A drawer looks like
574 this:
575 :DRAWERNAME:
576 .....
577 :END:
578 The drawer \"PROPERTIES\" is special for capturing properties through
579 the property API.
581 Drawers can be defined on the per-file basis with a line like:
583 #+DRAWERS: HIDDEN STATE PROPERTIES"
584 :group 'org-structure
585 :group 'org-cycle
586 :type '(repeat (string :tag "Drawer Name")))
588 (defcustom org-hide-block-startup nil
589 "Non-nil means, , entering Org-mode will fold all blocks.
590 This can also be set in on a per-file basis with
592 #+STARTUP: hideblocks
593 #+STARTUP: showblocks"
594 :group 'org-startup
595 :group 'org-cycle
596 :type 'boolean)
598 (defcustom org-cycle-global-at-bob nil
599 "Cycle globally if cursor is at beginning of buffer and not at a headline.
600 This makes it possible to do global cycling without having to use S-TAB or
601 C-u TAB. For this special case to work, the first line of the buffer
602 must not be a headline - it may be empty or some other text. When used in
603 this way, `org-cycle-hook' is disables temporarily, to make sure the
604 cursor stays at the beginning of the buffer.
605 When this option is nil, don't do anything special at the beginning
606 of the buffer."
607 :group 'org-cycle
608 :type 'boolean)
610 (defcustom org-cycle-emulate-tab t
611 "Where should `org-cycle' emulate TAB.
612 nil Never
613 white Only in completely white lines
614 whitestart Only at the beginning of lines, before the first non-white char
615 t Everywhere except in headlines
616 exc-hl-bol Everywhere except at the start of a headline
617 If TAB is used in a place where it does not emulate TAB, the current subtree
618 visibility is cycled."
619 :group 'org-cycle
620 :type '(choice (const :tag "Never" nil)
621 (const :tag "Only in completely white lines" white)
622 (const :tag "Before first char in a line" whitestart)
623 (const :tag "Everywhere except in headlines" t)
624 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
627 (defcustom org-cycle-separator-lines 2
628 "Number of empty lines needed to keep an empty line between collapsed trees.
629 If you leave an empty line between the end of a subtree and the following
630 headline, this empty line is hidden when the subtree is folded.
631 Org-mode will leave (exactly) one empty line visible if the number of
632 empty lines is equal or larger to the number given in this variable.
633 So the default 2 means, at least 2 empty lines after the end of a subtree
634 are needed to produce free space between a collapsed subtree and the
635 following headline.
637 Special case: when 0, never leave empty lines in collapsed view."
638 :group 'org-cycle
639 :type 'integer)
640 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
642 (defcustom org-pre-cycle-hook nil
643 "Hook that is run before visibility cycling is happening.
644 The function(s) in this hook must accept a single argument which indicates
645 the new state that will be set right after running this hook. The
646 argument is a symbol. Before a global state change, it can have the values
647 `overview', `content', or `all'. Before a local state change, it can have
648 the values `folded', `children', or `subtree'."
649 :group 'org-cycle
650 :type 'hook)
652 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
653 org-cycle-hide-drawers
654 org-cycle-show-empty-lines
655 org-optimize-window-after-visibility-change)
656 "Hook that is run after `org-cycle' has changed the buffer visibility.
657 The function(s) in this hook must accept a single argument which indicates
658 the new state that was set by the most recent `org-cycle' command. The
659 argument is a symbol. After a global state change, it can have the values
660 `overview', `content', or `all'. After a local state change, it can have
661 the values `folded', `children', or `subtree'."
662 :group 'org-cycle
663 :type 'hook)
665 (defgroup org-edit-structure nil
666 "Options concerning structure editing in Org-mode."
667 :tag "Org Edit Structure"
668 :group 'org-structure)
670 (defcustom org-odd-levels-only nil
671 "Non-nil means, skip even levels and only use odd levels for the outline.
672 This has the effect that two stars are being added/taken away in
673 promotion/demotion commands. It also influences how levels are
674 handled by the exporters.
675 Changing it requires restart of `font-lock-mode' to become effective
676 for fontification also in regions already fontified.
677 You may also set this on a per-file basis by adding one of the following
678 lines to the buffer:
680 #+STARTUP: odd
681 #+STARTUP: oddeven"
682 :group 'org-edit-structure
683 :group 'org-font-lock
684 :type 'boolean)
686 (defcustom org-adapt-indentation t
687 "Non-nil means, adapt indentation when promoting and demoting.
688 When this is set and the *entire* text in an entry is indented, the
689 indentation is increased by one space in a demotion command, and
690 decreased by one in a promotion command. If any line in the entry
691 body starts at column 0, indentation is not changed at all.
693 This variable also influences how property drawers and planning
694 information is inserted. When t, these lines drawers will be inserted
695 indented. When nil, they will not be indented."
696 :group 'org-edit-structure
697 :type 'boolean)
699 (defcustom org-special-ctrl-a/e nil
700 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
702 When t, `C-a' will bring back the cursor to the beginning of the
703 headline text, i.e. after the stars and after a possible TODO keyword.
704 In an item, this will be the position after the bullet.
705 When the cursor is already at that position, another `C-a' will bring
706 it to the beginning of the line.
708 `C-e' will jump to the end of the headline, ignoring the presence of tags
709 in the headline. A second `C-e' will then jump to the true end of the
710 line, after any tags.
712 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
713 and only a directly following, identical keypress will bring the cursor
714 to the special positions.
716 This may also be a cons cell where the behavior for `C-a' and `C-e' is
717 set separately."
718 :group 'org-edit-structure
719 :type '(choice
720 (const :tag "off" nil)
721 (const :tag "after stars/bullet and before tags first" t)
722 (const :tag "true line boundary first" reversed)
723 (cons :tag "Set C-a and C-e separately"
724 (choice :tag "Special C-a"
725 (const :tag "off" nil)
726 (const :tag "after stars/bullet first" t)
727 (const :tag "before stars/bullet first" reversed))
728 (choice :tag "Special C-e"
729 (const :tag "off" nil)
730 (const :tag "before tags first" t)
731 (const :tag "after tags first" reversed)))))
732 (if (fboundp 'defvaralias)
733 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
735 (defcustom org-special-ctrl-k nil
736 "Non-nil means `C-k' will behave specially in headlines.
737 When nil, `C-k' will call the default `kill-line' command.
738 When t, the following will happen while the cursor is in the headline:
740 - When the cursor is at the beginning of a headline, kill the entire
741 line and possible the folded subtree below the line.
742 - When in the middle of the headline text, kill the headline up to the tags.
743 - When after the headline text, kill the tags."
744 :group 'org-edit-structure
745 :type 'boolean)
747 (defcustom org-yank-folded-subtrees t
748 "Non-nil means, when yanking subtrees, fold them.
749 If the kill is a single subtree, or a sequence of subtrees, i.e. if
750 it starts with a heading and all other headings in it are either children
751 or siblings, then fold all the subtrees. However, do this only if no
752 text after the yank would be swallowed into a folded tree by this action."
753 :group 'org-edit-structure
754 :type 'boolean)
756 (defcustom org-yank-adjusted-subtrees nil
757 "Non-nil means, when yanking subtrees, adjust the level.
758 With this setting, `org-paste-subtree' is used to insert the subtree, see
759 this function for details."
760 :group 'org-edit-structure
761 :type 'boolean)
763 (defcustom org-M-RET-may-split-line '((default . t))
764 "Non-nil means, M-RET will split the line at the cursor position.
765 When nil, it will go to the end of the line before making a
766 new line.
767 You may also set this option in a different way for different
768 contexts. Valid contexts are:
770 headline when creating a new headline
771 item when creating a new item
772 table in a table field
773 default the value to be used for all contexts not explicitly
774 customized"
775 :group 'org-structure
776 :group 'org-table
777 :type '(choice
778 (const :tag "Always" t)
779 (const :tag "Never" nil)
780 (repeat :greedy t :tag "Individual contexts"
781 (cons
782 (choice :tag "Context"
783 (const headline)
784 (const item)
785 (const table)
786 (const default))
787 (boolean)))))
790 (defcustom org-insert-heading-respect-content nil
791 "Non-nil means, insert new headings after the current subtree.
792 When nil, the new heading is created directly after the current line.
793 The commands \\[org-insert-heading-respect-content] and
794 \\[org-insert-todo-heading-respect-content] turn this variable on
795 for the duration of the command."
796 :group 'org-structure
797 :type 'boolean)
799 (defcustom org-blank-before-new-entry '((heading . auto)
800 (plain-list-item . auto))
801 "Should `org-insert-heading' leave a blank line before new heading/item?
802 The value is an alist, with `heading' and `plain-list-item' as car,
803 and a boolean flag as cdr. For plain lists, if the variable
804 `org-empty-line-terminates-plain-lists' is set, the setting here
805 is ignored and no empty line is inserted, to keep the list in tact."
806 :group 'org-edit-structure
807 :type '(list
808 (cons (const heading)
809 (choice (const :tag "Never" nil)
810 (const :tag "Always" t)
811 (const :tag "Auto" auto)))
812 (cons (const plain-list-item)
813 (choice (const :tag "Never" nil)
814 (const :tag "Always" t)
815 (const :tag "Auto" auto)))))
817 (defcustom org-insert-heading-hook nil
818 "Hook being run after inserting a new heading."
819 :group 'org-edit-structure
820 :type 'hook)
822 (defcustom org-enable-fixed-width-editor t
823 "Non-nil means, lines starting with \":\" are treated as fixed-width.
824 This currently only means, they are never auto-wrapped.
825 When nil, such lines will be treated like ordinary lines.
826 See also the QUOTE keyword."
827 :group 'org-edit-structure
828 :type 'boolean)
830 (defcustom org-edit-src-region-extra nil
831 "Additional regexps to identify regions for editing with `org-edit-src-code'.
832 For examples see the function `org-edit-src-find-region-and-lang'.
833 The regular expression identifying the begin marker should end with a newline,
834 and the regexp marking the end line should start with a newline, to make sure
835 there are kept outside the narrowed region."
836 :group 'org-edit-structure
837 :type '(repeat
838 (list
839 (regexp :tag "begin regexp")
840 (regexp :tag "end regexp")
841 (choice :tag "language"
842 (string :tag "specify")
843 (integer :tag "from match group")
844 (const :tag "from `lang' element")
845 (const :tag "from `style' element")))))
847 (defcustom org-coderef-label-format "(ref:%s)"
848 "The default coderef format.
849 This format string will be used to search for coderef labels in literal
850 examples (EXAMPLE and SRC blocks). The format can be overwritten
851 an individual literal example with the -f option, like
853 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
855 #+END_SRC
857 If you want to use this for HTML export, make sure that the format does
858 not introduce special font-locking, and avoid the HTML special
859 characters `<', `>', and `&'. The reason for this restriction is that
860 the labels are searched for only after htmlize has done its job."
861 :group 'org-edit-structure ; FIXME this is not in the right group
862 :type 'string)
864 (defcustom org-edit-fixed-width-region-mode 'artist-mode
865 "The mode that should be used to edit fixed-width regions.
866 These are the regions where each line starts with a colon."
867 :group 'org-edit-structure
868 :type '(choice
869 (const artist-mode)
870 (const picture-mode)
871 (const fundamental-mode)
872 (function :tag "Other (specify)")))
874 (defcustom org-edit-src-persistent-message t
875 "Non-nil means show persistent exit help message while editing src examples.
876 The message is shown in the header-line, which will be created in the
877 first line of the window showing the editing buffer.
878 When nil, the message will only be shown intermittently in the echo area."
879 :group 'org-edit-structure
880 :type 'boolean)
882 (defcustom org-goto-auto-isearch t
883 "Non-nil means, typing characters in org-goto starts incremental search."
884 :group 'org-edit-structure
885 :type 'boolean)
887 (defgroup org-sparse-trees nil
888 "Options concerning sparse trees in Org-mode."
889 :tag "Org Sparse Trees"
890 :group 'org-structure)
892 (defcustom org-highlight-sparse-tree-matches t
893 "Non-nil means, highlight all matches that define a sparse tree.
894 The highlights will automatically disappear the next time the buffer is
895 changed by an edit command."
896 :group 'org-sparse-trees
897 :type 'boolean)
899 (defcustom org-remove-highlights-with-change t
900 "Non-nil means, any change to the buffer will remove temporary highlights.
901 Such highlights are created by `org-occur' and `org-clock-display'.
902 When nil, `C-c C-c needs to be used to get rid of the highlights.
903 The highlights created by `org-preview-latex-fragment' always need
904 `C-c C-c' to be removed."
905 :group 'org-sparse-trees
906 :group 'org-time
907 :type 'boolean)
910 (defcustom org-occur-hook '(org-first-headline-recenter)
911 "Hook that is run after `org-occur' has constructed a sparse tree.
912 This can be used to recenter the window to show as much of the structure
913 as possible."
914 :group 'org-sparse-trees
915 :type 'hook)
917 (defgroup org-imenu-and-speedbar nil
918 "Options concerning imenu and speedbar in Org-mode."
919 :tag "Org Imenu and Speedbar"
920 :group 'org-structure)
922 (defcustom org-imenu-depth 2
923 "The maximum level for Imenu access to Org-mode headlines.
924 This also applied for speedbar access."
925 :group 'org-imenu-and-speedbar
926 :type 'integer)
928 (defgroup org-table nil
929 "Options concerning tables in Org-mode."
930 :tag "Org Table"
931 :group 'org)
933 (defcustom org-enable-table-editor 'optimized
934 "Non-nil means, lines starting with \"|\" are handled by the table editor.
935 When nil, such lines will be treated like ordinary lines.
937 When equal to the symbol `optimized', the table editor will be optimized to
938 do the following:
939 - Automatic overwrite mode in front of whitespace in table fields.
940 This makes the structure of the table stay in tact as long as the edited
941 field does not exceed the column width.
942 - Minimize the number of realigns. Normally, the table is aligned each time
943 TAB or RET are pressed to move to another field. With optimization this
944 happens only if changes to a field might have changed the column width.
945 Optimization requires replacing the functions `self-insert-command',
946 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
947 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
948 very good at guessing when a re-align will be necessary, but you can always
949 force one with \\[org-ctrl-c-ctrl-c].
951 If you would like to use the optimized version in Org-mode, but the
952 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
954 This variable can be used to turn on and off the table editor during a session,
955 but in order to toggle optimization, a restart is required.
957 See also the variable `org-table-auto-blank-field'."
958 :group 'org-table
959 :type '(choice
960 (const :tag "off" nil)
961 (const :tag "on" t)
962 (const :tag "on, optimized" optimized)))
964 (defcustom org-self-insert-cluster-for-undo t
965 "Non-nil means cluster self-insert commands for undo when possible.
966 If this is set, then, like in the Emacs command loop, 20 consequtive
967 characters will be undone together.
968 This is configurable, because there is some impact on typing performance."
969 :group 'org-table
970 :type 'boolean)
972 (defcustom org-table-tab-recognizes-table.el t
973 "Non-nil means, TAB will automatically notice a table.el table.
974 When it sees such a table, it moves point into it and - if necessary -
975 calls `table-recognize-table'."
976 :group 'org-table-editing
977 :type 'boolean)
979 (defgroup org-link nil
980 "Options concerning links in Org-mode."
981 :tag "Org Link"
982 :group 'org)
984 (defvar org-link-abbrev-alist-local nil
985 "Buffer-local version of `org-link-abbrev-alist', which see.
986 The value of this is taken from the #+LINK lines.")
987 (make-variable-buffer-local 'org-link-abbrev-alist-local)
989 (defcustom org-link-abbrev-alist nil
990 "Alist of link abbreviations.
991 The car of each element is a string, to be replaced at the start of a link.
992 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
993 links in Org-mode buffers can have an optional tag after a double colon, e.g.
995 [[linkkey:tag][description]]
997 The 'linkkey' must be a word word, starting with a letter, followed
998 by letters, numbers, '-' or '_'.
1000 If REPLACE is a string, the tag will simply be appended to create the link.
1001 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1002 the placeholder \"%h\" will cause a url-encoded version of the tag to
1003 be inserted at that point (see the function `url-hexify-string').
1005 REPLACE may also be a function that will be called with the tag as the
1006 only argument to create the link, which should be returned as a string.
1008 See the manual for examples."
1009 :group 'org-link
1010 :type '(repeat
1011 (cons
1012 (string :tag "Protocol")
1013 (choice
1014 (string :tag "Format")
1015 (function)))))
1017 (defcustom org-descriptive-links t
1018 "Non-nil means, hide link part and only show description of bracket links.
1019 Bracket links are like [[link][description]]. This variable sets the initial
1020 state in new org-mode buffers. The setting can then be toggled on a
1021 per-buffer basis from the Org->Hyperlinks menu."
1022 :group 'org-link
1023 :type 'boolean)
1025 (defcustom org-link-file-path-type 'adaptive
1026 "How the path name in file links should be stored.
1027 Valid values are:
1029 relative Relative to the current directory, i.e. the directory of the file
1030 into which the link is being inserted.
1031 absolute Absolute path, if possible with ~ for home directory.
1032 noabbrev Absolute path, no abbreviation of home directory.
1033 adaptive Use relative path for files in the current directory and sub-
1034 directories of it. For other files, use an absolute path."
1035 :group 'org-link
1036 :type '(choice
1037 (const relative)
1038 (const absolute)
1039 (const noabbrev)
1040 (const adaptive)))
1042 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1043 "Types of links that should be activated in Org-mode files.
1044 This is a list of symbols, each leading to the activation of a certain link
1045 type. In principle, it does not hurt to turn on most link types - there may
1046 be a small gain when turning off unused link types. The types are:
1048 bracket The recommended [[link][description]] or [[link]] links with hiding.
1049 angular Links in angular brackets that may contain whitespace like
1050 <bbdb:Carsten Dominik>.
1051 plain Plain links in normal text, no whitespace, like http://google.com.
1052 radio Text that is matched by a radio target, see manual for details.
1053 tag Tag settings in a headline (link to tag search).
1054 date Time stamps (link to calendar).
1055 footnote Footnote labels.
1057 Changing this variable requires a restart of Emacs to become effective."
1058 :group 'org-link
1059 :type '(set :greedy t
1060 (const :tag "Double bracket links (new style)" bracket)
1061 (const :tag "Angular bracket links (old style)" angular)
1062 (const :tag "Plain text links" plain)
1063 (const :tag "Radio target matches" radio)
1064 (const :tag "Tags" tag)
1065 (const :tag "Timestamps" date)
1066 (const :tag "Footnotes" footnote)))
1068 (defcustom org-make-link-description-function nil
1069 "Function to use to generate link descriptions from links. If
1070 nil the link location will be used. This function must take two
1071 parameters; the first is the link and the second the description
1072 org-insert-link has generated, and should return the description
1073 to use."
1074 :group 'org-link
1075 :type 'function)
1077 (defgroup org-link-store nil
1078 "Options concerning storing links in Org-mode."
1079 :tag "Org Store Link"
1080 :group 'org-link)
1082 (defcustom org-email-link-description-format "Email %c: %.30s"
1083 "Format of the description part of a link to an email or usenet message.
1084 The following %-escapes will be replaced by corresponding information:
1086 %F full \"From\" field
1087 %f name, taken from \"From\" field, address if no name
1088 %T full \"To\" field
1089 %t first name in \"To\" field, address if no name
1090 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1091 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1092 %s subject
1093 %m message-id.
1095 You may use normal field width specification between the % and the letter.
1096 This is for example useful to limit the length of the subject.
1098 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1099 :group 'org-link-store
1100 :type 'string)
1102 (defcustom org-from-is-user-regexp
1103 (let (r1 r2)
1104 (when (and user-mail-address (not (string= user-mail-address "")))
1105 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1106 (when (and user-full-name (not (string= user-full-name "")))
1107 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1108 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1109 "Regexp matched against the \"From:\" header of an email or usenet message.
1110 It should match if the message is from the user him/herself."
1111 :group 'org-link-store
1112 :type 'regexp)
1114 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1115 "Non-nil means, storing a link to an Org file will use entry IDs.
1117 Note that before this variable is even considered, org-id must be loaded,
1118 to please customize `org-modules' and turn it on.
1120 The variable can have the following values:
1122 t Create an ID if needed to make a link to the current entry.
1124 create-if-interactive
1125 If `org-store-link' is called directly (interactively, as a user
1126 command), do create an ID to support the link. But when doing the
1127 job for remember, only use the ID if it already exists. The
1128 purpose of this setting is to avoid proliferation of unwanted
1129 IDs, just because you happen to be in an Org file when you
1130 call `org-remember' that automatically and preemptively
1131 creates a link. If you do want to get an ID link in a remember
1132 template to an entry not having an ID, create it first by
1133 explicitly creating a link to it, using `C-c C-l' first.
1135 use-existing
1136 Use existing ID, do not create one.
1138 nil Never use an ID to make a link, instead link using a text search for
1139 the headline text."
1140 :group 'org-link-store
1141 :type '(choice
1142 (const :tag "Create ID to make link" t)
1143 (const :tag "Create if storing link interactively"
1144 create-if-interactive)
1145 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1146 create-if-interactive-and-no-custom-id)
1147 (const :tag "Only use existing" use-existing)
1148 (const :tag "Do not use ID to create link" nil)))
1150 (defcustom org-context-in-file-links t
1151 "Non-nil means, file links from `org-store-link' contain context.
1152 A search string will be added to the file name with :: as separator and
1153 used to find the context when the link is activated by the command
1154 `org-open-at-point'.
1155 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1156 negates this setting for the duration of the command."
1157 :group 'org-link-store
1158 :type 'boolean)
1160 (defcustom org-keep-stored-link-after-insertion nil
1161 "Non-nil means, keep link in list for entire session.
1163 The command `org-store-link' adds a link pointing to the current
1164 location to an internal list. These links accumulate during a session.
1165 The command `org-insert-link' can be used to insert links into any
1166 Org-mode file (offering completion for all stored links). When this
1167 option is nil, every link which has been inserted once using \\[org-insert-link]
1168 will be removed from the list, to make completing the unused links
1169 more efficient."
1170 :group 'org-link-store
1171 :type 'boolean)
1173 (defgroup org-link-follow nil
1174 "Options concerning following links in Org-mode."
1175 :tag "Org Follow Link"
1176 :group 'org-link)
1178 (defcustom org-link-translation-function nil
1179 "Function to translate links with different syntax to Org syntax.
1180 This can be used to translate links created for example by the Planner
1181 or emacs-wiki packages to Org syntax.
1182 The function must accept two parameters, a TYPE containing the link
1183 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1184 which is everything after the link protocol. It should return a cons
1185 with possibly modified values of type and path.
1186 Org contains a function for this, so if you set this variable to
1187 `org-translate-link-from-planner', you should be able follow many
1188 links created by planner."
1189 :group 'org-link-follow
1190 :type 'function)
1192 (defcustom org-follow-link-hook nil
1193 "Hook that is run after a link has been followed."
1194 :group 'org-link-follow
1195 :type 'hook)
1197 (defcustom org-tab-follows-link nil
1198 "Non-nil means, on links TAB will follow the link.
1199 Needs to be set before org.el is loaded.
1200 This really should not be used, it does not make sense, and the
1201 implementation is bad."
1202 :group 'org-link-follow
1203 :type 'boolean)
1205 (defcustom org-return-follows-link nil
1206 "Non-nil means, on links RET will follow the link.
1207 Needs to be set before org.el is loaded."
1208 :group 'org-link-follow
1209 :type 'boolean)
1211 (defcustom org-mouse-1-follows-link
1212 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1213 "Non-nil means, mouse-1 on a link will follow the link.
1214 A longer mouse click will still set point. Does not work on XEmacs.
1215 Needs to be set before org.el is loaded."
1216 :group 'org-link-follow
1217 :type 'boolean)
1219 (defcustom org-mark-ring-length 4
1220 "Number of different positions to be recorded in the ring
1221 Changing this requires a restart of Emacs to work correctly."
1222 :group 'org-link-follow
1223 :type 'integer)
1225 (defcustom org-link-frame-setup
1226 '((vm . vm-visit-folder-other-frame)
1227 (gnus . gnus-other-frame)
1228 (file . find-file-other-window))
1229 "Setup the frame configuration for following links.
1230 When following a link with Emacs, it may often be useful to display
1231 this link in another window or frame. This variable can be used to
1232 set this up for the different types of links.
1233 For VM, use any of
1234 `vm-visit-folder'
1235 `vm-visit-folder-other-frame'
1236 For Gnus, use any of
1237 `gnus'
1238 `gnus-other-frame'
1239 `org-gnus-no-new-news'
1240 For FILE, use any of
1241 `find-file'
1242 `find-file-other-window'
1243 `find-file-other-frame'
1244 For the calendar, use the variable `calendar-setup'.
1245 For BBDB, it is currently only possible to display the matches in
1246 another window."
1247 :group 'org-link-follow
1248 :type '(list
1249 (cons (const vm)
1250 (choice
1251 (const vm-visit-folder)
1252 (const vm-visit-folder-other-window)
1253 (const vm-visit-folder-other-frame)))
1254 (cons (const gnus)
1255 (choice
1256 (const gnus)
1257 (const gnus-other-frame)
1258 (const org-gnus-no-new-news)))
1259 (cons (const file)
1260 (choice
1261 (const find-file)
1262 (const find-file-other-window)
1263 (const find-file-other-frame)))))
1265 (defcustom org-display-internal-link-with-indirect-buffer nil
1266 "Non-nil means, use indirect buffer to display infile links.
1267 Activating internal links (from one location in a file to another location
1268 in the same file) normally just jumps to the location. When the link is
1269 activated with a C-u prefix (or with mouse-3), the link is displayed in
1270 another window. When this option is set, the other window actually displays
1271 an indirect buffer clone of the current buffer, to avoid any visibility
1272 changes to the current buffer."
1273 :group 'org-link-follow
1274 :type 'boolean)
1276 (defcustom org-open-non-existing-files nil
1277 "Non-nil means, `org-open-file' will open non-existing files.
1278 When nil, an error will be generated."
1279 :group 'org-link-follow
1280 :type 'boolean)
1282 (defcustom org-open-directory-means-index-dot-org nil
1283 "Non-nil means, a link to a directory really means to index.org.
1284 When nil, following a directory link will run dired or open a finder/explorer
1285 window on that directory."
1286 :group 'org-link-follow
1287 :type 'boolean)
1289 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1290 "Function and arguments to call for following mailto links.
1291 This is a list with the first element being a lisp function, and the
1292 remaining elements being arguments to the function. In string arguments,
1293 %a will be replaced by the address, and %s will be replaced by the subject
1294 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1295 :group 'org-link-follow
1296 :type '(choice
1297 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1298 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1299 (const :tag "message-mail" (message-mail "%a" "%s"))
1300 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1302 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1303 "Non-nil means, ask for confirmation before executing shell links.
1304 Shell links can be dangerous: just think about a link
1306 [[shell:rm -rf ~/*][Google Search]]
1308 This link would show up in your Org-mode document as \"Google Search\",
1309 but really it would remove your entire home directory.
1310 Therefore we advise against setting this variable to nil.
1311 Just change it to `y-or-n-p' if you want to confirm with a
1312 single keystroke rather than having to type \"yes\"."
1313 :group 'org-link-follow
1314 :type '(choice
1315 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1316 (const :tag "with y-or-n (faster)" y-or-n-p)
1317 (const :tag "no confirmation (dangerous)" nil)))
1319 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1320 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1321 Elisp links can be dangerous: just think about a link
1323 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1325 This link would show up in your Org-mode document as \"Google Search\",
1326 but really it would remove your entire home directory.
1327 Therefore we advise against setting this variable to nil.
1328 Just change it to `y-or-n-p' if you want to confirm with a
1329 single keystroke rather than having to type \"yes\"."
1330 :group 'org-link-follow
1331 :type '(choice
1332 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1333 (const :tag "with y-or-n (faster)" y-or-n-p)
1334 (const :tag "no confirmation (dangerous)" nil)))
1336 (defconst org-file-apps-defaults-gnu
1337 '((remote . emacs)
1338 (system . mailcap)
1339 (t . mailcap))
1340 "Default file applications on a UNIX or GNU/Linux system.
1341 See `org-file-apps'.")
1343 (defconst org-file-apps-defaults-macosx
1344 '((remote . emacs)
1345 (t . "open %s")
1346 (system . "open %s")
1347 ("ps.gz" . "gv %s")
1348 ("eps.gz" . "gv %s")
1349 ("dvi" . "xdvi %s")
1350 ("fig" . "xfig %s"))
1351 "Default file applications on a MacOS X system.
1352 The system \"open\" is known as a default, but we use X11 applications
1353 for some files for which the OS does not have a good default.
1354 See `org-file-apps'.")
1356 (defconst org-file-apps-defaults-windowsnt
1357 (list
1358 '(remote . emacs)
1359 (cons t
1360 (list (if (featurep 'xemacs)
1361 'mswindows-shell-execute
1362 'w32-shell-execute)
1363 "open" 'file))
1364 (cons 'system
1365 (list (if (featurep 'xemacs)
1366 'mswindows-shell-execute
1367 'w32-shell-execute)
1368 "open" 'file)))
1369 "Default file applications on a Windows NT system.
1370 The system \"open\" is used for most files.
1371 See `org-file-apps'.")
1373 (defcustom org-file-apps
1375 (auto-mode . emacs)
1376 ("\\.x?html?\\'" . default)
1377 ("\\.pdf\\'" . default)
1379 "External applications for opening `file:path' items in a document.
1380 Org-mode uses system defaults for different file types, but
1381 you can use this variable to set the application for a given file
1382 extension. The entries in this list are cons cells where the car identifies
1383 files and the cdr the corresponding command. Possible values for the
1384 file identifier are
1385 \"regex\" Regular expression matched against the file name. For backward
1386 compatibility, this can also be a string with only alphanumeric
1387 characters, which is then interpreted as an extension.
1388 `directory' Matches a directory
1389 `remote' Matches a remote file, accessible through tramp or efs.
1390 Remote files most likely should be visited through Emacs
1391 because external applications cannot handle such paths.
1392 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1393 so all files Emacs knows how to handle. Using this with
1394 command `emacs' will open most files in Emacs. Beware that this
1395 will also open html files inside Emacs, unless you add
1396 (\"html\" . default) to the list as well.
1397 t Default for files not matched by any of the other options.
1398 `system' The system command to open files, like `open' on Windows
1399 and Mac OS X, and mailcap under GNU/Linux. This is the command
1400 that will be selected if you call `C-c C-o' with a double
1401 `C-u C-u' prefix.
1403 Possible values for the command are:
1404 `emacs' The file will be visited by the current Emacs process.
1405 `default' Use the default application for this file type, which is the
1406 association for t in the list, most likely in the system-specific
1407 part.
1408 This can be used to overrule an unwanted setting in the
1409 system-specific variable.
1410 `system' Use the system command for opening files, like \"open\".
1411 This command is specified by the entry whose car is `system'.
1412 Most likely, the system-specific version of this variable
1413 does define this command, but you can overrule/replace it
1414 here.
1415 string A command to be executed by a shell; %s will be replaced
1416 by the path to the file.
1417 sexp A Lisp form which will be evaluated. The file path will
1418 be available in the Lisp variable `file'.
1419 For more examples, see the system specific constants
1420 `org-file-apps-defaults-macosx'
1421 `org-file-apps-defaults-windowsnt'
1422 `org-file-apps-defaults-gnu'."
1423 :group 'org-link-follow
1424 :type '(repeat
1425 (cons (choice :value ""
1426 (string :tag "Extension")
1427 (const :tag "System command to open files" system)
1428 (const :tag "Default for unrecognized files" t)
1429 (const :tag "Remote file" remote)
1430 (const :tag "Links to a directory" directory)
1431 (const :tag "Any files that have Emacs modes"
1432 auto-mode))
1433 (choice :value ""
1434 (const :tag "Visit with Emacs" emacs)
1435 (const :tag "Use default" default)
1436 (const :tag "Use the system command" system)
1437 (string :tag "Command")
1438 (sexp :tag "Lisp form")))))
1440 (defgroup org-refile nil
1441 "Options concerning refiling entries in Org-mode."
1442 :tag "Org Refile"
1443 :group 'org)
1445 (defcustom org-directory "~/org"
1446 "Directory with org files.
1447 This is just a default location to look for Org files. There is no need
1448 at all to put your files into this directory. It is only used in the
1449 following situations:
1451 1. When a remember template specifies a target file that is not an
1452 absolute path. The path will then be interpreted relative to
1453 `org-directory'
1454 2. When a remember note is filed away in an interactive way (when exiting the
1455 note buffer with `C-1 C-c C-c'. The the user is prompted for an org file,
1456 with `org-directory' as the default path."
1457 :group 'org-refile
1458 :group 'org-remember
1459 :type 'directory)
1461 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1462 "Default target for storing notes.
1463 Used by the hooks for remember.el. This can be a string, or nil to mean
1464 the value of `remember-data-file'.
1465 You can set this on a per-template basis with the variable
1466 `org-remember-templates'."
1467 :group 'org-refile
1468 :group 'org-remember
1469 :type '(choice
1470 (const :tag "Default from remember-data-file" nil)
1471 file))
1473 (defcustom org-goto-interface 'outline
1474 "The default interface to be used for `org-goto'.
1475 Allowed values are:
1476 outline The interface shows an outline of the relevant file
1477 and the correct heading is found by moving through
1478 the outline or by searching with incremental search.
1479 outline-path-completion Headlines in the current buffer are offered via
1480 completion. This is the interface also used by
1481 the refile command."
1482 :group 'org-refile
1483 :type '(choice
1484 (const :tag "Outline" outline)
1485 (const :tag "Outline-path-completion" outline-path-completion)))
1487 (defcustom org-goto-max-level 5
1488 "Maximum level to be considered when running org-goto with refile interface."
1489 :group 'org-refile
1490 :type 'integer)
1492 (defcustom org-reverse-note-order nil
1493 "Non-nil means, store new notes at the beginning of a file or entry.
1494 When nil, new notes will be filed to the end of a file or entry.
1495 This can also be a list with cons cells of regular expressions that
1496 are matched against file names, and values."
1497 :group 'org-remember
1498 :group 'org-refile
1499 :type '(choice
1500 (const :tag "Reverse always" t)
1501 (const :tag "Reverse never" nil)
1502 (repeat :tag "By file name regexp"
1503 (cons regexp boolean))))
1505 (defcustom org-refile-targets nil
1506 "Targets for refiling entries with \\[org-refile].
1507 This is list of cons cells. Each cell contains:
1508 - a specification of the files to be considered, either a list of files,
1509 or a symbol whose function or variable value will be used to retrieve
1510 a file name or a list of file names. If you use `org-agenda-files' for
1511 that, all agenda files will be scanned for targets. Nil means, consider
1512 headings in the current buffer.
1513 - A specification of how to find candidate refile targets. This may be
1514 any of:
1515 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1516 This tag has to be present in all target headlines, inheritance will
1517 not be considered.
1518 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1519 todo keyword.
1520 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1521 headlines that are refiling targets.
1522 - a cons cell (:level . N). Any headline of level N is considered a target.
1523 Note that, when `org-odd-levels-only' is set, level corresponds to
1524 order in hierarchy, not to the number of stars.
1525 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1526 Note that, when `org-odd-levels-only' is set, level corresponds to
1527 order in hierarchy, not to the number of stars.
1529 You can set the variable `org-refile-target-verify-function' to a function
1530 to verify each headline found by the simple critery above.
1532 When this variable is nil, all top-level headlines in the current buffer
1533 are used, equivalent to the value `((nil . (:level . 1))'."
1534 :group 'org-refile
1535 :type '(repeat
1536 (cons
1537 (choice :value org-agenda-files
1538 (const :tag "All agenda files" org-agenda-files)
1539 (const :tag "Current buffer" nil)
1540 (function) (variable) (file))
1541 (choice :tag "Identify target headline by"
1542 (cons :tag "Specific tag" (const :value :tag) (string))
1543 (cons :tag "TODO keyword" (const :value :todo) (string))
1544 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1545 (cons :tag "Level number" (const :value :level) (integer))
1546 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1548 (defcustom org-refile-target-verify-function nil
1549 "Function to verify if the headline at point should be a refile target.
1550 The function will be called without arguments, with point at the
1551 beginning of the headline. It should return t and leave point
1552 where it is if the headline is a valid target for refiling.
1554 If the target should not be selected, the function must return nil.
1555 In addition to this, it may move point to a place from where the search
1556 should be continued. For example, the function may decide that the entire
1557 subtree of the current entry should be excluded and move point to the end
1558 of the subtree."
1559 :group 'org-refile
1560 :type 'function)
1562 (defcustom org-refile-use-outline-path nil
1563 "Non-nil means, provide refile targets as paths.
1564 So a level 3 headline will be available as level1/level2/level3.
1566 When the value is `file', also include the file name (without directory)
1567 into the path. In this case, you can also stop the completion after
1568 the file name, to get entries inserted as top level in the file.
1570 When `full-file-path', include the full file path."
1571 :group 'org-refile
1572 :type '(choice
1573 (const :tag "Not" nil)
1574 (const :tag "Yes" t)
1575 (const :tag "Start with file name" file)
1576 (const :tag "Start with full file path" full-file-path)))
1578 (defcustom org-outline-path-complete-in-steps t
1579 "Non-nil means, complete the outline path in hierarchical steps.
1580 When Org-mode uses the refile interface to select an outline path
1581 \(see variable `org-refile-use-outline-path'), the completion of
1582 the path can be done is a single go, or if can be done in steps down
1583 the headline hierarchy. Going in steps is probably the best if you
1584 do not use a special completion package like `ido' or `icicles'.
1585 However, when using these packages, going in one step can be very
1586 fast, while still showing the whole path to the entry."
1587 :group 'org-refile
1588 :type 'boolean)
1590 (defcustom org-refile-allow-creating-parent-nodes nil
1591 "Non-nil means, allow to create new nodes as refile targets.
1592 New nodes are then created by adding \"/new node name\" to the completion
1593 of an existing node. When the value of this variable is `confirm',
1594 new node creation must be confirmed by the user (recommended)
1595 When nil, the completion must match an existing entry.
1597 Note that, if the new heading is not seen by the criteria
1598 listed in `org-refile-targets', multiple instances of the same
1599 heading would be created by trying again to file under the new
1600 heading."
1601 :group 'org-refile
1602 :type '(choice
1603 (const :tag "Never" nil)
1604 (const :tag "Always" t)
1605 (const :tag "Prompt for confirmation" confirm)))
1607 (defgroup org-todo nil
1608 "Options concerning TODO items in Org-mode."
1609 :tag "Org TODO"
1610 :group 'org)
1612 (defgroup org-progress nil
1613 "Options concerning Progress logging in Org-mode."
1614 :tag "Org Progress"
1615 :group 'org-time)
1617 (defvar org-todo-interpretation-widgets
1619 (:tag "Sequence (cycling hits every state)" sequence)
1620 (:tag "Type (cycling directly to DONE)" type))
1621 "The available interpretation symbols for customizing
1622 `org-todo-keywords'.
1623 Interested libraries should add to this list.")
1625 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1626 "List of TODO entry keyword sequences and their interpretation.
1627 \\<org-mode-map>This is a list of sequences.
1629 Each sequence starts with a symbol, either `sequence' or `type',
1630 indicating if the keywords should be interpreted as a sequence of
1631 action steps, or as different types of TODO items. The first
1632 keywords are states requiring action - these states will select a headline
1633 for inclusion into the global TODO list Org-mode produces. If one of
1634 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1635 signify that no further action is necessary. If \"|\" is not found,
1636 the last keyword is treated as the only DONE state of the sequence.
1638 The command \\[org-todo] cycles an entry through these states, and one
1639 additional state where no keyword is present. For details about this
1640 cycling, see the manual.
1642 TODO keywords and interpretation can also be set on a per-file basis with
1643 the special #+SEQ_TODO and #+TYP_TODO lines.
1645 Each keyword can optionally specify a character for fast state selection
1646 \(in combination with the variable `org-use-fast-todo-selection')
1647 and specifiers for state change logging, using the same syntax
1648 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1649 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1650 indicates to record a time stamp each time this state is selected.
1652 Each keyword may also specify if a timestamp or a note should be
1653 recorded when entering or leaving the state, by adding additional
1654 characters in the parenthesis after the keyword. This looks like this:
1655 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1656 record only the time of the state change. With X and Y being either
1657 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1658 Y when leaving the state if and only if the *target* state does not
1659 define X. You may omit any of the fast-selection key or X or /Y,
1660 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1662 For backward compatibility, this variable may also be just a list
1663 of keywords - in this case the interpretation (sequence or type) will be
1664 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1665 :group 'org-todo
1666 :group 'org-keywords
1667 :type '(choice
1668 (repeat :tag "Old syntax, just keywords"
1669 (string :tag "Keyword"))
1670 (repeat :tag "New syntax"
1671 (cons
1672 (choice
1673 :tag "Interpretation"
1674 ;;Quick and dirty way to see
1675 ;;`org-todo-interpretations'. This takes the
1676 ;;place of item arguments
1677 :convert-widget
1678 (lambda (widget)
1679 (widget-put widget
1680 :args (mapcar
1681 #'(lambda (x)
1682 (widget-convert
1683 (cons 'const x)))
1684 org-todo-interpretation-widgets))
1685 widget))
1686 (repeat
1687 (string :tag "Keyword"))))))
1689 (defvar org-todo-keywords-1 nil
1690 "All TODO and DONE keywords active in a buffer.")
1691 (make-variable-buffer-local 'org-todo-keywords-1)
1692 (defvar org-todo-keywords-for-agenda nil)
1693 (defvar org-done-keywords-for-agenda nil)
1694 (defvar org-todo-keyword-alist-for-agenda nil)
1695 (defvar org-tag-alist-for-agenda nil)
1696 (defvar org-agenda-contributing-files nil)
1697 (defvar org-not-done-keywords nil)
1698 (make-variable-buffer-local 'org-not-done-keywords)
1699 (defvar org-done-keywords nil)
1700 (make-variable-buffer-local 'org-done-keywords)
1701 (defvar org-todo-heads nil)
1702 (make-variable-buffer-local 'org-todo-heads)
1703 (defvar org-todo-sets nil)
1704 (make-variable-buffer-local 'org-todo-sets)
1705 (defvar org-todo-log-states nil)
1706 (make-variable-buffer-local 'org-todo-log-states)
1707 (defvar org-todo-kwd-alist nil)
1708 (make-variable-buffer-local 'org-todo-kwd-alist)
1709 (defvar org-todo-key-alist nil)
1710 (make-variable-buffer-local 'org-todo-key-alist)
1711 (defvar org-todo-key-trigger nil)
1712 (make-variable-buffer-local 'org-todo-key-trigger)
1714 (defcustom org-todo-interpretation 'sequence
1715 "Controls how TODO keywords are interpreted.
1716 This variable is in principle obsolete and is only used for
1717 backward compatibility, if the interpretation of todo keywords is
1718 not given already in `org-todo-keywords'. See that variable for
1719 more information."
1720 :group 'org-todo
1721 :group 'org-keywords
1722 :type '(choice (const sequence)
1723 (const type)))
1725 (defcustom org-use-fast-todo-selection t
1726 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1727 This variable describes if and under what circumstances the cycling
1728 mechanism for TODO keywords will be replaced by a single-key, direct
1729 selection scheme.
1731 When nil, fast selection is never used.
1733 When the symbol `prefix', it will be used when `org-todo' is called with
1734 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1735 in an agenda buffer.
1737 When t, fast selection is used by default. In this case, the prefix
1738 argument forces cycling instead.
1740 In all cases, the special interface is only used if access keys have actually
1741 been assigned by the user, i.e. if keywords in the configuration are followed
1742 by a letter in parenthesis, like TODO(t)."
1743 :group 'org-todo
1744 :type '(choice
1745 (const :tag "Never" nil)
1746 (const :tag "By default" t)
1747 (const :tag "Only with C-u C-c C-t" prefix)))
1749 (defcustom org-provide-todo-statistics t
1750 "Non-nil means, update todo statistics after insert and toggle.
1751 When this is set, todo statistics is updated in the parent of the current
1752 entry each time a todo state is changed."
1753 :group 'org-todo
1754 :type 'boolean)
1756 (defcustom org-hierarchical-todo-statistics t
1757 "Non-nil means, TODO statistics covers just direct children.
1758 When nil, all entries in the subtree are considered.
1759 This has only an effect if `org-provide-todo-statistics' is set."
1760 :group 'org-todo
1761 :type 'boolean)
1763 (defcustom org-after-todo-state-change-hook nil
1764 "Hook which is run after the state of a TODO item was changed.
1765 The new state (a string with a TODO keyword, or nil) is available in the
1766 Lisp variable `state'."
1767 :group 'org-todo
1768 :type 'hook)
1770 (defvar org-blocker-hook nil
1771 "Hook for functions that are allowed to block a state change.
1773 Each function gets as its single argument a property list, see
1774 `org-trigger-hook' for more information about this list.
1776 If any of the functions in this hook returns nil, the state change
1777 is blocked.")
1779 (defvar org-trigger-hook nil
1780 "Hook for functions that are triggered by a state change.
1782 Each function gets as its single argument a property list with at least
1783 the following elements:
1785 (:type type-of-change :position pos-at-entry-start
1786 :from old-state :to new-state)
1788 Depending on the type, more properties may be present.
1790 This mechanism is currently implemented for:
1792 TODO state changes
1793 ------------------
1794 :type todo-state-change
1795 :from previous state (keyword as a string), or nil, or a symbol
1796 'todo' or 'done', to indicate the general type of state.
1797 :to new state, like in :from")
1799 (defcustom org-enforce-todo-dependencies nil
1800 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1801 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1802 be blocked if any prior sibling is not yet done.
1803 Finally, if the parent is blocked because of ordered siblings of its own,
1804 the child will also be blocked.
1805 This variable needs to be set before org.el is loaded, and you need to
1806 restart Emacs after a change to make the change effective. The only way
1807 to change is while Emacs is running is through the customize interface."
1808 :set (lambda (var val)
1809 (set var val)
1810 (if val
1811 (add-hook 'org-blocker-hook
1812 'org-block-todo-from-children-or-siblings-or-parent)
1813 (remove-hook 'org-blocker-hook
1814 'org-block-todo-from-children-or-siblings-or-parent)))
1815 :group 'org-todo
1816 :type 'boolean)
1818 (defcustom org-enforce-todo-checkbox-dependencies nil
1819 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1820 When this is nil, checkboxes have no influence on switching TODO states.
1821 When non-nil, you first need to check off all check boxes before the TODO
1822 entry can be switched to DONE.
1823 This variable needs to be set before org.el is loaded, and you need to
1824 restart Emacs after a change to make the change effective. The only way
1825 to change is while Emacs is running is through the customize interface."
1826 :set (lambda (var val)
1827 (set var val)
1828 (if val
1829 (add-hook 'org-blocker-hook
1830 'org-block-todo-from-checkboxes)
1831 (remove-hook 'org-blocker-hook
1832 'org-block-todo-from-checkboxes)))
1833 :group 'org-todo
1834 :type 'boolean)
1836 (defcustom org-treat-insert-todo-heading-as-state-change nil
1837 "Non-nil means, inserting a TODO heading is treated as state change.
1838 So when the command \\[org-insert-todo-heading] is used, state change
1839 logging will apply if appropriate. When nil, the new TODO item will
1840 be inserted directly, and no logging will take place."
1841 :group 'org-todo
1842 :type 'boolean)
1844 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1845 "Non-nil means, switching TODO states with S-cursor counts as state change.
1846 This is the default behavior. However, setting this to nil allows a
1847 convenient way to select a TODO state and bypass any logging associated
1848 with that."
1849 :group 'org-todo
1850 :type 'boolean)
1852 (defcustom org-todo-state-tags-triggers nil
1853 "Tag changes that should be triggered by TODO state changes.
1854 This is a list. Each entry is
1856 (state-change (tag . flag) .......)
1858 State-change can be a string with a state, and empty string to indicate the
1859 state that has no TODO keyword, or it can be one of the symbols `todo'
1860 or `done', meaning any not-done or done state, respectively."
1861 :group 'org-todo
1862 :group 'org-tags
1863 :type '(repeat
1864 (cons (choice :tag "When changing to"
1865 (const :tag "Not-done state" todo)
1866 (const :tag "Done state" done)
1867 (string :tag "State"))
1868 (repeat
1869 (cons :tag "Tag action"
1870 (string :tag "Tag")
1871 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1873 (defcustom org-log-done nil
1874 "Information to record when a task moves to the DONE state.
1876 Possible values are:
1878 nil Don't add anything, just change the keyword
1879 time Add a time stamp to the task
1880 note Prompt a closing note and add it with template `org-log-note-headings'
1882 This option can also be set with on a per-file-basis with
1884 #+STARTUP: nologdone
1885 #+STARTUP: logdone
1886 #+STARTUP: lognotedone
1888 You can have local logging settings for a subtree by setting the LOGGING
1889 property to one or more of these keywords."
1890 :group 'org-todo
1891 :group 'org-progress
1892 :type '(choice
1893 (const :tag "No logging" nil)
1894 (const :tag "Record CLOSED timestamp" time)
1895 (const :tag "Record CLOSED timestamp with closing note." note)))
1897 ;; Normalize old uses of org-log-done.
1898 (cond
1899 ((eq org-log-done t) (setq org-log-done 'time))
1900 ((and (listp org-log-done) (memq 'done org-log-done))
1901 (setq org-log-done 'note)))
1903 (defcustom org-log-note-clock-out nil
1904 "Non-nil means, record a note when clocking out of an item.
1905 This can also be configured on a per-file basis by adding one of
1906 the following lines anywhere in the buffer:
1908 #+STARTUP: lognoteclock-out
1909 #+STARTUP: nolognoteclock-out"
1910 :group 'org-todo
1911 :group 'org-progress
1912 :type 'boolean)
1914 (defcustom org-log-done-with-time t
1915 "Non-nil means, the CLOSED time stamp will contain date and time.
1916 When nil, only the date will be recorded."
1917 :group 'org-progress
1918 :type 'boolean)
1920 (defcustom org-log-note-headings
1921 '((done . "CLOSING NOTE %t")
1922 (state . "State %-12s from %-12S %t")
1923 (note . "Note taken on %t")
1924 (clock-out . ""))
1925 "Headings for notes added to entries.
1926 The value is an alist, with the car being a symbol indicating the note
1927 context, and the cdr is the heading to be used. The heading may also be the
1928 empty string.
1929 %t in the heading will be replaced by a time stamp.
1930 %s will be replaced by the new TODO state, in double quotes.
1931 %S will be replaced by the old TODO state, in double quotes.
1932 %u will be replaced by the user name.
1933 %U will be replaced by the full user name."
1934 :group 'org-todo
1935 :group 'org-progress
1936 :type '(list :greedy t
1937 (cons (const :tag "Heading when closing an item" done) string)
1938 (cons (const :tag
1939 "Heading when changing todo state (todo sequence only)"
1940 state) string)
1941 (cons (const :tag "Heading when just taking a note" note) string)
1942 (cons (const :tag "Heading when clocking out" clock-out) string)))
1944 (unless (assq 'note org-log-note-headings)
1945 (push '(note . "%t") org-log-note-headings))
1947 (defcustom org-log-into-drawer nil
1948 "Non-nil means, insert state change notes and time stamps into a drawer.
1949 When nil, state changes notes will be inserted after the headline and
1950 any scheduling and clock lines, but not inside a drawer.
1952 The value of this variable should be the name of the drawer to use.
1953 LOGBOOK is proposed at the default drawer for this purpose, you can
1954 also set this to a string to define the drawer of your choice.
1956 A value of t is also allowed, representing \"LOGBOOK\".
1958 If this variable is set, `org-log-state-notes-insert-after-drawers'
1959 will be ignored.
1961 You can set the property LOG_INTO_DRAWER to overrule this setting for
1962 a subtree."
1963 :group 'org-todo
1964 :group 'org-progress
1965 :type '(choice
1966 (const :tag "Not into a drawer" nil)
1967 (const :tag "LOGBOOK" t)
1968 (string :tag "Other")))
1970 (if (fboundp 'defvaralias)
1971 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
1973 (defun org-log-into-drawer ()
1974 "Return the value of `org-log-into-drawer', but let properties overrule.
1975 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
1976 used instead of the default value."
1977 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
1978 (cond
1979 ((or (not p) (equal p "nil")) org-log-into-drawer)
1980 ((equal p "t") "LOGBOOK")
1981 (t p))))
1983 (defcustom org-log-state-notes-insert-after-drawers nil
1984 "Non-nil means, insert state change notes after any drawers in entry.
1985 Only the drawers that *immediately* follow the headline and the
1986 deadline/scheduled line are skipped.
1987 When nil, insert notes right after the heading and perhaps the line
1988 with deadline/scheduling if present.
1990 This variable will have no effect if `org-log-into-drawer' is
1991 set."
1992 :group 'org-todo
1993 :group 'org-progress
1994 :type 'boolean)
1996 (defcustom org-log-states-order-reversed t
1997 "Non-nil means, the latest state change note will be directly after heading.
1998 When nil, the notes will be orderer according to time."
1999 :group 'org-todo
2000 :group 'org-progress
2001 :type 'boolean)
2003 (defcustom org-log-repeat 'time
2004 "Non-nil means, record moving through the DONE state when triggering repeat.
2005 An auto-repeating tasks is immediately switched back to TODO when marked
2006 done. If you are not logging state changes (by adding \"@\" or \"!\" to
2007 the TODO keyword definition, or recording a closing note by setting
2008 `org-log-done', there will be no record of the task moving through DONE.
2009 This variable forces taking a note anyway. Possible values are:
2011 nil Don't force a record
2012 time Record a time stamp
2013 note Record a note
2015 This option can also be set with on a per-file-basis with
2017 #+STARTUP: logrepeat
2018 #+STARTUP: lognoterepeat
2019 #+STARTUP: nologrepeat
2021 You can have local logging settings for a subtree by setting the LOGGING
2022 property to one or more of these keywords."
2023 :group 'org-todo
2024 :group 'org-progress
2025 :type '(choice
2026 (const :tag "Don't force a record" nil)
2027 (const :tag "Force recording the DONE state" time)
2028 (const :tag "Force recording a note with the DONE state" note)))
2031 (defgroup org-priorities nil
2032 "Priorities in Org-mode."
2033 :tag "Org Priorities"
2034 :group 'org-todo)
2036 (defcustom org-enable-priority-commands t
2037 "Non-nil means, priority commands are active.
2038 When nil, these commands will be disabled, so that you never accidentally
2039 set a priority."
2040 :group 'org-priorities
2041 :type 'boolean)
2043 (defcustom org-highest-priority ?A
2044 "The highest priority of TODO items. A character like ?A, ?B etc.
2045 Must have a smaller ASCII number than `org-lowest-priority'."
2046 :group 'org-priorities
2047 :type 'character)
2049 (defcustom org-lowest-priority ?C
2050 "The lowest priority of TODO items. A character like ?A, ?B etc.
2051 Must have a larger ASCII number than `org-highest-priority'."
2052 :group 'org-priorities
2053 :type 'character)
2055 (defcustom org-default-priority ?B
2056 "The default priority of TODO items.
2057 This is the priority an item get if no explicit priority is given."
2058 :group 'org-priorities
2059 :type 'character)
2061 (defcustom org-priority-start-cycle-with-default t
2062 "Non-nil means, start with default priority when starting to cycle.
2063 When this is nil, the first step in the cycle will be (depending on the
2064 command used) one higher or lower that the default priority."
2065 :group 'org-priorities
2066 :type 'boolean)
2068 (defgroup org-time nil
2069 "Options concerning time stamps and deadlines in Org-mode."
2070 :tag "Org Time"
2071 :group 'org)
2073 (defcustom org-insert-labeled-timestamps-at-point nil
2074 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
2075 When nil, these labeled time stamps are forces into the second line of an
2076 entry, just after the headline. When scheduling from the global TODO list,
2077 the time stamp will always be forced into the second line."
2078 :group 'org-time
2079 :type 'boolean)
2081 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2082 "Formats for `format-time-string' which are used for time stamps.
2083 It is not recommended to change this constant.")
2085 (defcustom org-time-stamp-rounding-minutes '(0 5)
2086 "Number of minutes to round time stamps to.
2087 These are two values, the first applies when first creating a time stamp.
2088 The second applies when changing it with the commands `S-up' and `S-down'.
2089 When changing the time stamp, this means that it will change in steps
2090 of N minutes, as given by the second value.
2092 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2093 numbers should be factors of 60, so for example 5, 10, 15.
2095 When this is larger than 1, you can still force an exact time-stamp by using
2096 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2097 and by using a prefix arg to `S-up/down' to specify the exact number
2098 of minutes to shift."
2099 :group 'org-time
2100 :get '(lambda (var) ; Make sure all entries have 5 elements
2101 (if (integerp (default-value var))
2102 (list (default-value var) 5)
2103 (default-value var)))
2104 :type '(list
2105 (integer :tag "when inserting times")
2106 (integer :tag "when modifying times")))
2108 ;; Normalize old customizations of this variable.
2109 (when (integerp org-time-stamp-rounding-minutes)
2110 (setq org-time-stamp-rounding-minutes
2111 (list org-time-stamp-rounding-minutes
2112 org-time-stamp-rounding-minutes)))
2114 (defcustom org-display-custom-times nil
2115 "Non-nil means, overlay custom formats over all time stamps.
2116 The formats are defined through the variable `org-time-stamp-custom-formats'.
2117 To turn this on on a per-file basis, insert anywhere in the file:
2118 #+STARTUP: customtime"
2119 :group 'org-time
2120 :set 'set-default
2121 :type 'sexp)
2122 (make-variable-buffer-local 'org-display-custom-times)
2124 (defcustom org-time-stamp-custom-formats
2125 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2126 "Custom formats for time stamps. See `format-time-string' for the syntax.
2127 These are overlayed over the default ISO format if the variable
2128 `org-display-custom-times' is set. Time like %H:%M should be at the
2129 end of the second format. The custom formats are also honored by export
2130 commands, if custom time display is turned on at the time of export."
2131 :group 'org-time
2132 :type 'sexp)
2134 (defun org-time-stamp-format (&optional long inactive)
2135 "Get the right format for a time string."
2136 (let ((f (if long (cdr org-time-stamp-formats)
2137 (car org-time-stamp-formats))))
2138 (if inactive
2139 (concat "[" (substring f 1 -1) "]")
2140 f)))
2142 (defcustom org-time-clocksum-format "%d:%02d"
2143 "The format string used when creating CLOCKSUM lines, or when
2144 org-mode generates a time duration."
2145 :group 'org-time
2146 :type 'string)
2148 (defcustom org-deadline-warning-days 14
2149 "No. of days before expiration during which a deadline becomes active.
2150 This variable governs the display in sparse trees and in the agenda.
2151 When 0 or negative, it means use this number (the absolute value of it)
2152 even if a deadline has a different individual lead time specified.
2154 Custom commands can set this variable in the options section."
2155 :group 'org-time
2156 :group 'org-agenda-daily/weekly
2157 :type 'integer)
2159 (defcustom org-read-date-prefer-future t
2160 "Non-nil means, assume future for incomplete date input from user.
2161 This affects the following situations:
2162 1. The user gives a day, but no month.
2163 For example, if today is the 15th, and you enter \"3\", Org-mode will
2164 read this as the third of *next* month. However, if you enter \"17\",
2165 it will be considered as *this* month.
2166 2. The user gives a month but not a year.
2167 For example, if it is april and you enter \"feb 2\", this will be read
2168 as feb 2, *next* year. \"May 5\", however, will be this year.
2170 Currently this does not work for ISO week specifications.
2172 When this option is nil, the current month and year will always be used
2173 as defaults."
2174 :group 'org-time
2175 :type 'boolean)
2177 (defcustom org-read-date-display-live t
2178 "Non-nil means, display current interpretation of date prompt live.
2179 This display will be in an overlay, in the minibuffer."
2180 :group 'org-time
2181 :type 'boolean)
2183 (defcustom org-read-date-popup-calendar t
2184 "Non-nil means, pop up a calendar when prompting for a date.
2185 In the calendar, the date can be selected with mouse-1. However, the
2186 minibuffer will also be active, and you can simply enter the date as well.
2187 When nil, only the minibuffer will be available."
2188 :group 'org-time
2189 :type 'boolean)
2190 (if (fboundp 'defvaralias)
2191 (defvaralias 'org-popup-calendar-for-date-prompt
2192 'org-read-date-popup-calendar))
2194 (defcustom org-read-date-minibuffer-setup-hook nil
2195 "Hook to be used to set up keys for the date/time interface.
2196 Add key definitions to `minibuffer-local-map', which will be a temporary
2197 copy."
2198 :group 'org-time
2199 :type 'hook)
2201 (defcustom org-extend-today-until 0
2202 "The hour when your day really ends. Must be an integer.
2203 This has influence for the following applications:
2204 - When switching the agenda to \"today\". It it is still earlier than
2205 the time given here, the day recognized as TODAY is actually yesterday.
2206 - When a date is read from the user and it is still before the time given
2207 here, the current date and time will be assumed to be yesterday, 23:59.
2208 Also, timestamps inserted in remember templates follow this rule.
2210 IMPORTANT: This is a feature whose implementation is and likely will
2211 remain incomplete. Really, it is only here because past midnight seems to
2212 be the favorite working time of John Wiegley :-)"
2213 :group 'org-time
2214 :type 'integer)
2216 (defcustom org-edit-timestamp-down-means-later nil
2217 "Non-nil means, S-down will increase the time in a time stamp.
2218 When nil, S-up will increase."
2219 :group 'org-time
2220 :type 'boolean)
2222 (defcustom org-calendar-follow-timestamp-change t
2223 "Non-nil means, make the calendar window follow timestamp changes.
2224 When a timestamp is modified and the calendar window is visible, it will be
2225 moved to the new date."
2226 :group 'org-time
2227 :type 'boolean)
2229 (defgroup org-tags nil
2230 "Options concerning tags in Org-mode."
2231 :tag "Org Tags"
2232 :group 'org)
2234 (defcustom org-tag-alist nil
2235 "List of tags allowed in Org-mode files.
2236 When this list is nil, Org-mode will base TAG input on what is already in the
2237 buffer.
2238 The value of this variable is an alist, the car of each entry must be a
2239 keyword as a string, the cdr may be a character that is used to select
2240 that tag through the fast-tag-selection interface.
2241 See the manual for details."
2242 :group 'org-tags
2243 :type '(repeat
2244 (choice
2245 (cons (string :tag "Tag name")
2246 (character :tag "Access char"))
2247 (const :tag "Start radio group" (:startgroup))
2248 (const :tag "End radio group" (:endgroup))
2249 (const :tag "New line" (:newline)))))
2251 (defcustom org-tag-persistent-alist nil
2252 "List of tags that will always appear in all Org-mode files.
2253 This is in addition to any in buffer settings or customizations
2254 of `org-tag-alist'.
2255 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2256 The value of this variable is an alist, the car of each entry must be a
2257 keyword as a string, the cdr may be a character that is used to select
2258 that tag through the fast-tag-selection interface.
2259 See the manual for details.
2260 To disable these tags on a per-file basis, insert anywhere in the file:
2261 #+STARTUP: noptag"
2262 :group 'org-tags
2263 :type '(repeat
2264 (choice
2265 (cons (string :tag "Tag name")
2266 (character :tag "Access char"))
2267 (const :tag "Start radio group" (:startgroup))
2268 (const :tag "End radio group" (:endgroup))
2269 (const :tag "New line" (:newline)))))
2271 (defvar org-file-tags nil
2272 "List of tags that can be inherited by all entries in the file.
2273 The tags will be inherited if the variable `org-use-tag-inheritance'
2274 says they should be.
2275 This variable is populated from #+TAG lines.")
2277 (defcustom org-use-fast-tag-selection 'auto
2278 "Non-nil means, use fast tag selection scheme.
2279 This is a special interface to select and deselect tags with single keys.
2280 When nil, fast selection is never used.
2281 When the symbol `auto', fast selection is used if and only if selection
2282 characters for tags have been configured, either through the variable
2283 `org-tag-alist' or through a #+TAGS line in the buffer.
2284 When t, fast selection is always used and selection keys are assigned
2285 automatically if necessary."
2286 :group 'org-tags
2287 :type '(choice
2288 (const :tag "Always" t)
2289 (const :tag "Never" nil)
2290 (const :tag "When selection characters are configured" 'auto)))
2292 (defcustom org-fast-tag-selection-single-key nil
2293 "Non-nil means, fast tag selection exits after first change.
2294 When nil, you have to press RET to exit it.
2295 During fast tag selection, you can toggle this flag with `C-c'.
2296 This variable can also have the value `expert'. In this case, the window
2297 displaying the tags menu is not even shown, until you press C-c again."
2298 :group 'org-tags
2299 :type '(choice
2300 (const :tag "No" nil)
2301 (const :tag "Yes" t)
2302 (const :tag "Expert" expert)))
2304 (defvar org-fast-tag-selection-include-todo nil
2305 "Non-nil means, fast tags selection interface will also offer TODO states.
2306 This is an undocumented feature, you should not rely on it.")
2308 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2309 "The column to which tags should be indented in a headline.
2310 If this number is positive, it specifies the column. If it is negative,
2311 it means that the tags should be flushright to that column. For example,
2312 -80 works well for a normal 80 character screen."
2313 :group 'org-tags
2314 :type 'integer)
2316 (defcustom org-auto-align-tags t
2317 "Non-nil means, realign tags after pro/demotion of TODO state change.
2318 These operations change the length of a headline and therefore shift
2319 the tags around. With this options turned on, after each such operation
2320 the tags are again aligned to `org-tags-column'."
2321 :group 'org-tags
2322 :type 'boolean)
2324 (defcustom org-use-tag-inheritance t
2325 "Non-nil means, tags in levels apply also for sublevels.
2326 When nil, only the tags directly given in a specific line apply there.
2327 This may also be a list of tags that should be inherited, or a regexp that
2328 matches tags that should be inherited. Additional control is possible
2329 with the variable `org-tags-exclude-from-inheritance' which gives an
2330 explicit list of tags to be excluded from inheritance., even if the value of
2331 `org-use-tag-inheritance' would select it for inheritance.
2333 If this option is t, a match early-on in a tree can lead to a large
2334 number of matches in the subtree when constructing the agenda or creating
2335 a sparse tree. If you only want to see the first match in a tree during
2336 a search, check out the variable `org-tags-match-list-sublevels'."
2337 :group 'org-tags
2338 :type '(choice
2339 (const :tag "Not" nil)
2340 (const :tag "Always" t)
2341 (repeat :tag "Specific tags" (string :tag "Tag"))
2342 (regexp :tag "Tags matched by regexp")))
2344 (defcustom org-tags-exclude-from-inheritance nil
2345 "List of tags that should never be inherited.
2346 This is a way to exclude a few tags from inheritance. For way to do
2347 the opposite, to actively allow inheritance for selected tags,
2348 see the variable `org-use-tag-inheritance'."
2349 :group 'org-tags
2350 :type '(repeat (string :tag "Tag")))
2352 (defun org-tag-inherit-p (tag)
2353 "Check if TAG is one that should be inherited."
2354 (cond
2355 ((member tag org-tags-exclude-from-inheritance) nil)
2356 ((eq org-use-tag-inheritance t) t)
2357 ((not org-use-tag-inheritance) nil)
2358 ((stringp org-use-tag-inheritance)
2359 (string-match org-use-tag-inheritance tag))
2360 ((listp org-use-tag-inheritance)
2361 (member tag org-use-tag-inheritance))
2362 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2364 (defcustom org-tags-match-list-sublevels t
2365 "Non-nil means list also sublevels of headlines matching a search.
2366 This variable applies to tags/property searches, and also to stuck
2367 projects because this search is based on a tags match as well.
2369 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2370 the sublevels of a headline matching a tag search often also match
2371 the same search. Listing all of them can create very long lists.
2372 Setting this variable to nil causes subtrees of a match to be skipped.
2374 As a special case, if the tag search is restricted to TODO items, the
2375 value of this variable is ignored and sublevels are always checked, to
2376 make sure all corresponding TODO items find their way into the list.
2378 This variable is semi-obsolete and probably should always be true. It
2379 is better to limit inheritance to certain tags using the variables
2380 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2381 :group 'org-tags
2382 :type '(choice
2383 (const :tag "No, don't list them" nil)
2384 (const :tag "Yes, do list them" t)
2385 (const :tag "List them, indented with leading dots" indented)))
2387 (defvar org-tags-history nil
2388 "History of minibuffer reads for tags.")
2389 (defvar org-last-tags-completion-table nil
2390 "The last used completion table for tags.")
2391 (defvar org-after-tags-change-hook nil
2392 "Hook that is run after the tags in a line have changed.")
2394 (defgroup org-properties nil
2395 "Options concerning properties in Org-mode."
2396 :tag "Org Properties"
2397 :group 'org)
2399 (defcustom org-property-format "%-10s %s"
2400 "How property key/value pairs should be formatted by `indent-line'.
2401 When `indent-line' hits a property definition, it will format the line
2402 according to this format, mainly to make sure that the values are
2403 lined-up with respect to each other."
2404 :group 'org-properties
2405 :type 'string)
2407 (defcustom org-use-property-inheritance nil
2408 "Non-nil means, properties apply also for sublevels.
2410 This setting is chiefly used during property searches. Turning it on can
2411 cause significant overhead when doing a search, which is why it is not
2412 on by default.
2414 When nil, only the properties directly given in the current entry count.
2415 When t, every property is inherited. The value may also be a list of
2416 properties that should have inheritance, or a regular expression matching
2417 properties that should be inherited.
2419 However, note that some special properties use inheritance under special
2420 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2421 and the properties ending in \"_ALL\" when they are used as descriptor
2422 for valid values of a property.
2424 Note for programmers:
2425 When querying an entry with `org-entry-get', you can control if inheritance
2426 should be used. By default, `org-entry-get' looks only at the local
2427 properties. You can request inheritance by setting the inherit argument
2428 to t (to force inheritance) or to `selective' (to respect the setting
2429 in this variable)."
2430 :group 'org-properties
2431 :type '(choice
2432 (const :tag "Not" nil)
2433 (const :tag "Always" t)
2434 (repeat :tag "Specific properties" (string :tag "Property"))
2435 (regexp :tag "Properties matched by regexp")))
2437 (defun org-property-inherit-p (property)
2438 "Check if PROPERTY is one that should be inherited."
2439 (cond
2440 ((eq org-use-property-inheritance t) t)
2441 ((not org-use-property-inheritance) nil)
2442 ((stringp org-use-property-inheritance)
2443 (string-match org-use-property-inheritance property))
2444 ((listp org-use-property-inheritance)
2445 (member property org-use-property-inheritance))
2446 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2448 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2449 "The default column format, if no other format has been defined.
2450 This variable can be set on the per-file basis by inserting a line
2452 #+COLUMNS: %25ITEM ....."
2453 :group 'org-properties
2454 :type 'string)
2456 (defcustom org-columns-ellipses ".."
2457 "The ellipses to be used when a field in column view is truncated.
2458 When this is the empty string, as many characters as possible are shown,
2459 but then there will be no visual indication that the field has been truncated.
2460 When this is a string of length N, the last N characters of a truncated
2461 field are replaced by this string. If the column is narrower than the
2462 ellipses string, only part of the ellipses string will be shown."
2463 :group 'org-properties
2464 :type 'string)
2466 (defcustom org-columns-modify-value-for-display-function nil
2467 "Function that modifies values for display in column view.
2468 For example, it can be used to cut out a certain part from a time stamp.
2469 The function must take 2 arguments:
2471 column-title The title of the column (*not* the property name)
2472 value The value that should be modified.
2474 The function should return the value that should be displayed,
2475 or nil if the normal value should be used."
2476 :group 'org-properties
2477 :type 'function)
2479 (defcustom org-effort-property "Effort"
2480 "The property that is being used to keep track of effort estimates.
2481 Effort estimates given in this property need to have the format H:MM."
2482 :group 'org-properties
2483 :group 'org-progress
2484 :type '(string :tag "Property"))
2486 (defconst org-global-properties-fixed
2487 '(("VISIBILITY_ALL" . "folded children content all")
2488 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2489 "List of property/value pairs that can be inherited by any entry.
2491 These are fixed values, for the preset properties. The user variable
2492 that can be used to add to this list is `org-global-properties'.
2494 The entries in this list are cons cells where the car is a property
2495 name and cdr is a string with the value. If the value represents
2496 multiple items like an \"_ALL\" property, separate the items by
2497 spaces.")
2499 (defcustom org-global-properties nil
2500 "List of property/value pairs that can be inherited by any entry.
2502 This list will be combined with the constant `org-global-properties-fixed'.
2504 The entries in this list are cons cells where the car is a property
2505 name and cdr is a string with the value.
2507 You can set buffer-local values for the same purpose in the variable
2508 `org-file-properties' this by adding lines like
2510 #+PROPERTY: NAME VALUE"
2511 :group 'org-properties
2512 :type '(repeat
2513 (cons (string :tag "Property")
2514 (string :tag "Value"))))
2516 (defvar org-file-properties nil
2517 "List of property/value pairs that can be inherited by any entry.
2518 Valid for the current buffer.
2519 This variable is populated from #+PROPERTY lines.")
2520 (make-variable-buffer-local 'org-file-properties)
2522 (defgroup org-agenda nil
2523 "Options concerning agenda views in Org-mode."
2524 :tag "Org Agenda"
2525 :group 'org)
2527 (defvar org-category nil
2528 "Variable used by org files to set a category for agenda display.
2529 Such files should use a file variable to set it, for example
2531 # -*- mode: org; org-category: \"ELisp\"
2533 or contain a special line
2535 #+CATEGORY: ELisp
2537 If the file does not specify a category, then file's base name
2538 is used instead.")
2539 (make-variable-buffer-local 'org-category)
2540 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2542 (defcustom org-agenda-files nil
2543 "The files to be used for agenda display.
2544 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2545 \\[org-remove-file]. You can also use customize to edit the list.
2547 If an entry is a directory, all files in that directory that are matched by
2548 `org-agenda-file-regexp' will be part of the file list.
2550 If the value of the variable is not a list but a single file name, then
2551 the list of agenda files is actually stored and maintained in that file, one
2552 agenda file per line."
2553 :group 'org-agenda
2554 :type '(choice
2555 (repeat :tag "List of files and directories" file)
2556 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2558 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2559 "Regular expression to match files for `org-agenda-files'.
2560 If any element in the list in that variable contains a directory instead
2561 of a normal file, all files in that directory that are matched by this
2562 regular expression will be included."
2563 :group 'org-agenda
2564 :type 'regexp)
2566 (defcustom org-agenda-text-search-extra-files nil
2567 "List of extra files to be searched by text search commands.
2568 These files will be search in addition to the agenda files by the
2569 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2570 Note that these files will only be searched for text search commands,
2571 not for the other agenda views like todo lists, tag searches or the weekly
2572 agenda. This variable is intended to list notes and possibly archive files
2573 that should also be searched by these two commands.
2574 In fact, if the first element in the list is the symbol `agenda-archives',
2575 than all archive files of all agenda files will be added to the search
2576 scope."
2577 :group 'org-agenda
2578 :type '(set :greedy t
2579 (const :tag "Agenda Archives" agenda-archives)
2580 (repeat :inline t (file))))
2582 (if (fboundp 'defvaralias)
2583 (defvaralias 'org-agenda-multi-occur-extra-files
2584 'org-agenda-text-search-extra-files))
2586 (defcustom org-agenda-skip-unavailable-files nil
2587 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2588 A nil value means to remove them, after a query, from the list."
2589 :group 'org-agenda
2590 :type 'boolean)
2592 (defcustom org-calendar-to-agenda-key [?c]
2593 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2594 The command `org-calendar-goto-agenda' will be bound to this key. The
2595 default is the character `c' because then `c' can be used to switch back and
2596 forth between agenda and calendar."
2597 :group 'org-agenda
2598 :type 'sexp)
2600 (defcustom org-calendar-agenda-action-key [?k]
2601 "The key to be installed in `calendar-mode-map' for agenda-action.
2602 The command `org-agenda-action' will be bound to this key. The
2603 default is the character `k' because we use the same key in the agenda."
2604 :group 'org-agenda
2605 :type 'sexp)
2607 (eval-after-load "calendar"
2608 '(progn
2609 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2610 'org-calendar-goto-agenda)
2611 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2612 'org-agenda-action)))
2614 (defgroup org-latex nil
2615 "Options for embedding LaTeX code into Org-mode."
2616 :tag "Org LaTeX"
2617 :group 'org)
2619 (defcustom org-format-latex-options
2620 '(:foreground default :background default :scale 1.0
2621 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2622 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2623 "Options for creating images from LaTeX fragments.
2624 This is a property list with the following properties:
2625 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2626 `default' means use the foreground of the default face.
2627 :background the background color, or \"Transparent\".
2628 `default' means use the background of the default face.
2629 :scale a scaling factor for the size of the images.
2630 :html-foreground, :html-background, :html-scale
2631 the same numbers for HTML export.
2632 :matchers a list indicating which matchers should be used to
2633 find LaTeX fragments. Valid members of this list are:
2634 \"begin\" find environments
2635 \"$1\" find single characters surrounded by $.$
2636 \"$\" find math expressions surrounded by $...$
2637 \"$$\" find math expressions surrounded by $$....$$
2638 \"\\(\" find math expressions surrounded by \\(...\\)
2639 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2640 :group 'org-latex
2641 :type 'plist)
2643 (defcustom org-format-latex-header "\\documentclass{article}
2644 \\usepackage{fullpage} % do not remove
2645 \\usepackage{amssymb}
2646 \\usepackage[usenames]{color}
2647 \\usepackage{amsmath}
2648 \\usepackage{latexsym}
2649 \\usepackage[mathscr]{eucal}
2650 \\pagestyle{empty} % do not remove"
2651 "The document header used for processing LaTeX fragments."
2652 :group 'org-latex
2653 :type 'string)
2656 (defgroup org-font-lock nil
2657 "Font-lock settings for highlighting in Org-mode."
2658 :tag "Org Font Lock"
2659 :group 'org)
2661 (defcustom org-level-color-stars-only nil
2662 "Non-nil means fontify only the stars in each headline.
2663 When nil, the entire headline is fontified.
2664 Changing it requires restart of `font-lock-mode' to become effective
2665 also in regions already fontified."
2666 :group 'org-font-lock
2667 :type 'boolean)
2669 (defcustom org-hide-leading-stars nil
2670 "Non-nil means, hide the first N-1 stars in a headline.
2671 This works by using the face `org-hide' for these stars. This
2672 face is white for a light background, and black for a dark
2673 background. You may have to customize the face `org-hide' to
2674 make this work.
2675 Changing it requires restart of `font-lock-mode' to become effective
2676 also in regions already fontified.
2677 You may also set this on a per-file basis by adding one of the following
2678 lines to the buffer:
2680 #+STARTUP: hidestars
2681 #+STARTUP: showstars"
2682 :group 'org-font-lock
2683 :type 'boolean)
2685 (defcustom org-fontify-done-headline nil
2686 "Non-nil means, change the face of a headline if it is marked DONE.
2687 Normally, only the TODO/DONE keyword indicates the state of a headline.
2688 When this is non-nil, the headline after the keyword is set to the
2689 `org-headline-done' as an additional indication."
2690 :group 'org-font-lock
2691 :type 'boolean)
2693 (defcustom org-fontify-emphasized-text t
2694 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2695 Changing this variable requires a restart of Emacs to take effect."
2696 :group 'org-font-lock
2697 :type 'boolean)
2699 (defcustom org-highlight-latex-fragments-and-specials nil
2700 "Non-nil means, fontify what is treated specially by the exporters."
2701 :group 'org-font-lock
2702 :type 'boolean)
2704 (defcustom org-hide-emphasis-markers nil
2705 "Non-nil mean font-lock should hide the emphasis marker characters."
2706 :group 'org-font-lock
2707 :type 'boolean)
2709 (defvar org-emph-re nil
2710 "Regular expression for matching emphasis.")
2711 (defvar org-verbatim-re nil
2712 "Regular expression for matching verbatim text.")
2713 (defvar org-emphasis-regexp-components) ; defined just below
2714 (defvar org-emphasis-alist) ; defined just below
2715 (defun org-set-emph-re (var val)
2716 "Set variable and compute the emphasis regular expression."
2717 (set var val)
2718 (when (and (boundp 'org-emphasis-alist)
2719 (boundp 'org-emphasis-regexp-components)
2720 org-emphasis-alist org-emphasis-regexp-components)
2721 (let* ((e org-emphasis-regexp-components)
2722 (pre (car e))
2723 (post (nth 1 e))
2724 (border (nth 2 e))
2725 (body (nth 3 e))
2726 (nl (nth 4 e))
2727 (body1 (concat body "*?"))
2728 (markers (mapconcat 'car org-emphasis-alist ""))
2729 (vmarkers (mapconcat
2730 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2731 org-emphasis-alist "")))
2732 ;; make sure special characters appear at the right position in the class
2733 (if (string-match "\\^" markers)
2734 (setq markers (concat (replace-match "" t t markers) "^")))
2735 (if (string-match "-" markers)
2736 (setq markers (concat (replace-match "" t t markers) "-")))
2737 (if (string-match "\\^" vmarkers)
2738 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2739 (if (string-match "-" vmarkers)
2740 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2741 (if (> nl 0)
2742 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2743 (int-to-string nl) "\\}")))
2744 ;; Make the regexp
2745 (setq org-emph-re
2746 (concat "\\([" pre "]\\|^\\)"
2747 "\\("
2748 "\\([" markers "]\\)"
2749 "\\("
2750 "[^" border "]\\|"
2751 "[^" border "]"
2752 body1
2753 "[^" border "]"
2754 "\\)"
2755 "\\3\\)"
2756 "\\([" post "]\\|$\\)"))
2757 (setq org-verbatim-re
2758 (concat "\\([" pre "]\\|^\\)"
2759 "\\("
2760 "\\([" vmarkers "]\\)"
2761 "\\("
2762 "[^" border "]\\|"
2763 "[^" border "]"
2764 body1
2765 "[^" border "]"
2766 "\\)"
2767 "\\3\\)"
2768 "\\([" post "]\\|$\\)")))))
2770 (defcustom org-emphasis-regexp-components
2771 '(" \t('\"{" "- \t.,:!?;'\")}" " \t\r\n,\"'" "." 1)
2772 "Components used to build the regular expression for emphasis.
2773 This is a list with 6 entries. Terminology: In an emphasis string
2774 like \" *strong word* \", we call the initial space PREMATCH, the final
2775 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2776 and \"trong wor\" is the body. The different components in this variable
2777 specify what is allowed/forbidden in each part:
2779 pre Chars allowed as prematch. Beginning of line will be allowed too.
2780 post Chars allowed as postmatch. End of line will be allowed too.
2781 border The chars *forbidden* as border characters.
2782 body-regexp A regexp like \".\" to match a body character. Don't use
2783 non-shy groups here, and don't allow newline here.
2784 newline The maximum number of newlines allowed in an emphasis exp.
2786 Use customize to modify this, or restart Emacs after changing it."
2787 :group 'org-font-lock
2788 :set 'org-set-emph-re
2789 :type '(list
2790 (sexp :tag "Allowed chars in pre ")
2791 (sexp :tag "Allowed chars in post ")
2792 (sexp :tag "Forbidden chars in border ")
2793 (sexp :tag "Regexp for body ")
2794 (integer :tag "number of newlines allowed")
2795 (option (boolean :tag "Please ignore this button"))))
2797 (defcustom org-emphasis-alist
2798 `(("*" bold "<b>" "</b>")
2799 ("/" italic "<i>" "</i>")
2800 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2801 ("=" org-code "<code>" "</code>" verbatim)
2802 ("~" org-verbatim "<code>" "</code>" verbatim)
2803 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2804 "<del>" "</del>")
2806 "Special syntax for emphasized text.
2807 Text starting and ending with a special character will be emphasized, for
2808 example *bold*, _underlined_ and /italic/. This variable sets the marker
2809 characters, the face to be used by font-lock for highlighting in Org-mode
2810 Emacs buffers, and the HTML tags to be used for this.
2811 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
2812 Use customize to modify this, or restart Emacs after changing it."
2813 :group 'org-font-lock
2814 :set 'org-set-emph-re
2815 :type '(repeat
2816 (list
2817 (string :tag "Marker character")
2818 (choice
2819 (face :tag "Font-lock-face")
2820 (plist :tag "Face property list"))
2821 (string :tag "HTML start tag")
2822 (string :tag "HTML end tag")
2823 (option (const verbatim)))))
2825 ;;; Miscellaneous options
2827 (defgroup org-completion nil
2828 "Completion in Org-mode."
2829 :tag "Org Completion"
2830 :group 'org)
2832 (defcustom org-completion-use-ido nil
2833 "Non-nil means, use ido completion wherever possible.
2834 Note that `ido-mode' must be active for this variable to be relevant.
2835 If you decide to turn this variable on, you might well want to turn off
2836 `org-outline-path-complete-in-steps'."
2837 :group 'org-completion
2838 :type 'boolean)
2840 (defcustom org-completion-fallback-command 'hippie-expand
2841 "The expansion command called by \\[org-complete] in normal context.
2842 Normal means, no org-mode-specific context."
2843 :group 'org-completion
2844 :type 'function)
2846 ;;; Functions and variables from ther packages
2847 ;; Declared here to avoid compiler warnings
2849 ;; XEmacs only
2850 (defvar outline-mode-menu-heading)
2851 (defvar outline-mode-menu-show)
2852 (defvar outline-mode-menu-hide)
2853 (defvar zmacs-regions) ; XEmacs regions
2855 ;; Emacs only
2856 (defvar mark-active)
2858 ;; Various packages
2859 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2860 (declare-function calendar-forward-day "cal-move" (arg))
2861 (declare-function calendar-goto-date "cal-move" (date))
2862 (declare-function calendar-goto-today "cal-move" ())
2863 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2864 (defvar calc-embedded-close-formula)
2865 (defvar calc-embedded-open-formula)
2866 (declare-function cdlatex-tab "ext:cdlatex" ())
2867 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2868 (defvar font-lock-unfontify-region-function)
2869 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2870 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2871 (defvar iswitchb-temp-buflist)
2872 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2873 (defvar org-agenda-tags-todo-honor-ignore-options)
2874 (declare-function org-agenda-skip "org-agenda" ())
2875 (declare-function org-format-agenda-item "org-agenda"
2876 (extra txt &optional category tags dotime noprefix remove-re))
2877 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2878 (declare-function org-agenda-change-all-lines "org-agenda"
2879 (newhead hdmarker &optional fixface just-this))
2880 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2881 (declare-function org-agenda-maybe-redo "org-agenda" ())
2882 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2883 (beg end))
2884 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2885 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2886 "org-agenda" (&optional end))
2888 (declare-function parse-time-string "parse-time" (string))
2889 (declare-function remember "remember" (&optional initial))
2890 (declare-function remember-buffer-desc "remember" ())
2891 (declare-function remember-finalize "remember" ())
2892 (defvar remember-save-after-remembering)
2893 (defvar remember-data-file)
2894 (defvar remember-register)
2895 (defvar remember-buffer)
2896 (defvar remember-handler-functions)
2897 (defvar remember-annotation-functions)
2898 (defvar texmathp-why)
2899 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2900 (declare-function table--at-cell-p "table" (position &optional object at-column))
2902 (defvar w3m-current-url)
2903 (defvar w3m-current-title)
2905 (defvar org-latex-regexps)
2907 ;;; Autoload and prepare some org modules
2909 ;; Some table stuff that needs to be defined here, because it is used
2910 ;; by the functions setting up org-mode or checking for table context.
2912 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2913 "Detects an org-type or table-type table.")
2914 (defconst org-table-line-regexp "^[ \t]*|"
2915 "Detects an org-type table line.")
2916 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2917 "Detects an org-type table line.")
2918 (defconst org-table-hline-regexp "^[ \t]*|-"
2919 "Detects an org-type table hline.")
2920 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2921 "Detects a table-type table hline.")
2922 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2923 "Searching from within a table (any type) this finds the first line
2924 outside the table.")
2926 ;; Autoload the functions in org-table.el that are needed by functions here.
2928 (eval-and-compile
2929 (org-autoload "org-table"
2930 '(org-table-align org-table-begin org-table-blank-field
2931 org-table-convert org-table-convert-region org-table-copy-down
2932 org-table-copy-region org-table-create
2933 org-table-create-or-convert-from-region
2934 org-table-create-with-table.el org-table-current-dline
2935 org-table-cut-region org-table-delete-column org-table-edit-field
2936 org-table-edit-formulas org-table-end org-table-eval-formula
2937 org-table-export org-table-field-info
2938 org-table-get-stored-formulas org-table-goto-column
2939 org-table-hline-and-move org-table-import org-table-insert-column
2940 org-table-insert-hline org-table-insert-row org-table-iterate
2941 org-table-justify-field-maybe org-table-kill-row
2942 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2943 org-table-move-column org-table-move-column-left
2944 org-table-move-column-right org-table-move-row
2945 org-table-move-row-down org-table-move-row-up
2946 org-table-next-field org-table-next-row org-table-paste-rectangle
2947 org-table-previous-field org-table-recalculate
2948 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2949 org-table-toggle-coordinate-overlays
2950 org-table-toggle-formula-debugger org-table-wrap-region
2951 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2953 (defun org-at-table-p (&optional table-type)
2954 "Return t if the cursor is inside an org-type table.
2955 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2956 (if org-enable-table-editor
2957 (save-excursion
2958 (beginning-of-line 1)
2959 (looking-at (if table-type org-table-any-line-regexp
2960 org-table-line-regexp)))
2961 nil))
2962 (defsubst org-table-p () (org-at-table-p))
2964 (defun org-at-table.el-p ()
2965 "Return t if and only if we are at a table.el table."
2966 (and (org-at-table-p 'any)
2967 (save-excursion
2968 (goto-char (org-table-begin 'any))
2969 (looking-at org-table1-hline-regexp))))
2970 (defun org-table-recognize-table.el ()
2971 "If there is a table.el table nearby, recognize it and move into it."
2972 (if org-table-tab-recognizes-table.el
2973 (if (org-at-table.el-p)
2974 (progn
2975 (beginning-of-line 1)
2976 (if (looking-at org-table-dataline-regexp)
2978 (if (looking-at org-table1-hline-regexp)
2979 (progn
2980 (beginning-of-line 2)
2981 (if (looking-at org-table-any-border-regexp)
2982 (beginning-of-line -1)))))
2983 (if (re-search-forward "|" (org-table-end t) t)
2984 (progn
2985 (require 'table)
2986 (if (table--at-cell-p (point))
2988 (message "recognizing table.el table...")
2989 (table-recognize-table)
2990 (message "recognizing table.el table...done")))
2991 (error "This should not happen..."))
2993 nil)
2994 nil))
2996 (defun org-at-table-hline-p ()
2997 "Return t if the cursor is inside a hline in a table."
2998 (if org-enable-table-editor
2999 (save-excursion
3000 (beginning-of-line 1)
3001 (looking-at org-table-hline-regexp))
3002 nil))
3004 (defvar org-table-clean-did-remove-column nil)
3006 (defun org-table-map-tables (function)
3007 "Apply FUNCTION to the start of all tables in the buffer."
3008 (save-excursion
3009 (save-restriction
3010 (widen)
3011 (goto-char (point-min))
3012 (while (re-search-forward org-table-any-line-regexp nil t)
3013 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
3014 (beginning-of-line 1)
3015 (if (looking-at org-table-line-regexp)
3016 (save-excursion (funcall function)))
3017 (re-search-forward org-table-any-border-regexp nil 1))))
3018 (message "Mapping tables: done"))
3020 ;; Declare and autoload functions from org-exp.el & Co
3022 (declare-function org-default-export-plist "org-exp")
3023 (declare-function org-infile-export-plist "org-exp")
3024 (declare-function org-get-current-options "org-exp")
3025 (eval-and-compile
3026 (org-autoload "org-exp"
3027 '(org-export org-export-visible
3028 org-insert-export-options-template
3029 org-table-clean-before-export))
3030 (org-autoload "org-ascii"
3031 '(org-export-as-ascii org-export-ascii-preprocess
3032 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3033 org-export-region-as-ascii))
3034 (org-autoload "org-html"
3035 '(org-export-as-html-and-open
3036 org-export-as-html-batch org-export-as-html-to-buffer
3037 org-replace-region-by-html org-export-region-as-html
3038 org-export-as-html))
3039 (org-autoload "org-icalendar"
3040 '(org-export-icalendar-this-file
3041 org-export-icalendar-all-agenda-files
3042 org-export-icalendar-combine-agenda-files))
3043 (org-autoload "org-xoxo" '(org-export-as-xoxo)))
3045 ;; Declare and autoload functions from org-agenda.el
3047 (eval-and-compile
3048 (org-autoload "org-agenda"
3049 '(org-agenda org-agenda-list org-search-view
3050 org-todo-list org-tags-view org-agenda-list-stuck-projects
3051 org-diary org-agenda-to-appt
3052 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3054 ;; Autoload org-remember
3056 (eval-and-compile
3057 (org-autoload "org-remember"
3058 '(org-remember-insinuate org-remember-annotation
3059 org-remember-apply-template org-remember org-remember-handler)))
3061 ;; Autoload org-clock.el
3064 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3065 (beg end))
3066 (declare-function org-clock-update-mode-line "org-clock" ())
3067 (defvar org-clock-start-time)
3068 (defvar org-clock-marker (make-marker)
3069 "Marker recording the last clock-in.")
3071 (eval-and-compile
3072 (org-autoload
3073 "org-clock"
3074 '(org-clock-in org-clock-out org-clock-cancel
3075 org-clock-goto org-clock-sum org-clock-display
3076 org-clock-remove-overlays org-clock-report
3077 org-clocktable-shift org-dblock-write:clocktable
3078 org-get-clocktable)))
3080 (defun org-clock-update-time-maybe ()
3081 "If this is a CLOCK line, update it and return t.
3082 Otherwise, return nil."
3083 (interactive)
3084 (save-excursion
3085 (beginning-of-line 1)
3086 (skip-chars-forward " \t")
3087 (when (looking-at org-clock-string)
3088 (let ((re (concat "[ \t]*" org-clock-string
3089 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3090 "\\([ \t]*=>.*\\)?\\)?"))
3091 ts te h m s neg)
3092 (cond
3093 ((not (looking-at re))
3094 nil)
3095 ((not (match-end 2))
3096 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3097 (> org-clock-marker (point))
3098 (<= org-clock-marker (point-at-eol)))
3099 ;; The clock is running here
3100 (setq org-clock-start-time
3101 (apply 'encode-time
3102 (org-parse-time-string (match-string 1))))
3103 (org-clock-update-mode-line)))
3105 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3106 (end-of-line 1)
3107 (setq ts (match-string 1)
3108 te (match-string 3))
3109 (setq s (- (time-to-seconds
3110 (apply 'encode-time (org-parse-time-string te)))
3111 (time-to-seconds
3112 (apply 'encode-time (org-parse-time-string ts))))
3113 neg (< s 0)
3114 s (abs s)
3115 h (floor (/ s 3600))
3116 s (- s (* 3600 h))
3117 m (floor (/ s 60))
3118 s (- s (* 60 s)))
3119 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3120 t))))))
3122 (defun org-check-running-clock ()
3123 "Check if the current buffer contains the running clock.
3124 If yes, offer to stop it and to save the buffer with the changes."
3125 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3126 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3127 (buffer-name))))
3128 (org-clock-out)
3129 (when (y-or-n-p "Save changed buffer?")
3130 (save-buffer))))
3132 (defun org-clocktable-try-shift (dir n)
3133 "Check if this line starts a clock table, if yes, shift the time block."
3134 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3135 (org-clocktable-shift dir n)))
3137 ;; Autoload org-timer.el
3139 (eval-and-compile
3140 (org-autoload
3141 "org-timer"
3142 '(org-timer-start org-timer org-timer-item
3143 org-timer-change-times-in-region)))
3145 ;; Autoload org-feed.el
3147 (eval-and-compile
3148 (org-autoload
3149 "org-feed"
3150 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3153 ;; Autoload archiving code
3154 ;; The stuff that is needed for cycling and tags has to be defined here.
3156 (defgroup org-archive nil
3157 "Options concerning archiving in Org-mode."
3158 :tag "Org Archive"
3159 :group 'org-structure)
3161 (defcustom org-archive-location "%s_archive::"
3162 "The location where subtrees should be archived.
3164 The value of this variable is a string, consisting of two parts,
3165 separated by a double-colon. The first part is a filename and
3166 the second part is a headline.
3168 When the filename is omitted, archiving happens in the same file.
3169 %s in the filename will be replaced by the current file
3170 name (without the directory part). Archiving to a different file
3171 is useful to keep archived entries from contributing to the
3172 Org-mode Agenda.
3174 The archived entries will be filed as subtrees of the specified
3175 headline. When the headline is omitted, the subtrees are simply
3176 filed away at the end of the file, as top-level entries. Also in
3177 the heading you can use %s to represent the file name, this can be
3178 useful when using the same archive for a number of different files.
3180 Here are a few examples:
3181 \"%s_archive::\"
3182 If the current file is Projects.org, archive in file
3183 Projects.org_archive, as top-level trees. This is the default.
3185 \"::* Archived Tasks\"
3186 Archive in the current file, under the top-level headline
3187 \"* Archived Tasks\".
3189 \"~/org/archive.org::\"
3190 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3192 \"~/org/archive.org::From %s\"
3193 Archive in file ~/org/archive.org (absolute path), und headlines
3194 \"From FILENAME\" where file name is the current file name.
3196 \"basement::** Finished Tasks\"
3197 Archive in file ./basement (relative path), as level 3 trees
3198 below the level 2 heading \"** Finished Tasks\".
3200 You may set this option on a per-file basis by adding to the buffer a
3201 line like
3203 #+ARCHIVE: basement::** Finished Tasks
3205 You may also define it locally for a subtree by setting an ARCHIVE property
3206 in the entry. If such a property is found in an entry, or anywhere up
3207 the hierarchy, it will be used."
3208 :group 'org-archive
3209 :type 'string)
3211 (defcustom org-archive-tag "ARCHIVE"
3212 "The tag that marks a subtree as archived.
3213 An archived subtree does not open during visibility cycling, and does
3214 not contribute to the agenda listings.
3215 After changing this, font-lock must be restarted in the relevant buffers to
3216 get the proper fontification."
3217 :group 'org-archive
3218 :group 'org-keywords
3219 :type 'string)
3221 (defcustom org-agenda-skip-archived-trees t
3222 "Non-nil means, the agenda will skip any items located in archived trees.
3223 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3224 variable is no longer recommended, you should leave it at the value t.
3225 Instead, use the key `v' to cycle the archives-mode in the agenda."
3226 :group 'org-archive
3227 :group 'org-agenda-skip
3228 :type 'boolean)
3230 (defcustom org-columns-skip-arrchived-trees t
3231 "Non-nil means, irgnore archived trees when creating column view."
3232 :group 'org-archive
3233 :group 'org-properties
3234 :type 'boolean)
3236 (defcustom org-cycle-open-archived-trees nil
3237 "Non-nil means, `org-cycle' will open archived trees.
3238 An archived tree is a tree marked with the tag ARCHIVE.
3239 When nil, archived trees will stay folded. You can still open them with
3240 normal outline commands like `show-all', but not with the cycling commands."
3241 :group 'org-archive
3242 :group 'org-cycle
3243 :type 'boolean)
3245 (defcustom org-sparse-tree-open-archived-trees nil
3246 "Non-nil means sparse tree construction shows matches in archived trees.
3247 When nil, matches in these trees are highlighted, but the trees are kept in
3248 collapsed state."
3249 :group 'org-archive
3250 :group 'org-sparse-trees
3251 :type 'boolean)
3253 (defun org-cycle-hide-archived-subtrees (state)
3254 "Re-hide all archived subtrees after a visibility state change."
3255 (when (and (not org-cycle-open-archived-trees)
3256 (not (memq state '(overview folded))))
3257 (save-excursion
3258 (let* ((globalp (memq state '(contents all)))
3259 (beg (if globalp (point-min) (point)))
3260 (end (if globalp (point-max) (org-end-of-subtree t))))
3261 (org-hide-archived-subtrees beg end)
3262 (goto-char beg)
3263 (if (looking-at (concat ".*:" org-archive-tag ":"))
3264 (message "%s" (substitute-command-keys
3265 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3267 (defun org-force-cycle-archived ()
3268 "Cycle subtree even if it is archived."
3269 (interactive)
3270 (setq this-command 'org-cycle)
3271 (let ((org-cycle-open-archived-trees t))
3272 (call-interactively 'org-cycle)))
3274 (defun org-hide-archived-subtrees (beg end)
3275 "Re-hide all archived subtrees after a visibility state change."
3276 (save-excursion
3277 (let* ((re (concat ":" org-archive-tag ":")))
3278 (goto-char beg)
3279 (while (re-search-forward re end t)
3280 (and (org-on-heading-p) (hide-subtree))
3281 (org-end-of-subtree t)))))
3283 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3285 (eval-and-compile
3286 (org-autoload "org-archive"
3287 '(org-add-archive-files org-archive-subtree
3288 org-archive-to-archive-sibling org-toggle-archive-tag)))
3290 ;; Autoload Column View Code
3292 (declare-function org-columns-number-to-string "org-colview")
3293 (declare-function org-columns-get-format-and-top-level "org-colview")
3294 (declare-function org-columns-compute "org-colview")
3296 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3297 '(org-columns-number-to-string org-columns-get-format-and-top-level
3298 org-columns-compute org-agenda-columns org-columns-remove-overlays
3299 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3301 ;; Autoload ID code
3303 (declare-function org-id-store-link "org-id")
3304 (declare-function org-id-locations-load "org-id")
3305 (declare-function org-id-locations-save "org-id")
3306 (defvar org-id-track-globally)
3307 (org-autoload "org-id"
3308 '(org-id-get-create org-id-new org-id-copy org-id-get
3309 org-id-get-with-outline-path-completion
3310 org-id-get-with-outline-drilling
3311 org-id-goto org-id-find org-id-store-link))
3313 ;; Autoload Plotting Code
3315 (org-autoload "org-plot"
3316 '(org-plot/gnuplot))
3318 ;;; Variables for pre-computed regular expressions, all buffer local
3320 (defvar org-drawer-regexp nil
3321 "Matches first line of a hidden block.")
3322 (make-variable-buffer-local 'org-drawer-regexp)
3323 (defvar org-todo-regexp nil
3324 "Matches any of the TODO state keywords.")
3325 (make-variable-buffer-local 'org-todo-regexp)
3326 (defvar org-not-done-regexp nil
3327 "Matches any of the TODO state keywords except the last one.")
3328 (make-variable-buffer-local 'org-not-done-regexp)
3329 (defvar org-not-done-heading-regexp nil
3330 "Matches a TODO headline that is not done.")
3331 (make-variable-buffer-local 'org-not-done-regexp)
3332 (defvar org-todo-line-regexp nil
3333 "Matches a headline and puts TODO state into group 2 if present.")
3334 (make-variable-buffer-local 'org-todo-line-regexp)
3335 (defvar org-complex-heading-regexp nil
3336 "Matches a headline and puts everything into groups:
3337 group 1: the stars
3338 group 2: The todo keyword, maybe
3339 group 3: Priority cookie
3340 group 4: True headline
3341 group 5: Tags")
3342 (make-variable-buffer-local 'org-complex-heading-regexp)
3343 (defvar org-todo-line-tags-regexp nil
3344 "Matches a headline and puts TODO state into group 2 if present.
3345 Also put tags into group 4 if tags are present.")
3346 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3347 (defvar org-nl-done-regexp nil
3348 "Matches newline followed by a headline with the DONE keyword.")
3349 (make-variable-buffer-local 'org-nl-done-regexp)
3350 (defvar org-looking-at-done-regexp nil
3351 "Matches the DONE keyword a point.")
3352 (make-variable-buffer-local 'org-looking-at-done-regexp)
3353 (defvar org-ds-keyword-length 12
3354 "Maximum length of the Deadline and SCHEDULED keywords.")
3355 (make-variable-buffer-local 'org-ds-keyword-length)
3356 (defvar org-deadline-regexp nil
3357 "Matches the DEADLINE keyword.")
3358 (make-variable-buffer-local 'org-deadline-regexp)
3359 (defvar org-deadline-time-regexp nil
3360 "Matches the DEADLINE keyword together with a time stamp.")
3361 (make-variable-buffer-local 'org-deadline-time-regexp)
3362 (defvar org-deadline-line-regexp nil
3363 "Matches the DEADLINE keyword and the rest of the line.")
3364 (make-variable-buffer-local 'org-deadline-line-regexp)
3365 (defvar org-scheduled-regexp nil
3366 "Matches the SCHEDULED keyword.")
3367 (make-variable-buffer-local 'org-scheduled-regexp)
3368 (defvar org-scheduled-time-regexp nil
3369 "Matches the SCHEDULED keyword together with a time stamp.")
3370 (make-variable-buffer-local 'org-scheduled-time-regexp)
3371 (defvar org-closed-time-regexp nil
3372 "Matches the CLOSED keyword together with a time stamp.")
3373 (make-variable-buffer-local 'org-closed-time-regexp)
3375 (defvar org-keyword-time-regexp nil
3376 "Matches any of the 4 keywords, together with the time stamp.")
3377 (make-variable-buffer-local 'org-keyword-time-regexp)
3378 (defvar org-keyword-time-not-clock-regexp nil
3379 "Matches any of the 3 keywords, together with the time stamp.")
3380 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3381 (defvar org-maybe-keyword-time-regexp nil
3382 "Matches a timestamp, possibly preceeded by a keyword.")
3383 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3384 (defvar org-planning-or-clock-line-re nil
3385 "Matches a line with planning or clock info.")
3386 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3388 (defconst org-plain-time-of-day-regexp
3389 (concat
3390 "\\(\\<[012]?[0-9]"
3391 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3392 "\\(--?"
3393 "\\(\\<[012]?[0-9]"
3394 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3395 "\\)?")
3396 "Regular expression to match a plain time or time range.
3397 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3398 groups carry important information:
3399 0 the full match
3400 1 the first time, range or not
3401 8 the second time, if it is a range.")
3403 (defconst org-plain-time-extension-regexp
3404 (concat
3405 "\\(\\<[012]?[0-9]"
3406 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3407 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3408 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3409 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3410 groups carry important information:
3411 0 the full match
3412 7 hours of duration
3413 9 minutes of duration")
3415 (defconst org-stamp-time-of-day-regexp
3416 (concat
3417 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3418 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3419 "\\(--?"
3420 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3421 "Regular expression to match a timestamp time or time range.
3422 After a match, the following groups carry important information:
3423 0 the full match
3424 1 date plus weekday, for backreferencing to make sure both times on same day
3425 2 the first time, range or not
3426 4 the second time, if it is a range.")
3428 (defconst org-startup-options
3429 '(("fold" org-startup-folded t)
3430 ("overview" org-startup-folded t)
3431 ("nofold" org-startup-folded nil)
3432 ("showall" org-startup-folded nil)
3433 ("content" org-startup-folded content)
3434 ("hidestars" org-hide-leading-stars t)
3435 ("showstars" org-hide-leading-stars nil)
3436 ("odd" org-odd-levels-only t)
3437 ("oddeven" org-odd-levels-only nil)
3438 ("align" org-startup-align-all-tables t)
3439 ("noalign" org-startup-align-all-tables nil)
3440 ("customtime" org-display-custom-times t)
3441 ("logdone" org-log-done time)
3442 ("lognotedone" org-log-done note)
3443 ("nologdone" org-log-done nil)
3444 ("lognoteclock-out" org-log-note-clock-out t)
3445 ("nolognoteclock-out" org-log-note-clock-out nil)
3446 ("logrepeat" org-log-repeat state)
3447 ("lognoterepeat" org-log-repeat note)
3448 ("nologrepeat" org-log-repeat nil)
3449 ("fninline" org-footnote-define-inline t)
3450 ("nofninline" org-footnote-define-inline nil)
3451 ("fnlocal" org-footnote-section nil)
3452 ("fnauto" org-footnote-auto-label t)
3453 ("fnprompt" org-footnote-auto-label nil)
3454 ("fnconfirm" org-footnote-auto-label confirm)
3455 ("fnplain" org-footnote-auto-label plain)
3456 ("constcgs" constants-unit-system cgs)
3457 ("constSI" constants-unit-system SI)
3458 ("noptag" org-tag-persistent-alist nil)
3459 ("hideblocks" org-hide-block-startup t)
3460 ("nohideblocks" org-hide-block-startup nil))
3461 "Variable associated with STARTUP options for org-mode.
3462 Each element is a list of three items: The startup options as written
3463 in the #+STARTUP line, the corresponding variable, and the value to
3464 set this variable to if the option is found. An optional forth element PUSH
3465 means to push this value onto the list in the variable.")
3467 (defun org-set-regexps-and-options ()
3468 "Precompute regular expressions for current buffer."
3469 (when (org-mode-p)
3470 (org-set-local 'org-todo-kwd-alist nil)
3471 (org-set-local 'org-todo-key-alist nil)
3472 (org-set-local 'org-todo-key-trigger nil)
3473 (org-set-local 'org-todo-keywords-1 nil)
3474 (org-set-local 'org-done-keywords nil)
3475 (org-set-local 'org-todo-heads nil)
3476 (org-set-local 'org-todo-sets nil)
3477 (org-set-local 'org-todo-log-states nil)
3478 (org-set-local 'org-file-properties nil)
3479 (org-set-local 'org-file-tags nil)
3480 (let ((re (org-make-options-regexp
3481 '("CATEGORY" "TODO" "COLUMNS"
3482 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3483 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3484 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3485 (splitre "[ \t]+")
3486 kwds kws0 kwsa key log value cat arch tags const links hw dws
3487 tail sep kws1 prio props ftags drawers
3488 ext-setup-or-nil setup-contents (start 0))
3489 (save-excursion
3490 (save-restriction
3491 (widen)
3492 (goto-char (point-min))
3493 (while (or (and ext-setup-or-nil
3494 (string-match re ext-setup-or-nil start)
3495 (setq start (match-end 0)))
3496 (and (setq ext-setup-or-nil nil start 0)
3497 (re-search-forward re nil t)))
3498 (setq key (upcase (match-string 1 ext-setup-or-nil))
3499 value (org-match-string-no-properties 2 ext-setup-or-nil))
3500 (cond
3501 ((equal key "CATEGORY")
3502 (if (string-match "[ \t]+$" value)
3503 (setq value (replace-match "" t t value)))
3504 (setq cat value))
3505 ((member key '("SEQ_TODO" "TODO"))
3506 (push (cons 'sequence (org-split-string value splitre)) kwds))
3507 ((equal key "TYP_TODO")
3508 (push (cons 'type (org-split-string value splitre)) kwds))
3509 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3510 ;; general TODO-like setup
3511 (push (cons (intern (downcase (match-string 1 key)))
3512 (org-split-string value splitre)) kwds))
3513 ((equal key "TAGS")
3514 (setq tags (append tags (if tags '("\\n") nil)
3515 (org-split-string value splitre))))
3516 ((equal key "COLUMNS")
3517 (org-set-local 'org-columns-default-format value))
3518 ((equal key "LINK")
3519 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3520 (push (cons (match-string 1 value)
3521 (org-trim (match-string 2 value)))
3522 links)))
3523 ((equal key "PRIORITIES")
3524 (setq prio (org-split-string value " +")))
3525 ((equal key "PROPERTY")
3526 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3527 (push (cons (match-string 1 value) (match-string 2 value))
3528 props)))
3529 ((equal key "FILETAGS")
3530 (when (string-match "\\S-" value)
3531 (setq ftags
3532 (append
3533 ftags
3534 (apply 'append
3535 (mapcar (lambda (x) (org-split-string x ":"))
3536 (org-split-string value)))))))
3537 ((equal key "DRAWERS")
3538 (setq drawers (org-split-string value splitre)))
3539 ((equal key "CONSTANTS")
3540 (setq const (append const (org-split-string value splitre))))
3541 ((equal key "STARTUP")
3542 (let ((opts (org-split-string value splitre))
3543 l var val)
3544 (while (setq l (pop opts))
3545 (when (setq l (assoc l org-startup-options))
3546 (setq var (nth 1 l) val (nth 2 l))
3547 (if (not (nth 3 l))
3548 (set (make-local-variable var) val)
3549 (if (not (listp (symbol-value var)))
3550 (set (make-local-variable var) nil))
3551 (set (make-local-variable var) (symbol-value var))
3552 (add-to-list var val))))))
3553 ((equal key "ARCHIVE")
3554 (string-match " *$" value)
3555 (setq arch (replace-match "" t t value))
3556 (remove-text-properties 0 (length arch)
3557 '(face t fontified t) arch))
3558 ((equal key "SETUPFILE")
3559 (setq setup-contents (org-file-contents
3560 (expand-file-name
3561 (org-remove-double-quotes value))
3562 'noerror))
3563 (if (not ext-setup-or-nil)
3564 (setq ext-setup-or-nil setup-contents start 0)
3565 (setq ext-setup-or-nil
3566 (concat (substring ext-setup-or-nil 0 start)
3567 "\n" setup-contents "\n"
3568 (substring ext-setup-or-nil start)))))
3569 ))))
3570 (when cat
3571 (org-set-local 'org-category (intern cat))
3572 (push (cons "CATEGORY" cat) props))
3573 (when prio
3574 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3575 (setq prio (mapcar 'string-to-char prio))
3576 (org-set-local 'org-highest-priority (nth 0 prio))
3577 (org-set-local 'org-lowest-priority (nth 1 prio))
3578 (org-set-local 'org-default-priority (nth 2 prio)))
3579 (and props (org-set-local 'org-file-properties (nreverse props)))
3580 (and ftags (org-set-local 'org-file-tags
3581 (mapcar 'org-add-prop-inherited ftags)))
3582 (and drawers (org-set-local 'org-drawers drawers))
3583 (and arch (org-set-local 'org-archive-location arch))
3584 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3585 ;; Process the TODO keywords
3586 (unless kwds
3587 ;; Use the global values as if they had been given locally.
3588 (setq kwds (default-value 'org-todo-keywords))
3589 (if (stringp (car kwds))
3590 (setq kwds (list (cons org-todo-interpretation
3591 (default-value 'org-todo-keywords)))))
3592 (setq kwds (reverse kwds)))
3593 (setq kwds (nreverse kwds))
3594 (let (inter kws kw)
3595 (while (setq kws (pop kwds))
3596 (let ((kws (or
3597 (run-hook-with-args-until-success
3598 'org-todo-setup-filter-hook kws)
3599 kws)))
3600 (setq inter (pop kws) sep (member "|" kws)
3601 kws0 (delete "|" (copy-sequence kws))
3602 kwsa nil
3603 kws1 (mapcar
3604 (lambda (x)
3605 ;; 1 2
3606 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3607 (progn
3608 (setq kw (match-string 1 x)
3609 key (and (match-end 2) (match-string 2 x))
3610 log (org-extract-log-state-settings x))
3611 (push (cons kw (and key (string-to-char key))) kwsa)
3612 (and log (push log org-todo-log-states))
3614 (error "Invalid TODO keyword %s" x)))
3615 kws0)
3616 kwsa (if kwsa (append '((:startgroup))
3617 (nreverse kwsa)
3618 '((:endgroup))))
3619 hw (car kws1)
3620 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3621 tail (list inter hw (car dws) (org-last dws))))
3622 (add-to-list 'org-todo-heads hw 'append)
3623 (push kws1 org-todo-sets)
3624 (setq org-done-keywords (append org-done-keywords dws nil))
3625 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3626 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3627 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3628 (setq org-todo-sets (nreverse org-todo-sets)
3629 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3630 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3631 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3632 ;; Process the constants
3633 (when const
3634 (let (e cst)
3635 (while (setq e (pop const))
3636 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3637 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3638 (setq org-table-formula-constants-local cst)))
3640 ;; Process the tags.
3641 (when tags
3642 (let (e tgs)
3643 (while (setq e (pop tags))
3644 (cond
3645 ((equal e "{") (push '(:startgroup) tgs))
3646 ((equal e "}") (push '(:endgroup) tgs))
3647 ((equal e "\\n") (push '(:newline) tgs))
3648 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3649 (push (cons (match-string 1 e)
3650 (string-to-char (match-string 2 e)))
3651 tgs))
3652 (t (push (list e) tgs))))
3653 (org-set-local 'org-tag-alist nil)
3654 (while (setq e (pop tgs))
3655 (or (and (stringp (car e))
3656 (assoc (car e) org-tag-alist))
3657 (push e org-tag-alist)))))
3659 ;; Compute the regular expressions and other local variables
3660 (if (not org-done-keywords)
3661 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3662 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3663 (length org-scheduled-string)
3664 (length org-clock-string)
3665 (length org-closed-string)))
3666 org-drawer-regexp
3667 (concat "^[ \t]*:\\("
3668 (mapconcat 'regexp-quote org-drawers "\\|")
3669 "\\):[ \t]*$")
3670 org-not-done-keywords
3671 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3672 org-todo-regexp
3673 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3674 "\\|") "\\)\\>")
3675 org-not-done-regexp
3676 (concat "\\<\\("
3677 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3678 "\\)\\>")
3679 org-not-done-heading-regexp
3680 (concat "^\\(\\*+\\)[ \t]+\\("
3681 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3682 "\\)\\>")
3683 org-todo-line-regexp
3684 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3685 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3686 "\\)\\>\\)?[ \t]*\\(.*\\)")
3687 org-complex-heading-regexp
3688 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3689 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3690 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3691 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3692 org-nl-done-regexp
3693 (concat "\n\\*+[ \t]+"
3694 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3695 "\\)" "\\>")
3696 org-todo-line-tags-regexp
3697 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3698 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3699 (org-re
3700 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3701 org-looking-at-done-regexp
3702 (concat "^" "\\(?:"
3703 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3704 "\\>")
3705 org-deadline-regexp (concat "\\<" org-deadline-string)
3706 org-deadline-time-regexp
3707 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3708 org-deadline-line-regexp
3709 (concat "\\<\\(" org-deadline-string "\\).*")
3710 org-scheduled-regexp
3711 (concat "\\<" org-scheduled-string)
3712 org-scheduled-time-regexp
3713 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3714 org-closed-time-regexp
3715 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3716 org-keyword-time-regexp
3717 (concat "\\<\\(" org-scheduled-string
3718 "\\|" org-deadline-string
3719 "\\|" org-closed-string
3720 "\\|" org-clock-string "\\)"
3721 " *[[<]\\([^]>]+\\)[]>]")
3722 org-keyword-time-not-clock-regexp
3723 (concat "\\<\\(" org-scheduled-string
3724 "\\|" org-deadline-string
3725 "\\|" org-closed-string
3726 "\\)"
3727 " *[[<]\\([^]>]+\\)[]>]")
3728 org-maybe-keyword-time-regexp
3729 (concat "\\(\\<\\(" org-scheduled-string
3730 "\\|" org-deadline-string
3731 "\\|" org-closed-string
3732 "\\|" org-clock-string "\\)\\)?"
3733 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3734 org-planning-or-clock-line-re
3735 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3736 "\\|" org-deadline-string
3737 "\\|" org-closed-string "\\|" org-clock-string
3738 "\\)\\>\\)")
3740 (org-compute-latex-and-specials-regexp)
3741 (org-set-font-lock-defaults))))
3743 (defun org-file-contents (file &optional noerror)
3744 "Return the contents of FILE, as a string."
3745 (if (or (not file)
3746 (not (file-readable-p file)))
3747 (if noerror
3748 (progn
3749 (message "Cannot read file %s" file)
3750 (ding) (sit-for 2)
3752 (error "Cannot read file %s" file))
3753 (with-temp-buffer
3754 (insert-file-contents file)
3755 (buffer-string))))
3757 (defun org-extract-log-state-settings (x)
3758 "Extract the log state setting from a TODO keyword string.
3759 This will extract info from a string like \"WAIT(w@/!)\"."
3760 (let (kw key log1 log2)
3761 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3762 (setq kw (match-string 1 x)
3763 key (and (match-end 2) (match-string 2 x))
3764 log1 (and (match-end 3) (match-string 3 x))
3765 log2 (and (match-end 4) (match-string 4 x)))
3766 (and (or log1 log2)
3767 (list kw
3768 (and log1 (if (equal log1 "!") 'time 'note))
3769 (and log2 (if (equal log2 "!") 'time 'note)))))))
3771 (defun org-remove-keyword-keys (list)
3772 "Remove a pair of parenthesis at the end of each string in LIST."
3773 (mapcar (lambda (x)
3774 (if (string-match "(.*)$" x)
3775 (substring x 0 (match-beginning 0))
3777 list))
3779 ;; FIXME: this could be done much better, using second characters etc.
3780 (defun org-assign-fast-keys (alist)
3781 "Assign fast keys to a keyword-key alist.
3782 Respect keys that are already there."
3783 (let (new e k c c1 c2 (char ?a))
3784 (while (setq e (pop alist))
3785 (cond
3786 ((equal e '(:startgroup)) (push e new))
3787 ((equal e '(:endgroup)) (push e new))
3788 ((equal e '(:newline)) (push e new))
3790 (setq k (car e) c2 nil)
3791 (if (cdr e)
3792 (setq c (cdr e))
3793 ;; automatically assign a character.
3794 (setq c1 (string-to-char
3795 (downcase (substring
3796 k (if (= (string-to-char k) ?@) 1 0)))))
3797 (if (or (rassoc c1 new) (rassoc c1 alist))
3798 (while (or (rassoc char new) (rassoc char alist))
3799 (setq char (1+ char)))
3800 (setq c2 c1))
3801 (setq c (or c2 char)))
3802 (push (cons k c) new))))
3803 (nreverse new)))
3805 ;;; Some variables used in various places
3807 (defvar org-window-configuration nil
3808 "Used in various places to store a window configuration.")
3809 (defvar org-finish-function nil
3810 "Function to be called when `C-c C-c' is used.
3811 This is for getting out of special buffers like remember.")
3814 ;; FIXME: Occasionally check by commenting these, to make sure
3815 ;; no other functions uses these, forgetting to let-bind them.
3816 (defvar entry)
3817 (defvar state)
3818 (defvar last-state)
3819 (defvar date)
3820 (defvar description)
3822 ;; Defined somewhere in this file, but used before definition.
3823 (defvar org-html-entities)
3824 (defvar org-struct-menu)
3825 (defvar org-org-menu)
3826 (defvar org-tbl-menu)
3827 (defvar org-agenda-keymap)
3829 ;;;; Define the Org-mode
3831 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3832 (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."))
3835 ;; We use a before-change function to check if a table might need
3836 ;; an update.
3837 (defvar org-table-may-need-update t
3838 "Indicates that a table might need an update.
3839 This variable is set by `org-before-change-function'.
3840 `org-table-align' sets it back to nil.")
3841 (defun org-before-change-function (beg end)
3842 "Every change indicates that a table might need an update."
3843 (setq org-table-may-need-update t))
3844 (defvar org-mode-map)
3845 (defvar org-mode-hook nil
3846 "Mode hook for Org-mode, run after the mode was turned on.")
3847 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3848 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3849 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
3850 (defvar org-table-buffer-is-an nil)
3851 (defconst org-outline-regexp "\\*+ ")
3853 ;;;###autoload
3854 (define-derived-mode org-mode outline-mode "Org"
3855 "Outline-based notes management and organizer, alias
3856 \"Carsten's outline-mode for keeping track of everything.\"
3858 Org-mode develops organizational tasks around a NOTES file which
3859 contains information about projects as plain text. Org-mode is
3860 implemented on top of outline-mode, which is ideal to keep the content
3861 of large files well structured. It supports ToDo items, deadlines and
3862 time stamps, which magically appear in the diary listing of the Emacs
3863 calendar. Tables are easily created with a built-in table editor.
3864 Plain text URL-like links connect to websites, emails (VM), Usenet
3865 messages (Gnus), BBDB entries, and any files related to the project.
3866 For printing and sharing of notes, an Org-mode file (or a part of it)
3867 can be exported as a structured ASCII or HTML file.
3869 The following commands are available:
3871 \\{org-mode-map}"
3873 ;; Get rid of Outline menus, they are not needed
3874 ;; Need to do this here because define-derived-mode sets up
3875 ;; the keymap so late. Still, it is a waste to call this each time
3876 ;; we switch another buffer into org-mode.
3877 (if (featurep 'xemacs)
3878 (when (boundp 'outline-mode-menu-heading)
3879 ;; Assume this is Greg's port, it used easymenu
3880 (easy-menu-remove outline-mode-menu-heading)
3881 (easy-menu-remove outline-mode-menu-show)
3882 (easy-menu-remove outline-mode-menu-hide))
3883 (define-key org-mode-map [menu-bar headings] 'undefined)
3884 (define-key org-mode-map [menu-bar hide] 'undefined)
3885 (define-key org-mode-map [menu-bar show] 'undefined))
3887 (org-load-modules-maybe)
3888 (easy-menu-add org-org-menu)
3889 (easy-menu-add org-tbl-menu)
3890 (org-install-agenda-files-menu)
3891 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3892 (org-add-to-invisibility-spec '(org-cwidth))
3893 (org-add-to-invisibility-spec '(org-hide-block . t))
3894 (when (featurep 'xemacs)
3895 (org-set-local 'line-move-ignore-invisible t))
3896 (org-set-local 'outline-regexp org-outline-regexp)
3897 (org-set-local 'outline-level 'org-outline-level)
3898 (when (and org-ellipsis
3899 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3900 (fboundp 'make-glyph-code))
3901 (unless org-display-table
3902 (setq org-display-table (make-display-table)))
3903 (set-display-table-slot
3904 org-display-table 4
3905 (vconcat (mapcar
3906 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3907 org-ellipsis)))
3908 (if (stringp org-ellipsis) org-ellipsis "..."))))
3909 (setq buffer-display-table org-display-table))
3910 (org-set-regexps-and-options)
3911 (when (and org-tag-faces (not org-tags-special-faces-re))
3912 ;; tag faces set outside customize.... force initialization.
3913 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3914 ;; Calc embedded
3915 (org-set-local 'calc-embedded-open-mode "# ")
3916 (modify-syntax-entry ?# "<")
3917 (modify-syntax-entry ?@ "w")
3918 (if org-startup-truncated (setq truncate-lines t))
3919 (org-set-local 'font-lock-unfontify-region-function
3920 'org-unfontify-region)
3921 ;; Activate before-change-function
3922 (org-set-local 'org-table-may-need-update t)
3923 (org-add-hook 'before-change-functions 'org-before-change-function nil
3924 'local)
3925 ;; Check for running clock before killing a buffer
3926 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3927 ;; Paragraphs and auto-filling
3928 (org-set-autofill-regexps)
3929 (setq indent-line-function 'org-indent-line-function)
3930 (org-update-radio-target-regexp)
3931 ;; Make sure dependence stuff works reliably, even for users who set it
3932 ;; too late :-(
3933 (if org-enforce-todo-dependencies
3934 (add-hook 'org-blocker-hook
3935 'org-block-todo-from-children-or-siblings-or-parent)
3936 (remove-hook 'org-blocker-hook
3937 'org-block-todo-from-children-or-siblings-or-parent))
3938 (if org-enforce-todo-checkbox-dependencies
3939 (add-hook 'org-blocker-hook
3940 'org-block-todo-from-checkboxes)
3941 (remove-hook 'org-blocker-hook
3942 'org-block-todo-from-checkboxes))
3944 ;; Comment characters
3945 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3946 (org-set-local 'comment-padding " ")
3948 ;; Align options lines
3949 (org-set-local
3950 'align-mode-rules-list
3951 '((org-in-buffer-settings
3952 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3953 (modes . '(org-mode)))))
3955 ;; Imenu
3956 (org-set-local 'imenu-create-index-function
3957 'org-imenu-get-tree)
3959 ;; Make isearch reveal context
3960 (if (or (featurep 'xemacs)
3961 (not (boundp 'outline-isearch-open-invisible-function)))
3962 ;; Emacs 21 and XEmacs make use of the hook
3963 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3964 ;; Emacs 22 deals with this through a special variable
3965 (org-set-local 'outline-isearch-open-invisible-function
3966 (lambda (&rest ignore) (org-show-context 'isearch))))
3968 ;; If empty file that did not turn on org-mode automatically, make it to.
3969 (if (and org-insert-mode-line-in-empty-file
3970 (interactive-p)
3971 (= (point-min) (point-max)))
3972 (insert "# -*- mode: org -*-\n\n"))
3974 (unless org-inhibit-startup
3975 (when org-startup-align-all-tables
3976 (let ((bmp (buffer-modified-p)))
3977 (org-table-map-tables 'org-table-align)
3978 (set-buffer-modified-p bmp)))
3979 (org-set-startup-visibility)))
3981 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3983 (defun org-current-time ()
3984 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3985 (if (> (car org-time-stamp-rounding-minutes) 1)
3986 (let ((r (car org-time-stamp-rounding-minutes))
3987 (time (decode-time)))
3988 (apply 'encode-time
3989 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3990 (nthcdr 2 time))))
3991 (current-time)))
3993 ;;;; Font-Lock stuff, including the activators
3995 (defvar org-mouse-map (make-sparse-keymap))
3996 (org-defkey org-mouse-map
3997 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3998 (org-defkey org-mouse-map
3999 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4000 (when org-mouse-1-follows-link
4001 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4002 (when org-tab-follows-link
4003 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4004 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4006 (require 'font-lock)
4008 (defconst org-non-link-chars "]\t\n\r<>")
4009 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4010 "shell" "elisp"))
4011 (defvar org-link-types-re nil
4012 "Matches a link that has a url-like prefix like \"http:\"")
4013 (defvar org-link-re-with-space nil
4014 "Matches a link with spaces, optional angular brackets around it.")
4015 (defvar org-link-re-with-space2 nil
4016 "Matches a link with spaces, optional angular brackets around it.")
4017 (defvar org-link-re-with-space3 nil
4018 "Matches a link with spaces, only for internal part in bracket links.")
4019 (defvar org-angle-link-re nil
4020 "Matches link with angular brackets, spaces are allowed.")
4021 (defvar org-plain-link-re nil
4022 "Matches plain link, without spaces.")
4023 (defvar org-bracket-link-regexp nil
4024 "Matches a link in double brackets.")
4025 (defvar org-bracket-link-analytic-regexp nil
4026 "Regular expression used to analyze links.
4027 Here is what the match groups contain after a match:
4028 1: http:
4029 2: http
4030 3: path
4031 4: [desc]
4032 5: desc")
4033 (defvar org-bracket-link-analytic-regexp++ nil
4034 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4035 (defvar org-any-link-re nil
4036 "Regular expression matching any link.")
4038 (defun org-make-link-regexps ()
4039 "Update the link regular expressions.
4040 This should be called after the variable `org-link-types' has changed."
4041 (setq org-link-types-re
4042 (concat
4043 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
4044 org-link-re-with-space
4045 (concat
4046 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4047 "\\([^" org-non-link-chars " ]"
4048 "[^" org-non-link-chars "]*"
4049 "[^" org-non-link-chars " ]\\)>?")
4050 org-link-re-with-space2
4051 (concat
4052 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4053 "\\([^" org-non-link-chars " ]"
4054 "[^\t\n\r]*"
4055 "[^" org-non-link-chars " ]\\)>?")
4056 org-link-re-with-space3
4057 (concat
4058 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4059 "\\([^" org-non-link-chars " ]"
4060 "[^\t\n\r]*\\)")
4061 org-angle-link-re
4062 (concat
4063 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4064 "\\([^" org-non-link-chars " ]"
4065 "[^" org-non-link-chars "]*"
4066 "\\)>")
4067 org-plain-link-re
4068 (concat
4069 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4070 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4071 org-bracket-link-regexp
4072 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4073 org-bracket-link-analytic-regexp
4074 (concat
4075 "\\[\\["
4076 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4077 "\\([^]]+\\)"
4078 "\\]"
4079 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4080 "\\]")
4081 org-bracket-link-analytic-regexp++
4082 (concat
4083 "\\[\\["
4084 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4085 "\\([^]]+\\)"
4086 "\\]"
4087 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4088 "\\]")
4089 org-any-link-re
4090 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4091 org-angle-link-re "\\)\\|\\("
4092 org-plain-link-re "\\)")))
4094 (org-make-link-regexps)
4096 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4097 "Regular expression for fast time stamp matching.")
4098 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4099 "Regular expression for fast time stamp matching.")
4100 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4101 "Regular expression matching time strings for analysis.
4102 This one does not require the space after the date, so it can be used
4103 on a string that terminates immediately after the date.")
4104 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4105 "Regular expression matching time strings for analysis.")
4106 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4107 "Regular expression matching time stamps, with groups.")
4108 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4109 "Regular expression matching time stamps (also [..]), with groups.")
4110 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4111 "Regular expression matching a time stamp range.")
4112 (defconst org-tr-regexp-both
4113 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4114 "Regular expression matching a time stamp range.")
4115 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4116 org-ts-regexp "\\)?")
4117 "Regular expression matching a time stamp or time stamp range.")
4118 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4119 org-ts-regexp-both "\\)?")
4120 "Regular expression matching a time stamp or time stamp range.
4121 The time stamps may be either active or inactive.")
4123 (defvar org-emph-face nil)
4125 (defun org-do-emphasis-faces (limit)
4126 "Run through the buffer and add overlays to links."
4127 (let (rtn a)
4128 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4129 (if (not (= (char-after (match-beginning 3))
4130 (char-after (match-beginning 4))))
4131 (progn
4132 (setq rtn t)
4133 (setq a (assoc (match-string 3) org-emphasis-alist))
4134 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4135 'face
4136 (nth 1 a))
4137 (and (nth 4 a)
4138 (org-remove-flyspell-overlays-in
4139 (match-beginning 0) (match-end 0)))
4140 (add-text-properties (match-beginning 2) (match-end 2)
4141 '(font-lock-multiline t))
4142 (when org-hide-emphasis-markers
4143 (add-text-properties (match-end 4) (match-beginning 5)
4144 '(invisible org-link))
4145 (add-text-properties (match-beginning 3) (match-end 3)
4146 '(invisible org-link)))))
4147 (backward-char 1))
4148 rtn))
4150 (defun org-emphasize (&optional char)
4151 "Insert or change an emphasis, i.e. a font like bold or italic.
4152 If there is an active region, change that region to a new emphasis.
4153 If there is no region, just insert the marker characters and position
4154 the cursor between them.
4155 CHAR should be either the marker character, or the first character of the
4156 HTML tag associated with that emphasis. If CHAR is a space, the means
4157 to remove the emphasis of the selected region.
4158 If char is not given (for example in an interactive call) it
4159 will be prompted for."
4160 (interactive)
4161 (let ((eal org-emphasis-alist) e det
4162 (erc org-emphasis-regexp-components)
4163 (prompt "")
4164 (string "") beg end move tag c s)
4165 (if (org-region-active-p)
4166 (setq beg (region-beginning) end (region-end)
4167 string (buffer-substring beg end))
4168 (setq move t))
4170 (while (setq e (pop eal))
4171 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4172 c (aref tag 0))
4173 (push (cons c (string-to-char (car e))) det)
4174 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4175 (substring tag 1)))))
4176 (setq det (nreverse det))
4177 (unless char
4178 (message "%s" (concat "Emphasis marker or tag:" prompt))
4179 (setq char (read-char-exclusive)))
4180 (setq char (or (cdr (assoc char det)) char))
4181 (if (equal char ?\ )
4182 (setq s "" move nil)
4183 (unless (assoc (char-to-string char) org-emphasis-alist)
4184 (error "No such emphasis marker: \"%c\"" char))
4185 (setq s (char-to-string char)))
4186 (while (and (> (length string) 1)
4187 (equal (substring string 0 1) (substring string -1))
4188 (assoc (substring string 0 1) org-emphasis-alist))
4189 (setq string (substring string 1 -1)))
4190 (setq string (concat s string s))
4191 (if beg (delete-region beg end))
4192 (unless (or (bolp)
4193 (string-match (concat "[" (nth 0 erc) "\n]")
4194 (char-to-string (char-before (point)))))
4195 (insert " "))
4196 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4197 (char-to-string (char-after (point))))
4198 (insert " ") (backward-char 1))
4199 (insert string)
4200 (and move (backward-char 1))))
4202 (defconst org-nonsticky-props
4203 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4205 (defsubst org-rear-nonsticky-at (pos)
4206 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4208 (defun org-activate-plain-links (limit)
4209 "Run through the buffer and add overlays to links."
4210 (catch 'exit
4211 (let (f)
4212 (while (re-search-forward org-plain-link-re limit t)
4213 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4214 (setq f (get-text-property (match-beginning 0) 'face))
4215 (if (or (eq f 'org-tag)
4216 (and (listp f) (memq 'org-tag f)))
4218 (add-text-properties (match-beginning 0) (match-end 0)
4219 (list 'mouse-face 'highlight
4220 'keymap org-mouse-map))
4221 (org-rear-nonsticky-at (match-end 0))
4222 (throw 'exit t))))))
4224 (defun org-activate-code (limit)
4225 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4226 (progn
4227 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4228 (remove-text-properties (match-beginning 0) (match-end 0)
4229 '(display t invisible t intangible t))
4230 t)))
4232 (defvar org-protecting-blocks
4233 '("src" "example" "latex" "ascii" "html" "docbook")
4234 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4235 This is needed for font-lock setup.")
4237 (defun org-fontify-meta-lines-and-blocks (limit)
4238 "Fontify #+ lines and blocks, in the correct ways."
4239 (let ((case-fold-search t))
4240 (if (re-search-forward
4241 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4242 limit t)
4243 (let ((beg (match-beginning 0))
4244 (beg1 (line-beginning-position 2))
4245 (dc1 (downcase (match-string 2)))
4246 (dc3 (downcase (match-string 3)))
4247 end end1 quoting)
4248 (cond
4249 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4250 ;; a single line of backend-specific content
4251 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4252 (remove-text-properties (match-beginning 0) (match-end 0)
4253 '(display t invisible t intangible t))
4254 (add-text-properties (match-beginning 1) (match-end 3)
4255 '(font-lock-fontified t face org-meta-line))
4256 (add-text-properties (match-beginning 6) (match-end 6)
4257 '(font-lock-fontified t face org-block))
4259 ((and (match-end 4) (equal dc3 "begin"))
4260 ;; Truely a block
4261 (setq quoting (member (downcase (match-string 5))
4262 org-protecting-blocks))
4263 (when (re-search-forward
4264 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4265 nil t) ;; on purpose, we look further than LIMIT
4266 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4267 (when quoting
4268 (remove-text-properties beg end
4269 '(display t invisible t intangible t)))
4270 (add-text-properties
4271 beg end
4272 '(font-lock-fontified t font-lock-multiline t))
4273 (add-text-properties beg beg1 '(face org-meta-line))
4274 (add-text-properties end1 end '(face org-meta-line))
4275 (when quoting
4276 (add-text-properties beg1 end1 '(face org-block)))
4278 ((not (member (char-after beg) '(?\ ?\t)))
4279 ;; just any other in-buffer setting, but not indented
4280 (add-text-properties
4281 beg (match-end 0)
4282 '(font-lock-fontified t face org-meta-line))
4284 ((or (member dc1 '("caption:" "label:" "orgtbl:" "tblfm:"))
4285 (and (match-end 4) (equal dc3 "attr")))
4286 (add-text-properties
4287 beg (match-end 0)
4288 '(font-lock-fontified t face org-meta-line))
4290 (t nil))))))
4292 (defun org-activate-angle-links (limit)
4293 "Run through the buffer and add overlays to links."
4294 (if (re-search-forward org-angle-link-re limit t)
4295 (progn
4296 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4297 (add-text-properties (match-beginning 0) (match-end 0)
4298 (list 'mouse-face 'highlight
4299 'keymap org-mouse-map))
4300 (org-rear-nonsticky-at (match-end 0))
4301 t)))
4303 (defun org-activate-footnote-links (limit)
4304 "Run through the buffer and add overlays to links."
4305 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4306 limit t)
4307 (progn
4308 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4309 (add-text-properties (match-beginning 2) (match-end 2)
4310 (list 'mouse-face 'highlight
4311 'keymap org-mouse-map
4312 'help-echo
4313 (if (= (point-at-bol) (match-beginning 2))
4314 "Footnote definition"
4315 "Footnote reference")
4317 (org-rear-nonsticky-at (match-end 2))
4318 t)))
4320 (defun org-activate-bracket-links (limit)
4321 "Run through the buffer and add overlays to bracketed links."
4322 (if (re-search-forward org-bracket-link-regexp limit t)
4323 (let* ((help (concat "LINK: "
4324 (org-match-string-no-properties 1)))
4325 ;; FIXME: above we should remove the escapes.
4326 ;; but that requires another match, protecting match data,
4327 ;; a lot of overhead for font-lock.
4328 (ip (org-maybe-intangible
4329 (list 'invisible 'org-link
4330 'keymap org-mouse-map 'mouse-face 'highlight
4331 'font-lock-multiline t 'help-echo help)))
4332 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4333 'font-lock-multiline t 'help-echo help)))
4334 ;; We need to remove the invisible property here. Table narrowing
4335 ;; may have made some of this invisible.
4336 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4337 (remove-text-properties (match-beginning 0) (match-end 0)
4338 '(invisible nil))
4339 (if (match-end 3)
4340 (progn
4341 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4342 (org-rear-nonsticky-at (match-beginning 3))
4343 (add-text-properties (match-beginning 3) (match-end 3) vp)
4344 (org-rear-nonsticky-at (match-end 3))
4345 (add-text-properties (match-end 3) (match-end 0) ip)
4346 (org-rear-nonsticky-at (match-end 0)))
4347 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4348 (org-rear-nonsticky-at (match-beginning 1))
4349 (add-text-properties (match-beginning 1) (match-end 1) vp)
4350 (org-rear-nonsticky-at (match-end 1))
4351 (add-text-properties (match-end 1) (match-end 0) ip)
4352 (org-rear-nonsticky-at (match-end 0)))
4353 t)))
4355 (defun org-activate-dates (limit)
4356 "Run through the buffer and add overlays to dates."
4357 (if (re-search-forward org-tsr-regexp-both limit t)
4358 (progn
4359 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4360 (add-text-properties (match-beginning 0) (match-end 0)
4361 (list 'mouse-face 'highlight
4362 'keymap org-mouse-map))
4363 (org-rear-nonsticky-at (match-end 0))
4364 (when org-display-custom-times
4365 (if (match-end 3)
4366 (org-display-custom-time (match-beginning 3) (match-end 3)))
4367 (org-display-custom-time (match-beginning 1) (match-end 1)))
4368 t)))
4370 (defvar org-target-link-regexp nil
4371 "Regular expression matching radio targets in plain text.")
4372 (make-variable-buffer-local 'org-target-link-regexp)
4373 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4374 "Regular expression matching a link target.")
4375 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4376 "Regular expression matching a radio target.")
4377 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4378 "Regular expression matching any target.")
4380 (defun org-activate-target-links (limit)
4381 "Run through the buffer and add overlays to target matches."
4382 (when org-target-link-regexp
4383 (let ((case-fold-search t))
4384 (if (re-search-forward org-target-link-regexp limit t)
4385 (progn
4386 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4387 (add-text-properties (match-beginning 0) (match-end 0)
4388 (list 'mouse-face 'highlight
4389 'keymap org-mouse-map
4390 'help-echo "Radio target link"
4391 'org-linked-text t))
4392 (org-rear-nonsticky-at (match-end 0))
4393 t)))))
4395 (defun org-update-radio-target-regexp ()
4396 "Find all radio targets in this file and update the regular expression."
4397 (interactive)
4398 (when (memq 'radio org-activate-links)
4399 (setq org-target-link-regexp
4400 (org-make-target-link-regexp (org-all-targets 'radio)))
4401 (org-restart-font-lock)))
4403 (defun org-hide-wide-columns (limit)
4404 (let (s e)
4405 (setq s (text-property-any (point) (or limit (point-max))
4406 'org-cwidth t))
4407 (when s
4408 (setq e (next-single-property-change s 'org-cwidth))
4409 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4410 (goto-char e)
4411 t)))
4413 (defvar org-latex-and-specials-regexp nil
4414 "Regular expression for highlighting export special stuff.")
4415 (defvar org-match-substring-regexp)
4416 (defvar org-match-substring-with-braces-regexp)
4417 (defvar org-export-html-special-string-regexps)
4419 (defun org-compute-latex-and-specials-regexp ()
4420 "Compute regular expression for stuff treated specially by exporters."
4421 (if (not org-highlight-latex-fragments-and-specials)
4422 (org-set-local 'org-latex-and-specials-regexp nil)
4423 (require 'org-exp)
4424 (let*
4425 ((matchers (plist-get org-format-latex-options :matchers))
4426 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4427 org-latex-regexps)))
4428 (options (org-combine-plists (org-default-export-plist)
4429 (org-infile-export-plist)))
4430 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4431 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4432 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4433 (org-export-html-expand (plist-get options :expand-quoted-html))
4434 (org-export-with-special-strings (plist-get options :special-strings))
4435 (re-sub
4436 (cond
4437 ((equal org-export-with-sub-superscripts '{})
4438 (list org-match-substring-with-braces-regexp))
4439 (org-export-with-sub-superscripts
4440 (list org-match-substring-regexp))
4441 (t nil)))
4442 (re-latex
4443 (if org-export-with-LaTeX-fragments
4444 (mapcar (lambda (x) (nth 1 x)) latexs)))
4445 (re-macros
4446 (if org-export-with-TeX-macros
4447 (list (concat "\\\\"
4448 (regexp-opt
4449 (append (mapcar 'car org-html-entities)
4450 (if (boundp 'org-latex-entities)
4451 (mapcar (lambda (x)
4452 (or (car-safe x) x))
4453 org-latex-entities)
4454 nil))
4455 'words))) ; FIXME
4457 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4458 (re-special (if org-export-with-special-strings
4459 (mapcar (lambda (x) (car x))
4460 org-export-html-special-string-regexps)))
4461 (re-rest
4462 (delq nil
4463 (list
4464 (if org-export-html-expand "@<[^>\n]+>")
4465 ))))
4466 (org-set-local
4467 'org-latex-and-specials-regexp
4468 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4469 re-rest) "\\|")))))
4471 (defun org-do-latex-and-special-faces (limit)
4472 "Run through the buffer and add overlays to links."
4473 (when org-latex-and-specials-regexp
4474 (let (rtn d)
4475 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4476 limit t))
4477 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4478 'face))
4479 '(org-code org-verbatim underline)))
4480 (progn
4481 (setq rtn t
4482 d (cond ((member (char-after (1+ (match-beginning 0)))
4483 '(?_ ?^)) 1)
4484 (t 0)))
4485 (font-lock-prepend-text-property
4486 (+ d (match-beginning 0)) (match-end 0)
4487 'face 'org-latex-and-export-specials)
4488 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4489 '(font-lock-multiline t)))))
4490 rtn)))
4492 (defun org-restart-font-lock ()
4493 "Restart font-lock-mode, to force refontification."
4494 (when (and (boundp 'font-lock-mode) font-lock-mode)
4495 (font-lock-mode -1)
4496 (font-lock-mode 1)))
4498 (defun org-all-targets (&optional radio)
4499 "Return a list of all targets in this file.
4500 With optional argument RADIO, only find radio targets."
4501 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4502 rtn)
4503 (save-excursion
4504 (goto-char (point-min))
4505 (while (re-search-forward re nil t)
4506 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4507 rtn)))
4509 (defun org-make-target-link-regexp (targets)
4510 "Make regular expression matching all strings in TARGETS.
4511 The regular expression finds the targets also if there is a line break
4512 between words."
4513 (and targets
4514 (concat
4515 "\\<\\("
4516 (mapconcat
4517 (lambda (x)
4518 (while (string-match " +" x)
4519 (setq x (replace-match "\\s-+" t t x)))
4521 targets
4522 "\\|")
4523 "\\)\\>")))
4525 (defun org-activate-tags (limit)
4526 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4527 (progn
4528 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4529 (add-text-properties (match-beginning 1) (match-end 1)
4530 (list 'mouse-face 'highlight
4531 'keymap org-mouse-map))
4532 (org-rear-nonsticky-at (match-end 1))
4533 t)))
4535 (defun org-outline-level ()
4536 (save-excursion
4537 (looking-at outline-regexp)
4538 (if (match-beginning 1)
4539 (+ (org-get-string-indentation (match-string 1)) 1000)
4540 (1- (- (match-end 0) (match-beginning 0))))))
4542 (defvar org-font-lock-keywords nil)
4544 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4545 "Regular expression matching a property line.")
4547 (defvar org-font-lock-hook nil
4548 "Functions to be called for special font lock stuff.")
4550 (defun org-font-lock-hook (limit)
4551 (run-hook-with-args 'org-font-lock-hook limit))
4553 (defun org-set-font-lock-defaults ()
4554 (let* ((em org-fontify-emphasized-text)
4555 (lk org-activate-links)
4556 (org-font-lock-extra-keywords
4557 (list
4558 ;; Call the hook
4559 '(org-font-lock-hook)
4560 ;; Headlines
4561 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4562 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4563 ;; Table lines
4564 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4565 (1 'org-table t))
4566 ;; Table internals
4567 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4568 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4569 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4570 ;; Drawers
4571 (list org-drawer-regexp '(0 'org-special-keyword t))
4572 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4573 ;; Properties
4574 (list org-property-re
4575 '(1 'org-special-keyword t)
4576 '(3 'org-property-value t))
4577 (if org-format-transports-properties-p
4578 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4579 ;; Links
4580 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4581 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4582 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4583 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4584 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4585 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4586 (if (memq 'footnote lk) '(org-activate-footnote-links
4587 (2 'org-footnote t)))
4588 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4589 '(org-hide-wide-columns (0 nil append))
4590 ;; TODO lines
4591 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4592 '(1 (org-get-todo-face 1) t))
4593 ;; DONE
4594 (if org-fontify-done-headline
4595 (list (concat "^[*]+ +\\<\\("
4596 (mapconcat 'regexp-quote org-done-keywords "\\|")
4597 "\\)\\(.*\\)")
4598 '(2 'org-headline-done t))
4599 nil)
4600 ;; Priorities
4601 '(org-font-lock-add-priority-faces)
4602 ;; Tags
4603 '(org-font-lock-add-tag-faces)
4604 ;; Special keywords
4605 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4606 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4607 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4608 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4609 ;; Emphasis
4610 (if em
4611 (if (featurep 'xemacs)
4612 '(org-do-emphasis-faces (0 nil append))
4613 '(org-do-emphasis-faces)))
4614 ;; Checkboxes
4615 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4616 2 'org-checkbox prepend)
4617 (if org-provide-checkbox-statistics
4618 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4619 (0 (org-get-checkbox-statistics-face) t)))
4620 ;; Description list items
4621 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4622 2 'bold prepend)
4623 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4624 '(1 'org-archived prepend))
4625 ;; Specials
4626 '(org-do-latex-and-special-faces)
4627 ;; Code
4628 '(org-activate-code (1 'org-code t))
4629 ;; COMMENT
4630 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4631 "\\|" org-quote-string "\\)\\>")
4632 '(1 'org-special-keyword t))
4633 '("^#.*" (0 'font-lock-comment-face t))
4634 ;; Blocks and meta lines
4635 '(org-fontify-meta-lines-and-blocks)
4637 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4638 ;; Now set the full font-lock-keywords
4639 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4640 (org-set-local 'font-lock-defaults
4641 '(org-font-lock-keywords t nil nil backward-paragraph))
4642 (kill-local-variable 'font-lock-keywords) nil))
4644 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
4645 "Fontify string S like in Org-mode"
4646 (with-temp-buffer
4647 (insert s)
4648 (let ((org-odd-levels-only odd-levels))
4649 (org-mode)
4650 (font-lock-fontify-buffer)
4651 (buffer-string))))
4653 (defvar org-m nil)
4654 (defvar org-l nil)
4655 (defvar org-f nil)
4656 (defun org-get-level-face (n)
4657 "Get the right face for match N in font-lock matching of headlines."
4658 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4659 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4660 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4661 (cond
4662 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4663 ((eq n 2) org-f)
4664 (t (if org-level-color-stars-only nil org-f))))
4666 (defun org-get-todo-face (kwd)
4667 "Get the right face for a TODO keyword KWD.
4668 If KWD is a number, get the corresponding match group."
4669 (if (numberp kwd) (setq kwd (match-string kwd)))
4670 (or (cdr (assoc kwd org-todo-keyword-faces))
4671 (and (member kwd org-done-keywords) 'org-done)
4672 'org-todo))
4674 (defun org-font-lock-add-tag-faces (limit)
4675 "Add the special tag faces."
4676 (when (and org-tag-faces org-tags-special-faces-re)
4677 (while (re-search-forward org-tags-special-faces-re limit t)
4678 (add-text-properties (match-beginning 1) (match-end 1)
4679 (list 'face (org-get-tag-face 1)
4680 'font-lock-fontified t))
4681 (backward-char 1))))
4683 (defun org-font-lock-add-priority-faces (limit)
4684 "Add the special priority faces."
4685 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4686 (add-text-properties
4687 (match-beginning 0) (match-end 0)
4688 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4689 org-priority-faces))
4690 'org-special-keyword)
4691 'font-lock-fontified t))))
4693 (defun org-get-tag-face (kwd)
4694 "Get the right face for a TODO keyword KWD.
4695 If KWD is a number, get the corresponding match group."
4696 (if (numberp kwd) (setq kwd (match-string kwd)))
4697 (or (cdr (assoc kwd org-tag-faces))
4698 'org-tag))
4700 (defun org-unfontify-region (beg end &optional maybe_loudly)
4701 "Remove fontification and activation overlays from links."
4702 (font-lock-default-unfontify-region beg end)
4703 (let* ((buffer-undo-list t)
4704 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4705 (inhibit-modification-hooks t)
4706 deactivate-mark buffer-file-name buffer-file-truename)
4707 (remove-text-properties beg end
4708 '(mouse-face t keymap t org-linked-text t
4709 invisible t intangible t))))
4711 ;;;; Visibility cycling, including org-goto and indirect buffer
4713 ;;; Cycling
4715 (defvar org-cycle-global-status nil)
4716 (make-variable-buffer-local 'org-cycle-global-status)
4717 (defvar org-cycle-subtree-status nil)
4718 (make-variable-buffer-local 'org-cycle-subtree-status)
4720 ;;;###autoload
4722 (defvar org-inlinetask-min-level)
4724 (defun org-cycle (&optional arg)
4725 "TAB-action and visibility cycling for Org-mode.
4727 This is the command invoked in Org-moe by the TAB key. It's main purpose
4728 is outine visibility cycling, but it also invokes other actions
4729 in special contexts.
4731 - When this function is called with a prefix argument, rotate the entire
4732 buffer through 3 states (global cycling)
4733 1. OVERVIEW: Show only top-level headlines.
4734 2. CONTENTS: Show all headlines of all levels, but no body text.
4735 3. SHOW ALL: Show everything.
4736 When called with two `C-u C-u' prefixes, switch to the startup visibility,
4737 determined by the variable `org-startup-folded', and by any VISIBILITY
4738 properties in the buffer.
4739 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
4740 including any drawers.
4742 - When inside a table, re-align the table and move to the next field.
4744 - When point is at the beginning of a headline, rotate the subtree started
4745 by this line through 3 different states (local cycling)
4746 1. FOLDED: Only the main headline is shown.
4747 2. CHILDREN: The main headline and the direct children are shown.
4748 From this state, you can move to one of the children
4749 and zoom in further.
4750 3. SUBTREE: Show the entire subtree, including body text.
4752 - When there is a numeric prefix, go up to a heading with level ARG, do
4753 a `show-subtree' and return to the previous cursor position. If ARG
4754 is negative, go up that many levels.
4756 - When point is not at the beginning of a headline, execute the global
4757 binding for TAB, which is re-indenting the line. See the option
4758 `org-cycle-emulate-tab' for details.
4760 - Special case: if point is at the beginning of the buffer and there is
4761 no headline in line 1, this function will act as if called with prefix arg.
4762 But only if also the variable `org-cycle-global-at-bob' is t."
4763 (interactive "P")
4764 (org-load-modules-maybe)
4765 (unless (run-hook-with-args-until-success 'org-tab-first-hook)
4766 (let* ((limit-level
4767 (or org-cycle-max-level
4768 (and (boundp 'org-inlinetask-min-level)
4769 org-inlinetask-min-level
4770 (1- org-inlinetask-min-level))))
4771 (nstars (and limit-level
4772 (if org-odd-levels-only
4773 (and limit-level (1- (* limit-level 2)))
4774 limit-level)))
4775 (outline-regexp
4776 (cond
4777 ((not (org-mode-p)) outline-regexp)
4778 (org-cycle-include-plain-lists
4779 (concat "\\(?:\\*"
4780 (if nstars (format "\\{1,%d\\}" nstars) "+")
4781 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
4782 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
4783 (bob-special (and org-cycle-global-at-bob (bobp)
4784 (not (looking-at outline-regexp))))
4785 (org-cycle-hook
4786 (if bob-special
4787 (delq 'org-optimize-window-after-visibility-change
4788 (copy-sequence org-cycle-hook))
4789 org-cycle-hook))
4790 (pos (point)))
4792 (if (or bob-special (equal arg '(4)))
4793 ;; special case: use global cycling
4794 (setq arg t))
4796 (cond
4798 ((equal arg '(16))
4799 (org-set-startup-visibility)
4800 (message "Startup visibility, plus VISIBILITY properties"))
4802 ((equal arg '(64))
4803 (show-all)
4804 (message "Entire buffer visible, including drawers"))
4806 ((org-at-table-p 'any)
4807 ;; Enter the table or move to the next field in the table
4808 (or (org-table-recognize-table.el)
4809 (progn
4810 (if arg (org-table-edit-field t)
4811 (org-table-justify-field-maybe)
4812 (call-interactively 'org-table-next-field)))))
4814 ((run-hook-with-args-until-success
4815 'org-tab-after-check-for-table-hook))
4817 ((eq arg t) ;; Global cycling
4818 (org-cycle-internal-global))
4820 ((and org-drawers org-drawer-regexp
4821 (save-excursion
4822 (beginning-of-line 1)
4823 (looking-at org-drawer-regexp)))
4824 ;; Toggle block visibility
4825 (org-flag-drawer
4826 (not (get-char-property (match-end 0) 'invisible))))
4828 ((integerp arg)
4829 ;; Show-subtree, ARG levels up from here.
4830 (save-excursion
4831 (org-back-to-heading)
4832 (outline-up-heading (if (< arg 0) (- arg)
4833 (- (funcall outline-level) arg)))
4834 (org-show-subtree)))
4836 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4837 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4839 (org-cycle-internal-local))
4841 ;; TAB emulation and template completion
4842 (buffer-read-only (org-back-to-heading))
4844 ((run-hook-with-args-until-success
4845 'org-tab-after-check-for-cycling-hook))
4847 ((org-try-structure-completion))
4849 ((org-try-cdlatex-tab))
4851 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4852 (or (not (bolp))
4853 (not (looking-at outline-regexp))))
4854 (call-interactively (global-key-binding "\t")))
4856 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4857 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4858 (or (and (eq org-cycle-emulate-tab 'white)
4859 (= (match-end 0) (point-at-eol)))
4860 (and (eq org-cycle-emulate-tab 'whitestart)
4861 (>= (match-end 0) pos))))
4863 (eq org-cycle-emulate-tab t))
4864 (call-interactively (global-key-binding "\t")))
4866 (t (save-excursion
4867 (org-back-to-heading)
4868 (org-cycle)))))))
4870 (defun org-cycle-internal-global ()
4871 "Do the global cycling action."
4872 (cond
4873 ((and (eq last-command this-command)
4874 (eq org-cycle-global-status 'overview))
4875 ;; We just created the overview - now do table of contents
4876 ;; This can be slow in very large buffers, so indicate action
4877 (run-hook-with-args 'org-pre-cycle-hook 'contents)
4878 (message "CONTENTS...")
4879 (org-content)
4880 (message "CONTENTS...done")
4881 (setq org-cycle-global-status 'contents)
4882 (run-hook-with-args 'org-cycle-hook 'contents))
4884 ((and (eq last-command this-command)
4885 (eq org-cycle-global-status 'contents))
4886 ;; We just showed the table of contents - now show everything
4887 (run-hook-with-args 'org-pre-cycle-hook 'all)
4888 (show-all)
4889 (message "SHOW ALL")
4890 (setq org-cycle-global-status 'all)
4891 (run-hook-with-args 'org-cycle-hook 'all))
4894 ;; Default action: go to overview
4895 (run-hook-with-args 'org-pre-cycle-hook 'overview)
4896 (org-overview)
4897 (message "OVERVIEW")
4898 (setq org-cycle-global-status 'overview)
4899 (run-hook-with-args 'org-cycle-hook 'overview))))
4901 (defun org-cycle-internal-local ()
4902 "Do the local cycling action."
4903 (org-back-to-heading)
4904 (let ((goal-column 0) eoh eol eos)
4905 ;; First, some boundaries
4906 (save-excursion
4907 (org-back-to-heading)
4908 (save-excursion
4909 (beginning-of-line 2)
4910 (while (and (not (eobp)) ;; this is like `next-line'
4911 (get-char-property (1- (point)) 'invisible))
4912 (beginning-of-line 2)) (setq eol (point)))
4913 (outline-end-of-heading) (setq eoh (point))
4914 (org-end-of-subtree t)
4915 (unless (eobp)
4916 (skip-chars-forward " \t\n")
4917 (beginning-of-line 1) ; in case this is an item
4919 (setq eos (1- (point))))
4920 ;; Find out what to do next and set `this-command'
4921 (cond
4922 ((= eos eoh)
4923 ;; Nothing is hidden behind this heading
4924 (run-hook-with-args 'org-pre-cycle-hook 'empty)
4925 (message "EMPTY ENTRY")
4926 (setq org-cycle-subtree-status nil)
4927 (save-excursion
4928 (goto-char eos)
4929 (outline-next-heading)
4930 (if (org-invisible-p) (org-flag-heading nil))))
4931 ((or (>= eol eos)
4932 (not (string-match "\\S-" (buffer-substring eol eos))))
4933 ;; Entire subtree is hidden in one line: open it
4934 (run-hook-with-args 'org-pre-cycle-hook 'children)
4935 (org-show-entry)
4936 (show-children)
4937 (message "CHILDREN")
4938 (save-excursion
4939 (goto-char eos)
4940 (outline-next-heading)
4941 (if (org-invisible-p) (org-flag-heading nil)))
4942 (setq org-cycle-subtree-status 'children)
4943 (run-hook-with-args 'org-cycle-hook 'children))
4944 ((and (eq last-command this-command)
4945 (eq org-cycle-subtree-status 'children))
4946 ;; We just showed the children, now show everything.
4947 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
4948 (org-show-subtree)
4949 (message "SUBTREE")
4950 (setq org-cycle-subtree-status 'subtree)
4951 (run-hook-with-args 'org-cycle-hook 'subtree))
4953 ;; Default action: hide the subtree.
4954 (run-hook-with-args 'org-pre-cycle-hook 'folded)
4955 (hide-subtree)
4956 (message "FOLDED")
4957 (setq org-cycle-subtree-status 'folded)
4958 (run-hook-with-args 'org-cycle-hook 'folded)))))
4960 ;;;###autoload
4961 (defun org-global-cycle (&optional arg)
4962 "Cycle the global visibility. For details see `org-cycle'.
4963 With C-u prefix arg, switch to startup visibility.
4964 With a numeric prefix, show all headlines up to that level."
4965 (interactive "P")
4966 (let ((org-cycle-include-plain-lists
4967 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4968 (cond
4969 ((integerp arg)
4970 (show-all)
4971 (hide-sublevels arg)
4972 (setq org-cycle-global-status 'contents))
4973 ((equal arg '(4))
4974 (org-set-startup-visibility)
4975 (message "Startup visibility, plus VISIBILITY properties."))
4977 (org-cycle '(4))))))
4979 (defun org-set-startup-visibility ()
4980 "Set the visibility required by startup options and properties."
4981 (cond
4982 ((eq org-startup-folded t)
4983 (org-cycle '(4)))
4984 ((eq org-startup-folded 'content)
4985 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4986 (org-cycle '(4)) (org-cycle '(4)))))
4987 (if org-hide-block-startup (org-hide-block-all))
4988 (org-set-visibility-according-to-property 'no-cleanup)
4989 (org-cycle-hide-archived-subtrees 'all)
4990 (org-cycle-hide-drawers 'all)
4991 (org-cycle-show-empty-lines 'all))
4993 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4994 "Switch subtree visibilities according to :VISIBILITY: property."
4995 (interactive)
4996 (let (org-show-entry-below state)
4997 (save-excursion
4998 (goto-char (point-min))
4999 (while (re-search-forward
5000 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5001 nil t)
5002 (setq state (match-string 1))
5003 (save-excursion
5004 (org-back-to-heading t)
5005 (hide-subtree)
5006 (org-reveal)
5007 (cond
5008 ((equal state '("fold" "folded"))
5009 (hide-subtree))
5010 ((equal state "children")
5011 (org-show-hidden-entry)
5012 (show-children))
5013 ((equal state "content")
5014 (save-excursion
5015 (save-restriction
5016 (org-narrow-to-subtree)
5017 (org-content))))
5018 ((member state '("all" "showall"))
5019 (show-subtree)))))
5020 (unless no-cleanup
5021 (org-cycle-hide-archived-subtrees 'all)
5022 (org-cycle-hide-drawers 'all)
5023 (org-cycle-show-empty-lines 'all)))))
5025 (defun org-overview ()
5026 "Switch to overview mode, showing only top-level headlines.
5027 Really, this shows all headlines with level equal or greater than the level
5028 of the first headline in the buffer. This is important, because if the
5029 first headline is not level one, then (hide-sublevels 1) gives confusing
5030 results."
5031 (interactive)
5032 (let ((level (save-excursion
5033 (goto-char (point-min))
5034 (if (re-search-forward (concat "^" outline-regexp) nil t)
5035 (progn
5036 (goto-char (match-beginning 0))
5037 (funcall outline-level))))))
5038 (and level (hide-sublevels level))))
5040 (defun org-content (&optional arg)
5041 "Show all headlines in the buffer, like a table of contents.
5042 With numerical argument N, show content up to level N."
5043 (interactive "P")
5044 (save-excursion
5045 ;; Visit all headings and show their offspring
5046 (and (integerp arg) (org-overview))
5047 (goto-char (point-max))
5048 (catch 'exit
5049 (while (and (progn (condition-case nil
5050 (outline-previous-visible-heading 1)
5051 (error (goto-char (point-min))))
5053 (looking-at outline-regexp))
5054 (if (integerp arg)
5055 (show-children (1- arg))
5056 (show-branches))
5057 (if (bobp) (throw 'exit nil))))))
5060 (defun org-optimize-window-after-visibility-change (state)
5061 "Adjust the window after a change in outline visibility.
5062 This function is the default value of the hook `org-cycle-hook'."
5063 (when (get-buffer-window (current-buffer))
5064 (cond
5065 ((eq state 'content) nil)
5066 ((eq state 'all) nil)
5067 ((eq state 'folded) nil)
5068 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5069 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5071 (defun org-compact-display-after-subtree-move ()
5072 "Show a compacter version of the tree of the entry's parent."
5073 (save-excursion
5074 (if (org-up-heading-safe)
5075 (progn
5076 (hide-subtree)
5077 (show-entry)
5078 (show-children)
5079 (org-cycle-show-empty-lines 'children)
5080 (org-cycle-hide-drawers 'children))
5081 (org-overview))))
5083 (defun org-cycle-show-empty-lines (state)
5084 "Show empty lines above all visible headlines.
5085 The region to be covered depends on STATE when called through
5086 `org-cycle-hook'. Lisp program can use t for STATE to get the
5087 entire buffer covered. Note that an empty line is only shown if there
5088 are at least `org-cycle-separator-lines' empty lines before the headline."
5089 (when (> org-cycle-separator-lines 0)
5090 (save-excursion
5091 (let* ((n org-cycle-separator-lines)
5092 (re (cond
5093 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5094 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5095 (t (let ((ns (number-to-string (- n 2))))
5096 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5097 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5098 beg end)
5099 (cond
5100 ((memq state '(overview contents t))
5101 (setq beg (point-min) end (point-max)))
5102 ((memq state '(children folded))
5103 (setq beg (point) end (progn (org-end-of-subtree t t)
5104 (beginning-of-line 2)
5105 (point)))))
5106 (when beg
5107 (goto-char beg)
5108 (while (re-search-forward re end t)
5109 (if (not (get-char-property (match-end 1) 'invisible))
5110 (outline-flag-region
5111 (match-beginning 1) (match-end 1) nil)))))))
5112 ;; Never hide empty lines at the end of the file.
5113 (save-excursion
5114 (goto-char (point-max))
5115 (outline-previous-heading)
5116 (outline-end-of-heading)
5117 (if (and (looking-at "[ \t\n]+")
5118 (= (match-end 0) (point-max)))
5119 (outline-flag-region (point) (match-end 0) nil))))
5121 (defun org-show-empty-lines-in-parent ()
5122 "Move to the parent and re-show empty lines before visible headlines."
5123 (save-excursion
5124 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5125 (org-cycle-show-empty-lines context))))
5127 (defun org-cycle-hide-drawers (state)
5128 "Re-hide all drawers after a visibility state change."
5129 (when (and (org-mode-p)
5130 (not (memq state '(overview folded))))
5131 (save-excursion
5132 (let* ((globalp (memq state '(contents all)))
5133 (beg (if globalp (point-min) (point)))
5134 (end (if globalp (point-max) (org-end-of-subtree t))))
5135 (goto-char beg)
5136 (while (re-search-forward org-drawer-regexp end t)
5137 (org-flag-drawer t))))))
5139 (defun org-flag-drawer (flag)
5140 (save-excursion
5141 (beginning-of-line 1)
5142 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5143 (let ((b (match-end 0))
5144 (outline-regexp org-outline-regexp))
5145 (if (re-search-forward
5146 "^[ \t]*:END:"
5147 (save-excursion (outline-next-heading) (point)) t)
5148 (outline-flag-region b (point-at-eol) flag)
5149 (error ":END: line missing"))))))
5151 (defun org-subtree-end-visible-p ()
5152 "Is the end of the current subtree visible?"
5153 (pos-visible-in-window-p
5154 (save-excursion (org-end-of-subtree t) (point))))
5156 (defun org-first-headline-recenter (&optional N)
5157 "Move cursor to the first headline and recenter the headline.
5158 Optional argument N means, put the headline into the Nth line of the window."
5159 (goto-char (point-min))
5160 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5161 (beginning-of-line)
5162 (recenter (prefix-numeric-value N))))
5164 ;;; Folding of blocks
5166 (defconst org-block-regexp
5168 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5169 "Regular expression for hiding blocks.")
5171 (defvar org-hide-block-overlays nil
5172 "Overays hiding blocks.")
5173 (make-variable-buffer-local 'org-hide-block-overlays)
5175 (defun org-block-map (function &optional start end)
5176 "Call func at the head of all source blocks in the current
5177 buffer. Optional arguments START and END can be used to limit
5178 the range."
5179 (let ((start (or start (point-min)))
5180 (end (or end (point-max))))
5181 (save-excursion
5182 (goto-char start)
5183 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5184 (save-excursion
5185 (save-match-data
5186 (goto-char (match-beginning 0))
5187 (funcall function)))))))
5189 (defun org-hide-block-toggle-all ()
5190 "Toggle the visibility of all blocks in the current buffer."
5191 (org-block-map #'org-hide-block-toggle))
5193 (defun org-hide-block-all ()
5194 "Fold all blocks in the current buffer."
5195 (interactive)
5196 (org-show-block-all)
5197 (org-block-map #'org-hide-block-toggle-maybe))
5199 (defun org-show-block-all ()
5200 "Unfold all blocks in the current buffer."
5201 (mapc 'org-delete-overlay org-hide-block-overlays)
5202 (setq org-hide-block-overlays nil))
5204 (defun org-hide-block-toggle-maybe ()
5205 "Toggle visibility of block at point."
5206 (interactive)
5207 (let ((case-fold-search t))
5208 (if (save-excursion
5209 (beginning-of-line 1)
5210 (looking-at org-block-regexp))
5211 (progn (org-hide-block-toggle)
5212 t) ;; to signal that we took action
5213 nil))) ;; to signal that we did not
5215 (defun org-hide-block-toggle (&optional force)
5216 "Toggle the visibility of the current block."
5217 (interactive)
5218 (save-excursion
5219 (beginning-of-line)
5220 (if (re-search-forward org-block-regexp nil t)
5221 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5222 (end (match-end 0))
5223 ov) ;; end of entire body
5224 (if (memq t (mapcar (lambda (overlay)
5225 (eq (org-overlay-get overlay 'invisible)
5226 'org-hide-block))
5227 (org-overlays-at start)))
5228 (if (or (not force) (eq force 'off))
5229 (mapc (lambda (ov)
5230 (when (member ov org-hide-block-overlays)
5231 (setq org-hide-block-overlays
5232 (delq ov org-hide-block-overlays)))
5233 (when (eq (org-overlay-get ov 'invisible)
5234 'org-hide-block)
5235 (org-delete-overlay ov)))
5236 (org-overlays-at start)))
5237 (setq ov (make-overlay start end))
5238 (org-overlay-put ov 'invisible 'org-hide-block)
5239 (push ov org-hide-block-overlays)))
5240 (error "Not looking at a source block"))))
5242 ;; org-tab-after-check-for-cycling-hook
5243 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5244 ;; Remove overlays when changing major mode
5245 (add-hook 'org-mode-hook
5246 (lambda () (org-add-hook 'change-major-mode-hook
5247 'org-show-block-all 'append 'local)))
5249 ;;; Org-goto
5251 (defvar org-goto-window-configuration nil)
5252 (defvar org-goto-marker nil)
5253 (defvar org-goto-map
5254 (let ((map (make-sparse-keymap)))
5255 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5256 (while (setq cmd (pop cmds))
5257 (substitute-key-definition cmd cmd map global-map)))
5258 (suppress-keymap map)
5259 (org-defkey map "\C-m" 'org-goto-ret)
5260 (org-defkey map [(return)] 'org-goto-ret)
5261 (org-defkey map [(left)] 'org-goto-left)
5262 (org-defkey map [(right)] 'org-goto-right)
5263 (org-defkey map [(control ?g)] 'org-goto-quit)
5264 (org-defkey map "\C-i" 'org-cycle)
5265 (org-defkey map [(tab)] 'org-cycle)
5266 (org-defkey map [(down)] 'outline-next-visible-heading)
5267 (org-defkey map [(up)] 'outline-previous-visible-heading)
5268 (if org-goto-auto-isearch
5269 (if (fboundp 'define-key-after)
5270 (define-key-after map [t] 'org-goto-local-auto-isearch)
5271 nil)
5272 (org-defkey map "q" 'org-goto-quit)
5273 (org-defkey map "n" 'outline-next-visible-heading)
5274 (org-defkey map "p" 'outline-previous-visible-heading)
5275 (org-defkey map "f" 'outline-forward-same-level)
5276 (org-defkey map "b" 'outline-backward-same-level)
5277 (org-defkey map "u" 'outline-up-heading))
5278 (org-defkey map "/" 'org-occur)
5279 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5280 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5281 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5282 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5283 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5284 map))
5286 (defconst org-goto-help
5287 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5288 RET=jump to location [Q]uit and return to previous location
5289 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5291 (defvar org-goto-start-pos) ; dynamically scoped parameter
5293 ;; FIXME: Docstring doe not mention both interfaces
5294 (defun org-goto (&optional alternative-interface)
5295 "Look up a different location in the current file, keeping current visibility.
5297 When you want look-up or go to a different location in a document, the
5298 fastest way is often to fold the entire buffer and then dive into the tree.
5299 This method has the disadvantage, that the previous location will be folded,
5300 which may not be what you want.
5302 This command works around this by showing a copy of the current buffer
5303 in an indirect buffer, in overview mode. You can dive into the tree in
5304 that copy, use org-occur and incremental search to find a location.
5305 When pressing RET or `Q', the command returns to the original buffer in
5306 which the visibility is still unchanged. After RET is will also jump to
5307 the location selected in the indirect buffer and expose the
5308 the headline hierarchy above."
5309 (interactive "P")
5310 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5311 (org-refile-use-outline-path t)
5312 (org-refile-target-verify-function nil)
5313 (interface
5314 (if (not alternative-interface)
5315 org-goto-interface
5316 (if (eq org-goto-interface 'outline)
5317 'outline-path-completion
5318 'outline)))
5319 (org-goto-start-pos (point))
5320 (selected-point
5321 (if (eq interface 'outline)
5322 (car (org-get-location (current-buffer) org-goto-help))
5323 (nth 3 (org-refile-get-location "Goto: ")))))
5324 (if selected-point
5325 (progn
5326 (org-mark-ring-push org-goto-start-pos)
5327 (goto-char selected-point)
5328 (if (or (org-invisible-p) (org-invisible-p2))
5329 (org-show-context 'org-goto)))
5330 (message "Quit"))))
5332 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5333 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5334 (defvar org-goto-local-auto-isearch-map) ; defined below
5336 (defun org-get-location (buf help)
5337 "Let the user select a location in the Org-mode buffer BUF.
5338 This function uses a recursive edit. It returns the selected position
5339 or nil."
5340 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5341 (isearch-hide-immediately nil)
5342 (isearch-search-fun-function
5343 (lambda () 'org-goto-local-search-headings))
5344 (org-goto-selected-point org-goto-exit-command))
5345 (save-excursion
5346 (save-window-excursion
5347 (delete-other-windows)
5348 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5349 (switch-to-buffer
5350 (condition-case nil
5351 (make-indirect-buffer (current-buffer) "*org-goto*")
5352 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5353 (with-output-to-temp-buffer "*Help*"
5354 (princ help))
5355 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5356 (setq buffer-read-only nil)
5357 (let ((org-startup-truncated t)
5358 (org-startup-folded nil)
5359 (org-startup-align-all-tables nil))
5360 (org-mode)
5361 (org-overview))
5362 (setq buffer-read-only t)
5363 (if (and (boundp 'org-goto-start-pos)
5364 (integer-or-marker-p org-goto-start-pos))
5365 (let ((org-show-hierarchy-above t)
5366 (org-show-siblings t)
5367 (org-show-following-heading t))
5368 (goto-char org-goto-start-pos)
5369 (and (org-invisible-p) (org-show-context)))
5370 (goto-char (point-min)))
5371 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5372 (message "Select location and press RET")
5373 (use-local-map org-goto-map)
5374 (recursive-edit)
5376 (kill-buffer "*org-goto*")
5377 (cons org-goto-selected-point org-goto-exit-command)))
5379 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5380 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5381 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5382 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5384 (defun org-goto-local-search-headings (string bound noerror)
5385 "Search and make sure that any matches are in headlines."
5386 (catch 'return
5387 (while (if isearch-forward
5388 (search-forward string bound noerror)
5389 (search-backward string bound noerror))
5390 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5391 (and (member :headline context)
5392 (not (member :tags context))))
5393 (throw 'return (point))))))
5395 (defun org-goto-local-auto-isearch ()
5396 "Start isearch."
5397 (interactive)
5398 (goto-char (point-min))
5399 (let ((keys (this-command-keys)))
5400 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5401 (isearch-mode t)
5402 (isearch-process-search-char (string-to-char keys)))))
5404 (defun org-goto-ret (&optional arg)
5405 "Finish `org-goto' by going to the new location."
5406 (interactive "P")
5407 (setq org-goto-selected-point (point)
5408 org-goto-exit-command 'return)
5409 (throw 'exit nil))
5411 (defun org-goto-left ()
5412 "Finish `org-goto' by going to the new location."
5413 (interactive)
5414 (if (org-on-heading-p)
5415 (progn
5416 (beginning-of-line 1)
5417 (setq org-goto-selected-point (point)
5418 org-goto-exit-command 'left)
5419 (throw 'exit nil))
5420 (error "Not on a heading")))
5422 (defun org-goto-right ()
5423 "Finish `org-goto' by going to the new location."
5424 (interactive)
5425 (if (org-on-heading-p)
5426 (progn
5427 (setq org-goto-selected-point (point)
5428 org-goto-exit-command 'right)
5429 (throw 'exit nil))
5430 (error "Not on a heading")))
5432 (defun org-goto-quit ()
5433 "Finish `org-goto' without cursor motion."
5434 (interactive)
5435 (setq org-goto-selected-point nil)
5436 (setq org-goto-exit-command 'quit)
5437 (throw 'exit nil))
5439 ;;; Indirect buffer display of subtrees
5441 (defvar org-indirect-dedicated-frame nil
5442 "This is the frame being used for indirect tree display.")
5443 (defvar org-last-indirect-buffer nil)
5445 (defun org-tree-to-indirect-buffer (&optional arg)
5446 "Create indirect buffer and narrow it to current subtree.
5447 With numerical prefix ARG, go up to this level and then take that tree.
5448 If ARG is negative, go up that many levels.
5449 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5450 indirect buffer previously made with this command, to avoid proliferation of
5451 indirect buffers. However, when you call the command with a `C-u' prefix, or
5452 when `org-indirect-buffer-display' is `new-frame', the last buffer
5453 is kept so that you can work with several indirect buffers at the same time.
5454 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5455 requests that a new frame be made for the new buffer, so that the dedicated
5456 frame is not changed."
5457 (interactive "P")
5458 (let ((cbuf (current-buffer))
5459 (cwin (selected-window))
5460 (pos (point))
5461 beg end level heading ibuf)
5462 (save-excursion
5463 (org-back-to-heading t)
5464 (when (numberp arg)
5465 (setq level (org-outline-level))
5466 (if (< arg 0) (setq arg (+ level arg)))
5467 (while (> (setq level (org-outline-level)) arg)
5468 (outline-up-heading 1 t)))
5469 (setq beg (point)
5470 heading (org-get-heading))
5471 (org-end-of-subtree t) (setq end (point)))
5472 (if (and (buffer-live-p org-last-indirect-buffer)
5473 (not (eq org-indirect-buffer-display 'new-frame))
5474 (not arg))
5475 (kill-buffer org-last-indirect-buffer))
5476 (setq ibuf (org-get-indirect-buffer cbuf)
5477 org-last-indirect-buffer ibuf)
5478 (cond
5479 ((or (eq org-indirect-buffer-display 'new-frame)
5480 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5481 (select-frame (make-frame))
5482 (delete-other-windows)
5483 (switch-to-buffer ibuf)
5484 (org-set-frame-title heading))
5485 ((eq org-indirect-buffer-display 'dedicated-frame)
5486 (raise-frame
5487 (select-frame (or (and org-indirect-dedicated-frame
5488 (frame-live-p org-indirect-dedicated-frame)
5489 org-indirect-dedicated-frame)
5490 (setq org-indirect-dedicated-frame (make-frame)))))
5491 (delete-other-windows)
5492 (switch-to-buffer ibuf)
5493 (org-set-frame-title (concat "Indirect: " heading)))
5494 ((eq org-indirect-buffer-display 'current-window)
5495 (switch-to-buffer ibuf))
5496 ((eq org-indirect-buffer-display 'other-window)
5497 (pop-to-buffer ibuf))
5498 (t (error "Invalid value.")))
5499 (if (featurep 'xemacs)
5500 (save-excursion (org-mode) (turn-on-font-lock)))
5501 (narrow-to-region beg end)
5502 (show-all)
5503 (goto-char pos)
5504 (and (window-live-p cwin) (select-window cwin))))
5506 (defun org-get-indirect-buffer (&optional buffer)
5507 (setq buffer (or buffer (current-buffer)))
5508 (let ((n 1) (base (buffer-name buffer)) bname)
5509 (while (buffer-live-p
5510 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5511 (setq n (1+ n)))
5512 (condition-case nil
5513 (make-indirect-buffer buffer bname 'clone)
5514 (error (make-indirect-buffer buffer bname)))))
5516 (defun org-set-frame-title (title)
5517 "Set the title of the current frame to the string TITLE."
5518 ;; FIXME: how to name a single frame in XEmacs???
5519 (unless (featurep 'xemacs)
5520 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5522 ;;;; Structure editing
5524 ;;; Inserting headlines
5526 (defun org-previous-line-empty-p ()
5527 (save-excursion
5528 (and (not (bobp))
5529 (or (beginning-of-line 0) t)
5530 (save-match-data
5531 (looking-at "[ \t]*$")))))
5533 (defun org-insert-heading (&optional force-heading)
5534 "Insert a new heading or item with same depth at point.
5535 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5536 If point is at the beginning of a headline, insert a sibling before the
5537 current headline. If point is not at the beginning, do not split the line,
5538 but create the new headline after the current line."
5539 (interactive "P")
5540 (if (= (buffer-size) 0)
5541 (insert "\n* ")
5542 (when (or force-heading (not (org-insert-item)))
5543 (let* ((empty-line-p nil)
5544 (head (save-excursion
5545 (condition-case nil
5546 (progn
5547 (org-back-to-heading)
5548 (setq empty-line-p (org-previous-line-empty-p))
5549 (match-string 0))
5550 (error "*"))))
5551 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5552 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5553 pos hide-previous previous-pos)
5554 (cond
5555 ((and (org-on-heading-p) (bolp)
5556 (or (bobp)
5557 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5558 ;; insert before the current line
5559 (open-line (if blank 2 1)))
5560 ((and (bolp)
5561 (or (bobp)
5562 (save-excursion
5563 (backward-char 1) (not (org-invisible-p)))))
5564 ;; insert right here
5565 nil)
5567 ;; somewhere in the line
5568 (save-excursion
5569 (setq previous-pos (point-at-bol))
5570 (end-of-line)
5571 (setq hide-previous (org-invisible-p)))
5572 (and org-insert-heading-respect-content (org-show-subtree))
5573 (let ((split
5574 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5575 (save-excursion
5576 (let ((p (point)))
5577 (goto-char (point-at-bol))
5578 (and (looking-at org-complex-heading-regexp)
5579 (> p (match-beginning 4)))))))
5580 tags pos)
5581 (cond
5582 (org-insert-heading-respect-content
5583 (org-end-of-subtree nil t)
5584 (or (bolp) (newline))
5585 (or (org-previous-line-empty-p)
5586 (and blank (newline)))
5587 (open-line 1))
5588 ((org-on-heading-p)
5589 (when hide-previous
5590 (show-children)
5591 (org-show-entry))
5592 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5593 (setq tags (and (match-end 2) (match-string 2)))
5594 (and (match-end 1)
5595 (delete-region (match-beginning 1) (match-end 1)))
5596 (setq pos (point-at-bol))
5597 (or split (end-of-line 1))
5598 (delete-horizontal-space)
5599 (newline (if blank 2 1))
5600 (when tags
5601 (save-excursion
5602 (goto-char pos)
5603 (end-of-line 1)
5604 (insert " " tags)
5605 (org-set-tags nil 'align))))
5607 (or split (end-of-line 1))
5608 (newline (if blank 2 1)))))))
5609 (insert head) (just-one-space)
5610 (setq pos (point))
5611 (end-of-line 1)
5612 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5613 (when (and org-insert-heading-respect-content hide-previous)
5614 (save-excursion
5615 (goto-char previous-pos)
5616 (hide-subtree)))
5617 (run-hooks 'org-insert-heading-hook)))))
5619 (defun org-get-heading (&optional no-tags)
5620 "Return the heading of the current entry, without the stars."
5621 (save-excursion
5622 (org-back-to-heading t)
5623 (if (looking-at
5624 (if no-tags
5625 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5626 "\\*+[ \t]+\\([^\r\n]*\\)"))
5627 (match-string 1) "")))
5629 (defun org-heading-components ()
5630 "Return the components of the current heading.
5631 This is a list with the following elements:
5632 - the level as an integer
5633 - the reduced level, different if `org-odd-levels-only' is set.
5634 - the TODO keyword, or nil
5635 - the priority character, like ?A, or nil if no priority is given
5636 - the headline text itself, or the tags string if no headline text
5637 - the tags string, or nil."
5638 (save-excursion
5639 (org-back-to-heading t)
5640 (if (looking-at org-complex-heading-regexp)
5641 (list (length (match-string 1))
5642 (org-reduced-level (length (match-string 1)))
5643 (org-match-string-no-properties 2)
5644 (and (match-end 3) (aref (match-string 3) 2))
5645 (org-match-string-no-properties 4)
5646 (org-match-string-no-properties 5)))))
5648 (defun org-get-entry ()
5649 "Get the entry text, after heading, entire subtree."
5650 (save-excursion
5651 (org-back-to-heading t)
5652 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
5654 (defun org-insert-heading-after-current ()
5655 "Insert a new heading with same level as current, after current subtree."
5656 (interactive)
5657 (org-back-to-heading)
5658 (org-insert-heading)
5659 (org-move-subtree-down)
5660 (end-of-line 1))
5662 (defun org-insert-heading-respect-content ()
5663 (interactive)
5664 (let ((org-insert-heading-respect-content t))
5665 (org-insert-heading t)))
5667 (defun org-insert-todo-heading-respect-content (&optional force-state)
5668 (interactive "P")
5669 (let ((org-insert-heading-respect-content t))
5670 (org-insert-todo-heading force-state t)))
5672 (defun org-insert-todo-heading (arg &optional force-heading)
5673 "Insert a new heading with the same level and TODO state as current heading.
5674 If the heading has no TODO state, or if the state is DONE, use the first
5675 state (TODO by default). Also with prefix arg, force first state."
5676 (interactive "P")
5677 (when (or force-heading (not (org-insert-item 'checkbox)))
5678 (org-insert-heading force-heading)
5679 (save-excursion
5680 (org-back-to-heading)
5681 (outline-previous-heading)
5682 (looking-at org-todo-line-regexp))
5683 (let*
5684 ((new-mark-x
5685 (if (or arg
5686 (not (match-beginning 2))
5687 (member (match-string 2) org-done-keywords))
5688 (car org-todo-keywords-1)
5689 (match-string 2)))
5690 (new-mark
5692 (run-hook-with-args-until-success
5693 'org-todo-get-default-hook new-mark-x nil)
5694 new-mark-x)))
5695 (beginning-of-line 1)
5696 (and (looking-at "\\*+ ") (goto-char (match-end 0))
5697 (if org-treat-insert-todo-heading-as-state-change
5698 (org-todo new-mark)
5699 (insert new-mark " "))))
5700 (when org-provide-todo-statistics
5701 (org-update-parent-todo-statistics))))
5703 (defun org-insert-subheading (arg)
5704 "Insert a new subheading and demote it.
5705 Works for outline headings and for plain lists alike."
5706 (interactive "P")
5707 (org-insert-heading arg)
5708 (cond
5709 ((org-on-heading-p) (org-do-demote))
5710 ((org-at-item-p) (org-indent-item 1))))
5712 (defun org-insert-todo-subheading (arg)
5713 "Insert a new subheading with TODO keyword or checkbox and demote it.
5714 Works for outline headings and for plain lists alike."
5715 (interactive "P")
5716 (org-insert-todo-heading arg)
5717 (cond
5718 ((org-on-heading-p) (org-do-demote))
5719 ((org-at-item-p) (org-indent-item 1))))
5721 ;;; Promotion and Demotion
5723 (defun org-promote-subtree ()
5724 "Promote the entire subtree.
5725 See also `org-promote'."
5726 (interactive)
5727 (save-excursion
5728 (org-map-tree 'org-promote))
5729 (org-fix-position-after-promote))
5731 (defun org-demote-subtree ()
5732 "Demote the entire subtree. See `org-demote'.
5733 See also `org-promote'."
5734 (interactive)
5735 (save-excursion
5736 (org-map-tree 'org-demote))
5737 (org-fix-position-after-promote))
5740 (defun org-do-promote ()
5741 "Promote the current heading higher up the tree.
5742 If the region is active in `transient-mark-mode', promote all headings
5743 in the region."
5744 (interactive)
5745 (save-excursion
5746 (if (org-region-active-p)
5747 (org-map-region 'org-promote (region-beginning) (region-end))
5748 (org-promote)))
5749 (org-fix-position-after-promote))
5751 (defun org-do-demote ()
5752 "Demote the current heading lower down the tree.
5753 If the region is active in `transient-mark-mode', demote all headings
5754 in the region."
5755 (interactive)
5756 (save-excursion
5757 (if (org-region-active-p)
5758 (org-map-region 'org-demote (region-beginning) (region-end))
5759 (org-demote)))
5760 (org-fix-position-after-promote))
5762 (defun org-fix-position-after-promote ()
5763 "Make sure that after pro/demotion cursor position is right."
5764 (let ((pos (point)))
5765 (when (save-excursion
5766 (beginning-of-line 1)
5767 (looking-at org-todo-line-regexp)
5768 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5769 (cond ((eobp) (insert " "))
5770 ((eolp) (insert " "))
5771 ((equal (char-after) ?\ ) (forward-char 1))))))
5773 (defun org-reduced-level (l)
5774 "Compute the effective level of a heading.
5775 This takes into account the setting of `org-odd-levels-only'."
5776 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5778 (defun org-get-valid-level (level &optional change)
5779 "Rectify a level change under the influence of `org-odd-levels-only'
5780 LEVEL is a current level, CHANGE is by how much the level should be
5781 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5782 even level numbers will become the next higher odd number."
5783 (if org-odd-levels-only
5784 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5785 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5786 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5787 (max 1 (+ level (or change 0)))))
5789 (if (boundp 'define-obsolete-function-alias)
5790 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5791 (define-obsolete-function-alias 'org-get-legal-level
5792 'org-get-valid-level)
5793 (define-obsolete-function-alias 'org-get-legal-level
5794 'org-get-valid-level "23.1")))
5796 (defun org-promote ()
5797 "Promote the current heading higher up the tree.
5798 If the region is active in `transient-mark-mode', promote all headings
5799 in the region."
5800 (org-back-to-heading t)
5801 (let* ((level (save-match-data (funcall outline-level)))
5802 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5803 (diff (abs (- level (length up-head) -1))))
5804 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5805 (replace-match up-head nil t)
5806 ;; Fixup tag positioning
5807 (and org-auto-align-tags (org-set-tags nil t))
5808 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5810 (defun org-demote ()
5811 "Demote the current heading lower down the tree.
5812 If the region is active in `transient-mark-mode', demote all headings
5813 in the region."
5814 (org-back-to-heading t)
5815 (let* ((level (save-match-data (funcall outline-level)))
5816 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5817 (diff (abs (- level (length down-head) -1))))
5818 (replace-match down-head nil t)
5819 ;; Fixup tag positioning
5820 (and org-auto-align-tags (org-set-tags nil t))
5821 (if org-adapt-indentation (org-fixup-indentation diff))))
5823 (defun org-map-tree (fun)
5824 "Call FUN for every heading underneath the current one."
5825 (org-back-to-heading)
5826 (let ((level (funcall outline-level)))
5827 (save-excursion
5828 (funcall fun)
5829 (while (and (progn
5830 (outline-next-heading)
5831 (> (funcall outline-level) level))
5832 (not (eobp)))
5833 (funcall fun)))))
5835 (defun org-map-region (fun beg end)
5836 "Call FUN for every heading between BEG and END."
5837 (let ((org-ignore-region t))
5838 (save-excursion
5839 (setq end (copy-marker end))
5840 (goto-char beg)
5841 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5842 (< (point) end))
5843 (funcall fun))
5844 (while (and (progn
5845 (outline-next-heading)
5846 (< (point) end))
5847 (not (eobp)))
5848 (funcall fun)))))
5850 (defun org-fixup-indentation (diff)
5851 "Change the indentation in the current entry by DIFF
5852 However, if any line in the current entry has no indentation, or if it
5853 would end up with no indentation after the change, nothing at all is done."
5854 (save-excursion
5855 (let ((end (save-excursion (outline-next-heading)
5856 (point-marker)))
5857 (prohibit (if (> diff 0)
5858 "^\\S-"
5859 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5860 col)
5861 (unless (save-excursion (end-of-line 1)
5862 (re-search-forward prohibit end t))
5863 (while (and (< (point) end)
5864 (re-search-forward "^[ \t]+" end t))
5865 (goto-char (match-end 0))
5866 (setq col (current-column))
5867 (if (< diff 0) (replace-match ""))
5868 (org-indent-to-column (+ diff col))))
5869 (move-marker end nil))))
5871 (defun org-convert-to-odd-levels ()
5872 "Convert an org-mode file with all levels allowed to one with odd levels.
5873 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5874 level 5 etc."
5875 (interactive)
5876 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5877 (let ((org-odd-levels-only nil) n)
5878 (save-excursion
5879 (goto-char (point-min))
5880 (while (re-search-forward "^\\*\\*+ " nil t)
5881 (setq n (- (length (match-string 0)) 2))
5882 (while (>= (setq n (1- n)) 0)
5883 (org-demote))
5884 (end-of-line 1))))))
5887 (defun org-convert-to-oddeven-levels ()
5888 "Convert an org-mode file with only odd levels to one with odd and even levels.
5889 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5890 section with an even level, conversion would destroy the structure of the file. An error
5891 is signaled in this case."
5892 (interactive)
5893 (goto-char (point-min))
5894 ;; First check if there are no even levels
5895 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5896 (org-show-context t)
5897 (error "Not all levels are odd in this file. Conversion not possible."))
5898 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5899 (let ((org-odd-levels-only nil) n)
5900 (save-excursion
5901 (goto-char (point-min))
5902 (while (re-search-forward "^\\*\\*+ " nil t)
5903 (setq n (/ (1- (length (match-string 0))) 2))
5904 (while (>= (setq n (1- n)) 0)
5905 (org-promote))
5906 (end-of-line 1))))))
5908 (defun org-tr-level (n)
5909 "Make N odd if required."
5910 (if org-odd-levels-only (1+ (/ n 2)) n))
5912 ;;; Vertical tree motion, cutting and pasting of subtrees
5914 (defun org-move-subtree-up (&optional arg)
5915 "Move the current subtree up past ARG headlines of the same level."
5916 (interactive "p")
5917 (org-move-subtree-down (- (prefix-numeric-value arg))))
5919 (defun org-move-subtree-down (&optional arg)
5920 "Move the current subtree down past ARG headlines of the same level."
5921 (interactive "p")
5922 (setq arg (prefix-numeric-value arg))
5923 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5924 'outline-get-last-sibling))
5925 (ins-point (make-marker))
5926 (cnt (abs arg))
5927 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5928 ;; Select the tree
5929 (org-back-to-heading)
5930 (setq beg0 (point))
5931 (save-excursion
5932 (setq ne-beg (org-back-over-empty-lines))
5933 (setq beg (point)))
5934 (save-match-data
5935 (save-excursion (outline-end-of-heading)
5936 (setq folded (org-invisible-p)))
5937 (outline-end-of-subtree))
5938 (outline-next-heading)
5939 (setq ne-end (org-back-over-empty-lines))
5940 (setq end (point))
5941 (goto-char beg0)
5942 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5943 ;; include less whitespace
5944 (save-excursion
5945 (goto-char beg)
5946 (forward-line (- ne-beg ne-end))
5947 (setq beg (point))))
5948 ;; Find insertion point, with error handling
5949 (while (> cnt 0)
5950 (or (and (funcall movfunc) (looking-at outline-regexp))
5951 (progn (goto-char beg0)
5952 (error "Cannot move past superior level or buffer limit")))
5953 (setq cnt (1- cnt)))
5954 (if (> arg 0)
5955 ;; Moving forward - still need to move over subtree
5956 (progn (org-end-of-subtree t t)
5957 (save-excursion
5958 (org-back-over-empty-lines)
5959 (or (bolp) (newline)))))
5960 (setq ne-ins (org-back-over-empty-lines))
5961 (move-marker ins-point (point))
5962 (setq txt (buffer-substring beg end))
5963 (org-save-markers-in-region beg end)
5964 (delete-region beg end)
5965 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5966 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5967 (and (not (bolp)) (looking-at "\n") (forward-char 1))
5968 (let ((bbb (point)))
5969 (insert-before-markers txt)
5970 (org-reinstall-markers-in-region bbb)
5971 (move-marker ins-point bbb))
5972 (or (bolp) (insert "\n"))
5973 (setq ins-end (point))
5974 (goto-char ins-point)
5975 (org-skip-whitespace)
5976 (when (and (< arg 0)
5977 (org-first-sibling-p)
5978 (> ne-ins ne-beg))
5979 ;; Move whitespace back to beginning
5980 (save-excursion
5981 (goto-char ins-end)
5982 (let ((kill-whole-line t))
5983 (kill-line (- ne-ins ne-beg)) (point)))
5984 (insert (make-string (- ne-ins ne-beg) ?\n)))
5985 (move-marker ins-point nil)
5986 (org-compact-display-after-subtree-move)
5987 (org-show-empty-lines-in-parent)
5988 (unless folded
5989 (org-show-entry)
5990 (show-children)
5991 (org-cycle-hide-drawers 'children))))
5993 (defvar org-subtree-clip ""
5994 "Clipboard for cut and paste of subtrees.
5995 This is actually only a copy of the kill, because we use the normal kill
5996 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5998 (defvar org-subtree-clip-folded nil
5999 "Was the last copied subtree folded?
6000 This is used to fold the tree back after pasting.")
6002 (defun org-cut-subtree (&optional n)
6003 "Cut the current subtree into the clipboard.
6004 With prefix arg N, cut this many sequential subtrees.
6005 This is a short-hand for marking the subtree and then cutting it."
6006 (interactive "p")
6007 (org-copy-subtree n 'cut))
6009 (defun org-copy-subtree (&optional n cut force-store-markers)
6010 "Cut the current subtree into the clipboard.
6011 With prefix arg N, cut this many sequential subtrees.
6012 This is a short-hand for marking the subtree and then copying it.
6013 If CUT is non-nil, actually cut the subtree.
6014 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6015 of some markers in the region, even if CUT is non-nil. This is
6016 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6017 (interactive "p")
6018 (let (beg end folded (beg0 (point)))
6019 (if (interactive-p)
6020 (org-back-to-heading nil) ; take what looks like a subtree
6021 (org-back-to-heading t)) ; take what is really there
6022 (org-back-over-empty-lines)
6023 (setq beg (point))
6024 (skip-chars-forward " \t\r\n")
6025 (save-match-data
6026 (save-excursion (outline-end-of-heading)
6027 (setq folded (org-invisible-p)))
6028 (condition-case nil
6029 (outline-forward-same-level (1- n))
6030 (error nil))
6031 (org-end-of-subtree t t))
6032 (org-back-over-empty-lines)
6033 (setq end (point))
6034 (goto-char beg0)
6035 (when (> end beg)
6036 (setq org-subtree-clip-folded folded)
6037 (when (or cut force-store-markers)
6038 (org-save-markers-in-region beg end))
6039 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6040 (setq org-subtree-clip (current-kill 0))
6041 (message "%s: Subtree(s) with %d characters"
6042 (if cut "Cut" "Copied")
6043 (length org-subtree-clip)))))
6045 (defun org-paste-subtree (&optional level tree for-yank)
6046 "Paste the clipboard as a subtree, with modification of headline level.
6047 The entire subtree is promoted or demoted in order to match a new headline
6048 level.
6050 If the cursor is at the beginning of a headline, the same level as
6051 that headline is used to paste the tree
6053 If not, the new level is derived from the *visible* headings
6054 before and after the insertion point, and taken to be the inferior headline
6055 level of the two. So if the previous visible heading is level 3 and the
6056 next is level 4 (or vice versa), level 4 will be used for insertion.
6057 This makes sure that the subtree remains an independent subtree and does
6058 not swallow low level entries.
6060 You can also force a different level, either by using a numeric prefix
6061 argument, or by inserting the heading marker by hand. For example, if the
6062 cursor is after \"*****\", then the tree will be shifted to level 5.
6064 If optional TREE is given, use this text instead of the kill ring.
6066 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6067 move back over whitespace before inserting, and move point to the end of
6068 the inserted text when done."
6069 (interactive "P")
6070 (unless (org-kill-is-subtree-p tree)
6071 (error "%s"
6072 (substitute-command-keys
6073 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6074 (let* ((visp (not (org-invisible-p)))
6075 (txt (or tree (and kill-ring (current-kill 0))))
6076 (^re (concat "^\\(" outline-regexp "\\)"))
6077 (re (concat "\\(" outline-regexp "\\)"))
6078 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6080 (old-level (if (string-match ^re txt)
6081 (- (match-end 0) (match-beginning 0) 1)
6082 -1))
6083 (force-level (cond (level (prefix-numeric-value level))
6084 ((and (looking-at "[ \t]*$")
6085 (string-match
6086 ^re_ (buffer-substring
6087 (point-at-bol) (point))))
6088 (- (match-end 1) (match-beginning 1)))
6089 ((and (bolp)
6090 (looking-at org-outline-regexp))
6091 (- (match-end 0) (point) 1))
6092 (t nil)))
6093 (previous-level (save-excursion
6094 (condition-case nil
6095 (progn
6096 (outline-previous-visible-heading 1)
6097 (if (looking-at re)
6098 (- (match-end 0) (match-beginning 0) 1)
6100 (error 1))))
6101 (next-level (save-excursion
6102 (condition-case nil
6103 (progn
6104 (or (looking-at outline-regexp)
6105 (outline-next-visible-heading 1))
6106 (if (looking-at re)
6107 (- (match-end 0) (match-beginning 0) 1)
6109 (error 1))))
6110 (new-level (or force-level (max previous-level next-level)))
6111 (shift (if (or (= old-level -1)
6112 (= new-level -1)
6113 (= old-level new-level))
6115 (- new-level old-level)))
6116 (delta (if (> shift 0) -1 1))
6117 (func (if (> shift 0) 'org-demote 'org-promote))
6118 (org-odd-levels-only nil)
6119 beg end newend)
6120 ;; Remove the forced level indicator
6121 (if force-level
6122 (delete-region (point-at-bol) (point)))
6123 ;; Paste
6124 (beginning-of-line 1)
6125 (unless for-yank (org-back-over-empty-lines))
6126 (setq beg (point))
6127 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6128 (insert-before-markers txt)
6129 (unless (string-match "\n\\'" txt) (insert "\n"))
6130 (setq newend (point))
6131 (org-reinstall-markers-in-region beg)
6132 (setq end (point))
6133 (goto-char beg)
6134 (skip-chars-forward " \t\n\r")
6135 (setq beg (point))
6136 (if (and (org-invisible-p) visp)
6137 (save-excursion (outline-show-heading)))
6138 ;; Shift if necessary
6139 (unless (= shift 0)
6140 (save-restriction
6141 (narrow-to-region beg end)
6142 (while (not (= shift 0))
6143 (org-map-region func (point-min) (point-max))
6144 (setq shift (+ delta shift)))
6145 (goto-char (point-min))
6146 (setq newend (point-max))))
6147 (when (or (interactive-p) for-yank)
6148 (message "Clipboard pasted as level %d subtree" new-level))
6149 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6150 kill-ring
6151 (eq org-subtree-clip (current-kill 0))
6152 org-subtree-clip-folded)
6153 ;; The tree was folded before it was killed/copied
6154 (hide-subtree))
6155 (and for-yank (goto-char newend))))
6157 (defun org-kill-is-subtree-p (&optional txt)
6158 "Check if the current kill is an outline subtree, or a set of trees.
6159 Returns nil if kill does not start with a headline, or if the first
6160 headline level is not the largest headline level in the tree.
6161 So this will actually accept several entries of equal levels as well,
6162 which is OK for `org-paste-subtree'.
6163 If optional TXT is given, check this string instead of the current kill."
6164 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6165 (start-level (and kill
6166 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6167 org-outline-regexp "\\)")
6168 kill)
6169 (- (match-end 2) (match-beginning 2) 1)))
6170 (re (concat "^" org-outline-regexp))
6171 (start (1+ (or (match-beginning 2) -1))))
6172 (if (not start-level)
6173 (progn
6174 nil) ;; does not even start with a heading
6175 (catch 'exit
6176 (while (setq start (string-match re kill (1+ start)))
6177 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6178 (throw 'exit nil)))
6179 t))))
6181 (defvar org-markers-to-move nil
6182 "Markers that should be moved with a cut-and-paste operation.
6183 Those markers are stored together with their positions relative to
6184 the start of the region.")
6186 (defun org-save-markers-in-region (beg end)
6187 "Check markers in region.
6188 If these markers are between BEG and END, record their position relative
6189 to BEG, so that after moving the block of text, we can put the markers back
6190 into place.
6191 This function gets called just before an entry or tree gets cut from the
6192 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6193 called immediately, to move the markers with the entries."
6194 (setq org-markers-to-move nil)
6195 (when (featurep 'org-clock)
6196 (org-clock-save-markers-for-cut-and-paste beg end))
6197 (when (featurep 'org-agenda)
6198 (org-agenda-save-markers-for-cut-and-paste beg end)))
6200 (defun org-check-and-save-marker (marker beg end)
6201 "Check if MARKER is between BEG and END.
6202 If yes, remember the marker and the distance to BEG."
6203 (when (and (marker-buffer marker)
6204 (equal (marker-buffer marker) (current-buffer)))
6205 (if (and (>= marker beg) (< marker end))
6206 (push (cons marker (- marker beg)) org-markers-to-move))))
6208 (defun org-reinstall-markers-in-region (beg)
6209 "Move all remembered markers to their position relative to BEG."
6210 (mapc (lambda (x)
6211 (move-marker (car x) (+ beg (cdr x))))
6212 org-markers-to-move)
6213 (setq org-markers-to-move nil))
6215 (defun org-narrow-to-subtree ()
6216 "Narrow buffer to the current subtree."
6217 (interactive)
6218 (save-excursion
6219 (save-match-data
6220 (narrow-to-region
6221 (progn (org-back-to-heading) (point))
6222 (progn (org-end-of-subtree t) (point))))))
6224 (defun org-clone-subtree-with-time-shift (n &optional shift)
6225 "Clone the task (subtree) at point N times.
6226 The clones will be inserted as siblings.
6228 In interactive use, the user will be prompted for the number of clones
6229 to be produced, and for a time SHIFT, which may be a repeater as used
6230 in time stamps, for example `+3d'.
6232 When a valid repeater is given and the entry contains any time stamps,
6233 the clones will become a sequence in time, with time stamps in the
6234 subtree shifted for each clone produced. If SHIFT is nil or the
6235 empty string, time stamps will be left alone.
6237 If the original subtree did contain time stamps with a repeater,
6238 the following will happen:
6239 - the repeater will be removed in each clone
6240 - an additional clone will be produced, with the current, unshifted
6241 date(s) in the entry.
6242 - the original entry will be placed *after* all the clones, with
6243 repeater intact.
6244 - the start days in the repeater in the original entry will be shifted
6245 to past the last clone.
6246 I this way you can spell out a number of instances of a repeating task,
6247 and still retain the repeater to cover future instances of the task."
6248 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6249 (let (beg end template task
6250 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6251 (if (not (and (integerp n) (> n 0)))
6252 (error "Invalid number of replications %s" n))
6253 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6254 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6255 shift)))
6256 (error "Invalid shift specification %s" shift))
6257 (when doshift
6258 (setq shift-n (string-to-number (match-string 1 shift))
6259 shift-what (cdr (assoc (match-string 2 shift)
6260 '(("d" . day) ("w" . week)
6261 ("m" . month) ("y" . year))))))
6262 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6263 (setq nmin 1 nmax n)
6264 (org-back-to-heading t)
6265 (setq beg (point))
6266 (org-end-of-subtree t t)
6267 (setq end (point))
6268 (setq template (buffer-substring beg end))
6269 (when (and doshift
6270 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6271 (delete-region beg end)
6272 (setq end beg)
6273 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6274 (goto-char end)
6275 (loop for n from nmin to nmax do
6276 (if (not doshift)
6277 (setq task template)
6278 (with-temp-buffer
6279 (insert template)
6280 (org-mode)
6281 (goto-char (point-min))
6282 (while (re-search-forward org-ts-regexp nil t)
6283 (org-timestamp-change (* n shift-n) shift-what))
6284 (unless (= n n-no-remove)
6285 (goto-char (point-min))
6286 (while (re-search-forward org-ts-regexp nil t)
6287 (save-excursion
6288 (goto-char (match-beginning 0))
6289 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6290 (delete-region (match-beginning 1) (match-end 1))))))
6291 (setq task (buffer-string))))
6292 (insert task))
6293 (goto-char beg)))
6295 ;;; Outline Sorting
6297 (defun org-sort (with-case)
6298 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6299 Optional argument WITH-CASE means sort case-sensitively.
6300 With a double prefix argument, also remove duplicate entries."
6301 (interactive "P")
6302 (if (org-at-table-p)
6303 (org-call-with-arg 'org-table-sort-lines with-case)
6304 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6306 (defun org-sort-remove-invisible (s)
6307 (remove-text-properties 0 (length s) org-rm-props s)
6308 (while (string-match org-bracket-link-regexp s)
6309 (setq s (replace-match (if (match-end 2)
6310 (match-string 3 s)
6311 (match-string 1 s)) t t s)))
6314 (defvar org-priority-regexp) ; defined later in the file
6316 (defvar org-after-sorting-entries-or-items-hook nil
6317 "Hook that is run after a bunch of entries or items have been sorted.
6318 When children are sorted, the cursor is in the parent line when this
6319 hook gets called. When a region or a plain list is sorted, the cursor
6320 will be in the first entry of the sorted region/list.")
6322 (defun org-sort-entries-or-items
6323 (&optional with-case sorting-type getkey-func compare-func property)
6324 "Sort entries on a certain level of an outline tree, or plain list items.
6325 If there is an active region, the entries in the region are sorted.
6326 Else, if the cursor is before the first entry, sort the top-level items.
6327 Else, the children of the entry at point are sorted.
6328 If the cursor is at the first item in a plain list, the list items will be
6329 sorted.
6331 Sorting can be alphabetically, numerically, by date/time as given by
6332 a time stamp, by a property or by priority.
6334 The command prompts for the sorting type unless it has been given to the
6335 function through the SORTING-TYPE argument, which needs to a character,
6336 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6337 precise meaning of each character:
6339 n Numerically, by converting the beginning of the entry/item to a number.
6340 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6341 t By date/time, either the first active time stamp in the entry, or, if
6342 none exist, by the first inactive one.
6343 In items, only the first line will be chekced.
6344 s By the scheduled date/time.
6345 d By deadline date/time.
6346 c By creation time, which is assumed to be the first inactive time stamp
6347 at the beginning of a line.
6348 p By priority according to the cookie.
6349 r By the value of a property.
6351 Capital letters will reverse the sort order.
6353 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6354 called with point at the beginning of the record. It must return either
6355 a string or a number that should serve as the sorting key for that record.
6357 Comparing entries ignores case by default. However, with an optional argument
6358 WITH-CASE, the sorting considers case as well."
6359 (interactive "P")
6360 (let ((case-func (if with-case 'identity 'downcase))
6361 start beg end stars re re2
6362 txt what tmp plain-list-p)
6363 ;; Find beginning and end of region to sort
6364 (cond
6365 ((org-region-active-p)
6366 ;; we will sort the region
6367 (setq end (region-end)
6368 what "region")
6369 (goto-char (region-beginning))
6370 (if (not (org-on-heading-p)) (outline-next-heading))
6371 (setq start (point)))
6372 ((org-at-item-p)
6373 ;; we will sort this plain list
6374 (org-beginning-of-item-list) (setq start (point))
6375 (org-end-of-item-list) (setq end (point))
6376 (goto-char start)
6377 (setq plain-list-p t
6378 what "plain list"))
6379 ((or (org-on-heading-p)
6380 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6381 ;; we will sort the children of the current headline
6382 (org-back-to-heading)
6383 (setq start (point)
6384 end (progn (org-end-of-subtree t t)
6385 (org-back-over-empty-lines)
6386 (point))
6387 what "children")
6388 (goto-char start)
6389 (show-subtree)
6390 (outline-next-heading))
6392 ;; we will sort the top-level entries in this file
6393 (goto-char (point-min))
6394 (or (org-on-heading-p) (outline-next-heading))
6395 (setq start (point) end (point-max) what "top-level")
6396 (goto-char start)
6397 (show-all)))
6399 (setq beg (point))
6400 (if (>= beg end) (error "Nothing to sort"))
6402 (unless plain-list-p
6403 (looking-at "\\(\\*+\\)")
6404 (setq stars (match-string 1)
6405 re (concat "^" (regexp-quote stars) " +")
6406 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6407 txt (buffer-substring beg end))
6408 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6409 (if (and (not (equal stars "*")) (string-match re2 txt))
6410 (error "Region to sort contains a level above the first entry")))
6412 (unless sorting-type
6413 (message
6414 (if plain-list-p
6415 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6416 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
6417 [t]ime [s]cheduled [d]eadline [c]reated
6418 A/N/T/S/D/C/P/O/F means reversed:")
6419 what)
6420 (setq sorting-type (read-char-exclusive))
6422 (and (= (downcase sorting-type) ?f)
6423 (setq getkey-func
6424 (org-ido-completing-read "Sort using function: "
6425 obarray 'fboundp t nil nil))
6426 (setq getkey-func (intern getkey-func)))
6428 (and (= (downcase sorting-type) ?r)
6429 (setq property
6430 (org-ido-completing-read "Property: "
6431 (mapcar 'list (org-buffer-property-keys t))
6432 nil t))))
6434 (message "Sorting entries...")
6436 (save-restriction
6437 (narrow-to-region start end)
6439 (let ((dcst (downcase sorting-type))
6440 (case-fold-search nil)
6441 (now (current-time)))
6442 (sort-subr
6443 (/= dcst sorting-type)
6444 ;; This function moves to the beginning character of the "record" to
6445 ;; be sorted.
6446 (if plain-list-p
6447 (lambda nil
6448 (if (org-at-item-p) t (goto-char (point-max))))
6449 (lambda nil
6450 (if (re-search-forward re nil t)
6451 (goto-char (match-beginning 0))
6452 (goto-char (point-max)))))
6453 ;; This function moves to the last character of the "record" being
6454 ;; sorted.
6455 (if plain-list-p
6456 'org-end-of-item
6457 (lambda nil
6458 (save-match-data
6459 (condition-case nil
6460 (outline-forward-same-level 1)
6461 (error
6462 (goto-char (point-max)))))))
6464 ;; This function returns the value that gets sorted against.
6465 (if plain-list-p
6466 (lambda nil
6467 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6468 (cond
6469 ((= dcst ?n)
6470 (string-to-number (buffer-substring (match-end 0)
6471 (point-at-eol))))
6472 ((= dcst ?a)
6473 (buffer-substring (match-end 0) (point-at-eol)))
6474 ((= dcst ?t)
6475 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
6476 (re-search-forward org-ts-regexp-both
6477 (point-at-eol) t))
6478 (org-time-string-to-seconds (match-string 0))
6479 (time-to-seconds now)))
6480 ((= dcst ?f)
6481 (if getkey-func
6482 (progn
6483 (setq tmp (funcall getkey-func))
6484 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6485 tmp)
6486 (error "Invalid key function `%s'" getkey-func)))
6487 (t (error "Invalid sorting type `%c'" sorting-type)))))
6488 (lambda nil
6489 (cond
6490 ((= dcst ?n)
6491 (if (looking-at org-complex-heading-regexp)
6492 (string-to-number (match-string 4))
6493 nil))
6494 ((= dcst ?a)
6495 (if (looking-at org-complex-heading-regexp)
6496 (funcall case-func (match-string 4))
6497 nil))
6498 ((= dcst ?t)
6499 (let ((end (save-excursion (outline-next-heading) (point))))
6500 (if (or (re-search-forward org-ts-regexp end t)
6501 (re-search-forward org-ts-regexp-both end t))
6502 (org-time-string-to-seconds (match-string 0))
6503 (time-to-seconds now))))
6504 ((= dcst ?c)
6505 (let ((end (save-excursion (outline-next-heading) (point))))
6506 (if (re-search-forward
6507 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
6508 end t)
6509 (org-time-string-to-seconds (match-string 0))
6510 (time-to-seconds now))))
6511 ((= dcst ?s)
6512 (let ((end (save-excursion (outline-next-heading) (point))))
6513 (if (re-search-forward org-scheduled-time-regexp end t)
6514 (org-time-string-to-seconds (match-string 1))
6515 (time-to-seconds now))))
6516 ((= dcst ?d)
6517 (let ((end (save-excursion (outline-next-heading) (point))))
6518 (if (re-search-forward org-deadline-time-regexp end t)
6519 (org-time-string-to-seconds (match-string 1))
6520 (time-to-seconds now))))
6521 ((= dcst ?p)
6522 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6523 (string-to-char (match-string 2))
6524 org-default-priority))
6525 ((= dcst ?r)
6526 (or (org-entry-get nil property) ""))
6527 ((= dcst ?o)
6528 (if (looking-at org-complex-heading-regexp)
6529 (- 9999 (length (member (match-string 2)
6530 org-todo-keywords-1)))))
6531 ((= dcst ?f)
6532 (if getkey-func
6533 (progn
6534 (setq tmp (funcall getkey-func))
6535 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6536 tmp)
6537 (error "Invalid key function `%s'" getkey-func)))
6538 (t (error "Invalid sorting type `%c'" sorting-type)))))
6540 (cond
6541 ((= dcst ?a) 'string<)
6542 ((= dcst ?f) compare-func)
6543 ((member dcst '(?p ?t ?s ?d ?c)) '<)
6544 (t nil)))))
6545 (run-hooks 'org-after-sorting-entries-or-items-hook)
6546 (message "Sorting entries...done")))
6548 (defun org-do-sort (table what &optional with-case sorting-type)
6549 "Sort TABLE of WHAT according to SORTING-TYPE.
6550 The user will be prompted for the SORTING-TYPE if the call to this
6551 function does not specify it. WHAT is only for the prompt, to indicate
6552 what is being sorted. The sorting key will be extracted from
6553 the car of the elements of the table.
6554 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6555 (unless sorting-type
6556 (message
6557 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6558 what)
6559 (setq sorting-type (read-char-exclusive)))
6560 (let ((dcst (downcase sorting-type))
6561 extractfun comparefun)
6562 ;; Define the appropriate functions
6563 (cond
6564 ((= dcst ?n)
6565 (setq extractfun 'string-to-number
6566 comparefun (if (= dcst sorting-type) '< '>)))
6567 ((= dcst ?a)
6568 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6569 (lambda(x) (downcase (org-sort-remove-invisible x))))
6570 comparefun (if (= dcst sorting-type)
6571 'string<
6572 (lambda (a b) (and (not (string< a b))
6573 (not (string= a b)))))))
6574 ((= dcst ?t)
6575 (setq extractfun
6576 (lambda (x)
6577 (if (or (string-match org-ts-regexp x)
6578 (string-match org-ts-regexp-both x))
6579 (time-to-seconds
6580 (org-time-string-to-time (match-string 0 x)))
6582 comparefun (if (= dcst sorting-type) '< '>)))
6583 (t (error "Invalid sorting type `%c'" sorting-type)))
6585 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6586 table)
6587 (lambda (a b) (funcall comparefun (car a) (car b))))))
6589 ;;; Editing source examples
6591 (defvar org-exit-edit-mode-map (make-sparse-keymap))
6592 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
6593 (define-key org-exit-edit-mode-map "\C-x\C-s" 'org-edit-src-save)
6594 (defvar org-edit-src-force-single-line nil)
6595 (defvar org-edit-src-from-org-mode nil)
6596 (defvar org-edit-src-picture nil)
6597 (defvar org-edit-src-beg-marker nil)
6598 (defvar org-edit-src-end-marker nil)
6599 (defvar org-edit-src-overlay nil)
6600 (defvar org-edit-src-nindent nil)
6602 (define-minor-mode org-exit-edit-mode
6603 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
6605 (defun org-edit-src-code ()
6606 "Edit the source code example at point.
6607 The example is copied to a separate buffer, and that buffer is switched
6608 to the correct language mode. When done, exit with \\[org-edit-src-exit].
6609 This will remove the original code in the Org buffer, and replace it with
6610 the edited version."
6611 (interactive)
6612 (let ((line (org-current-line))
6613 (case-fold-search t)
6614 (msg (substitute-command-keys
6615 "Edit, then exit with C-c ' (C-c and single quote)"))
6616 (info (org-edit-src-find-region-and-lang))
6617 (org-mode-p (eq major-mode 'org-mode))
6618 (beg (make-marker))
6619 (end (make-marker))
6620 nindent ovl lang lang-f single lfmt code begline buffer)
6621 (if (not info)
6623 (setq beg (move-marker beg (nth 0 info))
6624 end (move-marker end (nth 1 info))
6625 code (buffer-substring-no-properties beg end)
6626 lang (nth 2 info)
6627 single (nth 3 info)
6628 lfmt (nth 4 info)
6629 lang-f (intern (concat lang "-mode"))
6630 begline (save-excursion (goto-char beg) (org-current-line)))
6631 (unless (functionp lang-f)
6632 (error "No such language mode: %s" lang-f))
6633 (goto-line line)
6634 (if (and (setq buffer (org-edit-src-find-buffer beg end))
6635 (y-or-n-p "Return to existing edit buffer? [n] will revert changes: "))
6636 (switch-to-buffer buffer)
6637 (when buffer
6638 (with-current-buffer buffer
6639 (if (boundp 'org-edit-src-overlay)
6640 (org-delete-overlay org-edit-src-overlay)))
6641 (kill-buffer buffer))
6642 (setq buffer (generate-new-buffer "*Org Edit Src Example*"))
6643 (setq ovl (org-make-overlay beg end))
6644 (org-overlay-put ovl 'face 'secondary-selection)
6645 (org-overlay-put ovl 'edit-buffer buffer)
6646 (org-overlay-put ovl 'help-echo "Click with mouse-1 to switch to buffer editing this segment")
6647 (org-overlay-put ovl 'face 'secondary-selection)
6648 (org-overlay-put ovl
6649 'keymap
6650 (let ((map (make-sparse-keymap)))
6651 (define-key map [mouse-1] 'org-edit-src-continue)
6652 map))
6653 (org-overlay-put ovl :read-only "Leave me alone")
6654 (switch-to-buffer buffer)
6655 (insert code)
6656 (remove-text-properties (point-min) (point-max)
6657 '(display nil invisible nil intangible nil))
6658 (setq nindent (org-do-remove-indentation))
6659 (let ((org-inhibit-startup t))
6660 (funcall lang-f))
6661 (set (make-local-variable 'org-edit-src-force-single-line) single)
6662 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6663 (when lfmt
6664 (set (make-local-variable 'org-coderef-label-format) lfmt))
6665 (when org-mode-p
6666 (goto-char (point-min))
6667 (while (re-search-forward "^," nil t)
6668 (replace-match "")))
6669 (goto-line (1+ (- line begline)))
6670 (org-exit-edit-mode)
6671 (org-set-local 'org-edit-src-beg-marker beg)
6672 (org-set-local 'org-edit-src-end-marker end)
6673 (org-set-local 'org-edit-src-overlay ovl)
6674 (org-set-local 'org-edit-src-nindent nindent)
6675 (and org-edit-src-persistent-message
6676 (org-set-local 'header-line-format msg)))
6677 (message "%s" msg)
6678 t)))
6680 (defun org-edit-src-continue (e)
6681 (interactive "e")
6682 (mouse-set-point e)
6683 (let ((buf (get-char-property (point) 'edit-buffer)))
6684 (if buf (switch-to-buffer buf)
6685 (error "Something is wrong here"))))
6687 (defun org-edit-src-find-buffer (beg end)
6688 "Find a source editing buffer that is already editing the region BEG to END."
6689 (catch 'exit
6690 (mapc
6691 (lambda (b)
6692 (with-current-buffer b
6693 (if (and (string-match "\\`*Org Edit " (buffer-name))
6694 (local-variable-p 'org-edit-src-beg-marker (current-buffer))
6695 (local-variable-p 'org-edit-src-end-marker (current-buffer))
6696 (equal beg org-edit-src-beg-marker)
6697 (equal end org-edit-src-end-marker))
6698 (throw 'exit (current-buffer)))))
6699 (buffer-list))
6700 nil))
6702 (defun org-edit-fixed-width-region ()
6703 "Edit the fixed-width ascii drawing at point.
6704 This must be a region where each line starts with a colon followed by
6705 a space character.
6706 An new buffer is created and the fixed-width region is copied into it,
6707 and the buffer is switched into `artist-mode' for editing. When done,
6708 exit with \\[org-edit-src-exit]. The edited text will then replace
6709 the fragment in the Org-mode buffer."
6710 (interactive)
6711 (let ((line (org-current-line))
6712 (case-fold-search t)
6713 (msg (substitute-command-keys
6714 "Edit, then exit with C-c ' (C-c and single quote)"))
6715 (org-mode-p (eq major-mode 'org-mode))
6716 (beg (make-marker))
6717 (end (make-marker))
6718 nindent ovl beg1 end1 code begline buffer)
6719 (beginning-of-line 1)
6720 (if (looking-at "[ \t]*[^:\n \t]")
6722 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
6723 (setq beg1 (point) end1 beg1)
6724 (save-excursion
6725 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
6726 (setq beg1 (point-at-bol 2))
6727 (setq beg1 (point))))
6728 (save-excursion
6729 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
6730 (setq end1 (1- (match-beginning 0)))
6731 (setq end1 (point))))
6732 (goto-line line))
6733 (setq beg (move-marker beg beg1)
6734 end (move-marker end end1)
6735 code (buffer-substring-no-properties beg end)
6736 begline (save-excursion (goto-char beg) (org-current-line)))
6737 (if (and (setq buffer (org-edit-src-find-buffer beg end))
6738 (y-or-n-p "Return to existing edit buffer? [n] will revert changes: "))
6739 (switch-to-buffer buffer)
6740 (when buffer
6741 (with-current-buffer buffer
6742 (if (boundp 'org-edit-src-overlay)
6743 (org-delete-overlay org-edit-src-overlay)))
6744 (kill-buffer buffer))
6745 (setq buffer (generate-new-buffer "*Org Edit Src Example*"))
6746 (setq ovl (org-make-overlay beg end))
6747 (org-overlay-put ovl 'face 'secondary-selection)
6748 (org-overlay-put ovl 'edit-buffer buffer)
6749 (org-overlay-put ovl 'help-echo "Click with mouse-1 to switch to buffer editing this segment")
6750 (org-overlay-put ovl 'face 'secondary-selection)
6751 (org-overlay-put ovl
6752 'keymap
6753 (let ((map (make-sparse-keymap)))
6754 (define-key map [mouse-1] 'org-edit-src-continue)
6755 map))
6756 (org-overlay-put ovl :read-only "Leave me alone")
6757 (switch-to-buffer buffer)
6758 (insert code)
6759 (remove-text-properties (point-min) (point-max)
6760 '(display nil invisible nil intangible nil))
6761 (setq nindent (org-do-remove-indentation))
6762 (cond
6763 ((eq org-edit-fixed-width-region-mode 'artist-mode)
6764 (fundamental-mode)
6765 (artist-mode 1))
6766 (t (funcall org-edit-fixed-width-region-mode)))
6767 (set (make-local-variable 'org-edit-src-force-single-line) nil)
6768 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6769 (set (make-local-variable 'org-edit-src-picture) t)
6770 (goto-char (point-min))
6771 (while (re-search-forward "^[ \t]*: ?" nil t)
6772 (replace-match ""))
6773 (goto-line (1+ (- line begline)))
6774 (org-exit-edit-mode)
6775 (org-set-local 'org-edit-src-beg-marker beg)
6776 (org-set-local 'org-edit-src-end-marker end)
6777 (org-set-local 'org-edit-src-overlay ovl)
6778 (org-set-local 'org-edit-src-nindent nindent)
6779 (and org-edit-src-persistent-message
6780 (org-set-local 'header-line-format msg)))
6781 (message "%s" msg)
6782 t)))
6784 (defun org-edit-src-find-region-and-lang ()
6785 "Find the region and language for a local edit.
6786 Return a list with beginning and end of the region, a string representing
6787 the language, a switch telling of the content should be in a single line."
6788 (let ((re-list
6789 (append
6790 org-edit-src-region-extra
6792 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
6793 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
6794 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
6795 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
6796 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
6797 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
6798 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
6799 ("^[ \t]*#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n[ \t]*#\\+end_src" 2)
6800 ("^[ \t]*#\\+begin_example.*\n" "\n[ \t]*#\\+end_example" "fundamental")
6801 ("^[ \t]*#\\+html:" "\n" "html" single-line)
6802 ("^[ \t]*#\\+begin_html.*\n" "\n[ \t]*#\\+end_html" "html")
6803 ("^[ \t]*#\\+latex:" "\n" "latex" single-line)
6804 ("^[ \t]*#\\+begin_latex.*\n" "\n[ \t]*#\\+end_latex" "latex")
6805 ("^[ \t]*#\\+ascii:" "\n" "fundamental" single-line)
6806 ("^[ \t]*#\\+begin_ascii.*\n" "\n[ \t]*#\\+end_ascii" "fundamental")
6807 ("^[ \t]*#\\+docbook:" "\n" "xml" single-line)
6808 ("^[ \t]*#\\+begin_docbook.*\n" "\n[ \t]*#\\+end_docbook" "xml")
6810 (pos (point))
6811 re1 re2 single beg end lang lfmt match-re1)
6812 (catch 'exit
6813 (while (setq entry (pop re-list))
6814 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
6815 single (nth 3 entry))
6816 (save-excursion
6817 (if (or (looking-at re1)
6818 (re-search-backward re1 nil t))
6819 (progn
6820 (setq match-re1 (match-string 0))
6821 (setq beg (match-end 0)
6822 lang (org-edit-src-get-lang lang)
6823 lfmt (org-edit-src-get-label-format match-re1))
6824 (if (and (re-search-forward re2 nil t)
6825 (>= (match-end 0) pos))
6826 (throw 'exit (list beg (match-beginning 0)
6827 lang single lfmt))))
6828 (if (or (looking-at re2)
6829 (re-search-forward re2 nil t))
6830 (progn
6831 (setq end (match-beginning 0))
6832 (if (and (re-search-backward re1 nil t)
6833 (<= (match-beginning 0) pos))
6834 (progn
6835 (setq lfmt (org-edit-src-get-label-format
6836 (match-string 0)))
6837 (throw 'exit
6838 (list (match-end 0) end
6839 (org-edit-src-get-lang lang)
6840 single lfmt))))))))))))
6842 (defun org-edit-src-get-lang (lang)
6843 "Extract the src language."
6844 (let ((m (match-string 0)))
6845 (cond
6846 ((stringp lang) lang)
6847 ((integerp lang) (match-string lang))
6848 ((and (eq lang 'lang)
6849 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
6850 (match-string 1 m))
6851 ((and (eq lang 'style)
6852 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
6853 (match-string 1 m))
6854 (t "fundamental"))))
6856 (defun org-edit-src-get-label-format (s)
6857 "Extract the label format."
6858 (save-match-data
6859 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
6860 (match-string 1 s))))
6862 (defun org-edit-src-exit ()
6863 "Exit special edit and protect problematic lines."
6864 (interactive)
6865 (unless (string-match "\\`*Org Edit " (buffer-name (current-buffer)))
6866 (error "This is not an sub-editing buffer, something is wrong..."))
6867 (let ((line (if (org-bound-and-true-p org-edit-src-force-single-line)
6869 (org-current-line)))
6870 (beg org-edit-src-beg-marker)
6871 (end org-edit-src-end-marker)
6872 (ovl org-edit-src-overlay)
6873 (buffer (current-buffer))
6874 (nindent org-edit-src-nindent)
6875 code)
6876 (goto-char (point-min))
6877 (if (looking-at "[ \t\n]*\n") (replace-match ""))
6878 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
6879 (when (org-bound-and-true-p org-edit-src-force-single-line)
6880 (goto-char (point-min))
6881 (while (re-search-forward "\n" nil t)
6882 (replace-match " "))
6883 (goto-char (point-min))
6884 (if (looking-at "\\s-*") (replace-match " "))
6885 (if (re-search-forward "\\s-+\\'" nil t)
6886 (replace-match "")))
6887 (when (org-bound-and-true-p org-edit-src-from-org-mode)
6888 (goto-char (point-min))
6889 (while (re-search-forward
6890 (if (org-mode-p) "^\\(.\\)" "^\\([*]\\|[ \t]*#\\+\\)") nil t)
6891 (replace-match ",\\1")))
6892 (when (org-bound-and-true-p org-edit-src-picture)
6893 (untabify (point-min) (point-max))
6894 (goto-char (point-min))
6895 (while (re-search-forward "^" nil t)
6896 (replace-match ": ")))
6897 (when nindent
6898 (setq nindent (make-string nindent ?\ ))
6899 (goto-char (point-min))
6900 (while (re-search-forward "^" nil t)
6901 (replace-match nindent)))
6902 (setq code (buffer-string))
6903 (switch-to-buffer (marker-buffer beg))
6904 (kill-buffer buffer)
6905 (goto-char beg)
6906 (org-delete-overlay ovl)
6907 (delete-region beg end)
6908 (insert code)
6909 (goto-char beg)
6910 (goto-line (1- (+ (org-current-line) line)))
6911 (move-marker beg nil)
6912 (move-marker end nil)))
6914 (defun org-edit-src-save ()
6915 "Save parent buffer with current state source-code buffer."
6916 (interactive)
6917 (let ((p (point)) (m (mark)) msg)
6918 (org-edit-src-exit)
6919 (save-buffer)
6920 (setq msg (current-message))
6921 (org-edit-src-code)
6922 (push-mark m 'nomessage)
6923 (goto-char (min p (point-max)))
6924 (message (or msg ""))))
6926 ;;; The orgstruct minor mode
6928 ;; Define a minor mode which can be used in other modes in order to
6929 ;; integrate the org-mode structure editing commands.
6931 ;; This is really a hack, because the org-mode structure commands use
6932 ;; keys which normally belong to the major mode. Here is how it
6933 ;; works: The minor mode defines all the keys necessary to operate the
6934 ;; structure commands, but wraps the commands into a function which
6935 ;; tests if the cursor is currently at a headline or a plain list
6936 ;; item. If that is the case, the structure command is used,
6937 ;; temporarily setting many Org-mode variables like regular
6938 ;; expressions for filling etc. However, when any of those keys is
6939 ;; used at a different location, function uses `key-binding' to look
6940 ;; up if the key has an associated command in another currently active
6941 ;; keymap (minor modes, major mode, global), and executes that
6942 ;; command. There might be problems if any of the keys is otherwise
6943 ;; used as a prefix key.
6945 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6946 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6947 ;; addresses this by checking explicitly for both bindings.
6949 (defvar orgstruct-mode-map (make-sparse-keymap)
6950 "Keymap for the minor `orgstruct-mode'.")
6952 (defvar org-local-vars nil
6953 "List of local variables, for use by `orgstruct-mode'")
6955 ;;;###autoload
6956 (define-minor-mode orgstruct-mode
6957 "Toggle the minor more `orgstruct-mode'.
6958 This mode is for using Org-mode structure commands in other modes.
6959 The following key behave as if Org-mode was active, if the cursor
6960 is on a headline, or on a plain list item (both in the definition
6961 of Org-mode).
6963 M-up Move entry/item up
6964 M-down Move entry/item down
6965 M-left Promote
6966 M-right Demote
6967 M-S-up Move entry/item up
6968 M-S-down Move entry/item down
6969 M-S-left Promote subtree
6970 M-S-right Demote subtree
6971 M-q Fill paragraph and items like in Org-mode
6972 C-c ^ Sort entries
6973 C-c - Cycle list bullet
6974 TAB Cycle item visibility
6975 M-RET Insert new heading/item
6976 S-M-RET Insert new TODO heading / Checkbox item
6977 C-c C-c Set tags / toggle checkbox"
6978 nil " OrgStruct" nil
6979 (org-load-modules-maybe)
6980 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6982 ;;;###autoload
6983 (defun turn-on-orgstruct ()
6984 "Unconditionally turn on `orgstruct-mode'."
6985 (orgstruct-mode 1))
6987 (defun orgstruct++-mode (&optional arg)
6988 "Toggle `orgstruct-mode', the enhanced version of it.
6989 In addition to setting orgstruct-mode, this also exports all indentation and
6990 autofilling variables from org-mode into the buffer. It will also
6991 recognize item context in multiline items.
6992 Note that turning off orgstruct-mode will *not* remove the
6993 indentation/paragraph settings. This can only be done by refreshing the
6994 major mode, for example with \[normal-mode]."
6995 (interactive "P")
6996 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6997 (if (< arg 1)
6998 (orgstruct-mode -1)
6999 (orgstruct-mode 1)
7000 (let (var val)
7001 (mapc
7002 (lambda (x)
7003 (when (string-match
7004 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7005 (symbol-name (car x)))
7006 (setq var (car x) val (nth 1 x))
7007 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7008 org-local-vars)
7009 (org-set-local 'orgstruct-is-++ t))))
7011 (defvar orgstruct-is-++ nil
7012 "Is orgstruct-mode in ++ version in the current-buffer?")
7013 (make-variable-buffer-local 'orgstruct-is-++)
7015 ;;;###autoload
7016 (defun turn-on-orgstruct++ ()
7017 "Unconditionally turn on `orgstruct++-mode'."
7018 (orgstruct++-mode 1))
7020 (defun orgstruct-error ()
7021 "Error when there is no default binding for a structure key."
7022 (interactive)
7023 (error "This key has no function outside structure elements"))
7025 (defun orgstruct-setup ()
7026 "Setup orgstruct keymaps."
7027 (let ((nfunc 0)
7028 (bindings
7029 (list
7030 '([(meta up)] org-metaup)
7031 '([(meta down)] org-metadown)
7032 '([(meta left)] org-metaleft)
7033 '([(meta right)] org-metaright)
7034 '([(meta shift up)] org-shiftmetaup)
7035 '([(meta shift down)] org-shiftmetadown)
7036 '([(meta shift left)] org-shiftmetaleft)
7037 '([(meta shift right)] org-shiftmetaright)
7038 '([?\e (up)] org-metaup)
7039 '([?\e (down)] org-metadown)
7040 '([?\e (left)] org-metaleft)
7041 '([?\e (right)] org-metaright)
7042 '([?\e (shift up)] org-shiftmetaup)
7043 '([?\e (shift down)] org-shiftmetadown)
7044 '([?\e (shift left)] org-shiftmetaleft)
7045 '([?\e (shift right)] org-shiftmetaright)
7046 '([(shift up)] org-shiftup)
7047 '([(shift down)] org-shiftdown)
7048 '([(shift left)] org-shiftleft)
7049 '([(shift right)] org-shiftright)
7050 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7051 '("\M-q" fill-paragraph)
7052 '("\C-c^" org-sort)
7053 '("\C-c-" org-cycle-list-bullet)))
7054 elt key fun cmd)
7055 (while (setq elt (pop bindings))
7056 (setq nfunc (1+ nfunc))
7057 (setq key (org-key (car elt))
7058 fun (nth 1 elt)
7059 cmd (orgstruct-make-binding fun nfunc key))
7060 (org-defkey orgstruct-mode-map key cmd))
7062 ;; Special treatment needed for TAB and RET
7063 (org-defkey orgstruct-mode-map [(tab)]
7064 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7065 (org-defkey orgstruct-mode-map "\C-i"
7066 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7068 (org-defkey orgstruct-mode-map "\M-\C-m"
7069 (orgstruct-make-binding 'org-insert-heading 105
7070 "\M-\C-m" [(meta return)]))
7071 (org-defkey orgstruct-mode-map [(meta return)]
7072 (orgstruct-make-binding 'org-insert-heading 106
7073 [(meta return)] "\M-\C-m"))
7075 (org-defkey orgstruct-mode-map [(shift meta return)]
7076 (orgstruct-make-binding 'org-insert-todo-heading 107
7077 [(meta return)] "\M-\C-m"))
7079 (org-defkey orgstruct-mode-map "\e\C-m"
7080 (orgstruct-make-binding 'org-insert-heading 108
7081 "\e\C-m" [?\e (return)]))
7082 (org-defkey orgstruct-mode-map [?\e (return)]
7083 (orgstruct-make-binding 'org-insert-heading 109
7084 [?\e (return)] "\e\C-m"))
7085 (org-defkey orgstruct-mode-map [?\e (shift return)]
7086 (orgstruct-make-binding 'org-insert-todo-heading 110
7087 [?\e (return)] "\e\C-m"))
7089 (unless org-local-vars
7090 (setq org-local-vars (org-get-local-variables)))
7094 (defun orgstruct-make-binding (fun n &rest keys)
7095 "Create a function for binding in the structure minor mode.
7096 FUN is the command to call inside a table. N is used to create a unique
7097 command name. KEYS are keys that should be checked in for a command
7098 to execute outside of tables."
7099 (eval
7100 (list 'defun
7101 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7102 '(arg)
7103 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7104 "Outside of structure, run the binding of `"
7105 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7106 "'.")
7107 '(interactive "p")
7108 (list 'if
7109 `(org-context-p 'headline 'item
7110 (and orgstruct-is-++
7111 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7112 'item-body))
7113 (list 'org-run-like-in-org-mode (list 'quote fun))
7114 (list 'let '(orgstruct-mode)
7115 (list 'call-interactively
7116 (append '(or)
7117 (mapcar (lambda (k)
7118 (list 'key-binding k))
7119 keys)
7120 '('orgstruct-error))))))))
7122 (defun org-context-p (&rest contexts)
7123 "Check if local context is any of CONTEXTS.
7124 Possible values in the list of contexts are `table', `headline', and `item'."
7125 (let ((pos (point)))
7126 (goto-char (point-at-bol))
7127 (prog1 (or (and (memq 'table contexts)
7128 (looking-at "[ \t]*|"))
7129 (and (memq 'headline contexts)
7130 ;;????????? (looking-at "\\*+"))
7131 (looking-at outline-regexp))
7132 (and (memq 'item contexts)
7133 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7134 (and (memq 'item-body contexts)
7135 (org-in-item-p)))
7136 (goto-char pos))))
7138 (defun org-get-local-variables ()
7139 "Return a list of all local variables in an org-mode buffer."
7140 (let (varlist)
7141 (with-current-buffer (get-buffer-create "*Org tmp*")
7142 (erase-buffer)
7143 (org-mode)
7144 (setq varlist (buffer-local-variables)))
7145 (kill-buffer "*Org tmp*")
7146 (delq nil
7147 (mapcar
7148 (lambda (x)
7149 (setq x
7150 (if (symbolp x)
7151 (list x)
7152 (list (car x) (list 'quote (cdr x)))))
7153 (if (string-match
7154 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7155 (symbol-name (car x)))
7156 x nil))
7157 varlist))))
7159 ;;;###autoload
7160 (defun org-run-like-in-org-mode (cmd)
7161 "Run a command, pretending that the current buffer is in Org-mode.
7162 This will temporarily bind local variables that are typically bound in
7163 Org-mode to the values they have in Org-mode, and then interactively
7164 call CMD."
7165 (org-load-modules-maybe)
7166 (unless org-local-vars
7167 (setq org-local-vars (org-get-local-variables)))
7168 (eval (list 'let org-local-vars
7169 (list 'call-interactively (list 'quote cmd)))))
7171 ;;;; Archiving
7173 (defun org-get-category (&optional pos)
7174 "Get the category applying to position POS."
7175 (get-text-property (or pos (point)) 'org-category))
7177 (defun org-refresh-category-properties ()
7178 "Refresh category text properties in the buffer."
7179 (let ((def-cat (cond
7180 ((null org-category)
7181 (if buffer-file-name
7182 (file-name-sans-extension
7183 (file-name-nondirectory buffer-file-name))
7184 "???"))
7185 ((symbolp org-category) (symbol-name org-category))
7186 (t org-category)))
7187 beg end cat pos optionp)
7188 (org-unmodified
7189 (save-excursion
7190 (save-restriction
7191 (widen)
7192 (goto-char (point-min))
7193 (put-text-property (point) (point-max) 'org-category def-cat)
7194 (while (re-search-forward
7195 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7196 (setq pos (match-end 0)
7197 optionp (equal (char-after (match-beginning 0)) ?#)
7198 cat (org-trim (match-string 2)))
7199 (if optionp
7200 (setq beg (point-at-bol) end (point-max))
7201 (org-back-to-heading t)
7202 (setq beg (point) end (org-end-of-subtree t t)))
7203 (put-text-property beg end 'org-category cat)
7204 (goto-char pos)))))))
7207 ;;;; Link Stuff
7209 ;;; Link abbreviations
7211 (defun org-link-expand-abbrev (link)
7212 "Apply replacements as defined in `org-link-abbrev-alist."
7213 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7214 (let* ((key (match-string 1 link))
7215 (as (or (assoc key org-link-abbrev-alist-local)
7216 (assoc key org-link-abbrev-alist)))
7217 (tag (and (match-end 2) (match-string 3 link)))
7218 rpl)
7219 (if (not as)
7220 link
7221 (setq rpl (cdr as))
7222 (cond
7223 ((symbolp rpl) (funcall rpl tag))
7224 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7225 ((string-match "%h" rpl)
7226 (replace-match (url-hexify-string (or tag "")) t t rpl))
7227 (t (concat rpl tag)))))
7228 link))
7230 ;;; Storing and inserting links
7232 (defvar org-insert-link-history nil
7233 "Minibuffer history for links inserted with `org-insert-link'.")
7235 (defvar org-stored-links nil
7236 "Contains the links stored with `org-store-link'.")
7238 (defvar org-store-link-plist nil
7239 "Plist with info about the most recently link created with `org-store-link'.")
7241 (defvar org-link-protocols nil
7242 "Link protocols added to Org-mode using `org-add-link-type'.")
7244 (defvar org-store-link-functions nil
7245 "List of functions that are called to create and store a link.
7246 Each function will be called in turn until one returns a non-nil
7247 value. Each function should check if it is responsible for creating
7248 this link (for example by looking at the major mode).
7249 If not, it must exit and return nil.
7250 If yes, it should return a non-nil value after a calling
7251 `org-store-link-props' with a list of properties and values.
7252 Special properties are:
7254 :type The link prefix. like \"http\". This must be given.
7255 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7256 This is obligatory as well.
7257 :description Optional default description for the second pair
7258 of brackets in an Org-mode link. The user can still change
7259 this when inserting this link into an Org-mode buffer.
7261 In addition to these, any additional properties can be specified
7262 and then used in remember templates.")
7264 (defun org-add-link-type (type &optional follow export)
7265 "Add TYPE to the list of `org-link-types'.
7266 Re-compute all regular expressions depending on `org-link-types'
7268 FOLLOW and EXPORT are two functions.
7270 FOLLOW should take the link path as the single argument and do whatever
7271 is necessary to follow the link, for example find a file or display
7272 a mail message.
7274 EXPORT should format the link path for export to one of the export formats.
7275 It should be a function accepting three arguments:
7277 path the path of the link, the text after the prefix (like \"http:\")
7278 desc the description of the link, if any, nil if there was no description
7279 format the export format, a symbol like `html' or `latex'.
7281 The function may use the FORMAT information to return different values
7282 depending on the format. The return value will be put literally into
7283 the exported file.
7284 Org-mode has a built-in default for exporting links. If you are happy with
7285 this default, there is no need to define an export function for the link
7286 type. For a simple example of an export function, see `org-bbdb.el'."
7287 (add-to-list 'org-link-types type t)
7288 (org-make-link-regexps)
7289 (if (assoc type org-link-protocols)
7290 (setcdr (assoc type org-link-protocols) (list follow export))
7291 (push (list type follow export) org-link-protocols)))
7293 ;;;###autoload
7294 (defun org-store-link (arg)
7295 "\\<org-mode-map>Store an org-link to the current location.
7296 This link is added to `org-stored-links' and can later be inserted
7297 into an org-buffer with \\[org-insert-link].
7299 For some link types, a prefix arg is interpreted:
7300 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7301 For file links, arg negates `org-context-in-file-links'."
7302 (interactive "P")
7303 (org-load-modules-maybe)
7304 (setq org-store-link-plist nil) ; reset
7305 (let (link cpltxt desc description search txt custom-id)
7306 (cond
7308 ((run-hook-with-args-until-success 'org-store-link-functions)
7309 (setq link (plist-get org-store-link-plist :link)
7310 desc (or (plist-get org-store-link-plist :description) link)))
7312 ((equal (buffer-name) "*Org Edit Src Example*")
7313 (let (label gc)
7314 (while (or (not label)
7315 (save-excursion
7316 (save-restriction
7317 (widen)
7318 (goto-char (point-min))
7319 (re-search-forward
7320 (regexp-quote (format org-coderef-label-format label))
7321 nil t))))
7322 (when label (message "Label exists already") (sit-for 2))
7323 (setq label (read-string "Code line label: " label)))
7324 (end-of-line 1)
7325 (setq link (format org-coderef-label-format label))
7326 (setq gc (- 79 (length link)))
7327 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7328 (insert link)
7329 (setq link (concat "(" label ")") desc nil)))
7331 ((eq major-mode 'calendar-mode)
7332 (let ((cd (calendar-cursor-to-date)))
7333 (setq link
7334 (format-time-string
7335 (car org-time-stamp-formats)
7336 (apply 'encode-time
7337 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7338 nil nil nil))))
7339 (org-store-link-props :type "calendar" :date cd)))
7341 ((eq major-mode 'w3-mode)
7342 (setq cpltxt (if (and (buffer-name)
7343 (not (string-match "Untitled" (buffer-name))))
7344 (buffer-name)
7345 (url-view-url t))
7346 link (org-make-link (url-view-url t)))
7347 (org-store-link-props :type "w3" :url (url-view-url t)))
7349 ((eq major-mode 'w3m-mode)
7350 (setq cpltxt (or w3m-current-title w3m-current-url)
7351 link (org-make-link w3m-current-url))
7352 (org-store-link-props :type "w3m" :url (url-view-url t)))
7354 ((setq search (run-hook-with-args-until-success
7355 'org-create-file-search-functions))
7356 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7357 "::" search))
7358 (setq cpltxt (or description link)))
7360 ((eq major-mode 'image-mode)
7361 (setq cpltxt (concat "file:"
7362 (abbreviate-file-name buffer-file-name))
7363 link (org-make-link cpltxt))
7364 (org-store-link-props :type "image" :file buffer-file-name))
7366 ((eq major-mode 'dired-mode)
7367 ;; link to the file in the current line
7368 (setq cpltxt (concat "file:"
7369 (abbreviate-file-name
7370 (expand-file-name
7371 (dired-get-filename nil t))))
7372 link (org-make-link cpltxt)))
7374 ((and buffer-file-name (org-mode-p))
7375 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7376 (cond
7377 ((org-in-regexp "<<\\(.*?\\)>>")
7378 (setq cpltxt
7379 (concat "file:"
7380 (abbreviate-file-name buffer-file-name)
7381 "::" (match-string 1))
7382 link (org-make-link cpltxt)))
7383 ((and (featurep 'org-id)
7384 (or (eq org-link-to-org-use-id t)
7385 (and (eq org-link-to-org-use-id 'create-if-interactive)
7386 (interactive-p))
7387 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7388 (interactive-p)
7389 (not custom-id))
7390 (and org-link-to-org-use-id
7391 (condition-case nil
7392 (org-entry-get nil "ID")
7393 (error nil)))))
7394 ;; We can make a link using the ID.
7395 (setq link (condition-case nil
7396 (prog1 (org-id-store-link)
7397 (setq desc (plist-get org-store-link-plist
7398 :description)))
7399 (error
7400 ;; probably before first headline, link to file only
7401 (concat "file:"
7402 (abbreviate-file-name buffer-file-name))))))
7404 ;; Just link to current headline
7405 (setq cpltxt (concat "file:"
7406 (abbreviate-file-name buffer-file-name)))
7407 ;; Add a context search string
7408 (when (org-xor org-context-in-file-links arg)
7409 (setq txt (cond
7410 ((org-on-heading-p) nil)
7411 ((org-region-active-p)
7412 (buffer-substring (region-beginning) (region-end)))
7413 (t nil)))
7414 (when (or (null txt) (string-match "\\S-" txt))
7415 (setq cpltxt
7416 (concat cpltxt "::"
7417 (condition-case nil
7418 (org-make-org-heading-search-string txt)
7419 (error "")))
7420 desc "NONE")))
7421 (if (string-match "::\\'" cpltxt)
7422 (setq cpltxt (substring cpltxt 0 -2)))
7423 (setq link (org-make-link cpltxt)))))
7425 ((buffer-file-name (buffer-base-buffer))
7426 ;; Just link to this file here.
7427 (setq cpltxt (concat "file:"
7428 (abbreviate-file-name
7429 (buffer-file-name (buffer-base-buffer)))))
7430 ;; Add a context string
7431 (when (org-xor org-context-in-file-links arg)
7432 (setq txt (if (org-region-active-p)
7433 (buffer-substring (region-beginning) (region-end))
7434 (buffer-substring (point-at-bol) (point-at-eol))))
7435 ;; Only use search option if there is some text.
7436 (when (string-match "\\S-" txt)
7437 (setq cpltxt
7438 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7439 desc "NONE")))
7440 (setq link (org-make-link cpltxt)))
7442 ((interactive-p)
7443 (error "Cannot link to a buffer which is not visiting a file"))
7445 (t (setq link nil)))
7447 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7448 (setq link (or link cpltxt)
7449 desc (or desc cpltxt))
7450 (if (equal desc "NONE") (setq desc nil))
7452 (if (and (interactive-p) link)
7453 (progn
7454 (setq org-stored-links
7455 (cons (list link desc) org-stored-links))
7456 (message "Stored: %s" (or desc link))
7457 (when custom-id
7458 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7459 "::#" custom-id))
7460 (setq org-stored-links
7461 (cons (list link desc) org-stored-links))))
7462 (and link (org-make-link-string link desc)))))
7464 (defun org-store-link-props (&rest plist)
7465 "Store link properties, extract names and addresses."
7466 (let (x adr)
7467 (when (setq x (plist-get plist :from))
7468 (setq adr (mail-extract-address-components x))
7469 (setq plist (plist-put plist :fromname (car adr)))
7470 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7471 (when (setq x (plist-get plist :to))
7472 (setq adr (mail-extract-address-components x))
7473 (setq plist (plist-put plist :toname (car adr)))
7474 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7475 (let ((from (plist-get plist :from))
7476 (to (plist-get plist :to)))
7477 (when (and from to org-from-is-user-regexp)
7478 (setq plist
7479 (plist-put plist :fromto
7480 (if (string-match org-from-is-user-regexp from)
7481 (concat "to %t")
7482 (concat "from %f"))))))
7483 (setq org-store-link-plist plist))
7485 (defun org-add-link-props (&rest plist)
7486 "Add these properties to the link property list."
7487 (let (key value)
7488 (while plist
7489 (setq key (pop plist) value (pop plist))
7490 (setq org-store-link-plist
7491 (plist-put org-store-link-plist key value)))))
7493 (defun org-email-link-description (&optional fmt)
7494 "Return the description part of an email link.
7495 This takes information from `org-store-link-plist' and formats it
7496 according to FMT (default from `org-email-link-description-format')."
7497 (setq fmt (or fmt org-email-link-description-format))
7498 (let* ((p org-store-link-plist)
7499 (to (plist-get p :toaddress))
7500 (from (plist-get p :fromaddress))
7501 (table
7502 (list
7503 (cons "%c" (plist-get p :fromto))
7504 (cons "%F" (plist-get p :from))
7505 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7506 (cons "%T" (plist-get p :to))
7507 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7508 (cons "%s" (plist-get p :subject))
7509 (cons "%m" (plist-get p :message-id)))))
7510 (when (string-match "%c" fmt)
7511 ;; Check if the user wrote this message
7512 (if (and org-from-is-user-regexp from to
7513 (save-match-data (string-match org-from-is-user-regexp from)))
7514 (setq fmt (replace-match "to %t" t t fmt))
7515 (setq fmt (replace-match "from %f" t t fmt))))
7516 (org-replace-escapes fmt table)))
7518 (defun org-make-org-heading-search-string (&optional string heading)
7519 "Make search string for STRING or current headline."
7520 (interactive)
7521 (let ((s (or string (org-get-heading))))
7522 (unless (and string (not heading))
7523 ;; We are using a headline, clean up garbage in there.
7524 (if (string-match org-todo-regexp s)
7525 (setq s (replace-match "" t t s)))
7526 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7527 (setq s (replace-match "" t t s)))
7528 (setq s (org-trim s))
7529 (if (string-match (concat "^\\(" org-quote-string "\\|"
7530 org-comment-string "\\)") s)
7531 (setq s (replace-match "" t t s)))
7532 (while (string-match org-ts-regexp s)
7533 (setq s (replace-match "" t t s))))
7534 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7535 (setq s (replace-match " " t t s)))
7536 (or string (setq s (concat "*" s))) ; Add * for headlines
7537 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7539 (defun org-make-link (&rest strings)
7540 "Concatenate STRINGS."
7541 (apply 'concat strings))
7543 (defun org-make-link-string (link &optional description)
7544 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7545 (unless (string-match "\\S-" link)
7546 (error "Empty link"))
7547 (when (stringp description)
7548 ;; Remove brackets from the description, they are fatal.
7549 (while (string-match "\\[" description)
7550 (setq description (replace-match "{" t t description)))
7551 (while (string-match "\\]" description)
7552 (setq description (replace-match "}" t t description))))
7553 (when (equal (org-link-escape link) description)
7554 ;; No description needed, it is identical
7555 (setq description nil))
7556 (when (and (not description)
7557 (not (equal link (org-link-escape link))))
7558 (setq description (org-extract-attributes link)))
7559 (concat "[[" (org-link-escape link) "]"
7560 (if description (concat "[" description "]") "")
7561 "]"))
7563 (defconst org-link-escape-chars
7564 '((?\ . "%20")
7565 (?\[ . "%5B")
7566 (?\] . "%5D")
7567 (?\340 . "%E0") ; `a
7568 (?\342 . "%E2") ; ^a
7569 (?\347 . "%E7") ; ,c
7570 (?\350 . "%E8") ; `e
7571 (?\351 . "%E9") ; 'e
7572 (?\352 . "%EA") ; ^e
7573 (?\356 . "%EE") ; ^i
7574 (?\364 . "%F4") ; ^o
7575 (?\371 . "%F9") ; `u
7576 (?\373 . "%FB") ; ^u
7577 (?\; . "%3B")
7578 (?? . "%3F")
7579 (?= . "%3D")
7580 (?+ . "%2B")
7582 "Association list of escapes for some characters problematic in links.
7583 This is the list that is used for internal purposes.")
7585 (defvar org-url-encoding-use-url-hexify nil)
7587 (defconst org-link-escape-chars-browser
7588 '((?\ . "%20")) ; 32 for the SPC char
7589 "Association list of escapes for some characters problematic in links.
7590 This is the list that is used before handing over to the browser.")
7592 (defun org-link-escape (text &optional table)
7593 "Escape characters in TEXT that are problematic for links."
7594 (if org-url-encoding-use-url-hexify
7595 (url-hexify-string text)
7596 (setq table (or table org-link-escape-chars))
7597 (when text
7598 (let ((re (mapconcat (lambda (x) (regexp-quote
7599 (char-to-string (car x))))
7600 table "\\|")))
7601 (while (string-match re text)
7602 (setq text
7603 (replace-match
7604 (cdr (assoc (string-to-char (match-string 0 text))
7605 table))
7606 t t text)))
7607 text))))
7609 (defun org-link-unescape (text &optional table)
7610 "Reverse the action of `org-link-escape'."
7611 (if org-url-encoding-use-url-hexify
7612 (url-unhex-string text)
7613 (setq table (or table org-link-escape-chars))
7614 (when text
7615 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7616 table "\\|")))
7617 (while (string-match re text)
7618 (setq text
7619 (replace-match
7620 (char-to-string (car (rassoc (match-string 0 text) table)))
7621 t t text)))
7622 text))))
7624 (defun org-xor (a b)
7625 "Exclusive or."
7626 (if a (not b) b))
7628 (defun org-fixup-message-id-for-http (s)
7629 "Replace special characters in a message id, so it can be used in an http query."
7630 (while (string-match "<" s)
7631 (setq s (replace-match "%3C" t t s)))
7632 (while (string-match ">" s)
7633 (setq s (replace-match "%3E" t t s)))
7634 (while (string-match "@" s)
7635 (setq s (replace-match "%40" t t s)))
7638 ;;;###autoload
7639 (defun org-insert-link-global ()
7640 "Insert a link like Org-mode does.
7641 This command can be called in any mode to insert a link in Org-mode syntax."
7642 (interactive)
7643 (org-load-modules-maybe)
7644 (org-run-like-in-org-mode 'org-insert-link))
7646 (defun org-insert-link (&optional complete-file link-location)
7647 "Insert a link. At the prompt, enter the link.
7649 Completion can be used to insert any of the link protocol prefixes like
7650 http or ftp in use.
7652 The history can be used to select a link previously stored with
7653 `org-store-link'. When the empty string is entered (i.e. if you just
7654 press RET at the prompt), the link defaults to the most recently
7655 stored link. As SPC triggers completion in the minibuffer, you need to
7656 use M-SPC or C-q SPC to force the insertion of a space character.
7658 You will also be prompted for a description, and if one is given, it will
7659 be displayed in the buffer instead of the link.
7661 If there is already a link at point, this command will allow you to edit link
7662 and description parts.
7664 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7665 be selected using completion. The path to the file will be relative to the
7666 current directory if the file is in the current directory or a subdirectory.
7667 Otherwise, the link will be the absolute path as completed in the minibuffer
7668 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7669 option `org-link-file-path-type'.
7671 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7672 the current directory or below.
7674 With three \\[universal-argument] prefixes, negate the meaning of
7675 `org-keep-stored-link-after-insertion'.
7677 If `org-make-link-description-function' is non-nil, this function will be
7678 called with the link target, and the result will be the default
7679 link description.
7681 If the LINK-LOCATION parameter is non-nil, this value will be
7682 used as the link location instead of reading one interactively."
7683 (interactive "P")
7684 (let* ((wcf (current-window-configuration))
7685 (region (if (org-region-active-p)
7686 (buffer-substring (region-beginning) (region-end))))
7687 (remove (and region (list (region-beginning) (region-end))))
7688 (desc region)
7689 tmphist ; byte-compile incorrectly complains about this
7690 (link link-location)
7691 entry file all-prefixes)
7692 (cond
7693 (link-location) ; specified by arg, just use it.
7694 ((org-in-regexp org-bracket-link-regexp 1)
7695 ;; We do have a link at point, and we are going to edit it.
7696 (setq remove (list (match-beginning 0) (match-end 0)))
7697 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7698 (setq link (read-string "Link: "
7699 (org-link-unescape
7700 (org-match-string-no-properties 1)))))
7701 ((or (org-in-regexp org-angle-link-re)
7702 (org-in-regexp org-plain-link-re))
7703 ;; Convert to bracket link
7704 (setq remove (list (match-beginning 0) (match-end 0))
7705 link (read-string "Link: "
7706 (org-remove-angle-brackets (match-string 0)))))
7707 ((member complete-file '((4) (16)))
7708 ;; Completing read for file names.
7709 (setq link (org-file-complete-link complete-file)))
7711 ;; Read link, with completion for stored links.
7712 (with-output-to-temp-buffer "*Org Links*"
7713 (princ "Insert a link.
7714 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
7715 (when org-stored-links
7716 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7717 (princ (mapconcat
7718 (lambda (x)
7719 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7720 (reverse org-stored-links) "\n"))))
7721 (let ((cw (selected-window)))
7722 (select-window (get-buffer-window "*Org Links*"))
7723 (setq truncate-lines t)
7724 (unless (pos-visible-in-window-p (point-max))
7725 (org-fit-window-to-buffer))
7726 (and (window-live-p cw) (select-window cw)))
7727 ;; Fake a link history, containing the stored links.
7728 (setq tmphist (append (mapcar 'car org-stored-links)
7729 org-insert-link-history))
7730 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
7731 (mapcar 'car org-link-abbrev-alist)
7732 org-link-types))
7733 (unwind-protect
7734 (progn
7735 (setq link
7736 (let ((org-completion-use-ido nil))
7737 (org-completing-read
7738 "Link: "
7739 (mapcar (lambda (x) (list (concat x ":")))
7740 all-prefixes)
7741 nil nil nil
7742 'tmphist
7743 (or (car (car org-stored-links))))))
7744 (if (or (member link all-prefixes)
7745 (and (equal ":" (substring link -1))
7746 (member (substring link 0 -1) all-prefixes)
7747 (setq link (substring link 0 -1))))
7748 (setq link (org-link-try-special-completion link))))
7749 (set-window-configuration wcf)
7750 (kill-buffer "*Org Links*"))
7751 (setq entry (assoc link org-stored-links))
7752 (or entry (push link org-insert-link-history))
7753 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7754 (not org-keep-stored-link-after-insertion))
7755 (setq org-stored-links (delq (assoc link org-stored-links)
7756 org-stored-links)))
7757 (setq desc (or desc (nth 1 entry)))))
7759 (if (string-match org-plain-link-re link)
7760 ;; URL-like link, normalize the use of angular brackets.
7761 (setq link (org-make-link (org-remove-angle-brackets link))))
7763 ;; Check if we are linking to the current file with a search option
7764 ;; If yes, simplify the link by using only the search option.
7765 (when (and buffer-file-name
7766 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7767 (let* ((path (match-string 1 link))
7768 (case-fold-search nil)
7769 (search (match-string 2 link)))
7770 (save-match-data
7771 (if (equal (file-truename buffer-file-name) (file-truename path))
7772 ;; We are linking to this same file, with a search option
7773 (setq link search)))))
7775 ;; Check if we can/should use a relative path. If yes, simplify the link
7776 (when (string-match "^file:\\(.*\\)" link)
7777 (let* ((path (match-string 1 link))
7778 (origpath path)
7779 (case-fold-search nil))
7780 (cond
7781 ((or (eq org-link-file-path-type 'absolute)
7782 (equal complete-file '(16)))
7783 (setq path (abbreviate-file-name (expand-file-name path))))
7784 ((eq org-link-file-path-type 'noabbrev)
7785 (setq path (expand-file-name path)))
7786 ((eq org-link-file-path-type 'relative)
7787 (setq path (file-relative-name path)))
7789 (save-match-data
7790 (if (string-match (concat "^" (regexp-quote
7791 (file-name-as-directory
7792 (expand-file-name "."))))
7793 (expand-file-name path))
7794 ;; We are linking a file with relative path name.
7795 (setq path (substring (expand-file-name path)
7796 (match-end 0)))
7797 (setq path (abbreviate-file-name (expand-file-name path)))))))
7798 (setq link (concat "file:" path))
7799 (if (equal desc origpath)
7800 (setq desc path))))
7802 (if org-make-link-description-function
7803 (setq desc (funcall org-make-link-description-function link desc)))
7805 (setq desc (read-string "Description: " desc))
7806 (unless (string-match "\\S-" desc) (setq desc nil))
7807 (if remove (apply 'delete-region remove))
7808 (insert (org-make-link-string link desc))))
7810 (defun org-link-try-special-completion (type)
7811 "If there is completion support for link type TAPE, offer it."
7812 (let ((fun (intern (concat "org-" type "-complete-link"))))
7813 (if (functionp fun)
7814 (funcall fun)
7815 (read-string "Link (no completion support): " (concat type ":")))))
7817 (defun org-file-complete-link (&optional arg)
7818 "Create a file link using completion."
7819 (let (file link)
7820 (setq file (read-file-name "File: "))
7821 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7822 (pwd1 (file-name-as-directory (abbreviate-file-name
7823 (expand-file-name ".")))))
7824 (cond
7825 ((equal arg '(16))
7826 (setq link (org-make-link
7827 "file:"
7828 (abbreviate-file-name (expand-file-name file)))))
7829 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7830 (setq link (org-make-link "file:" (match-string 1 file))))
7831 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7832 (expand-file-name file))
7833 (setq link (org-make-link
7834 "file:" (match-string 1 (expand-file-name file)))))
7835 (t (setq link (org-make-link "file:" file)))))
7836 link))
7838 (defun org-completing-read (&rest args)
7839 "Completing-read with SPACE being a normal character."
7840 (let ((minibuffer-local-completion-map
7841 (copy-keymap minibuffer-local-completion-map)))
7842 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7843 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7844 (apply 'org-ido-completing-read args)))
7846 (defun org-completing-read-no-ido (&rest args)
7847 (let (org-completion-use-ido)
7848 (apply 'org-completing-read args)))
7850 (defun org-ido-completing-read (&rest args)
7851 "Completing-read using `ido-mode' speedups if available"
7852 (if (and org-completion-use-ido
7853 (fboundp 'ido-completing-read)
7854 (boundp 'ido-mode) ido-mode
7855 (listp (second args)))
7856 (let ((ido-enter-matching-directory nil))
7857 (apply 'ido-completing-read (concat (car args))
7858 (mapcar (lambda (x) (car x)) (nth 1 args))
7859 (cddr args)))
7860 (apply 'completing-read args)))
7862 (defun org-extract-attributes (s)
7863 "Extract the attributes cookie from a string and set as text property."
7864 (let (a attr (start 0) key value)
7865 (save-match-data
7866 (when (string-match "{{\\([^}]+\\)}}$" s)
7867 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7868 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7869 (setq key (match-string 1 a) value (match-string 2 a)
7870 start (match-end 0)
7871 attr (plist-put attr (intern key) value))))
7872 (org-add-props s nil 'org-attr attr))
7875 (defun org-extract-attributes-from-string (tag)
7876 (let (key value attr)
7877 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
7878 (setq key (match-string 1 tag) value (match-string 2 tag)
7879 tag (replace-match "" t t tag)
7880 attr (plist-put attr (intern key) value)))
7881 (cons tag attr)))
7883 (defun org-attributes-to-string (plist)
7884 "Format a property list into an HTML attribute list."
7885 (let ((s "") key value)
7886 (while plist
7887 (setq key (pop plist) value (pop plist))
7888 (and value
7889 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7892 ;;; Opening/following a link
7894 (defvar org-link-search-failed nil)
7896 (defun org-next-link ()
7897 "Move forward to the next link.
7898 If the link is in hidden text, expose it."
7899 (interactive)
7900 (when (and org-link-search-failed (eq this-command last-command))
7901 (goto-char (point-min))
7902 (message "Link search wrapped back to beginning of buffer"))
7903 (setq org-link-search-failed nil)
7904 (let* ((pos (point))
7905 (ct (org-context))
7906 (a (assoc :link ct)))
7907 (if a (goto-char (nth 2 a)))
7908 (if (re-search-forward org-any-link-re nil t)
7909 (progn
7910 (goto-char (match-beginning 0))
7911 (if (org-invisible-p) (org-show-context)))
7912 (goto-char pos)
7913 (setq org-link-search-failed t)
7914 (error "No further link found"))))
7916 (defun org-previous-link ()
7917 "Move backward to the previous link.
7918 If the link is in hidden text, expose it."
7919 (interactive)
7920 (when (and org-link-search-failed (eq this-command last-command))
7921 (goto-char (point-max))
7922 (message "Link search wrapped back to end of buffer"))
7923 (setq org-link-search-failed nil)
7924 (let* ((pos (point))
7925 (ct (org-context))
7926 (a (assoc :link ct)))
7927 (if a (goto-char (nth 1 a)))
7928 (if (re-search-backward org-any-link-re nil t)
7929 (progn
7930 (goto-char (match-beginning 0))
7931 (if (org-invisible-p) (org-show-context)))
7932 (goto-char pos)
7933 (setq org-link-search-failed t)
7934 (error "No further link found"))))
7936 (defun org-translate-link (s)
7937 "Translate a link string if a translation function has been defined."
7938 (if (and org-link-translation-function
7939 (fboundp org-link-translation-function)
7940 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7941 (progn
7942 (setq s (funcall org-link-translation-function
7943 (match-string 1) (match-string 2)))
7944 (concat (car s) ":" (cdr s)))
7947 (defun org-translate-link-from-planner (type path)
7948 "Translate a link from Emacs Planner syntax so that Org can follow it.
7949 This is still an experimental function, your mileage may vary."
7950 (cond
7951 ((member type '("http" "https" "news" "ftp"))
7952 ;; standard Internet links are the same.
7953 nil)
7954 ((and (equal type "irc") (string-match "^//" path))
7955 ;; Planner has two / at the beginning of an irc link, we have 1.
7956 ;; We should have zero, actually....
7957 (setq path (substring path 1)))
7958 ((and (equal type "lisp") (string-match "^/" path))
7959 ;; Planner has a slash, we do not.
7960 (setq type "elisp" path (substring path 1)))
7961 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7962 ;; A typical message link. Planner has the id after the fina slash,
7963 ;; we separate it with a hash mark
7964 (setq path (concat (match-string 1 path) "#"
7965 (org-remove-angle-brackets (match-string 2 path)))))
7967 (cons type path))
7969 (defun org-find-file-at-mouse (ev)
7970 "Open file link or URL at mouse."
7971 (interactive "e")
7972 (mouse-set-point ev)
7973 (org-open-at-point 'in-emacs))
7975 (defun org-open-at-mouse (ev)
7976 "Open file link or URL at mouse."
7977 (interactive "e")
7978 (mouse-set-point ev)
7979 (if (eq major-mode 'org-agenda-mode)
7980 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7981 (org-open-at-point))
7983 (defvar org-window-config-before-follow-link nil
7984 "The window configuration before following a link.
7985 This is saved in case the need arises to restore it.")
7987 (defvar org-open-link-marker (make-marker)
7988 "Marker pointing to the location where `org-open-at-point; was called.")
7990 ;;;###autoload
7991 (defun org-open-at-point-global ()
7992 "Follow a link like Org-mode does.
7993 This command can be called in any mode to follow a link that has
7994 Org-mode syntax."
7995 (interactive)
7996 (org-run-like-in-org-mode 'org-open-at-point))
7998 ;;;###autoload
7999 (defun org-open-link-from-string (s &optional arg)
8000 "Open a link in the string S, as if it was in Org-mode."
8001 (interactive "sLink: \nP")
8002 (let ((reference-buffer (current-buffer)))
8003 (with-temp-buffer
8004 (let ((org-inhibit-startup t))
8005 (org-mode)
8006 (insert s)
8007 (goto-char (point-min))
8008 (org-open-at-point arg reference-buffer)))))
8010 (defun org-open-at-point (&optional in-emacs reference-buffer)
8011 "Open link at or after point.
8012 If there is no link at point, this function will search forward up to
8013 the end of the current line.
8014 Normally, files will be opened by an appropriate application. If the
8015 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8016 With a double prefix argument, try to open outside of Emacs, in the
8017 application the system uses for this file type."
8018 (interactive "P")
8019 (org-load-modules-maybe)
8020 (move-marker org-open-link-marker (point))
8021 (setq org-window-config-before-follow-link (current-window-configuration))
8022 (org-remove-occur-highlights nil nil t)
8023 (cond
8024 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8025 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8026 (org-footnote-action))
8028 (let (type path link line search (pos (point)))
8029 (catch 'match
8030 (save-excursion
8031 (skip-chars-forward "^]\n\r")
8032 (when (org-in-regexp org-bracket-link-regexp)
8033 (setq link (org-extract-attributes
8034 (org-link-unescape (org-match-string-no-properties 1))))
8035 (while (string-match " *\n *" link)
8036 (setq link (replace-match " " t t link)))
8037 (setq link (org-link-expand-abbrev link))
8038 (cond
8039 ((or (file-name-absolute-p link)
8040 (string-match "^\\.\\.?/" link))
8041 (setq type "file" path link))
8042 ((string-match org-link-re-with-space3 link)
8043 (setq type (match-string 1 link) path (match-string 2 link)))
8044 (t (setq type "thisfile" path link)))
8045 (throw 'match t)))
8047 (when (get-text-property (point) 'org-linked-text)
8048 (setq type "thisfile"
8049 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8050 (1+ (point)) (point))
8051 path (buffer-substring
8052 (previous-single-property-change pos 'org-linked-text)
8053 (next-single-property-change pos 'org-linked-text)))
8054 (throw 'match t))
8056 (save-excursion
8057 (when (or (org-in-regexp org-angle-link-re)
8058 (org-in-regexp org-plain-link-re))
8059 (setq type (match-string 1) path (match-string 2))
8060 (throw 'match t)))
8061 (save-excursion
8062 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
8063 (setq type "tags"
8064 path (match-string 1))
8065 (while (string-match ":" path)
8066 (setq path (replace-match "+" t t path)))
8067 (throw 'match t)))
8068 (when (org-in-regexp "<\\([^><\n]+\\)>")
8069 (setq type "tree-match"
8070 path (match-string 1))
8071 (throw 'match t)))
8072 (unless path
8073 (error "No link found"))
8075 ;; switch back to reference buffer
8076 ;; needed when if called in a temporary buffer through
8077 ;; org-open-link-from-string
8078 (and reference-buffer (switch-to-buffer reference-buffer))
8080 ;; Remove any trailing spaces in path
8081 (if (string-match " +\\'" path)
8082 (setq path (replace-match "" t t path)))
8083 (if (and org-link-translation-function
8084 (fboundp org-link-translation-function))
8085 ;; Check if we need to translate the link
8086 (let ((tmp (funcall org-link-translation-function type path)))
8087 (setq type (car tmp) path (cdr tmp))))
8089 (cond
8091 ((assoc type org-link-protocols)
8092 (funcall (nth 1 (assoc type org-link-protocols)) path))
8094 ((equal type "mailto")
8095 (let ((cmd (car org-link-mailto-program))
8096 (args (cdr org-link-mailto-program)) args1
8097 (address path) (subject "") a)
8098 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8099 (setq address (match-string 1 path)
8100 subject (org-link-escape (match-string 2 path))))
8101 (while args
8102 (cond
8103 ((not (stringp (car args))) (push (pop args) args1))
8104 (t (setq a (pop args))
8105 (if (string-match "%a" a)
8106 (setq a (replace-match address t t a)))
8107 (if (string-match "%s" a)
8108 (setq a (replace-match subject t t a)))
8109 (push a args1))))
8110 (apply cmd (nreverse args1))))
8112 ((member type '("http" "https" "ftp" "news"))
8113 (browse-url (concat type ":" (org-link-escape
8114 path org-link-escape-chars-browser))))
8116 ((member type '("message"))
8117 (browse-url (concat type ":" path)))
8119 ((string= type "tags")
8120 (org-tags-view in-emacs path))
8121 ((string= type "thisfile")
8122 (if in-emacs
8123 (switch-to-buffer-other-window
8124 (org-get-buffer-for-internal-link (current-buffer)))
8125 (org-mark-ring-push))
8126 (let ((cmd `(org-link-search
8127 ,path
8128 ,(cond ((equal in-emacs '(4)) 'occur)
8129 ((equal in-emacs '(16)) 'org-occur)
8130 (t nil))
8131 ,pos)))
8132 (condition-case nil (eval cmd)
8133 (error (progn (widen) (eval cmd))))))
8135 ((string= type "tree-match")
8136 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8138 ((string= type "file")
8139 (if (string-match "::\\([0-9]+\\)\\'" path)
8140 (setq line (string-to-number (match-string 1 path))
8141 path (substring path 0 (match-beginning 0)))
8142 (if (string-match "::\\(.+\\)\\'" path)
8143 (setq search (match-string 1 path)
8144 path (substring path 0 (match-beginning 0)))))
8145 (if (string-match "[*?{]" (file-name-nondirectory path))
8146 (dired path)
8147 (org-open-file path in-emacs line search)))
8149 ((string= type "news")
8150 (require 'org-gnus)
8151 (org-gnus-follow-link path))
8153 ((string= type "shell")
8154 (let ((cmd path))
8155 (if (or (not org-confirm-shell-link-function)
8156 (funcall org-confirm-shell-link-function
8157 (format "Execute \"%s\" in shell? "
8158 (org-add-props cmd nil
8159 'face 'org-warning))))
8160 (progn
8161 (message "Executing %s" cmd)
8162 (shell-command cmd))
8163 (error "Abort"))))
8165 ((string= type "elisp")
8166 (let ((cmd path))
8167 (if (or (not org-confirm-elisp-link-function)
8168 (funcall org-confirm-elisp-link-function
8169 (format "Execute \"%s\" as elisp? "
8170 (org-add-props cmd nil
8171 'face 'org-warning))))
8172 (message "%s => %s" cmd
8173 (if (equal (string-to-char cmd) ?\()
8174 (eval (read cmd))
8175 (call-interactively (read cmd))))
8176 (error "Abort"))))
8179 (browse-url-at-point))))))
8180 (move-marker org-open-link-marker nil)
8181 (run-hook-with-args 'org-follow-link-hook))
8183 ;;;; Time estimates
8185 (defun org-get-effort (&optional pom)
8186 "Get the effort estimate for the current entry."
8187 (org-entry-get pom org-effort-property))
8189 ;;; File search
8191 (defvar org-create-file-search-functions nil
8192 "List of functions to construct the right search string for a file link.
8193 These functions are called in turn with point at the location to
8194 which the link should point.
8196 A function in the hook should first test if it would like to
8197 handle this file type, for example by checking the major-mode or
8198 the file extension. If it decides not to handle this file, it
8199 should just return nil to give other functions a chance. If it
8200 does handle the file, it must return the search string to be used
8201 when following the link. The search string will be part of the
8202 file link, given after a double colon, and `org-open-at-point'
8203 will automatically search for it. If special measures must be
8204 taken to make the search successful, another function should be
8205 added to the companion hook `org-execute-file-search-functions',
8206 which see.
8208 A function in this hook may also use `setq' to set the variable
8209 `description' to provide a suggestion for the descriptive text to
8210 be used for this link when it gets inserted into an Org-mode
8211 buffer with \\[org-insert-link].")
8213 (defvar org-execute-file-search-functions nil
8214 "List of functions to execute a file search triggered by a link.
8216 Functions added to this hook must accept a single argument, the
8217 search string that was part of the file link, the part after the
8218 double colon. The function must first check if it would like to
8219 handle this search, for example by checking the major-mode or the
8220 file extension. If it decides not to handle this search, it
8221 should just return nil to give other functions a chance. If it
8222 does handle the search, it must return a non-nil value to keep
8223 other functions from trying.
8225 Each function can access the current prefix argument through the
8226 variable `current-prefix-argument'. Note that a single prefix is
8227 used to force opening a link in Emacs, so it may be good to only
8228 use a numeric or double prefix to guide the search function.
8230 In case this is needed, a function in this hook can also restore
8231 the window configuration before `org-open-at-point' was called using:
8233 (set-window-configuration org-window-config-before-follow-link)")
8235 (defun org-link-search (s &optional type avoid-pos)
8236 "Search for a link search option.
8237 If S is surrounded by forward slashes, it is interpreted as a
8238 regular expression. In org-mode files, this will create an `org-occur'
8239 sparse tree. In ordinary files, `occur' will be used to list matches.
8240 If the current buffer is in `dired-mode', grep will be used to search
8241 in all files. If AVOID-POS is given, ignore matches near that position."
8242 (let ((case-fold-search t)
8243 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8244 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8245 (append '(("") (" ") ("\t") ("\n"))
8246 org-emphasis-alist)
8247 "\\|") "\\)"))
8248 (pos (point))
8249 (pre nil) (post nil)
8250 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8251 (cond
8252 ;; First check if there are any special
8253 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8254 ;; Now try the builtin stuff
8255 ((and (equal (string-to-char s0) ?#)
8256 (> (length s0) 1)
8257 (save-excursion
8258 (goto-char (point-min))
8259 (and
8260 (re-search-forward
8261 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8262 (setq type 'dedicated
8263 pos (match-beginning 0))))
8264 ;; There is an exact target for this
8265 (goto-char pos)
8266 (org-back-to-heading t)))
8267 ((save-excursion
8268 (goto-char (point-min))
8269 (and
8270 (re-search-forward
8271 (concat "<<" (regexp-quote s0) ">>") nil t)
8272 (setq type 'dedicated
8273 pos (match-beginning 0))))
8274 ;; There is an exact target for this
8275 (goto-char pos))
8276 ((and (string-match "^(\\(.*\\))$" s0)
8277 (save-excursion
8278 (goto-char (point-min))
8279 (and
8280 (re-search-forward
8281 (concat "[^[]" (regexp-quote
8282 (format org-coderef-label-format
8283 (match-string 1 s0))))
8284 nil t)
8285 (setq type 'dedicated
8286 pos (1+ (match-beginning 0))))))
8287 ;; There is a coderef target for this
8288 (goto-char pos))
8289 ((string-match "^/\\(.*\\)/$" s)
8290 ;; A regular expression
8291 (cond
8292 ((org-mode-p)
8293 (org-occur (match-string 1 s)))
8294 ;;((eq major-mode 'dired-mode)
8295 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8296 (t (org-do-occur (match-string 1 s)))))
8298 ;; A normal search strings
8299 (when (equal (string-to-char s) ?*)
8300 ;; Anchor on headlines, post may include tags.
8301 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8302 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8303 s (substring s 1)))
8304 (remove-text-properties
8305 0 (length s)
8306 '(face nil mouse-face nil keymap nil fontified nil) s)
8307 ;; Make a series of regular expressions to find a match
8308 (setq words (org-split-string s "[ \n\r\t]+")
8310 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8311 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8312 "\\)" markers)
8313 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8314 re2a (concat "[ \t\r\n]" re2a_)
8315 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8316 re4 (concat "[^a-zA-Z_]" re4_)
8318 re1 (concat pre re2 post)
8319 re3 (concat pre (if pre re4_ re4) post)
8320 re5 (concat pre ".*" re4)
8321 re2 (concat pre re2)
8322 re2a (concat pre (if pre re2a_ re2a))
8323 re4 (concat pre (if pre re4_ re4))
8324 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8325 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8326 re5 "\\)"
8328 (cond
8329 ((eq type 'org-occur) (org-occur reall))
8330 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8331 (t (goto-char (point-min))
8332 (setq type 'fuzzy)
8333 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8334 (org-search-not-self 1 re1 nil t)
8335 (org-search-not-self 1 re2 nil t)
8336 (org-search-not-self 1 re2a nil t)
8337 (org-search-not-self 1 re3 nil t)
8338 (org-search-not-self 1 re4 nil t)
8339 (org-search-not-self 1 re5 nil t)
8341 (goto-char (match-beginning 1))
8342 (goto-char pos)
8343 (error "No match")))))
8345 ;; Normal string-search
8346 (goto-char (point-min))
8347 (if (search-forward s nil t)
8348 (goto-char (match-beginning 0))
8349 (error "No match"))))
8350 (and (org-mode-p) (org-show-context 'link-search))
8351 type))
8353 (defun org-search-not-self (group &rest args)
8354 "Execute `re-search-forward', but only accept matches that do not
8355 enclose the position of `org-open-link-marker'."
8356 (let ((m org-open-link-marker))
8357 (catch 'exit
8358 (while (apply 're-search-forward args)
8359 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8360 (goto-char (match-end group))
8361 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8362 (> (match-beginning 0) (marker-position m))
8363 (< (match-end 0) (marker-position m)))
8364 (save-match-data
8365 (or (not (org-in-regexp
8366 org-bracket-link-analytic-regexp 1))
8367 (not (match-end 4)) ; no description
8368 (and (<= (match-beginning 4) (point))
8369 (>= (match-end 4) (point))))))
8370 (throw 'exit (point))))))))
8372 (defun org-get-buffer-for-internal-link (buffer)
8373 "Return a buffer to be used for displaying the link target of internal links."
8374 (cond
8375 ((not org-display-internal-link-with-indirect-buffer)
8376 buffer)
8377 ((string-match "(Clone)$" (buffer-name buffer))
8378 (message "Buffer is already a clone, not making another one")
8379 ;; we also do not modify visibility in this case
8380 buffer)
8381 (t ; make a new indirect buffer for displaying the link
8382 (let* ((bn (buffer-name buffer))
8383 (ibn (concat bn "(Clone)"))
8384 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8385 (with-current-buffer ib (org-overview))
8386 ib))))
8388 (defun org-do-occur (regexp &optional cleanup)
8389 "Call the Emacs command `occur'.
8390 If CLEANUP is non-nil, remove the printout of the regular expression
8391 in the *Occur* buffer. This is useful if the regex is long and not useful
8392 to read."
8393 (occur regexp)
8394 (when cleanup
8395 (let ((cwin (selected-window)) win beg end)
8396 (when (setq win (get-buffer-window "*Occur*"))
8397 (select-window win))
8398 (goto-char (point-min))
8399 (when (re-search-forward "match[a-z]+" nil t)
8400 (setq beg (match-end 0))
8401 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8402 (setq end (1- (match-beginning 0)))))
8403 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8404 (goto-char (point-min))
8405 (select-window cwin))))
8407 ;;; The mark ring for links jumps
8409 (defvar org-mark-ring nil
8410 "Mark ring for positions before jumps in Org-mode.")
8411 (defvar org-mark-ring-last-goto nil
8412 "Last position in the mark ring used to go back.")
8413 ;; Fill and close the ring
8414 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8415 (loop for i from 1 to org-mark-ring-length do
8416 (push (make-marker) org-mark-ring))
8417 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8418 org-mark-ring)
8420 (defun org-mark-ring-push (&optional pos buffer)
8421 "Put the current position or POS into the mark ring and rotate it."
8422 (interactive)
8423 (setq pos (or pos (point)))
8424 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8425 (move-marker (car org-mark-ring)
8426 (or pos (point))
8427 (or buffer (current-buffer)))
8428 (message "%s"
8429 (substitute-command-keys
8430 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8432 (defun org-mark-ring-goto (&optional n)
8433 "Jump to the previous position in the mark ring.
8434 With prefix arg N, jump back that many stored positions. When
8435 called several times in succession, walk through the entire ring.
8436 Org-mode commands jumping to a different position in the current file,
8437 or to another Org-mode file, automatically push the old position
8438 onto the ring."
8439 (interactive "p")
8440 (let (p m)
8441 (if (eq last-command this-command)
8442 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8443 (setq p org-mark-ring))
8444 (setq org-mark-ring-last-goto p)
8445 (setq m (car p))
8446 (switch-to-buffer (marker-buffer m))
8447 (goto-char m)
8448 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8450 (defun org-remove-angle-brackets (s)
8451 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8452 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8454 (defun org-add-angle-brackets (s)
8455 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8456 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8458 (defun org-remove-double-quotes (s)
8459 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8460 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8463 ;;; Following specific links
8465 (defun org-follow-timestamp-link ()
8466 (cond
8467 ((org-at-date-range-p t)
8468 (let ((org-agenda-start-on-weekday)
8469 (t1 (match-string 1))
8470 (t2 (match-string 2)))
8471 (setq t1 (time-to-days (org-time-string-to-time t1))
8472 t2 (time-to-days (org-time-string-to-time t2)))
8473 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8474 ((org-at-timestamp-p t)
8475 (org-agenda-list nil (time-to-days (org-time-string-to-time
8476 (substring (match-string 1) 0 10)))
8478 (t (error "This should not happen"))))
8481 ;;; Following file links
8482 (defvar org-wait nil)
8483 (defun org-open-file (path &optional in-emacs line search)
8484 "Open the file at PATH.
8485 First, this expands any special file name abbreviations. Then the
8486 configuration variable `org-file-apps' is checked if it contains an
8487 entry for this file type, and if yes, the corresponding command is launched.
8489 If no application is found, Emacs simply visits the file.
8491 With optional prefix argument IN-EMACS, Emacs will visit the file.
8492 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8493 and o use an external application to visit the file.
8495 Optional LINE specifies a line to go to, optional SEARCH a string to
8496 search for. If LINE or SEARCH is given, the file will always be
8497 opened in Emacs.
8498 If the file does not exist, an error is thrown."
8499 (setq in-emacs (or in-emacs line search))
8500 (let* ((file (if (equal path "")
8501 buffer-file-name
8502 (substitute-in-file-name (expand-file-name path))))
8503 (apps (append org-file-apps (org-default-apps)))
8504 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8505 (dirp (if remp nil (file-directory-p file)))
8506 (file (if (and dirp org-open-directory-means-index-dot-org)
8507 (concat (file-name-as-directory file) "index.org")
8508 file))
8509 (a-m-a-p (assq 'auto-mode apps))
8510 (dfile (downcase file))
8511 (old-buffer (current-buffer))
8512 (old-pos (point))
8513 (old-mode major-mode)
8514 ext cmd)
8515 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8516 (setq ext (match-string 1 dfile))
8517 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8518 (setq ext (match-string 1 dfile))))
8519 (cond
8520 ((equal in-emacs '(16))
8521 (setq cmd (cdr (assoc 'system apps))))
8522 (in-emacs (setq cmd 'emacs))
8524 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8525 (and dirp (cdr (assoc 'directory apps)))
8526 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8527 'string-match)
8528 (cdr (assoc ext apps))
8529 (cdr (assoc t apps))))))
8530 (when (eq cmd 'system)
8531 (setq cmd (cdr (assoc 'system apps))))
8532 (when (eq cmd 'default)
8533 (setq cmd (cdr (assoc t apps))))
8534 (when (eq cmd 'mailcap)
8535 (require 'mailcap)
8536 (mailcap-parse-mailcaps)
8537 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8538 (command (mailcap-mime-info mime-type)))
8539 (if (stringp command)
8540 (setq cmd command)
8541 (setq cmd 'emacs))))
8542 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8543 (not (file-exists-p file))
8544 (not org-open-non-existing-files))
8545 (error "No such file: %s" file))
8546 (cond
8547 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8548 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8549 (while (string-match "['\"]%s['\"]" cmd)
8550 (setq cmd (replace-match "%s" t t cmd)))
8551 (while (string-match "%s" cmd)
8552 (setq cmd (replace-match
8553 (save-match-data
8554 (shell-quote-argument
8555 (convert-standard-filename file)))
8556 t t cmd)))
8557 (save-window-excursion
8558 (start-process-shell-command cmd nil cmd)
8559 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8561 ((or (stringp cmd)
8562 (eq cmd 'emacs))
8563 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8564 (widen)
8565 (if line (goto-line line)
8566 (if search (org-link-search search))))
8567 ((consp cmd)
8568 (let ((file (convert-standard-filename file)))
8569 (eval cmd)))
8570 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8571 (and (org-mode-p) (eq old-mode 'org-mode)
8572 (or (not (equal old-buffer (current-buffer)))
8573 (not (equal old-pos (point))))
8574 (org-mark-ring-push old-pos old-buffer))))
8576 (defun org-default-apps ()
8577 "Return the default applications for this operating system."
8578 (cond
8579 ((eq system-type 'darwin)
8580 org-file-apps-defaults-macosx)
8581 ((eq system-type 'windows-nt)
8582 org-file-apps-defaults-windowsnt)
8583 (t org-file-apps-defaults-gnu)))
8585 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8586 "Convert extensions to regular expressions in the cars of LIST.
8587 Also, weed out any non-string entries, because the return value is used
8588 only for regexp matching.
8589 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8590 point to the symbol `emacs', indicating that the file should
8591 be opened in Emacs."
8592 (append
8593 (delq nil
8594 (mapcar (lambda (x)
8595 (if (not (stringp (car x)))
8597 (if (string-match "\\W" (car x))
8599 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8600 list))
8601 (if add-auto-mode
8602 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8604 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8605 (defun org-file-remote-p (file)
8606 "Test whether FILE specifies a location on a remote system.
8607 Return non-nil if the location is indeed remote.
8609 For example, the filename \"/user@host:/foo\" specifies a location
8610 on the system \"/user@host:\"."
8611 (cond ((fboundp 'file-remote-p)
8612 (file-remote-p file))
8613 ((fboundp 'tramp-handle-file-remote-p)
8614 (tramp-handle-file-remote-p file))
8615 ((and (boundp 'ange-ftp-name-format)
8616 (string-match (car ange-ftp-name-format) file))
8618 (t nil)))
8621 ;;;; Refiling
8623 (defun org-get-org-file ()
8624 "Read a filename, with default directory `org-directory'."
8625 (let ((default (or org-default-notes-file remember-data-file)))
8626 (read-file-name (format "File name [%s]: " default)
8627 (file-name-as-directory org-directory)
8628 default)))
8630 (defun org-notes-order-reversed-p ()
8631 "Check if the current file should receive notes in reversed order."
8632 (cond
8633 ((not org-reverse-note-order) nil)
8634 ((eq t org-reverse-note-order) t)
8635 ((not (listp org-reverse-note-order)) nil)
8636 (t (catch 'exit
8637 (let ((all org-reverse-note-order)
8638 entry)
8639 (while (setq entry (pop all))
8640 (if (string-match (car entry) buffer-file-name)
8641 (throw 'exit (cdr entry))))
8642 nil)))))
8644 (defvar org-refile-target-table nil
8645 "The list of refile targets, created by `org-refile'.")
8647 (defvar org-agenda-new-buffers nil
8648 "Buffers created to visit agenda files.")
8650 (defun org-get-refile-targets (&optional default-buffer)
8651 "Produce a table with refile targets."
8652 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
8653 targets txt re files f desc descre fast-path-p level pos0)
8654 (message "Getting targets...")
8655 (with-current-buffer (or default-buffer (current-buffer))
8656 (while (setq entry (pop entries))
8657 (setq files (car entry) desc (cdr entry))
8658 (setq fast-path-p nil)
8659 (cond
8660 ((null files) (setq files (list (current-buffer))))
8661 ((eq files 'org-agenda-files)
8662 (setq files (org-agenda-files 'unrestricted)))
8663 ((and (symbolp files) (fboundp files))
8664 (setq files (funcall files)))
8665 ((and (symbolp files) (boundp files))
8666 (setq files (symbol-value files))))
8667 (if (stringp files) (setq files (list files)))
8668 (cond
8669 ((eq (car desc) :tag)
8670 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8671 ((eq (car desc) :todo)
8672 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8673 ((eq (car desc) :regexp)
8674 (setq descre (cdr desc)))
8675 ((eq (car desc) :level)
8676 (setq descre (concat "^\\*\\{" (number-to-string
8677 (if org-odd-levels-only
8678 (1- (* 2 (cdr desc)))
8679 (cdr desc)))
8680 "\\}[ \t]")))
8681 ((eq (car desc) :maxlevel)
8682 (setq fast-path-p t)
8683 (setq descre (concat "^\\*\\{1," (number-to-string
8684 (if org-odd-levels-only
8685 (1- (* 2 (cdr desc)))
8686 (cdr desc)))
8687 "\\}[ \t]")))
8688 (t (error "Bad refiling target description %s" desc)))
8689 (while (setq f (pop files))
8690 (save-excursion
8691 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
8692 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8693 (setq f (expand-file-name f))
8694 (if (eq org-refile-use-outline-path 'file)
8695 (push (list (file-name-nondirectory f) f nil nil) targets))
8696 (save-excursion
8697 (save-restriction
8698 (widen)
8699 (goto-char (point-min))
8700 (while (re-search-forward descre nil t)
8701 (goto-char (setq pos0 (point-at-bol)))
8702 (catch 'next
8703 (when org-refile-target-verify-function
8704 (save-match-data
8705 (or (funcall org-refile-target-verify-function)
8706 (throw 'next t))))
8707 (when (looking-at org-complex-heading-regexp)
8708 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8709 txt (org-link-display-format (match-string 4))
8710 re (concat "^" (regexp-quote
8711 (buffer-substring (match-beginning 1)
8712 (match-end 4)))))
8713 (if (match-end 5) (setq re (concat re "[ \t]+"
8714 (regexp-quote
8715 (match-string 5)))))
8716 (setq re (concat re "[ \t]*$"))
8717 (when org-refile-use-outline-path
8718 (setq txt (mapconcat 'org-protect-slash
8719 (append
8720 (if (eq org-refile-use-outline-path 'file)
8721 (list (file-name-nondirectory
8722 (buffer-file-name (buffer-base-buffer))))
8723 (if (eq org-refile-use-outline-path 'full-file-path)
8724 (list (buffer-file-name (buffer-base-buffer)))))
8725 (org-get-outline-path fast-path-p level txt)
8726 (list txt))
8727 "/")))
8728 (push (list txt f re (point)) targets)))
8729 (when (= (point) pos0)
8730 ;; verification function has not moved point
8731 (goto-char (point-at-eol))))))))))
8732 (message "Getting targets...done")
8733 (nreverse targets)))
8735 (defun org-protect-slash (s)
8736 (while (string-match "/" s)
8737 (setq s (replace-match "\\" t t s)))
8740 (defvar org-olpa (make-vector 20 nil))
8742 (defun org-get-outline-path (&optional fastp level heading)
8743 "Return the outline path to the current entry, as a list."
8744 (if fastp
8745 (progn
8746 (if (> level 19)
8747 (error "Outline path failure, more than 19 levels."))
8748 (loop for i from level upto 19 do
8749 (aset org-olpa i nil))
8750 (prog1
8751 (delq nil (append org-olpa nil))
8752 (aset org-olpa level heading)))
8753 (let (rtn)
8754 (save-excursion
8755 (while (org-up-heading-safe)
8756 (when (looking-at org-complex-heading-regexp)
8757 (push (org-match-string-no-properties 4) rtn)))
8758 rtn))))
8760 (defvar org-refile-history nil
8761 "History for refiling operations.")
8763 (defvar org-after-refile-insert-hook nil
8764 "Hook run after `org-refile' has inserted its stuff at the new location.
8765 Note that this is still *before* the stuff will be removed from
8766 the *old* location.")
8768 (defun org-refile (&optional goto default-buffer)
8769 "Move the entry at point to another heading.
8770 The list of target headings is compiled using the information in
8771 `org-refile-targets', which see. This list is created before each use
8772 and will therefore always be up-to-date.
8774 At the target location, the entry is filed as a subitem of the target heading.
8775 Depending on `org-reverse-note-order', the new subitem will either be the
8776 first or the last subitem.
8778 If there is an active region, all entries in that region will be moved.
8779 However, the region must fulfil the requirement that the first heading
8780 is the first one sets the top-level of the moved text - at most siblings
8781 below it are allowed.
8783 With prefix arg GOTO, the command will only visit the target location,
8784 not actually move anything.
8785 With a double prefix `C-u C-u', go to the location where the last refiling
8786 operation has put the subtree.
8788 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
8789 (interactive "P")
8790 (let* ((cbuf (current-buffer))
8791 (regionp (org-region-active-p))
8792 (region-start (and regionp (region-beginning)))
8793 (region-end (and regionp (region-end)))
8794 (region-length (and regionp (- region-end region-start)))
8795 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8796 pos it nbuf file re level reversed)
8797 (when regionp (goto-char region-start)
8798 (unless (org-kill-is-subtree-p
8799 (buffer-substring region-start region-end))
8800 (error "The region is not a (sequence of) subtree(s)")))
8801 (if (equal goto '(16))
8802 (org-refile-goto-last-stored)
8803 (when (setq it (org-refile-get-location
8804 (if goto "Goto: " "Refile to: ") default-buffer
8805 org-refile-allow-creating-parent-nodes))
8806 (setq file (nth 1 it)
8807 re (nth 2 it)
8808 pos (nth 3 it))
8809 (if (and (not goto)
8811 (equal (buffer-file-name) file)
8812 (if regionp
8813 (and (>= pos region-start)
8814 (<= pos region-end))
8815 (and (>= pos (point))
8816 (< pos (save-excursion
8817 (org-end-of-subtree t t))))))
8818 (error "Cannot refile to position inside the tree or region"))
8820 (setq nbuf (or (find-buffer-visiting file)
8821 (find-file-noselect file)))
8822 (if goto
8823 (progn
8824 (switch-to-buffer nbuf)
8825 (goto-char pos)
8826 (org-show-context 'org-goto))
8827 (if regionp
8828 (progn
8829 (kill-new (buffer-substring region-start region-end))
8830 (org-save-markers-in-region region-start region-end))
8831 (org-copy-subtree 1 nil t))
8832 (save-excursion
8833 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8834 (find-file-noselect file))))
8835 (setq reversed (org-notes-order-reversed-p))
8836 (save-excursion
8837 (save-restriction
8838 (widen)
8839 (if pos
8840 (progn
8841 (goto-char pos)
8842 (looking-at outline-regexp)
8843 (setq level (org-get-valid-level (funcall outline-level) 1))
8844 (goto-char
8845 (if reversed
8846 (or (outline-next-heading) (point-max))
8847 (or (save-excursion (outline-get-next-sibling))
8848 (org-end-of-subtree t t)
8849 (point-max)))))
8850 (setq level 1)
8851 (if (not reversed)
8852 (goto-char (point-max))
8853 (goto-char (point-min))
8854 (or (outline-next-heading) (goto-char (point-max)))))
8855 (if (not (bolp)) (newline))
8856 (bookmark-set "org-refile-last-stored")
8857 (org-paste-subtree level)
8858 (run-hooks 'org-after-refile-insert-hook))))
8859 (if regionp
8860 (delete-region (point) (+ (point) region-length))
8861 (org-cut-subtree))
8862 (setq org-markers-to-move nil)
8863 (message "Refiled to \"%s\"" (car it))))))
8864 (org-reveal))
8866 (defun org-refile-goto-last-stored ()
8867 "Go to the location where the last refile was stored."
8868 (interactive)
8869 (bookmark-jump "org-refile-last-stored")
8870 (message "This is the location of the last refile"))
8872 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
8873 "Prompt the user for a refile location, using PROMPT."
8874 (let ((org-refile-targets org-refile-targets)
8875 (org-refile-use-outline-path org-refile-use-outline-path))
8876 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8877 (unless org-refile-target-table
8878 (error "No refile targets"))
8879 (let* ((cbuf (current-buffer))
8880 (partial-completion-mode nil)
8881 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8882 (cfunc (if (and org-refile-use-outline-path
8883 org-outline-path-complete-in-steps)
8884 'org-olpath-completing-read
8885 'org-ido-completing-read))
8886 (extra (if org-refile-use-outline-path "/" ""))
8887 (filename (and cfn (expand-file-name cfn)))
8888 (tbl (mapcar
8889 (lambda (x)
8890 (if (and (not (member org-refile-use-outline-path
8891 '(file full-file-path)))
8892 (not (equal filename (nth 1 x))))
8893 (cons (concat (car x) extra " ("
8894 (file-name-nondirectory (nth 1 x)) ")")
8895 (cdr x))
8896 (cons (concat (car x) extra) (cdr x))))
8897 org-refile-target-table))
8898 (completion-ignore-case t)
8899 pa answ parent-target child parent)
8900 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
8901 nil 'org-refile-history))
8902 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
8903 (if pa
8905 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
8906 (setq parent (match-string 1 answ)
8907 child (match-string 2 answ))
8908 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
8909 (when (and parent-target
8910 (or (eq new-nodes t)
8911 (and (eq new-nodes 'confirm)
8912 (y-or-n-p (format "Create new node \"%s\"? " child)))))
8913 (org-refile-new-child parent-target child))))))
8915 (defun org-refile-new-child (parent-target child)
8916 "Use refile target PARENT-TARGET to add new CHILD below it."
8917 (unless parent-target
8918 (error "Cannot find parent for new node"))
8919 (let ((file (nth 1 parent-target))
8920 (pos (nth 3 parent-target))
8921 level)
8922 (with-current-buffer (or (find-buffer-visiting file)
8923 (find-file-noselect file))
8924 (save-excursion
8925 (save-restriction
8926 (widen)
8927 (if pos
8928 (goto-char pos)
8929 (goto-char (point-max))
8930 (if (not (bolp)) (newline)))
8931 (when (looking-at outline-regexp)
8932 (setq level (funcall outline-level))
8933 (org-end-of-subtree t t))
8934 (org-back-over-empty-lines)
8935 (insert "\n" (make-string
8936 (if pos (org-get-valid-level level 1) 1) ?*)
8937 " " child "\n")
8938 (beginning-of-line 0)
8939 (list (concat (car parent-target) "/" child) file "" (point)))))))
8941 (defun org-olpath-completing-read (prompt collection &rest args)
8942 "Read an outline path like a file name."
8943 (let ((thetable collection)
8944 (org-completion-use-ido nil)) ; does not work with ido.
8945 (apply
8946 'org-ido-completing-read prompt
8947 (lambda (string predicate &optional flag)
8948 (let (rtn r f (l (length string)))
8949 (cond
8950 ((eq flag nil)
8951 ;; try completion
8952 (try-completion string thetable))
8953 ((eq flag t)
8954 ;; all-completions
8955 (setq rtn (all-completions string thetable predicate))
8956 (mapcar
8957 (lambda (x)
8958 (setq r (substring x l))
8959 (if (string-match " ([^)]*)$" x)
8960 (setq f (match-string 0 x))
8961 (setq f ""))
8962 (if (string-match "/" r)
8963 (concat string (substring r 0 (match-end 0)) f)
8965 rtn))
8966 ((eq flag 'lambda)
8967 ;; exact match?
8968 (assoc string thetable)))
8970 args)))
8972 ;;;; Dynamic blocks
8974 (defun org-find-dblock (name)
8975 "Find the first dynamic block with name NAME in the buffer.
8976 If not found, stay at current position and return nil."
8977 (let (pos)
8978 (save-excursion
8979 (goto-char (point-min))
8980 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8981 nil t)
8982 (match-beginning 0))))
8983 (if pos (goto-char pos))
8984 pos))
8986 (defconst org-dblock-start-re
8987 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8988 "Matches the startline of a dynamic block, with parameters.")
8990 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8991 "Matches the end of a dynamic block.")
8993 (defun org-create-dblock (plist)
8994 "Create a dynamic block section, with parameters taken from PLIST.
8995 PLIST must contain a :name entry which is used as name of the block."
8996 (unless (bolp) (newline))
8997 (let ((name (plist-get plist :name)))
8998 (insert "#+BEGIN: " name)
8999 (while plist
9000 (if (eq (car plist) :name)
9001 (setq plist (cddr plist))
9002 (insert " " (prin1-to-string (pop plist)))))
9003 (insert "\n\n#+END:\n")
9004 (beginning-of-line -2)))
9006 (defun org-prepare-dblock ()
9007 "Prepare dynamic block for refresh.
9008 This empties the block, puts the cursor at the insert position and returns
9009 the property list including an extra property :name with the block name."
9010 (unless (looking-at org-dblock-start-re)
9011 (error "Not at a dynamic block"))
9012 (let* ((begdel (1+ (match-end 0)))
9013 (name (org-no-properties (match-string 1)))
9014 (params (append (list :name name)
9015 (read (concat "(" (match-string 3) ")")))))
9016 (unless (re-search-forward org-dblock-end-re nil t)
9017 (error "Dynamic block not terminated"))
9018 (setq params
9019 (append params
9020 (list :content (buffer-substring
9021 begdel (match-beginning 0)))))
9022 (delete-region begdel (match-beginning 0))
9023 (goto-char begdel)
9024 (open-line 1)
9025 params))
9027 (defun org-map-dblocks (&optional command)
9028 "Apply COMMAND to all dynamic blocks in the current buffer.
9029 If COMMAND is not given, use `org-update-dblock'."
9030 (let ((cmd (or command 'org-update-dblock))
9031 pos)
9032 (save-excursion
9033 (goto-char (point-min))
9034 (while (re-search-forward org-dblock-start-re nil t)
9035 (goto-char (setq pos (match-beginning 0)))
9036 (condition-case nil
9037 (funcall cmd)
9038 (error (message "Error during update of dynamic block")))
9039 (goto-char pos)
9040 (unless (re-search-forward org-dblock-end-re nil t)
9041 (error "Dynamic block not terminated"))))))
9043 (defun org-dblock-update (&optional arg)
9044 "User command for updating dynamic blocks.
9045 Update the dynamic block at point. With prefix ARG, update all dynamic
9046 blocks in the buffer."
9047 (interactive "P")
9048 (if arg
9049 (org-update-all-dblocks)
9050 (or (looking-at org-dblock-start-re)
9051 (org-beginning-of-dblock))
9052 (org-update-dblock)))
9054 (defun org-update-dblock ()
9055 "Update the dynamic block at point
9056 This means to empty the block, parse for parameters and then call
9057 the correct writing function."
9058 (save-window-excursion
9059 (let* ((pos (point))
9060 (line (org-current-line))
9061 (params (org-prepare-dblock))
9062 (name (plist-get params :name))
9063 (cmd (intern (concat "org-dblock-write:" name))))
9064 (message "Updating dynamic block `%s' at line %d..." name line)
9065 (funcall cmd params)
9066 (message "Updating dynamic block `%s' at line %d...done" name line)
9067 (goto-char pos))))
9069 (defun org-beginning-of-dblock ()
9070 "Find the beginning of the dynamic block at point.
9071 Error if there is no such block at point."
9072 (let ((pos (point))
9073 beg)
9074 (end-of-line 1)
9075 (if (and (re-search-backward org-dblock-start-re nil t)
9076 (setq beg (match-beginning 0))
9077 (re-search-forward org-dblock-end-re nil t)
9078 (> (match-end 0) pos))
9079 (goto-char beg)
9080 (goto-char pos)
9081 (error "Not in a dynamic block"))))
9083 (defun org-update-all-dblocks ()
9084 "Update all dynamic blocks in the buffer.
9085 This function can be used in a hook."
9086 (when (org-mode-p)
9087 (org-map-dblocks 'org-update-dblock)))
9090 ;;;; Completion
9092 (defconst org-additional-option-like-keywords
9093 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
9094 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
9095 "LATEX_HEADER:"
9096 "BEGIN_EXAMPLE" "END_EXAMPLE"
9097 "BEGIN_QUOTE" "END_QUOTE"
9098 "BEGIN_VERSE" "END_VERSE"
9099 "BEGIN_CENTER" "END_CENTER"
9100 "BEGIN_SRC" "END_SRC"
9101 "CATEGORY" "COLUMNS"
9102 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
9104 (defcustom org-structure-template-alist
9106 ("s" "#+begin_src ?\n\n#+end_src"
9107 "<src lang=\"?\">\n\n</src>")
9108 ("e" "#+begin_example\n?\n#+end_example"
9109 "<example>\n?\n</example>")
9110 ("q" "#+begin_quote\n?\n#+end_quote"
9111 "<quote>\n?\n</quote>")
9112 ("v" "#+begin_verse\n?\n#+end_verse"
9113 "<verse>\n?\n/verse>")
9114 ("c" "#+begin_center\n?\n#+end_center"
9115 "<center>\n?\n/center>")
9116 ("l" "#+begin_latex\n?\n#+end_latex"
9117 "<literal style=\"latex\">\n?\n</literal>")
9118 ("L" "#+latex: "
9119 "<literal style=\"latex\">?</literal>")
9120 ("h" "#+begin_html\n?\n#+end_html"
9121 "<literal style=\"html\">\n?\n</literal>")
9122 ("H" "#+html: "
9123 "<literal style=\"html\">?</literal>")
9124 ("a" "#+begin_ascii\n?\n#+end_ascii")
9125 ("A" "#+ascii: ")
9126 ("i" "#+include %file ?"
9127 "<include file=%file markup=\"?\">")
9129 "Structure completion elements.
9130 This is a list of abbreviation keys and values. The value gets inserted
9131 it you type @samp{.} followed by the key and then the completion key,
9132 usually `M-TAB'. %file will be replaced by a file name after prompting
9133 for the file using completion.
9134 There are two templates for each key, the first uses the original Org syntax,
9135 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
9136 the default when the /org-mtags.el/ module has been loaded. See also the
9137 variable `org-mtags-prefer-muse-templates'.
9138 This is an experimental feature, it is undecided if it is going to stay in."
9139 :group 'org-completion
9140 :type '(repeat
9141 (string :tag "Key")
9142 (string :tag "Template")
9143 (string :tag "Muse Template")))
9145 (defun org-try-structure-completion ()
9146 "Try to complete a structure template before point.
9147 This looks for strings like \"<e\" on an otherwise empty line and
9148 expands them."
9149 (let ((l (buffer-substring (point-at-bol) (point)))
9151 (when (and (looking-at "[ \t]*$")
9152 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9153 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9154 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9155 (match-beginning 1)) a)
9156 t)))
9158 (defun org-complete-expand-structure-template (start cell)
9159 "Expand a structure template."
9160 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
9161 (rpl (nth (if musep 2 1) cell))
9162 (ind ""))
9163 (delete-region start (point))
9164 (when (string-match "\\`#\\+" rpl)
9165 (cond
9166 ((bolp))
9167 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
9168 (setq ind (buffer-substring (point-at-bol) (point))))
9169 (t (newline))))
9170 (setq start (point))
9171 (if (string-match "%file" rpl)
9172 (setq rpl (replace-match
9173 (concat
9174 "\""
9175 (save-match-data
9176 (abbreviate-file-name (read-file-name "Include file: ")))
9177 "\"")
9178 t t rpl)))
9179 (setq rpl (mapconcat 'identity (split-string rpl "\n")
9180 (concat "\n" ind)))
9181 (insert rpl)
9182 (if (re-search-backward "\\?" start t) (delete-char 1))))
9185 (defun org-complete (&optional arg)
9186 "Perform completion on word at point.
9187 At the beginning of a headline, this completes TODO keywords as given in
9188 `org-todo-keywords'.
9189 If the current word is preceded by a backslash, completes the TeX symbols
9190 that are supported for HTML support.
9191 If the current word is preceded by \"#+\", completes special words for
9192 setting file options.
9193 In the line after \"#+STARTUP:, complete valid keywords.\"
9194 At all other locations, this simply calls the value of
9195 `org-completion-fallback-command'."
9196 (interactive "P")
9197 (org-without-partial-completion
9198 (catch 'exit
9199 (let* ((a nil)
9200 (end (point))
9201 (beg1 (save-excursion
9202 (skip-chars-backward (org-re "[:alnum:]_@"))
9203 (point)))
9204 (beg (save-excursion
9205 (skip-chars-backward "a-zA-Z0-9_:$")
9206 (point)))
9207 (confirm (lambda (x) (stringp (car x))))
9208 (searchhead (equal (char-before beg) ?*))
9209 (struct
9210 (when (and (member (char-before beg1) '(?. ?<))
9211 (setq a (assoc (buffer-substring beg1 (point))
9212 org-structure-template-alist)))
9213 (org-complete-expand-structure-template (1- beg1) a)
9214 (throw 'exit t)))
9215 (tag (and (equal (char-before beg1) ?:)
9216 (equal (char-after (point-at-bol)) ?*)))
9217 (prop (and (equal (char-before beg1) ?:)
9218 (not (equal (char-after (point-at-bol)) ?*))))
9219 (texp (equal (char-before beg) ?\\))
9220 (link (equal (char-before beg) ?\[))
9221 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9222 beg)
9223 "#+"))
9224 (startup (string-match "^#\\+STARTUP:.*"
9225 (buffer-substring (point-at-bol) (point))))
9226 (completion-ignore-case opt)
9227 (type nil)
9228 (tbl nil)
9229 (table (cond
9230 (opt
9231 (setq type :opt)
9232 (require 'org-exp)
9233 (append
9234 (mapcar
9235 (lambda (x)
9236 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9237 (cons (match-string 2 x) (match-string 1 x)))
9238 (org-split-string (org-get-current-options) "\n"))
9239 (mapcar 'list org-additional-option-like-keywords)))
9240 (startup
9241 (setq type :startup)
9242 org-startup-options)
9243 (link (append org-link-abbrev-alist-local
9244 org-link-abbrev-alist))
9245 (texp
9246 (setq type :tex)
9247 org-html-entities)
9248 ((string-match "\\`\\*+[ \t]+\\'"
9249 (buffer-substring (point-at-bol) beg))
9250 (setq type :todo)
9251 (mapcar 'list org-todo-keywords-1))
9252 (searchhead
9253 (setq type :searchhead)
9254 (save-excursion
9255 (goto-char (point-min))
9256 (while (re-search-forward org-todo-line-regexp nil t)
9257 (push (list
9258 (org-make-org-heading-search-string
9259 (match-string 3) t))
9260 tbl)))
9261 tbl)
9262 (tag (setq type :tag beg beg1)
9263 (or org-tag-alist (org-get-buffer-tags)))
9264 (prop (setq type :prop beg beg1)
9265 (mapcar 'list (org-buffer-property-keys nil t t)))
9266 (t (progn
9267 (call-interactively org-completion-fallback-command)
9268 (throw 'exit nil)))))
9269 (pattern (buffer-substring-no-properties beg end))
9270 (completion (try-completion pattern table confirm)))
9271 (cond ((eq completion t)
9272 (if (not (assoc (upcase pattern) table))
9273 (message "Already complete")
9274 (if (and (equal type :opt)
9275 (not (member (car (assoc (upcase pattern) table))
9276 org-additional-option-like-keywords)))
9277 (insert (substring (cdr (assoc (upcase pattern) table))
9278 (length pattern)))
9279 (if (memq type '(:tag :prop)) (insert ":")))))
9280 ((null completion)
9281 (message "Can't find completion for \"%s\"" pattern)
9282 (ding))
9283 ((not (string= pattern completion))
9284 (delete-region beg end)
9285 (if (string-match " +$" completion)
9286 (setq completion (replace-match "" t t completion)))
9287 (insert completion)
9288 (if (get-buffer-window "*Completions*")
9289 (delete-window (get-buffer-window "*Completions*")))
9290 (if (assoc completion table)
9291 (if (eq type :todo) (insert " ")
9292 (if (memq type '(:tag :prop)) (insert ":"))))
9293 (if (and (equal type :opt) (assoc completion table))
9294 (message "%s" (substitute-command-keys
9295 "Press \\[org-complete] again to insert example settings"))))
9297 (message "Making completion list...")
9298 (let ((list (sort (all-completions pattern table confirm)
9299 'string<)))
9300 (with-output-to-temp-buffer "*Completions*"
9301 (condition-case nil
9302 ;; Protection needed for XEmacs and emacs 21
9303 (display-completion-list list pattern)
9304 (error (display-completion-list list)))))
9305 (message "Making completion list...%s" "done")))))))
9307 ;;;; TODO, DEADLINE, Comments
9309 (defun org-toggle-comment ()
9310 "Change the COMMENT state of an entry."
9311 (interactive)
9312 (save-excursion
9313 (org-back-to-heading)
9314 (let (case-fold-search)
9315 (if (looking-at (concat outline-regexp
9316 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9317 (replace-match "" t t nil 1)
9318 (if (looking-at outline-regexp)
9319 (progn
9320 (goto-char (match-end 0))
9321 (insert org-comment-string " ")))))))
9323 (defvar org-last-todo-state-is-todo nil
9324 "This is non-nil when the last TODO state change led to a TODO state.
9325 If the last change removed the TODO tag or switched to DONE, then
9326 this is nil.")
9328 (defvar org-setting-tags nil) ; dynamically skipped
9330 (defun org-parse-local-options (string var)
9331 "Parse STRING for startup setting relevant for variable VAR."
9332 (let ((rtn (symbol-value var))
9333 e opts)
9334 (save-match-data
9335 (if (or (not string) (not (string-match "\\S-" string)))
9337 (setq opts (delq nil (mapcar (lambda (x)
9338 (setq e (assoc x org-startup-options))
9339 (if (eq (nth 1 e) var) e nil))
9340 (org-split-string string "[ \t]+"))))
9341 (if (not opts)
9343 (setq rtn nil)
9344 (while (setq e (pop opts))
9345 (if (not (nth 3 e))
9346 (setq rtn (nth 2 e))
9347 (if (not (listp rtn)) (setq rtn nil))
9348 (push (nth 2 e) rtn)))
9349 rtn)))))
9351 (defvar org-todo-setup-filter-hook nil
9352 "Hook for functions that pre-filter todo specs.
9354 Each function takes a todo spec and returns either `nil' or the spec
9355 transformed into canonical form." )
9357 (defvar org-todo-get-default-hook nil
9358 "Hook for functions that get a default item for todo.
9360 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9361 `nil' or a string to be used for the todo mark." )
9363 (defvar org-agenda-headline-snapshot-before-repeat)
9365 (defun org-todo (&optional arg)
9366 "Change the TODO state of an item.
9367 The state of an item is given by a keyword at the start of the heading,
9368 like
9369 *** TODO Write paper
9370 *** DONE Call mom
9372 The different keywords are specified in the variable `org-todo-keywords'.
9373 By default the available states are \"TODO\" and \"DONE\".
9374 So for this example: when the item starts with TODO, it is changed to DONE.
9375 When it starts with DONE, the DONE is removed. And when neither TODO nor
9376 DONE are present, add TODO at the beginning of the heading.
9378 With C-u prefix arg, use completion to determine the new state.
9379 With numeric prefix arg, switch to that state.
9380 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9381 With a tripple C-u prefix, circumvent any state blocking.
9383 For calling through lisp, arg is also interpreted in the following way:
9384 'none -> empty state
9385 \"\"(empty string) -> switch to empty state
9386 'done -> switch to DONE
9387 'nextset -> switch to the next set of keywords
9388 'previousset -> switch to the previous set of keywords
9389 \"WAITING\" -> switch to the specified keyword, but only if it
9390 really is a member of `org-todo-keywords'."
9391 (interactive "P")
9392 (if (equal arg '(16)) (setq arg 'nextset))
9393 (let ((org-blocker-hook org-blocker-hook)
9394 (case-fold-search nil))
9395 (when (equal arg '(64))
9396 (setq arg nil org-blocker-hook nil))
9397 (when (and org-blocker-hook
9398 (org-entry-get nil "NOBLOCKING"))
9399 (setq org-blocker-hook nil))
9400 (save-excursion
9401 (catch 'exit
9402 (org-back-to-heading)
9403 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9404 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9405 (looking-at " *"))
9406 (let* ((match-data (match-data))
9407 (startpos (point-at-bol))
9408 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9409 (org-log-done org-log-done)
9410 (org-log-repeat org-log-repeat)
9411 (org-todo-log-states org-todo-log-states)
9412 (this (match-string 1))
9413 (hl-pos (match-beginning 0))
9414 (head (org-get-todo-sequence-head this))
9415 (ass (assoc head org-todo-kwd-alist))
9416 (interpret (nth 1 ass))
9417 (done-word (nth 3 ass))
9418 (final-done-word (nth 4 ass))
9419 (last-state (or this ""))
9420 (completion-ignore-case t)
9421 (member (member this org-todo-keywords-1))
9422 (tail (cdr member))
9423 (state (cond
9424 ((and org-todo-key-trigger
9425 (or (and (equal arg '(4))
9426 (eq org-use-fast-todo-selection 'prefix))
9427 (and (not arg) org-use-fast-todo-selection
9428 (not (eq org-use-fast-todo-selection
9429 'prefix)))))
9430 ;; Use fast selection
9431 (org-fast-todo-selection))
9432 ((and (equal arg '(4))
9433 (or (not org-use-fast-todo-selection)
9434 (not org-todo-key-trigger)))
9435 ;; Read a state with completion
9436 (org-ido-completing-read
9437 "State: " (mapcar (lambda(x) (list x))
9438 org-todo-keywords-1)
9439 nil t))
9440 ((eq arg 'right)
9441 (if this
9442 (if tail (car tail) nil)
9443 (car org-todo-keywords-1)))
9444 ((eq arg 'left)
9445 (if (equal member org-todo-keywords-1)
9447 (if this
9448 (nth (- (length org-todo-keywords-1)
9449 (length tail) 2)
9450 org-todo-keywords-1)
9451 (org-last org-todo-keywords-1))))
9452 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9453 (setq arg nil))) ; hack to fall back to cycling
9454 (arg
9455 ;; user or caller requests a specific state
9456 (cond
9457 ((equal arg "") nil)
9458 ((eq arg 'none) nil)
9459 ((eq arg 'done) (or done-word (car org-done-keywords)))
9460 ((eq arg 'nextset)
9461 (or (car (cdr (member head org-todo-heads)))
9462 (car org-todo-heads)))
9463 ((eq arg 'previousset)
9464 (let ((org-todo-heads (reverse org-todo-heads)))
9465 (or (car (cdr (member head org-todo-heads)))
9466 (car org-todo-heads))))
9467 ((car (member arg org-todo-keywords-1)))
9468 ((nth (1- (prefix-numeric-value arg))
9469 org-todo-keywords-1))))
9470 ((null member) (or head (car org-todo-keywords-1)))
9471 ((equal this final-done-word) nil) ;; -> make empty
9472 ((null tail) nil) ;; -> first entry
9473 ((memq interpret '(type priority))
9474 (if (eq this-command last-command)
9475 (car tail)
9476 (if (> (length tail) 0)
9477 (or done-word (car org-done-keywords))
9478 nil)))
9480 (car tail))))
9481 (state (or
9482 (run-hook-with-args-until-success
9483 'org-todo-get-default-hook state last-state)
9484 state))
9485 (next (if state (concat " " state " ") " "))
9486 (change-plist (list :type 'todo-state-change :from this :to state
9487 :position startpos))
9488 dolog now-done-p)
9489 (when org-blocker-hook
9490 (setq org-last-todo-state-is-todo
9491 (not (member this org-done-keywords)))
9492 (unless (save-excursion
9493 (save-match-data
9494 (run-hook-with-args-until-failure
9495 'org-blocker-hook change-plist)))
9496 (if (interactive-p)
9497 (error "TODO state change from %s to %s blocked" this state)
9498 ;; fail silently
9499 (message "TODO state change from %s to %s blocked" this state)
9500 (throw 'exit nil))))
9501 (store-match-data match-data)
9502 (replace-match next t t)
9503 (unless (pos-visible-in-window-p hl-pos)
9504 (message "TODO state changed to %s" (org-trim next)))
9505 (unless head
9506 (setq head (org-get-todo-sequence-head state)
9507 ass (assoc head org-todo-kwd-alist)
9508 interpret (nth 1 ass)
9509 done-word (nth 3 ass)
9510 final-done-word (nth 4 ass)))
9511 (when (memq arg '(nextset previousset))
9512 (message "Keyword-Set %d/%d: %s"
9513 (- (length org-todo-sets) -1
9514 (length (memq (assoc state org-todo-sets) org-todo-sets)))
9515 (length org-todo-sets)
9516 (mapconcat 'identity (assoc state org-todo-sets) " ")))
9517 (setq org-last-todo-state-is-todo
9518 (not (member state org-done-keywords)))
9519 (setq now-done-p (and (member state org-done-keywords)
9520 (not (member this org-done-keywords))))
9521 (and logging (org-local-logging logging))
9522 (when (and (or org-todo-log-states org-log-done)
9523 (not org-inhibit-logging)
9524 (not (memq arg '(nextset previousset))))
9525 ;; we need to look at recording a time and note
9526 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
9527 (nth 2 (assoc this org-todo-log-states))))
9528 (when (and state
9529 (member state org-not-done-keywords)
9530 (not (member this org-not-done-keywords)))
9531 ;; This is now a todo state and was not one before
9532 ;; If there was a CLOSED time stamp, get rid of it.
9533 (org-add-planning-info nil nil 'closed))
9534 (when (and now-done-p org-log-done)
9535 ;; It is now done, and it was not done before
9536 (org-add-planning-info 'closed (org-current-time))
9537 (if (and (not dolog) (eq 'note org-log-done))
9538 (org-add-log-setup 'done state this 'findpos 'note)))
9539 (when (and state dolog)
9540 ;; This is a non-nil state, and we need to log it
9541 (org-add-log-setup 'state state this 'findpos dolog)))
9542 ;; Fixup tag positioning
9543 (org-todo-trigger-tag-changes state)
9544 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
9545 (when org-provide-todo-statistics
9546 (org-update-parent-todo-statistics))
9547 (run-hooks 'org-after-todo-state-change-hook)
9548 (if (and arg (not (member state org-done-keywords)))
9549 (setq head (org-get-todo-sequence-head state)))
9550 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9551 ;; Do we need to trigger a repeat?
9552 (when now-done-p
9553 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
9554 ;; This is for the agenda, take a snapshot of the headline.
9555 (save-match-data
9556 (setq org-agenda-headline-snapshot-before-repeat
9557 (org-get-heading))))
9558 (org-auto-repeat-maybe state))
9559 ;; Fixup cursor location if close to the keyword
9560 (if (and (outline-on-heading-p)
9561 (not (bolp))
9562 (save-excursion (beginning-of-line 1)
9563 (looking-at org-todo-line-regexp))
9564 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9565 (progn
9566 (goto-char (or (match-end 2) (match-end 1)))
9567 (and (looking-at " ") (just-one-space))))
9568 (when org-trigger-hook
9569 (save-excursion
9570 (run-hook-with-args 'org-trigger-hook change-plist))))))))
9572 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
9573 "Block turning an entry into a TODO, using the hierarchy.
9574 This checks whether the current task should be blocked from state
9575 changes. Such blocking occurs when:
9577 1. The task has children which are not all in a completed state.
9579 2. A task has a parent with the property :ORDERED:, and there
9580 are siblings prior to the current task with incomplete
9581 status.
9583 3. The parent of the task is blocked because it has siblings that should
9584 be done first, or is child of a block grandparent TODO entry."
9586 (catch 'dont-block
9587 ;; If this is not a todo state change, or if this entry is already DONE,
9588 ;; do not block
9589 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9590 (member (plist-get change-plist :from)
9591 (cons 'done org-done-keywords))
9592 (member (plist-get change-plist :to)
9593 (cons 'todo org-not-done-keywords)))
9594 (throw 'dont-block t))
9595 ;; If this task has children, and any are undone, it's blocked
9596 (save-excursion
9597 (org-back-to-heading t)
9598 (let ((this-level (funcall outline-level)))
9599 (outline-next-heading)
9600 (let ((child-level (funcall outline-level)))
9601 (while (and (not (eobp))
9602 (> child-level this-level))
9603 ;; this todo has children, check whether they are all
9604 ;; completed
9605 (if (and (not (org-entry-is-done-p))
9606 (org-entry-is-todo-p))
9607 (throw 'dont-block nil))
9608 (outline-next-heading)
9609 (setq child-level (funcall outline-level))))))
9610 ;; Otherwise, if the task's parent has the :ORDERED: property, and
9611 ;; any previous siblings are undone, it's blocked
9612 (save-excursion
9613 (org-back-to-heading t)
9614 (let* ((pos (point))
9615 (parent-pos (and (org-up-heading-safe) (point))))
9616 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9617 (when (and (org-entry-get (point) "ORDERED")
9618 (forward-line 1)
9619 (re-search-forward org-not-done-heading-regexp pos t))
9620 (throw 'dont-block nil)) ; block, there is an older sibling not done.
9621 ;; Search further up the hierarchy, to see if an anchestor is blocked
9622 (while t
9623 (goto-char parent-pos)
9624 (if (not (looking-at org-not-done-heading-regexp))
9625 (throw 'dont-block t)) ; do not block, parent is not a TODO
9626 (setq pos (point))
9627 (setq parent-pos (and (org-up-heading-safe) (point)))
9628 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9629 (when (and (org-entry-get (point) "ORDERED")
9630 (forward-line 1)
9631 (re-search-forward org-not-done-heading-regexp pos t))
9632 (throw 'dont-block nil))))))) ; block, older sibling not done.
9634 (defcustom org-track-ordered-property-with-tag nil
9635 "Should the ORDERED property also be shown as a tag?
9636 The ORDERED property decides if an entry should require subtasks to be
9637 completed in sequence. Since a property is not very visible, setting
9638 this option means that toggling the ORDERED property with the command
9639 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
9640 not relevant for the behavior, but it makes things more visible.
9642 Note that toggling the tag with tags commands will not change the property
9643 and therefore not influence behavior!
9645 This can be t, meaning the tag ORDERED should be used, It can also be a
9646 string to select a different tag for this task."
9647 :group 'org-todo
9648 :type '(choice
9649 (const :tag "No tracking" nil)
9650 (const :tag "Track with ORDERED tag" t)
9651 (string :tag "Use other tag")))
9653 (defun org-toggle-ordered-property ()
9654 "Toggle the ORDERED property of the current entry.
9655 For better visibility, you can track the value of this property with a tag.
9656 See variable `org-track-ordered-property-with-tag'."
9657 (interactive)
9658 (let* ((t1 org-track-ordered-property-with-tag)
9659 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
9660 (save-excursion
9661 (org-back-to-heading)
9662 (if (org-entry-get nil "ORDERED")
9663 (progn
9664 (org-delete-property "ORDERED")
9665 (and tag (org-toggle-tag tag 'off))
9666 (message "Subtasks can be completed in arbitrary order"))
9667 (org-entry-put nil "ORDERED" "t")
9668 (and tag (org-toggle-tag tag 'on))
9669 (message "Subtasks must be completed in sequence")))))
9671 (defvar org-blocked-by-checkboxes) ; dynamically scoped
9672 (defun org-block-todo-from-checkboxes (change-plist)
9673 "Block turning an entry into a TODO, using checkboxes.
9674 This checks whether the current task should be blocked from state
9675 changes because there are uncheckd boxes in this entry."
9676 (catch 'dont-block
9677 ;; If this is not a todo state change, or if this entry is already DONE,
9678 ;; do not block
9679 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9680 (member (plist-get change-plist :from)
9681 (cons 'done org-done-keywords))
9682 (member (plist-get change-plist :to)
9683 (cons 'todo org-not-done-keywords)))
9684 (throw 'dont-block t))
9685 ;; If this task has checkboxes that are not checked, it's blocked
9686 (save-excursion
9687 (org-back-to-heading t)
9688 (let ((beg (point)) end)
9689 (outline-next-heading)
9690 (setq end (point))
9691 (goto-char beg)
9692 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
9693 end t)
9694 (progn
9695 (if (boundp 'org-blocked-by-checkboxes)
9696 (setq org-blocked-by-checkboxes t))
9697 (throw 'dont-block nil)))))
9698 t)) ; do not block
9700 (defvar org-entry-property-inherited-from) ;; defined below
9701 (defun org-update-parent-todo-statistics ()
9702 "Update any statistics cookie in the parent of the current headline.
9703 When `org-hierarchical-todo-statistics' is nil, statistics will cover
9704 the entire subtree and this will travel up the hierarchy and update
9705 statistics everywhere."
9706 (interactive)
9707 (let* ((lim 0) prop
9708 (recursive (or (not org-hierarchical-todo-statistics)
9709 (string-match
9710 "\\<recursive\\>"
9711 (or (setq prop (org-entry-get
9712 nil "COOKIE_DATA" 'inherit)) ""))))
9713 (lim (or (and prop (marker-position
9714 org-entry-property-inherited-from))
9715 lim))
9716 (first t)
9717 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
9718 level ltoggle l1
9719 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
9720 (catch 'exit
9721 (save-excursion
9722 (beginning-of-line 1)
9723 (if (org-at-heading-p)
9724 (setq ltoggle (funcall outline-level))
9725 (error "This should not happen"))
9726 (while (and (setq level (org-up-heading-safe))
9727 (or recursive first)
9728 (>= (point) lim))
9729 (setq first nil)
9730 (unless (and level
9731 (not (string-match
9732 "\\<checkbox\\>"
9733 (downcase
9734 (or (org-entry-get
9735 nil "COOKIE_DATA")
9736 "")))))
9737 (throw 'exit nil))
9738 (while (re-search-forward box-re (point-at-eol) t)
9739 (setq cnt-all 0 cnt-done 0 cookie-present t)
9740 (setq is-percent (match-end 2))
9741 (save-match-data
9742 (unless (outline-next-heading) (throw 'exit nil))
9743 (while (and (looking-at org-complex-heading-regexp)
9744 (> (setq l1 (length (match-string 1))) level))
9745 (setq kwd (and (or recursive (= l1 ltoggle))
9746 (match-string 2)))
9747 (and kwd (setq cnt-all (1+ cnt-all)))
9748 (and (member kwd org-done-keywords)
9749 (setq cnt-done (1+ cnt-done)))
9750 (outline-next-heading)))
9751 (replace-match
9752 (if is-percent
9753 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
9754 (format "[%d/%d]" cnt-done cnt-all)))))
9755 (when cookie-present
9756 (run-hook-with-args 'org-after-todo-statistics-hook
9757 cnt-done (- cnt-all cnt-done)))))
9758 (run-hooks 'org-todo-statistics-hook)))
9760 (defvar org-after-todo-statistics-hook nil
9761 "Hook that is called after a TODO statistics cookie has been updated.
9762 Each function is called with two arguments: the number of not-done entries
9763 and the number of done entries.
9765 For example, the following function, when added to this hook, will switch
9766 an entry to DONE when all children are done, and back to TODO when new
9767 entries are set to a TODO status. Note that this hook is only called
9768 when there is a statistics cookie in the headline!
9770 (defun org-summary-todo (n-done n-not-done)
9771 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
9772 (let (org-log-done org-log-states) ; turn off logging
9773 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
9776 (defvar org-todo-statistics-hook nil
9777 "Hook that is run whenever Org thinks TODO statistics should be updated.
9778 This hook runs even if there is no statisics cookie present, in which case
9779 `org-after-todo-statistics-hook' would not run.")
9781 (defun org-todo-trigger-tag-changes (state)
9782 "Apply the changes defined in `org-todo-state-tags-triggers'."
9783 (let ((l org-todo-state-tags-triggers)
9784 changes)
9785 (when (or (not state) (equal state ""))
9786 (setq changes (append changes (cdr (assoc "" l)))))
9787 (when (and (stringp state) (> (length state) 0))
9788 (setq changes (append changes (cdr (assoc state l)))))
9789 (when (member state org-not-done-keywords)
9790 (setq changes (append changes (cdr (assoc 'todo l)))))
9791 (when (member state org-done-keywords)
9792 (setq changes (append changes (cdr (assoc 'done l)))))
9793 (dolist (c changes)
9794 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
9796 (defun org-local-logging (value)
9797 "Get logging settings from a property VALUE."
9798 (let* (words w a)
9799 ;; directly set the variables, they are already local.
9800 (setq org-log-done nil
9801 org-log-repeat nil
9802 org-todo-log-states nil)
9803 (setq words (org-split-string value))
9804 (while (setq w (pop words))
9805 (cond
9806 ((setq a (assoc w org-startup-options))
9807 (and (member (nth 1 a) '(org-log-done org-log-repeat))
9808 (set (nth 1 a) (nth 2 a))))
9809 ((setq a (org-extract-log-state-settings w))
9810 (and (member (car a) org-todo-keywords-1)
9811 (push a org-todo-log-states)))))))
9813 (defun org-get-todo-sequence-head (kwd)
9814 "Return the head of the TODO sequence to which KWD belongs.
9815 If KWD is not set, check if there is a text property remembering the
9816 right sequence."
9817 (let (p)
9818 (cond
9819 ((not kwd)
9820 (or (get-text-property (point-at-bol) 'org-todo-head)
9821 (progn
9822 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
9823 nil (point-at-eol)))
9824 (get-text-property p 'org-todo-head))))
9825 ((not (member kwd org-todo-keywords-1))
9826 (car org-todo-keywords-1))
9827 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
9829 (defun org-fast-todo-selection ()
9830 "Fast TODO keyword selection with single keys.
9831 Returns the new TODO keyword, or nil if no state change should occur."
9832 (let* ((fulltable org-todo-key-alist)
9833 (done-keywords org-done-keywords) ;; needed for the faces.
9834 (maxlen (apply 'max (mapcar
9835 (lambda (x)
9836 (if (stringp (car x)) (string-width (car x)) 0))
9837 fulltable)))
9838 (expert nil)
9839 (fwidth (+ maxlen 3 1 3))
9840 (ncol (/ (- (window-width) 4) fwidth))
9841 tg cnt e c tbl
9842 groups ingroup)
9843 (save-excursion
9844 (save-window-excursion
9845 (if expert
9846 (set-buffer (get-buffer-create " *Org todo*"))
9847 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
9848 (erase-buffer)
9849 (org-set-local 'org-done-keywords done-keywords)
9850 (setq tbl fulltable cnt 0)
9851 (while (setq e (pop tbl))
9852 (cond
9853 ((equal e '(:startgroup))
9854 (push '() groups) (setq ingroup t)
9855 (when (not (= cnt 0))
9856 (setq cnt 0)
9857 (insert "\n"))
9858 (insert "{ "))
9859 ((equal e '(:endgroup))
9860 (setq ingroup nil cnt 0)
9861 (insert "}\n"))
9862 ((equal e '(:newline))
9863 (when (not (= cnt 0))
9864 (setq cnt 0)
9865 (insert "\n")
9866 (setq e (car tbl))
9867 (while (equal (car tbl) '(:newline))
9868 (insert "\n")
9869 (setq tbl (cdr tbl)))))
9871 (setq tg (car e) c (cdr e))
9872 (if ingroup (push tg (car groups)))
9873 (setq tg (org-add-props tg nil 'face
9874 (org-get-todo-face tg)))
9875 (if (and (= cnt 0) (not ingroup)) (insert " "))
9876 (insert "[" c "] " tg (make-string
9877 (- fwidth 4 (length tg)) ?\ ))
9878 (when (= (setq cnt (1+ cnt)) ncol)
9879 (insert "\n")
9880 (if ingroup (insert " "))
9881 (setq cnt 0)))))
9882 (insert "\n")
9883 (goto-char (point-min))
9884 (if (not expert) (org-fit-window-to-buffer))
9885 (message "[a-z..]:Set [SPC]:clear")
9886 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9887 (cond
9888 ((or (= c ?\C-g)
9889 (and (= c ?q) (not (rassoc c fulltable))))
9890 (setq quit-flag t))
9891 ((= c ?\ ) nil)
9892 ((setq e (rassoc c fulltable) tg (car e))
9894 (t (setq quit-flag t)))))))
9896 (defun org-entry-is-todo-p ()
9897 (member (org-get-todo-state) org-not-done-keywords))
9899 (defun org-entry-is-done-p ()
9900 (member (org-get-todo-state) org-done-keywords))
9902 (defun org-get-todo-state ()
9903 (save-excursion
9904 (org-back-to-heading t)
9905 (and (looking-at org-todo-line-regexp)
9906 (match-end 2)
9907 (match-string 2))))
9909 (defun org-at-date-range-p (&optional inactive-ok)
9910 "Is the cursor inside a date range?"
9911 (interactive)
9912 (save-excursion
9913 (catch 'exit
9914 (let ((pos (point)))
9915 (skip-chars-backward "^[<\r\n")
9916 (skip-chars-backward "<[")
9917 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9918 (>= (match-end 0) pos)
9919 (throw 'exit t))
9920 (skip-chars-backward "^<[\r\n")
9921 (skip-chars-backward "<[")
9922 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9923 (>= (match-end 0) pos)
9924 (throw 'exit t)))
9925 nil)))
9927 (defun org-get-repeat ()
9928 "Check if there is a deadline/schedule with repeater in this entry."
9929 (save-match-data
9930 (save-excursion
9931 (org-back-to-heading t)
9932 (if (re-search-forward
9933 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9934 (match-string 1)))))
9936 (defvar org-last-changed-timestamp)
9937 (defvar org-last-inserted-timestamp)
9938 (defvar org-log-post-message)
9939 (defvar org-log-note-purpose)
9940 (defvar org-log-note-how)
9941 (defvar org-log-note-extra)
9942 (defun org-auto-repeat-maybe (done-word)
9943 "Check if the current headline contains a repeated deadline/schedule.
9944 If yes, set TODO state back to what it was and change the base date
9945 of repeating deadline/scheduled time stamps to new date.
9946 This function is run automatically after each state change to a DONE state."
9947 ;; last-state is dynamically scoped into this function
9948 (let* ((repeat (org-get-repeat))
9949 (aa (assoc last-state org-todo-kwd-alist))
9950 (interpret (nth 1 aa))
9951 (head (nth 2 aa))
9952 (whata '(("d" . day) ("m" . month) ("y" . year)))
9953 (msg "Entry repeats: ")
9954 (org-log-done nil)
9955 (org-todo-log-states nil)
9956 (nshiftmax 10) (nshift 0)
9957 re type n what ts time)
9958 (when repeat
9959 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9960 (org-todo (if (eq interpret 'type) last-state head))
9961 (org-entry-put nil "LAST_REPEAT" (format-time-string
9962 (org-time-stamp-format t t)))
9963 (when org-log-repeat
9964 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9965 (memq 'org-add-log-note post-command-hook))
9966 ;; OK, we are already setup for some record
9967 (if (eq org-log-repeat 'note)
9968 ;; make sure we take a note, not only a time stamp
9969 (setq org-log-note-how 'note))
9970 ;; Set up for taking a record
9971 (org-add-log-setup 'state (or done-word (car org-done-keywords))
9972 last-state
9973 'findpos org-log-repeat)))
9974 (org-back-to-heading t)
9975 (org-add-planning-info nil nil 'closed)
9976 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9977 org-deadline-time-regexp "\\)\\|\\("
9978 org-ts-regexp "\\)"))
9979 (while (re-search-forward
9980 re (save-excursion (outline-next-heading) (point)) t)
9981 (setq type (if (match-end 1) org-scheduled-string
9982 (if (match-end 3) org-deadline-string "Plain:"))
9983 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
9984 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
9985 (setq n (string-to-number (match-string 2 ts))
9986 what (match-string 3 ts))
9987 (if (equal what "w") (setq n (* n 7) what "d"))
9988 ;; Preparation, see if we need to modify the start date for the change
9989 (when (match-end 1)
9990 (setq time (save-match-data (org-time-string-to-time ts)))
9991 (cond
9992 ((equal (match-string 1 ts) ".")
9993 ;; Shift starting date to today
9994 (org-timestamp-change
9995 (- (time-to-days (current-time)) (time-to-days time))
9996 'day))
9997 ((equal (match-string 1 ts) "+")
9998 (while (or (= nshift 0)
9999 (<= (time-to-days time) (time-to-days (current-time))))
10000 (when (= (incf nshift) nshiftmax)
10001 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
10002 (error "Abort")))
10003 (org-timestamp-change n (cdr (assoc what whata)))
10004 (org-at-timestamp-p t)
10005 (setq ts (match-string 1))
10006 (setq time (save-match-data (org-time-string-to-time ts))))
10007 (org-timestamp-change (- n) (cdr (assoc what whata)))
10008 ;; rematch, so that we have everything in place for the real shift
10009 (org-at-timestamp-p t)
10010 (setq ts (match-string 1))
10011 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
10012 (org-timestamp-change n (cdr (assoc what whata)))
10013 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
10014 (setq org-log-post-message msg)
10015 (message "%s" msg))))
10017 (defun org-show-todo-tree (arg)
10018 "Make a compact tree which shows all headlines marked with TODO.
10019 The tree will show the lines where the regexp matches, and all higher
10020 headlines above the match.
10021 With a \\[universal-argument] prefix, prompt for a regexp to match.
10022 With a numeric prefix N, construct a sparse tree for the Nth element
10023 of `org-todo-keywords-1'."
10024 (interactive "P")
10025 (let ((case-fold-search nil)
10026 (kwd-re
10027 (cond ((null arg) org-not-done-regexp)
10028 ((equal arg '(4))
10029 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
10030 (mapcar 'list org-todo-keywords-1))))
10031 (concat "\\("
10032 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10033 "\\)\\>")))
10034 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10035 (regexp-quote (nth (1- (prefix-numeric-value arg))
10036 org-todo-keywords-1)))
10037 (t (error "Invalid prefix argument: %s" arg)))))
10038 (message "%d TODO entries found"
10039 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
10041 (defun org-deadline (&optional remove time)
10042 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
10043 With argument REMOVE, remove any deadline from the item.
10044 When TIME is set, it should be an internal time specification, and the
10045 scheduling will use the corresponding date."
10046 (interactive "P")
10047 (if remove
10048 (progn
10049 (org-remove-timestamp-with-keyword org-deadline-string)
10050 (message "Item no longer has a deadline."))
10051 (if (org-get-repeat)
10052 (error "Cannot change deadline on task with repeater, please do that by hand")
10053 (org-add-planning-info 'deadline time 'closed)
10054 (message "Deadline on %s" org-last-inserted-timestamp))))
10056 (defun org-schedule (&optional remove time)
10057 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
10058 With argument REMOVE, remove any scheduling date from the item.
10059 When TIME is set, it should be an internal time specification, and the
10060 scheduling will use the corresponding date."
10061 (interactive "P")
10062 (if remove
10063 (progn
10064 (org-remove-timestamp-with-keyword org-scheduled-string)
10065 (message "Item is no longer scheduled."))
10066 (if (org-get-repeat)
10067 (error "Cannot reschedule task with repeater, please do that by hand")
10068 (org-add-planning-info 'scheduled time 'closed)
10069 (message "Scheduled to %s" org-last-inserted-timestamp))))
10071 (defun org-get-scheduled-time (pom &optional inherit)
10072 "Get the scheduled time as a time tuple, of a format suitable
10073 for calling org-schedule with, or if there is no scheduling,
10074 returns nil."
10075 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
10076 (when time
10077 (apply 'encode-time (org-parse-time-string time)))))
10079 (defun org-get-deadline-time (pom &optional inherit)
10080 "Get the deadine as a time tuple, of a format suitable for
10081 calling org-deadlin with, or if there is no scheduling, returns
10082 nil."
10083 (let ((time (org-entry-get pom "DEADLINE" inherit)))
10084 (when time
10085 (apply 'encode-time (org-parse-time-string time)))))
10087 (defun org-remove-timestamp-with-keyword (keyword)
10088 "Remove all time stamps with KEYWORD in the current entry."
10089 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
10090 beg)
10091 (save-excursion
10092 (org-back-to-heading t)
10093 (setq beg (point))
10094 (org-end-of-subtree t t)
10095 (while (re-search-backward re beg t)
10096 (replace-match "")
10097 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
10098 (equal (char-before) ?\ ))
10099 (backward-delete-char 1)
10100 (if (string-match "^[ \t]*$" (buffer-substring
10101 (point-at-bol) (point-at-eol)))
10102 (delete-region (point-at-bol)
10103 (min (point-max) (1+ (point-at-eol))))))))))
10105 (defun org-add-planning-info (what &optional time &rest remove)
10106 "Insert new timestamp with keyword in the line directly after the headline.
10107 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
10108 If non is given, the user is prompted for a date.
10109 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
10110 be removed."
10111 (interactive)
10112 (let (org-time-was-given org-end-time-was-given ts
10113 end default-time default-input)
10115 (catch 'exit
10116 (when (and (not time) (memq what '(scheduled deadline)))
10117 ;; Try to get a default date/time from existing timestamp
10118 (save-excursion
10119 (org-back-to-heading t)
10120 (setq end (save-excursion (outline-next-heading) (point)))
10121 (when (re-search-forward (if (eq what 'scheduled)
10122 org-scheduled-time-regexp
10123 org-deadline-time-regexp)
10124 end t)
10125 (setq ts (match-string 1)
10126 default-time
10127 (apply 'encode-time (org-parse-time-string ts))
10128 default-input (and ts (org-get-compact-tod ts))))))
10129 (when what
10130 ;; If necessary, get the time from the user
10131 (setq time (or time (org-read-date nil 'to-time nil nil
10132 default-time default-input))))
10134 (when (and org-insert-labeled-timestamps-at-point
10135 (member what '(scheduled deadline)))
10136 (insert
10137 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
10138 (org-insert-time-stamp time org-time-was-given
10139 nil nil nil (list org-end-time-was-given))
10140 (setq what nil))
10141 (save-excursion
10142 (save-restriction
10143 (let (col list elt ts buffer-invisibility-spec)
10144 (org-back-to-heading t)
10145 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
10146 (goto-char (match-end 1))
10147 (setq col (current-column))
10148 (goto-char (match-end 0))
10149 (if (eobp) (insert "\n") (forward-char 1))
10150 (when (and (not what)
10151 (not (looking-at
10152 (concat "[ \t]*"
10153 org-keyword-time-not-clock-regexp))))
10154 ;; Nothing to add, nothing to remove...... :-)
10155 (throw 'exit nil))
10156 (if (and (not (looking-at outline-regexp))
10157 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
10158 "[^\r\n]*"))
10159 (not (equal (match-string 1) org-clock-string)))
10160 (narrow-to-region (match-beginning 0) (match-end 0))
10161 (insert-before-markers "\n")
10162 (backward-char 1)
10163 (narrow-to-region (point) (point))
10164 (and org-adapt-indentation (org-indent-to-column col)))
10165 ;; Check if we have to remove something.
10166 (setq list (cons what remove))
10167 (while list
10168 (setq elt (pop list))
10169 (goto-char (point-min))
10170 (when (or (and (eq elt 'scheduled)
10171 (re-search-forward org-scheduled-time-regexp nil t))
10172 (and (eq elt 'deadline)
10173 (re-search-forward org-deadline-time-regexp nil t))
10174 (and (eq elt 'closed)
10175 (re-search-forward org-closed-time-regexp nil t)))
10176 (replace-match "")
10177 (if (looking-at "--+<[^>]+>") (replace-match ""))
10178 (if (looking-at " +") (replace-match ""))))
10179 (goto-char (point-max))
10180 (when what
10181 (insert
10182 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
10183 (cond ((eq what 'scheduled) org-scheduled-string)
10184 ((eq what 'deadline) org-deadline-string)
10185 ((eq what 'closed) org-closed-string))
10186 " ")
10187 (setq ts (org-insert-time-stamp
10188 time
10189 (or org-time-was-given
10190 (and (eq what 'closed) org-log-done-with-time))
10191 (eq what 'closed)
10192 nil nil (list org-end-time-was-given)))
10193 (end-of-line 1))
10194 (goto-char (point-min))
10195 (widen)
10196 (if (and (looking-at "[ \t]+\n")
10197 (equal (char-before) ?\n))
10198 (delete-region (1- (point)) (point-at-eol)))
10199 ts))))))
10201 (defvar org-log-note-marker (make-marker))
10202 (defvar org-log-note-purpose nil)
10203 (defvar org-log-note-state nil)
10204 (defvar org-log-note-previous-state nil)
10205 (defvar org-log-note-how nil)
10206 (defvar org-log-note-extra nil)
10207 (defvar org-log-note-window-configuration nil)
10208 (defvar org-log-note-return-to (make-marker))
10209 (defvar org-log-post-message nil
10210 "Message to be displayed after a log note has been stored.
10211 The auto-repeater uses this.")
10213 (defun org-add-note ()
10214 "Add a note to the current entry.
10215 This is done in the same way as adding a state change note."
10216 (interactive)
10217 (org-add-log-setup 'note nil nil 'findpos nil))
10219 (defvar org-property-end-re)
10220 (defun org-add-log-setup (&optional purpose state prev-state
10221 findpos how &optional extra)
10222 "Set up the post command hook to take a note.
10223 If this is about to TODO state change, the new state is expected in STATE.
10224 When FINDPOS is non-nil, find the correct position for the note in
10225 the current entry. If not, assume that it can be inserted at point.
10226 HOW is an indicator what kind of note should be created.
10227 EXTRA is additional text that will be inserted into the notes buffer."
10228 (let* ((org-log-into-drawer (org-log-into-drawer))
10229 (drawer (cond ((stringp org-log-into-drawer)
10230 org-log-into-drawer)
10231 (org-log-into-drawer "LOGBOOK")
10232 (t nil))))
10233 (save-restriction
10234 (save-excursion
10235 (when findpos
10236 (org-back-to-heading t)
10237 (narrow-to-region (point) (save-excursion
10238 (outline-next-heading) (point)))
10239 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
10240 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
10241 "[^\r\n]*\\)?"))
10242 (goto-char (match-end 0))
10243 (cond
10244 (drawer
10245 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
10246 nil t)
10247 (progn
10248 (goto-char (match-end 0))
10249 (or org-log-states-order-reversed
10250 (and (re-search-forward org-property-end-re nil t)
10251 (goto-char (1- (match-beginning 0))))))
10252 (insert "\n:" drawer ":\n:END:")
10253 (beginning-of-line 0)
10254 (org-indent-line-function)
10255 (beginning-of-line 2)
10256 (org-indent-line-function)
10257 (end-of-line 0)))
10258 ((and org-log-state-notes-insert-after-drawers
10259 (save-excursion
10260 (forward-line) (looking-at org-drawer-regexp)))
10261 (forward-line)
10262 (while (looking-at org-drawer-regexp)
10263 (goto-char (match-end 0))
10264 (re-search-forward org-property-end-re (point-max) t)
10265 (forward-line))
10266 (forward-line -1)))
10267 (unless org-log-states-order-reversed
10268 (and (= (char-after) ?\n) (forward-char 1))
10269 (org-skip-over-state-notes)
10270 (skip-chars-backward " \t\n\r")))
10271 (move-marker org-log-note-marker (point))
10272 (setq org-log-note-purpose purpose
10273 org-log-note-state state
10274 org-log-note-previous-state prev-state
10275 org-log-note-how how
10276 org-log-note-extra extra)
10277 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
10279 (defun org-skip-over-state-notes ()
10280 "Skip past the list of State notes in an entry."
10281 (if (looking-at "\n[ \t]*- State") (forward-char 1))
10282 (while (looking-at "[ \t]*- State")
10283 (condition-case nil
10284 (org-next-item)
10285 (error (org-end-of-item)))))
10287 (defun org-add-log-note (&optional purpose)
10288 "Pop up a window for taking a note, and add this note later at point."
10289 (remove-hook 'post-command-hook 'org-add-log-note)
10290 (setq org-log-note-window-configuration (current-window-configuration))
10291 (delete-other-windows)
10292 (move-marker org-log-note-return-to (point))
10293 (switch-to-buffer (marker-buffer org-log-note-marker))
10294 (goto-char org-log-note-marker)
10295 (org-switch-to-buffer-other-window "*Org Note*")
10296 (erase-buffer)
10297 (if (memq org-log-note-how '(time state))
10298 (let (current-prefix-arg) (org-store-log-note))
10299 (let ((org-inhibit-startup t)) (org-mode))
10300 (insert (format "# Insert note for %s.
10301 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10302 (cond
10303 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10304 ((eq org-log-note-purpose 'done) "closed todo item")
10305 ((eq org-log-note-purpose 'state)
10306 (format "state change from \"%s\" to \"%s\""
10307 (or org-log-note-previous-state "")
10308 (or org-log-note-state "")))
10309 ((eq org-log-note-purpose 'note)
10310 "this entry")
10311 (t (error "This should not happen")))))
10312 (if org-log-note-extra (insert org-log-note-extra))
10313 (org-set-local 'org-finish-function 'org-store-log-note)))
10315 (defvar org-note-abort nil) ; dynamically scoped
10316 (defun org-store-log-note ()
10317 "Finish taking a log note, and insert it to where it belongs."
10318 (let ((txt (buffer-string))
10319 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10320 lines ind)
10321 (kill-buffer (current-buffer))
10322 (while (string-match "\\`#.*\n[ \t\n]*" txt)
10323 (setq txt (replace-match "" t t txt)))
10324 (if (string-match "\\s-+\\'" txt)
10325 (setq txt (replace-match "" t t txt)))
10326 (setq lines (org-split-string txt "\n"))
10327 (when (and note (string-match "\\S-" note))
10328 (setq note
10329 (org-replace-escapes
10330 note
10331 (list (cons "%u" (user-login-name))
10332 (cons "%U" user-full-name)
10333 (cons "%t" (format-time-string
10334 (org-time-stamp-format 'long 'inactive)
10335 (current-time)))
10336 (cons "%s" (if org-log-note-state
10337 (concat "\"" org-log-note-state "\"")
10338 ""))
10339 (cons "%S" (if org-log-note-previous-state
10340 (concat "\"" org-log-note-previous-state "\"")
10341 "\"\"")))))
10342 (if lines (setq note (concat note " \\\\")))
10343 (push note lines))
10344 (when (or current-prefix-arg org-note-abort)
10345 (when org-log-into-drawer
10346 (org-remove-empty-drawer-at
10347 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
10348 org-log-note-marker))
10349 (setq lines nil))
10350 (when lines
10351 (save-excursion
10352 (set-buffer (marker-buffer org-log-note-marker))
10353 (save-excursion
10354 (goto-char org-log-note-marker)
10355 (move-marker org-log-note-marker nil)
10356 (end-of-line 1)
10357 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
10358 (insert "- " (pop lines))
10359 (org-indent-line-function)
10360 (beginning-of-line 1)
10361 (looking-at "[ \t]*")
10362 (setq ind (concat (match-string 0) " "))
10363 (end-of-line 1)
10364 (while lines (insert "\n" ind (pop lines)))
10365 (message "Note stored")
10366 (org-back-to-heading t)
10367 (org-cycle-hide-drawers 'children)))))
10368 (set-window-configuration org-log-note-window-configuration)
10369 (with-current-buffer (marker-buffer org-log-note-return-to)
10370 (goto-char org-log-note-return-to))
10371 (move-marker org-log-note-return-to nil)
10372 (and org-log-post-message (message "%s" org-log-post-message)))
10374 (defun org-remove-empty-drawer-at (drawer pos)
10375 "Remove an emptyr DARWER drawer at position POS.
10376 POS may also be a marker."
10377 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
10378 (save-excursion
10379 (save-restriction
10380 (widen)
10381 (goto-char pos)
10382 (if (org-in-regexp
10383 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
10384 (replace-match ""))))))
10386 (defun org-sparse-tree (&optional arg)
10387 "Create a sparse tree, prompt for the details.
10388 This command can create sparse trees. You first need to select the type
10389 of match used to create the tree:
10391 t Show entries with a specific TODO keyword.
10392 m Show entries selected by a tags/property match.
10393 p Enter a property name and its value (both with completion on existing
10394 names/values) and show entries with that property.
10395 r Show entries matching a regular expression.
10396 d Show deadlines due within `org-deadline-warning-days'.
10397 b Show deadlines and scheduled items before a date.
10398 a Show deadlines and scheduled items after a date."
10399 (interactive "P")
10400 (let (ans kwd value)
10401 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
10402 (setq ans (read-char-exclusive))
10403 (cond
10404 ((equal ans ?d)
10405 (call-interactively 'org-check-deadlines))
10406 ((equal ans ?b)
10407 (call-interactively 'org-check-before-date))
10408 ((equal ans ?a)
10409 (call-interactively 'org-check-after-date))
10410 ((equal ans ?t)
10411 (org-show-todo-tree '(4)))
10412 ((member ans '(?T ?m))
10413 (call-interactively 'org-match-sparse-tree))
10414 ((member ans '(?p ?P))
10415 (setq kwd (org-ido-completing-read "Property: "
10416 (mapcar 'list (org-buffer-property-keys))))
10417 (setq value (org-ido-completing-read "Value: "
10418 (mapcar 'list (org-property-values kwd))))
10419 (unless (string-match "\\`{.*}\\'" value)
10420 (setq value (concat "\"" value "\"")))
10421 (org-match-sparse-tree arg (concat kwd "=" value)))
10422 ((member ans '(?r ?R ?/))
10423 (call-interactively 'org-occur))
10424 (t (error "No such sparse tree command \"%c\"" ans)))))
10426 (defvar org-occur-highlights nil
10427 "List of overlays used for occur matches.")
10428 (make-variable-buffer-local 'org-occur-highlights)
10429 (defvar org-occur-parameters nil
10430 "Parameters of the active org-occur calls.
10431 This is a list, each call to org-occur pushes as cons cell,
10432 containing the regular expression and the callback, onto the list.
10433 The list can contain several entries if `org-occur' has been called
10434 several time with the KEEP-PREVIOUS argument. Otherwise, this list
10435 will only contain one set of parameters. When the highlights are
10436 removed (for example with `C-c C-c', or with the next edit (depending
10437 on `org-remove-highlights-with-change'), this variable is emptied
10438 as well.")
10439 (make-variable-buffer-local 'org-occur-parameters)
10441 (defun org-occur (regexp &optional keep-previous callback)
10442 "Make a compact tree which shows all matches of REGEXP.
10443 The tree will show the lines where the regexp matches, and all higher
10444 headlines above the match. It will also show the heading after the match,
10445 to make sure editing the matching entry is easy.
10446 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
10447 call to `org-occur' will be kept, to allow stacking of calls to this
10448 command.
10449 If CALLBACK is non-nil, it is a function which is called to confirm
10450 that the match should indeed be shown."
10451 (interactive "sRegexp: \nP")
10452 (unless keep-previous
10453 (org-remove-occur-highlights nil nil t))
10454 (push (cons regexp callback) org-occur-parameters)
10455 (let ((cnt 0))
10456 (save-excursion
10457 (goto-char (point-min))
10458 (if (or (not keep-previous) ; do not want to keep
10459 (not org-occur-highlights)) ; no previous matches
10460 ;; hide everything
10461 (org-overview))
10462 (while (re-search-forward regexp nil t)
10463 (when (or (not callback)
10464 (save-match-data (funcall callback)))
10465 (setq cnt (1+ cnt))
10466 (when org-highlight-sparse-tree-matches
10467 (org-highlight-new-match (match-beginning 0) (match-end 0)))
10468 (org-show-context 'occur-tree))))
10469 (when org-remove-highlights-with-change
10470 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10471 nil 'local))
10472 (unless org-sparse-tree-open-archived-trees
10473 (org-hide-archived-subtrees (point-min) (point-max)))
10474 (run-hooks 'org-occur-hook)
10475 (if (interactive-p)
10476 (message "%d match(es) for regexp %s" cnt regexp))
10477 cnt))
10479 (defun org-show-context (&optional key)
10480 "Make sure point and context and visible.
10481 How much context is shown depends upon the variables
10482 `org-show-hierarchy-above', `org-show-following-heading'. and
10483 `org-show-siblings'."
10484 (let ((heading-p (org-on-heading-p t))
10485 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
10486 (following-p (org-get-alist-option org-show-following-heading key))
10487 (entry-p (org-get-alist-option org-show-entry-below key))
10488 (siblings-p (org-get-alist-option org-show-siblings key)))
10489 (catch 'exit
10490 ;; Show heading or entry text
10491 (if (and heading-p (not entry-p))
10492 (org-flag-heading nil) ; only show the heading
10493 (and (or entry-p (org-invisible-p) (org-invisible-p2))
10494 (org-show-hidden-entry))) ; show entire entry
10495 (when following-p
10496 ;; Show next sibling, or heading below text
10497 (save-excursion
10498 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10499 (org-flag-heading nil))))
10500 (when siblings-p (org-show-siblings))
10501 (when hierarchy-p
10502 ;; show all higher headings, possibly with siblings
10503 (save-excursion
10504 (while (and (condition-case nil
10505 (progn (org-up-heading-all 1) t)
10506 (error nil))
10507 (not (bobp)))
10508 (org-flag-heading nil)
10509 (when siblings-p (org-show-siblings))))))))
10511 (defun org-reveal (&optional siblings)
10512 "Show current entry, hierarchy above it, and the following headline.
10513 This can be used to show a consistent set of context around locations
10514 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10515 not t for the search context.
10517 With optional argument SIBLINGS, on each level of the hierarchy all
10518 siblings are shown. This repairs the tree structure to what it would
10519 look like when opened with hierarchical calls to `org-cycle'."
10520 (interactive "P")
10521 (let ((org-show-hierarchy-above t)
10522 (org-show-following-heading t)
10523 (org-show-siblings (if siblings t org-show-siblings)))
10524 (org-show-context nil)))
10526 (defun org-highlight-new-match (beg end)
10527 "Highlight from BEG to END and mark the highlight is an occur headline."
10528 (let ((ov (org-make-overlay beg end)))
10529 (org-overlay-put ov 'face 'secondary-selection)
10530 (push ov org-occur-highlights)))
10532 (defun org-remove-occur-highlights (&optional beg end noremove)
10533 "Remove the occur highlights from the buffer.
10534 BEG and END are ignored. If NOREMOVE is nil, remove this function
10535 from the `before-change-functions' in the current buffer."
10536 (interactive)
10537 (unless org-inhibit-highlight-removal
10538 (mapc 'org-delete-overlay org-occur-highlights)
10539 (setq org-occur-highlights nil)
10540 (setq org-occur-parameters nil)
10541 (unless noremove
10542 (remove-hook 'before-change-functions
10543 'org-remove-occur-highlights 'local))))
10545 ;;;; Priorities
10547 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
10548 "Regular expression matching the priority indicator.")
10550 (defvar org-remove-priority-next-time nil)
10552 (defun org-priority-up ()
10553 "Increase the priority of the current item."
10554 (interactive)
10555 (org-priority 'up))
10557 (defun org-priority-down ()
10558 "Decrease the priority of the current item."
10559 (interactive)
10560 (org-priority 'down))
10562 (defun org-priority (&optional action)
10563 "Change the priority of an item by ARG.
10564 ACTION can be `set', `up', `down', or a character."
10565 (interactive)
10566 (unless org-enable-priority-commands
10567 (error "Priority commands are disabled"))
10568 (setq action (or action 'set))
10569 (let (current new news have remove)
10570 (save-excursion
10571 (org-back-to-heading t)
10572 (if (looking-at org-priority-regexp)
10573 (setq current (string-to-char (match-string 2))
10574 have t)
10575 (setq current org-default-priority))
10576 (cond
10577 ((or (eq action 'set)
10578 (if (featurep 'xemacs) (characterp action) (integerp action)))
10579 (if (not (eq action 'set))
10580 (setq new action)
10581 (message "Priority %c-%c, SPC to remove: "
10582 org-highest-priority org-lowest-priority)
10583 (setq new (read-char-exclusive)))
10584 (if (and (= (upcase org-highest-priority) org-highest-priority)
10585 (= (upcase org-lowest-priority) org-lowest-priority))
10586 (setq new (upcase new)))
10587 (cond ((equal new ?\ ) (setq remove t))
10588 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
10589 (error "Priority must be between `%c' and `%c'"
10590 org-highest-priority org-lowest-priority))))
10591 ((eq action 'up)
10592 (if (and (not have) (eq last-command this-command))
10593 (setq new org-lowest-priority)
10594 (setq new (if (and org-priority-start-cycle-with-default (not have))
10595 org-default-priority (1- current)))))
10596 ((eq action 'down)
10597 (if (and (not have) (eq last-command this-command))
10598 (setq new org-highest-priority)
10599 (setq new (if (and org-priority-start-cycle-with-default (not have))
10600 org-default-priority (1+ current)))))
10601 (t (error "Invalid action")))
10602 (if (or (< (upcase new) org-highest-priority)
10603 (> (upcase new) org-lowest-priority))
10604 (setq remove t))
10605 (setq news (format "%c" new))
10606 (if have
10607 (if remove
10608 (replace-match "" t t nil 1)
10609 (replace-match news t t nil 2))
10610 (if remove
10611 (error "No priority cookie found in line")
10612 (let ((case-fold-search nil))
10613 (looking-at org-todo-line-regexp))
10614 (if (match-end 2)
10615 (progn
10616 (goto-char (match-end 2))
10617 (insert " [#" news "]"))
10618 (goto-char (match-beginning 3))
10619 (insert "[#" news "] ")))))
10620 (org-preserve-lc (org-set-tags nil 'align))
10621 (if remove
10622 (message "Priority removed")
10623 (message "Priority of current item set to %s" news))))
10626 (defun org-get-priority (s)
10627 "Find priority cookie and return priority."
10628 (save-match-data
10629 (if (not (string-match org-priority-regexp s))
10630 (* 1000 (- org-lowest-priority org-default-priority))
10631 (* 1000 (- org-lowest-priority
10632 (string-to-char (match-string 2 s)))))))
10634 ;;;; Tags
10636 (defvar org-agenda-archives-mode)
10637 (defvar org-map-continue-from nil
10638 "Position from where mapping should continue.
10639 Can be set byt the action argument to `org-scan-tag's and `org-map-entries'.")
10641 (defvar org-scanner-tags nil
10642 "The current tag list while the tags scanner is running.")
10643 (defvar org-trust-scanner-tags nil
10644 "Should `org-get-tags-at' use the tags fro the scanner.
10645 This is for internal dynamical scoping only.
10646 When this is non-nil, the function `org-get-tags-at' will return the value
10647 of `org-scanner-tags' instead of building the list by itself. This
10648 can lead to large speed-ups when the tags scanner is used in a file with
10649 many entries, and when the list of tags is retrieved, for example to
10650 obtain a list of properties. Building the tags list for each entry in such
10651 a file becomes an N^2 operation - but with this variable set, it scales
10652 as N.")
10654 (defun org-scan-tags (action matcher &optional todo-only)
10655 "Scan headline tags with inheritance and produce output ACTION.
10657 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
10658 or `agenda' to produce an entry list for an agenda view. It can also be
10659 a Lisp form or a function that should be called at each matched headline, in
10660 this case the return value is a list of all return values from these calls.
10662 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
10663 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
10664 only lines with a TODO keyword are included in the output."
10665 (require 'org-agenda)
10666 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
10667 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
10668 (org-re
10669 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
10670 (props (list 'face 'default
10671 'done-face 'org-agenda-done
10672 'undone-face 'default
10673 'mouse-face 'highlight
10674 'org-not-done-regexp org-not-done-regexp
10675 'org-todo-regexp org-todo-regexp
10676 'keymap org-agenda-keymap
10677 'help-echo
10678 (format "mouse-2 or RET jump to org file %s"
10679 (abbreviate-file-name
10680 (or (buffer-file-name (buffer-base-buffer))
10681 (buffer-name (buffer-base-buffer)))))))
10682 (case-fold-search nil)
10683 (org-map-continue-from nil)
10684 lspos tags tags-list
10685 (tags-alist (list (cons 0 org-file-tags)))
10686 (llast 0) rtn rtn1 level category i txt
10687 todo marker entry priority)
10688 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
10689 (setq action (list 'lambda nil action)))
10690 (save-excursion
10691 (goto-char (point-min))
10692 (when (eq action 'sparse-tree)
10693 (org-overview)
10694 (org-remove-occur-highlights))
10695 (while (re-search-forward re nil t)
10696 (catch :skip
10697 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
10698 tags (if (match-end 4) (org-match-string-no-properties 4)))
10699 (goto-char (setq lspos (match-beginning 0)))
10700 (setq level (org-reduced-level (funcall outline-level))
10701 category (org-get-category))
10702 (setq i llast llast level)
10703 ;; remove tag lists from same and sublevels
10704 (while (>= i level)
10705 (when (setq entry (assoc i tags-alist))
10706 (setq tags-alist (delete entry tags-alist)))
10707 (setq i (1- i)))
10708 ;; add the next tags
10709 (when tags
10710 (setq tags (org-split-string tags ":")
10711 tags-alist
10712 (cons (cons level tags) tags-alist)))
10713 ;; compile tags for current headline
10714 (setq tags-list
10715 (if org-use-tag-inheritance
10716 (apply 'append (mapcar 'cdr (reverse tags-alist)))
10717 tags)
10718 org-scanner-tags tags-list)
10719 (when org-use-tag-inheritance
10720 (setcdr (car tags-alist)
10721 (mapcar (lambda (x)
10722 (setq x (copy-sequence x))
10723 (org-add-prop-inherited x))
10724 (cdar tags-alist))))
10725 (when (and tags org-use-tag-inheritance
10726 (or (not (eq t org-use-tag-inheritance))
10727 org-tags-exclude-from-inheritance))
10728 ;; selective inheritance, remove uninherited ones
10729 (setcdr (car tags-alist)
10730 (org-remove-uniherited-tags (cdar tags-alist))))
10731 (when (and (or (not todo-only)
10732 (and (member todo org-not-done-keywords)
10733 (or (not org-agenda-tags-todo-honor-ignore-options)
10734 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
10735 (let ((case-fold-search t)) (eval matcher))
10737 (not (member org-archive-tag tags-list))
10738 ;; we have an archive tag, should we use this anyway?
10739 (or (not org-agenda-skip-archived-trees)
10740 (and (eq action 'agenda) org-agenda-archives-mode))))
10741 (unless (eq action 'sparse-tree) (org-agenda-skip))
10743 ;; select this headline
10745 (cond
10746 ((eq action 'sparse-tree)
10747 (and org-highlight-sparse-tree-matches
10748 (org-get-heading) (match-end 0)
10749 (org-highlight-new-match
10750 (match-beginning 0) (match-beginning 1)))
10751 (org-show-context 'tags-tree))
10752 ((eq action 'agenda)
10753 (setq txt (org-format-agenda-item
10755 (concat
10756 (if (eq org-tags-match-list-sublevels 'indented)
10757 (make-string (1- level) ?.) "")
10758 (org-get-heading))
10759 category
10760 tags-list
10762 priority (org-get-priority txt))
10763 (goto-char lspos)
10764 (setq marker (org-agenda-new-marker))
10765 (org-add-props txt props
10766 'org-marker marker 'org-hd-marker marker 'org-category category
10767 'todo-state todo
10768 'priority priority 'type "tagsmatch")
10769 (push txt rtn))
10770 ((functionp action)
10771 (setq org-map-continue-from nil)
10772 (save-excursion
10773 (setq rtn1 (funcall action))
10774 (push rtn1 rtn)))
10775 (t (error "Invalid action")))
10777 ;; if we are to skip sublevels, jump to end of subtree
10778 (unless org-tags-match-list-sublevels
10779 (org-end-of-subtree t)
10780 (backward-char 1))))
10781 ;; Get the correct position from where to continue
10782 (if org-map-continue-from
10783 (goto-char org-map-continue-from)
10784 (and (= (point) lspos) (end-of-line 1)))))
10785 (when (and (eq action 'sparse-tree)
10786 (not org-sparse-tree-open-archived-trees))
10787 (org-hide-archived-subtrees (point-min) (point-max)))
10788 (nreverse rtn)))
10790 (defun org-remove-uniherited-tags (tags)
10791 "Remove all tags that are not inherited from the list TAGS."
10792 (cond
10793 ((eq org-use-tag-inheritance t)
10794 (if org-tags-exclude-from-inheritance
10795 (org-delete-all org-tags-exclude-from-inheritance tags)
10796 tags))
10797 ((not org-use-tag-inheritance) nil)
10798 ((stringp org-use-tag-inheritance)
10799 (delq nil (mapcar
10800 (lambda (x)
10801 (if (and (string-match org-use-tag-inheritance x)
10802 (not (member x org-tags-exclude-from-inheritance)))
10803 x nil))
10804 tags)))
10805 ((listp org-use-tag-inheritance)
10806 (delq nil (mapcar
10807 (lambda (x)
10808 (if (member x org-use-tag-inheritance) x nil))
10809 tags)))))
10811 (defvar todo-only) ;; dynamically scoped
10813 (defun org-match-sparse-tree (&optional todo-only match)
10814 "Create a sparse tree according to tags string MATCH.
10815 MATCH can contain positive and negative selection of tags, like
10816 \"+WORK+URGENT-WITHBOSS\".
10817 If optional argument TODO-ONLY is non-nil, only select lines that are
10818 also TODO lines."
10819 (interactive "P")
10820 (org-prepare-agenda-buffers (list (current-buffer)))
10821 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
10823 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
10825 (defvar org-cached-props nil)
10826 (defun org-cached-entry-get (pom property)
10827 (if (or (eq t org-use-property-inheritance)
10828 (and (stringp org-use-property-inheritance)
10829 (string-match org-use-property-inheritance property))
10830 (and (listp org-use-property-inheritance)
10831 (member property org-use-property-inheritance)))
10832 ;; Caching is not possible, check it directly
10833 (org-entry-get pom property 'inherit)
10834 ;; Get all properties, so that we can do complicated checks easily
10835 (cdr (assoc property (or org-cached-props
10836 (setq org-cached-props
10837 (org-entry-properties pom)))))))
10839 (defun org-global-tags-completion-table (&optional files)
10840 "Return the list of all tags in all agenda buffer/files."
10841 (save-excursion
10842 (org-uniquify
10843 (delq nil
10844 (apply 'append
10845 (mapcar
10846 (lambda (file)
10847 (set-buffer (find-file-noselect file))
10848 (append (org-get-buffer-tags)
10849 (mapcar (lambda (x) (if (stringp (car-safe x))
10850 (list (car-safe x)) nil))
10851 org-tag-alist)))
10852 (if (and files (car files))
10853 files
10854 (org-agenda-files))))))))
10856 (defun org-make-tags-matcher (match)
10857 "Create the TAGS//TODO matcher form for the selection string MATCH."
10858 ;; todo-only is scoped dynamically into this function, and the function
10859 ;; may change it if the matcher asks for it.
10860 (unless match
10861 ;; Get a new match request, with completion
10862 (let ((org-last-tags-completion-table
10863 (org-global-tags-completion-table)))
10864 (setq match (org-completing-read-no-ido
10865 "Match: " 'org-tags-completion-function nil nil nil
10866 'org-tags-history))))
10868 ;; Parse the string and create a lisp form
10869 (let ((match0 match)
10870 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
10871 minus tag mm
10872 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
10873 orterms term orlist re-p str-p level-p level-op time-p
10874 prop-p pn pv po cat-p gv rest)
10875 (if (string-match "/+" match)
10876 ;; match contains also a todo-matching request
10877 (progn
10878 (setq tagsmatch (substring match 0 (match-beginning 0))
10879 todomatch (substring match (match-end 0)))
10880 (if (string-match "^!" todomatch)
10881 (setq todo-only t todomatch (substring todomatch 1)))
10882 (if (string-match "^\\s-*$" todomatch)
10883 (setq todomatch nil)))
10884 ;; only matching tags
10885 (setq tagsmatch match todomatch nil))
10887 ;; Make the tags matcher
10888 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10889 (setq tagsmatcher t)
10890 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10891 (while (setq term (pop orterms))
10892 (while (and (equal (substring term -1) "\\") orterms)
10893 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10894 (while (string-match re term)
10895 (setq rest (substring term (match-end 0))
10896 minus (and (match-end 1)
10897 (equal (match-string 1 term) "-"))
10898 tag (match-string 2 term)
10899 re-p (equal (string-to-char tag) ?{)
10900 level-p (match-end 4)
10901 prop-p (match-end 5)
10902 mm (cond
10903 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10904 (level-p
10905 (setq level-op (org-op-to-function (match-string 3 term)))
10906 `(,level-op level ,(string-to-number
10907 (match-string 4 term))))
10908 (prop-p
10909 (setq pn (match-string 5 term)
10910 po (match-string 6 term)
10911 pv (match-string 7 term)
10912 cat-p (equal pn "CATEGORY")
10913 re-p (equal (string-to-char pv) ?{)
10914 str-p (equal (string-to-char pv) ?\")
10915 time-p (save-match-data
10916 (string-match "^\"[[<].*[]>]\"$" pv))
10917 pv (if (or re-p str-p) (substring pv 1 -1) pv))
10918 (if time-p (setq pv (org-matcher-time pv)))
10919 (setq po (org-op-to-function po (if time-p 'time str-p)))
10920 (cond
10921 ((equal pn "CATEGORY")
10922 (setq gv '(get-text-property (point) 'org-category)))
10923 ((equal pn "TODO")
10924 (setq gv 'todo))
10926 (setq gv `(org-cached-entry-get nil ,pn))))
10927 (if re-p
10928 (if (eq po 'org<>)
10929 `(not (string-match ,pv (or ,gv "")))
10930 `(string-match ,pv (or ,gv "")))
10931 (if str-p
10932 `(,po (or ,gv "") ,pv)
10933 `(,po (string-to-number (or ,gv ""))
10934 ,(string-to-number pv) ))))
10935 (t `(member ,tag tags-list)))
10936 mm (if minus (list 'not mm) mm)
10937 term rest)
10938 (push mm tagsmatcher))
10939 (push (if (> (length tagsmatcher) 1)
10940 (cons 'and tagsmatcher)
10941 (car tagsmatcher))
10942 orlist)
10943 (setq tagsmatcher nil))
10944 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
10945 (setq tagsmatcher
10946 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
10947 ;; Make the todo matcher
10948 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10949 (setq todomatcher t)
10950 (setq orterms (org-split-string todomatch "|") orlist nil)
10951 (while (setq term (pop orterms))
10952 (while (string-match re term)
10953 (setq minus (and (match-end 1)
10954 (equal (match-string 1 term) "-"))
10955 kwd (match-string 2 term)
10956 re-p (equal (string-to-char kwd) ?{)
10957 term (substring term (match-end 0))
10958 mm (if re-p
10959 `(string-match ,(substring kwd 1 -1) todo)
10960 (list 'equal 'todo kwd))
10961 mm (if minus (list 'not mm) mm))
10962 (push mm todomatcher))
10963 (push (if (> (length todomatcher) 1)
10964 (cons 'and todomatcher)
10965 (car todomatcher))
10966 orlist)
10967 (setq todomatcher nil))
10968 (setq todomatcher (if (> (length orlist) 1)
10969 (cons 'or orlist) (car orlist))))
10971 ;; Return the string and lisp forms of the matcher
10972 (setq matcher (if todomatcher
10973 (list 'and tagsmatcher todomatcher)
10974 tagsmatcher))
10975 (cons match0 matcher)))
10977 (defun org-op-to-function (op &optional stringp)
10978 "Turn an operator into the appropriate function."
10979 (setq op
10980 (cond
10981 ((equal op "<" ) '(< string< org-time<))
10982 ((equal op ">" ) '(> org-string> org-time>))
10983 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
10984 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
10985 ((member op '("=" "==")) '(= string= org-time=))
10986 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
10987 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
10989 (defun org<> (a b) (not (= a b)))
10990 (defun org-string<= (a b) (or (string= a b) (string< a b)))
10991 (defun org-string>= (a b) (not (string< a b)))
10992 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
10993 (defun org-string<> (a b) (not (string= a b)))
10994 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
10995 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
10996 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
10997 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
10998 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
10999 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
11000 (defun org-2ft (s)
11001 "Convert S to a floating point time.
11002 If S is already a number, just return it. If it is a string, parse
11003 it as a time string and apply `float-time' to it. If S is nil, just return 0."
11004 (cond
11005 ((numberp s) s)
11006 ((stringp s)
11007 (condition-case nil
11008 (float-time (apply 'encode-time (org-parse-time-string s)))
11009 (error 0.)))
11010 (t 0.)))
11012 (defun org-time-today ()
11013 "Time in seconds today at 0:00.
11014 Returns the float number of seconds since the beginning of the
11015 epoch to the beginning of today (00:00)."
11016 (float-time (apply 'encode-time
11017 (append '(0 0 0) (nthcdr 3 (decode-time))))))
11019 (defun org-matcher-time (s)
11020 "Interpret a time comparison value."
11021 (save-match-data
11022 (cond
11023 ((string= s "<now>") (float-time))
11024 ((string= s "<today>") (org-time-today))
11025 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
11026 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
11027 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
11028 (+ (org-time-today)
11029 (* (string-to-number (match-string 1 s))
11030 (cdr (assoc (match-string 2 s)
11031 '(("d" . 86400.0) ("w" . 604800.0)
11032 ("m" . 2678400.0) ("y" . 31557600.0)))))))
11033 (t (org-2ft s)))))
11035 (defun org-match-any-p (re list)
11036 "Does re match any element of list?"
11037 (setq list (mapcar (lambda (x) (string-match re x)) list))
11038 (delq nil list))
11040 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
11041 (defvar org-tags-overlay (org-make-overlay 1 1))
11042 (org-detach-overlay org-tags-overlay)
11044 (defun org-get-local-tags-at (&optional pos)
11045 "Get a list of tags defined in the current headline."
11046 (org-get-tags-at pos 'local))
11048 (defun org-get-local-tags ()
11049 "Get a list of tags defined in the current headline."
11050 (org-get-tags-at nil 'local))
11052 (defun org-get-tags-at (&optional pos local)
11053 "Get a list of all headline tags applicable at POS.
11054 POS defaults to point. If tags are inherited, the list contains
11055 the targets in the same sequence as the headlines appear, i.e.
11056 the tags of the current headline come last.
11057 When LOCAL is non-nil, only return tags from the current headline,
11058 ignore inherited ones."
11059 (interactive)
11060 (if (and org-trust-scanner-tags
11061 (or (not pos) (equal pos (point)))
11062 (not local))
11063 org-scanner-tags
11064 (let (tags ltags lastpos parent)
11065 (save-excursion
11066 (save-restriction
11067 (widen)
11068 (goto-char (or pos (point)))
11069 (save-match-data
11070 (catch 'done
11071 (condition-case nil
11072 (progn
11073 (org-back-to-heading t)
11074 (while (not (equal lastpos (point)))
11075 (setq lastpos (point))
11076 (when (looking-at
11077 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
11078 (setq ltags (org-split-string
11079 (org-match-string-no-properties 1) ":"))
11080 (when parent
11081 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
11082 (setq tags (append
11083 (if parent
11084 (org-remove-uniherited-tags ltags)
11085 ltags)
11086 tags)))
11087 (or org-use-tag-inheritance (throw 'done t))
11088 (if local (throw 'done t))
11089 (or (org-up-heading-safe) (error nil))
11090 (setq parent t)))
11091 (error nil)))))
11092 (append (org-remove-uniherited-tags org-file-tags) tags)))))
11094 (defun org-add-prop-inherited (s)
11095 (add-text-properties 0 (length s) '(inherited t) s)
11098 (defun org-toggle-tag (tag &optional onoff)
11099 "Toggle the tag TAG for the current line.
11100 If ONOFF is `on' or `off', don't toggle but set to this state."
11101 (let (res current)
11102 (save-excursion
11103 (org-back-to-heading t)
11104 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
11105 (point-at-eol) t)
11106 (progn
11107 (setq current (match-string 1))
11108 (replace-match ""))
11109 (setq current ""))
11110 (setq current (nreverse (org-split-string current ":")))
11111 (cond
11112 ((eq onoff 'on)
11113 (setq res t)
11114 (or (member tag current) (push tag current)))
11115 ((eq onoff 'off)
11116 (or (not (member tag current)) (setq current (delete tag current))))
11117 (t (if (member tag current)
11118 (setq current (delete tag current))
11119 (setq res t)
11120 (push tag current))))
11121 (end-of-line 1)
11122 (if current
11123 (progn
11124 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
11125 (org-set-tags nil t))
11126 (delete-horizontal-space))
11127 (run-hooks 'org-after-tags-change-hook))
11128 res))
11130 (defun org-align-tags-here (to-col)
11131 ;; Assumes that this is a headline
11132 (let ((pos (point)) (col (current-column)) ncol tags-l p)
11133 (beginning-of-line 1)
11134 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11135 (< pos (match-beginning 2)))
11136 (progn
11137 (setq tags-l (- (match-end 2) (match-beginning 2)))
11138 (goto-char (match-beginning 1))
11139 (insert " ")
11140 (delete-region (point) (1+ (match-beginning 2)))
11141 (setq ncol (max (1+ (current-column))
11142 (1+ col)
11143 (if (> to-col 0)
11144 to-col
11145 (- (abs to-col) tags-l))))
11146 (setq p (point))
11147 (insert (make-string (- ncol (current-column)) ?\ ))
11148 (setq ncol (current-column))
11149 (when indent-tabs-mode (tabify p (point-at-eol)))
11150 (org-move-to-column (min ncol col) t))
11151 (goto-char pos))))
11153 (defun org-set-tags-command (&optional arg just-align)
11154 "Call the set-tags command for the current entry."
11155 (interactive "P")
11156 (if (org-on-heading-p)
11157 (org-set-tags arg just-align)
11158 (save-excursion
11159 (org-back-to-heading t)
11160 (org-set-tags arg just-align))))
11162 (defun org-set-tags (&optional arg just-align)
11163 "Set the tags for the current headline.
11164 With prefix ARG, realign all tags in headings in the current buffer."
11165 (interactive "P")
11166 (let* ((re (concat "^" outline-regexp))
11167 (current (org-get-tags-string))
11168 (col (current-column))
11169 (org-setting-tags t)
11170 table current-tags inherited-tags ; computed below when needed
11171 tags p0 c0 c1 rpl)
11172 (if arg
11173 (save-excursion
11174 (goto-char (point-min))
11175 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
11176 (while (re-search-forward re nil t)
11177 (org-set-tags nil t)
11178 (end-of-line 1)))
11179 (message "All tags realigned to column %d" org-tags-column))
11180 (if just-align
11181 (setq tags current)
11182 ;; Get a new set of tags from the user
11183 (save-excursion
11184 (setq table (append org-tag-persistent-alist
11185 (or org-tag-alist (org-get-buffer-tags)))
11186 org-last-tags-completion-table table
11187 current-tags (org-split-string current ":")
11188 inherited-tags (nreverse
11189 (nthcdr (length current-tags)
11190 (nreverse (org-get-tags-at))))
11191 tags
11192 (if (or (eq t org-use-fast-tag-selection)
11193 (and org-use-fast-tag-selection
11194 (delq nil (mapcar 'cdr table))))
11195 (org-fast-tag-selection
11196 current-tags inherited-tags table
11197 (if org-fast-tag-selection-include-todo org-todo-key-alist))
11198 (let ((org-add-colon-after-tag-completion t))
11199 (org-trim
11200 (org-without-partial-completion
11201 (org-ido-completing-read "Tags: " 'org-tags-completion-function
11202 nil nil current 'org-tags-history)))))))
11203 (while (string-match "[-+&]+" tags)
11204 ;; No boolean logic, just a list
11205 (setq tags (replace-match ":" t t tags))))
11207 (if (string-match "\\`[\t ]*\\'" tags)
11208 (setq tags "")
11209 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
11210 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
11212 ;; Insert new tags at the correct column
11213 (beginning-of-line 1)
11214 (cond
11215 ((and (equal current "") (equal tags "")))
11216 ((re-search-forward
11217 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
11218 (point-at-eol) t)
11219 (if (equal tags "")
11220 (setq rpl "")
11221 (goto-char (match-beginning 0))
11222 (setq c0 (current-column) p0 (point)
11223 c1 (max (1+ c0) (if (> org-tags-column 0)
11224 org-tags-column
11225 (- (- org-tags-column) (length tags))))
11226 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
11227 (replace-match rpl t t)
11228 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
11229 tags)
11230 (t (error "Tags alignment failed")))
11231 (org-move-to-column col)
11232 (unless just-align
11233 (run-hooks 'org-after-tags-change-hook)))))
11235 (defun org-change-tag-in-region (beg end tag off)
11236 "Add or remove TAG for each entry in the region.
11237 This works in the agenda, and also in an org-mode buffer."
11238 (interactive
11239 (list (region-beginning) (region-end)
11240 (let ((org-last-tags-completion-table
11241 (if (org-mode-p)
11242 (org-get-buffer-tags)
11243 (org-global-tags-completion-table))))
11244 (org-ido-completing-read
11245 "Tag: " 'org-tags-completion-function nil nil nil
11246 'org-tags-history))
11247 (progn
11248 (message "[s]et or [r]emove? ")
11249 (equal (read-char-exclusive) ?r))))
11250 (if (fboundp 'deactivate-mark) (deactivate-mark))
11251 (let ((agendap (equal major-mode 'org-agenda-mode))
11252 l1 l2 m buf pos newhead (cnt 0))
11253 (goto-char end)
11254 (setq l2 (1- (org-current-line)))
11255 (goto-char beg)
11256 (setq l1 (org-current-line))
11257 (loop for l from l1 to l2 do
11258 (goto-line l)
11259 (setq m (get-text-property (point) 'org-hd-marker))
11260 (when (or (and (org-mode-p) (org-on-heading-p))
11261 (and agendap m))
11262 (setq buf (if agendap (marker-buffer m) (current-buffer))
11263 pos (if agendap m (point)))
11264 (with-current-buffer buf
11265 (save-excursion
11266 (save-restriction
11267 (goto-char pos)
11268 (setq cnt (1+ cnt))
11269 (org-toggle-tag tag (if off 'off 'on))
11270 (setq newhead (org-get-heading)))))
11271 (and agendap (org-agenda-change-all-lines newhead m))))
11272 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
11274 (defun org-tags-completion-function (string predicate &optional flag)
11275 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
11276 (confirm (lambda (x) (stringp (car x)))))
11277 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
11278 (setq s1 (match-string 1 string)
11279 s2 (match-string 2 string))
11280 (setq s1 "" s2 string))
11281 (cond
11282 ((eq flag nil)
11283 ;; try completion
11284 (setq rtn (try-completion s2 ctable confirm))
11285 (if (stringp rtn)
11286 (setq rtn
11287 (concat s1 s2 (substring rtn (length s2))
11288 (if (and org-add-colon-after-tag-completion
11289 (assoc rtn ctable))
11290 ":" ""))))
11291 rtn)
11292 ((eq flag t)
11293 ;; all-completions
11294 (all-completions s2 ctable confirm)
11296 ((eq flag 'lambda)
11297 ;; exact match?
11298 (assoc s2 ctable)))
11301 (defun org-fast-tag-insert (kwd tags face &optional end)
11302 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
11303 (insert (format "%-12s" (concat kwd ":"))
11304 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
11305 (or end "")))
11307 (defun org-fast-tag-show-exit (flag)
11308 (save-excursion
11309 (goto-line 3)
11310 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
11311 (replace-match ""))
11312 (when flag
11313 (end-of-line 1)
11314 (org-move-to-column (- (window-width) 19) t)
11315 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
11317 (defun org-set-current-tags-overlay (current prefix)
11318 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
11319 (if (featurep 'xemacs)
11320 (org-overlay-display org-tags-overlay (concat prefix s)
11321 'secondary-selection)
11322 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
11323 (org-overlay-display org-tags-overlay (concat prefix s)))))
11325 (defun org-fast-tag-selection (current inherited table &optional todo-table)
11326 "Fast tag selection with single keys.
11327 CURRENT is the current list of tags in the headline, INHERITED is the
11328 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
11329 possibly with grouping information. TODO-TABLE is a similar table with
11330 TODO keywords, should these have keys assigned to them.
11331 If the keys are nil, a-z are automatically assigned.
11332 Returns the new tags string, or nil to not change the current settings."
11333 (let* ((fulltable (append table todo-table))
11334 (maxlen (apply 'max (mapcar
11335 (lambda (x)
11336 (if (stringp (car x)) (string-width (car x)) 0))
11337 fulltable)))
11338 (buf (current-buffer))
11339 (expert (eq org-fast-tag-selection-single-key 'expert))
11340 (buffer-tags nil)
11341 (fwidth (+ maxlen 3 1 3))
11342 (ncol (/ (- (window-width) 4) fwidth))
11343 (i-face 'org-done)
11344 (c-face 'org-todo)
11345 tg cnt e c char c1 c2 ntable tbl rtn
11346 ov-start ov-end ov-prefix
11347 (exit-after-next org-fast-tag-selection-single-key)
11348 (done-keywords org-done-keywords)
11349 groups ingroup)
11350 (save-excursion
11351 (beginning-of-line 1)
11352 (if (looking-at
11353 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11354 (setq ov-start (match-beginning 1)
11355 ov-end (match-end 1)
11356 ov-prefix "")
11357 (setq ov-start (1- (point-at-eol))
11358 ov-end (1+ ov-start))
11359 (skip-chars-forward "^\n\r")
11360 (setq ov-prefix
11361 (concat
11362 (buffer-substring (1- (point)) (point))
11363 (if (> (current-column) org-tags-column)
11365 (make-string (- org-tags-column (current-column)) ?\ ))))))
11366 (org-move-overlay org-tags-overlay ov-start ov-end)
11367 (save-window-excursion
11368 (if expert
11369 (set-buffer (get-buffer-create " *Org tags*"))
11370 (delete-other-windows)
11371 (split-window-vertically)
11372 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
11373 (erase-buffer)
11374 (org-set-local 'org-done-keywords done-keywords)
11375 (org-fast-tag-insert "Inherited" inherited i-face "\n")
11376 (org-fast-tag-insert "Current" current c-face "\n\n")
11377 (org-fast-tag-show-exit exit-after-next)
11378 (org-set-current-tags-overlay current ov-prefix)
11379 (setq tbl fulltable char ?a cnt 0)
11380 (while (setq e (pop tbl))
11381 (cond
11382 ((equal e '(:startgroup))
11383 (push '() groups) (setq ingroup t)
11384 (when (not (= cnt 0))
11385 (setq cnt 0)
11386 (insert "\n"))
11387 (insert "{ "))
11388 ((equal e '(:endgroup))
11389 (setq ingroup nil cnt 0)
11390 (insert "}\n"))
11391 ((equal e '(:newline))
11392 (when (not (= cnt 0))
11393 (setq cnt 0)
11394 (insert "\n")
11395 (setq e (car tbl))
11396 (while (equal (car tbl) '(:newline))
11397 (insert "\n")
11398 (setq tbl (cdr tbl)))))
11400 (setq tg (car e) c2 nil)
11401 (if (cdr e)
11402 (setq c (cdr e))
11403 ;; automatically assign a character.
11404 (setq c1 (string-to-char
11405 (downcase (substring
11406 tg (if (= (string-to-char tg) ?@) 1 0)))))
11407 (if (or (rassoc c1 ntable) (rassoc c1 table))
11408 (while (or (rassoc char ntable) (rassoc char table))
11409 (setq char (1+ char)))
11410 (setq c2 c1))
11411 (setq c (or c2 char)))
11412 (if ingroup (push tg (car groups)))
11413 (setq tg (org-add-props tg nil 'face
11414 (cond
11415 ((not (assoc tg table))
11416 (org-get-todo-face tg))
11417 ((member tg current) c-face)
11418 ((member tg inherited) i-face)
11419 (t nil))))
11420 (if (and (= cnt 0) (not ingroup)) (insert " "))
11421 (insert "[" c "] " tg (make-string
11422 (- fwidth 4 (length tg)) ?\ ))
11423 (push (cons tg c) ntable)
11424 (when (= (setq cnt (1+ cnt)) ncol)
11425 (insert "\n")
11426 (if ingroup (insert " "))
11427 (setq cnt 0)))))
11428 (setq ntable (nreverse ntable))
11429 (insert "\n")
11430 (goto-char (point-min))
11431 (if (not expert) (org-fit-window-to-buffer))
11432 (setq rtn
11433 (catch 'exit
11434 (while t
11435 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
11436 (if groups " [!] no groups" " [!]groups")
11437 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
11438 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11439 (cond
11440 ((= c ?\r) (throw 'exit t))
11441 ((= c ?!)
11442 (setq groups (not groups))
11443 (goto-char (point-min))
11444 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
11445 ((= c ?\C-c)
11446 (if (not expert)
11447 (org-fast-tag-show-exit
11448 (setq exit-after-next (not exit-after-next)))
11449 (setq expert nil)
11450 (delete-other-windows)
11451 (split-window-vertically)
11452 (org-switch-to-buffer-other-window " *Org tags*")
11453 (org-fit-window-to-buffer)))
11454 ((or (= c ?\C-g)
11455 (and (= c ?q) (not (rassoc c ntable))))
11456 (org-detach-overlay org-tags-overlay)
11457 (setq quit-flag t))
11458 ((= c ?\ )
11459 (setq current nil)
11460 (if exit-after-next (setq exit-after-next 'now)))
11461 ((= c ?\t)
11462 (condition-case nil
11463 (setq tg (org-ido-completing-read
11464 "Tag: "
11465 (or buffer-tags
11466 (with-current-buffer buf
11467 (org-get-buffer-tags)))))
11468 (quit (setq tg "")))
11469 (when (string-match "\\S-" tg)
11470 (add-to-list 'buffer-tags (list tg))
11471 (if (member tg current)
11472 (setq current (delete tg current))
11473 (push tg current)))
11474 (if exit-after-next (setq exit-after-next 'now)))
11475 ((setq e (rassoc c todo-table) tg (car e))
11476 (with-current-buffer buf
11477 (save-excursion (org-todo tg)))
11478 (if exit-after-next (setq exit-after-next 'now)))
11479 ((setq e (rassoc c ntable) tg (car e))
11480 (if (member tg current)
11481 (setq current (delete tg current))
11482 (loop for g in groups do
11483 (if (member tg g)
11484 (mapc (lambda (x)
11485 (setq current (delete x current)))
11486 g)))
11487 (push tg current))
11488 (if exit-after-next (setq exit-after-next 'now))))
11490 ;; Create a sorted list
11491 (setq current
11492 (sort current
11493 (lambda (a b)
11494 (assoc b (cdr (memq (assoc a ntable) ntable))))))
11495 (if (eq exit-after-next 'now) (throw 'exit t))
11496 (goto-char (point-min))
11497 (beginning-of-line 2)
11498 (delete-region (point) (point-at-eol))
11499 (org-fast-tag-insert "Current" current c-face)
11500 (org-set-current-tags-overlay current ov-prefix)
11501 (while (re-search-forward
11502 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
11503 (setq tg (match-string 1))
11504 (add-text-properties
11505 (match-beginning 1) (match-end 1)
11506 (list 'face
11507 (cond
11508 ((member tg current) c-face)
11509 ((member tg inherited) i-face)
11510 (t (get-text-property (match-beginning 1) 'face))))))
11511 (goto-char (point-min)))))
11512 (org-detach-overlay org-tags-overlay)
11513 (if rtn
11514 (mapconcat 'identity current ":")
11515 nil))))
11517 (defun org-get-tags-string ()
11518 "Get the TAGS string in the current headline."
11519 (unless (org-on-heading-p t)
11520 (error "Not on a heading"))
11521 (save-excursion
11522 (beginning-of-line 1)
11523 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11524 (org-match-string-no-properties 1)
11525 "")))
11527 (defun org-get-tags ()
11528 "Get the list of tags specified in the current headline."
11529 (org-split-string (org-get-tags-string) ":"))
11531 (defun org-get-buffer-tags ()
11532 "Get a table of all tags used in the buffer, for completion."
11533 (let (tags)
11534 (save-excursion
11535 (goto-char (point-min))
11536 (while (re-search-forward
11537 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
11538 (when (equal (char-after (point-at-bol 0)) ?*)
11539 (mapc (lambda (x) (add-to-list 'tags x))
11540 (org-split-string (org-match-string-no-properties 1) ":")))))
11541 (mapcar 'list tags)))
11543 ;;;; The mapping API
11545 ;;;###autoload
11546 (defun org-map-entries (func &optional match scope &rest skip)
11547 "Call FUNC at each headline selected by MATCH in SCOPE.
11549 FUNC is a function or a lisp form. The function will be called without
11550 arguments, with the cursor positioned at the beginning of the headline.
11551 The return values of all calls to the function will be collected and
11552 returned as a list.
11554 The call to FUNC will be wrapped into a save-excursion form, so FUNC
11555 does not need to preserve point. After evaluaton, the cursor will be
11556 moved to the end of the line (presumably of the headline of the
11557 processed entry) and search continues from there. Under some
11558 circumstances, this may not produce the wanted results. For example,
11559 if you have removed (e.g. archived) the current (sub)tree it could
11560 mean that the next entry will be skipped entirely. In such cases, you
11561 can specify the position from where search should continue by making
11562 FUNC set the variable `org-map-continue-from' to the desired buffer
11563 position.
11565 MATCH is a tags/property/todo match as it is used in the agenda tags view.
11566 Only headlines that are matched by this query will be considered during
11567 the iteration. When MATCH is nil or t, all headlines will be
11568 visited by the iteration.
11570 SCOPE determines the scope of this command. It can be any of:
11572 nil The current buffer, respecting the restriction if any
11573 tree The subtree started with the entry at point
11574 file The current buffer, without restriction
11575 file-with-archives
11576 The current buffer, and any archives associated with it
11577 agenda All agenda files
11578 agenda-with-archives
11579 All agenda files with any archive files associated with them
11580 \(file1 file2 ...)
11581 If this is a list, all files in the list will be scanned
11583 The remaining args are treated as settings for the skipping facilities of
11584 the scanner. The following items can be given here:
11586 archive skip trees with the archive tag.
11587 comment skip trees with the COMMENT keyword
11588 function or Emacs Lisp form:
11589 will be used as value for `org-agenda-skip-function', so whenever
11590 the the function returns t, FUNC will not be called for that
11591 entry and search will continue from the point where the
11592 function leaves it.
11594 If your function needs to retrieve the tags including inherited tags
11595 at the *current* entry, you can use the value of the variable
11596 `org-scanner-tags' which will be much faster than getting the value
11597 with `org-get-tags-at'. If your function gets properties with
11598 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
11599 to t around the call to `org-entry-properties' to get the same speedup.
11600 Note that if your function moves around to retrieve tags and properties at
11601 a *different* entry, you cannot use these techniques."
11602 (let* ((org-agenda-archives-mode nil) ; just to make sure
11603 (org-agenda-skip-archived-trees (memq 'archive skip))
11604 (org-agenda-skip-comment-trees (memq 'comment skip))
11605 (org-agenda-skip-function
11606 (car (org-delete-all '(comment archive) skip)))
11607 (org-tags-match-list-sublevels t)
11608 matcher file res
11609 org-todo-keywords-for-agenda
11610 org-done-keywords-for-agenda
11611 org-todo-keyword-alist-for-agenda
11612 org-tag-alist-for-agenda)
11614 (cond
11615 ((eq match t) (setq matcher t))
11616 ((eq match nil) (setq matcher t))
11617 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
11619 (save-excursion
11620 (save-restriction
11621 (when (eq scope 'tree)
11622 (org-back-to-heading t)
11623 (org-narrow-to-subtree)
11624 (setq scope nil))
11626 (if (not scope)
11627 (progn
11628 (org-prepare-agenda-buffers
11629 (list (buffer-file-name (current-buffer))))
11630 (setq res (org-scan-tags func matcher)))
11631 ;; Get the right scope
11632 (cond
11633 ((and scope (listp scope) (symbolp (car scope)))
11634 (setq scope (eval scope)))
11635 ((eq scope 'agenda)
11636 (setq scope (org-agenda-files t)))
11637 ((eq scope 'agenda-with-archives)
11638 (setq scope (org-agenda-files t))
11639 (setq scope (org-add-archive-files scope)))
11640 ((eq scope 'file)
11641 (setq scope (list (buffer-file-name))))
11642 ((eq scope 'file-with-archives)
11643 (setq scope (org-add-archive-files (list (buffer-file-name))))))
11644 (org-prepare-agenda-buffers scope)
11645 (while (setq file (pop scope))
11646 (with-current-buffer (org-find-base-buffer-visiting file)
11647 (save-excursion
11648 (save-restriction
11649 (widen)
11650 (goto-char (point-min))
11651 (setq res (append res (org-scan-tags func matcher))))))))))
11652 res))
11654 ;;;; Properties
11656 ;;; Setting and retrieving properties
11658 (defconst org-special-properties
11659 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
11660 "TIMESTAMP" "TIMESTAMP_IA")
11661 "The special properties valid in Org-mode.
11663 These are properties that are not defined in the property drawer,
11664 but in some other way.")
11666 (defconst org-default-properties
11667 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
11668 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
11669 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
11670 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
11671 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
11672 "CLOCK_MODELINE_TOTAL")
11673 "Some properties that are used by Org-mode for various purposes.
11674 Being in this list makes sure that they are offered for completion.")
11676 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
11677 "Regular expression matching the first line of a property drawer.")
11679 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
11680 "Regular expression matching the first line of a property drawer.")
11682 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
11683 "Regular expression matching the first line of a property drawer.")
11685 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
11686 "Regular expression matching the first line of a property drawer.")
11688 (defconst org-property-drawer-re
11689 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
11690 org-property-end-re "\\)\n?")
11691 "Matches an entire property drawer.")
11693 (defconst org-clock-drawer-re
11694 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
11695 org-property-end-re "\\)\n?")
11696 "Matches an entire clock drawer.")
11698 (defun org-property-action ()
11699 "Do an action on properties."
11700 (interactive)
11701 (let (c)
11702 (org-at-property-p)
11703 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
11704 (setq c (read-char-exclusive))
11705 (cond
11706 ((equal c ?s)
11707 (call-interactively 'org-set-property))
11708 ((equal c ?d)
11709 (call-interactively 'org-delete-property))
11710 ((equal c ?D)
11711 (call-interactively 'org-delete-property-globally))
11712 ((equal c ?c)
11713 (call-interactively 'org-compute-property-at-point))
11714 (t (error "No such property action %c" c)))))
11716 (defun org-at-property-p ()
11717 "Is the cursor in a property line?"
11718 ;; FIXME: Does not check if we are actually in the drawer.
11719 ;; FIXME: also returns true on any drawers.....
11720 ;; This is used by C-c C-c for property action.
11721 (save-excursion
11722 (beginning-of-line 1)
11723 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
11725 (defun org-get-property-block (&optional beg end force)
11726 "Return the (beg . end) range of the body of the property drawer.
11727 BEG and END can be beginning and end of subtree, if not given
11728 they will be found.
11729 If the drawer does not exist and FORCE is non-nil, create the drawer."
11730 (catch 'exit
11731 (save-excursion
11732 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
11733 (end (or end (progn (outline-next-heading) (point)))))
11734 (goto-char beg)
11735 (if (re-search-forward org-property-start-re end t)
11736 (setq beg (1+ (match-end 0)))
11737 (if force
11738 (save-excursion
11739 (org-insert-property-drawer)
11740 (setq end (progn (outline-next-heading) (point))))
11741 (throw 'exit nil))
11742 (goto-char beg)
11743 (if (re-search-forward org-property-start-re end t)
11744 (setq beg (1+ (match-end 0)))))
11745 (if (re-search-forward org-property-end-re end t)
11746 (setq end (match-beginning 0))
11747 (or force (throw 'exit nil))
11748 (goto-char beg)
11749 (setq end beg)
11750 (org-indent-line-function)
11751 (insert ":END:\n"))
11752 (cons beg end)))))
11754 (defun org-entry-properties (&optional pom which)
11755 "Get all properties of the entry at point-or-marker POM.
11756 This includes the TODO keyword, the tags, time strings for deadline,
11757 scheduled, and clocking, and any additional properties defined in the
11758 entry. The return value is an alist, keys may occur multiple times
11759 if the property key was used several times.
11760 POM may also be nil, in which case the current entry is used.
11761 If WHICH is nil or `all', get all properties. If WHICH is
11762 `special' or `standard', only get that subclass."
11763 (setq which (or which 'all))
11764 (org-with-point-at pom
11765 (let ((clockstr (substring org-clock-string 0 -1))
11766 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
11767 beg end range props sum-props key value string clocksum)
11768 (save-excursion
11769 (when (condition-case nil
11770 (and (org-mode-p) (org-back-to-heading t))
11771 (error nil))
11772 (setq beg (point))
11773 (setq sum-props (get-text-property (point) 'org-summaries))
11774 (setq clocksum (get-text-property (point) :org-clock-minutes))
11775 (outline-next-heading)
11776 (setq end (point))
11777 (when (memq which '(all special))
11778 ;; Get the special properties, like TODO and tags
11779 (goto-char beg)
11780 (when (and (looking-at org-todo-line-regexp) (match-end 2))
11781 (push (cons "TODO" (org-match-string-no-properties 2)) props))
11782 (when (looking-at org-priority-regexp)
11783 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
11784 (when (and (setq value (org-get-tags-string))
11785 (string-match "\\S-" value))
11786 (push (cons "TAGS" value) props))
11787 (when (setq value (org-get-tags-at))
11788 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
11789 props))
11790 (while (re-search-forward org-maybe-keyword-time-regexp end t)
11791 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
11792 string (if (equal key clockstr)
11793 (org-no-properties
11794 (org-trim
11795 (buffer-substring
11796 (match-beginning 3) (goto-char (point-at-eol)))))
11797 (substring (org-match-string-no-properties 3) 1 -1)))
11798 (unless key
11799 (if (= (char-after (match-beginning 3)) ?\[)
11800 (setq key "TIMESTAMP_IA")
11801 (setq key "TIMESTAMP")))
11802 (when (or (equal key clockstr) (not (assoc key props)))
11803 (push (cons key string) props)))
11807 (when (memq which '(all standard))
11808 ;; Get the standard properties, like :PROP: ...
11809 (setq range (org-get-property-block beg end))
11810 (when range
11811 (goto-char (car range))
11812 (while (re-search-forward
11813 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
11814 (cdr range) t)
11815 (setq key (org-match-string-no-properties 1)
11816 value (org-trim (or (org-match-string-no-properties 2) "")))
11817 (unless (member key excluded)
11818 (push (cons key (or value "")) props)))))
11819 (if clocksum
11820 (push (cons "CLOCKSUM"
11821 (org-columns-number-to-string (/ (float clocksum) 60.)
11822 'add_times))
11823 props))
11824 (unless (assoc "CATEGORY" props)
11825 (setq value (or (org-get-category)
11826 (progn (org-refresh-category-properties)
11827 (org-get-category))))
11828 (push (cons "CATEGORY" value) props))
11829 (append sum-props (nreverse props)))))))
11831 (defun org-entry-get (pom property &optional inherit)
11832 "Get value of PROPERTY for entry at point-or-marker POM.
11833 If INHERIT is non-nil and the entry does not have the property,
11834 then also check higher levels of the hierarchy.
11835 If INHERIT is the symbol `selective', use inheritance only if the setting
11836 in `org-use-property-inheritance' selects PROPERTY for inheritance.
11837 If the property is present but empty, the return value is the empty string.
11838 If the property is not present at all, nil is returned."
11839 (org-with-point-at pom
11840 (if (and inherit (if (eq inherit 'selective)
11841 (org-property-inherit-p property)
11843 (org-entry-get-with-inheritance property)
11844 (if (member property org-special-properties)
11845 ;; We need a special property. Use brute force, get all properties.
11846 (cdr (assoc property (org-entry-properties nil 'special)))
11847 (let ((range (org-get-property-block)))
11848 (if (and range
11849 (goto-char (car range))
11850 (re-search-forward
11851 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
11852 (cdr range) t))
11853 ;; Found the property, return it.
11854 (if (match-end 1)
11855 (org-match-string-no-properties 1)
11856 "")))))))
11858 (defun org-property-or-variable-value (var &optional inherit)
11859 "Check if there is a property fixing the value of VAR.
11860 If yes, return this value. If not, return the current value of the variable."
11861 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
11862 (if (and prop (stringp prop) (string-match "\\S-" prop))
11863 (read prop)
11864 (symbol-value var))))
11866 (defun org-entry-delete (pom property)
11867 "Delete the property PROPERTY from entry at point-or-marker POM."
11868 (org-with-point-at pom
11869 (if (member property org-special-properties)
11870 nil ; cannot delete these properties.
11871 (let ((range (org-get-property-block)))
11872 (if (and range
11873 (goto-char (car range))
11874 (re-search-forward
11875 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
11876 (cdr range) t))
11877 (progn
11878 (delete-region (match-beginning 0) (1+ (point-at-eol)))
11880 nil)))))
11882 ;; Multi-values properties are properties that contain multiple values
11883 ;; These values are assumed to be single words, separated by whitespace.
11884 (defun org-entry-add-to-multivalued-property (pom property value)
11885 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
11886 (let* ((old (org-entry-get pom property))
11887 (values (and old (org-split-string old "[ \t]"))))
11888 (setq value (org-entry-protect-space value))
11889 (unless (member value values)
11890 (setq values (cons value values))
11891 (org-entry-put pom property
11892 (mapconcat 'identity values " ")))))
11894 (defun org-entry-remove-from-multivalued-property (pom property value)
11895 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
11896 (let* ((old (org-entry-get pom property))
11897 (values (and old (org-split-string old "[ \t]"))))
11898 (setq value (org-entry-protect-space value))
11899 (when (member value values)
11900 (setq values (delete value values))
11901 (org-entry-put pom property
11902 (mapconcat 'identity values " ")))))
11904 (defun org-entry-member-in-multivalued-property (pom property value)
11905 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
11906 (let* ((old (org-entry-get pom property))
11907 (values (and old (org-split-string old "[ \t]"))))
11908 (setq value (org-entry-protect-space value))
11909 (member value values)))
11911 (defun org-entry-get-multivalued-property (pom property)
11912 "Return a list of values in a multivalued property."
11913 (let* ((value (org-entry-get pom property))
11914 (values (and value (org-split-string value "[ \t]"))))
11915 (mapcar 'org-entry-restore-space values)))
11917 (defun org-entry-put-multivalued-property (pom property &rest values)
11918 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
11919 VALUES should be a list of strings. Spaces will be protected."
11920 (org-entry-put pom property
11921 (mapconcat 'org-entry-protect-space values " "))
11922 (let* ((value (org-entry-get pom property))
11923 (values (and value (org-split-string value "[ \t]"))))
11924 (mapcar 'org-entry-restore-space values)))
11926 (defun org-entry-protect-space (s)
11927 "Protect spaces and newline in string S."
11928 (while (string-match " " s)
11929 (setq s (replace-match "%20" t t s)))
11930 (while (string-match "\n" s)
11931 (setq s (replace-match "%0A" t t s)))
11934 (defun org-entry-restore-space (s)
11935 "Restore spaces and newline in string S."
11936 (while (string-match "%20" s)
11937 (setq s (replace-match " " t t s)))
11938 (while (string-match "%0A" s)
11939 (setq s (replace-match "\n" t t s)))
11942 (defvar org-entry-property-inherited-from (make-marker)
11943 "Marker pointing to the entry from where a property was inherited.
11944 Each call to `org-entry-get-with-inheritance' will set this marker to the
11945 location of the entry where the inheritance search matched. If there was
11946 no match, the marker will point nowhere.
11947 Note that also `org-entry-get' calls this function, if the INHERIT flag
11948 is set.")
11950 (defun org-entry-get-with-inheritance (property)
11951 "Get entry property, and search higher levels if not present."
11952 (move-marker org-entry-property-inherited-from nil)
11953 (let (tmp)
11954 (save-excursion
11955 (save-restriction
11956 (widen)
11957 (catch 'ex
11958 (while t
11959 (when (setq tmp (org-entry-get nil property))
11960 (org-back-to-heading t)
11961 (move-marker org-entry-property-inherited-from (point))
11962 (throw 'ex tmp))
11963 (or (org-up-heading-safe) (throw 'ex nil)))))
11964 (or tmp
11965 (cdr (assoc property org-file-properties))
11966 (cdr (assoc property org-global-properties))
11967 (cdr (assoc property org-global-properties-fixed))))))
11969 (defun org-entry-put (pom property value)
11970 "Set PROPERTY to VALUE for entry at point-or-marker POM."
11971 (org-with-point-at pom
11972 (org-back-to-heading t)
11973 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
11974 range)
11975 (cond
11976 ((equal property "TODO")
11977 (when (and (stringp value) (string-match "\\S-" value)
11978 (not (member value org-todo-keywords-1)))
11979 (error "\"%s\" is not a valid TODO state" value))
11980 (if (or (not value)
11981 (not (string-match "\\S-" value)))
11982 (setq value 'none))
11983 (org-todo value)
11984 (org-set-tags nil 'align))
11985 ((equal property "PRIORITY")
11986 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
11987 (string-to-char value) ?\ ))
11988 (org-set-tags nil 'align))
11989 ((equal property "SCHEDULED")
11990 (if (re-search-forward org-scheduled-time-regexp end t)
11991 (cond
11992 ((eq value 'earlier) (org-timestamp-change -1 'day))
11993 ((eq value 'later) (org-timestamp-change 1 'day))
11994 (t (call-interactively 'org-schedule)))
11995 (call-interactively 'org-schedule)))
11996 ((equal property "DEADLINE")
11997 (if (re-search-forward org-deadline-time-regexp end t)
11998 (cond
11999 ((eq value 'earlier) (org-timestamp-change -1 'day))
12000 ((eq value 'later) (org-timestamp-change 1 'day))
12001 (t (call-interactively 'org-deadline)))
12002 (call-interactively 'org-deadline)))
12003 ((member property org-special-properties)
12004 (error "The %s property can not yet be set with `org-entry-put'"
12005 property))
12006 (t ; a non-special property
12007 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
12008 (setq range (org-get-property-block beg end 'force))
12009 (goto-char (car range))
12010 (if (re-search-forward
12011 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
12012 (progn
12013 (delete-region (match-beginning 1) (match-end 1))
12014 (goto-char (match-beginning 1)))
12015 (goto-char (cdr range))
12016 (insert "\n")
12017 (backward-char 1)
12018 (org-indent-line-function)
12019 (insert ":" property ":"))
12020 (and value (insert " " value))
12021 (org-indent-line-function)))))))
12023 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
12024 "Get all property keys in the current buffer.
12025 With INCLUDE-SPECIALS, also list the special properties that reflect things
12026 like tags and TODO state.
12027 With INCLUDE-DEFAULTS, also include properties that has special meaning
12028 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
12029 With INCLUDE-COLUMNS, also include property names given in COLUMN
12030 formats in the current buffer."
12031 (let (rtn range cfmt s p)
12032 (save-excursion
12033 (save-restriction
12034 (widen)
12035 (goto-char (point-min))
12036 (while (re-search-forward org-property-start-re nil t)
12037 (setq range (org-get-property-block))
12038 (goto-char (car range))
12039 (while (re-search-forward
12040 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
12041 (cdr range) t)
12042 (add-to-list 'rtn (org-match-string-no-properties 1)))
12043 (outline-next-heading))))
12045 (when include-specials
12046 (setq rtn (append org-special-properties rtn)))
12048 (when include-defaults
12049 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
12050 (add-to-list 'rtn org-effort-property))
12052 (when include-columns
12053 (save-excursion
12054 (save-restriction
12055 (widen)
12056 (goto-char (point-min))
12057 (while (re-search-forward
12058 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
12059 nil t)
12060 (setq cfmt (match-string 2) s 0)
12061 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
12062 cfmt s)
12063 (setq s (match-end 0)
12064 p (match-string 1 cfmt))
12065 (unless (or (equal p "ITEM")
12066 (member p org-special-properties))
12067 (add-to-list 'rtn (match-string 1 cfmt))))))))
12069 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
12071 (defun org-property-values (key)
12072 "Return a list of all values of property KEY."
12073 (save-excursion
12074 (save-restriction
12075 (widen)
12076 (goto-char (point-min))
12077 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
12078 values)
12079 (while (re-search-forward re nil t)
12080 (add-to-list 'values (org-trim (match-string 1))))
12081 (delete "" values)))))
12083 (defun org-insert-property-drawer ()
12084 "Insert a property drawer into the current entry."
12085 (interactive)
12086 (org-back-to-heading t)
12087 (looking-at outline-regexp)
12088 (let ((indent (if org-adapt-indentation
12089 (- (match-end 0)(match-beginning 0))
12091 (beg (point))
12092 (re (concat "^[ \t]*" org-keyword-time-regexp))
12093 end hiddenp)
12094 (outline-next-heading)
12095 (setq end (point))
12096 (goto-char beg)
12097 (while (re-search-forward re end t))
12098 (setq hiddenp (org-invisible-p))
12099 (end-of-line 1)
12100 (and (equal (char-after) ?\n) (forward-char 1))
12101 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
12102 (if (member (match-string 1) '("CLOCK:" ":END:"))
12103 ;; just skip this line
12104 (beginning-of-line 2)
12105 ;; Drawer start, find the end
12106 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
12107 (beginning-of-line 1)))
12108 (org-skip-over-state-notes)
12109 (skip-chars-backward " \t\n\r")
12110 (if (eq (char-before) ?*) (forward-char 1))
12111 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
12112 (beginning-of-line 0)
12113 (org-indent-to-column indent)
12114 (beginning-of-line 2)
12115 (org-indent-to-column indent)
12116 (beginning-of-line 0)
12117 (if hiddenp
12118 (save-excursion
12119 (org-back-to-heading t)
12120 (hide-entry))
12121 (org-flag-drawer t))))
12123 (defun org-set-property (property value)
12124 "In the current entry, set PROPERTY to VALUE.
12125 When called interactively, this will prompt for a property name, offering
12126 completion on existing and default properties. And then it will prompt
12127 for a value, offering completion either on allowed values (via an inherited
12128 xxx_ALL property) or on existing values in other instances of this property
12129 in the current file."
12130 (interactive
12131 (let* ((completion-ignore-case t)
12132 (keys (org-buffer-property-keys nil t t))
12133 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
12134 (prop (if (member prop0 keys)
12135 prop0
12136 (or (cdr (assoc (downcase prop0)
12137 (mapcar (lambda (x) (cons (downcase x) x))
12138 keys)))
12139 prop0)))
12140 (cur (org-entry-get nil prop))
12141 (allowed (org-property-get-allowed-values nil prop 'table))
12142 (existing (mapcar 'list (org-property-values prop)))
12143 (val (if allowed
12144 (org-completing-read "Value: " allowed nil 'req-match)
12145 (let (org-completion-use-ido)
12146 (org-completing-read
12147 (concat "Value" (if (and cur (string-match "\\S-" cur))
12148 (concat "[" cur "]") "")
12149 ": ")
12150 existing nil nil "" nil cur)))))
12151 (list prop (if (equal val "") cur val))))
12152 (unless (equal (org-entry-get nil property) value)
12153 (org-entry-put nil property value)))
12155 (defun org-delete-property (property)
12156 "In the current entry, delete PROPERTY."
12157 (interactive
12158 (let* ((completion-ignore-case t)
12159 (prop (org-ido-completing-read
12160 "Property: " (org-entry-properties nil 'standard))))
12161 (list prop)))
12162 (message "Property %s %s" property
12163 (if (org-entry-delete nil property)
12164 "deleted"
12165 "was not present in the entry")))
12167 (defun org-delete-property-globally (property)
12168 "Remove PROPERTY globally, from all entries."
12169 (interactive
12170 (let* ((completion-ignore-case t)
12171 (prop (org-ido-completing-read
12172 "Globally remove property: "
12173 (mapcar 'list (org-buffer-property-keys)))))
12174 (list prop)))
12175 (save-excursion
12176 (save-restriction
12177 (widen)
12178 (goto-char (point-min))
12179 (let ((cnt 0))
12180 (while (re-search-forward
12181 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
12182 nil t)
12183 (setq cnt (1+ cnt))
12184 (replace-match ""))
12185 (message "Property \"%s\" removed from %d entries" property cnt)))))
12187 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
12189 (defun org-compute-property-at-point ()
12190 "Compute the property at point.
12191 This looks for an enclosing column format, extracts the operator and
12192 then applies it to the property in the column format's scope."
12193 (interactive)
12194 (unless (org-at-property-p)
12195 (error "Not at a property"))
12196 (let ((prop (org-match-string-no-properties 2)))
12197 (org-columns-get-format-and-top-level)
12198 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
12199 (error "No operator defined for property %s" prop))
12200 (org-columns-compute prop)))
12202 (defun org-property-get-allowed-values (pom property &optional table)
12203 "Get allowed values for the property PROPERTY.
12204 When TABLE is non-nil, return an alist that can directly be used for
12205 completion."
12206 (let (vals)
12207 (cond
12208 ((equal property "TODO")
12209 (setq vals (org-with-point-at pom
12210 (append org-todo-keywords-1 '("")))))
12211 ((equal property "PRIORITY")
12212 (let ((n org-lowest-priority))
12213 (while (>= n org-highest-priority)
12214 (push (char-to-string n) vals)
12215 (setq n (1- n)))))
12216 ((member property org-special-properties))
12218 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
12220 (when (and vals (string-match "\\S-" vals))
12221 (setq vals (car (read-from-string (concat "(" vals ")"))))
12222 (setq vals (mapcar (lambda (x)
12223 (cond ((stringp x) x)
12224 ((numberp x) (number-to-string x))
12225 ((symbolp x) (symbol-name x))
12226 (t "???")))
12227 vals)))))
12228 (if table (mapcar 'list vals) vals)))
12230 (defun org-property-previous-allowed-value (&optional previous)
12231 "Switch to the next allowed value for this property."
12232 (interactive)
12233 (org-property-next-allowed-value t))
12235 (defun org-property-next-allowed-value (&optional previous)
12236 "Switch to the next allowed value for this property."
12237 (interactive)
12238 (unless (org-at-property-p)
12239 (error "Not at a property"))
12240 (let* ((key (match-string 2))
12241 (value (match-string 3))
12242 (allowed (or (org-property-get-allowed-values (point) key)
12243 (and (member value '("[ ]" "[-]" "[X]"))
12244 '("[ ]" "[X]"))))
12245 nval)
12246 (unless allowed
12247 (error "Allowed values for this property have not been defined"))
12248 (if previous (setq allowed (reverse allowed)))
12249 (if (member value allowed)
12250 (setq nval (car (cdr (member value allowed)))))
12251 (setq nval (or nval (car allowed)))
12252 (if (equal nval value)
12253 (error "Only one allowed value for this property"))
12254 (org-at-property-p)
12255 (replace-match (concat " :" key ": " nval) t t)
12256 (org-indent-line-function)
12257 (beginning-of-line 1)
12258 (skip-chars-forward " \t")))
12260 (defun org-find-entry-with-id (ident)
12261 "Locate the entry that contains the ID property with exact value IDENT.
12262 IDENT can be a string, a symbol or a number, this function will search for
12263 the string representation of it.
12264 Return the position where this entry starts, or nil if there is no such entry."
12265 (interactive "sID: ")
12266 (let ((id (cond
12267 ((stringp ident) ident)
12268 ((symbol-name ident) (symbol-name ident))
12269 ((numberp ident) (number-to-string ident))
12270 (t (error "IDENT %s must be a string, symbol or number" ident))))
12271 (case-fold-search nil))
12272 (save-excursion
12273 (save-restriction
12274 (widen)
12275 (goto-char (point-min))
12276 (when (re-search-forward
12277 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
12278 nil t)
12279 (org-back-to-heading)
12280 (point))))))
12282 ;;;; Timestamps
12284 (defvar org-last-changed-timestamp nil)
12285 (defvar org-last-inserted-timestamp nil
12286 "The last time stamp inserted with `org-insert-time-stamp'.")
12287 (defvar org-time-was-given) ; dynamically scoped parameter
12288 (defvar org-end-time-was-given) ; dynamically scoped parameter
12289 (defvar org-ts-what) ; dynamically scoped parameter
12291 (defun org-time-stamp (arg &optional inactive)
12292 "Prompt for a date/time and insert a time stamp.
12293 If the user specifies a time like HH:MM, or if this command is called
12294 with a prefix argument, the time stamp will contain date and time.
12295 Otherwise, only the date will be included. All parts of a date not
12296 specified by the user will be filled in from the current date/time.
12297 So if you press just return without typing anything, the time stamp
12298 will represent the current date/time. If there is already a timestamp
12299 at the cursor, it will be modified."
12300 (interactive "P")
12301 (let* ((ts nil)
12302 (default-time
12303 ;; Default time is either today, or, when entering a range,
12304 ;; the range start.
12305 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
12306 (save-excursion
12307 (re-search-backward
12308 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
12309 (- (point) 20) t)))
12310 (apply 'encode-time (org-parse-time-string (match-string 1)))
12311 (current-time)))
12312 (default-input (and ts (org-get-compact-tod ts)))
12313 org-time-was-given org-end-time-was-given time)
12314 (cond
12315 ((and (org-at-timestamp-p t)
12316 (memq last-command '(org-time-stamp org-time-stamp-inactive))
12317 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
12318 (insert "--")
12319 (setq time (let ((this-command this-command))
12320 (org-read-date arg 'totime nil nil
12321 default-time default-input)))
12322 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
12323 ((org-at-timestamp-p t)
12324 (setq time (let ((this-command this-command))
12325 (org-read-date arg 'totime nil nil default-time default-input)))
12326 (when (org-at-timestamp-p t) ; just to get the match data
12327 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
12328 (replace-match "")
12329 (setq org-last-changed-timestamp
12330 (org-insert-time-stamp
12331 time (or org-time-was-given arg)
12332 inactive nil nil (list org-end-time-was-given))))
12333 (message "Timestamp updated"))
12335 (setq time (let ((this-command this-command))
12336 (org-read-date arg 'totime nil nil default-time default-input)))
12337 (org-insert-time-stamp time (or org-time-was-given arg) inactive
12338 nil nil (list org-end-time-was-given))))))
12340 ;; FIXME: can we use this for something else, like computing time differences?
12341 (defun org-get-compact-tod (s)
12342 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
12343 (let* ((t1 (match-string 1 s))
12344 (h1 (string-to-number (match-string 2 s)))
12345 (m1 (string-to-number (match-string 3 s)))
12346 (t2 (and (match-end 4) (match-string 5 s)))
12347 (h2 (and t2 (string-to-number (match-string 6 s))))
12348 (m2 (and t2 (string-to-number (match-string 7 s))))
12349 dh dm)
12350 (if (not t2)
12352 (setq dh (- h2 h1) dm (- m2 m1))
12353 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
12354 (concat t1 "+" (number-to-string dh)
12355 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
12357 (defun org-time-stamp-inactive (&optional arg)
12358 "Insert an inactive time stamp.
12359 An inactive time stamp is enclosed in square brackets instead of angle
12360 brackets. It is inactive in the sense that it does not trigger agenda entries,
12361 does not link to the calendar and cannot be changed with the S-cursor keys.
12362 So these are more for recording a certain time/date."
12363 (interactive "P")
12364 (org-time-stamp arg 'inactive))
12366 (defvar org-date-ovl (org-make-overlay 1 1))
12367 (org-overlay-put org-date-ovl 'face 'org-warning)
12368 (org-detach-overlay org-date-ovl)
12370 (defvar org-ans1) ; dynamically scoped parameter
12371 (defvar org-ans2) ; dynamically scoped parameter
12373 (defvar org-plain-time-of-day-regexp) ; defined below
12375 (defvar org-overriding-default-time nil) ; dynamically scoped
12376 (defvar org-read-date-overlay nil)
12377 (defvar org-dcst nil) ; dynamically scoped
12378 (defvar org-read-date-history nil)
12380 (defun org-read-date (&optional with-time to-time from-string prompt
12381 default-time default-input)
12382 "Read a date, possibly a time, and make things smooth for the user.
12383 The prompt will suggest to enter an ISO date, but you can also enter anything
12384 which will at least partially be understood by `parse-time-string'.
12385 Unrecognized parts of the date will default to the current day, month, year,
12386 hour and minute. If this command is called to replace a timestamp at point,
12387 of to enter the second timestamp of a range, the default time is taken from the
12388 existing stamp. For example,
12389 3-2-5 --> 2003-02-05
12390 feb 15 --> currentyear-02-15
12391 sep 12 9 --> 2009-09-12
12392 12:45 --> today 12:45
12393 22 sept 0:34 --> currentyear-09-22 0:34
12394 12 --> currentyear-currentmonth-12
12395 Fri --> nearest Friday (today or later)
12396 etc.
12398 Furthermore you can specify a relative date by giving, as the *first* thing
12399 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
12400 change in days weeks, months, years.
12401 With a single plus or minus, the date is relative to today. With a double
12402 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
12403 +4d --> four days from today
12404 +4 --> same as above
12405 +2w --> two weeks from today
12406 ++5 --> five days from default date
12408 The function understands only English month and weekday abbreviations,
12409 but this can be configured with the variables `parse-time-months' and
12410 `parse-time-weekdays'.
12412 While prompting, a calendar is popped up - you can also select the
12413 date with the mouse (button 1). The calendar shows a period of three
12414 months. To scroll it to other months, use the keys `>' and `<'.
12415 If you don't like the calendar, turn it off with
12416 \(setq org-read-date-popup-calendar nil)
12418 With optional argument TO-TIME, the date will immediately be converted
12419 to an internal time.
12420 With an optional argument WITH-TIME, the prompt will suggest to also
12421 insert a time. Note that when WITH-TIME is not set, you can still
12422 enter a time, and this function will inform the calling routine about
12423 this change. The calling routine may then choose to change the format
12424 used to insert the time stamp into the buffer to include the time.
12425 With optional argument FROM-STRING, read from this string instead from
12426 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
12427 the time/date that is used for everything that is not specified by the
12428 user."
12429 (require 'parse-time)
12430 (let* ((org-time-stamp-rounding-minutes
12431 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
12432 (org-dcst org-display-custom-times)
12433 (ct (org-current-time))
12434 (def (or org-overriding-default-time default-time ct))
12435 (defdecode (decode-time def))
12436 (dummy (progn
12437 (when (< (nth 2 defdecode) org-extend-today-until)
12438 (setcar (nthcdr 2 defdecode) -1)
12439 (setcar (nthcdr 1 defdecode) 59)
12440 (setq def (apply 'encode-time defdecode)
12441 defdecode (decode-time def)))))
12442 (calendar-move-hook nil)
12443 (calendar-view-diary-initially-flag nil)
12444 (view-diary-entries-initially nil)
12445 (calendar-view-holidays-initially-flag nil)
12446 (view-calendar-holidays-initially nil)
12447 (timestr (format-time-string
12448 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
12449 (prompt (concat (if prompt (concat prompt " ") "")
12450 (format "Date+time [%s]: " timestr)))
12451 ans (org-ans0 "") org-ans1 org-ans2 final)
12453 (cond
12454 (from-string (setq ans from-string))
12455 (org-read-date-popup-calendar
12456 (save-excursion
12457 (save-window-excursion
12458 (calendar)
12459 (calendar-forward-day (- (time-to-days def)
12460 (calendar-absolute-from-gregorian
12461 (calendar-current-date))))
12462 (org-eval-in-calendar nil t)
12463 (let* ((old-map (current-local-map))
12464 (map (copy-keymap calendar-mode-map))
12465 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12466 (org-defkey map (kbd "RET") 'org-calendar-select)
12467 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
12468 'org-calendar-select-mouse)
12469 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
12470 'org-calendar-select-mouse)
12471 (org-defkey minibuffer-local-map [(meta shift left)]
12472 (lambda () (interactive)
12473 (org-eval-in-calendar '(calendar-backward-month 1))))
12474 (org-defkey minibuffer-local-map [(meta shift right)]
12475 (lambda () (interactive)
12476 (org-eval-in-calendar '(calendar-forward-month 1))))
12477 (org-defkey minibuffer-local-map [(meta shift up)]
12478 (lambda () (interactive)
12479 (org-eval-in-calendar '(calendar-backward-year 1))))
12480 (org-defkey minibuffer-local-map [(meta shift down)]
12481 (lambda () (interactive)
12482 (org-eval-in-calendar '(calendar-forward-year 1))))
12483 (org-defkey minibuffer-local-map [?\e (shift left)]
12484 (lambda () (interactive)
12485 (org-eval-in-calendar '(calendar-backward-month 1))))
12486 (org-defkey minibuffer-local-map [?\e (shift right)]
12487 (lambda () (interactive)
12488 (org-eval-in-calendar '(calendar-forward-month 1))))
12489 (org-defkey minibuffer-local-map [?\e (shift up)]
12490 (lambda () (interactive)
12491 (org-eval-in-calendar '(calendar-backward-year 1))))
12492 (org-defkey minibuffer-local-map [?\e (shift down)]
12493 (lambda () (interactive)
12494 (org-eval-in-calendar '(calendar-forward-year 1))))
12495 (org-defkey minibuffer-local-map [(shift up)]
12496 (lambda () (interactive)
12497 (org-eval-in-calendar '(calendar-backward-week 1))))
12498 (org-defkey minibuffer-local-map [(shift down)]
12499 (lambda () (interactive)
12500 (org-eval-in-calendar '(calendar-forward-week 1))))
12501 (org-defkey minibuffer-local-map [(shift left)]
12502 (lambda () (interactive)
12503 (org-eval-in-calendar '(calendar-backward-day 1))))
12504 (org-defkey minibuffer-local-map [(shift right)]
12505 (lambda () (interactive)
12506 (org-eval-in-calendar '(calendar-forward-day 1))))
12507 (org-defkey minibuffer-local-map ">"
12508 (lambda () (interactive)
12509 (org-eval-in-calendar '(scroll-calendar-left 1))))
12510 (org-defkey minibuffer-local-map "<"
12511 (lambda () (interactive)
12512 (org-eval-in-calendar '(scroll-calendar-right 1))))
12513 (run-hooks 'org-read-date-minibuffer-setup-hook)
12514 (unwind-protect
12515 (progn
12516 (use-local-map map)
12517 (add-hook 'post-command-hook 'org-read-date-display)
12518 (setq org-ans0 (read-string prompt default-input
12519 'org-read-date-history nil))
12520 ;; org-ans0: from prompt
12521 ;; org-ans1: from mouse click
12522 ;; org-ans2: from calendar motion
12523 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
12524 (remove-hook 'post-command-hook 'org-read-date-display)
12525 (use-local-map old-map)
12526 (when org-read-date-overlay
12527 (org-delete-overlay org-read-date-overlay)
12528 (setq org-read-date-overlay nil)))))))
12530 (t ; Naked prompt only
12531 (unwind-protect
12532 (setq ans (read-string prompt default-input
12533 'org-read-date-history timestr))
12534 (when org-read-date-overlay
12535 (org-delete-overlay org-read-date-overlay)
12536 (setq org-read-date-overlay nil)))))
12538 (setq final (org-read-date-analyze ans def defdecode))
12540 (if to-time
12541 (apply 'encode-time final)
12542 (if (and (boundp 'org-time-was-given) org-time-was-given)
12543 (format "%04d-%02d-%02d %02d:%02d"
12544 (nth 5 final) (nth 4 final) (nth 3 final)
12545 (nth 2 final) (nth 1 final))
12546 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
12547 (defvar def)
12548 (defvar defdecode)
12549 (defvar with-time)
12550 (defun org-read-date-display ()
12551 "Display the current date prompt interpretation in the minibuffer."
12552 (when org-read-date-display-live
12553 (when org-read-date-overlay
12554 (org-delete-overlay org-read-date-overlay))
12555 (let ((p (point)))
12556 (end-of-line 1)
12557 (while (not (equal (buffer-substring
12558 (max (point-min) (- (point) 4)) (point))
12559 " "))
12560 (insert " "))
12561 (goto-char p))
12562 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
12563 " " (or org-ans1 org-ans2)))
12564 (org-end-time-was-given nil)
12565 (f (org-read-date-analyze ans def defdecode))
12566 (fmts (if org-dcst
12567 org-time-stamp-custom-formats
12568 org-time-stamp-formats))
12569 (fmt (if (or with-time
12570 (and (boundp 'org-time-was-given) org-time-was-given))
12571 (cdr fmts)
12572 (car fmts)))
12573 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
12574 (when (and org-end-time-was-given
12575 (string-match org-plain-time-of-day-regexp txt))
12576 (setq txt (concat (substring txt 0 (match-end 0)) "-"
12577 org-end-time-was-given
12578 (substring txt (match-end 0)))))
12579 (setq org-read-date-overlay
12580 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
12581 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
12583 (defun org-read-date-analyze (ans def defdecode)
12584 "Analyse the combined answer of the date prompt."
12585 ;; FIXME: cleanup and comment
12586 (let (delta deltan deltaw deltadef year month day
12587 hour minute second wday pm h2 m2 tl wday1
12588 iso-year iso-weekday iso-week iso-year iso-date)
12590 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
12591 (setq ans "+0"))
12593 (when (setq delta (org-read-date-get-relative ans (current-time) def))
12594 (setq ans (replace-match "" t t ans)
12595 deltan (car delta)
12596 deltaw (nth 1 delta)
12597 deltadef (nth 2 delta)))
12599 ;; Check if there is an iso week date in there
12600 ;; If yes, sore the info and postpone interpreting it until the rest
12601 ;; of the parsing is done
12602 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
12603 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
12604 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
12605 iso-week (string-to-number (match-string 2 ans)))
12606 (setq ans (replace-match "" t t ans)))
12608 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
12609 (when (string-match
12610 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
12611 (setq year (if (match-end 2)
12612 (string-to-number (match-string 2 ans))
12613 (string-to-number (format-time-string "%Y")))
12614 month (string-to-number (match-string 3 ans))
12615 day (string-to-number (match-string 4 ans)))
12616 (if (< year 100) (setq year (+ 2000 year)))
12617 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
12618 t nil ans)))
12619 ;; Help matching am/pm times, because `parse-time-string' does not do that.
12620 ;; If there is a time with am/pm, and *no* time without it, we convert
12621 ;; so that matching will be successful.
12622 (loop for i from 1 to 2 do ; twice, for end time as well
12623 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
12624 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
12625 (setq hour (string-to-number (match-string 1 ans))
12626 minute (if (match-end 3)
12627 (string-to-number (match-string 3 ans))
12629 pm (equal ?p
12630 (string-to-char (downcase (match-string 4 ans)))))
12631 (if (and (= hour 12) (not pm))
12632 (setq hour 0)
12633 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
12634 (setq ans (replace-match (format "%02d:%02d" hour minute)
12635 t t ans))))
12637 ;; Check if a time range is given as a duration
12638 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
12639 (setq hour (string-to-number (match-string 1 ans))
12640 h2 (+ hour (string-to-number (match-string 3 ans)))
12641 minute (string-to-number (match-string 2 ans))
12642 m2 (+ minute (if (match-end 5) (string-to-number
12643 (match-string 5 ans))0)))
12644 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
12645 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
12646 t t ans)))
12648 ;; Check if there is a time range
12649 (when (boundp 'org-end-time-was-given)
12650 (setq org-time-was-given nil)
12651 (when (and (string-match org-plain-time-of-day-regexp ans)
12652 (match-end 8))
12653 (setq org-end-time-was-given (match-string 8 ans))
12654 (setq ans (concat (substring ans 0 (match-beginning 7))
12655 (substring ans (match-end 7))))))
12657 (setq tl (parse-time-string ans)
12658 day (or (nth 3 tl) (nth 3 defdecode))
12659 month (or (nth 4 tl)
12660 (if (and org-read-date-prefer-future
12661 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
12662 (1+ (nth 4 defdecode))
12663 (nth 4 defdecode)))
12664 year (or (nth 5 tl)
12665 (if (and org-read-date-prefer-future
12666 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
12667 (1+ (nth 5 defdecode))
12668 (nth 5 defdecode)))
12669 hour (or (nth 2 tl) (nth 2 defdecode))
12670 minute (or (nth 1 tl) (nth 1 defdecode))
12671 second (or (nth 0 tl) 0)
12672 wday (nth 6 tl))
12674 ;; Special date definitions below
12675 (cond
12676 (iso-week
12677 ;; There was an iso week
12678 (setq year (or iso-year year)
12679 day (or iso-weekday wday 1)
12680 wday nil ; to make sure that the trigger below does not match
12681 iso-date (calendar-gregorian-from-absolute
12682 (calendar-absolute-from-iso
12683 (list iso-week day year))))
12684 ; FIXME: Should we also push ISO weeks into the future?
12685 ; (when (and org-read-date-prefer-future
12686 ; (not iso-year)
12687 ; (< (calendar-absolute-from-gregorian iso-date)
12688 ; (time-to-days (current-time))))
12689 ; (setq year (1+ year)
12690 ; iso-date (calendar-gregorian-from-absolute
12691 ; (calendar-absolute-from-iso
12692 ; (list iso-week day year)))))
12693 (setq month (car iso-date)
12694 year (nth 2 iso-date)
12695 day (nth 1 iso-date)))
12696 (deltan
12697 (unless deltadef
12698 (let ((now (decode-time (current-time))))
12699 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
12700 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
12701 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
12702 ((equal deltaw "m") (setq month (+ month deltan)))
12703 ((equal deltaw "y") (setq year (+ year deltan)))))
12704 ((and wday (not (nth 3 tl)))
12705 ;; Weekday was given, but no day, so pick that day in the week
12706 ;; on or after the derived date.
12707 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
12708 (unless (equal wday wday1)
12709 (setq day (+ day (% (- wday wday1 -7) 7))))))
12710 (if (and (boundp 'org-time-was-given)
12711 (nth 2 tl))
12712 (setq org-time-was-given t))
12713 (if (< year 100) (setq year (+ 2000 year)))
12714 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
12715 (list second minute hour day month year)))
12717 (defvar parse-time-weekdays)
12719 (defun org-read-date-get-relative (s today default)
12720 "Check string S for special relative date string.
12721 TODAY and DEFAULT are internal times, for today and for a default.
12722 Return shift list (N what def-flag)
12723 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
12724 N is the number of WHATs to shift.
12725 DEF-FLAG is t when a double ++ or -- indicates shift relative to
12726 the DEFAULT date rather than TODAY."
12727 (when (and
12728 (string-match
12729 (concat
12730 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
12731 "\\([0-9]+\\)?"
12732 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
12733 "\\([ \t]\\|$\\)") s)
12734 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
12735 (let* ((dir (if (> (match-end 1) (match-beginning 1))
12736 (string-to-char (substring (match-string 1 s) -1))
12737 ?+))
12738 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
12739 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
12740 (what (if (match-end 3) (match-string 3 s) "d"))
12741 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
12742 (date (if rel default today))
12743 (wday (nth 6 (decode-time date)))
12744 delta)
12745 (if wday1
12746 (progn
12747 (setq delta (mod (+ 7 (- wday1 wday)) 7))
12748 (if (= dir ?-) (setq delta (- delta 7)))
12749 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
12750 (list delta "d" rel))
12751 (list (* n (if (= dir ?-) -1 1)) what rel)))))
12753 (defun org-eval-in-calendar (form &optional keepdate)
12754 "Eval FORM in the calendar window and return to current window.
12755 Also, store the cursor date in variable org-ans2."
12756 (let ((sw (selected-window)))
12757 (select-window (get-buffer-window "*Calendar*"))
12758 (eval form)
12759 (when (and (not keepdate) (calendar-cursor-to-date))
12760 (let* ((date (calendar-cursor-to-date))
12761 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12762 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
12763 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
12764 (select-window sw)))
12766 (defun org-calendar-select ()
12767 "Return to `org-read-date' with the date currently selected.
12768 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12769 (interactive)
12770 (when (calendar-cursor-to-date)
12771 (let* ((date (calendar-cursor-to-date))
12772 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12773 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12774 (if (active-minibuffer-window) (exit-minibuffer))))
12776 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
12777 "Insert a date stamp for the date given by the internal TIME.
12778 WITH-HM means, use the stamp format that includes the time of the day.
12779 INACTIVE means use square brackets instead of angular ones, so that the
12780 stamp will not contribute to the agenda.
12781 PRE and POST are optional strings to be inserted before and after the
12782 stamp.
12783 The command returns the inserted time stamp."
12784 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
12785 stamp)
12786 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
12787 (insert-before-markers (or pre ""))
12788 (insert-before-markers (setq stamp (format-time-string fmt time)))
12789 (when (listp extra)
12790 (setq extra (car extra))
12791 (if (and (stringp extra)
12792 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
12793 (setq extra (format "-%02d:%02d"
12794 (string-to-number (match-string 1 extra))
12795 (string-to-number (match-string 2 extra))))
12796 (setq extra nil)))
12797 (when extra
12798 (backward-char 1)
12799 (insert-before-markers extra)
12800 (forward-char 1))
12801 (insert-before-markers (or post ""))
12802 (setq org-last-inserted-timestamp stamp)))
12804 (defun org-toggle-time-stamp-overlays ()
12805 "Toggle the use of custom time stamp formats."
12806 (interactive)
12807 (setq org-display-custom-times (not org-display-custom-times))
12808 (unless org-display-custom-times
12809 (let ((p (point-min)) (bmp (buffer-modified-p)))
12810 (while (setq p (next-single-property-change p 'display))
12811 (if (and (get-text-property p 'display)
12812 (eq (get-text-property p 'face) 'org-date))
12813 (remove-text-properties
12814 p (setq p (next-single-property-change p 'display))
12815 '(display t))))
12816 (set-buffer-modified-p bmp)))
12817 (if (featurep 'xemacs)
12818 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12819 (org-restart-font-lock)
12820 (setq org-table-may-need-update t)
12821 (if org-display-custom-times
12822 (message "Time stamps are overlayed with custom format")
12823 (message "Time stamp overlays removed")))
12825 (defun org-display-custom-time (beg end)
12826 "Overlay modified time stamp format over timestamp between BEG and END."
12827 (let* ((ts (buffer-substring beg end))
12828 t1 w1 with-hm tf time str w2 (off 0))
12829 (save-match-data
12830 (setq t1 (org-parse-time-string ts t))
12831 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
12832 (setq off (- (match-end 0) (match-beginning 0)))))
12833 (setq end (- end off))
12834 (setq w1 (- end beg)
12835 with-hm (and (nth 1 t1) (nth 2 t1))
12836 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
12837 time (org-fix-decoded-time t1)
12838 str (org-add-props
12839 (format-time-string
12840 (substring tf 1 -1) (apply 'encode-time time))
12841 nil 'mouse-face 'highlight)
12842 w2 (length str))
12843 (if (not (= w2 w1))
12844 (add-text-properties (1+ beg) (+ 2 beg)
12845 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12846 (if (featurep 'xemacs)
12847 (progn
12848 (put-text-property beg end 'invisible t)
12849 (put-text-property beg end 'end-glyph (make-glyph str)))
12850 (put-text-property beg end 'display str))))
12852 (defun org-translate-time (string)
12853 "Translate all timestamps in STRING to custom format.
12854 But do this only if the variable `org-display-custom-times' is set."
12855 (when org-display-custom-times
12856 (save-match-data
12857 (let* ((start 0)
12858 (re org-ts-regexp-both)
12859 t1 with-hm inactive tf time str beg end)
12860 (while (setq start (string-match re string start))
12861 (setq beg (match-beginning 0)
12862 end (match-end 0)
12863 t1 (save-match-data
12864 (org-parse-time-string (substring string beg end) t))
12865 with-hm (and (nth 1 t1) (nth 2 t1))
12866 inactive (equal (substring string beg (1+ beg)) "[")
12867 tf (funcall (if with-hm 'cdr 'car)
12868 org-time-stamp-custom-formats)
12869 time (org-fix-decoded-time t1)
12870 str (format-time-string
12871 (concat
12872 (if inactive "[" "<") (substring tf 1 -1)
12873 (if inactive "]" ">"))
12874 (apply 'encode-time time))
12875 string (replace-match str t t string)
12876 start (+ start (length str)))))))
12877 string)
12879 (defun org-fix-decoded-time (time)
12880 "Set 0 instead of nil for the first 6 elements of time.
12881 Don't touch the rest."
12882 (let ((n 0))
12883 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12885 (defun org-days-to-time (timestamp-string)
12886 "Difference between TIMESTAMP-STRING and now in days."
12887 (- (time-to-days (org-time-string-to-time timestamp-string))
12888 (time-to-days (current-time))))
12890 (defun org-deadline-close (timestamp-string &optional ndays)
12891 "Is the time in TIMESTAMP-STRING close to the current date?"
12892 (setq ndays (or ndays (org-get-wdays timestamp-string)))
12893 (and (< (org-days-to-time timestamp-string) ndays)
12894 (not (org-entry-is-done-p))))
12896 (defun org-get-wdays (ts)
12897 "Get the deadline lead time appropriate for timestring TS."
12898 (cond
12899 ((<= org-deadline-warning-days 0)
12900 ;; 0 or negative, enforce this value no matter what
12901 (- org-deadline-warning-days))
12902 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
12903 ;; lead time is specified.
12904 (floor (* (string-to-number (match-string 1 ts))
12905 (cdr (assoc (match-string 2 ts)
12906 '(("d" . 1) ("w" . 7)
12907 ("m" . 30.4) ("y" . 365.25)))))))
12908 ;; go for the default.
12909 (t org-deadline-warning-days)))
12911 (defun org-calendar-select-mouse (ev)
12912 "Return to `org-read-date' with the date currently selected.
12913 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12914 (interactive "e")
12915 (mouse-set-point ev)
12916 (when (calendar-cursor-to-date)
12917 (let* ((date (calendar-cursor-to-date))
12918 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12919 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12920 (if (active-minibuffer-window) (exit-minibuffer))))
12922 (defun org-check-deadlines (ndays)
12923 "Check if there are any deadlines due or past due.
12924 A deadline is considered due if it happens within `org-deadline-warning-days'
12925 days from today's date. If the deadline appears in an entry marked DONE,
12926 it is not shown. The prefix arg NDAYS can be used to test that many
12927 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12928 (interactive "P")
12929 (let* ((org-warn-days
12930 (cond
12931 ((equal ndays '(4)) 100000)
12932 (ndays (prefix-numeric-value ndays))
12933 (t (abs org-deadline-warning-days))))
12934 (case-fold-search nil)
12935 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12936 (callback
12937 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12939 (message "%d deadlines past-due or due within %d days"
12940 (org-occur regexp nil callback)
12941 org-warn-days)))
12943 (defun org-check-before-date (date)
12944 "Check if there are deadlines or scheduled entries before DATE."
12945 (interactive (list (org-read-date)))
12946 (let ((case-fold-search nil)
12947 (regexp (concat "\\<\\(" org-deadline-string
12948 "\\|" org-scheduled-string
12949 "\\) *<\\([^>]+\\)>"))
12950 (callback
12951 (lambda () (time-less-p
12952 (org-time-string-to-time (match-string 2))
12953 (org-time-string-to-time date)))))
12954 (message "%d entries before %s"
12955 (org-occur regexp nil callback) date)))
12957 (defun org-check-after-date (date)
12958 "Check if there are deadlines or scheduled entries after DATE."
12959 (interactive (list (org-read-date)))
12960 (let ((case-fold-search nil)
12961 (regexp (concat "\\<\\(" org-deadline-string
12962 "\\|" org-scheduled-string
12963 "\\) *<\\([^>]+\\)>"))
12964 (callback
12965 (lambda () (not
12966 (time-less-p
12967 (org-time-string-to-time (match-string 2))
12968 (org-time-string-to-time date))))))
12969 (message "%d entries after %s"
12970 (org-occur regexp nil callback) date)))
12972 (defun org-evaluate-time-range (&optional to-buffer)
12973 "Evaluate a time range by computing the difference between start and end.
12974 Normally the result is just printed in the echo area, but with prefix arg
12975 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12976 If the time range is actually in a table, the result is inserted into the
12977 next column.
12978 For time difference computation, a year is assumed to be exactly 365
12979 days in order to avoid rounding problems."
12980 (interactive "P")
12982 (org-clock-update-time-maybe)
12983 (save-excursion
12984 (unless (org-at-date-range-p t)
12985 (goto-char (point-at-bol))
12986 (re-search-forward org-tr-regexp-both (point-at-eol) t))
12987 (if (not (org-at-date-range-p t))
12988 (error "Not at a time-stamp range, and none found in current line")))
12989 (let* ((ts1 (match-string 1))
12990 (ts2 (match-string 2))
12991 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12992 (match-end (match-end 0))
12993 (time1 (org-time-string-to-time ts1))
12994 (time2 (org-time-string-to-time ts2))
12995 (t1 (time-to-seconds time1))
12996 (t2 (time-to-seconds time2))
12997 (diff (abs (- t2 t1)))
12998 (negative (< (- t2 t1) 0))
12999 ;; (ys (floor (* 365 24 60 60)))
13000 (ds (* 24 60 60))
13001 (hs (* 60 60))
13002 (fy "%dy %dd %02d:%02d")
13003 (fy1 "%dy %dd")
13004 (fd "%dd %02d:%02d")
13005 (fd1 "%dd")
13006 (fh "%02d:%02d")
13007 y d h m align)
13008 (if havetime
13009 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13011 d (floor (/ diff ds)) diff (mod diff ds)
13012 h (floor (/ diff hs)) diff (mod diff hs)
13013 m (floor (/ diff 60)))
13014 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13016 d (floor (+ (/ diff ds) 0.5))
13017 h 0 m 0))
13018 (if (not to-buffer)
13019 (message "%s" (org-make-tdiff-string y d h m))
13020 (if (org-at-table-p)
13021 (progn
13022 (goto-char match-end)
13023 (setq align t)
13024 (and (looking-at " *|") (goto-char (match-end 0))))
13025 (goto-char match-end))
13026 (if (looking-at
13027 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
13028 (replace-match ""))
13029 (if negative (insert " -"))
13030 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
13031 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
13032 (insert " " (format fh h m))))
13033 (if align (org-table-align))
13034 (message "Time difference inserted")))))
13036 (defun org-make-tdiff-string (y d h m)
13037 (let ((fmt "")
13038 (l nil))
13039 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
13040 l (push y l)))
13041 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
13042 l (push d l)))
13043 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
13044 l (push h l)))
13045 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
13046 l (push m l)))
13047 (apply 'format fmt (nreverse l))))
13049 (defun org-time-string-to-time (s)
13050 (apply 'encode-time (org-parse-time-string s)))
13051 (defun org-time-string-to-seconds (s)
13052 (time-to-seconds (org-time-string-to-time s)))
13054 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
13055 "Convert a time stamp to an absolute day number.
13056 If there is a specifyer for a cyclic time stamp, get the closest date to
13057 DAYNR.
13058 PREFER and SHOW-ALL are passed through to `org-closest-date'."
13059 (cond
13060 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
13061 (if (org-diary-sexp-entry (match-string 1 s) "" date)
13062 daynr
13063 (+ daynr 1000)))
13064 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
13065 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
13066 (time-to-days (current-time))) (match-string 0 s)
13067 prefer show-all))
13068 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
13070 (defun org-days-to-iso-week (days)
13071 "Return the iso week number."
13072 (require 'cal-iso)
13073 (car (calendar-iso-from-absolute days)))
13075 (defun org-small-year-to-year (year)
13076 "Convert 2-digit years into 4-digit years.
13077 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
13078 The year 2000 cannot be abbreviated. Any year larger than 99
13079 is returned unchanged."
13080 (if (< year 38)
13081 (setq year (+ 2000 year))
13082 (if (< year 100)
13083 (setq year (+ 1900 year))))
13084 year)
13086 (defun org-time-from-absolute (d)
13087 "Return the time corresponding to date D.
13088 D may be an absolute day number, or a calendar-type list (month day year)."
13089 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
13090 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
13092 (defun org-calendar-holiday ()
13093 "List of holidays, for Diary display in Org-mode."
13094 (require 'holidays)
13095 (let ((hl (funcall
13096 (if (fboundp 'calendar-check-holidays)
13097 'calendar-check-holidays 'check-calendar-holidays) date)))
13098 (if hl (mapconcat 'identity hl "; "))))
13100 (defun org-diary-sexp-entry (sexp entry date)
13101 "Process a SEXP diary ENTRY for DATE."
13102 (require 'diary-lib)
13103 (let ((result (if calendar-debug-sexp
13104 (let ((stack-trace-on-error t))
13105 (eval (car (read-from-string sexp))))
13106 (condition-case nil
13107 (eval (car (read-from-string sexp)))
13108 (error
13109 (beep)
13110 (message "Bad sexp at line %d in %s: %s"
13111 (org-current-line)
13112 (buffer-file-name) sexp)
13113 (sleep-for 2))))))
13114 (cond ((stringp result) result)
13115 ((and (consp result)
13116 (stringp (cdr result))) (cdr result))
13117 (result entry)
13118 (t nil))))
13120 (defun org-diary-to-ical-string (frombuf)
13121 "Get iCalendar entries from diary entries in buffer FROMBUF.
13122 This uses the icalendar.el library."
13123 (let* ((tmpdir (if (featurep 'xemacs)
13124 (temp-directory)
13125 temporary-file-directory))
13126 (tmpfile (make-temp-name
13127 (expand-file-name "orgics" tmpdir)))
13128 buf rtn b e)
13129 (save-excursion
13130 (set-buffer frombuf)
13131 (icalendar-export-region (point-min) (point-max) tmpfile)
13132 (setq buf (find-buffer-visiting tmpfile))
13133 (set-buffer buf)
13134 (goto-char (point-min))
13135 (if (re-search-forward "^BEGIN:VEVENT" nil t)
13136 (setq b (match-beginning 0)))
13137 (goto-char (point-max))
13138 (if (re-search-backward "^END:VEVENT" nil t)
13139 (setq e (match-end 0)))
13140 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
13141 (kill-buffer buf)
13142 (delete-file tmpfile)
13143 rtn))
13145 (defun org-closest-date (start current change prefer show-all)
13146 "Find the date closest to CURRENT that is consistent with START and CHANGE.
13147 When PREFER is `past' return a date that is either CURRENT or past.
13148 When PREFER is `future', return a date that is either CURRENT or future.
13149 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
13150 ;; Make the proper lists from the dates
13151 (catch 'exit
13152 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
13153 dn dw sday cday n1 n2 n0
13154 d m y y1 y2 date1 date2 nmonths nm ny m2)
13156 (setq start (org-date-to-gregorian start)
13157 current (org-date-to-gregorian
13158 (if show-all
13159 current
13160 (time-to-days (current-time))))
13161 sday (calendar-absolute-from-gregorian start)
13162 cday (calendar-absolute-from-gregorian current))
13164 (if (<= cday sday) (throw 'exit sday))
13166 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
13167 (setq dn (string-to-number (match-string 1 change))
13168 dw (cdr (assoc (match-string 2 change) a1)))
13169 (error "Invalid change specifyer: %s" change))
13170 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
13171 (cond
13172 ((eq dw 'day)
13173 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
13174 n2 (+ n1 dn)))
13175 ((eq dw 'year)
13176 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
13177 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
13178 (setq date1 (list m d y1)
13179 n1 (calendar-absolute-from-gregorian date1)
13180 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
13181 n2 (calendar-absolute-from-gregorian date2)))
13182 ((eq dw 'month)
13183 ;; approx number of month between the two dates
13184 (setq nmonths (floor (/ (- cday sday) 30.436875)))
13185 ;; How often does dn fit in there?
13186 (setq d (nth 1 start) m (car start) y (nth 2 start)
13187 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
13188 m (+ m nm)
13189 ny (floor (/ m 12))
13190 y (+ y ny)
13191 m (- m (* ny 12)))
13192 (while (> m 12) (setq m (- m 12) y (1+ y)))
13193 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
13194 (setq m2 (+ m dn) y2 y)
13195 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13196 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
13197 (while (<= n2 cday)
13198 (setq n1 n2 m m2 y y2)
13199 (setq m2 (+ m dn) y2 y)
13200 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13201 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
13202 ;; Make sure n1 is the earlier date
13203 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
13204 (if show-all
13205 (cond
13206 ((eq prefer 'past) n1)
13207 ((eq prefer 'future) (if (= cday n1) n1 n2))
13208 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
13209 (cond
13210 ((eq prefer 'past) n1)
13211 ((eq prefer 'future) (if (= cday n1) n1 n2))
13212 (t (if (= cday n1) n1 n2)))))))
13214 (defun org-date-to-gregorian (date)
13215 "Turn any specification of DATE into a gregorian date for the calendar."
13216 (cond ((integerp date) (calendar-gregorian-from-absolute date))
13217 ((and (listp date) (= (length date) 3)) date)
13218 ((stringp date)
13219 (setq date (org-parse-time-string date))
13220 (list (nth 4 date) (nth 3 date) (nth 5 date)))
13221 ((listp date)
13222 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
13224 (defun org-parse-time-string (s &optional nodefault)
13225 "Parse the standard Org-mode time string.
13226 This should be a lot faster than the normal `parse-time-string'.
13227 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
13228 hour and minute fields will be nil if not given."
13229 (if (string-match org-ts-regexp0 s)
13230 (list 0
13231 (if (or (match-beginning 8) (not nodefault))
13232 (string-to-number (or (match-string 8 s) "0")))
13233 (if (or (match-beginning 7) (not nodefault))
13234 (string-to-number (or (match-string 7 s) "0")))
13235 (string-to-number (match-string 4 s))
13236 (string-to-number (match-string 3 s))
13237 (string-to-number (match-string 2 s))
13238 nil nil nil)
13239 (make-list 9 0)))
13241 (defun org-timestamp-up (&optional arg)
13242 "Increase the date item at the cursor by one.
13243 If the cursor is on the year, change the year. If it is on the month or
13244 the day, change that.
13245 With prefix ARG, change by that many units."
13246 (interactive "p")
13247 (org-timestamp-change (prefix-numeric-value arg)))
13249 (defun org-timestamp-down (&optional arg)
13250 "Decrease the date item at the cursor by one.
13251 If the cursor is on the year, change the year. If it is on the month or
13252 the day, change that.
13253 With prefix ARG, change by that many units."
13254 (interactive "p")
13255 (org-timestamp-change (- (prefix-numeric-value arg))))
13257 (defun org-timestamp-up-day (&optional arg)
13258 "Increase the date in the time stamp by one day.
13259 With prefix ARG, change that many days."
13260 (interactive "p")
13261 (if (and (not (org-at-timestamp-p t))
13262 (org-on-heading-p))
13263 (org-todo 'up)
13264 (org-timestamp-change (prefix-numeric-value arg) 'day)))
13266 (defun org-timestamp-down-day (&optional arg)
13267 "Decrease the date in the time stamp by one day.
13268 With prefix ARG, change that many days."
13269 (interactive "p")
13270 (if (and (not (org-at-timestamp-p t))
13271 (org-on-heading-p))
13272 (org-todo 'down)
13273 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
13275 (defun org-at-timestamp-p (&optional inactive-ok)
13276 "Determine if the cursor is in or at a timestamp."
13277 (interactive)
13278 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
13279 (pos (point))
13280 (ans (or (looking-at tsr)
13281 (save-excursion
13282 (skip-chars-backward "^[<\n\r\t")
13283 (if (> (point) (point-min)) (backward-char 1))
13284 (and (looking-at tsr)
13285 (> (- (match-end 0) pos) -1))))))
13286 (and ans
13287 (boundp 'org-ts-what)
13288 (setq org-ts-what
13289 (cond
13290 ((= pos (match-beginning 0)) 'bracket)
13291 ((= pos (1- (match-end 0))) 'bracket)
13292 ((org-pos-in-match-range pos 2) 'year)
13293 ((org-pos-in-match-range pos 3) 'month)
13294 ((org-pos-in-match-range pos 7) 'hour)
13295 ((org-pos-in-match-range pos 8) 'minute)
13296 ((or (org-pos-in-match-range pos 4)
13297 (org-pos-in-match-range pos 5)) 'day)
13298 ((and (> pos (or (match-end 8) (match-end 5)))
13299 (< pos (match-end 0)))
13300 (- pos (or (match-end 8) (match-end 5))))
13301 (t 'day))))
13302 ans))
13304 (defun org-toggle-timestamp-type ()
13305 "Toggle the type (<active> or [inactive]) of a time stamp."
13306 (interactive)
13307 (when (org-at-timestamp-p t)
13308 (let ((beg (match-beginning 0)) (end (match-end 0))
13309 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
13310 (save-excursion
13311 (goto-char beg)
13312 (while (re-search-forward "[][<>]" end t)
13313 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
13314 t t)))
13315 (message "Timestamp is now %sactive"
13316 (if (equal (char-after beg) ?<) "" "in")))))
13318 (defun org-timestamp-change (n &optional what)
13319 "Change the date in the time stamp at point.
13320 The date will be changed by N times WHAT. WHAT can be `day', `month',
13321 `year', `minute', `second'. If WHAT is not given, the cursor position
13322 in the timestamp determines what will be changed."
13323 (let ((pos (point))
13324 with-hm inactive
13325 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
13326 org-ts-what
13327 extra rem
13328 ts time time0)
13329 (if (not (org-at-timestamp-p t))
13330 (error "Not at a timestamp"))
13331 (if (and (not what) (eq org-ts-what 'bracket))
13332 (org-toggle-timestamp-type)
13333 (if (and (not what) (not (eq org-ts-what 'day))
13334 org-display-custom-times
13335 (get-text-property (point) 'display)
13336 (not (get-text-property (1- (point)) 'display)))
13337 (setq org-ts-what 'day))
13338 (setq org-ts-what (or what org-ts-what)
13339 inactive (= (char-after (match-beginning 0)) ?\[)
13340 ts (match-string 0))
13341 (replace-match "")
13342 (if (string-match
13343 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
13345 (setq extra (match-string 1 ts)))
13346 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
13347 (setq with-hm t))
13348 (setq time0 (org-parse-time-string ts))
13349 (when (and (eq org-ts-what 'minute)
13350 (eq current-prefix-arg nil))
13351 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
13352 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
13353 (setcar (cdr time0) (+ (nth 1 time0)
13354 (if (> n 0) (- rem) (- dm rem))))))
13355 (setq time
13356 (encode-time (or (car time0) 0)
13357 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
13358 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
13359 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
13360 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
13361 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
13362 (nthcdr 6 time0)))
13363 (when (and (member org-ts-what '(hour minute))
13364 extra
13365 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
13366 (setq extra (org-modify-ts-extra
13367 extra
13368 (if (eq org-ts-what 'hour) 2 5)
13369 n dm)))
13370 (when (integerp org-ts-what)
13371 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
13372 (if (eq what 'calendar)
13373 (let ((cal-date (org-get-date-from-calendar)))
13374 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
13375 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
13376 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
13377 (setcar time0 (or (car time0) 0))
13378 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
13379 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
13380 (setq time (apply 'encode-time time0))))
13381 (setq org-last-changed-timestamp
13382 (org-insert-time-stamp time with-hm inactive nil nil extra))
13383 (org-clock-update-time-maybe)
13384 (goto-char pos)
13385 ;; Try to recenter the calendar window, if any
13386 (if (and org-calendar-follow-timestamp-change
13387 (get-buffer-window "*Calendar*" t)
13388 (memq org-ts-what '(day month year)))
13389 (org-recenter-calendar (time-to-days time))))))
13391 (defun org-modify-ts-extra (s pos n dm)
13392 "Change the different parts of the lead-time and repeat fields in timestamp."
13393 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
13394 ng h m new rem)
13395 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
13396 (cond
13397 ((or (org-pos-in-match-range pos 2)
13398 (org-pos-in-match-range pos 3))
13399 (setq m (string-to-number (match-string 3 s))
13400 h (string-to-number (match-string 2 s)))
13401 (if (org-pos-in-match-range pos 2)
13402 (setq h (+ h n))
13403 (setq n (* dm (org-no-warnings (signum n))))
13404 (when (not (= 0 (setq rem (% m dm))))
13405 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
13406 (setq m (+ m n)))
13407 (if (< m 0) (setq m (+ m 60) h (1- h)))
13408 (if (> m 59) (setq m (- m 60) h (1+ h)))
13409 (setq h (min 24 (max 0 h)))
13410 (setq ng 1 new (format "-%02d:%02d" h m)))
13411 ((org-pos-in-match-range pos 6)
13412 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
13413 ((org-pos-in-match-range pos 5)
13414 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
13416 ((org-pos-in-match-range pos 9)
13417 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
13418 ((org-pos-in-match-range pos 8)
13419 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
13421 (when ng
13422 (setq s (concat
13423 (substring s 0 (match-beginning ng))
13425 (substring s (match-end ng))))))
13428 (defun org-recenter-calendar (date)
13429 "If the calendar is visible, recenter it to DATE."
13430 (let* ((win (selected-window))
13431 (cwin (get-buffer-window "*Calendar*" t))
13432 (calendar-move-hook nil))
13433 (when cwin
13434 (select-window cwin)
13435 (calendar-goto-date (if (listp date) date
13436 (calendar-gregorian-from-absolute date)))
13437 (select-window win))))
13439 (defun org-goto-calendar (&optional arg)
13440 "Go to the Emacs calendar at the current date.
13441 If there is a time stamp in the current line, go to that date.
13442 A prefix ARG can be used to force the current date."
13443 (interactive "P")
13444 (let ((tsr org-ts-regexp) diff
13445 (calendar-move-hook nil)
13446 (calendar-view-holidays-initially-flag nil)
13447 (view-calendar-holidays-initially nil)
13448 (calendar-view-diary-initially-flag nil)
13449 (view-diary-entries-initially nil))
13450 (if (or (org-at-timestamp-p)
13451 (save-excursion
13452 (beginning-of-line 1)
13453 (looking-at (concat ".*" tsr))))
13454 (let ((d1 (time-to-days (current-time)))
13455 (d2 (time-to-days
13456 (org-time-string-to-time (match-string 1)))))
13457 (setq diff (- d2 d1))))
13458 (calendar)
13459 (calendar-goto-today)
13460 (if (and diff (not arg)) (calendar-forward-day diff))))
13462 (defun org-get-date-from-calendar ()
13463 "Return a list (month day year) of date at point in calendar."
13464 (with-current-buffer "*Calendar*"
13465 (save-match-data
13466 (calendar-cursor-to-date))))
13468 (defun org-date-from-calendar ()
13469 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
13470 If there is already a time stamp at the cursor position, update it."
13471 (interactive)
13472 (if (org-at-timestamp-p t)
13473 (org-timestamp-change 0 'calendar)
13474 (let ((cal-date (org-get-date-from-calendar)))
13475 (org-insert-time-stamp
13476 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
13478 (defun org-minutes-to-hh:mm-string (m)
13479 "Compute H:MM from a number of minutes."
13480 (let ((h (/ m 60)))
13481 (setq m (- m (* 60 h)))
13482 (format org-time-clocksum-format h m)))
13484 (defun org-hh:mm-string-to-minutes (s)
13485 "Convert a string H:MM to a number of minutes."
13486 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
13487 (+ (* (string-to-number (match-string 1 s)) 60)
13488 (string-to-number (match-string 2 s)))
13491 ;;;; Files
13493 (defun org-save-all-org-buffers ()
13494 "Save all Org-mode buffers without user confirmation."
13495 (interactive)
13496 (message "Saving all Org-mode buffers...")
13497 (save-some-buffers t 'org-mode-p)
13498 (when (featurep 'org-id) (org-id-locations-save))
13499 (message "Saving all Org-mode buffers... done"))
13501 (defun org-revert-all-org-buffers ()
13502 "Revert all Org-mode buffers.
13503 Prompt for confirmation when there are unsaved changes.
13504 Be sure you know what you are doing before letting this function
13505 overwrite your changes.
13507 This function is useful in a setup where one tracks org files
13508 with a version control system, to revert on one machine after pulling
13509 changes from another. I believe the procedure must be like this:
13511 1. M-x org-save-all-org-buffers
13512 2. Pull changes from the other machine, resolve conflicts
13513 3. M-x org-revert-all-org-buffers"
13514 (interactive)
13515 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
13516 (error "Abort"))
13517 (save-excursion
13518 (save-window-excursion
13519 (mapc
13520 (lambda (b)
13521 (when (and (with-current-buffer b (org-mode-p))
13522 (with-current-buffer b buffer-file-name))
13523 (switch-to-buffer b)
13524 (revert-buffer t 'no-confirm)))
13525 (buffer-list))
13526 (when (and (featurep 'org-id) org-id-track-globally)
13527 (org-id-locations-load)))))
13529 ;;;; Agenda files
13531 ;;;###autoload
13532 (defun org-iswitchb (&optional arg)
13533 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
13534 With a prefix argument, restrict available to files.
13535 With two prefix arguments, restrict available buffers to agenda files.
13537 Due to some yet unresolved reason, the global function
13538 `iswitchb-mode' needs to be active for this function to work."
13539 (interactive "P")
13540 (require 'iswitchb)
13541 (let ((enabled iswitchb-mode) blist)
13542 (or enabled (iswitchb-mode 1))
13543 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13544 ((equal arg '(16)) (org-buffer-list 'agenda))
13545 (t (org-buffer-list))))
13546 (unwind-protect
13547 (let ((iswitchb-make-buflist-hook
13548 (lambda ()
13549 (setq iswitchb-temp-buflist
13550 (mapcar 'buffer-name blist)))))
13551 (switch-to-buffer
13552 (iswitchb-read-buffer
13553 "Switch-to: " nil t))
13554 (or enabled (iswitchb-mode -1))))))
13556 ;;;###autoload
13557 (defun org-ido-switchb (&optional arg)
13558 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
13559 With a prefix argument, restrict available to files.
13560 With two prefix arguments, restrict available buffers to agenda files."
13561 (interactive "P")
13562 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13563 ((equal arg '(16)) (org-buffer-list 'agenda))
13564 (t (org-buffer-list)))))
13565 (switch-to-buffer
13566 (org-ido-completing-read "Org buffer: "
13567 (mapcar 'list (mapcar 'buffer-name blist))
13568 nil t))))
13570 (defun org-buffer-list (&optional predicate exclude-tmp)
13571 "Return a list of Org buffers.
13572 PREDICATE can be `export', `files' or `agenda'.
13574 export restrict the list to Export buffers.
13575 files restrict the list to buffers visiting Org files.
13576 agenda restrict the list to buffers visiting agenda files.
13578 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
13579 (let* ((bfn nil)
13580 (agenda-files (and (eq predicate 'agenda)
13581 (mapcar 'file-truename (org-agenda-files t))))
13582 (filter
13583 (cond
13584 ((eq predicate 'files)
13585 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
13586 ((eq predicate 'export)
13587 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
13588 ((eq predicate 'agenda)
13589 (lambda (b)
13590 (with-current-buffer b
13591 (and (eq major-mode 'org-mode)
13592 (setq bfn (buffer-file-name b))
13593 (member (file-truename bfn) agenda-files)))))
13594 (t (lambda (b) (with-current-buffer b
13595 (or (eq major-mode 'org-mode)
13596 (string-match "\*Org .*Export"
13597 (buffer-name b)))))))))
13598 (delq nil
13599 (mapcar
13600 (lambda(b)
13601 (if (and (funcall filter b)
13602 (or (not exclude-tmp)
13603 (not (string-match "tmp" (buffer-name b)))))
13605 nil))
13606 (buffer-list)))))
13608 (defun org-agenda-files (&optional unrestricted archives)
13609 "Get the list of agenda files.
13610 Optional UNRESTRICTED means return the full list even if a restriction
13611 is currently in place.
13612 When ARCHIVES is t, include all archive files hat are really being
13613 used by the agenda files. If ARCHIVE is `ifmode', do this only if
13614 `org-agenda-archives-mode' is t."
13615 (let ((files
13616 (cond
13617 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
13618 ((stringp org-agenda-files) (org-read-agenda-file-list))
13619 ((listp org-agenda-files) org-agenda-files)
13620 (t (error "Invalid value of `org-agenda-files'")))))
13621 (setq files (apply 'append
13622 (mapcar (lambda (f)
13623 (if (file-directory-p f)
13624 (directory-files
13625 f t org-agenda-file-regexp)
13626 (list f)))
13627 files)))
13628 (when org-agenda-skip-unavailable-files
13629 (setq files (delq nil
13630 (mapcar (function
13631 (lambda (file)
13632 (and (file-readable-p file) file)))
13633 files))))
13634 (when (or (eq archives t)
13635 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
13636 (setq files (org-add-archive-files files)))
13637 files))
13639 (defun org-edit-agenda-file-list ()
13640 "Edit the list of agenda files.
13641 Depending on setup, this either uses customize to edit the variable
13642 `org-agenda-files', or it visits the file that is holding the list. In the
13643 latter case, the buffer is set up in a way that saving it automatically kills
13644 the buffer and restores the previous window configuration."
13645 (interactive)
13646 (if (stringp org-agenda-files)
13647 (let ((cw (current-window-configuration)))
13648 (find-file org-agenda-files)
13649 (org-set-local 'org-window-configuration cw)
13650 (org-add-hook 'after-save-hook
13651 (lambda ()
13652 (set-window-configuration
13653 (prog1 org-window-configuration
13654 (kill-buffer (current-buffer))))
13655 (org-install-agenda-files-menu)
13656 (message "New agenda file list installed"))
13657 nil 'local)
13658 (message "%s" (substitute-command-keys
13659 "Edit list and finish with \\[save-buffer]")))
13660 (customize-variable 'org-agenda-files)))
13662 (defun org-store-new-agenda-file-list (list)
13663 "Set new value for the agenda file list and save it correctly."
13664 (if (stringp org-agenda-files)
13665 (let ((f org-agenda-files) b)
13666 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
13667 (with-temp-file f
13668 (insert (mapconcat 'identity list "\n") "\n")))
13669 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
13670 (setq org-agenda-files list)
13671 (customize-save-variable 'org-agenda-files org-agenda-files))))
13673 (defun org-read-agenda-file-list ()
13674 "Read the list of agenda files from a file."
13675 (when (file-directory-p org-agenda-files)
13676 (error "`org-agenda-files' cannot be a single directory"))
13677 (when (stringp org-agenda-files)
13678 (with-temp-buffer
13679 (insert-file-contents org-agenda-files)
13680 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
13683 ;;;###autoload
13684 (defun org-cycle-agenda-files ()
13685 "Cycle through the files in `org-agenda-files'.
13686 If the current buffer visits an agenda file, find the next one in the list.
13687 If the current buffer does not, find the first agenda file."
13688 (interactive)
13689 (let* ((fs (org-agenda-files t))
13690 (files (append fs (list (car fs))))
13691 (tcf (if buffer-file-name (file-truename buffer-file-name)))
13692 file)
13693 (unless files (error "No agenda files"))
13694 (catch 'exit
13695 (while (setq file (pop files))
13696 (if (equal (file-truename file) tcf)
13697 (when (car files)
13698 (find-file (car files))
13699 (throw 'exit t))))
13700 (find-file (car fs)))
13701 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
13703 (defun org-agenda-file-to-front (&optional to-end)
13704 "Move/add the current file to the top of the agenda file list.
13705 If the file is not present in the list, it is added to the front. If it is
13706 present, it is moved there. With optional argument TO-END, add/move to the
13707 end of the list."
13708 (interactive "P")
13709 (let ((org-agenda-skip-unavailable-files nil)
13710 (file-alist (mapcar (lambda (x)
13711 (cons (file-truename x) x))
13712 (org-agenda-files t)))
13713 (ctf (file-truename buffer-file-name))
13714 x had)
13715 (setq x (assoc ctf file-alist) had x)
13717 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
13718 (if to-end
13719 (setq file-alist (append (delq x file-alist) (list x)))
13720 (setq file-alist (cons x (delq x file-alist))))
13721 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
13722 (org-install-agenda-files-menu)
13723 (message "File %s to %s of agenda file list"
13724 (if had "moved" "added") (if to-end "end" "front"))))
13726 (defun org-remove-file (&optional file)
13727 "Remove current file from the list of files in variable `org-agenda-files'.
13728 These are the files which are being checked for agenda entries.
13729 Optional argument FILE means, use this file instead of the current."
13730 (interactive)
13731 (let* ((org-agenda-skip-unavailable-files nil)
13732 (file (or file buffer-file-name))
13733 (true-file (file-truename file))
13734 (afile (abbreviate-file-name file))
13735 (files (delq nil (mapcar
13736 (lambda (x)
13737 (if (equal true-file
13738 (file-truename x))
13739 nil x))
13740 (org-agenda-files t)))))
13741 (if (not (= (length files) (length (org-agenda-files t))))
13742 (progn
13743 (org-store-new-agenda-file-list files)
13744 (org-install-agenda-files-menu)
13745 (message "Removed file: %s" afile))
13746 (message "File was not in list: %s (not removed)" afile))))
13748 (defun org-file-menu-entry (file)
13749 (vector file (list 'find-file file) t))
13751 (defun org-check-agenda-file (file)
13752 "Make sure FILE exists. If not, ask user what to do."
13753 (when (not (file-exists-p file))
13754 (message "non-existent file %s. [R]emove from list or [A]bort?"
13755 (abbreviate-file-name file))
13756 (let ((r (downcase (read-char-exclusive))))
13757 (cond
13758 ((equal r ?r)
13759 (org-remove-file file)
13760 (throw 'nextfile t))
13761 (t (error "Abort"))))))
13763 (defun org-get-agenda-file-buffer (file)
13764 "Get a buffer visiting FILE. If the buffer needs to be created, add
13765 it to the list of buffers which might be released later."
13766 (let ((buf (org-find-base-buffer-visiting file)))
13767 (if buf
13768 buf ; just return it
13769 ;; Make a new buffer and remember it
13770 (setq buf (find-file-noselect file))
13771 (if buf (push buf org-agenda-new-buffers))
13772 buf)))
13774 (defun org-release-buffers (blist)
13775 "Release all buffers in list, asking the user for confirmation when needed.
13776 When a buffer is unmodified, it is just killed. When modified, it is saved
13777 \(if the user agrees) and then killed."
13778 (let (buf file)
13779 (while (setq buf (pop blist))
13780 (setq file (buffer-file-name buf))
13781 (when (and (buffer-modified-p buf)
13782 file
13783 (y-or-n-p (format "Save file %s? " file)))
13784 (with-current-buffer buf (save-buffer)))
13785 (kill-buffer buf))))
13787 (defun org-prepare-agenda-buffers (files)
13788 "Create buffers for all agenda files, protect archived trees and comments."
13789 (interactive)
13790 (let ((pa '(:org-archived t))
13791 (pc '(:org-comment t))
13792 (pall '(:org-archived t :org-comment t))
13793 (inhibit-read-only t)
13794 (rea (concat ":" org-archive-tag ":"))
13795 bmp file re)
13796 (save-excursion
13797 (save-restriction
13798 (while (setq file (pop files))
13799 (catch 'nextfile
13800 (if (bufferp file)
13801 (set-buffer file)
13802 (org-check-agenda-file file)
13803 (set-buffer (org-get-agenda-file-buffer file)))
13804 (widen)
13805 (setq bmp (buffer-modified-p))
13806 (org-refresh-category-properties)
13807 (setq org-todo-keywords-for-agenda
13808 (append org-todo-keywords-for-agenda org-todo-keywords-1))
13809 (setq org-done-keywords-for-agenda
13810 (append org-done-keywords-for-agenda org-done-keywords))
13811 (setq org-todo-keyword-alist-for-agenda
13812 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
13813 (setq org-tag-alist-for-agenda
13814 (append org-tag-alist-for-agenda org-tag-alist))
13816 (save-excursion
13817 (remove-text-properties (point-min) (point-max) pall)
13818 (when org-agenda-skip-archived-trees
13819 (goto-char (point-min))
13820 (while (re-search-forward rea nil t)
13821 (if (org-on-heading-p t)
13822 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
13823 (goto-char (point-min))
13824 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
13825 (while (re-search-forward re nil t)
13826 (add-text-properties
13827 (match-beginning 0) (org-end-of-subtree t) pc)))
13828 (set-buffer-modified-p bmp)))))
13829 (setq org-todo-keyword-alist-for-agenda
13830 (org-uniquify org-todo-keyword-alist-for-agenda)
13831 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
13833 ;;;; Embedded LaTeX
13835 (defvar org-cdlatex-mode-map (make-sparse-keymap)
13836 "Keymap for the minor `org-cdlatex-mode'.")
13838 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
13839 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
13840 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
13841 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
13842 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
13844 (defvar org-cdlatex-texmathp-advice-is-done nil
13845 "Flag remembering if we have applied the advice to texmathp already.")
13847 (define-minor-mode org-cdlatex-mode
13848 "Toggle the minor `org-cdlatex-mode'.
13849 This mode supports entering LaTeX environment and math in LaTeX fragments
13850 in Org-mode.
13851 \\{org-cdlatex-mode-map}"
13852 nil " OCDL" nil
13853 (when org-cdlatex-mode (require 'cdlatex))
13854 (unless org-cdlatex-texmathp-advice-is-done
13855 (setq org-cdlatex-texmathp-advice-is-done t)
13856 (defadvice texmathp (around org-math-always-on activate)
13857 "Always return t in org-mode buffers.
13858 This is because we want to insert math symbols without dollars even outside
13859 the LaTeX math segments. If Orgmode thinks that point is actually inside
13860 an embedded LaTeX fragment, let texmathp do its job.
13861 \\[org-cdlatex-mode-map]"
13862 (interactive)
13863 (let (p)
13864 (cond
13865 ((not (org-mode-p)) ad-do-it)
13866 ((eq this-command 'cdlatex-math-symbol)
13867 (setq ad-return-value t
13868 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
13870 (let ((p (org-inside-LaTeX-fragment-p)))
13871 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
13872 (setq ad-return-value t
13873 texmathp-why '("Org-mode embedded math" . 0))
13874 (if p ad-do-it)))))))))
13876 (defun turn-on-org-cdlatex ()
13877 "Unconditionally turn on `org-cdlatex-mode'."
13878 (org-cdlatex-mode 1))
13880 (defun org-inside-LaTeX-fragment-p ()
13881 "Test if point is inside a LaTeX fragment.
13882 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
13883 sequence appearing also before point.
13884 Even though the matchers for math are configurable, this function assumes
13885 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
13886 delimiters are skipped when they have been removed by customization.
13887 The return value is nil, or a cons cell with the delimiter and
13888 and the position of this delimiter.
13890 This function does a reasonably good job, but can locally be fooled by
13891 for example currency specifications. For example it will assume being in
13892 inline math after \"$22.34\". The LaTeX fragment formatter will only format
13893 fragments that are properly closed, but during editing, we have to live
13894 with the uncertainty caused by missing closing delimiters. This function
13895 looks only before point, not after."
13896 (catch 'exit
13897 (let ((pos (point))
13898 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
13899 (lim (progn
13900 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
13901 (point)))
13902 dd-on str (start 0) m re)
13903 (goto-char pos)
13904 (when dodollar
13905 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
13906 re (nth 1 (assoc "$" org-latex-regexps)))
13907 (while (string-match re str start)
13908 (cond
13909 ((= (match-end 0) (length str))
13910 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
13911 ((= (match-end 0) (- (length str) 5))
13912 (throw 'exit nil))
13913 (t (setq start (match-end 0))))))
13914 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
13915 (goto-char pos)
13916 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
13917 (and (match-beginning 2) (throw 'exit nil))
13918 ;; count $$
13919 (while (re-search-backward "\\$\\$" lim t)
13920 (setq dd-on (not dd-on)))
13921 (goto-char pos)
13922 (if dd-on (cons "$$" m))))))
13925 (defun org-try-cdlatex-tab ()
13926 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
13927 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
13928 - inside a LaTeX fragment, or
13929 - after the first word in a line, where an abbreviation expansion could
13930 insert a LaTeX environment."
13931 (when org-cdlatex-mode
13932 (cond
13933 ((save-excursion
13934 (skip-chars-backward "a-zA-Z0-9*")
13935 (skip-chars-backward " \t")
13936 (bolp))
13937 (cdlatex-tab) t)
13938 ((org-inside-LaTeX-fragment-p)
13939 (cdlatex-tab) t)
13940 (t nil))))
13942 (defun org-cdlatex-underscore-caret (&optional arg)
13943 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
13944 Revert to the normal definition outside of these fragments."
13945 (interactive "P")
13946 (if (org-inside-LaTeX-fragment-p)
13947 (call-interactively 'cdlatex-sub-superscript)
13948 (let (org-cdlatex-mode)
13949 (call-interactively (key-binding (vector last-input-event))))))
13951 (defun org-cdlatex-math-modify (&optional arg)
13952 "Execute `cdlatex-math-modify' in LaTeX fragments.
13953 Revert to the normal definition outside of these fragments."
13954 (interactive "P")
13955 (if (org-inside-LaTeX-fragment-p)
13956 (call-interactively 'cdlatex-math-modify)
13957 (let (org-cdlatex-mode)
13958 (call-interactively (key-binding (vector last-input-event))))))
13960 (defvar org-latex-fragment-image-overlays nil
13961 "List of overlays carrying the images of latex fragments.")
13962 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
13964 (defun org-remove-latex-fragment-image-overlays ()
13965 "Remove all overlays with LaTeX fragment images in current buffer."
13966 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
13967 (setq org-latex-fragment-image-overlays nil))
13969 (defun org-preview-latex-fragment (&optional subtree)
13970 "Preview the LaTeX fragment at point, or all locally or globally.
13971 If the cursor is in a LaTeX fragment, create the image and overlay
13972 it over the source code. If there is no fragment at point, display
13973 all fragments in the current text, from one headline to the next. With
13974 prefix SUBTREE, display all fragments in the current subtree. With a
13975 double prefix `C-u C-u', or when the cursor is before the first headline,
13976 display all fragments in the buffer.
13977 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
13978 (interactive "P")
13979 (org-remove-latex-fragment-image-overlays)
13980 (save-excursion
13981 (save-restriction
13982 (let (beg end at msg)
13983 (cond
13984 ((or (equal subtree '(16))
13985 (not (save-excursion
13986 (re-search-backward (concat "^" outline-regexp) nil t))))
13987 (setq beg (point-min) end (point-max)
13988 msg "Creating images for buffer...%s"))
13989 ((equal subtree '(4))
13990 (org-back-to-heading)
13991 (setq beg (point) end (org-end-of-subtree t)
13992 msg "Creating images for subtree...%s"))
13994 (if (setq at (org-inside-LaTeX-fragment-p))
13995 (goto-char (max (point-min) (- (cdr at) 2)))
13996 (org-back-to-heading))
13997 (setq beg (point) end (progn (outline-next-heading) (point))
13998 msg (if at "Creating image...%s"
13999 "Creating images for entry...%s"))))
14000 (message msg "")
14001 (narrow-to-region beg end)
14002 (goto-char beg)
14003 (org-format-latex
14004 (concat "ltxpng/" (file-name-sans-extension
14005 (file-name-nondirectory
14006 buffer-file-name)))
14007 default-directory 'overlays msg at 'forbuffer)
14008 (message msg "done. Use `C-c C-c' to remove images.")))))
14010 (defvar org-latex-regexps
14011 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
14012 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
14013 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
14014 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14015 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14016 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
14017 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
14018 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
14019 "Regular expressions for matching embedded LaTeX.")
14021 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
14022 "Replace LaTeX fragments with links to an image, and produce images."
14023 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
14024 (let* ((prefixnodir (file-name-nondirectory prefix))
14025 (absprefix (expand-file-name prefix dir))
14026 (todir (file-name-directory absprefix))
14027 (opt org-format-latex-options)
14028 (matchers (plist-get opt :matchers))
14029 (re-list org-latex-regexps)
14030 (cnt 0) txt link beg end re e checkdir
14031 executables-checked
14032 m n block linkfile movefile ov)
14033 ;; Check if there are old images files with this prefix, and remove them
14034 (when (file-directory-p todir)
14035 (mapc 'delete-file
14036 (directory-files
14037 todir 'full
14038 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
14039 ;; Check the different regular expressions
14040 (while (setq e (pop re-list))
14041 (setq m (car e) re (nth 1 e) n (nth 2 e)
14042 block (if (nth 3 e) "\n\n" ""))
14043 (when (member m matchers)
14044 (goto-char (point-min))
14045 (while (re-search-forward re nil t)
14046 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
14047 (not (get-text-property (match-beginning n)
14048 'org-protected)))
14049 (setq txt (match-string n)
14050 beg (match-beginning n) end (match-end n)
14051 cnt (1+ cnt)
14052 linkfile (format "%s_%04d.png" prefix cnt)
14053 movefile (format "%s_%04d.png" absprefix cnt)
14054 link (concat block "[[file:" linkfile "]]" block))
14055 (if msg (message msg cnt))
14056 (goto-char beg)
14057 (unless checkdir ; make sure the directory exists
14058 (setq checkdir t)
14059 (or (file-directory-p todir) (make-directory todir)))
14061 (unless executables-checked
14062 (org-check-external-command
14063 "latex" "needed to convert LaTeX fragments to images")
14064 (org-check-external-command
14065 "dvipng" "needed to convert LaTeX fragments to images")
14066 (setq executables-checked t))
14068 (org-create-formula-image
14069 txt movefile opt forbuffer)
14070 (if overlays
14071 (progn
14072 (setq ov (org-make-overlay beg end))
14073 (if (featurep 'xemacs)
14074 (progn
14075 (org-overlay-put ov 'invisible t)
14076 (org-overlay-put
14077 ov 'end-glyph
14078 (make-glyph (vector 'png :file movefile))))
14079 (org-overlay-put
14080 ov 'display
14081 (list 'image :type 'png :file movefile :ascent 'center)))
14082 (push ov org-latex-fragment-image-overlays)
14083 (goto-char end))
14084 (delete-region beg end)
14085 (insert link))))))))
14087 ;; This function borrows from Ganesh Swami's latex2png.el
14088 (defun org-create-formula-image (string tofile options buffer)
14089 (let* ((tmpdir (if (featurep 'xemacs)
14090 (temp-directory)
14091 temporary-file-directory))
14092 (texfilebase (make-temp-name
14093 (expand-file-name "orgtex" tmpdir)))
14094 (texfile (concat texfilebase ".tex"))
14095 (dvifile (concat texfilebase ".dvi"))
14096 (pngfile (concat texfilebase ".png"))
14097 (fnh (if (featurep 'xemacs)
14098 (font-height (get-face-font 'default))
14099 (face-attribute 'default :height nil)))
14100 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
14101 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
14102 (fg (or (plist-get options (if buffer :foreground :html-foreground))
14103 "Black"))
14104 (bg (or (plist-get options (if buffer :background :html-background))
14105 "Transparent")))
14106 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
14107 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
14108 (with-temp-file texfile
14109 (insert org-format-latex-header
14110 "\n\\begin{document}\n" string "\n\\end{document}\n"))
14111 (let ((dir default-directory))
14112 (condition-case nil
14113 (progn
14114 (cd tmpdir)
14115 (call-process "latex" nil nil nil texfile))
14116 (error nil))
14117 (cd dir))
14118 (if (not (file-exists-p dvifile))
14119 (progn (message "Failed to create dvi file from %s" texfile) nil)
14120 (condition-case nil
14121 (call-process "dvipng" nil nil nil
14122 "-E" "-fg" fg "-bg" bg
14123 "-D" dpi
14124 ;;"-x" scale "-y" scale
14125 "-T" "tight"
14126 "-o" pngfile
14127 dvifile)
14128 (error nil))
14129 (if (not (file-exists-p pngfile))
14130 (progn (message "Failed to create png file from %s" texfile) nil)
14131 ;; Use the requested file name and clean up
14132 (copy-file pngfile tofile 'replace)
14133 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
14134 (delete-file (concat texfilebase e)))
14135 pngfile))))
14137 (defun org-dvipng-color (attr)
14138 "Return an rgb color specification for dvipng."
14139 (apply 'format "rgb %s %s %s"
14140 (mapcar 'org-normalize-color
14141 (color-values (face-attribute 'default attr nil)))))
14143 (defun org-normalize-color (value)
14144 "Return string to be used as color value for an RGB component."
14145 (format "%g" (/ value 65535.0)))
14147 ;;;; Key bindings
14149 ;; Make `C-c C-x' a prefix key
14150 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
14152 ;; TAB key with modifiers
14153 (org-defkey org-mode-map "\C-i" 'org-cycle)
14154 (org-defkey org-mode-map [(tab)] 'org-cycle)
14155 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
14156 (org-defkey org-mode-map [(meta tab)] 'org-complete)
14157 (org-defkey org-mode-map "\M-\t" 'org-complete)
14158 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
14159 ;; The following line is necessary under Suse GNU/Linux
14160 (unless (featurep 'xemacs)
14161 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
14162 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
14163 (define-key org-mode-map [backtab] 'org-shifttab)
14165 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
14166 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
14167 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
14169 ;; Cursor keys with modifiers
14170 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
14171 (org-defkey org-mode-map [(meta right)] 'org-metaright)
14172 (org-defkey org-mode-map [(meta up)] 'org-metaup)
14173 (org-defkey org-mode-map [(meta down)] 'org-metadown)
14175 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
14176 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
14177 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
14178 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
14180 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
14181 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
14182 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
14183 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
14185 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
14186 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
14188 ;;; Extra keys for tty access.
14189 ;; We only set them when really needed because otherwise the
14190 ;; menus don't show the simple keys
14192 (when (or org-use-extra-keys
14193 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
14194 (not window-system))
14195 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
14196 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
14197 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
14198 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
14199 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
14200 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
14201 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
14202 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
14203 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
14204 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
14205 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
14206 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
14207 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
14208 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
14209 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
14210 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
14211 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
14212 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
14213 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
14214 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
14215 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
14216 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
14217 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
14218 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
14219 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
14220 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
14221 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
14222 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
14224 ;; All the other keys
14226 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
14227 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
14228 (if (boundp 'narrow-map)
14229 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
14230 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
14231 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
14232 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
14233 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
14234 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
14235 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
14236 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
14237 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
14238 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
14239 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
14240 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
14241 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
14242 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
14243 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
14244 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
14245 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
14246 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
14247 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
14248 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
14249 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
14250 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
14251 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
14252 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
14253 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
14254 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
14255 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
14256 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
14257 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
14258 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
14259 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
14260 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
14261 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
14262 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
14263 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
14264 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
14265 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
14266 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
14267 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
14268 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
14269 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
14270 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14271 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
14272 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
14273 (org-defkey org-mode-map "\C-c^" 'org-sort)
14274 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
14275 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
14276 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
14277 (org-defkey org-mode-map "\C-m" 'org-return)
14278 (org-defkey org-mode-map "\C-j" 'org-return-indent)
14279 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
14280 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
14281 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
14282 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
14283 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
14284 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
14285 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
14286 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
14287 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
14288 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
14289 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
14290 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
14291 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
14292 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
14293 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
14294 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
14296 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
14297 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
14298 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
14299 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
14301 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
14302 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
14303 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
14304 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
14305 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
14306 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
14307 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
14308 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
14309 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
14310 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
14311 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
14312 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
14313 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
14315 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
14316 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
14317 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
14318 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
14320 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
14322 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
14324 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
14325 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
14327 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
14330 (when (featurep 'xemacs)
14331 (org-defkey org-mode-map 'button3 'popup-mode-menu))
14334 (defvar org-self-insert-command-undo-counter 0)
14336 (defvar org-table-auto-blank-field) ; defined in org-table.el
14337 (defun org-self-insert-command (N)
14338 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
14339 If the cursor is in a table looking at whitespace, the whitespace is
14340 overwritten, and the table is not marked as requiring realignment."
14341 (interactive "p")
14342 (if (and
14343 (org-table-p)
14344 (progn
14345 ;; check if we blank the field, and if that triggers align
14346 (and (featurep 'org-table) org-table-auto-blank-field
14347 (member last-command
14348 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
14349 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
14350 ;; got extra space, this field does not determine column width
14351 (let (org-table-may-need-update) (org-table-blank-field))
14352 ;; no extra space, this field may determine column width
14353 (org-table-blank-field)))
14355 (eq N 1)
14356 (looking-at "[^|\n]* |"))
14357 (let (org-table-may-need-update)
14358 (goto-char (1- (match-end 0)))
14359 (delete-backward-char 1)
14360 (goto-char (match-beginning 0))
14361 (self-insert-command N))
14362 (setq org-table-may-need-update t)
14363 (self-insert-command N)
14364 (org-fix-tags-on-the-fly)
14365 (if org-self-insert-cluster-for-undo
14366 (if (not (eq last-command 'org-self-insert-command))
14367 (setq org-self-insert-command-undo-counter 1)
14368 (if (>= org-self-insert-command-undo-counter 20)
14369 (setq org-self-insert-command-undo-counter 1)
14370 (and (> org-self-insert-command-undo-counter 0)
14371 buffer-undo-list
14372 (not (cadr buffer-undo-list)) ; remove nil entry
14373 (setcdr buffer-undo-list (cddr buffer-undo-list)))
14374 (setq org-self-insert-command-undo-counter
14375 (1+ org-self-insert-command-undo-counter)))))))
14377 (defun org-fix-tags-on-the-fly ()
14378 (when (and (equal (char-after (point-at-bol)) ?*)
14379 (org-on-heading-p))
14380 (org-align-tags-here org-tags-column)))
14382 (defun org-delete-backward-char (N)
14383 "Like `delete-backward-char', insert whitespace at field end in tables.
14384 When deleting backwards, in tables this function will insert whitespace in
14385 front of the next \"|\" separator, to keep the table aligned. The table will
14386 still be marked for re-alignment if the field did fill the entire column,
14387 because, in this case the deletion might narrow the column."
14388 (interactive "p")
14389 (if (and (org-table-p)
14390 (eq N 1)
14391 (string-match "|" (buffer-substring (point-at-bol) (point)))
14392 (looking-at ".*?|"))
14393 (let ((pos (point))
14394 (noalign (looking-at "[^|\n\r]* |"))
14395 (c org-table-may-need-update))
14396 (backward-delete-char N)
14397 (skip-chars-forward "^|")
14398 (insert " ")
14399 (goto-char (1- pos))
14400 ;; noalign: if there were two spaces at the end, this field
14401 ;; does not determine the width of the column.
14402 (if noalign (setq org-table-may-need-update c)))
14403 (backward-delete-char N)
14404 (org-fix-tags-on-the-fly)))
14406 (defun org-delete-char (N)
14407 "Like `delete-char', but insert whitespace at field end in tables.
14408 When deleting characters, in tables this function will insert whitespace in
14409 front of the next \"|\" separator, to keep the table aligned. The table will
14410 still be marked for re-alignment if the field did fill the entire column,
14411 because, in this case the deletion might narrow the column."
14412 (interactive "p")
14413 (if (and (org-table-p)
14414 (not (bolp))
14415 (not (= (char-after) ?|))
14416 (eq N 1))
14417 (if (looking-at ".*?|")
14418 (let ((pos (point))
14419 (noalign (looking-at "[^|\n\r]* |"))
14420 (c org-table-may-need-update))
14421 (replace-match (concat
14422 (substring (match-string 0) 1 -1)
14423 " |"))
14424 (goto-char pos)
14425 ;; noalign: if there were two spaces at the end, this field
14426 ;; does not determine the width of the column.
14427 (if noalign (setq org-table-may-need-update c)))
14428 (delete-char N))
14429 (delete-char N)
14430 (org-fix-tags-on-the-fly)))
14432 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
14433 (put 'org-self-insert-command 'delete-selection t)
14434 (put 'orgtbl-self-insert-command 'delete-selection t)
14435 (put 'org-delete-char 'delete-selection 'supersede)
14436 (put 'org-delete-backward-char 'delete-selection 'supersede)
14437 (put 'org-yank 'delete-selection 'yank)
14439 ;; Make `flyspell-mode' delay after some commands
14440 (put 'org-self-insert-command 'flyspell-delayed t)
14441 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
14442 (put 'org-delete-char 'flyspell-delayed t)
14443 (put 'org-delete-backward-char 'flyspell-delayed t)
14445 ;; Make pabbrev-mode expand after org-mode commands
14446 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
14447 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
14449 ;; How to do this: Measure non-white length of current string
14450 ;; If equal to column width, we should realign.
14452 (defun org-remap (map &rest commands)
14453 "In MAP, remap the functions given in COMMANDS.
14454 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
14455 (let (new old)
14456 (while commands
14457 (setq old (pop commands) new (pop commands))
14458 (if (fboundp 'command-remapping)
14459 (org-defkey map (vector 'remap old) new)
14460 (substitute-key-definition old new map global-map)))))
14462 (when (eq org-enable-table-editor 'optimized)
14463 ;; If the user wants maximum table support, we need to hijack
14464 ;; some standard editing functions
14465 (org-remap org-mode-map
14466 'self-insert-command 'org-self-insert-command
14467 'delete-char 'org-delete-char
14468 'delete-backward-char 'org-delete-backward-char)
14469 (org-defkey org-mode-map "|" 'org-force-self-insert))
14471 (defvar org-ctrl-c-ctrl-c-hook nil
14472 "Hook for functions attaching themselves to `C-c C-c'.
14473 This can be used to add additional functionality to the C-c C-c key which
14474 executes context-dependent commands.
14475 Each function will be called with no arguments. The function must check
14476 if the context is appropriate for it to act. If yes, it should do its
14477 thing and then return a non-nil value. If the context is wrong,
14478 just do nothing and return nil.")
14480 (defvar org-tab-first-hook nil
14481 "Hook for functions to attach themselves to TAB.
14482 See `org-ctrl-c-ctrl-c-hook' for more information.
14483 This hook runs as the first action when TAB is pressed, even before
14484 `org-cycle' messes around with the `outline-regexp' to cater for
14485 inline tasks and plain list item folding.
14486 If any function in this hook returns t, not other actions like table
14487 field motion visibility cycling will be done.")
14489 (defvar org-tab-after-check-for-table-hook nil
14490 "Hook for functions to attach themselves to TAB.
14491 See `org-ctrl-c-ctrl-c-hook' for more information.
14492 This hook runs after it has been established that the cursor is not in a
14493 table, but before checking if the cursor is in a headline or if global cycling
14494 should be done.
14495 If any function in this hook returns t, not other actions like visibility
14496 cycling will be done.")
14498 (defvar org-tab-after-check-for-cycling-hook nil
14499 "Hook for functions to attach themselves to TAB.
14500 See `org-ctrl-c-ctrl-c-hook' for more information.
14501 This hook runs after it has been established that not table field motion and
14502 not visibility should be done because of current context. This is probably
14503 the place where a package like yasnippets can hook in.")
14505 (defvar org-metaleft-hook nil
14506 "Hook for functions attaching themselves to `M-left'.
14507 See `org-ctrl-c-ctrl-c-hook' for more information.")
14508 (defvar org-metaright-hook nil
14509 "Hook for functions attaching themselves to `M-right'.
14510 See `org-ctrl-c-ctrl-c-hook' for more information.")
14511 (defvar org-metaup-hook nil
14512 "Hook for functions attaching themselves to `M-up'.
14513 See `org-ctrl-c-ctrl-c-hook' for more information.")
14514 (defvar org-metadown-hook nil
14515 "Hook for functions attaching themselves to `M-down'.
14516 See `org-ctrl-c-ctrl-c-hook' for more information.")
14517 (defvar org-shiftmetaleft-hook nil
14518 "Hook for functions attaching themselves to `M-S-left'.
14519 See `org-ctrl-c-ctrl-c-hook' for more information.")
14520 (defvar org-shiftmetaright-hook nil
14521 "Hook for functions attaching themselves to `M-S-right'.
14522 See `org-ctrl-c-ctrl-c-hook' for more information.")
14523 (defvar org-shiftmetaup-hook nil
14524 "Hook for functions attaching themselves to `M-S-up'.
14525 See `org-ctrl-c-ctrl-c-hook' for more information.")
14526 (defvar org-shiftmetadown-hook nil
14527 "Hook for functions attaching themselves to `M-S-down'.
14528 See `org-ctrl-c-ctrl-c-hook' for more information.")
14529 (defvar org-metareturn-hook nil
14530 "Hook for functions attaching themselves to `M-RET'.
14531 See `org-ctrl-c-ctrl-c-hook' for more information.")
14533 (defun org-modifier-cursor-error ()
14534 "Throw an error, a modified cursor command was applied in wrong context."
14535 (error "This command is active in special context like tables, headlines or items"))
14537 (defun org-shiftselect-error ()
14538 "Throw an error because Shift-Cursor command was applied in wrong context."
14539 (if (and (boundp 'shift-select-mode) shift-select-mode)
14540 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
14541 (error "This command works only in special context like headlines or timestamps.")))
14543 (defun org-call-for-shift-select (cmd)
14544 (let ((this-command-keys-shift-translated t))
14545 (call-interactively cmd)))
14547 (defun org-shifttab (&optional arg)
14548 "Global visibility cycling or move to previous table field.
14549 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
14550 on context.
14551 See the individual commands for more information."
14552 (interactive "P")
14553 (cond
14554 ((org-at-table-p) (call-interactively 'org-table-previous-field))
14555 ((integerp arg)
14556 (message "Content view to level: %d" arg)
14557 (org-content (prefix-numeric-value arg))
14558 (setq org-cycle-global-status 'overview))
14559 (t (call-interactively 'org-global-cycle))))
14561 (defun org-shiftmetaleft ()
14562 "Promote subtree or delete table column.
14563 Calls `org-promote-subtree', `org-outdent-item',
14564 or `org-table-delete-column', depending on context.
14565 See the individual commands for more information."
14566 (interactive)
14567 (cond
14568 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
14569 ((org-at-table-p) (call-interactively 'org-table-delete-column))
14570 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
14571 ((org-at-item-p) (call-interactively 'org-outdent-item))
14572 (t (org-modifier-cursor-error))))
14574 (defun org-shiftmetaright ()
14575 "Demote subtree or insert table column.
14576 Calls `org-demote-subtree', `org-indent-item',
14577 or `org-table-insert-column', depending on context.
14578 See the individual commands for more information."
14579 (interactive)
14580 (cond
14581 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
14582 ((org-at-table-p) (call-interactively 'org-table-insert-column))
14583 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
14584 ((org-at-item-p) (call-interactively 'org-indent-item))
14585 (t (org-modifier-cursor-error))))
14587 (defun org-shiftmetaup (&optional arg)
14588 "Move subtree up or kill table row.
14589 Calls `org-move-subtree-up' or `org-table-kill-row' or
14590 `org-move-item-up' depending on context. See the individual commands
14591 for more information."
14592 (interactive "P")
14593 (cond
14594 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
14595 ((org-at-table-p) (call-interactively 'org-table-kill-row))
14596 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14597 ((org-at-item-p) (call-interactively 'org-move-item-up))
14598 (t (org-modifier-cursor-error))))
14600 (defun org-shiftmetadown (&optional arg)
14601 "Move subtree down or insert table row.
14602 Calls `org-move-subtree-down' or `org-table-insert-row' or
14603 `org-move-item-down', depending on context. See the individual
14604 commands for more information."
14605 (interactive "P")
14606 (cond
14607 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
14608 ((org-at-table-p) (call-interactively 'org-table-insert-row))
14609 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14610 ((org-at-item-p) (call-interactively 'org-move-item-down))
14611 (t (org-modifier-cursor-error))))
14613 (defun org-metaleft (&optional arg)
14614 "Promote heading or move table column to left.
14615 Calls `org-do-promote' or `org-table-move-column', depending on context.
14616 With no specific context, calls the Emacs default `backward-word'.
14617 See the individual commands for more information."
14618 (interactive "P")
14619 (cond
14620 ((run-hook-with-args-until-success 'org-metaleft-hook))
14621 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
14622 ((or (org-on-heading-p)
14623 (and (org-region-active-p)
14624 (save-excursion
14625 (goto-char (region-beginning))
14626 (org-on-heading-p))))
14627 (call-interactively 'org-do-promote))
14628 ((or (org-at-item-p)
14629 (and (org-region-active-p)
14630 (save-excursion
14631 (goto-char (region-beginning))
14632 (org-at-item-p))))
14633 (call-interactively 'org-outdent-item))
14634 (t (call-interactively 'backward-word))))
14636 (defun org-metaright (&optional arg)
14637 "Demote subtree or move table column to right.
14638 Calls `org-do-demote' or `org-table-move-column', depending on context.
14639 With no specific context, calls the Emacs default `forward-word'.
14640 See the individual commands for more information."
14641 (interactive "P")
14642 (cond
14643 ((run-hook-with-args-until-success 'org-metaright-hook))
14644 ((org-at-table-p) (call-interactively 'org-table-move-column))
14645 ((or (org-on-heading-p)
14646 (and (org-region-active-p)
14647 (save-excursion
14648 (goto-char (region-beginning))
14649 (org-on-heading-p))))
14650 (call-interactively 'org-do-demote))
14651 ((or (org-at-item-p)
14652 (and (org-region-active-p)
14653 (save-excursion
14654 (goto-char (region-beginning))
14655 (org-at-item-p))))
14656 (call-interactively 'org-indent-item))
14657 (t (call-interactively 'forward-word))))
14659 (defun org-metaup (&optional arg)
14660 "Move subtree up or move table row up.
14661 Calls `org-move-subtree-up' or `org-table-move-row' or
14662 `org-move-item-up', depending on context. See the individual commands
14663 for more information."
14664 (interactive "P")
14665 (cond
14666 ((run-hook-with-args-until-success 'org-metaup-hook))
14667 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
14668 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14669 ((org-at-item-p) (call-interactively 'org-move-item-up))
14670 (t (transpose-lines 1) (beginning-of-line -1))))
14672 (defun org-metadown (&optional arg)
14673 "Move subtree down or move table row down.
14674 Calls `org-move-subtree-down' or `org-table-move-row' or
14675 `org-move-item-down', depending on context. See the individual
14676 commands for more information."
14677 (interactive "P")
14678 (cond
14679 ((run-hook-with-args-until-success 'org-metadown-hook))
14680 ((org-at-table-p) (call-interactively 'org-table-move-row))
14681 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14682 ((org-at-item-p) (call-interactively 'org-move-item-down))
14683 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
14685 (defun org-shiftup (&optional arg)
14686 "Increase item in timestamp or increase priority of current headline.
14687 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
14688 depending on context. See the individual commands for more information."
14689 (interactive "P")
14690 (cond
14691 ((and org-support-shift-select (org-region-active-p))
14692 (org-call-for-shift-select 'previous-line))
14693 ((org-at-timestamp-p t)
14694 (call-interactively (if org-edit-timestamp-down-means-later
14695 'org-timestamp-down 'org-timestamp-up)))
14696 ((and (not (eq org-support-shift-select 'always))
14697 org-enable-priority-commands
14698 (org-on-heading-p))
14699 (call-interactively 'org-priority-up))
14700 ((and (not org-support-shift-select) (org-at-item-p))
14701 (call-interactively 'org-previous-item))
14702 ((org-clocktable-try-shift 'up arg))
14703 (org-support-shift-select
14704 (org-call-for-shift-select 'previous-line))
14705 (t (org-shiftselect-error))))
14707 (defun org-shiftdown (&optional arg)
14708 "Decrease item in timestamp or decrease priority of current headline.
14709 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
14710 depending on context. See the individual commands for more information."
14711 (interactive "P")
14712 (cond
14713 ((and org-support-shift-select (org-region-active-p))
14714 (org-call-for-shift-select 'next-line))
14715 ((org-at-timestamp-p t)
14716 (call-interactively (if org-edit-timestamp-down-means-later
14717 'org-timestamp-up 'org-timestamp-down)))
14718 ((and (not (eq org-support-shift-select 'always))
14719 org-enable-priority-commands
14720 (org-on-heading-p))
14721 (call-interactively 'org-priority-down))
14722 ((and (not org-support-shift-select) (org-at-item-p))
14723 (call-interactively 'org-next-item))
14724 ((org-clocktable-try-shift 'down arg))
14725 (org-support-shift-select
14726 (org-call-for-shift-select 'next-line))
14727 (t (org-shiftselect-error))))
14729 (defun org-shiftright (&optional arg)
14730 "Cycle the thing at point or in the current line, depending on context.
14731 Depending on context, this does one of the following:
14733 - switch a timestamp at point one day into the future
14734 - on a headline, switch to the next TODO keyword.
14735 - on an item, switch entire list to the next bullet type
14736 - on a property line, switch to the next allowed value
14737 - on a clocktable definition line, move time block into the future"
14738 (interactive "P")
14739 (cond
14740 ((and org-support-shift-select (org-region-active-p))
14741 (org-call-for-shift-select 'forward-char))
14742 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
14743 ((and (not (eq org-support-shift-select 'always))
14744 (org-on-heading-p))
14745 (let ((org-inhibit-logging
14746 (not org-treat-S-cursor-todo-selection-as-state-change)))
14747 (org-call-with-arg 'org-todo 'right)))
14748 ((or (and org-support-shift-select
14749 (not (eq org-support-shift-select 'always))
14750 (org-at-item-bullet-p))
14751 (and (not org-support-shift-select) (org-at-item-p)))
14752 (org-call-with-arg 'org-cycle-list-bullet nil))
14753 ((and (not (eq org-support-shift-select 'always))
14754 (org-at-property-p))
14755 (call-interactively 'org-property-next-allowed-value))
14756 ((org-clocktable-try-shift 'right arg))
14757 (org-support-shift-select
14758 (org-call-for-shift-select 'forward-char))
14759 (t (org-shiftselect-error))))
14761 (defun org-shiftleft (&optional arg)
14762 "Cycle the thing at point or in the current line, depending on context.
14763 Depending on context, this does one of the following:
14765 - switch a timestamp at point one day into the past
14766 - on a headline, switch to the previous TODO keyword.
14767 - on an item, switch entire list to the previous bullet type
14768 - on a property line, switch to the previous allowed value
14769 - on a clocktable definition line, move time block into the past"
14770 (interactive "P")
14771 (cond
14772 ((and org-support-shift-select (org-region-active-p))
14773 (org-call-for-shift-select 'backward-char))
14774 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
14775 ((and (not (eq org-support-shift-select 'always))
14776 (org-on-heading-p))
14777 (let ((org-inhibit-logging
14778 (not org-treat-S-cursor-todo-selection-as-state-change)))
14779 (org-call-with-arg 'org-todo 'left)))
14780 ((or (and org-support-shift-select
14781 (not (eq org-support-shift-select 'always))
14782 (org-at-item-bullet-p))
14783 (and (not org-support-shift-select) (org-at-item-p)))
14784 (org-call-with-arg 'org-cycle-list-bullet 'previous))
14785 ((and (not (eq org-support-shift-select 'always))
14786 (org-at-property-p))
14787 (call-interactively 'org-property-previous-allowed-value))
14788 ((org-clocktable-try-shift 'left arg))
14789 (org-support-shift-select
14790 (org-call-for-shift-select 'backward-char))
14791 (t (org-shiftselect-error))))
14793 (defun org-shiftcontrolright ()
14794 "Switch to next TODO set."
14795 (interactive)
14796 (cond
14797 ((and org-support-shift-select (org-region-active-p))
14798 (org-call-for-shift-select 'forward-word))
14799 ((and (not (eq org-support-shift-select 'always))
14800 (org-on-heading-p))
14801 (org-call-with-arg 'org-todo 'nextset))
14802 (org-support-shift-select
14803 (org-call-for-shift-select 'forward-word))
14804 (t (org-shiftselect-error))))
14806 (defun org-shiftcontrolleft ()
14807 "Switch to previous TODO set."
14808 (interactive)
14809 (cond
14810 ((and org-support-shift-select (org-region-active-p))
14811 (org-call-for-shift-select 'backward-word))
14812 ((and (not (eq org-support-shift-select 'always))
14813 (org-on-heading-p))
14814 (org-call-with-arg 'org-todo 'previousset))
14815 (org-support-shift-select
14816 (org-call-for-shift-select 'backward-word))
14817 (t (org-shiftselect-error))))
14819 (defun org-ctrl-c-ret ()
14820 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
14821 (interactive)
14822 (cond
14823 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
14824 (t (call-interactively 'org-insert-heading))))
14826 (defun org-copy-special ()
14827 "Copy region in table or copy current subtree.
14828 Calls `org-table-copy' or `org-copy-subtree', depending on context.
14829 See the individual commands for more information."
14830 (interactive)
14831 (call-interactively
14832 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
14834 (defun org-cut-special ()
14835 "Cut region in table or cut current subtree.
14836 Calls `org-table-copy' or `org-cut-subtree', depending on context.
14837 See the individual commands for more information."
14838 (interactive)
14839 (call-interactively
14840 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
14842 (defun org-paste-special (arg)
14843 "Paste rectangular region into table, or past subtree relative to level.
14844 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
14845 See the individual commands for more information."
14846 (interactive "P")
14847 (if (org-at-table-p)
14848 (org-table-paste-rectangle)
14849 (org-paste-subtree arg)))
14851 (defun org-edit-special ()
14852 "Call a special editor for the stuff at point.
14853 When at a table, call the formula editor with `org-table-edit-formulas'.
14854 When at the first line of an src example, call `org-edit-src-code'.
14855 When in an #+include line, visit the include file. Otherwise call
14856 `ffap' to visit the file at point."
14857 (interactive)
14858 (cond
14859 ((org-at-table-p)
14860 (call-interactively 'org-table-edit-formulas))
14861 ((save-excursion
14862 (beginning-of-line 1)
14863 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
14864 (find-file (org-trim (match-string 1))))
14865 ((org-edit-src-code))
14866 ((org-edit-fixed-width-region))
14867 (t (call-interactively 'ffap))))
14870 (defun org-ctrl-c-ctrl-c (&optional arg)
14871 "Set tags in headline, or update according to changed information at point.
14873 This command does many different things, depending on context:
14875 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
14876 this is what we do.
14878 - If the cursor is in a headline, prompt for tags and insert them
14879 into the current line, aligned to `org-tags-column'. When called
14880 with prefix arg, realign all tags in the current buffer.
14882 - If the cursor is in one of the special #+KEYWORD lines, this
14883 triggers scanning the buffer for these lines and updating the
14884 information.
14886 - If the cursor is inside a table, realign the table. This command
14887 works even if the automatic table editor has been turned off.
14889 - If the cursor is on a #+TBLFM line, re-apply the formulas to
14890 the entire table.
14892 - If the cursor is at a footnote reference or definition, jump to
14893 the corresponding definition or references, respectively.
14895 - If the cursor is a the beginning of a dynamic block, update it.
14897 - If the cursor is inside a table created by the table.el package,
14898 activate that table.
14900 - If the current buffer is a remember buffer, close note and file
14901 it. A prefix argument of 1 files to the default location
14902 without further interaction. A prefix argument of 2 files to
14903 the currently clocking task.
14905 - If the cursor is on a <<<target>>>, update radio targets and corresponding
14906 links in this buffer.
14908 - If the cursor is on a numbered item in a plain list, renumber the
14909 ordered list.
14911 - If the cursor is on a checkbox, toggle it."
14912 (interactive "P")
14913 (let ((org-enable-table-editor t))
14914 (cond
14915 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
14916 org-occur-highlights
14917 org-latex-fragment-image-overlays)
14918 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
14919 (org-remove-occur-highlights)
14920 (org-remove-latex-fragment-image-overlays)
14921 (message "Temporary highlights/overlays removed from current buffer"))
14922 ((and (local-variable-p 'org-finish-function (current-buffer))
14923 (fboundp org-finish-function))
14924 (funcall org-finish-function))
14925 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
14926 ((org-at-property-p)
14927 (call-interactively 'org-property-action))
14928 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
14929 ((org-on-heading-p) (call-interactively 'org-set-tags))
14930 ((org-at-table.el-p)
14931 (require 'table)
14932 (beginning-of-line 1)
14933 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
14934 (call-interactively 'table-recognize-table))
14935 ((org-at-table-p)
14936 (org-table-maybe-eval-formula)
14937 (if arg
14938 (call-interactively 'org-table-recalculate)
14939 (org-table-maybe-recalculate-line))
14940 (call-interactively 'org-table-align))
14941 ((or (org-footnote-at-reference-p)
14942 (org-footnote-at-definition-p))
14943 (call-interactively 'org-footnote-action))
14944 ((org-at-item-checkbox-p)
14945 (call-interactively 'org-toggle-checkbox))
14946 ((org-at-item-p)
14947 (if arg
14948 (call-interactively 'org-toggle-checkbox)
14949 (call-interactively 'org-maybe-renumber-ordered-list)))
14950 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
14951 ;; Dynamic block
14952 (beginning-of-line 1)
14953 (save-excursion (org-update-dblock)))
14954 ((save-excursion
14955 (beginning-of-line 1)
14956 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
14957 (cond
14958 ((equal (match-string 1) "TBLFM")
14959 ;; Recalculate the table before this line
14960 (save-excursion
14961 (beginning-of-line 1)
14962 (skip-chars-backward " \r\n\t")
14963 (if (org-at-table-p)
14964 (org-call-with-arg 'org-table-recalculate t))))
14966 ; (org-set-regexps-and-options)
14967 ; (org-restart-font-lock)
14968 (let ((org-inhibit-startup t)) (org-mode-restart))
14969 (message "Local setup has been refreshed"))))
14970 ((org-clock-update-time-maybe))
14971 (t (error "C-c C-c can do nothing useful at this location.")))))
14973 (defun org-mode-restart ()
14974 "Restart Org-mode, to scan again for special lines.
14975 Also updates the keyword regular expressions."
14976 (interactive)
14977 (org-mode)
14978 (message "Org-mode restarted"))
14980 (defun org-kill-note-or-show-branches ()
14981 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
14982 (interactive)
14983 (if (not org-finish-function)
14984 (call-interactively 'show-branches)
14985 (let ((org-note-abort t))
14986 (funcall org-finish-function))))
14988 (defun org-return (&optional indent)
14989 "Goto next table row or insert a newline.
14990 Calls `org-table-next-row' or `newline', depending on context.
14991 See the individual commands for more information."
14992 (interactive)
14993 (cond
14994 ((bobp) (if indent (newline-and-indent) (newline)))
14995 ((org-at-table-p)
14996 (org-table-justify-field-maybe)
14997 (call-interactively 'org-table-next-row))
14998 ((and org-return-follows-link
14999 (eq (get-text-property (point) 'face) 'org-link))
15000 (call-interactively 'org-open-at-point))
15001 ((and (org-at-heading-p)
15002 (looking-at
15003 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
15004 (org-show-entry)
15005 (end-of-line 1)
15006 (newline))
15007 (t (if indent (newline-and-indent) (newline)))))
15009 (defun org-return-indent ()
15010 "Goto next table row or insert a newline and indent.
15011 Calls `org-table-next-row' or `newline-and-indent', depending on
15012 context. See the individual commands for more information."
15013 (interactive)
15014 (org-return t))
15016 (defun org-ctrl-c-star ()
15017 "Compute table, or change heading status of lines.
15018 Calls `org-table-recalculate' or `org-toggle-heading',
15019 depending on context."
15020 (interactive)
15021 (cond
15022 ((org-at-table-p)
15023 (call-interactively 'org-table-recalculate))
15025 ;; Convert all lines in region to list items
15026 (call-interactively 'org-toggle-heading))))
15028 (defun org-ctrl-c-minus ()
15029 "Insert separator line in table or modify bullet status of line.
15030 Also turns a plain line or a region of lines into list items.
15031 Calls `org-table-insert-hline', `org-toggle-item', or
15032 `org-cycle-list-bullet', depending on context."
15033 (interactive)
15034 (cond
15035 ((org-at-table-p)
15036 (call-interactively 'org-table-insert-hline))
15037 ((org-region-active-p)
15038 (call-interactively 'org-toggle-item))
15039 ((org-in-item-p)
15040 (call-interactively 'org-cycle-list-bullet))
15042 (call-interactively 'org-toggle-item))))
15044 (defun org-toggle-item ()
15045 "Convert headings or normal lines to items, items to normal lines.
15046 If there is no active region, only the current line is considered.
15048 If the first line in the region is a headline, convert all headlines to items.
15050 If the first line in the region is an item, convert all items to normal lines.
15052 If the first line is normal text, add an item bullet to each line."
15053 (interactive)
15054 (let (l2 l beg end)
15055 (if (org-region-active-p)
15056 (setq beg (region-beginning) end (region-end))
15057 (setq beg (point-at-bol)
15058 end (min (1+ (point-at-eol)) (point-max))))
15059 (save-excursion
15060 (goto-char end)
15061 (setq l2 (org-current-line))
15062 (goto-char beg)
15063 (beginning-of-line 1)
15064 (setq l (1- (org-current-line)))
15065 (if (org-at-item-p)
15066 ;; We already have items, de-itemize
15067 (while (< (setq l (1+ l)) l2)
15068 (when (org-at-item-p)
15069 (goto-char (match-beginning 2))
15070 (delete-region (match-beginning 2) (match-end 2))
15071 (and (looking-at "[ \t]+") (replace-match "")))
15072 (beginning-of-line 2))
15073 (if (org-on-heading-p)
15074 ;; Headings, convert to items
15075 (while (< (setq l (1+ l)) l2)
15076 (if (looking-at org-outline-regexp)
15077 (replace-match "- " t t))
15078 (beginning-of-line 2))
15079 ;; normal lines, turn them into items
15080 (while (< (setq l (1+ l)) l2)
15081 (unless (org-at-item-p)
15082 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15083 (replace-match "\\1- \\2")))
15084 (beginning-of-line 2)))))))
15086 (defun org-toggle-heading (&optional nstars)
15087 "Convert headings to normal text, or items or text to headings.
15088 If there is no active region, only the current line is considered.
15090 If the first line is a heading, remove the stars from all headlines
15091 in the region.
15093 If the first line is a plain list item, turn all plain list items into
15094 headings.
15096 If the first line is a normal line, turn each and every line in the region
15097 into a heading.
15099 When converting a line into a heading, the number of stars is chosen
15100 such that the lines become children of the current entry. However, when
15101 a prefix argument is given, its value determines the number of stars to add."
15102 (interactive "P")
15103 (let (l2 l itemp beg end)
15104 (if (org-region-active-p)
15105 (setq beg (region-beginning) end (region-end))
15106 (setq beg (point-at-bol)
15107 end (min (1+ (point-at-eol)) (point-max))))
15108 (save-excursion
15109 (goto-char end)
15110 (setq l2 (org-current-line))
15111 (goto-char beg)
15112 (beginning-of-line 1)
15113 (setq l (1- (org-current-line)))
15114 (if (org-on-heading-p)
15115 ;; We already have headlines, de-star them
15116 (while (< (setq l (1+ l)) l2)
15117 (when (org-on-heading-p t)
15118 (and (looking-at outline-regexp) (replace-match "")))
15119 (beginning-of-line 2))
15120 (setq itemp (org-at-item-p))
15121 (let* ((stars
15122 (if nstars
15123 (make-string (prefix-numeric-value current-prefix-arg)
15125 (save-excursion
15126 (re-search-backward org-complex-heading-regexp nil t)
15127 (or (match-string 1) ""))))
15128 (add-stars (cond (nstars "")
15129 ((equal stars "") "*")
15130 (org-odd-levels-only "**")
15131 (t "*")))
15132 (rpl (concat stars add-stars " ")))
15133 (while (< (setq l (1+ l)) l2)
15134 (if itemp
15135 (and (org-at-item-p) (replace-match rpl t t))
15136 (unless (org-on-heading-p)
15137 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15138 (replace-match (concat rpl (match-string 2))))))
15139 (beginning-of-line 2)))))))
15141 (defun org-meta-return (&optional arg)
15142 "Insert a new heading or wrap a region in a table.
15143 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
15144 See the individual commands for more information."
15145 (interactive "P")
15146 (cond
15147 ((run-hook-with-args-until-success 'org-metareturn-hook))
15148 ((org-at-table-p)
15149 (call-interactively 'org-table-wrap-region))
15150 (t (call-interactively 'org-insert-heading))))
15152 ;;; Menu entries
15154 ;; Define the Org-mode menus
15155 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
15156 '("Tbl"
15157 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
15158 ["Next Field" org-cycle (org-at-table-p)]
15159 ["Previous Field" org-shifttab (org-at-table-p)]
15160 ["Next Row" org-return (org-at-table-p)]
15161 "--"
15162 ["Blank Field" org-table-blank-field (org-at-table-p)]
15163 ["Edit Field" org-table-edit-field (org-at-table-p)]
15164 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
15165 "--"
15166 ("Column"
15167 ["Move Column Left" org-metaleft (org-at-table-p)]
15168 ["Move Column Right" org-metaright (org-at-table-p)]
15169 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
15170 ["Insert Column" org-shiftmetaright (org-at-table-p)])
15171 ("Row"
15172 ["Move Row Up" org-metaup (org-at-table-p)]
15173 ["Move Row Down" org-metadown (org-at-table-p)]
15174 ["Delete Row" org-shiftmetaup (org-at-table-p)]
15175 ["Insert Row" org-shiftmetadown (org-at-table-p)]
15176 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
15177 "--"
15178 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
15179 ("Rectangle"
15180 ["Copy Rectangle" org-copy-special (org-at-table-p)]
15181 ["Cut Rectangle" org-cut-special (org-at-table-p)]
15182 ["Paste Rectangle" org-paste-special (org-at-table-p)]
15183 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
15184 "--"
15185 ("Calculate"
15186 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
15187 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
15188 ["Edit Formulas" org-edit-special (org-at-table-p)]
15189 "--"
15190 ["Recalculate line" org-table-recalculate (org-at-table-p)]
15191 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
15192 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
15193 "--"
15194 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
15195 "--"
15196 ["Sum Column/Rectangle" org-table-sum
15197 (or (org-at-table-p) (org-region-active-p))]
15198 ["Which Column?" org-table-current-column (org-at-table-p)])
15199 ["Debug Formulas"
15200 org-table-toggle-formula-debugger
15201 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
15202 ["Show Col/Row Numbers"
15203 org-table-toggle-coordinate-overlays
15204 :style toggle
15205 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
15206 "--"
15207 ["Create" org-table-create (and (not (org-at-table-p))
15208 org-enable-table-editor)]
15209 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
15210 ["Import from File" org-table-import (not (org-at-table-p))]
15211 ["Export to File" org-table-export (org-at-table-p)]
15212 "--"
15213 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
15215 (easy-menu-define org-org-menu org-mode-map "Org menu"
15216 '("Org"
15217 ("Show/Hide"
15218 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
15219 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
15220 ["Sparse Tree..." org-sparse-tree t]
15221 ["Reveal Context" org-reveal t]
15222 ["Show All" show-all t]
15223 "--"
15224 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
15225 "--"
15226 ["New Heading" org-insert-heading t]
15227 ("Navigate Headings"
15228 ["Up" outline-up-heading t]
15229 ["Next" outline-next-visible-heading t]
15230 ["Previous" outline-previous-visible-heading t]
15231 ["Next Same Level" outline-forward-same-level t]
15232 ["Previous Same Level" outline-backward-same-level t]
15233 "--"
15234 ["Jump" org-goto t])
15235 ("Edit Structure"
15236 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
15237 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
15238 "--"
15239 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
15240 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
15241 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
15242 "--"
15243 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
15244 "--"
15245 ["Promote Heading" org-metaleft (not (org-at-table-p))]
15246 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
15247 ["Demote Heading" org-metaright (not (org-at-table-p))]
15248 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
15249 "--"
15250 ["Sort Region/Children" org-sort (not (org-at-table-p))]
15251 "--"
15252 ["Convert to odd levels" org-convert-to-odd-levels t]
15253 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
15254 ("Editing"
15255 ["Emphasis..." org-emphasize t]
15256 ["Edit Source Example" org-edit-special t]
15257 "--"
15258 ["Footnote new/jump" org-footnote-action t]
15259 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
15260 ("Archive"
15261 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
15262 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
15263 ; :active t :keys "C-u C-c C-x C-a"]
15264 ["Sparse trees open ARCHIVE trees"
15265 (setq org-sparse-tree-open-archived-trees
15266 (not org-sparse-tree-open-archived-trees))
15267 :style toggle :selected org-sparse-tree-open-archived-trees]
15268 ["Cycling opens ARCHIVE trees"
15269 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
15270 :style toggle :selected org-cycle-open-archived-trees]
15271 "--"
15272 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
15273 ["Move Subtree to Archive" org-advertized-archive-subtree t]
15274 ; ["Check and Move Children" (org-archive-subtree '(4))
15275 ; :active t :keys "C-u C-c C-x C-s"]
15277 "--"
15278 ("Hyperlinks"
15279 ["Store Link (Global)" org-store-link t]
15280 ["Insert Link" org-insert-link t]
15281 ["Follow Link" org-open-at-point t]
15282 "--"
15283 ["Next link" org-next-link t]
15284 ["Previous link" org-previous-link t]
15285 "--"
15286 ["Descriptive Links"
15287 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
15288 :style radio
15289 :selected (member '(org-link) buffer-invisibility-spec)]
15290 ["Literal Links"
15291 (progn
15292 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
15293 :style radio
15294 :selected (not (member '(org-link) buffer-invisibility-spec))])
15295 "--"
15296 ("TODO Lists"
15297 ["TODO/DONE/-" org-todo t]
15298 ("Select keyword"
15299 ["Next keyword" org-shiftright (org-on-heading-p)]
15300 ["Previous keyword" org-shiftleft (org-on-heading-p)]
15301 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
15302 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
15303 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
15304 ["Show TODO Tree" org-show-todo-tree t]
15305 ["Global TODO list" org-todo-list t]
15306 "--"
15307 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
15308 :selected org-enforce-todo-dependencies :style toggle :active t]
15309 "Settings for tree at point"
15310 ["Do Children sequentially" org-toggle-ordered-property :style radio
15311 :selected (ignore-errors (org-entry-get nil "ORDERED"))
15312 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15313 ["Do Children parallel" org-toggle-ordered-property :style radio
15314 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
15315 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15316 "--"
15317 ["Set Priority" org-priority t]
15318 ["Priority Up" org-shiftup t]
15319 ["Priority Down" org-shiftdown t]
15320 "--"
15321 ["Get news from all feeds" org-feed-update-all t]
15322 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
15323 ["Customize feeds" (customize-variable 'org-feed-alist) t])
15324 ("TAGS and Properties"
15325 ["Set Tags" org-set-tags-command t]
15326 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
15327 "--"
15328 ["Set property" org-set-property t]
15329 ["Column view of properties" org-columns t]
15330 ["Insert Column View DBlock" org-insert-columns-dblock t])
15331 ("Dates and Scheduling"
15332 ["Timestamp" org-time-stamp t]
15333 ["Timestamp (inactive)" org-time-stamp-inactive t]
15334 ("Change Date"
15335 ["1 Day Later" org-shiftright t]
15336 ["1 Day Earlier" org-shiftleft t]
15337 ["1 ... Later" org-shiftup t]
15338 ["1 ... Earlier" org-shiftdown t])
15339 ["Compute Time Range" org-evaluate-time-range t]
15340 ["Schedule Item" org-schedule t]
15341 ["Deadline" org-deadline t]
15342 "--"
15343 ["Custom time format" org-toggle-time-stamp-overlays
15344 :style radio :selected org-display-custom-times]
15345 "--"
15346 ["Goto Calendar" org-goto-calendar t]
15347 ["Date from Calendar" org-date-from-calendar t]
15348 "--"
15349 ["Start/Restart Timer" org-timer-start t]
15350 ["Pause/Continue Timer" org-timer-pause-or-continue t]
15351 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
15352 ["Insert Timer String" org-timer t]
15353 ["Insert Timer Item" org-timer-item t])
15354 ("Logging work"
15355 ["Clock in" org-clock-in t]
15356 ["Clock out" org-clock-out t]
15357 ["Clock cancel" org-clock-cancel t]
15358 ["Goto running clock" org-clock-goto t]
15359 ["Display times" org-clock-display t]
15360 ["Create clock table" org-clock-report t]
15361 "--"
15362 ["Record DONE time"
15363 (progn (setq org-log-done (not org-log-done))
15364 (message "Switching to %s will %s record a timestamp"
15365 (car org-done-keywords)
15366 (if org-log-done "automatically" "not")))
15367 :style toggle :selected org-log-done])
15368 "--"
15369 ["Agenda Command..." org-agenda t]
15370 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
15371 ("File List for Agenda")
15372 ("Special views current file"
15373 ["TODO Tree" org-show-todo-tree t]
15374 ["Check Deadlines" org-check-deadlines t]
15375 ["Timeline" org-timeline t]
15376 ["Tags/Property tree" org-match-sparse-tree t])
15377 "--"
15378 ["Export/Publish..." org-export t]
15379 ("LaTeX"
15380 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
15381 :selected org-cdlatex-mode]
15382 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
15383 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
15384 ["Modify math symbol" org-cdlatex-math-modify
15385 (org-inside-LaTeX-fragment-p)]
15386 ["Insert citation" org-reftex-citation t]
15387 "--"
15388 ["Export LaTeX fragments as images"
15389 (if (featurep 'org-exp)
15390 (setq org-export-with-LaTeX-fragments
15391 (not org-export-with-LaTeX-fragments))
15392 (require 'org-exp))
15393 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
15394 org-export-with-LaTeX-fragments)])
15395 "--"
15396 ("Documentation"
15397 ["Show Version" org-version t]
15398 ["Info Documentation" org-info t])
15399 ("Customize"
15400 ["Browse Org Group" org-customize t]
15401 "--"
15402 ["Expand This Menu" org-create-customize-menu
15403 (fboundp 'customize-menu-create)])
15404 "--"
15405 ("Refresh/Reload"
15406 ["Refresh setup current buffer" org-mode-restart t]
15407 ["Reload Org (after update)" org-reload t]
15408 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
15411 (defun org-info (&optional node)
15412 "Read documentation for Org-mode in the info system.
15413 With optional NODE, go directly to that node."
15414 (interactive)
15415 (info (format "(org)%s" (or node ""))))
15417 (defun org-install-agenda-files-menu ()
15418 (let ((bl (buffer-list)))
15419 (save-excursion
15420 (while bl
15421 (set-buffer (pop bl))
15422 (if (org-mode-p) (setq bl nil)))
15423 (when (org-mode-p)
15424 (easy-menu-change
15425 '("Org") "File List for Agenda"
15426 (append
15427 (list
15428 ["Edit File List" (org-edit-agenda-file-list) t]
15429 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
15430 ["Remove Current File from List" org-remove-file t]
15431 ["Cycle through agenda files" org-cycle-agenda-files t]
15432 ["Occur in all agenda files" org-occur-in-agenda-files t]
15433 "--")
15434 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
15436 ;;;; Documentation
15438 ;;;###autoload
15439 (defun org-require-autoloaded-modules ()
15440 (interactive)
15441 (mapc 'require
15442 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
15443 org-docbook org-exp org-html org-icalendar
15444 org-id org-latex
15445 org-publish org-remember org-table
15446 org-timer org-xoxo)))
15448 ;;;###autoload
15449 (defun org-reload (&optional uncompiled)
15450 "Reload all org lisp files.
15451 With prefix arg UNCOMPILED, load the uncompiled versions."
15452 (interactive "P")
15453 (require 'find-func)
15454 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
15455 (dir-org (file-name-directory (org-find-library-name "org")))
15456 (dir-org-contrib (ignore-errors
15457 (file-name-directory
15458 (org-find-library-name "org-contribdir"))))
15459 (files
15460 (append (directory-files dir-org t file-re)
15461 (and dir-org-contrib
15462 (directory-files dir-org-contrib t file-re))))
15463 (remove-re (concat (if (featurep 'xemacs)
15464 "org-colview" "org-colview-xemacs")
15465 "\\'")))
15466 (setq files (mapcar 'file-name-sans-extension files))
15467 (setq files (mapcar
15468 (lambda (x) (if (string-match remove-re x) nil x))
15469 files))
15470 (setq files (delq nil files))
15471 (mapc
15472 (lambda (f)
15473 (when (featurep (intern (file-name-nondirectory f)))
15474 (if (and (not uncompiled)
15475 (file-exists-p (concat f ".elc")))
15476 (load (concat f ".elc") nil nil t)
15477 (load (concat f ".el") nil nil t))))
15478 files))
15479 (org-version))
15481 ;;;###autoload
15482 (defun org-customize ()
15483 "Call the customize function with org as argument."
15484 (interactive)
15485 (org-load-modules-maybe)
15486 (org-require-autoloaded-modules)
15487 (customize-browse 'org))
15489 (defun org-create-customize-menu ()
15490 "Create a full customization menu for Org-mode, insert it into the menu."
15491 (interactive)
15492 (org-load-modules-maybe)
15493 (org-require-autoloaded-modules)
15494 (if (fboundp 'customize-menu-create)
15495 (progn
15496 (easy-menu-change
15497 '("Org") "Customize"
15498 `(["Browse Org group" org-customize t]
15499 "--"
15500 ,(customize-menu-create 'org)
15501 ["Set" Custom-set t]
15502 ["Save" Custom-save t]
15503 ["Reset to Current" Custom-reset-current t]
15504 ["Reset to Saved" Custom-reset-saved t]
15505 ["Reset to Standard Settings" Custom-reset-standard t]))
15506 (message "\"Org\"-menu now contains full customization menu"))
15507 (error "Cannot expand menu (outdated version of cus-edit.el)")))
15509 ;;;; Miscellaneous stuff
15511 ;;; Generally useful functions
15513 (defun org-find-text-property-in-string (prop s)
15514 "Return the first non-nil value of property PROP in string S."
15515 (or (get-text-property 0 prop s)
15516 (get-text-property (or (next-single-property-change 0 prop s) 0)
15517 prop s)))
15519 (defun org-display-warning (message) ;; Copied from Emacs-Muse
15520 "Display the given MESSAGE as a warning."
15521 (if (fboundp 'display-warning)
15522 (display-warning 'org message
15523 (if (featurep 'xemacs)
15524 'warning
15525 :warning))
15526 (let ((buf (get-buffer-create "*Org warnings*")))
15527 (with-current-buffer buf
15528 (goto-char (point-max))
15529 (insert "Warning (Org): " message)
15530 (unless (bolp)
15531 (newline)))
15532 (display-buffer buf)
15533 (sit-for 0))))
15535 (defun org-goto-marker-or-bmk (marker &optional bookmark)
15536 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
15537 (if (and marker (marker-buffer marker)
15538 (buffer-live-p (marker-buffer marker)))
15539 (progn
15540 (switch-to-buffer (marker-buffer marker))
15541 (if (or (> marker (point-max)) (< marker (point-min)))
15542 (widen))
15543 (goto-char marker)
15544 (org-show-context 'org-goto))
15545 (if bookmark
15546 (bookmark-jump bookmark)
15547 (error "Cannot find location"))))
15549 (defun org-quote-csv-field (s)
15550 "Quote field for inclusion in CSV material."
15551 (if (string-match "[\",]" s)
15552 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
15555 (defun org-plist-delete (plist property)
15556 "Delete PROPERTY from PLIST.
15557 This is in contrast to merely setting it to 0."
15558 (let (p)
15559 (while plist
15560 (if (not (eq property (car plist)))
15561 (setq p (plist-put p (car plist) (nth 1 plist))))
15562 (setq plist (cddr plist)))
15565 (defun org-force-self-insert (N)
15566 "Needed to enforce self-insert under remapping."
15567 (interactive "p")
15568 (self-insert-command N))
15570 (defun org-string-width (s)
15571 "Compute width of string, ignoring invisible characters.
15572 This ignores character with invisibility property `org-link', and also
15573 characters with property `org-cwidth', because these will become invisible
15574 upon the next fontification round."
15575 (let (b l)
15576 (when (or (eq t buffer-invisibility-spec)
15577 (assq 'org-link buffer-invisibility-spec))
15578 (while (setq b (text-property-any 0 (length s)
15579 'invisible 'org-link s))
15580 (setq s (concat (substring s 0 b)
15581 (substring s (or (next-single-property-change
15582 b 'invisible s) (length s)))))))
15583 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
15584 (setq s (concat (substring s 0 b)
15585 (substring s (or (next-single-property-change
15586 b 'org-cwidth s) (length s))))))
15587 (setq l (string-width s) b -1)
15588 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
15589 (setq l (- l (get-text-property b 'org-dwidth-n s))))
15592 (defun org-get-indentation (&optional line)
15593 "Get the indentation of the current line, interpreting tabs.
15594 When LINE is given, assume it represents a line and compute its indentation."
15595 (if line
15596 (if (string-match "^ *" (org-remove-tabs line))
15597 (match-end 0))
15598 (save-excursion
15599 (beginning-of-line 1)
15600 (skip-chars-forward " \t")
15601 (current-column))))
15603 (defun org-remove-tabs (s &optional width)
15604 "Replace tabulators in S with spaces.
15605 Assumes that s is a single line, starting in column 0."
15606 (setq width (or width tab-width))
15607 (while (string-match "\t" s)
15608 (setq s (replace-match
15609 (make-string
15610 (- (* width (/ (+ (match-beginning 0) width) width))
15611 (match-beginning 0)) ?\ )
15612 t t s)))
15615 (defun org-fix-indentation (line ind)
15616 "Fix indentation in LINE.
15617 IND is a cons cell with target and minimum indentation.
15618 If the current indentation in LINE is smaller than the minimum,
15619 leave it alone. If it is larger than ind, set it to the target."
15620 (let* ((l (org-remove-tabs line))
15621 (i (org-get-indentation l))
15622 (i1 (car ind)) (i2 (cdr ind)))
15623 (if (>= i i2) (setq l (substring line i2)))
15624 (if (> i1 0)
15625 (concat (make-string i1 ?\ ) l)
15626 l)))
15628 (defun org-remove-indentation (code &optional n)
15629 "Remove the maximum common indentation from the lines in CODE.
15630 N may optionally be the number of spaces to remove."
15631 (with-temp-buffer
15632 (insert code)
15633 (org-do-remove-indentation n)
15634 (buffer-string)))
15636 (defun org-do-remove-indentation (&optional n)
15637 "Remove the maximum common indentation from the buffer."
15638 (untabify (point-min) (point-max))
15639 (let ((min 10000) re)
15640 (if n
15641 (setq min n)
15642 (goto-char (point-min))
15643 (while (re-search-forward "^ *[^ \n]" nil t)
15644 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
15645 (unless (or (= min 0) (= min 10000))
15646 (setq re (format "^ \\{%d\\}" min))
15647 (goto-char (point-min))
15648 (while (re-search-forward re nil t)
15649 (replace-match "")
15650 (end-of-line 1))
15651 min)))
15653 (defun org-base-buffer (buffer)
15654 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
15655 (if (not buffer)
15656 buffer
15657 (or (buffer-base-buffer buffer)
15658 buffer)))
15660 (defun org-trim (s)
15661 "Remove whitespace at beginning and end of string."
15662 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
15663 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
15666 (defun org-wrap (string &optional width lines)
15667 "Wrap string to either a number of lines, or a width in characters.
15668 If WIDTH is non-nil, the string is wrapped to that width, however many lines
15669 that costs. If there is a word longer than WIDTH, the text is actually
15670 wrapped to the length of that word.
15671 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
15672 many lines, whatever width that takes.
15673 The return value is a list of lines, without newlines at the end."
15674 (let* ((words (org-split-string string "[ \t\n]+"))
15675 (maxword (apply 'max (mapcar 'org-string-width words)))
15676 w ll)
15677 (cond (width
15678 (org-do-wrap words (max maxword width)))
15679 (lines
15680 (setq w maxword)
15681 (setq ll (org-do-wrap words maxword))
15682 (if (<= (length ll) lines)
15684 (setq ll words)
15685 (while (> (length ll) lines)
15686 (setq w (1+ w))
15687 (setq ll (org-do-wrap words w)))
15688 ll))
15689 (t (error "Cannot wrap this")))))
15691 (defun org-do-wrap (words width)
15692 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
15693 (let (lines line)
15694 (while words
15695 (setq line (pop words))
15696 (while (and words (< (+ (length line) (length (car words))) width))
15697 (setq line (concat line " " (pop words))))
15698 (setq lines (push line lines)))
15699 (nreverse lines)))
15701 (defun org-split-string (string &optional separators)
15702 "Splits STRING into substrings at SEPARATORS.
15703 No empty strings are returned if there are matches at the beginning
15704 and end of string."
15705 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
15706 (start 0)
15707 notfirst
15708 (list nil))
15709 (while (and (string-match rexp string
15710 (if (and notfirst
15711 (= start (match-beginning 0))
15712 (< start (length string)))
15713 (1+ start) start))
15714 (< (match-beginning 0) (length string)))
15715 (setq notfirst t)
15716 (or (eq (match-beginning 0) 0)
15717 (and (eq (match-beginning 0) (match-end 0))
15718 (eq (match-beginning 0) start))
15719 (setq list
15720 (cons (substring string start (match-beginning 0))
15721 list)))
15722 (setq start (match-end 0)))
15723 (or (eq start (length string))
15724 (setq list
15725 (cons (substring string start)
15726 list)))
15727 (nreverse list)))
15729 (defun org-uuidgen-p (s)
15730 "Is S an ID created by UUIDGEN?"
15731 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
15733 (defun org-context ()
15734 "Return a list of contexts of the current cursor position.
15735 If several contexts apply, all are returned.
15736 Each context entry is a list with a symbol naming the context, and
15737 two positions indicating start and end of the context. Possible
15738 contexts are:
15740 :headline anywhere in a headline
15741 :headline-stars on the leading stars in a headline
15742 :todo-keyword on a TODO keyword (including DONE) in a headline
15743 :tags on the TAGS in a headline
15744 :priority on the priority cookie in a headline
15745 :item on the first line of a plain list item
15746 :item-bullet on the bullet/number of a plain list item
15747 :checkbox on the checkbox in a plain list item
15748 :table in an org-mode table
15749 :table-special on a special filed in a table
15750 :table-table in a table.el table
15751 :link on a hyperlink
15752 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
15753 :target on a <<target>>
15754 :radio-target on a <<<radio-target>>>
15755 :latex-fragment on a LaTeX fragment
15756 :latex-preview on a LaTeX fragment with overlayed preview image
15758 This function expects the position to be visible because it uses font-lock
15759 faces as a help to recognize the following contexts: :table-special, :link,
15760 and :keyword."
15761 (let* ((f (get-text-property (point) 'face))
15762 (faces (if (listp f) f (list f)))
15763 (p (point)) clist o)
15764 ;; First the large context
15765 (cond
15766 ((org-on-heading-p t)
15767 (push (list :headline (point-at-bol) (point-at-eol)) clist)
15768 (when (progn
15769 (beginning-of-line 1)
15770 (looking-at org-todo-line-tags-regexp))
15771 (push (org-point-in-group p 1 :headline-stars) clist)
15772 (push (org-point-in-group p 2 :todo-keyword) clist)
15773 (push (org-point-in-group p 4 :tags) clist))
15774 (goto-char p)
15775 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
15776 (if (looking-at "\\[#[A-Z0-9]\\]")
15777 (push (org-point-in-group p 0 :priority) clist)))
15779 ((org-at-item-p)
15780 (push (org-point-in-group p 2 :item-bullet) clist)
15781 (push (list :item (point-at-bol)
15782 (save-excursion (org-end-of-item) (point)))
15783 clist)
15784 (and (org-at-item-checkbox-p)
15785 (push (org-point-in-group p 0 :checkbox) clist)))
15787 ((org-at-table-p)
15788 (push (list :table (org-table-begin) (org-table-end)) clist)
15789 (if (memq 'org-formula faces)
15790 (push (list :table-special
15791 (previous-single-property-change p 'face)
15792 (next-single-property-change p 'face)) clist)))
15793 ((org-at-table-p 'any)
15794 (push (list :table-table) clist)))
15795 (goto-char p)
15797 ;; Now the small context
15798 (cond
15799 ((org-at-timestamp-p)
15800 (push (org-point-in-group p 0 :timestamp) clist))
15801 ((memq 'org-link faces)
15802 (push (list :link
15803 (previous-single-property-change p 'face)
15804 (next-single-property-change p 'face)) clist))
15805 ((memq 'org-special-keyword faces)
15806 (push (list :keyword
15807 (previous-single-property-change p 'face)
15808 (next-single-property-change p 'face)) clist))
15809 ((org-on-target-p)
15810 (push (org-point-in-group p 0 :target) clist)
15811 (goto-char (1- (match-beginning 0)))
15812 (if (looking-at org-radio-target-regexp)
15813 (push (org-point-in-group p 0 :radio-target) clist))
15814 (goto-char p))
15815 ((setq o (car (delq nil
15816 (mapcar
15817 (lambda (x)
15818 (if (memq x org-latex-fragment-image-overlays) x))
15819 (org-overlays-at (point))))))
15820 (push (list :latex-fragment
15821 (org-overlay-start o) (org-overlay-end o)) clist)
15822 (push (list :latex-preview
15823 (org-overlay-start o) (org-overlay-end o)) clist))
15824 ((org-inside-LaTeX-fragment-p)
15825 ;; FIXME: positions wrong.
15826 (push (list :latex-fragment (point) (point)) clist)))
15828 (setq clist (nreverse (delq nil clist)))
15829 clist))
15831 ;; FIXME: Compare with at-regexp-p Do we need both?
15832 (defun org-in-regexp (re &optional nlines visually)
15833 "Check if point is inside a match of regexp.
15834 Normally only the current line is checked, but you can include NLINES extra
15835 lines both before and after point into the search.
15836 If VISUALLY is set, require that the cursor is not after the match but
15837 really on, so that the block visually is on the match."
15838 (catch 'exit
15839 (let ((pos (point))
15840 (eol (point-at-eol (+ 1 (or nlines 0))))
15841 (inc (if visually 1 0)))
15842 (save-excursion
15843 (beginning-of-line (- 1 (or nlines 0)))
15844 (while (re-search-forward re eol t)
15845 (if (and (<= (match-beginning 0) pos)
15846 (>= (+ inc (match-end 0)) pos))
15847 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
15849 (defun org-at-regexp-p (regexp)
15850 "Is point inside a match of REGEXP in the current line?"
15851 (catch 'exit
15852 (save-excursion
15853 (let ((pos (point)) (end (point-at-eol)))
15854 (beginning-of-line 1)
15855 (while (re-search-forward regexp end t)
15856 (if (and (<= (match-beginning 0) pos)
15857 (>= (match-end 0) pos))
15858 (throw 'exit t)))
15859 nil))))
15861 (defun org-occur-in-agenda-files (regexp &optional nlines)
15862 "Call `multi-occur' with buffers for all agenda files."
15863 (interactive "sOrg-files matching: \np")
15864 (let* ((files (org-agenda-files))
15865 (tnames (mapcar 'file-truename files))
15866 (extra org-agenda-text-search-extra-files)
15868 (when (eq (car extra) 'agenda-archives)
15869 (setq extra (cdr extra))
15870 (setq files (org-add-archive-files files)))
15871 (while (setq f (pop extra))
15872 (unless (member (file-truename f) tnames)
15873 (add-to-list 'files f 'append)
15874 (add-to-list 'tnames (file-truename f) 'append)))
15875 (multi-occur
15876 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
15877 regexp)))
15879 (if (boundp 'occur-mode-find-occurrence-hook)
15880 ;; Emacs 23
15881 (add-hook 'occur-mode-find-occurrence-hook
15882 (lambda ()
15883 (when (org-mode-p)
15884 (org-reveal))))
15885 ;; Emacs 22
15886 (defadvice occur-mode-goto-occurrence
15887 (after org-occur-reveal activate)
15888 (and (org-mode-p) (org-reveal)))
15889 (defadvice occur-mode-goto-occurrence-other-window
15890 (after org-occur-reveal activate)
15891 (and (org-mode-p) (org-reveal)))
15892 (defadvice occur-mode-display-occurrence
15893 (after org-occur-reveal activate)
15894 (when (org-mode-p)
15895 (let ((pos (occur-mode-find-occurrence)))
15896 (with-current-buffer (marker-buffer pos)
15897 (save-excursion
15898 (goto-char pos)
15899 (org-reveal)))))))
15901 (defun org-uniquify (list)
15902 "Remove duplicate elements from LIST."
15903 (let (res)
15904 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
15905 res))
15907 (defun org-delete-all (elts list)
15908 "Remove all elements in ELTS from LIST."
15909 (while elts
15910 (setq list (delete (pop elts) list)))
15911 list)
15913 (defun org-back-over-empty-lines ()
15914 "Move backwards over whitespace, to the beginning of the first empty line.
15915 Returns the number of empty lines passed."
15916 (let ((pos (point)))
15917 (skip-chars-backward " \t\n\r")
15918 (beginning-of-line 2)
15919 (goto-char (min (point) pos))
15920 (count-lines (point) pos)))
15922 (defun org-skip-whitespace ()
15923 (skip-chars-forward " \t\n\r"))
15925 (defun org-point-in-group (point group &optional context)
15926 "Check if POINT is in match-group GROUP.
15927 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
15928 match. If the match group does ot exist or point is not inside it,
15929 return nil."
15930 (and (match-beginning group)
15931 (>= point (match-beginning group))
15932 (<= point (match-end group))
15933 (if context
15934 (list context (match-beginning group) (match-end group))
15935 t)))
15937 (defun org-switch-to-buffer-other-window (&rest args)
15938 "Switch to buffer in a second window on the current frame.
15939 In particular, do not allow pop-up frames."
15940 (let (pop-up-frames special-display-buffer-names special-display-regexps
15941 special-display-function)
15942 (apply 'switch-to-buffer-other-window args)))
15944 (defun org-combine-plists (&rest plists)
15945 "Create a single property list from all plists in PLISTS.
15946 The process starts by copying the first list, and then setting properties
15947 from the other lists. Settings in the last list are the most significant
15948 ones and overrule settings in the other lists."
15949 (let ((rtn (copy-sequence (pop plists)))
15950 p v ls)
15951 (while plists
15952 (setq ls (pop plists))
15953 (while ls
15954 (setq p (pop ls) v (pop ls))
15955 (setq rtn (plist-put rtn p v))))
15956 rtn))
15958 (defun org-move-line-down (arg)
15959 "Move the current line down. With prefix argument, move it past ARG lines."
15960 (interactive "p")
15961 (let ((col (current-column))
15962 beg end pos)
15963 (beginning-of-line 1) (setq beg (point))
15964 (beginning-of-line 2) (setq end (point))
15965 (beginning-of-line (+ 1 arg))
15966 (setq pos (move-marker (make-marker) (point)))
15967 (insert (delete-and-extract-region beg end))
15968 (goto-char pos)
15969 (org-move-to-column col)))
15971 (defun org-move-line-up (arg)
15972 "Move the current line up. With prefix argument, move it past ARG lines."
15973 (interactive "p")
15974 (let ((col (current-column))
15975 beg end pos)
15976 (beginning-of-line 1) (setq beg (point))
15977 (beginning-of-line 2) (setq end (point))
15978 (beginning-of-line (- arg))
15979 (setq pos (move-marker (make-marker) (point)))
15980 (insert (delete-and-extract-region beg end))
15981 (goto-char pos)
15982 (org-move-to-column col)))
15984 (defun org-replace-escapes (string table)
15985 "Replace %-escapes in STRING with values in TABLE.
15986 TABLE is an association list with keys like \"%a\" and string values.
15987 The sequences in STRING may contain normal field width and padding information,
15988 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
15989 so values can contain further %-escapes if they are define later in TABLE."
15990 (let ((case-fold-search nil)
15991 e re rpl)
15992 (while (setq e (pop table))
15993 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
15994 (while (string-match re string)
15995 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
15996 (cdr e)))
15997 (setq string (replace-match rpl t t string))))
15998 string))
16001 (defun org-sublist (list start end)
16002 "Return a section of LIST, from START to END.
16003 Counting starts at 1."
16004 (let (rtn (c start))
16005 (setq list (nthcdr (1- start) list))
16006 (while (and list (<= c end))
16007 (push (pop list) rtn)
16008 (setq c (1+ c)))
16009 (nreverse rtn)))
16011 (defun org-find-base-buffer-visiting (file)
16012 "Like `find-buffer-visiting' but always return the base buffer and
16013 not an indirect buffer."
16014 (let ((buf (or (get-file-buffer file)
16015 (find-buffer-visiting file))))
16016 (if buf
16017 (or (buffer-base-buffer buf) buf)
16018 nil)))
16020 (defun org-image-file-name-regexp (&optional extensions)
16021 "Return regexp matching the file names of images.
16022 If EXTENSIONS is given, only match these."
16023 (if (and (not extensions) (fboundp 'image-file-name-regexp))
16024 (image-file-name-regexp)
16025 (let ((image-file-name-extensions
16026 (or extensions
16027 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
16028 "xbm" "xpm" "pbm" "pgm" "ppm"))))
16029 (concat "\\."
16030 (regexp-opt (nconc (mapcar 'upcase
16031 image-file-name-extensions)
16032 image-file-name-extensions)
16034 "\\'"))))
16036 (defun org-file-image-p (file &optional extensions)
16037 "Return non-nil if FILE is an image."
16038 (save-match-data
16039 (string-match (org-image-file-name-regexp extensions) file)))
16041 (defun org-get-cursor-date ()
16042 "Return the date at cursor in as a time.
16043 This works in the calendar and in the agenda, anywhere else it just
16044 returns the current time."
16045 (let (date day defd)
16046 (cond
16047 ((eq major-mode 'calendar-mode)
16048 (setq date (calendar-cursor-to-date)
16049 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16050 ((eq major-mode 'org-agenda-mode)
16051 (setq day (get-text-property (point) 'day))
16052 (if day
16053 (setq date (calendar-gregorian-from-absolute day)
16054 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
16055 (nth 2 date))))))
16056 (or defd (current-time))))
16058 (defvar org-agenda-action-marker (make-marker)
16059 "Marker pointing to the entry for the next agenda action.")
16061 (defun org-mark-entry-for-agenda-action ()
16062 "Mark the current entry as target of an agenda action.
16063 Agenda actions are actions executed from the agenda with the key `k',
16064 which make use of the date at the cursor."
16065 (interactive)
16066 (move-marker org-agenda-action-marker
16067 (save-excursion (org-back-to-heading t) (point))
16068 (current-buffer))
16069 (message
16070 "Entry marked for action; press `k' at desired date in agenda or calendar"))
16072 ;;; Paragraph filling stuff.
16073 ;; We want this to be just right, so use the full arsenal.
16075 (defun org-indent-line-function ()
16076 "Indent line like previous, but further if previous was headline or item."
16077 (interactive)
16078 (let* ((pos (point))
16079 (itemp (org-at-item-p))
16080 (org-drawer-regexp (or org-drawer-regexp "\000"))
16081 column bpos bcol tpos tcol bullet btype bullet-type)
16082 ;; Find the previous relevant line
16083 (beginning-of-line 1)
16084 (cond
16085 ((looking-at "#") (setq column 0))
16086 ((looking-at "\\*+ ") (setq column 0))
16087 ((and (looking-at "[ \t]*:END:")
16088 (save-excursion (re-search-backward org-drawer-regexp nil t)))
16089 (save-excursion
16090 (goto-char (1- (match-beginning 1)))
16091 (setq column (current-column))))
16093 (beginning-of-line 0)
16094 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
16095 (not (looking-at "[ \t]*:END:"))
16096 (not (looking-at org-drawer-regexp)))
16097 (beginning-of-line 0))
16098 (cond
16099 ((looking-at "\\*+[ \t]+")
16100 (if (not org-adapt-indentation)
16101 (setq column 0)
16102 (goto-char (match-end 0))
16103 (setq column (current-column))))
16104 ((looking-at org-drawer-regexp)
16105 (goto-char (1- (match-beginning 1)))
16106 (setq column (current-column)))
16107 ((looking-at "\\([ \t]*\\):END:")
16108 (goto-char (match-end 1))
16109 (setq column (current-column)))
16110 ((org-in-item-p)
16111 (org-beginning-of-item)
16112 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
16113 (setq bpos (match-beginning 1) tpos (match-end 0)
16114 bcol (progn (goto-char bpos) (current-column))
16115 tcol (progn (goto-char tpos) (current-column))
16116 bullet (match-string 1)
16117 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
16118 (if (> tcol (+ bcol org-description-max-indent))
16119 (setq tcol (+ bcol 5)))
16120 (if (not itemp)
16121 (setq column tcol)
16122 (goto-char pos)
16123 (beginning-of-line 1)
16124 (if (looking-at "\\S-")
16125 (progn
16126 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
16127 (setq bullet (match-string 1)
16128 btype (if (string-match "[0-9]" bullet) "n" bullet))
16129 (setq column (if (equal btype bullet-type) bcol tcol)))
16130 (setq column (org-get-indentation)))))
16131 (t (setq column (org-get-indentation))))))
16132 (goto-char pos)
16133 (if (<= (current-column) (current-indentation))
16134 (org-indent-line-to column)
16135 (save-excursion (org-indent-line-to column)))
16136 (setq column (current-column))
16137 (beginning-of-line 1)
16138 (if (looking-at
16139 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
16140 (replace-match (concat "\\1" (format org-property-format
16141 (match-string 2) (match-string 3)))
16142 t nil))
16143 (org-move-to-column column)))
16145 (defun org-set-autofill-regexps ()
16146 (interactive)
16147 ;; In the paragraph separator we include headlines, because filling
16148 ;; text in a line directly attached to a headline would otherwise
16149 ;; fill the headline as well.
16150 (org-set-local 'comment-start-skip "^#+[ \t]*")
16151 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
16152 ;; The paragraph starter includes hand-formatted lists.
16153 (org-set-local 'paragraph-start
16154 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
16155 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
16156 ;; But only if the user has not turned off tables or fixed-width regions
16157 (org-set-local
16158 'auto-fill-inhibit-regexp
16159 (concat "\\*+ \\|#\\+"
16160 "\\|[ \t]*" org-keyword-time-regexp
16161 (if (or org-enable-table-editor org-enable-fixed-width-editor)
16162 (concat
16163 "\\|[ \t]*["
16164 (if org-enable-table-editor "|" "")
16165 (if org-enable-fixed-width-editor ":" "")
16166 "]"))))
16167 ;; We use our own fill-paragraph function, to make sure that tables
16168 ;; and fixed-width regions are not wrapped. That function will pass
16169 ;; through to `fill-paragraph' when appropriate.
16170 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
16171 ; Adaptive filling: To get full control, first make sure that
16172 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
16173 (org-set-local 'adaptive-fill-regexp "\000")
16174 (org-set-local 'adaptive-fill-function
16175 'org-adaptive-fill-function)
16176 (org-set-local
16177 'align-mode-rules-list
16178 '((org-in-buffer-settings
16179 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
16180 (modes . '(org-mode))))))
16182 (defun org-fill-paragraph (&optional justify)
16183 "Re-align a table, pass through to fill-paragraph if no table."
16184 (let ((table-p (org-at-table-p))
16185 (table.el-p (org-at-table.el-p)))
16186 (cond ((and (equal (char-after (point-at-bol)) ?*)
16187 (save-excursion (goto-char (point-at-bol))
16188 (looking-at outline-regexp)))
16189 t) ; skip headlines
16190 (table.el-p t) ; skip table.el tables
16191 (table-p (org-table-align) t) ; align org-mode tables
16192 (t nil)))) ; call paragraph-fill
16194 ;; For reference, this is the default value of adaptive-fill-regexp
16195 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
16197 (defun org-adaptive-fill-function ()
16198 "Return a fill prefix for org-mode files.
16199 In particular, this makes sure hanging paragraphs for hand-formatted lists
16200 work correctly."
16201 (cond ((looking-at "#[ \t]+")
16202 (match-string 0))
16203 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
16204 (save-excursion
16205 (if (> (match-end 1) (+ (match-beginning 1)
16206 org-description-max-indent))
16207 (goto-char (+ (match-beginning 1) 5))
16208 (goto-char (match-end 0)))
16209 (make-string (current-column) ?\ )))
16210 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
16211 (save-excursion
16212 (goto-char (match-end 0))
16213 (make-string (current-column) ?\ )))
16214 (t nil)))
16216 ;;; Other stuff.
16218 (defun org-toggle-fixed-width-section (arg)
16219 "Toggle the fixed-width export.
16220 If there is no active region, the QUOTE keyword at the current headline is
16221 inserted or removed. When present, it causes the text between this headline
16222 and the next to be exported as fixed-width text, and unmodified.
16223 If there is an active region, this command adds or removes a colon as the
16224 first character of this line. If the first character of a line is a colon,
16225 this line is also exported in fixed-width font."
16226 (interactive "P")
16227 (let* ((cc 0)
16228 (regionp (org-region-active-p))
16229 (beg (if regionp (region-beginning) (point)))
16230 (end (if regionp (region-end)))
16231 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
16232 (case-fold-search nil)
16233 (re "[ \t]*\\(: \\)")
16234 off)
16235 (if regionp
16236 (save-excursion
16237 (goto-char beg)
16238 (setq cc (current-column))
16239 (beginning-of-line 1)
16240 (setq off (looking-at re))
16241 (while (> nlines 0)
16242 (setq nlines (1- nlines))
16243 (beginning-of-line 1)
16244 (cond
16245 (arg
16246 (org-move-to-column cc t)
16247 (insert ": \n")
16248 (forward-line -1))
16249 ((and off (looking-at re))
16250 (replace-match "" t t nil 1))
16251 ((not off) (org-move-to-column cc t) (insert ": ")))
16252 (forward-line 1)))
16253 (save-excursion
16254 (org-back-to-heading)
16255 (if (looking-at (concat outline-regexp
16256 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
16257 (replace-match "" t t nil 1)
16258 (if (looking-at outline-regexp)
16259 (progn
16260 (goto-char (match-end 0))
16261 (insert org-quote-string " "))))))))
16263 (defun org-reftex-citation ()
16264 "Use reftex-citation to insert a citation into the buffer.
16265 This looks for a line like
16267 #+BIBLIOGRAPHY: foo plain option:-d
16269 and derives from it that foo.bib is the bbliography file relevant
16270 for this document. It then installs the necessary environment for RefTeX
16271 to work in this buffer and calls `reftex-citation' to insert a citation
16272 into the buffer.
16274 Export of such citations to both LaTeX and HTML is handled by the contributed
16275 package org-exp-bibtex by Taru Karttunen."
16276 (interactive)
16277 (let ((reftex-docstruct-symbol 'rds)
16278 (reftex-cite-format "\\cite{%l}")
16279 rds bib)
16280 (save-excursion
16281 (save-restriction
16282 (widen)
16283 (let ((case-fold-search t)
16284 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
16285 (if (not (save-excursion
16286 (or (re-search-forward re nil t)
16287 (re-search-backward re nil t))))
16288 (error "No bibliography defined in file")
16289 (setq bib (concat (match-string 1) ".bib")
16290 rds (list (list 'bib bib)))))))
16291 (call-interactively 'reftex-citation)))
16293 ;;;; Functions extending outline functionality
16295 (defun org-beginning-of-line (&optional arg)
16296 "Go to the beginning of the current line. If that is invisible, continue
16297 to a visible line beginning. This makes the function of C-a more intuitive.
16298 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16299 first attempt, and only move to after the tags when the cursor is already
16300 beyond the end of the headline."
16301 (interactive "P")
16302 (let ((pos (point))
16303 (special (if (consp org-special-ctrl-a/e)
16304 (car org-special-ctrl-a/e)
16305 org-special-ctrl-a/e))
16306 refpos)
16307 (beginning-of-line 1)
16308 (if (and arg (fboundp 'move-beginning-of-line))
16309 (call-interactively 'move-beginning-of-line)
16310 (if (bobp)
16312 (backward-char 1)
16313 (if (org-invisible-p)
16314 (while (and (not (bobp)) (org-invisible-p))
16315 (backward-char 1)
16316 (beginning-of-line 1))
16317 (forward-char 1))))
16318 (when special
16319 (cond
16320 ((and (looking-at org-complex-heading-regexp)
16321 (= (char-after (match-end 1)) ?\ ))
16322 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
16323 (point-at-eol)))
16324 (goto-char
16325 (if (eq special t)
16326 (cond ((> pos refpos) refpos)
16327 ((= pos (point)) refpos)
16328 (t (point)))
16329 (cond ((> pos (point)) (point))
16330 ((not (eq last-command this-command)) (point))
16331 (t refpos)))))
16332 ((org-at-item-p)
16333 (goto-char
16334 (if (eq special t)
16335 (cond ((> pos (match-end 4)) (match-end 4))
16336 ((= pos (point)) (match-end 4))
16337 (t (point)))
16338 (cond ((> pos (point)) (point))
16339 ((not (eq last-command this-command)) (point))
16340 (t (match-end 4))))))))
16341 (org-no-warnings
16342 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16344 (defun org-end-of-line (&optional arg)
16345 "Go to the end of the line.
16346 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16347 first attempt, and only move to after the tags when the cursor is already
16348 beyond the end of the headline."
16349 (interactive "P")
16350 (let ((special (if (consp org-special-ctrl-a/e)
16351 (cdr org-special-ctrl-a/e)
16352 org-special-ctrl-a/e)))
16353 (if (or (not special)
16354 (not (org-on-heading-p))
16355 arg)
16356 (call-interactively (if (fboundp 'move-end-of-line)
16357 'move-end-of-line
16358 'end-of-line))
16359 (let ((pos (point)))
16360 (beginning-of-line 1)
16361 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
16362 (if (eq special t)
16363 (if (or (< pos (match-beginning 1))
16364 (= pos (match-end 0)))
16365 (goto-char (match-beginning 1))
16366 (goto-char (match-end 0)))
16367 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
16368 (goto-char (match-end 0))
16369 (goto-char (match-beginning 1))))
16370 (call-interactively (if (fboundp 'move-end-of-line)
16371 'move-end-of-line
16372 'end-of-line)))))
16373 (org-no-warnings
16374 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16376 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
16377 (define-key org-mode-map "\C-e" 'org-end-of-line)
16379 (defun org-backward-sentence (&optional arg)
16380 "Go to beginning of sentence, or beginning of table field.
16381 This will call `backward-sentence' or `org-table-beginning-of-field',
16382 depending on context."
16383 (interactive "P")
16384 (cond
16385 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
16386 (t (call-interactively 'backward-sentence))))
16388 (defun org-forward-sentence (&optional arg)
16389 "Go to end of sentence, or end of table field.
16390 This will call `forward-sentence' or `org-table-end-of-field',
16391 depending on context."
16392 (interactive "P")
16393 (cond
16394 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
16395 (t (call-interactively 'forward-sentence))))
16397 (define-key org-mode-map "\M-a" 'org-backward-sentence)
16398 (define-key org-mode-map "\M-e" 'org-forward-sentence)
16400 (defun org-kill-line (&optional arg)
16401 "Kill line, to tags or end of line."
16402 (interactive "P")
16403 (cond
16404 ((or (not org-special-ctrl-k)
16405 (bolp)
16406 (not (org-on-heading-p)))
16407 (call-interactively 'kill-line))
16408 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
16409 (kill-region (point) (match-beginning 1))
16410 (org-set-tags nil t))
16411 (t (kill-region (point) (point-at-eol)))))
16413 (define-key org-mode-map "\C-k" 'org-kill-line)
16415 (defun org-yank (&optional arg)
16416 "Yank. If the kill is a subtree, treat it specially.
16417 This command will look at the current kill and check if is a single
16418 subtree, or a series of subtrees[1]. If it passes the test, and if the
16419 cursor is at the beginning of a line or after the stars of a currently
16420 empty headline, then the yank is handled specially. How exactly depends
16421 on the value of the following variables, both set by default.
16423 org-yank-folded-subtrees
16424 When set, the subtree(s) will be folded after insertion, but only
16425 if doing so would now swallow text after the yanked text.
16427 org-yank-adjusted-subtrees
16428 When set, the subtree will be promoted or demoted in order to
16429 fit into the local outline tree structure, which means that the level
16430 will be adjusted so that it becomes the smaller one of the two
16431 *visible* surrounding headings.
16433 Any prefix to this command will cause `yank' to be called directly with
16434 no special treatment. In particular, a simple `C-u' prefix will just
16435 plainly yank the text as it is.
16437 \[1] The test checks if the first non-white line is a heading
16438 and if there are no other headings with fewer stars."
16439 (interactive "P")
16440 (org-yank-generic 'yank arg))
16442 (defun org-yank-generic (command arg)
16443 "Perform some yank-like command.
16445 This function implements the behavior described in the `org-yank'
16446 documentation. However, it has been generalized to work for any
16447 interactive command with similar behavior."
16449 ;; pretend to be command COMMAND
16450 (setq this-command command)
16452 (if arg
16453 (call-interactively command)
16455 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
16456 (and (org-kill-is-subtree-p)
16457 (or (bolp)
16458 (and (looking-at "[ \t]*$")
16459 (string-match
16460 "\\`\\*+\\'"
16461 (buffer-substring (point-at-bol) (point)))))))
16462 swallowp)
16463 (cond
16464 ((and subtreep org-yank-folded-subtrees)
16465 (let ((beg (point))
16466 end)
16467 (if (and subtreep org-yank-adjusted-subtrees)
16468 (org-paste-subtree nil nil 'for-yank)
16469 (call-interactively command))
16471 (setq end (point))
16472 (goto-char beg)
16473 (when (and (bolp) subtreep
16474 (not (setq swallowp
16475 (org-yank-folding-would-swallow-text beg end))))
16476 (or (looking-at outline-regexp)
16477 (re-search-forward (concat "^" outline-regexp) end t))
16478 (while (and (< (point) end) (looking-at outline-regexp))
16479 (hide-subtree)
16480 (org-cycle-show-empty-lines 'folded)
16481 (condition-case nil
16482 (outline-forward-same-level 1)
16483 (error (goto-char end)))))
16484 (when swallowp
16485 (message
16486 "Inserted text not folded because that would swallow text"))
16488 (goto-char end)
16489 (skip-chars-forward " \t\n\r")
16490 (beginning-of-line 1)
16491 (push-mark beg 'nomsg)))
16492 ((and subtreep org-yank-adjusted-subtrees)
16493 (let ((beg (point-at-bol)))
16494 (org-paste-subtree nil nil 'for-yank)
16495 (push-mark beg 'nomsg)))
16497 (call-interactively command))))))
16499 (defun org-yank-folding-would-swallow-text (beg end)
16500 "Would hide-subtree at BEG swallow any text after END?"
16501 (let (level)
16502 (save-excursion
16503 (goto-char beg)
16504 (when (or (looking-at outline-regexp)
16505 (re-search-forward (concat "^" outline-regexp) end t))
16506 (setq level (org-outline-level)))
16507 (goto-char end)
16508 (skip-chars-forward " \t\r\n\v\f")
16509 (if (or (eobp)
16510 (and (bolp) (looking-at org-outline-regexp)
16511 (<= (org-outline-level) level)))
16512 nil ; Nothing would be swallowed
16513 t)))) ; something would swallow
16515 (define-key org-mode-map "\C-y" 'org-yank)
16517 (defun org-invisible-p ()
16518 "Check if point is at a character currently not visible."
16519 ;; Early versions of noutline don't have `outline-invisible-p'.
16520 (if (fboundp 'outline-invisible-p)
16521 (outline-invisible-p)
16522 (get-char-property (point) 'invisible)))
16524 (defun org-invisible-p2 ()
16525 "Check if point is at a character currently not visible."
16526 (save-excursion
16527 (if (and (eolp) (not (bobp))) (backward-char 1))
16528 ;; Early versions of noutline don't have `outline-invisible-p'.
16529 (if (fboundp 'outline-invisible-p)
16530 (outline-invisible-p)
16531 (get-char-property (point) 'invisible))))
16533 (defun org-back-to-heading (&optional invisible-ok)
16534 "Call `outline-back-to-heading', but provide a better error message."
16535 (condition-case nil
16536 (outline-back-to-heading invisible-ok)
16537 (error (error "Before first headline at position %d in buffer %s"
16538 (point) (current-buffer)))))
16540 (defun org-before-first-heading-p ()
16541 "Before first heading?"
16542 (save-excursion
16543 (null (re-search-backward "^\\*+ " nil t))))
16545 (defalias 'org-on-heading-p 'outline-on-heading-p)
16546 (defalias 'org-at-heading-p 'outline-on-heading-p)
16547 (defun org-at-heading-or-item-p ()
16548 (or (org-on-heading-p) (org-at-item-p)))
16550 (defun org-on-target-p ()
16551 (or (org-in-regexp org-radio-target-regexp)
16552 (org-in-regexp org-target-regexp)))
16554 (defun org-up-heading-all (arg)
16555 "Move to the heading line of which the present line is a subheading.
16556 This function considers both visible and invisible heading lines.
16557 With argument, move up ARG levels."
16558 (if (fboundp 'outline-up-heading-all)
16559 (outline-up-heading-all arg) ; emacs 21 version of outline.el
16560 (outline-up-heading arg t))) ; emacs 22 version of outline.el
16562 (defun org-up-heading-safe ()
16563 "Move to the heading line of which the present line is a subheading.
16564 This version will not throw an error. It will return the level of the
16565 headline found, or nil if no higher level is found.
16567 Also, this function will be a lot faster than `outline-up-heading',
16568 because it relies on stars being the outline starters. This can really
16569 make a significant difference in outlines with very many siblings."
16570 (let (start-level re)
16571 (org-back-to-heading t)
16572 (setq start-level (funcall outline-level))
16573 (if (equal start-level 1)
16575 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
16576 (if (re-search-backward re nil t)
16577 (funcall outline-level)))))
16579 (defun org-first-sibling-p ()
16580 "Is this heading the first child of its parents?"
16581 (interactive)
16582 (let ((re (concat "^" outline-regexp))
16583 level l)
16584 (unless (org-at-heading-p t)
16585 (error "Not at a heading"))
16586 (setq level (funcall outline-level))
16587 (save-excursion
16588 (if (not (re-search-backward re nil t))
16590 (setq l (funcall outline-level))
16591 (< l level)))))
16593 (defun org-goto-sibling (&optional previous)
16594 "Goto the next sibling, even if it is invisible.
16595 When PREVIOUS is set, go to the previous sibling instead. Returns t
16596 when a sibling was found. When none is found, return nil and don't
16597 move point."
16598 (let ((fun (if previous 're-search-backward 're-search-forward))
16599 (pos (point))
16600 (re (concat "^" outline-regexp))
16601 level l)
16602 (when (condition-case nil (org-back-to-heading t) (error nil))
16603 (setq level (funcall outline-level))
16604 (catch 'exit
16605 (or previous (forward-char 1))
16606 (while (funcall fun re nil t)
16607 (setq l (funcall outline-level))
16608 (when (< l level) (goto-char pos) (throw 'exit nil))
16609 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
16610 (goto-char pos)
16611 nil))))
16613 (defun org-show-siblings ()
16614 "Show all siblings of the current headline."
16615 (save-excursion
16616 (while (org-goto-sibling) (org-flag-heading nil)))
16617 (save-excursion
16618 (while (org-goto-sibling 'previous)
16619 (org-flag-heading nil))))
16621 (defun org-show-hidden-entry ()
16622 "Show an entry where even the heading is hidden."
16623 (save-excursion
16624 (org-show-entry)))
16626 (defun org-flag-heading (flag &optional entry)
16627 "Flag the current heading. FLAG non-nil means make invisible.
16628 When ENTRY is non-nil, show the entire entry."
16629 (save-excursion
16630 (org-back-to-heading t)
16631 ;; Check if we should show the entire entry
16632 (if entry
16633 (progn
16634 (org-show-entry)
16635 (save-excursion
16636 (and (outline-next-heading)
16637 (org-flag-heading nil))))
16638 (outline-flag-region (max (point-min) (1- (point)))
16639 (save-excursion (outline-end-of-heading) (point))
16640 flag))))
16642 (defun org-forward-same-level (arg)
16643 "Move forward to the ARG'th subheading at same level as this one.
16644 Stop at the first and last subheadings of a superior heading.
16645 This is like outline-forward-same-level, but invisible headings are ok."
16646 (interactive "p")
16647 (org-back-to-heading t)
16648 (while (> arg 0)
16649 (let ((point-to-move-to (save-excursion
16650 (org-get-next-sibling))))
16651 (if point-to-move-to
16652 (progn
16653 (goto-char point-to-move-to)
16654 (setq arg (1- arg)))
16655 (progn
16656 (setq arg 0)
16657 (error "No following same-level heading"))))))
16659 (defun org-get-next-sibling ()
16660 "Move to next heading of the same level, and return point.
16661 If there is no such heading, return nil.
16662 This is like outline-next-sibling, but invisible headings are ok."
16663 (let ((level (funcall outline-level)))
16664 (outline-next-heading)
16665 (while (and (not (eobp)) (> (funcall outline-level) level))
16666 (outline-next-heading))
16667 (if (or (eobp) (< (funcall outline-level) level))
16669 (point))))
16671 (defun org-end-of-subtree (&optional invisible-OK to-heading)
16672 ;; This contains an exact copy of the original function, but it uses
16673 ;; `org-back-to-heading', to make it work also in invisible
16674 ;; trees. And is uses an invisible-OK argument.
16675 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
16676 ;; Furthermore, when used inside Org, finding the end of a large subtree
16677 ;; with many children and grandchildren etc, this can be much faster
16678 ;; than the outline version.
16679 (org-back-to-heading invisible-OK)
16680 (let ((first t)
16681 (level (funcall outline-level)))
16682 (if (and (org-mode-p) (< level 1000))
16683 ;; A true heading (not a plain list item), in Org-mode
16684 ;; This means we can easily find the end by looking
16685 ;; only for the right number of stars. Using a regexp to do
16686 ;; this is so much faster than using a Lisp loop.
16687 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
16688 (forward-char 1)
16689 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
16690 ;; something else, do it the slow way
16691 (while (and (not (eobp))
16692 (or first (> (funcall outline-level) level)))
16693 (setq first nil)
16694 (outline-next-heading)))
16695 (unless to-heading
16696 (if (memq (preceding-char) '(?\n ?\^M))
16697 (progn
16698 ;; Go to end of line before heading
16699 (forward-char -1)
16700 (if (memq (preceding-char) '(?\n ?\^M))
16701 ;; leave blank line before heading
16702 (forward-char -1))))))
16703 (point))
16705 (defun org-show-subtree ()
16706 "Show everything after this heading at deeper levels."
16707 (outline-flag-region
16708 (point)
16709 (save-excursion
16710 (outline-end-of-subtree) (outline-next-heading) (point))
16711 nil))
16713 (defun org-show-entry ()
16714 "Show the body directly following this heading.
16715 Show the heading too, if it is currently invisible."
16716 (interactive)
16717 (save-excursion
16718 (condition-case nil
16719 (progn
16720 (org-back-to-heading t)
16721 (outline-flag-region
16722 (max (point-min) (1- (point)))
16723 (save-excursion
16724 (if (re-search-forward
16725 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
16726 (match-beginning 1)
16727 (point-max)))
16728 nil))
16729 (error nil))))
16731 (defun org-make-options-regexp (kwds &optional extra)
16732 "Make a regular expression for keyword lines."
16733 (concat
16735 "#?[ \t]*\\+\\("
16736 (mapconcat 'regexp-quote kwds "\\|")
16737 (if extra (concat "\\|" extra))
16738 "\\):[ \t]*"
16739 "\\(.+\\)"))
16741 ;; Make isearch reveal the necessary context
16742 (defun org-isearch-end ()
16743 "Reveal context after isearch exits."
16744 (when isearch-success ; only if search was successful
16745 (if (featurep 'xemacs)
16746 ;; Under XEmacs, the hook is run in the correct place,
16747 ;; we directly show the context.
16748 (org-show-context 'isearch)
16749 ;; In Emacs the hook runs *before* restoring the overlays.
16750 ;; So we have to use a one-time post-command-hook to do this.
16751 ;; (Emacs 22 has a special variable, see function `org-mode')
16752 (unless (and (boundp 'isearch-mode-end-hook-quit)
16753 isearch-mode-end-hook-quit)
16754 ;; Only when the isearch was not quitted.
16755 (org-add-hook 'post-command-hook 'org-isearch-post-command
16756 'append 'local)))))
16758 (defun org-isearch-post-command ()
16759 "Remove self from hook, and show context."
16760 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
16761 (org-show-context 'isearch))
16764 ;;;; Integration with and fixes for other packages
16766 ;;; Imenu support
16768 (defvar org-imenu-markers nil
16769 "All markers currently used by Imenu.")
16770 (make-variable-buffer-local 'org-imenu-markers)
16772 (defun org-imenu-new-marker (&optional pos)
16773 "Return a new marker for use by Imenu, and remember the marker."
16774 (let ((m (make-marker)))
16775 (move-marker m (or pos (point)))
16776 (push m org-imenu-markers)
16779 (defun org-imenu-get-tree ()
16780 "Produce the index for Imenu."
16781 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
16782 (setq org-imenu-markers nil)
16783 (let* ((n org-imenu-depth)
16784 (re (concat "^" outline-regexp))
16785 (subs (make-vector (1+ n) nil))
16786 (last-level 0)
16787 m level head)
16788 (save-excursion
16789 (save-restriction
16790 (widen)
16791 (goto-char (point-max))
16792 (while (re-search-backward re nil t)
16793 (setq level (org-reduced-level (funcall outline-level)))
16794 (when (<= level n)
16795 (looking-at org-complex-heading-regexp)
16796 (setq head (org-link-display-format
16797 (org-match-string-no-properties 4))
16798 m (org-imenu-new-marker))
16799 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
16800 (if (>= level last-level)
16801 (push (cons head m) (aref subs level))
16802 (push (cons head (aref subs (1+ level))) (aref subs level))
16803 (loop for i from (1+ level) to n do (aset subs i nil)))
16804 (setq last-level level)))))
16805 (aref subs 1)))
16807 (eval-after-load "imenu"
16808 '(progn
16809 (add-hook 'imenu-after-jump-hook
16810 (lambda ()
16811 (if (eq major-mode 'org-mode)
16812 (org-show-context 'org-goto))))))
16814 (defun org-link-display-format (link)
16815 "Replace a link with either the description, or the link target
16816 if no description is present"
16817 (save-match-data
16818 (if (string-match org-bracket-link-analytic-regexp link)
16819 (replace-match (or (match-string 5 link)
16820 (concat (match-string 1 link)
16821 (match-string 3 link)))
16822 nil nil link)
16823 link)))
16825 ;; Speedbar support
16827 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
16828 "Overlay marking the agenda restriction line in speedbar.")
16829 (org-overlay-put org-speedbar-restriction-lock-overlay
16830 'face 'org-agenda-restriction-lock)
16831 (org-overlay-put org-speedbar-restriction-lock-overlay
16832 'help-echo "Agendas are currently limited to this item.")
16833 (org-detach-overlay org-speedbar-restriction-lock-overlay)
16835 (defun org-speedbar-set-agenda-restriction ()
16836 "Restrict future agenda commands to the location at point in speedbar.
16837 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
16838 (interactive)
16839 (require 'org-agenda)
16840 (let (p m tp np dir txt)
16841 (cond
16842 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16843 'org-imenu t))
16844 (setq m (get-text-property p 'org-imenu-marker))
16845 (save-excursion
16846 (save-restriction
16847 (set-buffer (marker-buffer m))
16848 (goto-char m)
16849 (org-agenda-set-restriction-lock 'subtree))))
16850 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16851 'speedbar-function 'speedbar-find-file))
16852 (setq tp (previous-single-property-change
16853 (1+ p) 'speedbar-function)
16854 np (next-single-property-change
16855 tp 'speedbar-function)
16856 dir (speedbar-line-directory)
16857 txt (buffer-substring-no-properties (or tp (point-min))
16858 (or np (point-max))))
16859 (save-excursion
16860 (save-restriction
16861 (set-buffer (find-file-noselect
16862 (let ((default-directory dir))
16863 (expand-file-name txt))))
16864 (unless (org-mode-p)
16865 (error "Cannot restrict to non-Org-mode file"))
16866 (org-agenda-set-restriction-lock 'file))))
16867 (t (error "Don't know how to restrict Org-mode's agenda")))
16868 (org-move-overlay org-speedbar-restriction-lock-overlay
16869 (point-at-bol) (point-at-eol))
16870 (setq current-prefix-arg nil)
16871 (org-agenda-maybe-redo)))
16873 (eval-after-load "speedbar"
16874 '(progn
16875 (speedbar-add-supported-extension ".org")
16876 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
16877 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
16878 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
16879 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16880 (add-hook 'speedbar-visiting-tag-hook
16881 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
16884 ;;; Fixes and Hacks for problems with other packages
16886 ;; Make flyspell not check words in links, to not mess up our keymap
16887 (defun org-mode-flyspell-verify ()
16888 "Don't let flyspell put overlays at active buttons."
16889 (not (get-text-property (point) 'keymap)))
16891 (defun org-remove-flyspell-overlays-in (beg end)
16892 "Remove flyspell overlays in region."
16893 (and (org-bound-and-true-p flyspell-mode)
16894 (fboundp 'flyspell-delete-region-overlays)
16895 (flyspell-delete-region-overlays beg end)))
16897 ;; Make `bookmark-jump' show the jump location if it was hidden.
16898 (eval-after-load "bookmark"
16899 '(if (boundp 'bookmark-after-jump-hook)
16900 ;; We can use the hook
16901 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
16902 ;; Hook not available, use advice
16903 (defadvice bookmark-jump (after org-make-visible activate)
16904 "Make the position visible."
16905 (org-bookmark-jump-unhide))))
16907 ;; Make sure saveplace show the location if it was hidden
16908 (eval-after-load "saveplace"
16909 '(defadvice save-place-find-file-hook (after org-make-visible activate)
16910 "Make the position visible."
16911 (org-bookmark-jump-unhide)))
16913 (defun org-bookmark-jump-unhide ()
16914 "Unhide the current position, to show the bookmark location."
16915 (and (org-mode-p)
16916 (or (org-invisible-p)
16917 (save-excursion (goto-char (max (point-min) (1- (point))))
16918 (org-invisible-p)))
16919 (org-show-context 'bookmark-jump)))
16921 ;; Make session.el ignore our circular variable
16922 (eval-after-load "session"
16923 '(add-to-list 'session-globals-exclude 'org-mark-ring))
16925 ;;;; Experimental code
16927 (defun org-closed-in-range ()
16928 "Sparse tree of items closed in a certain time range.
16929 Still experimental, may disappear in the future."
16930 (interactive)
16931 ;; Get the time interval from the user.
16932 (let* ((time1 (time-to-seconds
16933 (org-read-date nil 'to-time nil "Starting date: ")))
16934 (time2 (time-to-seconds
16935 (org-read-date nil 'to-time nil "End date:")))
16936 ;; callback function
16937 (callback (lambda ()
16938 (let ((time
16939 (time-to-seconds
16940 (apply 'encode-time
16941 (org-parse-time-string
16942 (match-string 1))))))
16943 ;; check if time in interval
16944 (and (>= time time1) (<= time time2))))))
16945 ;; make tree, check each match with the callback
16946 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
16948 ;;;; Finish up
16950 (provide 'org)
16952 (run-hooks 'org-load-hook)
16954 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
16956 ;;; org.el ends here