Statistics: New hooks
[org-mode.git] / lisp / org.el
blob9b415e35d370efd0cffb4c9cbe87b8c767f6a2d3
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009
4 ;; Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;; Version: 6.26trans
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum)
76 (require 'calendar))
77 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
78 ;; the file noutline.el being loaded.
79 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
80 ;; We require noutline, which might be provided in outline.el
81 (require 'outline) (require 'noutline)
82 ;; Other stuff we need.
83 (require 'time-date)
84 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
85 (require 'easymenu)
87 (require 'org-macs)
88 (require 'org-compat)
89 (require 'org-faces)
90 (require 'org-list)
91 (require 'org-footnote)
93 ;;;; Customization variables
95 ;;; Version
97 (defconst org-version "6.26trans"
98 "The version number of the file org.el.")
100 (defun org-version (&optional here)
101 "Show the org-mode version in the echo area.
102 With prefix arg HERE, insert it at point."
103 (interactive "P")
104 (let ((version (format "Org-mode version %s" org-version)))
105 (message version)
106 (if here
107 (insert version))))
109 ;;; Compatibility constants
111 ;;; The custom variables
113 (defgroup org nil
114 "Outline-based notes management and organizer."
115 :tag "Org"
116 :group 'outlines
117 :group 'hypermedia
118 :group 'calendar)
120 (defcustom org-load-hook nil
121 "Hook that is run after org.el has been loaded."
122 :group 'org
123 :type 'hook)
125 (defvar org-modules) ; defined below
126 (defvar org-modules-loaded nil
127 "Have the modules been loaded already?")
129 (defun org-load-modules-maybe (&optional force)
130 "Load all extensions listed in `org-modules'."
131 (when (or force (not org-modules-loaded))
132 (mapc (lambda (ext)
133 (condition-case nil (require ext)
134 (error (message "Problems while trying to load feature `%s'" ext))))
135 org-modules)
136 (setq org-modules-loaded t)))
138 (defun org-set-modules (var value)
139 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
140 (set var value)
141 (when (featurep 'org)
142 (org-load-modules-maybe 'force)))
144 (when (org-bound-and-true-p org-modules)
145 (let ((a (member 'org-infojs org-modules)))
146 (and a (setcar a 'org-jsinfo))))
148 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
149 "Modules that should always be loaded together with org.el.
150 If a description starts with <C>, the file is not part of Emacs
151 and loading it will require that you have downloaded and properly installed
152 the org-mode distribution.
154 You can also use this system to load external packages (i.e. neither Org
155 core modules, not modules from the CONTRIB directory). Just add symbols
156 to the end of the list. If the package is called org-xyz.el, then you need
157 to add the symbol `xyz', and the package must have a call to
159 (provide 'org-xyz)"
160 :group 'org
161 :set 'org-set-modules
162 :type
163 '(set :greedy t
164 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
165 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
166 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
167 (const :tag " id: Global IDs for identifying entries" org-id)
168 (const :tag " info: Links to Info nodes" org-info)
169 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
170 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
171 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
172 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
173 (const :tag " mew Links to Mew folders/messages" org-mew)
174 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
175 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
176 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
177 (const :tag " vm: Links to VM folders/messages" org-vm)
178 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
179 (const :tag " w3m: Special cut/paste from w3m to Org." org-w3m)
180 (const :tag " mouse: Additional mouse support" org-mouse)
182 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
183 (const :tag "C annotation-helper: Call Remember directly from Browser (OBSOLETE, use org-protocol)" org-annotation-helper)
184 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
185 (const :tag "C browser-url: Store link, directly from Browser (OBSOLETE, use org-protocol)" org-browser-url)
186 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
187 (const :tag "C collector: Collect properties into tables" org-collector)
188 (const :tag "C depend: TODO dependencies for Org-mode (PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
189 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
190 (const :tag "C eval: Include command output as text" org-eval)
191 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
192 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
193 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
194 (const :tag "C exp-blocks: Pre-process blocks for export" org-exp-blocks)
195 (const :tag "C interactive-query: Interactive modification of tags query (PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
196 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
197 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
198 (const :tag "C mtags: Support for muse-like tags" org-mtags)
199 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
200 (const :tag "C R: Computation using the R language" org-R)
201 (const :tag "C registry: A registry for Org links" org-registry)
202 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
203 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
204 (const :tag "C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
205 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
206 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
207 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
209 (defcustom org-support-shift-select nil
210 "Non-nil means, make shift-cursor commands select text when possible.
212 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
213 selecting a region, or enlarge thusly regions started in this way.
214 In Org-mode, in special contexts, these same keys are used for other
215 purposes, important enough to compete with shift selection. Org tries
216 to balance these needs by supporting `shift-select-mode' outside these
217 special contexts, under control of this variable.
219 The default of this variable is nil, to avoid confusing behavior. Shifted
220 cursor keys will then execute Org commands in the following contexts:
221 - on a headline, changing TODO state (left/right) and priority (up/down)
222 - on a time stamp, changing the time
223 - in a plain list item, changing the bullet type
224 - in a property definition line, switching between allowed values
225 - in the BEGIN line of a clock table (changing the time block).
226 Outside these contexts, the commands will throw an error.
228 When this variable is t and the cursor is not in a special context,
229 Org-mode will support shift-selection for making and enlarging regions.
230 To make this more effective, the bullet cycling will no longer happen
231 anywhere in an item line, but only if the cursor is exactly on the bullet.
233 If you set this variable to the symbol `always', then the keys
234 will not be special in headlines, property lines, and item lines, to make
235 shift selection work there as well. If this is what you want, you can
236 use the following alternative commands: `C-c C-t' and `C-c ,' to
237 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
238 TODO sets, `C-c -' to cycle item bullet types, and properties can be
239 edited by hand or in column view.
241 However, when the cursor is on a timestamp, shift-cursor commands
242 will still edit the time stamp - this is just too good to give up.
244 XEmacs user should have this variable set to nil, because shift-select-mode
245 is Emacs 23 only."
246 :group 'org
247 :type '(choice
248 (const :tag "Never" nil)
249 (const :tag "When outside special context" t)
250 (const :tag "Everywhere except timestamps" always)))
252 (defgroup org-startup nil
253 "Options concerning startup of Org-mode."
254 :tag "Org Startup"
255 :group 'org)
257 (defcustom org-startup-folded t
258 "Non-nil means, entering Org-mode will switch to OVERVIEW.
259 This can also be configured on a per-file basis by adding one of
260 the following lines anywhere in the buffer:
262 #+STARTUP: fold
263 #+STARTUP: nofold
264 #+STARTUP: content"
265 :group 'org-startup
266 :type '(choice
267 (const :tag "nofold: show all" nil)
268 (const :tag "fold: overview" t)
269 (const :tag "content: all headlines" content)))
271 (defcustom org-startup-truncated t
272 "Non-nil means, entering Org-mode will set `truncate-lines'.
273 This is useful since some lines containing links can be very long and
274 uninteresting. Also tables look terrible when wrapped."
275 :group 'org-startup
276 :type 'boolean)
278 (defcustom org-startup-align-all-tables nil
279 "Non-nil means, align all tables when visiting a file.
280 This is useful when the column width in tables is forced with <N> cookies
281 in table fields. Such tables will look correct only after the first re-align.
282 This can also be configured on a per-file basis by adding one of
283 the following lines anywhere in the buffer:
284 #+STARTUP: align
285 #+STARTUP: noalign"
286 :group 'org-startup
287 :type 'boolean)
289 (defcustom org-insert-mode-line-in-empty-file nil
290 "Non-nil means insert the first line setting Org-mode in empty files.
291 When the function `org-mode' is called interactively in an empty file, this
292 normally means that the file name does not automatically trigger Org-mode.
293 To ensure that the file will always be in Org-mode in the future, a
294 line enforcing Org-mode will be inserted into the buffer, if this option
295 has been set."
296 :group 'org-startup
297 :type 'boolean)
299 (defcustom org-replace-disputed-keys nil
300 "Non-nil means use alternative key bindings for some keys.
301 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
302 These keys are also used by other packages like shift-selection-mode'
303 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
304 If you want to use Org-mode together with one of these other modes,
305 or more generally if you would like to move some Org-mode commands to
306 other keys, set this variable and configure the keys with the variable
307 `org-disputed-keys'.
309 This option is only relevant at load-time of Org-mode, and must be set
310 *before* org.el is loaded. Changing it requires a restart of Emacs to
311 become effective."
312 :group 'org-startup
313 :type 'boolean)
315 (defcustom org-use-extra-keys nil
316 "Non-nil means use extra key sequence definitions for certain
317 commands. This happens automatically if you run XEmacs or if
318 window-system is nil. This variable lets you do the same
319 manually. You must set it before loading org.
321 Example: on Carbon Emacs 22 running graphically, with an external
322 keyboard on a Powerbook, the default way of setting M-left might
323 not work for either Alt or ESC. Setting this variable will make
324 it work for ESC."
325 :group 'org-startup
326 :type 'boolean)
328 (if (fboundp 'defvaralias)
329 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
331 (defcustom org-disputed-keys
332 '(([(shift up)] . [(meta p)])
333 ([(shift down)] . [(meta n)])
334 ([(shift left)] . [(meta -)])
335 ([(shift right)] . [(meta +)])
336 ([(control shift right)] . [(meta shift +)])
337 ([(control shift left)] . [(meta shift -)]))
338 "Keys for which Org-mode and other modes compete.
339 This is an alist, cars are the default keys, second element specifies
340 the alternative to use when `org-replace-disputed-keys' is t.
342 Keys can be specified in any syntax supported by `define-key'.
343 The value of this option takes effect only at Org-mode's startup,
344 therefore you'll have to restart Emacs to apply it after changing."
345 :group 'org-startup
346 :type 'alist)
348 (defun org-key (key)
349 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
350 Or return the original if not disputed."
351 (if org-replace-disputed-keys
352 (let* ((nkey (key-description key))
353 (x (org-find-if (lambda (x)
354 (equal (key-description (car x)) nkey))
355 org-disputed-keys)))
356 (if x (cdr x) key))
357 key))
359 (defun org-find-if (predicate seq)
360 (catch 'exit
361 (while seq
362 (if (funcall predicate (car seq))
363 (throw 'exit (car seq))
364 (pop seq)))))
366 (defun org-defkey (keymap key def)
367 "Define a key, possibly translated, as returned by `org-key'."
368 (define-key keymap (org-key key) def))
370 (defcustom org-ellipsis nil
371 "The ellipsis to use in the Org-mode outline.
372 When nil, just use the standard three dots. When a string, use that instead,
373 When a face, use the standard 3 dots, but with the specified face.
374 The change affects only Org-mode (which will then use its own display table).
375 Changing this requires executing `M-x org-mode' in a buffer to become
376 effective."
377 :group 'org-startup
378 :type '(choice (const :tag "Default" nil)
379 (face :tag "Face" :value org-warning)
380 (string :tag "String" :value "...#")))
382 (defvar org-display-table nil
383 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
385 (defgroup org-keywords nil
386 "Keywords in Org-mode."
387 :tag "Org Keywords"
388 :group 'org)
390 (defcustom org-deadline-string "DEADLINE:"
391 "String to mark deadline entries.
392 A deadline is this string, followed by a time stamp. Should be a word,
393 terminated by a colon. You can insert a schedule keyword and
394 a timestamp with \\[org-deadline].
395 Changes become only effective after restarting Emacs."
396 :group 'org-keywords
397 :type 'string)
399 (defcustom org-scheduled-string "SCHEDULED:"
400 "String to mark scheduled TODO entries.
401 A schedule is this string, followed by a time stamp. Should be a word,
402 terminated by a colon. You can insert a schedule keyword and
403 a timestamp with \\[org-schedule].
404 Changes become only effective after restarting Emacs."
405 :group 'org-keywords
406 :type 'string)
408 (defcustom org-closed-string "CLOSED:"
409 "String used as the prefix for timestamps logging closing a TODO entry."
410 :group 'org-keywords
411 :type 'string)
413 (defcustom org-clock-string "CLOCK:"
414 "String used as prefix for timestamps clocking work hours on an item."
415 :group 'org-keywords
416 :type 'string)
418 (defcustom org-comment-string "COMMENT"
419 "Entries starting with this keyword will never be exported.
420 An entry can be toggled between COMMENT and normal with
421 \\[org-toggle-comment].
422 Changes become only effective after restarting Emacs."
423 :group 'org-keywords
424 :type 'string)
426 (defcustom org-quote-string "QUOTE"
427 "Entries starting with this keyword will be exported in fixed-width font.
428 Quoting applies only to the text in the entry following the headline, and does
429 not extend beyond the next headline, even if that is lower level.
430 An entry can be toggled between QUOTE and normal with
431 \\[org-toggle-fixed-width-section]."
432 :group 'org-keywords
433 :type 'string)
435 (defconst org-repeat-re
436 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
437 "Regular expression for specifying repeated events.
438 After a match, group 1 contains the repeat expression.")
440 (defgroup org-structure nil
441 "Options concerning the general structure of Org-mode files."
442 :tag "Org Structure"
443 :group 'org)
445 (defgroup org-reveal-location nil
446 "Options about how to make context of a location visible."
447 :tag "Org Reveal Location"
448 :group 'org-structure)
450 (defconst org-context-choice
451 '(choice
452 (const :tag "Always" t)
453 (const :tag "Never" nil)
454 (repeat :greedy t :tag "Individual contexts"
455 (cons
456 (choice :tag "Context"
457 (const agenda)
458 (const org-goto)
459 (const occur-tree)
460 (const tags-tree)
461 (const link-search)
462 (const mark-goto)
463 (const bookmark-jump)
464 (const isearch)
465 (const default))
466 (boolean))))
467 "Contexts for the reveal options.")
469 (defcustom org-show-hierarchy-above '((default . t))
470 "Non-nil means, show full hierarchy when revealing a location.
471 Org-mode often shows locations in an org-mode file which might have
472 been invisible before. When this is set, the hierarchy of headings
473 above the exposed location is shown.
474 Turning this off for example for sparse trees makes them very compact.
475 Instead of t, this can also be an alist specifying this option for different
476 contexts. Valid contexts are
477 agenda when exposing an entry from the agenda
478 org-goto when using the command `org-goto' on key C-c C-j
479 occur-tree when using the command `org-occur' on key C-c /
480 tags-tree when constructing a sparse tree based on tags matches
481 link-search when exposing search matches associated with a link
482 mark-goto when exposing the jump goal of a mark
483 bookmark-jump when exposing a bookmark location
484 isearch when exiting from an incremental search
485 default default for all contexts not set explicitly"
486 :group 'org-reveal-location
487 :type org-context-choice)
489 (defcustom org-show-following-heading '((default . nil))
490 "Non-nil means, show following heading when revealing a location.
491 Org-mode often shows locations in an org-mode file which might have
492 been invisible before. When this is set, the heading following the
493 match is shown.
494 Turning this off for example for sparse trees makes them very compact,
495 but makes it harder to edit the location of the match. In such a case,
496 use the command \\[org-reveal] to show more context.
497 Instead of t, this can also be an alist specifying this option for different
498 contexts. See `org-show-hierarchy-above' for valid contexts."
499 :group 'org-reveal-location
500 :type org-context-choice)
502 (defcustom org-show-siblings '((default . nil) (isearch t))
503 "Non-nil means, show all sibling heading when revealing a location.
504 Org-mode often shows locations in an org-mode file which might have
505 been invisible before. When this is set, the sibling of the current entry
506 heading are all made visible. If `org-show-hierarchy-above' is t,
507 the same happens on each level of the hierarchy above the current entry.
509 By default this is on for the isearch context, off for all other contexts.
510 Turning this off for example for sparse trees makes them very compact,
511 but makes it harder to edit the location of the match. In such a case,
512 use the command \\[org-reveal] to show more context.
513 Instead of t, this can also be an alist specifying this option for different
514 contexts. See `org-show-hierarchy-above' for valid contexts."
515 :group 'org-reveal-location
516 :type org-context-choice)
518 (defcustom org-show-entry-below '((default . nil))
519 "Non-nil means, show the entry below a headline when revealing a location.
520 Org-mode often shows locations in an org-mode file which might have
521 been invisible before. When this is set, the text below the headline that is
522 exposed is also shown.
524 By default this is off for all contexts.
525 Instead of t, this can also be an alist specifying this option for different
526 contexts. See `org-show-hierarchy-above' for valid contexts."
527 :group 'org-reveal-location
528 :type org-context-choice)
530 (defcustom org-indirect-buffer-display 'other-window
531 "How should indirect tree buffers be displayed?
532 This applies to indirect buffers created with the commands
533 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
534 Valid values are:
535 current-window Display in the current window
536 other-window Just display in another window.
537 dedicated-frame Create one new frame, and re-use it each time.
538 new-frame Make a new frame each time. Note that in this case
539 previously-made indirect buffers are kept, and you need to
540 kill these buffers yourself."
541 :group 'org-structure
542 :group 'org-agenda-windows
543 :type '(choice
544 (const :tag "In current window" current-window)
545 (const :tag "In current frame, other window" other-window)
546 (const :tag "Each time a new frame" new-frame)
547 (const :tag "One dedicated frame" dedicated-frame)))
549 (defgroup org-cycle nil
550 "Options concerning visibility cycling in Org-mode."
551 :tag "Org Cycle"
552 :group 'org-structure)
554 (defcustom org-cycle-max-level nil
555 "Maximum level which should still be subject to visibility cycling.
556 Levels higher than this will, for cycling, be treated as text, not a headline.
557 When `org-odd-levels-only' is set, a value of N in this variable actually
558 means 2N-1 stars as the limiting headline.
559 When nil, cycle all levels.
560 Note that the limiting level of cycling is also influenced by
561 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
562 `org-inlinetask-min-level' is, cycling will be limited to levels one less
563 than its value."
564 :group 'org-cycle
565 :type '(choice
566 (const :tag "No limit" nil)
567 (integer :tag "Maximum level")))
569 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
570 "Names of drawers. Drawers are not opened by cycling on the headline above.
571 Drawers only open with a TAB on the drawer line itself. A drawer looks like
572 this:
573 :DRAWERNAME:
574 .....
575 :END:
576 The drawer \"PROPERTIES\" is special for capturing properties through
577 the property API.
579 Drawers can be defined on the per-file basis with a line like:
581 #+DRAWERS: HIDDEN STATE PROPERTIES"
582 :group 'org-structure
583 :group 'org-cycle
584 :type '(repeat (string :tag "Drawer Name")))
586 (defcustom org-cycle-global-at-bob nil
587 "Cycle globally if cursor is at beginning of buffer and not at a headline.
588 This makes it possible to do global cycling without having to use S-TAB or
589 C-u TAB. For this special case to work, the first line of the buffer
590 must not be a headline - it may be empty or some other text. When used in
591 this way, `org-cycle-hook' is disables temporarily, to make sure the
592 cursor stays at the beginning of the buffer.
593 When this option is nil, don't do anything special at the beginning
594 of the buffer."
595 :group 'org-cycle
596 :type 'boolean)
598 (defcustom org-cycle-emulate-tab t
599 "Where should `org-cycle' emulate TAB.
600 nil Never
601 white Only in completely white lines
602 whitestart Only at the beginning of lines, before the first non-white char
603 t Everywhere except in headlines
604 exc-hl-bol Everywhere except at the start of a headline
605 If TAB is used in a place where it does not emulate TAB, the current subtree
606 visibility is cycled."
607 :group 'org-cycle
608 :type '(choice (const :tag "Never" nil)
609 (const :tag "Only in completely white lines" white)
610 (const :tag "Before first char in a line" whitestart)
611 (const :tag "Everywhere except in headlines" t)
612 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
615 (defcustom org-cycle-separator-lines 2
616 "Number of empty lines needed to keep an empty line between collapsed trees.
617 If you leave an empty line between the end of a subtree and the following
618 headline, this empty line is hidden when the subtree is folded.
619 Org-mode will leave (exactly) one empty line visible if the number of
620 empty lines is equal or larger to the number given in this variable.
621 So the default 2 means, at least 2 empty lines after the end of a subtree
622 are needed to produce free space between a collapsed subtree and the
623 following headline.
625 Special case: when 0, never leave empty lines in collapsed view."
626 :group 'org-cycle
627 :type 'integer)
628 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
630 (defcustom org-pre-cycle-hook nil
631 "Hook that is run before visibility cycling is happening.
632 The function(s) in this hook must accept a single argument which indicates
633 the new state that will be set right after running this hook. The
634 argument is a symbol. Before a global state change, it can have the values
635 `overview', `content', or `all'. Before a local state change, it can have
636 the values `folded', `children', or `subtree'."
637 :group 'org-cycle
638 :type 'hook)
640 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
641 org-cycle-hide-drawers
642 org-cycle-show-empty-lines
643 org-optimize-window-after-visibility-change)
644 "Hook that is run after `org-cycle' has changed the buffer visibility.
645 The function(s) in this hook must accept a single argument which indicates
646 the new state that was set by the most recent `org-cycle' command. The
647 argument is a symbol. After a global state change, it can have the values
648 `overview', `content', or `all'. After a local state change, it can have
649 the values `folded', `children', or `subtree'."
650 :group 'org-cycle
651 :type 'hook)
653 (defgroup org-edit-structure nil
654 "Options concerning structure editing in Org-mode."
655 :tag "Org Edit Structure"
656 :group 'org-structure)
658 (defcustom org-odd-levels-only nil
659 "Non-nil means, skip even levels and only use odd levels for the outline.
660 This has the effect that two stars are being added/taken away in
661 promotion/demotion commands. It also influences how levels are
662 handled by the exporters.
663 Changing it requires restart of `font-lock-mode' to become effective
664 for fontification also in regions already fontified.
665 You may also set this on a per-file basis by adding one of the following
666 lines to the buffer:
668 #+STARTUP: odd
669 #+STARTUP: oddeven"
670 :group 'org-edit-structure
671 :group 'org-font-lock
672 :type 'boolean)
674 (defcustom org-adapt-indentation t
675 "Non-nil means, adapt indentation when promoting and demoting.
676 When this is set and the *entire* text in an entry is indented, the
677 indentation is increased by one space in a demotion command, and
678 decreased by one in a promotion command. If any line in the entry
679 body starts at column 0, indentation is not changed at all."
680 :group 'org-edit-structure
681 :type 'boolean)
683 (defcustom org-special-ctrl-a/e nil
684 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
686 When t, `C-a' will bring back the cursor to the beginning of the
687 headline text, i.e. after the stars and after a possible TODO keyword.
688 In an item, this will be the position after the bullet.
689 When the cursor is already at that position, another `C-a' will bring
690 it to the beginning of the line.
692 `C-e' will jump to the end of the headline, ignoring the presence of tags
693 in the headline. A second `C-e' will then jump to the true end of the
694 line, after any tags.
696 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
697 and only a directly following, identical keypress will bring the cursor
698 to the special positions.
700 This may also be a cons cell where the behavior for `C-a' and `C-e' is
701 set separately."
702 :group 'org-edit-structure
703 :type '(choice
704 (const :tag "off" nil)
705 (const :tag "after stars/bullet and before tags first" t)
706 (const :tag "true line boundary first" reversed)
707 (cons :tag "Set C-a and C-e separately"
708 (choice :tag "Special C-a"
709 (const :tag "off" nil)
710 (const :tag "after stars/bullet first" t)
711 (const :tag "before stars/bullet first" reversed))
712 (choice :tag "Special C-e"
713 (const :tag "off" nil)
714 (const :tag "before tags first" t)
715 (const :tag "after tags first" reversed)))))
716 (if (fboundp 'defvaralias)
717 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
719 (defcustom org-special-ctrl-k nil
720 "Non-nil means `C-k' will behave specially in headlines.
721 When nil, `C-k' will call the default `kill-line' command.
722 When t, the following will happen while the cursor is in the headline:
724 - When the cursor is at the beginning of a headline, kill the entire
725 line and possible the folded subtree below the line.
726 - When in the middle of the headline text, kill the headline up to the tags.
727 - When after the headline text, kill the tags."
728 :group 'org-edit-structure
729 :type 'boolean)
731 (defcustom org-yank-folded-subtrees t
732 "Non-nil means, when yanking subtrees, fold them.
733 If the kill is a single subtree, or a sequence of subtrees, i.e. if
734 it starts with a heading and all other headings in it are either children
735 or siblings, then fold all the subtrees. However, do this only if no
736 text after the yank would be swallowed into a folded tree by this action."
737 :group 'org-edit-structure
738 :type 'boolean)
740 (defcustom org-yank-adjusted-subtrees nil
741 "Non-nil means, when yanking subtrees, adjust the level.
742 With this setting, `org-paste-subtree' is used to insert the subtree, see
743 this function for details."
744 :group 'org-edit-structure
745 :type 'boolean)
747 (defcustom org-M-RET-may-split-line '((default . t))
748 "Non-nil means, M-RET will split the line at the cursor position.
749 When nil, it will go to the end of the line before making a
750 new line.
751 You may also set this option in a different way for different
752 contexts. Valid contexts are:
754 headline when creating a new headline
755 item when creating a new item
756 table in a table field
757 default the value to be used for all contexts not explicitly
758 customized"
759 :group 'org-structure
760 :group 'org-table
761 :type '(choice
762 (const :tag "Always" t)
763 (const :tag "Never" nil)
764 (repeat :greedy t :tag "Individual contexts"
765 (cons
766 (choice :tag "Context"
767 (const headline)
768 (const item)
769 (const table)
770 (const default))
771 (boolean)))))
774 (defcustom org-insert-heading-respect-content nil
775 "Non-nil means, insert new headings after the current subtree.
776 When nil, the new heading is created directly after the current line.
777 The commands \\[org-insert-heading-respect-content] and
778 \\[org-insert-todo-heading-respect-content] turn this variable on
779 for the duration of the command."
780 :group 'org-structure
781 :type 'boolean)
783 (defcustom org-blank-before-new-entry '((heading . auto)
784 (plain-list-item . auto))
785 "Should `org-insert-heading' leave a blank line before new heading/item?
786 The value is an alist, with `heading' and `plain-list-item' as car,
787 and a boolean flag as cdr. For plain lists, if the variable
788 `org-empty-line-terminates-plain-lists' is set, the setting here
789 is ignored and no empty line is inserted, to keep the list in tact."
790 :group 'org-edit-structure
791 :type '(list
792 (cons (const heading)
793 (choice (const :tag "Never" nil)
794 (const :tag "Always" t)
795 (const :tag "Auto" auto)))
796 (cons (const plain-list-item)
797 (choice (const :tag "Never" nil)
798 (const :tag "Always" t)
799 (const :tag "Auto" auto)))))
801 (defcustom org-insert-heading-hook nil
802 "Hook being run after inserting a new heading."
803 :group 'org-edit-structure
804 :type 'hook)
806 (defcustom org-enable-fixed-width-editor t
807 "Non-nil means, lines starting with \":\" are treated as fixed-width.
808 This currently only means, they are never auto-wrapped.
809 When nil, such lines will be treated like ordinary lines.
810 See also the QUOTE keyword."
811 :group 'org-edit-structure
812 :type 'boolean)
814 (defcustom org-edit-src-region-extra nil
815 "Additional regexps to identify regions for editing with `org-edit-src-code'.
816 For examples see the function `org-edit-src-find-region-and-lang'.
817 The regular expression identifying the begin marker should end with a newline,
818 and the regexp marking the end line should start with a newline, to make sure
819 there are kept outside the narrowed region."
820 :group 'org-edit-structure
821 :type '(repeat
822 (list
823 (regexp :tag "begin regexp")
824 (regexp :tag "end regexp")
825 (choice :tag "language"
826 (string :tag "specify")
827 (integer :tag "from match group")
828 (const :tag "from `lang' element")
829 (const :tag "from `style' element")))))
831 (defcustom org-coderef-label-format "(ref:%s)"
832 "The default coderef format.
833 This format string will be used to search for coderef labels in literal
834 examples (EXAMPLE and SRC blocks). The format can be overwritten
835 an individual literal example with the -f option, like
837 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
839 #+END_SRC
841 If you want to use this for HTML export, make sure that the format does
842 not introduce special font-locking, and avoid the HTML special
843 characters `<', `>', and `&'. The reason for this restriction is that
844 the labels are searched for only after htmlize has done its job."
845 :group 'org-edit-structure ; FIXME this is not in the right group
846 :type 'string)
848 (defcustom org-edit-fixed-width-region-mode 'artist-mode
849 "The mode that should be used to edit fixed-width regions.
850 These are the regions where each line starts with a colon."
851 :group 'org-edit-structure
852 :type '(choice
853 (const artist-mode)
854 (const picture-mode)
855 (const fundamental-mode)
856 (function :tag "Other (specify)")))
858 (defcustom org-edit-src-persistent-message t
859 "Non-nil means show persistent exit help message while editing src examples.
860 The message is shown in the header-line, which will be created in the
861 first line of the window showing the editing buffer.
862 When nil, the message will only be shown intermittently in the echo area."
863 :group 'org-edit-structure
864 :type 'boolean)
866 (defcustom org-goto-auto-isearch t
867 "Non-nil means, typing characters in org-goto starts incremental search."
868 :group 'org-edit-structure
869 :type 'boolean)
871 (defgroup org-sparse-trees nil
872 "Options concerning sparse trees in Org-mode."
873 :tag "Org Sparse Trees"
874 :group 'org-structure)
876 (defcustom org-highlight-sparse-tree-matches t
877 "Non-nil means, highlight all matches that define a sparse tree.
878 The highlights will automatically disappear the next time the buffer is
879 changed by an edit command."
880 :group 'org-sparse-trees
881 :type 'boolean)
883 (defcustom org-remove-highlights-with-change t
884 "Non-nil means, any change to the buffer will remove temporary highlights.
885 Such highlights are created by `org-occur' and `org-clock-display'.
886 When nil, `C-c C-c needs to be used to get rid of the highlights.
887 The highlights created by `org-preview-latex-fragment' always need
888 `C-c C-c' to be removed."
889 :group 'org-sparse-trees
890 :group 'org-time
891 :type 'boolean)
894 (defcustom org-occur-hook '(org-first-headline-recenter)
895 "Hook that is run after `org-occur' has constructed a sparse tree.
896 This can be used to recenter the window to show as much of the structure
897 as possible."
898 :group 'org-sparse-trees
899 :type 'hook)
901 (defgroup org-imenu-and-speedbar nil
902 "Options concerning imenu and speedbar in Org-mode."
903 :tag "Org Imenu and Speedbar"
904 :group 'org-structure)
906 (defcustom org-imenu-depth 2
907 "The maximum level for Imenu access to Org-mode headlines.
908 This also applied for speedbar access."
909 :group 'org-imenu-and-speedbar
910 :type 'integer)
912 (defgroup org-table nil
913 "Options concerning tables in Org-mode."
914 :tag "Org Table"
915 :group 'org)
917 (defcustom org-enable-table-editor 'optimized
918 "Non-nil means, lines starting with \"|\" are handled by the table editor.
919 When nil, such lines will be treated like ordinary lines.
921 When equal to the symbol `optimized', the table editor will be optimized to
922 do the following:
923 - Automatic overwrite mode in front of whitespace in table fields.
924 This makes the structure of the table stay in tact as long as the edited
925 field does not exceed the column width.
926 - Minimize the number of realigns. Normally, the table is aligned each time
927 TAB or RET are pressed to move to another field. With optimization this
928 happens only if changes to a field might have changed the column width.
929 Optimization requires replacing the functions `self-insert-command',
930 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
931 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
932 very good at guessing when a re-align will be necessary, but you can always
933 force one with \\[org-ctrl-c-ctrl-c].
935 If you would like to use the optimized version in Org-mode, but the
936 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
938 This variable can be used to turn on and off the table editor during a session,
939 but in order to toggle optimization, a restart is required.
941 See also the variable `org-table-auto-blank-field'."
942 :group 'org-table
943 :type '(choice
944 (const :tag "off" nil)
945 (const :tag "on" t)
946 (const :tag "on, optimized" optimized)))
948 (defcustom org-self-insert-cluster-for-undo t
949 "Non-nil means cluster self-insert commands for undo when possible.
950 If this is set, then, like in the Emacs command loop, 20 consequtive
951 characters will be undone together.
952 This is configurable, because there is some impact on typing performance."
953 :group 'org-table
954 :type 'boolean)
956 (defcustom org-table-tab-recognizes-table.el t
957 "Non-nil means, TAB will automatically notice a table.el table.
958 When it sees such a table, it moves point into it and - if necessary -
959 calls `table-recognize-table'."
960 :group 'org-table-editing
961 :type 'boolean)
963 (defgroup org-link nil
964 "Options concerning links in Org-mode."
965 :tag "Org Link"
966 :group 'org)
968 (defvar org-link-abbrev-alist-local nil
969 "Buffer-local version of `org-link-abbrev-alist', which see.
970 The value of this is taken from the #+LINK lines.")
971 (make-variable-buffer-local 'org-link-abbrev-alist-local)
973 (defcustom org-link-abbrev-alist nil
974 "Alist of link abbreviations.
975 The car of each element is a string, to be replaced at the start of a link.
976 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
977 links in Org-mode buffers can have an optional tag after a double colon, e.g.
979 [[linkkey:tag][description]]
981 The 'linkkey' must be a word word, starting with a letter, followed
982 by letters, numbers, '-' or '_'.
984 If REPLACE is a string, the tag will simply be appended to create the link.
985 If the string contains \"%s\", the tag will be inserted there. Alternatively,
986 the placeholder \"%h\" will cause a url-encoded version of the tag to
987 be inserted at that point (see the function `url-hexify-string').
989 REPLACE may also be a function that will be called with the tag as the
990 only argument to create the link, which should be returned as a string.
992 See the manual for examples."
993 :group 'org-link
994 :type '(repeat
995 (cons
996 (string :tag "Protocol")
997 (choice
998 (string :tag "Format")
999 (function)))))
1001 (defcustom org-descriptive-links t
1002 "Non-nil means, hide link part and only show description of bracket links.
1003 Bracket links are like [[link][description]]. This variable sets the initial
1004 state in new org-mode buffers. The setting can then be toggled on a
1005 per-buffer basis from the Org->Hyperlinks menu."
1006 :group 'org-link
1007 :type 'boolean)
1009 (defcustom org-link-file-path-type 'adaptive
1010 "How the path name in file links should be stored.
1011 Valid values are:
1013 relative Relative to the current directory, i.e. the directory of the file
1014 into which the link is being inserted.
1015 absolute Absolute path, if possible with ~ for home directory.
1016 noabbrev Absolute path, no abbreviation of home directory.
1017 adaptive Use relative path for files in the current directory and sub-
1018 directories of it. For other files, use an absolute path."
1019 :group 'org-link
1020 :type '(choice
1021 (const relative)
1022 (const absolute)
1023 (const noabbrev)
1024 (const adaptive)))
1026 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1027 "Types of links that should be activated in Org-mode files.
1028 This is a list of symbols, each leading to the activation of a certain link
1029 type. In principle, it does not hurt to turn on most link types - there may
1030 be a small gain when turning off unused link types. The types are:
1032 bracket The recommended [[link][description]] or [[link]] links with hiding.
1033 angular Links in angular brackets that may contain whitespace like
1034 <bbdb:Carsten Dominik>.
1035 plain Plain links in normal text, no whitespace, like http://google.com.
1036 radio Text that is matched by a radio target, see manual for details.
1037 tag Tag settings in a headline (link to tag search).
1038 date Time stamps (link to calendar).
1039 footnote Footnote labels.
1041 Changing this variable requires a restart of Emacs to become effective."
1042 :group 'org-link
1043 :type '(set :greedy t
1044 (const :tag "Double bracket links (new style)" bracket)
1045 (const :tag "Angular bracket links (old style)" angular)
1046 (const :tag "Plain text links" plain)
1047 (const :tag "Radio target matches" radio)
1048 (const :tag "Tags" tag)
1049 (const :tag "Timestamps" date)
1050 (const :tag "Footnotes" footnote)))
1052 (defcustom org-make-link-description-function nil
1053 "Function to use to generate link descriptions from links. If
1054 nil the link location will be used. This function must take two
1055 parameters; the first is the link and the second the description
1056 org-insert-link has generated, and should return the description
1057 to use."
1058 :group 'org-link
1059 :type 'function)
1061 (defgroup org-link-store nil
1062 "Options concerning storing links in Org-mode."
1063 :tag "Org Store Link"
1064 :group 'org-link)
1066 (defcustom org-email-link-description-format "Email %c: %.30s"
1067 "Format of the description part of a link to an email or usenet message.
1068 The following %-escapes will be replaced by corresponding information:
1070 %F full \"From\" field
1071 %f name, taken from \"From\" field, address if no name
1072 %T full \"To\" field
1073 %t first name in \"To\" field, address if no name
1074 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1075 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1076 %s subject
1077 %m message-id.
1079 You may use normal field width specification between the % and the letter.
1080 This is for example useful to limit the length of the subject.
1082 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1083 :group 'org-link-store
1084 :type 'string)
1086 (defcustom org-from-is-user-regexp
1087 (let (r1 r2)
1088 (when (and user-mail-address (not (string= user-mail-address "")))
1089 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1090 (when (and user-full-name (not (string= user-full-name "")))
1091 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1092 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1093 "Regexp matched against the \"From:\" header of an email or usenet message.
1094 It should match if the message is from the user him/herself."
1095 :group 'org-link-store
1096 :type 'regexp)
1098 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1099 "Non-nil means, storing a link to an Org file will use entry IDs.
1101 Note that before this variable is even considered, org-id must be loaded,
1102 to please customize `org-modules' and turn it on.
1104 The variable can have the following values:
1106 t Create an ID if needed to make a link to the current entry.
1108 create-if-interactive
1109 If `org-store-link' is called directly (interactively, as a user
1110 command), do create an ID to support the link. But when doing the
1111 job for remember, only use the ID if it already exists. The
1112 purpose of this setting is to avoid proliferation of unwanted
1113 IDs, just because you happen to be in an Org file when you
1114 call `org-remember' that automatically and preemptively
1115 creates a link. If you do want to get an ID link in a remember
1116 template to an entry not having an ID, create it first by
1117 explicitly creating a link to it, using `C-c C-l' first.
1119 use-existing
1120 Use existing ID, do not create one.
1122 nil Never use an ID to make a link, instead link using a text search for
1123 the headline text."
1124 :group 'org-link-store
1125 :type '(choice
1126 (const :tag "Create ID to make link" t)
1127 (const :tag "Create if storing link interactively"
1128 create-if-interactive)
1129 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1130 create-if-interactive-and-no-custom-id)
1131 (const :tag "Only use existing" use-existing)
1132 (const :tag "Do not use ID to create link" nil)))
1134 (defcustom org-context-in-file-links t
1135 "Non-nil means, file links from `org-store-link' contain context.
1136 A search string will be added to the file name with :: as separator and
1137 used to find the context when the link is activated by the command
1138 `org-open-at-point'.
1139 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1140 negates this setting for the duration of the command."
1141 :group 'org-link-store
1142 :type 'boolean)
1144 (defcustom org-keep-stored-link-after-insertion nil
1145 "Non-nil means, keep link in list for entire session.
1147 The command `org-store-link' adds a link pointing to the current
1148 location to an internal list. These links accumulate during a session.
1149 The command `org-insert-link' can be used to insert links into any
1150 Org-mode file (offering completion for all stored links). When this
1151 option is nil, every link which has been inserted once using \\[org-insert-link]
1152 will be removed from the list, to make completing the unused links
1153 more efficient."
1154 :group 'org-link-store
1155 :type 'boolean)
1157 (defgroup org-link-follow nil
1158 "Options concerning following links in Org-mode."
1159 :tag "Org Follow Link"
1160 :group 'org-link)
1162 (defcustom org-link-translation-function nil
1163 "Function to translate links with different syntax to Org syntax.
1164 This can be used to translate links created for example by the Planner
1165 or emacs-wiki packages to Org syntax.
1166 The function must accept two parameters, a TYPE containing the link
1167 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1168 which is everything after the link protocol. It should return a cons
1169 with possibly modified values of type and path.
1170 Org contains a function for this, so if you set this variable to
1171 `org-translate-link-from-planner', you should be able follow many
1172 links created by planner."
1173 :group 'org-link-follow
1174 :type 'function)
1176 (defcustom org-follow-link-hook nil
1177 "Hook that is run after a link has been followed."
1178 :group 'org-link-follow
1179 :type 'hook)
1181 (defcustom org-tab-follows-link nil
1182 "Non-nil means, on links TAB will follow the link.
1183 Needs to be set before org.el is loaded.
1184 This really should not be used, it does not make sense, and the
1185 implementation is bad."
1186 :group 'org-link-follow
1187 :type 'boolean)
1189 (defcustom org-return-follows-link nil
1190 "Non-nil means, on links RET will follow the link.
1191 Needs to be set before org.el is loaded."
1192 :group 'org-link-follow
1193 :type 'boolean)
1195 (defcustom org-mouse-1-follows-link
1196 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1197 "Non-nil means, mouse-1 on a link will follow the link.
1198 A longer mouse click will still set point. Does not work on XEmacs.
1199 Needs to be set before org.el is loaded."
1200 :group 'org-link-follow
1201 :type 'boolean)
1203 (defcustom org-mark-ring-length 4
1204 "Number of different positions to be recorded in the ring
1205 Changing this requires a restart of Emacs to work correctly."
1206 :group 'org-link-follow
1207 :type 'integer)
1209 (defcustom org-link-frame-setup
1210 '((vm . vm-visit-folder-other-frame)
1211 (gnus . gnus-other-frame)
1212 (file . find-file-other-window))
1213 "Setup the frame configuration for following links.
1214 When following a link with Emacs, it may often be useful to display
1215 this link in another window or frame. This variable can be used to
1216 set this up for the different types of links.
1217 For VM, use any of
1218 `vm-visit-folder'
1219 `vm-visit-folder-other-frame'
1220 For Gnus, use any of
1221 `gnus'
1222 `gnus-other-frame'
1223 `org-gnus-no-new-news'
1224 For FILE, use any of
1225 `find-file'
1226 `find-file-other-window'
1227 `find-file-other-frame'
1228 For the calendar, use the variable `calendar-setup'.
1229 For BBDB, it is currently only possible to display the matches in
1230 another window."
1231 :group 'org-link-follow
1232 :type '(list
1233 (cons (const vm)
1234 (choice
1235 (const vm-visit-folder)
1236 (const vm-visit-folder-other-window)
1237 (const vm-visit-folder-other-frame)))
1238 (cons (const gnus)
1239 (choice
1240 (const gnus)
1241 (const gnus-other-frame)
1242 (const org-gnus-no-new-news)))
1243 (cons (const file)
1244 (choice
1245 (const find-file)
1246 (const find-file-other-window)
1247 (const find-file-other-frame)))))
1249 (defcustom org-display-internal-link-with-indirect-buffer nil
1250 "Non-nil means, use indirect buffer to display infile links.
1251 Activating internal links (from one location in a file to another location
1252 in the same file) normally just jumps to the location. When the link is
1253 activated with a C-u prefix (or with mouse-3), the link is displayed in
1254 another window. When this option is set, the other window actually displays
1255 an indirect buffer clone of the current buffer, to avoid any visibility
1256 changes to the current buffer."
1257 :group 'org-link-follow
1258 :type 'boolean)
1260 (defcustom org-open-non-existing-files nil
1261 "Non-nil means, `org-open-file' will open non-existing files.
1262 When nil, an error will be generated."
1263 :group 'org-link-follow
1264 :type 'boolean)
1266 (defcustom org-open-directory-means-index-dot-org nil
1267 "Non-nil means, a link to a directory really means to index.org.
1268 When nil, following a directory link will run dired or open a finder/explorer
1269 window on that directory."
1270 :group 'org-link-follow
1271 :type 'boolean)
1273 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1274 "Function and arguments to call for following mailto links.
1275 This is a list with the first element being a lisp function, and the
1276 remaining elements being arguments to the function. In string arguments,
1277 %a will be replaced by the address, and %s will be replaced by the subject
1278 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1279 :group 'org-link-follow
1280 :type '(choice
1281 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1282 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1283 (const :tag "message-mail" (message-mail "%a" "%s"))
1284 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1286 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1287 "Non-nil means, ask for confirmation before executing shell links.
1288 Shell links can be dangerous: just think about a link
1290 [[shell:rm -rf ~/*][Google Search]]
1292 This link would show up in your Org-mode document as \"Google Search\",
1293 but really it would remove your entire home directory.
1294 Therefore we advise against setting this variable to nil.
1295 Just change it to `y-or-n-p' if you want to confirm with a
1296 single keystroke rather than having to type \"yes\"."
1297 :group 'org-link-follow
1298 :type '(choice
1299 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1300 (const :tag "with y-or-n (faster)" y-or-n-p)
1301 (const :tag "no confirmation (dangerous)" nil)))
1303 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1304 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1305 Elisp links can be dangerous: just think about a link
1307 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1309 This link would show up in your Org-mode document as \"Google Search\",
1310 but really it would remove your entire home directory.
1311 Therefore we advise against setting this variable to nil.
1312 Just change it to `y-or-n-p' if you want to confirm with a
1313 single keystroke rather than having to type \"yes\"."
1314 :group 'org-link-follow
1315 :type '(choice
1316 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1317 (const :tag "with y-or-n (faster)" y-or-n-p)
1318 (const :tag "no confirmation (dangerous)" nil)))
1320 (defconst org-file-apps-defaults-gnu
1321 '((remote . emacs)
1322 (system . mailcap)
1323 (t . mailcap))
1324 "Default file applications on a UNIX or GNU/Linux system.
1325 See `org-file-apps'.")
1327 (defconst org-file-apps-defaults-macosx
1328 '((remote . emacs)
1329 (t . "open %s")
1330 (system . "open %s")
1331 ("ps.gz" . "gv %s")
1332 ("eps.gz" . "gv %s")
1333 ("dvi" . "xdvi %s")
1334 ("fig" . "xfig %s"))
1335 "Default file applications on a MacOS X system.
1336 The system \"open\" is known as a default, but we use X11 applications
1337 for some files for which the OS does not have a good default.
1338 See `org-file-apps'.")
1340 (defconst org-file-apps-defaults-windowsnt
1341 (list
1342 '(remote . emacs)
1343 (cons t
1344 (list (if (featurep 'xemacs)
1345 'mswindows-shell-execute
1346 'w32-shell-execute)
1347 "open" 'file))
1348 (cons 'system
1349 (list (if (featurep 'xemacs)
1350 'mswindows-shell-execute
1351 'w32-shell-execute)
1352 "open" 'file)))
1353 "Default file applications on a Windows NT system.
1354 The system \"open\" is used for most files.
1355 See `org-file-apps'.")
1357 (defcustom org-file-apps
1359 (auto-mode . emacs)
1360 ("\\.x?html?\\'" . default)
1361 ("\\.pdf\\'" . default)
1363 "External applications for opening `file:path' items in a document.
1364 Org-mode uses system defaults for different file types, but
1365 you can use this variable to set the application for a given file
1366 extension. The entries in this list are cons cells where the car identifies
1367 files and the cdr the corresponding command. Possible values for the
1368 file identifier are
1369 \"regex\" Regular expression matched against the file name. For backward
1370 compatibility, this can also be a string with only alphanumeric
1371 characters, which is then interpreted as an extension.
1372 `directory' Matches a directory
1373 `remote' Matches a remote file, accessible through tramp or efs.
1374 Remote files most likely should be visited through Emacs
1375 because external applications cannot handle such paths.
1376 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1377 so all files Emacs knows how to handle. Using this with
1378 command `emacs' will open most files in Emacs. Beware that this
1379 will also open html files inside Emacs, unless you add
1380 (\"html\" . default) to the list as well.
1381 t Default for files not matched by any of the other options.
1382 `system' The system command to open files, like `open' on Windows
1383 and Mac OS X, and mailcap under GNU/Linux. This is the command
1384 that will be selected if you call `C-c C-o' with a double
1385 `C-u C-u' prefix.
1387 Possible values for the command are:
1388 `emacs' The file will be visited by the current Emacs process.
1389 `default' Use the default application for this file type, which is the
1390 association for t in the list, most likely in the system-specific
1391 part.
1392 This can be used to overrule an unwanted setting in the
1393 system-specific variable.
1394 `system' Use the system command for opening files, like \"open\".
1395 This command is specified by the entry whose car is `system'.
1396 Most likely, the system-specific version of this variable
1397 does define this command, but you can overrule/replace it
1398 here.
1399 string A command to be executed by a shell; %s will be replaced
1400 by the path to the file.
1401 sexp A Lisp form which will be evaluated. The file path will
1402 be available in the Lisp variable `file'.
1403 For more examples, see the system specific constants
1404 `org-file-apps-defaults-macosx'
1405 `org-file-apps-defaults-windowsnt'
1406 `org-file-apps-defaults-gnu'."
1407 :group 'org-link-follow
1408 :type '(repeat
1409 (cons (choice :value ""
1410 (string :tag "Extension")
1411 (const :tag "System command to open files" system)
1412 (const :tag "Default for unrecognized files" t)
1413 (const :tag "Remote file" remote)
1414 (const :tag "Links to a directory" directory)
1415 (const :tag "Any files that have Emacs modes"
1416 auto-mode))
1417 (choice :value ""
1418 (const :tag "Visit with Emacs" emacs)
1419 (const :tag "Use default" default)
1420 (const :tag "Use the system command" system)
1421 (string :tag "Command")
1422 (sexp :tag "Lisp form")))))
1424 (defgroup org-refile nil
1425 "Options concerning refiling entries in Org-mode."
1426 :tag "Org Refile"
1427 :group 'org)
1429 (defcustom org-directory "~/org"
1430 "Directory with org files.
1431 This is just a default location to look for Org files. There is no need
1432 at all to put your files into this directory. It is only used in the
1433 following situations:
1435 1. When a remember template specifies a target file that is not an
1436 absolute path. The path will then be interpreted relative to
1437 `org-directory'
1438 2. When a remember note is filed away in an interactive way (when exiting the
1439 note buffer with `C-1 C-c C-c'. The the user is prompted for an org file,
1440 with `org-directory' as the default path."
1441 :group 'org-refile
1442 :group 'org-remember
1443 :type 'directory)
1445 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1446 "Default target for storing notes.
1447 Used by the hooks for remember.el. This can be a string, or nil to mean
1448 the value of `remember-data-file'.
1449 You can set this on a per-template basis with the variable
1450 `org-remember-templates'."
1451 :group 'org-refile
1452 :group 'org-remember
1453 :type '(choice
1454 (const :tag "Default from remember-data-file" nil)
1455 file))
1457 (defcustom org-goto-interface 'outline
1458 "The default interface to be used for `org-goto'.
1459 Allowed values are:
1460 outline The interface shows an outline of the relevant file
1461 and the correct heading is found by moving through
1462 the outline or by searching with incremental search.
1463 outline-path-completion Headlines in the current buffer are offered via
1464 completion. This is the interface also used by
1465 the refile command."
1466 :group 'org-refile
1467 :type '(choice
1468 (const :tag "Outline" outline)
1469 (const :tag "Outline-path-completion" outline-path-completion)))
1471 (defcustom org-goto-max-level 5
1472 "Maximum level to be considered when running org-goto with refile interface."
1473 :group 'org-refile
1474 :type 'integer)
1476 (defcustom org-reverse-note-order nil
1477 "Non-nil means, store new notes at the beginning of a file or entry.
1478 When nil, new notes will be filed to the end of a file or entry.
1479 This can also be a list with cons cells of regular expressions that
1480 are matched against file names, and values."
1481 :group 'org-remember
1482 :group 'org-refile
1483 :type '(choice
1484 (const :tag "Reverse always" t)
1485 (const :tag "Reverse never" nil)
1486 (repeat :tag "By file name regexp"
1487 (cons regexp boolean))))
1489 (defcustom org-refile-targets nil
1490 "Targets for refiling entries with \\[org-refile].
1491 This is list of cons cells. Each cell contains:
1492 - a specification of the files to be considered, either a list of files,
1493 or a symbol whose function or variable value will be used to retrieve
1494 a file name or a list of file names. If you use `org-agenda-files' for
1495 that, all agenda files will be scanned for targets. Nil means, consider
1496 headings in the current buffer.
1497 - A specification of how to find candidate refile targets. This may be
1498 any of:
1499 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1500 This tag has to be present in all target headlines, inheritance will
1501 not be considered.
1502 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1503 todo keyword.
1504 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1505 headlines that are refiling targets.
1506 - a cons cell (:level . N). Any headline of level N is considered a target.
1507 Note that, when `org-odd-levels-only' is set, level corresponds to
1508 order in hierarchy, not to the number of stars.
1509 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1510 Note that, when `org-odd-levels-only' is set, level corresponds to
1511 order in hierarchy, not to the number of stars.
1513 You can set the variable `org-refile-target-verify-function' to a function
1514 to verify each headline found by the simple critery above.
1516 When this variable is nil, all top-level headlines in the current buffer
1517 are used, equivalent to the value `((nil . (:level . 1))'."
1518 :group 'org-refile
1519 :type '(repeat
1520 (cons
1521 (choice :value org-agenda-files
1522 (const :tag "All agenda files" org-agenda-files)
1523 (const :tag "Current buffer" nil)
1524 (function) (variable) (file))
1525 (choice :tag "Identify target headline by"
1526 (cons :tag "Specific tag" (const :value :tag) (string))
1527 (cons :tag "TODO keyword" (const :value :todo) (string))
1528 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1529 (cons :tag "Level number" (const :value :level) (integer))
1530 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1532 (defcustom org-refile-target-verify-function nil
1533 "Function to verify if the headline at point should be a refile target.
1534 The function will be called without arguments, with point at the
1535 beginning of the headline. It should return t and leave point
1536 where it is if the headline is a valid target for refiling.
1538 If the target should not be selected, the function must return nil.
1539 In addition to this, it may move point to a place from where the search
1540 should be continued. For example, the function may decide that the entire
1541 subtree of the current entry should be excluded and move point to the end
1542 of the subtree."
1543 :group 'org-refile
1544 :type 'function)
1546 (defcustom org-refile-use-outline-path nil
1547 "Non-nil means, provide refile targets as paths.
1548 So a level 3 headline will be available as level1/level2/level3.
1550 When the value is `file', also include the file name (without directory)
1551 into the path. In this case, you can also stop the completion after
1552 the file name, to get entries inserted as top level in the file.
1554 When `full-file-path', include the full file path."
1555 :group 'org-refile
1556 :type '(choice
1557 (const :tag "Not" nil)
1558 (const :tag "Yes" t)
1559 (const :tag "Start with file name" file)
1560 (const :tag "Start with full file path" full-file-path)))
1562 (defcustom org-outline-path-complete-in-steps t
1563 "Non-nil means, complete the outline path in hierarchical steps.
1564 When Org-mode uses the refile interface to select an outline path
1565 \(see variable `org-refile-use-outline-path'), the completion of
1566 the path can be done is a single go, or if can be done in steps down
1567 the headline hierarchy. Going in steps is probably the best if you
1568 do not use a special completion package like `ido' or `icicles'.
1569 However, when using these packages, going in one step can be very
1570 fast, while still showing the whole path to the entry."
1571 :group 'org-refile
1572 :type 'boolean)
1574 (defcustom org-refile-allow-creating-parent-nodes nil
1575 "Non-nil means, allow to create new nodes as refile targets.
1576 New nodes are then created by adding \"/new node name\" to the completion
1577 of an existing node. When the value of this variable is `confirm',
1578 new node creation must be confirmed by the user (recommended)
1579 When nil, the completion must match an existing entry.
1581 Note that, if the new heading is not seen by the criteria
1582 listed in `org-refile-targets', multiple instances of the same
1583 heading would be created by trying again to file under the new
1584 heading."
1585 :group 'org-refile
1586 :type '(choice
1587 (const :tag "Never" nil)
1588 (const :tag "Always" t)
1589 (const :tag "Prompt for confirmation" confirm)))
1591 (defgroup org-todo nil
1592 "Options concerning TODO items in Org-mode."
1593 :tag "Org TODO"
1594 :group 'org)
1596 (defgroup org-progress nil
1597 "Options concerning Progress logging in Org-mode."
1598 :tag "Org Progress"
1599 :group 'org-time)
1601 (defvar org-todo-interpretation-widgets
1603 (:tag "Sequence (cycling hits every state)" sequence)
1604 (:tag "Type (cycling directly to DONE)" type))
1605 "The available interpretation symbols for customizing
1606 `org-todo-keywords'.
1607 Interested libraries should add to this list.")
1609 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1610 "List of TODO entry keyword sequences and their interpretation.
1611 \\<org-mode-map>This is a list of sequences.
1613 Each sequence starts with a symbol, either `sequence' or `type',
1614 indicating if the keywords should be interpreted as a sequence of
1615 action steps, or as different types of TODO items. The first
1616 keywords are states requiring action - these states will select a headline
1617 for inclusion into the global TODO list Org-mode produces. If one of
1618 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1619 signify that no further action is necessary. If \"|\" is not found,
1620 the last keyword is treated as the only DONE state of the sequence.
1622 The command \\[org-todo] cycles an entry through these states, and one
1623 additional state where no keyword is present. For details about this
1624 cycling, see the manual.
1626 TODO keywords and interpretation can also be set on a per-file basis with
1627 the special #+SEQ_TODO and #+TYP_TODO lines.
1629 Each keyword can optionally specify a character for fast state selection
1630 \(in combination with the variable `org-use-fast-todo-selection')
1631 and specifiers for state change logging, using the same syntax
1632 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1633 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1634 indicates to record a time stamp each time this state is selected.
1636 Each keyword may also specify if a timestamp or a note should be
1637 recorded when entering or leaving the state, by adding additional
1638 characters in the parenthesis after the keyword. This looks like this:
1639 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1640 record only the time of the state change. With X and Y being either
1641 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1642 Y when leaving the state if and only if the *target* state does not
1643 define X. You may omit any of the fast-selection key or X or /Y,
1644 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1646 For backward compatibility, this variable may also be just a list
1647 of keywords - in this case the interpretation (sequence or type) will be
1648 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1649 :group 'org-todo
1650 :group 'org-keywords
1651 :type '(choice
1652 (repeat :tag "Old syntax, just keywords"
1653 (string :tag "Keyword"))
1654 (repeat :tag "New syntax"
1655 (cons
1656 (choice
1657 :tag "Interpretation"
1658 ;;Quick and dirty way to see
1659 ;;`org-todo-interpretations'. This takes the
1660 ;;place of item arguments
1661 :convert-widget
1662 (lambda (widget)
1663 (widget-put widget
1664 :args (mapcar
1665 #'(lambda (x)
1666 (widget-convert
1667 (cons 'const x)))
1668 org-todo-interpretation-widgets))
1669 widget))
1670 (repeat
1671 (string :tag "Keyword"))))))
1673 (defvar org-todo-keywords-1 nil
1674 "All TODO and DONE keywords active in a buffer.")
1675 (make-variable-buffer-local 'org-todo-keywords-1)
1676 (defvar org-todo-keywords-for-agenda nil)
1677 (defvar org-done-keywords-for-agenda nil)
1678 (defvar org-todo-keyword-alist-for-agenda nil)
1679 (defvar org-tag-alist-for-agenda nil)
1680 (defvar org-agenda-contributing-files nil)
1681 (defvar org-not-done-keywords nil)
1682 (make-variable-buffer-local 'org-not-done-keywords)
1683 (defvar org-done-keywords nil)
1684 (make-variable-buffer-local 'org-done-keywords)
1685 (defvar org-todo-heads nil)
1686 (make-variable-buffer-local 'org-todo-heads)
1687 (defvar org-todo-sets nil)
1688 (make-variable-buffer-local 'org-todo-sets)
1689 (defvar org-todo-log-states nil)
1690 (make-variable-buffer-local 'org-todo-log-states)
1691 (defvar org-todo-kwd-alist nil)
1692 (make-variable-buffer-local 'org-todo-kwd-alist)
1693 (defvar org-todo-key-alist nil)
1694 (make-variable-buffer-local 'org-todo-key-alist)
1695 (defvar org-todo-key-trigger nil)
1696 (make-variable-buffer-local 'org-todo-key-trigger)
1698 (defcustom org-todo-interpretation 'sequence
1699 "Controls how TODO keywords are interpreted.
1700 This variable is in principle obsolete and is only used for
1701 backward compatibility, if the interpretation of todo keywords is
1702 not given already in `org-todo-keywords'. See that variable for
1703 more information."
1704 :group 'org-todo
1705 :group 'org-keywords
1706 :type '(choice (const sequence)
1707 (const type)))
1709 (defcustom org-use-fast-todo-selection t
1710 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1711 This variable describes if and under what circumstances the cycling
1712 mechanism for TODO keywords will be replaced by a single-key, direct
1713 selection scheme.
1715 When nil, fast selection is never used.
1717 When the symbol `prefix', it will be used when `org-todo' is called with
1718 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1719 in an agenda buffer.
1721 When t, fast selection is used by default. In this case, the prefix
1722 argument forces cycling instead.
1724 In all cases, the special interface is only used if access keys have actually
1725 been assigned by the user, i.e. if keywords in the configuration are followed
1726 by a letter in parenthesis, like TODO(t)."
1727 :group 'org-todo
1728 :type '(choice
1729 (const :tag "Never" nil)
1730 (const :tag "By default" t)
1731 (const :tag "Only with C-u C-c C-t" prefix)))
1733 (defcustom org-provide-todo-statistics t
1734 "Non-nil means, update todo statistics after insert and toggle.
1735 When this is set, todo statistics is updated in the parent of the current
1736 entry each time a todo state is changed."
1737 :group 'org-todo
1738 :type 'boolean)
1740 (defcustom org-after-todo-state-change-hook nil
1741 "Hook which is run after the state of a TODO item was changed.
1742 The new state (a string with a TODO keyword, or nil) is available in the
1743 Lisp variable `state'."
1744 :group 'org-todo
1745 :type 'hook)
1747 (defvar org-blocker-hook nil
1748 "Hook for functions that are allowed to block a state change.
1750 Each function gets as its single argument a property list, see
1751 `org-trigger-hook' for more information about this list.
1753 If any of the functions in this hook returns nil, the state change
1754 is blocked.")
1756 (defvar org-trigger-hook nil
1757 "Hook for functions that are triggered by a state change.
1759 Each function gets as its single argument a property list with at least
1760 the following elements:
1762 (:type type-of-change :position pos-at-entry-start
1763 :from old-state :to new-state)
1765 Depending on the type, more properties may be present.
1767 This mechanism is currently implemented for:
1769 TODO state changes
1770 ------------------
1771 :type todo-state-change
1772 :from previous state (keyword as a string), or nil, or a symbol
1773 'todo' or 'done', to indicate the general type of state.
1774 :to new state, like in :from")
1776 (defcustom org-enforce-todo-dependencies nil
1777 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1778 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1779 be blocked if any prior sibling is not yet done.
1780 Finally, if the parent is blocked because of ordered siblings of its own,
1781 the child will also be blocked.
1782 This variable needs to be set before org.el is loaded, and you need to
1783 restart Emacs after a change to make the change effective. The only way
1784 to change is while Emacs is running is through the customize interface."
1785 :set (lambda (var val)
1786 (set var val)
1787 (if val
1788 (add-hook 'org-blocker-hook
1789 'org-block-todo-from-children-or-siblings-or-parent)
1790 (remove-hook 'org-blocker-hook
1791 'org-block-todo-from-children-or-siblings-or-parent)))
1792 :group 'org-todo
1793 :type 'boolean)
1795 (defcustom org-enforce-todo-checkbox-dependencies nil
1796 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1797 When this is nil, checkboxes have no influence on switching TODO states.
1798 When non-nil, you first need to check off all check boxes before the TODO
1799 entry can be switched to DONE.
1800 This variable needs to be set before org.el is loaded, and you need to
1801 restart Emacs after a change to make the change effective. The only way
1802 to change is while Emacs is running is through the customize interface."
1803 :set (lambda (var val)
1804 (set var val)
1805 (if val
1806 (add-hook 'org-blocker-hook
1807 'org-block-todo-from-checkboxes)
1808 (remove-hook 'org-blocker-hook
1809 'org-block-todo-from-checkboxes)))
1810 :group 'org-todo
1811 :type 'boolean)
1813 (defcustom org-todo-state-tags-triggers nil
1814 "Tag changes that should be triggered by TODO state changes.
1815 This is a list. Each entry is
1817 (state-change (tag . flag) .......)
1819 State-change can be a string with a state, and empty string to indicate the
1820 state that has no TODO keyword, or it can be one of the symbols `todo'
1821 or `done', meaning any not-done or done state, respectively."
1822 :group 'org-todo
1823 :group 'org-tags
1824 :type '(repeat
1825 (cons (choice :tag "When changing to"
1826 (const :tag "Not-done state" todo)
1827 (const :tag "Done state" done)
1828 (string :tag "State"))
1829 (repeat
1830 (cons :tag "Tag action"
1831 (string :tag "Tag")
1832 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1834 (defcustom org-log-done nil
1835 "Information to record when a task moves to the DONE state.
1837 Possible values are:
1839 nil Don't add anything, just change the keyword
1840 time Add a time stamp to the task
1841 note Prompt a closing note and add it with template `org-log-note-headings'
1843 This option can also be set with on a per-file-basis with
1845 #+STARTUP: nologdone
1846 #+STARTUP: logdone
1847 #+STARTUP: lognotedone
1849 You can have local logging settings for a subtree by setting the LOGGING
1850 property to one or more of these keywords."
1851 :group 'org-todo
1852 :group 'org-progress
1853 :type '(choice
1854 (const :tag "No logging" nil)
1855 (const :tag "Record CLOSED timestamp" time)
1856 (const :tag "Record CLOSED timestamp with closing note." note)))
1858 ;; Normalize old uses of org-log-done.
1859 (cond
1860 ((eq org-log-done t) (setq org-log-done 'time))
1861 ((and (listp org-log-done) (memq 'done org-log-done))
1862 (setq org-log-done 'note)))
1864 (defcustom org-log-note-clock-out nil
1865 "Non-nil means, record a note when clocking out of an item.
1866 This can also be configured on a per-file basis by adding one of
1867 the following lines anywhere in the buffer:
1869 #+STARTUP: lognoteclock-out
1870 #+STARTUP: nolognoteclock-out"
1871 :group 'org-todo
1872 :group 'org-progress
1873 :type 'boolean)
1875 (defcustom org-log-done-with-time t
1876 "Non-nil means, the CLOSED time stamp will contain date and time.
1877 When nil, only the date will be recorded."
1878 :group 'org-progress
1879 :type 'boolean)
1881 (defcustom org-log-note-headings
1882 '((done . "CLOSING NOTE %t")
1883 (state . "State %-12s from %-12S %t")
1884 (note . "Note taken on %t")
1885 (clock-out . ""))
1886 "Headings for notes added to entries.
1887 The value is an alist, with the car being a symbol indicating the note
1888 context, and the cdr is the heading to be used. The heading may also be the
1889 empty string.
1890 %t in the heading will be replaced by a time stamp.
1891 %s will be replaced by the new TODO state, in double quotes.
1892 %S will be replaced by the old TODO state, in double quotes.
1893 %u will be replaced by the user name.
1894 %U will be replaced by the full user name."
1895 :group 'org-todo
1896 :group 'org-progress
1897 :type '(list :greedy t
1898 (cons (const :tag "Heading when closing an item" done) string)
1899 (cons (const :tag
1900 "Heading when changing todo state (todo sequence only)"
1901 state) string)
1902 (cons (const :tag "Heading when just taking a note" note) string)
1903 (cons (const :tag "Heading when clocking out" clock-out) string)))
1905 (unless (assq 'note org-log-note-headings)
1906 (push '(note . "%t") org-log-note-headings))
1908 (defcustom org-log-into-drawer nil
1909 "Non-nil means, insert state change notes and time stamps into a drawer.
1910 When nil, state changes notes will be inserted after the headline and
1911 any scheduling and clock lines, but not inside a drawer.
1913 The value of this variable should be the name of the drawer to use.
1914 LOGBOOK is proposed at the default drawer for this purpose, you can
1915 also set this to a string to define the drawer of your choice.
1917 A value of t is also allowed, representing \"LOGBOOK\".
1919 If this variable is set, `org-log-state-notes-insert-after-drawers'
1920 will be ignored."
1921 :group 'org-todo
1922 :group 'org-progress
1923 :type '(choice
1924 (const :tag "Not into a drawer" nil)
1925 (const :tag "LOGBOOK" t)
1926 (string :tag "Other")))
1928 (if (fboundp 'defvaralias)
1929 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
1931 (defcustom org-log-state-notes-insert-after-drawers nil
1932 "Non-nil means, insert state change notes after any drawers in entry.
1933 Only the drawers that *immediately* follow the headline and the
1934 deadline/scheduled line are skipped.
1935 When nil, insert notes right after the heading and perhaps the line
1936 with deadline/scheduling if present.
1938 This variable will have no effect if `org-log-into-drawer' is
1939 set."
1940 :group 'org-todo
1941 :group 'org-progress
1942 :type 'boolean)
1944 (defcustom org-log-states-order-reversed t
1945 "Non-nil means, the latest state change note will be directly after heading.
1946 When nil, the notes will be orderer according to time."
1947 :group 'org-todo
1948 :group 'org-progress
1949 :type 'boolean)
1951 (defcustom org-log-repeat 'time
1952 "Non-nil means, record moving through the DONE state when triggering repeat.
1953 An auto-repeating tasks is immediately switched back to TODO when marked
1954 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1955 the TODO keyword definition, or recording a closing note by setting
1956 `org-log-done', there will be no record of the task moving through DONE.
1957 This variable forces taking a note anyway. Possible values are:
1959 nil Don't force a record
1960 time Record a time stamp
1961 note Record a note
1963 This option can also be set with on a per-file-basis with
1965 #+STARTUP: logrepeat
1966 #+STARTUP: lognoterepeat
1967 #+STARTUP: nologrepeat
1969 You can have local logging settings for a subtree by setting the LOGGING
1970 property to one or more of these keywords."
1971 :group 'org-todo
1972 :group 'org-progress
1973 :type '(choice
1974 (const :tag "Don't force a record" nil)
1975 (const :tag "Force recording the DONE state" time)
1976 (const :tag "Force recording a note with the DONE state" note)))
1979 (defgroup org-priorities nil
1980 "Priorities in Org-mode."
1981 :tag "Org Priorities"
1982 :group 'org-todo)
1984 (defcustom org-highest-priority ?A
1985 "The highest priority of TODO items. A character like ?A, ?B etc.
1986 Must have a smaller ASCII number than `org-lowest-priority'."
1987 :group 'org-priorities
1988 :type 'character)
1990 (defcustom org-lowest-priority ?C
1991 "The lowest priority of TODO items. A character like ?A, ?B etc.
1992 Must have a larger ASCII number than `org-highest-priority'."
1993 :group 'org-priorities
1994 :type 'character)
1996 (defcustom org-default-priority ?B
1997 "The default priority of TODO items.
1998 This is the priority an item get if no explicit priority is given."
1999 :group 'org-priorities
2000 :type 'character)
2002 (defcustom org-priority-start-cycle-with-default t
2003 "Non-nil means, start with default priority when starting to cycle.
2004 When this is nil, the first step in the cycle will be (depending on the
2005 command used) one higher or lower that the default priority."
2006 :group 'org-priorities
2007 :type 'boolean)
2009 (defgroup org-time nil
2010 "Options concerning time stamps and deadlines in Org-mode."
2011 :tag "Org Time"
2012 :group 'org)
2014 (defcustom org-insert-labeled-timestamps-at-point nil
2015 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
2016 When nil, these labeled time stamps are forces into the second line of an
2017 entry, just after the headline. When scheduling from the global TODO list,
2018 the time stamp will always be forced into the second line."
2019 :group 'org-time
2020 :type 'boolean)
2022 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2023 "Formats for `format-time-string' which are used for time stamps.
2024 It is not recommended to change this constant.")
2026 (defcustom org-time-stamp-rounding-minutes '(0 5)
2027 "Number of minutes to round time stamps to.
2028 These are two values, the first applies when first creating a time stamp.
2029 The second applies when changing it with the commands `S-up' and `S-down'.
2030 When changing the time stamp, this means that it will change in steps
2031 of N minutes, as given by the second value.
2033 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2034 numbers should be factors of 60, so for example 5, 10, 15.
2036 When this is larger than 1, you can still force an exact time-stamp by using
2037 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2038 and by using a prefix arg to `S-up/down' to specify the exact number
2039 of minutes to shift."
2040 :group 'org-time
2041 :get '(lambda (var) ; Make sure all entries have 5 elements
2042 (if (integerp (default-value var))
2043 (list (default-value var) 5)
2044 (default-value var)))
2045 :type '(list
2046 (integer :tag "when inserting times")
2047 (integer :tag "when modifying times")))
2049 ;; Normalize old customizations of this variable.
2050 (when (integerp org-time-stamp-rounding-minutes)
2051 (setq org-time-stamp-rounding-minutes
2052 (list org-time-stamp-rounding-minutes
2053 org-time-stamp-rounding-minutes)))
2055 (defcustom org-display-custom-times nil
2056 "Non-nil means, overlay custom formats over all time stamps.
2057 The formats are defined through the variable `org-time-stamp-custom-formats'.
2058 To turn this on on a per-file basis, insert anywhere in the file:
2059 #+STARTUP: customtime"
2060 :group 'org-time
2061 :set 'set-default
2062 :type 'sexp)
2063 (make-variable-buffer-local 'org-display-custom-times)
2065 (defcustom org-time-stamp-custom-formats
2066 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2067 "Custom formats for time stamps. See `format-time-string' for the syntax.
2068 These are overlayed over the default ISO format if the variable
2069 `org-display-custom-times' is set. Time like %H:%M should be at the
2070 end of the second format. The custom formats are also honored by export
2071 commands, if custom time display is turned on at the time of export."
2072 :group 'org-time
2073 :type 'sexp)
2075 (defun org-time-stamp-format (&optional long inactive)
2076 "Get the right format for a time string."
2077 (let ((f (if long (cdr org-time-stamp-formats)
2078 (car org-time-stamp-formats))))
2079 (if inactive
2080 (concat "[" (substring f 1 -1) "]")
2081 f)))
2083 (defcustom org-time-clocksum-format "%d:%02d"
2084 "The format string used when creating CLOCKSUM lines, or when
2085 org-mode generates a time duration."
2086 :group 'org-time
2087 :type 'string)
2089 (defcustom org-deadline-warning-days 14
2090 "No. of days before expiration during which a deadline becomes active.
2091 This variable governs the display in sparse trees and in the agenda.
2092 When 0 or negative, it means use this number (the absolute value of it)
2093 even if a deadline has a different individual lead time specified.
2095 Custom commands can set this variable in the options section."
2096 :group 'org-time
2097 :group 'org-agenda-daily/weekly
2098 :type 'integer)
2100 (defcustom org-read-date-prefer-future t
2101 "Non-nil means, assume future for incomplete date input from user.
2102 This affects the following situations:
2103 1. The user gives a day, but no month.
2104 For example, if today is the 15th, and you enter \"3\", Org-mode will
2105 read this as the third of *next* month. However, if you enter \"17\",
2106 it will be considered as *this* month.
2107 2. The user gives a month but not a year.
2108 For example, if it is april and you enter \"feb 2\", this will be read
2109 as feb 2, *next* year. \"May 5\", however, will be this year.
2111 Currently this does not work for ISO week specifications.
2113 When this option is nil, the current month and year will always be used
2114 as defaults."
2115 :group 'org-time
2116 :type 'boolean)
2118 (defcustom org-read-date-display-live t
2119 "Non-nil means, display current interpretation of date prompt live.
2120 This display will be in an overlay, in the minibuffer."
2121 :group 'org-time
2122 :type 'boolean)
2124 (defcustom org-read-date-popup-calendar t
2125 "Non-nil means, pop up a calendar when prompting for a date.
2126 In the calendar, the date can be selected with mouse-1. However, the
2127 minibuffer will also be active, and you can simply enter the date as well.
2128 When nil, only the minibuffer will be available."
2129 :group 'org-time
2130 :type 'boolean)
2131 (if (fboundp 'defvaralias)
2132 (defvaralias 'org-popup-calendar-for-date-prompt
2133 'org-read-date-popup-calendar))
2135 (defcustom org-read-date-minibuffer-setup-hook nil
2136 "Hook to be used to set up keys for the date/time interface.
2137 Add key definitions to `minibuffer-local-map', which will be a temporary
2138 copy."
2139 :group 'org-time
2140 :type 'hook)
2142 (defcustom org-extend-today-until 0
2143 "The hour when your day really ends. Must be an integer.
2144 This has influence for the following applications:
2145 - When switching the agenda to \"today\". It it is still earlier than
2146 the time given here, the day recognized as TODAY is actually yesterday.
2147 - When a date is read from the user and it is still before the time given
2148 here, the current date and time will be assumed to be yesterday, 23:59.
2149 Also, timestamps inserted in remember templates follow this rule.
2151 IMPORTANT: This is a feature whose implementation is and likely will
2152 remain incomplete. Really, it is only here because past midnight seems to
2153 be the favorite working time of John Wiegley :-)"
2154 :group 'org-time
2155 :type 'integer)
2157 (defcustom org-edit-timestamp-down-means-later nil
2158 "Non-nil means, S-down will increase the time in a time stamp.
2159 When nil, S-up will increase."
2160 :group 'org-time
2161 :type 'boolean)
2163 (defcustom org-calendar-follow-timestamp-change t
2164 "Non-nil means, make the calendar window follow timestamp changes.
2165 When a timestamp is modified and the calendar window is visible, it will be
2166 moved to the new date."
2167 :group 'org-time
2168 :type 'boolean)
2170 (defgroup org-tags nil
2171 "Options concerning tags in Org-mode."
2172 :tag "Org Tags"
2173 :group 'org)
2175 (defcustom org-tag-alist nil
2176 "List of tags allowed in Org-mode files.
2177 When this list is nil, Org-mode will base TAG input on what is already in the
2178 buffer.
2179 The value of this variable is an alist, the car of each entry must be a
2180 keyword as a string, the cdr may be a character that is used to select
2181 that tag through the fast-tag-selection interface.
2182 See the manual for details."
2183 :group 'org-tags
2184 :type '(repeat
2185 (choice
2186 (cons (string :tag "Tag name")
2187 (character :tag "Access char"))
2188 (const :tag "Start radio group" (:startgroup))
2189 (const :tag "End radio group" (:endgroup))
2190 (const :tag "New line" (:newline)))))
2192 (defcustom org-tag-persistent-alist nil
2193 "List of tags that will always appear in all Org-mode files.
2194 This is in addition to any in buffer settings or customizations
2195 of `org-tag-alist'.
2196 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2197 The value of this variable is an alist, the car of each entry must be a
2198 keyword as a string, the cdr may be a character that is used to select
2199 that tag through the fast-tag-selection interface.
2200 See the manual for details.
2201 To disable these tags on a per-file basis, insert anywhere in the file:
2202 #+STARTUP: noptag"
2203 :group 'org-tags
2204 :type '(repeat
2205 (choice
2206 (cons (string :tag "Tag name")
2207 (character :tag "Access char"))
2208 (const :tag "Start radio group" (:startgroup))
2209 (const :tag "End radio group" (:endgroup))
2210 (const :tag "New line" (:newline)))))
2212 (defvar org-file-tags nil
2213 "List of tags that can be inherited by all entries in the file.
2214 The tags will be inherited if the variable `org-use-tag-inheritance'
2215 says they should be.
2216 This variable is populated from #+TAG lines.")
2218 (defcustom org-use-fast-tag-selection 'auto
2219 "Non-nil means, use fast tag selection scheme.
2220 This is a special interface to select and deselect tags with single keys.
2221 When nil, fast selection is never used.
2222 When the symbol `auto', fast selection is used if and only if selection
2223 characters for tags have been configured, either through the variable
2224 `org-tag-alist' or through a #+TAGS line in the buffer.
2225 When t, fast selection is always used and selection keys are assigned
2226 automatically if necessary."
2227 :group 'org-tags
2228 :type '(choice
2229 (const :tag "Always" t)
2230 (const :tag "Never" nil)
2231 (const :tag "When selection characters are configured" 'auto)))
2233 (defcustom org-fast-tag-selection-single-key nil
2234 "Non-nil means, fast tag selection exits after first change.
2235 When nil, you have to press RET to exit it.
2236 During fast tag selection, you can toggle this flag with `C-c'.
2237 This variable can also have the value `expert'. In this case, the window
2238 displaying the tags menu is not even shown, until you press C-c again."
2239 :group 'org-tags
2240 :type '(choice
2241 (const :tag "No" nil)
2242 (const :tag "Yes" t)
2243 (const :tag "Expert" expert)))
2245 (defvar org-fast-tag-selection-include-todo nil
2246 "Non-nil means, fast tags selection interface will also offer TODO states.
2247 This is an undocumented feature, you should not rely on it.")
2249 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2250 "The column to which tags should be indented in a headline.
2251 If this number is positive, it specifies the column. If it is negative,
2252 it means that the tags should be flushright to that column. For example,
2253 -80 works well for a normal 80 character screen."
2254 :group 'org-tags
2255 :type 'integer)
2257 (defcustom org-auto-align-tags t
2258 "Non-nil means, realign tags after pro/demotion of TODO state change.
2259 These operations change the length of a headline and therefore shift
2260 the tags around. With this options turned on, after each such operation
2261 the tags are again aligned to `org-tags-column'."
2262 :group 'org-tags
2263 :type 'boolean)
2265 (defcustom org-use-tag-inheritance t
2266 "Non-nil means, tags in levels apply also for sublevels.
2267 When nil, only the tags directly given in a specific line apply there.
2268 This may also be a list of tags that should be inherited, or a regexp that
2269 matches tags that should be inherited. Additional control is possible
2270 with the variable `org-tags-exclude-from-inheritance' which gives an
2271 explicit list of tags to be excluded from inheritance., even if the value of
2272 `org-use-tag-inheritance' would select it for inheritance.
2274 If this option is t, a match early-on in a tree can lead to a large
2275 number of matches in the subtree when constructing the agenda or creating
2276 a sparse tree. If you only want to see the first match in a tree during
2277 a search, check out the variable `org-tags-match-list-sublevels'."
2278 :group 'org-tags
2279 :type '(choice
2280 (const :tag "Not" nil)
2281 (const :tag "Always" t)
2282 (repeat :tag "Specific tags" (string :tag "Tag"))
2283 (regexp :tag "Tags matched by regexp")))
2285 (defcustom org-tags-exclude-from-inheritance nil
2286 "List of tags that should never be inherited.
2287 This is a way to exclude a few tags from inheritance. For way to do
2288 the opposite, to actively allow inheritance for selected tags,
2289 see the variable `org-use-tag-inheritance'."
2290 :group 'org-tags
2291 :type '(repeat (string :tag "Tag")))
2293 (defun org-tag-inherit-p (tag)
2294 "Check if TAG is one that should be inherited."
2295 (cond
2296 ((member tag org-tags-exclude-from-inheritance) nil)
2297 ((eq org-use-tag-inheritance t) t)
2298 ((not org-use-tag-inheritance) nil)
2299 ((stringp org-use-tag-inheritance)
2300 (string-match org-use-tag-inheritance tag))
2301 ((listp org-use-tag-inheritance)
2302 (member tag org-use-tag-inheritance))
2303 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2305 (defcustom org-tags-match-list-sublevels t
2306 "Non-nil means list also sublevels of headlines matching a search.
2307 This variable applies to tags/property searches, and also to stuck
2308 projects because this search is based on a tags match as well.
2310 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2311 the sublevels of a headline matching a tag search often also match
2312 the same search. Listing all of them can create very long lists.
2313 Setting this variable to nil causes subtrees of a match to be skipped.
2315 As a special case, if the tag search is restricted to TODO items, the
2316 value of this variable is ignored and sublevels are always checked, to
2317 make sure all corresponding TODO items find their way into the list.
2319 This variable is semi-obsolete and probably should always be true. It
2320 is better to limit inheritance to certain tags using the variables
2321 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2322 :group 'org-tags
2323 :type '(choice
2324 (const :tag "No, don't list them" nil)
2325 (const :tag "Yes, do list them" t)
2326 (const :tag "List them, indented with leading dots" indented)))
2328 (defvar org-tags-history nil
2329 "History of minibuffer reads for tags.")
2330 (defvar org-last-tags-completion-table nil
2331 "The last used completion table for tags.")
2332 (defvar org-after-tags-change-hook nil
2333 "Hook that is run after the tags in a line have changed.")
2335 (defgroup org-properties nil
2336 "Options concerning properties in Org-mode."
2337 :tag "Org Properties"
2338 :group 'org)
2340 (defcustom org-property-format "%-10s %s"
2341 "How property key/value pairs should be formatted by `indent-line'.
2342 When `indent-line' hits a property definition, it will format the line
2343 according to this format, mainly to make sure that the values are
2344 lined-up with respect to each other."
2345 :group 'org-properties
2346 :type 'string)
2348 (defcustom org-use-property-inheritance nil
2349 "Non-nil means, properties apply also for sublevels.
2351 This setting is chiefly used during property searches. Turning it on can
2352 cause significant overhead when doing a search, which is why it is not
2353 on by default.
2355 When nil, only the properties directly given in the current entry count.
2356 When t, every property is inherited. The value may also be a list of
2357 properties that should have inheritance, or a regular expression matching
2358 properties that should be inherited.
2360 However, note that some special properties use inheritance under special
2361 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2362 and the properties ending in \"_ALL\" when they are used as descriptor
2363 for valid values of a property.
2365 Note for programmers:
2366 When querying an entry with `org-entry-get', you can control if inheritance
2367 should be used. By default, `org-entry-get' looks only at the local
2368 properties. You can request inheritance by setting the inherit argument
2369 to t (to force inheritance) or to `selective' (to respect the setting
2370 in this variable)."
2371 :group 'org-properties
2372 :type '(choice
2373 (const :tag "Not" nil)
2374 (const :tag "Always" t)
2375 (repeat :tag "Specific properties" (string :tag "Property"))
2376 (regexp :tag "Properties matched by regexp")))
2378 (defun org-property-inherit-p (property)
2379 "Check if PROPERTY is one that should be inherited."
2380 (cond
2381 ((eq org-use-property-inheritance t) t)
2382 ((not org-use-property-inheritance) nil)
2383 ((stringp org-use-property-inheritance)
2384 (string-match org-use-property-inheritance property))
2385 ((listp org-use-property-inheritance)
2386 (member property org-use-property-inheritance))
2387 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2389 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2390 "The default column format, if no other format has been defined.
2391 This variable can be set on the per-file basis by inserting a line
2393 #+COLUMNS: %25ITEM ....."
2394 :group 'org-properties
2395 :type 'string)
2397 (defcustom org-columns-ellipses ".."
2398 "The ellipses to be used when a field in column view is truncated.
2399 When this is the empty string, as many characters as possible are shown,
2400 but then there will be no visual indication that the field has been truncated.
2401 When this is a string of length N, the last N characters of a truncated
2402 field are replaced by this string. If the column is narrower than the
2403 ellipses string, only part of the ellipses string will be shown."
2404 :group 'org-properties
2405 :type 'string)
2407 (defcustom org-columns-modify-value-for-display-function nil
2408 "Function that modifies values for display in column view.
2409 For example, it can be used to cut out a certain part from a time stamp.
2410 The function must take 2 arguments:
2412 column-title The title of the column (*not* the property name)
2413 value The value that should be modified.
2415 The function should return the value that should be displayed,
2416 or nil if the normal value should be used."
2417 :group 'org-properties
2418 :type 'function)
2420 (defcustom org-effort-property "Effort"
2421 "The property that is being used to keep track of effort estimates.
2422 Effort estimates given in this property need to have the format H:MM."
2423 :group 'org-properties
2424 :group 'org-progress
2425 :type '(string :tag "Property"))
2427 (defconst org-global-properties-fixed
2428 '(("VISIBILITY_ALL" . "folded children content all"))
2429 "List of property/value pairs that can be inherited by any entry.
2431 These are fixed values, for the preset properties. The user variable
2432 that can be used to add to this list is `org-global-properties'.
2434 The entries in this list are cons cells where the car is a property
2435 name and cdr is a string with the value. If the value represents
2436 multiple items like an \"_ALL\" property, separate the items by
2437 spaces.")
2439 (defcustom org-global-properties nil
2440 "List of property/value pairs that can be inherited by any entry.
2442 This list will be combined with the constant `org-global-properties-fixed'.
2444 The entries in this list are cons cells where the car is a property
2445 name and cdr is a string with the value.
2447 You can set buffer-local values for the same purpose in the variable
2448 `org-file-properties' this by adding lines like
2450 #+PROPERTY: NAME VALUE"
2451 :group 'org-properties
2452 :type '(repeat
2453 (cons (string :tag "Property")
2454 (string :tag "Value"))))
2456 (defvar org-file-properties nil
2457 "List of property/value pairs that can be inherited by any entry.
2458 Valid for the current buffer.
2459 This variable is populated from #+PROPERTY lines.")
2460 (make-variable-buffer-local 'org-file-properties)
2462 (defgroup org-agenda nil
2463 "Options concerning agenda views in Org-mode."
2464 :tag "Org Agenda"
2465 :group 'org)
2467 (defvar org-category nil
2468 "Variable used by org files to set a category for agenda display.
2469 Such files should use a file variable to set it, for example
2471 # -*- mode: org; org-category: \"ELisp\"
2473 or contain a special line
2475 #+CATEGORY: ELisp
2477 If the file does not specify a category, then file's base name
2478 is used instead.")
2479 (make-variable-buffer-local 'org-category)
2480 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2482 (defcustom org-agenda-files nil
2483 "The files to be used for agenda display.
2484 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2485 \\[org-remove-file]. You can also use customize to edit the list.
2487 If an entry is a directory, all files in that directory that are matched by
2488 `org-agenda-file-regexp' will be part of the file list.
2490 If the value of the variable is not a list but a single file name, then
2491 the list of agenda files is actually stored and maintained in that file, one
2492 agenda file per line."
2493 :group 'org-agenda
2494 :type '(choice
2495 (repeat :tag "List of files and directories" file)
2496 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2498 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2499 "Regular expression to match files for `org-agenda-files'.
2500 If any element in the list in that variable contains a directory instead
2501 of a normal file, all files in that directory that are matched by this
2502 regular expression will be included."
2503 :group 'org-agenda
2504 :type 'regexp)
2506 (defcustom org-agenda-text-search-extra-files nil
2507 "List of extra files to be searched by text search commands.
2508 These files will be search in addition to the agenda files by the
2509 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2510 Note that these files will only be searched for text search commands,
2511 not for the other agenda views like todo lists, tag searches or the weekly
2512 agenda. This variable is intended to list notes and possibly archive files
2513 that should also be searched by these two commands.
2514 In fact, if the first element in the list is the symbol `agenda-archives',
2515 than all archive files of all agenda files will be added to the search
2516 scope."
2517 :group 'org-agenda
2518 :type '(set :greedy t
2519 (const :tag "Agenda Archives" agenda-archives)
2520 (repeat :inline t (file))))
2522 (if (fboundp 'defvaralias)
2523 (defvaralias 'org-agenda-multi-occur-extra-files
2524 'org-agenda-text-search-extra-files))
2526 (defcustom org-agenda-skip-unavailable-files nil
2527 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2528 A nil value means to remove them, after a query, from the list."
2529 :group 'org-agenda
2530 :type 'boolean)
2532 (defcustom org-calendar-to-agenda-key [?c]
2533 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2534 The command `org-calendar-goto-agenda' will be bound to this key. The
2535 default is the character `c' because then `c' can be used to switch back and
2536 forth between agenda and calendar."
2537 :group 'org-agenda
2538 :type 'sexp)
2540 (defcustom org-calendar-agenda-action-key [?k]
2541 "The key to be installed in `calendar-mode-map' for agenda-action.
2542 The command `org-agenda-action' will be bound to this key. The
2543 default is the character `k' because we use the same key in the agenda."
2544 :group 'org-agenda
2545 :type 'sexp)
2547 (eval-after-load "calendar"
2548 '(progn
2549 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2550 'org-calendar-goto-agenda)
2551 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2552 'org-agenda-action)))
2554 (defgroup org-latex nil
2555 "Options for embedding LaTeX code into Org-mode."
2556 :tag "Org LaTeX"
2557 :group 'org)
2559 (defcustom org-format-latex-options
2560 '(:foreground default :background default :scale 1.0
2561 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2562 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2563 "Options for creating images from LaTeX fragments.
2564 This is a property list with the following properties:
2565 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2566 `default' means use the foreground of the default face.
2567 :background the background color, or \"Transparent\".
2568 `default' means use the background of the default face.
2569 :scale a scaling factor for the size of the images.
2570 :html-foreground, :html-background, :html-scale
2571 the same numbers for HTML export.
2572 :matchers a list indicating which matchers should be used to
2573 find LaTeX fragments. Valid members of this list are:
2574 \"begin\" find environments
2575 \"$1\" find single characters surrounded by $.$
2576 \"$\" find math expressions surrounded by $...$
2577 \"$$\" find math expressions surrounded by $$....$$
2578 \"\\(\" find math expressions surrounded by \\(...\\)
2579 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2580 :group 'org-latex
2581 :type 'plist)
2583 (defcustom org-format-latex-header "\\documentclass{article}
2584 \\usepackage{fullpage} % do not remove
2585 \\usepackage{amssymb}
2586 \\usepackage[usenames]{color}
2587 \\usepackage{amsmath}
2588 \\usepackage{latexsym}
2589 \\usepackage[mathscr]{eucal}
2590 \\pagestyle{empty} % do not remove"
2591 "The document header used for processing LaTeX fragments."
2592 :group 'org-latex
2593 :type 'string)
2596 (defgroup org-font-lock nil
2597 "Font-lock settings for highlighting in Org-mode."
2598 :tag "Org Font Lock"
2599 :group 'org)
2601 (defcustom org-level-color-stars-only nil
2602 "Non-nil means fontify only the stars in each headline.
2603 When nil, the entire headline is fontified.
2604 Changing it requires restart of `font-lock-mode' to become effective
2605 also in regions already fontified."
2606 :group 'org-font-lock
2607 :type 'boolean)
2609 (defcustom org-hide-leading-stars nil
2610 "Non-nil means, hide the first N-1 stars in a headline.
2611 This works by using the face `org-hide' for these stars. This
2612 face is white for a light background, and black for a dark
2613 background. You may have to customize the face `org-hide' to
2614 make this work.
2615 Changing it requires restart of `font-lock-mode' to become effective
2616 also in regions already fontified.
2617 You may also set this on a per-file basis by adding one of the following
2618 lines to the buffer:
2620 #+STARTUP: hidestars
2621 #+STARTUP: showstars"
2622 :group 'org-font-lock
2623 :type 'boolean)
2625 (defcustom org-fontify-done-headline nil
2626 "Non-nil means, change the face of a headline if it is marked DONE.
2627 Normally, only the TODO/DONE keyword indicates the state of a headline.
2628 When this is non-nil, the headline after the keyword is set to the
2629 `org-headline-done' as an additional indication."
2630 :group 'org-font-lock
2631 :type 'boolean)
2633 (defcustom org-fontify-emphasized-text t
2634 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2635 Changing this variable requires a restart of Emacs to take effect."
2636 :group 'org-font-lock
2637 :type 'boolean)
2639 (defcustom org-highlight-latex-fragments-and-specials nil
2640 "Non-nil means, fontify what is treated specially by the exporters."
2641 :group 'org-font-lock
2642 :type 'boolean)
2644 (defcustom org-hide-emphasis-markers nil
2645 "Non-nil mean font-lock should hide the emphasis marker characters."
2646 :group 'org-font-lock
2647 :type 'boolean)
2649 (defvar org-emph-re nil
2650 "Regular expression for matching emphasis.")
2651 (defvar org-verbatim-re nil
2652 "Regular expression for matching verbatim text.")
2653 (defvar org-emphasis-regexp-components) ; defined just below
2654 (defvar org-emphasis-alist) ; defined just below
2655 (defun org-set-emph-re (var val)
2656 "Set variable and compute the emphasis regular expression."
2657 (set var val)
2658 (when (and (boundp 'org-emphasis-alist)
2659 (boundp 'org-emphasis-regexp-components)
2660 org-emphasis-alist org-emphasis-regexp-components)
2661 (let* ((e org-emphasis-regexp-components)
2662 (pre (car e))
2663 (post (nth 1 e))
2664 (border (nth 2 e))
2665 (body (nth 3 e))
2666 (nl (nth 4 e))
2667 (body1 (concat body "*?"))
2668 (markers (mapconcat 'car org-emphasis-alist ""))
2669 (vmarkers (mapconcat
2670 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2671 org-emphasis-alist "")))
2672 ;; make sure special characters appear at the right position in the class
2673 (if (string-match "\\^" markers)
2674 (setq markers (concat (replace-match "" t t markers) "^")))
2675 (if (string-match "-" markers)
2676 (setq markers (concat (replace-match "" t t markers) "-")))
2677 (if (string-match "\\^" vmarkers)
2678 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2679 (if (string-match "-" vmarkers)
2680 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2681 (if (> nl 0)
2682 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2683 (int-to-string nl) "\\}")))
2684 ;; Make the regexp
2685 (setq org-emph-re
2686 (concat "\\([" pre "]\\|^\\)"
2687 "\\("
2688 "\\([" markers "]\\)"
2689 "\\("
2690 "[^" border "]\\|"
2691 "[^" border "]"
2692 body1
2693 "[^" border "]"
2694 "\\)"
2695 "\\3\\)"
2696 "\\([" post "]\\|$\\)"))
2697 (setq org-verbatim-re
2698 (concat "\\([" pre "]\\|^\\)"
2699 "\\("
2700 "\\([" vmarkers "]\\)"
2701 "\\("
2702 "[^" border "]\\|"
2703 "[^" border "]"
2704 body1
2705 "[^" border "]"
2706 "\\)"
2707 "\\3\\)"
2708 "\\([" post "]\\|$\\)")))))
2710 (defcustom org-emphasis-regexp-components
2711 '(" \t('\"{" "- \t.,:!?;'\")}" " \t\r\n,\"'" "." 1)
2712 "Components used to build the regular expression for emphasis.
2713 This is a list with 6 entries. Terminology: In an emphasis string
2714 like \" *strong word* \", we call the initial space PREMATCH, the final
2715 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2716 and \"trong wor\" is the body. The different components in this variable
2717 specify what is allowed/forbidden in each part:
2719 pre Chars allowed as prematch. Beginning of line will be allowed too.
2720 post Chars allowed as postmatch. End of line will be allowed too.
2721 border The chars *forbidden* as border characters.
2722 body-regexp A regexp like \".\" to match a body character. Don't use
2723 non-shy groups here, and don't allow newline here.
2724 newline The maximum number of newlines allowed in an emphasis exp.
2726 Use customize to modify this, or restart Emacs after changing it."
2727 :group 'org-font-lock
2728 :set 'org-set-emph-re
2729 :type '(list
2730 (sexp :tag "Allowed chars in pre ")
2731 (sexp :tag "Allowed chars in post ")
2732 (sexp :tag "Forbidden chars in border ")
2733 (sexp :tag "Regexp for body ")
2734 (integer :tag "number of newlines allowed")
2735 (option (boolean :tag "Please ignore this button"))))
2737 (defcustom org-emphasis-alist
2738 `(("*" bold "<b>" "</b>")
2739 ("/" italic "<i>" "</i>")
2740 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2741 ("=" org-code "<code>" "</code>" verbatim)
2742 ("~" org-verbatim "<code>" "</code>" verbatim)
2743 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2744 "<del>" "</del>")
2746 "Special syntax for emphasized text.
2747 Text starting and ending with a special character will be emphasized, for
2748 example *bold*, _underlined_ and /italic/. This variable sets the marker
2749 characters, the face to be used by font-lock for highlighting in Org-mode
2750 Emacs buffers, and the HTML tags to be used for this.
2751 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
2752 Use customize to modify this, or restart Emacs after changing it."
2753 :group 'org-font-lock
2754 :set 'org-set-emph-re
2755 :type '(repeat
2756 (list
2757 (string :tag "Marker character")
2758 (choice
2759 (face :tag "Font-lock-face")
2760 (plist :tag "Face property list"))
2761 (string :tag "HTML start tag")
2762 (string :tag "HTML end tag")
2763 (option (const verbatim)))))
2765 ;;; Miscellaneous options
2767 (defgroup org-completion nil
2768 "Completion in Org-mode."
2769 :tag "Org Completion"
2770 :group 'org)
2772 (defcustom org-completion-use-ido nil
2773 "Non-nil means, use ido completion wherever possible.
2774 Note that `ido-mode' must be active for this variable to be relevant.
2775 If you decide to turn this variable on, you might well want to turn off
2776 `org-outline-path-complete-in-steps'."
2777 :group 'org-completion
2778 :type 'boolean)
2780 (defcustom org-completion-fallback-command 'hippie-expand
2781 "The expansion command called by \\[org-complete] in normal context.
2782 Normal means, no org-mode-specific context."
2783 :group 'org-completion
2784 :type 'function)
2786 ;;; Functions and variables from ther packages
2787 ;; Declared here to avoid compiler warnings
2789 ;; XEmacs only
2790 (defvar outline-mode-menu-heading)
2791 (defvar outline-mode-menu-show)
2792 (defvar outline-mode-menu-hide)
2793 (defvar zmacs-regions) ; XEmacs regions
2795 ;; Emacs only
2796 (defvar mark-active)
2798 ;; Various packages
2799 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2800 (declare-function calendar-forward-day "cal-move" (arg))
2801 (declare-function calendar-goto-date "cal-move" (date))
2802 (declare-function calendar-goto-today "cal-move" ())
2803 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2804 (defvar calc-embedded-close-formula)
2805 (defvar calc-embedded-open-formula)
2806 (declare-function cdlatex-tab "ext:cdlatex" ())
2807 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2808 (defvar font-lock-unfontify-region-function)
2809 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2810 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2811 (defvar iswitchb-temp-buflist)
2812 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2813 (defvar org-agenda-tags-todo-honor-ignore-options)
2814 (declare-function org-agenda-skip "org-agenda" ())
2815 (declare-function org-format-agenda-item "org-agenda"
2816 (extra txt &optional category tags dotime noprefix remove-re))
2817 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2818 (declare-function org-agenda-change-all-lines "org-agenda"
2819 (newhead hdmarker &optional fixface just-this))
2820 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2821 (declare-function org-agenda-maybe-redo "org-agenda" ())
2822 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2823 (beg end))
2824 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2825 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2826 "org-agenda" (&optional end))
2828 (declare-function parse-time-string "parse-time" (string))
2829 (declare-function remember "remember" (&optional initial))
2830 (declare-function remember-buffer-desc "remember" ())
2831 (declare-function remember-finalize "remember" ())
2832 (defvar remember-save-after-remembering)
2833 (defvar remember-data-file)
2834 (defvar remember-register)
2835 (defvar remember-buffer)
2836 (defvar remember-handler-functions)
2837 (defvar remember-annotation-functions)
2838 (defvar texmathp-why)
2839 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2840 (declare-function table--at-cell-p "table" (position &optional object at-column))
2842 (defvar w3m-current-url)
2843 (defvar w3m-current-title)
2845 (defvar org-latex-regexps)
2847 ;;; Autoload and prepare some org modules
2849 ;; Some table stuff that needs to be defined here, because it is used
2850 ;; by the functions setting up org-mode or checking for table context.
2852 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2853 "Detects an org-type or table-type table.")
2854 (defconst org-table-line-regexp "^[ \t]*|"
2855 "Detects an org-type table line.")
2856 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2857 "Detects an org-type table line.")
2858 (defconst org-table-hline-regexp "^[ \t]*|-"
2859 "Detects an org-type table hline.")
2860 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2861 "Detects a table-type table hline.")
2862 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2863 "Searching from within a table (any type) this finds the first line
2864 outside the table.")
2866 ;; Autoload the functions in org-table.el that are needed by functions here.
2868 (eval-and-compile
2869 (org-autoload "org-table"
2870 '(org-table-align org-table-begin org-table-blank-field
2871 org-table-convert org-table-convert-region org-table-copy-down
2872 org-table-copy-region org-table-create
2873 org-table-create-or-convert-from-region
2874 org-table-create-with-table.el org-table-current-dline
2875 org-table-cut-region org-table-delete-column org-table-edit-field
2876 org-table-edit-formulas org-table-end org-table-eval-formula
2877 org-table-export org-table-field-info
2878 org-table-get-stored-formulas org-table-goto-column
2879 org-table-hline-and-move org-table-import org-table-insert-column
2880 org-table-insert-hline org-table-insert-row org-table-iterate
2881 org-table-justify-field-maybe org-table-kill-row
2882 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2883 org-table-move-column org-table-move-column-left
2884 org-table-move-column-right org-table-move-row
2885 org-table-move-row-down org-table-move-row-up
2886 org-table-next-field org-table-next-row org-table-paste-rectangle
2887 org-table-previous-field org-table-recalculate
2888 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2889 org-table-toggle-coordinate-overlays
2890 org-table-toggle-formula-debugger org-table-wrap-region
2891 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2893 (defun org-at-table-p (&optional table-type)
2894 "Return t if the cursor is inside an org-type table.
2895 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2896 (if org-enable-table-editor
2897 (save-excursion
2898 (beginning-of-line 1)
2899 (looking-at (if table-type org-table-any-line-regexp
2900 org-table-line-regexp)))
2901 nil))
2902 (defsubst org-table-p () (org-at-table-p))
2904 (defun org-at-table.el-p ()
2905 "Return t if and only if we are at a table.el table."
2906 (and (org-at-table-p 'any)
2907 (save-excursion
2908 (goto-char (org-table-begin 'any))
2909 (looking-at org-table1-hline-regexp))))
2910 (defun org-table-recognize-table.el ()
2911 "If there is a table.el table nearby, recognize it and move into it."
2912 (if org-table-tab-recognizes-table.el
2913 (if (org-at-table.el-p)
2914 (progn
2915 (beginning-of-line 1)
2916 (if (looking-at org-table-dataline-regexp)
2918 (if (looking-at org-table1-hline-regexp)
2919 (progn
2920 (beginning-of-line 2)
2921 (if (looking-at org-table-any-border-regexp)
2922 (beginning-of-line -1)))))
2923 (if (re-search-forward "|" (org-table-end t) t)
2924 (progn
2925 (require 'table)
2926 (if (table--at-cell-p (point))
2928 (message "recognizing table.el table...")
2929 (table-recognize-table)
2930 (message "recognizing table.el table...done")))
2931 (error "This should not happen..."))
2933 nil)
2934 nil))
2936 (defun org-at-table-hline-p ()
2937 "Return t if the cursor is inside a hline in a table."
2938 (if org-enable-table-editor
2939 (save-excursion
2940 (beginning-of-line 1)
2941 (looking-at org-table-hline-regexp))
2942 nil))
2944 (defvar org-table-clean-did-remove-column nil)
2946 (defun org-table-map-tables (function)
2947 "Apply FUNCTION to the start of all tables in the buffer."
2948 (save-excursion
2949 (save-restriction
2950 (widen)
2951 (goto-char (point-min))
2952 (while (re-search-forward org-table-any-line-regexp nil t)
2953 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2954 (beginning-of-line 1)
2955 (if (looking-at org-table-line-regexp)
2956 (save-excursion (funcall function)))
2957 (re-search-forward org-table-any-border-regexp nil 1))))
2958 (message "Mapping tables: done"))
2960 ;; Declare and autoload functions from org-exp.el & Co
2962 (declare-function org-default-export-plist "org-exp")
2963 (declare-function org-infile-export-plist "org-exp")
2964 (declare-function org-get-current-options "org-exp")
2965 (eval-and-compile
2966 (org-autoload "org-exp"
2967 '(org-export org-export-visible
2968 org-insert-export-options-template
2969 org-table-clean-before-export))
2970 (org-autoload "org-ascii"
2971 '(org-export-as-ascii org-export-ascii-preprocess
2972 org-export-as-ascii-to-buffer org-replace-region-by-ascii
2973 org-export-region-as-ascii))
2974 (org-autoload "org-html"
2975 '(org-export-as-html-and-open
2976 org-export-as-html-batch org-export-as-html-to-buffer
2977 org-replace-region-by-html org-export-region-as-html
2978 org-export-as-html))
2979 (org-autoload "org-icalendar"
2980 '(org-export-icalendar-this-file
2981 org-export-icalendar-all-agenda-files
2982 org-export-icalendar-combine-agenda-files))
2983 (org-autoload "org-xoxo" '(org-export-as-xoxo)))
2985 ;; Declare and autoload functions from org-agenda.el
2987 (eval-and-compile
2988 (org-autoload "org-agenda"
2989 '(org-agenda org-agenda-list org-search-view
2990 org-todo-list org-tags-view org-agenda-list-stuck-projects
2991 org-diary org-agenda-to-appt
2992 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
2994 ;; Autoload org-remember
2996 (eval-and-compile
2997 (org-autoload "org-remember"
2998 '(org-remember-insinuate org-remember-annotation
2999 org-remember-apply-template org-remember org-remember-handler)))
3001 ;; Autoload org-clock.el
3004 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3005 (beg end))
3006 (declare-function org-clock-update-mode-line "org-clock" ())
3007 (defvar org-clock-start-time)
3008 (defvar org-clock-marker (make-marker)
3009 "Marker recording the last clock-in.")
3011 (eval-and-compile
3012 (org-autoload
3013 "org-clock"
3014 '(org-clock-in org-clock-out org-clock-cancel
3015 org-clock-goto org-clock-sum org-clock-display
3016 org-clock-remove-overlays org-clock-report
3017 org-clocktable-shift org-dblock-write:clocktable
3018 org-get-clocktable)))
3020 (defun org-clock-update-time-maybe ()
3021 "If this is a CLOCK line, update it and return t.
3022 Otherwise, return nil."
3023 (interactive)
3024 (save-excursion
3025 (beginning-of-line 1)
3026 (skip-chars-forward " \t")
3027 (when (looking-at org-clock-string)
3028 (let ((re (concat "[ \t]*" org-clock-string
3029 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3030 "\\([ \t]*=>.*\\)?\\)?"))
3031 ts te h m s neg)
3032 (cond
3033 ((not (looking-at re))
3034 nil)
3035 ((not (match-end 2))
3036 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3037 (> org-clock-marker (point))
3038 (<= org-clock-marker (point-at-eol)))
3039 ;; The clock is running here
3040 (setq org-clock-start-time
3041 (apply 'encode-time
3042 (org-parse-time-string (match-string 1))))
3043 (org-clock-update-mode-line)))
3045 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3046 (end-of-line 1)
3047 (setq ts (match-string 1)
3048 te (match-string 3))
3049 (setq s (- (time-to-seconds
3050 (apply 'encode-time (org-parse-time-string te)))
3051 (time-to-seconds
3052 (apply 'encode-time (org-parse-time-string ts))))
3053 neg (< s 0)
3054 s (abs s)
3055 h (floor (/ s 3600))
3056 s (- s (* 3600 h))
3057 m (floor (/ s 60))
3058 s (- s (* 60 s)))
3059 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3060 t))))))
3062 (defun org-check-running-clock ()
3063 "Check if the current buffer contains the running clock.
3064 If yes, offer to stop it and to save the buffer with the changes."
3065 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3066 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3067 (buffer-name))))
3068 (org-clock-out)
3069 (when (y-or-n-p "Save changed buffer?")
3070 (save-buffer))))
3072 (defun org-clocktable-try-shift (dir n)
3073 "Check if this line starts a clock table, if yes, shift the time block."
3074 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3075 (org-clocktable-shift dir n)))
3077 ;; Autoload org-timer.el
3079 (eval-and-compile
3080 (org-autoload
3081 "org-timer"
3082 '(org-timer-start org-timer org-timer-item
3083 org-timer-change-times-in-region)))
3085 ;; Autoload org-feed.el
3087 (eval-and-compile
3088 (org-autoload
3089 "org-feed"
3090 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3093 ;; Autoload archiving code
3094 ;; The stuff that is needed for cycling and tags has to be defined here.
3096 (defgroup org-archive nil
3097 "Options concerning archiving in Org-mode."
3098 :tag "Org Archive"
3099 :group 'org-structure)
3101 (defcustom org-archive-location "%s_archive::"
3102 "The location where subtrees should be archived.
3104 The value of this variable is a string, consisting of two parts,
3105 separated by a double-colon. The first part is a filename and
3106 the second part is a headline.
3108 When the filename is omitted, archiving happens in the same file.
3109 %s in the filename will be replaced by the current file
3110 name (without the directory part). Archiving to a different file
3111 is useful to keep archived entries from contributing to the
3112 Org-mode Agenda.
3114 The archived entries will be filed as subtrees of the specified
3115 headline. When the headline is omitted, the subtrees are simply
3116 filed away at the end of the file, as top-level entries. Also in
3117 the heading you can use %s to represent the file name, this can be
3118 useful when using the same archive for a number of different files.
3120 Here are a few examples:
3121 \"%s_archive::\"
3122 If the current file is Projects.org, archive in file
3123 Projects.org_archive, as top-level trees. This is the default.
3125 \"::* Archived Tasks\"
3126 Archive in the current file, under the top-level headline
3127 \"* Archived Tasks\".
3129 \"~/org/archive.org::\"
3130 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3132 \"~/org/archive.org::From %s\"
3133 Archive in file ~/org/archive.org (absolute path), und headlines
3134 \"From FILENAME\" where file name is the current file name.
3136 \"basement::** Finished Tasks\"
3137 Archive in file ./basement (relative path), as level 3 trees
3138 below the level 2 heading \"** Finished Tasks\".
3140 You may set this option on a per-file basis by adding to the buffer a
3141 line like
3143 #+ARCHIVE: basement::** Finished Tasks
3145 You may also define it locally for a subtree by setting an ARCHIVE property
3146 in the entry. If such a property is found in an entry, or anywhere up
3147 the hierarchy, it will be used."
3148 :group 'org-archive
3149 :type 'string)
3151 (defcustom org-archive-tag "ARCHIVE"
3152 "The tag that marks a subtree as archived.
3153 An archived subtree does not open during visibility cycling, and does
3154 not contribute to the agenda listings.
3155 After changing this, font-lock must be restarted in the relevant buffers to
3156 get the proper fontification."
3157 :group 'org-archive
3158 :group 'org-keywords
3159 :type 'string)
3161 (defcustom org-agenda-skip-archived-trees t
3162 "Non-nil means, the agenda will skip any items located in archived trees.
3163 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3164 variable is no longer recommended, you should leave it at the value t.
3165 Instead, use the key `v' to cycle the archives-mode in the agenda."
3166 :group 'org-archive
3167 :group 'org-agenda-skip
3168 :type 'boolean)
3170 (defcustom org-columns-skip-arrchived-trees t
3171 "Non-nil means, irgnore archived trees when creating column view."
3172 :group 'org-archive
3173 :group 'org-properties
3174 :type 'boolean)
3176 (defcustom org-cycle-open-archived-trees nil
3177 "Non-nil means, `org-cycle' will open archived trees.
3178 An archived tree is a tree marked with the tag ARCHIVE.
3179 When nil, archived trees will stay folded. You can still open them with
3180 normal outline commands like `show-all', but not with the cycling commands."
3181 :group 'org-archive
3182 :group 'org-cycle
3183 :type 'boolean)
3185 (defcustom org-sparse-tree-open-archived-trees nil
3186 "Non-nil means sparse tree construction shows matches in archived trees.
3187 When nil, matches in these trees are highlighted, but the trees are kept in
3188 collapsed state."
3189 :group 'org-archive
3190 :group 'org-sparse-trees
3191 :type 'boolean)
3193 (defun org-cycle-hide-archived-subtrees (state)
3194 "Re-hide all archived subtrees after a visibility state change."
3195 (when (and (not org-cycle-open-archived-trees)
3196 (not (memq state '(overview folded))))
3197 (save-excursion
3198 (let* ((globalp (memq state '(contents all)))
3199 (beg (if globalp (point-min) (point)))
3200 (end (if globalp (point-max) (org-end-of-subtree t))))
3201 (org-hide-archived-subtrees beg end)
3202 (goto-char beg)
3203 (if (looking-at (concat ".*:" org-archive-tag ":"))
3204 (message "%s" (substitute-command-keys
3205 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3207 (defun org-force-cycle-archived ()
3208 "Cycle subtree even if it is archived."
3209 (interactive)
3210 (setq this-command 'org-cycle)
3211 (let ((org-cycle-open-archived-trees t))
3212 (call-interactively 'org-cycle)))
3214 (defun org-hide-archived-subtrees (beg end)
3215 "Re-hide all archived subtrees after a visibility state change."
3216 (save-excursion
3217 (let* ((re (concat ":" org-archive-tag ":")))
3218 (goto-char beg)
3219 (while (re-search-forward re end t)
3220 (and (org-on-heading-p) (hide-subtree))
3221 (org-end-of-subtree t)))))
3223 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3225 (eval-and-compile
3226 (org-autoload "org-archive"
3227 '(org-add-archive-files org-archive-subtree
3228 org-archive-to-archive-sibling org-toggle-archive-tag)))
3230 ;; Autoload Column View Code
3232 (declare-function org-columns-number-to-string "org-colview")
3233 (declare-function org-columns-get-format-and-top-level "org-colview")
3234 (declare-function org-columns-compute "org-colview")
3236 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3237 '(org-columns-number-to-string org-columns-get-format-and-top-level
3238 org-columns-compute org-agenda-columns org-columns-remove-overlays
3239 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3241 ;; Autoload ID code
3243 (declare-function org-id-store-link "org-id")
3244 (declare-function org-id-locations-load "org-id")
3245 (declare-function org-id-locations-save "org-id")
3246 (defvar org-id-track-globally)
3247 (org-autoload "org-id"
3248 '(org-id-get-create org-id-new org-id-copy org-id-get
3249 org-id-get-with-outline-path-completion
3250 org-id-get-with-outline-drilling
3251 org-id-goto org-id-find org-id-store-link))
3253 ;; Autoload Plotting Code
3255 (org-autoload "org-plot"
3256 '(org-plot/gnuplot))
3258 ;;; Variables for pre-computed regular expressions, all buffer local
3260 (defvar org-drawer-regexp nil
3261 "Matches first line of a hidden block.")
3262 (make-variable-buffer-local 'org-drawer-regexp)
3263 (defvar org-todo-regexp nil
3264 "Matches any of the TODO state keywords.")
3265 (make-variable-buffer-local 'org-todo-regexp)
3266 (defvar org-not-done-regexp nil
3267 "Matches any of the TODO state keywords except the last one.")
3268 (make-variable-buffer-local 'org-not-done-regexp)
3269 (defvar org-not-done-heading-regexp nil
3270 "Matches a TODO headline that is not done.")
3271 (make-variable-buffer-local 'org-not-done-regexp)
3272 (defvar org-todo-line-regexp nil
3273 "Matches a headline and puts TODO state into group 2 if present.")
3274 (make-variable-buffer-local 'org-todo-line-regexp)
3275 (defvar org-complex-heading-regexp nil
3276 "Matches a headline and puts everything into groups:
3277 group 1: the stars
3278 group 2: The todo keyword, maybe
3279 group 3: Priority cookie
3280 group 4: True headline
3281 group 5: Tags")
3282 (make-variable-buffer-local 'org-complex-heading-regexp)
3283 (defvar org-todo-line-tags-regexp nil
3284 "Matches a headline and puts TODO state into group 2 if present.
3285 Also put tags into group 4 if tags are present.")
3286 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3287 (defvar org-nl-done-regexp nil
3288 "Matches newline followed by a headline with the DONE keyword.")
3289 (make-variable-buffer-local 'org-nl-done-regexp)
3290 (defvar org-looking-at-done-regexp nil
3291 "Matches the DONE keyword a point.")
3292 (make-variable-buffer-local 'org-looking-at-done-regexp)
3293 (defvar org-ds-keyword-length 12
3294 "Maximum length of the Deadline and SCHEDULED keywords.")
3295 (make-variable-buffer-local 'org-ds-keyword-length)
3296 (defvar org-deadline-regexp nil
3297 "Matches the DEADLINE keyword.")
3298 (make-variable-buffer-local 'org-deadline-regexp)
3299 (defvar org-deadline-time-regexp nil
3300 "Matches the DEADLINE keyword together with a time stamp.")
3301 (make-variable-buffer-local 'org-deadline-time-regexp)
3302 (defvar org-deadline-line-regexp nil
3303 "Matches the DEADLINE keyword and the rest of the line.")
3304 (make-variable-buffer-local 'org-deadline-line-regexp)
3305 (defvar org-scheduled-regexp nil
3306 "Matches the SCHEDULED keyword.")
3307 (make-variable-buffer-local 'org-scheduled-regexp)
3308 (defvar org-scheduled-time-regexp nil
3309 "Matches the SCHEDULED keyword together with a time stamp.")
3310 (make-variable-buffer-local 'org-scheduled-time-regexp)
3311 (defvar org-closed-time-regexp nil
3312 "Matches the CLOSED keyword together with a time stamp.")
3313 (make-variable-buffer-local 'org-closed-time-regexp)
3315 (defvar org-keyword-time-regexp nil
3316 "Matches any of the 4 keywords, together with the time stamp.")
3317 (make-variable-buffer-local 'org-keyword-time-regexp)
3318 (defvar org-keyword-time-not-clock-regexp nil
3319 "Matches any of the 3 keywords, together with the time stamp.")
3320 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3321 (defvar org-maybe-keyword-time-regexp nil
3322 "Matches a timestamp, possibly preceeded by a keyword.")
3323 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3324 (defvar org-planning-or-clock-line-re nil
3325 "Matches a line with planning or clock info.")
3326 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3328 (defconst org-plain-time-of-day-regexp
3329 (concat
3330 "\\(\\<[012]?[0-9]"
3331 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3332 "\\(--?"
3333 "\\(\\<[012]?[0-9]"
3334 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3335 "\\)?")
3336 "Regular expression to match a plain time or time range.
3337 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3338 groups carry important information:
3339 0 the full match
3340 1 the first time, range or not
3341 8 the second time, if it is a range.")
3343 (defconst org-plain-time-extension-regexp
3344 (concat
3345 "\\(\\<[012]?[0-9]"
3346 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3347 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3348 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3349 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3350 groups carry important information:
3351 0 the full match
3352 7 hours of duration
3353 9 minutes of duration")
3355 (defconst org-stamp-time-of-day-regexp
3356 (concat
3357 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3358 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3359 "\\(--?"
3360 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3361 "Regular expression to match a timestamp time or time range.
3362 After a match, the following groups carry important information:
3363 0 the full match
3364 1 date plus weekday, for backreferencing to make sure both times on same day
3365 2 the first time, range or not
3366 4 the second time, if it is a range.")
3368 (defconst org-startup-options
3369 '(("fold" org-startup-folded t)
3370 ("overview" org-startup-folded t)
3371 ("nofold" org-startup-folded nil)
3372 ("showall" org-startup-folded nil)
3373 ("content" org-startup-folded content)
3374 ("hidestars" org-hide-leading-stars t)
3375 ("showstars" org-hide-leading-stars nil)
3376 ("odd" org-odd-levels-only t)
3377 ("oddeven" org-odd-levels-only nil)
3378 ("align" org-startup-align-all-tables t)
3379 ("noalign" org-startup-align-all-tables nil)
3380 ("customtime" org-display-custom-times t)
3381 ("logdone" org-log-done time)
3382 ("lognotedone" org-log-done note)
3383 ("nologdone" org-log-done nil)
3384 ("lognoteclock-out" org-log-note-clock-out t)
3385 ("nolognoteclock-out" org-log-note-clock-out nil)
3386 ("logrepeat" org-log-repeat state)
3387 ("lognoterepeat" org-log-repeat note)
3388 ("nologrepeat" org-log-repeat nil)
3389 ("fninline" org-footnote-define-inline t)
3390 ("nofninline" org-footnote-define-inline nil)
3391 ("fnlocal" org-footnote-section nil)
3392 ("fnauto" org-footnote-auto-label t)
3393 ("fnprompt" org-footnote-auto-label nil)
3394 ("fnconfirm" org-footnote-auto-label confirm)
3395 ("fnplain" org-footnote-auto-label plain)
3396 ("constcgs" constants-unit-system cgs)
3397 ("constSI" constants-unit-system SI)
3398 ("noptag" org-tag-persistent-alist nil))
3399 "Variable associated with STARTUP options for org-mode.
3400 Each element is a list of three items: The startup options as written
3401 in the #+STARTUP line, the corresponding variable, and the value to
3402 set this variable to if the option is found. An optional forth element PUSH
3403 means to push this value onto the list in the variable.")
3405 (defun org-set-regexps-and-options ()
3406 "Precompute regular expressions for current buffer."
3407 (when (org-mode-p)
3408 (org-set-local 'org-todo-kwd-alist nil)
3409 (org-set-local 'org-todo-key-alist nil)
3410 (org-set-local 'org-todo-key-trigger nil)
3411 (org-set-local 'org-todo-keywords-1 nil)
3412 (org-set-local 'org-done-keywords nil)
3413 (org-set-local 'org-todo-heads nil)
3414 (org-set-local 'org-todo-sets nil)
3415 (org-set-local 'org-todo-log-states nil)
3416 (org-set-local 'org-file-properties nil)
3417 (org-set-local 'org-file-tags nil)
3418 (let ((re (org-make-options-regexp
3419 '("CATEGORY" "TODO" "COLUMNS"
3420 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3421 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3422 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3423 (splitre "[ \t]+")
3424 kwds kws0 kwsa key log value cat arch tags const links hw dws
3425 tail sep kws1 prio props ftags drawers
3426 ext-setup-or-nil setup-contents (start 0))
3427 (save-excursion
3428 (save-restriction
3429 (widen)
3430 (goto-char (point-min))
3431 (while (or (and ext-setup-or-nil
3432 (string-match re ext-setup-or-nil start)
3433 (setq start (match-end 0)))
3434 (and (setq ext-setup-or-nil nil start 0)
3435 (re-search-forward re nil t)))
3436 (setq key (upcase (match-string 1 ext-setup-or-nil))
3437 value (org-match-string-no-properties 2 ext-setup-or-nil))
3438 (cond
3439 ((equal key "CATEGORY")
3440 (if (string-match "[ \t]+$" value)
3441 (setq value (replace-match "" t t value)))
3442 (setq cat value))
3443 ((member key '("SEQ_TODO" "TODO"))
3444 (push (cons 'sequence (org-split-string value splitre)) kwds))
3445 ((equal key "TYP_TODO")
3446 (push (cons 'type (org-split-string value splitre)) kwds))
3447 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3448 ;; general TODO-like setup
3449 (push (cons (intern (downcase (match-string 1 key)))
3450 (org-split-string value splitre)) kwds))
3451 ((equal key "TAGS")
3452 (setq tags (append tags (if tags '("\\n") nil)
3453 (org-split-string value splitre))))
3454 ((equal key "COLUMNS")
3455 (org-set-local 'org-columns-default-format value))
3456 ((equal key "LINK")
3457 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3458 (push (cons (match-string 1 value)
3459 (org-trim (match-string 2 value)))
3460 links)))
3461 ((equal key "PRIORITIES")
3462 (setq prio (org-split-string value " +")))
3463 ((equal key "PROPERTY")
3464 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3465 (push (cons (match-string 1 value) (match-string 2 value))
3466 props)))
3467 ((equal key "FILETAGS")
3468 (when (string-match "\\S-" value)
3469 (setq ftags
3470 (append
3471 ftags
3472 (apply 'append
3473 (mapcar (lambda (x) (org-split-string x ":"))
3474 (org-split-string value)))))))
3475 ((equal key "DRAWERS")
3476 (setq drawers (org-split-string value splitre)))
3477 ((equal key "CONSTANTS")
3478 (setq const (append const (org-split-string value splitre))))
3479 ((equal key "STARTUP")
3480 (let ((opts (org-split-string value splitre))
3481 l var val)
3482 (while (setq l (pop opts))
3483 (when (setq l (assoc l org-startup-options))
3484 (setq var (nth 1 l) val (nth 2 l))
3485 (if (not (nth 3 l))
3486 (set (make-local-variable var) val)
3487 (if (not (listp (symbol-value var)))
3488 (set (make-local-variable var) nil))
3489 (set (make-local-variable var) (symbol-value var))
3490 (add-to-list var val))))))
3491 ((equal key "ARCHIVE")
3492 (string-match " *$" value)
3493 (setq arch (replace-match "" t t value))
3494 (remove-text-properties 0 (length arch)
3495 '(face t fontified t) arch))
3496 ((equal key "SETUPFILE")
3497 (setq setup-contents (org-file-contents
3498 (expand-file-name
3499 (org-remove-double-quotes value))
3500 'noerror))
3501 (if (not ext-setup-or-nil)
3502 (setq ext-setup-or-nil setup-contents start 0)
3503 (setq ext-setup-or-nil
3504 (concat (substring ext-setup-or-nil 0 start)
3505 "\n" setup-contents "\n"
3506 (substring ext-setup-or-nil start)))))
3507 ))))
3508 (when cat
3509 (org-set-local 'org-category (intern cat))
3510 (push (cons "CATEGORY" cat) props))
3511 (when prio
3512 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3513 (setq prio (mapcar 'string-to-char prio))
3514 (org-set-local 'org-highest-priority (nth 0 prio))
3515 (org-set-local 'org-lowest-priority (nth 1 prio))
3516 (org-set-local 'org-default-priority (nth 2 prio)))
3517 (and props (org-set-local 'org-file-properties (nreverse props)))
3518 (and ftags (org-set-local 'org-file-tags
3519 (mapcar 'org-add-prop-inherited ftags)))
3520 (and drawers (org-set-local 'org-drawers drawers))
3521 (and arch (org-set-local 'org-archive-location arch))
3522 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3523 ;; Process the TODO keywords
3524 (unless kwds
3525 ;; Use the global values as if they had been given locally.
3526 (setq kwds (default-value 'org-todo-keywords))
3527 (if (stringp (car kwds))
3528 (setq kwds (list (cons org-todo-interpretation
3529 (default-value 'org-todo-keywords)))))
3530 (setq kwds (reverse kwds)))
3531 (setq kwds (nreverse kwds))
3532 (let (inter kws kw)
3533 (while (setq kws (pop kwds))
3534 (let ((kws (or
3535 (run-hook-with-args-until-success
3536 'org-todo-setup-filter-hook kws)
3537 kws)))
3538 (setq inter (pop kws) sep (member "|" kws)
3539 kws0 (delete "|" (copy-sequence kws))
3540 kwsa nil
3541 kws1 (mapcar
3542 (lambda (x)
3543 ;; 1 2
3544 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3545 (progn
3546 (setq kw (match-string 1 x)
3547 key (and (match-end 2) (match-string 2 x))
3548 log (org-extract-log-state-settings x))
3549 (push (cons kw (and key (string-to-char key))) kwsa)
3550 (and log (push log org-todo-log-states))
3552 (error "Invalid TODO keyword %s" x)))
3553 kws0)
3554 kwsa (if kwsa (append '((:startgroup))
3555 (nreverse kwsa)
3556 '((:endgroup))))
3557 hw (car kws1)
3558 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3559 tail (list inter hw (car dws) (org-last dws))))
3560 (add-to-list 'org-todo-heads hw 'append)
3561 (push kws1 org-todo-sets)
3562 (setq org-done-keywords (append org-done-keywords dws nil))
3563 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3564 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3565 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3566 (setq org-todo-sets (nreverse org-todo-sets)
3567 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3568 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3569 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3570 ;; Process the constants
3571 (when const
3572 (let (e cst)
3573 (while (setq e (pop const))
3574 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3575 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3576 (setq org-table-formula-constants-local cst)))
3578 ;; Process the tags.
3579 (when tags
3580 (let (e tgs)
3581 (while (setq e (pop tags))
3582 (cond
3583 ((equal e "{") (push '(:startgroup) tgs))
3584 ((equal e "}") (push '(:endgroup) tgs))
3585 ((equal e "\\n") (push '(:newline) tgs))
3586 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3587 (push (cons (match-string 1 e)
3588 (string-to-char (match-string 2 e)))
3589 tgs))
3590 (t (push (list e) tgs))))
3591 (org-set-local 'org-tag-alist nil)
3592 (while (setq e (pop tgs))
3593 (or (and (stringp (car e))
3594 (assoc (car e) org-tag-alist))
3595 (push e org-tag-alist)))))
3597 ;; Compute the regular expressions and other local variables
3598 (if (not org-done-keywords)
3599 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3600 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3601 (length org-scheduled-string)
3602 (length org-clock-string)
3603 (length org-closed-string)))
3604 org-drawer-regexp
3605 (concat "^[ \t]*:\\("
3606 (mapconcat 'regexp-quote org-drawers "\\|")
3607 "\\):[ \t]*$")
3608 org-not-done-keywords
3609 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3610 org-todo-regexp
3611 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3612 "\\|") "\\)\\>")
3613 org-not-done-regexp
3614 (concat "\\<\\("
3615 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3616 "\\)\\>")
3617 org-not-done-heading-regexp
3618 (concat "^\\(\\*+\\)[ \t]+\\("
3619 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3620 "\\)\\>")
3621 org-todo-line-regexp
3622 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3623 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3624 "\\)\\>\\)?[ \t]*\\(.*\\)")
3625 org-complex-heading-regexp
3626 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3627 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3628 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3629 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3630 org-nl-done-regexp
3631 (concat "\n\\*+[ \t]+"
3632 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3633 "\\)" "\\>")
3634 org-todo-line-tags-regexp
3635 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3636 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3637 (org-re
3638 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3639 org-looking-at-done-regexp
3640 (concat "^" "\\(?:"
3641 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3642 "\\>")
3643 org-deadline-regexp (concat "\\<" org-deadline-string)
3644 org-deadline-time-regexp
3645 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3646 org-deadline-line-regexp
3647 (concat "\\<\\(" org-deadline-string "\\).*")
3648 org-scheduled-regexp
3649 (concat "\\<" org-scheduled-string)
3650 org-scheduled-time-regexp
3651 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3652 org-closed-time-regexp
3653 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3654 org-keyword-time-regexp
3655 (concat "\\<\\(" org-scheduled-string
3656 "\\|" org-deadline-string
3657 "\\|" org-closed-string
3658 "\\|" org-clock-string "\\)"
3659 " *[[<]\\([^]>]+\\)[]>]")
3660 org-keyword-time-not-clock-regexp
3661 (concat "\\<\\(" org-scheduled-string
3662 "\\|" org-deadline-string
3663 "\\|" org-closed-string
3664 "\\)"
3665 " *[[<]\\([^]>]+\\)[]>]")
3666 org-maybe-keyword-time-regexp
3667 (concat "\\(\\<\\(" org-scheduled-string
3668 "\\|" org-deadline-string
3669 "\\|" org-closed-string
3670 "\\|" org-clock-string "\\)\\)?"
3671 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3672 org-planning-or-clock-line-re
3673 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3674 "\\|" org-deadline-string
3675 "\\|" org-closed-string "\\|" org-clock-string
3676 "\\)\\>\\)")
3678 (org-compute-latex-and-specials-regexp)
3679 (org-set-font-lock-defaults))))
3681 (defun org-file-contents (file &optional noerror)
3682 "Return the contents of FILE, as a string."
3683 (if (or (not file)
3684 (not (file-readable-p file)))
3685 (if noerror
3686 (progn
3687 (message "Cannot read file %s" file)
3688 (ding) (sit-for 2)
3690 (error "Cannot read file %s" file))
3691 (with-temp-buffer
3692 (insert-file-contents file)
3693 (buffer-string))))
3695 (defun org-extract-log-state-settings (x)
3696 "Extract the log state setting from a TODO keyword string.
3697 This will extract info from a string like \"WAIT(w@/!)\"."
3698 (let (kw key log1 log2)
3699 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3700 (setq kw (match-string 1 x)
3701 key (and (match-end 2) (match-string 2 x))
3702 log1 (and (match-end 3) (match-string 3 x))
3703 log2 (and (match-end 4) (match-string 4 x)))
3704 (and (or log1 log2)
3705 (list kw
3706 (and log1 (if (equal log1 "!") 'time 'note))
3707 (and log2 (if (equal log2 "!") 'time 'note)))))))
3709 (defun org-remove-keyword-keys (list)
3710 "Remove a pair of parenthesis at the end of each string in LIST."
3711 (mapcar (lambda (x)
3712 (if (string-match "(.*)$" x)
3713 (substring x 0 (match-beginning 0))
3715 list))
3717 ;; FIXME: this could be done much better, using second characters etc.
3718 (defun org-assign-fast-keys (alist)
3719 "Assign fast keys to a keyword-key alist.
3720 Respect keys that are already there."
3721 (let (new e k c c1 c2 (char ?a))
3722 (while (setq e (pop alist))
3723 (cond
3724 ((equal e '(:startgroup)) (push e new))
3725 ((equal e '(:endgroup)) (push e new))
3726 ((equal e '(:newline)) (push e new))
3728 (setq k (car e) c2 nil)
3729 (if (cdr e)
3730 (setq c (cdr e))
3731 ;; automatically assign a character.
3732 (setq c1 (string-to-char
3733 (downcase (substring
3734 k (if (= (string-to-char k) ?@) 1 0)))))
3735 (if (or (rassoc c1 new) (rassoc c1 alist))
3736 (while (or (rassoc char new) (rassoc char alist))
3737 (setq char (1+ char)))
3738 (setq c2 c1))
3739 (setq c (or c2 char)))
3740 (push (cons k c) new))))
3741 (nreverse new)))
3743 ;;; Some variables used in various places
3745 (defvar org-window-configuration nil
3746 "Used in various places to store a window configuration.")
3747 (defvar org-finish-function nil
3748 "Function to be called when `C-c C-c' is used.
3749 This is for getting out of special buffers like remember.")
3752 ;; FIXME: Occasionally check by commenting these, to make sure
3753 ;; no other functions uses these, forgetting to let-bind them.
3754 (defvar entry)
3755 (defvar state)
3756 (defvar last-state)
3757 (defvar date)
3758 (defvar description)
3760 ;; Defined somewhere in this file, but used before definition.
3761 (defvar org-html-entities)
3762 (defvar org-struct-menu)
3763 (defvar org-org-menu)
3764 (defvar org-tbl-menu)
3765 (defvar org-agenda-keymap)
3767 ;;;; Define the Org-mode
3769 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3770 (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."))
3773 ;; We use a before-change function to check if a table might need
3774 ;; an update.
3775 (defvar org-table-may-need-update t
3776 "Indicates that a table might need an update.
3777 This variable is set by `org-before-change-function'.
3778 `org-table-align' sets it back to nil.")
3779 (defun org-before-change-function (beg end)
3780 "Every change indicates that a table might need an update."
3781 (setq org-table-may-need-update t))
3782 (defvar org-mode-map)
3783 (defvar org-mode-hook nil
3784 "Mode hook for Org-mode, run after the mode was turned on.")
3785 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3786 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3787 (defvar org-table-buffer-is-an nil)
3788 (defconst org-outline-regexp "\\*+ ")
3790 ;;;###autoload
3791 (define-derived-mode org-mode outline-mode "Org"
3792 "Outline-based notes management and organizer, alias
3793 \"Carsten's outline-mode for keeping track of everything.\"
3795 Org-mode develops organizational tasks around a NOTES file which
3796 contains information about projects as plain text. Org-mode is
3797 implemented on top of outline-mode, which is ideal to keep the content
3798 of large files well structured. It supports ToDo items, deadlines and
3799 time stamps, which magically appear in the diary listing of the Emacs
3800 calendar. Tables are easily created with a built-in table editor.
3801 Plain text URL-like links connect to websites, emails (VM), Usenet
3802 messages (Gnus), BBDB entries, and any files related to the project.
3803 For printing and sharing of notes, an Org-mode file (or a part of it)
3804 can be exported as a structured ASCII or HTML file.
3806 The following commands are available:
3808 \\{org-mode-map}"
3810 ;; Get rid of Outline menus, they are not needed
3811 ;; Need to do this here because define-derived-mode sets up
3812 ;; the keymap so late. Still, it is a waste to call this each time
3813 ;; we switch another buffer into org-mode.
3814 (if (featurep 'xemacs)
3815 (when (boundp 'outline-mode-menu-heading)
3816 ;; Assume this is Greg's port, it used easymenu
3817 (easy-menu-remove outline-mode-menu-heading)
3818 (easy-menu-remove outline-mode-menu-show)
3819 (easy-menu-remove outline-mode-menu-hide))
3820 (define-key org-mode-map [menu-bar headings] 'undefined)
3821 (define-key org-mode-map [menu-bar hide] 'undefined)
3822 (define-key org-mode-map [menu-bar show] 'undefined))
3824 (org-load-modules-maybe)
3825 (easy-menu-add org-org-menu)
3826 (easy-menu-add org-tbl-menu)
3827 (org-install-agenda-files-menu)
3828 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3829 (org-add-to-invisibility-spec '(org-cwidth))
3830 (when (featurep 'xemacs)
3831 (org-set-local 'line-move-ignore-invisible t))
3832 (org-set-local 'outline-regexp org-outline-regexp)
3833 (org-set-local 'outline-level 'org-outline-level)
3834 (when (and org-ellipsis
3835 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3836 (fboundp 'make-glyph-code))
3837 (unless org-display-table
3838 (setq org-display-table (make-display-table)))
3839 (set-display-table-slot
3840 org-display-table 4
3841 (vconcat (mapcar
3842 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3843 org-ellipsis)))
3844 (if (stringp org-ellipsis) org-ellipsis "..."))))
3845 (setq buffer-display-table org-display-table))
3846 (org-set-regexps-and-options)
3847 (when (and org-tag-faces (not org-tags-special-faces-re))
3848 ;; tag faces set outside customize.... force initialization.
3849 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3850 ;; Calc embedded
3851 (org-set-local 'calc-embedded-open-mode "# ")
3852 (modify-syntax-entry ?# "<")
3853 (modify-syntax-entry ?@ "w")
3854 (if org-startup-truncated (setq truncate-lines t))
3855 (org-set-local 'font-lock-unfontify-region-function
3856 'org-unfontify-region)
3857 ;; Activate before-change-function
3858 (org-set-local 'org-table-may-need-update t)
3859 (org-add-hook 'before-change-functions 'org-before-change-function nil
3860 'local)
3861 ;; Check for running clock before killing a buffer
3862 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3863 ;; Paragraphs and auto-filling
3864 (org-set-autofill-regexps)
3865 (setq indent-line-function 'org-indent-line-function)
3866 (org-update-radio-target-regexp)
3867 ;; Make sure dependence stuff works reliably, even for users who set it
3868 ;; too late :-(
3869 (if org-enforce-todo-dependencies
3870 (add-hook 'org-blocker-hook
3871 'org-block-todo-from-children-or-siblings-or-parent)
3872 (remove-hook 'org-blocker-hook
3873 'org-block-todo-from-children-or-siblings-or-parent))
3874 (if org-enforce-todo-checkbox-dependencies
3875 (add-hook 'org-blocker-hook
3876 'org-block-todo-from-checkboxes)
3877 (remove-hook 'org-blocker-hook
3878 'org-block-todo-from-checkboxes))
3880 ;; Comment characters
3881 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3882 (org-set-local 'comment-padding " ")
3884 ;; Align options lines
3885 (org-set-local
3886 'align-mode-rules-list
3887 '((org-in-buffer-settings
3888 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3889 (modes . '(org-mode)))))
3891 ;; Imenu
3892 (org-set-local 'imenu-create-index-function
3893 'org-imenu-get-tree)
3895 ;; Make isearch reveal context
3896 (if (or (featurep 'xemacs)
3897 (not (boundp 'outline-isearch-open-invisible-function)))
3898 ;; Emacs 21 and XEmacs make use of the hook
3899 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3900 ;; Emacs 22 deals with this through a special variable
3901 (org-set-local 'outline-isearch-open-invisible-function
3902 (lambda (&rest ignore) (org-show-context 'isearch))))
3904 ;; If empty file that did not turn on org-mode automatically, make it to.
3905 (if (and org-insert-mode-line-in-empty-file
3906 (interactive-p)
3907 (= (point-min) (point-max)))
3908 (insert "# -*- mode: org -*-\n\n"))
3910 (unless org-inhibit-startup
3911 (when org-startup-align-all-tables
3912 (let ((bmp (buffer-modified-p)))
3913 (org-table-map-tables 'org-table-align)
3914 (set-buffer-modified-p bmp)))
3915 (org-set-startup-visibility)))
3917 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3919 (defun org-current-time ()
3920 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3921 (if (> (car org-time-stamp-rounding-minutes) 1)
3922 (let ((r (car org-time-stamp-rounding-minutes))
3923 (time (decode-time)))
3924 (apply 'encode-time
3925 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3926 (nthcdr 2 time))))
3927 (current-time)))
3929 ;;;; Font-Lock stuff, including the activators
3931 (defvar org-mouse-map (make-sparse-keymap))
3932 (org-defkey org-mouse-map
3933 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3934 (org-defkey org-mouse-map
3935 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3936 (when org-mouse-1-follows-link
3937 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3938 (when org-tab-follows-link
3939 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3940 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3942 (require 'font-lock)
3944 (defconst org-non-link-chars "]\t\n\r<>")
3945 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3946 "shell" "elisp"))
3947 (defvar org-link-types-re nil
3948 "Matches a link that has a url-like prefix like \"http:\"")
3949 (defvar org-link-re-with-space nil
3950 "Matches a link with spaces, optional angular brackets around it.")
3951 (defvar org-link-re-with-space2 nil
3952 "Matches a link with spaces, optional angular brackets around it.")
3953 (defvar org-link-re-with-space3 nil
3954 "Matches a link with spaces, only for internal part in bracket links.")
3955 (defvar org-angle-link-re nil
3956 "Matches link with angular brackets, spaces are allowed.")
3957 (defvar org-plain-link-re nil
3958 "Matches plain link, without spaces.")
3959 (defvar org-bracket-link-regexp nil
3960 "Matches a link in double brackets.")
3961 (defvar org-bracket-link-analytic-regexp nil
3962 "Regular expression used to analyze links.
3963 Here is what the match groups contain after a match:
3964 1: http:
3965 2: http
3966 3: path
3967 4: [desc]
3968 5: desc")
3969 (defvar org-bracket-link-analytic-regexp++ nil
3970 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3971 (defvar org-any-link-re nil
3972 "Regular expression matching any link.")
3974 (defun org-make-link-regexps ()
3975 "Update the link regular expressions.
3976 This should be called after the variable `org-link-types' has changed."
3977 (setq org-link-types-re
3978 (concat
3979 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3980 org-link-re-with-space
3981 (concat
3982 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3983 "\\([^" org-non-link-chars " ]"
3984 "[^" org-non-link-chars "]*"
3985 "[^" org-non-link-chars " ]\\)>?")
3986 org-link-re-with-space2
3987 (concat
3988 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3989 "\\([^" org-non-link-chars " ]"
3990 "[^\t\n\r]*"
3991 "[^" org-non-link-chars " ]\\)>?")
3992 org-link-re-with-space3
3993 (concat
3994 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3995 "\\([^" org-non-link-chars " ]"
3996 "[^\t\n\r]*\\)")
3997 org-angle-link-re
3998 (concat
3999 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4000 "\\([^" org-non-link-chars " ]"
4001 "[^" org-non-link-chars "]*"
4002 "\\)>")
4003 org-plain-link-re
4004 (concat
4005 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4006 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4007 org-bracket-link-regexp
4008 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4009 org-bracket-link-analytic-regexp
4010 (concat
4011 "\\[\\["
4012 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4013 "\\([^]]+\\)"
4014 "\\]"
4015 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4016 "\\]")
4017 org-bracket-link-analytic-regexp++
4018 (concat
4019 "\\[\\["
4020 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4021 "\\([^]]+\\)"
4022 "\\]"
4023 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4024 "\\]")
4025 org-any-link-re
4026 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4027 org-angle-link-re "\\)\\|\\("
4028 org-plain-link-re "\\)")))
4030 (org-make-link-regexps)
4032 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4033 "Regular expression for fast time stamp matching.")
4034 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4035 "Regular expression for fast time stamp matching.")
4036 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4037 "Regular expression matching time strings for analysis.
4038 This one does not require the space after the date, so it can be used
4039 on a string that terminates immediately after the date.")
4040 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4041 "Regular expression matching time strings for analysis.")
4042 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4043 "Regular expression matching time stamps, with groups.")
4044 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4045 "Regular expression matching time stamps (also [..]), with groups.")
4046 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4047 "Regular expression matching a time stamp range.")
4048 (defconst org-tr-regexp-both
4049 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4050 "Regular expression matching a time stamp range.")
4051 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4052 org-ts-regexp "\\)?")
4053 "Regular expression matching a time stamp or time stamp range.")
4054 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4055 org-ts-regexp-both "\\)?")
4056 "Regular expression matching a time stamp or time stamp range.
4057 The time stamps may be either active or inactive.")
4059 (defvar org-emph-face nil)
4061 (defun org-do-emphasis-faces (limit)
4062 "Run through the buffer and add overlays to links."
4063 (let (rtn)
4064 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4065 (if (not (= (char-after (match-beginning 3))
4066 (char-after (match-beginning 4))))
4067 (progn
4068 (setq rtn t)
4069 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4070 'face
4071 (nth 1 (assoc (match-string 3)
4072 org-emphasis-alist)))
4073 (add-text-properties (match-beginning 2) (match-end 2)
4074 '(font-lock-multiline t))
4075 (when org-hide-emphasis-markers
4076 (add-text-properties (match-end 4) (match-beginning 5)
4077 '(invisible org-link))
4078 (add-text-properties (match-beginning 3) (match-end 3)
4079 '(invisible org-link)))))
4080 (backward-char 1))
4081 rtn))
4083 (defun org-emphasize (&optional char)
4084 "Insert or change an emphasis, i.e. a font like bold or italic.
4085 If there is an active region, change that region to a new emphasis.
4086 If there is no region, just insert the marker characters and position
4087 the cursor between them.
4088 CHAR should be either the marker character, or the first character of the
4089 HTML tag associated with that emphasis. If CHAR is a space, the means
4090 to remove the emphasis of the selected region.
4091 If char is not given (for example in an interactive call) it
4092 will be prompted for."
4093 (interactive)
4094 (let ((eal org-emphasis-alist) e det
4095 (erc org-emphasis-regexp-components)
4096 (prompt "")
4097 (string "") beg end move tag c s)
4098 (if (org-region-active-p)
4099 (setq beg (region-beginning) end (region-end)
4100 string (buffer-substring beg end))
4101 (setq move t))
4103 (while (setq e (pop eal))
4104 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4105 c (aref tag 0))
4106 (push (cons c (string-to-char (car e))) det)
4107 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4108 (substring tag 1)))))
4109 (setq det (nreverse det))
4110 (unless char
4111 (message "%s" (concat "Emphasis marker or tag:" prompt))
4112 (setq char (read-char-exclusive)))
4113 (setq char (or (cdr (assoc char det)) char))
4114 (if (equal char ?\ )
4115 (setq s "" move nil)
4116 (unless (assoc (char-to-string char) org-emphasis-alist)
4117 (error "No such emphasis marker: \"%c\"" char))
4118 (setq s (char-to-string char)))
4119 (while (and (> (length string) 1)
4120 (equal (substring string 0 1) (substring string -1))
4121 (assoc (substring string 0 1) org-emphasis-alist))
4122 (setq string (substring string 1 -1)))
4123 (setq string (concat s string s))
4124 (if beg (delete-region beg end))
4125 (unless (or (bolp)
4126 (string-match (concat "[" (nth 0 erc) "\n]")
4127 (char-to-string (char-before (point)))))
4128 (insert " "))
4129 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4130 (char-to-string (char-after (point))))
4131 (insert " ") (backward-char 1))
4132 (insert string)
4133 (and move (backward-char 1))))
4135 (defconst org-nonsticky-props
4136 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4138 (defsubst org-rear-nonsticky-at (pos)
4139 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4141 (defun org-activate-plain-links (limit)
4142 "Run through the buffer and add overlays to links."
4143 (catch 'exit
4144 (let (f)
4145 (while (re-search-forward org-plain-link-re limit t)
4146 (setq f (get-text-property (match-beginning 0) 'face))
4147 (if (or (eq f 'org-tag)
4148 (and (listp f) (memq 'org-tag f)))
4150 (add-text-properties (match-beginning 0) (match-end 0)
4151 (list 'mouse-face 'highlight
4152 'keymap org-mouse-map))
4153 (org-rear-nonsticky-at (match-end 0))
4154 (throw 'exit t))))))
4156 (defun org-activate-code (limit)
4157 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4158 (progn
4159 (remove-text-properties (match-beginning 0) (match-end 0)
4160 '(display t invisible t intangible t))
4161 t)))
4163 (defun org-activate-angle-links (limit)
4164 "Run through the buffer and add overlays to links."
4165 (if (re-search-forward org-angle-link-re limit t)
4166 (progn
4167 (add-text-properties (match-beginning 0) (match-end 0)
4168 (list 'mouse-face 'highlight
4169 'keymap org-mouse-map))
4170 (org-rear-nonsticky-at (match-end 0))
4171 t)))
4173 (defun org-activate-footnote-links (limit)
4174 "Run through the buffer and add overlays to links."
4175 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4176 limit t)
4177 (progn
4178 (add-text-properties (match-beginning 2) (match-end 2)
4179 (list 'mouse-face 'highlight
4180 'keymap org-mouse-map
4181 'help-echo
4182 (if (= (point-at-bol) (match-beginning 2))
4183 "Footnote definition"
4184 "Footnote reference")
4186 (org-rear-nonsticky-at (match-end 2))
4187 t)))
4189 (defun org-activate-bracket-links (limit)
4190 "Run through the buffer and add overlays to bracketed links."
4191 (if (re-search-forward org-bracket-link-regexp limit t)
4192 (let* ((help (concat "LINK: "
4193 (org-match-string-no-properties 1)))
4194 ;; FIXME: above we should remove the escapes.
4195 ;; but that requires another match, protecting match data,
4196 ;; a lot of overhead for font-lock.
4197 (ip (org-maybe-intangible
4198 (list 'invisible 'org-link
4199 'keymap org-mouse-map 'mouse-face 'highlight
4200 'font-lock-multiline t 'help-echo help)))
4201 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4202 'font-lock-multiline t 'help-echo help)))
4203 ;; We need to remove the invisible property here. Table narrowing
4204 ;; may have made some of this invisible.
4205 (remove-text-properties (match-beginning 0) (match-end 0)
4206 '(invisible nil))
4207 (if (match-end 3)
4208 (progn
4209 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4210 (org-rear-nonsticky-at (match-beginning 3))
4211 (add-text-properties (match-beginning 3) (match-end 3) vp)
4212 (org-rear-nonsticky-at (match-end 3))
4213 (add-text-properties (match-end 3) (match-end 0) ip)
4214 (org-rear-nonsticky-at (match-end 0)))
4215 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4216 (org-rear-nonsticky-at (match-beginning 1))
4217 (add-text-properties (match-beginning 1) (match-end 1) vp)
4218 (org-rear-nonsticky-at (match-end 1))
4219 (add-text-properties (match-end 1) (match-end 0) ip)
4220 (org-rear-nonsticky-at (match-end 0)))
4221 t)))
4223 (defun org-activate-dates (limit)
4224 "Run through the buffer and add overlays to dates."
4225 (if (re-search-forward org-tsr-regexp-both limit t)
4226 (progn
4227 (add-text-properties (match-beginning 0) (match-end 0)
4228 (list 'mouse-face 'highlight
4229 'keymap org-mouse-map))
4230 (org-rear-nonsticky-at (match-end 0))
4231 (when org-display-custom-times
4232 (if (match-end 3)
4233 (org-display-custom-time (match-beginning 3) (match-end 3)))
4234 (org-display-custom-time (match-beginning 1) (match-end 1)))
4235 t)))
4237 (defvar org-target-link-regexp nil
4238 "Regular expression matching radio targets in plain text.")
4239 (make-variable-buffer-local 'org-target-link-regexp)
4240 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4241 "Regular expression matching a link target.")
4242 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4243 "Regular expression matching a radio target.")
4244 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4245 "Regular expression matching any target.")
4247 (defun org-activate-target-links (limit)
4248 "Run through the buffer and add overlays to target matches."
4249 (when org-target-link-regexp
4250 (let ((case-fold-search t))
4251 (if (re-search-forward org-target-link-regexp limit t)
4252 (progn
4253 (add-text-properties (match-beginning 0) (match-end 0)
4254 (list 'mouse-face 'highlight
4255 'keymap org-mouse-map
4256 'help-echo "Radio target link"
4257 'org-linked-text t))
4258 (org-rear-nonsticky-at (match-end 0))
4259 t)))))
4261 (defun org-update-radio-target-regexp ()
4262 "Find all radio targets in this file and update the regular expression."
4263 (interactive)
4264 (when (memq 'radio org-activate-links)
4265 (setq org-target-link-regexp
4266 (org-make-target-link-regexp (org-all-targets 'radio)))
4267 (org-restart-font-lock)))
4269 (defun org-hide-wide-columns (limit)
4270 (let (s e)
4271 (setq s (text-property-any (point) (or limit (point-max))
4272 'org-cwidth t))
4273 (when s
4274 (setq e (next-single-property-change s 'org-cwidth))
4275 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4276 (goto-char e)
4277 t)))
4279 (defvar org-latex-and-specials-regexp nil
4280 "Regular expression for highlighting export special stuff.")
4281 (defvar org-match-substring-regexp)
4282 (defvar org-match-substring-with-braces-regexp)
4283 (defvar org-export-html-special-string-regexps)
4285 (defun org-compute-latex-and-specials-regexp ()
4286 "Compute regular expression for stuff treated specially by exporters."
4287 (if (not org-highlight-latex-fragments-and-specials)
4288 (org-set-local 'org-latex-and-specials-regexp nil)
4289 (require 'org-exp)
4290 (let*
4291 ((matchers (plist-get org-format-latex-options :matchers))
4292 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4293 org-latex-regexps)))
4294 (options (org-combine-plists (org-default-export-plist)
4295 (org-infile-export-plist)))
4296 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4297 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4298 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4299 (org-export-html-expand (plist-get options :expand-quoted-html))
4300 (org-export-with-special-strings (plist-get options :special-strings))
4301 (re-sub
4302 (cond
4303 ((equal org-export-with-sub-superscripts '{})
4304 (list org-match-substring-with-braces-regexp))
4305 (org-export-with-sub-superscripts
4306 (list org-match-substring-regexp))
4307 (t nil)))
4308 (re-latex
4309 (if org-export-with-LaTeX-fragments
4310 (mapcar (lambda (x) (nth 1 x)) latexs)))
4311 (re-macros
4312 (if org-export-with-TeX-macros
4313 (list (concat "\\\\"
4314 (regexp-opt
4315 (append (mapcar 'car org-html-entities)
4316 (if (boundp 'org-latex-entities)
4317 org-latex-entities nil))
4318 'words))) ; FIXME
4320 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4321 (re-special (if org-export-with-special-strings
4322 (mapcar (lambda (x) (car x))
4323 org-export-html-special-string-regexps)))
4324 (re-rest
4325 (delq nil
4326 (list
4327 (if org-export-html-expand "@<[^>\n]+>")
4328 ))))
4329 (org-set-local
4330 'org-latex-and-specials-regexp
4331 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4332 re-rest) "\\|")))))
4334 (defun org-do-latex-and-special-faces (limit)
4335 "Run through the buffer and add overlays to links."
4336 (when org-latex-and-specials-regexp
4337 (let (rtn d)
4338 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4339 limit t))
4340 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4341 'face))
4342 '(org-code org-verbatim underline)))
4343 (progn
4344 (setq rtn t
4345 d (cond ((member (char-after (1+ (match-beginning 0)))
4346 '(?_ ?^)) 1)
4347 (t 0)))
4348 (font-lock-prepend-text-property
4349 (+ d (match-beginning 0)) (match-end 0)
4350 'face 'org-latex-and-export-specials)
4351 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4352 '(font-lock-multiline t)))))
4353 rtn)))
4355 (defun org-restart-font-lock ()
4356 "Restart font-lock-mode, to force refontification."
4357 (when (and (boundp 'font-lock-mode) font-lock-mode)
4358 (font-lock-mode -1)
4359 (font-lock-mode 1)))
4361 (defun org-all-targets (&optional radio)
4362 "Return a list of all targets in this file.
4363 With optional argument RADIO, only find radio targets."
4364 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4365 rtn)
4366 (save-excursion
4367 (goto-char (point-min))
4368 (while (re-search-forward re nil t)
4369 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4370 rtn)))
4372 (defun org-make-target-link-regexp (targets)
4373 "Make regular expression matching all strings in TARGETS.
4374 The regular expression finds the targets also if there is a line break
4375 between words."
4376 (and targets
4377 (concat
4378 "\\<\\("
4379 (mapconcat
4380 (lambda (x)
4381 (while (string-match " +" x)
4382 (setq x (replace-match "\\s-+" t t x)))
4384 targets
4385 "\\|")
4386 "\\)\\>")))
4388 (defun org-activate-tags (limit)
4389 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4390 (progn
4391 (add-text-properties (match-beginning 1) (match-end 1)
4392 (list 'mouse-face 'highlight
4393 'keymap org-mouse-map))
4394 (org-rear-nonsticky-at (match-end 1))
4395 t)))
4397 (defun org-outline-level ()
4398 (save-excursion
4399 (looking-at outline-regexp)
4400 (if (match-beginning 1)
4401 (+ (org-get-string-indentation (match-string 1)) 1000)
4402 (1- (- (match-end 0) (match-beginning 0))))))
4404 (defvar org-font-lock-keywords nil)
4406 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4407 "Regular expression matching a property line.")
4409 (defvar org-font-lock-hook nil
4410 "Functions to be called for special font lock stuff.")
4412 (defun org-font-lock-hook (limit)
4413 (run-hook-with-args 'org-font-lock-hook limit))
4415 (defun org-set-font-lock-defaults ()
4416 (let* ((em org-fontify-emphasized-text)
4417 (lk org-activate-links)
4418 (org-font-lock-extra-keywords
4419 (list
4420 ;; Call the hook
4421 '(org-font-lock-hook)
4422 ;; Headlines
4423 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4424 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4425 ;; Table lines
4426 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4427 (1 'org-table t))
4428 ;; Table internals
4429 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4430 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4431 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4432 ;; Drawers
4433 (list org-drawer-regexp '(0 'org-special-keyword t))
4434 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4435 ;; Properties
4436 (list org-property-re
4437 '(1 'org-special-keyword t)
4438 '(3 'org-property-value t))
4439 (if org-format-transports-properties-p
4440 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4441 ;; Links
4442 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4443 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4444 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4445 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4446 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4447 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4448 (if (memq 'footnote lk) '(org-activate-footnote-links
4449 (2 'org-footnote t)))
4450 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4451 '(org-hide-wide-columns (0 nil append))
4452 ;; TODO lines
4453 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4454 '(1 (org-get-todo-face 1) t))
4455 ;; DONE
4456 (if org-fontify-done-headline
4457 (list (concat "^[*]+ +\\<\\("
4458 (mapconcat 'regexp-quote org-done-keywords "\\|")
4459 "\\)\\(.*\\)")
4460 '(2 'org-headline-done t))
4461 nil)
4462 ;; Priorities
4463 '(org-font-lock-add-priority-faces)
4464 ;; Tags
4465 '(org-font-lock-add-tag-faces)
4466 ;; Special keywords
4467 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4468 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4469 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4470 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4471 ;; Emphasis
4472 (if em
4473 (if (featurep 'xemacs)
4474 '(org-do-emphasis-faces (0 nil append))
4475 '(org-do-emphasis-faces)))
4476 ;; Checkboxes
4477 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4478 2 'org-checkbox prepend)
4479 (if org-provide-checkbox-statistics
4480 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4481 (0 (org-get-checkbox-statistics-face) t)))
4482 ;; Description list items
4483 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4484 2 'bold prepend)
4485 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4486 '(1 'org-archived prepend))
4487 ;; Specials
4488 '(org-do-latex-and-special-faces)
4489 ;; Code
4490 '(org-activate-code (1 'org-code t))
4491 ;; COMMENT
4492 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4493 "\\|" org-quote-string "\\)\\>")
4494 '(1 'org-special-keyword t))
4495 '("^#.*" (0 'font-lock-comment-face t))
4497 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4498 ;; Now set the full font-lock-keywords
4499 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4500 (org-set-local 'font-lock-defaults
4501 '(org-font-lock-keywords t nil nil backward-paragraph))
4502 (kill-local-variable 'font-lock-keywords) nil))
4504 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
4505 "Fontify string S like in Org-mode"
4506 (with-temp-buffer
4507 (insert s)
4508 (let ((org-odd-levels-only odd-levels))
4509 (org-mode)
4510 (font-lock-fontify-buffer)
4511 (buffer-string))))
4513 (defvar org-m nil)
4514 (defvar org-l nil)
4515 (defvar org-f nil)
4516 (defun org-get-level-face (n)
4517 "Get the right face for match N in font-lock matching of headlines."
4518 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4519 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4520 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4521 (cond
4522 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4523 ((eq n 2) org-f)
4524 (t (if org-level-color-stars-only nil org-f))))
4526 (defun org-get-todo-face (kwd)
4527 "Get the right face for a TODO keyword KWD.
4528 If KWD is a number, get the corresponding match group."
4529 (if (numberp kwd) (setq kwd (match-string kwd)))
4530 (or (cdr (assoc kwd org-todo-keyword-faces))
4531 (and (member kwd org-done-keywords) 'org-done)
4532 'org-todo))
4534 (defun org-font-lock-add-tag-faces (limit)
4535 "Add the special tag faces."
4536 (when (and org-tag-faces org-tags-special-faces-re)
4537 (while (re-search-forward org-tags-special-faces-re limit t)
4538 (add-text-properties (match-beginning 1) (match-end 1)
4539 (list 'face (org-get-tag-face 1)
4540 'font-lock-fontified t))
4541 (backward-char 1))))
4543 (defun org-font-lock-add-priority-faces (limit)
4544 "Add the special priority faces."
4545 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4546 (add-text-properties
4547 (match-beginning 0) (match-end 0)
4548 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4549 org-priority-faces))
4550 'org-special-keyword)
4551 'font-lock-fontified t))))
4553 (defun org-get-tag-face (kwd)
4554 "Get the right face for a TODO keyword KWD.
4555 If KWD is a number, get the corresponding match group."
4556 (if (numberp kwd) (setq kwd (match-string kwd)))
4557 (or (cdr (assoc kwd org-tag-faces))
4558 'org-tag))
4560 (defun org-unfontify-region (beg end &optional maybe_loudly)
4561 "Remove fontification and activation overlays from links."
4562 (font-lock-default-unfontify-region beg end)
4563 (let* ((buffer-undo-list t)
4564 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4565 (inhibit-modification-hooks t)
4566 deactivate-mark buffer-file-name buffer-file-truename)
4567 (remove-text-properties beg end
4568 '(mouse-face t keymap t org-linked-text t
4569 invisible t intangible t))))
4571 ;;;; Visibility cycling, including org-goto and indirect buffer
4573 ;;; Cycling
4575 (defvar org-cycle-global-status nil)
4576 (make-variable-buffer-local 'org-cycle-global-status)
4577 (defvar org-cycle-subtree-status nil)
4578 (make-variable-buffer-local 'org-cycle-subtree-status)
4580 ;;;###autoload
4582 (defvar org-inlinetask-min-level)
4584 (defun org-cycle (&optional arg)
4585 "TAB-action and visibility cycling for Org-mode.
4587 This is the command invoked in Org-moe by the TAB key. It's main purpose
4588 is outine visibility cycling, but it also invokes other actions
4589 in special contexts.
4591 - When this function is called with a prefix argument, rotate the entire
4592 buffer through 3 states (global cycling)
4593 1. OVERVIEW: Show only top-level headlines.
4594 2. CONTENTS: Show all headlines of all levels, but no body text.
4595 3. SHOW ALL: Show everything.
4596 When called with two `C-u C-u' prefixes, switch to the startup visibility,
4597 determined by the variable `org-startup-folded', and by any VISIBILITY
4598 properties in the buffer.
4599 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
4600 including any drawers.
4602 - When inside a table, re-align the table and move to the next field.
4604 - When point is at the beginning of a headline, rotate the subtree started
4605 by this line through 3 different states (local cycling)
4606 1. FOLDED: Only the main headline is shown.
4607 2. CHILDREN: The main headline and the direct children are shown.
4608 From this state, you can move to one of the children
4609 and zoom in further.
4610 3. SUBTREE: Show the entire subtree, including body text.
4612 - When there is a numeric prefix, go up to a heading with level ARG, do
4613 a `show-subtree' and return to the previous cursor position. If ARG
4614 is negative, go up that many levels.
4616 - When point is not at the beginning of a headline, execute the global
4617 binding for TAB, which is re-indenting the line. See the option
4618 `org-cycle-emulate-tab' for details.
4620 - Special case: if point is at the beginning of the buffer and there is
4621 no headline in line 1, this function will act as if called with prefix arg.
4622 But only if also the variable `org-cycle-global-at-bob' is t."
4623 (interactive "P")
4624 (org-load-modules-maybe)
4625 (unless (run-hook-with-args-until-success 'org-tab-first-hook)
4626 (let* ((limit-level
4627 (or org-cycle-max-level
4628 (and (boundp 'org-inlinetask-min-level)
4629 org-inlinetask-min-level
4630 (1- org-inlinetask-min-level))))
4631 (nstars (and limit-level
4632 (if org-odd-levels-only
4633 (and limit-level (1- (* limit-level 2)))
4634 limit-level)))
4635 (outline-regexp
4636 (cond
4637 ((not (org-mode-p)) outline-regexp)
4638 (org-cycle-include-plain-lists
4639 (concat "\\(?:\\*"
4640 (if nstars (format "\\{1,%d\\}" nstars) "+")
4641 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
4642 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
4643 (bob-special (and org-cycle-global-at-bob (bobp)
4644 (not (looking-at outline-regexp))))
4645 (org-cycle-hook
4646 (if bob-special
4647 (delq 'org-optimize-window-after-visibility-change
4648 (copy-sequence org-cycle-hook))
4649 org-cycle-hook))
4650 (pos (point)))
4652 (if (or bob-special (equal arg '(4)))
4653 ;; special case: use global cycling
4654 (setq arg t))
4656 (cond
4658 ((equal arg '(16))
4659 (org-set-startup-visibility)
4660 (message "Startup visibility, plus VISIBILITY properties"))
4662 ((equal arg '(64))
4663 (show-all)
4664 (message "Entire buffer visible, including drawers"))
4666 ((org-at-table-p 'any)
4667 ;; Enter the table or move to the next field in the table
4668 (or (org-table-recognize-table.el)
4669 (progn
4670 (if arg (org-table-edit-field t)
4671 (org-table-justify-field-maybe)
4672 (call-interactively 'org-table-next-field)))))
4674 ((run-hook-with-args-until-success
4675 'org-tab-after-check-for-table-hook))
4677 ((eq arg t) ;; Global cycling
4678 (org-cycle-internal-global))
4680 ((and org-drawers org-drawer-regexp
4681 (save-excursion
4682 (beginning-of-line 1)
4683 (looking-at org-drawer-regexp)))
4684 ;; Toggle block visibility
4685 (org-flag-drawer
4686 (not (get-char-property (match-end 0) 'invisible))))
4688 ((integerp arg)
4689 ;; Show-subtree, ARG levels up from here.
4690 (save-excursion
4691 (org-back-to-heading)
4692 (outline-up-heading (if (< arg 0) (- arg)
4693 (- (funcall outline-level) arg)))
4694 (org-show-subtree)))
4696 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4697 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4699 (org-cycle-internal-local))
4701 ;; TAB emulation and template completion
4702 (buffer-read-only (org-back-to-heading))
4704 ((run-hook-with-args-until-success
4705 'org-tab-after-check-for-cycling-hook))
4707 ((org-try-structure-completion))
4709 ((org-try-cdlatex-tab))
4711 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4712 (or (not (bolp))
4713 (not (looking-at outline-regexp))))
4714 (call-interactively (global-key-binding "\t")))
4716 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4717 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4718 (or (and (eq org-cycle-emulate-tab 'white)
4719 (= (match-end 0) (point-at-eol)))
4720 (and (eq org-cycle-emulate-tab 'whitestart)
4721 (>= (match-end 0) pos))))
4723 (eq org-cycle-emulate-tab t))
4724 (call-interactively (global-key-binding "\t")))
4726 (t (save-excursion
4727 (org-back-to-heading)
4728 (org-cycle)))))))
4730 (defun org-cycle-internal-global ()
4731 "Do the global cycling action."
4732 (cond
4733 ((and (eq last-command this-command)
4734 (eq org-cycle-global-status 'overview))
4735 ;; We just created the overview - now do table of contents
4736 ;; This can be slow in very large buffers, so indicate action
4737 (run-hook-with-args 'org-pre-cycle-hook 'contents)
4738 (message "CONTENTS...")
4739 (org-content)
4740 (message "CONTENTS...done")
4741 (setq org-cycle-global-status 'contents)
4742 (run-hook-with-args 'org-cycle-hook 'contents))
4744 ((and (eq last-command this-command)
4745 (eq org-cycle-global-status 'contents))
4746 ;; We just showed the table of contents - now show everything
4747 (run-hook-with-args 'org-pre-cycle-hook 'all)
4748 (show-all)
4749 (message "SHOW ALL")
4750 (setq org-cycle-global-status 'all)
4751 (run-hook-with-args 'org-cycle-hook 'all))
4754 ;; Default action: go to overview
4755 (run-hook-with-args 'org-pre-cycle-hook 'overview)
4756 (org-overview)
4757 (message "OVERVIEW")
4758 (setq org-cycle-global-status 'overview)
4759 (run-hook-with-args 'org-cycle-hook 'overview))))
4761 (defun org-cycle-internal-local ()
4762 "Do the local cycling action."
4763 (org-back-to-heading)
4764 (let ((goal-column 0) eoh eol eos)
4765 ;; First, some boundaries
4766 (save-excursion
4767 (org-back-to-heading)
4768 (save-excursion
4769 (beginning-of-line 2)
4770 (while (and (not (eobp)) ;; this is like `next-line'
4771 (get-char-property (1- (point)) 'invisible))
4772 (beginning-of-line 2)) (setq eol (point)))
4773 (outline-end-of-heading) (setq eoh (point))
4774 (org-end-of-subtree t)
4775 (unless (eobp)
4776 (skip-chars-forward " \t\n")
4777 (beginning-of-line 1) ; in case this is an item
4779 (setq eos (1- (point))))
4780 ;; Find out what to do next and set `this-command'
4781 (cond
4782 ((= eos eoh)
4783 ;; Nothing is hidden behind this heading
4784 (run-hook-with-args 'org-pre-cycle-hook 'empty)
4785 (message "EMPTY ENTRY")
4786 (setq org-cycle-subtree-status nil)
4787 (save-excursion
4788 (goto-char eos)
4789 (outline-next-heading)
4790 (if (org-invisible-p) (org-flag-heading nil))))
4791 ((or (>= eol eos)
4792 (not (string-match "\\S-" (buffer-substring eol eos))))
4793 ;; Entire subtree is hidden in one line: open it
4794 (run-hook-with-args 'org-pre-cycle-hook 'children)
4795 (org-show-entry)
4796 (show-children)
4797 (message "CHILDREN")
4798 (save-excursion
4799 (goto-char eos)
4800 (outline-next-heading)
4801 (if (org-invisible-p) (org-flag-heading nil)))
4802 (setq org-cycle-subtree-status 'children)
4803 (run-hook-with-args 'org-cycle-hook 'children))
4804 ((and (eq last-command this-command)
4805 (eq org-cycle-subtree-status 'children))
4806 ;; We just showed the children, now show everything.
4807 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
4808 (org-show-subtree)
4809 (message "SUBTREE")
4810 (setq org-cycle-subtree-status 'subtree)
4811 (run-hook-with-args 'org-cycle-hook 'subtree))
4813 ;; Default action: hide the subtree.
4814 (run-hook-with-args 'org-pre-cycle-hook 'folded)
4815 (hide-subtree)
4816 (message "FOLDED")
4817 (setq org-cycle-subtree-status 'folded)
4818 (run-hook-with-args 'org-cycle-hook 'folded)))))
4820 ;;;###autoload
4821 (defun org-global-cycle (&optional arg)
4822 "Cycle the global visibility. For details see `org-cycle'.
4823 With C-u prefix arg, switch to startup visibility.
4824 With a numeric prefix, show all headlines up to that level."
4825 (interactive "P")
4826 (let ((org-cycle-include-plain-lists
4827 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4828 (cond
4829 ((integerp arg)
4830 (show-all)
4831 (hide-sublevels arg)
4832 (setq org-cycle-global-status 'contents))
4833 ((equal arg '(4))
4834 (org-set-startup-visibility)
4835 (message "Startup visibility, plus VISIBILITY properties."))
4837 (org-cycle '(4))))))
4839 (defun org-set-startup-visibility ()
4840 "Set the visibility required by startup options and properties."
4841 (cond
4842 ((eq org-startup-folded t)
4843 (org-cycle '(4)))
4844 ((eq org-startup-folded 'content)
4845 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4846 (org-cycle '(4)) (org-cycle '(4)))))
4847 (org-set-visibility-according-to-property 'no-cleanup)
4848 (org-cycle-hide-archived-subtrees 'all)
4849 (org-cycle-hide-drawers 'all)
4850 (org-cycle-show-empty-lines 'all))
4852 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4853 "Switch subtree visibilities according to :VISIBILITY: property."
4854 (interactive)
4855 (let (org-show-entry-below state)
4856 (save-excursion
4857 (goto-char (point-min))
4858 (while (re-search-forward
4859 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4860 nil t)
4861 (setq state (match-string 1))
4862 (save-excursion
4863 (org-back-to-heading t)
4864 (hide-subtree)
4865 (org-reveal)
4866 (cond
4867 ((equal state '("fold" "folded"))
4868 (hide-subtree))
4869 ((equal state "children")
4870 (org-show-hidden-entry)
4871 (show-children))
4872 ((equal state "content")
4873 (save-excursion
4874 (save-restriction
4875 (org-narrow-to-subtree)
4876 (org-content))))
4877 ((member state '("all" "showall"))
4878 (show-subtree)))))
4879 (unless no-cleanup
4880 (org-cycle-hide-archived-subtrees 'all)
4881 (org-cycle-hide-drawers 'all)
4882 (org-cycle-show-empty-lines 'all)))))
4884 (defun org-overview ()
4885 "Switch to overview mode, showing only top-level headlines.
4886 Really, this shows all headlines with level equal or greater than the level
4887 of the first headline in the buffer. This is important, because if the
4888 first headline is not level one, then (hide-sublevels 1) gives confusing
4889 results."
4890 (interactive)
4891 (let ((level (save-excursion
4892 (goto-char (point-min))
4893 (if (re-search-forward (concat "^" outline-regexp) nil t)
4894 (progn
4895 (goto-char (match-beginning 0))
4896 (funcall outline-level))))))
4897 (and level (hide-sublevels level))))
4899 (defun org-content (&optional arg)
4900 "Show all headlines in the buffer, like a table of contents.
4901 With numerical argument N, show content up to level N."
4902 (interactive "P")
4903 (save-excursion
4904 ;; Visit all headings and show their offspring
4905 (and (integerp arg) (org-overview))
4906 (goto-char (point-max))
4907 (catch 'exit
4908 (while (and (progn (condition-case nil
4909 (outline-previous-visible-heading 1)
4910 (error (goto-char (point-min))))
4912 (looking-at outline-regexp))
4913 (if (integerp arg)
4914 (show-children (1- arg))
4915 (show-branches))
4916 (if (bobp) (throw 'exit nil))))))
4919 (defun org-optimize-window-after-visibility-change (state)
4920 "Adjust the window after a change in outline visibility.
4921 This function is the default value of the hook `org-cycle-hook'."
4922 (when (get-buffer-window (current-buffer))
4923 (cond
4924 ((eq state 'content) nil)
4925 ((eq state 'all) nil)
4926 ((eq state 'folded) nil)
4927 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4928 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4930 (defun org-compact-display-after-subtree-move ()
4931 "Show a compacter version of the tree of the entry's parent."
4932 (save-excursion
4933 (if (org-up-heading-safe)
4934 (progn
4935 (hide-subtree)
4936 (show-entry)
4937 (show-children)
4938 (org-cycle-show-empty-lines 'children)
4939 (org-cycle-hide-drawers 'children))
4940 (org-overview))))
4942 (defun org-cycle-show-empty-lines (state)
4943 "Show empty lines above all visible headlines.
4944 The region to be covered depends on STATE when called through
4945 `org-cycle-hook'. Lisp program can use t for STATE to get the
4946 entire buffer covered. Note that an empty line is only shown if there
4947 are at least `org-cycle-separator-lines' empty lines before the headline."
4948 (when (> org-cycle-separator-lines 0)
4949 (save-excursion
4950 (let* ((n org-cycle-separator-lines)
4951 (re (cond
4952 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4953 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4954 (t (let ((ns (number-to-string (- n 2))))
4955 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4956 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4957 beg end)
4958 (cond
4959 ((memq state '(overview contents t))
4960 (setq beg (point-min) end (point-max)))
4961 ((memq state '(children folded))
4962 (setq beg (point) end (progn (org-end-of-subtree t t)
4963 (beginning-of-line 2)
4964 (point)))))
4965 (when beg
4966 (goto-char beg)
4967 (while (re-search-forward re end t)
4968 (if (not (get-char-property (match-end 1) 'invisible))
4969 (outline-flag-region
4970 (match-beginning 1) (match-end 1) nil)))))))
4971 ;; Never hide empty lines at the end of the file.
4972 (save-excursion
4973 (goto-char (point-max))
4974 (outline-previous-heading)
4975 (outline-end-of-heading)
4976 (if (and (looking-at "[ \t\n]+")
4977 (= (match-end 0) (point-max)))
4978 (outline-flag-region (point) (match-end 0) nil))))
4980 (defun org-show-empty-lines-in-parent ()
4981 "Move to the parent and re-show empty lines before visible headlines."
4982 (save-excursion
4983 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4984 (org-cycle-show-empty-lines context))))
4986 (defun org-cycle-hide-drawers (state)
4987 "Re-hide all drawers after a visibility state change."
4988 (when (and (org-mode-p)
4989 (not (memq state '(overview folded))))
4990 (save-excursion
4991 (let* ((globalp (memq state '(contents all)))
4992 (beg (if globalp (point-min) (point)))
4993 (end (if globalp (point-max) (org-end-of-subtree t))))
4994 (goto-char beg)
4995 (while (re-search-forward org-drawer-regexp end t)
4996 (org-flag-drawer t))))))
4998 (defun org-flag-drawer (flag)
4999 (save-excursion
5000 (beginning-of-line 1)
5001 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5002 (let ((b (match-end 0))
5003 (outline-regexp org-outline-regexp))
5004 (if (re-search-forward
5005 "^[ \t]*:END:"
5006 (save-excursion (outline-next-heading) (point)) t)
5007 (outline-flag-region b (point-at-eol) flag)
5008 (error ":END: line missing"))))))
5010 (defun org-subtree-end-visible-p ()
5011 "Is the end of the current subtree visible?"
5012 (pos-visible-in-window-p
5013 (save-excursion (org-end-of-subtree t) (point))))
5015 (defun org-first-headline-recenter (&optional N)
5016 "Move cursor to the first headline and recenter the headline.
5017 Optional argument N means, put the headline into the Nth line of the window."
5018 (goto-char (point-min))
5019 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5020 (beginning-of-line)
5021 (recenter (prefix-numeric-value N))))
5023 ;;; Org-goto
5025 (defvar org-goto-window-configuration nil)
5026 (defvar org-goto-marker nil)
5027 (defvar org-goto-map
5028 (let ((map (make-sparse-keymap)))
5029 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5030 (while (setq cmd (pop cmds))
5031 (substitute-key-definition cmd cmd map global-map)))
5032 (suppress-keymap map)
5033 (org-defkey map "\C-m" 'org-goto-ret)
5034 (org-defkey map [(return)] 'org-goto-ret)
5035 (org-defkey map [(left)] 'org-goto-left)
5036 (org-defkey map [(right)] 'org-goto-right)
5037 (org-defkey map [(control ?g)] 'org-goto-quit)
5038 (org-defkey map "\C-i" 'org-cycle)
5039 (org-defkey map [(tab)] 'org-cycle)
5040 (org-defkey map [(down)] 'outline-next-visible-heading)
5041 (org-defkey map [(up)] 'outline-previous-visible-heading)
5042 (if org-goto-auto-isearch
5043 (if (fboundp 'define-key-after)
5044 (define-key-after map [t] 'org-goto-local-auto-isearch)
5045 nil)
5046 (org-defkey map "q" 'org-goto-quit)
5047 (org-defkey map "n" 'outline-next-visible-heading)
5048 (org-defkey map "p" 'outline-previous-visible-heading)
5049 (org-defkey map "f" 'outline-forward-same-level)
5050 (org-defkey map "b" 'outline-backward-same-level)
5051 (org-defkey map "u" 'outline-up-heading))
5052 (org-defkey map "/" 'org-occur)
5053 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5054 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5055 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5056 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5057 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5058 map))
5060 (defconst org-goto-help
5061 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5062 RET=jump to location [Q]uit and return to previous location
5063 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5065 (defvar org-goto-start-pos) ; dynamically scoped parameter
5067 ;; FIXME: Docstring doe not mention both interfaces
5068 (defun org-goto (&optional alternative-interface)
5069 "Look up a different location in the current file, keeping current visibility.
5071 When you want look-up or go to a different location in a document, the
5072 fastest way is often to fold the entire buffer and then dive into the tree.
5073 This method has the disadvantage, that the previous location will be folded,
5074 which may not be what you want.
5076 This command works around this by showing a copy of the current buffer
5077 in an indirect buffer, in overview mode. You can dive into the tree in
5078 that copy, use org-occur and incremental search to find a location.
5079 When pressing RET or `Q', the command returns to the original buffer in
5080 which the visibility is still unchanged. After RET is will also jump to
5081 the location selected in the indirect buffer and expose the
5082 the headline hierarchy above."
5083 (interactive "P")
5084 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5085 (org-refile-use-outline-path t)
5086 (org-refile-target-verify-function nil)
5087 (interface
5088 (if (not alternative-interface)
5089 org-goto-interface
5090 (if (eq org-goto-interface 'outline)
5091 'outline-path-completion
5092 'outline)))
5093 (org-goto-start-pos (point))
5094 (selected-point
5095 (if (eq interface 'outline)
5096 (car (org-get-location (current-buffer) org-goto-help))
5097 (nth 3 (org-refile-get-location "Goto: ")))))
5098 (if selected-point
5099 (progn
5100 (org-mark-ring-push org-goto-start-pos)
5101 (goto-char selected-point)
5102 (if (or (org-invisible-p) (org-invisible-p2))
5103 (org-show-context 'org-goto)))
5104 (message "Quit"))))
5106 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5107 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5108 (defvar org-goto-local-auto-isearch-map) ; defined below
5110 (defun org-get-location (buf help)
5111 "Let the user select a location in the Org-mode buffer BUF.
5112 This function uses a recursive edit. It returns the selected position
5113 or nil."
5114 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5115 (isearch-hide-immediately nil)
5116 (isearch-search-fun-function
5117 (lambda () 'org-goto-local-search-headings))
5118 (org-goto-selected-point org-goto-exit-command))
5119 (save-excursion
5120 (save-window-excursion
5121 (delete-other-windows)
5122 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5123 (switch-to-buffer
5124 (condition-case nil
5125 (make-indirect-buffer (current-buffer) "*org-goto*")
5126 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5127 (with-output-to-temp-buffer "*Help*"
5128 (princ help))
5129 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5130 (setq buffer-read-only nil)
5131 (let ((org-startup-truncated t)
5132 (org-startup-folded nil)
5133 (org-startup-align-all-tables nil))
5134 (org-mode)
5135 (org-overview))
5136 (setq buffer-read-only t)
5137 (if (and (boundp 'org-goto-start-pos)
5138 (integer-or-marker-p org-goto-start-pos))
5139 (let ((org-show-hierarchy-above t)
5140 (org-show-siblings t)
5141 (org-show-following-heading t))
5142 (goto-char org-goto-start-pos)
5143 (and (org-invisible-p) (org-show-context)))
5144 (goto-char (point-min)))
5145 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5146 (message "Select location and press RET")
5147 (use-local-map org-goto-map)
5148 (recursive-edit)
5150 (kill-buffer "*org-goto*")
5151 (cons org-goto-selected-point org-goto-exit-command)))
5153 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5154 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5155 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5156 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5158 (defun org-goto-local-search-headings (string bound noerror)
5159 "Search and make sure that any matches are in headlines."
5160 (catch 'return
5161 (while (if isearch-forward
5162 (search-forward string bound noerror)
5163 (search-backward string bound noerror))
5164 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5165 (and (member :headline context)
5166 (not (member :tags context))))
5167 (throw 'return (point))))))
5169 (defun org-goto-local-auto-isearch ()
5170 "Start isearch."
5171 (interactive)
5172 (goto-char (point-min))
5173 (let ((keys (this-command-keys)))
5174 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5175 (isearch-mode t)
5176 (isearch-process-search-char (string-to-char keys)))))
5178 (defun org-goto-ret (&optional arg)
5179 "Finish `org-goto' by going to the new location."
5180 (interactive "P")
5181 (setq org-goto-selected-point (point)
5182 org-goto-exit-command 'return)
5183 (throw 'exit nil))
5185 (defun org-goto-left ()
5186 "Finish `org-goto' by going to the new location."
5187 (interactive)
5188 (if (org-on-heading-p)
5189 (progn
5190 (beginning-of-line 1)
5191 (setq org-goto-selected-point (point)
5192 org-goto-exit-command 'left)
5193 (throw 'exit nil))
5194 (error "Not on a heading")))
5196 (defun org-goto-right ()
5197 "Finish `org-goto' by going to the new location."
5198 (interactive)
5199 (if (org-on-heading-p)
5200 (progn
5201 (setq org-goto-selected-point (point)
5202 org-goto-exit-command 'right)
5203 (throw 'exit nil))
5204 (error "Not on a heading")))
5206 (defun org-goto-quit ()
5207 "Finish `org-goto' without cursor motion."
5208 (interactive)
5209 (setq org-goto-selected-point nil)
5210 (setq org-goto-exit-command 'quit)
5211 (throw 'exit nil))
5213 ;;; Indirect buffer display of subtrees
5215 (defvar org-indirect-dedicated-frame nil
5216 "This is the frame being used for indirect tree display.")
5217 (defvar org-last-indirect-buffer nil)
5219 (defun org-tree-to-indirect-buffer (&optional arg)
5220 "Create indirect buffer and narrow it to current subtree.
5221 With numerical prefix ARG, go up to this level and then take that tree.
5222 If ARG is negative, go up that many levels.
5223 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5224 indirect buffer previously made with this command, to avoid proliferation of
5225 indirect buffers. However, when you call the command with a `C-u' prefix, or
5226 when `org-indirect-buffer-display' is `new-frame', the last buffer
5227 is kept so that you can work with several indirect buffers at the same time.
5228 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5229 requests that a new frame be made for the new buffer, so that the dedicated
5230 frame is not changed."
5231 (interactive "P")
5232 (let ((cbuf (current-buffer))
5233 (cwin (selected-window))
5234 (pos (point))
5235 beg end level heading ibuf)
5236 (save-excursion
5237 (org-back-to-heading t)
5238 (when (numberp arg)
5239 (setq level (org-outline-level))
5240 (if (< arg 0) (setq arg (+ level arg)))
5241 (while (> (setq level (org-outline-level)) arg)
5242 (outline-up-heading 1 t)))
5243 (setq beg (point)
5244 heading (org-get-heading))
5245 (org-end-of-subtree t) (setq end (point)))
5246 (if (and (buffer-live-p org-last-indirect-buffer)
5247 (not (eq org-indirect-buffer-display 'new-frame))
5248 (not arg))
5249 (kill-buffer org-last-indirect-buffer))
5250 (setq ibuf (org-get-indirect-buffer cbuf)
5251 org-last-indirect-buffer ibuf)
5252 (cond
5253 ((or (eq org-indirect-buffer-display 'new-frame)
5254 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5255 (select-frame (make-frame))
5256 (delete-other-windows)
5257 (switch-to-buffer ibuf)
5258 (org-set-frame-title heading))
5259 ((eq org-indirect-buffer-display 'dedicated-frame)
5260 (raise-frame
5261 (select-frame (or (and org-indirect-dedicated-frame
5262 (frame-live-p org-indirect-dedicated-frame)
5263 org-indirect-dedicated-frame)
5264 (setq org-indirect-dedicated-frame (make-frame)))))
5265 (delete-other-windows)
5266 (switch-to-buffer ibuf)
5267 (org-set-frame-title (concat "Indirect: " heading)))
5268 ((eq org-indirect-buffer-display 'current-window)
5269 (switch-to-buffer ibuf))
5270 ((eq org-indirect-buffer-display 'other-window)
5271 (pop-to-buffer ibuf))
5272 (t (error "Invalid value.")))
5273 (if (featurep 'xemacs)
5274 (save-excursion (org-mode) (turn-on-font-lock)))
5275 (narrow-to-region beg end)
5276 (show-all)
5277 (goto-char pos)
5278 (and (window-live-p cwin) (select-window cwin))))
5280 (defun org-get-indirect-buffer (&optional buffer)
5281 (setq buffer (or buffer (current-buffer)))
5282 (let ((n 1) (base (buffer-name buffer)) bname)
5283 (while (buffer-live-p
5284 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5285 (setq n (1+ n)))
5286 (condition-case nil
5287 (make-indirect-buffer buffer bname 'clone)
5288 (error (make-indirect-buffer buffer bname)))))
5290 (defun org-set-frame-title (title)
5291 "Set the title of the current frame to the string TITLE."
5292 ;; FIXME: how to name a single frame in XEmacs???
5293 (unless (featurep 'xemacs)
5294 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5296 ;;;; Structure editing
5298 ;;; Inserting headlines
5300 (defun org-previous-line-empty-p ()
5301 (save-excursion
5302 (and (not (bobp))
5303 (or (beginning-of-line 0) t)
5304 (save-match-data
5305 (looking-at "[ \t]*$")))))
5307 (defun org-insert-heading (&optional force-heading)
5308 "Insert a new heading or item with same depth at point.
5309 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5310 If point is at the beginning of a headline, insert a sibling before the
5311 current headline. If point is not at the beginning, do not split the line,
5312 but create the new headline after the current line."
5313 (interactive "P")
5314 (if (= (buffer-size) 0)
5315 (insert "\n* ")
5316 (when (or force-heading (not (org-insert-item)))
5317 (let* ((empty-line-p nil)
5318 (head (save-excursion
5319 (condition-case nil
5320 (progn
5321 (org-back-to-heading)
5322 (setq empty-line-p (org-previous-line-empty-p))
5323 (match-string 0))
5324 (error "*"))))
5325 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5326 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5327 pos hide-previous previous-pos)
5328 (cond
5329 ((and (org-on-heading-p) (bolp)
5330 (or (bobp)
5331 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5332 ;; insert before the current line
5333 (open-line (if blank 2 1)))
5334 ((and (bolp)
5335 (or (bobp)
5336 (save-excursion
5337 (backward-char 1) (not (org-invisible-p)))))
5338 ;; insert right here
5339 nil)
5341 ;; somewhere in the line
5342 (save-excursion
5343 (setq previous-pos (point-at-bol))
5344 (end-of-line)
5345 (setq hide-previous (org-invisible-p)))
5346 (and org-insert-heading-respect-content (org-show-subtree))
5347 (let ((split
5348 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5349 (save-excursion
5350 (let ((p (point)))
5351 (goto-char (point-at-bol))
5352 (and (looking-at org-complex-heading-regexp)
5353 (> p (match-beginning 4)))))))
5354 tags pos)
5355 (cond
5356 (org-insert-heading-respect-content
5357 (org-end-of-subtree nil t)
5358 (or (bolp) (newline))
5359 (or (org-previous-line-empty-p)
5360 (and blank (newline)))
5361 (open-line 1))
5362 ((org-on-heading-p)
5363 (when hide-previous
5364 (show-children)
5365 (org-show-entry))
5366 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5367 (setq tags (and (match-end 2) (match-string 2)))
5368 (and (match-end 1)
5369 (delete-region (match-beginning 1) (match-end 1)))
5370 (setq pos (point-at-bol))
5371 (or split (end-of-line 1))
5372 (delete-horizontal-space)
5373 (newline (if blank 2 1))
5374 (when tags
5375 (save-excursion
5376 (goto-char pos)
5377 (end-of-line 1)
5378 (insert " " tags)
5379 (org-set-tags nil 'align))))
5381 (or split (end-of-line 1))
5382 (newline (if blank 2 1)))))))
5383 (insert head) (just-one-space)
5384 (setq pos (point))
5385 (end-of-line 1)
5386 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5387 (when (and org-insert-heading-respect-content hide-previous)
5388 (save-excursion
5389 (goto-char previous-pos)
5390 (hide-subtree)))
5391 (run-hooks 'org-insert-heading-hook)))))
5393 (defun org-get-heading (&optional no-tags)
5394 "Return the heading of the current entry, without the stars."
5395 (save-excursion
5396 (org-back-to-heading t)
5397 (if (looking-at
5398 (if no-tags
5399 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5400 "\\*+[ \t]+\\([^\r\n]*\\)"))
5401 (match-string 1) "")))
5403 (defun org-heading-components ()
5404 "Return the components of the current heading.
5405 This is a list with the following elements:
5406 - the level as an integer
5407 - the reduced level, different if `org-odd-levels-only' is set.
5408 - the TODO keyword, or nil
5409 - the priority character, like ?A, or nil if no priority is given
5410 - the headline text itself, or the tags string if no headline text
5411 - the tags string, or nil."
5412 (save-excursion
5413 (org-back-to-heading t)
5414 (if (looking-at org-complex-heading-regexp)
5415 (list (length (match-string 1))
5416 (org-reduced-level (length (match-string 1)))
5417 (org-match-string-no-properties 2)
5418 (and (match-end 3) (aref (match-string 3) 2))
5419 (org-match-string-no-properties 4)
5420 (org-match-string-no-properties 5)))))
5422 (defun org-get-entry ()
5423 "Get the entry text, after heading, entire subtree."
5424 (save-excursion
5425 (org-back-to-heading t)
5426 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
5428 (defun org-insert-heading-after-current ()
5429 "Insert a new heading with same level as current, after current subtree."
5430 (interactive)
5431 (org-back-to-heading)
5432 (org-insert-heading)
5433 (org-move-subtree-down)
5434 (end-of-line 1))
5436 (defun org-insert-heading-respect-content ()
5437 (interactive)
5438 (let ((org-insert-heading-respect-content t))
5439 (org-insert-heading t)))
5441 (defun org-insert-todo-heading-respect-content (&optional force-state)
5442 (interactive "P")
5443 (let ((org-insert-heading-respect-content t))
5444 (org-insert-todo-heading force-state t)))
5446 (defun org-insert-todo-heading (arg &optional force-heading)
5447 "Insert a new heading with the same level and TODO state as current heading.
5448 If the heading has no TODO state, or if the state is DONE, use the first
5449 state (TODO by default). Also with prefix arg, force first state."
5450 (interactive "P")
5451 (when (or force-heading (not (org-insert-item 'checkbox)))
5452 (org-insert-heading force-heading)
5453 (save-excursion
5454 (org-back-to-heading)
5455 (outline-previous-heading)
5456 (looking-at org-todo-line-regexp))
5457 (let*
5458 ((new-mark-x
5459 (if (or arg
5460 (not (match-beginning 2))
5461 (member (match-string 2) org-done-keywords))
5462 (car org-todo-keywords-1)
5463 (match-string 2)))
5464 (new-mark
5466 (run-hook-with-args-until-success
5467 'org-todo-get-default-hook new-mark-x nil)
5468 new-mark-x)))
5469 (beginning-of-line 1)
5470 (and (looking-at "\\*+ ") (goto-char (match-end 0))
5471 (insert new-mark " ")))
5472 (when org-provide-todo-statistics
5473 (org-update-parent-todo-statistics))))
5475 (defun org-insert-subheading (arg)
5476 "Insert a new subheading and demote it.
5477 Works for outline headings and for plain lists alike."
5478 (interactive "P")
5479 (org-insert-heading arg)
5480 (cond
5481 ((org-on-heading-p) (org-do-demote))
5482 ((org-at-item-p) (org-indent-item 1))))
5484 (defun org-insert-todo-subheading (arg)
5485 "Insert a new subheading with TODO keyword or checkbox and demote it.
5486 Works for outline headings and for plain lists alike."
5487 (interactive "P")
5488 (org-insert-todo-heading arg)
5489 (cond
5490 ((org-on-heading-p) (org-do-demote))
5491 ((org-at-item-p) (org-indent-item 1))))
5493 ;;; Promotion and Demotion
5495 (defun org-promote-subtree ()
5496 "Promote the entire subtree.
5497 See also `org-promote'."
5498 (interactive)
5499 (save-excursion
5500 (org-map-tree 'org-promote))
5501 (org-fix-position-after-promote))
5503 (defun org-demote-subtree ()
5504 "Demote the entire subtree. See `org-demote'.
5505 See also `org-promote'."
5506 (interactive)
5507 (save-excursion
5508 (org-map-tree 'org-demote))
5509 (org-fix-position-after-promote))
5512 (defun org-do-promote ()
5513 "Promote the current heading higher up the tree.
5514 If the region is active in `transient-mark-mode', promote all headings
5515 in the region."
5516 (interactive)
5517 (save-excursion
5518 (if (org-region-active-p)
5519 (org-map-region 'org-promote (region-beginning) (region-end))
5520 (org-promote)))
5521 (org-fix-position-after-promote))
5523 (defun org-do-demote ()
5524 "Demote the current heading lower down the tree.
5525 If the region is active in `transient-mark-mode', demote all headings
5526 in the region."
5527 (interactive)
5528 (save-excursion
5529 (if (org-region-active-p)
5530 (org-map-region 'org-demote (region-beginning) (region-end))
5531 (org-demote)))
5532 (org-fix-position-after-promote))
5534 (defun org-fix-position-after-promote ()
5535 "Make sure that after pro/demotion cursor position is right."
5536 (let ((pos (point)))
5537 (when (save-excursion
5538 (beginning-of-line 1)
5539 (looking-at org-todo-line-regexp)
5540 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5541 (cond ((eobp) (insert " "))
5542 ((eolp) (insert " "))
5543 ((equal (char-after) ?\ ) (forward-char 1))))))
5545 (defun org-reduced-level (l)
5546 "Compute the effective level of a heading.
5547 This takes into account the setting of `org-odd-levels-only'."
5548 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5550 (defun org-get-valid-level (level &optional change)
5551 "Rectify a level change under the influence of `org-odd-levels-only'
5552 LEVEL is a current level, CHANGE is by how much the level should be
5553 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5554 even level numbers will become the next higher odd number."
5555 (if org-odd-levels-only
5556 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5557 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5558 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5559 (max 1 (+ level (or change 0)))))
5561 (if (boundp 'define-obsolete-function-alias)
5562 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5563 (define-obsolete-function-alias 'org-get-legal-level
5564 'org-get-valid-level)
5565 (define-obsolete-function-alias 'org-get-legal-level
5566 'org-get-valid-level "23.1")))
5568 (defun org-promote ()
5569 "Promote the current heading higher up the tree.
5570 If the region is active in `transient-mark-mode', promote all headings
5571 in the region."
5572 (org-back-to-heading t)
5573 (let* ((level (save-match-data (funcall outline-level)))
5574 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5575 (diff (abs (- level (length up-head) -1))))
5576 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5577 (replace-match up-head nil t)
5578 ;; Fixup tag positioning
5579 (and org-auto-align-tags (org-set-tags nil t))
5580 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5582 (defun org-demote ()
5583 "Demote the current heading lower down the tree.
5584 If the region is active in `transient-mark-mode', demote all headings
5585 in the region."
5586 (org-back-to-heading t)
5587 (let* ((level (save-match-data (funcall outline-level)))
5588 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5589 (diff (abs (- level (length down-head) -1))))
5590 (replace-match down-head nil t)
5591 ;; Fixup tag positioning
5592 (and org-auto-align-tags (org-set-tags nil t))
5593 (if org-adapt-indentation (org-fixup-indentation diff))))
5595 (defun org-map-tree (fun)
5596 "Call FUN for every heading underneath the current one."
5597 (org-back-to-heading)
5598 (let ((level (funcall outline-level)))
5599 (save-excursion
5600 (funcall fun)
5601 (while (and (progn
5602 (outline-next-heading)
5603 (> (funcall outline-level) level))
5604 (not (eobp)))
5605 (funcall fun)))))
5607 (defun org-map-region (fun beg end)
5608 "Call FUN for every heading between BEG and END."
5609 (let ((org-ignore-region t))
5610 (save-excursion
5611 (setq end (copy-marker end))
5612 (goto-char beg)
5613 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5614 (< (point) end))
5615 (funcall fun))
5616 (while (and (progn
5617 (outline-next-heading)
5618 (< (point) end))
5619 (not (eobp)))
5620 (funcall fun)))))
5622 (defun org-fixup-indentation (diff)
5623 "Change the indentation in the current entry by DIFF
5624 However, if any line in the current entry has no indentation, or if it
5625 would end up with no indentation after the change, nothing at all is done."
5626 (save-excursion
5627 (let ((end (save-excursion (outline-next-heading)
5628 (point-marker)))
5629 (prohibit (if (> diff 0)
5630 "^\\S-"
5631 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5632 col)
5633 (unless (save-excursion (end-of-line 1)
5634 (re-search-forward prohibit end t))
5635 (while (and (< (point) end)
5636 (re-search-forward "^[ \t]+" end t))
5637 (goto-char (match-end 0))
5638 (setq col (current-column))
5639 (if (< diff 0) (replace-match ""))
5640 (org-indent-to-column (+ diff col))))
5641 (move-marker end nil))))
5643 (defun org-convert-to-odd-levels ()
5644 "Convert an org-mode file with all levels allowed to one with odd levels.
5645 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5646 level 5 etc."
5647 (interactive)
5648 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5649 (let ((org-odd-levels-only nil) n)
5650 (save-excursion
5651 (goto-char (point-min))
5652 (while (re-search-forward "^\\*\\*+ " nil t)
5653 (setq n (- (length (match-string 0)) 2))
5654 (while (>= (setq n (1- n)) 0)
5655 (org-demote))
5656 (end-of-line 1))))))
5659 (defun org-convert-to-oddeven-levels ()
5660 "Convert an org-mode file with only odd levels to one with odd and even levels.
5661 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5662 section with an even level, conversion would destroy the structure of the file. An error
5663 is signaled in this case."
5664 (interactive)
5665 (goto-char (point-min))
5666 ;; First check if there are no even levels
5667 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5668 (org-show-context t)
5669 (error "Not all levels are odd in this file. Conversion not possible."))
5670 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5671 (let ((org-odd-levels-only nil) n)
5672 (save-excursion
5673 (goto-char (point-min))
5674 (while (re-search-forward "^\\*\\*+ " nil t)
5675 (setq n (/ (1- (length (match-string 0))) 2))
5676 (while (>= (setq n (1- n)) 0)
5677 (org-promote))
5678 (end-of-line 1))))))
5680 (defun org-tr-level (n)
5681 "Make N odd if required."
5682 (if org-odd-levels-only (1+ (/ n 2)) n))
5684 ;;; Vertical tree motion, cutting and pasting of subtrees
5686 (defun org-move-subtree-up (&optional arg)
5687 "Move the current subtree up past ARG headlines of the same level."
5688 (interactive "p")
5689 (org-move-subtree-down (- (prefix-numeric-value arg))))
5691 (defun org-move-subtree-down (&optional arg)
5692 "Move the current subtree down past ARG headlines of the same level."
5693 (interactive "p")
5694 (setq arg (prefix-numeric-value arg))
5695 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5696 'outline-get-last-sibling))
5697 (ins-point (make-marker))
5698 (cnt (abs arg))
5699 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5700 ;; Select the tree
5701 (org-back-to-heading)
5702 (setq beg0 (point))
5703 (save-excursion
5704 (setq ne-beg (org-back-over-empty-lines))
5705 (setq beg (point)))
5706 (save-match-data
5707 (save-excursion (outline-end-of-heading)
5708 (setq folded (org-invisible-p)))
5709 (outline-end-of-subtree))
5710 (outline-next-heading)
5711 (setq ne-end (org-back-over-empty-lines))
5712 (setq end (point))
5713 (goto-char beg0)
5714 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5715 ;; include less whitespace
5716 (save-excursion
5717 (goto-char beg)
5718 (forward-line (- ne-beg ne-end))
5719 (setq beg (point))))
5720 ;; Find insertion point, with error handling
5721 (while (> cnt 0)
5722 (or (and (funcall movfunc) (looking-at outline-regexp))
5723 (progn (goto-char beg0)
5724 (error "Cannot move past superior level or buffer limit")))
5725 (setq cnt (1- cnt)))
5726 (if (> arg 0)
5727 ;; Moving forward - still need to move over subtree
5728 (progn (org-end-of-subtree t t)
5729 (save-excursion
5730 (org-back-over-empty-lines)
5731 (or (bolp) (newline)))))
5732 (setq ne-ins (org-back-over-empty-lines))
5733 (move-marker ins-point (point))
5734 (setq txt (buffer-substring beg end))
5735 (org-save-markers-in-region beg end)
5736 (delete-region beg end)
5737 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5738 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5739 (and (not (bolp)) (looking-at "\n") (forward-char 1))
5740 (let ((bbb (point)))
5741 (insert-before-markers txt)
5742 (org-reinstall-markers-in-region bbb)
5743 (move-marker ins-point bbb))
5744 (or (bolp) (insert "\n"))
5745 (setq ins-end (point))
5746 (goto-char ins-point)
5747 (org-skip-whitespace)
5748 (when (and (< arg 0)
5749 (org-first-sibling-p)
5750 (> ne-ins ne-beg))
5751 ;; Move whitespace back to beginning
5752 (save-excursion
5753 (goto-char ins-end)
5754 (let ((kill-whole-line t))
5755 (kill-line (- ne-ins ne-beg)) (point)))
5756 (insert (make-string (- ne-ins ne-beg) ?\n)))
5757 (move-marker ins-point nil)
5758 (org-compact-display-after-subtree-move)
5759 (org-show-empty-lines-in-parent)
5760 (unless folded
5761 (org-show-entry)
5762 (show-children)
5763 (org-cycle-hide-drawers 'children))))
5765 (defvar org-subtree-clip ""
5766 "Clipboard for cut and paste of subtrees.
5767 This is actually only a copy of the kill, because we use the normal kill
5768 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5770 (defvar org-subtree-clip-folded nil
5771 "Was the last copied subtree folded?
5772 This is used to fold the tree back after pasting.")
5774 (defun org-cut-subtree (&optional n)
5775 "Cut the current subtree into the clipboard.
5776 With prefix arg N, cut this many sequential subtrees.
5777 This is a short-hand for marking the subtree and then cutting it."
5778 (interactive "p")
5779 (org-copy-subtree n 'cut))
5781 (defun org-copy-subtree (&optional n cut force-store-markers)
5782 "Cut the current subtree into the clipboard.
5783 With prefix arg N, cut this many sequential subtrees.
5784 This is a short-hand for marking the subtree and then copying it.
5785 If CUT is non-nil, actually cut the subtree.
5786 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5787 of some markers in the region, even if CUT is non-nil. This is
5788 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5789 (interactive "p")
5790 (let (beg end folded (beg0 (point)))
5791 (if (interactive-p)
5792 (org-back-to-heading nil) ; take what looks like a subtree
5793 (org-back-to-heading t)) ; take what is really there
5794 (org-back-over-empty-lines)
5795 (setq beg (point))
5796 (skip-chars-forward " \t\r\n")
5797 (save-match-data
5798 (save-excursion (outline-end-of-heading)
5799 (setq folded (org-invisible-p)))
5800 (condition-case nil
5801 (outline-forward-same-level (1- n))
5802 (error nil))
5803 (org-end-of-subtree t t))
5804 (org-back-over-empty-lines)
5805 (setq end (point))
5806 (goto-char beg0)
5807 (when (> end beg)
5808 (setq org-subtree-clip-folded folded)
5809 (when (or cut force-store-markers)
5810 (org-save-markers-in-region beg end))
5811 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5812 (setq org-subtree-clip (current-kill 0))
5813 (message "%s: Subtree(s) with %d characters"
5814 (if cut "Cut" "Copied")
5815 (length org-subtree-clip)))))
5817 (defun org-paste-subtree (&optional level tree for-yank)
5818 "Paste the clipboard as a subtree, with modification of headline level.
5819 The entire subtree is promoted or demoted in order to match a new headline
5820 level.
5822 If the cursor is at the beginning of a headline, the same level as
5823 that headline is used to paste the tree
5825 If not, the new level is derived from the *visible* headings
5826 before and after the insertion point, and taken to be the inferior headline
5827 level of the two. So if the previous visible heading is level 3 and the
5828 next is level 4 (or vice versa), level 4 will be used for insertion.
5829 This makes sure that the subtree remains an independent subtree and does
5830 not swallow low level entries.
5832 You can also force a different level, either by using a numeric prefix
5833 argument, or by inserting the heading marker by hand. For example, if the
5834 cursor is after \"*****\", then the tree will be shifted to level 5.
5836 If optional TREE is given, use this text instead of the kill ring.
5838 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5839 move back over whitespace before inserting, and move point to the end of
5840 the inserted text when done."
5841 (interactive "P")
5842 (unless (org-kill-is-subtree-p tree)
5843 (error "%s"
5844 (substitute-command-keys
5845 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5846 (let* ((visp (not (org-invisible-p)))
5847 (txt (or tree (and kill-ring (current-kill 0))))
5848 (^re (concat "^\\(" outline-regexp "\\)"))
5849 (re (concat "\\(" outline-regexp "\\)"))
5850 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5852 (old-level (if (string-match ^re txt)
5853 (- (match-end 0) (match-beginning 0) 1)
5854 -1))
5855 (force-level (cond (level (prefix-numeric-value level))
5856 ((and (looking-at "[ \t]*$")
5857 (string-match
5858 ^re_ (buffer-substring
5859 (point-at-bol) (point))))
5860 (- (match-end 1) (match-beginning 1)))
5861 ((and (bolp)
5862 (looking-at org-outline-regexp))
5863 (- (match-end 0) (point) 1))
5864 (t nil)))
5865 (previous-level (save-excursion
5866 (condition-case nil
5867 (progn
5868 (outline-previous-visible-heading 1)
5869 (if (looking-at re)
5870 (- (match-end 0) (match-beginning 0) 1)
5872 (error 1))))
5873 (next-level (save-excursion
5874 (condition-case nil
5875 (progn
5876 (or (looking-at outline-regexp)
5877 (outline-next-visible-heading 1))
5878 (if (looking-at re)
5879 (- (match-end 0) (match-beginning 0) 1)
5881 (error 1))))
5882 (new-level (or force-level (max previous-level next-level)))
5883 (shift (if (or (= old-level -1)
5884 (= new-level -1)
5885 (= old-level new-level))
5887 (- new-level old-level)))
5888 (delta (if (> shift 0) -1 1))
5889 (func (if (> shift 0) 'org-demote 'org-promote))
5890 (org-odd-levels-only nil)
5891 beg end newend)
5892 ;; Remove the forced level indicator
5893 (if force-level
5894 (delete-region (point-at-bol) (point)))
5895 ;; Paste
5896 (beginning-of-line 1)
5897 (unless for-yank (org-back-over-empty-lines))
5898 (setq beg (point))
5899 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5900 (insert-before-markers txt)
5901 (unless (string-match "\n\\'" txt) (insert "\n"))
5902 (setq newend (point))
5903 (org-reinstall-markers-in-region beg)
5904 (setq end (point))
5905 (goto-char beg)
5906 (skip-chars-forward " \t\n\r")
5907 (setq beg (point))
5908 (if (and (org-invisible-p) visp)
5909 (save-excursion (outline-show-heading)))
5910 ;; Shift if necessary
5911 (unless (= shift 0)
5912 (save-restriction
5913 (narrow-to-region beg end)
5914 (while (not (= shift 0))
5915 (org-map-region func (point-min) (point-max))
5916 (setq shift (+ delta shift)))
5917 (goto-char (point-min))
5918 (setq newend (point-max))))
5919 (when (or (interactive-p) for-yank)
5920 (message "Clipboard pasted as level %d subtree" new-level))
5921 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5922 kill-ring
5923 (eq org-subtree-clip (current-kill 0))
5924 org-subtree-clip-folded)
5925 ;; The tree was folded before it was killed/copied
5926 (hide-subtree))
5927 (and for-yank (goto-char newend))))
5929 (defun org-kill-is-subtree-p (&optional txt)
5930 "Check if the current kill is an outline subtree, or a set of trees.
5931 Returns nil if kill does not start with a headline, or if the first
5932 headline level is not the largest headline level in the tree.
5933 So this will actually accept several entries of equal levels as well,
5934 which is OK for `org-paste-subtree'.
5935 If optional TXT is given, check this string instead of the current kill."
5936 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5937 (start-level (and kill
5938 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5939 org-outline-regexp "\\)")
5940 kill)
5941 (- (match-end 2) (match-beginning 2) 1)))
5942 (re (concat "^" org-outline-regexp))
5943 (start (1+ (or (match-beginning 2) -1))))
5944 (if (not start-level)
5945 (progn
5946 nil) ;; does not even start with a heading
5947 (catch 'exit
5948 (while (setq start (string-match re kill (1+ start)))
5949 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5950 (throw 'exit nil)))
5951 t))))
5953 (defvar org-markers-to-move nil
5954 "Markers that should be moved with a cut-and-paste operation.
5955 Those markers are stored together with their positions relative to
5956 the start of the region.")
5958 (defun org-save-markers-in-region (beg end)
5959 "Check markers in region.
5960 If these markers are between BEG and END, record their position relative
5961 to BEG, so that after moving the block of text, we can put the markers back
5962 into place.
5963 This function gets called just before an entry or tree gets cut from the
5964 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5965 called immediately, to move the markers with the entries."
5966 (setq org-markers-to-move nil)
5967 (when (featurep 'org-clock)
5968 (org-clock-save-markers-for-cut-and-paste beg end))
5969 (when (featurep 'org-agenda)
5970 (org-agenda-save-markers-for-cut-and-paste beg end)))
5972 (defun org-check-and-save-marker (marker beg end)
5973 "Check if MARKER is between BEG and END.
5974 If yes, remember the marker and the distance to BEG."
5975 (when (and (marker-buffer marker)
5976 (equal (marker-buffer marker) (current-buffer)))
5977 (if (and (>= marker beg) (< marker end))
5978 (push (cons marker (- marker beg)) org-markers-to-move))))
5980 (defun org-reinstall-markers-in-region (beg)
5981 "Move all remembered markers to their position relative to BEG."
5982 (mapc (lambda (x)
5983 (move-marker (car x) (+ beg (cdr x))))
5984 org-markers-to-move)
5985 (setq org-markers-to-move nil))
5987 (defun org-narrow-to-subtree ()
5988 "Narrow buffer to the current subtree."
5989 (interactive)
5990 (save-excursion
5991 (save-match-data
5992 (narrow-to-region
5993 (progn (org-back-to-heading) (point))
5994 (progn (org-end-of-subtree t) (point))))))
5996 (defun org-clone-subtree-with-time-shift (n &optional shift)
5997 "Clone the task (subtree) at point N times.
5998 The clones will be inserted as siblings.
6000 In interactive use, the user will be prompted for the number of clones
6001 to be produced, and for a time SHIFT, which may be a repeater as used
6002 in time stamps, for example `+3d'.
6004 When a valid repeater is given and the entry contains any time stamps,
6005 the clones will become a sequence in time, with time stamps in the
6006 subtree shifted for each clone produced. If SHIFT is nil or the
6007 empty string, time stamps will be left alone.
6009 If the original subtree did contain time stamps with a repeater,
6010 the following will happen:
6011 - the repeater will be removed in each clone
6012 - an additional clone will be produced, with the current, unshifted
6013 date(s) in the entry.
6014 - the original entry will be placed *after* all the clones, with
6015 repeater intact.
6016 - the start days in the repeater in the original entry will be shifted
6017 to past the last clone.
6018 I this way you can spell out a number of instances of a repeating task,
6019 and still retain the repeater to cover future instances of the task."
6020 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6021 (let (beg end template task
6022 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6023 (if (not (and (integerp n) (> n 0)))
6024 (error "Invalid number of replications %s" n))
6025 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6026 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6027 shift)))
6028 (error "Invalid shift specification %s" shift))
6029 (when doshift
6030 (setq shift-n (string-to-number (match-string 1 shift))
6031 shift-what (cdr (assoc (match-string 2 shift)
6032 '(("d" . day) ("w" . week)
6033 ("m" . month) ("y" . year))))))
6034 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6035 (setq nmin 1 nmax n)
6036 (org-back-to-heading t)
6037 (setq beg (point))
6038 (org-end-of-subtree t t)
6039 (setq end (point))
6040 (setq template (buffer-substring beg end))
6041 (when (and doshift
6042 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6043 (delete-region beg end)
6044 (setq end beg)
6045 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6046 (goto-char end)
6047 (loop for n from nmin to nmax do
6048 (if (not doshift)
6049 (setq task template)
6050 (with-temp-buffer
6051 (insert template)
6052 (org-mode)
6053 (goto-char (point-min))
6054 (while (re-search-forward org-ts-regexp nil t)
6055 (org-timestamp-change (* n shift-n) shift-what))
6056 (unless (= n n-no-remove)
6057 (goto-char (point-min))
6058 (while (re-search-forward org-ts-regexp nil t)
6059 (save-excursion
6060 (goto-char (match-beginning 0))
6061 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6062 (delete-region (match-beginning 1) (match-end 1))))))
6063 (setq task (buffer-string))))
6064 (insert task))
6065 (goto-char beg)))
6067 ;;; Outline Sorting
6069 (defun org-sort (with-case)
6070 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6071 Optional argument WITH-CASE means sort case-sensitively.
6072 With a double prefix argument, also remove duplicate entries."
6073 (interactive "P")
6074 (if (org-at-table-p)
6075 (org-call-with-arg 'org-table-sort-lines with-case)
6076 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6078 (defun org-sort-remove-invisible (s)
6079 (remove-text-properties 0 (length s) org-rm-props s)
6080 (while (string-match org-bracket-link-regexp s)
6081 (setq s (replace-match (if (match-end 2)
6082 (match-string 3 s)
6083 (match-string 1 s)) t t s)))
6086 (defvar org-priority-regexp) ; defined later in the file
6088 (defvar org-after-sorting-entries-or-items-hook nil
6089 "Hook that is run after a bunch of entries or items have been sorted.
6090 When children are sorted, the cursor is in the parent line when this
6091 hook gets called. When a region or a plain list is sorted, the cursor
6092 will be in the first entry of the sorted region/list.")
6094 (defun org-sort-entries-or-items
6095 (&optional with-case sorting-type getkey-func compare-func property)
6096 "Sort entries on a certain level of an outline tree, or plain list items.
6097 If there is an active region, the entries in the region are sorted.
6098 Else, if the cursor is before the first entry, sort the top-level items.
6099 Else, the children of the entry at point are sorted.
6100 If the cursor is at the first item in a plain list, the list items will be
6101 sorted.
6103 Sorting can be alphabetically, numerically, by date/time as given by
6104 a time stamp, by a property or by priority.
6106 The command prompts for the sorting type unless it has been given to the
6107 function through the SORTING-TYPE argument, which needs to a character,
6108 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6109 precise meaning of each character:
6111 n Numerically, by converting the beginning of the entry/item to a number.
6112 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6113 t By date/time, either the first active time stamp in the entry, or, if
6114 none exist, by the first inactive one.
6115 In items, only the first line will be chekced.
6116 s By the scheduled date/time.
6117 d By deadline date/time.
6118 c By creation time, which is assumed to be the first inactive time stamp
6119 at the beginning of a line.
6120 p By priority according to the cookie.
6121 r By the value of a property.
6123 Capital letters will reverse the sort order.
6125 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6126 called with point at the beginning of the record. It must return either
6127 a string or a number that should serve as the sorting key for that record.
6129 Comparing entries ignores case by default. However, with an optional argument
6130 WITH-CASE, the sorting considers case as well."
6131 (interactive "P")
6132 (let ((case-func (if with-case 'identity 'downcase))
6133 start beg end stars re re2
6134 txt what tmp plain-list-p)
6135 ;; Find beginning and end of region to sort
6136 (cond
6137 ((org-region-active-p)
6138 ;; we will sort the region
6139 (setq end (region-end)
6140 what "region")
6141 (goto-char (region-beginning))
6142 (if (not (org-on-heading-p)) (outline-next-heading))
6143 (setq start (point)))
6144 ((org-at-item-p)
6145 ;; we will sort this plain list
6146 (org-beginning-of-item-list) (setq start (point))
6147 (org-end-of-item-list) (setq end (point))
6148 (goto-char start)
6149 (setq plain-list-p t
6150 what "plain list"))
6151 ((or (org-on-heading-p)
6152 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6153 ;; we will sort the children of the current headline
6154 (org-back-to-heading)
6155 (setq start (point)
6156 end (progn (org-end-of-subtree t t)
6157 (org-back-over-empty-lines)
6158 (point))
6159 what "children")
6160 (goto-char start)
6161 (show-subtree)
6162 (outline-next-heading))
6164 ;; we will sort the top-level entries in this file
6165 (goto-char (point-min))
6166 (or (org-on-heading-p) (outline-next-heading))
6167 (setq start (point) end (point-max) what "top-level")
6168 (goto-char start)
6169 (show-all)))
6171 (setq beg (point))
6172 (if (>= beg end) (error "Nothing to sort"))
6174 (unless plain-list-p
6175 (looking-at "\\(\\*+\\)")
6176 (setq stars (match-string 1)
6177 re (concat "^" (regexp-quote stars) " +")
6178 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6179 txt (buffer-substring beg end))
6180 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6181 (if (and (not (equal stars "*")) (string-match re2 txt))
6182 (error "Region to sort contains a level above the first entry")))
6184 (unless sorting-type
6185 (message
6186 (if plain-list-p
6187 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6188 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
6189 [t]ime [s ]cheduled [d]eadline [c]reated
6190 A/N/T/S/D/C/P/O/F means reversed:")
6191 what)
6192 (setq sorting-type (read-char-exclusive))
6194 (and (= (downcase sorting-type) ?f)
6195 (setq getkey-func
6196 (org-ido-completing-read "Sort using function: "
6197 obarray 'fboundp t nil nil))
6198 (setq getkey-func (intern getkey-func)))
6200 (and (= (downcase sorting-type) ?r)
6201 (setq property
6202 (org-ido-completing-read "Property: "
6203 (mapcar 'list (org-buffer-property-keys t))
6204 nil t))))
6206 (message "Sorting entries...")
6208 (save-restriction
6209 (narrow-to-region start end)
6211 (let ((dcst (downcase sorting-type))
6212 (case-fold-search nil)
6213 (now (current-time)))
6214 (sort-subr
6215 (/= dcst sorting-type)
6216 ;; This function moves to the beginning character of the "record" to
6217 ;; be sorted.
6218 (if plain-list-p
6219 (lambda nil
6220 (if (org-at-item-p) t (goto-char (point-max))))
6221 (lambda nil
6222 (if (re-search-forward re nil t)
6223 (goto-char (match-beginning 0))
6224 (goto-char (point-max)))))
6225 ;; This function moves to the last character of the "record" being
6226 ;; sorted.
6227 (if plain-list-p
6228 'org-end-of-item
6229 (lambda nil
6230 (save-match-data
6231 (condition-case nil
6232 (outline-forward-same-level 1)
6233 (error
6234 (goto-char (point-max)))))))
6236 ;; This function returns the value that gets sorted against.
6237 (if plain-list-p
6238 (lambda nil
6239 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6240 (cond
6241 ((= dcst ?n)
6242 (string-to-number (buffer-substring (match-end 0)
6243 (point-at-eol))))
6244 ((= dcst ?a)
6245 (buffer-substring (match-end 0) (point-at-eol)))
6246 ((= dcst ?t)
6247 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
6248 (re-search-forward org-ts-regexp-both
6249 (point-at-eol) t))
6250 (time-to-seconds
6251 (org-time-string-to-time (match-string 0)))
6252 (time-to-seconds now)))
6253 ((= dcst ?f)
6254 (if getkey-func
6255 (progn
6256 (setq tmp (funcall getkey-func))
6257 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6258 tmp)
6259 (error "Invalid key function `%s'" getkey-func)))
6260 (t (error "Invalid sorting type `%c'" sorting-type)))))
6261 (lambda nil
6262 (cond
6263 ((= dcst ?n)
6264 (if (looking-at org-complex-heading-regexp)
6265 (string-to-number (match-string 4))
6266 nil))
6267 ((= dcst ?a)
6268 (if (looking-at org-complex-heading-regexp)
6269 (funcall case-func (match-string 4))
6270 nil))
6271 ((= dcst ?t)
6272 (let ((end (save-excursion (outline-next-heading) (point))))
6273 (if (or (re-search-forward org-ts-regexp end t)
6274 (re-search-forward org-ts-regexp-both end t))
6275 (org-time-string-to-time (match-string 0))
6276 (org-time-string-to-time now))))
6277 ((= dcst ?c)
6278 (let ((end (save-excursion (outline-next-heading) (point))))
6279 (if (re-search-forward
6280 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
6281 end t)
6282 (time-to-seconds (org-time-string-to-time
6283 (match-string 0)))
6284 (time-to-seconds now))))
6285 ((= dcst ?s)
6286 (let ((end (save-excursion (outline-next-heading) (point))))
6287 (if (re-search-forward org-scheduled-time-regexp end t)
6288 (org-time-string-to-time (match-string 1))
6289 (org-time-string-to-time now))))
6290 ((= dcst ?d)
6291 (let ((end (save-excursion (outline-next-heading) (point))))
6292 (if (re-search-forward org-deadline-time-regexp end t)
6293 (org-time-string-to-time (match-string 1))
6294 (org-time-string-to-time now))))
6295 ((= dcst ?p)
6296 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6297 (string-to-char (match-string 2))
6298 org-default-priority))
6299 ((= dcst ?r)
6300 (or (org-entry-get nil property) ""))
6301 ((= dcst ?o)
6302 (if (looking-at org-complex-heading-regexp)
6303 (- 9999 (length (member (match-string 2)
6304 org-todo-keywords-1)))))
6305 ((= dcst ?f)
6306 (if getkey-func
6307 (progn
6308 (setq tmp (funcall getkey-func))
6309 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6310 tmp)
6311 (error "Invalid key function `%s'" getkey-func)))
6312 (t (error "Invalid sorting type `%c'" sorting-type)))))
6314 (cond
6315 ((= dcst ?a) 'string<)
6316 ((= dcst ?t) 'time-less-p)
6317 ((= dcst ?f) compare-func)
6318 ((= dcst ?p) '<)
6319 (t nil)))))
6320 (run-hooks 'org-after-sorting-entries-or-items-hook)
6321 (message "Sorting entries...done")))
6323 (defun org-do-sort (table what &optional with-case sorting-type)
6324 "Sort TABLE of WHAT according to SORTING-TYPE.
6325 The user will be prompted for the SORTING-TYPE if the call to this
6326 function does not specify it. WHAT is only for the prompt, to indicate
6327 what is being sorted. The sorting key will be extracted from
6328 the car of the elements of the table.
6329 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6330 (unless sorting-type
6331 (message
6332 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6333 what)
6334 (setq sorting-type (read-char-exclusive)))
6335 (let ((dcst (downcase sorting-type))
6336 extractfun comparefun)
6337 ;; Define the appropriate functions
6338 (cond
6339 ((= dcst ?n)
6340 (setq extractfun 'string-to-number
6341 comparefun (if (= dcst sorting-type) '< '>)))
6342 ((= dcst ?a)
6343 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6344 (lambda(x) (downcase (org-sort-remove-invisible x))))
6345 comparefun (if (= dcst sorting-type)
6346 'string<
6347 (lambda (a b) (and (not (string< a b))
6348 (not (string= a b)))))))
6349 ((= dcst ?t)
6350 (setq extractfun
6351 (lambda (x)
6352 (if (or (string-match org-ts-regexp x)
6353 (string-match org-ts-regexp-both x))
6354 (time-to-seconds
6355 (org-time-string-to-time (match-string 0 x)))
6357 comparefun (if (= dcst sorting-type) '< '>)))
6358 (t (error "Invalid sorting type `%c'" sorting-type)))
6360 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6361 table)
6362 (lambda (a b) (funcall comparefun (car a) (car b))))))
6364 ;;; Editing source examples
6366 (defvar org-exit-edit-mode-map (make-sparse-keymap))
6367 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
6368 (defvar org-edit-src-force-single-line nil)
6369 (defvar org-edit-src-from-org-mode nil)
6370 (defvar org-edit-src-picture nil)
6371 (defvar org-edit-src-beg-marker nil)
6372 (defvar org-edit-src-end-marker nil)
6374 (define-minor-mode org-exit-edit-mode
6375 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
6377 (defun org-edit-src-code ()
6378 "Edit the source code example at point.
6379 The example is copied to a separate buffer, and that buffer is switched
6380 to the correct language mode. When done, exit with \\[org-edit-src-exit].
6381 This will remove the original code in the Org buffer, and replace it with
6382 the edited version."
6383 (interactive)
6384 (let ((line (org-current-line))
6385 (case-fold-search t)
6386 (msg (substitute-command-keys
6387 "Edit, then exit with C-c ' (C-c and single quote)"))
6388 (info (org-edit-src-find-region-and-lang))
6389 (org-mode-p (eq major-mode 'org-mode))
6390 (beg (make-marker))
6391 (end (make-marker))
6392 ovl lang lang-f single lfmt code begline buffer)
6393 (if (not info)
6395 (setq beg (move-marker beg (nth 0 info))
6396 end (move-marker end (nth 1 info))
6397 code (buffer-substring-no-properties beg end)
6398 lang (nth 2 info)
6399 single (nth 3 info)
6400 lfmt (nth 4 info)
6401 lang-f (intern (concat lang "-mode"))
6402 begline (save-excursion (goto-char beg) (org-current-line)))
6403 (unless (functionp lang-f)
6404 (error "No such language mode: %s" lang-f))
6405 (goto-line line)
6406 (if (and (setq buffer (org-edit-src-find-buffer beg end))
6407 (y-or-n-p "Return to existing edit buffer? [n] will revert changes: "))
6408 (switch-to-buffer buffer)
6409 (when buffer
6410 (with-current-buffer buffer
6411 (if (boundp 'org-edit-src-overlay)
6412 (org-delete-overlay org-edit-src-overlay)))
6413 (kill-buffer buffer))
6414 (setq buffer (generate-new-buffer "*Org Edit Src Example*"))
6415 (setq ovl (org-make-overlay beg end))
6416 (org-overlay-put ovl 'face 'secondary-selection)
6417 (org-overlay-put ovl 'edit-buffer buffer)
6418 (org-overlay-put ovl 'help-echo "Click with mouse-1 to switch to buffer editing this segment")
6419 (org-overlay-put ovl 'face 'secondary-selection)
6420 (org-overlay-put ovl
6421 'keymap
6422 (let ((map (make-sparse-keymap)))
6423 (define-key map [mouse-1] 'org-edit-src-continue)
6424 map))
6425 (org-overlay-put ovl :read-only "Leave me alone")
6426 (switch-to-buffer buffer)
6427 (insert code)
6428 (remove-text-properties (point-min) (point-max)
6429 '(display nil invisible nil intangible nil))
6430 (let ((org-inhibit-startup t))
6431 (funcall lang-f))
6432 (set (make-local-variable 'org-edit-src-force-single-line) single)
6433 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6434 (when lfmt
6435 (set (make-local-variable 'org-coderef-label-format) lfmt))
6436 (when org-mode-p
6437 (goto-char (point-min))
6438 (while (re-search-forward "^," nil t)
6439 (replace-match "")))
6440 (goto-line (1+ (- line begline)))
6441 (org-exit-edit-mode)
6442 (org-set-local 'org-edit-src-beg-marker beg)
6443 (org-set-local 'org-edit-src-end-marker end)
6444 (org-set-local 'org-edit-src-overlay ovl)
6445 (and org-edit-src-persistent-message
6446 (org-set-local 'header-line-format msg)))
6447 (message "%s" msg)
6448 t)))
6450 (defun org-edit-src-continue (e)
6451 (interactive "e")
6452 (mouse-set-point e)
6453 (let ((buf (get-char-property (point) 'edit-buffer)))
6454 (if buf (switch-to-buffer buf)
6455 (error "Something is wrong here"))))
6457 (defun org-edit-src-find-buffer (beg end)
6458 "Find a source editing buffer that is already editing the region BEG to END."
6459 (catch 'exit
6460 (mapc
6461 (lambda (b)
6462 (with-current-buffer b
6463 (if (and (string-match "\\`*Org Edit " (buffer-name))
6464 (local-variable-p 'org-edit-src-beg-marker (current-buffer))
6465 (local-variable-p 'org-edit-src-end-marker (current-buffer))
6466 (equal beg org-edit-src-beg-marker)
6467 (equal end org-edit-src-end-marker))
6468 (throw 'exit (current-buffer)))))
6469 (buffer-list))
6470 nil))
6472 (defun org-edit-fixed-width-region ()
6473 "Edit the fixed-width ascii drawing at point.
6474 This must be a region where each line starts with a colon followed by
6475 a space character.
6476 An new buffer is created and the fixed-width region is copied into it,
6477 and the buffer is switched into `artist-mode' for editing. When done,
6478 exit with \\[org-edit-src-exit]. The edited text will then replace
6479 the fragment in the Org-mode buffer."
6480 (interactive)
6481 (let ((line (org-current-line))
6482 (case-fold-search t)
6483 (msg (substitute-command-keys
6484 "Edit, then exit with C-c ' (C-c and single quote)"))
6485 (org-mode-p (eq major-mode 'org-mode))
6486 (beg (make-marker))
6487 (end (make-marker))
6488 ovl beg1 end1 code begline buffer)
6489 (beginning-of-line 1)
6490 (if (looking-at "[ \t]*[^:\n \t]")
6492 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
6493 (setq beg1 (point) end1 beg1)
6494 (save-excursion
6495 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
6496 (setq beg1 (point-at-bol 2))
6497 (setq beg1 (point))))
6498 (save-excursion
6499 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
6500 (setq end1 (1- (match-beginning 0)))
6501 (setq end1 (point))))
6502 (goto-line line))
6503 (setq beg (move-marker beg beg1)
6504 end (move-marker end end1)
6505 code (buffer-substring-no-properties beg end)
6506 begline (save-excursion (goto-char beg) (org-current-line)))
6507 (if (and (setq buffer (org-edit-src-find-buffer beg end))
6508 (y-or-n-p "Return to existing edit buffer? [n] will revert changes: "))
6509 (switch-to-buffer buffer)
6510 (when buffer
6511 (with-current-buffer buffer
6512 (if (boundp 'org-edit-src-overlay)
6513 (org-delete-overlay org-edit-src-overlay)))
6514 (kill-buffer buffer))
6515 (setq buffer (generate-new-buffer "*Org Edit Src Example*"))
6516 (setq ovl (org-make-overlay beg end))
6517 (org-overlay-put ovl 'face 'secondary-selection)
6518 (org-overlay-put ovl 'edit-buffer buffer)
6519 (org-overlay-put ovl 'help-echo "Click with mouse-1 to switch to buffer editing this segment")
6520 (org-overlay-put ovl 'face 'secondary-selection)
6521 (org-overlay-put ovl
6522 'keymap
6523 (let ((map (make-sparse-keymap)))
6524 (define-key map [mouse-1] 'org-edit-src-continue)
6525 map))
6526 (org-overlay-put ovl :read-only "Leave me alone")
6527 (switch-to-buffer buffer)
6528 (insert code)
6529 (remove-text-properties (point-min) (point-max)
6530 '(display nil invisible nil intangible nil))
6531 (cond
6532 ((eq org-edit-fixed-width-region-mode 'artist-mode)
6533 (fundamental-mode)
6534 (artist-mode 1))
6535 (t (funcall org-edit-fixed-width-region-mode)))
6536 (set (make-local-variable 'org-edit-src-force-single-line) nil)
6537 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6538 (set (make-local-variable 'org-edit-src-picture) t)
6539 (goto-char (point-min))
6540 (while (re-search-forward "^[ \t]*: ?" nil t)
6541 (replace-match ""))
6542 (goto-line (1+ (- line begline)))
6543 (org-exit-edit-mode)
6544 (org-set-local 'org-edit-src-beg-marker beg)
6545 (org-set-local 'org-edit-src-end-marker end)
6546 (org-set-local 'org-edit-src-overlay ovl)
6547 (and org-edit-src-persistent-message
6548 (org-set-local 'header-line-format msg)))
6549 (message "%s" msg)
6550 t)))
6552 (defun org-edit-src-find-region-and-lang ()
6553 "Find the region and language for a local edit.
6554 Return a list with beginning and end of the region, a string representing
6555 the language, a switch telling of the content should be in a single line."
6556 (let ((re-list
6557 (append
6558 org-edit-src-region-extra
6560 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
6561 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
6562 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
6563 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
6564 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
6565 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
6566 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
6567 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
6568 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
6569 ("^#\\+html:" "\n" "html" single-line)
6570 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
6571 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
6572 ("^#\\+latex:" "\n" "latex" single-line)
6573 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
6574 ("^#\\+ascii:" "\n" "ascii" single-line)
6576 (pos (point))
6577 re1 re2 single beg end lang lfmt match-re1)
6578 (catch 'exit
6579 (while (setq entry (pop re-list))
6580 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
6581 single (nth 3 entry))
6582 (save-excursion
6583 (if (or (looking-at re1)
6584 (re-search-backward re1 nil t))
6585 (progn
6586 (setq match-re1 (match-string 0))
6587 (setq beg (match-end 0)
6588 lang (org-edit-src-get-lang lang)
6589 lfmt (org-edit-src-get-label-format match-re1))
6590 (if (and (re-search-forward re2 nil t)
6591 (>= (match-end 0) pos))
6592 (throw 'exit (list beg (match-beginning 0)
6593 lang single lfmt))))
6594 (if (or (looking-at re2)
6595 (re-search-forward re2 nil t))
6596 (progn
6597 (setq end (match-beginning 0))
6598 (if (and (re-search-backward re1 nil t)
6599 (<= (match-beginning 0) pos))
6600 (progn
6601 (setq lfmt (org-edit-src-get-label-format
6602 (match-string 0)))
6603 (throw 'exit
6604 (list (match-end 0) end
6605 (org-edit-src-get-lang lang)
6606 single lfmt))))))))))))
6608 (defun org-edit-src-get-lang (lang)
6609 "Extract the src language."
6610 (let ((m (match-string 0)))
6611 (cond
6612 ((stringp lang) lang)
6613 ((integerp lang) (match-string lang))
6614 ((and (eq lang 'lang)
6615 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
6616 (match-string 1 m))
6617 ((and (eq lang 'style)
6618 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
6619 (match-string 1 m))
6620 (t "fundamental"))))
6622 (defun org-edit-src-get-label-format (s)
6623 "Extract the label format."
6624 (save-match-data
6625 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
6626 (match-string 1 s))))
6628 (defun org-edit-src-exit ()
6629 "Exit special edit and protect problematic lines."
6630 (interactive)
6631 (unless (string-match "\\`*Org Edit " (buffer-name (current-buffer)))
6632 (error "This is not an sub-editing buffer, something is wrong..."))
6633 (let ((line (if (org-bound-and-true-p org-edit-src-force-single-line)
6635 (org-current-line)))
6636 (beg org-edit-src-beg-marker)
6637 (end org-edit-src-end-marker)
6638 (ovl org-edit-src-overlay)
6639 (buffer (current-buffer))
6640 code)
6641 (goto-char (point-min))
6642 (if (looking-at "[ \t\n]*\n") (replace-match ""))
6643 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
6644 (when (org-bound-and-true-p org-edit-src-force-single-line)
6645 (goto-char (point-min))
6646 (while (re-search-forward "\n" nil t)
6647 (replace-match " "))
6648 (goto-char (point-min))
6649 (if (looking-at "\\s-*") (replace-match " "))
6650 (if (re-search-forward "\\s-+\\'" nil t)
6651 (replace-match "")))
6652 (when (org-bound-and-true-p org-edit-src-from-org-mode)
6653 (goto-char (point-min))
6654 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
6655 (replace-match ",\\1"))
6656 (when font-lock-mode
6657 (font-lock-unfontify-region (point-min) (point-max)))
6658 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6659 (when (org-bound-and-true-p org-edit-src-picture)
6660 (untabify (point-min) (point-max))
6661 (goto-char (point-min))
6662 (while (re-search-forward "^" nil t)
6663 (replace-match ": "))
6664 (when font-lock-mode
6665 (font-lock-unfontify-region (point-min) (point-max)))
6666 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6667 (setq code (buffer-string))
6668 (switch-to-buffer (marker-buffer beg))
6669 (kill-buffer buffer)
6670 (goto-char beg)
6671 (org-delete-overlay ovl)
6672 (delete-region beg end)
6673 (insert code)
6674 (goto-char beg)
6675 (goto-line (1- (+ (org-current-line) line)))
6676 (move-marker beg nil)
6677 (move-marker end nil)))
6680 ;;; The orgstruct minor mode
6682 ;; Define a minor mode which can be used in other modes in order to
6683 ;; integrate the org-mode structure editing commands.
6685 ;; This is really a hack, because the org-mode structure commands use
6686 ;; keys which normally belong to the major mode. Here is how it
6687 ;; works: The minor mode defines all the keys necessary to operate the
6688 ;; structure commands, but wraps the commands into a function which
6689 ;; tests if the cursor is currently at a headline or a plain list
6690 ;; item. If that is the case, the structure command is used,
6691 ;; temporarily setting many Org-mode variables like regular
6692 ;; expressions for filling etc. However, when any of those keys is
6693 ;; used at a different location, function uses `key-binding' to look
6694 ;; up if the key has an associated command in another currently active
6695 ;; keymap (minor modes, major mode, global), and executes that
6696 ;; command. There might be problems if any of the keys is otherwise
6697 ;; used as a prefix key.
6699 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6700 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6701 ;; addresses this by checking explicitly for both bindings.
6703 (defvar orgstruct-mode-map (make-sparse-keymap)
6704 "Keymap for the minor `orgstruct-mode'.")
6706 (defvar org-local-vars nil
6707 "List of local variables, for use by `orgstruct-mode'")
6709 ;;;###autoload
6710 (define-minor-mode orgstruct-mode
6711 "Toggle the minor more `orgstruct-mode'.
6712 This mode is for using Org-mode structure commands in other modes.
6713 The following key behave as if Org-mode was active, if the cursor
6714 is on a headline, or on a plain list item (both in the definition
6715 of Org-mode).
6717 M-up Move entry/item up
6718 M-down Move entry/item down
6719 M-left Promote
6720 M-right Demote
6721 M-S-up Move entry/item up
6722 M-S-down Move entry/item down
6723 M-S-left Promote subtree
6724 M-S-right Demote subtree
6725 M-q Fill paragraph and items like in Org-mode
6726 C-c ^ Sort entries
6727 C-c - Cycle list bullet
6728 TAB Cycle item visibility
6729 M-RET Insert new heading/item
6730 S-M-RET Insert new TODO heading / Checkbox item
6731 C-c C-c Set tags / toggle checkbox"
6732 nil " OrgStruct" nil
6733 (org-load-modules-maybe)
6734 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6736 ;;;###autoload
6737 (defun turn-on-orgstruct ()
6738 "Unconditionally turn on `orgstruct-mode'."
6739 (orgstruct-mode 1))
6741 (defun orgstruct++-mode (&optional arg)
6742 "Toggle `orgstruct-mode', the enhanced version of it.
6743 In addition to setting orgstruct-mode, this also exports all indentation and
6744 autofilling variables from org-mode into the buffer. It will also
6745 recognize item context in multiline items.
6746 Note that turning off orgstruct-mode will *not* remove the
6747 indentation/paragraph settings. This can only be done by refreshing the
6748 major mode, for example with \[normal-mode]."
6749 (interactive "P")
6750 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6751 (if (< arg 1)
6752 (orgstruct-mode -1)
6753 (orgstruct-mode 1)
6754 (let (var val)
6755 (mapc
6756 (lambda (x)
6757 (when (string-match
6758 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6759 (symbol-name (car x)))
6760 (setq var (car x) val (nth 1 x))
6761 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6762 org-local-vars)
6763 (org-set-local 'orgstruct-is-++ t))))
6765 (defvar orgstruct-is-++ nil
6766 "Is orgstruct-mode in ++ version in the current-buffer?")
6767 (make-variable-buffer-local 'orgstruct-is-++)
6769 ;;;###autoload
6770 (defun turn-on-orgstruct++ ()
6771 "Unconditionally turn on `orgstruct++-mode'."
6772 (orgstruct++-mode 1))
6774 (defun orgstruct-error ()
6775 "Error when there is no default binding for a structure key."
6776 (interactive)
6777 (error "This key has no function outside structure elements"))
6779 (defun orgstruct-setup ()
6780 "Setup orgstruct keymaps."
6781 (let ((nfunc 0)
6782 (bindings
6783 (list
6784 '([(meta up)] org-metaup)
6785 '([(meta down)] org-metadown)
6786 '([(meta left)] org-metaleft)
6787 '([(meta right)] org-metaright)
6788 '([(meta shift up)] org-shiftmetaup)
6789 '([(meta shift down)] org-shiftmetadown)
6790 '([(meta shift left)] org-shiftmetaleft)
6791 '([(meta shift right)] org-shiftmetaright)
6792 '([(shift up)] org-shiftup)
6793 '([(shift down)] org-shiftdown)
6794 '([(shift left)] org-shiftleft)
6795 '([(shift right)] org-shiftright)
6796 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6797 '("\M-q" fill-paragraph)
6798 '("\C-c^" org-sort)
6799 '("\C-c-" org-cycle-list-bullet)))
6800 elt key fun cmd)
6801 (while (setq elt (pop bindings))
6802 (setq nfunc (1+ nfunc))
6803 (setq key (org-key (car elt))
6804 fun (nth 1 elt)
6805 cmd (orgstruct-make-binding fun nfunc key))
6806 (org-defkey orgstruct-mode-map key cmd))
6808 ;; Special treatment needed for TAB and RET
6809 (org-defkey orgstruct-mode-map [(tab)]
6810 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6811 (org-defkey orgstruct-mode-map "\C-i"
6812 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6814 (org-defkey orgstruct-mode-map "\M-\C-m"
6815 (orgstruct-make-binding 'org-insert-heading 105
6816 "\M-\C-m" [(meta return)]))
6817 (org-defkey orgstruct-mode-map [(meta return)]
6818 (orgstruct-make-binding 'org-insert-heading 106
6819 [(meta return)] "\M-\C-m"))
6821 (org-defkey orgstruct-mode-map [(shift meta return)]
6822 (orgstruct-make-binding 'org-insert-todo-heading 107
6823 [(meta return)] "\M-\C-m"))
6825 (unless org-local-vars
6826 (setq org-local-vars (org-get-local-variables)))
6830 (defun orgstruct-make-binding (fun n &rest keys)
6831 "Create a function for binding in the structure minor mode.
6832 FUN is the command to call inside a table. N is used to create a unique
6833 command name. KEYS are keys that should be checked in for a command
6834 to execute outside of tables."
6835 (eval
6836 (list 'defun
6837 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6838 '(arg)
6839 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6840 "Outside of structure, run the binding of `"
6841 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6842 "'.")
6843 '(interactive "p")
6844 (list 'if
6845 `(org-context-p 'headline 'item
6846 (and orgstruct-is-++
6847 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
6848 'item-body))
6849 (list 'org-run-like-in-org-mode (list 'quote fun))
6850 (list 'let '(orgstruct-mode)
6851 (list 'call-interactively
6852 (append '(or)
6853 (mapcar (lambda (k)
6854 (list 'key-binding k))
6855 keys)
6856 '('orgstruct-error))))))))
6858 (defun org-context-p (&rest contexts)
6859 "Check if local context is any of CONTEXTS.
6860 Possible values in the list of contexts are `table', `headline', and `item'."
6861 (let ((pos (point)))
6862 (goto-char (point-at-bol))
6863 (prog1 (or (and (memq 'table contexts)
6864 (looking-at "[ \t]*|"))
6865 (and (memq 'headline contexts)
6866 ;;????????? (looking-at "\\*+"))
6867 (looking-at outline-regexp))
6868 (and (memq 'item contexts)
6869 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
6870 (and (memq 'item-body contexts)
6871 (org-in-item-p)))
6872 (goto-char pos))))
6874 (defun org-get-local-variables ()
6875 "Return a list of all local variables in an org-mode buffer."
6876 (let (varlist)
6877 (with-current-buffer (get-buffer-create "*Org tmp*")
6878 (erase-buffer)
6879 (org-mode)
6880 (setq varlist (buffer-local-variables)))
6881 (kill-buffer "*Org tmp*")
6882 (delq nil
6883 (mapcar
6884 (lambda (x)
6885 (setq x
6886 (if (symbolp x)
6887 (list x)
6888 (list (car x) (list 'quote (cdr x)))))
6889 (if (string-match
6890 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6891 (symbol-name (car x)))
6892 x nil))
6893 varlist))))
6895 ;;;###autoload
6896 (defun org-run-like-in-org-mode (cmd)
6897 "Run a command, pretending that the current buffer is in Org-mode.
6898 This will temporarily bind local variables that are typically bound in
6899 Org-mode to the values they have in Org-mode, and then interactively
6900 call CMD."
6901 (org-load-modules-maybe)
6902 (unless org-local-vars
6903 (setq org-local-vars (org-get-local-variables)))
6904 (eval (list 'let org-local-vars
6905 (list 'call-interactively (list 'quote cmd)))))
6907 ;;;; Archiving
6909 (defun org-get-category (&optional pos)
6910 "Get the category applying to position POS."
6911 (get-text-property (or pos (point)) 'org-category))
6913 (defun org-refresh-category-properties ()
6914 "Refresh category text properties in the buffer."
6915 (let ((def-cat (cond
6916 ((null org-category)
6917 (if buffer-file-name
6918 (file-name-sans-extension
6919 (file-name-nondirectory buffer-file-name))
6920 "???"))
6921 ((symbolp org-category) (symbol-name org-category))
6922 (t org-category)))
6923 beg end cat pos optionp)
6924 (org-unmodified
6925 (save-excursion
6926 (save-restriction
6927 (widen)
6928 (goto-char (point-min))
6929 (put-text-property (point) (point-max) 'org-category def-cat)
6930 (while (re-search-forward
6931 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6932 (setq pos (match-end 0)
6933 optionp (equal (char-after (match-beginning 0)) ?#)
6934 cat (org-trim (match-string 2)))
6935 (if optionp
6936 (setq beg (point-at-bol) end (point-max))
6937 (org-back-to-heading t)
6938 (setq beg (point) end (org-end-of-subtree t t)))
6939 (put-text-property beg end 'org-category cat)
6940 (goto-char pos)))))))
6943 ;;;; Link Stuff
6945 ;;; Link abbreviations
6947 (defun org-link-expand-abbrev (link)
6948 "Apply replacements as defined in `org-link-abbrev-alist."
6949 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6950 (let* ((key (match-string 1 link))
6951 (as (or (assoc key org-link-abbrev-alist-local)
6952 (assoc key org-link-abbrev-alist)))
6953 (tag (and (match-end 2) (match-string 3 link)))
6954 rpl)
6955 (if (not as)
6956 link
6957 (setq rpl (cdr as))
6958 (cond
6959 ((symbolp rpl) (funcall rpl tag))
6960 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6961 ((string-match "%h" rpl)
6962 (replace-match (url-hexify-string (or tag "")) t t rpl))
6963 (t (concat rpl tag)))))
6964 link))
6966 ;;; Storing and inserting links
6968 (defvar org-insert-link-history nil
6969 "Minibuffer history for links inserted with `org-insert-link'.")
6971 (defvar org-stored-links nil
6972 "Contains the links stored with `org-store-link'.")
6974 (defvar org-store-link-plist nil
6975 "Plist with info about the most recently link created with `org-store-link'.")
6977 (defvar org-link-protocols nil
6978 "Link protocols added to Org-mode using `org-add-link-type'.")
6980 (defvar org-store-link-functions nil
6981 "List of functions that are called to create and store a link.
6982 Each function will be called in turn until one returns a non-nil
6983 value. Each function should check if it is responsible for creating
6984 this link (for example by looking at the major mode).
6985 If not, it must exit and return nil.
6986 If yes, it should return a non-nil value after a calling
6987 `org-store-link-props' with a list of properties and values.
6988 Special properties are:
6990 :type The link prefix. like \"http\". This must be given.
6991 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6992 This is obligatory as well.
6993 :description Optional default description for the second pair
6994 of brackets in an Org-mode link. The user can still change
6995 this when inserting this link into an Org-mode buffer.
6997 In addition to these, any additional properties can be specified
6998 and then used in remember templates.")
7000 (defun org-add-link-type (type &optional follow export)
7001 "Add TYPE to the list of `org-link-types'.
7002 Re-compute all regular expressions depending on `org-link-types'
7004 FOLLOW and EXPORT are two functions.
7006 FOLLOW should take the link path as the single argument and do whatever
7007 is necessary to follow the link, for example find a file or display
7008 a mail message.
7010 EXPORT should format the link path for export to one of the export formats.
7011 It should be a function accepting three arguments:
7013 path the path of the link, the text after the prefix (like \"http:\")
7014 desc the description of the link, if any, nil if there was no description
7015 format the export format, a symbol like `html' or `latex'.
7017 The function may use the FORMAT information to return different values
7018 depending on the format. The return value will be put literally into
7019 the exported file.
7020 Org-mode has a built-in default for exporting links. If you are happy with
7021 this default, there is no need to define an export function for the link
7022 type. For a simple example of an export function, see `org-bbdb.el'."
7023 (add-to-list 'org-link-types type t)
7024 (org-make-link-regexps)
7025 (if (assoc type org-link-protocols)
7026 (setcdr (assoc type org-link-protocols) (list follow export))
7027 (push (list type follow export) org-link-protocols)))
7029 ;;;###autoload
7030 (defun org-store-link (arg)
7031 "\\<org-mode-map>Store an org-link to the current location.
7032 This link is added to `org-stored-links' and can later be inserted
7033 into an org-buffer with \\[org-insert-link].
7035 For some link types, a prefix arg is interpreted:
7036 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7037 For file links, arg negates `org-context-in-file-links'."
7038 (interactive "P")
7039 (org-load-modules-maybe)
7040 (setq org-store-link-plist nil) ; reset
7041 (let (link cpltxt desc description search txt custom-id)
7042 (cond
7044 ((run-hook-with-args-until-success 'org-store-link-functions)
7045 (setq link (plist-get org-store-link-plist :link)
7046 desc (or (plist-get org-store-link-plist :description) link)))
7048 ((equal (buffer-name) "*Org Edit Src Example*")
7049 (let (label gc)
7050 (while (or (not label)
7051 (save-excursion
7052 (save-restriction
7053 (widen)
7054 (goto-char (point-min))
7055 (re-search-forward
7056 (regexp-quote (format org-coderef-label-format label))
7057 nil t))))
7058 (when label (message "Label exists already") (sit-for 2))
7059 (setq label (read-string "Code line label: " label)))
7060 (end-of-line 1)
7061 (setq link (format org-coderef-label-format label))
7062 (setq gc (- 79 (length link)))
7063 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7064 (insert link)
7065 (setq link (concat "(" label ")") desc nil)))
7067 ((eq major-mode 'calendar-mode)
7068 (let ((cd (calendar-cursor-to-date)))
7069 (setq link
7070 (format-time-string
7071 (car org-time-stamp-formats)
7072 (apply 'encode-time
7073 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7074 nil nil nil))))
7075 (org-store-link-props :type "calendar" :date cd)))
7077 ((eq major-mode 'w3-mode)
7078 (setq cpltxt (if (and (buffer-name)
7079 (not (string-match "Untitled" (buffer-name))))
7080 (buffer-name)
7081 (url-view-url t))
7082 link (org-make-link (url-view-url t)))
7083 (org-store-link-props :type "w3" :url (url-view-url t)))
7085 ((eq major-mode 'w3m-mode)
7086 (setq cpltxt (or w3m-current-title w3m-current-url)
7087 link (org-make-link w3m-current-url))
7088 (org-store-link-props :type "w3m" :url (url-view-url t)))
7090 ((setq search (run-hook-with-args-until-success
7091 'org-create-file-search-functions))
7092 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7093 "::" search))
7094 (setq cpltxt (or description link)))
7096 ((eq major-mode 'image-mode)
7097 (setq cpltxt (concat "file:"
7098 (abbreviate-file-name buffer-file-name))
7099 link (org-make-link cpltxt))
7100 (org-store-link-props :type "image" :file buffer-file-name))
7102 ((eq major-mode 'dired-mode)
7103 ;; link to the file in the current line
7104 (setq cpltxt (concat "file:"
7105 (abbreviate-file-name
7106 (expand-file-name
7107 (dired-get-filename nil t))))
7108 link (org-make-link cpltxt)))
7110 ((and buffer-file-name (org-mode-p))
7111 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7112 (cond
7113 ((org-in-regexp "<<\\(.*?\\)>>")
7114 (setq cpltxt
7115 (concat "file:"
7116 (abbreviate-file-name buffer-file-name)
7117 "::" (match-string 1))
7118 link (org-make-link cpltxt)))
7119 ((and (featurep 'org-id)
7120 (or (eq org-link-to-org-use-id t)
7121 (and (eq org-link-to-org-use-id 'create-if-interactive)
7122 (interactive-p))
7123 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7124 (interactive-p)
7125 (not custom-id))
7126 (and org-link-to-org-use-id
7127 (condition-case nil
7128 (org-entry-get nil "ID")
7129 (error nil)))))
7130 ;; We can make a link using the ID.
7131 (setq link (condition-case nil
7132 (prog1 (org-id-store-link)
7133 (setq desc (plist-get org-store-link-plist
7134 :description)))
7135 (error
7136 ;; probably before first headline, link to file only
7137 (concat "file:"
7138 (abbreviate-file-name buffer-file-name))))))
7140 ;; Just link to current headline
7141 (setq cpltxt (concat "file:"
7142 (abbreviate-file-name buffer-file-name)))
7143 ;; Add a context search string
7144 (when (org-xor org-context-in-file-links arg)
7145 (setq txt (cond
7146 ((org-on-heading-p) nil)
7147 ((org-region-active-p)
7148 (buffer-substring (region-beginning) (region-end)))
7149 (t nil)))
7150 (when (or (null txt) (string-match "\\S-" txt))
7151 (setq cpltxt
7152 (concat cpltxt "::"
7153 (condition-case nil
7154 (org-make-org-heading-search-string txt)
7155 (error "")))
7156 desc "NONE")))
7157 (if (string-match "::\\'" cpltxt)
7158 (setq cpltxt (substring cpltxt 0 -2)))
7159 (setq link (org-make-link cpltxt)))))
7161 ((buffer-file-name (buffer-base-buffer))
7162 ;; Just link to this file here.
7163 (setq cpltxt (concat "file:"
7164 (abbreviate-file-name
7165 (buffer-file-name (buffer-base-buffer)))))
7166 ;; Add a context string
7167 (when (org-xor org-context-in-file-links arg)
7168 (setq txt (if (org-region-active-p)
7169 (buffer-substring (region-beginning) (region-end))
7170 (buffer-substring (point-at-bol) (point-at-eol))))
7171 ;; Only use search option if there is some text.
7172 (when (string-match "\\S-" txt)
7173 (setq cpltxt
7174 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7175 desc "NONE")))
7176 (setq link (org-make-link cpltxt)))
7178 ((interactive-p)
7179 (error "Cannot link to a buffer which is not visiting a file"))
7181 (t (setq link nil)))
7183 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7184 (setq link (or link cpltxt)
7185 desc (or desc cpltxt))
7186 (if (equal desc "NONE") (setq desc nil))
7188 (if (and (interactive-p) link)
7189 (progn
7190 (setq org-stored-links
7191 (cons (list link desc) org-stored-links))
7192 (message "Stored: %s" (or desc link))
7193 (when custom-id
7194 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7195 "::#" custom-id))
7196 (setq org-stored-links
7197 (cons (list link desc) org-stored-links))))
7198 (and link (org-make-link-string link desc)))))
7200 (defun org-store-link-props (&rest plist)
7201 "Store link properties, extract names and addresses."
7202 (let (x adr)
7203 (when (setq x (plist-get plist :from))
7204 (setq adr (mail-extract-address-components x))
7205 (setq plist (plist-put plist :fromname (car adr)))
7206 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7207 (when (setq x (plist-get plist :to))
7208 (setq adr (mail-extract-address-components x))
7209 (setq plist (plist-put plist :toname (car adr)))
7210 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7211 (let ((from (plist-get plist :from))
7212 (to (plist-get plist :to)))
7213 (when (and from to org-from-is-user-regexp)
7214 (setq plist
7215 (plist-put plist :fromto
7216 (if (string-match org-from-is-user-regexp from)
7217 (concat "to %t")
7218 (concat "from %f"))))))
7219 (setq org-store-link-plist plist))
7221 (defun org-add-link-props (&rest plist)
7222 "Add these properties to the link property list."
7223 (let (key value)
7224 (while plist
7225 (setq key (pop plist) value (pop plist))
7226 (setq org-store-link-plist
7227 (plist-put org-store-link-plist key value)))))
7229 (defun org-email-link-description (&optional fmt)
7230 "Return the description part of an email link.
7231 This takes information from `org-store-link-plist' and formats it
7232 according to FMT (default from `org-email-link-description-format')."
7233 (setq fmt (or fmt org-email-link-description-format))
7234 (let* ((p org-store-link-plist)
7235 (to (plist-get p :toaddress))
7236 (from (plist-get p :fromaddress))
7237 (table
7238 (list
7239 (cons "%c" (plist-get p :fromto))
7240 (cons "%F" (plist-get p :from))
7241 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7242 (cons "%T" (plist-get p :to))
7243 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7244 (cons "%s" (plist-get p :subject))
7245 (cons "%m" (plist-get p :message-id)))))
7246 (when (string-match "%c" fmt)
7247 ;; Check if the user wrote this message
7248 (if (and org-from-is-user-regexp from to
7249 (save-match-data (string-match org-from-is-user-regexp from)))
7250 (setq fmt (replace-match "to %t" t t fmt))
7251 (setq fmt (replace-match "from %f" t t fmt))))
7252 (org-replace-escapes fmt table)))
7254 (defun org-make-org-heading-search-string (&optional string heading)
7255 "Make search string for STRING or current headline."
7256 (interactive)
7257 (let ((s (or string (org-get-heading))))
7258 (unless (and string (not heading))
7259 ;; We are using a headline, clean up garbage in there.
7260 (if (string-match org-todo-regexp s)
7261 (setq s (replace-match "" t t s)))
7262 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7263 (setq s (replace-match "" t t s)))
7264 (setq s (org-trim s))
7265 (if (string-match (concat "^\\(" org-quote-string "\\|"
7266 org-comment-string "\\)") s)
7267 (setq s (replace-match "" t t s)))
7268 (while (string-match org-ts-regexp s)
7269 (setq s (replace-match "" t t s))))
7270 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7271 (setq s (replace-match " " t t s)))
7272 (or string (setq s (concat "*" s))) ; Add * for headlines
7273 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7275 (defun org-make-link (&rest strings)
7276 "Concatenate STRINGS."
7277 (apply 'concat strings))
7279 (defun org-make-link-string (link &optional description)
7280 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7281 (unless (string-match "\\S-" link)
7282 (error "Empty link"))
7283 (when (stringp description)
7284 ;; Remove brackets from the description, they are fatal.
7285 (while (string-match "\\[" description)
7286 (setq description (replace-match "{" t t description)))
7287 (while (string-match "\\]" description)
7288 (setq description (replace-match "}" t t description))))
7289 (when (equal (org-link-escape link) description)
7290 ;; No description needed, it is identical
7291 (setq description nil))
7292 (when (and (not description)
7293 (not (equal link (org-link-escape link))))
7294 (setq description (org-extract-attributes link)))
7295 (concat "[[" (org-link-escape link) "]"
7296 (if description (concat "[" description "]") "")
7297 "]"))
7299 (defconst org-link-escape-chars
7300 '((?\ . "%20")
7301 (?\[ . "%5B")
7302 (?\] . "%5D")
7303 (?\340 . "%E0") ; `a
7304 (?\342 . "%E2") ; ^a
7305 (?\347 . "%E7") ; ,c
7306 (?\350 . "%E8") ; `e
7307 (?\351 . "%E9") ; 'e
7308 (?\352 . "%EA") ; ^e
7309 (?\356 . "%EE") ; ^i
7310 (?\364 . "%F4") ; ^o
7311 (?\371 . "%F9") ; `u
7312 (?\373 . "%FB") ; ^u
7313 (?\; . "%3B")
7314 (?? . "%3F")
7315 (?= . "%3D")
7316 (?+ . "%2B")
7318 "Association list of escapes for some characters problematic in links.
7319 This is the list that is used for internal purposes.")
7321 (defvar org-url-encoding-use-url-hexify nil)
7323 (defconst org-link-escape-chars-browser
7324 '((?\ . "%20")) ; 32 for the SPC char
7325 "Association list of escapes for some characters problematic in links.
7326 This is the list that is used before handing over to the browser.")
7328 (defun org-link-escape (text &optional table)
7329 "Escape characters in TEXT that are problematic for links."
7330 (if org-url-encoding-use-url-hexify
7331 (url-hexify-string text)
7332 (setq table (or table org-link-escape-chars))
7333 (when text
7334 (let ((re (mapconcat (lambda (x) (regexp-quote
7335 (char-to-string (car x))))
7336 table "\\|")))
7337 (while (string-match re text)
7338 (setq text
7339 (replace-match
7340 (cdr (assoc (string-to-char (match-string 0 text))
7341 table))
7342 t t text)))
7343 text))))
7345 (defun org-link-unescape (text &optional table)
7346 "Reverse the action of `org-link-escape'."
7347 (if org-url-encoding-use-url-hexify
7348 (url-unhex-string text)
7349 (setq table (or table org-link-escape-chars))
7350 (when text
7351 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7352 table "\\|")))
7353 (while (string-match re text)
7354 (setq text
7355 (replace-match
7356 (char-to-string (car (rassoc (match-string 0 text) table)))
7357 t t text)))
7358 text))))
7360 (defun org-xor (a b)
7361 "Exclusive or."
7362 (if a (not b) b))
7364 (defun org-fixup-message-id-for-http (s)
7365 "Replace special characters in a message id, so it can be used in an http query."
7366 (while (string-match "<" s)
7367 (setq s (replace-match "%3C" t t s)))
7368 (while (string-match ">" s)
7369 (setq s (replace-match "%3E" t t s)))
7370 (while (string-match "@" s)
7371 (setq s (replace-match "%40" t t s)))
7374 ;;;###autoload
7375 (defun org-insert-link-global ()
7376 "Insert a link like Org-mode does.
7377 This command can be called in any mode to insert a link in Org-mode syntax."
7378 (interactive)
7379 (org-load-modules-maybe)
7380 (org-run-like-in-org-mode 'org-insert-link))
7382 (defun org-insert-link (&optional complete-file link-location)
7383 "Insert a link. At the prompt, enter the link.
7385 Completion can be used to insert any of the link protocol prefixes like
7386 http or ftp in use.
7388 The history can be used to select a link previously stored with
7389 `org-store-link'. When the empty string is entered (i.e. if you just
7390 press RET at the prompt), the link defaults to the most recently
7391 stored link. As SPC triggers completion in the minibuffer, you need to
7392 use M-SPC or C-q SPC to force the insertion of a space character.
7394 You will also be prompted for a description, and if one is given, it will
7395 be displayed in the buffer instead of the link.
7397 If there is already a link at point, this command will allow you to edit link
7398 and description parts.
7400 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7401 be selected using completion. The path to the file will be relative to the
7402 current directory if the file is in the current directory or a subdirectory.
7403 Otherwise, the link will be the absolute path as completed in the minibuffer
7404 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7405 option `org-link-file-path-type'.
7407 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7408 the current directory or below.
7410 With three \\[universal-argument] prefixes, negate the meaning of
7411 `org-keep-stored-link-after-insertion'.
7413 If `org-make-link-description-function' is non-nil, this function will be
7414 called with the link target, and the result will be the default
7415 link description.
7417 If the LINK-LOCATION parameter is non-nil, this value will be
7418 used as the link location instead of reading one interactively."
7419 (interactive "P")
7420 (let* ((wcf (current-window-configuration))
7421 (region (if (org-region-active-p)
7422 (buffer-substring (region-beginning) (region-end))))
7423 (remove (and region (list (region-beginning) (region-end))))
7424 (desc region)
7425 tmphist ; byte-compile incorrectly complains about this
7426 (link link-location)
7427 entry file all-prefixes)
7428 (cond
7429 (link-location) ; specified by arg, just use it.
7430 ((org-in-regexp org-bracket-link-regexp 1)
7431 ;; We do have a link at point, and we are going to edit it.
7432 (setq remove (list (match-beginning 0) (match-end 0)))
7433 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7434 (setq link (read-string "Link: "
7435 (org-link-unescape
7436 (org-match-string-no-properties 1)))))
7437 ((or (org-in-regexp org-angle-link-re)
7438 (org-in-regexp org-plain-link-re))
7439 ;; Convert to bracket link
7440 (setq remove (list (match-beginning 0) (match-end 0))
7441 link (read-string "Link: "
7442 (org-remove-angle-brackets (match-string 0)))))
7443 ((member complete-file '((4) (16)))
7444 ;; Completing read for file names.
7445 (setq link (org-file-complete-link complete-file)))
7447 ;; Read link, with completion for stored links.
7448 (with-output-to-temp-buffer "*Org Links*"
7449 (princ "Insert a link.
7450 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
7451 (when org-stored-links
7452 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7453 (princ (mapconcat
7454 (lambda (x)
7455 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7456 (reverse org-stored-links) "\n"))))
7457 (let ((cw (selected-window)))
7458 (select-window (get-buffer-window "*Org Links*"))
7459 (setq truncate-lines t)
7460 (unless (pos-visible-in-window-p (point-max))
7461 (org-fit-window-to-buffer))
7462 (and (window-live-p cw) (select-window cw)))
7463 ;; Fake a link history, containing the stored links.
7464 (setq tmphist (append (mapcar 'car org-stored-links)
7465 org-insert-link-history))
7466 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
7467 (mapcar 'car org-link-abbrev-alist)
7468 org-link-types))
7469 (unwind-protect
7470 (progn
7471 (setq link
7472 (let ((org-completion-use-ido nil))
7473 (org-completing-read
7474 "Link: "
7475 (mapcar (lambda (x) (list (concat x ":")))
7476 all-prefixes)
7477 nil nil nil
7478 'tmphist
7479 (or (car (car org-stored-links))))))
7480 (if (or (member link all-prefixes)
7481 (and (equal ":" (substring link -1))
7482 (member (substring link 0 -1) all-prefixes)
7483 (setq link (substring link 0 -1))))
7484 (setq link (org-link-try-special-completion link))))
7485 (set-window-configuration wcf)
7486 (kill-buffer "*Org Links*"))
7487 (setq entry (assoc link org-stored-links))
7488 (or entry (push link org-insert-link-history))
7489 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7490 (not org-keep-stored-link-after-insertion))
7491 (setq org-stored-links (delq (assoc link org-stored-links)
7492 org-stored-links)))
7493 (setq desc (or desc (nth 1 entry)))))
7495 (if (string-match org-plain-link-re link)
7496 ;; URL-like link, normalize the use of angular brackets.
7497 (setq link (org-make-link (org-remove-angle-brackets link))))
7499 ;; Check if we are linking to the current file with a search option
7500 ;; If yes, simplify the link by using only the search option.
7501 (when (and buffer-file-name
7502 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7503 (let* ((path (match-string 1 link))
7504 (case-fold-search nil)
7505 (search (match-string 2 link)))
7506 (save-match-data
7507 (if (equal (file-truename buffer-file-name) (file-truename path))
7508 ;; We are linking to this same file, with a search option
7509 (setq link search)))))
7511 ;; Check if we can/should use a relative path. If yes, simplify the link
7512 (when (string-match "^file:\\(.*\\)" link)
7513 (let* ((path (match-string 1 link))
7514 (origpath path)
7515 (case-fold-search nil))
7516 (cond
7517 ((or (eq org-link-file-path-type 'absolute)
7518 (equal complete-file '(16)))
7519 (setq path (abbreviate-file-name (expand-file-name path))))
7520 ((eq org-link-file-path-type 'noabbrev)
7521 (setq path (expand-file-name path)))
7522 ((eq org-link-file-path-type 'relative)
7523 (setq path (file-relative-name path)))
7525 (save-match-data
7526 (if (string-match (concat "^" (regexp-quote
7527 (file-name-as-directory
7528 (expand-file-name "."))))
7529 (expand-file-name path))
7530 ;; We are linking a file with relative path name.
7531 (setq path (substring (expand-file-name path)
7532 (match-end 0)))
7533 (setq path (abbreviate-file-name (expand-file-name path)))))))
7534 (setq link (concat "file:" path))
7535 (if (equal desc origpath)
7536 (setq desc path))))
7538 (if org-make-link-description-function
7539 (setq desc (funcall org-make-link-description-function link desc)))
7541 (setq desc (read-string "Description: " desc))
7542 (unless (string-match "\\S-" desc) (setq desc nil))
7543 (if remove (apply 'delete-region remove))
7544 (insert (org-make-link-string link desc))))
7546 (defun org-link-try-special-completion (type)
7547 "If there is completion support for link type TAPE, offer it."
7548 (let ((fun (intern (concat "org-" type "-complete-link"))))
7549 (if (functionp fun)
7550 (funcall fun)
7551 (read-string "Link (no completion support): " (concat type ":")))))
7553 (defun org-file-complete-link (&optional arg)
7554 "Create a file link using completion."
7555 (let (file link)
7556 (setq file (read-file-name "File: "))
7557 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7558 (pwd1 (file-name-as-directory (abbreviate-file-name
7559 (expand-file-name ".")))))
7560 (cond
7561 ((equal arg '(16))
7562 (setq link (org-make-link
7563 "file:"
7564 (abbreviate-file-name (expand-file-name file)))))
7565 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7566 (setq link (org-make-link "file:" (match-string 1 file))))
7567 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7568 (expand-file-name file))
7569 (setq link (org-make-link
7570 "file:" (match-string 1 (expand-file-name file)))))
7571 (t (setq link (org-make-link "file:" file)))))
7572 link))
7574 (defun org-completing-read (&rest args)
7575 "Completing-read with SPACE being a normal character."
7576 (let ((minibuffer-local-completion-map
7577 (copy-keymap minibuffer-local-completion-map)))
7578 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7579 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7580 (apply 'org-ido-completing-read args)))
7582 (defun org-completing-read-no-ido (&rest args)
7583 (let (org-completion-use-ido)
7584 (apply 'org-completing-read args)))
7586 (defun org-ido-completing-read (&rest args)
7587 "Completing-read using `ido-mode' speedups if available"
7588 (if (and org-completion-use-ido
7589 (fboundp 'ido-completing-read)
7590 (boundp 'ido-mode) ido-mode
7591 (listp (second args)))
7592 (let ((ido-enter-matching-directory nil))
7593 (apply 'ido-completing-read (concat (car args))
7594 (mapcar (lambda (x) (car x)) (nth 1 args))
7595 (cddr args)))
7596 (apply 'completing-read args)))
7598 (defun org-extract-attributes (s)
7599 "Extract the attributes cookie from a string and set as text property."
7600 (let (a attr (start 0) key value)
7601 (save-match-data
7602 (when (string-match "{{\\([^}]+\\)}}$" s)
7603 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7604 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7605 (setq key (match-string 1 a) value (match-string 2 a)
7606 start (match-end 0)
7607 attr (plist-put attr (intern key) value))))
7608 (org-add-props s nil 'org-attr attr))
7611 (defun org-extract-attributes-from-string (tag)
7612 (let (key value attr)
7613 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
7614 (setq key (match-string 1 tag) value (match-string 2 tag)
7615 tag (replace-match "" t t tag)
7616 attr (plist-put attr (intern key) value)))
7617 (cons tag attr)))
7619 (defun org-attributes-to-string (plist)
7620 "Format a property list into an HTML attribute list."
7621 (let ((s "") key value)
7622 (while plist
7623 (setq key (pop plist) value (pop plist))
7624 (and value
7625 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7628 ;;; Opening/following a link
7630 (defvar org-link-search-failed nil)
7632 (defun org-next-link ()
7633 "Move forward to the next link.
7634 If the link is in hidden text, expose it."
7635 (interactive)
7636 (when (and org-link-search-failed (eq this-command last-command))
7637 (goto-char (point-min))
7638 (message "Link search wrapped back to beginning of buffer"))
7639 (setq org-link-search-failed nil)
7640 (let* ((pos (point))
7641 (ct (org-context))
7642 (a (assoc :link ct)))
7643 (if a (goto-char (nth 2 a)))
7644 (if (re-search-forward org-any-link-re nil t)
7645 (progn
7646 (goto-char (match-beginning 0))
7647 (if (org-invisible-p) (org-show-context)))
7648 (goto-char pos)
7649 (setq org-link-search-failed t)
7650 (error "No further link found"))))
7652 (defun org-previous-link ()
7653 "Move backward to the previous link.
7654 If the link is in hidden text, expose it."
7655 (interactive)
7656 (when (and org-link-search-failed (eq this-command last-command))
7657 (goto-char (point-max))
7658 (message "Link search wrapped back to end of buffer"))
7659 (setq org-link-search-failed nil)
7660 (let* ((pos (point))
7661 (ct (org-context))
7662 (a (assoc :link ct)))
7663 (if a (goto-char (nth 1 a)))
7664 (if (re-search-backward org-any-link-re nil t)
7665 (progn
7666 (goto-char (match-beginning 0))
7667 (if (org-invisible-p) (org-show-context)))
7668 (goto-char pos)
7669 (setq org-link-search-failed t)
7670 (error "No further link found"))))
7672 (defun org-translate-link (s)
7673 "Translate a link string if a translation function has been defined."
7674 (if (and org-link-translation-function
7675 (fboundp org-link-translation-function)
7676 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7677 (progn
7678 (setq s (funcall org-link-translation-function
7679 (match-string 1) (match-string 2)))
7680 (concat (car s) ":" (cdr s)))
7683 (defun org-translate-link-from-planner (type path)
7684 "Translate a link from Emacs Planner syntax so that Org can follow it.
7685 This is still an experimental function, your mileage may vary."
7686 (cond
7687 ((member type '("http" "https" "news" "ftp"))
7688 ;; standard Internet links are the same.
7689 nil)
7690 ((and (equal type "irc") (string-match "^//" path))
7691 ;; Planner has two / at the beginning of an irc link, we have 1.
7692 ;; We should have zero, actually....
7693 (setq path (substring path 1)))
7694 ((and (equal type "lisp") (string-match "^/" path))
7695 ;; Planner has a slash, we do not.
7696 (setq type "elisp" path (substring path 1)))
7697 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7698 ;; A typical message link. Planner has the id after the fina slash,
7699 ;; we separate it with a hash mark
7700 (setq path (concat (match-string 1 path) "#"
7701 (org-remove-angle-brackets (match-string 2 path)))))
7703 (cons type path))
7705 (defun org-find-file-at-mouse (ev)
7706 "Open file link or URL at mouse."
7707 (interactive "e")
7708 (mouse-set-point ev)
7709 (org-open-at-point 'in-emacs))
7711 (defun org-open-at-mouse (ev)
7712 "Open file link or URL at mouse."
7713 (interactive "e")
7714 (mouse-set-point ev)
7715 (if (eq major-mode 'org-agenda-mode)
7716 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7717 (org-open-at-point))
7719 (defvar org-window-config-before-follow-link nil
7720 "The window configuration before following a link.
7721 This is saved in case the need arises to restore it.")
7723 (defvar org-open-link-marker (make-marker)
7724 "Marker pointing to the location where `org-open-at-point; was called.")
7726 ;;;###autoload
7727 (defun org-open-at-point-global ()
7728 "Follow a link like Org-mode does.
7729 This command can be called in any mode to follow a link that has
7730 Org-mode syntax."
7731 (interactive)
7732 (org-run-like-in-org-mode 'org-open-at-point))
7734 ;;;###autoload
7735 (defun org-open-link-from-string (s &optional arg)
7736 "Open a link in the string S, as if it was in Org-mode."
7737 (interactive "sLink: \nP")
7738 (let ((reference-buffer (current-buffer)))
7739 (with-temp-buffer
7740 (let ((org-inhibit-startup t))
7741 (org-mode)
7742 (insert s)
7743 (goto-char (point-min))
7744 (org-open-at-point arg reference-buffer)))))
7746 (defun org-open-at-point (&optional in-emacs reference-buffer)
7747 "Open link at or after point.
7748 If there is no link at point, this function will search forward up to
7749 the end of the current line.
7750 Normally, files will be opened by an appropriate application. If the
7751 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7752 With a double prefix argument, try to open outside of Emacs, in the
7753 application the system uses for this file type."
7754 (interactive "P")
7755 (org-load-modules-maybe)
7756 (move-marker org-open-link-marker (point))
7757 (setq org-window-config-before-follow-link (current-window-configuration))
7758 (org-remove-occur-highlights nil nil t)
7759 (cond
7760 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7761 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7762 (org-footnote-action))
7764 (let (type path link line search (pos (point)))
7765 (catch 'match
7766 (save-excursion
7767 (skip-chars-forward "^]\n\r")
7768 (when (org-in-regexp org-bracket-link-regexp)
7769 (setq link (org-extract-attributes
7770 (org-link-unescape (org-match-string-no-properties 1))))
7771 (while (string-match " *\n *" link)
7772 (setq link (replace-match " " t t link)))
7773 (setq link (org-link-expand-abbrev link))
7774 (cond
7775 ((or (file-name-absolute-p link)
7776 (string-match "^\\.\\.?/" link))
7777 (setq type "file" path link))
7778 ((string-match org-link-re-with-space3 link)
7779 (setq type (match-string 1 link) path (match-string 2 link)))
7780 (t (setq type "thisfile" path link)))
7781 (throw 'match t)))
7783 (when (get-text-property (point) 'org-linked-text)
7784 (setq type "thisfile"
7785 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7786 (1+ (point)) (point))
7787 path (buffer-substring
7788 (previous-single-property-change pos 'org-linked-text)
7789 (next-single-property-change pos 'org-linked-text)))
7790 (throw 'match t))
7792 (save-excursion
7793 (when (or (org-in-regexp org-angle-link-re)
7794 (org-in-regexp org-plain-link-re))
7795 (setq type (match-string 1) path (match-string 2))
7796 (throw 'match t)))
7797 (save-excursion
7798 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7799 (setq type "tags"
7800 path (match-string 1))
7801 (while (string-match ":" path)
7802 (setq path (replace-match "+" t t path)))
7803 (throw 'match t)))
7804 (when (org-in-regexp "<\\([^><\n]+\\)>")
7805 (setq type "tree-match"
7806 path (match-string 1))
7807 (throw 'match t)))
7808 (unless path
7809 (error "No link found"))
7811 ;; switch back to reference buffer
7812 ;; needed when if called in a temporary buffer through
7813 ;; org-open-link-from-string
7814 (and reference-buffer (switch-to-buffer reference-buffer))
7816 ;; Remove any trailing spaces in path
7817 (if (string-match " +\\'" path)
7818 (setq path (replace-match "" t t path)))
7819 (if (and org-link-translation-function
7820 (fboundp org-link-translation-function))
7821 ;; Check if we need to translate the link
7822 (let ((tmp (funcall org-link-translation-function type path)))
7823 (setq type (car tmp) path (cdr tmp))))
7825 (cond
7827 ((assoc type org-link-protocols)
7828 (funcall (nth 1 (assoc type org-link-protocols)) path))
7830 ((equal type "mailto")
7831 (let ((cmd (car org-link-mailto-program))
7832 (args (cdr org-link-mailto-program)) args1
7833 (address path) (subject "") a)
7834 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7835 (setq address (match-string 1 path)
7836 subject (org-link-escape (match-string 2 path))))
7837 (while args
7838 (cond
7839 ((not (stringp (car args))) (push (pop args) args1))
7840 (t (setq a (pop args))
7841 (if (string-match "%a" a)
7842 (setq a (replace-match address t t a)))
7843 (if (string-match "%s" a)
7844 (setq a (replace-match subject t t a)))
7845 (push a args1))))
7846 (apply cmd (nreverse args1))))
7848 ((member type '("http" "https" "ftp" "news"))
7849 (browse-url (concat type ":" (org-link-escape
7850 path org-link-escape-chars-browser))))
7852 ((member type '("message"))
7853 (browse-url (concat type ":" path)))
7855 ((string= type "tags")
7856 (org-tags-view in-emacs path))
7857 ((string= type "thisfile")
7858 (if in-emacs
7859 (switch-to-buffer-other-window
7860 (org-get-buffer-for-internal-link (current-buffer)))
7861 (org-mark-ring-push))
7862 (let ((cmd `(org-link-search
7863 ,path
7864 ,(cond ((equal in-emacs '(4)) 'occur)
7865 ((equal in-emacs '(16)) 'org-occur)
7866 (t nil))
7867 ,pos)))
7868 (condition-case nil (eval cmd)
7869 (error (progn (widen) (eval cmd))))))
7871 ((string= type "tree-match")
7872 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7874 ((string= type "file")
7875 (if (string-match "::\\([0-9]+\\)\\'" path)
7876 (setq line (string-to-number (match-string 1 path))
7877 path (substring path 0 (match-beginning 0)))
7878 (if (string-match "::\\(.+\\)\\'" path)
7879 (setq search (match-string 1 path)
7880 path (substring path 0 (match-beginning 0)))))
7881 (if (string-match "[*?{]" (file-name-nondirectory path))
7882 (dired path)
7883 (org-open-file path in-emacs line search)))
7885 ((string= type "news")
7886 (require 'org-gnus)
7887 (org-gnus-follow-link path))
7889 ((string= type "shell")
7890 (let ((cmd path))
7891 (if (or (not org-confirm-shell-link-function)
7892 (funcall org-confirm-shell-link-function
7893 (format "Execute \"%s\" in shell? "
7894 (org-add-props cmd nil
7895 'face 'org-warning))))
7896 (progn
7897 (message "Executing %s" cmd)
7898 (shell-command cmd))
7899 (error "Abort"))))
7901 ((string= type "elisp")
7902 (let ((cmd path))
7903 (if (or (not org-confirm-elisp-link-function)
7904 (funcall org-confirm-elisp-link-function
7905 (format "Execute \"%s\" as elisp? "
7906 (org-add-props cmd nil
7907 'face 'org-warning))))
7908 (message "%s => %s" cmd
7909 (if (equal (string-to-char cmd) ?\()
7910 (eval (read cmd))
7911 (call-interactively (read cmd))))
7912 (error "Abort"))))
7915 (browse-url-at-point))))))
7916 (move-marker org-open-link-marker nil)
7917 (run-hook-with-args 'org-follow-link-hook))
7919 ;;;; Time estimates
7921 (defun org-get-effort (&optional pom)
7922 "Get the effort estimate for the current entry."
7923 (org-entry-get pom org-effort-property))
7925 ;;; File search
7927 (defvar org-create-file-search-functions nil
7928 "List of functions to construct the right search string for a file link.
7929 These functions are called in turn with point at the location to
7930 which the link should point.
7932 A function in the hook should first test if it would like to
7933 handle this file type, for example by checking the major-mode or
7934 the file extension. If it decides not to handle this file, it
7935 should just return nil to give other functions a chance. If it
7936 does handle the file, it must return the search string to be used
7937 when following the link. The search string will be part of the
7938 file link, given after a double colon, and `org-open-at-point'
7939 will automatically search for it. If special measures must be
7940 taken to make the search successful, another function should be
7941 added to the companion hook `org-execute-file-search-functions',
7942 which see.
7944 A function in this hook may also use `setq' to set the variable
7945 `description' to provide a suggestion for the descriptive text to
7946 be used for this link when it gets inserted into an Org-mode
7947 buffer with \\[org-insert-link].")
7949 (defvar org-execute-file-search-functions nil
7950 "List of functions to execute a file search triggered by a link.
7952 Functions added to this hook must accept a single argument, the
7953 search string that was part of the file link, the part after the
7954 double colon. The function must first check if it would like to
7955 handle this search, for example by checking the major-mode or the
7956 file extension. If it decides not to handle this search, it
7957 should just return nil to give other functions a chance. If it
7958 does handle the search, it must return a non-nil value to keep
7959 other functions from trying.
7961 Each function can access the current prefix argument through the
7962 variable `current-prefix-argument'. Note that a single prefix is
7963 used to force opening a link in Emacs, so it may be good to only
7964 use a numeric or double prefix to guide the search function.
7966 In case this is needed, a function in this hook can also restore
7967 the window configuration before `org-open-at-point' was called using:
7969 (set-window-configuration org-window-config-before-follow-link)")
7971 (defun org-link-search (s &optional type avoid-pos)
7972 "Search for a link search option.
7973 If S is surrounded by forward slashes, it is interpreted as a
7974 regular expression. In org-mode files, this will create an `org-occur'
7975 sparse tree. In ordinary files, `occur' will be used to list matches.
7976 If the current buffer is in `dired-mode', grep will be used to search
7977 in all files. If AVOID-POS is given, ignore matches near that position."
7978 (let ((case-fold-search t)
7979 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7980 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7981 (append '(("") (" ") ("\t") ("\n"))
7982 org-emphasis-alist)
7983 "\\|") "\\)"))
7984 (pos (point))
7985 (pre nil) (post nil)
7986 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7987 (cond
7988 ;; First check if there are any special
7989 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7990 ;; Now try the builtin stuff
7991 ((and (equal (string-to-char s0) ?#)
7992 (> (length s0) 1)
7993 (save-excursion
7994 (goto-char (point-min))
7995 (and
7996 (re-search-forward
7997 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
7998 (setq type 'dedicated
7999 pos (match-beginning 0))))
8000 ;; There is an exact target for this
8001 (goto-char pos)
8002 (org-back-to-heading t)))
8003 ((save-excursion
8004 (goto-char (point-min))
8005 (and
8006 (re-search-forward
8007 (concat "<<" (regexp-quote s0) ">>") nil t)
8008 (setq type 'dedicated
8009 pos (match-beginning 0))))
8010 ;; There is an exact target for this
8011 (goto-char pos))
8012 ((and (string-match "^(\\(.*\\))$" s0)
8013 (save-excursion
8014 (goto-char (point-min))
8015 (and
8016 (re-search-forward
8017 (concat "[^[]" (regexp-quote
8018 (format org-coderef-label-format
8019 (match-string 1 s0))))
8020 nil t)
8021 (setq type 'dedicated
8022 pos (1+ (match-beginning 0))))))
8023 ;; There is a coderef target for this
8024 (goto-char pos))
8025 ((string-match "^/\\(.*\\)/$" s)
8026 ;; A regular expression
8027 (cond
8028 ((org-mode-p)
8029 (org-occur (match-string 1 s)))
8030 ;;((eq major-mode 'dired-mode)
8031 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8032 (t (org-do-occur (match-string 1 s)))))
8034 ;; A normal search strings
8035 (when (equal (string-to-char s) ?*)
8036 ;; Anchor on headlines, post may include tags.
8037 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8038 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8039 s (substring s 1)))
8040 (remove-text-properties
8041 0 (length s)
8042 '(face nil mouse-face nil keymap nil fontified nil) s)
8043 ;; Make a series of regular expressions to find a match
8044 (setq words (org-split-string s "[ \n\r\t]+")
8046 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8047 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8048 "\\)" markers)
8049 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8050 re2a (concat "[ \t\r\n]" re2a_)
8051 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8052 re4 (concat "[^a-zA-Z_]" re4_)
8054 re1 (concat pre re2 post)
8055 re3 (concat pre (if pre re4_ re4) post)
8056 re5 (concat pre ".*" re4)
8057 re2 (concat pre re2)
8058 re2a (concat pre (if pre re2a_ re2a))
8059 re4 (concat pre (if pre re4_ re4))
8060 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8061 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8062 re5 "\\)"
8064 (cond
8065 ((eq type 'org-occur) (org-occur reall))
8066 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8067 (t (goto-char (point-min))
8068 (setq type 'fuzzy)
8069 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8070 (org-search-not-self 1 re1 nil t)
8071 (org-search-not-self 1 re2 nil t)
8072 (org-search-not-self 1 re2a nil t)
8073 (org-search-not-self 1 re3 nil t)
8074 (org-search-not-self 1 re4 nil t)
8075 (org-search-not-self 1 re5 nil t)
8077 (goto-char (match-beginning 1))
8078 (goto-char pos)
8079 (error "No match")))))
8081 ;; Normal string-search
8082 (goto-char (point-min))
8083 (if (search-forward s nil t)
8084 (goto-char (match-beginning 0))
8085 (error "No match"))))
8086 (and (org-mode-p) (org-show-context 'link-search))
8087 type))
8089 (defun org-search-not-self (group &rest args)
8090 "Execute `re-search-forward', but only accept matches that do not
8091 enclose the position of `org-open-link-marker'."
8092 (let ((m org-open-link-marker))
8093 (catch 'exit
8094 (while (apply 're-search-forward args)
8095 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8096 (goto-char (match-end group))
8097 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8098 (> (match-beginning 0) (marker-position m))
8099 (< (match-end 0) (marker-position m)))
8100 (save-match-data
8101 (or (not (org-in-regexp
8102 org-bracket-link-analytic-regexp 1))
8103 (not (match-end 4)) ; no description
8104 (and (<= (match-beginning 4) (point))
8105 (>= (match-end 4) (point))))))
8106 (throw 'exit (point))))))))
8108 (defun org-get-buffer-for-internal-link (buffer)
8109 "Return a buffer to be used for displaying the link target of internal links."
8110 (cond
8111 ((not org-display-internal-link-with-indirect-buffer)
8112 buffer)
8113 ((string-match "(Clone)$" (buffer-name buffer))
8114 (message "Buffer is already a clone, not making another one")
8115 ;; we also do not modify visibility in this case
8116 buffer)
8117 (t ; make a new indirect buffer for displaying the link
8118 (let* ((bn (buffer-name buffer))
8119 (ibn (concat bn "(Clone)"))
8120 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8121 (with-current-buffer ib (org-overview))
8122 ib))))
8124 (defun org-do-occur (regexp &optional cleanup)
8125 "Call the Emacs command `occur'.
8126 If CLEANUP is non-nil, remove the printout of the regular expression
8127 in the *Occur* buffer. This is useful if the regex is long and not useful
8128 to read."
8129 (occur regexp)
8130 (when cleanup
8131 (let ((cwin (selected-window)) win beg end)
8132 (when (setq win (get-buffer-window "*Occur*"))
8133 (select-window win))
8134 (goto-char (point-min))
8135 (when (re-search-forward "match[a-z]+" nil t)
8136 (setq beg (match-end 0))
8137 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8138 (setq end (1- (match-beginning 0)))))
8139 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8140 (goto-char (point-min))
8141 (select-window cwin))))
8143 ;;; The mark ring for links jumps
8145 (defvar org-mark-ring nil
8146 "Mark ring for positions before jumps in Org-mode.")
8147 (defvar org-mark-ring-last-goto nil
8148 "Last position in the mark ring used to go back.")
8149 ;; Fill and close the ring
8150 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8151 (loop for i from 1 to org-mark-ring-length do
8152 (push (make-marker) org-mark-ring))
8153 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8154 org-mark-ring)
8156 (defun org-mark-ring-push (&optional pos buffer)
8157 "Put the current position or POS into the mark ring and rotate it."
8158 (interactive)
8159 (setq pos (or pos (point)))
8160 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8161 (move-marker (car org-mark-ring)
8162 (or pos (point))
8163 (or buffer (current-buffer)))
8164 (message "%s"
8165 (substitute-command-keys
8166 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8168 (defun org-mark-ring-goto (&optional n)
8169 "Jump to the previous position in the mark ring.
8170 With prefix arg N, jump back that many stored positions. When
8171 called several times in succession, walk through the entire ring.
8172 Org-mode commands jumping to a different position in the current file,
8173 or to another Org-mode file, automatically push the old position
8174 onto the ring."
8175 (interactive "p")
8176 (let (p m)
8177 (if (eq last-command this-command)
8178 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8179 (setq p org-mark-ring))
8180 (setq org-mark-ring-last-goto p)
8181 (setq m (car p))
8182 (switch-to-buffer (marker-buffer m))
8183 (goto-char m)
8184 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8186 (defun org-remove-angle-brackets (s)
8187 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8188 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8190 (defun org-add-angle-brackets (s)
8191 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8192 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8194 (defun org-remove-double-quotes (s)
8195 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8196 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8199 ;;; Following specific links
8201 (defun org-follow-timestamp-link ()
8202 (cond
8203 ((org-at-date-range-p t)
8204 (let ((org-agenda-start-on-weekday)
8205 (t1 (match-string 1))
8206 (t2 (match-string 2)))
8207 (setq t1 (time-to-days (org-time-string-to-time t1))
8208 t2 (time-to-days (org-time-string-to-time t2)))
8209 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8210 ((org-at-timestamp-p t)
8211 (org-agenda-list nil (time-to-days (org-time-string-to-time
8212 (substring (match-string 1) 0 10)))
8214 (t (error "This should not happen"))))
8217 ;;; Following file links
8218 (defvar org-wait nil)
8219 (defun org-open-file (path &optional in-emacs line search)
8220 "Open the file at PATH.
8221 First, this expands any special file name abbreviations. Then the
8222 configuration variable `org-file-apps' is checked if it contains an
8223 entry for this file type, and if yes, the corresponding command is launched.
8225 If no application is found, Emacs simply visits the file.
8227 With optional prefix argument IN-EMACS, Emacs will visit the file.
8228 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8229 and o use an external application to visit the file.
8231 Optional LINE specifies a line to go to, optional SEARCH a string to
8232 search for. If LINE or SEARCH is given, the file will always be
8233 opened in Emacs.
8234 If the file does not exist, an error is thrown."
8235 (setq in-emacs (or in-emacs line search))
8236 (let* ((file (if (equal path "")
8237 buffer-file-name
8238 (substitute-in-file-name (expand-file-name path))))
8239 (apps (append org-file-apps (org-default-apps)))
8240 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8241 (dirp (if remp nil (file-directory-p file)))
8242 (file (if (and dirp org-open-directory-means-index-dot-org)
8243 (concat (file-name-as-directory file) "index.org")
8244 file))
8245 (a-m-a-p (assq 'auto-mode apps))
8246 (dfile (downcase file))
8247 (old-buffer (current-buffer))
8248 (old-pos (point))
8249 (old-mode major-mode)
8250 ext cmd)
8251 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8252 (setq ext (match-string 1 dfile))
8253 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8254 (setq ext (match-string 1 dfile))))
8255 (cond
8256 ((equal in-emacs '(16))
8257 (setq cmd (cdr (assoc 'system apps))))
8258 (in-emacs (setq cmd 'emacs))
8260 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8261 (and dirp (cdr (assoc 'directory apps)))
8262 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8263 'string-match)
8264 (cdr (assoc ext apps))
8265 (cdr (assoc t apps))))))
8266 (when (eq cmd 'system)
8267 (setq cmd (cdr (assoc 'system apps))))
8268 (when (eq cmd 'default)
8269 (setq cmd (cdr (assoc t apps))))
8270 (when (eq cmd 'mailcap)
8271 (require 'mailcap)
8272 (mailcap-parse-mailcaps)
8273 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8274 (command (mailcap-mime-info mime-type)))
8275 (if (stringp command)
8276 (setq cmd command)
8277 (setq cmd 'emacs))))
8278 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8279 (not (file-exists-p file))
8280 (not org-open-non-existing-files))
8281 (error "No such file: %s" file))
8282 (cond
8283 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8284 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8285 (while (string-match "['\"]%s['\"]" cmd)
8286 (setq cmd (replace-match "%s" t t cmd)))
8287 (while (string-match "%s" cmd)
8288 (setq cmd (replace-match
8289 (save-match-data
8290 (shell-quote-argument
8291 (convert-standard-filename file)))
8292 t t cmd)))
8293 (save-window-excursion
8294 (start-process-shell-command cmd nil cmd)
8295 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8297 ((or (stringp cmd)
8298 (eq cmd 'emacs))
8299 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8300 (widen)
8301 (if line (goto-line line)
8302 (if search (org-link-search search))))
8303 ((consp cmd)
8304 (let ((file (convert-standard-filename file)))
8305 (eval cmd)))
8306 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8307 (and (org-mode-p) (eq old-mode 'org-mode)
8308 (or (not (equal old-buffer (current-buffer)))
8309 (not (equal old-pos (point))))
8310 (org-mark-ring-push old-pos old-buffer))))
8312 (defun org-default-apps ()
8313 "Return the default applications for this operating system."
8314 (cond
8315 ((eq system-type 'darwin)
8316 org-file-apps-defaults-macosx)
8317 ((eq system-type 'windows-nt)
8318 org-file-apps-defaults-windowsnt)
8319 (t org-file-apps-defaults-gnu)))
8321 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8322 "Convert extensions to regular expressions in the cars of LIST.
8323 Also, weed out any non-string entries, because the return value is used
8324 only for regexp matching.
8325 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8326 point to the symbol `emacs', indicating that the file should
8327 be opened in Emacs."
8328 (append
8329 (delq nil
8330 (mapcar (lambda (x)
8331 (if (not (stringp (car x)))
8333 (if (string-match "\\W" (car x))
8335 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8336 list))
8337 (if add-auto-mode
8338 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8340 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8341 (defun org-file-remote-p (file)
8342 "Test whether FILE specifies a location on a remote system.
8343 Return non-nil if the location is indeed remote.
8345 For example, the filename \"/user@host:/foo\" specifies a location
8346 on the system \"/user@host:\"."
8347 (cond ((fboundp 'file-remote-p)
8348 (file-remote-p file))
8349 ((fboundp 'tramp-handle-file-remote-p)
8350 (tramp-handle-file-remote-p file))
8351 ((and (boundp 'ange-ftp-name-format)
8352 (string-match (car ange-ftp-name-format) file))
8354 (t nil)))
8357 ;;;; Refiling
8359 (defun org-get-org-file ()
8360 "Read a filename, with default directory `org-directory'."
8361 (let ((default (or org-default-notes-file remember-data-file)))
8362 (read-file-name (format "File name [%s]: " default)
8363 (file-name-as-directory org-directory)
8364 default)))
8366 (defun org-notes-order-reversed-p ()
8367 "Check if the current file should receive notes in reversed order."
8368 (cond
8369 ((not org-reverse-note-order) nil)
8370 ((eq t org-reverse-note-order) t)
8371 ((not (listp org-reverse-note-order)) nil)
8372 (t (catch 'exit
8373 (let ((all org-reverse-note-order)
8374 entry)
8375 (while (setq entry (pop all))
8376 (if (string-match (car entry) buffer-file-name)
8377 (throw 'exit (cdr entry))))
8378 nil)))))
8380 (defvar org-refile-target-table nil
8381 "The list of refile targets, created by `org-refile'.")
8383 (defvar org-agenda-new-buffers nil
8384 "Buffers created to visit agenda files.")
8386 (defun org-get-refile-targets (&optional default-buffer)
8387 "Produce a table with refile targets."
8388 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
8389 targets txt re files f desc descre fast-path-p level pos0)
8390 (message "Getting targets...")
8391 (with-current-buffer (or default-buffer (current-buffer))
8392 (while (setq entry (pop entries))
8393 (setq files (car entry) desc (cdr entry))
8394 (setq fast-path-p nil)
8395 (cond
8396 ((null files) (setq files (list (current-buffer))))
8397 ((eq files 'org-agenda-files)
8398 (setq files (org-agenda-files 'unrestricted)))
8399 ((and (symbolp files) (fboundp files))
8400 (setq files (funcall files)))
8401 ((and (symbolp files) (boundp files))
8402 (setq files (symbol-value files))))
8403 (if (stringp files) (setq files (list files)))
8404 (cond
8405 ((eq (car desc) :tag)
8406 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8407 ((eq (car desc) :todo)
8408 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8409 ((eq (car desc) :regexp)
8410 (setq descre (cdr desc)))
8411 ((eq (car desc) :level)
8412 (setq descre (concat "^\\*\\{" (number-to-string
8413 (if org-odd-levels-only
8414 (1- (* 2 (cdr desc)))
8415 (cdr desc)))
8416 "\\}[ \t]")))
8417 ((eq (car desc) :maxlevel)
8418 (setq fast-path-p t)
8419 (setq descre (concat "^\\*\\{1," (number-to-string
8420 (if org-odd-levels-only
8421 (1- (* 2 (cdr desc)))
8422 (cdr desc)))
8423 "\\}[ \t]")))
8424 (t (error "Bad refiling target description %s" desc)))
8425 (while (setq f (pop files))
8426 (save-excursion
8427 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
8428 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8429 (setq f (expand-file-name f))
8430 (if (eq org-refile-use-outline-path 'file)
8431 (push (list (file-name-nondirectory f) f nil nil) targets))
8432 (save-excursion
8433 (save-restriction
8434 (widen)
8435 (goto-char (point-min))
8436 (while (re-search-forward descre nil t)
8437 (goto-char (setq pos0 (point-at-bol)))
8438 (catch 'next
8439 (when org-refile-target-verify-function
8440 (save-match-data
8441 (or (funcall org-refile-target-verify-function)
8442 (throw 'next t))))
8443 (when (looking-at org-complex-heading-regexp)
8444 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8445 txt (org-link-display-format (match-string 4))
8446 re (concat "^" (regexp-quote
8447 (buffer-substring (match-beginning 1)
8448 (match-end 4)))))
8449 (if (match-end 5) (setq re (concat re "[ \t]+"
8450 (regexp-quote
8451 (match-string 5)))))
8452 (setq re (concat re "[ \t]*$"))
8453 (when org-refile-use-outline-path
8454 (setq txt (mapconcat 'org-protect-slash
8455 (append
8456 (if (eq org-refile-use-outline-path 'file)
8457 (list (file-name-nondirectory
8458 (buffer-file-name (buffer-base-buffer))))
8459 (if (eq org-refile-use-outline-path 'full-file-path)
8460 (list (buffer-file-name (buffer-base-buffer)))))
8461 (org-get-outline-path fast-path-p level txt)
8462 (list txt))
8463 "/")))
8464 (push (list txt f re (point)) targets)))
8465 (when (= (point) pos0)
8466 ;; verification function has not moved point
8467 (goto-char (point-at-eol))))))))))
8468 (message "Getting targets...done")
8469 (nreverse targets)))
8471 (defun org-protect-slash (s)
8472 (while (string-match "/" s)
8473 (setq s (replace-match "\\" t t s)))
8476 (defvar org-olpa (make-vector 20 nil))
8478 (defun org-get-outline-path (&optional fastp level heading)
8479 "Return the outline path to the current entry, as a list."
8480 (if fastp
8481 (progn
8482 (if (> level 19)
8483 (error "Outline path failure, more than 19 levels."))
8484 (loop for i from level upto 19 do
8485 (aset org-olpa i nil))
8486 (prog1
8487 (delq nil (append org-olpa nil))
8488 (aset org-olpa level heading)))
8489 (let (rtn)
8490 (save-excursion
8491 (while (org-up-heading-safe)
8492 (when (looking-at org-complex-heading-regexp)
8493 (push (org-match-string-no-properties 4) rtn)))
8494 rtn))))
8496 (defvar org-refile-history nil
8497 "History for refiling operations.")
8499 (defvar org-after-refile-insert-hook nil
8500 "Hook run after `org-refile' has inserted its stuff at the new location.
8501 Note that this is still *before* the stuff will be removed from
8502 the *old* location.")
8504 (defun org-refile (&optional goto default-buffer)
8505 "Move the entry at point to another heading.
8506 The list of target headings is compiled using the information in
8507 `org-refile-targets', which see. This list is created before each use
8508 and will therefore always be up-to-date.
8510 At the target location, the entry is filed as a subitem of the target heading.
8511 Depending on `org-reverse-note-order', the new subitem will either be the
8512 first or the last subitem.
8514 If there is an active region, all entries in that region will be moved.
8515 However, the region must fulfil the requirement that the first heading
8516 is the first one sets the top-level of the moved text - at most siblings
8517 below it are allowed.
8519 With prefix arg GOTO, the command will only visit the target location,
8520 not actually move anything.
8521 With a double prefix `C-u C-u', go to the location where the last refiling
8522 operation has put the subtree.
8524 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
8525 (interactive "P")
8526 (let* ((cbuf (current-buffer))
8527 (regionp (org-region-active-p))
8528 (region-start (and regionp (region-beginning)))
8529 (region-end (and regionp (region-end)))
8530 (region-length (and regionp (- region-end region-start)))
8531 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8532 pos it nbuf file re level reversed)
8533 (when regionp (goto-char region-start)
8534 (unless (org-kill-is-subtree-p
8535 (buffer-substring region-start region-end))
8536 (error "The region is not a (sequence of) subtree(s)")))
8537 (if (equal goto '(16))
8538 (org-refile-goto-last-stored)
8539 (when (setq it (org-refile-get-location
8540 (if goto "Goto: " "Refile to: ") default-buffer
8541 org-refile-allow-creating-parent-nodes))
8542 (setq file (nth 1 it)
8543 re (nth 2 it)
8544 pos (nth 3 it))
8545 (if (and (not goto)
8547 (equal (buffer-file-name) file)
8548 (if regionp
8549 (and (>= pos region-start)
8550 (<= pos region-end))
8551 (and (>= pos (point))
8552 (< pos (save-excursion
8553 (org-end-of-subtree t t))))))
8554 (error "Cannot refile to position inside the tree or region"))
8556 (setq nbuf (or (find-buffer-visiting file)
8557 (find-file-noselect file)))
8558 (if goto
8559 (progn
8560 (switch-to-buffer nbuf)
8561 (goto-char pos)
8562 (org-show-context 'org-goto))
8563 (if regionp
8564 (progn
8565 (kill-new (buffer-substring region-start region-end))
8566 (org-save-markers-in-region region-start region-end))
8567 (org-copy-subtree 1 nil t))
8568 (save-excursion
8569 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8570 (find-file-noselect file))))
8571 (setq reversed (org-notes-order-reversed-p))
8572 (save-excursion
8573 (save-restriction
8574 (widen)
8575 (if pos
8576 (progn
8577 (goto-char pos)
8578 (looking-at outline-regexp)
8579 (setq level (org-get-valid-level (funcall outline-level) 1))
8580 (goto-char
8581 (if reversed
8582 (or (outline-next-heading) (point-max))
8583 (or (save-excursion (outline-get-next-sibling))
8584 (org-end-of-subtree t t)
8585 (point-max)))))
8586 (setq level 1)
8587 (if (not reversed)
8588 (goto-char (point-max))
8589 (goto-char (point-min))
8590 (or (outline-next-heading) (goto-char (point-max)))))
8591 (if (not (bolp)) (newline))
8592 (bookmark-set "org-refile-last-stored")
8593 (org-paste-subtree level)
8594 (run-hooks 'org-after-refile-insert-hook))))
8595 (if regionp
8596 (delete-region (point) (+ (point) region-length))
8597 (org-cut-subtree))
8598 (setq org-markers-to-move nil)
8599 (message "Refiled to \"%s\"" (car it))))))
8600 (org-reveal))
8602 (defun org-refile-goto-last-stored ()
8603 "Go to the location where the last refile was stored."
8604 (interactive)
8605 (bookmark-jump "org-refile-last-stored")
8606 (message "This is the location of the last refile"))
8608 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
8609 "Prompt the user for a refile location, using PROMPT."
8610 (let ((org-refile-targets org-refile-targets)
8611 (org-refile-use-outline-path org-refile-use-outline-path))
8612 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8613 (unless org-refile-target-table
8614 (error "No refile targets"))
8615 (let* ((cbuf (current-buffer))
8616 (partial-completion-mode nil)
8617 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8618 (cfunc (if (and org-refile-use-outline-path
8619 org-outline-path-complete-in-steps)
8620 'org-olpath-completing-read
8621 'org-ido-completing-read))
8622 (extra (if org-refile-use-outline-path "/" ""))
8623 (filename (and cfn (expand-file-name cfn)))
8624 (tbl (mapcar
8625 (lambda (x)
8626 (if (and (not (member org-refile-use-outline-path
8627 '(file full-file-path)))
8628 (not (equal filename (nth 1 x))))
8629 (cons (concat (car x) extra " ("
8630 (file-name-nondirectory (nth 1 x)) ")")
8631 (cdr x))
8632 (cons (concat (car x) extra) (cdr x))))
8633 org-refile-target-table))
8634 (completion-ignore-case t)
8635 pa answ parent-target child parent)
8636 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
8637 nil 'org-refile-history))
8638 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
8639 (if pa
8641 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
8642 (setq parent (match-string 1 answ)
8643 child (match-string 2 answ))
8644 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
8645 (when (and parent-target
8646 (or (eq new-nodes t)
8647 (and (eq new-nodes 'confirm)
8648 (y-or-n-p (format "Create new node \"%s\"? " child)))))
8649 (org-refile-new-child parent-target child))))))
8651 (defun org-refile-new-child (parent-target child)
8652 "Use refile target PARENT-TARGET to add new CHILD below it."
8653 (unless parent-target
8654 (error "Cannot find parent for new node"))
8655 (let ((file (nth 1 parent-target))
8656 (pos (nth 3 parent-target))
8657 level)
8658 (with-current-buffer (or (find-buffer-visiting file)
8659 (find-file-noselect file))
8660 (save-excursion
8661 (save-restriction
8662 (widen)
8663 (if pos
8664 (goto-char pos)
8665 (goto-char (point-max))
8666 (if (not (bolp)) (newline)))
8667 (when (looking-at outline-regexp)
8668 (setq level (funcall outline-level))
8669 (org-end-of-subtree t t))
8670 (org-back-over-empty-lines)
8671 (insert "\n" (make-string
8672 (if pos (org-get-valid-level level 1) 1) ?*)
8673 " " child "\n")
8674 (beginning-of-line 0)
8675 (list (concat (car parent-target) "/" child) file "" (point)))))))
8677 (defun org-olpath-completing-read (prompt collection &rest args)
8678 "Read an outline path like a file name."
8679 (let ((thetable collection)
8680 (org-completion-use-ido nil)) ; does not work with ido.
8681 (apply
8682 'org-ido-completing-read prompt
8683 (lambda (string predicate &optional flag)
8684 (let (rtn r f (l (length string)))
8685 (cond
8686 ((eq flag nil)
8687 ;; try completion
8688 (try-completion string thetable))
8689 ((eq flag t)
8690 ;; all-completions
8691 (setq rtn (all-completions string thetable predicate))
8692 (mapcar
8693 (lambda (x)
8694 (setq r (substring x l))
8695 (if (string-match " ([^)]*)$" x)
8696 (setq f (match-string 0 x))
8697 (setq f ""))
8698 (if (string-match "/" r)
8699 (concat string (substring r 0 (match-end 0)) f)
8701 rtn))
8702 ((eq flag 'lambda)
8703 ;; exact match?
8704 (assoc string thetable)))
8706 args)))
8708 ;;;; Dynamic blocks
8710 (defun org-find-dblock (name)
8711 "Find the first dynamic block with name NAME in the buffer.
8712 If not found, stay at current position and return nil."
8713 (let (pos)
8714 (save-excursion
8715 (goto-char (point-min))
8716 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8717 nil t)
8718 (match-beginning 0))))
8719 (if pos (goto-char pos))
8720 pos))
8722 (defconst org-dblock-start-re
8723 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8724 "Matches the startline of a dynamic block, with parameters.")
8726 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8727 "Matches the end of a dynamic block.")
8729 (defun org-create-dblock (plist)
8730 "Create a dynamic block section, with parameters taken from PLIST.
8731 PLIST must contain a :name entry which is used as name of the block."
8732 (unless (bolp) (newline))
8733 (let ((name (plist-get plist :name)))
8734 (insert "#+BEGIN: " name)
8735 (while plist
8736 (if (eq (car plist) :name)
8737 (setq plist (cddr plist))
8738 (insert " " (prin1-to-string (pop plist)))))
8739 (insert "\n\n#+END:\n")
8740 (beginning-of-line -2)))
8742 (defun org-prepare-dblock ()
8743 "Prepare dynamic block for refresh.
8744 This empties the block, puts the cursor at the insert position and returns
8745 the property list including an extra property :name with the block name."
8746 (unless (looking-at org-dblock-start-re)
8747 (error "Not at a dynamic block"))
8748 (let* ((begdel (1+ (match-end 0)))
8749 (name (org-no-properties (match-string 1)))
8750 (params (append (list :name name)
8751 (read (concat "(" (match-string 3) ")")))))
8752 (unless (re-search-forward org-dblock-end-re nil t)
8753 (error "Dynamic block not terminated"))
8754 (setq params
8755 (append params
8756 (list :content (buffer-substring
8757 begdel (match-beginning 0)))))
8758 (delete-region begdel (match-beginning 0))
8759 (goto-char begdel)
8760 (open-line 1)
8761 params))
8763 (defun org-map-dblocks (&optional command)
8764 "Apply COMMAND to all dynamic blocks in the current buffer.
8765 If COMMAND is not given, use `org-update-dblock'."
8766 (let ((cmd (or command 'org-update-dblock))
8767 pos)
8768 (save-excursion
8769 (goto-char (point-min))
8770 (while (re-search-forward org-dblock-start-re nil t)
8771 (goto-char (setq pos (match-beginning 0)))
8772 (condition-case nil
8773 (funcall cmd)
8774 (error (message "Error during update of dynamic block")))
8775 (goto-char pos)
8776 (unless (re-search-forward org-dblock-end-re nil t)
8777 (error "Dynamic block not terminated"))))))
8779 (defun org-dblock-update (&optional arg)
8780 "User command for updating dynamic blocks.
8781 Update the dynamic block at point. With prefix ARG, update all dynamic
8782 blocks in the buffer."
8783 (interactive "P")
8784 (if arg
8785 (org-update-all-dblocks)
8786 (or (looking-at org-dblock-start-re)
8787 (org-beginning-of-dblock))
8788 (org-update-dblock)))
8790 (defun org-update-dblock ()
8791 "Update the dynamic block at point
8792 This means to empty the block, parse for parameters and then call
8793 the correct writing function."
8794 (save-window-excursion
8795 (let* ((pos (point))
8796 (line (org-current-line))
8797 (params (org-prepare-dblock))
8798 (name (plist-get params :name))
8799 (cmd (intern (concat "org-dblock-write:" name))))
8800 (message "Updating dynamic block `%s' at line %d..." name line)
8801 (funcall cmd params)
8802 (message "Updating dynamic block `%s' at line %d...done" name line)
8803 (goto-char pos))))
8805 (defun org-beginning-of-dblock ()
8806 "Find the beginning of the dynamic block at point.
8807 Error if there is no such block at point."
8808 (let ((pos (point))
8809 beg)
8810 (end-of-line 1)
8811 (if (and (re-search-backward org-dblock-start-re nil t)
8812 (setq beg (match-beginning 0))
8813 (re-search-forward org-dblock-end-re nil t)
8814 (> (match-end 0) pos))
8815 (goto-char beg)
8816 (goto-char pos)
8817 (error "Not in a dynamic block"))))
8819 (defun org-update-all-dblocks ()
8820 "Update all dynamic blocks in the buffer.
8821 This function can be used in a hook."
8822 (when (org-mode-p)
8823 (org-map-dblocks 'org-update-dblock)))
8826 ;;;; Completion
8828 (defconst org-additional-option-like-keywords
8829 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8830 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8831 "LATEX_HEADER:"
8832 "BEGIN_EXAMPLE" "END_EXAMPLE"
8833 "BEGIN_QUOTE" "END_QUOTE"
8834 "BEGIN_VERSE" "END_VERSE"
8835 "BEGIN_CENTER" "END_CENTER"
8836 "BEGIN_SRC" "END_SRC"
8837 "CATEGORY" "COLUMNS"
8838 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
8840 (defcustom org-structure-template-alist
8842 ("s" "#+begin_src ?\n\n#+end_src"
8843 "<src lang=\"?\">\n\n</src>")
8844 ("e" "#+begin_example\n?\n#+end_example"
8845 "<example>\n?\n</example>")
8846 ("q" "#+begin_quote\n?\n#+end_quote"
8847 "<quote>\n?\n</quote>")
8848 ("v" "#+begin_verse\n?\n#+end_verse"
8849 "<verse>\n?\n/verse>")
8850 ("c" "#+begin_center\n?\n#+end_center"
8851 "<center>\n?\n/center>")
8852 ("l" "#+begin_latex\n?\n#+end_latex"
8853 "<literal style=\"latex\">\n?\n</literal>")
8854 ("L" "#+latex: "
8855 "<literal style=\"latex\">?</literal>")
8856 ("h" "#+begin_html\n?\n#+end_html"
8857 "<literal style=\"html\">\n?\n</literal>")
8858 ("H" "#+html: "
8859 "<literal style=\"html\">?</literal>")
8860 ("a" "#+begin_ascii\n?\n#+end_ascii")
8861 ("A" "#+ascii: ")
8862 ("i" "#+include %file ?"
8863 "<include file=%file markup=\"?\">")
8865 "Structure completion elements.
8866 This is a list of abbreviation keys and values. The value gets inserted
8867 it you type @samp{.} followed by the key and then the completion key,
8868 usually `M-TAB'. %file will be replaced by a file name after prompting
8869 for the file using completion.
8870 There are two templates for each key, the first uses the original Org syntax,
8871 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8872 the default when the /org-mtags.el/ module has been loaded. See also the
8873 variable `org-mtags-prefer-muse-templates'.
8874 This is an experimental feature, it is undecided if it is going to stay in."
8875 :group 'org-completion
8876 :type '(repeat
8877 (string :tag "Key")
8878 (string :tag "Template")
8879 (string :tag "Muse Template")))
8881 (defun org-try-structure-completion ()
8882 "Try to complete a structure template before point.
8883 This looks for strings like \"<e\" on an otherwise empty line and
8884 expands them."
8885 (let ((l (buffer-substring (point-at-bol) (point)))
8887 (when (and (looking-at "[ \t]*$")
8888 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8889 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8890 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8891 (match-beginning 1)) a)
8892 t)))
8894 (defun org-complete-expand-structure-template (start cell)
8895 "Expand a structure template."
8896 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8897 (rpl (nth (if musep 2 1) cell)))
8898 (delete-region start (point))
8899 (when (string-match "\\`#\\+" rpl)
8900 (cond
8901 ((bolp))
8902 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8903 (delete-region (point-at-bol) (point)))
8904 (t (newline))))
8905 (setq start (point))
8906 (if (string-match "%file" rpl)
8907 (setq rpl (replace-match
8908 (concat
8909 "\""
8910 (save-match-data
8911 (abbreviate-file-name (read-file-name "Include file: ")))
8912 "\"")
8913 t t rpl)))
8914 (insert rpl)
8915 (if (re-search-backward "\\?" start t) (delete-char 1))))
8918 (defun org-complete (&optional arg)
8919 "Perform completion on word at point.
8920 At the beginning of a headline, this completes TODO keywords as given in
8921 `org-todo-keywords'.
8922 If the current word is preceded by a backslash, completes the TeX symbols
8923 that are supported for HTML support.
8924 If the current word is preceded by \"#+\", completes special words for
8925 setting file options.
8926 In the line after \"#+STARTUP:, complete valid keywords.\"
8927 At all other locations, this simply calls the value of
8928 `org-completion-fallback-command'."
8929 (interactive "P")
8930 (org-without-partial-completion
8931 (catch 'exit
8932 (let* ((a nil)
8933 (end (point))
8934 (beg1 (save-excursion
8935 (skip-chars-backward (org-re "[:alnum:]_@"))
8936 (point)))
8937 (beg (save-excursion
8938 (skip-chars-backward "a-zA-Z0-9_:$")
8939 (point)))
8940 (confirm (lambda (x) (stringp (car x))))
8941 (searchhead (equal (char-before beg) ?*))
8942 (struct
8943 (when (and (member (char-before beg1) '(?. ?<))
8944 (setq a (assoc (buffer-substring beg1 (point))
8945 org-structure-template-alist)))
8946 (org-complete-expand-structure-template (1- beg1) a)
8947 (throw 'exit t)))
8948 (tag (and (equal (char-before beg1) ?:)
8949 (equal (char-after (point-at-bol)) ?*)))
8950 (prop (and (equal (char-before beg1) ?:)
8951 (not (equal (char-after (point-at-bol)) ?*))))
8952 (texp (equal (char-before beg) ?\\))
8953 (link (equal (char-before beg) ?\[))
8954 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8955 beg)
8956 "#+"))
8957 (startup (string-match "^#\\+STARTUP:.*"
8958 (buffer-substring (point-at-bol) (point))))
8959 (completion-ignore-case opt)
8960 (type nil)
8961 (tbl nil)
8962 (table (cond
8963 (opt
8964 (setq type :opt)
8965 (require 'org-exp)
8966 (append
8967 (mapcar
8968 (lambda (x)
8969 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8970 (cons (match-string 2 x) (match-string 1 x)))
8971 (org-split-string (org-get-current-options) "\n"))
8972 (mapcar 'list org-additional-option-like-keywords)))
8973 (startup
8974 (setq type :startup)
8975 org-startup-options)
8976 (link (append org-link-abbrev-alist-local
8977 org-link-abbrev-alist))
8978 (texp
8979 (setq type :tex)
8980 org-html-entities)
8981 ((string-match "\\`\\*+[ \t]+\\'"
8982 (buffer-substring (point-at-bol) beg))
8983 (setq type :todo)
8984 (mapcar 'list org-todo-keywords-1))
8985 (searchhead
8986 (setq type :searchhead)
8987 (save-excursion
8988 (goto-char (point-min))
8989 (while (re-search-forward org-todo-line-regexp nil t)
8990 (push (list
8991 (org-make-org-heading-search-string
8992 (match-string 3) t))
8993 tbl)))
8994 tbl)
8995 (tag (setq type :tag beg beg1)
8996 (or org-tag-alist (org-get-buffer-tags)))
8997 (prop (setq type :prop beg beg1)
8998 (mapcar 'list (org-buffer-property-keys nil t t)))
8999 (t (progn
9000 (call-interactively org-completion-fallback-command)
9001 (throw 'exit nil)))))
9002 (pattern (buffer-substring-no-properties beg end))
9003 (completion (try-completion pattern table confirm)))
9004 (cond ((eq completion t)
9005 (if (not (assoc (upcase pattern) table))
9006 (message "Already complete")
9007 (if (and (equal type :opt)
9008 (not (member (car (assoc (upcase pattern) table))
9009 org-additional-option-like-keywords)))
9010 (insert (substring (cdr (assoc (upcase pattern) table))
9011 (length pattern)))
9012 (if (memq type '(:tag :prop)) (insert ":")))))
9013 ((null completion)
9014 (message "Can't find completion for \"%s\"" pattern)
9015 (ding))
9016 ((not (string= pattern completion))
9017 (delete-region beg end)
9018 (if (string-match " +$" completion)
9019 (setq completion (replace-match "" t t completion)))
9020 (insert completion)
9021 (if (get-buffer-window "*Completions*")
9022 (delete-window (get-buffer-window "*Completions*")))
9023 (if (assoc completion table)
9024 (if (eq type :todo) (insert " ")
9025 (if (memq type '(:tag :prop)) (insert ":"))))
9026 (if (and (equal type :opt) (assoc completion table))
9027 (message "%s" (substitute-command-keys
9028 "Press \\[org-complete] again to insert example settings"))))
9030 (message "Making completion list...")
9031 (let ((list (sort (all-completions pattern table confirm)
9032 'string<)))
9033 (with-output-to-temp-buffer "*Completions*"
9034 (condition-case nil
9035 ;; Protection needed for XEmacs and emacs 21
9036 (display-completion-list list pattern)
9037 (error (display-completion-list list)))))
9038 (message "Making completion list...%s" "done")))))))
9040 ;;;; TODO, DEADLINE, Comments
9042 (defun org-toggle-comment ()
9043 "Change the COMMENT state of an entry."
9044 (interactive)
9045 (save-excursion
9046 (org-back-to-heading)
9047 (let (case-fold-search)
9048 (if (looking-at (concat outline-regexp
9049 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9050 (replace-match "" t t nil 1)
9051 (if (looking-at outline-regexp)
9052 (progn
9053 (goto-char (match-end 0))
9054 (insert org-comment-string " ")))))))
9056 (defvar org-last-todo-state-is-todo nil
9057 "This is non-nil when the last TODO state change led to a TODO state.
9058 If the last change removed the TODO tag or switched to DONE, then
9059 this is nil.")
9061 (defvar org-setting-tags nil) ; dynamically skipped
9063 (defun org-parse-local-options (string var)
9064 "Parse STRING for startup setting relevant for variable VAR."
9065 (let ((rtn (symbol-value var))
9066 e opts)
9067 (save-match-data
9068 (if (or (not string) (not (string-match "\\S-" string)))
9070 (setq opts (delq nil (mapcar (lambda (x)
9071 (setq e (assoc x org-startup-options))
9072 (if (eq (nth 1 e) var) e nil))
9073 (org-split-string string "[ \t]+"))))
9074 (if (not opts)
9076 (setq rtn nil)
9077 (while (setq e (pop opts))
9078 (if (not (nth 3 e))
9079 (setq rtn (nth 2 e))
9080 (if (not (listp rtn)) (setq rtn nil))
9081 (push (nth 2 e) rtn)))
9082 rtn)))))
9084 (defvar org-todo-setup-filter-hook nil
9085 "Hook for functions that pre-filter todo specs.
9087 Each function takes a todo spec and returns either `nil' or the spec
9088 transformed into canonical form." )
9090 (defvar org-todo-get-default-hook nil
9091 "Hook for functions that get a default item for todo.
9093 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9094 `nil' or a string to be used for the todo mark." )
9096 (defvar org-agenda-headline-snapshot-before-repeat)
9097 (defun org-todo (&optional arg)
9098 "Change the TODO state of an item.
9099 The state of an item is given by a keyword at the start of the heading,
9100 like
9101 *** TODO Write paper
9102 *** DONE Call mom
9104 The different keywords are specified in the variable `org-todo-keywords'.
9105 By default the available states are \"TODO\" and \"DONE\".
9106 So for this example: when the item starts with TODO, it is changed to DONE.
9107 When it starts with DONE, the DONE is removed. And when neither TODO nor
9108 DONE are present, add TODO at the beginning of the heading.
9110 With C-u prefix arg, use completion to determine the new state.
9111 With numeric prefix arg, switch to that state.
9112 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9113 With a tripple C-u prefix, circumvent any state blocking.
9115 For calling through lisp, arg is also interpreted in the following way:
9116 'none -> empty state
9117 \"\"(empty string) -> switch to empty state
9118 'done -> switch to DONE
9119 'nextset -> switch to the next set of keywords
9120 'previousset -> switch to the previous set of keywords
9121 \"WAITING\" -> switch to the specified keyword, but only if it
9122 really is a member of `org-todo-keywords'."
9123 (interactive "P")
9124 (if (equal arg '(16)) (setq arg 'nextset))
9125 (let ((org-blocker-hook org-blocker-hook)
9126 (case-fold-search nil))
9127 (when (equal arg '(64))
9128 (setq arg nil org-blocker-hook nil))
9129 (when (and org-blocker-hook
9130 (org-entry-get nil "NOBLOCKING"))
9131 (setq org-blocker-hook nil))
9132 (save-excursion
9133 (catch 'exit
9134 (org-back-to-heading)
9135 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9136 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9137 (looking-at " *"))
9138 (let* ((match-data (match-data))
9139 (startpos (point-at-bol))
9140 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9141 (org-log-done org-log-done)
9142 (org-log-repeat org-log-repeat)
9143 (org-todo-log-states org-todo-log-states)
9144 (this (match-string 1))
9145 (hl-pos (match-beginning 0))
9146 (head (org-get-todo-sequence-head this))
9147 (ass (assoc head org-todo-kwd-alist))
9148 (interpret (nth 1 ass))
9149 (done-word (nth 3 ass))
9150 (final-done-word (nth 4 ass))
9151 (last-state (or this ""))
9152 (completion-ignore-case t)
9153 (member (member this org-todo-keywords-1))
9154 (tail (cdr member))
9155 (state (cond
9156 ((and org-todo-key-trigger
9157 (or (and (equal arg '(4))
9158 (eq org-use-fast-todo-selection 'prefix))
9159 (and (not arg) org-use-fast-todo-selection
9160 (not (eq org-use-fast-todo-selection
9161 'prefix)))))
9162 ;; Use fast selection
9163 (org-fast-todo-selection))
9164 ((and (equal arg '(4))
9165 (or (not org-use-fast-todo-selection)
9166 (not org-todo-key-trigger)))
9167 ;; Read a state with completion
9168 (org-ido-completing-read
9169 "State: " (mapcar (lambda(x) (list x))
9170 org-todo-keywords-1)
9171 nil t))
9172 ((eq arg 'right)
9173 (if this
9174 (if tail (car tail) nil)
9175 (car org-todo-keywords-1)))
9176 ((eq arg 'left)
9177 (if (equal member org-todo-keywords-1)
9179 (if this
9180 (nth (- (length org-todo-keywords-1)
9181 (length tail) 2)
9182 org-todo-keywords-1)
9183 (org-last org-todo-keywords-1))))
9184 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9185 (setq arg nil))) ; hack to fall back to cycling
9186 (arg
9187 ;; user or caller requests a specific state
9188 (cond
9189 ((equal arg "") nil)
9190 ((eq arg 'none) nil)
9191 ((eq arg 'done) (or done-word (car org-done-keywords)))
9192 ((eq arg 'nextset)
9193 (or (car (cdr (member head org-todo-heads)))
9194 (car org-todo-heads)))
9195 ((eq arg 'previousset)
9196 (let ((org-todo-heads (reverse org-todo-heads)))
9197 (or (car (cdr (member head org-todo-heads)))
9198 (car org-todo-heads))))
9199 ((car (member arg org-todo-keywords-1)))
9200 ((nth (1- (prefix-numeric-value arg))
9201 org-todo-keywords-1))))
9202 ((null member) (or head (car org-todo-keywords-1)))
9203 ((equal this final-done-word) nil) ;; -> make empty
9204 ((null tail) nil) ;; -> first entry
9205 ((memq interpret '(type priority))
9206 (if (eq this-command last-command)
9207 (car tail)
9208 (if (> (length tail) 0)
9209 (or done-word (car org-done-keywords))
9210 nil)))
9212 (car tail))))
9213 (state (or
9214 (run-hook-with-args-until-success
9215 'org-todo-get-default-hook state last-state)
9216 state))
9217 (next (if state (concat " " state " ") " "))
9218 (change-plist (list :type 'todo-state-change :from this :to state
9219 :position startpos))
9220 dolog now-done-p)
9221 (when org-blocker-hook
9222 (setq org-last-todo-state-is-todo
9223 (not (member this org-done-keywords)))
9224 (unless (save-excursion
9225 (save-match-data
9226 (run-hook-with-args-until-failure
9227 'org-blocker-hook change-plist)))
9228 (if (interactive-p)
9229 (error "TODO state change from %s to %s blocked" this state)
9230 ;; fail silently
9231 (message "TODO state change from %s to %s blocked" this state)
9232 (throw 'exit nil))))
9233 (store-match-data match-data)
9234 (replace-match next t t)
9235 (unless (pos-visible-in-window-p hl-pos)
9236 (message "TODO state changed to %s" (org-trim next)))
9237 (unless head
9238 (setq head (org-get-todo-sequence-head state)
9239 ass (assoc head org-todo-kwd-alist)
9240 interpret (nth 1 ass)
9241 done-word (nth 3 ass)
9242 final-done-word (nth 4 ass)))
9243 (when (memq arg '(nextset previousset))
9244 (message "Keyword-Set %d/%d: %s"
9245 (- (length org-todo-sets) -1
9246 (length (memq (assoc state org-todo-sets) org-todo-sets)))
9247 (length org-todo-sets)
9248 (mapconcat 'identity (assoc state org-todo-sets) " ")))
9249 (setq org-last-todo-state-is-todo
9250 (not (member state org-done-keywords)))
9251 (setq now-done-p (and (member state org-done-keywords)
9252 (not (member this org-done-keywords))))
9253 (and logging (org-local-logging logging))
9254 (when (and (or org-todo-log-states org-log-done)
9255 (not (memq arg '(nextset previousset))))
9256 ;; we need to look at recording a time and note
9257 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
9258 (nth 2 (assoc this org-todo-log-states))))
9259 (when (and state
9260 (member state org-not-done-keywords)
9261 (not (member this org-not-done-keywords)))
9262 ;; This is now a todo state and was not one before
9263 ;; If there was a CLOSED time stamp, get rid of it.
9264 (org-add-planning-info nil nil 'closed))
9265 (when (and now-done-p org-log-done)
9266 ;; It is now done, and it was not done before
9267 (org-add-planning-info 'closed (org-current-time))
9268 (if (and (not dolog) (eq 'note org-log-done))
9269 (org-add-log-setup 'done state this 'findpos 'note)))
9270 (when (and state dolog)
9271 ;; This is a non-nil state, and we need to log it
9272 (org-add-log-setup 'state state this 'findpos dolog)))
9273 ;; Fixup tag positioning
9274 (org-todo-trigger-tag-changes state)
9275 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
9276 (when org-provide-todo-statistics
9277 (org-update-parent-todo-statistics))
9278 (run-hooks 'org-after-todo-state-change-hook)
9279 (if (and arg (not (member state org-done-keywords)))
9280 (setq head (org-get-todo-sequence-head state)))
9281 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9282 ;; Do we need to trigger a repeat?
9283 (when now-done-p
9284 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
9285 ;; This is for the agenda, take a snapshot of the headline.
9286 (save-match-data
9287 (setq org-agenda-headline-snapshot-before-repeat
9288 (org-get-heading))))
9289 (org-auto-repeat-maybe state))
9290 ;; Fixup cursor location if close to the keyword
9291 (if (and (outline-on-heading-p)
9292 (not (bolp))
9293 (save-excursion (beginning-of-line 1)
9294 (looking-at org-todo-line-regexp))
9295 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9296 (progn
9297 (goto-char (or (match-end 2) (match-end 1)))
9298 (and (looking-at " ") (just-one-space))))
9299 (when org-trigger-hook
9300 (save-excursion
9301 (run-hook-with-args 'org-trigger-hook change-plist))))))))
9303 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
9304 "Block turning an entry into a TODO, using the hierarchy.
9305 This checks whether the current task should be blocked from state
9306 changes. Such blocking occurs when:
9308 1. The task has children which are not all in a completed state.
9310 2. A task has a parent with the property :ORDERED:, and there
9311 are siblings prior to the current task with incomplete
9312 status.
9314 3. The parent of the task is blocked because it has siblings that should
9315 be done first, or is child of a block grandparent TODO entry."
9317 (catch 'dont-block
9318 ;; If this is not a todo state change, or if this entry is already DONE,
9319 ;; do not block
9320 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9321 (member (plist-get change-plist :from)
9322 (cons 'done org-done-keywords))
9323 (member (plist-get change-plist :to)
9324 (cons 'todo org-not-done-keywords)))
9325 (throw 'dont-block t))
9326 ;; If this task has children, and any are undone, it's blocked
9327 (save-excursion
9328 (org-back-to-heading t)
9329 (let ((this-level (funcall outline-level)))
9330 (outline-next-heading)
9331 (let ((child-level (funcall outline-level)))
9332 (while (and (not (eobp))
9333 (> child-level this-level))
9334 ;; this todo has children, check whether they are all
9335 ;; completed
9336 (if (and (not (org-entry-is-done-p))
9337 (org-entry-is-todo-p))
9338 (throw 'dont-block nil))
9339 (outline-next-heading)
9340 (setq child-level (funcall outline-level))))))
9341 ;; Otherwise, if the task's parent has the :ORDERED: property, and
9342 ;; any previous siblings are undone, it's blocked
9343 (save-excursion
9344 (org-back-to-heading t)
9345 (let* ((pos (point))
9346 (parent-pos (and (org-up-heading-safe) (point))))
9347 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9348 (when (and (org-entry-get (point) "ORDERED")
9349 (forward-line 1)
9350 (re-search-forward org-not-done-heading-regexp pos t))
9351 (throw 'dont-block nil)) ; block, there is an older sibling not done.
9352 ;; Search further up the hierarchy, to see if an anchestor is blocked
9353 (while t
9354 (goto-char parent-pos)
9355 (if (not (looking-at org-not-done-heading-regexp))
9356 (throw 'dont-block t)) ; do not block, parent is not a TODO
9357 (setq pos (point))
9358 (setq parent-pos (and (org-up-heading-safe) (point)))
9359 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9360 (when (and (org-entry-get (point) "ORDERED")
9361 (forward-line 1)
9362 (re-search-forward org-not-done-heading-regexp pos t))
9363 (throw 'dont-block nil))))))) ; block, older sibling not done.
9365 (defcustom org-track-ordered-property-with-tag nil
9366 "Should the ORDERED property also be shown as a tag?
9367 The ORDERED property decides if an entry should require subtasks to be
9368 completed in sequence. Since a property is not very visible, setting
9369 this option means that toggling the ORDERED property with the command
9370 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
9371 not relevant for the behavior, but it makes things more visible.
9373 Note that toggling the tag with tags commands will not change the property
9374 and therefore not influence behavior!
9376 This can be t, meaning the tag ORDERED should be used, It can also be a
9377 string to select a different tag for this task."
9378 :group 'org-todo
9379 :type '(choice
9380 (const :tag "No tracking" nil)
9381 (const :tag "Track with ORDERED tag" t)
9382 (string :tag "Use other tag")))
9384 (defun org-toggle-ordered-property ()
9385 "Toggle the ORDERED property of the current entry.
9386 For better visibility, you can track the value of this property with a tag.
9387 See variable `org-track-ordered-property-with-tag'."
9388 (interactive)
9389 (let* ((t1 org-track-ordered-property-with-tag)
9390 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
9391 (save-excursion
9392 (org-back-to-heading)
9393 (if (org-entry-get nil "ORDERED")
9394 (progn
9395 (org-delete-property "ORDERED")
9396 (and tag (org-toggle-tag tag 'off))
9397 (message "Subtasks can be completed in arbitrary order"))
9398 (org-entry-put nil "ORDERED" "t")
9399 (and tag (org-toggle-tag tag 'on))
9400 (message "Subtasks must be completed in sequence")))))
9402 (defvar org-blocked-by-checkboxes) ; dynamically scoped
9403 (defun org-block-todo-from-checkboxes (change-plist)
9404 "Block turning an entry into a TODO, using checkboxes.
9405 This checks whether the current task should be blocked from state
9406 changes because there are uncheckd boxes in this entry."
9407 (catch 'dont-block
9408 ;; If this is not a todo state change, or if this entry is already DONE,
9409 ;; do not block
9410 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9411 (member (plist-get change-plist :from)
9412 (cons 'done org-done-keywords))
9413 (member (plist-get change-plist :to)
9414 (cons 'todo org-not-done-keywords)))
9415 (throw 'dont-block t))
9416 ;; If this task has checkboxes that are not checked, it's blocked
9417 (save-excursion
9418 (org-back-to-heading t)
9419 (let ((beg (point)) end)
9420 (outline-next-heading)
9421 (setq end (point))
9422 (goto-char beg)
9423 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
9424 end t)
9425 (progn
9426 (if (boundp 'org-blocked-by-checkboxes)
9427 (setq org-blocked-by-checkboxes t))
9428 (throw 'dont-block nil)))))
9429 t)) ; do not block
9431 (defun org-update-parent-todo-statistics ()
9432 "Update any statistics cookie in the parent of the current headline."
9433 (interactive)
9434 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
9435 level (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
9436 (catch 'exit
9437 (save-excursion
9438 (setq level (org-up-heading-safe))
9439 (unless (and level
9440 (not (equal (downcase
9441 (or (org-entry-get
9442 nil "COOKIE_DATA")
9443 ""))
9444 "checkbox")))
9445 (throw 'exit nil))
9446 (while (re-search-forward box-re (point-at-eol) t)
9447 (setq cnt-all 0 cnt-done 0 cookie-present t)
9448 (setq is-percent (match-end 2))
9449 (save-match-data
9450 (unless (outline-next-heading) (throw 'exit nil))
9451 (while (looking-at org-todo-line-regexp)
9452 (setq kwd (match-string 2))
9453 (and kwd (setq cnt-all (1+ cnt-all)))
9454 (and (member kwd org-done-keywords)
9455 (setq cnt-done (1+ cnt-done)))
9456 (condition-case nil
9457 (org-forward-same-level 1)
9458 (error (end-of-line 1)))))
9459 (replace-match
9460 (if is-percent
9461 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
9462 (format "[%d/%d]" cnt-done cnt-all))))
9463 (when cookie-present
9464 (run-hook-with-args 'org-after-todo-statistics-hook
9465 cnt-done (- cnt-all cnt-done)))))
9466 (run-hooks 'org-todo-statistics-hook)))
9468 (defvar org-after-todo-statistics-hook nil
9469 "Hook that is called after a TODO statistics cookie has been updated.
9470 Each function is called with two arguments: the number of not-done entries
9471 and the number of done entries.
9473 For example, the following function, when added to this hook, will switch
9474 an entry to DONE when all children are done, and back to TODO when new
9475 entries are set to a TODO status. Note that this hook is only called
9476 when there is a statistics cookie in the headline!
9478 (defun org-summary-todo (n-done n-not-done)
9479 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
9480 (let (org-log-done org-log-states) ; turn off logging
9481 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
9484 (defvar org-todo-statistics-hook nil
9485 "Hook that is run whenever Org thinks TODO statistics should be updated.
9486 This hook runs even if there is no statisics cookie present, in which case
9487 `org-after-todo-statistics-hook' would not run.")
9489 (defun org-todo-trigger-tag-changes (state)
9490 "Apply the changes defined in `org-todo-state-tags-triggers'."
9491 (let ((l org-todo-state-tags-triggers)
9492 changes)
9493 (when (or (not state) (equal state ""))
9494 (setq changes (append changes (cdr (assoc "" l)))))
9495 (when (and (stringp state) (> (length state) 0))
9496 (setq changes (append changes (cdr (assoc state l)))))
9497 (when (member state org-not-done-keywords)
9498 (setq changes (append changes (cdr (assoc 'todo l)))))
9499 (when (member state org-done-keywords)
9500 (setq changes (append changes (cdr (assoc 'done l)))))
9501 (dolist (c changes)
9502 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
9504 (defun org-local-logging (value)
9505 "Get logging settings from a property VALUE."
9506 (let* (words w a)
9507 ;; directly set the variables, they are already local.
9508 (setq org-log-done nil
9509 org-log-repeat nil
9510 org-todo-log-states nil)
9511 (setq words (org-split-string value))
9512 (while (setq w (pop words))
9513 (cond
9514 ((setq a (assoc w org-startup-options))
9515 (and (member (nth 1 a) '(org-log-done org-log-repeat))
9516 (set (nth 1 a) (nth 2 a))))
9517 ((setq a (org-extract-log-state-settings w))
9518 (and (member (car a) org-todo-keywords-1)
9519 (push a org-todo-log-states)))))))
9521 (defun org-get-todo-sequence-head (kwd)
9522 "Return the head of the TODO sequence to which KWD belongs.
9523 If KWD is not set, check if there is a text property remembering the
9524 right sequence."
9525 (let (p)
9526 (cond
9527 ((not kwd)
9528 (or (get-text-property (point-at-bol) 'org-todo-head)
9529 (progn
9530 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
9531 nil (point-at-eol)))
9532 (get-text-property p 'org-todo-head))))
9533 ((not (member kwd org-todo-keywords-1))
9534 (car org-todo-keywords-1))
9535 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
9537 (defun org-fast-todo-selection ()
9538 "Fast TODO keyword selection with single keys.
9539 Returns the new TODO keyword, or nil if no state change should occur."
9540 (let* ((fulltable org-todo-key-alist)
9541 (done-keywords org-done-keywords) ;; needed for the faces.
9542 (maxlen (apply 'max (mapcar
9543 (lambda (x)
9544 (if (stringp (car x)) (string-width (car x)) 0))
9545 fulltable)))
9546 (expert nil)
9547 (fwidth (+ maxlen 3 1 3))
9548 (ncol (/ (- (window-width) 4) fwidth))
9549 tg cnt e c tbl
9550 groups ingroup)
9551 (save-excursion
9552 (save-window-excursion
9553 (if expert
9554 (set-buffer (get-buffer-create " *Org todo*"))
9555 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
9556 (erase-buffer)
9557 (org-set-local 'org-done-keywords done-keywords)
9558 (setq tbl fulltable cnt 0)
9559 (while (setq e (pop tbl))
9560 (cond
9561 ((equal e '(:startgroup))
9562 (push '() groups) (setq ingroup t)
9563 (when (not (= cnt 0))
9564 (setq cnt 0)
9565 (insert "\n"))
9566 (insert "{ "))
9567 ((equal e '(:endgroup))
9568 (setq ingroup nil cnt 0)
9569 (insert "}\n"))
9570 ((equal e '(:newline))
9571 (when (not (= cnt 0))
9572 (setq cnt 0)
9573 (insert "\n")
9574 (setq e (car tbl))
9575 (while (equal (car tbl) '(:newline))
9576 (insert "\n")
9577 (setq tbl (cdr tbl)))))
9579 (setq tg (car e) c (cdr e))
9580 (if ingroup (push tg (car groups)))
9581 (setq tg (org-add-props tg nil 'face
9582 (org-get-todo-face tg)))
9583 (if (and (= cnt 0) (not ingroup)) (insert " "))
9584 (insert "[" c "] " tg (make-string
9585 (- fwidth 4 (length tg)) ?\ ))
9586 (when (= (setq cnt (1+ cnt)) ncol)
9587 (insert "\n")
9588 (if ingroup (insert " "))
9589 (setq cnt 0)))))
9590 (insert "\n")
9591 (goto-char (point-min))
9592 (if (not expert) (org-fit-window-to-buffer))
9593 (message "[a-z..]:Set [SPC]:clear")
9594 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9595 (cond
9596 ((or (= c ?\C-g)
9597 (and (= c ?q) (not (rassoc c fulltable))))
9598 (setq quit-flag t))
9599 ((= c ?\ ) nil)
9600 ((setq e (rassoc c fulltable) tg (car e))
9602 (t (setq quit-flag t)))))))
9604 (defun org-entry-is-todo-p ()
9605 (member (org-get-todo-state) org-not-done-keywords))
9607 (defun org-entry-is-done-p ()
9608 (member (org-get-todo-state) org-done-keywords))
9610 (defun org-get-todo-state ()
9611 (save-excursion
9612 (org-back-to-heading t)
9613 (and (looking-at org-todo-line-regexp)
9614 (match-end 2)
9615 (match-string 2))))
9617 (defun org-at-date-range-p (&optional inactive-ok)
9618 "Is the cursor inside a date range?"
9619 (interactive)
9620 (save-excursion
9621 (catch 'exit
9622 (let ((pos (point)))
9623 (skip-chars-backward "^[<\r\n")
9624 (skip-chars-backward "<[")
9625 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9626 (>= (match-end 0) pos)
9627 (throw 'exit t))
9628 (skip-chars-backward "^<[\r\n")
9629 (skip-chars-backward "<[")
9630 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9631 (>= (match-end 0) pos)
9632 (throw 'exit t)))
9633 nil)))
9635 (defun org-get-repeat ()
9636 "Check if there is a deadline/schedule with repeater in this entry."
9637 (save-match-data
9638 (save-excursion
9639 (org-back-to-heading t)
9640 (if (re-search-forward
9641 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9642 (match-string 1)))))
9644 (defvar org-last-changed-timestamp)
9645 (defvar org-last-inserted-timestamp)
9646 (defvar org-log-post-message)
9647 (defvar org-log-note-purpose)
9648 (defvar org-log-note-how)
9649 (defvar org-log-note-extra)
9650 (defun org-auto-repeat-maybe (done-word)
9651 "Check if the current headline contains a repeated deadline/schedule.
9652 If yes, set TODO state back to what it was and change the base date
9653 of repeating deadline/scheduled time stamps to new date.
9654 This function is run automatically after each state change to a DONE state."
9655 ;; last-state is dynamically scoped into this function
9656 (let* ((repeat (org-get-repeat))
9657 (aa (assoc last-state org-todo-kwd-alist))
9658 (interpret (nth 1 aa))
9659 (head (nth 2 aa))
9660 (whata '(("d" . day) ("m" . month) ("y" . year)))
9661 (msg "Entry repeats: ")
9662 (org-log-done nil)
9663 (org-todo-log-states nil)
9664 (nshiftmax 10) (nshift 0)
9665 re type n what ts time)
9666 (when repeat
9667 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9668 (org-todo (if (eq interpret 'type) last-state head))
9669 (when org-log-repeat
9670 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9671 (memq 'org-add-log-note post-command-hook))
9672 ;; OK, we are already setup for some record
9673 (if (eq org-log-repeat 'note)
9674 ;; make sure we take a note, not only a time stamp
9675 (setq org-log-note-how 'note))
9676 ;; Set up for taking a record
9677 (org-add-log-setup 'state (or done-word (car org-done-keywords))
9678 last-state
9679 'findpos org-log-repeat)))
9680 (org-back-to-heading t)
9681 (org-add-planning-info nil nil 'closed)
9682 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9683 org-deadline-time-regexp "\\)\\|\\("
9684 org-ts-regexp "\\)"))
9685 (while (re-search-forward
9686 re (save-excursion (outline-next-heading) (point)) t)
9687 (setq type (if (match-end 1) org-scheduled-string
9688 (if (match-end 3) org-deadline-string "Plain:"))
9689 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
9690 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
9691 (setq n (string-to-number (match-string 2 ts))
9692 what (match-string 3 ts))
9693 (if (equal what "w") (setq n (* n 7) what "d"))
9694 ;; Preparation, see if we need to modify the start date for the change
9695 (when (match-end 1)
9696 (setq time (save-match-data (org-time-string-to-time ts)))
9697 (cond
9698 ((equal (match-string 1 ts) ".")
9699 ;; Shift starting date to today
9700 (org-timestamp-change
9701 (- (time-to-days (current-time)) (time-to-days time))
9702 'day))
9703 ((equal (match-string 1 ts) "+")
9704 (while (or (= nshift 0)
9705 (<= (time-to-days time) (time-to-days (current-time))))
9706 (when (= (incf nshift) nshiftmax)
9707 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
9708 (error "Abort")))
9709 (org-timestamp-change n (cdr (assoc what whata)))
9710 (org-at-timestamp-p t)
9711 (setq ts (match-string 1))
9712 (setq time (save-match-data (org-time-string-to-time ts))))
9713 (org-timestamp-change (- n) (cdr (assoc what whata)))
9714 ;; rematch, so that we have everything in place for the real shift
9715 (org-at-timestamp-p t)
9716 (setq ts (match-string 1))
9717 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
9718 (org-timestamp-change n (cdr (assoc what whata)))
9719 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
9720 (setq org-log-post-message msg)
9721 (message "%s" msg))))
9723 (defun org-show-todo-tree (arg)
9724 "Make a compact tree which shows all headlines marked with TODO.
9725 The tree will show the lines where the regexp matches, and all higher
9726 headlines above the match.
9727 With a \\[universal-argument] prefix, also show the DONE entries.
9728 With a numeric prefix N, construct a sparse tree for the Nth element
9729 of `org-todo-keywords-1'."
9730 (interactive "P")
9731 (let ((case-fold-search nil)
9732 (kwd-re
9733 (cond ((null arg) org-not-done-regexp)
9734 ((equal arg '(4))
9735 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
9736 (mapcar 'list org-todo-keywords-1))))
9737 (concat "\\("
9738 (mapconcat 'identity (org-split-string kwd "|") "\\|")
9739 "\\)\\>")))
9740 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
9741 (regexp-quote (nth (1- (prefix-numeric-value arg))
9742 org-todo-keywords-1)))
9743 (t (error "Invalid prefix argument: %s" arg)))))
9744 (message "%d TODO entries found"
9745 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
9747 (defun org-deadline (&optional remove time)
9748 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
9749 With argument REMOVE, remove any deadline from the item.
9750 When TIME is set, it should be an internal time specification, and the
9751 scheduling will use the corresponding date."
9752 (interactive "P")
9753 (if remove
9754 (progn
9755 (org-remove-timestamp-with-keyword org-deadline-string)
9756 (message "Item no longer has a deadline."))
9757 (if (org-get-repeat)
9758 (error "Cannot change deadline on task with repeater, please do that by hand")
9759 (org-add-planning-info 'deadline time 'closed)
9760 (message "Deadline on %s" org-last-inserted-timestamp))))
9762 (defun org-schedule (&optional remove time)
9763 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
9764 With argument REMOVE, remove any scheduling date from the item.
9765 When TIME is set, it should be an internal time specification, and the
9766 scheduling will use the corresponding date."
9767 (interactive "P")
9768 (if remove
9769 (progn
9770 (org-remove-timestamp-with-keyword org-scheduled-string)
9771 (message "Item is no longer scheduled."))
9772 (if (org-get-repeat)
9773 (error "Cannot reschedule task with repeater, please do that by hand")
9774 (org-add-planning-info 'scheduled time 'closed)
9775 (message "Scheduled to %s" org-last-inserted-timestamp))))
9777 (defun org-get-scheduled-time (pom &optional inherit)
9778 "Get the scheduled time as a time tuple, of a format suitable
9779 for calling org-schedule with, or if there is no scheduling,
9780 returns nil."
9781 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
9782 (when time
9783 (apply 'encode-time (org-parse-time-string time)))))
9785 (defun org-get-deadline-time (pom &optional inherit)
9786 "Get the deadine as a time tuple, of a format suitable for
9787 calling org-deadlin with, or if there is no scheduling, returns
9788 nil."
9789 (let ((time (org-entry-get pom "DEADLINE" inherit)))
9790 (when time
9791 (apply 'encode-time (org-parse-time-string time)))))
9793 (defun org-remove-timestamp-with-keyword (keyword)
9794 "Remove all time stamps with KEYWORD in the current entry."
9795 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
9796 beg)
9797 (save-excursion
9798 (org-back-to-heading t)
9799 (setq beg (point))
9800 (org-end-of-subtree t t)
9801 (while (re-search-backward re beg t)
9802 (replace-match "")
9803 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9804 (equal (char-before) ?\ ))
9805 (backward-delete-char 1)
9806 (if (string-match "^[ \t]*$" (buffer-substring
9807 (point-at-bol) (point-at-eol)))
9808 (delete-region (point-at-bol)
9809 (min (point-max) (1+ (point-at-eol))))))))))
9811 (defun org-add-planning-info (what &optional time &rest remove)
9812 "Insert new timestamp with keyword in the line directly after the headline.
9813 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9814 If non is given, the user is prompted for a date.
9815 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9816 be removed."
9817 (interactive)
9818 (let (org-time-was-given org-end-time-was-given ts
9819 end default-time default-input)
9821 (catch 'exit
9822 (when (and (not time) (memq what '(scheduled deadline)))
9823 ;; Try to get a default date/time from existing timestamp
9824 (save-excursion
9825 (org-back-to-heading t)
9826 (setq end (save-excursion (outline-next-heading) (point)))
9827 (when (re-search-forward (if (eq what 'scheduled)
9828 org-scheduled-time-regexp
9829 org-deadline-time-regexp)
9830 end t)
9831 (setq ts (match-string 1)
9832 default-time
9833 (apply 'encode-time (org-parse-time-string ts))
9834 default-input (and ts (org-get-compact-tod ts))))))
9835 (when what
9836 ;; If necessary, get the time from the user
9837 (setq time (or time (org-read-date nil 'to-time nil nil
9838 default-time default-input))))
9840 (when (and org-insert-labeled-timestamps-at-point
9841 (member what '(scheduled deadline)))
9842 (insert
9843 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9844 (org-insert-time-stamp time org-time-was-given
9845 nil nil nil (list org-end-time-was-given))
9846 (setq what nil))
9847 (save-excursion
9848 (save-restriction
9849 (let (col list elt ts buffer-invisibility-spec)
9850 (org-back-to-heading t)
9851 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9852 (goto-char (match-end 1))
9853 (setq col (current-column))
9854 (goto-char (match-end 0))
9855 (if (eobp) (insert "\n") (forward-char 1))
9856 (when (and (not what)
9857 (not (looking-at
9858 (concat "[ \t]*"
9859 org-keyword-time-not-clock-regexp))))
9860 ;; Nothing to add, nothing to remove...... :-)
9861 (throw 'exit nil))
9862 (if (and (not (looking-at outline-regexp))
9863 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9864 "[^\r\n]*"))
9865 (not (equal (match-string 1) org-clock-string)))
9866 (narrow-to-region (match-beginning 0) (match-end 0))
9867 (insert-before-markers "\n")
9868 (backward-char 1)
9869 (narrow-to-region (point) (point))
9870 (and org-adapt-indentation (org-indent-to-column col)))
9871 ;; Check if we have to remove something.
9872 (setq list (cons what remove))
9873 (while list
9874 (setq elt (pop list))
9875 (goto-char (point-min))
9876 (when (or (and (eq elt 'scheduled)
9877 (re-search-forward org-scheduled-time-regexp nil t))
9878 (and (eq elt 'deadline)
9879 (re-search-forward org-deadline-time-regexp nil t))
9880 (and (eq elt 'closed)
9881 (re-search-forward org-closed-time-regexp nil t)))
9882 (replace-match "")
9883 (if (looking-at "--+<[^>]+>") (replace-match ""))
9884 (if (looking-at " +") (replace-match ""))))
9885 (goto-char (point-max))
9886 (when what
9887 (insert
9888 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9889 (cond ((eq what 'scheduled) org-scheduled-string)
9890 ((eq what 'deadline) org-deadline-string)
9891 ((eq what 'closed) org-closed-string))
9892 " ")
9893 (setq ts (org-insert-time-stamp
9894 time
9895 (or org-time-was-given
9896 (and (eq what 'closed) org-log-done-with-time))
9897 (eq what 'closed)
9898 nil nil (list org-end-time-was-given)))
9899 (end-of-line 1))
9900 (goto-char (point-min))
9901 (widen)
9902 (if (and (looking-at "[ \t]+\n")
9903 (equal (char-before) ?\n))
9904 (delete-region (1- (point)) (point-at-eol)))
9905 ts))))))
9907 (defvar org-log-note-marker (make-marker))
9908 (defvar org-log-note-purpose nil)
9909 (defvar org-log-note-state nil)
9910 (defvar org-log-note-previous-state nil)
9911 (defvar org-log-note-how nil)
9912 (defvar org-log-note-extra nil)
9913 (defvar org-log-note-window-configuration nil)
9914 (defvar org-log-note-return-to (make-marker))
9915 (defvar org-log-post-message nil
9916 "Message to be displayed after a log note has been stored.
9917 The auto-repeater uses this.")
9919 (defun org-add-note ()
9920 "Add a note to the current entry.
9921 This is done in the same way as adding a state change note."
9922 (interactive)
9923 (org-add-log-setup 'note nil nil 'findpos nil))
9925 (defvar org-property-end-re)
9926 (defun org-add-log-setup (&optional purpose state prev-state
9927 findpos how &optional extra)
9928 "Set up the post command hook to take a note.
9929 If this is about to TODO state change, the new state is expected in STATE.
9930 When FINDPOS is non-nil, find the correct position for the note in
9931 the current entry. If not, assume that it can be inserted at point.
9932 HOW is an indicator what kind of note should be created.
9933 EXTRA is additional text that will be inserted into the notes buffer."
9934 (let ((drawer (cond ((stringp org-log-into-drawer)
9935 org-log-into-drawer)
9936 (org-log-into-drawer "LOGBOOK")
9937 (t nil))))
9938 (save-restriction
9939 (save-excursion
9940 (when findpos
9941 (org-back-to-heading t)
9942 (narrow-to-region (point) (save-excursion
9943 (outline-next-heading) (point)))
9944 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9945 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9946 "[^\r\n]*\\)?"))
9947 (goto-char (match-end 0))
9948 (cond
9949 (drawer
9950 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
9951 nil t)
9952 (progn
9953 (goto-char (match-end 0))
9954 (or org-log-states-order-reversed
9955 (and (re-search-forward org-property-end-re nil t)
9956 (goto-char (1- (match-beginning 0))))))
9957 (insert "\n:" drawer ":\n:END:")
9958 (beginning-of-line 0)
9959 (org-indent-line-function)
9960 (beginning-of-line 2)
9961 (org-indent-line-function)
9962 (end-of-line 0)))
9963 ((and org-log-state-notes-insert-after-drawers
9964 (save-excursion
9965 (forward-line) (looking-at org-drawer-regexp)))
9966 (forward-line)
9967 (while (looking-at org-drawer-regexp)
9968 (goto-char (match-end 0))
9969 (re-search-forward org-property-end-re (point-max) t)
9970 (forward-line))
9971 (forward-line -1)))
9972 (unless org-log-states-order-reversed
9973 (and (= (char-after) ?\n) (forward-char 1))
9974 (org-skip-over-state-notes)
9975 (skip-chars-backward " \t\n\r")))
9976 (move-marker org-log-note-marker (point))
9977 (setq org-log-note-purpose purpose
9978 org-log-note-state state
9979 org-log-note-previous-state prev-state
9980 org-log-note-how how
9981 org-log-note-extra extra)
9982 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
9984 (defun org-skip-over-state-notes ()
9985 "Skip past the list of State notes in an entry."
9986 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9987 (while (looking-at "[ \t]*- State")
9988 (condition-case nil
9989 (org-next-item)
9990 (error (org-end-of-item)))))
9992 (defun org-add-log-note (&optional purpose)
9993 "Pop up a window for taking a note, and add this note later at point."
9994 (remove-hook 'post-command-hook 'org-add-log-note)
9995 (setq org-log-note-window-configuration (current-window-configuration))
9996 (delete-other-windows)
9997 (move-marker org-log-note-return-to (point))
9998 (switch-to-buffer (marker-buffer org-log-note-marker))
9999 (goto-char org-log-note-marker)
10000 (org-switch-to-buffer-other-window "*Org Note*")
10001 (erase-buffer)
10002 (if (memq org-log-note-how '(time state))
10003 (let (current-prefix-arg) (org-store-log-note))
10004 (let ((org-inhibit-startup t)) (org-mode))
10005 (insert (format "# Insert note for %s.
10006 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10007 (cond
10008 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10009 ((eq org-log-note-purpose 'done) "closed todo item")
10010 ((eq org-log-note-purpose 'state)
10011 (format "state change from \"%s\" to \"%s\""
10012 (or org-log-note-previous-state "")
10013 (or org-log-note-state "")))
10014 ((eq org-log-note-purpose 'note)
10015 "this entry")
10016 (t (error "This should not happen")))))
10017 (if org-log-note-extra (insert org-log-note-extra))
10018 (org-set-local 'org-finish-function 'org-store-log-note)))
10020 (defvar org-note-abort nil) ; dynamically scoped
10021 (defun org-store-log-note ()
10022 "Finish taking a log note, and insert it to where it belongs."
10023 (let ((txt (buffer-string))
10024 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10025 lines ind)
10026 (kill-buffer (current-buffer))
10027 (while (string-match "\\`#.*\n[ \t\n]*" txt)
10028 (setq txt (replace-match "" t t txt)))
10029 (if (string-match "\\s-+\\'" txt)
10030 (setq txt (replace-match "" t t txt)))
10031 (setq lines (org-split-string txt "\n"))
10032 (when (and note (string-match "\\S-" note))
10033 (setq note
10034 (org-replace-escapes
10035 note
10036 (list (cons "%u" (user-login-name))
10037 (cons "%U" user-full-name)
10038 (cons "%t" (format-time-string
10039 (org-time-stamp-format 'long 'inactive)
10040 (current-time)))
10041 (cons "%s" (if org-log-note-state
10042 (concat "\"" org-log-note-state "\"")
10043 ""))
10044 (cons "%S" (if org-log-note-previous-state
10045 (concat "\"" org-log-note-previous-state "\"")
10046 "\"\"")))))
10047 (if lines (setq note (concat note " \\\\")))
10048 (push note lines))
10049 (when (or current-prefix-arg org-note-abort)
10050 (when org-log-into-drawer
10051 (org-remove-empty-drawer-at
10052 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
10053 org-log-note-marker))
10054 (setq lines nil))
10055 (when lines
10056 (save-excursion
10057 (set-buffer (marker-buffer org-log-note-marker))
10058 (save-excursion
10059 (goto-char org-log-note-marker)
10060 (move-marker org-log-note-marker nil)
10061 (end-of-line 1)
10062 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
10063 (insert "- " (pop lines))
10064 (org-indent-line-function)
10065 (beginning-of-line 1)
10066 (looking-at "[ \t]*")
10067 (setq ind (concat (match-string 0) " "))
10068 (end-of-line 1)
10069 (while lines (insert "\n" ind (pop lines)))
10070 (message "Note stored")
10071 (org-back-to-heading t)
10072 (org-cycle-hide-drawers 'children)))))
10073 (set-window-configuration org-log-note-window-configuration)
10074 (with-current-buffer (marker-buffer org-log-note-return-to)
10075 (goto-char org-log-note-return-to))
10076 (move-marker org-log-note-return-to nil)
10077 (and org-log-post-message (message "%s" org-log-post-message)))
10079 (defun org-remove-empty-drawer-at (drawer pos)
10080 "Remove an emptyr DARWER drawer at position POS.
10081 POS may also be a marker."
10082 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
10083 (save-excursion
10084 (save-restriction
10085 (widen)
10086 (goto-char pos)
10087 (if (org-in-regexp
10088 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
10089 (replace-match ""))))))
10091 (defun org-sparse-tree (&optional arg)
10092 "Create a sparse tree, prompt for the details.
10093 This command can create sparse trees. You first need to select the type
10094 of match used to create the tree:
10096 t Show entries with a specific TODO keyword.
10097 m Show entries selected by a tags/property match.
10098 p Enter a property name and its value (both with completion on existing
10099 names/values) and show entries with that property.
10100 r Show entries matching a regular expression.
10101 d Show deadlines due within `org-deadline-warning-days'.
10102 b Show deadlines and scheduled items before a date.
10103 a Show deadlines and scheduled items after a date."
10104 (interactive "P")
10105 (let (ans kwd value)
10106 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
10107 (setq ans (read-char-exclusive))
10108 (cond
10109 ((equal ans ?d)
10110 (call-interactively 'org-check-deadlines))
10111 ((equal ans ?b)
10112 (call-interactively 'org-check-before-date))
10113 ((equal ans ?a)
10114 (call-interactively 'org-check-after-date))
10115 ((equal ans ?t)
10116 (org-show-todo-tree '(4)))
10117 ((member ans '(?T ?m))
10118 (call-interactively 'org-match-sparse-tree))
10119 ((member ans '(?p ?P))
10120 (setq kwd (org-ido-completing-read "Property: "
10121 (mapcar 'list (org-buffer-property-keys))))
10122 (setq value (org-ido-completing-read "Value: "
10123 (mapcar 'list (org-property-values kwd))))
10124 (unless (string-match "\\`{.*}\\'" value)
10125 (setq value (concat "\"" value "\"")))
10126 (org-match-sparse-tree arg (concat kwd "=" value)))
10127 ((member ans '(?r ?R ?/))
10128 (call-interactively 'org-occur))
10129 (t (error "No such sparse tree command \"%c\"" ans)))))
10131 (defvar org-occur-highlights nil
10132 "List of overlays used for occur matches.")
10133 (make-variable-buffer-local 'org-occur-highlights)
10134 (defvar org-occur-parameters nil
10135 "Parameters of the active org-occur calls.
10136 This is a list, each call to org-occur pushes as cons cell,
10137 containing the regular expression and the callback, onto the list.
10138 The list can contain several entries if `org-occur' has been called
10139 several time with the KEEP-PREVIOUS argument. Otherwise, this list
10140 will only contain one set of parameters. When the highlights are
10141 removed (for example with `C-c C-c', or with the next edit (depending
10142 on `org-remove-highlights-with-change'), this variable is emptied
10143 as well.")
10144 (make-variable-buffer-local 'org-occur-parameters)
10146 (defun org-occur (regexp &optional keep-previous callback)
10147 "Make a compact tree which shows all matches of REGEXP.
10148 The tree will show the lines where the regexp matches, and all higher
10149 headlines above the match. It will also show the heading after the match,
10150 to make sure editing the matching entry is easy.
10151 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
10152 call to `org-occur' will be kept, to allow stacking of calls to this
10153 command.
10154 If CALLBACK is non-nil, it is a function which is called to confirm
10155 that the match should indeed be shown."
10156 (interactive "sRegexp: \nP")
10157 (unless keep-previous
10158 (org-remove-occur-highlights nil nil t))
10159 (push (cons regexp callback) org-occur-parameters)
10160 (let ((cnt 0))
10161 (save-excursion
10162 (goto-char (point-min))
10163 (if (or (not keep-previous) ; do not want to keep
10164 (not org-occur-highlights)) ; no previous matches
10165 ;; hide everything
10166 (org-overview))
10167 (while (re-search-forward regexp nil t)
10168 (when (or (not callback)
10169 (save-match-data (funcall callback)))
10170 (setq cnt (1+ cnt))
10171 (when org-highlight-sparse-tree-matches
10172 (org-highlight-new-match (match-beginning 0) (match-end 0)))
10173 (org-show-context 'occur-tree))))
10174 (when org-remove-highlights-with-change
10175 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10176 nil 'local))
10177 (unless org-sparse-tree-open-archived-trees
10178 (org-hide-archived-subtrees (point-min) (point-max)))
10179 (run-hooks 'org-occur-hook)
10180 (if (interactive-p)
10181 (message "%d match(es) for regexp %s" cnt regexp))
10182 cnt))
10184 (defun org-show-context (&optional key)
10185 "Make sure point and context and visible.
10186 How much context is shown depends upon the variables
10187 `org-show-hierarchy-above', `org-show-following-heading'. and
10188 `org-show-siblings'."
10189 (let ((heading-p (org-on-heading-p t))
10190 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
10191 (following-p (org-get-alist-option org-show-following-heading key))
10192 (entry-p (org-get-alist-option org-show-entry-below key))
10193 (siblings-p (org-get-alist-option org-show-siblings key)))
10194 (catch 'exit
10195 ;; Show heading or entry text
10196 (if (and heading-p (not entry-p))
10197 (org-flag-heading nil) ; only show the heading
10198 (and (or entry-p (org-invisible-p) (org-invisible-p2))
10199 (org-show-hidden-entry))) ; show entire entry
10200 (when following-p
10201 ;; Show next sibling, or heading below text
10202 (save-excursion
10203 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10204 (org-flag-heading nil))))
10205 (when siblings-p (org-show-siblings))
10206 (when hierarchy-p
10207 ;; show all higher headings, possibly with siblings
10208 (save-excursion
10209 (while (and (condition-case nil
10210 (progn (org-up-heading-all 1) t)
10211 (error nil))
10212 (not (bobp)))
10213 (org-flag-heading nil)
10214 (when siblings-p (org-show-siblings))))))))
10216 (defun org-reveal (&optional siblings)
10217 "Show current entry, hierarchy above it, and the following headline.
10218 This can be used to show a consistent set of context around locations
10219 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10220 not t for the search context.
10222 With optional argument SIBLINGS, on each level of the hierarchy all
10223 siblings are shown. This repairs the tree structure to what it would
10224 look like when opened with hierarchical calls to `org-cycle'."
10225 (interactive "P")
10226 (let ((org-show-hierarchy-above t)
10227 (org-show-following-heading t)
10228 (org-show-siblings (if siblings t org-show-siblings)))
10229 (org-show-context nil)))
10231 (defun org-highlight-new-match (beg end)
10232 "Highlight from BEG to END and mark the highlight is an occur headline."
10233 (let ((ov (org-make-overlay beg end)))
10234 (org-overlay-put ov 'face 'secondary-selection)
10235 (push ov org-occur-highlights)))
10237 (defun org-remove-occur-highlights (&optional beg end noremove)
10238 "Remove the occur highlights from the buffer.
10239 BEG and END are ignored. If NOREMOVE is nil, remove this function
10240 from the `before-change-functions' in the current buffer."
10241 (interactive)
10242 (unless org-inhibit-highlight-removal
10243 (mapc 'org-delete-overlay org-occur-highlights)
10244 (setq org-occur-highlights nil)
10245 (setq org-occur-parameters nil)
10246 (unless noremove
10247 (remove-hook 'before-change-functions
10248 'org-remove-occur-highlights 'local))))
10250 ;;;; Priorities
10252 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
10253 "Regular expression matching the priority indicator.")
10255 (defvar org-remove-priority-next-time nil)
10257 (defun org-priority-up ()
10258 "Increase the priority of the current item."
10259 (interactive)
10260 (org-priority 'up))
10262 (defun org-priority-down ()
10263 "Decrease the priority of the current item."
10264 (interactive)
10265 (org-priority 'down))
10267 (defun org-priority (&optional action)
10268 "Change the priority of an item by ARG.
10269 ACTION can be `set', `up', `down', or a character."
10270 (interactive)
10271 (setq action (or action 'set))
10272 (let (current new news have remove)
10273 (save-excursion
10274 (org-back-to-heading t)
10275 (if (looking-at org-priority-regexp)
10276 (setq current (string-to-char (match-string 2))
10277 have t)
10278 (setq current org-default-priority))
10279 (cond
10280 ((or (eq action 'set)
10281 (if (featurep 'xemacs) (characterp action) (integerp action)))
10282 (if (not (eq action 'set))
10283 (setq new action)
10284 (message "Priority %c-%c, SPC to remove: "
10285 org-highest-priority org-lowest-priority)
10286 (setq new (read-char-exclusive)))
10287 (if (and (= (upcase org-highest-priority) org-highest-priority)
10288 (= (upcase org-lowest-priority) org-lowest-priority))
10289 (setq new (upcase new)))
10290 (cond ((equal new ?\ ) (setq remove t))
10291 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
10292 (error "Priority must be between `%c' and `%c'"
10293 org-highest-priority org-lowest-priority))))
10294 ((eq action 'up)
10295 (if (and (not have) (eq last-command this-command))
10296 (setq new org-lowest-priority)
10297 (setq new (if (and org-priority-start-cycle-with-default (not have))
10298 org-default-priority (1- current)))))
10299 ((eq action 'down)
10300 (if (and (not have) (eq last-command this-command))
10301 (setq new org-highest-priority)
10302 (setq new (if (and org-priority-start-cycle-with-default (not have))
10303 org-default-priority (1+ current)))))
10304 (t (error "Invalid action")))
10305 (if (or (< (upcase new) org-highest-priority)
10306 (> (upcase new) org-lowest-priority))
10307 (setq remove t))
10308 (setq news (format "%c" new))
10309 (if have
10310 (if remove
10311 (replace-match "" t t nil 1)
10312 (replace-match news t t nil 2))
10313 (if remove
10314 (error "No priority cookie found in line")
10315 (let ((case-fold-search nil))
10316 (looking-at org-todo-line-regexp))
10317 (if (match-end 2)
10318 (progn
10319 (goto-char (match-end 2))
10320 (insert " [#" news "]"))
10321 (goto-char (match-beginning 3))
10322 (insert "[#" news "] ")))))
10323 (org-preserve-lc (org-set-tags nil 'align))
10324 (if remove
10325 (message "Priority removed")
10326 (message "Priority of current item set to %s" news))))
10329 (defun org-get-priority (s)
10330 "Find priority cookie and return priority."
10331 (save-match-data
10332 (if (not (string-match org-priority-regexp s))
10333 (* 1000 (- org-lowest-priority org-default-priority))
10334 (* 1000 (- org-lowest-priority
10335 (string-to-char (match-string 2 s)))))))
10337 ;;;; Tags
10339 (defvar org-agenda-archives-mode)
10340 (defvar org-map-continue-from nil
10341 "Position from where mapping should continue.
10342 Can be set byt the action argument to `org-scan-tag's and `org-map-entries'.")
10344 (defvar org-scanner-tags nil
10345 "The current tag list while the tags scanner is running.")
10346 (defvar org-trust-scanner-tags nil
10347 "Should `org-get-tags-at' use the tags fro the scanner.
10348 This is for internal dynamical scoping only.
10349 When this is non-nil, the function `org-get-tags-at' will return the value
10350 of `org-scanner-tags' instead of building the list by itself. This
10351 can lead to large speed-ups when the tags scanner is used in a file with
10352 many entries, and when the list of tags is retrieved, for example to
10353 obtain a list of properties. Building the tags list for each entry in such
10354 a file becomes an N^2 operation - but with this variable set, it scales
10355 as N.")
10357 (defun org-scan-tags (action matcher &optional todo-only)
10358 "Scan headline tags with inheritance and produce output ACTION.
10360 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
10361 or `agenda' to produce an entry list for an agenda view. It can also be
10362 a Lisp form or a function that should be called at each matched headline, in
10363 this case the return value is a list of all return values from these calls.
10365 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
10366 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
10367 only lines with a TODO keyword are included in the output."
10368 (require 'org-agenda)
10369 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
10370 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
10371 (org-re
10372 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
10373 (props (list 'face 'default
10374 'done-face 'org-agenda-done
10375 'undone-face 'default
10376 'mouse-face 'highlight
10377 'org-not-done-regexp org-not-done-regexp
10378 'org-todo-regexp org-todo-regexp
10379 'keymap org-agenda-keymap
10380 'help-echo
10381 (format "mouse-2 or RET jump to org file %s"
10382 (abbreviate-file-name
10383 (or (buffer-file-name (buffer-base-buffer))
10384 (buffer-name (buffer-base-buffer)))))))
10385 (case-fold-search nil)
10386 (org-map-continue-from nil)
10387 lspos tags tags-list
10388 (tags-alist (list (cons 0 org-file-tags)))
10389 (llast 0) rtn rtn1 level category i txt
10390 todo marker entry priority)
10391 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
10392 (setq action (list 'lambda nil action)))
10393 (save-excursion
10394 (goto-char (point-min))
10395 (when (eq action 'sparse-tree)
10396 (org-overview)
10397 (org-remove-occur-highlights))
10398 (while (re-search-forward re nil t)
10399 (catch :skip
10400 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
10401 tags (if (match-end 4) (org-match-string-no-properties 4)))
10402 (goto-char (setq lspos (match-beginning 0)))
10403 (setq level (org-reduced-level (funcall outline-level))
10404 category (org-get-category))
10405 (setq i llast llast level)
10406 ;; remove tag lists from same and sublevels
10407 (while (>= i level)
10408 (when (setq entry (assoc i tags-alist))
10409 (setq tags-alist (delete entry tags-alist)))
10410 (setq i (1- i)))
10411 ;; add the next tags
10412 (when tags
10413 (setq tags (org-split-string tags ":")
10414 tags-alist
10415 (cons (cons level tags) tags-alist)))
10416 ;; compile tags for current headline
10417 (setq tags-list
10418 (if org-use-tag-inheritance
10419 (apply 'append (mapcar 'cdr (reverse tags-alist)))
10420 tags)
10421 org-scanner-tags tags-list)
10422 (when org-use-tag-inheritance
10423 (setcdr (car tags-alist)
10424 (mapcar (lambda (x)
10425 (setq x (copy-sequence x))
10426 (org-add-prop-inherited x))
10427 (cdar tags-alist))))
10428 (when (and tags org-use-tag-inheritance
10429 (or (not (eq t org-use-tag-inheritance))
10430 org-tags-exclude-from-inheritance))
10431 ;; selective inheritance, remove uninherited ones
10432 (setcdr (car tags-alist)
10433 (org-remove-uniherited-tags (cdar tags-alist))))
10434 (when (and (or (not todo-only)
10435 (and (member todo org-not-done-keywords)
10436 (or (not org-agenda-tags-todo-honor-ignore-options)
10437 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
10438 (let ((case-fold-search t)) (eval matcher))
10440 (not (member org-archive-tag tags-list))
10441 ;; we have an archive tag, should we use this anyway?
10442 (or (not org-agenda-skip-archived-trees)
10443 (and (eq action 'agenda) org-agenda-archives-mode))))
10444 (unless (eq action 'sparse-tree) (org-agenda-skip))
10446 ;; select this headline
10448 (cond
10449 ((eq action 'sparse-tree)
10450 (and org-highlight-sparse-tree-matches
10451 (org-get-heading) (match-end 0)
10452 (org-highlight-new-match
10453 (match-beginning 0) (match-beginning 1)))
10454 (org-show-context 'tags-tree))
10455 ((eq action 'agenda)
10456 (setq txt (org-format-agenda-item
10458 (concat
10459 (if (eq org-tags-match-list-sublevels 'indented)
10460 (make-string (1- level) ?.) "")
10461 (org-get-heading))
10462 category
10463 tags-list
10465 priority (org-get-priority txt))
10466 (goto-char lspos)
10467 (setq marker (org-agenda-new-marker))
10468 (org-add-props txt props
10469 'org-marker marker 'org-hd-marker marker 'org-category category
10470 'todo-state todo
10471 'priority priority 'type "tagsmatch")
10472 (push txt rtn))
10473 ((functionp action)
10474 (setq org-map-continue-from nil)
10475 (save-excursion
10476 (setq rtn1 (funcall action))
10477 (push rtn1 rtn)))
10478 (t (error "Invalid action")))
10480 ;; if we are to skip sublevels, jump to end of subtree
10481 (unless org-tags-match-list-sublevels
10482 (org-end-of-subtree t)
10483 (backward-char 1))))
10484 ;; Get the correct position from where to continue
10485 (if org-map-continue-from
10486 (goto-char org-map-continue-from)
10487 (and (= (point) lspos) (end-of-line 1)))))
10488 (when (and (eq action 'sparse-tree)
10489 (not org-sparse-tree-open-archived-trees))
10490 (org-hide-archived-subtrees (point-min) (point-max)))
10491 (nreverse rtn)))
10493 (defun org-remove-uniherited-tags (tags)
10494 "Remove all tags that are not inherited from the list TAGS."
10495 (cond
10496 ((eq org-use-tag-inheritance t)
10497 (if org-tags-exclude-from-inheritance
10498 (org-delete-all org-tags-exclude-from-inheritance tags)
10499 tags))
10500 ((not org-use-tag-inheritance) nil)
10501 ((stringp org-use-tag-inheritance)
10502 (delq nil (mapcar
10503 (lambda (x)
10504 (if (and (string-match org-use-tag-inheritance x)
10505 (not (member x org-tags-exclude-from-inheritance)))
10506 x nil))
10507 tags)))
10508 ((listp org-use-tag-inheritance)
10509 (delq nil (mapcar
10510 (lambda (x)
10511 (if (member x org-use-tag-inheritance) x nil))
10512 tags)))))
10514 (defvar todo-only) ;; dynamically scoped
10516 (defun org-match-sparse-tree (&optional todo-only match)
10517 "Create a sparse tree according to tags string MATCH.
10518 MATCH can contain positive and negative selection of tags, like
10519 \"+WORK+URGENT-WITHBOSS\".
10520 If optional argument TODO-ONLY is non-nil, only select lines that are
10521 also TODO lines."
10522 (interactive "P")
10523 (org-prepare-agenda-buffers (list (current-buffer)))
10524 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
10526 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
10528 (defvar org-cached-props nil)
10529 (defun org-cached-entry-get (pom property)
10530 (if (or (eq t org-use-property-inheritance)
10531 (and (stringp org-use-property-inheritance)
10532 (string-match org-use-property-inheritance property))
10533 (and (listp org-use-property-inheritance)
10534 (member property org-use-property-inheritance)))
10535 ;; Caching is not possible, check it directly
10536 (org-entry-get pom property 'inherit)
10537 ;; Get all properties, so that we can do complicated checks easily
10538 (cdr (assoc property (or org-cached-props
10539 (setq org-cached-props
10540 (org-entry-properties pom)))))))
10542 (defun org-global-tags-completion-table (&optional files)
10543 "Return the list of all tags in all agenda buffer/files."
10544 (save-excursion
10545 (org-uniquify
10546 (delq nil
10547 (apply 'append
10548 (mapcar
10549 (lambda (file)
10550 (set-buffer (find-file-noselect file))
10551 (append (org-get-buffer-tags)
10552 (mapcar (lambda (x) (if (stringp (car-safe x))
10553 (list (car-safe x)) nil))
10554 org-tag-alist)))
10555 (if (and files (car files))
10556 files
10557 (org-agenda-files))))))))
10559 (defun org-make-tags-matcher (match)
10560 "Create the TAGS//TODO matcher form for the selection string MATCH."
10561 ;; todo-only is scoped dynamically into this function, and the function
10562 ;; may change it if the matcher asks for it.
10563 (unless match
10564 ;; Get a new match request, with completion
10565 (let ((org-last-tags-completion-table
10566 (org-global-tags-completion-table)))
10567 (setq match (org-completing-read-no-ido
10568 "Match: " 'org-tags-completion-function nil nil nil
10569 'org-tags-history))))
10571 ;; Parse the string and create a lisp form
10572 (let ((match0 match)
10573 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
10574 minus tag mm
10575 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
10576 orterms term orlist re-p str-p level-p level-op time-p
10577 prop-p pn pv po cat-p gv rest)
10578 (if (string-match "/+" match)
10579 ;; match contains also a todo-matching request
10580 (progn
10581 (setq tagsmatch (substring match 0 (match-beginning 0))
10582 todomatch (substring match (match-end 0)))
10583 (if (string-match "^!" todomatch)
10584 (setq todo-only t todomatch (substring todomatch 1)))
10585 (if (string-match "^\\s-*$" todomatch)
10586 (setq todomatch nil)))
10587 ;; only matching tags
10588 (setq tagsmatch match todomatch nil))
10590 ;; Make the tags matcher
10591 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10592 (setq tagsmatcher t)
10593 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10594 (while (setq term (pop orterms))
10595 (while (and (equal (substring term -1) "\\") orterms)
10596 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10597 (while (string-match re term)
10598 (setq rest (substring term (match-end 0))
10599 minus (and (match-end 1)
10600 (equal (match-string 1 term) "-"))
10601 tag (match-string 2 term)
10602 re-p (equal (string-to-char tag) ?{)
10603 level-p (match-end 4)
10604 prop-p (match-end 5)
10605 mm (cond
10606 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10607 (level-p
10608 (setq level-op (org-op-to-function (match-string 3 term)))
10609 `(,level-op level ,(string-to-number
10610 (match-string 4 term))))
10611 (prop-p
10612 (setq pn (match-string 5 term)
10613 po (match-string 6 term)
10614 pv (match-string 7 term)
10615 cat-p (equal pn "CATEGORY")
10616 re-p (equal (string-to-char pv) ?{)
10617 str-p (equal (string-to-char pv) ?\")
10618 time-p (save-match-data
10619 (string-match "^\"[[<].*[]>]\"$" pv))
10620 pv (if (or re-p str-p) (substring pv 1 -1) pv))
10621 (if time-p (setq pv (org-matcher-time pv)))
10622 (setq po (org-op-to-function po (if time-p 'time str-p)))
10623 (cond
10624 ((equal pn "CATEGORY")
10625 (setq gv '(get-text-property (point) 'org-category)))
10626 ((equal pn "TODO")
10627 (setq gv 'todo))
10629 (setq gv `(org-cached-entry-get nil ,pn))))
10630 (if re-p
10631 (if (eq po 'org<>)
10632 `(not (string-match ,pv (or ,gv "")))
10633 `(string-match ,pv (or ,gv "")))
10634 (if str-p
10635 `(,po (or ,gv "") ,pv)
10636 `(,po (string-to-number (or ,gv ""))
10637 ,(string-to-number pv) ))))
10638 (t `(member ,tag tags-list)))
10639 mm (if minus (list 'not mm) mm)
10640 term rest)
10641 (push mm tagsmatcher))
10642 (push (if (> (length tagsmatcher) 1)
10643 (cons 'and tagsmatcher)
10644 (car tagsmatcher))
10645 orlist)
10646 (setq tagsmatcher nil))
10647 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
10648 (setq tagsmatcher
10649 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
10650 ;; Make the todo matcher
10651 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10652 (setq todomatcher t)
10653 (setq orterms (org-split-string todomatch "|") orlist nil)
10654 (while (setq term (pop orterms))
10655 (while (string-match re term)
10656 (setq minus (and (match-end 1)
10657 (equal (match-string 1 term) "-"))
10658 kwd (match-string 2 term)
10659 re-p (equal (string-to-char kwd) ?{)
10660 term (substring term (match-end 0))
10661 mm (if re-p
10662 `(string-match ,(substring kwd 1 -1) todo)
10663 (list 'equal 'todo kwd))
10664 mm (if minus (list 'not mm) mm))
10665 (push mm todomatcher))
10666 (push (if (> (length todomatcher) 1)
10667 (cons 'and todomatcher)
10668 (car todomatcher))
10669 orlist)
10670 (setq todomatcher nil))
10671 (setq todomatcher (if (> (length orlist) 1)
10672 (cons 'or orlist) (car orlist))))
10674 ;; Return the string and lisp forms of the matcher
10675 (setq matcher (if todomatcher
10676 (list 'and tagsmatcher todomatcher)
10677 tagsmatcher))
10678 (cons match0 matcher)))
10680 (defun org-op-to-function (op &optional stringp)
10681 "Turn an operator into the appropriate function."
10682 (setq op
10683 (cond
10684 ((equal op "<" ) '(< string< org-time<))
10685 ((equal op ">" ) '(> org-string> org-time>))
10686 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
10687 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
10688 ((member op '("=" "==")) '(= string= org-time=))
10689 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
10690 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
10692 (defun org<> (a b) (not (= a b)))
10693 (defun org-string<= (a b) (or (string= a b) (string< a b)))
10694 (defun org-string>= (a b) (not (string< a b)))
10695 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
10696 (defun org-string<> (a b) (not (string= a b)))
10697 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
10698 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
10699 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
10700 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
10701 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
10702 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
10703 (defun org-2ft (s)
10704 "Convert S to a floating point time.
10705 If S is already a number, just return it. If it is a string, parse
10706 it as a time string and apply `float-time' to it. If S is nil, just return 0."
10707 (cond
10708 ((numberp s) s)
10709 ((stringp s)
10710 (condition-case nil
10711 (float-time (apply 'encode-time (org-parse-time-string s)))
10712 (error 0.)))
10713 (t 0.)))
10715 (defun org-time-today ()
10716 "Time in seconds today at 0:00.
10717 Returns the float number of seconds since the beginning of the
10718 epoch to the beginning of today (00:00)."
10719 (float-time (apply 'encode-time
10720 (append '(0 0 0) (nthcdr 3 (decode-time))))))
10722 (defun org-matcher-time (s)
10723 "Interpret a time comparison value."
10724 (save-match-data
10725 (cond
10726 ((string= s "<now>") (float-time))
10727 ((string= s "<today>") (org-time-today))
10728 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
10729 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
10730 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
10731 (+ (org-time-today)
10732 (* (string-to-number (match-string 1 s))
10733 (cdr (assoc (match-string 2 s)
10734 '(("d" . 86400.0) ("w" . 604800.0)
10735 ("m" . 2678400.0) ("y" . 31557600.0)))))))
10736 (t (org-2ft s)))))
10738 (defun org-match-any-p (re list)
10739 "Does re match any element of list?"
10740 (setq list (mapcar (lambda (x) (string-match re x)) list))
10741 (delq nil list))
10743 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
10744 (defvar org-tags-overlay (org-make-overlay 1 1))
10745 (org-detach-overlay org-tags-overlay)
10747 (defun org-get-local-tags-at (&optional pos)
10748 "Get a list of tags defined in the current headline."
10749 (org-get-tags-at pos 'local))
10751 (defun org-get-local-tags ()
10752 "Get a list of tags defined in the current headline."
10753 (org-get-tags-at nil 'local))
10755 (defun org-get-tags-at (&optional pos local)
10756 "Get a list of all headline tags applicable at POS.
10757 POS defaults to point. If tags are inherited, the list contains
10758 the targets in the same sequence as the headlines appear, i.e.
10759 the tags of the current headline come last.
10760 When LOCAL is non-nil, only return tags from the current headline,
10761 ignore inherited ones."
10762 (interactive)
10763 (if (and org-trust-scanner-tags
10764 (or (not pos) (equal pos (point)))
10765 (not local))
10766 org-scanner-tags
10767 (let (tags ltags lastpos parent)
10768 (save-excursion
10769 (save-restriction
10770 (widen)
10771 (goto-char (or pos (point)))
10772 (save-match-data
10773 (catch 'done
10774 (condition-case nil
10775 (progn
10776 (org-back-to-heading t)
10777 (while (not (equal lastpos (point)))
10778 (setq lastpos (point))
10779 (when (looking-at
10780 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
10781 (setq ltags (org-split-string
10782 (org-match-string-no-properties 1) ":"))
10783 (when parent
10784 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
10785 (setq tags (append
10786 (if parent
10787 (org-remove-uniherited-tags ltags)
10788 ltags)
10789 tags)))
10790 (or org-use-tag-inheritance (throw 'done t))
10791 (if local (throw 'done t))
10792 (or (org-up-heading-safe) (error nil))
10793 (setq parent t)))
10794 (error nil)))))
10795 (append (org-remove-uniherited-tags org-file-tags) tags)))))
10797 (defun org-add-prop-inherited (s)
10798 (add-text-properties 0 (length s) '(inherited t) s)
10801 (defun org-toggle-tag (tag &optional onoff)
10802 "Toggle the tag TAG for the current line.
10803 If ONOFF is `on' or `off', don't toggle but set to this state."
10804 (let (res current)
10805 (save-excursion
10806 (org-back-to-heading t)
10807 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
10808 (point-at-eol) t)
10809 (progn
10810 (setq current (match-string 1))
10811 (replace-match ""))
10812 (setq current ""))
10813 (setq current (nreverse (org-split-string current ":")))
10814 (cond
10815 ((eq onoff 'on)
10816 (setq res t)
10817 (or (member tag current) (push tag current)))
10818 ((eq onoff 'off)
10819 (or (not (member tag current)) (setq current (delete tag current))))
10820 (t (if (member tag current)
10821 (setq current (delete tag current))
10822 (setq res t)
10823 (push tag current))))
10824 (end-of-line 1)
10825 (if current
10826 (progn
10827 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
10828 (org-set-tags nil t))
10829 (delete-horizontal-space))
10830 (run-hooks 'org-after-tags-change-hook))
10831 res))
10833 (defun org-align-tags-here (to-col)
10834 ;; Assumes that this is a headline
10835 (let ((pos (point)) (col (current-column)) ncol tags-l p)
10836 (beginning-of-line 1)
10837 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10838 (< pos (match-beginning 2)))
10839 (progn
10840 (setq tags-l (- (match-end 2) (match-beginning 2)))
10841 (goto-char (match-beginning 1))
10842 (insert " ")
10843 (delete-region (point) (1+ (match-beginning 2)))
10844 (setq ncol (max (1+ (current-column))
10845 (1+ col)
10846 (if (> to-col 0)
10847 to-col
10848 (- (abs to-col) tags-l))))
10849 (setq p (point))
10850 (insert (make-string (- ncol (current-column)) ?\ ))
10851 (setq ncol (current-column))
10852 (when indent-tabs-mode (tabify p (point-at-eol)))
10853 (org-move-to-column (min ncol col) t))
10854 (goto-char pos))))
10856 (defun org-set-tags-command (&optional arg just-align)
10857 "Call the set-tags command for the current entry."
10858 (interactive "P")
10859 (if (org-on-heading-p)
10860 (org-set-tags arg just-align)
10861 (save-excursion
10862 (org-back-to-heading t)
10863 (org-set-tags arg just-align))))
10865 (defun org-set-tags (&optional arg just-align)
10866 "Set the tags for the current headline.
10867 With prefix ARG, realign all tags in headings in the current buffer."
10868 (interactive "P")
10869 (let* ((re (concat "^" outline-regexp))
10870 (current (org-get-tags-string))
10871 (col (current-column))
10872 (org-setting-tags t)
10873 table current-tags inherited-tags ; computed below when needed
10874 tags p0 c0 c1 rpl)
10875 (if arg
10876 (save-excursion
10877 (goto-char (point-min))
10878 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
10879 (while (re-search-forward re nil t)
10880 (org-set-tags nil t)
10881 (end-of-line 1)))
10882 (message "All tags realigned to column %d" org-tags-column))
10883 (if just-align
10884 (setq tags current)
10885 ;; Get a new set of tags from the user
10886 (save-excursion
10887 (setq table (append org-tag-persistent-alist
10888 (or org-tag-alist (org-get-buffer-tags)))
10889 org-last-tags-completion-table table
10890 current-tags (org-split-string current ":")
10891 inherited-tags (nreverse
10892 (nthcdr (length current-tags)
10893 (nreverse (org-get-tags-at))))
10894 tags
10895 (if (or (eq t org-use-fast-tag-selection)
10896 (and org-use-fast-tag-selection
10897 (delq nil (mapcar 'cdr table))))
10898 (org-fast-tag-selection
10899 current-tags inherited-tags table
10900 (if org-fast-tag-selection-include-todo org-todo-key-alist))
10901 (let ((org-add-colon-after-tag-completion t))
10902 (org-trim
10903 (org-without-partial-completion
10904 (org-ido-completing-read "Tags: " 'org-tags-completion-function
10905 nil nil current 'org-tags-history)))))))
10906 (while (string-match "[-+&]+" tags)
10907 ;; No boolean logic, just a list
10908 (setq tags (replace-match ":" t t tags))))
10910 (if (string-match "\\`[\t ]*\\'" tags)
10911 (setq tags "")
10912 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
10913 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
10915 ;; Insert new tags at the correct column
10916 (beginning-of-line 1)
10917 (cond
10918 ((and (equal current "") (equal tags "")))
10919 ((re-search-forward
10920 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10921 (point-at-eol) t)
10922 (if (equal tags "")
10923 (setq rpl "")
10924 (goto-char (match-beginning 0))
10925 (setq c0 (current-column) p0 (point)
10926 c1 (max (1+ c0) (if (> org-tags-column 0)
10927 org-tags-column
10928 (- (- org-tags-column) (length tags))))
10929 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10930 (replace-match rpl t t)
10931 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
10932 tags)
10933 (t (error "Tags alignment failed")))
10934 (org-move-to-column col)
10935 (unless just-align
10936 (run-hooks 'org-after-tags-change-hook)))))
10938 (defun org-change-tag-in-region (beg end tag off)
10939 "Add or remove TAG for each entry in the region.
10940 This works in the agenda, and also in an org-mode buffer."
10941 (interactive
10942 (list (region-beginning) (region-end)
10943 (let ((org-last-tags-completion-table
10944 (if (org-mode-p)
10945 (org-get-buffer-tags)
10946 (org-global-tags-completion-table))))
10947 (org-ido-completing-read
10948 "Tag: " 'org-tags-completion-function nil nil nil
10949 'org-tags-history))
10950 (progn
10951 (message "[s]et or [r]emove? ")
10952 (equal (read-char-exclusive) ?r))))
10953 (if (fboundp 'deactivate-mark) (deactivate-mark))
10954 (let ((agendap (equal major-mode 'org-agenda-mode))
10955 l1 l2 m buf pos newhead (cnt 0))
10956 (goto-char end)
10957 (setq l2 (1- (org-current-line)))
10958 (goto-char beg)
10959 (setq l1 (org-current-line))
10960 (loop for l from l1 to l2 do
10961 (goto-line l)
10962 (setq m (get-text-property (point) 'org-hd-marker))
10963 (when (or (and (org-mode-p) (org-on-heading-p))
10964 (and agendap m))
10965 (setq buf (if agendap (marker-buffer m) (current-buffer))
10966 pos (if agendap m (point)))
10967 (with-current-buffer buf
10968 (save-excursion
10969 (save-restriction
10970 (goto-char pos)
10971 (setq cnt (1+ cnt))
10972 (org-toggle-tag tag (if off 'off 'on))
10973 (setq newhead (org-get-heading)))))
10974 (and agendap (org-agenda-change-all-lines newhead m))))
10975 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
10977 (defun org-tags-completion-function (string predicate &optional flag)
10978 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10979 (confirm (lambda (x) (stringp (car x)))))
10980 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10981 (setq s1 (match-string 1 string)
10982 s2 (match-string 2 string))
10983 (setq s1 "" s2 string))
10984 (cond
10985 ((eq flag nil)
10986 ;; try completion
10987 (setq rtn (try-completion s2 ctable confirm))
10988 (if (stringp rtn)
10989 (setq rtn
10990 (concat s1 s2 (substring rtn (length s2))
10991 (if (and org-add-colon-after-tag-completion
10992 (assoc rtn ctable))
10993 ":" ""))))
10994 rtn)
10995 ((eq flag t)
10996 ;; all-completions
10997 (all-completions s2 ctable confirm)
10999 ((eq flag 'lambda)
11000 ;; exact match?
11001 (assoc s2 ctable)))
11004 (defun org-fast-tag-insert (kwd tags face &optional end)
11005 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
11006 (insert (format "%-12s" (concat kwd ":"))
11007 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
11008 (or end "")))
11010 (defun org-fast-tag-show-exit (flag)
11011 (save-excursion
11012 (goto-line 3)
11013 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
11014 (replace-match ""))
11015 (when flag
11016 (end-of-line 1)
11017 (org-move-to-column (- (window-width) 19) t)
11018 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
11020 (defun org-set-current-tags-overlay (current prefix)
11021 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
11022 (if (featurep 'xemacs)
11023 (org-overlay-display org-tags-overlay (concat prefix s)
11024 'secondary-selection)
11025 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
11026 (org-overlay-display org-tags-overlay (concat prefix s)))))
11028 (defun org-fast-tag-selection (current inherited table &optional todo-table)
11029 "Fast tag selection with single keys.
11030 CURRENT is the current list of tags in the headline, INHERITED is the
11031 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
11032 possibly with grouping information. TODO-TABLE is a similar table with
11033 TODO keywords, should these have keys assigned to them.
11034 If the keys are nil, a-z are automatically assigned.
11035 Returns the new tags string, or nil to not change the current settings."
11036 (let* ((fulltable (append table todo-table))
11037 (maxlen (apply 'max (mapcar
11038 (lambda (x)
11039 (if (stringp (car x)) (string-width (car x)) 0))
11040 fulltable)))
11041 (buf (current-buffer))
11042 (expert (eq org-fast-tag-selection-single-key 'expert))
11043 (buffer-tags nil)
11044 (fwidth (+ maxlen 3 1 3))
11045 (ncol (/ (- (window-width) 4) fwidth))
11046 (i-face 'org-done)
11047 (c-face 'org-todo)
11048 tg cnt e c char c1 c2 ntable tbl rtn
11049 ov-start ov-end ov-prefix
11050 (exit-after-next org-fast-tag-selection-single-key)
11051 (done-keywords org-done-keywords)
11052 groups ingroup)
11053 (save-excursion
11054 (beginning-of-line 1)
11055 (if (looking-at
11056 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11057 (setq ov-start (match-beginning 1)
11058 ov-end (match-end 1)
11059 ov-prefix "")
11060 (setq ov-start (1- (point-at-eol))
11061 ov-end (1+ ov-start))
11062 (skip-chars-forward "^\n\r")
11063 (setq ov-prefix
11064 (concat
11065 (buffer-substring (1- (point)) (point))
11066 (if (> (current-column) org-tags-column)
11068 (make-string (- org-tags-column (current-column)) ?\ ))))))
11069 (org-move-overlay org-tags-overlay ov-start ov-end)
11070 (save-window-excursion
11071 (if expert
11072 (set-buffer (get-buffer-create " *Org tags*"))
11073 (delete-other-windows)
11074 (split-window-vertically)
11075 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
11076 (erase-buffer)
11077 (org-set-local 'org-done-keywords done-keywords)
11078 (org-fast-tag-insert "Inherited" inherited i-face "\n")
11079 (org-fast-tag-insert "Current" current c-face "\n\n")
11080 (org-fast-tag-show-exit exit-after-next)
11081 (org-set-current-tags-overlay current ov-prefix)
11082 (setq tbl fulltable char ?a cnt 0)
11083 (while (setq e (pop tbl))
11084 (cond
11085 ((equal e '(:startgroup))
11086 (push '() groups) (setq ingroup t)
11087 (when (not (= cnt 0))
11088 (setq cnt 0)
11089 (insert "\n"))
11090 (insert "{ "))
11091 ((equal e '(:endgroup))
11092 (setq ingroup nil cnt 0)
11093 (insert "}\n"))
11094 ((equal e '(:newline))
11095 (when (not (= cnt 0))
11096 (setq cnt 0)
11097 (insert "\n")
11098 (setq e (car tbl))
11099 (while (equal (car tbl) '(:newline))
11100 (insert "\n")
11101 (setq tbl (cdr tbl)))))
11103 (setq tg (car e) c2 nil)
11104 (if (cdr e)
11105 (setq c (cdr e))
11106 ;; automatically assign a character.
11107 (setq c1 (string-to-char
11108 (downcase (substring
11109 tg (if (= (string-to-char tg) ?@) 1 0)))))
11110 (if (or (rassoc c1 ntable) (rassoc c1 table))
11111 (while (or (rassoc char ntable) (rassoc char table))
11112 (setq char (1+ char)))
11113 (setq c2 c1))
11114 (setq c (or c2 char)))
11115 (if ingroup (push tg (car groups)))
11116 (setq tg (org-add-props tg nil 'face
11117 (cond
11118 ((not (assoc tg table))
11119 (org-get-todo-face tg))
11120 ((member tg current) c-face)
11121 ((member tg inherited) i-face)
11122 (t nil))))
11123 (if (and (= cnt 0) (not ingroup)) (insert " "))
11124 (insert "[" c "] " tg (make-string
11125 (- fwidth 4 (length tg)) ?\ ))
11126 (push (cons tg c) ntable)
11127 (when (= (setq cnt (1+ cnt)) ncol)
11128 (insert "\n")
11129 (if ingroup (insert " "))
11130 (setq cnt 0)))))
11131 (setq ntable (nreverse ntable))
11132 (insert "\n")
11133 (goto-char (point-min))
11134 (if (not expert) (org-fit-window-to-buffer))
11135 (setq rtn
11136 (catch 'exit
11137 (while t
11138 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
11139 (if groups " [!] no groups" " [!]groups")
11140 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
11141 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11142 (cond
11143 ((= c ?\r) (throw 'exit t))
11144 ((= c ?!)
11145 (setq groups (not groups))
11146 (goto-char (point-min))
11147 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
11148 ((= c ?\C-c)
11149 (if (not expert)
11150 (org-fast-tag-show-exit
11151 (setq exit-after-next (not exit-after-next)))
11152 (setq expert nil)
11153 (delete-other-windows)
11154 (split-window-vertically)
11155 (org-switch-to-buffer-other-window " *Org tags*")
11156 (org-fit-window-to-buffer)))
11157 ((or (= c ?\C-g)
11158 (and (= c ?q) (not (rassoc c ntable))))
11159 (org-detach-overlay org-tags-overlay)
11160 (setq quit-flag t))
11161 ((= c ?\ )
11162 (setq current nil)
11163 (if exit-after-next (setq exit-after-next 'now)))
11164 ((= c ?\t)
11165 (condition-case nil
11166 (setq tg (org-ido-completing-read
11167 "Tag: "
11168 (or buffer-tags
11169 (with-current-buffer buf
11170 (org-get-buffer-tags)))))
11171 (quit (setq tg "")))
11172 (when (string-match "\\S-" tg)
11173 (add-to-list 'buffer-tags (list tg))
11174 (if (member tg current)
11175 (setq current (delete tg current))
11176 (push tg current)))
11177 (if exit-after-next (setq exit-after-next 'now)))
11178 ((setq e (rassoc c todo-table) tg (car e))
11179 (with-current-buffer buf
11180 (save-excursion (org-todo tg)))
11181 (if exit-after-next (setq exit-after-next 'now)))
11182 ((setq e (rassoc c ntable) tg (car e))
11183 (if (member tg current)
11184 (setq current (delete tg current))
11185 (loop for g in groups do
11186 (if (member tg g)
11187 (mapc (lambda (x)
11188 (setq current (delete x current)))
11189 g)))
11190 (push tg current))
11191 (if exit-after-next (setq exit-after-next 'now))))
11193 ;; Create a sorted list
11194 (setq current
11195 (sort current
11196 (lambda (a b)
11197 (assoc b (cdr (memq (assoc a ntable) ntable))))))
11198 (if (eq exit-after-next 'now) (throw 'exit t))
11199 (goto-char (point-min))
11200 (beginning-of-line 2)
11201 (delete-region (point) (point-at-eol))
11202 (org-fast-tag-insert "Current" current c-face)
11203 (org-set-current-tags-overlay current ov-prefix)
11204 (while (re-search-forward
11205 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
11206 (setq tg (match-string 1))
11207 (add-text-properties
11208 (match-beginning 1) (match-end 1)
11209 (list 'face
11210 (cond
11211 ((member tg current) c-face)
11212 ((member tg inherited) i-face)
11213 (t (get-text-property (match-beginning 1) 'face))))))
11214 (goto-char (point-min)))))
11215 (org-detach-overlay org-tags-overlay)
11216 (if rtn
11217 (mapconcat 'identity current ":")
11218 nil))))
11220 (defun org-get-tags-string ()
11221 "Get the TAGS string in the current headline."
11222 (unless (org-on-heading-p t)
11223 (error "Not on a heading"))
11224 (save-excursion
11225 (beginning-of-line 1)
11226 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11227 (org-match-string-no-properties 1)
11228 "")))
11230 (defun org-get-tags ()
11231 "Get the list of tags specified in the current headline."
11232 (org-split-string (org-get-tags-string) ":"))
11234 (defun org-get-buffer-tags ()
11235 "Get a table of all tags used in the buffer, for completion."
11236 (let (tags)
11237 (save-excursion
11238 (goto-char (point-min))
11239 (while (re-search-forward
11240 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
11241 (when (equal (char-after (point-at-bol 0)) ?*)
11242 (mapc (lambda (x) (add-to-list 'tags x))
11243 (org-split-string (org-match-string-no-properties 1) ":")))))
11244 (mapcar 'list tags)))
11246 ;;;; The mapping API
11248 ;;;###autoload
11249 (defun org-map-entries (func &optional match scope &rest skip)
11250 "Call FUNC at each headline selected by MATCH in SCOPE.
11252 FUNC is a function or a lisp form. The function will be called without
11253 arguments, with the cursor positioned at the beginning of the headline.
11254 The return values of all calls to the function will be collected and
11255 returned as a list.
11257 The call to FUNC will be wrapped into a save-excursion form, so FUNC
11258 does not need to preserve point. After evaluaton, the cursor will be
11259 moved to the end of the line (presumably of the headline of the
11260 processed entry) and search continues from there. Under some
11261 circumstances, this may not produce the wanted results. For example,
11262 if you have removed (e.g. archived) the current (sub)tree it could
11263 mean that the next entry will be skipped entirely. In such cases, you
11264 can specify the position from where search should continue by making
11265 FUNC set the variable `org-map-continue-from' to the desired buffer
11266 position.
11268 MATCH is a tags/property/todo match as it is used in the agenda tags view.
11269 Only headlines that are matched by this query will be considered during
11270 the iteration. When MATCH is nil or t, all headlines will be
11271 visited by the iteration.
11273 SCOPE determines the scope of this command. It can be any of:
11275 nil The current buffer, respecting the restriction if any
11276 tree The subtree started with the entry at point
11277 file The current buffer, without restriction
11278 file-with-archives
11279 The current buffer, and any archives associated with it
11280 agenda All agenda files
11281 agenda-with-archives
11282 All agenda files with any archive files associated with them
11283 \(file1 file2 ...)
11284 If this is a list, all files in the list will be scanned
11286 The remaining args are treated as settings for the skipping facilities of
11287 the scanner. The following items can be given here:
11289 archive skip trees with the archive tag.
11290 comment skip trees with the COMMENT keyword
11291 function or Emacs Lisp form:
11292 will be used as value for `org-agenda-skip-function', so whenever
11293 the the function returns t, FUNC will not be called for that
11294 entry and search will continue from the point where the
11295 function leaves it.
11297 If your function needs to retrieve the tags including inherited tags
11298 at the *current* entry, you can use the value of the variable
11299 `org-scanner-tags' which will be much faster than getting the value
11300 with `org-get-tags-at'. If your function gets properties with
11301 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
11302 to t around the call to `org-entry-properties' to get the same speedup.
11303 Note that if your function moves around to retrieve tags and properties at
11304 a *different* entry, you cannot use these techniques."
11305 (let* ((org-agenda-archives-mode nil) ; just to make sure
11306 (org-agenda-skip-archived-trees (memq 'archive skip))
11307 (org-agenda-skip-comment-trees (memq 'comment skip))
11308 (org-agenda-skip-function
11309 (car (org-delete-all '(comment archive) skip)))
11310 (org-tags-match-list-sublevels t)
11311 matcher file res
11312 org-todo-keywords-for-agenda
11313 org-done-keywords-for-agenda
11314 org-todo-keyword-alist-for-agenda
11315 org-tag-alist-for-agenda)
11317 (cond
11318 ((eq match t) (setq matcher t))
11319 ((eq match nil) (setq matcher t))
11320 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
11322 (save-excursion
11323 (save-restriction
11324 (when (eq scope 'tree)
11325 (org-back-to-heading t)
11326 (org-narrow-to-subtree)
11327 (setq scope nil))
11329 (if (not scope)
11330 (progn
11331 (org-prepare-agenda-buffers
11332 (list (buffer-file-name (current-buffer))))
11333 (setq res (org-scan-tags func matcher)))
11334 ;; Get the right scope
11335 (cond
11336 ((and scope (listp scope) (symbolp (car scope)))
11337 (setq scope (eval scope)))
11338 ((eq scope 'agenda)
11339 (setq scope (org-agenda-files t)))
11340 ((eq scope 'agenda-with-archives)
11341 (setq scope (org-agenda-files t))
11342 (setq scope (org-add-archive-files scope)))
11343 ((eq scope 'file)
11344 (setq scope (list (buffer-file-name))))
11345 ((eq scope 'file-with-archives)
11346 (setq scope (org-add-archive-files (list (buffer-file-name))))))
11347 (org-prepare-agenda-buffers scope)
11348 (while (setq file (pop scope))
11349 (with-current-buffer (org-find-base-buffer-visiting file)
11350 (save-excursion
11351 (save-restriction
11352 (widen)
11353 (goto-char (point-min))
11354 (setq res (append res (org-scan-tags func matcher))))))))))
11355 res))
11357 ;;;; Properties
11359 ;;; Setting and retrieving properties
11361 (defconst org-special-properties
11362 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
11363 "TIMESTAMP" "TIMESTAMP_IA")
11364 "The special properties valid in Org-mode.
11366 These are properties that are not defined in the property drawer,
11367 but in some other way.")
11369 (defconst org-default-properties
11370 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
11371 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
11372 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
11373 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
11374 "ORDERED" "NOBLOCKING" "COOKIE_DATA")
11375 "Some properties that are used by Org-mode for various purposes.
11376 Being in this list makes sure that they are offered for completion.")
11378 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
11379 "Regular expression matching the first line of a property drawer.")
11381 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
11382 "Regular expression matching the first line of a property drawer.")
11384 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
11385 "Regular expression matching the first line of a property drawer.")
11387 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
11388 "Regular expression matching the first line of a property drawer.")
11390 (defconst org-property-drawer-re
11391 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
11392 org-property-end-re "\\)\n?")
11393 "Matches an entire property drawer.")
11395 (defconst org-clock-drawer-re
11396 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
11397 org-property-end-re "\\)\n?")
11398 "Matches an entire clock drawer.")
11400 (defun org-property-action ()
11401 "Do an action on properties."
11402 (interactive)
11403 (let (c)
11404 (org-at-property-p)
11405 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
11406 (setq c (read-char-exclusive))
11407 (cond
11408 ((equal c ?s)
11409 (call-interactively 'org-set-property))
11410 ((equal c ?d)
11411 (call-interactively 'org-delete-property))
11412 ((equal c ?D)
11413 (call-interactively 'org-delete-property-globally))
11414 ((equal c ?c)
11415 (call-interactively 'org-compute-property-at-point))
11416 (t (error "No such property action %c" c)))))
11418 (defun org-at-property-p ()
11419 "Is the cursor in a property line?"
11420 ;; FIXME: Does not check if we are actually in the drawer.
11421 ;; FIXME: also returns true on any drawers.....
11422 ;; This is used by C-c C-c for property action.
11423 (save-excursion
11424 (beginning-of-line 1)
11425 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
11427 (defun org-get-property-block (&optional beg end force)
11428 "Return the (beg . end) range of the body of the property drawer.
11429 BEG and END can be beginning and end of subtree, if not given
11430 they will be found.
11431 If the drawer does not exist and FORCE is non-nil, create the drawer."
11432 (catch 'exit
11433 (save-excursion
11434 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
11435 (end (or end (progn (outline-next-heading) (point)))))
11436 (goto-char beg)
11437 (if (re-search-forward org-property-start-re end t)
11438 (setq beg (1+ (match-end 0)))
11439 (if force
11440 (save-excursion
11441 (org-insert-property-drawer)
11442 (setq end (progn (outline-next-heading) (point))))
11443 (throw 'exit nil))
11444 (goto-char beg)
11445 (if (re-search-forward org-property-start-re end t)
11446 (setq beg (1+ (match-end 0)))))
11447 (if (re-search-forward org-property-end-re end t)
11448 (setq end (match-beginning 0))
11449 (or force (throw 'exit nil))
11450 (goto-char beg)
11451 (setq end beg)
11452 (org-indent-line-function)
11453 (insert ":END:\n"))
11454 (cons beg end)))))
11456 (defun org-entry-properties (&optional pom which)
11457 "Get all properties of the entry at point-or-marker POM.
11458 This includes the TODO keyword, the tags, time strings for deadline,
11459 scheduled, and clocking, and any additional properties defined in the
11460 entry. The return value is an alist, keys may occur multiple times
11461 if the property key was used several times.
11462 POM may also be nil, in which case the current entry is used.
11463 If WHICH is nil or `all', get all properties. If WHICH is
11464 `special' or `standard', only get that subclass."
11465 (setq which (or which 'all))
11466 (org-with-point-at pom
11467 (let ((clockstr (substring org-clock-string 0 -1))
11468 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
11469 beg end range props sum-props key value string clocksum)
11470 (save-excursion
11471 (when (condition-case nil
11472 (and (org-mode-p) (org-back-to-heading t))
11473 (error nil))
11474 (setq beg (point))
11475 (setq sum-props (get-text-property (point) 'org-summaries))
11476 (setq clocksum (get-text-property (point) :org-clock-minutes))
11477 (outline-next-heading)
11478 (setq end (point))
11479 (when (memq which '(all special))
11480 ;; Get the special properties, like TODO and tags
11481 (goto-char beg)
11482 (when (and (looking-at org-todo-line-regexp) (match-end 2))
11483 (push (cons "TODO" (org-match-string-no-properties 2)) props))
11484 (when (looking-at org-priority-regexp)
11485 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
11486 (when (and (setq value (org-get-tags-string))
11487 (string-match "\\S-" value))
11488 (push (cons "TAGS" value) props))
11489 (when (setq value (org-get-tags-at))
11490 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
11491 props))
11492 (while (re-search-forward org-maybe-keyword-time-regexp end t)
11493 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
11494 string (if (equal key clockstr)
11495 (org-no-properties
11496 (org-trim
11497 (buffer-substring
11498 (match-beginning 3) (goto-char (point-at-eol)))))
11499 (substring (org-match-string-no-properties 3) 1 -1)))
11500 (unless key
11501 (if (= (char-after (match-beginning 3)) ?\[)
11502 (setq key "TIMESTAMP_IA")
11503 (setq key "TIMESTAMP")))
11504 (when (or (equal key clockstr) (not (assoc key props)))
11505 (push (cons key string) props)))
11509 (when (memq which '(all standard))
11510 ;; Get the standard properties, like :PROP: ...
11511 (setq range (org-get-property-block beg end))
11512 (when range
11513 (goto-char (car range))
11514 (while (re-search-forward
11515 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
11516 (cdr range) t)
11517 (setq key (org-match-string-no-properties 1)
11518 value (org-trim (or (org-match-string-no-properties 2) "")))
11519 (unless (member key excluded)
11520 (push (cons key (or value "")) props)))))
11521 (if clocksum
11522 (push (cons "CLOCKSUM"
11523 (org-columns-number-to-string (/ (float clocksum) 60.)
11524 'add_times))
11525 props))
11526 (unless (assoc "CATEGORY" props)
11527 (setq value (or (org-get-category)
11528 (progn (org-refresh-category-properties)
11529 (org-get-category))))
11530 (push (cons "CATEGORY" value) props))
11531 (append sum-props (nreverse props)))))))
11533 (defun org-entry-get (pom property &optional inherit)
11534 "Get value of PROPERTY for entry at point-or-marker POM.
11535 If INHERIT is non-nil and the entry does not have the property,
11536 then also check higher levels of the hierarchy.
11537 If INHERIT is the symbol `selective', use inheritance only if the setting
11538 in `org-use-property-inheritance' selects PROPERTY for inheritance.
11539 If the property is present but empty, the return value is the empty string.
11540 If the property is not present at all, nil is returned."
11541 (org-with-point-at pom
11542 (if (and inherit (if (eq inherit 'selective)
11543 (org-property-inherit-p property)
11545 (org-entry-get-with-inheritance property)
11546 (if (member property org-special-properties)
11547 ;; We need a special property. Use brute force, get all properties.
11548 (cdr (assoc property (org-entry-properties nil 'special)))
11549 (let ((range (org-get-property-block)))
11550 (if (and range
11551 (goto-char (car range))
11552 (re-search-forward
11553 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
11554 (cdr range) t))
11555 ;; Found the property, return it.
11556 (if (match-end 1)
11557 (org-match-string-no-properties 1)
11558 "")))))))
11560 (defun org-property-or-variable-value (var &optional inherit)
11561 "Check if there is a property fixing the value of VAR.
11562 If yes, return this value. If not, return the current value of the variable."
11563 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
11564 (if (and prop (stringp prop) (string-match "\\S-" prop))
11565 (read prop)
11566 (symbol-value var))))
11568 (defun org-entry-delete (pom property)
11569 "Delete the property PROPERTY from entry at point-or-marker POM."
11570 (org-with-point-at pom
11571 (if (member property org-special-properties)
11572 nil ; cannot delete these properties.
11573 (let ((range (org-get-property-block)))
11574 (if (and range
11575 (goto-char (car range))
11576 (re-search-forward
11577 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
11578 (cdr range) t))
11579 (progn
11580 (delete-region (match-beginning 0) (1+ (point-at-eol)))
11582 nil)))))
11584 ;; Multi-values properties are properties that contain multiple values
11585 ;; These values are assumed to be single words, separated by whitespace.
11586 (defun org-entry-add-to-multivalued-property (pom property value)
11587 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
11588 (let* ((old (org-entry-get pom property))
11589 (values (and old (org-split-string old "[ \t]"))))
11590 (setq value (org-entry-protect-space value))
11591 (unless (member value values)
11592 (setq values (cons value values))
11593 (org-entry-put pom property
11594 (mapconcat 'identity values " ")))))
11596 (defun org-entry-remove-from-multivalued-property (pom property value)
11597 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
11598 (let* ((old (org-entry-get pom property))
11599 (values (and old (org-split-string old "[ \t]"))))
11600 (setq value (org-entry-protect-space value))
11601 (when (member value values)
11602 (setq values (delete value values))
11603 (org-entry-put pom property
11604 (mapconcat 'identity values " ")))))
11606 (defun org-entry-member-in-multivalued-property (pom property value)
11607 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
11608 (let* ((old (org-entry-get pom property))
11609 (values (and old (org-split-string old "[ \t]"))))
11610 (setq value (org-entry-protect-space value))
11611 (member value values)))
11613 (defun org-entry-get-multivalued-property (pom property)
11614 "Return a list of values in a multivalued property."
11615 (let* ((value (org-entry-get pom property))
11616 (values (and value (org-split-string value "[ \t]"))))
11617 (mapcar 'org-entry-restore-space values)))
11619 (defun org-entry-put-multivalued-property (pom property &rest values)
11620 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
11621 VALUES should be a list of strings. Spaces will be protected."
11622 (org-entry-put pom property
11623 (mapconcat 'org-entry-protect-space values " "))
11624 (let* ((value (org-entry-get pom property))
11625 (values (and value (org-split-string value "[ \t]"))))
11626 (mapcar 'org-entry-restore-space values)))
11628 (defun org-entry-protect-space (s)
11629 "Protect spaces and newline in string S."
11630 (while (string-match " " s)
11631 (setq s (replace-match "%20" t t s)))
11632 (while (string-match "\n" s)
11633 (setq s (replace-match "%0A" t t s)))
11636 (defun org-entry-restore-space (s)
11637 "Restore spaces and newline in string S."
11638 (while (string-match "%20" s)
11639 (setq s (replace-match " " t t s)))
11640 (while (string-match "%0A" s)
11641 (setq s (replace-match "\n" t t s)))
11644 (defvar org-entry-property-inherited-from (make-marker)
11645 "Marker pointing to the entry from where a property was inherited.
11646 Each call to `org-entry-get-with-inheritance' will set this marker to the
11647 location of the entry where the inheritance search matched. If there was
11648 no match, the marker will point nowhere.
11649 Note that also `org-entry-get' calls this function, if the INHERIT flag
11650 is set.")
11652 (defun org-entry-get-with-inheritance (property)
11653 "Get entry property, and search higher levels if not present."
11654 (move-marker org-entry-property-inherited-from nil)
11655 (let (tmp)
11656 (save-excursion
11657 (save-restriction
11658 (widen)
11659 (catch 'ex
11660 (while t
11661 (when (setq tmp (org-entry-get nil property))
11662 (org-back-to-heading t)
11663 (move-marker org-entry-property-inherited-from (point))
11664 (throw 'ex tmp))
11665 (or (org-up-heading-safe) (throw 'ex nil)))))
11666 (or tmp
11667 (cdr (assoc property org-file-properties))
11668 (cdr (assoc property org-global-properties))
11669 (cdr (assoc property org-global-properties-fixed))))))
11671 (defun org-entry-put (pom property value)
11672 "Set PROPERTY to VALUE for entry at point-or-marker POM."
11673 (org-with-point-at pom
11674 (org-back-to-heading t)
11675 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
11676 range)
11677 (cond
11678 ((equal property "TODO")
11679 (when (and (stringp value) (string-match "\\S-" value)
11680 (not (member value org-todo-keywords-1)))
11681 (error "\"%s\" is not a valid TODO state" value))
11682 (if (or (not value)
11683 (not (string-match "\\S-" value)))
11684 (setq value 'none))
11685 (org-todo value)
11686 (org-set-tags nil 'align))
11687 ((equal property "PRIORITY")
11688 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
11689 (string-to-char value) ?\ ))
11690 (org-set-tags nil 'align))
11691 ((equal property "SCHEDULED")
11692 (if (re-search-forward org-scheduled-time-regexp end t)
11693 (cond
11694 ((eq value 'earlier) (org-timestamp-change -1 'day))
11695 ((eq value 'later) (org-timestamp-change 1 'day))
11696 (t (call-interactively 'org-schedule)))
11697 (call-interactively 'org-schedule)))
11698 ((equal property "DEADLINE")
11699 (if (re-search-forward org-deadline-time-regexp end t)
11700 (cond
11701 ((eq value 'earlier) (org-timestamp-change -1 'day))
11702 ((eq value 'later) (org-timestamp-change 1 'day))
11703 (t (call-interactively 'org-deadline)))
11704 (call-interactively 'org-deadline)))
11705 ((member property org-special-properties)
11706 (error "The %s property can not yet be set with `org-entry-put'"
11707 property))
11708 (t ; a non-special property
11709 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
11710 (setq range (org-get-property-block beg end 'force))
11711 (goto-char (car range))
11712 (if (re-search-forward
11713 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
11714 (progn
11715 (delete-region (match-beginning 1) (match-end 1))
11716 (goto-char (match-beginning 1)))
11717 (goto-char (cdr range))
11718 (insert "\n")
11719 (backward-char 1)
11720 (org-indent-line-function)
11721 (insert ":" property ":"))
11722 (and value (insert " " value))
11723 (org-indent-line-function)))))))
11725 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
11726 "Get all property keys in the current buffer.
11727 With INCLUDE-SPECIALS, also list the special properties that reflect things
11728 like tags and TODO state.
11729 With INCLUDE-DEFAULTS, also include properties that has special meaning
11730 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
11731 With INCLUDE-COLUMNS, also include property names given in COLUMN
11732 formats in the current buffer."
11733 (let (rtn range cfmt s p)
11734 (save-excursion
11735 (save-restriction
11736 (widen)
11737 (goto-char (point-min))
11738 (while (re-search-forward org-property-start-re nil t)
11739 (setq range (org-get-property-block))
11740 (goto-char (car range))
11741 (while (re-search-forward
11742 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
11743 (cdr range) t)
11744 (add-to-list 'rtn (org-match-string-no-properties 1)))
11745 (outline-next-heading))))
11747 (when include-specials
11748 (setq rtn (append org-special-properties rtn)))
11750 (when include-defaults
11751 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
11753 (when include-columns
11754 (save-excursion
11755 (save-restriction
11756 (widen)
11757 (goto-char (point-min))
11758 (while (re-search-forward
11759 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
11760 nil t)
11761 (setq cfmt (match-string 2) s 0)
11762 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
11763 cfmt s)
11764 (setq s (match-end 0)
11765 p (match-string 1 cfmt))
11766 (unless (or (equal p "ITEM")
11767 (member p org-special-properties))
11768 (add-to-list 'rtn (match-string 1 cfmt))))))))
11770 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
11772 (defun org-property-values (key)
11773 "Return a list of all values of property KEY."
11774 (save-excursion
11775 (save-restriction
11776 (widen)
11777 (goto-char (point-min))
11778 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
11779 values)
11780 (while (re-search-forward re nil t)
11781 (add-to-list 'values (org-trim (match-string 1))))
11782 (delete "" values)))))
11784 (defun org-insert-property-drawer ()
11785 "Insert a property drawer into the current entry."
11786 (interactive)
11787 (org-back-to-heading t)
11788 (looking-at outline-regexp)
11789 (let ((indent (- (match-end 0)(match-beginning 0)))
11790 (beg (point))
11791 (re (concat "^[ \t]*" org-keyword-time-regexp))
11792 end hiddenp)
11793 (outline-next-heading)
11794 (setq end (point))
11795 (goto-char beg)
11796 (while (re-search-forward re end t))
11797 (setq hiddenp (org-invisible-p))
11798 (end-of-line 1)
11799 (and (equal (char-after) ?\n) (forward-char 1))
11800 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
11801 (if (member (match-string 1) '("CLOCK:" ":END:"))
11802 ;; just skip this line
11803 (beginning-of-line 2)
11804 ;; Drawer start, find the end
11805 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
11806 (beginning-of-line 1)))
11807 (org-skip-over-state-notes)
11808 (skip-chars-backward " \t\n\r")
11809 (if (eq (char-before) ?*) (forward-char 1))
11810 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
11811 (beginning-of-line 0)
11812 (org-indent-to-column indent)
11813 (beginning-of-line 2)
11814 (org-indent-to-column indent)
11815 (beginning-of-line 0)
11816 (if hiddenp
11817 (save-excursion
11818 (org-back-to-heading t)
11819 (hide-entry))
11820 (org-flag-drawer t))))
11822 (defun org-set-property (property value)
11823 "In the current entry, set PROPERTY to VALUE.
11824 When called interactively, this will prompt for a property name, offering
11825 completion on existing and default properties. And then it will prompt
11826 for a value, offering completion either on allowed values (via an inherited
11827 xxx_ALL property) or on existing values in other instances of this property
11828 in the current file."
11829 (interactive
11830 (let* ((completion-ignore-case t)
11831 (keys (org-buffer-property-keys nil t t))
11832 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
11833 (prop (if (member prop0 keys)
11834 prop0
11835 (or (cdr (assoc (downcase prop0)
11836 (mapcar (lambda (x) (cons (downcase x) x))
11837 keys)))
11838 prop0)))
11839 (cur (org-entry-get nil prop))
11840 (allowed (org-property-get-allowed-values nil prop 'table))
11841 (existing (mapcar 'list (org-property-values prop)))
11842 (val (if allowed
11843 (org-completing-read "Value: " allowed nil 'req-match)
11844 (let (org-completion-use-ido)
11845 (org-completing-read
11846 (concat "Value" (if (and cur (string-match "\\S-" cur))
11847 (concat "[" cur "]") "")
11848 ": ")
11849 existing nil nil "" nil cur)))))
11850 (list prop (if (equal val "") cur val))))
11851 (unless (equal (org-entry-get nil property) value)
11852 (org-entry-put nil property value)))
11854 (defun org-delete-property (property)
11855 "In the current entry, delete PROPERTY."
11856 (interactive
11857 (let* ((completion-ignore-case t)
11858 (prop (org-ido-completing-read
11859 "Property: " (org-entry-properties nil 'standard))))
11860 (list prop)))
11861 (message "Property %s %s" property
11862 (if (org-entry-delete nil property)
11863 "deleted"
11864 "was not present in the entry")))
11866 (defun org-delete-property-globally (property)
11867 "Remove PROPERTY globally, from all entries."
11868 (interactive
11869 (let* ((completion-ignore-case t)
11870 (prop (org-ido-completing-read
11871 "Globally remove property: "
11872 (mapcar 'list (org-buffer-property-keys)))))
11873 (list prop)))
11874 (save-excursion
11875 (save-restriction
11876 (widen)
11877 (goto-char (point-min))
11878 (let ((cnt 0))
11879 (while (re-search-forward
11880 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
11881 nil t)
11882 (setq cnt (1+ cnt))
11883 (replace-match ""))
11884 (message "Property \"%s\" removed from %d entries" property cnt)))))
11886 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
11888 (defun org-compute-property-at-point ()
11889 "Compute the property at point.
11890 This looks for an enclosing column format, extracts the operator and
11891 then applies it to the property in the column format's scope."
11892 (interactive)
11893 (unless (org-at-property-p)
11894 (error "Not at a property"))
11895 (let ((prop (org-match-string-no-properties 2)))
11896 (org-columns-get-format-and-top-level)
11897 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
11898 (error "No operator defined for property %s" prop))
11899 (org-columns-compute prop)))
11901 (defun org-property-get-allowed-values (pom property &optional table)
11902 "Get allowed values for the property PROPERTY.
11903 When TABLE is non-nil, return an alist that can directly be used for
11904 completion."
11905 (let (vals)
11906 (cond
11907 ((equal property "TODO")
11908 (setq vals (org-with-point-at pom
11909 (append org-todo-keywords-1 '("")))))
11910 ((equal property "PRIORITY")
11911 (let ((n org-lowest-priority))
11912 (while (>= n org-highest-priority)
11913 (push (char-to-string n) vals)
11914 (setq n (1- n)))))
11915 ((member property org-special-properties))
11917 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
11919 (when (and vals (string-match "\\S-" vals))
11920 (setq vals (car (read-from-string (concat "(" vals ")"))))
11921 (setq vals (mapcar (lambda (x)
11922 (cond ((stringp x) x)
11923 ((numberp x) (number-to-string x))
11924 ((symbolp x) (symbol-name x))
11925 (t "???")))
11926 vals)))))
11927 (if table (mapcar 'list vals) vals)))
11929 (defun org-property-previous-allowed-value (&optional previous)
11930 "Switch to the next allowed value for this property."
11931 (interactive)
11932 (org-property-next-allowed-value t))
11934 (defun org-property-next-allowed-value (&optional previous)
11935 "Switch to the next allowed value for this property."
11936 (interactive)
11937 (unless (org-at-property-p)
11938 (error "Not at a property"))
11939 (let* ((key (match-string 2))
11940 (value (match-string 3))
11941 (allowed (or (org-property-get-allowed-values (point) key)
11942 (and (member value '("[ ]" "[-]" "[X]"))
11943 '("[ ]" "[X]"))))
11944 nval)
11945 (unless allowed
11946 (error "Allowed values for this property have not been defined"))
11947 (if previous (setq allowed (reverse allowed)))
11948 (if (member value allowed)
11949 (setq nval (car (cdr (member value allowed)))))
11950 (setq nval (or nval (car allowed)))
11951 (if (equal nval value)
11952 (error "Only one allowed value for this property"))
11953 (org-at-property-p)
11954 (replace-match (concat " :" key ": " nval) t t)
11955 (org-indent-line-function)
11956 (beginning-of-line 1)
11957 (skip-chars-forward " \t")))
11959 (defun org-find-entry-with-id (ident)
11960 "Locate the entry that contains the ID property with exact value IDENT.
11961 IDENT can be a string, a symbol or a number, this function will search for
11962 the string representation of it.
11963 Return the position where this entry starts, or nil if there is no such entry."
11964 (interactive "sID: ")
11965 (let ((id (cond
11966 ((stringp ident) ident)
11967 ((symbol-name ident) (symbol-name ident))
11968 ((numberp ident) (number-to-string ident))
11969 (t (error "IDENT %s must be a string, symbol or number" ident))))
11970 (case-fold-search nil))
11971 (save-excursion
11972 (save-restriction
11973 (widen)
11974 (goto-char (point-min))
11975 (when (re-search-forward
11976 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
11977 nil t)
11978 (org-back-to-heading)
11979 (point))))))
11981 ;;;; Timestamps
11983 (defvar org-last-changed-timestamp nil)
11984 (defvar org-last-inserted-timestamp nil
11985 "The last time stamp inserted with `org-insert-time-stamp'.")
11986 (defvar org-time-was-given) ; dynamically scoped parameter
11987 (defvar org-end-time-was-given) ; dynamically scoped parameter
11988 (defvar org-ts-what) ; dynamically scoped parameter
11990 (defun org-time-stamp (arg &optional inactive)
11991 "Prompt for a date/time and insert a time stamp.
11992 If the user specifies a time like HH:MM, or if this command is called
11993 with a prefix argument, the time stamp will contain date and time.
11994 Otherwise, only the date will be included. All parts of a date not
11995 specified by the user will be filled in from the current date/time.
11996 So if you press just return without typing anything, the time stamp
11997 will represent the current date/time. If there is already a timestamp
11998 at the cursor, it will be modified."
11999 (interactive "P")
12000 (let* ((ts nil)
12001 (default-time
12002 ;; Default time is either today, or, when entering a range,
12003 ;; the range start.
12004 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
12005 (save-excursion
12006 (re-search-backward
12007 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
12008 (- (point) 20) t)))
12009 (apply 'encode-time (org-parse-time-string (match-string 1)))
12010 (current-time)))
12011 (default-input (and ts (org-get-compact-tod ts)))
12012 org-time-was-given org-end-time-was-given time)
12013 (cond
12014 ((and (org-at-timestamp-p t)
12015 (memq last-command '(org-time-stamp org-time-stamp-inactive))
12016 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
12017 (insert "--")
12018 (setq time (let ((this-command this-command))
12019 (org-read-date arg 'totime nil nil
12020 default-time default-input)))
12021 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
12022 ((org-at-timestamp-p t)
12023 (setq time (let ((this-command this-command))
12024 (org-read-date arg 'totime nil nil default-time default-input)))
12025 (when (org-at-timestamp-p t) ; just to get the match data
12026 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
12027 (replace-match "")
12028 (setq org-last-changed-timestamp
12029 (org-insert-time-stamp
12030 time (or org-time-was-given arg)
12031 inactive nil nil (list org-end-time-was-given))))
12032 (message "Timestamp updated"))
12034 (setq time (let ((this-command this-command))
12035 (org-read-date arg 'totime nil nil default-time default-input)))
12036 (org-insert-time-stamp time (or org-time-was-given arg) inactive
12037 nil nil (list org-end-time-was-given))))))
12039 ;; FIXME: can we use this for something else, like computing time differences?
12040 (defun org-get-compact-tod (s)
12041 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
12042 (let* ((t1 (match-string 1 s))
12043 (h1 (string-to-number (match-string 2 s)))
12044 (m1 (string-to-number (match-string 3 s)))
12045 (t2 (and (match-end 4) (match-string 5 s)))
12046 (h2 (and t2 (string-to-number (match-string 6 s))))
12047 (m2 (and t2 (string-to-number (match-string 7 s))))
12048 dh dm)
12049 (if (not t2)
12051 (setq dh (- h2 h1) dm (- m2 m1))
12052 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
12053 (concat t1 "+" (number-to-string dh)
12054 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
12056 (defun org-time-stamp-inactive (&optional arg)
12057 "Insert an inactive time stamp.
12058 An inactive time stamp is enclosed in square brackets instead of angle
12059 brackets. It is inactive in the sense that it does not trigger agenda entries,
12060 does not link to the calendar and cannot be changed with the S-cursor keys.
12061 So these are more for recording a certain time/date."
12062 (interactive "P")
12063 (org-time-stamp arg 'inactive))
12065 (defvar org-date-ovl (org-make-overlay 1 1))
12066 (org-overlay-put org-date-ovl 'face 'org-warning)
12067 (org-detach-overlay org-date-ovl)
12069 (defvar org-ans1) ; dynamically scoped parameter
12070 (defvar org-ans2) ; dynamically scoped parameter
12072 (defvar org-plain-time-of-day-regexp) ; defined below
12074 (defvar org-overriding-default-time nil) ; dynamically scoped
12075 (defvar org-read-date-overlay nil)
12076 (defvar org-dcst nil) ; dynamically scoped
12077 (defvar org-read-date-history nil)
12079 (defun org-read-date (&optional with-time to-time from-string prompt
12080 default-time default-input)
12081 "Read a date, possibly a time, and make things smooth for the user.
12082 The prompt will suggest to enter an ISO date, but you can also enter anything
12083 which will at least partially be understood by `parse-time-string'.
12084 Unrecognized parts of the date will default to the current day, month, year,
12085 hour and minute. If this command is called to replace a timestamp at point,
12086 of to enter the second timestamp of a range, the default time is taken from the
12087 existing stamp. For example,
12088 3-2-5 --> 2003-02-05
12089 feb 15 --> currentyear-02-15
12090 sep 12 9 --> 2009-09-12
12091 12:45 --> today 12:45
12092 22 sept 0:34 --> currentyear-09-22 0:34
12093 12 --> currentyear-currentmonth-12
12094 Fri --> nearest Friday (today or later)
12095 etc.
12097 Furthermore you can specify a relative date by giving, as the *first* thing
12098 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
12099 change in days weeks, months, years.
12100 With a single plus or minus, the date is relative to today. With a double
12101 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
12102 +4d --> four days from today
12103 +4 --> same as above
12104 +2w --> two weeks from today
12105 ++5 --> five days from default date
12107 The function understands only English month and weekday abbreviations,
12108 but this can be configured with the variables `parse-time-months' and
12109 `parse-time-weekdays'.
12111 While prompting, a calendar is popped up - you can also select the
12112 date with the mouse (button 1). The calendar shows a period of three
12113 months. To scroll it to other months, use the keys `>' and `<'.
12114 If you don't like the calendar, turn it off with
12115 \(setq org-read-date-popup-calendar nil)
12117 With optional argument TO-TIME, the date will immediately be converted
12118 to an internal time.
12119 With an optional argument WITH-TIME, the prompt will suggest to also
12120 insert a time. Note that when WITH-TIME is not set, you can still
12121 enter a time, and this function will inform the calling routine about
12122 this change. The calling routine may then choose to change the format
12123 used to insert the time stamp into the buffer to include the time.
12124 With optional argument FROM-STRING, read from this string instead from
12125 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
12126 the time/date that is used for everything that is not specified by the
12127 user."
12128 (require 'parse-time)
12129 (let* ((org-time-stamp-rounding-minutes
12130 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
12131 (org-dcst org-display-custom-times)
12132 (ct (org-current-time))
12133 (def (or org-overriding-default-time default-time ct))
12134 (defdecode (decode-time def))
12135 (dummy (progn
12136 (when (< (nth 2 defdecode) org-extend-today-until)
12137 (setcar (nthcdr 2 defdecode) -1)
12138 (setcar (nthcdr 1 defdecode) 59)
12139 (setq def (apply 'encode-time defdecode)
12140 defdecode (decode-time def)))))
12141 (calendar-move-hook nil)
12142 (calendar-view-diary-initially-flag nil)
12143 (view-diary-entries-initially nil)
12144 (calendar-view-holidays-initially-flag nil)
12145 (view-calendar-holidays-initially nil)
12146 (timestr (format-time-string
12147 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
12148 (prompt (concat (if prompt (concat prompt " ") "")
12149 (format "Date+time [%s]: " timestr)))
12150 ans (org-ans0 "") org-ans1 org-ans2 final)
12152 (cond
12153 (from-string (setq ans from-string))
12154 (org-read-date-popup-calendar
12155 (save-excursion
12156 (save-window-excursion
12157 (calendar)
12158 (calendar-forward-day (- (time-to-days def)
12159 (calendar-absolute-from-gregorian
12160 (calendar-current-date))))
12161 (org-eval-in-calendar nil t)
12162 (let* ((old-map (current-local-map))
12163 (map (copy-keymap calendar-mode-map))
12164 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12165 (org-defkey map (kbd "RET") 'org-calendar-select)
12166 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
12167 'org-calendar-select-mouse)
12168 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
12169 'org-calendar-select-mouse)
12170 (org-defkey minibuffer-local-map [(meta shift left)]
12171 (lambda () (interactive)
12172 (org-eval-in-calendar '(calendar-backward-month 1))))
12173 (org-defkey minibuffer-local-map [(meta shift right)]
12174 (lambda () (interactive)
12175 (org-eval-in-calendar '(calendar-forward-month 1))))
12176 (org-defkey minibuffer-local-map [(meta shift up)]
12177 (lambda () (interactive)
12178 (org-eval-in-calendar '(calendar-backward-year 1))))
12179 (org-defkey minibuffer-local-map [(meta shift down)]
12180 (lambda () (interactive)
12181 (org-eval-in-calendar '(calendar-forward-year 1))))
12182 (org-defkey minibuffer-local-map [(shift up)]
12183 (lambda () (interactive)
12184 (org-eval-in-calendar '(calendar-backward-week 1))))
12185 (org-defkey minibuffer-local-map [(shift down)]
12186 (lambda () (interactive)
12187 (org-eval-in-calendar '(calendar-forward-week 1))))
12188 (org-defkey minibuffer-local-map [(shift left)]
12189 (lambda () (interactive)
12190 (org-eval-in-calendar '(calendar-backward-day 1))))
12191 (org-defkey minibuffer-local-map [(shift right)]
12192 (lambda () (interactive)
12193 (org-eval-in-calendar '(calendar-forward-day 1))))
12194 (org-defkey minibuffer-local-map ">"
12195 (lambda () (interactive)
12196 (org-eval-in-calendar '(scroll-calendar-left 1))))
12197 (org-defkey minibuffer-local-map "<"
12198 (lambda () (interactive)
12199 (org-eval-in-calendar '(scroll-calendar-right 1))))
12200 (run-hooks 'org-read-date-minibuffer-setup-hook)
12201 (unwind-protect
12202 (progn
12203 (use-local-map map)
12204 (add-hook 'post-command-hook 'org-read-date-display)
12205 (setq org-ans0 (read-string prompt default-input
12206 'org-read-date-history nil))
12207 ;; org-ans0: from prompt
12208 ;; org-ans1: from mouse click
12209 ;; org-ans2: from calendar motion
12210 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
12211 (remove-hook 'post-command-hook 'org-read-date-display)
12212 (use-local-map old-map)
12213 (when org-read-date-overlay
12214 (org-delete-overlay org-read-date-overlay)
12215 (setq org-read-date-overlay nil)))))))
12217 (t ; Naked prompt only
12218 (unwind-protect
12219 (setq ans (read-string prompt default-input
12220 'org-read-date-history timestr))
12221 (when org-read-date-overlay
12222 (org-delete-overlay org-read-date-overlay)
12223 (setq org-read-date-overlay nil)))))
12225 (setq final (org-read-date-analyze ans def defdecode))
12227 (if to-time
12228 (apply 'encode-time final)
12229 (if (and (boundp 'org-time-was-given) org-time-was-given)
12230 (format "%04d-%02d-%02d %02d:%02d"
12231 (nth 5 final) (nth 4 final) (nth 3 final)
12232 (nth 2 final) (nth 1 final))
12233 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
12234 (defvar def)
12235 (defvar defdecode)
12236 (defvar with-time)
12237 (defun org-read-date-display ()
12238 "Display the current date prompt interpretation in the minibuffer."
12239 (when org-read-date-display-live
12240 (when org-read-date-overlay
12241 (org-delete-overlay org-read-date-overlay))
12242 (let ((p (point)))
12243 (end-of-line 1)
12244 (while (not (equal (buffer-substring
12245 (max (point-min) (- (point) 4)) (point))
12246 " "))
12247 (insert " "))
12248 (goto-char p))
12249 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
12250 " " (or org-ans1 org-ans2)))
12251 (org-end-time-was-given nil)
12252 (f (org-read-date-analyze ans def defdecode))
12253 (fmts (if org-dcst
12254 org-time-stamp-custom-formats
12255 org-time-stamp-formats))
12256 (fmt (if (or with-time
12257 (and (boundp 'org-time-was-given) org-time-was-given))
12258 (cdr fmts)
12259 (car fmts)))
12260 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
12261 (when (and org-end-time-was-given
12262 (string-match org-plain-time-of-day-regexp txt))
12263 (setq txt (concat (substring txt 0 (match-end 0)) "-"
12264 org-end-time-was-given
12265 (substring txt (match-end 0)))))
12266 (setq org-read-date-overlay
12267 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
12268 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
12270 (defun org-read-date-analyze (ans def defdecode)
12271 "Analyse the combined answer of the date prompt."
12272 ;; FIXME: cleanup and comment
12273 (let (delta deltan deltaw deltadef year month day
12274 hour minute second wday pm h2 m2 tl wday1
12275 iso-year iso-weekday iso-week iso-year iso-date)
12277 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
12278 (setq ans "+0"))
12280 (when (setq delta (org-read-date-get-relative ans (current-time) def))
12281 (setq ans (replace-match "" t t ans)
12282 deltan (car delta)
12283 deltaw (nth 1 delta)
12284 deltadef (nth 2 delta)))
12286 ;; Check if there is an iso week date in there
12287 ;; If yes, sore the info and postpone interpreting it until the rest
12288 ;; of the parsing is done
12289 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
12290 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
12291 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
12292 iso-week (string-to-number (match-string 2 ans)))
12293 (setq ans (replace-match "" t t ans)))
12295 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
12296 (when (string-match
12297 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
12298 (setq year (if (match-end 2)
12299 (string-to-number (match-string 2 ans))
12300 (string-to-number (format-time-string "%Y")))
12301 month (string-to-number (match-string 3 ans))
12302 day (string-to-number (match-string 4 ans)))
12303 (if (< year 100) (setq year (+ 2000 year)))
12304 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
12305 t nil ans)))
12306 ;; Help matching am/pm times, because `parse-time-string' does not do that.
12307 ;; If there is a time with am/pm, and *no* time without it, we convert
12308 ;; so that matching will be successful.
12309 (loop for i from 1 to 2 do ; twice, for end time as well
12310 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
12311 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
12312 (setq hour (string-to-number (match-string 1 ans))
12313 minute (if (match-end 3)
12314 (string-to-number (match-string 3 ans))
12316 pm (equal ?p
12317 (string-to-char (downcase (match-string 4 ans)))))
12318 (if (and (= hour 12) (not pm))
12319 (setq hour 0)
12320 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
12321 (setq ans (replace-match (format "%02d:%02d" hour minute)
12322 t t ans))))
12324 ;; Check if a time range is given as a duration
12325 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
12326 (setq hour (string-to-number (match-string 1 ans))
12327 h2 (+ hour (string-to-number (match-string 3 ans)))
12328 minute (string-to-number (match-string 2 ans))
12329 m2 (+ minute (if (match-end 5) (string-to-number
12330 (match-string 5 ans))0)))
12331 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
12332 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
12333 t t ans)))
12335 ;; Check if there is a time range
12336 (when (boundp 'org-end-time-was-given)
12337 (setq org-time-was-given nil)
12338 (when (and (string-match org-plain-time-of-day-regexp ans)
12339 (match-end 8))
12340 (setq org-end-time-was-given (match-string 8 ans))
12341 (setq ans (concat (substring ans 0 (match-beginning 7))
12342 (substring ans (match-end 7))))))
12344 (setq tl (parse-time-string ans)
12345 day (or (nth 3 tl) (nth 3 defdecode))
12346 month (or (nth 4 tl)
12347 (if (and org-read-date-prefer-future
12348 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
12349 (1+ (nth 4 defdecode))
12350 (nth 4 defdecode)))
12351 year (or (nth 5 tl)
12352 (if (and org-read-date-prefer-future
12353 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
12354 (1+ (nth 5 defdecode))
12355 (nth 5 defdecode)))
12356 hour (or (nth 2 tl) (nth 2 defdecode))
12357 minute (or (nth 1 tl) (nth 1 defdecode))
12358 second (or (nth 0 tl) 0)
12359 wday (nth 6 tl))
12361 ;; Special date definitions below
12362 (cond
12363 (iso-week
12364 ;; There was an iso week
12365 (setq year (or iso-year year)
12366 day (or iso-weekday wday 1)
12367 wday nil ; to make sure that the trigger below does not match
12368 iso-date (calendar-gregorian-from-absolute
12369 (calendar-absolute-from-iso
12370 (list iso-week day year))))
12371 ; FIXME: Should we also push ISO weeks into the future?
12372 ; (when (and org-read-date-prefer-future
12373 ; (not iso-year)
12374 ; (< (calendar-absolute-from-gregorian iso-date)
12375 ; (time-to-days (current-time))))
12376 ; (setq year (1+ year)
12377 ; iso-date (calendar-gregorian-from-absolute
12378 ; (calendar-absolute-from-iso
12379 ; (list iso-week day year)))))
12380 (setq month (car iso-date)
12381 year (nth 2 iso-date)
12382 day (nth 1 iso-date)))
12383 (deltan
12384 (unless deltadef
12385 (let ((now (decode-time (current-time))))
12386 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
12387 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
12388 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
12389 ((equal deltaw "m") (setq month (+ month deltan)))
12390 ((equal deltaw "y") (setq year (+ year deltan)))))
12391 ((and wday (not (nth 3 tl)))
12392 ;; Weekday was given, but no day, so pick that day in the week
12393 ;; on or after the derived date.
12394 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
12395 (unless (equal wday wday1)
12396 (setq day (+ day (% (- wday wday1 -7) 7))))))
12397 (if (and (boundp 'org-time-was-given)
12398 (nth 2 tl))
12399 (setq org-time-was-given t))
12400 (if (< year 100) (setq year (+ 2000 year)))
12401 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
12402 (list second minute hour day month year)))
12404 (defvar parse-time-weekdays)
12406 (defun org-read-date-get-relative (s today default)
12407 "Check string S for special relative date string.
12408 TODAY and DEFAULT are internal times, for today and for a default.
12409 Return shift list (N what def-flag)
12410 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
12411 N is the number of WHATs to shift.
12412 DEF-FLAG is t when a double ++ or -- indicates shift relative to
12413 the DEFAULT date rather than TODAY."
12414 (when (and
12415 (string-match
12416 (concat
12417 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
12418 "\\([0-9]+\\)?"
12419 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
12420 "\\([ \t]\\|$\\)") s)
12421 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
12422 (let* ((dir (if (> (match-end 1) (match-beginning 1))
12423 (string-to-char (substring (match-string 1 s) -1))
12424 ?+))
12425 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
12426 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
12427 (what (if (match-end 3) (match-string 3 s) "d"))
12428 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
12429 (date (if rel default today))
12430 (wday (nth 6 (decode-time date)))
12431 delta)
12432 (if wday1
12433 (progn
12434 (setq delta (mod (+ 7 (- wday1 wday)) 7))
12435 (if (= dir ?-) (setq delta (- delta 7)))
12436 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
12437 (list delta "d" rel))
12438 (list (* n (if (= dir ?-) -1 1)) what rel)))))
12440 (defun org-eval-in-calendar (form &optional keepdate)
12441 "Eval FORM in the calendar window and return to current window.
12442 Also, store the cursor date in variable org-ans2."
12443 (let ((sw (selected-window)))
12444 (select-window (get-buffer-window "*Calendar*"))
12445 (eval form)
12446 (when (and (not keepdate) (calendar-cursor-to-date))
12447 (let* ((date (calendar-cursor-to-date))
12448 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12449 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
12450 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
12451 (select-window sw)))
12453 (defun org-calendar-select ()
12454 "Return to `org-read-date' with the date currently selected.
12455 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12456 (interactive)
12457 (when (calendar-cursor-to-date)
12458 (let* ((date (calendar-cursor-to-date))
12459 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12460 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12461 (if (active-minibuffer-window) (exit-minibuffer))))
12463 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
12464 "Insert a date stamp for the date given by the internal TIME.
12465 WITH-HM means, use the stamp format that includes the time of the day.
12466 INACTIVE means use square brackets instead of angular ones, so that the
12467 stamp will not contribute to the agenda.
12468 PRE and POST are optional strings to be inserted before and after the
12469 stamp.
12470 The command returns the inserted time stamp."
12471 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
12472 stamp)
12473 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
12474 (insert-before-markers (or pre ""))
12475 (insert-before-markers (setq stamp (format-time-string fmt time)))
12476 (when (listp extra)
12477 (setq extra (car extra))
12478 (if (and (stringp extra)
12479 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
12480 (setq extra (format "-%02d:%02d"
12481 (string-to-number (match-string 1 extra))
12482 (string-to-number (match-string 2 extra))))
12483 (setq extra nil)))
12484 (when extra
12485 (backward-char 1)
12486 (insert-before-markers extra)
12487 (forward-char 1))
12488 (insert-before-markers (or post ""))
12489 (setq org-last-inserted-timestamp stamp)))
12491 (defun org-toggle-time-stamp-overlays ()
12492 "Toggle the use of custom time stamp formats."
12493 (interactive)
12494 (setq org-display-custom-times (not org-display-custom-times))
12495 (unless org-display-custom-times
12496 (let ((p (point-min)) (bmp (buffer-modified-p)))
12497 (while (setq p (next-single-property-change p 'display))
12498 (if (and (get-text-property p 'display)
12499 (eq (get-text-property p 'face) 'org-date))
12500 (remove-text-properties
12501 p (setq p (next-single-property-change p 'display))
12502 '(display t))))
12503 (set-buffer-modified-p bmp)))
12504 (if (featurep 'xemacs)
12505 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12506 (org-restart-font-lock)
12507 (setq org-table-may-need-update t)
12508 (if org-display-custom-times
12509 (message "Time stamps are overlayed with custom format")
12510 (message "Time stamp overlays removed")))
12512 (defun org-display-custom-time (beg end)
12513 "Overlay modified time stamp format over timestamp between BEG and END."
12514 (let* ((ts (buffer-substring beg end))
12515 t1 w1 with-hm tf time str w2 (off 0))
12516 (save-match-data
12517 (setq t1 (org-parse-time-string ts t))
12518 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
12519 (setq off (- (match-end 0) (match-beginning 0)))))
12520 (setq end (- end off))
12521 (setq w1 (- end beg)
12522 with-hm (and (nth 1 t1) (nth 2 t1))
12523 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
12524 time (org-fix-decoded-time t1)
12525 str (org-add-props
12526 (format-time-string
12527 (substring tf 1 -1) (apply 'encode-time time))
12528 nil 'mouse-face 'highlight)
12529 w2 (length str))
12530 (if (not (= w2 w1))
12531 (add-text-properties (1+ beg) (+ 2 beg)
12532 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12533 (if (featurep 'xemacs)
12534 (progn
12535 (put-text-property beg end 'invisible t)
12536 (put-text-property beg end 'end-glyph (make-glyph str)))
12537 (put-text-property beg end 'display str))))
12539 (defun org-translate-time (string)
12540 "Translate all timestamps in STRING to custom format.
12541 But do this only if the variable `org-display-custom-times' is set."
12542 (when org-display-custom-times
12543 (save-match-data
12544 (let* ((start 0)
12545 (re org-ts-regexp-both)
12546 t1 with-hm inactive tf time str beg end)
12547 (while (setq start (string-match re string start))
12548 (setq beg (match-beginning 0)
12549 end (match-end 0)
12550 t1 (save-match-data
12551 (org-parse-time-string (substring string beg end) t))
12552 with-hm (and (nth 1 t1) (nth 2 t1))
12553 inactive (equal (substring string beg (1+ beg)) "[")
12554 tf (funcall (if with-hm 'cdr 'car)
12555 org-time-stamp-custom-formats)
12556 time (org-fix-decoded-time t1)
12557 str (format-time-string
12558 (concat
12559 (if inactive "[" "<") (substring tf 1 -1)
12560 (if inactive "]" ">"))
12561 (apply 'encode-time time))
12562 string (replace-match str t t string)
12563 start (+ start (length str)))))))
12564 string)
12566 (defun org-fix-decoded-time (time)
12567 "Set 0 instead of nil for the first 6 elements of time.
12568 Don't touch the rest."
12569 (let ((n 0))
12570 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12572 (defun org-days-to-time (timestamp-string)
12573 "Difference between TIMESTAMP-STRING and now in days."
12574 (- (time-to-days (org-time-string-to-time timestamp-string))
12575 (time-to-days (current-time))))
12577 (defun org-deadline-close (timestamp-string &optional ndays)
12578 "Is the time in TIMESTAMP-STRING close to the current date?"
12579 (setq ndays (or ndays (org-get-wdays timestamp-string)))
12580 (and (< (org-days-to-time timestamp-string) ndays)
12581 (not (org-entry-is-done-p))))
12583 (defun org-get-wdays (ts)
12584 "Get the deadline lead time appropriate for timestring TS."
12585 (cond
12586 ((<= org-deadline-warning-days 0)
12587 ;; 0 or negative, enforce this value no matter what
12588 (- org-deadline-warning-days))
12589 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
12590 ;; lead time is specified.
12591 (floor (* (string-to-number (match-string 1 ts))
12592 (cdr (assoc (match-string 2 ts)
12593 '(("d" . 1) ("w" . 7)
12594 ("m" . 30.4) ("y" . 365.25)))))))
12595 ;; go for the default.
12596 (t org-deadline-warning-days)))
12598 (defun org-calendar-select-mouse (ev)
12599 "Return to `org-read-date' with the date currently selected.
12600 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12601 (interactive "e")
12602 (mouse-set-point ev)
12603 (when (calendar-cursor-to-date)
12604 (let* ((date (calendar-cursor-to-date))
12605 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12606 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12607 (if (active-minibuffer-window) (exit-minibuffer))))
12609 (defun org-check-deadlines (ndays)
12610 "Check if there are any deadlines due or past due.
12611 A deadline is considered due if it happens within `org-deadline-warning-days'
12612 days from today's date. If the deadline appears in an entry marked DONE,
12613 it is not shown. The prefix arg NDAYS can be used to test that many
12614 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12615 (interactive "P")
12616 (let* ((org-warn-days
12617 (cond
12618 ((equal ndays '(4)) 100000)
12619 (ndays (prefix-numeric-value ndays))
12620 (t (abs org-deadline-warning-days))))
12621 (case-fold-search nil)
12622 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12623 (callback
12624 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12626 (message "%d deadlines past-due or due within %d days"
12627 (org-occur regexp nil callback)
12628 org-warn-days)))
12630 (defun org-check-before-date (date)
12631 "Check if there are deadlines or scheduled entries before DATE."
12632 (interactive (list (org-read-date)))
12633 (let ((case-fold-search nil)
12634 (regexp (concat "\\<\\(" org-deadline-string
12635 "\\|" org-scheduled-string
12636 "\\) *<\\([^>]+\\)>"))
12637 (callback
12638 (lambda () (time-less-p
12639 (org-time-string-to-time (match-string 2))
12640 (org-time-string-to-time date)))))
12641 (message "%d entries before %s"
12642 (org-occur regexp nil callback) date)))
12644 (defun org-check-after-date (date)
12645 "Check if there are deadlines or scheduled entries after DATE."
12646 (interactive (list (org-read-date)))
12647 (let ((case-fold-search nil)
12648 (regexp (concat "\\<\\(" org-deadline-string
12649 "\\|" org-scheduled-string
12650 "\\) *<\\([^>]+\\)>"))
12651 (callback
12652 (lambda () (not
12653 (time-less-p
12654 (org-time-string-to-time (match-string 2))
12655 (org-time-string-to-time date))))))
12656 (message "%d entries after %s"
12657 (org-occur regexp nil callback) date)))
12659 (defun org-evaluate-time-range (&optional to-buffer)
12660 "Evaluate a time range by computing the difference between start and end.
12661 Normally the result is just printed in the echo area, but with prefix arg
12662 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12663 If the time range is actually in a table, the result is inserted into the
12664 next column.
12665 For time difference computation, a year is assumed to be exactly 365
12666 days in order to avoid rounding problems."
12667 (interactive "P")
12669 (org-clock-update-time-maybe)
12670 (save-excursion
12671 (unless (org-at-date-range-p t)
12672 (goto-char (point-at-bol))
12673 (re-search-forward org-tr-regexp-both (point-at-eol) t))
12674 (if (not (org-at-date-range-p t))
12675 (error "Not at a time-stamp range, and none found in current line")))
12676 (let* ((ts1 (match-string 1))
12677 (ts2 (match-string 2))
12678 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12679 (match-end (match-end 0))
12680 (time1 (org-time-string-to-time ts1))
12681 (time2 (org-time-string-to-time ts2))
12682 (t1 (time-to-seconds time1))
12683 (t2 (time-to-seconds time2))
12684 (diff (abs (- t2 t1)))
12685 (negative (< (- t2 t1) 0))
12686 ;; (ys (floor (* 365 24 60 60)))
12687 (ds (* 24 60 60))
12688 (hs (* 60 60))
12689 (fy "%dy %dd %02d:%02d")
12690 (fy1 "%dy %dd")
12691 (fd "%dd %02d:%02d")
12692 (fd1 "%dd")
12693 (fh "%02d:%02d")
12694 y d h m align)
12695 (if havetime
12696 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12698 d (floor (/ diff ds)) diff (mod diff ds)
12699 h (floor (/ diff hs)) diff (mod diff hs)
12700 m (floor (/ diff 60)))
12701 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12703 d (floor (+ (/ diff ds) 0.5))
12704 h 0 m 0))
12705 (if (not to-buffer)
12706 (message "%s" (org-make-tdiff-string y d h m))
12707 (if (org-at-table-p)
12708 (progn
12709 (goto-char match-end)
12710 (setq align t)
12711 (and (looking-at " *|") (goto-char (match-end 0))))
12712 (goto-char match-end))
12713 (if (looking-at
12714 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12715 (replace-match ""))
12716 (if negative (insert " -"))
12717 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12718 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12719 (insert " " (format fh h m))))
12720 (if align (org-table-align))
12721 (message "Time difference inserted")))))
12723 (defun org-make-tdiff-string (y d h m)
12724 (let ((fmt "")
12725 (l nil))
12726 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12727 l (push y l)))
12728 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12729 l (push d l)))
12730 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12731 l (push h l)))
12732 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12733 l (push m l)))
12734 (apply 'format fmt (nreverse l))))
12736 (defun org-time-string-to-time (s)
12737 (apply 'encode-time (org-parse-time-string s)))
12739 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
12740 "Convert a time stamp to an absolute day number.
12741 If there is a specifyer for a cyclic time stamp, get the closest date to
12742 DAYNR.
12743 PREFER and SHOW-ALL are passed through to `org-closest-date'."
12744 (cond
12745 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
12746 (if (org-diary-sexp-entry (match-string 1 s) "" date)
12747 daynr
12748 (+ daynr 1000)))
12749 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
12750 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
12751 (time-to-days (current-time))) (match-string 0 s)
12752 prefer show-all))
12753 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
12755 (defun org-days-to-iso-week (days)
12756 "Return the iso week number."
12757 (require 'cal-iso)
12758 (car (calendar-iso-from-absolute days)))
12760 (defun org-small-year-to-year (year)
12761 "Convert 2-digit years into 4-digit years.
12762 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
12763 The year 2000 cannot be abbreviated. Any year larger than 99
12764 is returned unchanged."
12765 (if (< year 38)
12766 (setq year (+ 2000 year))
12767 (if (< year 100)
12768 (setq year (+ 1900 year))))
12769 year)
12771 (defun org-time-from-absolute (d)
12772 "Return the time corresponding to date D.
12773 D may be an absolute day number, or a calendar-type list (month day year)."
12774 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
12775 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
12777 (defun org-calendar-holiday ()
12778 "List of holidays, for Diary display in Org-mode."
12779 (require 'holidays)
12780 (let ((hl (funcall
12781 (if (fboundp 'calendar-check-holidays)
12782 'calendar-check-holidays 'check-calendar-holidays) date)))
12783 (if hl (mapconcat 'identity hl "; "))))
12785 (defun org-diary-sexp-entry (sexp entry date)
12786 "Process a SEXP diary ENTRY for DATE."
12787 (require 'diary-lib)
12788 (let ((result (if calendar-debug-sexp
12789 (let ((stack-trace-on-error t))
12790 (eval (car (read-from-string sexp))))
12791 (condition-case nil
12792 (eval (car (read-from-string sexp)))
12793 (error
12794 (beep)
12795 (message "Bad sexp at line %d in %s: %s"
12796 (org-current-line)
12797 (buffer-file-name) sexp)
12798 (sleep-for 2))))))
12799 (cond ((stringp result) result)
12800 ((and (consp result)
12801 (stringp (cdr result))) (cdr result))
12802 (result entry)
12803 (t nil))))
12805 (defun org-diary-to-ical-string (frombuf)
12806 "Get iCalendar entries from diary entries in buffer FROMBUF.
12807 This uses the icalendar.el library."
12808 (let* ((tmpdir (if (featurep 'xemacs)
12809 (temp-directory)
12810 temporary-file-directory))
12811 (tmpfile (make-temp-name
12812 (expand-file-name "orgics" tmpdir)))
12813 buf rtn b e)
12814 (save-excursion
12815 (set-buffer frombuf)
12816 (icalendar-export-region (point-min) (point-max) tmpfile)
12817 (setq buf (find-buffer-visiting tmpfile))
12818 (set-buffer buf)
12819 (goto-char (point-min))
12820 (if (re-search-forward "^BEGIN:VEVENT" nil t)
12821 (setq b (match-beginning 0)))
12822 (goto-char (point-max))
12823 (if (re-search-backward "^END:VEVENT" nil t)
12824 (setq e (match-end 0)))
12825 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
12826 (kill-buffer buf)
12827 (delete-file tmpfile)
12828 rtn))
12830 (defun org-closest-date (start current change prefer show-all)
12831 "Find the date closest to CURRENT that is consistent with START and CHANGE.
12832 When PREFER is `past' return a date that is either CURRENT or past.
12833 When PREFER is `future', return a date that is either CURRENT or future.
12834 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
12835 ;; Make the proper lists from the dates
12836 (catch 'exit
12837 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
12838 dn dw sday cday n1 n2 n0
12839 d m y y1 y2 date1 date2 nmonths nm ny m2)
12841 (setq start (org-date-to-gregorian start)
12842 current (org-date-to-gregorian
12843 (if show-all
12844 current
12845 (time-to-days (current-time))))
12846 sday (calendar-absolute-from-gregorian start)
12847 cday (calendar-absolute-from-gregorian current))
12849 (if (<= cday sday) (throw 'exit sday))
12851 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
12852 (setq dn (string-to-number (match-string 1 change))
12853 dw (cdr (assoc (match-string 2 change) a1)))
12854 (error "Invalid change specifyer: %s" change))
12855 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
12856 (cond
12857 ((eq dw 'day)
12858 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
12859 n2 (+ n1 dn)))
12860 ((eq dw 'year)
12861 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
12862 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
12863 (setq date1 (list m d y1)
12864 n1 (calendar-absolute-from-gregorian date1)
12865 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
12866 n2 (calendar-absolute-from-gregorian date2)))
12867 ((eq dw 'month)
12868 ;; approx number of month between the two dates
12869 (setq nmonths (floor (/ (- cday sday) 30.436875)))
12870 ;; How often does dn fit in there?
12871 (setq d (nth 1 start) m (car start) y (nth 2 start)
12872 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
12873 m (+ m nm)
12874 ny (floor (/ m 12))
12875 y (+ y ny)
12876 m (- m (* ny 12)))
12877 (while (> m 12) (setq m (- m 12) y (1+ y)))
12878 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
12879 (setq m2 (+ m dn) y2 y)
12880 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12881 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
12882 (while (<= n2 cday)
12883 (setq n1 n2 m m2 y y2)
12884 (setq m2 (+ m dn) y2 y)
12885 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12886 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
12887 ;; Make sure n1 is the earlier date
12888 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
12889 (if show-all
12890 (cond
12891 ((eq prefer 'past) n1)
12892 ((eq prefer 'future) (if (= cday n1) n1 n2))
12893 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
12894 (cond
12895 ((eq prefer 'past) n1)
12896 ((eq prefer 'future) (if (= cday n1) n1 n2))
12897 (t (if (= cday n1) n1 n2)))))))
12899 (defun org-date-to-gregorian (date)
12900 "Turn any specification of DATE into a gregorian date for the calendar."
12901 (cond ((integerp date) (calendar-gregorian-from-absolute date))
12902 ((and (listp date) (= (length date) 3)) date)
12903 ((stringp date)
12904 (setq date (org-parse-time-string date))
12905 (list (nth 4 date) (nth 3 date) (nth 5 date)))
12906 ((listp date)
12907 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
12909 (defun org-parse-time-string (s &optional nodefault)
12910 "Parse the standard Org-mode time string.
12911 This should be a lot faster than the normal `parse-time-string'.
12912 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12913 hour and minute fields will be nil if not given."
12914 (if (string-match org-ts-regexp0 s)
12915 (list 0
12916 (if (or (match-beginning 8) (not nodefault))
12917 (string-to-number (or (match-string 8 s) "0")))
12918 (if (or (match-beginning 7) (not nodefault))
12919 (string-to-number (or (match-string 7 s) "0")))
12920 (string-to-number (match-string 4 s))
12921 (string-to-number (match-string 3 s))
12922 (string-to-number (match-string 2 s))
12923 nil nil nil)
12924 (make-list 9 0)))
12926 (defun org-timestamp-up (&optional arg)
12927 "Increase the date item at the cursor by one.
12928 If the cursor is on the year, change the year. If it is on the month or
12929 the day, change that.
12930 With prefix ARG, change by that many units."
12931 (interactive "p")
12932 (org-timestamp-change (prefix-numeric-value arg)))
12934 (defun org-timestamp-down (&optional arg)
12935 "Decrease the date item at the cursor by one.
12936 If the cursor is on the year, change the year. If it is on the month or
12937 the day, change that.
12938 With prefix ARG, change by that many units."
12939 (interactive "p")
12940 (org-timestamp-change (- (prefix-numeric-value arg))))
12942 (defun org-timestamp-up-day (&optional arg)
12943 "Increase the date in the time stamp by one day.
12944 With prefix ARG, change that many days."
12945 (interactive "p")
12946 (if (and (not (org-at-timestamp-p t))
12947 (org-on-heading-p))
12948 (org-todo 'up)
12949 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12951 (defun org-timestamp-down-day (&optional arg)
12952 "Decrease the date in the time stamp by one day.
12953 With prefix ARG, change that many days."
12954 (interactive "p")
12955 (if (and (not (org-at-timestamp-p t))
12956 (org-on-heading-p))
12957 (org-todo 'down)
12958 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12960 (defun org-at-timestamp-p (&optional inactive-ok)
12961 "Determine if the cursor is in or at a timestamp."
12962 (interactive)
12963 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12964 (pos (point))
12965 (ans (or (looking-at tsr)
12966 (save-excursion
12967 (skip-chars-backward "^[<\n\r\t")
12968 (if (> (point) (point-min)) (backward-char 1))
12969 (and (looking-at tsr)
12970 (> (- (match-end 0) pos) -1))))))
12971 (and ans
12972 (boundp 'org-ts-what)
12973 (setq org-ts-what
12974 (cond
12975 ((= pos (match-beginning 0)) 'bracket)
12976 ((= pos (1- (match-end 0))) 'bracket)
12977 ((org-pos-in-match-range pos 2) 'year)
12978 ((org-pos-in-match-range pos 3) 'month)
12979 ((org-pos-in-match-range pos 7) 'hour)
12980 ((org-pos-in-match-range pos 8) 'minute)
12981 ((or (org-pos-in-match-range pos 4)
12982 (org-pos-in-match-range pos 5)) 'day)
12983 ((and (> pos (or (match-end 8) (match-end 5)))
12984 (< pos (match-end 0)))
12985 (- pos (or (match-end 8) (match-end 5))))
12986 (t 'day))))
12987 ans))
12989 (defun org-toggle-timestamp-type ()
12990 "Toggle the type (<active> or [inactive]) of a time stamp."
12991 (interactive)
12992 (when (org-at-timestamp-p t)
12993 (let ((beg (match-beginning 0)) (end (match-end 0))
12994 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
12995 (save-excursion
12996 (goto-char beg)
12997 (while (re-search-forward "[][<>]" end t)
12998 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
12999 t t)))
13000 (message "Timestamp is now %sactive"
13001 (if (equal (char-after beg) ?<) "" "in")))))
13003 (defun org-timestamp-change (n &optional what)
13004 "Change the date in the time stamp at point.
13005 The date will be changed by N times WHAT. WHAT can be `day', `month',
13006 `year', `minute', `second'. If WHAT is not given, the cursor position
13007 in the timestamp determines what will be changed."
13008 (let ((pos (point))
13009 with-hm inactive
13010 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
13011 org-ts-what
13012 extra rem
13013 ts time time0)
13014 (if (not (org-at-timestamp-p t))
13015 (error "Not at a timestamp"))
13016 (if (and (not what) (eq org-ts-what 'bracket))
13017 (org-toggle-timestamp-type)
13018 (if (and (not what) (not (eq org-ts-what 'day))
13019 org-display-custom-times
13020 (get-text-property (point) 'display)
13021 (not (get-text-property (1- (point)) 'display)))
13022 (setq org-ts-what 'day))
13023 (setq org-ts-what (or what org-ts-what)
13024 inactive (= (char-after (match-beginning 0)) ?\[)
13025 ts (match-string 0))
13026 (replace-match "")
13027 (if (string-match
13028 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
13030 (setq extra (match-string 1 ts)))
13031 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
13032 (setq with-hm t))
13033 (setq time0 (org-parse-time-string ts))
13034 (when (and (eq org-ts-what 'minute)
13035 (eq current-prefix-arg nil))
13036 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
13037 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
13038 (setcar (cdr time0) (+ (nth 1 time0)
13039 (if (> n 0) (- rem) (- dm rem))))))
13040 (setq time
13041 (encode-time (or (car time0) 0)
13042 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
13043 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
13044 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
13045 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
13046 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
13047 (nthcdr 6 time0)))
13048 (when (and (member org-ts-what '(hour minute))
13049 extra
13050 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
13051 (setq extra (org-modify-ts-extra
13052 extra
13053 (if (eq org-ts-what 'hour) 2 5)
13054 n dm)))
13055 (when (integerp org-ts-what)
13056 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
13057 (if (eq what 'calendar)
13058 (let ((cal-date (org-get-date-from-calendar)))
13059 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
13060 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
13061 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
13062 (setcar time0 (or (car time0) 0))
13063 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
13064 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
13065 (setq time (apply 'encode-time time0))))
13066 (setq org-last-changed-timestamp
13067 (org-insert-time-stamp time with-hm inactive nil nil extra))
13068 (org-clock-update-time-maybe)
13069 (goto-char pos)
13070 ;; Try to recenter the calendar window, if any
13071 (if (and org-calendar-follow-timestamp-change
13072 (get-buffer-window "*Calendar*" t)
13073 (memq org-ts-what '(day month year)))
13074 (org-recenter-calendar (time-to-days time))))))
13076 (defun org-modify-ts-extra (s pos n dm)
13077 "Change the different parts of the lead-time and repeat fields in timestamp."
13078 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
13079 ng h m new rem)
13080 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
13081 (cond
13082 ((or (org-pos-in-match-range pos 2)
13083 (org-pos-in-match-range pos 3))
13084 (setq m (string-to-number (match-string 3 s))
13085 h (string-to-number (match-string 2 s)))
13086 (if (org-pos-in-match-range pos 2)
13087 (setq h (+ h n))
13088 (setq n (* dm (org-no-warnings (signum n))))
13089 (when (not (= 0 (setq rem (% m dm))))
13090 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
13091 (setq m (+ m n)))
13092 (if (< m 0) (setq m (+ m 60) h (1- h)))
13093 (if (> m 59) (setq m (- m 60) h (1+ h)))
13094 (setq h (min 24 (max 0 h)))
13095 (setq ng 1 new (format "-%02d:%02d" h m)))
13096 ((org-pos-in-match-range pos 6)
13097 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
13098 ((org-pos-in-match-range pos 5)
13099 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
13101 ((org-pos-in-match-range pos 9)
13102 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
13103 ((org-pos-in-match-range pos 8)
13104 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
13106 (when ng
13107 (setq s (concat
13108 (substring s 0 (match-beginning ng))
13110 (substring s (match-end ng))))))
13113 (defun org-recenter-calendar (date)
13114 "If the calendar is visible, recenter it to DATE."
13115 (let* ((win (selected-window))
13116 (cwin (get-buffer-window "*Calendar*" t))
13117 (calendar-move-hook nil))
13118 (when cwin
13119 (select-window cwin)
13120 (calendar-goto-date (if (listp date) date
13121 (calendar-gregorian-from-absolute date)))
13122 (select-window win))))
13124 (defun org-goto-calendar (&optional arg)
13125 "Go to the Emacs calendar at the current date.
13126 If there is a time stamp in the current line, go to that date.
13127 A prefix ARG can be used to force the current date."
13128 (interactive "P")
13129 (let ((tsr org-ts-regexp) diff
13130 (calendar-move-hook nil)
13131 (calendar-view-holidays-initially-flag nil)
13132 (view-calendar-holidays-initially nil)
13133 (calendar-view-diary-initially-flag nil)
13134 (view-diary-entries-initially nil))
13135 (if (or (org-at-timestamp-p)
13136 (save-excursion
13137 (beginning-of-line 1)
13138 (looking-at (concat ".*" tsr))))
13139 (let ((d1 (time-to-days (current-time)))
13140 (d2 (time-to-days
13141 (org-time-string-to-time (match-string 1)))))
13142 (setq diff (- d2 d1))))
13143 (calendar)
13144 (calendar-goto-today)
13145 (if (and diff (not arg)) (calendar-forward-day diff))))
13147 (defun org-get-date-from-calendar ()
13148 "Return a list (month day year) of date at point in calendar."
13149 (with-current-buffer "*Calendar*"
13150 (save-match-data
13151 (calendar-cursor-to-date))))
13153 (defun org-date-from-calendar ()
13154 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
13155 If there is already a time stamp at the cursor position, update it."
13156 (interactive)
13157 (if (org-at-timestamp-p t)
13158 (org-timestamp-change 0 'calendar)
13159 (let ((cal-date (org-get-date-from-calendar)))
13160 (org-insert-time-stamp
13161 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
13163 (defun org-minutes-to-hh:mm-string (m)
13164 "Compute H:MM from a number of minutes."
13165 (let ((h (/ m 60)))
13166 (setq m (- m (* 60 h)))
13167 (format org-time-clocksum-format h m)))
13169 (defun org-hh:mm-string-to-minutes (s)
13170 "Convert a string H:MM to a number of minutes."
13171 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
13172 (+ (* (string-to-number (match-string 1 s)) 60)
13173 (string-to-number (match-string 2 s)))
13176 ;;;; Files
13178 (defun org-save-all-org-buffers ()
13179 "Save all Org-mode buffers without user confirmation."
13180 (interactive)
13181 (message "Saving all Org-mode buffers...")
13182 (save-some-buffers t 'org-mode-p)
13183 (when (featurep 'org-id) (org-id-locations-save))
13184 (message "Saving all Org-mode buffers... done"))
13186 (defun org-revert-all-org-buffers ()
13187 "Revert all Org-mode buffers.
13188 Prompt for confirmation when there are unsaved changes.
13189 Be sure you know what you are doing before letting this function
13190 overwrite your changes.
13192 This function is useful in a setup where one tracks org files
13193 with a version control system, to revert on one machine after pulling
13194 changes from another. I believe the procedure must be like this:
13196 1. M-x org-save-all-org-buffers
13197 2. Pull changes from the other machine, resolve conflicts
13198 3. M-x org-revert-all-org-buffers"
13199 (interactive)
13200 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
13201 (error "Abort"))
13202 (save-excursion
13203 (save-window-excursion
13204 (mapc
13205 (lambda (b)
13206 (when (and (with-current-buffer b (org-mode-p))
13207 (with-current-buffer b buffer-file-name))
13208 (switch-to-buffer b)
13209 (revert-buffer t 'no-confirm)))
13210 (buffer-list))
13211 (when (and (featurep 'org-id) org-id-track-globally)
13212 (org-id-locations-load)))))
13214 ;;;; Agenda files
13216 ;;;###autoload
13217 (defun org-iswitchb (&optional arg)
13218 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
13219 With a prefix argument, restrict available to files.
13220 With two prefix arguments, restrict available buffers to agenda files.
13222 Due to some yet unresolved reason, the global function
13223 `iswitchb-mode' needs to be active for this function to work."
13224 (interactive "P")
13225 (require 'iswitchb)
13226 (let ((enabled iswitchb-mode) blist)
13227 (or enabled (iswitchb-mode 1))
13228 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13229 ((equal arg '(16)) (org-buffer-list 'agenda))
13230 (t (org-buffer-list))))
13231 (unwind-protect
13232 (let ((iswitchb-make-buflist-hook
13233 (lambda ()
13234 (setq iswitchb-temp-buflist
13235 (mapcar 'buffer-name blist)))))
13236 (switch-to-buffer
13237 (iswitchb-read-buffer
13238 "Switch-to: " nil t))
13239 (or enabled (iswitchb-mode -1))))))
13241 ;;;###autoload
13242 (defun org-ido-switchb (&optional arg)
13243 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
13244 With a prefix argument, restrict available to files.
13245 With two prefix arguments, restrict available buffers to agenda files."
13246 (interactive "P")
13247 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13248 ((equal arg '(16)) (org-buffer-list 'agenda))
13249 (t (org-buffer-list)))))
13250 (switch-to-buffer
13251 (org-ido-completing-read "Org buffer: "
13252 (mapcar 'list (mapcar 'buffer-name blist))
13253 nil t))))
13255 (defun org-buffer-list (&optional predicate exclude-tmp)
13256 "Return a list of Org buffers.
13257 PREDICATE can be `export', `files' or `agenda'.
13259 export restrict the list to Export buffers.
13260 files restrict the list to buffers visiting Org files.
13261 agenda restrict the list to buffers visiting agenda files.
13263 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
13264 (let* ((bfn nil)
13265 (agenda-files (and (eq predicate 'agenda)
13266 (mapcar 'file-truename (org-agenda-files t))))
13267 (filter
13268 (cond
13269 ((eq predicate 'files)
13270 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
13271 ((eq predicate 'export)
13272 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
13273 ((eq predicate 'agenda)
13274 (lambda (b)
13275 (with-current-buffer b
13276 (and (eq major-mode 'org-mode)
13277 (setq bfn (buffer-file-name b))
13278 (member (file-truename bfn) agenda-files)))))
13279 (t (lambda (b) (with-current-buffer b
13280 (or (eq major-mode 'org-mode)
13281 (string-match "\*Org .*Export"
13282 (buffer-name b)))))))))
13283 (delq nil
13284 (mapcar
13285 (lambda(b)
13286 (if (and (funcall filter b)
13287 (or (not exclude-tmp)
13288 (not (string-match "tmp" (buffer-name b)))))
13290 nil))
13291 (buffer-list)))))
13293 (defun org-agenda-files (&optional unrestricted archives)
13294 "Get the list of agenda files.
13295 Optional UNRESTRICTED means return the full list even if a restriction
13296 is currently in place.
13297 When ARCHIVES is t, include all archive files hat are really being
13298 used by the agenda files. If ARCHIVE is `ifmode', do this only if
13299 `org-agenda-archives-mode' is t."
13300 (let ((files
13301 (cond
13302 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
13303 ((stringp org-agenda-files) (org-read-agenda-file-list))
13304 ((listp org-agenda-files) org-agenda-files)
13305 (t (error "Invalid value of `org-agenda-files'")))))
13306 (setq files (apply 'append
13307 (mapcar (lambda (f)
13308 (if (file-directory-p f)
13309 (directory-files
13310 f t org-agenda-file-regexp)
13311 (list f)))
13312 files)))
13313 (when org-agenda-skip-unavailable-files
13314 (setq files (delq nil
13315 (mapcar (function
13316 (lambda (file)
13317 (and (file-readable-p file) file)))
13318 files))))
13319 (when (or (eq archives t)
13320 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
13321 (setq files (org-add-archive-files files)))
13322 files))
13324 (defun org-edit-agenda-file-list ()
13325 "Edit the list of agenda files.
13326 Depending on setup, this either uses customize to edit the variable
13327 `org-agenda-files', or it visits the file that is holding the list. In the
13328 latter case, the buffer is set up in a way that saving it automatically kills
13329 the buffer and restores the previous window configuration."
13330 (interactive)
13331 (if (stringp org-agenda-files)
13332 (let ((cw (current-window-configuration)))
13333 (find-file org-agenda-files)
13334 (org-set-local 'org-window-configuration cw)
13335 (org-add-hook 'after-save-hook
13336 (lambda ()
13337 (set-window-configuration
13338 (prog1 org-window-configuration
13339 (kill-buffer (current-buffer))))
13340 (org-install-agenda-files-menu)
13341 (message "New agenda file list installed"))
13342 nil 'local)
13343 (message "%s" (substitute-command-keys
13344 "Edit list and finish with \\[save-buffer]")))
13345 (customize-variable 'org-agenda-files)))
13347 (defun org-store-new-agenda-file-list (list)
13348 "Set new value for the agenda file list and save it correctly."
13349 (if (stringp org-agenda-files)
13350 (let ((f org-agenda-files) b)
13351 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
13352 (with-temp-file f
13353 (insert (mapconcat 'identity list "\n") "\n")))
13354 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
13355 (setq org-agenda-files list)
13356 (customize-save-variable 'org-agenda-files org-agenda-files))))
13358 (defun org-read-agenda-file-list ()
13359 "Read the list of agenda files from a file."
13360 (when (file-directory-p org-agenda-files)
13361 (error "`org-agenda-files' cannot be a single directory"))
13362 (when (stringp org-agenda-files)
13363 (with-temp-buffer
13364 (insert-file-contents org-agenda-files)
13365 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
13368 ;;;###autoload
13369 (defun org-cycle-agenda-files ()
13370 "Cycle through the files in `org-agenda-files'.
13371 If the current buffer visits an agenda file, find the next one in the list.
13372 If the current buffer does not, find the first agenda file."
13373 (interactive)
13374 (let* ((fs (org-agenda-files t))
13375 (files (append fs (list (car fs))))
13376 (tcf (if buffer-file-name (file-truename buffer-file-name)))
13377 file)
13378 (unless files (error "No agenda files"))
13379 (catch 'exit
13380 (while (setq file (pop files))
13381 (if (equal (file-truename file) tcf)
13382 (when (car files)
13383 (find-file (car files))
13384 (throw 'exit t))))
13385 (find-file (car fs)))
13386 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
13388 (defun org-agenda-file-to-front (&optional to-end)
13389 "Move/add the current file to the top of the agenda file list.
13390 If the file is not present in the list, it is added to the front. If it is
13391 present, it is moved there. With optional argument TO-END, add/move to the
13392 end of the list."
13393 (interactive "P")
13394 (let ((org-agenda-skip-unavailable-files nil)
13395 (file-alist (mapcar (lambda (x)
13396 (cons (file-truename x) x))
13397 (org-agenda-files t)))
13398 (ctf (file-truename buffer-file-name))
13399 x had)
13400 (setq x (assoc ctf file-alist) had x)
13402 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
13403 (if to-end
13404 (setq file-alist (append (delq x file-alist) (list x)))
13405 (setq file-alist (cons x (delq x file-alist))))
13406 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
13407 (org-install-agenda-files-menu)
13408 (message "File %s to %s of agenda file list"
13409 (if had "moved" "added") (if to-end "end" "front"))))
13411 (defun org-remove-file (&optional file)
13412 "Remove current file from the list of files in variable `org-agenda-files'.
13413 These are the files which are being checked for agenda entries.
13414 Optional argument FILE means, use this file instead of the current."
13415 (interactive)
13416 (let* ((org-agenda-skip-unavailable-files nil)
13417 (file (or file buffer-file-name))
13418 (true-file (file-truename file))
13419 (afile (abbreviate-file-name file))
13420 (files (delq nil (mapcar
13421 (lambda (x)
13422 (if (equal true-file
13423 (file-truename x))
13424 nil x))
13425 (org-agenda-files t)))))
13426 (if (not (= (length files) (length (org-agenda-files t))))
13427 (progn
13428 (org-store-new-agenda-file-list files)
13429 (org-install-agenda-files-menu)
13430 (message "Removed file: %s" afile))
13431 (message "File was not in list: %s (not removed)" afile))))
13433 (defun org-file-menu-entry (file)
13434 (vector file (list 'find-file file) t))
13436 (defun org-check-agenda-file (file)
13437 "Make sure FILE exists. If not, ask user what to do."
13438 (when (not (file-exists-p file))
13439 (message "non-existent file %s. [R]emove from list or [A]bort?"
13440 (abbreviate-file-name file))
13441 (let ((r (downcase (read-char-exclusive))))
13442 (cond
13443 ((equal r ?r)
13444 (org-remove-file file)
13445 (throw 'nextfile t))
13446 (t (error "Abort"))))))
13448 (defun org-get-agenda-file-buffer (file)
13449 "Get a buffer visiting FILE. If the buffer needs to be created, add
13450 it to the list of buffers which might be released later."
13451 (let ((buf (org-find-base-buffer-visiting file)))
13452 (if buf
13453 buf ; just return it
13454 ;; Make a new buffer and remember it
13455 (setq buf (find-file-noselect file))
13456 (if buf (push buf org-agenda-new-buffers))
13457 buf)))
13459 (defun org-release-buffers (blist)
13460 "Release all buffers in list, asking the user for confirmation when needed.
13461 When a buffer is unmodified, it is just killed. When modified, it is saved
13462 \(if the user agrees) and then killed."
13463 (let (buf file)
13464 (while (setq buf (pop blist))
13465 (setq file (buffer-file-name buf))
13466 (when (and (buffer-modified-p buf)
13467 file
13468 (y-or-n-p (format "Save file %s? " file)))
13469 (with-current-buffer buf (save-buffer)))
13470 (kill-buffer buf))))
13472 (defun org-prepare-agenda-buffers (files)
13473 "Create buffers for all agenda files, protect archived trees and comments."
13474 (interactive)
13475 (let ((pa '(:org-archived t))
13476 (pc '(:org-comment t))
13477 (pall '(:org-archived t :org-comment t))
13478 (inhibit-read-only t)
13479 (rea (concat ":" org-archive-tag ":"))
13480 bmp file re)
13481 (save-excursion
13482 (save-restriction
13483 (while (setq file (pop files))
13484 (catch 'nextfile
13485 (if (bufferp file)
13486 (set-buffer file)
13487 (org-check-agenda-file file)
13488 (set-buffer (org-get-agenda-file-buffer file)))
13489 (widen)
13490 (setq bmp (buffer-modified-p))
13491 (org-refresh-category-properties)
13492 (setq org-todo-keywords-for-agenda
13493 (append org-todo-keywords-for-agenda org-todo-keywords-1))
13494 (setq org-done-keywords-for-agenda
13495 (append org-done-keywords-for-agenda org-done-keywords))
13496 (setq org-todo-keyword-alist-for-agenda
13497 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
13498 (setq org-tag-alist-for-agenda
13499 (append org-tag-alist-for-agenda org-tag-alist))
13501 (save-excursion
13502 (remove-text-properties (point-min) (point-max) pall)
13503 (when org-agenda-skip-archived-trees
13504 (goto-char (point-min))
13505 (while (re-search-forward rea nil t)
13506 (if (org-on-heading-p t)
13507 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
13508 (goto-char (point-min))
13509 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
13510 (while (re-search-forward re nil t)
13511 (add-text-properties
13512 (match-beginning 0) (org-end-of-subtree t) pc)))
13513 (set-buffer-modified-p bmp)))))
13514 (setq org-todo-keyword-alist-for-agenda
13515 (org-uniquify org-todo-keyword-alist-for-agenda)
13516 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
13518 ;;;; Embedded LaTeX
13520 (defvar org-cdlatex-mode-map (make-sparse-keymap)
13521 "Keymap for the minor `org-cdlatex-mode'.")
13523 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
13524 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
13525 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
13526 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
13527 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
13529 (defvar org-cdlatex-texmathp-advice-is-done nil
13530 "Flag remembering if we have applied the advice to texmathp already.")
13532 (define-minor-mode org-cdlatex-mode
13533 "Toggle the minor `org-cdlatex-mode'.
13534 This mode supports entering LaTeX environment and math in LaTeX fragments
13535 in Org-mode.
13536 \\{org-cdlatex-mode-map}"
13537 nil " OCDL" nil
13538 (when org-cdlatex-mode (require 'cdlatex))
13539 (unless org-cdlatex-texmathp-advice-is-done
13540 (setq org-cdlatex-texmathp-advice-is-done t)
13541 (defadvice texmathp (around org-math-always-on activate)
13542 "Always return t in org-mode buffers.
13543 This is because we want to insert math symbols without dollars even outside
13544 the LaTeX math segments. If Orgmode thinks that point is actually inside
13545 an embedded LaTeX fragment, let texmathp do its job.
13546 \\[org-cdlatex-mode-map]"
13547 (interactive)
13548 (let (p)
13549 (cond
13550 ((not (org-mode-p)) ad-do-it)
13551 ((eq this-command 'cdlatex-math-symbol)
13552 (setq ad-return-value t
13553 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
13555 (let ((p (org-inside-LaTeX-fragment-p)))
13556 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
13557 (setq ad-return-value t
13558 texmathp-why '("Org-mode embedded math" . 0))
13559 (if p ad-do-it)))))))))
13561 (defun turn-on-org-cdlatex ()
13562 "Unconditionally turn on `org-cdlatex-mode'."
13563 (org-cdlatex-mode 1))
13565 (defun org-inside-LaTeX-fragment-p ()
13566 "Test if point is inside a LaTeX fragment.
13567 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
13568 sequence appearing also before point.
13569 Even though the matchers for math are configurable, this function assumes
13570 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
13571 delimiters are skipped when they have been removed by customization.
13572 The return value is nil, or a cons cell with the delimiter and
13573 and the position of this delimiter.
13575 This function does a reasonably good job, but can locally be fooled by
13576 for example currency specifications. For example it will assume being in
13577 inline math after \"$22.34\". The LaTeX fragment formatter will only format
13578 fragments that are properly closed, but during editing, we have to live
13579 with the uncertainty caused by missing closing delimiters. This function
13580 looks only before point, not after."
13581 (catch 'exit
13582 (let ((pos (point))
13583 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
13584 (lim (progn
13585 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
13586 (point)))
13587 dd-on str (start 0) m re)
13588 (goto-char pos)
13589 (when dodollar
13590 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
13591 re (nth 1 (assoc "$" org-latex-regexps)))
13592 (while (string-match re str start)
13593 (cond
13594 ((= (match-end 0) (length str))
13595 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
13596 ((= (match-end 0) (- (length str) 5))
13597 (throw 'exit nil))
13598 (t (setq start (match-end 0))))))
13599 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
13600 (goto-char pos)
13601 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
13602 (and (match-beginning 2) (throw 'exit nil))
13603 ;; count $$
13604 (while (re-search-backward "\\$\\$" lim t)
13605 (setq dd-on (not dd-on)))
13606 (goto-char pos)
13607 (if dd-on (cons "$$" m))))))
13610 (defun org-try-cdlatex-tab ()
13611 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
13612 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
13613 - inside a LaTeX fragment, or
13614 - after the first word in a line, where an abbreviation expansion could
13615 insert a LaTeX environment."
13616 (when org-cdlatex-mode
13617 (cond
13618 ((save-excursion
13619 (skip-chars-backward "a-zA-Z0-9*")
13620 (skip-chars-backward " \t")
13621 (bolp))
13622 (cdlatex-tab) t)
13623 ((org-inside-LaTeX-fragment-p)
13624 (cdlatex-tab) t)
13625 (t nil))))
13627 (defun org-cdlatex-underscore-caret (&optional arg)
13628 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
13629 Revert to the normal definition outside of these fragments."
13630 (interactive "P")
13631 (if (org-inside-LaTeX-fragment-p)
13632 (call-interactively 'cdlatex-sub-superscript)
13633 (let (org-cdlatex-mode)
13634 (call-interactively (key-binding (vector last-input-event))))))
13636 (defun org-cdlatex-math-modify (&optional arg)
13637 "Execute `cdlatex-math-modify' in LaTeX fragments.
13638 Revert to the normal definition outside of these fragments."
13639 (interactive "P")
13640 (if (org-inside-LaTeX-fragment-p)
13641 (call-interactively 'cdlatex-math-modify)
13642 (let (org-cdlatex-mode)
13643 (call-interactively (key-binding (vector last-input-event))))))
13645 (defvar org-latex-fragment-image-overlays nil
13646 "List of overlays carrying the images of latex fragments.")
13647 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
13649 (defun org-remove-latex-fragment-image-overlays ()
13650 "Remove all overlays with LaTeX fragment images in current buffer."
13651 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
13652 (setq org-latex-fragment-image-overlays nil))
13654 (defun org-preview-latex-fragment (&optional subtree)
13655 "Preview the LaTeX fragment at point, or all locally or globally.
13656 If the cursor is in a LaTeX fragment, create the image and overlay
13657 it over the source code. If there is no fragment at point, display
13658 all fragments in the current text, from one headline to the next. With
13659 prefix SUBTREE, display all fragments in the current subtree. With a
13660 double prefix `C-u C-u', or when the cursor is before the first headline,
13661 display all fragments in the buffer.
13662 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
13663 (interactive "P")
13664 (org-remove-latex-fragment-image-overlays)
13665 (save-excursion
13666 (save-restriction
13667 (let (beg end at msg)
13668 (cond
13669 ((or (equal subtree '(16))
13670 (not (save-excursion
13671 (re-search-backward (concat "^" outline-regexp) nil t))))
13672 (setq beg (point-min) end (point-max)
13673 msg "Creating images for buffer...%s"))
13674 ((equal subtree '(4))
13675 (org-back-to-heading)
13676 (setq beg (point) end (org-end-of-subtree t)
13677 msg "Creating images for subtree...%s"))
13679 (if (setq at (org-inside-LaTeX-fragment-p))
13680 (goto-char (max (point-min) (- (cdr at) 2)))
13681 (org-back-to-heading))
13682 (setq beg (point) end (progn (outline-next-heading) (point))
13683 msg (if at "Creating image...%s"
13684 "Creating images for entry...%s"))))
13685 (message msg "")
13686 (narrow-to-region beg end)
13687 (goto-char beg)
13688 (org-format-latex
13689 (concat "ltxpng/" (file-name-sans-extension
13690 (file-name-nondirectory
13691 buffer-file-name)))
13692 default-directory 'overlays msg at 'forbuffer)
13693 (message msg "done. Use `C-c C-c' to remove images.")))))
13695 (defvar org-latex-regexps
13696 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
13697 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
13698 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
13699 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13700 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13701 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
13702 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
13703 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
13704 "Regular expressions for matching embedded LaTeX.")
13706 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
13707 "Replace LaTeX fragments with links to an image, and produce images."
13708 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
13709 (let* ((prefixnodir (file-name-nondirectory prefix))
13710 (absprefix (expand-file-name prefix dir))
13711 (todir (file-name-directory absprefix))
13712 (opt org-format-latex-options)
13713 (matchers (plist-get opt :matchers))
13714 (re-list org-latex-regexps)
13715 (cnt 0) txt link beg end re e checkdir
13716 executables-checked
13717 m n block linkfile movefile ov)
13718 ;; Check if there are old images files with this prefix, and remove them
13719 (when (file-directory-p todir)
13720 (mapc 'delete-file
13721 (directory-files
13722 todir 'full
13723 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
13724 ;; Check the different regular expressions
13725 (while (setq e (pop re-list))
13726 (setq m (car e) re (nth 1 e) n (nth 2 e)
13727 block (if (nth 3 e) "\n\n" ""))
13728 (when (member m matchers)
13729 (goto-char (point-min))
13730 (while (re-search-forward re nil t)
13731 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
13732 (not (get-text-property (match-beginning n)
13733 'org-protected)))
13734 (setq txt (match-string n)
13735 beg (match-beginning n) end (match-end n)
13736 cnt (1+ cnt)
13737 linkfile (format "%s_%04d.png" prefix cnt)
13738 movefile (format "%s_%04d.png" absprefix cnt)
13739 link (concat block "[[file:" linkfile "]]" block))
13740 (if msg (message msg cnt))
13741 (goto-char beg)
13742 (unless checkdir ; make sure the directory exists
13743 (setq checkdir t)
13744 (or (file-directory-p todir) (make-directory todir)))
13746 (unless executables-checked
13747 (org-check-external-command
13748 "latex" "needed to convert LaTeX fragments to images")
13749 (org-check-external-command
13750 "dvipng" "needed to convert LaTeX fragments to images")
13751 (setq executables-checked t))
13753 (org-create-formula-image
13754 txt movefile opt forbuffer)
13755 (if overlays
13756 (progn
13757 (setq ov (org-make-overlay beg end))
13758 (if (featurep 'xemacs)
13759 (progn
13760 (org-overlay-put ov 'invisible t)
13761 (org-overlay-put
13762 ov 'end-glyph
13763 (make-glyph (vector 'png :file movefile))))
13764 (org-overlay-put
13765 ov 'display
13766 (list 'image :type 'png :file movefile :ascent 'center)))
13767 (push ov org-latex-fragment-image-overlays)
13768 (goto-char end))
13769 (delete-region beg end)
13770 (insert link))))))))
13772 ;; This function borrows from Ganesh Swami's latex2png.el
13773 (defun org-create-formula-image (string tofile options buffer)
13774 (let* ((tmpdir (if (featurep 'xemacs)
13775 (temp-directory)
13776 temporary-file-directory))
13777 (texfilebase (make-temp-name
13778 (expand-file-name "orgtex" tmpdir)))
13779 (texfile (concat texfilebase ".tex"))
13780 (dvifile (concat texfilebase ".dvi"))
13781 (pngfile (concat texfilebase ".png"))
13782 (fnh (if (featurep 'xemacs)
13783 (font-height (get-face-font 'default))
13784 (face-attribute 'default :height nil)))
13785 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
13786 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
13787 (fg (or (plist-get options (if buffer :foreground :html-foreground))
13788 "Black"))
13789 (bg (or (plist-get options (if buffer :background :html-background))
13790 "Transparent")))
13791 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
13792 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
13793 (with-temp-file texfile
13794 (insert org-format-latex-header
13795 "\n\\begin{document}\n" string "\n\\end{document}\n"))
13796 (let ((dir default-directory))
13797 (condition-case nil
13798 (progn
13799 (cd tmpdir)
13800 (call-process "latex" nil nil nil texfile))
13801 (error nil))
13802 (cd dir))
13803 (if (not (file-exists-p dvifile))
13804 (progn (message "Failed to create dvi file from %s" texfile) nil)
13805 (condition-case nil
13806 (call-process "dvipng" nil nil nil
13807 "-E" "-fg" fg "-bg" bg
13808 "-D" dpi
13809 ;;"-x" scale "-y" scale
13810 "-T" "tight"
13811 "-o" pngfile
13812 dvifile)
13813 (error nil))
13814 (if (not (file-exists-p pngfile))
13815 (progn (message "Failed to create png file from %s" texfile) nil)
13816 ;; Use the requested file name and clean up
13817 (copy-file pngfile tofile 'replace)
13818 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
13819 (delete-file (concat texfilebase e)))
13820 pngfile))))
13822 (defun org-dvipng-color (attr)
13823 "Return an rgb color specification for dvipng."
13824 (apply 'format "rgb %s %s %s"
13825 (mapcar 'org-normalize-color
13826 (color-values (face-attribute 'default attr nil)))))
13828 (defun org-normalize-color (value)
13829 "Return string to be used as color value for an RGB component."
13830 (format "%g" (/ value 65535.0)))
13832 ;;;; Key bindings
13834 ;; Make `C-c C-x' a prefix key
13835 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
13837 ;; TAB key with modifiers
13838 (org-defkey org-mode-map "\C-i" 'org-cycle)
13839 (org-defkey org-mode-map [(tab)] 'org-cycle)
13840 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
13841 (org-defkey org-mode-map [(meta tab)] 'org-complete)
13842 (org-defkey org-mode-map "\M-\t" 'org-complete)
13843 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
13844 ;; The following line is necessary under Suse GNU/Linux
13845 (unless (featurep 'xemacs)
13846 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
13847 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
13848 (define-key org-mode-map [backtab] 'org-shifttab)
13850 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
13851 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
13852 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
13854 ;; Cursor keys with modifiers
13855 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
13856 (org-defkey org-mode-map [(meta right)] 'org-metaright)
13857 (org-defkey org-mode-map [(meta up)] 'org-metaup)
13858 (org-defkey org-mode-map [(meta down)] 'org-metadown)
13860 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
13861 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
13862 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
13863 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
13865 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
13866 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
13867 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
13868 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
13870 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
13871 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
13873 ;;; Extra keys for tty access.
13874 ;; We only set them when really needed because otherwise the
13875 ;; menus don't show the simple keys
13877 (when (or org-use-extra-keys
13878 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
13879 (not window-system))
13880 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
13881 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
13882 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
13883 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
13884 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
13885 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
13886 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
13887 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
13888 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
13889 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
13890 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
13891 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
13892 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
13893 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
13894 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
13895 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
13896 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
13897 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
13898 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
13899 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
13900 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
13901 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
13903 ;; All the other keys
13905 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
13906 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
13907 (if (boundp 'narrow-map)
13908 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
13909 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
13910 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
13911 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
13912 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
13913 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
13914 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
13915 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
13916 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
13917 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
13918 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
13919 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
13920 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
13921 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
13922 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
13923 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
13924 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
13925 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
13926 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
13927 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
13928 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
13929 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
13930 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
13931 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
13932 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
13933 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
13934 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
13935 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
13936 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
13937 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
13938 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
13939 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
13940 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
13941 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
13942 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
13943 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
13944 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
13945 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
13946 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
13947 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
13948 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
13949 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13950 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
13951 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
13952 (org-defkey org-mode-map "\C-c^" 'org-sort)
13953 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
13954 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
13955 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
13956 (org-defkey org-mode-map "\C-m" 'org-return)
13957 (org-defkey org-mode-map "\C-j" 'org-return-indent)
13958 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
13959 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
13960 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
13961 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
13962 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
13963 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
13964 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
13965 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
13966 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
13967 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
13968 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
13969 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
13970 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
13971 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
13972 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
13973 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
13975 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
13976 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
13977 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
13978 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
13980 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
13981 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
13982 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
13983 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
13984 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
13985 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
13986 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
13987 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
13988 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
13989 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
13990 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
13991 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
13992 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
13994 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
13995 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
13996 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
13997 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
13999 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
14001 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
14003 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
14004 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
14006 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
14009 (when (featurep 'xemacs)
14010 (org-defkey org-mode-map 'button3 'popup-mode-menu))
14013 (defvar org-self-insert-command-undo-counter 0)
14015 (defvar org-table-auto-blank-field) ; defined in org-table.el
14016 (defun org-self-insert-command (N)
14017 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
14018 If the cursor is in a table looking at whitespace, the whitespace is
14019 overwritten, and the table is not marked as requiring realignment."
14020 (interactive "p")
14021 (if (and
14022 (org-table-p)
14023 (progn
14024 ;; check if we blank the field, and if that triggers align
14025 (and (featurep 'org-table) org-table-auto-blank-field
14026 (member last-command
14027 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
14028 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
14029 ;; got extra space, this field does not determine column width
14030 (let (org-table-may-need-update) (org-table-blank-field))
14031 ;; no extra space, this field may determine column width
14032 (org-table-blank-field)))
14034 (eq N 1)
14035 (looking-at "[^|\n]* |"))
14036 (let (org-table-may-need-update)
14037 (goto-char (1- (match-end 0)))
14038 (delete-backward-char 1)
14039 (goto-char (match-beginning 0))
14040 (self-insert-command N))
14041 (setq org-table-may-need-update t)
14042 (self-insert-command N)
14043 (org-fix-tags-on-the-fly)
14044 (if org-self-insert-cluster-for-undo
14045 (if (not (eq last-command 'org-self-insert-command))
14046 (setq org-self-insert-command-undo-counter 1)
14047 (if (>= org-self-insert-command-undo-counter 20)
14048 (setq org-self-insert-command-undo-counter 1)
14049 (and (> org-self-insert-command-undo-counter 0)
14050 buffer-undo-list
14051 (not (cadr buffer-undo-list)) ; remove nil entry
14052 (setcdr buffer-undo-list (cddr buffer-undo-list)))
14053 (setq org-self-insert-command-undo-counter
14054 (1+ org-self-insert-command-undo-counter)))))))
14056 (defun org-fix-tags-on-the-fly ()
14057 (when (and (equal (char-after (point-at-bol)) ?*)
14058 (org-on-heading-p))
14059 (org-align-tags-here org-tags-column)))
14061 (defun org-delete-backward-char (N)
14062 "Like `delete-backward-char', insert whitespace at field end in tables.
14063 When deleting backwards, in tables this function will insert whitespace in
14064 front of the next \"|\" separator, to keep the table aligned. The table will
14065 still be marked for re-alignment if the field did fill the entire column,
14066 because, in this case the deletion might narrow the column."
14067 (interactive "p")
14068 (if (and (org-table-p)
14069 (eq N 1)
14070 (string-match "|" (buffer-substring (point-at-bol) (point)))
14071 (looking-at ".*?|"))
14072 (let ((pos (point))
14073 (noalign (looking-at "[^|\n\r]* |"))
14074 (c org-table-may-need-update))
14075 (backward-delete-char N)
14076 (skip-chars-forward "^|")
14077 (insert " ")
14078 (goto-char (1- pos))
14079 ;; noalign: if there were two spaces at the end, this field
14080 ;; does not determine the width of the column.
14081 (if noalign (setq org-table-may-need-update c)))
14082 (backward-delete-char N)
14083 (org-fix-tags-on-the-fly)))
14085 (defun org-delete-char (N)
14086 "Like `delete-char', but insert whitespace at field end in tables.
14087 When deleting characters, in tables this function will insert whitespace in
14088 front of the next \"|\" separator, to keep the table aligned. The table will
14089 still be marked for re-alignment if the field did fill the entire column,
14090 because, in this case the deletion might narrow the column."
14091 (interactive "p")
14092 (if (and (org-table-p)
14093 (not (bolp))
14094 (not (= (char-after) ?|))
14095 (eq N 1))
14096 (if (looking-at ".*?|")
14097 (let ((pos (point))
14098 (noalign (looking-at "[^|\n\r]* |"))
14099 (c org-table-may-need-update))
14100 (replace-match (concat
14101 (substring (match-string 0) 1 -1)
14102 " |"))
14103 (goto-char pos)
14104 ;; noalign: if there were two spaces at the end, this field
14105 ;; does not determine the width of the column.
14106 (if noalign (setq org-table-may-need-update c)))
14107 (delete-char N))
14108 (delete-char N)
14109 (org-fix-tags-on-the-fly)))
14111 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
14112 (put 'org-self-insert-command 'delete-selection t)
14113 (put 'orgtbl-self-insert-command 'delete-selection t)
14114 (put 'org-delete-char 'delete-selection 'supersede)
14115 (put 'org-delete-backward-char 'delete-selection 'supersede)
14116 (put 'org-yank 'delete-selection 'yank)
14118 ;; Make `flyspell-mode' delay after some commands
14119 (put 'org-self-insert-command 'flyspell-delayed t)
14120 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
14121 (put 'org-delete-char 'flyspell-delayed t)
14122 (put 'org-delete-backward-char 'flyspell-delayed t)
14124 ;; Make pabbrev-mode expand after org-mode commands
14125 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
14126 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
14128 ;; How to do this: Measure non-white length of current string
14129 ;; If equal to column width, we should realign.
14131 (defun org-remap (map &rest commands)
14132 "In MAP, remap the functions given in COMMANDS.
14133 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
14134 (let (new old)
14135 (while commands
14136 (setq old (pop commands) new (pop commands))
14137 (if (fboundp 'command-remapping)
14138 (org-defkey map (vector 'remap old) new)
14139 (substitute-key-definition old new map global-map)))))
14141 (when (eq org-enable-table-editor 'optimized)
14142 ;; If the user wants maximum table support, we need to hijack
14143 ;; some standard editing functions
14144 (org-remap org-mode-map
14145 'self-insert-command 'org-self-insert-command
14146 'delete-char 'org-delete-char
14147 'delete-backward-char 'org-delete-backward-char)
14148 (org-defkey org-mode-map "|" 'org-force-self-insert))
14150 (defvar org-ctrl-c-ctrl-c-hook nil
14151 "Hook for functions attaching themselves to `C-c C-c'.
14152 This can be used to add additional functionality to the C-c C-c key which
14153 executes context-dependent commands.
14154 Each function will be called with no arguments. The function must check
14155 if the context is appropriate for it to act. If yes, it should do its
14156 thing and then return a non-nil value. If the context is wrong,
14157 just do nothing and return nil.")
14159 (defvar org-tab-first-hook nil
14160 "Hook for functions to attach themselves to TAB.
14161 See `org-ctrl-c-ctrl-c-hook' for more information.
14162 This hook runs as the first action when TAB is pressed, even before
14163 `org-cycle' messes around with the `outline-regexp' to cater for
14164 inline tasks and plain list item folding.
14165 If any function in this hook returns t, not other actions like table
14166 field motion visibility cycling will be done.")
14168 (defvar org-tab-after-check-for-table-hook nil
14169 "Hook for functions to attach themselves to TAB.
14170 See `org-ctrl-c-ctrl-c-hook' for more information.
14171 This hook runs after it has been established that the cursor is not in a
14172 table, but before checking if the cursor is in a headline or if global cycling
14173 should be done.
14174 If any function in this hook returns t, not other actions like visibility
14175 cycling will be done.")
14177 (defvar org-tab-after-check-for-cycling-hook nil
14178 "Hook for functions to attach themselves to TAB.
14179 See `org-ctrl-c-ctrl-c-hook' for more information.
14180 This hook runs after it has been established that not table field motion and
14181 not visibility should be done because of current context. This is probably
14182 the place where a package like yasnippets can hook in.")
14184 (defvar org-metaleft-hook nil
14185 "Hook for functions attaching themselves to `M-left'.
14186 See `org-ctrl-c-ctrl-c-hook' for more information.")
14187 (defvar org-metaright-hook nil
14188 "Hook for functions attaching themselves to `M-right'.
14189 See `org-ctrl-c-ctrl-c-hook' for more information.")
14190 (defvar org-metaup-hook nil
14191 "Hook for functions attaching themselves to `M-up'.
14192 See `org-ctrl-c-ctrl-c-hook' for more information.")
14193 (defvar org-metadown-hook nil
14194 "Hook for functions attaching themselves to `M-down'.
14195 See `org-ctrl-c-ctrl-c-hook' for more information.")
14196 (defvar org-shiftmetaleft-hook nil
14197 "Hook for functions attaching themselves to `M-S-left'.
14198 See `org-ctrl-c-ctrl-c-hook' for more information.")
14199 (defvar org-shiftmetaright-hook nil
14200 "Hook for functions attaching themselves to `M-S-right'.
14201 See `org-ctrl-c-ctrl-c-hook' for more information.")
14202 (defvar org-shiftmetaup-hook nil
14203 "Hook for functions attaching themselves to `M-S-up'.
14204 See `org-ctrl-c-ctrl-c-hook' for more information.")
14205 (defvar org-shiftmetadown-hook nil
14206 "Hook for functions attaching themselves to `M-S-down'.
14207 See `org-ctrl-c-ctrl-c-hook' for more information.")
14208 (defvar org-metareturn-hook nil
14209 "Hook for functions attaching themselves to `M-RET'.
14210 See `org-ctrl-c-ctrl-c-hook' for more information.")
14212 (defun org-modifier-cursor-error ()
14213 "Throw an error, a modified cursor command was applied in wrong context."
14214 (error "This command is active in special context like tables, headlines or items"))
14216 (defun org-shiftselect-error ()
14217 "Throw an error because Shift-Cursor command was applied in wrong context."
14218 (if (and (boundp 'shift-select-mode) shift-select-mode)
14219 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
14220 (error "This command works only in special context like headlines or timestamps.")))
14222 (defun org-call-for-shift-select (cmd)
14223 (let ((this-command-keys-shift-translated t))
14224 (call-interactively cmd)))
14226 (defun org-shifttab (&optional arg)
14227 "Global visibility cycling or move to previous table field.
14228 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
14229 on context.
14230 See the individual commands for more information."
14231 (interactive "P")
14232 (cond
14233 ((org-at-table-p) (call-interactively 'org-table-previous-field))
14234 ((integerp arg)
14235 (message "Content view to level: %d" arg)
14236 (org-content (prefix-numeric-value arg))
14237 (setq org-cycle-global-status 'overview))
14238 (t (call-interactively 'org-global-cycle))))
14240 (defun org-shiftmetaleft ()
14241 "Promote subtree or delete table column.
14242 Calls `org-promote-subtree', `org-outdent-item',
14243 or `org-table-delete-column', depending on context.
14244 See the individual commands for more information."
14245 (interactive)
14246 (cond
14247 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
14248 ((org-at-table-p) (call-interactively 'org-table-delete-column))
14249 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
14250 ((org-at-item-p) (call-interactively 'org-outdent-item))
14251 (t (org-modifier-cursor-error))))
14253 (defun org-shiftmetaright ()
14254 "Demote subtree or insert table column.
14255 Calls `org-demote-subtree', `org-indent-item',
14256 or `org-table-insert-column', depending on context.
14257 See the individual commands for more information."
14258 (interactive)
14259 (cond
14260 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
14261 ((org-at-table-p) (call-interactively 'org-table-insert-column))
14262 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
14263 ((org-at-item-p) (call-interactively 'org-indent-item))
14264 (t (org-modifier-cursor-error))))
14266 (defun org-shiftmetaup (&optional arg)
14267 "Move subtree up or kill table row.
14268 Calls `org-move-subtree-up' or `org-table-kill-row' or
14269 `org-move-item-up' depending on context. See the individual commands
14270 for more information."
14271 (interactive "P")
14272 (cond
14273 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
14274 ((org-at-table-p) (call-interactively 'org-table-kill-row))
14275 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14276 ((org-at-item-p) (call-interactively 'org-move-item-up))
14277 (t (org-modifier-cursor-error))))
14279 (defun org-shiftmetadown (&optional arg)
14280 "Move subtree down or insert table row.
14281 Calls `org-move-subtree-down' or `org-table-insert-row' or
14282 `org-move-item-down', depending on context. See the individual
14283 commands for more information."
14284 (interactive "P")
14285 (cond
14286 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
14287 ((org-at-table-p) (call-interactively 'org-table-insert-row))
14288 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14289 ((org-at-item-p) (call-interactively 'org-move-item-down))
14290 (t (org-modifier-cursor-error))))
14292 (defun org-metaleft (&optional arg)
14293 "Promote heading or move table column to left.
14294 Calls `org-do-promote' or `org-table-move-column', depending on context.
14295 With no specific context, calls the Emacs default `backward-word'.
14296 See the individual commands for more information."
14297 (interactive "P")
14298 (cond
14299 ((run-hook-with-args-until-success 'org-metaleft-hook))
14300 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
14301 ((or (org-on-heading-p)
14302 (and (org-region-active-p)
14303 (save-excursion
14304 (goto-char (region-beginning))
14305 (org-on-heading-p))))
14306 (call-interactively 'org-do-promote))
14307 ((or (org-at-item-p)
14308 (and (org-region-active-p)
14309 (save-excursion
14310 (goto-char (region-beginning))
14311 (org-at-item-p))))
14312 (call-interactively 'org-outdent-item))
14313 (t (call-interactively 'backward-word))))
14315 (defun org-metaright (&optional arg)
14316 "Demote subtree or move table column to right.
14317 Calls `org-do-demote' or `org-table-move-column', depending on context.
14318 With no specific context, calls the Emacs default `forward-word'.
14319 See the individual commands for more information."
14320 (interactive "P")
14321 (cond
14322 ((run-hook-with-args-until-success 'org-metaright-hook))
14323 ((org-at-table-p) (call-interactively 'org-table-move-column))
14324 ((or (org-on-heading-p)
14325 (and (org-region-active-p)
14326 (save-excursion
14327 (goto-char (region-beginning))
14328 (org-on-heading-p))))
14329 (call-interactively 'org-do-demote))
14330 ((or (org-at-item-p)
14331 (and (org-region-active-p)
14332 (save-excursion
14333 (goto-char (region-beginning))
14334 (org-at-item-p))))
14335 (call-interactively 'org-indent-item))
14336 (t (call-interactively 'forward-word))))
14338 (defun org-metaup (&optional arg)
14339 "Move subtree up or move table row up.
14340 Calls `org-move-subtree-up' or `org-table-move-row' or
14341 `org-move-item-up', depending on context. See the individual commands
14342 for more information."
14343 (interactive "P")
14344 (cond
14345 ((run-hook-with-args-until-success 'org-metaup-hook))
14346 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
14347 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14348 ((org-at-item-p) (call-interactively 'org-move-item-up))
14349 (t (transpose-lines 1) (beginning-of-line -1))))
14351 (defun org-metadown (&optional arg)
14352 "Move subtree down or move table row down.
14353 Calls `org-move-subtree-down' or `org-table-move-row' or
14354 `org-move-item-down', depending on context. See the individual
14355 commands for more information."
14356 (interactive "P")
14357 (cond
14358 ((run-hook-with-args-until-success 'org-metadown-hook))
14359 ((org-at-table-p) (call-interactively 'org-table-move-row))
14360 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14361 ((org-at-item-p) (call-interactively 'org-move-item-down))
14362 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
14364 (defun org-shiftup (&optional arg)
14365 "Increase item in timestamp or increase priority of current headline.
14366 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
14367 depending on context. See the individual commands for more information."
14368 (interactive "P")
14369 (cond
14370 ((and org-support-shift-select (org-region-active-p))
14371 (org-call-for-shift-select 'previous-line))
14372 ((org-at-timestamp-p t)
14373 (call-interactively (if org-edit-timestamp-down-means-later
14374 'org-timestamp-down 'org-timestamp-up)))
14375 ((and (not (eq org-support-shift-select 'always))
14376 (org-on-heading-p))
14377 (call-interactively 'org-priority-up))
14378 ((and (not org-support-shift-select) (org-at-item-p))
14379 (call-interactively 'org-previous-item))
14380 ((org-clocktable-try-shift 'up arg))
14381 (org-support-shift-select
14382 (org-call-for-shift-select 'previous-line))
14383 (t (org-shiftselect-error))))
14385 (defun org-shiftdown (&optional arg)
14386 "Decrease item in timestamp or decrease priority of current headline.
14387 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
14388 depending on context. See the individual commands for more information."
14389 (interactive "P")
14390 (cond
14391 ((and org-support-shift-select (org-region-active-p))
14392 (org-call-for-shift-select 'next-line))
14393 ((org-at-timestamp-p t)
14394 (call-interactively (if org-edit-timestamp-down-means-later
14395 'org-timestamp-up 'org-timestamp-down)))
14396 ((and (not (eq org-support-shift-select 'always))
14397 (org-on-heading-p))
14398 (call-interactively 'org-priority-down))
14399 ((and (not org-support-shift-select) (org-at-item-p))
14400 (call-interactively 'org-next-item))
14401 ((org-clocktable-try-shift 'down arg))
14402 (org-support-shift-select
14403 (org-call-for-shift-select 'next-line))
14404 (t (org-shiftselect-error))))
14406 (defun org-shiftright (&optional arg)
14407 "Cycle the thing at point or in the current line, depending on context.
14408 Depending on context, this does one of the following:
14410 - switch a timestamp at point one day into the future
14411 - on a headline, switch to the next TODO keyword.
14412 - on an item, switch entire list to the next bullet type
14413 - on a property line, switch to the next allowed value
14414 - on a clocktable definition line, move time block into the future"
14415 (interactive "P")
14416 (cond
14417 ((and org-support-shift-select (org-region-active-p))
14418 (org-call-for-shift-select 'forward-char))
14419 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
14420 ((and (not (eq org-support-shift-select 'always))
14421 (org-on-heading-p))
14422 (org-call-with-arg 'org-todo 'right))
14423 ((or (and org-support-shift-select
14424 (not (eq org-support-shift-select 'always))
14425 (org-at-item-bullet-p))
14426 (and (not org-support-shift-select) (org-at-item-p)))
14427 (org-call-with-arg 'org-cycle-list-bullet nil))
14428 ((and (not (eq org-support-shift-select 'always))
14429 (org-at-property-p))
14430 (call-interactively 'org-property-next-allowed-value))
14431 ((org-clocktable-try-shift 'right arg))
14432 (org-support-shift-select
14433 (org-call-for-shift-select 'forward-char))
14434 (t (org-shiftselect-error))))
14436 (defun org-shiftleft (&optional arg)
14437 "Cycle the thing at point or in the current line, depending on context.
14438 Depending on context, this does one of the following:
14440 - switch a timestamp at point one day into the past
14441 - on a headline, switch to the previous TODO keyword.
14442 - on an item, switch entire list to the previous bullet type
14443 - on a property line, switch to the previous allowed value
14444 - on a clocktable definition line, move time block into the past"
14445 (interactive "P")
14446 (cond
14447 ((and org-support-shift-select (org-region-active-p))
14448 (org-call-for-shift-select 'backward-char))
14449 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
14450 ((and (not (eq org-support-shift-select 'always))
14451 (org-on-heading-p))
14452 (org-call-with-arg 'org-todo 'left))
14453 ((or (and org-support-shift-select
14454 (not (eq org-support-shift-select 'always))
14455 (org-at-item-bullet-p))
14456 (and (not org-support-shift-select) (org-at-item-p)))
14457 (org-call-with-arg 'org-cycle-list-bullet 'previous))
14458 ((and (not (eq org-support-shift-select 'always))
14459 (org-at-property-p))
14460 (call-interactively 'org-property-previous-allowed-value))
14461 ((org-clocktable-try-shift 'left arg))
14462 (org-support-shift-select
14463 (org-call-for-shift-select 'backward-char))
14464 (t (org-shiftselect-error))))
14466 (defun org-shiftcontrolright ()
14467 "Switch to next TODO set."
14468 (interactive)
14469 (cond
14470 ((and org-support-shift-select (org-region-active-p))
14471 (org-call-for-shift-select 'forward-word))
14472 ((and (not (eq org-support-shift-select 'always))
14473 (org-on-heading-p))
14474 (org-call-with-arg 'org-todo 'nextset))
14475 (org-support-shift-select
14476 (org-call-for-shift-select 'forward-word))
14477 (t (org-shiftselect-error))))
14479 (defun org-shiftcontrolleft ()
14480 "Switch to previous TODO set."
14481 (interactive)
14482 (cond
14483 ((and org-support-shift-select (org-region-active-p))
14484 (org-call-for-shift-select 'backward-word))
14485 ((and (not (eq org-support-shift-select 'always))
14486 (org-on-heading-p))
14487 (org-call-with-arg 'org-todo 'previousset))
14488 (org-support-shift-select
14489 (org-call-for-shift-select 'backward-word))
14490 (t (org-shiftselect-error))))
14492 (defun org-ctrl-c-ret ()
14493 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
14494 (interactive)
14495 (cond
14496 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
14497 (t (call-interactively 'org-insert-heading))))
14499 (defun org-copy-special ()
14500 "Copy region in table or copy current subtree.
14501 Calls `org-table-copy' or `org-copy-subtree', depending on context.
14502 See the individual commands for more information."
14503 (interactive)
14504 (call-interactively
14505 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
14507 (defun org-cut-special ()
14508 "Cut region in table or cut current subtree.
14509 Calls `org-table-copy' or `org-cut-subtree', depending on context.
14510 See the individual commands for more information."
14511 (interactive)
14512 (call-interactively
14513 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
14515 (defun org-paste-special (arg)
14516 "Paste rectangular region into table, or past subtree relative to level.
14517 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
14518 See the individual commands for more information."
14519 (interactive "P")
14520 (if (org-at-table-p)
14521 (org-table-paste-rectangle)
14522 (org-paste-subtree arg)))
14524 (defun org-edit-special ()
14525 "Call a special editor for the stuff at point.
14526 When at a table, call the formula editor with `org-table-edit-formulas'.
14527 When at the first line of an src example, call `org-edit-src-code'.
14528 When in an #+include line, visit the include file. Otherwise call
14529 `ffap' to visit the file at point."
14530 (interactive)
14531 (cond
14532 ((org-at-table-p)
14533 (call-interactively 'org-table-edit-formulas))
14534 ((save-excursion
14535 (beginning-of-line 1)
14536 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
14537 (find-file (org-trim (match-string 1))))
14538 ((org-edit-src-code))
14539 ((org-edit-fixed-width-region))
14540 (t (call-interactively 'ffap))))
14543 (defun org-ctrl-c-ctrl-c (&optional arg)
14544 "Set tags in headline, or update according to changed information at point.
14546 This command does many different things, depending on context:
14548 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
14549 this is what we do.
14551 - If the cursor is in a headline, prompt for tags and insert them
14552 into the current line, aligned to `org-tags-column'. When called
14553 with prefix arg, realign all tags in the current buffer.
14555 - If the cursor is in one of the special #+KEYWORD lines, this
14556 triggers scanning the buffer for these lines and updating the
14557 information.
14559 - If the cursor is inside a table, realign the table. This command
14560 works even if the automatic table editor has been turned off.
14562 - If the cursor is on a #+TBLFM line, re-apply the formulas to
14563 the entire table.
14565 - If the cursor is at a footnote reference or definition, jump to
14566 the corresponding definition or references, respectively.
14568 - If the cursor is a the beginning of a dynamic block, update it.
14570 - If the cursor is inside a table created by the table.el package,
14571 activate that table.
14573 - If the current buffer is a remember buffer, close note and file
14574 it. A prefix argument of 1 files to the default location
14575 without further interaction. A prefix argument of 2 files to
14576 the currently clocking task.
14578 - If the cursor is on a <<<target>>>, update radio targets and corresponding
14579 links in this buffer.
14581 - If the cursor is on a numbered item in a plain list, renumber the
14582 ordered list.
14584 - If the cursor is on a checkbox, toggle it."
14585 (interactive "P")
14586 (let ((org-enable-table-editor t))
14587 (cond
14588 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
14589 org-occur-highlights
14590 org-latex-fragment-image-overlays)
14591 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
14592 (org-remove-occur-highlights)
14593 (org-remove-latex-fragment-image-overlays)
14594 (message "Temporary highlights/overlays removed from current buffer"))
14595 ((and (local-variable-p 'org-finish-function (current-buffer))
14596 (fboundp org-finish-function))
14597 (funcall org-finish-function))
14598 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
14599 ((org-at-property-p)
14600 (call-interactively 'org-property-action))
14601 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
14602 ((org-on-heading-p) (call-interactively 'org-set-tags))
14603 ((org-at-table.el-p)
14604 (require 'table)
14605 (beginning-of-line 1)
14606 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
14607 (call-interactively 'table-recognize-table))
14608 ((org-at-table-p)
14609 (org-table-maybe-eval-formula)
14610 (if arg
14611 (call-interactively 'org-table-recalculate)
14612 (org-table-maybe-recalculate-line))
14613 (call-interactively 'org-table-align))
14614 ((or (org-footnote-at-reference-p)
14615 (org-footnote-at-definition-p))
14616 (call-interactively 'org-footnote-action))
14617 ((org-at-item-checkbox-p)
14618 (call-interactively 'org-toggle-checkbox))
14619 ((org-at-item-p)
14620 (if arg
14621 (call-interactively 'org-toggle-checkbox)
14622 (call-interactively 'org-maybe-renumber-ordered-list)))
14623 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
14624 ;; Dynamic block
14625 (beginning-of-line 1)
14626 (save-excursion (org-update-dblock)))
14627 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
14628 (cond
14629 ((equal (match-string 1) "TBLFM")
14630 ;; Recalculate the table before this line
14631 (save-excursion
14632 (beginning-of-line 1)
14633 (skip-chars-backward " \r\n\t")
14634 (if (org-at-table-p)
14635 (org-call-with-arg 'org-table-recalculate t))))
14637 ; (org-set-regexps-and-options)
14638 ; (org-restart-font-lock)
14639 (let ((org-inhibit-startup t)) (org-mode-restart))
14640 (message "Local setup has been refreshed"))))
14641 (t (error "C-c C-c can do nothing useful at this location.")))))
14643 (defun org-mode-restart ()
14644 "Restart Org-mode, to scan again for special lines.
14645 Also updates the keyword regular expressions."
14646 (interactive)
14647 (org-mode)
14648 (message "Org-mode restarted"))
14650 (defun org-kill-note-or-show-branches ()
14651 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
14652 (interactive)
14653 (if (not org-finish-function)
14654 (call-interactively 'show-branches)
14655 (let ((org-note-abort t))
14656 (funcall org-finish-function))))
14658 (defun org-return (&optional indent)
14659 "Goto next table row or insert a newline.
14660 Calls `org-table-next-row' or `newline', depending on context.
14661 See the individual commands for more information."
14662 (interactive)
14663 (cond
14664 ((bobp) (if indent (newline-and-indent) (newline)))
14665 ((org-at-table-p)
14666 (org-table-justify-field-maybe)
14667 (call-interactively 'org-table-next-row))
14668 ((and org-return-follows-link
14669 (eq (get-text-property (point) 'face) 'org-link))
14670 (call-interactively 'org-open-at-point))
14671 ((and (org-at-heading-p)
14672 (looking-at
14673 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
14674 (org-show-entry)
14675 (end-of-line 1)
14676 (newline))
14677 (t (if indent (newline-and-indent) (newline)))))
14679 (defun org-return-indent ()
14680 "Goto next table row or insert a newline and indent.
14681 Calls `org-table-next-row' or `newline-and-indent', depending on
14682 context. See the individual commands for more information."
14683 (interactive)
14684 (org-return t))
14686 (defun org-ctrl-c-star ()
14687 "Compute table, or change heading status of lines.
14688 Calls `org-table-recalculate' or `org-toggle-heading',
14689 depending on context."
14690 (interactive)
14691 (cond
14692 ((org-at-table-p)
14693 (call-interactively 'org-table-recalculate))
14695 ;; Convert all lines in region to list items
14696 (call-interactively 'org-toggle-heading))))
14698 (defun org-ctrl-c-minus ()
14699 "Insert separator line in table or modify bullet status of line.
14700 Also turns a plain line or a region of lines into list items.
14701 Calls `org-table-insert-hline', `org-toggle-item', or
14702 `org-cycle-list-bullet', depending on context."
14703 (interactive)
14704 (cond
14705 ((org-at-table-p)
14706 (call-interactively 'org-table-insert-hline))
14707 ((org-region-active-p)
14708 (call-interactively 'org-toggle-item))
14709 ((org-in-item-p)
14710 (call-interactively 'org-cycle-list-bullet))
14712 (call-interactively 'org-toggle-item))))
14714 (defun org-toggle-item ()
14715 "Convert headings or normal lines to items, items to normal lines.
14716 If there is no active region, only the current line is considered.
14718 If the first line in the region is a headline, convert all headlines to items.
14720 If the first line in the region is an item, convert all items to normal lines.
14722 If the first line is normal text, add an item bullet to each line."
14723 (interactive)
14724 (let (l2 l beg end)
14725 (if (org-region-active-p)
14726 (setq beg (region-beginning) end (region-end))
14727 (setq beg (point-at-bol)
14728 end (min (1+ (point-at-eol)) (point-max))))
14729 (save-excursion
14730 (goto-char end)
14731 (setq l2 (org-current-line))
14732 (goto-char beg)
14733 (beginning-of-line 1)
14734 (setq l (1- (org-current-line)))
14735 (if (org-at-item-p)
14736 ;; We already have items, de-itemize
14737 (while (< (setq l (1+ l)) l2)
14738 (when (org-at-item-p)
14739 (goto-char (match-beginning 2))
14740 (delete-region (match-beginning 2) (match-end 2))
14741 (and (looking-at "[ \t]+") (replace-match "")))
14742 (beginning-of-line 2))
14743 (if (org-on-heading-p)
14744 ;; Headings, convert to items
14745 (while (< (setq l (1+ l)) l2)
14746 (if (looking-at org-outline-regexp)
14747 (replace-match "- " t t))
14748 (beginning-of-line 2))
14749 ;; normal lines, turn them into items
14750 (while (< (setq l (1+ l)) l2)
14751 (unless (org-at-item-p)
14752 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14753 (replace-match "\\1- \\2")))
14754 (beginning-of-line 2)))))))
14756 (defun org-toggle-heading (&optional nstars)
14757 "Convert headings to normal text, or items or text to headings.
14758 If there is no active region, only the current line is considered.
14760 If the first line is a heading, remove the stars from all headlines
14761 in the region.
14763 If the first line is a plain list item, turn all plain list items into
14764 headings.
14766 If the first line is a normal line, turn each and every line in the region
14767 into a heading.
14769 When converting a line into a heading, the number of stars is chosen
14770 such that the lines become children of the current entry. However, when
14771 a prefix argument is given, its value determines the number of stars to add."
14772 (interactive "P")
14773 (let (l2 l itemp beg end)
14774 (if (org-region-active-p)
14775 (setq beg (region-beginning) end (region-end))
14776 (setq beg (point-at-bol)
14777 end (min (1+ (point-at-eol)) (point-max))))
14778 (save-excursion
14779 (goto-char end)
14780 (setq l2 (org-current-line))
14781 (goto-char beg)
14782 (beginning-of-line 1)
14783 (setq l (1- (org-current-line)))
14784 (if (org-on-heading-p)
14785 ;; We already have headlines, de-star them
14786 (while (< (setq l (1+ l)) l2)
14787 (when (org-on-heading-p t)
14788 (and (looking-at outline-regexp) (replace-match "")))
14789 (beginning-of-line 2))
14790 (setq itemp (org-at-item-p))
14791 (let* ((stars
14792 (if nstars
14793 (make-string (prefix-numeric-value current-prefix-arg)
14795 (save-excursion
14796 (re-search-backward org-complex-heading-regexp nil t)
14797 (or (match-string 1) ""))))
14798 (add-stars (cond (nstars "")
14799 ((equal stars "") "*")
14800 (org-odd-levels-only "**")
14801 (t "*")))
14802 (rpl (concat stars add-stars " ")))
14803 (while (< (setq l (1+ l)) l2)
14804 (if itemp
14805 (and (org-at-item-p) (replace-match rpl t t))
14806 (unless (org-on-heading-p)
14807 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14808 (replace-match (concat rpl (match-string 2))))))
14809 (beginning-of-line 2)))))))
14811 (defun org-meta-return (&optional arg)
14812 "Insert a new heading or wrap a region in a table.
14813 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
14814 See the individual commands for more information."
14815 (interactive "P")
14816 (cond
14817 ((run-hook-with-args-until-success 'org-metareturn-hook))
14818 ((org-at-table-p)
14819 (call-interactively 'org-table-wrap-region))
14820 (t (call-interactively 'org-insert-heading))))
14822 ;;; Menu entries
14824 ;; Define the Org-mode menus
14825 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
14826 '("Tbl"
14827 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
14828 ["Next Field" org-cycle (org-at-table-p)]
14829 ["Previous Field" org-shifttab (org-at-table-p)]
14830 ["Next Row" org-return (org-at-table-p)]
14831 "--"
14832 ["Blank Field" org-table-blank-field (org-at-table-p)]
14833 ["Edit Field" org-table-edit-field (org-at-table-p)]
14834 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
14835 "--"
14836 ("Column"
14837 ["Move Column Left" org-metaleft (org-at-table-p)]
14838 ["Move Column Right" org-metaright (org-at-table-p)]
14839 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
14840 ["Insert Column" org-shiftmetaright (org-at-table-p)])
14841 ("Row"
14842 ["Move Row Up" org-metaup (org-at-table-p)]
14843 ["Move Row Down" org-metadown (org-at-table-p)]
14844 ["Delete Row" org-shiftmetaup (org-at-table-p)]
14845 ["Insert Row" org-shiftmetadown (org-at-table-p)]
14846 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
14847 "--"
14848 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
14849 ("Rectangle"
14850 ["Copy Rectangle" org-copy-special (org-at-table-p)]
14851 ["Cut Rectangle" org-cut-special (org-at-table-p)]
14852 ["Paste Rectangle" org-paste-special (org-at-table-p)]
14853 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
14854 "--"
14855 ("Calculate"
14856 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
14857 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
14858 ["Edit Formulas" org-edit-special (org-at-table-p)]
14859 "--"
14860 ["Recalculate line" org-table-recalculate (org-at-table-p)]
14861 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
14862 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
14863 "--"
14864 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
14865 "--"
14866 ["Sum Column/Rectangle" org-table-sum
14867 (or (org-at-table-p) (org-region-active-p))]
14868 ["Which Column?" org-table-current-column (org-at-table-p)])
14869 ["Debug Formulas"
14870 org-table-toggle-formula-debugger
14871 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
14872 ["Show Col/Row Numbers"
14873 org-table-toggle-coordinate-overlays
14874 :style toggle
14875 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
14876 "--"
14877 ["Create" org-table-create (and (not (org-at-table-p))
14878 org-enable-table-editor)]
14879 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
14880 ["Import from File" org-table-import (not (org-at-table-p))]
14881 ["Export to File" org-table-export (org-at-table-p)]
14882 "--"
14883 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
14885 (easy-menu-define org-org-menu org-mode-map "Org menu"
14886 '("Org"
14887 ("Show/Hide"
14888 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
14889 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
14890 ["Sparse Tree..." org-sparse-tree t]
14891 ["Reveal Context" org-reveal t]
14892 ["Show All" show-all t]
14893 "--"
14894 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
14895 "--"
14896 ["New Heading" org-insert-heading t]
14897 ("Navigate Headings"
14898 ["Up" outline-up-heading t]
14899 ["Next" outline-next-visible-heading t]
14900 ["Previous" outline-previous-visible-heading t]
14901 ["Next Same Level" outline-forward-same-level t]
14902 ["Previous Same Level" outline-backward-same-level t]
14903 "--"
14904 ["Jump" org-goto t])
14905 ("Edit Structure"
14906 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
14907 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
14908 "--"
14909 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
14910 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
14911 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
14912 "--"
14913 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
14914 "--"
14915 ["Promote Heading" org-metaleft (not (org-at-table-p))]
14916 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
14917 ["Demote Heading" org-metaright (not (org-at-table-p))]
14918 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
14919 "--"
14920 ["Sort Region/Children" org-sort (not (org-at-table-p))]
14921 "--"
14922 ["Convert to odd levels" org-convert-to-odd-levels t]
14923 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
14924 ("Editing"
14925 ["Emphasis..." org-emphasize t]
14926 ["Edit Source Example" org-edit-special t]
14927 "--"
14928 ["Footnote new/jump" org-footnote-action t]
14929 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
14930 ("Archive"
14931 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
14932 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
14933 ; :active t :keys "C-u C-c C-x C-a"]
14934 ["Sparse trees open ARCHIVE trees"
14935 (setq org-sparse-tree-open-archived-trees
14936 (not org-sparse-tree-open-archived-trees))
14937 :style toggle :selected org-sparse-tree-open-archived-trees]
14938 ["Cycling opens ARCHIVE trees"
14939 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
14940 :style toggle :selected org-cycle-open-archived-trees]
14941 "--"
14942 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
14943 ["Move Subtree to Archive" org-advertized-archive-subtree t]
14944 ; ["Check and Move Children" (org-archive-subtree '(4))
14945 ; :active t :keys "C-u C-c C-x C-s"]
14947 "--"
14948 ("Hyperlinks"
14949 ["Store Link (Global)" org-store-link t]
14950 ["Insert Link" org-insert-link t]
14951 ["Follow Link" org-open-at-point t]
14952 "--"
14953 ["Next link" org-next-link t]
14954 ["Previous link" org-previous-link t]
14955 "--"
14956 ["Descriptive Links"
14957 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
14958 :style radio
14959 :selected (member '(org-link) buffer-invisibility-spec)]
14960 ["Literal Links"
14961 (progn
14962 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
14963 :style radio
14964 :selected (not (member '(org-link) buffer-invisibility-spec))])
14965 "--"
14966 ("TODO Lists"
14967 ["TODO/DONE/-" org-todo t]
14968 ("Select keyword"
14969 ["Next keyword" org-shiftright (org-on-heading-p)]
14970 ["Previous keyword" org-shiftleft (org-on-heading-p)]
14971 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
14972 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
14973 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
14974 ["Show TODO Tree" org-show-todo-tree t]
14975 ["Global TODO list" org-todo-list t]
14976 "--"
14977 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
14978 :selected org-enforce-todo-dependencies :style toggle :active t]
14979 "Settings for tree at point"
14980 ["Do Children sequentially" org-toggle-ordered-property :style radio
14981 :selected (ignore-errors (org-entry-get nil "ORDERED"))
14982 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14983 ["Do Children parallel" org-toggle-ordered-property :style radio
14984 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
14985 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14986 "--"
14987 ["Set Priority" org-priority t]
14988 ["Priority Up" org-shiftup t]
14989 ["Priority Down" org-shiftdown t]
14990 "--"
14991 ["Get news from all feeds" org-feed-update-all t]
14992 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
14993 ["Customize feeds" (customize-variable 'org-feed-alist) t])
14994 ("TAGS and Properties"
14995 ["Set Tags" org-set-tags-command t]
14996 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
14997 "--"
14998 ["Set property" org-set-property t]
14999 ["Column view of properties" org-columns t]
15000 ["Insert Column View DBlock" org-insert-columns-dblock t])
15001 ("Dates and Scheduling"
15002 ["Timestamp" org-time-stamp t]
15003 ["Timestamp (inactive)" org-time-stamp-inactive t]
15004 ("Change Date"
15005 ["1 Day Later" org-shiftright t]
15006 ["1 Day Earlier" org-shiftleft t]
15007 ["1 ... Later" org-shiftup t]
15008 ["1 ... Earlier" org-shiftdown t])
15009 ["Compute Time Range" org-evaluate-time-range t]
15010 ["Schedule Item" org-schedule t]
15011 ["Deadline" org-deadline t]
15012 "--"
15013 ["Custom time format" org-toggle-time-stamp-overlays
15014 :style radio :selected org-display-custom-times]
15015 "--"
15016 ["Goto Calendar" org-goto-calendar t]
15017 ["Date from Calendar" org-date-from-calendar t]
15018 "--"
15019 ["Start/Restart Timer" org-timer-start t]
15020 ["Pause/Continue Timer" org-timer-pause-or-continue t]
15021 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
15022 ["Insert Timer String" org-timer t]
15023 ["Insert Timer Item" org-timer-item t])
15024 ("Logging work"
15025 ["Clock in" org-clock-in t]
15026 ["Clock out" org-clock-out t]
15027 ["Clock cancel" org-clock-cancel t]
15028 ["Goto running clock" org-clock-goto t]
15029 ["Display times" org-clock-display t]
15030 ["Create clock table" org-clock-report t]
15031 "--"
15032 ["Record DONE time"
15033 (progn (setq org-log-done (not org-log-done))
15034 (message "Switching to %s will %s record a timestamp"
15035 (car org-done-keywords)
15036 (if org-log-done "automatically" "not")))
15037 :style toggle :selected org-log-done])
15038 "--"
15039 ["Agenda Command..." org-agenda t]
15040 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
15041 ("File List for Agenda")
15042 ("Special views current file"
15043 ["TODO Tree" org-show-todo-tree t]
15044 ["Check Deadlines" org-check-deadlines t]
15045 ["Timeline" org-timeline t]
15046 ["Tags/Property tree" org-match-sparse-tree t])
15047 "--"
15048 ["Export/Publish..." org-export t]
15049 ("LaTeX"
15050 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
15051 :selected org-cdlatex-mode]
15052 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
15053 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
15054 ["Modify math symbol" org-cdlatex-math-modify
15055 (org-inside-LaTeX-fragment-p)]
15056 ["Insert citation" org-reftex-citation t]
15057 "--"
15058 ["Export LaTeX fragments as images"
15059 (if (featurep 'org-exp)
15060 (setq org-export-with-LaTeX-fragments
15061 (not org-export-with-LaTeX-fragments))
15062 (require 'org-exp))
15063 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
15064 org-export-with-LaTeX-fragments)])
15065 "--"
15066 ("Documentation"
15067 ["Show Version" org-version t]
15068 ["Info Documentation" org-info t])
15069 ("Customize"
15070 ["Browse Org Group" org-customize t]
15071 "--"
15072 ["Expand This Menu" org-create-customize-menu
15073 (fboundp 'customize-menu-create)])
15074 "--"
15075 ("Refresh/Reload"
15076 ["Refresh setup current buffer" org-mode-restart t]
15077 ["Reload Org (after update)" org-reload t]
15078 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
15081 (defun org-info (&optional node)
15082 "Read documentation for Org-mode in the info system.
15083 With optional NODE, go directly to that node."
15084 (interactive)
15085 (info (format "(org)%s" (or node ""))))
15087 (defun org-install-agenda-files-menu ()
15088 (let ((bl (buffer-list)))
15089 (save-excursion
15090 (while bl
15091 (set-buffer (pop bl))
15092 (if (org-mode-p) (setq bl nil)))
15093 (when (org-mode-p)
15094 (easy-menu-change
15095 '("Org") "File List for Agenda"
15096 (append
15097 (list
15098 ["Edit File List" (org-edit-agenda-file-list) t]
15099 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
15100 ["Remove Current File from List" org-remove-file t]
15101 ["Cycle through agenda files" org-cycle-agenda-files t]
15102 ["Occur in all agenda files" org-occur-in-agenda-files t]
15103 "--")
15104 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
15106 ;;;; Documentation
15108 ;;;###autoload
15109 (defun org-require-autoloaded-modules ()
15110 (interactive)
15111 (mapc 'require
15112 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
15113 org-docbook org-exp org-html org-icalendar
15114 org-id org-latex
15115 org-publish org-remember org-table
15116 org-timer org-xoxo)))
15118 ;;;###autoload
15119 (defun org-reload (&optional uncompiled)
15120 "Reload all org lisp files.
15121 With prefix arg UNCOMPILED, load the uncompiled versions."
15122 (interactive "P")
15123 (require 'find-func)
15124 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
15125 (dir-org (file-name-directory (org-find-library-name "org")))
15126 (dir-org-contrib (ignore-errors
15127 (file-name-directory
15128 (org-find-library-name "org-contribdir"))))
15129 (files
15130 (append (directory-files dir-org t file-re)
15131 (and dir-org-contrib
15132 (directory-files dir-org-contrib t file-re))))
15133 (remove-re (concat (if (featurep 'xemacs)
15134 "org-colview" "org-colview-xemacs")
15135 "\\'")))
15136 (setq files (mapcar 'file-name-sans-extension files))
15137 (setq files (mapcar
15138 (lambda (x) (if (string-match remove-re x) nil x))
15139 files))
15140 (setq files (delq nil files))
15141 (mapc
15142 (lambda (f)
15143 (when (featurep (intern (file-name-nondirectory f)))
15144 (if (and (not uncompiled)
15145 (file-exists-p (concat f ".elc")))
15146 (load (concat f ".elc") nil nil t)
15147 (load (concat f ".el") nil nil t))))
15148 files))
15149 (org-version))
15151 ;;;###autoload
15152 (defun org-customize ()
15153 "Call the customize function with org as argument."
15154 (interactive)
15155 (org-load-modules-maybe)
15156 (org-require-autoloaded-modules)
15157 (customize-browse 'org))
15159 (defun org-create-customize-menu ()
15160 "Create a full customization menu for Org-mode, insert it into the menu."
15161 (interactive)
15162 (org-load-modules-maybe)
15163 (org-require-autoloaded-modules)
15164 (if (fboundp 'customize-menu-create)
15165 (progn
15166 (easy-menu-change
15167 '("Org") "Customize"
15168 `(["Browse Org group" org-customize t]
15169 "--"
15170 ,(customize-menu-create 'org)
15171 ["Set" Custom-set t]
15172 ["Save" Custom-save t]
15173 ["Reset to Current" Custom-reset-current t]
15174 ["Reset to Saved" Custom-reset-saved t]
15175 ["Reset to Standard Settings" Custom-reset-standard t]))
15176 (message "\"Org\"-menu now contains full customization menu"))
15177 (error "Cannot expand menu (outdated version of cus-edit.el)")))
15179 ;;;; Miscellaneous stuff
15181 ;;; Generally useful functions
15183 (defun org-find-text-property-in-string (prop s)
15184 "Return the first non-nil value of property PROP in string S."
15185 (or (get-text-property 0 prop s)
15186 (get-text-property (or (next-single-property-change 0 prop s) 0)
15187 prop s)))
15189 (defun org-display-warning (message) ;; Copied from Emacs-Muse
15190 "Display the given MESSAGE as a warning."
15191 (if (fboundp 'display-warning)
15192 (display-warning 'org message
15193 (if (featurep 'xemacs)
15194 'warning
15195 :warning))
15196 (let ((buf (get-buffer-create "*Org warnings*")))
15197 (with-current-buffer buf
15198 (goto-char (point-max))
15199 (insert "Warning (Org): " message)
15200 (unless (bolp)
15201 (newline)))
15202 (display-buffer buf)
15203 (sit-for 0))))
15205 (defun org-goto-marker-or-bmk (marker &optional bookmark)
15206 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
15207 (if (and marker (marker-buffer marker)
15208 (buffer-live-p (marker-buffer marker)))
15209 (progn
15210 (switch-to-buffer (marker-buffer marker))
15211 (if (or (> marker (point-max)) (< marker (point-min)))
15212 (widen))
15213 (goto-char marker)
15214 (org-show-context 'org-goto))
15215 (if bookmark
15216 (bookmark-jump bookmark)
15217 (error "Cannot find location"))))
15219 (defun org-quote-csv-field (s)
15220 "Quote field for inclusion in CSV material."
15221 (if (string-match "[\",]" s)
15222 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
15225 (defun org-plist-delete (plist property)
15226 "Delete PROPERTY from PLIST.
15227 This is in contrast to merely setting it to 0."
15228 (let (p)
15229 (while plist
15230 (if (not (eq property (car plist)))
15231 (setq p (plist-put p (car plist) (nth 1 plist))))
15232 (setq plist (cddr plist)))
15235 (defun org-force-self-insert (N)
15236 "Needed to enforce self-insert under remapping."
15237 (interactive "p")
15238 (self-insert-command N))
15240 (defun org-string-width (s)
15241 "Compute width of string, ignoring invisible characters.
15242 This ignores character with invisibility property `org-link', and also
15243 characters with property `org-cwidth', because these will become invisible
15244 upon the next fontification round."
15245 (let (b l)
15246 (when (or (eq t buffer-invisibility-spec)
15247 (assq 'org-link buffer-invisibility-spec))
15248 (while (setq b (text-property-any 0 (length s)
15249 'invisible 'org-link s))
15250 (setq s (concat (substring s 0 b)
15251 (substring s (or (next-single-property-change
15252 b 'invisible s) (length s)))))))
15253 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
15254 (setq s (concat (substring s 0 b)
15255 (substring s (or (next-single-property-change
15256 b 'org-cwidth s) (length s))))))
15257 (setq l (string-width s) b -1)
15258 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
15259 (setq l (- l (get-text-property b 'org-dwidth-n s))))
15262 (defun org-get-indentation (&optional line)
15263 "Get the indentation of the current line, interpreting tabs.
15264 When LINE is given, assume it represents a line and compute its indentation."
15265 (if line
15266 (if (string-match "^ *" (org-remove-tabs line))
15267 (match-end 0))
15268 (save-excursion
15269 (beginning-of-line 1)
15270 (skip-chars-forward " \t")
15271 (current-column))))
15273 (defun org-remove-tabs (s &optional width)
15274 "Replace tabulators in S with spaces.
15275 Assumes that s is a single line, starting in column 0."
15276 (setq width (or width tab-width))
15277 (while (string-match "\t" s)
15278 (setq s (replace-match
15279 (make-string
15280 (- (* width (/ (+ (match-beginning 0) width) width))
15281 (match-beginning 0)) ?\ )
15282 t t s)))
15285 (defun org-fix-indentation (line ind)
15286 "Fix indentation in LINE.
15287 IND is a cons cell with target and minimum indentation.
15288 If the current indentation in LINE is smaller than the minimum,
15289 leave it alone. If it is larger than ind, set it to the target."
15290 (let* ((l (org-remove-tabs line))
15291 (i (org-get-indentation l))
15292 (i1 (car ind)) (i2 (cdr ind)))
15293 (if (>= i i2) (setq l (substring line i2)))
15294 (if (> i1 0)
15295 (concat (make-string i1 ?\ ) l)
15296 l)))
15298 (defun org-base-buffer (buffer)
15299 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
15300 (if (not buffer)
15301 buffer
15302 (or (buffer-base-buffer buffer)
15303 buffer)))
15305 (defun org-trim (s)
15306 "Remove whitespace at beginning and end of string."
15307 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
15308 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
15311 (defun org-wrap (string &optional width lines)
15312 "Wrap string to either a number of lines, or a width in characters.
15313 If WIDTH is non-nil, the string is wrapped to that width, however many lines
15314 that costs. If there is a word longer than WIDTH, the text is actually
15315 wrapped to the length of that word.
15316 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
15317 many lines, whatever width that takes.
15318 The return value is a list of lines, without newlines at the end."
15319 (let* ((words (org-split-string string "[ \t\n]+"))
15320 (maxword (apply 'max (mapcar 'org-string-width words)))
15321 w ll)
15322 (cond (width
15323 (org-do-wrap words (max maxword width)))
15324 (lines
15325 (setq w maxword)
15326 (setq ll (org-do-wrap words maxword))
15327 (if (<= (length ll) lines)
15329 (setq ll words)
15330 (while (> (length ll) lines)
15331 (setq w (1+ w))
15332 (setq ll (org-do-wrap words w)))
15333 ll))
15334 (t (error "Cannot wrap this")))))
15336 (defun org-do-wrap (words width)
15337 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
15338 (let (lines line)
15339 (while words
15340 (setq line (pop words))
15341 (while (and words (< (+ (length line) (length (car words))) width))
15342 (setq line (concat line " " (pop words))))
15343 (setq lines (push line lines)))
15344 (nreverse lines)))
15346 (defun org-split-string (string &optional separators)
15347 "Splits STRING into substrings at SEPARATORS.
15348 No empty strings are returned if there are matches at the beginning
15349 and end of string."
15350 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
15351 (start 0)
15352 notfirst
15353 (list nil))
15354 (while (and (string-match rexp string
15355 (if (and notfirst
15356 (= start (match-beginning 0))
15357 (< start (length string)))
15358 (1+ start) start))
15359 (< (match-beginning 0) (length string)))
15360 (setq notfirst t)
15361 (or (eq (match-beginning 0) 0)
15362 (and (eq (match-beginning 0) (match-end 0))
15363 (eq (match-beginning 0) start))
15364 (setq list
15365 (cons (substring string start (match-beginning 0))
15366 list)))
15367 (setq start (match-end 0)))
15368 (or (eq start (length string))
15369 (setq list
15370 (cons (substring string start)
15371 list)))
15372 (nreverse list)))
15374 (defun org-uuidgen-p (s)
15375 "Is S an ID created by UUIDGEN?"
15376 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
15378 (defun org-context ()
15379 "Return a list of contexts of the current cursor position.
15380 If several contexts apply, all are returned.
15381 Each context entry is a list with a symbol naming the context, and
15382 two positions indicating start and end of the context. Possible
15383 contexts are:
15385 :headline anywhere in a headline
15386 :headline-stars on the leading stars in a headline
15387 :todo-keyword on a TODO keyword (including DONE) in a headline
15388 :tags on the TAGS in a headline
15389 :priority on the priority cookie in a headline
15390 :item on the first line of a plain list item
15391 :item-bullet on the bullet/number of a plain list item
15392 :checkbox on the checkbox in a plain list item
15393 :table in an org-mode table
15394 :table-special on a special filed in a table
15395 :table-table in a table.el table
15396 :link on a hyperlink
15397 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
15398 :target on a <<target>>
15399 :radio-target on a <<<radio-target>>>
15400 :latex-fragment on a LaTeX fragment
15401 :latex-preview on a LaTeX fragment with overlayed preview image
15403 This function expects the position to be visible because it uses font-lock
15404 faces as a help to recognize the following contexts: :table-special, :link,
15405 and :keyword."
15406 (let* ((f (get-text-property (point) 'face))
15407 (faces (if (listp f) f (list f)))
15408 (p (point)) clist o)
15409 ;; First the large context
15410 (cond
15411 ((org-on-heading-p t)
15412 (push (list :headline (point-at-bol) (point-at-eol)) clist)
15413 (when (progn
15414 (beginning-of-line 1)
15415 (looking-at org-todo-line-tags-regexp))
15416 (push (org-point-in-group p 1 :headline-stars) clist)
15417 (push (org-point-in-group p 2 :todo-keyword) clist)
15418 (push (org-point-in-group p 4 :tags) clist))
15419 (goto-char p)
15420 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
15421 (if (looking-at "\\[#[A-Z0-9]\\]")
15422 (push (org-point-in-group p 0 :priority) clist)))
15424 ((org-at-item-p)
15425 (push (org-point-in-group p 2 :item-bullet) clist)
15426 (push (list :item (point-at-bol)
15427 (save-excursion (org-end-of-item) (point)))
15428 clist)
15429 (and (org-at-item-checkbox-p)
15430 (push (org-point-in-group p 0 :checkbox) clist)))
15432 ((org-at-table-p)
15433 (push (list :table (org-table-begin) (org-table-end)) clist)
15434 (if (memq 'org-formula faces)
15435 (push (list :table-special
15436 (previous-single-property-change p 'face)
15437 (next-single-property-change p 'face)) clist)))
15438 ((org-at-table-p 'any)
15439 (push (list :table-table) clist)))
15440 (goto-char p)
15442 ;; Now the small context
15443 (cond
15444 ((org-at-timestamp-p)
15445 (push (org-point-in-group p 0 :timestamp) clist))
15446 ((memq 'org-link faces)
15447 (push (list :link
15448 (previous-single-property-change p 'face)
15449 (next-single-property-change p 'face)) clist))
15450 ((memq 'org-special-keyword faces)
15451 (push (list :keyword
15452 (previous-single-property-change p 'face)
15453 (next-single-property-change p 'face)) clist))
15454 ((org-on-target-p)
15455 (push (org-point-in-group p 0 :target) clist)
15456 (goto-char (1- (match-beginning 0)))
15457 (if (looking-at org-radio-target-regexp)
15458 (push (org-point-in-group p 0 :radio-target) clist))
15459 (goto-char p))
15460 ((setq o (car (delq nil
15461 (mapcar
15462 (lambda (x)
15463 (if (memq x org-latex-fragment-image-overlays) x))
15464 (org-overlays-at (point))))))
15465 (push (list :latex-fragment
15466 (org-overlay-start o) (org-overlay-end o)) clist)
15467 (push (list :latex-preview
15468 (org-overlay-start o) (org-overlay-end o)) clist))
15469 ((org-inside-LaTeX-fragment-p)
15470 ;; FIXME: positions wrong.
15471 (push (list :latex-fragment (point) (point)) clist)))
15473 (setq clist (nreverse (delq nil clist)))
15474 clist))
15476 ;; FIXME: Compare with at-regexp-p Do we need both?
15477 (defun org-in-regexp (re &optional nlines visually)
15478 "Check if point is inside a match of regexp.
15479 Normally only the current line is checked, but you can include NLINES extra
15480 lines both before and after point into the search.
15481 If VISUALLY is set, require that the cursor is not after the match but
15482 really on, so that the block visually is on the match."
15483 (catch 'exit
15484 (let ((pos (point))
15485 (eol (point-at-eol (+ 1 (or nlines 0))))
15486 (inc (if visually 1 0)))
15487 (save-excursion
15488 (beginning-of-line (- 1 (or nlines 0)))
15489 (while (re-search-forward re eol t)
15490 (if (and (<= (match-beginning 0) pos)
15491 (>= (+ inc (match-end 0)) pos))
15492 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
15494 (defun org-at-regexp-p (regexp)
15495 "Is point inside a match of REGEXP in the current line?"
15496 (catch 'exit
15497 (save-excursion
15498 (let ((pos (point)) (end (point-at-eol)))
15499 (beginning-of-line 1)
15500 (while (re-search-forward regexp end t)
15501 (if (and (<= (match-beginning 0) pos)
15502 (>= (match-end 0) pos))
15503 (throw 'exit t)))
15504 nil))))
15506 (defun org-occur-in-agenda-files (regexp &optional nlines)
15507 "Call `multi-occur' with buffers for all agenda files."
15508 (interactive "sOrg-files matching: \np")
15509 (let* ((files (org-agenda-files))
15510 (tnames (mapcar 'file-truename files))
15511 (extra org-agenda-text-search-extra-files)
15513 (when (eq (car extra) 'agenda-archives)
15514 (setq extra (cdr extra))
15515 (setq files (org-add-archive-files files)))
15516 (while (setq f (pop extra))
15517 (unless (member (file-truename f) tnames)
15518 (add-to-list 'files f 'append)
15519 (add-to-list 'tnames (file-truename f) 'append)))
15520 (multi-occur
15521 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
15522 regexp)))
15524 (if (boundp 'occur-mode-find-occurrence-hook)
15525 ;; Emacs 23
15526 (add-hook 'occur-mode-find-occurrence-hook
15527 (lambda ()
15528 (when (org-mode-p)
15529 (org-reveal))))
15530 ;; Emacs 22
15531 (defadvice occur-mode-goto-occurrence
15532 (after org-occur-reveal activate)
15533 (and (org-mode-p) (org-reveal)))
15534 (defadvice occur-mode-goto-occurrence-other-window
15535 (after org-occur-reveal activate)
15536 (and (org-mode-p) (org-reveal)))
15537 (defadvice occur-mode-display-occurrence
15538 (after org-occur-reveal activate)
15539 (when (org-mode-p)
15540 (let ((pos (occur-mode-find-occurrence)))
15541 (with-current-buffer (marker-buffer pos)
15542 (save-excursion
15543 (goto-char pos)
15544 (org-reveal)))))))
15546 (defun org-uniquify (list)
15547 "Remove duplicate elements from LIST."
15548 (let (res)
15549 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
15550 res))
15552 (defun org-delete-all (elts list)
15553 "Remove all elements in ELTS from LIST."
15554 (while elts
15555 (setq list (delete (pop elts) list)))
15556 list)
15558 (defun org-back-over-empty-lines ()
15559 "Move backwards over whitespace, to the beginning of the first empty line.
15560 Returns the number of empty lines passed."
15561 (let ((pos (point)))
15562 (skip-chars-backward " \t\n\r")
15563 (beginning-of-line 2)
15564 (goto-char (min (point) pos))
15565 (count-lines (point) pos)))
15567 (defun org-skip-whitespace ()
15568 (skip-chars-forward " \t\n\r"))
15570 (defun org-point-in-group (point group &optional context)
15571 "Check if POINT is in match-group GROUP.
15572 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
15573 match. If the match group does ot exist or point is not inside it,
15574 return nil."
15575 (and (match-beginning group)
15576 (>= point (match-beginning group))
15577 (<= point (match-end group))
15578 (if context
15579 (list context (match-beginning group) (match-end group))
15580 t)))
15582 (defun org-switch-to-buffer-other-window (&rest args)
15583 "Switch to buffer in a second window on the current frame.
15584 In particular, do not allow pop-up frames."
15585 (let (pop-up-frames special-display-buffer-names special-display-regexps
15586 special-display-function)
15587 (apply 'switch-to-buffer-other-window args)))
15589 (defun org-combine-plists (&rest plists)
15590 "Create a single property list from all plists in PLISTS.
15591 The process starts by copying the first list, and then setting properties
15592 from the other lists. Settings in the last list are the most significant
15593 ones and overrule settings in the other lists."
15594 (let ((rtn (copy-sequence (pop plists)))
15595 p v ls)
15596 (while plists
15597 (setq ls (pop plists))
15598 (while ls
15599 (setq p (pop ls) v (pop ls))
15600 (setq rtn (plist-put rtn p v))))
15601 rtn))
15603 (defun org-move-line-down (arg)
15604 "Move the current line down. With prefix argument, move it past ARG lines."
15605 (interactive "p")
15606 (let ((col (current-column))
15607 beg end pos)
15608 (beginning-of-line 1) (setq beg (point))
15609 (beginning-of-line 2) (setq end (point))
15610 (beginning-of-line (+ 1 arg))
15611 (setq pos (move-marker (make-marker) (point)))
15612 (insert (delete-and-extract-region beg end))
15613 (goto-char pos)
15614 (org-move-to-column col)))
15616 (defun org-move-line-up (arg)
15617 "Move the current line up. With prefix argument, move it past ARG lines."
15618 (interactive "p")
15619 (let ((col (current-column))
15620 beg end pos)
15621 (beginning-of-line 1) (setq beg (point))
15622 (beginning-of-line 2) (setq end (point))
15623 (beginning-of-line (- arg))
15624 (setq pos (move-marker (make-marker) (point)))
15625 (insert (delete-and-extract-region beg end))
15626 (goto-char pos)
15627 (org-move-to-column col)))
15629 (defun org-replace-escapes (string table)
15630 "Replace %-escapes in STRING with values in TABLE.
15631 TABLE is an association list with keys like \"%a\" and string values.
15632 The sequences in STRING may contain normal field width and padding information,
15633 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
15634 so values can contain further %-escapes if they are define later in TABLE."
15635 (let ((case-fold-search nil)
15636 e re rpl)
15637 (while (setq e (pop table))
15638 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
15639 (while (string-match re string)
15640 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
15641 (cdr e)))
15642 (setq string (replace-match rpl t t string))))
15643 string))
15646 (defun org-sublist (list start end)
15647 "Return a section of LIST, from START to END.
15648 Counting starts at 1."
15649 (let (rtn (c start))
15650 (setq list (nthcdr (1- start) list))
15651 (while (and list (<= c end))
15652 (push (pop list) rtn)
15653 (setq c (1+ c)))
15654 (nreverse rtn)))
15656 (defun org-find-base-buffer-visiting (file)
15657 "Like `find-buffer-visiting' but always return the base buffer and
15658 not an indirect buffer."
15659 (let ((buf (or (get-file-buffer file)
15660 (find-buffer-visiting file))))
15661 (if buf
15662 (or (buffer-base-buffer buf) buf)
15663 nil)))
15665 (defun org-image-file-name-regexp (&optional extensions)
15666 "Return regexp matching the file names of images.
15667 If EXTENSIONS is given, only match these."
15668 (if (and (not extensions) (fboundp 'image-file-name-regexp))
15669 (image-file-name-regexp)
15670 (let ((image-file-name-extensions
15671 (or extensions
15672 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
15673 "xbm" "xpm" "pbm" "pgm" "ppm"))))
15674 (concat "\\."
15675 (regexp-opt (nconc (mapcar 'upcase
15676 image-file-name-extensions)
15677 image-file-name-extensions)
15679 "\\'"))))
15681 (defun org-file-image-p (file &optional extensions)
15682 "Return non-nil if FILE is an image."
15683 (save-match-data
15684 (string-match (org-image-file-name-regexp extensions) file)))
15686 (defun org-get-cursor-date ()
15687 "Return the date at cursor in as a time.
15688 This works in the calendar and in the agenda, anywhere else it just
15689 returns the current time."
15690 (let (date day defd)
15691 (cond
15692 ((eq major-mode 'calendar-mode)
15693 (setq date (calendar-cursor-to-date)
15694 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15695 ((eq major-mode 'org-agenda-mode)
15696 (setq day (get-text-property (point) 'day))
15697 (if day
15698 (setq date (calendar-gregorian-from-absolute day)
15699 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
15700 (nth 2 date))))))
15701 (or defd (current-time))))
15703 (defvar org-agenda-action-marker (make-marker)
15704 "Marker pointing to the entry for the next agenda action.")
15706 (defun org-mark-entry-for-agenda-action ()
15707 "Mark the current entry as target of an agenda action.
15708 Agenda actions are actions executed from the agenda with the key `k',
15709 which make use of the date at the cursor."
15710 (interactive)
15711 (move-marker org-agenda-action-marker
15712 (save-excursion (org-back-to-heading t) (point))
15713 (current-buffer))
15714 (message
15715 "Entry marked for action; press `k' at desired date in agenda or calendar"))
15717 ;;; Paragraph filling stuff.
15718 ;; We want this to be just right, so use the full arsenal.
15720 (defun org-indent-line-function ()
15721 "Indent line like previous, but further if previous was headline or item."
15722 (interactive)
15723 (let* ((pos (point))
15724 (itemp (org-at-item-p))
15725 (org-drawer-regexp (or org-drawer-regexp "\000"))
15726 column bpos bcol tpos tcol bullet btype bullet-type)
15727 ;; Find the previous relevant line
15728 (beginning-of-line 1)
15729 (cond
15730 ((looking-at "#") (setq column 0))
15731 ((looking-at "\\*+ ") (setq column 0))
15732 ((and (looking-at "[ \t]*:END:")
15733 (save-excursion (re-search-backward org-drawer-regexp nil t)))
15734 (save-excursion
15735 (goto-char (1- (match-beginning 1)))
15736 (setq column (current-column))))
15738 (beginning-of-line 0)
15739 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
15740 (not (looking-at "[ \t]*:END:"))
15741 (not (looking-at org-drawer-regexp)))
15742 (beginning-of-line 0))
15743 (cond
15744 ((looking-at "\\*+[ \t]+")
15745 (if (not org-adapt-indentation)
15746 (setq column 0)
15747 (goto-char (match-end 0))
15748 (setq column (current-column))))
15749 ((looking-at org-drawer-regexp)
15750 (goto-char (1- (match-beginning 1)))
15751 (setq column (current-column)))
15752 ((looking-at "\\([ \t]*\\):END:")
15753 (goto-char (match-end 1))
15754 (setq column (current-column)))
15755 ((org-in-item-p)
15756 (org-beginning-of-item)
15757 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
15758 (setq bpos (match-beginning 1) tpos (match-end 0)
15759 bcol (progn (goto-char bpos) (current-column))
15760 tcol (progn (goto-char tpos) (current-column))
15761 bullet (match-string 1)
15762 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
15763 (if (> tcol (+ bcol org-description-max-indent))
15764 (setq tcol (+ bcol 5)))
15765 (if (not itemp)
15766 (setq column tcol)
15767 (goto-char pos)
15768 (beginning-of-line 1)
15769 (if (looking-at "\\S-")
15770 (progn
15771 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
15772 (setq bullet (match-string 1)
15773 btype (if (string-match "[0-9]" bullet) "n" bullet))
15774 (setq column (if (equal btype bullet-type) bcol tcol)))
15775 (setq column (org-get-indentation)))))
15776 (t (setq column (org-get-indentation))))))
15777 (goto-char pos)
15778 (if (<= (current-column) (current-indentation))
15779 (org-indent-line-to column)
15780 (save-excursion (org-indent-line-to column)))
15781 (setq column (current-column))
15782 (beginning-of-line 1)
15783 (if (looking-at
15784 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
15785 (replace-match (concat "\\1" (format org-property-format
15786 (match-string 2) (match-string 3)))
15787 t nil))
15788 (org-move-to-column column)))
15790 (defun org-set-autofill-regexps ()
15791 (interactive)
15792 ;; In the paragraph separator we include headlines, because filling
15793 ;; text in a line directly attached to a headline would otherwise
15794 ;; fill the headline as well.
15795 (org-set-local 'comment-start-skip "^#+[ \t]*")
15796 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
15797 ;; The paragraph starter includes hand-formatted lists.
15798 (org-set-local 'paragraph-start
15799 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
15800 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
15801 ;; But only if the user has not turned off tables or fixed-width regions
15802 (org-set-local
15803 'auto-fill-inhibit-regexp
15804 (concat "\\*+ \\|#\\+"
15805 "\\|[ \t]*" org-keyword-time-regexp
15806 (if (or org-enable-table-editor org-enable-fixed-width-editor)
15807 (concat
15808 "\\|[ \t]*["
15809 (if org-enable-table-editor "|" "")
15810 (if org-enable-fixed-width-editor ":" "")
15811 "]"))))
15812 ;; We use our own fill-paragraph function, to make sure that tables
15813 ;; and fixed-width regions are not wrapped. That function will pass
15814 ;; through to `fill-paragraph' when appropriate.
15815 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
15816 ; Adaptive filling: To get full control, first make sure that
15817 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
15818 (org-set-local 'adaptive-fill-regexp "\000")
15819 (org-set-local 'adaptive-fill-function
15820 'org-adaptive-fill-function)
15821 (org-set-local
15822 'align-mode-rules-list
15823 '((org-in-buffer-settings
15824 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
15825 (modes . '(org-mode))))))
15827 (defun org-fill-paragraph (&optional justify)
15828 "Re-align a table, pass through to fill-paragraph if no table."
15829 (let ((table-p (org-at-table-p))
15830 (table.el-p (org-at-table.el-p)))
15831 (cond ((and (equal (char-after (point-at-bol)) ?*)
15832 (save-excursion (goto-char (point-at-bol))
15833 (looking-at outline-regexp)))
15834 t) ; skip headlines
15835 (table.el-p t) ; skip table.el tables
15836 (table-p (org-table-align) t) ; align org-mode tables
15837 (t nil)))) ; call paragraph-fill
15839 ;; For reference, this is the default value of adaptive-fill-regexp
15840 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
15842 (defun org-adaptive-fill-function ()
15843 "Return a fill prefix for org-mode files.
15844 In particular, this makes sure hanging paragraphs for hand-formatted lists
15845 work correctly."
15846 (cond ((looking-at "#[ \t]+")
15847 (match-string 0))
15848 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
15849 (save-excursion
15850 (if (> (match-end 1) (+ (match-beginning 1)
15851 org-description-max-indent))
15852 (goto-char (+ (match-beginning 1) 5))
15853 (goto-char (match-end 0)))
15854 (make-string (current-column) ?\ )))
15855 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
15856 (save-excursion
15857 (goto-char (match-end 0))
15858 (make-string (current-column) ?\ )))
15859 (t nil)))
15861 ;;; Other stuff.
15863 (defun org-toggle-fixed-width-section (arg)
15864 "Toggle the fixed-width export.
15865 If there is no active region, the QUOTE keyword at the current headline is
15866 inserted or removed. When present, it causes the text between this headline
15867 and the next to be exported as fixed-width text, and unmodified.
15868 If there is an active region, this command adds or removes a colon as the
15869 first character of this line. If the first character of a line is a colon,
15870 this line is also exported in fixed-width font."
15871 (interactive "P")
15872 (let* ((cc 0)
15873 (regionp (org-region-active-p))
15874 (beg (if regionp (region-beginning) (point)))
15875 (end (if regionp (region-end)))
15876 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
15877 (case-fold-search nil)
15878 (re "[ \t]*\\(: \\)")
15879 off)
15880 (if regionp
15881 (save-excursion
15882 (goto-char beg)
15883 (setq cc (current-column))
15884 (beginning-of-line 1)
15885 (setq off (looking-at re))
15886 (while (> nlines 0)
15887 (setq nlines (1- nlines))
15888 (beginning-of-line 1)
15889 (cond
15890 (arg
15891 (org-move-to-column cc t)
15892 (insert ": \n")
15893 (forward-line -1))
15894 ((and off (looking-at re))
15895 (replace-match "" t t nil 1))
15896 ((not off) (org-move-to-column cc t) (insert ": ")))
15897 (forward-line 1)))
15898 (save-excursion
15899 (org-back-to-heading)
15900 (if (looking-at (concat outline-regexp
15901 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
15902 (replace-match "" t t nil 1)
15903 (if (looking-at outline-regexp)
15904 (progn
15905 (goto-char (match-end 0))
15906 (insert org-quote-string " "))))))))
15908 (defun org-reftex-citation ()
15909 "Use reftex-citation to insert a citation into the buffer.
15910 This looks for a line like
15912 #+BIBLIOGRAPHY: foo plain option:-d
15914 and derives from it that foo.bib is the bbliography file relevant
15915 for this document. It then installs the necessary environment for RefTeX
15916 to work in this buffer and calls `reftex-citation' to insert a citation
15917 into the buffer.
15919 Export of such citations to both LaTeX and HTML is handled by the contributed
15920 package org-exp-bibtex by Taru Karttunen."
15921 (interactive)
15922 (let ((reftex-docstruct-symbol 'rds)
15923 (reftex-cite-format "\\cite{%l}")
15924 rds bib)
15925 (save-excursion
15926 (save-restriction
15927 (widen)
15928 (let ((case-fold-search t)
15929 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
15930 (if (not (save-excursion
15931 (or (re-search-forward re nil t)
15932 (re-search-backward re nil t))))
15933 (error "No bibliography defined in file")
15934 (setq bib (concat (match-string 1) ".bib")
15935 rds (list (list 'bib bib)))))))
15936 (call-interactively 'reftex-citation)))
15938 ;;;; Functions extending outline functionality
15940 (defun org-beginning-of-line (&optional arg)
15941 "Go to the beginning of the current line. If that is invisible, continue
15942 to a visible line beginning. This makes the function of C-a more intuitive.
15943 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15944 first attempt, and only move to after the tags when the cursor is already
15945 beyond the end of the headline."
15946 (interactive "P")
15947 (let ((pos (point))
15948 (special (if (consp org-special-ctrl-a/e)
15949 (car org-special-ctrl-a/e)
15950 org-special-ctrl-a/e))
15951 refpos)
15952 (beginning-of-line 1)
15953 (if (and arg (fboundp 'move-beginning-of-line))
15954 (call-interactively 'move-beginning-of-line)
15955 (if (bobp)
15957 (backward-char 1)
15958 (if (org-invisible-p)
15959 (while (and (not (bobp)) (org-invisible-p))
15960 (backward-char 1)
15961 (beginning-of-line 1))
15962 (forward-char 1))))
15963 (when special
15964 (cond
15965 ((and (looking-at org-complex-heading-regexp)
15966 (= (char-after (match-end 1)) ?\ ))
15967 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
15968 (point-at-eol)))
15969 (goto-char
15970 (if (eq special t)
15971 (cond ((> pos refpos) refpos)
15972 ((= pos (point)) refpos)
15973 (t (point)))
15974 (cond ((> pos (point)) (point))
15975 ((not (eq last-command this-command)) (point))
15976 (t refpos)))))
15977 ((org-at-item-p)
15978 (goto-char
15979 (if (eq special t)
15980 (cond ((> pos (match-end 4)) (match-end 4))
15981 ((= pos (point)) (match-end 4))
15982 (t (point)))
15983 (cond ((> pos (point)) (point))
15984 ((not (eq last-command this-command)) (point))
15985 (t (match-end 4))))))))
15986 (org-no-warnings
15987 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15989 (defun org-end-of-line (&optional arg)
15990 "Go to the end of the line.
15991 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15992 first attempt, and only move to after the tags when the cursor is already
15993 beyond the end of the headline."
15994 (interactive "P")
15995 (let ((special (if (consp org-special-ctrl-a/e)
15996 (cdr org-special-ctrl-a/e)
15997 org-special-ctrl-a/e)))
15998 (if (or (not special)
15999 (not (org-on-heading-p))
16000 arg)
16001 (call-interactively (if (fboundp 'move-end-of-line)
16002 'move-end-of-line
16003 'end-of-line))
16004 (let ((pos (point)))
16005 (beginning-of-line 1)
16006 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
16007 (if (eq special t)
16008 (if (or (< pos (match-beginning 1))
16009 (= pos (match-end 0)))
16010 (goto-char (match-beginning 1))
16011 (goto-char (match-end 0)))
16012 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
16013 (goto-char (match-end 0))
16014 (goto-char (match-beginning 1))))
16015 (call-interactively (if (fboundp 'move-end-of-line)
16016 'move-end-of-line
16017 'end-of-line)))))
16018 (org-no-warnings
16019 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16021 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
16022 (define-key org-mode-map "\C-e" 'org-end-of-line)
16024 (defun org-backward-sentence (&optional arg)
16025 "Go to beginning of sentence, or beginning of table field.
16026 This will call `backward-sentence' or `org-table-beginning-of-field',
16027 depending on context."
16028 (interactive "P")
16029 (cond
16030 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
16031 (t (call-interactively 'backward-sentence))))
16033 (defun org-forward-sentence (&optional arg)
16034 "Go to end of sentence, or end of table field.
16035 This will call `forward-sentence' or `org-table-end-of-field',
16036 depending on context."
16037 (interactive "P")
16038 (cond
16039 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
16040 (t (call-interactively 'forward-sentence))))
16042 (define-key org-mode-map "\M-a" 'org-backward-sentence)
16043 (define-key org-mode-map "\M-e" 'org-forward-sentence)
16045 (defun org-kill-line (&optional arg)
16046 "Kill line, to tags or end of line."
16047 (interactive "P")
16048 (cond
16049 ((or (not org-special-ctrl-k)
16050 (bolp)
16051 (not (org-on-heading-p)))
16052 (call-interactively 'kill-line))
16053 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
16054 (kill-region (point) (match-beginning 1))
16055 (org-set-tags nil t))
16056 (t (kill-region (point) (point-at-eol)))))
16058 (define-key org-mode-map "\C-k" 'org-kill-line)
16060 (defun org-yank (&optional arg)
16061 "Yank. If the kill is a subtree, treat it specially.
16062 This command will look at the current kill and check if is a single
16063 subtree, or a series of subtrees[1]. If it passes the test, and if the
16064 cursor is at the beginning of a line or after the stars of a currently
16065 empty headline, then the yank is handled specially. How exactly depends
16066 on the value of the following variables, both set by default.
16068 org-yank-folded-subtrees
16069 When set, the subtree(s) will be folded after insertion, but only
16070 if doing so would now swallow text after the yanked text.
16072 org-yank-adjusted-subtrees
16073 When set, the subtree will be promoted or demoted in order to
16074 fit into the local outline tree structure, which means that the level
16075 will be adjusted so that it becomes the smaller one of the two
16076 *visible* surrounding headings.
16078 Any prefix to this command will cause `yank' to be called directly with
16079 no special treatment. In particular, a simple `C-u' prefix will just
16080 plainly yank the text as it is.
16082 \[1] The test checks if the first non-white line is a heading
16083 and if there are no other headings with fewer stars."
16084 (interactive "P")
16085 (org-yank-generic 'yank arg))
16087 (defun org-yank-generic (command arg)
16088 "Perform some yank-like command.
16090 This function implements the behavior described in the `org-yank'
16091 documentation. However, it has been generalized to work for any
16092 interactive command with similar behavior."
16094 ;; pretend to be command COMMAND
16095 (setq this-command command)
16097 (if arg
16098 (call-interactively command)
16100 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
16101 (and (org-kill-is-subtree-p)
16102 (or (bolp)
16103 (and (looking-at "[ \t]*$")
16104 (string-match
16105 "\\`\\*+\\'"
16106 (buffer-substring (point-at-bol) (point)))))))
16107 swallowp)
16108 (cond
16109 ((and subtreep org-yank-folded-subtrees)
16110 (let ((beg (point))
16111 end)
16112 (if (and subtreep org-yank-adjusted-subtrees)
16113 (org-paste-subtree nil nil 'for-yank)
16114 (call-interactively command))
16116 (setq end (point))
16117 (goto-char beg)
16118 (when (and (bolp) subtreep
16119 (not (setq swallowp
16120 (org-yank-folding-would-swallow-text beg end))))
16121 (or (looking-at outline-regexp)
16122 (re-search-forward (concat "^" outline-regexp) end t))
16123 (while (and (< (point) end) (looking-at outline-regexp))
16124 (hide-subtree)
16125 (org-cycle-show-empty-lines 'folded)
16126 (condition-case nil
16127 (outline-forward-same-level 1)
16128 (error (goto-char end)))))
16129 (when swallowp
16130 (message
16131 "Inserted text not folded because that would swallow text"))
16133 (goto-char end)
16134 (skip-chars-forward " \t\n\r")
16135 (beginning-of-line 1)
16136 (push-mark beg 'nomsg)))
16137 ((and subtreep org-yank-adjusted-subtrees)
16138 (let ((beg (point-at-bol)))
16139 (org-paste-subtree nil nil 'for-yank)
16140 (push-mark beg 'nomsg)))
16142 (call-interactively command))))))
16144 (defun org-yank-folding-would-swallow-text (beg end)
16145 "Would hide-subtree at BEG swallow any text after END?"
16146 (let (level)
16147 (save-excursion
16148 (goto-char beg)
16149 (when (or (looking-at outline-regexp)
16150 (re-search-forward (concat "^" outline-regexp) end t))
16151 (setq level (org-outline-level)))
16152 (goto-char end)
16153 (skip-chars-forward " \t\r\n\v\f")
16154 (if (or (eobp)
16155 (and (bolp) (looking-at org-outline-regexp)
16156 (<= (org-outline-level) level)))
16157 nil ; Nothing would be swallowed
16158 t)))) ; something would swallow
16160 (define-key org-mode-map "\C-y" 'org-yank)
16162 (defun org-invisible-p ()
16163 "Check if point is at a character currently not visible."
16164 ;; Early versions of noutline don't have `outline-invisible-p'.
16165 (if (fboundp 'outline-invisible-p)
16166 (outline-invisible-p)
16167 (get-char-property (point) 'invisible)))
16169 (defun org-invisible-p2 ()
16170 "Check if point is at a character currently not visible."
16171 (save-excursion
16172 (if (and (eolp) (not (bobp))) (backward-char 1))
16173 ;; Early versions of noutline don't have `outline-invisible-p'.
16174 (if (fboundp 'outline-invisible-p)
16175 (outline-invisible-p)
16176 (get-char-property (point) 'invisible))))
16178 (defun org-back-to-heading (&optional invisible-ok)
16179 "Call `outline-back-to-heading', but provide a better error message."
16180 (condition-case nil
16181 (outline-back-to-heading invisible-ok)
16182 (error (error "Before first headline at position %d in buffer %s"
16183 (point) (current-buffer)))))
16185 (defun org-before-first-heading-p ()
16186 "Before first heading?"
16187 (save-excursion
16188 (null (re-search-backward "^\\*+ " nil t))))
16190 (defalias 'org-on-heading-p 'outline-on-heading-p)
16191 (defalias 'org-at-heading-p 'outline-on-heading-p)
16192 (defun org-at-heading-or-item-p ()
16193 (or (org-on-heading-p) (org-at-item-p)))
16195 (defun org-on-target-p ()
16196 (or (org-in-regexp org-radio-target-regexp)
16197 (org-in-regexp org-target-regexp)))
16199 (defun org-up-heading-all (arg)
16200 "Move to the heading line of which the present line is a subheading.
16201 This function considers both visible and invisible heading lines.
16202 With argument, move up ARG levels."
16203 (if (fboundp 'outline-up-heading-all)
16204 (outline-up-heading-all arg) ; emacs 21 version of outline.el
16205 (outline-up-heading arg t))) ; emacs 22 version of outline.el
16207 (defun org-up-heading-safe ()
16208 "Move to the heading line of which the present line is a subheading.
16209 This version will not throw an error. It will return the level of the
16210 headline found, or nil if no higher level is found.
16212 Also, this function will be a lot faster than `outline-up-heading',
16213 because it relies on stars being the outline starters. This can really
16214 make a significant difference in outlines with very many siblings."
16215 (let (start-level re)
16216 (org-back-to-heading t)
16217 (setq start-level (funcall outline-level))
16218 (if (equal start-level 1)
16220 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
16221 (if (re-search-backward re nil t)
16222 (funcall outline-level)))))
16224 (defun org-first-sibling-p ()
16225 "Is this heading the first child of its parents?"
16226 (interactive)
16227 (let ((re (concat "^" outline-regexp))
16228 level l)
16229 (unless (org-at-heading-p t)
16230 (error "Not at a heading"))
16231 (setq level (funcall outline-level))
16232 (save-excursion
16233 (if (not (re-search-backward re nil t))
16235 (setq l (funcall outline-level))
16236 (< l level)))))
16238 (defun org-goto-sibling (&optional previous)
16239 "Goto the next sibling, even if it is invisible.
16240 When PREVIOUS is set, go to the previous sibling instead. Returns t
16241 when a sibling was found. When none is found, return nil and don't
16242 move point."
16243 (let ((fun (if previous 're-search-backward 're-search-forward))
16244 (pos (point))
16245 (re (concat "^" outline-regexp))
16246 level l)
16247 (when (condition-case nil (org-back-to-heading t) (error nil))
16248 (setq level (funcall outline-level))
16249 (catch 'exit
16250 (or previous (forward-char 1))
16251 (while (funcall fun re nil t)
16252 (setq l (funcall outline-level))
16253 (when (< l level) (goto-char pos) (throw 'exit nil))
16254 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
16255 (goto-char pos)
16256 nil))))
16258 (defun org-show-siblings ()
16259 "Show all siblings of the current headline."
16260 (save-excursion
16261 (while (org-goto-sibling) (org-flag-heading nil)))
16262 (save-excursion
16263 (while (org-goto-sibling 'previous)
16264 (org-flag-heading nil))))
16266 (defun org-show-hidden-entry ()
16267 "Show an entry where even the heading is hidden."
16268 (save-excursion
16269 (org-show-entry)))
16271 (defun org-flag-heading (flag &optional entry)
16272 "Flag the current heading. FLAG non-nil means make invisible.
16273 When ENTRY is non-nil, show the entire entry."
16274 (save-excursion
16275 (org-back-to-heading t)
16276 ;; Check if we should show the entire entry
16277 (if entry
16278 (progn
16279 (org-show-entry)
16280 (save-excursion
16281 (and (outline-next-heading)
16282 (org-flag-heading nil))))
16283 (outline-flag-region (max (point-min) (1- (point)))
16284 (save-excursion (outline-end-of-heading) (point))
16285 flag))))
16287 (defun org-forward-same-level (arg)
16288 "Move forward to the ARG'th subheading at same level as this one.
16289 Stop at the first and last subheadings of a superior heading.
16290 This is like outline-forward-same-level, but invisible headings are ok."
16291 (interactive "p")
16292 (org-back-to-heading t)
16293 (while (> arg 0)
16294 (let ((point-to-move-to (save-excursion
16295 (org-get-next-sibling))))
16296 (if point-to-move-to
16297 (progn
16298 (goto-char point-to-move-to)
16299 (setq arg (1- arg)))
16300 (progn
16301 (setq arg 0)
16302 (error "No following same-level heading"))))))
16304 (defun org-get-next-sibling ()
16305 "Move to next heading of the same level, and return point.
16306 If there is no such heading, return nil.
16307 This is like outline-next-sibling, but invisible headings are ok."
16308 (let ((level (funcall outline-level)))
16309 (outline-next-heading)
16310 (while (and (not (eobp)) (> (funcall outline-level) level))
16311 (outline-next-heading))
16312 (if (or (eobp) (< (funcall outline-level) level))
16314 (point))))
16316 (defun org-end-of-subtree (&optional invisible-OK to-heading)
16317 ;; This contains an exact copy of the original function, but it uses
16318 ;; `org-back-to-heading', to make it work also in invisible
16319 ;; trees. And is uses an invisible-OK argument.
16320 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
16321 ;; Furthermore, when used inside Org, finding the end of a large subtree
16322 ;; with many children and grandchildren etc, this can be much faster
16323 ;; than the outline version.
16324 (org-back-to-heading invisible-OK)
16325 (let ((first t)
16326 (level (funcall outline-level)))
16327 (if (and (org-mode-p) (< level 1000))
16328 ;; A true heading (not a plain list item), in Org-mode
16329 ;; This means we can easily find the end by looking
16330 ;; only for the right number of stars. Using a regexp to do
16331 ;; this is so much faster than using a Lisp loop.
16332 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
16333 (forward-char 1)
16334 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
16335 ;; something else, do it the slow way
16336 (while (and (not (eobp))
16337 (or first (> (funcall outline-level) level)))
16338 (setq first nil)
16339 (outline-next-heading)))
16340 (unless to-heading
16341 (if (memq (preceding-char) '(?\n ?\^M))
16342 (progn
16343 ;; Go to end of line before heading
16344 (forward-char -1)
16345 (if (memq (preceding-char) '(?\n ?\^M))
16346 ;; leave blank line before heading
16347 (forward-char -1))))))
16348 (point))
16350 (defun org-show-subtree ()
16351 "Show everything after this heading at deeper levels."
16352 (outline-flag-region
16353 (point)
16354 (save-excursion
16355 (outline-end-of-subtree) (outline-next-heading) (point))
16356 nil))
16358 (defun org-show-entry ()
16359 "Show the body directly following this heading.
16360 Show the heading too, if it is currently invisible."
16361 (interactive)
16362 (save-excursion
16363 (condition-case nil
16364 (progn
16365 (org-back-to-heading t)
16366 (outline-flag-region
16367 (max (point-min) (1- (point)))
16368 (save-excursion
16369 (if (re-search-forward
16370 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
16371 (match-beginning 1)
16372 (point-max)))
16373 nil))
16374 (error nil))))
16376 (defun org-make-options-regexp (kwds &optional extra)
16377 "Make a regular expression for keyword lines."
16378 (concat
16380 "#?[ \t]*\\+\\("
16381 (mapconcat 'regexp-quote kwds "\\|")
16382 (if extra (concat "\\|" extra))
16383 "\\):[ \t]*"
16384 "\\(.+\\)"))
16386 ;; Make isearch reveal the necessary context
16387 (defun org-isearch-end ()
16388 "Reveal context after isearch exits."
16389 (when isearch-success ; only if search was successful
16390 (if (featurep 'xemacs)
16391 ;; Under XEmacs, the hook is run in the correct place,
16392 ;; we directly show the context.
16393 (org-show-context 'isearch)
16394 ;; In Emacs the hook runs *before* restoring the overlays.
16395 ;; So we have to use a one-time post-command-hook to do this.
16396 ;; (Emacs 22 has a special variable, see function `org-mode')
16397 (unless (and (boundp 'isearch-mode-end-hook-quit)
16398 isearch-mode-end-hook-quit)
16399 ;; Only when the isearch was not quitted.
16400 (org-add-hook 'post-command-hook 'org-isearch-post-command
16401 'append 'local)))))
16403 (defun org-isearch-post-command ()
16404 "Remove self from hook, and show context."
16405 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
16406 (org-show-context 'isearch))
16409 ;;;; Integration with and fixes for other packages
16411 ;;; Imenu support
16413 (defvar org-imenu-markers nil
16414 "All markers currently used by Imenu.")
16415 (make-variable-buffer-local 'org-imenu-markers)
16417 (defun org-imenu-new-marker (&optional pos)
16418 "Return a new marker for use by Imenu, and remember the marker."
16419 (let ((m (make-marker)))
16420 (move-marker m (or pos (point)))
16421 (push m org-imenu-markers)
16424 (defun org-imenu-get-tree ()
16425 "Produce the index for Imenu."
16426 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
16427 (setq org-imenu-markers nil)
16428 (let* ((n org-imenu-depth)
16429 (re (concat "^" outline-regexp))
16430 (subs (make-vector (1+ n) nil))
16431 (last-level 0)
16432 m level head)
16433 (save-excursion
16434 (save-restriction
16435 (widen)
16436 (goto-char (point-max))
16437 (while (re-search-backward re nil t)
16438 (setq level (org-reduced-level (funcall outline-level)))
16439 (when (<= level n)
16440 (looking-at org-complex-heading-regexp)
16441 (setq head (org-link-display-format
16442 (org-match-string-no-properties 4))
16443 m (org-imenu-new-marker))
16444 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
16445 (if (>= level last-level)
16446 (push (cons head m) (aref subs level))
16447 (push (cons head (aref subs (1+ level))) (aref subs level))
16448 (loop for i from (1+ level) to n do (aset subs i nil)))
16449 (setq last-level level)))))
16450 (aref subs 1)))
16452 (eval-after-load "imenu"
16453 '(progn
16454 (add-hook 'imenu-after-jump-hook
16455 (lambda ()
16456 (if (eq major-mode 'org-mode)
16457 (org-show-context 'org-goto))))))
16459 (defun org-link-display-format (link)
16460 "Replace a link with either the description, or the link target
16461 if no description is present"
16462 (save-match-data
16463 (if (string-match org-bracket-link-analytic-regexp link)
16464 (replace-match (or (match-string 5 link)
16465 (concat (match-string 1 link)
16466 (match-string 3 link)))
16467 nil nil link)
16468 link)))
16470 ;; Speedbar support
16472 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
16473 "Overlay marking the agenda restriction line in speedbar.")
16474 (org-overlay-put org-speedbar-restriction-lock-overlay
16475 'face 'org-agenda-restriction-lock)
16476 (org-overlay-put org-speedbar-restriction-lock-overlay
16477 'help-echo "Agendas are currently limited to this item.")
16478 (org-detach-overlay org-speedbar-restriction-lock-overlay)
16480 (defun org-speedbar-set-agenda-restriction ()
16481 "Restrict future agenda commands to the location at point in speedbar.
16482 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
16483 (interactive)
16484 (require 'org-agenda)
16485 (let (p m tp np dir txt)
16486 (cond
16487 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16488 'org-imenu t))
16489 (setq m (get-text-property p 'org-imenu-marker))
16490 (save-excursion
16491 (save-restriction
16492 (set-buffer (marker-buffer m))
16493 (goto-char m)
16494 (org-agenda-set-restriction-lock 'subtree))))
16495 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16496 'speedbar-function 'speedbar-find-file))
16497 (setq tp (previous-single-property-change
16498 (1+ p) 'speedbar-function)
16499 np (next-single-property-change
16500 tp 'speedbar-function)
16501 dir (speedbar-line-directory)
16502 txt (buffer-substring-no-properties (or tp (point-min))
16503 (or np (point-max))))
16504 (save-excursion
16505 (save-restriction
16506 (set-buffer (find-file-noselect
16507 (let ((default-directory dir))
16508 (expand-file-name txt))))
16509 (unless (org-mode-p)
16510 (error "Cannot restrict to non-Org-mode file"))
16511 (org-agenda-set-restriction-lock 'file))))
16512 (t (error "Don't know how to restrict Org-mode's agenda")))
16513 (org-move-overlay org-speedbar-restriction-lock-overlay
16514 (point-at-bol) (point-at-eol))
16515 (setq current-prefix-arg nil)
16516 (org-agenda-maybe-redo)))
16518 (eval-after-load "speedbar"
16519 '(progn
16520 (speedbar-add-supported-extension ".org")
16521 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
16522 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
16523 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
16524 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16525 (add-hook 'speedbar-visiting-tag-hook
16526 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
16529 ;;; Fixes and Hacks for problems with other packages
16531 ;; Make flyspell not check words in links, to not mess up our keymap
16532 (defun org-mode-flyspell-verify ()
16533 "Don't let flyspell put overlays at active buttons."
16534 (not (get-text-property (point) 'keymap)))
16536 ;; Make `bookmark-jump' show the jump location if it was hidden.
16537 (eval-after-load "bookmark"
16538 '(if (boundp 'bookmark-after-jump-hook)
16539 ;; We can use the hook
16540 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
16541 ;; Hook not available, use advice
16542 (defadvice bookmark-jump (after org-make-visible activate)
16543 "Make the position visible."
16544 (org-bookmark-jump-unhide))))
16546 ;; Make sure saveplace show the location if it was hidden
16547 (eval-after-load "saveplace"
16548 '(defadvice save-place-find-file-hook (after org-make-visible activate)
16549 "Make the position visible."
16550 (org-bookmark-jump-unhide)))
16552 (defun org-bookmark-jump-unhide ()
16553 "Unhide the current position, to show the bookmark location."
16554 (and (org-mode-p)
16555 (or (org-invisible-p)
16556 (save-excursion (goto-char (max (point-min) (1- (point))))
16557 (org-invisible-p)))
16558 (org-show-context 'bookmark-jump)))
16560 ;; Make session.el ignore our circular variable
16561 (eval-after-load "session"
16562 '(add-to-list 'session-globals-exclude 'org-mark-ring))
16564 ;;;; Experimental code
16566 (defun org-closed-in-range ()
16567 "Sparse tree of items closed in a certain time range.
16568 Still experimental, may disappear in the future."
16569 (interactive)
16570 ;; Get the time interval from the user.
16571 (let* ((time1 (time-to-seconds
16572 (org-read-date nil 'to-time nil "Starting date: ")))
16573 (time2 (time-to-seconds
16574 (org-read-date nil 'to-time nil "End date:")))
16575 ;; callback function
16576 (callback (lambda ()
16577 (let ((time
16578 (time-to-seconds
16579 (apply 'encode-time
16580 (org-parse-time-string
16581 (match-string 1))))))
16582 ;; check if time in interval
16583 (and (>= time time1) (<= time time2))))))
16584 ;; make tree, check each match with the callback
16585 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
16587 ;;;; Finish up
16589 (provide 'org)
16591 (run-hooks 'org-load-hook)
16593 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
16595 ;;; org.el ends here