Release 6.27
[org-mode/org-tableheadings.git] / lisp / org.el
blob698df96813e7ce9f26364e370656cfefb7321ec9
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.27
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.27"
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-hierarchical-todo-statistics t
1741 "Non-nil means, TODO statistics covers just direct children.
1742 When nil, all entries in the subtree are considered.
1743 This has only an effect if `org-provide-todo-statistics' is set."
1744 :group 'org-todo
1745 :type 'boolean)
1747 (defcustom org-after-todo-state-change-hook nil
1748 "Hook which is run after the state of a TODO item was changed.
1749 The new state (a string with a TODO keyword, or nil) is available in the
1750 Lisp variable `state'."
1751 :group 'org-todo
1752 :type 'hook)
1754 (defvar org-blocker-hook nil
1755 "Hook for functions that are allowed to block a state change.
1757 Each function gets as its single argument a property list, see
1758 `org-trigger-hook' for more information about this list.
1760 If any of the functions in this hook returns nil, the state change
1761 is blocked.")
1763 (defvar org-trigger-hook nil
1764 "Hook for functions that are triggered by a state change.
1766 Each function gets as its single argument a property list with at least
1767 the following elements:
1769 (:type type-of-change :position pos-at-entry-start
1770 :from old-state :to new-state)
1772 Depending on the type, more properties may be present.
1774 This mechanism is currently implemented for:
1776 TODO state changes
1777 ------------------
1778 :type todo-state-change
1779 :from previous state (keyword as a string), or nil, or a symbol
1780 'todo' or 'done', to indicate the general type of state.
1781 :to new state, like in :from")
1783 (defcustom org-enforce-todo-dependencies nil
1784 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1785 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1786 be blocked if any prior sibling is not yet done.
1787 Finally, if the parent is blocked because of ordered siblings of its own,
1788 the child will also be blocked.
1789 This variable needs to be set before org.el is loaded, and you need to
1790 restart Emacs after a change to make the change effective. The only way
1791 to change is while Emacs is running is through the customize interface."
1792 :set (lambda (var val)
1793 (set var val)
1794 (if val
1795 (add-hook 'org-blocker-hook
1796 'org-block-todo-from-children-or-siblings-or-parent)
1797 (remove-hook 'org-blocker-hook
1798 'org-block-todo-from-children-or-siblings-or-parent)))
1799 :group 'org-todo
1800 :type 'boolean)
1802 (defcustom org-enforce-todo-checkbox-dependencies nil
1803 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1804 When this is nil, checkboxes have no influence on switching TODO states.
1805 When non-nil, you first need to check off all check boxes before the TODO
1806 entry can be switched to DONE.
1807 This variable needs to be set before org.el is loaded, and you need to
1808 restart Emacs after a change to make the change effective. The only way
1809 to change is while Emacs is running is through the customize interface."
1810 :set (lambda (var val)
1811 (set var val)
1812 (if val
1813 (add-hook 'org-blocker-hook
1814 'org-block-todo-from-checkboxes)
1815 (remove-hook 'org-blocker-hook
1816 'org-block-todo-from-checkboxes)))
1817 :group 'org-todo
1818 :type 'boolean)
1820 (defcustom org-todo-state-tags-triggers nil
1821 "Tag changes that should be triggered by TODO state changes.
1822 This is a list. Each entry is
1824 (state-change (tag . flag) .......)
1826 State-change can be a string with a state, and empty string to indicate the
1827 state that has no TODO keyword, or it can be one of the symbols `todo'
1828 or `done', meaning any not-done or done state, respectively."
1829 :group 'org-todo
1830 :group 'org-tags
1831 :type '(repeat
1832 (cons (choice :tag "When changing to"
1833 (const :tag "Not-done state" todo)
1834 (const :tag "Done state" done)
1835 (string :tag "State"))
1836 (repeat
1837 (cons :tag "Tag action"
1838 (string :tag "Tag")
1839 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1841 (defcustom org-log-done nil
1842 "Information to record when a task moves to the DONE state.
1844 Possible values are:
1846 nil Don't add anything, just change the keyword
1847 time Add a time stamp to the task
1848 note Prompt a closing note and add it with template `org-log-note-headings'
1850 This option can also be set with on a per-file-basis with
1852 #+STARTUP: nologdone
1853 #+STARTUP: logdone
1854 #+STARTUP: lognotedone
1856 You can have local logging settings for a subtree by setting the LOGGING
1857 property to one or more of these keywords."
1858 :group 'org-todo
1859 :group 'org-progress
1860 :type '(choice
1861 (const :tag "No logging" nil)
1862 (const :tag "Record CLOSED timestamp" time)
1863 (const :tag "Record CLOSED timestamp with closing note." note)))
1865 ;; Normalize old uses of org-log-done.
1866 (cond
1867 ((eq org-log-done t) (setq org-log-done 'time))
1868 ((and (listp org-log-done) (memq 'done org-log-done))
1869 (setq org-log-done 'note)))
1871 (defcustom org-log-note-clock-out nil
1872 "Non-nil means, record a note when clocking out of an item.
1873 This can also be configured on a per-file basis by adding one of
1874 the following lines anywhere in the buffer:
1876 #+STARTUP: lognoteclock-out
1877 #+STARTUP: nolognoteclock-out"
1878 :group 'org-todo
1879 :group 'org-progress
1880 :type 'boolean)
1882 (defcustom org-log-done-with-time t
1883 "Non-nil means, the CLOSED time stamp will contain date and time.
1884 When nil, only the date will be recorded."
1885 :group 'org-progress
1886 :type 'boolean)
1888 (defcustom org-log-note-headings
1889 '((done . "CLOSING NOTE %t")
1890 (state . "State %-12s from %-12S %t")
1891 (note . "Note taken on %t")
1892 (clock-out . ""))
1893 "Headings for notes added to entries.
1894 The value is an alist, with the car being a symbol indicating the note
1895 context, and the cdr is the heading to be used. The heading may also be the
1896 empty string.
1897 %t in the heading will be replaced by a time stamp.
1898 %s will be replaced by the new TODO state, in double quotes.
1899 %S will be replaced by the old TODO state, in double quotes.
1900 %u will be replaced by the user name.
1901 %U will be replaced by the full user name."
1902 :group 'org-todo
1903 :group 'org-progress
1904 :type '(list :greedy t
1905 (cons (const :tag "Heading when closing an item" done) string)
1906 (cons (const :tag
1907 "Heading when changing todo state (todo sequence only)"
1908 state) string)
1909 (cons (const :tag "Heading when just taking a note" note) string)
1910 (cons (const :tag "Heading when clocking out" clock-out) string)))
1912 (unless (assq 'note org-log-note-headings)
1913 (push '(note . "%t") org-log-note-headings))
1915 (defcustom org-log-into-drawer nil
1916 "Non-nil means, insert state change notes and time stamps into a drawer.
1917 When nil, state changes notes will be inserted after the headline and
1918 any scheduling and clock lines, but not inside a drawer.
1920 The value of this variable should be the name of the drawer to use.
1921 LOGBOOK is proposed at the default drawer for this purpose, you can
1922 also set this to a string to define the drawer of your choice.
1924 A value of t is also allowed, representing \"LOGBOOK\".
1926 If this variable is set, `org-log-state-notes-insert-after-drawers'
1927 will be ignored.
1929 You can set the property LOG_INTO_DRAWER to overrule this setting for
1930 a subtree."
1931 :group 'org-todo
1932 :group 'org-progress
1933 :type '(choice
1934 (const :tag "Not into a drawer" nil)
1935 (const :tag "LOGBOOK" t)
1936 (string :tag "Other")))
1938 (if (fboundp 'defvaralias)
1939 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
1941 (defun org-log-into-drawer ()
1942 "Return the value of `org-log-into-drawer', but let properties overrule.
1943 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
1944 used instead of the default value."
1945 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
1946 (cond
1947 ((or (not p) (equal p "nil")) org-log-into-drawer)
1948 ((equal p "t") "LOGBOOK")
1949 (t p))))
1951 (defcustom org-log-state-notes-insert-after-drawers nil
1952 "Non-nil means, insert state change notes after any drawers in entry.
1953 Only the drawers that *immediately* follow the headline and the
1954 deadline/scheduled line are skipped.
1955 When nil, insert notes right after the heading and perhaps the line
1956 with deadline/scheduling if present.
1958 This variable will have no effect if `org-log-into-drawer' is
1959 set."
1960 :group 'org-todo
1961 :group 'org-progress
1962 :type 'boolean)
1964 (defcustom org-log-states-order-reversed t
1965 "Non-nil means, the latest state change note will be directly after heading.
1966 When nil, the notes will be orderer according to time."
1967 :group 'org-todo
1968 :group 'org-progress
1969 :type 'boolean)
1971 (defcustom org-log-repeat 'time
1972 "Non-nil means, record moving through the DONE state when triggering repeat.
1973 An auto-repeating tasks is immediately switched back to TODO when marked
1974 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1975 the TODO keyword definition, or recording a closing note by setting
1976 `org-log-done', there will be no record of the task moving through DONE.
1977 This variable forces taking a note anyway. Possible values are:
1979 nil Don't force a record
1980 time Record a time stamp
1981 note Record a note
1983 This option can also be set with on a per-file-basis with
1985 #+STARTUP: logrepeat
1986 #+STARTUP: lognoterepeat
1987 #+STARTUP: nologrepeat
1989 You can have local logging settings for a subtree by setting the LOGGING
1990 property to one or more of these keywords."
1991 :group 'org-todo
1992 :group 'org-progress
1993 :type '(choice
1994 (const :tag "Don't force a record" nil)
1995 (const :tag "Force recording the DONE state" time)
1996 (const :tag "Force recording a note with the DONE state" note)))
1999 (defgroup org-priorities nil
2000 "Priorities in Org-mode."
2001 :tag "Org Priorities"
2002 :group 'org-todo)
2004 (defcustom org-enable-priority-commands t
2005 "Non-nil means, priority commands are active.
2006 When nil, these commands will be disabled, so that you never accidentally
2007 set a priority."
2008 :group 'org-priorities
2009 :type 'boolean)
2011 (defcustom org-highest-priority ?A
2012 "The highest priority of TODO items. A character like ?A, ?B etc.
2013 Must have a smaller ASCII number than `org-lowest-priority'."
2014 :group 'org-priorities
2015 :type 'character)
2017 (defcustom org-lowest-priority ?C
2018 "The lowest priority of TODO items. A character like ?A, ?B etc.
2019 Must have a larger ASCII number than `org-highest-priority'."
2020 :group 'org-priorities
2021 :type 'character)
2023 (defcustom org-default-priority ?B
2024 "The default priority of TODO items.
2025 This is the priority an item get if no explicit priority is given."
2026 :group 'org-priorities
2027 :type 'character)
2029 (defcustom org-priority-start-cycle-with-default t
2030 "Non-nil means, start with default priority when starting to cycle.
2031 When this is nil, the first step in the cycle will be (depending on the
2032 command used) one higher or lower that the default priority."
2033 :group 'org-priorities
2034 :type 'boolean)
2036 (defgroup org-time nil
2037 "Options concerning time stamps and deadlines in Org-mode."
2038 :tag "Org Time"
2039 :group 'org)
2041 (defcustom org-insert-labeled-timestamps-at-point nil
2042 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
2043 When nil, these labeled time stamps are forces into the second line of an
2044 entry, just after the headline. When scheduling from the global TODO list,
2045 the time stamp will always be forced into the second line."
2046 :group 'org-time
2047 :type 'boolean)
2049 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2050 "Formats for `format-time-string' which are used for time stamps.
2051 It is not recommended to change this constant.")
2053 (defcustom org-time-stamp-rounding-minutes '(0 5)
2054 "Number of minutes to round time stamps to.
2055 These are two values, the first applies when first creating a time stamp.
2056 The second applies when changing it with the commands `S-up' and `S-down'.
2057 When changing the time stamp, this means that it will change in steps
2058 of N minutes, as given by the second value.
2060 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2061 numbers should be factors of 60, so for example 5, 10, 15.
2063 When this is larger than 1, you can still force an exact time-stamp by using
2064 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2065 and by using a prefix arg to `S-up/down' to specify the exact number
2066 of minutes to shift."
2067 :group 'org-time
2068 :get '(lambda (var) ; Make sure all entries have 5 elements
2069 (if (integerp (default-value var))
2070 (list (default-value var) 5)
2071 (default-value var)))
2072 :type '(list
2073 (integer :tag "when inserting times")
2074 (integer :tag "when modifying times")))
2076 ;; Normalize old customizations of this variable.
2077 (when (integerp org-time-stamp-rounding-minutes)
2078 (setq org-time-stamp-rounding-minutes
2079 (list org-time-stamp-rounding-minutes
2080 org-time-stamp-rounding-minutes)))
2082 (defcustom org-display-custom-times nil
2083 "Non-nil means, overlay custom formats over all time stamps.
2084 The formats are defined through the variable `org-time-stamp-custom-formats'.
2085 To turn this on on a per-file basis, insert anywhere in the file:
2086 #+STARTUP: customtime"
2087 :group 'org-time
2088 :set 'set-default
2089 :type 'sexp)
2090 (make-variable-buffer-local 'org-display-custom-times)
2092 (defcustom org-time-stamp-custom-formats
2093 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2094 "Custom formats for time stamps. See `format-time-string' for the syntax.
2095 These are overlayed over the default ISO format if the variable
2096 `org-display-custom-times' is set. Time like %H:%M should be at the
2097 end of the second format. The custom formats are also honored by export
2098 commands, if custom time display is turned on at the time of export."
2099 :group 'org-time
2100 :type 'sexp)
2102 (defun org-time-stamp-format (&optional long inactive)
2103 "Get the right format for a time string."
2104 (let ((f (if long (cdr org-time-stamp-formats)
2105 (car org-time-stamp-formats))))
2106 (if inactive
2107 (concat "[" (substring f 1 -1) "]")
2108 f)))
2110 (defcustom org-time-clocksum-format "%d:%02d"
2111 "The format string used when creating CLOCKSUM lines, or when
2112 org-mode generates a time duration."
2113 :group 'org-time
2114 :type 'string)
2116 (defcustom org-deadline-warning-days 14
2117 "No. of days before expiration during which a deadline becomes active.
2118 This variable governs the display in sparse trees and in the agenda.
2119 When 0 or negative, it means use this number (the absolute value of it)
2120 even if a deadline has a different individual lead time specified.
2122 Custom commands can set this variable in the options section."
2123 :group 'org-time
2124 :group 'org-agenda-daily/weekly
2125 :type 'integer)
2127 (defcustom org-read-date-prefer-future t
2128 "Non-nil means, assume future for incomplete date input from user.
2129 This affects the following situations:
2130 1. The user gives a day, but no month.
2131 For example, if today is the 15th, and you enter \"3\", Org-mode will
2132 read this as the third of *next* month. However, if you enter \"17\",
2133 it will be considered as *this* month.
2134 2. The user gives a month but not a year.
2135 For example, if it is april and you enter \"feb 2\", this will be read
2136 as feb 2, *next* year. \"May 5\", however, will be this year.
2138 Currently this does not work for ISO week specifications.
2140 When this option is nil, the current month and year will always be used
2141 as defaults."
2142 :group 'org-time
2143 :type 'boolean)
2145 (defcustom org-read-date-display-live t
2146 "Non-nil means, display current interpretation of date prompt live.
2147 This display will be in an overlay, in the minibuffer."
2148 :group 'org-time
2149 :type 'boolean)
2151 (defcustom org-read-date-popup-calendar t
2152 "Non-nil means, pop up a calendar when prompting for a date.
2153 In the calendar, the date can be selected with mouse-1. However, the
2154 minibuffer will also be active, and you can simply enter the date as well.
2155 When nil, only the minibuffer will be available."
2156 :group 'org-time
2157 :type 'boolean)
2158 (if (fboundp 'defvaralias)
2159 (defvaralias 'org-popup-calendar-for-date-prompt
2160 'org-read-date-popup-calendar))
2162 (defcustom org-read-date-minibuffer-setup-hook nil
2163 "Hook to be used to set up keys for the date/time interface.
2164 Add key definitions to `minibuffer-local-map', which will be a temporary
2165 copy."
2166 :group 'org-time
2167 :type 'hook)
2169 (defcustom org-extend-today-until 0
2170 "The hour when your day really ends. Must be an integer.
2171 This has influence for the following applications:
2172 - When switching the agenda to \"today\". It it is still earlier than
2173 the time given here, the day recognized as TODAY is actually yesterday.
2174 - When a date is read from the user and it is still before the time given
2175 here, the current date and time will be assumed to be yesterday, 23:59.
2176 Also, timestamps inserted in remember templates follow this rule.
2178 IMPORTANT: This is a feature whose implementation is and likely will
2179 remain incomplete. Really, it is only here because past midnight seems to
2180 be the favorite working time of John Wiegley :-)"
2181 :group 'org-time
2182 :type 'integer)
2184 (defcustom org-edit-timestamp-down-means-later nil
2185 "Non-nil means, S-down will increase the time in a time stamp.
2186 When nil, S-up will increase."
2187 :group 'org-time
2188 :type 'boolean)
2190 (defcustom org-calendar-follow-timestamp-change t
2191 "Non-nil means, make the calendar window follow timestamp changes.
2192 When a timestamp is modified and the calendar window is visible, it will be
2193 moved to the new date."
2194 :group 'org-time
2195 :type 'boolean)
2197 (defgroup org-tags nil
2198 "Options concerning tags in Org-mode."
2199 :tag "Org Tags"
2200 :group 'org)
2202 (defcustom org-tag-alist nil
2203 "List of tags allowed in Org-mode files.
2204 When this list is nil, Org-mode will base TAG input on what is already in the
2205 buffer.
2206 The value of this variable is an alist, the car of each entry must be a
2207 keyword as a string, the cdr may be a character that is used to select
2208 that tag through the fast-tag-selection interface.
2209 See the manual for details."
2210 :group 'org-tags
2211 :type '(repeat
2212 (choice
2213 (cons (string :tag "Tag name")
2214 (character :tag "Access char"))
2215 (const :tag "Start radio group" (:startgroup))
2216 (const :tag "End radio group" (:endgroup))
2217 (const :tag "New line" (:newline)))))
2219 (defcustom org-tag-persistent-alist nil
2220 "List of tags that will always appear in all Org-mode files.
2221 This is in addition to any in buffer settings or customizations
2222 of `org-tag-alist'.
2223 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2224 The value of this variable is an alist, the car of each entry must be a
2225 keyword as a string, the cdr may be a character that is used to select
2226 that tag through the fast-tag-selection interface.
2227 See the manual for details.
2228 To disable these tags on a per-file basis, insert anywhere in the file:
2229 #+STARTUP: noptag"
2230 :group 'org-tags
2231 :type '(repeat
2232 (choice
2233 (cons (string :tag "Tag name")
2234 (character :tag "Access char"))
2235 (const :tag "Start radio group" (:startgroup))
2236 (const :tag "End radio group" (:endgroup))
2237 (const :tag "New line" (:newline)))))
2239 (defvar org-file-tags nil
2240 "List of tags that can be inherited by all entries in the file.
2241 The tags will be inherited if the variable `org-use-tag-inheritance'
2242 says they should be.
2243 This variable is populated from #+TAG lines.")
2245 (defcustom org-use-fast-tag-selection 'auto
2246 "Non-nil means, use fast tag selection scheme.
2247 This is a special interface to select and deselect tags with single keys.
2248 When nil, fast selection is never used.
2249 When the symbol `auto', fast selection is used if and only if selection
2250 characters for tags have been configured, either through the variable
2251 `org-tag-alist' or through a #+TAGS line in the buffer.
2252 When t, fast selection is always used and selection keys are assigned
2253 automatically if necessary."
2254 :group 'org-tags
2255 :type '(choice
2256 (const :tag "Always" t)
2257 (const :tag "Never" nil)
2258 (const :tag "When selection characters are configured" 'auto)))
2260 (defcustom org-fast-tag-selection-single-key nil
2261 "Non-nil means, fast tag selection exits after first change.
2262 When nil, you have to press RET to exit it.
2263 During fast tag selection, you can toggle this flag with `C-c'.
2264 This variable can also have the value `expert'. In this case, the window
2265 displaying the tags menu is not even shown, until you press C-c again."
2266 :group 'org-tags
2267 :type '(choice
2268 (const :tag "No" nil)
2269 (const :tag "Yes" t)
2270 (const :tag "Expert" expert)))
2272 (defvar org-fast-tag-selection-include-todo nil
2273 "Non-nil means, fast tags selection interface will also offer TODO states.
2274 This is an undocumented feature, you should not rely on it.")
2276 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2277 "The column to which tags should be indented in a headline.
2278 If this number is positive, it specifies the column. If it is negative,
2279 it means that the tags should be flushright to that column. For example,
2280 -80 works well for a normal 80 character screen."
2281 :group 'org-tags
2282 :type 'integer)
2284 (defcustom org-auto-align-tags t
2285 "Non-nil means, realign tags after pro/demotion of TODO state change.
2286 These operations change the length of a headline and therefore shift
2287 the tags around. With this options turned on, after each such operation
2288 the tags are again aligned to `org-tags-column'."
2289 :group 'org-tags
2290 :type 'boolean)
2292 (defcustom org-use-tag-inheritance t
2293 "Non-nil means, tags in levels apply also for sublevels.
2294 When nil, only the tags directly given in a specific line apply there.
2295 This may also be a list of tags that should be inherited, or a regexp that
2296 matches tags that should be inherited. Additional control is possible
2297 with the variable `org-tags-exclude-from-inheritance' which gives an
2298 explicit list of tags to be excluded from inheritance., even if the value of
2299 `org-use-tag-inheritance' would select it for inheritance.
2301 If this option is t, a match early-on in a tree can lead to a large
2302 number of matches in the subtree when constructing the agenda or creating
2303 a sparse tree. If you only want to see the first match in a tree during
2304 a search, check out the variable `org-tags-match-list-sublevels'."
2305 :group 'org-tags
2306 :type '(choice
2307 (const :tag "Not" nil)
2308 (const :tag "Always" t)
2309 (repeat :tag "Specific tags" (string :tag "Tag"))
2310 (regexp :tag "Tags matched by regexp")))
2312 (defcustom org-tags-exclude-from-inheritance nil
2313 "List of tags that should never be inherited.
2314 This is a way to exclude a few tags from inheritance. For way to do
2315 the opposite, to actively allow inheritance for selected tags,
2316 see the variable `org-use-tag-inheritance'."
2317 :group 'org-tags
2318 :type '(repeat (string :tag "Tag")))
2320 (defun org-tag-inherit-p (tag)
2321 "Check if TAG is one that should be inherited."
2322 (cond
2323 ((member tag org-tags-exclude-from-inheritance) nil)
2324 ((eq org-use-tag-inheritance t) t)
2325 ((not org-use-tag-inheritance) nil)
2326 ((stringp org-use-tag-inheritance)
2327 (string-match org-use-tag-inheritance tag))
2328 ((listp org-use-tag-inheritance)
2329 (member tag org-use-tag-inheritance))
2330 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2332 (defcustom org-tags-match-list-sublevels t
2333 "Non-nil means list also sublevels of headlines matching a search.
2334 This variable applies to tags/property searches, and also to stuck
2335 projects because this search is based on a tags match as well.
2337 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2338 the sublevels of a headline matching a tag search often also match
2339 the same search. Listing all of them can create very long lists.
2340 Setting this variable to nil causes subtrees of a match to be skipped.
2342 As a special case, if the tag search is restricted to TODO items, the
2343 value of this variable is ignored and sublevels are always checked, to
2344 make sure all corresponding TODO items find their way into the list.
2346 This variable is semi-obsolete and probably should always be true. It
2347 is better to limit inheritance to certain tags using the variables
2348 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2349 :group 'org-tags
2350 :type '(choice
2351 (const :tag "No, don't list them" nil)
2352 (const :tag "Yes, do list them" t)
2353 (const :tag "List them, indented with leading dots" indented)))
2355 (defvar org-tags-history nil
2356 "History of minibuffer reads for tags.")
2357 (defvar org-last-tags-completion-table nil
2358 "The last used completion table for tags.")
2359 (defvar org-after-tags-change-hook nil
2360 "Hook that is run after the tags in a line have changed.")
2362 (defgroup org-properties nil
2363 "Options concerning properties in Org-mode."
2364 :tag "Org Properties"
2365 :group 'org)
2367 (defcustom org-property-format "%-10s %s"
2368 "How property key/value pairs should be formatted by `indent-line'.
2369 When `indent-line' hits a property definition, it will format the line
2370 according to this format, mainly to make sure that the values are
2371 lined-up with respect to each other."
2372 :group 'org-properties
2373 :type 'string)
2375 (defcustom org-use-property-inheritance nil
2376 "Non-nil means, properties apply also for sublevels.
2378 This setting is chiefly used during property searches. Turning it on can
2379 cause significant overhead when doing a search, which is why it is not
2380 on by default.
2382 When nil, only the properties directly given in the current entry count.
2383 When t, every property is inherited. The value may also be a list of
2384 properties that should have inheritance, or a regular expression matching
2385 properties that should be inherited.
2387 However, note that some special properties use inheritance under special
2388 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2389 and the properties ending in \"_ALL\" when they are used as descriptor
2390 for valid values of a property.
2392 Note for programmers:
2393 When querying an entry with `org-entry-get', you can control if inheritance
2394 should be used. By default, `org-entry-get' looks only at the local
2395 properties. You can request inheritance by setting the inherit argument
2396 to t (to force inheritance) or to `selective' (to respect the setting
2397 in this variable)."
2398 :group 'org-properties
2399 :type '(choice
2400 (const :tag "Not" nil)
2401 (const :tag "Always" t)
2402 (repeat :tag "Specific properties" (string :tag "Property"))
2403 (regexp :tag "Properties matched by regexp")))
2405 (defun org-property-inherit-p (property)
2406 "Check if PROPERTY is one that should be inherited."
2407 (cond
2408 ((eq org-use-property-inheritance t) t)
2409 ((not org-use-property-inheritance) nil)
2410 ((stringp org-use-property-inheritance)
2411 (string-match org-use-property-inheritance property))
2412 ((listp org-use-property-inheritance)
2413 (member property org-use-property-inheritance))
2414 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2416 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2417 "The default column format, if no other format has been defined.
2418 This variable can be set on the per-file basis by inserting a line
2420 #+COLUMNS: %25ITEM ....."
2421 :group 'org-properties
2422 :type 'string)
2424 (defcustom org-columns-ellipses ".."
2425 "The ellipses to be used when a field in column view is truncated.
2426 When this is the empty string, as many characters as possible are shown,
2427 but then there will be no visual indication that the field has been truncated.
2428 When this is a string of length N, the last N characters of a truncated
2429 field are replaced by this string. If the column is narrower than the
2430 ellipses string, only part of the ellipses string will be shown."
2431 :group 'org-properties
2432 :type 'string)
2434 (defcustom org-columns-modify-value-for-display-function nil
2435 "Function that modifies values for display in column view.
2436 For example, it can be used to cut out a certain part from a time stamp.
2437 The function must take 2 arguments:
2439 column-title The title of the column (*not* the property name)
2440 value The value that should be modified.
2442 The function should return the value that should be displayed,
2443 or nil if the normal value should be used."
2444 :group 'org-properties
2445 :type 'function)
2447 (defcustom org-effort-property "Effort"
2448 "The property that is being used to keep track of effort estimates.
2449 Effort estimates given in this property need to have the format H:MM."
2450 :group 'org-properties
2451 :group 'org-progress
2452 :type '(string :tag "Property"))
2454 (defconst org-global-properties-fixed
2455 '(("VISIBILITY_ALL" . "folded children content all"))
2456 "List of property/value pairs that can be inherited by any entry.
2458 These are fixed values, for the preset properties. The user variable
2459 that can be used to add to this list is `org-global-properties'.
2461 The entries in this list are cons cells where the car is a property
2462 name and cdr is a string with the value. If the value represents
2463 multiple items like an \"_ALL\" property, separate the items by
2464 spaces.")
2466 (defcustom org-global-properties nil
2467 "List of property/value pairs that can be inherited by any entry.
2469 This list will be combined with the constant `org-global-properties-fixed'.
2471 The entries in this list are cons cells where the car is a property
2472 name and cdr is a string with the value.
2474 You can set buffer-local values for the same purpose in the variable
2475 `org-file-properties' this by adding lines like
2477 #+PROPERTY: NAME VALUE"
2478 :group 'org-properties
2479 :type '(repeat
2480 (cons (string :tag "Property")
2481 (string :tag "Value"))))
2483 (defvar org-file-properties nil
2484 "List of property/value pairs that can be inherited by any entry.
2485 Valid for the current buffer.
2486 This variable is populated from #+PROPERTY lines.")
2487 (make-variable-buffer-local 'org-file-properties)
2489 (defgroup org-agenda nil
2490 "Options concerning agenda views in Org-mode."
2491 :tag "Org Agenda"
2492 :group 'org)
2494 (defvar org-category nil
2495 "Variable used by org files to set a category for agenda display.
2496 Such files should use a file variable to set it, for example
2498 # -*- mode: org; org-category: \"ELisp\"
2500 or contain a special line
2502 #+CATEGORY: ELisp
2504 If the file does not specify a category, then file's base name
2505 is used instead.")
2506 (make-variable-buffer-local 'org-category)
2507 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2509 (defcustom org-agenda-files nil
2510 "The files to be used for agenda display.
2511 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2512 \\[org-remove-file]. You can also use customize to edit the list.
2514 If an entry is a directory, all files in that directory that are matched by
2515 `org-agenda-file-regexp' will be part of the file list.
2517 If the value of the variable is not a list but a single file name, then
2518 the list of agenda files is actually stored and maintained in that file, one
2519 agenda file per line."
2520 :group 'org-agenda
2521 :type '(choice
2522 (repeat :tag "List of files and directories" file)
2523 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2525 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2526 "Regular expression to match files for `org-agenda-files'.
2527 If any element in the list in that variable contains a directory instead
2528 of a normal file, all files in that directory that are matched by this
2529 regular expression will be included."
2530 :group 'org-agenda
2531 :type 'regexp)
2533 (defcustom org-agenda-text-search-extra-files nil
2534 "List of extra files to be searched by text search commands.
2535 These files will be search in addition to the agenda files by the
2536 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2537 Note that these files will only be searched for text search commands,
2538 not for the other agenda views like todo lists, tag searches or the weekly
2539 agenda. This variable is intended to list notes and possibly archive files
2540 that should also be searched by these two commands.
2541 In fact, if the first element in the list is the symbol `agenda-archives',
2542 than all archive files of all agenda files will be added to the search
2543 scope."
2544 :group 'org-agenda
2545 :type '(set :greedy t
2546 (const :tag "Agenda Archives" agenda-archives)
2547 (repeat :inline t (file))))
2549 (if (fboundp 'defvaralias)
2550 (defvaralias 'org-agenda-multi-occur-extra-files
2551 'org-agenda-text-search-extra-files))
2553 (defcustom org-agenda-skip-unavailable-files nil
2554 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2555 A nil value means to remove them, after a query, from the list."
2556 :group 'org-agenda
2557 :type 'boolean)
2559 (defcustom org-calendar-to-agenda-key [?c]
2560 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2561 The command `org-calendar-goto-agenda' will be bound to this key. The
2562 default is the character `c' because then `c' can be used to switch back and
2563 forth between agenda and calendar."
2564 :group 'org-agenda
2565 :type 'sexp)
2567 (defcustom org-calendar-agenda-action-key [?k]
2568 "The key to be installed in `calendar-mode-map' for agenda-action.
2569 The command `org-agenda-action' will be bound to this key. The
2570 default is the character `k' because we use the same key in the agenda."
2571 :group 'org-agenda
2572 :type 'sexp)
2574 (eval-after-load "calendar"
2575 '(progn
2576 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2577 'org-calendar-goto-agenda)
2578 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2579 'org-agenda-action)))
2581 (defgroup org-latex nil
2582 "Options for embedding LaTeX code into Org-mode."
2583 :tag "Org LaTeX"
2584 :group 'org)
2586 (defcustom org-format-latex-options
2587 '(:foreground default :background default :scale 1.0
2588 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2589 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2590 "Options for creating images from LaTeX fragments.
2591 This is a property list with the following properties:
2592 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2593 `default' means use the foreground of the default face.
2594 :background the background color, or \"Transparent\".
2595 `default' means use the background of the default face.
2596 :scale a scaling factor for the size of the images.
2597 :html-foreground, :html-background, :html-scale
2598 the same numbers for HTML export.
2599 :matchers a list indicating which matchers should be used to
2600 find LaTeX fragments. Valid members of this list are:
2601 \"begin\" find environments
2602 \"$1\" find single characters surrounded by $.$
2603 \"$\" find math expressions surrounded by $...$
2604 \"$$\" find math expressions surrounded by $$....$$
2605 \"\\(\" find math expressions surrounded by \\(...\\)
2606 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2607 :group 'org-latex
2608 :type 'plist)
2610 (defcustom org-format-latex-header "\\documentclass{article}
2611 \\usepackage{fullpage} % do not remove
2612 \\usepackage{amssymb}
2613 \\usepackage[usenames]{color}
2614 \\usepackage{amsmath}
2615 \\usepackage{latexsym}
2616 \\usepackage[mathscr]{eucal}
2617 \\pagestyle{empty} % do not remove"
2618 "The document header used for processing LaTeX fragments."
2619 :group 'org-latex
2620 :type 'string)
2623 (defgroup org-font-lock nil
2624 "Font-lock settings for highlighting in Org-mode."
2625 :tag "Org Font Lock"
2626 :group 'org)
2628 (defcustom org-level-color-stars-only nil
2629 "Non-nil means fontify only the stars in each headline.
2630 When nil, the entire headline is fontified.
2631 Changing it requires restart of `font-lock-mode' to become effective
2632 also in regions already fontified."
2633 :group 'org-font-lock
2634 :type 'boolean)
2636 (defcustom org-hide-leading-stars nil
2637 "Non-nil means, hide the first N-1 stars in a headline.
2638 This works by using the face `org-hide' for these stars. This
2639 face is white for a light background, and black for a dark
2640 background. You may have to customize the face `org-hide' to
2641 make this work.
2642 Changing it requires restart of `font-lock-mode' to become effective
2643 also in regions already fontified.
2644 You may also set this on a per-file basis by adding one of the following
2645 lines to the buffer:
2647 #+STARTUP: hidestars
2648 #+STARTUP: showstars"
2649 :group 'org-font-lock
2650 :type 'boolean)
2652 (defcustom org-fontify-done-headline nil
2653 "Non-nil means, change the face of a headline if it is marked DONE.
2654 Normally, only the TODO/DONE keyword indicates the state of a headline.
2655 When this is non-nil, the headline after the keyword is set to the
2656 `org-headline-done' as an additional indication."
2657 :group 'org-font-lock
2658 :type 'boolean)
2660 (defcustom org-fontify-emphasized-text t
2661 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2662 Changing this variable requires a restart of Emacs to take effect."
2663 :group 'org-font-lock
2664 :type 'boolean)
2666 (defcustom org-highlight-latex-fragments-and-specials nil
2667 "Non-nil means, fontify what is treated specially by the exporters."
2668 :group 'org-font-lock
2669 :type 'boolean)
2671 (defcustom org-hide-emphasis-markers nil
2672 "Non-nil mean font-lock should hide the emphasis marker characters."
2673 :group 'org-font-lock
2674 :type 'boolean)
2676 (defvar org-emph-re nil
2677 "Regular expression for matching emphasis.")
2678 (defvar org-verbatim-re nil
2679 "Regular expression for matching verbatim text.")
2680 (defvar org-emphasis-regexp-components) ; defined just below
2681 (defvar org-emphasis-alist) ; defined just below
2682 (defun org-set-emph-re (var val)
2683 "Set variable and compute the emphasis regular expression."
2684 (set var val)
2685 (when (and (boundp 'org-emphasis-alist)
2686 (boundp 'org-emphasis-regexp-components)
2687 org-emphasis-alist org-emphasis-regexp-components)
2688 (let* ((e org-emphasis-regexp-components)
2689 (pre (car e))
2690 (post (nth 1 e))
2691 (border (nth 2 e))
2692 (body (nth 3 e))
2693 (nl (nth 4 e))
2694 (body1 (concat body "*?"))
2695 (markers (mapconcat 'car org-emphasis-alist ""))
2696 (vmarkers (mapconcat
2697 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2698 org-emphasis-alist "")))
2699 ;; make sure special characters appear at the right position in the class
2700 (if (string-match "\\^" markers)
2701 (setq markers (concat (replace-match "" t t markers) "^")))
2702 (if (string-match "-" markers)
2703 (setq markers (concat (replace-match "" t t markers) "-")))
2704 (if (string-match "\\^" vmarkers)
2705 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2706 (if (string-match "-" vmarkers)
2707 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2708 (if (> nl 0)
2709 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2710 (int-to-string nl) "\\}")))
2711 ;; Make the regexp
2712 (setq org-emph-re
2713 (concat "\\([" pre "]\\|^\\)"
2714 "\\("
2715 "\\([" markers "]\\)"
2716 "\\("
2717 "[^" border "]\\|"
2718 "[^" border "]"
2719 body1
2720 "[^" border "]"
2721 "\\)"
2722 "\\3\\)"
2723 "\\([" post "]\\|$\\)"))
2724 (setq org-verbatim-re
2725 (concat "\\([" pre "]\\|^\\)"
2726 "\\("
2727 "\\([" vmarkers "]\\)"
2728 "\\("
2729 "[^" border "]\\|"
2730 "[^" border "]"
2731 body1
2732 "[^" border "]"
2733 "\\)"
2734 "\\3\\)"
2735 "\\([" post "]\\|$\\)")))))
2737 (defcustom org-emphasis-regexp-components
2738 '(" \t('\"{" "- \t.,:!?;'\")}" " \t\r\n,\"'" "." 1)
2739 "Components used to build the regular expression for emphasis.
2740 This is a list with 6 entries. Terminology: In an emphasis string
2741 like \" *strong word* \", we call the initial space PREMATCH, the final
2742 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2743 and \"trong wor\" is the body. The different components in this variable
2744 specify what is allowed/forbidden in each part:
2746 pre Chars allowed as prematch. Beginning of line will be allowed too.
2747 post Chars allowed as postmatch. End of line will be allowed too.
2748 border The chars *forbidden* as border characters.
2749 body-regexp A regexp like \".\" to match a body character. Don't use
2750 non-shy groups here, and don't allow newline here.
2751 newline The maximum number of newlines allowed in an emphasis exp.
2753 Use customize to modify this, or restart Emacs after changing it."
2754 :group 'org-font-lock
2755 :set 'org-set-emph-re
2756 :type '(list
2757 (sexp :tag "Allowed chars in pre ")
2758 (sexp :tag "Allowed chars in post ")
2759 (sexp :tag "Forbidden chars in border ")
2760 (sexp :tag "Regexp for body ")
2761 (integer :tag "number of newlines allowed")
2762 (option (boolean :tag "Please ignore this button"))))
2764 (defcustom org-emphasis-alist
2765 `(("*" bold "<b>" "</b>")
2766 ("/" italic "<i>" "</i>")
2767 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2768 ("=" org-code "<code>" "</code>" verbatim)
2769 ("~" org-verbatim "<code>" "</code>" verbatim)
2770 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2771 "<del>" "</del>")
2773 "Special syntax for emphasized text.
2774 Text starting and ending with a special character will be emphasized, for
2775 example *bold*, _underlined_ and /italic/. This variable sets the marker
2776 characters, the face to be used by font-lock for highlighting in Org-mode
2777 Emacs buffers, and the HTML tags to be used for this.
2778 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
2779 Use customize to modify this, or restart Emacs after changing it."
2780 :group 'org-font-lock
2781 :set 'org-set-emph-re
2782 :type '(repeat
2783 (list
2784 (string :tag "Marker character")
2785 (choice
2786 (face :tag "Font-lock-face")
2787 (plist :tag "Face property list"))
2788 (string :tag "HTML start tag")
2789 (string :tag "HTML end tag")
2790 (option (const verbatim)))))
2792 ;;; Miscellaneous options
2794 (defgroup org-completion nil
2795 "Completion in Org-mode."
2796 :tag "Org Completion"
2797 :group 'org)
2799 (defcustom org-completion-use-ido nil
2800 "Non-nil means, use ido completion wherever possible.
2801 Note that `ido-mode' must be active for this variable to be relevant.
2802 If you decide to turn this variable on, you might well want to turn off
2803 `org-outline-path-complete-in-steps'."
2804 :group 'org-completion
2805 :type 'boolean)
2807 (defcustom org-completion-fallback-command 'hippie-expand
2808 "The expansion command called by \\[org-complete] in normal context.
2809 Normal means, no org-mode-specific context."
2810 :group 'org-completion
2811 :type 'function)
2813 ;;; Functions and variables from ther packages
2814 ;; Declared here to avoid compiler warnings
2816 ;; XEmacs only
2817 (defvar outline-mode-menu-heading)
2818 (defvar outline-mode-menu-show)
2819 (defvar outline-mode-menu-hide)
2820 (defvar zmacs-regions) ; XEmacs regions
2822 ;; Emacs only
2823 (defvar mark-active)
2825 ;; Various packages
2826 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2827 (declare-function calendar-forward-day "cal-move" (arg))
2828 (declare-function calendar-goto-date "cal-move" (date))
2829 (declare-function calendar-goto-today "cal-move" ())
2830 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2831 (defvar calc-embedded-close-formula)
2832 (defvar calc-embedded-open-formula)
2833 (declare-function cdlatex-tab "ext:cdlatex" ())
2834 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2835 (defvar font-lock-unfontify-region-function)
2836 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2837 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2838 (defvar iswitchb-temp-buflist)
2839 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2840 (defvar org-agenda-tags-todo-honor-ignore-options)
2841 (declare-function org-agenda-skip "org-agenda" ())
2842 (declare-function org-format-agenda-item "org-agenda"
2843 (extra txt &optional category tags dotime noprefix remove-re))
2844 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2845 (declare-function org-agenda-change-all-lines "org-agenda"
2846 (newhead hdmarker &optional fixface just-this))
2847 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2848 (declare-function org-agenda-maybe-redo "org-agenda" ())
2849 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2850 (beg end))
2851 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2852 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2853 "org-agenda" (&optional end))
2855 (declare-function parse-time-string "parse-time" (string))
2856 (declare-function remember "remember" (&optional initial))
2857 (declare-function remember-buffer-desc "remember" ())
2858 (declare-function remember-finalize "remember" ())
2859 (defvar remember-save-after-remembering)
2860 (defvar remember-data-file)
2861 (defvar remember-register)
2862 (defvar remember-buffer)
2863 (defvar remember-handler-functions)
2864 (defvar remember-annotation-functions)
2865 (defvar texmathp-why)
2866 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2867 (declare-function table--at-cell-p "table" (position &optional object at-column))
2869 (defvar w3m-current-url)
2870 (defvar w3m-current-title)
2872 (defvar org-latex-regexps)
2874 ;;; Autoload and prepare some org modules
2876 ;; Some table stuff that needs to be defined here, because it is used
2877 ;; by the functions setting up org-mode or checking for table context.
2879 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2880 "Detects an org-type or table-type table.")
2881 (defconst org-table-line-regexp "^[ \t]*|"
2882 "Detects an org-type table line.")
2883 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2884 "Detects an org-type table line.")
2885 (defconst org-table-hline-regexp "^[ \t]*|-"
2886 "Detects an org-type table hline.")
2887 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2888 "Detects a table-type table hline.")
2889 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2890 "Searching from within a table (any type) this finds the first line
2891 outside the table.")
2893 ;; Autoload the functions in org-table.el that are needed by functions here.
2895 (eval-and-compile
2896 (org-autoload "org-table"
2897 '(org-table-align org-table-begin org-table-blank-field
2898 org-table-convert org-table-convert-region org-table-copy-down
2899 org-table-copy-region org-table-create
2900 org-table-create-or-convert-from-region
2901 org-table-create-with-table.el org-table-current-dline
2902 org-table-cut-region org-table-delete-column org-table-edit-field
2903 org-table-edit-formulas org-table-end org-table-eval-formula
2904 org-table-export org-table-field-info
2905 org-table-get-stored-formulas org-table-goto-column
2906 org-table-hline-and-move org-table-import org-table-insert-column
2907 org-table-insert-hline org-table-insert-row org-table-iterate
2908 org-table-justify-field-maybe org-table-kill-row
2909 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2910 org-table-move-column org-table-move-column-left
2911 org-table-move-column-right org-table-move-row
2912 org-table-move-row-down org-table-move-row-up
2913 org-table-next-field org-table-next-row org-table-paste-rectangle
2914 org-table-previous-field org-table-recalculate
2915 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2916 org-table-toggle-coordinate-overlays
2917 org-table-toggle-formula-debugger org-table-wrap-region
2918 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2920 (defun org-at-table-p (&optional table-type)
2921 "Return t if the cursor is inside an org-type table.
2922 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2923 (if org-enable-table-editor
2924 (save-excursion
2925 (beginning-of-line 1)
2926 (looking-at (if table-type org-table-any-line-regexp
2927 org-table-line-regexp)))
2928 nil))
2929 (defsubst org-table-p () (org-at-table-p))
2931 (defun org-at-table.el-p ()
2932 "Return t if and only if we are at a table.el table."
2933 (and (org-at-table-p 'any)
2934 (save-excursion
2935 (goto-char (org-table-begin 'any))
2936 (looking-at org-table1-hline-regexp))))
2937 (defun org-table-recognize-table.el ()
2938 "If there is a table.el table nearby, recognize it and move into it."
2939 (if org-table-tab-recognizes-table.el
2940 (if (org-at-table.el-p)
2941 (progn
2942 (beginning-of-line 1)
2943 (if (looking-at org-table-dataline-regexp)
2945 (if (looking-at org-table1-hline-regexp)
2946 (progn
2947 (beginning-of-line 2)
2948 (if (looking-at org-table-any-border-regexp)
2949 (beginning-of-line -1)))))
2950 (if (re-search-forward "|" (org-table-end t) t)
2951 (progn
2952 (require 'table)
2953 (if (table--at-cell-p (point))
2955 (message "recognizing table.el table...")
2956 (table-recognize-table)
2957 (message "recognizing table.el table...done")))
2958 (error "This should not happen..."))
2960 nil)
2961 nil))
2963 (defun org-at-table-hline-p ()
2964 "Return t if the cursor is inside a hline in a table."
2965 (if org-enable-table-editor
2966 (save-excursion
2967 (beginning-of-line 1)
2968 (looking-at org-table-hline-regexp))
2969 nil))
2971 (defvar org-table-clean-did-remove-column nil)
2973 (defun org-table-map-tables (function)
2974 "Apply FUNCTION to the start of all tables in the buffer."
2975 (save-excursion
2976 (save-restriction
2977 (widen)
2978 (goto-char (point-min))
2979 (while (re-search-forward org-table-any-line-regexp nil t)
2980 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2981 (beginning-of-line 1)
2982 (if (looking-at org-table-line-regexp)
2983 (save-excursion (funcall function)))
2984 (re-search-forward org-table-any-border-regexp nil 1))))
2985 (message "Mapping tables: done"))
2987 ;; Declare and autoload functions from org-exp.el & Co
2989 (declare-function org-default-export-plist "org-exp")
2990 (declare-function org-infile-export-plist "org-exp")
2991 (declare-function org-get-current-options "org-exp")
2992 (eval-and-compile
2993 (org-autoload "org-exp"
2994 '(org-export org-export-visible
2995 org-insert-export-options-template
2996 org-table-clean-before-export))
2997 (org-autoload "org-ascii"
2998 '(org-export-as-ascii org-export-ascii-preprocess
2999 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3000 org-export-region-as-ascii))
3001 (org-autoload "org-html"
3002 '(org-export-as-html-and-open
3003 org-export-as-html-batch org-export-as-html-to-buffer
3004 org-replace-region-by-html org-export-region-as-html
3005 org-export-as-html))
3006 (org-autoload "org-icalendar"
3007 '(org-export-icalendar-this-file
3008 org-export-icalendar-all-agenda-files
3009 org-export-icalendar-combine-agenda-files))
3010 (org-autoload "org-xoxo" '(org-export-as-xoxo)))
3012 ;; Declare and autoload functions from org-agenda.el
3014 (eval-and-compile
3015 (org-autoload "org-agenda"
3016 '(org-agenda org-agenda-list org-search-view
3017 org-todo-list org-tags-view org-agenda-list-stuck-projects
3018 org-diary org-agenda-to-appt
3019 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3021 ;; Autoload org-remember
3023 (eval-and-compile
3024 (org-autoload "org-remember"
3025 '(org-remember-insinuate org-remember-annotation
3026 org-remember-apply-template org-remember org-remember-handler)))
3028 ;; Autoload org-clock.el
3031 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3032 (beg end))
3033 (declare-function org-clock-update-mode-line "org-clock" ())
3034 (defvar org-clock-start-time)
3035 (defvar org-clock-marker (make-marker)
3036 "Marker recording the last clock-in.")
3038 (eval-and-compile
3039 (org-autoload
3040 "org-clock"
3041 '(org-clock-in org-clock-out org-clock-cancel
3042 org-clock-goto org-clock-sum org-clock-display
3043 org-clock-remove-overlays org-clock-report
3044 org-clocktable-shift org-dblock-write:clocktable
3045 org-get-clocktable)))
3047 (defun org-clock-update-time-maybe ()
3048 "If this is a CLOCK line, update it and return t.
3049 Otherwise, return nil."
3050 (interactive)
3051 (save-excursion
3052 (beginning-of-line 1)
3053 (skip-chars-forward " \t")
3054 (when (looking-at org-clock-string)
3055 (let ((re (concat "[ \t]*" org-clock-string
3056 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3057 "\\([ \t]*=>.*\\)?\\)?"))
3058 ts te h m s neg)
3059 (cond
3060 ((not (looking-at re))
3061 nil)
3062 ((not (match-end 2))
3063 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3064 (> org-clock-marker (point))
3065 (<= org-clock-marker (point-at-eol)))
3066 ;; The clock is running here
3067 (setq org-clock-start-time
3068 (apply 'encode-time
3069 (org-parse-time-string (match-string 1))))
3070 (org-clock-update-mode-line)))
3072 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3073 (end-of-line 1)
3074 (setq ts (match-string 1)
3075 te (match-string 3))
3076 (setq s (- (time-to-seconds
3077 (apply 'encode-time (org-parse-time-string te)))
3078 (time-to-seconds
3079 (apply 'encode-time (org-parse-time-string ts))))
3080 neg (< s 0)
3081 s (abs s)
3082 h (floor (/ s 3600))
3083 s (- s (* 3600 h))
3084 m (floor (/ s 60))
3085 s (- s (* 60 s)))
3086 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3087 t))))))
3089 (defun org-check-running-clock ()
3090 "Check if the current buffer contains the running clock.
3091 If yes, offer to stop it and to save the buffer with the changes."
3092 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3093 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3094 (buffer-name))))
3095 (org-clock-out)
3096 (when (y-or-n-p "Save changed buffer?")
3097 (save-buffer))))
3099 (defun org-clocktable-try-shift (dir n)
3100 "Check if this line starts a clock table, if yes, shift the time block."
3101 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3102 (org-clocktable-shift dir n)))
3104 ;; Autoload org-timer.el
3106 (eval-and-compile
3107 (org-autoload
3108 "org-timer"
3109 '(org-timer-start org-timer org-timer-item
3110 org-timer-change-times-in-region)))
3112 ;; Autoload org-feed.el
3114 (eval-and-compile
3115 (org-autoload
3116 "org-feed"
3117 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3120 ;; Autoload archiving code
3121 ;; The stuff that is needed for cycling and tags has to be defined here.
3123 (defgroup org-archive nil
3124 "Options concerning archiving in Org-mode."
3125 :tag "Org Archive"
3126 :group 'org-structure)
3128 (defcustom org-archive-location "%s_archive::"
3129 "The location where subtrees should be archived.
3131 The value of this variable is a string, consisting of two parts,
3132 separated by a double-colon. The first part is a filename and
3133 the second part is a headline.
3135 When the filename is omitted, archiving happens in the same file.
3136 %s in the filename will be replaced by the current file
3137 name (without the directory part). Archiving to a different file
3138 is useful to keep archived entries from contributing to the
3139 Org-mode Agenda.
3141 The archived entries will be filed as subtrees of the specified
3142 headline. When the headline is omitted, the subtrees are simply
3143 filed away at the end of the file, as top-level entries. Also in
3144 the heading you can use %s to represent the file name, this can be
3145 useful when using the same archive for a number of different files.
3147 Here are a few examples:
3148 \"%s_archive::\"
3149 If the current file is Projects.org, archive in file
3150 Projects.org_archive, as top-level trees. This is the default.
3152 \"::* Archived Tasks\"
3153 Archive in the current file, under the top-level headline
3154 \"* Archived Tasks\".
3156 \"~/org/archive.org::\"
3157 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3159 \"~/org/archive.org::From %s\"
3160 Archive in file ~/org/archive.org (absolute path), und headlines
3161 \"From FILENAME\" where file name is the current file name.
3163 \"basement::** Finished Tasks\"
3164 Archive in file ./basement (relative path), as level 3 trees
3165 below the level 2 heading \"** Finished Tasks\".
3167 You may set this option on a per-file basis by adding to the buffer a
3168 line like
3170 #+ARCHIVE: basement::** Finished Tasks
3172 You may also define it locally for a subtree by setting an ARCHIVE property
3173 in the entry. If such a property is found in an entry, or anywhere up
3174 the hierarchy, it will be used."
3175 :group 'org-archive
3176 :type 'string)
3178 (defcustom org-archive-tag "ARCHIVE"
3179 "The tag that marks a subtree as archived.
3180 An archived subtree does not open during visibility cycling, and does
3181 not contribute to the agenda listings.
3182 After changing this, font-lock must be restarted in the relevant buffers to
3183 get the proper fontification."
3184 :group 'org-archive
3185 :group 'org-keywords
3186 :type 'string)
3188 (defcustom org-agenda-skip-archived-trees t
3189 "Non-nil means, the agenda will skip any items located in archived trees.
3190 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3191 variable is no longer recommended, you should leave it at the value t.
3192 Instead, use the key `v' to cycle the archives-mode in the agenda."
3193 :group 'org-archive
3194 :group 'org-agenda-skip
3195 :type 'boolean)
3197 (defcustom org-columns-skip-arrchived-trees t
3198 "Non-nil means, irgnore archived trees when creating column view."
3199 :group 'org-archive
3200 :group 'org-properties
3201 :type 'boolean)
3203 (defcustom org-cycle-open-archived-trees nil
3204 "Non-nil means, `org-cycle' will open archived trees.
3205 An archived tree is a tree marked with the tag ARCHIVE.
3206 When nil, archived trees will stay folded. You can still open them with
3207 normal outline commands like `show-all', but not with the cycling commands."
3208 :group 'org-archive
3209 :group 'org-cycle
3210 :type 'boolean)
3212 (defcustom org-sparse-tree-open-archived-trees nil
3213 "Non-nil means sparse tree construction shows matches in archived trees.
3214 When nil, matches in these trees are highlighted, but the trees are kept in
3215 collapsed state."
3216 :group 'org-archive
3217 :group 'org-sparse-trees
3218 :type 'boolean)
3220 (defun org-cycle-hide-archived-subtrees (state)
3221 "Re-hide all archived subtrees after a visibility state change."
3222 (when (and (not org-cycle-open-archived-trees)
3223 (not (memq state '(overview folded))))
3224 (save-excursion
3225 (let* ((globalp (memq state '(contents all)))
3226 (beg (if globalp (point-min) (point)))
3227 (end (if globalp (point-max) (org-end-of-subtree t))))
3228 (org-hide-archived-subtrees beg end)
3229 (goto-char beg)
3230 (if (looking-at (concat ".*:" org-archive-tag ":"))
3231 (message "%s" (substitute-command-keys
3232 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3234 (defun org-force-cycle-archived ()
3235 "Cycle subtree even if it is archived."
3236 (interactive)
3237 (setq this-command 'org-cycle)
3238 (let ((org-cycle-open-archived-trees t))
3239 (call-interactively 'org-cycle)))
3241 (defun org-hide-archived-subtrees (beg end)
3242 "Re-hide all archived subtrees after a visibility state change."
3243 (save-excursion
3244 (let* ((re (concat ":" org-archive-tag ":")))
3245 (goto-char beg)
3246 (while (re-search-forward re end t)
3247 (and (org-on-heading-p) (hide-subtree))
3248 (org-end-of-subtree t)))))
3250 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3252 (eval-and-compile
3253 (org-autoload "org-archive"
3254 '(org-add-archive-files org-archive-subtree
3255 org-archive-to-archive-sibling org-toggle-archive-tag)))
3257 ;; Autoload Column View Code
3259 (declare-function org-columns-number-to-string "org-colview")
3260 (declare-function org-columns-get-format-and-top-level "org-colview")
3261 (declare-function org-columns-compute "org-colview")
3263 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3264 '(org-columns-number-to-string org-columns-get-format-and-top-level
3265 org-columns-compute org-agenda-columns org-columns-remove-overlays
3266 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3268 ;; Autoload ID code
3270 (declare-function org-id-store-link "org-id")
3271 (declare-function org-id-locations-load "org-id")
3272 (declare-function org-id-locations-save "org-id")
3273 (defvar org-id-track-globally)
3274 (org-autoload "org-id"
3275 '(org-id-get-create org-id-new org-id-copy org-id-get
3276 org-id-get-with-outline-path-completion
3277 org-id-get-with-outline-drilling
3278 org-id-goto org-id-find org-id-store-link))
3280 ;; Autoload Plotting Code
3282 (org-autoload "org-plot"
3283 '(org-plot/gnuplot))
3285 ;;; Variables for pre-computed regular expressions, all buffer local
3287 (defvar org-drawer-regexp nil
3288 "Matches first line of a hidden block.")
3289 (make-variable-buffer-local 'org-drawer-regexp)
3290 (defvar org-todo-regexp nil
3291 "Matches any of the TODO state keywords.")
3292 (make-variable-buffer-local 'org-todo-regexp)
3293 (defvar org-not-done-regexp nil
3294 "Matches any of the TODO state keywords except the last one.")
3295 (make-variable-buffer-local 'org-not-done-regexp)
3296 (defvar org-not-done-heading-regexp nil
3297 "Matches a TODO headline that is not done.")
3298 (make-variable-buffer-local 'org-not-done-regexp)
3299 (defvar org-todo-line-regexp nil
3300 "Matches a headline and puts TODO state into group 2 if present.")
3301 (make-variable-buffer-local 'org-todo-line-regexp)
3302 (defvar org-complex-heading-regexp nil
3303 "Matches a headline and puts everything into groups:
3304 group 1: the stars
3305 group 2: The todo keyword, maybe
3306 group 3: Priority cookie
3307 group 4: True headline
3308 group 5: Tags")
3309 (make-variable-buffer-local 'org-complex-heading-regexp)
3310 (defvar org-todo-line-tags-regexp nil
3311 "Matches a headline and puts TODO state into group 2 if present.
3312 Also put tags into group 4 if tags are present.")
3313 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3314 (defvar org-nl-done-regexp nil
3315 "Matches newline followed by a headline with the DONE keyword.")
3316 (make-variable-buffer-local 'org-nl-done-regexp)
3317 (defvar org-looking-at-done-regexp nil
3318 "Matches the DONE keyword a point.")
3319 (make-variable-buffer-local 'org-looking-at-done-regexp)
3320 (defvar org-ds-keyword-length 12
3321 "Maximum length of the Deadline and SCHEDULED keywords.")
3322 (make-variable-buffer-local 'org-ds-keyword-length)
3323 (defvar org-deadline-regexp nil
3324 "Matches the DEADLINE keyword.")
3325 (make-variable-buffer-local 'org-deadline-regexp)
3326 (defvar org-deadline-time-regexp nil
3327 "Matches the DEADLINE keyword together with a time stamp.")
3328 (make-variable-buffer-local 'org-deadline-time-regexp)
3329 (defvar org-deadline-line-regexp nil
3330 "Matches the DEADLINE keyword and the rest of the line.")
3331 (make-variable-buffer-local 'org-deadline-line-regexp)
3332 (defvar org-scheduled-regexp nil
3333 "Matches the SCHEDULED keyword.")
3334 (make-variable-buffer-local 'org-scheduled-regexp)
3335 (defvar org-scheduled-time-regexp nil
3336 "Matches the SCHEDULED keyword together with a time stamp.")
3337 (make-variable-buffer-local 'org-scheduled-time-regexp)
3338 (defvar org-closed-time-regexp nil
3339 "Matches the CLOSED keyword together with a time stamp.")
3340 (make-variable-buffer-local 'org-closed-time-regexp)
3342 (defvar org-keyword-time-regexp nil
3343 "Matches any of the 4 keywords, together with the time stamp.")
3344 (make-variable-buffer-local 'org-keyword-time-regexp)
3345 (defvar org-keyword-time-not-clock-regexp nil
3346 "Matches any of the 3 keywords, together with the time stamp.")
3347 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3348 (defvar org-maybe-keyword-time-regexp nil
3349 "Matches a timestamp, possibly preceeded by a keyword.")
3350 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3351 (defvar org-planning-or-clock-line-re nil
3352 "Matches a line with planning or clock info.")
3353 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3355 (defconst org-plain-time-of-day-regexp
3356 (concat
3357 "\\(\\<[012]?[0-9]"
3358 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3359 "\\(--?"
3360 "\\(\\<[012]?[0-9]"
3361 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3362 "\\)?")
3363 "Regular expression to match a plain time or time range.
3364 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3365 groups carry important information:
3366 0 the full match
3367 1 the first time, range or not
3368 8 the second time, if it is a range.")
3370 (defconst org-plain-time-extension-regexp
3371 (concat
3372 "\\(\\<[012]?[0-9]"
3373 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3374 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3375 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3376 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3377 groups carry important information:
3378 0 the full match
3379 7 hours of duration
3380 9 minutes of duration")
3382 (defconst org-stamp-time-of-day-regexp
3383 (concat
3384 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3385 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3386 "\\(--?"
3387 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3388 "Regular expression to match a timestamp time or time range.
3389 After a match, the following groups carry important information:
3390 0 the full match
3391 1 date plus weekday, for backreferencing to make sure both times on same day
3392 2 the first time, range or not
3393 4 the second time, if it is a range.")
3395 (defconst org-startup-options
3396 '(("fold" org-startup-folded t)
3397 ("overview" org-startup-folded t)
3398 ("nofold" org-startup-folded nil)
3399 ("showall" org-startup-folded nil)
3400 ("content" org-startup-folded content)
3401 ("hidestars" org-hide-leading-stars t)
3402 ("showstars" org-hide-leading-stars nil)
3403 ("odd" org-odd-levels-only t)
3404 ("oddeven" org-odd-levels-only nil)
3405 ("align" org-startup-align-all-tables t)
3406 ("noalign" org-startup-align-all-tables nil)
3407 ("customtime" org-display-custom-times t)
3408 ("logdone" org-log-done time)
3409 ("lognotedone" org-log-done note)
3410 ("nologdone" org-log-done nil)
3411 ("lognoteclock-out" org-log-note-clock-out t)
3412 ("nolognoteclock-out" org-log-note-clock-out nil)
3413 ("logrepeat" org-log-repeat state)
3414 ("lognoterepeat" org-log-repeat note)
3415 ("nologrepeat" org-log-repeat nil)
3416 ("fninline" org-footnote-define-inline t)
3417 ("nofninline" org-footnote-define-inline nil)
3418 ("fnlocal" org-footnote-section nil)
3419 ("fnauto" org-footnote-auto-label t)
3420 ("fnprompt" org-footnote-auto-label nil)
3421 ("fnconfirm" org-footnote-auto-label confirm)
3422 ("fnplain" org-footnote-auto-label plain)
3423 ("constcgs" constants-unit-system cgs)
3424 ("constSI" constants-unit-system SI)
3425 ("noptag" org-tag-persistent-alist nil))
3426 "Variable associated with STARTUP options for org-mode.
3427 Each element is a list of three items: The startup options as written
3428 in the #+STARTUP line, the corresponding variable, and the value to
3429 set this variable to if the option is found. An optional forth element PUSH
3430 means to push this value onto the list in the variable.")
3432 (defun org-set-regexps-and-options ()
3433 "Precompute regular expressions for current buffer."
3434 (when (org-mode-p)
3435 (org-set-local 'org-todo-kwd-alist nil)
3436 (org-set-local 'org-todo-key-alist nil)
3437 (org-set-local 'org-todo-key-trigger nil)
3438 (org-set-local 'org-todo-keywords-1 nil)
3439 (org-set-local 'org-done-keywords nil)
3440 (org-set-local 'org-todo-heads nil)
3441 (org-set-local 'org-todo-sets nil)
3442 (org-set-local 'org-todo-log-states nil)
3443 (org-set-local 'org-file-properties nil)
3444 (org-set-local 'org-file-tags nil)
3445 (let ((re (org-make-options-regexp
3446 '("CATEGORY" "TODO" "COLUMNS"
3447 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3448 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3449 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3450 (splitre "[ \t]+")
3451 kwds kws0 kwsa key log value cat arch tags const links hw dws
3452 tail sep kws1 prio props ftags drawers
3453 ext-setup-or-nil setup-contents (start 0))
3454 (save-excursion
3455 (save-restriction
3456 (widen)
3457 (goto-char (point-min))
3458 (while (or (and ext-setup-or-nil
3459 (string-match re ext-setup-or-nil start)
3460 (setq start (match-end 0)))
3461 (and (setq ext-setup-or-nil nil start 0)
3462 (re-search-forward re nil t)))
3463 (setq key (upcase (match-string 1 ext-setup-or-nil))
3464 value (org-match-string-no-properties 2 ext-setup-or-nil))
3465 (cond
3466 ((equal key "CATEGORY")
3467 (if (string-match "[ \t]+$" value)
3468 (setq value (replace-match "" t t value)))
3469 (setq cat value))
3470 ((member key '("SEQ_TODO" "TODO"))
3471 (push (cons 'sequence (org-split-string value splitre)) kwds))
3472 ((equal key "TYP_TODO")
3473 (push (cons 'type (org-split-string value splitre)) kwds))
3474 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3475 ;; general TODO-like setup
3476 (push (cons (intern (downcase (match-string 1 key)))
3477 (org-split-string value splitre)) kwds))
3478 ((equal key "TAGS")
3479 (setq tags (append tags (if tags '("\\n") nil)
3480 (org-split-string value splitre))))
3481 ((equal key "COLUMNS")
3482 (org-set-local 'org-columns-default-format value))
3483 ((equal key "LINK")
3484 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3485 (push (cons (match-string 1 value)
3486 (org-trim (match-string 2 value)))
3487 links)))
3488 ((equal key "PRIORITIES")
3489 (setq prio (org-split-string value " +")))
3490 ((equal key "PROPERTY")
3491 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3492 (push (cons (match-string 1 value) (match-string 2 value))
3493 props)))
3494 ((equal key "FILETAGS")
3495 (when (string-match "\\S-" value)
3496 (setq ftags
3497 (append
3498 ftags
3499 (apply 'append
3500 (mapcar (lambda (x) (org-split-string x ":"))
3501 (org-split-string value)))))))
3502 ((equal key "DRAWERS")
3503 (setq drawers (org-split-string value splitre)))
3504 ((equal key "CONSTANTS")
3505 (setq const (append const (org-split-string value splitre))))
3506 ((equal key "STARTUP")
3507 (let ((opts (org-split-string value splitre))
3508 l var val)
3509 (while (setq l (pop opts))
3510 (when (setq l (assoc l org-startup-options))
3511 (setq var (nth 1 l) val (nth 2 l))
3512 (if (not (nth 3 l))
3513 (set (make-local-variable var) val)
3514 (if (not (listp (symbol-value var)))
3515 (set (make-local-variable var) nil))
3516 (set (make-local-variable var) (symbol-value var))
3517 (add-to-list var val))))))
3518 ((equal key "ARCHIVE")
3519 (string-match " *$" value)
3520 (setq arch (replace-match "" t t value))
3521 (remove-text-properties 0 (length arch)
3522 '(face t fontified t) arch))
3523 ((equal key "SETUPFILE")
3524 (setq setup-contents (org-file-contents
3525 (expand-file-name
3526 (org-remove-double-quotes value))
3527 'noerror))
3528 (if (not ext-setup-or-nil)
3529 (setq ext-setup-or-nil setup-contents start 0)
3530 (setq ext-setup-or-nil
3531 (concat (substring ext-setup-or-nil 0 start)
3532 "\n" setup-contents "\n"
3533 (substring ext-setup-or-nil start)))))
3534 ))))
3535 (when cat
3536 (org-set-local 'org-category (intern cat))
3537 (push (cons "CATEGORY" cat) props))
3538 (when prio
3539 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3540 (setq prio (mapcar 'string-to-char prio))
3541 (org-set-local 'org-highest-priority (nth 0 prio))
3542 (org-set-local 'org-lowest-priority (nth 1 prio))
3543 (org-set-local 'org-default-priority (nth 2 prio)))
3544 (and props (org-set-local 'org-file-properties (nreverse props)))
3545 (and ftags (org-set-local 'org-file-tags
3546 (mapcar 'org-add-prop-inherited ftags)))
3547 (and drawers (org-set-local 'org-drawers drawers))
3548 (and arch (org-set-local 'org-archive-location arch))
3549 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3550 ;; Process the TODO keywords
3551 (unless kwds
3552 ;; Use the global values as if they had been given locally.
3553 (setq kwds (default-value 'org-todo-keywords))
3554 (if (stringp (car kwds))
3555 (setq kwds (list (cons org-todo-interpretation
3556 (default-value 'org-todo-keywords)))))
3557 (setq kwds (reverse kwds)))
3558 (setq kwds (nreverse kwds))
3559 (let (inter kws kw)
3560 (while (setq kws (pop kwds))
3561 (let ((kws (or
3562 (run-hook-with-args-until-success
3563 'org-todo-setup-filter-hook kws)
3564 kws)))
3565 (setq inter (pop kws) sep (member "|" kws)
3566 kws0 (delete "|" (copy-sequence kws))
3567 kwsa nil
3568 kws1 (mapcar
3569 (lambda (x)
3570 ;; 1 2
3571 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3572 (progn
3573 (setq kw (match-string 1 x)
3574 key (and (match-end 2) (match-string 2 x))
3575 log (org-extract-log-state-settings x))
3576 (push (cons kw (and key (string-to-char key))) kwsa)
3577 (and log (push log org-todo-log-states))
3579 (error "Invalid TODO keyword %s" x)))
3580 kws0)
3581 kwsa (if kwsa (append '((:startgroup))
3582 (nreverse kwsa)
3583 '((:endgroup))))
3584 hw (car kws1)
3585 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3586 tail (list inter hw (car dws) (org-last dws))))
3587 (add-to-list 'org-todo-heads hw 'append)
3588 (push kws1 org-todo-sets)
3589 (setq org-done-keywords (append org-done-keywords dws nil))
3590 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3591 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3592 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3593 (setq org-todo-sets (nreverse org-todo-sets)
3594 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3595 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3596 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3597 ;; Process the constants
3598 (when const
3599 (let (e cst)
3600 (while (setq e (pop const))
3601 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3602 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3603 (setq org-table-formula-constants-local cst)))
3605 ;; Process the tags.
3606 (when tags
3607 (let (e tgs)
3608 (while (setq e (pop tags))
3609 (cond
3610 ((equal e "{") (push '(:startgroup) tgs))
3611 ((equal e "}") (push '(:endgroup) tgs))
3612 ((equal e "\\n") (push '(:newline) tgs))
3613 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3614 (push (cons (match-string 1 e)
3615 (string-to-char (match-string 2 e)))
3616 tgs))
3617 (t (push (list e) tgs))))
3618 (org-set-local 'org-tag-alist nil)
3619 (while (setq e (pop tgs))
3620 (or (and (stringp (car e))
3621 (assoc (car e) org-tag-alist))
3622 (push e org-tag-alist)))))
3624 ;; Compute the regular expressions and other local variables
3625 (if (not org-done-keywords)
3626 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3627 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3628 (length org-scheduled-string)
3629 (length org-clock-string)
3630 (length org-closed-string)))
3631 org-drawer-regexp
3632 (concat "^[ \t]*:\\("
3633 (mapconcat 'regexp-quote org-drawers "\\|")
3634 "\\):[ \t]*$")
3635 org-not-done-keywords
3636 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3637 org-todo-regexp
3638 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3639 "\\|") "\\)\\>")
3640 org-not-done-regexp
3641 (concat "\\<\\("
3642 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3643 "\\)\\>")
3644 org-not-done-heading-regexp
3645 (concat "^\\(\\*+\\)[ \t]+\\("
3646 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3647 "\\)\\>")
3648 org-todo-line-regexp
3649 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3650 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3651 "\\)\\>\\)?[ \t]*\\(.*\\)")
3652 org-complex-heading-regexp
3653 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3654 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3655 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3656 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3657 org-nl-done-regexp
3658 (concat "\n\\*+[ \t]+"
3659 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3660 "\\)" "\\>")
3661 org-todo-line-tags-regexp
3662 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3663 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3664 (org-re
3665 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3666 org-looking-at-done-regexp
3667 (concat "^" "\\(?:"
3668 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3669 "\\>")
3670 org-deadline-regexp (concat "\\<" org-deadline-string)
3671 org-deadline-time-regexp
3672 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3673 org-deadline-line-regexp
3674 (concat "\\<\\(" org-deadline-string "\\).*")
3675 org-scheduled-regexp
3676 (concat "\\<" org-scheduled-string)
3677 org-scheduled-time-regexp
3678 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3679 org-closed-time-regexp
3680 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3681 org-keyword-time-regexp
3682 (concat "\\<\\(" org-scheduled-string
3683 "\\|" org-deadline-string
3684 "\\|" org-closed-string
3685 "\\|" org-clock-string "\\)"
3686 " *[[<]\\([^]>]+\\)[]>]")
3687 org-keyword-time-not-clock-regexp
3688 (concat "\\<\\(" org-scheduled-string
3689 "\\|" org-deadline-string
3690 "\\|" org-closed-string
3691 "\\)"
3692 " *[[<]\\([^]>]+\\)[]>]")
3693 org-maybe-keyword-time-regexp
3694 (concat "\\(\\<\\(" org-scheduled-string
3695 "\\|" org-deadline-string
3696 "\\|" org-closed-string
3697 "\\|" org-clock-string "\\)\\)?"
3698 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3699 org-planning-or-clock-line-re
3700 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3701 "\\|" org-deadline-string
3702 "\\|" org-closed-string "\\|" org-clock-string
3703 "\\)\\>\\)")
3705 (org-compute-latex-and-specials-regexp)
3706 (org-set-font-lock-defaults))))
3708 (defun org-file-contents (file &optional noerror)
3709 "Return the contents of FILE, as a string."
3710 (if (or (not file)
3711 (not (file-readable-p file)))
3712 (if noerror
3713 (progn
3714 (message "Cannot read file %s" file)
3715 (ding) (sit-for 2)
3717 (error "Cannot read file %s" file))
3718 (with-temp-buffer
3719 (insert-file-contents file)
3720 (buffer-string))))
3722 (defun org-extract-log-state-settings (x)
3723 "Extract the log state setting from a TODO keyword string.
3724 This will extract info from a string like \"WAIT(w@/!)\"."
3725 (let (kw key log1 log2)
3726 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3727 (setq kw (match-string 1 x)
3728 key (and (match-end 2) (match-string 2 x))
3729 log1 (and (match-end 3) (match-string 3 x))
3730 log2 (and (match-end 4) (match-string 4 x)))
3731 (and (or log1 log2)
3732 (list kw
3733 (and log1 (if (equal log1 "!") 'time 'note))
3734 (and log2 (if (equal log2 "!") 'time 'note)))))))
3736 (defun org-remove-keyword-keys (list)
3737 "Remove a pair of parenthesis at the end of each string in LIST."
3738 (mapcar (lambda (x)
3739 (if (string-match "(.*)$" x)
3740 (substring x 0 (match-beginning 0))
3742 list))
3744 ;; FIXME: this could be done much better, using second characters etc.
3745 (defun org-assign-fast-keys (alist)
3746 "Assign fast keys to a keyword-key alist.
3747 Respect keys that are already there."
3748 (let (new e k c c1 c2 (char ?a))
3749 (while (setq e (pop alist))
3750 (cond
3751 ((equal e '(:startgroup)) (push e new))
3752 ((equal e '(:endgroup)) (push e new))
3753 ((equal e '(:newline)) (push e new))
3755 (setq k (car e) c2 nil)
3756 (if (cdr e)
3757 (setq c (cdr e))
3758 ;; automatically assign a character.
3759 (setq c1 (string-to-char
3760 (downcase (substring
3761 k (if (= (string-to-char k) ?@) 1 0)))))
3762 (if (or (rassoc c1 new) (rassoc c1 alist))
3763 (while (or (rassoc char new) (rassoc char alist))
3764 (setq char (1+ char)))
3765 (setq c2 c1))
3766 (setq c (or c2 char)))
3767 (push (cons k c) new))))
3768 (nreverse new)))
3770 ;;; Some variables used in various places
3772 (defvar org-window-configuration nil
3773 "Used in various places to store a window configuration.")
3774 (defvar org-finish-function nil
3775 "Function to be called when `C-c C-c' is used.
3776 This is for getting out of special buffers like remember.")
3779 ;; FIXME: Occasionally check by commenting these, to make sure
3780 ;; no other functions uses these, forgetting to let-bind them.
3781 (defvar entry)
3782 (defvar state)
3783 (defvar last-state)
3784 (defvar date)
3785 (defvar description)
3787 ;; Defined somewhere in this file, but used before definition.
3788 (defvar org-html-entities)
3789 (defvar org-struct-menu)
3790 (defvar org-org-menu)
3791 (defvar org-tbl-menu)
3792 (defvar org-agenda-keymap)
3794 ;;;; Define the Org-mode
3796 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3797 (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."))
3800 ;; We use a before-change function to check if a table might need
3801 ;; an update.
3802 (defvar org-table-may-need-update t
3803 "Indicates that a table might need an update.
3804 This variable is set by `org-before-change-function'.
3805 `org-table-align' sets it back to nil.")
3806 (defun org-before-change-function (beg end)
3807 "Every change indicates that a table might need an update."
3808 (setq org-table-may-need-update t))
3809 (defvar org-mode-map)
3810 (defvar org-mode-hook nil
3811 "Mode hook for Org-mode, run after the mode was turned on.")
3812 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3813 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3814 (defvar org-table-buffer-is-an nil)
3815 (defconst org-outline-regexp "\\*+ ")
3817 ;;;###autoload
3818 (define-derived-mode org-mode outline-mode "Org"
3819 "Outline-based notes management and organizer, alias
3820 \"Carsten's outline-mode for keeping track of everything.\"
3822 Org-mode develops organizational tasks around a NOTES file which
3823 contains information about projects as plain text. Org-mode is
3824 implemented on top of outline-mode, which is ideal to keep the content
3825 of large files well structured. It supports ToDo items, deadlines and
3826 time stamps, which magically appear in the diary listing of the Emacs
3827 calendar. Tables are easily created with a built-in table editor.
3828 Plain text URL-like links connect to websites, emails (VM), Usenet
3829 messages (Gnus), BBDB entries, and any files related to the project.
3830 For printing and sharing of notes, an Org-mode file (or a part of it)
3831 can be exported as a structured ASCII or HTML file.
3833 The following commands are available:
3835 \\{org-mode-map}"
3837 ;; Get rid of Outline menus, they are not needed
3838 ;; Need to do this here because define-derived-mode sets up
3839 ;; the keymap so late. Still, it is a waste to call this each time
3840 ;; we switch another buffer into org-mode.
3841 (if (featurep 'xemacs)
3842 (when (boundp 'outline-mode-menu-heading)
3843 ;; Assume this is Greg's port, it used easymenu
3844 (easy-menu-remove outline-mode-menu-heading)
3845 (easy-menu-remove outline-mode-menu-show)
3846 (easy-menu-remove outline-mode-menu-hide))
3847 (define-key org-mode-map [menu-bar headings] 'undefined)
3848 (define-key org-mode-map [menu-bar hide] 'undefined)
3849 (define-key org-mode-map [menu-bar show] 'undefined))
3851 (org-load-modules-maybe)
3852 (easy-menu-add org-org-menu)
3853 (easy-menu-add org-tbl-menu)
3854 (org-install-agenda-files-menu)
3855 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3856 (org-add-to-invisibility-spec '(org-cwidth))
3857 (when (featurep 'xemacs)
3858 (org-set-local 'line-move-ignore-invisible t))
3859 (org-set-local 'outline-regexp org-outline-regexp)
3860 (org-set-local 'outline-level 'org-outline-level)
3861 (when (and org-ellipsis
3862 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3863 (fboundp 'make-glyph-code))
3864 (unless org-display-table
3865 (setq org-display-table (make-display-table)))
3866 (set-display-table-slot
3867 org-display-table 4
3868 (vconcat (mapcar
3869 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3870 org-ellipsis)))
3871 (if (stringp org-ellipsis) org-ellipsis "..."))))
3872 (setq buffer-display-table org-display-table))
3873 (org-set-regexps-and-options)
3874 (when (and org-tag-faces (not org-tags-special-faces-re))
3875 ;; tag faces set outside customize.... force initialization.
3876 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3877 ;; Calc embedded
3878 (org-set-local 'calc-embedded-open-mode "# ")
3879 (modify-syntax-entry ?# "<")
3880 (modify-syntax-entry ?@ "w")
3881 (if org-startup-truncated (setq truncate-lines t))
3882 (org-set-local 'font-lock-unfontify-region-function
3883 'org-unfontify-region)
3884 ;; Activate before-change-function
3885 (org-set-local 'org-table-may-need-update t)
3886 (org-add-hook 'before-change-functions 'org-before-change-function nil
3887 'local)
3888 ;; Check for running clock before killing a buffer
3889 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3890 ;; Paragraphs and auto-filling
3891 (org-set-autofill-regexps)
3892 (setq indent-line-function 'org-indent-line-function)
3893 (org-update-radio-target-regexp)
3894 ;; Make sure dependence stuff works reliably, even for users who set it
3895 ;; too late :-(
3896 (if org-enforce-todo-dependencies
3897 (add-hook 'org-blocker-hook
3898 'org-block-todo-from-children-or-siblings-or-parent)
3899 (remove-hook 'org-blocker-hook
3900 'org-block-todo-from-children-or-siblings-or-parent))
3901 (if org-enforce-todo-checkbox-dependencies
3902 (add-hook 'org-blocker-hook
3903 'org-block-todo-from-checkboxes)
3904 (remove-hook 'org-blocker-hook
3905 'org-block-todo-from-checkboxes))
3907 ;; Comment characters
3908 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3909 (org-set-local 'comment-padding " ")
3911 ;; Align options lines
3912 (org-set-local
3913 'align-mode-rules-list
3914 '((org-in-buffer-settings
3915 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3916 (modes . '(org-mode)))))
3918 ;; Imenu
3919 (org-set-local 'imenu-create-index-function
3920 'org-imenu-get-tree)
3922 ;; Make isearch reveal context
3923 (if (or (featurep 'xemacs)
3924 (not (boundp 'outline-isearch-open-invisible-function)))
3925 ;; Emacs 21 and XEmacs make use of the hook
3926 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3927 ;; Emacs 22 deals with this through a special variable
3928 (org-set-local 'outline-isearch-open-invisible-function
3929 (lambda (&rest ignore) (org-show-context 'isearch))))
3931 ;; If empty file that did not turn on org-mode automatically, make it to.
3932 (if (and org-insert-mode-line-in-empty-file
3933 (interactive-p)
3934 (= (point-min) (point-max)))
3935 (insert "# -*- mode: org -*-\n\n"))
3937 (unless org-inhibit-startup
3938 (when org-startup-align-all-tables
3939 (let ((bmp (buffer-modified-p)))
3940 (org-table-map-tables 'org-table-align)
3941 (set-buffer-modified-p bmp)))
3942 (org-set-startup-visibility)))
3944 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3946 (defun org-current-time ()
3947 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3948 (if (> (car org-time-stamp-rounding-minutes) 1)
3949 (let ((r (car org-time-stamp-rounding-minutes))
3950 (time (decode-time)))
3951 (apply 'encode-time
3952 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3953 (nthcdr 2 time))))
3954 (current-time)))
3956 ;;;; Font-Lock stuff, including the activators
3958 (defvar org-mouse-map (make-sparse-keymap))
3959 (org-defkey org-mouse-map
3960 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3961 (org-defkey org-mouse-map
3962 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3963 (when org-mouse-1-follows-link
3964 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3965 (when org-tab-follows-link
3966 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3967 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3969 (require 'font-lock)
3971 (defconst org-non-link-chars "]\t\n\r<>")
3972 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3973 "shell" "elisp"))
3974 (defvar org-link-types-re nil
3975 "Matches a link that has a url-like prefix like \"http:\"")
3976 (defvar org-link-re-with-space nil
3977 "Matches a link with spaces, optional angular brackets around it.")
3978 (defvar org-link-re-with-space2 nil
3979 "Matches a link with spaces, optional angular brackets around it.")
3980 (defvar org-link-re-with-space3 nil
3981 "Matches a link with spaces, only for internal part in bracket links.")
3982 (defvar org-angle-link-re nil
3983 "Matches link with angular brackets, spaces are allowed.")
3984 (defvar org-plain-link-re nil
3985 "Matches plain link, without spaces.")
3986 (defvar org-bracket-link-regexp nil
3987 "Matches a link in double brackets.")
3988 (defvar org-bracket-link-analytic-regexp nil
3989 "Regular expression used to analyze links.
3990 Here is what the match groups contain after a match:
3991 1: http:
3992 2: http
3993 3: path
3994 4: [desc]
3995 5: desc")
3996 (defvar org-bracket-link-analytic-regexp++ nil
3997 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3998 (defvar org-any-link-re nil
3999 "Regular expression matching any link.")
4001 (defun org-make-link-regexps ()
4002 "Update the link regular expressions.
4003 This should be called after the variable `org-link-types' has changed."
4004 (setq org-link-types-re
4005 (concat
4006 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
4007 org-link-re-with-space
4008 (concat
4009 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4010 "\\([^" org-non-link-chars " ]"
4011 "[^" org-non-link-chars "]*"
4012 "[^" org-non-link-chars " ]\\)>?")
4013 org-link-re-with-space2
4014 (concat
4015 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4016 "\\([^" org-non-link-chars " ]"
4017 "[^\t\n\r]*"
4018 "[^" org-non-link-chars " ]\\)>?")
4019 org-link-re-with-space3
4020 (concat
4021 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4022 "\\([^" org-non-link-chars " ]"
4023 "[^\t\n\r]*\\)")
4024 org-angle-link-re
4025 (concat
4026 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4027 "\\([^" org-non-link-chars " ]"
4028 "[^" org-non-link-chars "]*"
4029 "\\)>")
4030 org-plain-link-re
4031 (concat
4032 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4033 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4034 org-bracket-link-regexp
4035 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4036 org-bracket-link-analytic-regexp
4037 (concat
4038 "\\[\\["
4039 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4040 "\\([^]]+\\)"
4041 "\\]"
4042 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4043 "\\]")
4044 org-bracket-link-analytic-regexp++
4045 (concat
4046 "\\[\\["
4047 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4048 "\\([^]]+\\)"
4049 "\\]"
4050 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4051 "\\]")
4052 org-any-link-re
4053 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4054 org-angle-link-re "\\)\\|\\("
4055 org-plain-link-re "\\)")))
4057 (org-make-link-regexps)
4059 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4060 "Regular expression for fast time stamp matching.")
4061 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4062 "Regular expression for fast time stamp matching.")
4063 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4064 "Regular expression matching time strings for analysis.
4065 This one does not require the space after the date, so it can be used
4066 on a string that terminates immediately after the date.")
4067 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4068 "Regular expression matching time strings for analysis.")
4069 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4070 "Regular expression matching time stamps, with groups.")
4071 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4072 "Regular expression matching time stamps (also [..]), with groups.")
4073 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4074 "Regular expression matching a time stamp range.")
4075 (defconst org-tr-regexp-both
4076 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4077 "Regular expression matching a time stamp range.")
4078 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4079 org-ts-regexp "\\)?")
4080 "Regular expression matching a time stamp or time stamp range.")
4081 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4082 org-ts-regexp-both "\\)?")
4083 "Regular expression matching a time stamp or time stamp range.
4084 The time stamps may be either active or inactive.")
4086 (defvar org-emph-face nil)
4088 (defun org-do-emphasis-faces (limit)
4089 "Run through the buffer and add overlays to links."
4090 (let (rtn)
4091 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4092 (if (not (= (char-after (match-beginning 3))
4093 (char-after (match-beginning 4))))
4094 (progn
4095 (setq rtn t)
4096 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4097 'face
4098 (nth 1 (assoc (match-string 3)
4099 org-emphasis-alist)))
4100 (add-text-properties (match-beginning 2) (match-end 2)
4101 '(font-lock-multiline t))
4102 (when org-hide-emphasis-markers
4103 (add-text-properties (match-end 4) (match-beginning 5)
4104 '(invisible org-link))
4105 (add-text-properties (match-beginning 3) (match-end 3)
4106 '(invisible org-link)))))
4107 (backward-char 1))
4108 rtn))
4110 (defun org-emphasize (&optional char)
4111 "Insert or change an emphasis, i.e. a font like bold or italic.
4112 If there is an active region, change that region to a new emphasis.
4113 If there is no region, just insert the marker characters and position
4114 the cursor between them.
4115 CHAR should be either the marker character, or the first character of the
4116 HTML tag associated with that emphasis. If CHAR is a space, the means
4117 to remove the emphasis of the selected region.
4118 If char is not given (for example in an interactive call) it
4119 will be prompted for."
4120 (interactive)
4121 (let ((eal org-emphasis-alist) e det
4122 (erc org-emphasis-regexp-components)
4123 (prompt "")
4124 (string "") beg end move tag c s)
4125 (if (org-region-active-p)
4126 (setq beg (region-beginning) end (region-end)
4127 string (buffer-substring beg end))
4128 (setq move t))
4130 (while (setq e (pop eal))
4131 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4132 c (aref tag 0))
4133 (push (cons c (string-to-char (car e))) det)
4134 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4135 (substring tag 1)))))
4136 (setq det (nreverse det))
4137 (unless char
4138 (message "%s" (concat "Emphasis marker or tag:" prompt))
4139 (setq char (read-char-exclusive)))
4140 (setq char (or (cdr (assoc char det)) char))
4141 (if (equal char ?\ )
4142 (setq s "" move nil)
4143 (unless (assoc (char-to-string char) org-emphasis-alist)
4144 (error "No such emphasis marker: \"%c\"" char))
4145 (setq s (char-to-string char)))
4146 (while (and (> (length string) 1)
4147 (equal (substring string 0 1) (substring string -1))
4148 (assoc (substring string 0 1) org-emphasis-alist))
4149 (setq string (substring string 1 -1)))
4150 (setq string (concat s string s))
4151 (if beg (delete-region beg end))
4152 (unless (or (bolp)
4153 (string-match (concat "[" (nth 0 erc) "\n]")
4154 (char-to-string (char-before (point)))))
4155 (insert " "))
4156 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4157 (char-to-string (char-after (point))))
4158 (insert " ") (backward-char 1))
4159 (insert string)
4160 (and move (backward-char 1))))
4162 (defconst org-nonsticky-props
4163 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4165 (defsubst org-rear-nonsticky-at (pos)
4166 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4168 (defun org-activate-plain-links (limit)
4169 "Run through the buffer and add overlays to links."
4170 (catch 'exit
4171 (let (f)
4172 (while (re-search-forward org-plain-link-re limit t)
4173 (setq f (get-text-property (match-beginning 0) 'face))
4174 (if (or (eq f 'org-tag)
4175 (and (listp f) (memq 'org-tag f)))
4177 (add-text-properties (match-beginning 0) (match-end 0)
4178 (list 'mouse-face 'highlight
4179 'keymap org-mouse-map))
4180 (org-rear-nonsticky-at (match-end 0))
4181 (throw 'exit t))))))
4183 (defun org-activate-code (limit)
4184 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4185 (progn
4186 (remove-text-properties (match-beginning 0) (match-end 0)
4187 '(display t invisible t intangible t))
4188 t)))
4190 (defun org-activate-angle-links (limit)
4191 "Run through the buffer and add overlays to links."
4192 (if (re-search-forward org-angle-link-re limit t)
4193 (progn
4194 (add-text-properties (match-beginning 0) (match-end 0)
4195 (list 'mouse-face 'highlight
4196 'keymap org-mouse-map))
4197 (org-rear-nonsticky-at (match-end 0))
4198 t)))
4200 (defun org-activate-footnote-links (limit)
4201 "Run through the buffer and add overlays to links."
4202 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4203 limit t)
4204 (progn
4205 (add-text-properties (match-beginning 2) (match-end 2)
4206 (list 'mouse-face 'highlight
4207 'keymap org-mouse-map
4208 'help-echo
4209 (if (= (point-at-bol) (match-beginning 2))
4210 "Footnote definition"
4211 "Footnote reference")
4213 (org-rear-nonsticky-at (match-end 2))
4214 t)))
4216 (defun org-activate-bracket-links (limit)
4217 "Run through the buffer and add overlays to bracketed links."
4218 (if (re-search-forward org-bracket-link-regexp limit t)
4219 (let* ((help (concat "LINK: "
4220 (org-match-string-no-properties 1)))
4221 ;; FIXME: above we should remove the escapes.
4222 ;; but that requires another match, protecting match data,
4223 ;; a lot of overhead for font-lock.
4224 (ip (org-maybe-intangible
4225 (list 'invisible 'org-link
4226 'keymap org-mouse-map 'mouse-face 'highlight
4227 'font-lock-multiline t 'help-echo help)))
4228 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4229 'font-lock-multiline t 'help-echo help)))
4230 ;; We need to remove the invisible property here. Table narrowing
4231 ;; may have made some of this invisible.
4232 (remove-text-properties (match-beginning 0) (match-end 0)
4233 '(invisible nil))
4234 (if (match-end 3)
4235 (progn
4236 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4237 (org-rear-nonsticky-at (match-beginning 3))
4238 (add-text-properties (match-beginning 3) (match-end 3) vp)
4239 (org-rear-nonsticky-at (match-end 3))
4240 (add-text-properties (match-end 3) (match-end 0) ip)
4241 (org-rear-nonsticky-at (match-end 0)))
4242 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4243 (org-rear-nonsticky-at (match-beginning 1))
4244 (add-text-properties (match-beginning 1) (match-end 1) vp)
4245 (org-rear-nonsticky-at (match-end 1))
4246 (add-text-properties (match-end 1) (match-end 0) ip)
4247 (org-rear-nonsticky-at (match-end 0)))
4248 t)))
4250 (defun org-activate-dates (limit)
4251 "Run through the buffer and add overlays to dates."
4252 (if (re-search-forward org-tsr-regexp-both limit t)
4253 (progn
4254 (add-text-properties (match-beginning 0) (match-end 0)
4255 (list 'mouse-face 'highlight
4256 'keymap org-mouse-map))
4257 (org-rear-nonsticky-at (match-end 0))
4258 (when org-display-custom-times
4259 (if (match-end 3)
4260 (org-display-custom-time (match-beginning 3) (match-end 3)))
4261 (org-display-custom-time (match-beginning 1) (match-end 1)))
4262 t)))
4264 (defvar org-target-link-regexp nil
4265 "Regular expression matching radio targets in plain text.")
4266 (make-variable-buffer-local 'org-target-link-regexp)
4267 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4268 "Regular expression matching a link target.")
4269 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4270 "Regular expression matching a radio target.")
4271 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4272 "Regular expression matching any target.")
4274 (defun org-activate-target-links (limit)
4275 "Run through the buffer and add overlays to target matches."
4276 (when org-target-link-regexp
4277 (let ((case-fold-search t))
4278 (if (re-search-forward org-target-link-regexp limit t)
4279 (progn
4280 (add-text-properties (match-beginning 0) (match-end 0)
4281 (list 'mouse-face 'highlight
4282 'keymap org-mouse-map
4283 'help-echo "Radio target link"
4284 'org-linked-text t))
4285 (org-rear-nonsticky-at (match-end 0))
4286 t)))))
4288 (defun org-update-radio-target-regexp ()
4289 "Find all radio targets in this file and update the regular expression."
4290 (interactive)
4291 (when (memq 'radio org-activate-links)
4292 (setq org-target-link-regexp
4293 (org-make-target-link-regexp (org-all-targets 'radio)))
4294 (org-restart-font-lock)))
4296 (defun org-hide-wide-columns (limit)
4297 (let (s e)
4298 (setq s (text-property-any (point) (or limit (point-max))
4299 'org-cwidth t))
4300 (when s
4301 (setq e (next-single-property-change s 'org-cwidth))
4302 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4303 (goto-char e)
4304 t)))
4306 (defvar org-latex-and-specials-regexp nil
4307 "Regular expression for highlighting export special stuff.")
4308 (defvar org-match-substring-regexp)
4309 (defvar org-match-substring-with-braces-regexp)
4310 (defvar org-export-html-special-string-regexps)
4312 (defun org-compute-latex-and-specials-regexp ()
4313 "Compute regular expression for stuff treated specially by exporters."
4314 (if (not org-highlight-latex-fragments-and-specials)
4315 (org-set-local 'org-latex-and-specials-regexp nil)
4316 (require 'org-exp)
4317 (let*
4318 ((matchers (plist-get org-format-latex-options :matchers))
4319 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4320 org-latex-regexps)))
4321 (options (org-combine-plists (org-default-export-plist)
4322 (org-infile-export-plist)))
4323 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4324 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4325 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4326 (org-export-html-expand (plist-get options :expand-quoted-html))
4327 (org-export-with-special-strings (plist-get options :special-strings))
4328 (re-sub
4329 (cond
4330 ((equal org-export-with-sub-superscripts '{})
4331 (list org-match-substring-with-braces-regexp))
4332 (org-export-with-sub-superscripts
4333 (list org-match-substring-regexp))
4334 (t nil)))
4335 (re-latex
4336 (if org-export-with-LaTeX-fragments
4337 (mapcar (lambda (x) (nth 1 x)) latexs)))
4338 (re-macros
4339 (if org-export-with-TeX-macros
4340 (list (concat "\\\\"
4341 (regexp-opt
4342 (append (mapcar 'car org-html-entities)
4343 (if (boundp 'org-latex-entities)
4344 org-latex-entities nil))
4345 'words))) ; FIXME
4347 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4348 (re-special (if org-export-with-special-strings
4349 (mapcar (lambda (x) (car x))
4350 org-export-html-special-string-regexps)))
4351 (re-rest
4352 (delq nil
4353 (list
4354 (if org-export-html-expand "@<[^>\n]+>")
4355 ))))
4356 (org-set-local
4357 'org-latex-and-specials-regexp
4358 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4359 re-rest) "\\|")))))
4361 (defun org-do-latex-and-special-faces (limit)
4362 "Run through the buffer and add overlays to links."
4363 (when org-latex-and-specials-regexp
4364 (let (rtn d)
4365 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4366 limit t))
4367 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4368 'face))
4369 '(org-code org-verbatim underline)))
4370 (progn
4371 (setq rtn t
4372 d (cond ((member (char-after (1+ (match-beginning 0)))
4373 '(?_ ?^)) 1)
4374 (t 0)))
4375 (font-lock-prepend-text-property
4376 (+ d (match-beginning 0)) (match-end 0)
4377 'face 'org-latex-and-export-specials)
4378 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4379 '(font-lock-multiline t)))))
4380 rtn)))
4382 (defun org-restart-font-lock ()
4383 "Restart font-lock-mode, to force refontification."
4384 (when (and (boundp 'font-lock-mode) font-lock-mode)
4385 (font-lock-mode -1)
4386 (font-lock-mode 1)))
4388 (defun org-all-targets (&optional radio)
4389 "Return a list of all targets in this file.
4390 With optional argument RADIO, only find radio targets."
4391 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4392 rtn)
4393 (save-excursion
4394 (goto-char (point-min))
4395 (while (re-search-forward re nil t)
4396 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4397 rtn)))
4399 (defun org-make-target-link-regexp (targets)
4400 "Make regular expression matching all strings in TARGETS.
4401 The regular expression finds the targets also if there is a line break
4402 between words."
4403 (and targets
4404 (concat
4405 "\\<\\("
4406 (mapconcat
4407 (lambda (x)
4408 (while (string-match " +" x)
4409 (setq x (replace-match "\\s-+" t t x)))
4411 targets
4412 "\\|")
4413 "\\)\\>")))
4415 (defun org-activate-tags (limit)
4416 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4417 (progn
4418 (add-text-properties (match-beginning 1) (match-end 1)
4419 (list 'mouse-face 'highlight
4420 'keymap org-mouse-map))
4421 (org-rear-nonsticky-at (match-end 1))
4422 t)))
4424 (defun org-outline-level ()
4425 (save-excursion
4426 (looking-at outline-regexp)
4427 (if (match-beginning 1)
4428 (+ (org-get-string-indentation (match-string 1)) 1000)
4429 (1- (- (match-end 0) (match-beginning 0))))))
4431 (defvar org-font-lock-keywords nil)
4433 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4434 "Regular expression matching a property line.")
4436 (defvar org-font-lock-hook nil
4437 "Functions to be called for special font lock stuff.")
4439 (defun org-font-lock-hook (limit)
4440 (run-hook-with-args 'org-font-lock-hook limit))
4442 (defun org-set-font-lock-defaults ()
4443 (let* ((em org-fontify-emphasized-text)
4444 (lk org-activate-links)
4445 (org-font-lock-extra-keywords
4446 (list
4447 ;; Call the hook
4448 '(org-font-lock-hook)
4449 ;; Headlines
4450 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4451 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4452 ;; Table lines
4453 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4454 (1 'org-table t))
4455 ;; Table internals
4456 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4457 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4458 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4459 ;; Drawers
4460 (list org-drawer-regexp '(0 'org-special-keyword t))
4461 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4462 ;; Properties
4463 (list org-property-re
4464 '(1 'org-special-keyword t)
4465 '(3 'org-property-value t))
4466 (if org-format-transports-properties-p
4467 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4468 ;; Links
4469 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4470 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4471 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4472 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4473 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4474 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4475 (if (memq 'footnote lk) '(org-activate-footnote-links
4476 (2 'org-footnote t)))
4477 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4478 '(org-hide-wide-columns (0 nil append))
4479 ;; TODO lines
4480 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4481 '(1 (org-get-todo-face 1) t))
4482 ;; DONE
4483 (if org-fontify-done-headline
4484 (list (concat "^[*]+ +\\<\\("
4485 (mapconcat 'regexp-quote org-done-keywords "\\|")
4486 "\\)\\(.*\\)")
4487 '(2 'org-headline-done t))
4488 nil)
4489 ;; Priorities
4490 '(org-font-lock-add-priority-faces)
4491 ;; Tags
4492 '(org-font-lock-add-tag-faces)
4493 ;; Special keywords
4494 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4495 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4496 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4497 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4498 ;; Emphasis
4499 (if em
4500 (if (featurep 'xemacs)
4501 '(org-do-emphasis-faces (0 nil append))
4502 '(org-do-emphasis-faces)))
4503 ;; Checkboxes
4504 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4505 2 'org-checkbox prepend)
4506 (if org-provide-checkbox-statistics
4507 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4508 (0 (org-get-checkbox-statistics-face) t)))
4509 ;; Description list items
4510 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4511 2 'bold prepend)
4512 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4513 '(1 'org-archived prepend))
4514 ;; Specials
4515 '(org-do-latex-and-special-faces)
4516 ;; Code
4517 '(org-activate-code (1 'org-code t))
4518 ;; COMMENT
4519 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4520 "\\|" org-quote-string "\\)\\>")
4521 '(1 'org-special-keyword t))
4522 '("^#.*" (0 'font-lock-comment-face t))
4524 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4525 ;; Now set the full font-lock-keywords
4526 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4527 (org-set-local 'font-lock-defaults
4528 '(org-font-lock-keywords t nil nil backward-paragraph))
4529 (kill-local-variable 'font-lock-keywords) nil))
4531 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
4532 "Fontify string S like in Org-mode"
4533 (with-temp-buffer
4534 (insert s)
4535 (let ((org-odd-levels-only odd-levels))
4536 (org-mode)
4537 (font-lock-fontify-buffer)
4538 (buffer-string))))
4540 (defvar org-m nil)
4541 (defvar org-l nil)
4542 (defvar org-f nil)
4543 (defun org-get-level-face (n)
4544 "Get the right face for match N in font-lock matching of headlines."
4545 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4546 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4547 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4548 (cond
4549 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4550 ((eq n 2) org-f)
4551 (t (if org-level-color-stars-only nil org-f))))
4553 (defun org-get-todo-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-todo-keyword-faces))
4558 (and (member kwd org-done-keywords) 'org-done)
4559 'org-todo))
4561 (defun org-font-lock-add-tag-faces (limit)
4562 "Add the special tag faces."
4563 (when (and org-tag-faces org-tags-special-faces-re)
4564 (while (re-search-forward org-tags-special-faces-re limit t)
4565 (add-text-properties (match-beginning 1) (match-end 1)
4566 (list 'face (org-get-tag-face 1)
4567 'font-lock-fontified t))
4568 (backward-char 1))))
4570 (defun org-font-lock-add-priority-faces (limit)
4571 "Add the special priority faces."
4572 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4573 (add-text-properties
4574 (match-beginning 0) (match-end 0)
4575 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4576 org-priority-faces))
4577 'org-special-keyword)
4578 'font-lock-fontified t))))
4580 (defun org-get-tag-face (kwd)
4581 "Get the right face for a TODO keyword KWD.
4582 If KWD is a number, get the corresponding match group."
4583 (if (numberp kwd) (setq kwd (match-string kwd)))
4584 (or (cdr (assoc kwd org-tag-faces))
4585 'org-tag))
4587 (defun org-unfontify-region (beg end &optional maybe_loudly)
4588 "Remove fontification and activation overlays from links."
4589 (font-lock-default-unfontify-region beg end)
4590 (let* ((buffer-undo-list t)
4591 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4592 (inhibit-modification-hooks t)
4593 deactivate-mark buffer-file-name buffer-file-truename)
4594 (remove-text-properties beg end
4595 '(mouse-face t keymap t org-linked-text t
4596 invisible t intangible t))))
4598 ;;;; Visibility cycling, including org-goto and indirect buffer
4600 ;;; Cycling
4602 (defvar org-cycle-global-status nil)
4603 (make-variable-buffer-local 'org-cycle-global-status)
4604 (defvar org-cycle-subtree-status nil)
4605 (make-variable-buffer-local 'org-cycle-subtree-status)
4607 ;;;###autoload
4609 (defvar org-inlinetask-min-level)
4611 (defun org-cycle (&optional arg)
4612 "TAB-action and visibility cycling for Org-mode.
4614 This is the command invoked in Org-moe by the TAB key. It's main purpose
4615 is outine visibility cycling, but it also invokes other actions
4616 in special contexts.
4618 - When this function is called with a prefix argument, rotate the entire
4619 buffer through 3 states (global cycling)
4620 1. OVERVIEW: Show only top-level headlines.
4621 2. CONTENTS: Show all headlines of all levels, but no body text.
4622 3. SHOW ALL: Show everything.
4623 When called with two `C-u C-u' prefixes, switch to the startup visibility,
4624 determined by the variable `org-startup-folded', and by any VISIBILITY
4625 properties in the buffer.
4626 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
4627 including any drawers.
4629 - When inside a table, re-align the table and move to the next field.
4631 - When point is at the beginning of a headline, rotate the subtree started
4632 by this line through 3 different states (local cycling)
4633 1. FOLDED: Only the main headline is shown.
4634 2. CHILDREN: The main headline and the direct children are shown.
4635 From this state, you can move to one of the children
4636 and zoom in further.
4637 3. SUBTREE: Show the entire subtree, including body text.
4639 - When there is a numeric prefix, go up to a heading with level ARG, do
4640 a `show-subtree' and return to the previous cursor position. If ARG
4641 is negative, go up that many levels.
4643 - When point is not at the beginning of a headline, execute the global
4644 binding for TAB, which is re-indenting the line. See the option
4645 `org-cycle-emulate-tab' for details.
4647 - Special case: if point is at the beginning of the buffer and there is
4648 no headline in line 1, this function will act as if called with prefix arg.
4649 But only if also the variable `org-cycle-global-at-bob' is t."
4650 (interactive "P")
4651 (org-load-modules-maybe)
4652 (unless (run-hook-with-args-until-success 'org-tab-first-hook)
4653 (let* ((limit-level
4654 (or org-cycle-max-level
4655 (and (boundp 'org-inlinetask-min-level)
4656 org-inlinetask-min-level
4657 (1- org-inlinetask-min-level))))
4658 (nstars (and limit-level
4659 (if org-odd-levels-only
4660 (and limit-level (1- (* limit-level 2)))
4661 limit-level)))
4662 (outline-regexp
4663 (cond
4664 ((not (org-mode-p)) outline-regexp)
4665 (org-cycle-include-plain-lists
4666 (concat "\\(?:\\*"
4667 (if nstars (format "\\{1,%d\\}" nstars) "+")
4668 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
4669 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
4670 (bob-special (and org-cycle-global-at-bob (bobp)
4671 (not (looking-at outline-regexp))))
4672 (org-cycle-hook
4673 (if bob-special
4674 (delq 'org-optimize-window-after-visibility-change
4675 (copy-sequence org-cycle-hook))
4676 org-cycle-hook))
4677 (pos (point)))
4679 (if (or bob-special (equal arg '(4)))
4680 ;; special case: use global cycling
4681 (setq arg t))
4683 (cond
4685 ((equal arg '(16))
4686 (org-set-startup-visibility)
4687 (message "Startup visibility, plus VISIBILITY properties"))
4689 ((equal arg '(64))
4690 (show-all)
4691 (message "Entire buffer visible, including drawers"))
4693 ((org-at-table-p 'any)
4694 ;; Enter the table or move to the next field in the table
4695 (or (org-table-recognize-table.el)
4696 (progn
4697 (if arg (org-table-edit-field t)
4698 (org-table-justify-field-maybe)
4699 (call-interactively 'org-table-next-field)))))
4701 ((run-hook-with-args-until-success
4702 'org-tab-after-check-for-table-hook))
4704 ((eq arg t) ;; Global cycling
4705 (org-cycle-internal-global))
4707 ((and org-drawers org-drawer-regexp
4708 (save-excursion
4709 (beginning-of-line 1)
4710 (looking-at org-drawer-regexp)))
4711 ;; Toggle block visibility
4712 (org-flag-drawer
4713 (not (get-char-property (match-end 0) 'invisible))))
4715 ((integerp arg)
4716 ;; Show-subtree, ARG levels up from here.
4717 (save-excursion
4718 (org-back-to-heading)
4719 (outline-up-heading (if (< arg 0) (- arg)
4720 (- (funcall outline-level) arg)))
4721 (org-show-subtree)))
4723 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4724 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4726 (org-cycle-internal-local))
4728 ;; TAB emulation and template completion
4729 (buffer-read-only (org-back-to-heading))
4731 ((run-hook-with-args-until-success
4732 'org-tab-after-check-for-cycling-hook))
4734 ((org-try-structure-completion))
4736 ((org-try-cdlatex-tab))
4738 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4739 (or (not (bolp))
4740 (not (looking-at outline-regexp))))
4741 (call-interactively (global-key-binding "\t")))
4743 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4744 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4745 (or (and (eq org-cycle-emulate-tab 'white)
4746 (= (match-end 0) (point-at-eol)))
4747 (and (eq org-cycle-emulate-tab 'whitestart)
4748 (>= (match-end 0) pos))))
4750 (eq org-cycle-emulate-tab t))
4751 (call-interactively (global-key-binding "\t")))
4753 (t (save-excursion
4754 (org-back-to-heading)
4755 (org-cycle)))))))
4757 (defun org-cycle-internal-global ()
4758 "Do the global cycling action."
4759 (cond
4760 ((and (eq last-command this-command)
4761 (eq org-cycle-global-status 'overview))
4762 ;; We just created the overview - now do table of contents
4763 ;; This can be slow in very large buffers, so indicate action
4764 (run-hook-with-args 'org-pre-cycle-hook 'contents)
4765 (message "CONTENTS...")
4766 (org-content)
4767 (message "CONTENTS...done")
4768 (setq org-cycle-global-status 'contents)
4769 (run-hook-with-args 'org-cycle-hook 'contents))
4771 ((and (eq last-command this-command)
4772 (eq org-cycle-global-status 'contents))
4773 ;; We just showed the table of contents - now show everything
4774 (run-hook-with-args 'org-pre-cycle-hook 'all)
4775 (show-all)
4776 (message "SHOW ALL")
4777 (setq org-cycle-global-status 'all)
4778 (run-hook-with-args 'org-cycle-hook 'all))
4781 ;; Default action: go to overview
4782 (run-hook-with-args 'org-pre-cycle-hook 'overview)
4783 (org-overview)
4784 (message "OVERVIEW")
4785 (setq org-cycle-global-status 'overview)
4786 (run-hook-with-args 'org-cycle-hook 'overview))))
4788 (defun org-cycle-internal-local ()
4789 "Do the local cycling action."
4790 (org-back-to-heading)
4791 (let ((goal-column 0) eoh eol eos)
4792 ;; First, some boundaries
4793 (save-excursion
4794 (org-back-to-heading)
4795 (save-excursion
4796 (beginning-of-line 2)
4797 (while (and (not (eobp)) ;; this is like `next-line'
4798 (get-char-property (1- (point)) 'invisible))
4799 (beginning-of-line 2)) (setq eol (point)))
4800 (outline-end-of-heading) (setq eoh (point))
4801 (org-end-of-subtree t)
4802 (unless (eobp)
4803 (skip-chars-forward " \t\n")
4804 (beginning-of-line 1) ; in case this is an item
4806 (setq eos (1- (point))))
4807 ;; Find out what to do next and set `this-command'
4808 (cond
4809 ((= eos eoh)
4810 ;; Nothing is hidden behind this heading
4811 (run-hook-with-args 'org-pre-cycle-hook 'empty)
4812 (message "EMPTY ENTRY")
4813 (setq org-cycle-subtree-status nil)
4814 (save-excursion
4815 (goto-char eos)
4816 (outline-next-heading)
4817 (if (org-invisible-p) (org-flag-heading nil))))
4818 ((or (>= eol eos)
4819 (not (string-match "\\S-" (buffer-substring eol eos))))
4820 ;; Entire subtree is hidden in one line: open it
4821 (run-hook-with-args 'org-pre-cycle-hook 'children)
4822 (org-show-entry)
4823 (show-children)
4824 (message "CHILDREN")
4825 (save-excursion
4826 (goto-char eos)
4827 (outline-next-heading)
4828 (if (org-invisible-p) (org-flag-heading nil)))
4829 (setq org-cycle-subtree-status 'children)
4830 (run-hook-with-args 'org-cycle-hook 'children))
4831 ((and (eq last-command this-command)
4832 (eq org-cycle-subtree-status 'children))
4833 ;; We just showed the children, now show everything.
4834 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
4835 (org-show-subtree)
4836 (message "SUBTREE")
4837 (setq org-cycle-subtree-status 'subtree)
4838 (run-hook-with-args 'org-cycle-hook 'subtree))
4840 ;; Default action: hide the subtree.
4841 (run-hook-with-args 'org-pre-cycle-hook 'folded)
4842 (hide-subtree)
4843 (message "FOLDED")
4844 (setq org-cycle-subtree-status 'folded)
4845 (run-hook-with-args 'org-cycle-hook 'folded)))))
4847 ;;;###autoload
4848 (defun org-global-cycle (&optional arg)
4849 "Cycle the global visibility. For details see `org-cycle'.
4850 With C-u prefix arg, switch to startup visibility.
4851 With a numeric prefix, show all headlines up to that level."
4852 (interactive "P")
4853 (let ((org-cycle-include-plain-lists
4854 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4855 (cond
4856 ((integerp arg)
4857 (show-all)
4858 (hide-sublevels arg)
4859 (setq org-cycle-global-status 'contents))
4860 ((equal arg '(4))
4861 (org-set-startup-visibility)
4862 (message "Startup visibility, plus VISIBILITY properties."))
4864 (org-cycle '(4))))))
4866 (defun org-set-startup-visibility ()
4867 "Set the visibility required by startup options and properties."
4868 (cond
4869 ((eq org-startup-folded t)
4870 (org-cycle '(4)))
4871 ((eq org-startup-folded 'content)
4872 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4873 (org-cycle '(4)) (org-cycle '(4)))))
4874 (org-set-visibility-according-to-property 'no-cleanup)
4875 (org-cycle-hide-archived-subtrees 'all)
4876 (org-cycle-hide-drawers 'all)
4877 (org-cycle-show-empty-lines 'all))
4879 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4880 "Switch subtree visibilities according to :VISIBILITY: property."
4881 (interactive)
4882 (let (org-show-entry-below state)
4883 (save-excursion
4884 (goto-char (point-min))
4885 (while (re-search-forward
4886 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4887 nil t)
4888 (setq state (match-string 1))
4889 (save-excursion
4890 (org-back-to-heading t)
4891 (hide-subtree)
4892 (org-reveal)
4893 (cond
4894 ((equal state '("fold" "folded"))
4895 (hide-subtree))
4896 ((equal state "children")
4897 (org-show-hidden-entry)
4898 (show-children))
4899 ((equal state "content")
4900 (save-excursion
4901 (save-restriction
4902 (org-narrow-to-subtree)
4903 (org-content))))
4904 ((member state '("all" "showall"))
4905 (show-subtree)))))
4906 (unless no-cleanup
4907 (org-cycle-hide-archived-subtrees 'all)
4908 (org-cycle-hide-drawers 'all)
4909 (org-cycle-show-empty-lines 'all)))))
4911 (defun org-overview ()
4912 "Switch to overview mode, showing only top-level headlines.
4913 Really, this shows all headlines with level equal or greater than the level
4914 of the first headline in the buffer. This is important, because if the
4915 first headline is not level one, then (hide-sublevels 1) gives confusing
4916 results."
4917 (interactive)
4918 (let ((level (save-excursion
4919 (goto-char (point-min))
4920 (if (re-search-forward (concat "^" outline-regexp) nil t)
4921 (progn
4922 (goto-char (match-beginning 0))
4923 (funcall outline-level))))))
4924 (and level (hide-sublevels level))))
4926 (defun org-content (&optional arg)
4927 "Show all headlines in the buffer, like a table of contents.
4928 With numerical argument N, show content up to level N."
4929 (interactive "P")
4930 (save-excursion
4931 ;; Visit all headings and show their offspring
4932 (and (integerp arg) (org-overview))
4933 (goto-char (point-max))
4934 (catch 'exit
4935 (while (and (progn (condition-case nil
4936 (outline-previous-visible-heading 1)
4937 (error (goto-char (point-min))))
4939 (looking-at outline-regexp))
4940 (if (integerp arg)
4941 (show-children (1- arg))
4942 (show-branches))
4943 (if (bobp) (throw 'exit nil))))))
4946 (defun org-optimize-window-after-visibility-change (state)
4947 "Adjust the window after a change in outline visibility.
4948 This function is the default value of the hook `org-cycle-hook'."
4949 (when (get-buffer-window (current-buffer))
4950 (cond
4951 ((eq state 'content) nil)
4952 ((eq state 'all) nil)
4953 ((eq state 'folded) nil)
4954 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4955 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4957 (defun org-compact-display-after-subtree-move ()
4958 "Show a compacter version of the tree of the entry's parent."
4959 (save-excursion
4960 (if (org-up-heading-safe)
4961 (progn
4962 (hide-subtree)
4963 (show-entry)
4964 (show-children)
4965 (org-cycle-show-empty-lines 'children)
4966 (org-cycle-hide-drawers 'children))
4967 (org-overview))))
4969 (defun org-cycle-show-empty-lines (state)
4970 "Show empty lines above all visible headlines.
4971 The region to be covered depends on STATE when called through
4972 `org-cycle-hook'. Lisp program can use t for STATE to get the
4973 entire buffer covered. Note that an empty line is only shown if there
4974 are at least `org-cycle-separator-lines' empty lines before the headline."
4975 (when (> org-cycle-separator-lines 0)
4976 (save-excursion
4977 (let* ((n org-cycle-separator-lines)
4978 (re (cond
4979 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4980 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4981 (t (let ((ns (number-to-string (- n 2))))
4982 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4983 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4984 beg end)
4985 (cond
4986 ((memq state '(overview contents t))
4987 (setq beg (point-min) end (point-max)))
4988 ((memq state '(children folded))
4989 (setq beg (point) end (progn (org-end-of-subtree t t)
4990 (beginning-of-line 2)
4991 (point)))))
4992 (when beg
4993 (goto-char beg)
4994 (while (re-search-forward re end t)
4995 (if (not (get-char-property (match-end 1) 'invisible))
4996 (outline-flag-region
4997 (match-beginning 1) (match-end 1) nil)))))))
4998 ;; Never hide empty lines at the end of the file.
4999 (save-excursion
5000 (goto-char (point-max))
5001 (outline-previous-heading)
5002 (outline-end-of-heading)
5003 (if (and (looking-at "[ \t\n]+")
5004 (= (match-end 0) (point-max)))
5005 (outline-flag-region (point) (match-end 0) nil))))
5007 (defun org-show-empty-lines-in-parent ()
5008 "Move to the parent and re-show empty lines before visible headlines."
5009 (save-excursion
5010 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5011 (org-cycle-show-empty-lines context))))
5013 (defun org-cycle-hide-drawers (state)
5014 "Re-hide all drawers after a visibility state change."
5015 (when (and (org-mode-p)
5016 (not (memq state '(overview folded))))
5017 (save-excursion
5018 (let* ((globalp (memq state '(contents all)))
5019 (beg (if globalp (point-min) (point)))
5020 (end (if globalp (point-max) (org-end-of-subtree t))))
5021 (goto-char beg)
5022 (while (re-search-forward org-drawer-regexp end t)
5023 (org-flag-drawer t))))))
5025 (defun org-flag-drawer (flag)
5026 (save-excursion
5027 (beginning-of-line 1)
5028 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5029 (let ((b (match-end 0))
5030 (outline-regexp org-outline-regexp))
5031 (if (re-search-forward
5032 "^[ \t]*:END:"
5033 (save-excursion (outline-next-heading) (point)) t)
5034 (outline-flag-region b (point-at-eol) flag)
5035 (error ":END: line missing"))))))
5037 (defun org-subtree-end-visible-p ()
5038 "Is the end of the current subtree visible?"
5039 (pos-visible-in-window-p
5040 (save-excursion (org-end-of-subtree t) (point))))
5042 (defun org-first-headline-recenter (&optional N)
5043 "Move cursor to the first headline and recenter the headline.
5044 Optional argument N means, put the headline into the Nth line of the window."
5045 (goto-char (point-min))
5046 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5047 (beginning-of-line)
5048 (recenter (prefix-numeric-value N))))
5050 ;;; Org-goto
5052 (defvar org-goto-window-configuration nil)
5053 (defvar org-goto-marker nil)
5054 (defvar org-goto-map
5055 (let ((map (make-sparse-keymap)))
5056 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5057 (while (setq cmd (pop cmds))
5058 (substitute-key-definition cmd cmd map global-map)))
5059 (suppress-keymap map)
5060 (org-defkey map "\C-m" 'org-goto-ret)
5061 (org-defkey map [(return)] 'org-goto-ret)
5062 (org-defkey map [(left)] 'org-goto-left)
5063 (org-defkey map [(right)] 'org-goto-right)
5064 (org-defkey map [(control ?g)] 'org-goto-quit)
5065 (org-defkey map "\C-i" 'org-cycle)
5066 (org-defkey map [(tab)] 'org-cycle)
5067 (org-defkey map [(down)] 'outline-next-visible-heading)
5068 (org-defkey map [(up)] 'outline-previous-visible-heading)
5069 (if org-goto-auto-isearch
5070 (if (fboundp 'define-key-after)
5071 (define-key-after map [t] 'org-goto-local-auto-isearch)
5072 nil)
5073 (org-defkey map "q" 'org-goto-quit)
5074 (org-defkey map "n" 'outline-next-visible-heading)
5075 (org-defkey map "p" 'outline-previous-visible-heading)
5076 (org-defkey map "f" 'outline-forward-same-level)
5077 (org-defkey map "b" 'outline-backward-same-level)
5078 (org-defkey map "u" 'outline-up-heading))
5079 (org-defkey map "/" 'org-occur)
5080 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5081 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5082 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5083 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5084 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5085 map))
5087 (defconst org-goto-help
5088 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5089 RET=jump to location [Q]uit and return to previous location
5090 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5092 (defvar org-goto-start-pos) ; dynamically scoped parameter
5094 ;; FIXME: Docstring doe not mention both interfaces
5095 (defun org-goto (&optional alternative-interface)
5096 "Look up a different location in the current file, keeping current visibility.
5098 When you want look-up or go to a different location in a document, the
5099 fastest way is often to fold the entire buffer and then dive into the tree.
5100 This method has the disadvantage, that the previous location will be folded,
5101 which may not be what you want.
5103 This command works around this by showing a copy of the current buffer
5104 in an indirect buffer, in overview mode. You can dive into the tree in
5105 that copy, use org-occur and incremental search to find a location.
5106 When pressing RET or `Q', the command returns to the original buffer in
5107 which the visibility is still unchanged. After RET is will also jump to
5108 the location selected in the indirect buffer and expose the
5109 the headline hierarchy above."
5110 (interactive "P")
5111 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5112 (org-refile-use-outline-path t)
5113 (org-refile-target-verify-function nil)
5114 (interface
5115 (if (not alternative-interface)
5116 org-goto-interface
5117 (if (eq org-goto-interface 'outline)
5118 'outline-path-completion
5119 'outline)))
5120 (org-goto-start-pos (point))
5121 (selected-point
5122 (if (eq interface 'outline)
5123 (car (org-get-location (current-buffer) org-goto-help))
5124 (nth 3 (org-refile-get-location "Goto: ")))))
5125 (if selected-point
5126 (progn
5127 (org-mark-ring-push org-goto-start-pos)
5128 (goto-char selected-point)
5129 (if (or (org-invisible-p) (org-invisible-p2))
5130 (org-show-context 'org-goto)))
5131 (message "Quit"))))
5133 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5134 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5135 (defvar org-goto-local-auto-isearch-map) ; defined below
5137 (defun org-get-location (buf help)
5138 "Let the user select a location in the Org-mode buffer BUF.
5139 This function uses a recursive edit. It returns the selected position
5140 or nil."
5141 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5142 (isearch-hide-immediately nil)
5143 (isearch-search-fun-function
5144 (lambda () 'org-goto-local-search-headings))
5145 (org-goto-selected-point org-goto-exit-command))
5146 (save-excursion
5147 (save-window-excursion
5148 (delete-other-windows)
5149 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5150 (switch-to-buffer
5151 (condition-case nil
5152 (make-indirect-buffer (current-buffer) "*org-goto*")
5153 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5154 (with-output-to-temp-buffer "*Help*"
5155 (princ help))
5156 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5157 (setq buffer-read-only nil)
5158 (let ((org-startup-truncated t)
5159 (org-startup-folded nil)
5160 (org-startup-align-all-tables nil))
5161 (org-mode)
5162 (org-overview))
5163 (setq buffer-read-only t)
5164 (if (and (boundp 'org-goto-start-pos)
5165 (integer-or-marker-p org-goto-start-pos))
5166 (let ((org-show-hierarchy-above t)
5167 (org-show-siblings t)
5168 (org-show-following-heading t))
5169 (goto-char org-goto-start-pos)
5170 (and (org-invisible-p) (org-show-context)))
5171 (goto-char (point-min)))
5172 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5173 (message "Select location and press RET")
5174 (use-local-map org-goto-map)
5175 (recursive-edit)
5177 (kill-buffer "*org-goto*")
5178 (cons org-goto-selected-point org-goto-exit-command)))
5180 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5181 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5182 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5183 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5185 (defun org-goto-local-search-headings (string bound noerror)
5186 "Search and make sure that any matches are in headlines."
5187 (catch 'return
5188 (while (if isearch-forward
5189 (search-forward string bound noerror)
5190 (search-backward string bound noerror))
5191 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5192 (and (member :headline context)
5193 (not (member :tags context))))
5194 (throw 'return (point))))))
5196 (defun org-goto-local-auto-isearch ()
5197 "Start isearch."
5198 (interactive)
5199 (goto-char (point-min))
5200 (let ((keys (this-command-keys)))
5201 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5202 (isearch-mode t)
5203 (isearch-process-search-char (string-to-char keys)))))
5205 (defun org-goto-ret (&optional arg)
5206 "Finish `org-goto' by going to the new location."
5207 (interactive "P")
5208 (setq org-goto-selected-point (point)
5209 org-goto-exit-command 'return)
5210 (throw 'exit nil))
5212 (defun org-goto-left ()
5213 "Finish `org-goto' by going to the new location."
5214 (interactive)
5215 (if (org-on-heading-p)
5216 (progn
5217 (beginning-of-line 1)
5218 (setq org-goto-selected-point (point)
5219 org-goto-exit-command 'left)
5220 (throw 'exit nil))
5221 (error "Not on a heading")))
5223 (defun org-goto-right ()
5224 "Finish `org-goto' by going to the new location."
5225 (interactive)
5226 (if (org-on-heading-p)
5227 (progn
5228 (setq org-goto-selected-point (point)
5229 org-goto-exit-command 'right)
5230 (throw 'exit nil))
5231 (error "Not on a heading")))
5233 (defun org-goto-quit ()
5234 "Finish `org-goto' without cursor motion."
5235 (interactive)
5236 (setq org-goto-selected-point nil)
5237 (setq org-goto-exit-command 'quit)
5238 (throw 'exit nil))
5240 ;;; Indirect buffer display of subtrees
5242 (defvar org-indirect-dedicated-frame nil
5243 "This is the frame being used for indirect tree display.")
5244 (defvar org-last-indirect-buffer nil)
5246 (defun org-tree-to-indirect-buffer (&optional arg)
5247 "Create indirect buffer and narrow it to current subtree.
5248 With numerical prefix ARG, go up to this level and then take that tree.
5249 If ARG is negative, go up that many levels.
5250 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5251 indirect buffer previously made with this command, to avoid proliferation of
5252 indirect buffers. However, when you call the command with a `C-u' prefix, or
5253 when `org-indirect-buffer-display' is `new-frame', the last buffer
5254 is kept so that you can work with several indirect buffers at the same time.
5255 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5256 requests that a new frame be made for the new buffer, so that the dedicated
5257 frame is not changed."
5258 (interactive "P")
5259 (let ((cbuf (current-buffer))
5260 (cwin (selected-window))
5261 (pos (point))
5262 beg end level heading ibuf)
5263 (save-excursion
5264 (org-back-to-heading t)
5265 (when (numberp arg)
5266 (setq level (org-outline-level))
5267 (if (< arg 0) (setq arg (+ level arg)))
5268 (while (> (setq level (org-outline-level)) arg)
5269 (outline-up-heading 1 t)))
5270 (setq beg (point)
5271 heading (org-get-heading))
5272 (org-end-of-subtree t) (setq end (point)))
5273 (if (and (buffer-live-p org-last-indirect-buffer)
5274 (not (eq org-indirect-buffer-display 'new-frame))
5275 (not arg))
5276 (kill-buffer org-last-indirect-buffer))
5277 (setq ibuf (org-get-indirect-buffer cbuf)
5278 org-last-indirect-buffer ibuf)
5279 (cond
5280 ((or (eq org-indirect-buffer-display 'new-frame)
5281 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5282 (select-frame (make-frame))
5283 (delete-other-windows)
5284 (switch-to-buffer ibuf)
5285 (org-set-frame-title heading))
5286 ((eq org-indirect-buffer-display 'dedicated-frame)
5287 (raise-frame
5288 (select-frame (or (and org-indirect-dedicated-frame
5289 (frame-live-p org-indirect-dedicated-frame)
5290 org-indirect-dedicated-frame)
5291 (setq org-indirect-dedicated-frame (make-frame)))))
5292 (delete-other-windows)
5293 (switch-to-buffer ibuf)
5294 (org-set-frame-title (concat "Indirect: " heading)))
5295 ((eq org-indirect-buffer-display 'current-window)
5296 (switch-to-buffer ibuf))
5297 ((eq org-indirect-buffer-display 'other-window)
5298 (pop-to-buffer ibuf))
5299 (t (error "Invalid value.")))
5300 (if (featurep 'xemacs)
5301 (save-excursion (org-mode) (turn-on-font-lock)))
5302 (narrow-to-region beg end)
5303 (show-all)
5304 (goto-char pos)
5305 (and (window-live-p cwin) (select-window cwin))))
5307 (defun org-get-indirect-buffer (&optional buffer)
5308 (setq buffer (or buffer (current-buffer)))
5309 (let ((n 1) (base (buffer-name buffer)) bname)
5310 (while (buffer-live-p
5311 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5312 (setq n (1+ n)))
5313 (condition-case nil
5314 (make-indirect-buffer buffer bname 'clone)
5315 (error (make-indirect-buffer buffer bname)))))
5317 (defun org-set-frame-title (title)
5318 "Set the title of the current frame to the string TITLE."
5319 ;; FIXME: how to name a single frame in XEmacs???
5320 (unless (featurep 'xemacs)
5321 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5323 ;;;; Structure editing
5325 ;;; Inserting headlines
5327 (defun org-previous-line-empty-p ()
5328 (save-excursion
5329 (and (not (bobp))
5330 (or (beginning-of-line 0) t)
5331 (save-match-data
5332 (looking-at "[ \t]*$")))))
5334 (defun org-insert-heading (&optional force-heading)
5335 "Insert a new heading or item with same depth at point.
5336 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5337 If point is at the beginning of a headline, insert a sibling before the
5338 current headline. If point is not at the beginning, do not split the line,
5339 but create the new headline after the current line."
5340 (interactive "P")
5341 (if (= (buffer-size) 0)
5342 (insert "\n* ")
5343 (when (or force-heading (not (org-insert-item)))
5344 (let* ((empty-line-p nil)
5345 (head (save-excursion
5346 (condition-case nil
5347 (progn
5348 (org-back-to-heading)
5349 (setq empty-line-p (org-previous-line-empty-p))
5350 (match-string 0))
5351 (error "*"))))
5352 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5353 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5354 pos hide-previous previous-pos)
5355 (cond
5356 ((and (org-on-heading-p) (bolp)
5357 (or (bobp)
5358 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5359 ;; insert before the current line
5360 (open-line (if blank 2 1)))
5361 ((and (bolp)
5362 (or (bobp)
5363 (save-excursion
5364 (backward-char 1) (not (org-invisible-p)))))
5365 ;; insert right here
5366 nil)
5368 ;; somewhere in the line
5369 (save-excursion
5370 (setq previous-pos (point-at-bol))
5371 (end-of-line)
5372 (setq hide-previous (org-invisible-p)))
5373 (and org-insert-heading-respect-content (org-show-subtree))
5374 (let ((split
5375 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5376 (save-excursion
5377 (let ((p (point)))
5378 (goto-char (point-at-bol))
5379 (and (looking-at org-complex-heading-regexp)
5380 (> p (match-beginning 4)))))))
5381 tags pos)
5382 (cond
5383 (org-insert-heading-respect-content
5384 (org-end-of-subtree nil t)
5385 (or (bolp) (newline))
5386 (or (org-previous-line-empty-p)
5387 (and blank (newline)))
5388 (open-line 1))
5389 ((org-on-heading-p)
5390 (when hide-previous
5391 (show-children)
5392 (org-show-entry))
5393 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5394 (setq tags (and (match-end 2) (match-string 2)))
5395 (and (match-end 1)
5396 (delete-region (match-beginning 1) (match-end 1)))
5397 (setq pos (point-at-bol))
5398 (or split (end-of-line 1))
5399 (delete-horizontal-space)
5400 (newline (if blank 2 1))
5401 (when tags
5402 (save-excursion
5403 (goto-char pos)
5404 (end-of-line 1)
5405 (insert " " tags)
5406 (org-set-tags nil 'align))))
5408 (or split (end-of-line 1))
5409 (newline (if blank 2 1)))))))
5410 (insert head) (just-one-space)
5411 (setq pos (point))
5412 (end-of-line 1)
5413 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5414 (when (and org-insert-heading-respect-content hide-previous)
5415 (save-excursion
5416 (goto-char previous-pos)
5417 (hide-subtree)))
5418 (run-hooks 'org-insert-heading-hook)))))
5420 (defun org-get-heading (&optional no-tags)
5421 "Return the heading of the current entry, without the stars."
5422 (save-excursion
5423 (org-back-to-heading t)
5424 (if (looking-at
5425 (if no-tags
5426 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5427 "\\*+[ \t]+\\([^\r\n]*\\)"))
5428 (match-string 1) "")))
5430 (defun org-heading-components ()
5431 "Return the components of the current heading.
5432 This is a list with the following elements:
5433 - the level as an integer
5434 - the reduced level, different if `org-odd-levels-only' is set.
5435 - the TODO keyword, or nil
5436 - the priority character, like ?A, or nil if no priority is given
5437 - the headline text itself, or the tags string if no headline text
5438 - the tags string, or nil."
5439 (save-excursion
5440 (org-back-to-heading t)
5441 (if (looking-at org-complex-heading-regexp)
5442 (list (length (match-string 1))
5443 (org-reduced-level (length (match-string 1)))
5444 (org-match-string-no-properties 2)
5445 (and (match-end 3) (aref (match-string 3) 2))
5446 (org-match-string-no-properties 4)
5447 (org-match-string-no-properties 5)))))
5449 (defun org-get-entry ()
5450 "Get the entry text, after heading, entire subtree."
5451 (save-excursion
5452 (org-back-to-heading t)
5453 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
5455 (defun org-insert-heading-after-current ()
5456 "Insert a new heading with same level as current, after current subtree."
5457 (interactive)
5458 (org-back-to-heading)
5459 (org-insert-heading)
5460 (org-move-subtree-down)
5461 (end-of-line 1))
5463 (defun org-insert-heading-respect-content ()
5464 (interactive)
5465 (let ((org-insert-heading-respect-content t))
5466 (org-insert-heading t)))
5468 (defun org-insert-todo-heading-respect-content (&optional force-state)
5469 (interactive "P")
5470 (let ((org-insert-heading-respect-content t))
5471 (org-insert-todo-heading force-state t)))
5473 (defun org-insert-todo-heading (arg &optional force-heading)
5474 "Insert a new heading with the same level and TODO state as current heading.
5475 If the heading has no TODO state, or if the state is DONE, use the first
5476 state (TODO by default). Also with prefix arg, force first state."
5477 (interactive "P")
5478 (when (or force-heading (not (org-insert-item 'checkbox)))
5479 (org-insert-heading force-heading)
5480 (save-excursion
5481 (org-back-to-heading)
5482 (outline-previous-heading)
5483 (looking-at org-todo-line-regexp))
5484 (let*
5485 ((new-mark-x
5486 (if (or arg
5487 (not (match-beginning 2))
5488 (member (match-string 2) org-done-keywords))
5489 (car org-todo-keywords-1)
5490 (match-string 2)))
5491 (new-mark
5493 (run-hook-with-args-until-success
5494 'org-todo-get-default-hook new-mark-x nil)
5495 new-mark-x)))
5496 (beginning-of-line 1)
5497 (and (looking-at "\\*+ ") (goto-char (match-end 0))
5498 (insert new-mark " ")))
5499 (when org-provide-todo-statistics
5500 (org-update-parent-todo-statistics))))
5502 (defun org-insert-subheading (arg)
5503 "Insert a new subheading and demote it.
5504 Works for outline headings and for plain lists alike."
5505 (interactive "P")
5506 (org-insert-heading arg)
5507 (cond
5508 ((org-on-heading-p) (org-do-demote))
5509 ((org-at-item-p) (org-indent-item 1))))
5511 (defun org-insert-todo-subheading (arg)
5512 "Insert a new subheading with TODO keyword or checkbox and demote it.
5513 Works for outline headings and for plain lists alike."
5514 (interactive "P")
5515 (org-insert-todo-heading arg)
5516 (cond
5517 ((org-on-heading-p) (org-do-demote))
5518 ((org-at-item-p) (org-indent-item 1))))
5520 ;;; Promotion and Demotion
5522 (defun org-promote-subtree ()
5523 "Promote the entire subtree.
5524 See also `org-promote'."
5525 (interactive)
5526 (save-excursion
5527 (org-map-tree 'org-promote))
5528 (org-fix-position-after-promote))
5530 (defun org-demote-subtree ()
5531 "Demote the entire subtree. See `org-demote'.
5532 See also `org-promote'."
5533 (interactive)
5534 (save-excursion
5535 (org-map-tree 'org-demote))
5536 (org-fix-position-after-promote))
5539 (defun org-do-promote ()
5540 "Promote the current heading higher up the tree.
5541 If the region is active in `transient-mark-mode', promote all headings
5542 in the region."
5543 (interactive)
5544 (save-excursion
5545 (if (org-region-active-p)
5546 (org-map-region 'org-promote (region-beginning) (region-end))
5547 (org-promote)))
5548 (org-fix-position-after-promote))
5550 (defun org-do-demote ()
5551 "Demote the current heading lower down the tree.
5552 If the region is active in `transient-mark-mode', demote all headings
5553 in the region."
5554 (interactive)
5555 (save-excursion
5556 (if (org-region-active-p)
5557 (org-map-region 'org-demote (region-beginning) (region-end))
5558 (org-demote)))
5559 (org-fix-position-after-promote))
5561 (defun org-fix-position-after-promote ()
5562 "Make sure that after pro/demotion cursor position is right."
5563 (let ((pos (point)))
5564 (when (save-excursion
5565 (beginning-of-line 1)
5566 (looking-at org-todo-line-regexp)
5567 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5568 (cond ((eobp) (insert " "))
5569 ((eolp) (insert " "))
5570 ((equal (char-after) ?\ ) (forward-char 1))))))
5572 (defun org-reduced-level (l)
5573 "Compute the effective level of a heading.
5574 This takes into account the setting of `org-odd-levels-only'."
5575 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5577 (defun org-get-valid-level (level &optional change)
5578 "Rectify a level change under the influence of `org-odd-levels-only'
5579 LEVEL is a current level, CHANGE is by how much the level should be
5580 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5581 even level numbers will become the next higher odd number."
5582 (if org-odd-levels-only
5583 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5584 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5585 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5586 (max 1 (+ level (or change 0)))))
5588 (if (boundp 'define-obsolete-function-alias)
5589 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5590 (define-obsolete-function-alias 'org-get-legal-level
5591 'org-get-valid-level)
5592 (define-obsolete-function-alias 'org-get-legal-level
5593 'org-get-valid-level "23.1")))
5595 (defun org-promote ()
5596 "Promote the current heading higher up the tree.
5597 If the region is active in `transient-mark-mode', promote all headings
5598 in the region."
5599 (org-back-to-heading t)
5600 (let* ((level (save-match-data (funcall outline-level)))
5601 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5602 (diff (abs (- level (length up-head) -1))))
5603 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5604 (replace-match up-head nil t)
5605 ;; Fixup tag positioning
5606 (and org-auto-align-tags (org-set-tags nil t))
5607 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5609 (defun org-demote ()
5610 "Demote the current heading lower down the tree.
5611 If the region is active in `transient-mark-mode', demote all headings
5612 in the region."
5613 (org-back-to-heading t)
5614 (let* ((level (save-match-data (funcall outline-level)))
5615 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5616 (diff (abs (- level (length down-head) -1))))
5617 (replace-match down-head nil t)
5618 ;; Fixup tag positioning
5619 (and org-auto-align-tags (org-set-tags nil t))
5620 (if org-adapt-indentation (org-fixup-indentation diff))))
5622 (defun org-map-tree (fun)
5623 "Call FUN for every heading underneath the current one."
5624 (org-back-to-heading)
5625 (let ((level (funcall outline-level)))
5626 (save-excursion
5627 (funcall fun)
5628 (while (and (progn
5629 (outline-next-heading)
5630 (> (funcall outline-level) level))
5631 (not (eobp)))
5632 (funcall fun)))))
5634 (defun org-map-region (fun beg end)
5635 "Call FUN for every heading between BEG and END."
5636 (let ((org-ignore-region t))
5637 (save-excursion
5638 (setq end (copy-marker end))
5639 (goto-char beg)
5640 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5641 (< (point) end))
5642 (funcall fun))
5643 (while (and (progn
5644 (outline-next-heading)
5645 (< (point) end))
5646 (not (eobp)))
5647 (funcall fun)))))
5649 (defun org-fixup-indentation (diff)
5650 "Change the indentation in the current entry by DIFF
5651 However, if any line in the current entry has no indentation, or if it
5652 would end up with no indentation after the change, nothing at all is done."
5653 (save-excursion
5654 (let ((end (save-excursion (outline-next-heading)
5655 (point-marker)))
5656 (prohibit (if (> diff 0)
5657 "^\\S-"
5658 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5659 col)
5660 (unless (save-excursion (end-of-line 1)
5661 (re-search-forward prohibit end t))
5662 (while (and (< (point) end)
5663 (re-search-forward "^[ \t]+" end t))
5664 (goto-char (match-end 0))
5665 (setq col (current-column))
5666 (if (< diff 0) (replace-match ""))
5667 (org-indent-to-column (+ diff col))))
5668 (move-marker end nil))))
5670 (defun org-convert-to-odd-levels ()
5671 "Convert an org-mode file with all levels allowed to one with odd levels.
5672 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5673 level 5 etc."
5674 (interactive)
5675 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5676 (let ((org-odd-levels-only nil) n)
5677 (save-excursion
5678 (goto-char (point-min))
5679 (while (re-search-forward "^\\*\\*+ " nil t)
5680 (setq n (- (length (match-string 0)) 2))
5681 (while (>= (setq n (1- n)) 0)
5682 (org-demote))
5683 (end-of-line 1))))))
5686 (defun org-convert-to-oddeven-levels ()
5687 "Convert an org-mode file with only odd levels to one with odd and even levels.
5688 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5689 section with an even level, conversion would destroy the structure of the file. An error
5690 is signaled in this case."
5691 (interactive)
5692 (goto-char (point-min))
5693 ;; First check if there are no even levels
5694 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5695 (org-show-context t)
5696 (error "Not all levels are odd in this file. Conversion not possible."))
5697 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5698 (let ((org-odd-levels-only nil) n)
5699 (save-excursion
5700 (goto-char (point-min))
5701 (while (re-search-forward "^\\*\\*+ " nil t)
5702 (setq n (/ (1- (length (match-string 0))) 2))
5703 (while (>= (setq n (1- n)) 0)
5704 (org-promote))
5705 (end-of-line 1))))))
5707 (defun org-tr-level (n)
5708 "Make N odd if required."
5709 (if org-odd-levels-only (1+ (/ n 2)) n))
5711 ;;; Vertical tree motion, cutting and pasting of subtrees
5713 (defun org-move-subtree-up (&optional arg)
5714 "Move the current subtree up past ARG headlines of the same level."
5715 (interactive "p")
5716 (org-move-subtree-down (- (prefix-numeric-value arg))))
5718 (defun org-move-subtree-down (&optional arg)
5719 "Move the current subtree down past ARG headlines of the same level."
5720 (interactive "p")
5721 (setq arg (prefix-numeric-value arg))
5722 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5723 'outline-get-last-sibling))
5724 (ins-point (make-marker))
5725 (cnt (abs arg))
5726 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5727 ;; Select the tree
5728 (org-back-to-heading)
5729 (setq beg0 (point))
5730 (save-excursion
5731 (setq ne-beg (org-back-over-empty-lines))
5732 (setq beg (point)))
5733 (save-match-data
5734 (save-excursion (outline-end-of-heading)
5735 (setq folded (org-invisible-p)))
5736 (outline-end-of-subtree))
5737 (outline-next-heading)
5738 (setq ne-end (org-back-over-empty-lines))
5739 (setq end (point))
5740 (goto-char beg0)
5741 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5742 ;; include less whitespace
5743 (save-excursion
5744 (goto-char beg)
5745 (forward-line (- ne-beg ne-end))
5746 (setq beg (point))))
5747 ;; Find insertion point, with error handling
5748 (while (> cnt 0)
5749 (or (and (funcall movfunc) (looking-at outline-regexp))
5750 (progn (goto-char beg0)
5751 (error "Cannot move past superior level or buffer limit")))
5752 (setq cnt (1- cnt)))
5753 (if (> arg 0)
5754 ;; Moving forward - still need to move over subtree
5755 (progn (org-end-of-subtree t t)
5756 (save-excursion
5757 (org-back-over-empty-lines)
5758 (or (bolp) (newline)))))
5759 (setq ne-ins (org-back-over-empty-lines))
5760 (move-marker ins-point (point))
5761 (setq txt (buffer-substring beg end))
5762 (org-save-markers-in-region beg end)
5763 (delete-region beg end)
5764 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5765 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5766 (and (not (bolp)) (looking-at "\n") (forward-char 1))
5767 (let ((bbb (point)))
5768 (insert-before-markers txt)
5769 (org-reinstall-markers-in-region bbb)
5770 (move-marker ins-point bbb))
5771 (or (bolp) (insert "\n"))
5772 (setq ins-end (point))
5773 (goto-char ins-point)
5774 (org-skip-whitespace)
5775 (when (and (< arg 0)
5776 (org-first-sibling-p)
5777 (> ne-ins ne-beg))
5778 ;; Move whitespace back to beginning
5779 (save-excursion
5780 (goto-char ins-end)
5781 (let ((kill-whole-line t))
5782 (kill-line (- ne-ins ne-beg)) (point)))
5783 (insert (make-string (- ne-ins ne-beg) ?\n)))
5784 (move-marker ins-point nil)
5785 (org-compact-display-after-subtree-move)
5786 (org-show-empty-lines-in-parent)
5787 (unless folded
5788 (org-show-entry)
5789 (show-children)
5790 (org-cycle-hide-drawers 'children))))
5792 (defvar org-subtree-clip ""
5793 "Clipboard for cut and paste of subtrees.
5794 This is actually only a copy of the kill, because we use the normal kill
5795 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5797 (defvar org-subtree-clip-folded nil
5798 "Was the last copied subtree folded?
5799 This is used to fold the tree back after pasting.")
5801 (defun org-cut-subtree (&optional n)
5802 "Cut the current subtree into the clipboard.
5803 With prefix arg N, cut this many sequential subtrees.
5804 This is a short-hand for marking the subtree and then cutting it."
5805 (interactive "p")
5806 (org-copy-subtree n 'cut))
5808 (defun org-copy-subtree (&optional n cut force-store-markers)
5809 "Cut the current subtree into the clipboard.
5810 With prefix arg N, cut this many sequential subtrees.
5811 This is a short-hand for marking the subtree and then copying it.
5812 If CUT is non-nil, actually cut the subtree.
5813 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5814 of some markers in the region, even if CUT is non-nil. This is
5815 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5816 (interactive "p")
5817 (let (beg end folded (beg0 (point)))
5818 (if (interactive-p)
5819 (org-back-to-heading nil) ; take what looks like a subtree
5820 (org-back-to-heading t)) ; take what is really there
5821 (org-back-over-empty-lines)
5822 (setq beg (point))
5823 (skip-chars-forward " \t\r\n")
5824 (save-match-data
5825 (save-excursion (outline-end-of-heading)
5826 (setq folded (org-invisible-p)))
5827 (condition-case nil
5828 (outline-forward-same-level (1- n))
5829 (error nil))
5830 (org-end-of-subtree t t))
5831 (org-back-over-empty-lines)
5832 (setq end (point))
5833 (goto-char beg0)
5834 (when (> end beg)
5835 (setq org-subtree-clip-folded folded)
5836 (when (or cut force-store-markers)
5837 (org-save-markers-in-region beg end))
5838 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5839 (setq org-subtree-clip (current-kill 0))
5840 (message "%s: Subtree(s) with %d characters"
5841 (if cut "Cut" "Copied")
5842 (length org-subtree-clip)))))
5844 (defun org-paste-subtree (&optional level tree for-yank)
5845 "Paste the clipboard as a subtree, with modification of headline level.
5846 The entire subtree is promoted or demoted in order to match a new headline
5847 level.
5849 If the cursor is at the beginning of a headline, the same level as
5850 that headline is used to paste the tree
5852 If not, the new level is derived from the *visible* headings
5853 before and after the insertion point, and taken to be the inferior headline
5854 level of the two. So if the previous visible heading is level 3 and the
5855 next is level 4 (or vice versa), level 4 will be used for insertion.
5856 This makes sure that the subtree remains an independent subtree and does
5857 not swallow low level entries.
5859 You can also force a different level, either by using a numeric prefix
5860 argument, or by inserting the heading marker by hand. For example, if the
5861 cursor is after \"*****\", then the tree will be shifted to level 5.
5863 If optional TREE is given, use this text instead of the kill ring.
5865 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5866 move back over whitespace before inserting, and move point to the end of
5867 the inserted text when done."
5868 (interactive "P")
5869 (unless (org-kill-is-subtree-p tree)
5870 (error "%s"
5871 (substitute-command-keys
5872 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5873 (let* ((visp (not (org-invisible-p)))
5874 (txt (or tree (and kill-ring (current-kill 0))))
5875 (^re (concat "^\\(" outline-regexp "\\)"))
5876 (re (concat "\\(" outline-regexp "\\)"))
5877 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5879 (old-level (if (string-match ^re txt)
5880 (- (match-end 0) (match-beginning 0) 1)
5881 -1))
5882 (force-level (cond (level (prefix-numeric-value level))
5883 ((and (looking-at "[ \t]*$")
5884 (string-match
5885 ^re_ (buffer-substring
5886 (point-at-bol) (point))))
5887 (- (match-end 1) (match-beginning 1)))
5888 ((and (bolp)
5889 (looking-at org-outline-regexp))
5890 (- (match-end 0) (point) 1))
5891 (t nil)))
5892 (previous-level (save-excursion
5893 (condition-case nil
5894 (progn
5895 (outline-previous-visible-heading 1)
5896 (if (looking-at re)
5897 (- (match-end 0) (match-beginning 0) 1)
5899 (error 1))))
5900 (next-level (save-excursion
5901 (condition-case nil
5902 (progn
5903 (or (looking-at outline-regexp)
5904 (outline-next-visible-heading 1))
5905 (if (looking-at re)
5906 (- (match-end 0) (match-beginning 0) 1)
5908 (error 1))))
5909 (new-level (or force-level (max previous-level next-level)))
5910 (shift (if (or (= old-level -1)
5911 (= new-level -1)
5912 (= old-level new-level))
5914 (- new-level old-level)))
5915 (delta (if (> shift 0) -1 1))
5916 (func (if (> shift 0) 'org-demote 'org-promote))
5917 (org-odd-levels-only nil)
5918 beg end newend)
5919 ;; Remove the forced level indicator
5920 (if force-level
5921 (delete-region (point-at-bol) (point)))
5922 ;; Paste
5923 (beginning-of-line 1)
5924 (unless for-yank (org-back-over-empty-lines))
5925 (setq beg (point))
5926 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5927 (insert-before-markers txt)
5928 (unless (string-match "\n\\'" txt) (insert "\n"))
5929 (setq newend (point))
5930 (org-reinstall-markers-in-region beg)
5931 (setq end (point))
5932 (goto-char beg)
5933 (skip-chars-forward " \t\n\r")
5934 (setq beg (point))
5935 (if (and (org-invisible-p) visp)
5936 (save-excursion (outline-show-heading)))
5937 ;; Shift if necessary
5938 (unless (= shift 0)
5939 (save-restriction
5940 (narrow-to-region beg end)
5941 (while (not (= shift 0))
5942 (org-map-region func (point-min) (point-max))
5943 (setq shift (+ delta shift)))
5944 (goto-char (point-min))
5945 (setq newend (point-max))))
5946 (when (or (interactive-p) for-yank)
5947 (message "Clipboard pasted as level %d subtree" new-level))
5948 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5949 kill-ring
5950 (eq org-subtree-clip (current-kill 0))
5951 org-subtree-clip-folded)
5952 ;; The tree was folded before it was killed/copied
5953 (hide-subtree))
5954 (and for-yank (goto-char newend))))
5956 (defun org-kill-is-subtree-p (&optional txt)
5957 "Check if the current kill is an outline subtree, or a set of trees.
5958 Returns nil if kill does not start with a headline, or if the first
5959 headline level is not the largest headline level in the tree.
5960 So this will actually accept several entries of equal levels as well,
5961 which is OK for `org-paste-subtree'.
5962 If optional TXT is given, check this string instead of the current kill."
5963 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5964 (start-level (and kill
5965 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5966 org-outline-regexp "\\)")
5967 kill)
5968 (- (match-end 2) (match-beginning 2) 1)))
5969 (re (concat "^" org-outline-regexp))
5970 (start (1+ (or (match-beginning 2) -1))))
5971 (if (not start-level)
5972 (progn
5973 nil) ;; does not even start with a heading
5974 (catch 'exit
5975 (while (setq start (string-match re kill (1+ start)))
5976 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5977 (throw 'exit nil)))
5978 t))))
5980 (defvar org-markers-to-move nil
5981 "Markers that should be moved with a cut-and-paste operation.
5982 Those markers are stored together with their positions relative to
5983 the start of the region.")
5985 (defun org-save-markers-in-region (beg end)
5986 "Check markers in region.
5987 If these markers are between BEG and END, record their position relative
5988 to BEG, so that after moving the block of text, we can put the markers back
5989 into place.
5990 This function gets called just before an entry or tree gets cut from the
5991 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5992 called immediately, to move the markers with the entries."
5993 (setq org-markers-to-move nil)
5994 (when (featurep 'org-clock)
5995 (org-clock-save-markers-for-cut-and-paste beg end))
5996 (when (featurep 'org-agenda)
5997 (org-agenda-save-markers-for-cut-and-paste beg end)))
5999 (defun org-check-and-save-marker (marker beg end)
6000 "Check if MARKER is between BEG and END.
6001 If yes, remember the marker and the distance to BEG."
6002 (when (and (marker-buffer marker)
6003 (equal (marker-buffer marker) (current-buffer)))
6004 (if (and (>= marker beg) (< marker end))
6005 (push (cons marker (- marker beg)) org-markers-to-move))))
6007 (defun org-reinstall-markers-in-region (beg)
6008 "Move all remembered markers to their position relative to BEG."
6009 (mapc (lambda (x)
6010 (move-marker (car x) (+ beg (cdr x))))
6011 org-markers-to-move)
6012 (setq org-markers-to-move nil))
6014 (defun org-narrow-to-subtree ()
6015 "Narrow buffer to the current subtree."
6016 (interactive)
6017 (save-excursion
6018 (save-match-data
6019 (narrow-to-region
6020 (progn (org-back-to-heading) (point))
6021 (progn (org-end-of-subtree t) (point))))))
6023 (defun org-clone-subtree-with-time-shift (n &optional shift)
6024 "Clone the task (subtree) at point N times.
6025 The clones will be inserted as siblings.
6027 In interactive use, the user will be prompted for the number of clones
6028 to be produced, and for a time SHIFT, which may be a repeater as used
6029 in time stamps, for example `+3d'.
6031 When a valid repeater is given and the entry contains any time stamps,
6032 the clones will become a sequence in time, with time stamps in the
6033 subtree shifted for each clone produced. If SHIFT is nil or the
6034 empty string, time stamps will be left alone.
6036 If the original subtree did contain time stamps with a repeater,
6037 the following will happen:
6038 - the repeater will be removed in each clone
6039 - an additional clone will be produced, with the current, unshifted
6040 date(s) in the entry.
6041 - the original entry will be placed *after* all the clones, with
6042 repeater intact.
6043 - the start days in the repeater in the original entry will be shifted
6044 to past the last clone.
6045 I this way you can spell out a number of instances of a repeating task,
6046 and still retain the repeater to cover future instances of the task."
6047 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6048 (let (beg end template task
6049 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6050 (if (not (and (integerp n) (> n 0)))
6051 (error "Invalid number of replications %s" n))
6052 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6053 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6054 shift)))
6055 (error "Invalid shift specification %s" shift))
6056 (when doshift
6057 (setq shift-n (string-to-number (match-string 1 shift))
6058 shift-what (cdr (assoc (match-string 2 shift)
6059 '(("d" . day) ("w" . week)
6060 ("m" . month) ("y" . year))))))
6061 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6062 (setq nmin 1 nmax n)
6063 (org-back-to-heading t)
6064 (setq beg (point))
6065 (org-end-of-subtree t t)
6066 (setq end (point))
6067 (setq template (buffer-substring beg end))
6068 (when (and doshift
6069 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6070 (delete-region beg end)
6071 (setq end beg)
6072 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6073 (goto-char end)
6074 (loop for n from nmin to nmax do
6075 (if (not doshift)
6076 (setq task template)
6077 (with-temp-buffer
6078 (insert template)
6079 (org-mode)
6080 (goto-char (point-min))
6081 (while (re-search-forward org-ts-regexp nil t)
6082 (org-timestamp-change (* n shift-n) shift-what))
6083 (unless (= n n-no-remove)
6084 (goto-char (point-min))
6085 (while (re-search-forward org-ts-regexp nil t)
6086 (save-excursion
6087 (goto-char (match-beginning 0))
6088 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6089 (delete-region (match-beginning 1) (match-end 1))))))
6090 (setq task (buffer-string))))
6091 (insert task))
6092 (goto-char beg)))
6094 ;;; Outline Sorting
6096 (defun org-sort (with-case)
6097 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6098 Optional argument WITH-CASE means sort case-sensitively.
6099 With a double prefix argument, also remove duplicate entries."
6100 (interactive "P")
6101 (if (org-at-table-p)
6102 (org-call-with-arg 'org-table-sort-lines with-case)
6103 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6105 (defun org-sort-remove-invisible (s)
6106 (remove-text-properties 0 (length s) org-rm-props s)
6107 (while (string-match org-bracket-link-regexp s)
6108 (setq s (replace-match (if (match-end 2)
6109 (match-string 3 s)
6110 (match-string 1 s)) t t s)))
6113 (defvar org-priority-regexp) ; defined later in the file
6115 (defvar org-after-sorting-entries-or-items-hook nil
6116 "Hook that is run after a bunch of entries or items have been sorted.
6117 When children are sorted, the cursor is in the parent line when this
6118 hook gets called. When a region or a plain list is sorted, the cursor
6119 will be in the first entry of the sorted region/list.")
6121 (defun org-sort-entries-or-items
6122 (&optional with-case sorting-type getkey-func compare-func property)
6123 "Sort entries on a certain level of an outline tree, or plain list items.
6124 If there is an active region, the entries in the region are sorted.
6125 Else, if the cursor is before the first entry, sort the top-level items.
6126 Else, the children of the entry at point are sorted.
6127 If the cursor is at the first item in a plain list, the list items will be
6128 sorted.
6130 Sorting can be alphabetically, numerically, by date/time as given by
6131 a time stamp, by a property or by priority.
6133 The command prompts for the sorting type unless it has been given to the
6134 function through the SORTING-TYPE argument, which needs to a character,
6135 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6136 precise meaning of each character:
6138 n Numerically, by converting the beginning of the entry/item to a number.
6139 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6140 t By date/time, either the first active time stamp in the entry, or, if
6141 none exist, by the first inactive one.
6142 In items, only the first line will be chekced.
6143 s By the scheduled date/time.
6144 d By deadline date/time.
6145 c By creation time, which is assumed to be the first inactive time stamp
6146 at the beginning of a line.
6147 p By priority according to the cookie.
6148 r By the value of a property.
6150 Capital letters will reverse the sort order.
6152 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6153 called with point at the beginning of the record. It must return either
6154 a string or a number that should serve as the sorting key for that record.
6156 Comparing entries ignores case by default. However, with an optional argument
6157 WITH-CASE, the sorting considers case as well."
6158 (interactive "P")
6159 (let ((case-func (if with-case 'identity 'downcase))
6160 start beg end stars re re2
6161 txt what tmp plain-list-p)
6162 ;; Find beginning and end of region to sort
6163 (cond
6164 ((org-region-active-p)
6165 ;; we will sort the region
6166 (setq end (region-end)
6167 what "region")
6168 (goto-char (region-beginning))
6169 (if (not (org-on-heading-p)) (outline-next-heading))
6170 (setq start (point)))
6171 ((org-at-item-p)
6172 ;; we will sort this plain list
6173 (org-beginning-of-item-list) (setq start (point))
6174 (org-end-of-item-list) (setq end (point))
6175 (goto-char start)
6176 (setq plain-list-p t
6177 what "plain list"))
6178 ((or (org-on-heading-p)
6179 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6180 ;; we will sort the children of the current headline
6181 (org-back-to-heading)
6182 (setq start (point)
6183 end (progn (org-end-of-subtree t t)
6184 (org-back-over-empty-lines)
6185 (point))
6186 what "children")
6187 (goto-char start)
6188 (show-subtree)
6189 (outline-next-heading))
6191 ;; we will sort the top-level entries in this file
6192 (goto-char (point-min))
6193 (or (org-on-heading-p) (outline-next-heading))
6194 (setq start (point) end (point-max) what "top-level")
6195 (goto-char start)
6196 (show-all)))
6198 (setq beg (point))
6199 (if (>= beg end) (error "Nothing to sort"))
6201 (unless plain-list-p
6202 (looking-at "\\(\\*+\\)")
6203 (setq stars (match-string 1)
6204 re (concat "^" (regexp-quote stars) " +")
6205 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6206 txt (buffer-substring beg end))
6207 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6208 (if (and (not (equal stars "*")) (string-match re2 txt))
6209 (error "Region to sort contains a level above the first entry")))
6211 (unless sorting-type
6212 (message
6213 (if plain-list-p
6214 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6215 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
6216 [t]ime [s ]cheduled [d]eadline [c]reated
6217 A/N/T/S/D/C/P/O/F means reversed:")
6218 what)
6219 (setq sorting-type (read-char-exclusive))
6221 (and (= (downcase sorting-type) ?f)
6222 (setq getkey-func
6223 (org-ido-completing-read "Sort using function: "
6224 obarray 'fboundp t nil nil))
6225 (setq getkey-func (intern getkey-func)))
6227 (and (= (downcase sorting-type) ?r)
6228 (setq property
6229 (org-ido-completing-read "Property: "
6230 (mapcar 'list (org-buffer-property-keys t))
6231 nil t))))
6233 (message "Sorting entries...")
6235 (save-restriction
6236 (narrow-to-region start end)
6238 (let ((dcst (downcase sorting-type))
6239 (case-fold-search nil)
6240 (now (current-time)))
6241 (sort-subr
6242 (/= dcst sorting-type)
6243 ;; This function moves to the beginning character of the "record" to
6244 ;; be sorted.
6245 (if plain-list-p
6246 (lambda nil
6247 (if (org-at-item-p) t (goto-char (point-max))))
6248 (lambda nil
6249 (if (re-search-forward re nil t)
6250 (goto-char (match-beginning 0))
6251 (goto-char (point-max)))))
6252 ;; This function moves to the last character of the "record" being
6253 ;; sorted.
6254 (if plain-list-p
6255 'org-end-of-item
6256 (lambda nil
6257 (save-match-data
6258 (condition-case nil
6259 (outline-forward-same-level 1)
6260 (error
6261 (goto-char (point-max)))))))
6263 ;; This function returns the value that gets sorted against.
6264 (if plain-list-p
6265 (lambda nil
6266 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6267 (cond
6268 ((= dcst ?n)
6269 (string-to-number (buffer-substring (match-end 0)
6270 (point-at-eol))))
6271 ((= dcst ?a)
6272 (buffer-substring (match-end 0) (point-at-eol)))
6273 ((= dcst ?t)
6274 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
6275 (re-search-forward org-ts-regexp-both
6276 (point-at-eol) t))
6277 (time-to-seconds
6278 (org-time-string-to-time (match-string 0)))
6279 (time-to-seconds now)))
6280 ((= dcst ?f)
6281 (if getkey-func
6282 (progn
6283 (setq tmp (funcall getkey-func))
6284 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6285 tmp)
6286 (error "Invalid key function `%s'" getkey-func)))
6287 (t (error "Invalid sorting type `%c'" sorting-type)))))
6288 (lambda nil
6289 (cond
6290 ((= dcst ?n)
6291 (if (looking-at org-complex-heading-regexp)
6292 (string-to-number (match-string 4))
6293 nil))
6294 ((= dcst ?a)
6295 (if (looking-at org-complex-heading-regexp)
6296 (funcall case-func (match-string 4))
6297 nil))
6298 ((= dcst ?t)
6299 (let ((end (save-excursion (outline-next-heading) (point))))
6300 (if (or (re-search-forward org-ts-regexp end t)
6301 (re-search-forward org-ts-regexp-both end t))
6302 (org-time-string-to-time (match-string 0))
6303 (org-time-string-to-time now))))
6304 ((= dcst ?c)
6305 (let ((end (save-excursion (outline-next-heading) (point))))
6306 (if (re-search-forward
6307 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
6308 end t)
6309 (time-to-seconds (org-time-string-to-time
6310 (match-string 0)))
6311 (time-to-seconds now))))
6312 ((= dcst ?s)
6313 (let ((end (save-excursion (outline-next-heading) (point))))
6314 (if (re-search-forward org-scheduled-time-regexp end t)
6315 (org-time-string-to-time (match-string 1))
6316 (org-time-string-to-time now))))
6317 ((= dcst ?d)
6318 (let ((end (save-excursion (outline-next-heading) (point))))
6319 (if (re-search-forward org-deadline-time-regexp end t)
6320 (org-time-string-to-time (match-string 1))
6321 (org-time-string-to-time now))))
6322 ((= dcst ?p)
6323 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6324 (string-to-char (match-string 2))
6325 org-default-priority))
6326 ((= dcst ?r)
6327 (or (org-entry-get nil property) ""))
6328 ((= dcst ?o)
6329 (if (looking-at org-complex-heading-regexp)
6330 (- 9999 (length (member (match-string 2)
6331 org-todo-keywords-1)))))
6332 ((= dcst ?f)
6333 (if getkey-func
6334 (progn
6335 (setq tmp (funcall getkey-func))
6336 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6337 tmp)
6338 (error "Invalid key function `%s'" getkey-func)))
6339 (t (error "Invalid sorting type `%c'" sorting-type)))))
6341 (cond
6342 ((= dcst ?a) 'string<)
6343 ((= dcst ?t) 'time-less-p)
6344 ((= dcst ?f) compare-func)
6345 ((= dcst ?p) '<)
6346 (t nil)))))
6347 (run-hooks 'org-after-sorting-entries-or-items-hook)
6348 (message "Sorting entries...done")))
6350 (defun org-do-sort (table what &optional with-case sorting-type)
6351 "Sort TABLE of WHAT according to SORTING-TYPE.
6352 The user will be prompted for the SORTING-TYPE if the call to this
6353 function does not specify it. WHAT is only for the prompt, to indicate
6354 what is being sorted. The sorting key will be extracted from
6355 the car of the elements of the table.
6356 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6357 (unless sorting-type
6358 (message
6359 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6360 what)
6361 (setq sorting-type (read-char-exclusive)))
6362 (let ((dcst (downcase sorting-type))
6363 extractfun comparefun)
6364 ;; Define the appropriate functions
6365 (cond
6366 ((= dcst ?n)
6367 (setq extractfun 'string-to-number
6368 comparefun (if (= dcst sorting-type) '< '>)))
6369 ((= dcst ?a)
6370 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6371 (lambda(x) (downcase (org-sort-remove-invisible x))))
6372 comparefun (if (= dcst sorting-type)
6373 'string<
6374 (lambda (a b) (and (not (string< a b))
6375 (not (string= a b)))))))
6376 ((= dcst ?t)
6377 (setq extractfun
6378 (lambda (x)
6379 (if (or (string-match org-ts-regexp x)
6380 (string-match org-ts-regexp-both x))
6381 (time-to-seconds
6382 (org-time-string-to-time (match-string 0 x)))
6384 comparefun (if (= dcst sorting-type) '< '>)))
6385 (t (error "Invalid sorting type `%c'" sorting-type)))
6387 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6388 table)
6389 (lambda (a b) (funcall comparefun (car a) (car b))))))
6391 ;;; Editing source examples
6393 (defvar org-exit-edit-mode-map (make-sparse-keymap))
6394 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
6395 (defvar org-edit-src-force-single-line nil)
6396 (defvar org-edit-src-from-org-mode nil)
6397 (defvar org-edit-src-picture nil)
6398 (defvar org-edit-src-beg-marker nil)
6399 (defvar org-edit-src-end-marker nil)
6400 (defvar org-edit-src-overlay nil)
6402 (define-minor-mode org-exit-edit-mode
6403 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
6405 (defun org-edit-src-code ()
6406 "Edit the source code example at point.
6407 The example is copied to a separate buffer, and that buffer is switched
6408 to the correct language mode. When done, exit with \\[org-edit-src-exit].
6409 This will remove the original code in the Org buffer, and replace it with
6410 the edited version."
6411 (interactive)
6412 (let ((line (org-current-line))
6413 (case-fold-search t)
6414 (msg (substitute-command-keys
6415 "Edit, then exit with C-c ' (C-c and single quote)"))
6416 (info (org-edit-src-find-region-and-lang))
6417 (org-mode-p (eq major-mode 'org-mode))
6418 (beg (make-marker))
6419 (end (make-marker))
6420 ovl lang lang-f single lfmt code begline buffer)
6421 (if (not info)
6423 (setq beg (move-marker beg (nth 0 info))
6424 end (move-marker end (nth 1 info))
6425 code (buffer-substring-no-properties beg end)
6426 lang (nth 2 info)
6427 single (nth 3 info)
6428 lfmt (nth 4 info)
6429 lang-f (intern (concat lang "-mode"))
6430 begline (save-excursion (goto-char beg) (org-current-line)))
6431 (unless (functionp lang-f)
6432 (error "No such language mode: %s" lang-f))
6433 (goto-line line)
6434 (if (and (setq buffer (org-edit-src-find-buffer beg end))
6435 (y-or-n-p "Return to existing edit buffer? [n] will revert changes: "))
6436 (switch-to-buffer buffer)
6437 (when buffer
6438 (with-current-buffer buffer
6439 (if (boundp 'org-edit-src-overlay)
6440 (org-delete-overlay org-edit-src-overlay)))
6441 (kill-buffer buffer))
6442 (setq buffer (generate-new-buffer "*Org Edit Src Example*"))
6443 (setq ovl (org-make-overlay beg end))
6444 (org-overlay-put ovl 'face 'secondary-selection)
6445 (org-overlay-put ovl 'edit-buffer buffer)
6446 (org-overlay-put ovl 'help-echo "Click with mouse-1 to switch to buffer editing this segment")
6447 (org-overlay-put ovl 'face 'secondary-selection)
6448 (org-overlay-put ovl
6449 'keymap
6450 (let ((map (make-sparse-keymap)))
6451 (define-key map [mouse-1] 'org-edit-src-continue)
6452 map))
6453 (org-overlay-put ovl :read-only "Leave me alone")
6454 (switch-to-buffer buffer)
6455 (insert code)
6456 (remove-text-properties (point-min) (point-max)
6457 '(display nil invisible nil intangible nil))
6458 (let ((org-inhibit-startup t))
6459 (funcall lang-f))
6460 (set (make-local-variable 'org-edit-src-force-single-line) single)
6461 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6462 (when lfmt
6463 (set (make-local-variable 'org-coderef-label-format) lfmt))
6464 (when org-mode-p
6465 (goto-char (point-min))
6466 (while (re-search-forward "^," nil t)
6467 (replace-match "")))
6468 (goto-line (1+ (- line begline)))
6469 (org-exit-edit-mode)
6470 (org-set-local 'org-edit-src-beg-marker beg)
6471 (org-set-local 'org-edit-src-end-marker end)
6472 (org-set-local 'org-edit-src-overlay ovl)
6473 (and org-edit-src-persistent-message
6474 (org-set-local 'header-line-format msg)))
6475 (message "%s" msg)
6476 t)))
6478 (defun org-edit-src-continue (e)
6479 (interactive "e")
6480 (mouse-set-point e)
6481 (let ((buf (get-char-property (point) 'edit-buffer)))
6482 (if buf (switch-to-buffer buf)
6483 (error "Something is wrong here"))))
6485 (defun org-edit-src-find-buffer (beg end)
6486 "Find a source editing buffer that is already editing the region BEG to END."
6487 (catch 'exit
6488 (mapc
6489 (lambda (b)
6490 (with-current-buffer b
6491 (if (and (string-match "\\`*Org Edit " (buffer-name))
6492 (local-variable-p 'org-edit-src-beg-marker (current-buffer))
6493 (local-variable-p 'org-edit-src-end-marker (current-buffer))
6494 (equal beg org-edit-src-beg-marker)
6495 (equal end org-edit-src-end-marker))
6496 (throw 'exit (current-buffer)))))
6497 (buffer-list))
6498 nil))
6500 (defun org-edit-fixed-width-region ()
6501 "Edit the fixed-width ascii drawing at point.
6502 This must be a region where each line starts with a colon followed by
6503 a space character.
6504 An new buffer is created and the fixed-width region is copied into it,
6505 and the buffer is switched into `artist-mode' for editing. When done,
6506 exit with \\[org-edit-src-exit]. The edited text will then replace
6507 the fragment in the Org-mode buffer."
6508 (interactive)
6509 (let ((line (org-current-line))
6510 (case-fold-search t)
6511 (msg (substitute-command-keys
6512 "Edit, then exit with C-c ' (C-c and single quote)"))
6513 (org-mode-p (eq major-mode 'org-mode))
6514 (beg (make-marker))
6515 (end (make-marker))
6516 ovl beg1 end1 code begline buffer)
6517 (beginning-of-line 1)
6518 (if (looking-at "[ \t]*[^:\n \t]")
6520 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
6521 (setq beg1 (point) end1 beg1)
6522 (save-excursion
6523 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
6524 (setq beg1 (point-at-bol 2))
6525 (setq beg1 (point))))
6526 (save-excursion
6527 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
6528 (setq end1 (1- (match-beginning 0)))
6529 (setq end1 (point))))
6530 (goto-line line))
6531 (setq beg (move-marker beg beg1)
6532 end (move-marker end end1)
6533 code (buffer-substring-no-properties beg end)
6534 begline (save-excursion (goto-char beg) (org-current-line)))
6535 (if (and (setq buffer (org-edit-src-find-buffer beg end))
6536 (y-or-n-p "Return to existing edit buffer? [n] will revert changes: "))
6537 (switch-to-buffer buffer)
6538 (when buffer
6539 (with-current-buffer buffer
6540 (if (boundp 'org-edit-src-overlay)
6541 (org-delete-overlay org-edit-src-overlay)))
6542 (kill-buffer buffer))
6543 (setq buffer (generate-new-buffer "*Org Edit Src Example*"))
6544 (setq ovl (org-make-overlay beg end))
6545 (org-overlay-put ovl 'face 'secondary-selection)
6546 (org-overlay-put ovl 'edit-buffer buffer)
6547 (org-overlay-put ovl 'help-echo "Click with mouse-1 to switch to buffer editing this segment")
6548 (org-overlay-put ovl 'face 'secondary-selection)
6549 (org-overlay-put ovl
6550 'keymap
6551 (let ((map (make-sparse-keymap)))
6552 (define-key map [mouse-1] 'org-edit-src-continue)
6553 map))
6554 (org-overlay-put ovl :read-only "Leave me alone")
6555 (switch-to-buffer buffer)
6556 (insert code)
6557 (remove-text-properties (point-min) (point-max)
6558 '(display nil invisible nil intangible nil))
6559 (cond
6560 ((eq org-edit-fixed-width-region-mode 'artist-mode)
6561 (fundamental-mode)
6562 (artist-mode 1))
6563 (t (funcall org-edit-fixed-width-region-mode)))
6564 (set (make-local-variable 'org-edit-src-force-single-line) nil)
6565 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6566 (set (make-local-variable 'org-edit-src-picture) t)
6567 (goto-char (point-min))
6568 (while (re-search-forward "^[ \t]*: ?" nil t)
6569 (replace-match ""))
6570 (goto-line (1+ (- line begline)))
6571 (org-exit-edit-mode)
6572 (org-set-local 'org-edit-src-beg-marker beg)
6573 (org-set-local 'org-edit-src-end-marker end)
6574 (org-set-local 'org-edit-src-overlay ovl)
6575 (and org-edit-src-persistent-message
6576 (org-set-local 'header-line-format msg)))
6577 (message "%s" msg)
6578 t)))
6580 (defun org-edit-src-find-region-and-lang ()
6581 "Find the region and language for a local edit.
6582 Return a list with beginning and end of the region, a string representing
6583 the language, a switch telling of the content should be in a single line."
6584 (let ((re-list
6585 (append
6586 org-edit-src-region-extra
6588 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
6589 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
6590 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
6591 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
6592 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
6593 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
6594 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
6595 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
6596 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
6597 ("^#\\+html:" "\n" "html" single-line)
6598 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
6599 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
6600 ("^#\\+latex:" "\n" "latex" single-line)
6601 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
6602 ("^#\\+ascii:" "\n" "ascii" single-line)
6604 (pos (point))
6605 re1 re2 single beg end lang lfmt match-re1)
6606 (catch 'exit
6607 (while (setq entry (pop re-list))
6608 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
6609 single (nth 3 entry))
6610 (save-excursion
6611 (if (or (looking-at re1)
6612 (re-search-backward re1 nil t))
6613 (progn
6614 (setq match-re1 (match-string 0))
6615 (setq beg (match-end 0)
6616 lang (org-edit-src-get-lang lang)
6617 lfmt (org-edit-src-get-label-format match-re1))
6618 (if (and (re-search-forward re2 nil t)
6619 (>= (match-end 0) pos))
6620 (throw 'exit (list beg (match-beginning 0)
6621 lang single lfmt))))
6622 (if (or (looking-at re2)
6623 (re-search-forward re2 nil t))
6624 (progn
6625 (setq end (match-beginning 0))
6626 (if (and (re-search-backward re1 nil t)
6627 (<= (match-beginning 0) pos))
6628 (progn
6629 (setq lfmt (org-edit-src-get-label-format
6630 (match-string 0)))
6631 (throw 'exit
6632 (list (match-end 0) end
6633 (org-edit-src-get-lang lang)
6634 single lfmt))))))))))))
6636 (defun org-edit-src-get-lang (lang)
6637 "Extract the src language."
6638 (let ((m (match-string 0)))
6639 (cond
6640 ((stringp lang) lang)
6641 ((integerp lang) (match-string lang))
6642 ((and (eq lang 'lang)
6643 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
6644 (match-string 1 m))
6645 ((and (eq lang 'style)
6646 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
6647 (match-string 1 m))
6648 (t "fundamental"))))
6650 (defun org-edit-src-get-label-format (s)
6651 "Extract the label format."
6652 (save-match-data
6653 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
6654 (match-string 1 s))))
6656 (defun org-edit-src-exit ()
6657 "Exit special edit and protect problematic lines."
6658 (interactive)
6659 (unless (string-match "\\`*Org Edit " (buffer-name (current-buffer)))
6660 (error "This is not an sub-editing buffer, something is wrong..."))
6661 (let ((line (if (org-bound-and-true-p org-edit-src-force-single-line)
6663 (org-current-line)))
6664 (beg org-edit-src-beg-marker)
6665 (end org-edit-src-end-marker)
6666 (ovl org-edit-src-overlay)
6667 (buffer (current-buffer))
6668 code)
6669 (goto-char (point-min))
6670 (if (looking-at "[ \t\n]*\n") (replace-match ""))
6671 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
6672 (when (org-bound-and-true-p org-edit-src-force-single-line)
6673 (goto-char (point-min))
6674 (while (re-search-forward "\n" nil t)
6675 (replace-match " "))
6676 (goto-char (point-min))
6677 (if (looking-at "\\s-*") (replace-match " "))
6678 (if (re-search-forward "\\s-+\\'" nil t)
6679 (replace-match "")))
6680 (when (org-bound-and-true-p org-edit-src-from-org-mode)
6681 (goto-char (point-min))
6682 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
6683 (replace-match ",\\1"))
6684 (when font-lock-mode
6685 (font-lock-unfontify-region (point-min) (point-max)))
6686 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6687 (when (org-bound-and-true-p org-edit-src-picture)
6688 (untabify (point-min) (point-max))
6689 (goto-char (point-min))
6690 (while (re-search-forward "^" nil t)
6691 (replace-match ": "))
6692 (when font-lock-mode
6693 (font-lock-unfontify-region (point-min) (point-max)))
6694 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6695 (setq code (buffer-string))
6696 (switch-to-buffer (marker-buffer beg))
6697 (kill-buffer buffer)
6698 (goto-char beg)
6699 (org-delete-overlay ovl)
6700 (delete-region beg end)
6701 (insert code)
6702 (goto-char beg)
6703 (goto-line (1- (+ (org-current-line) line)))
6704 (move-marker beg nil)
6705 (move-marker end nil)))
6708 ;;; The orgstruct minor mode
6710 ;; Define a minor mode which can be used in other modes in order to
6711 ;; integrate the org-mode structure editing commands.
6713 ;; This is really a hack, because the org-mode structure commands use
6714 ;; keys which normally belong to the major mode. Here is how it
6715 ;; works: The minor mode defines all the keys necessary to operate the
6716 ;; structure commands, but wraps the commands into a function which
6717 ;; tests if the cursor is currently at a headline or a plain list
6718 ;; item. If that is the case, the structure command is used,
6719 ;; temporarily setting many Org-mode variables like regular
6720 ;; expressions for filling etc. However, when any of those keys is
6721 ;; used at a different location, function uses `key-binding' to look
6722 ;; up if the key has an associated command in another currently active
6723 ;; keymap (minor modes, major mode, global), and executes that
6724 ;; command. There might be problems if any of the keys is otherwise
6725 ;; used as a prefix key.
6727 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6728 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6729 ;; addresses this by checking explicitly for both bindings.
6731 (defvar orgstruct-mode-map (make-sparse-keymap)
6732 "Keymap for the minor `orgstruct-mode'.")
6734 (defvar org-local-vars nil
6735 "List of local variables, for use by `orgstruct-mode'")
6737 ;;;###autoload
6738 (define-minor-mode orgstruct-mode
6739 "Toggle the minor more `orgstruct-mode'.
6740 This mode is for using Org-mode structure commands in other modes.
6741 The following key behave as if Org-mode was active, if the cursor
6742 is on a headline, or on a plain list item (both in the definition
6743 of Org-mode).
6745 M-up Move entry/item up
6746 M-down Move entry/item down
6747 M-left Promote
6748 M-right Demote
6749 M-S-up Move entry/item up
6750 M-S-down Move entry/item down
6751 M-S-left Promote subtree
6752 M-S-right Demote subtree
6753 M-q Fill paragraph and items like in Org-mode
6754 C-c ^ Sort entries
6755 C-c - Cycle list bullet
6756 TAB Cycle item visibility
6757 M-RET Insert new heading/item
6758 S-M-RET Insert new TODO heading / Checkbox item
6759 C-c C-c Set tags / toggle checkbox"
6760 nil " OrgStruct" nil
6761 (org-load-modules-maybe)
6762 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6764 ;;;###autoload
6765 (defun turn-on-orgstruct ()
6766 "Unconditionally turn on `orgstruct-mode'."
6767 (orgstruct-mode 1))
6769 (defun orgstruct++-mode (&optional arg)
6770 "Toggle `orgstruct-mode', the enhanced version of it.
6771 In addition to setting orgstruct-mode, this also exports all indentation and
6772 autofilling variables from org-mode into the buffer. It will also
6773 recognize item context in multiline items.
6774 Note that turning off orgstruct-mode will *not* remove the
6775 indentation/paragraph settings. This can only be done by refreshing the
6776 major mode, for example with \[normal-mode]."
6777 (interactive "P")
6778 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6779 (if (< arg 1)
6780 (orgstruct-mode -1)
6781 (orgstruct-mode 1)
6782 (let (var val)
6783 (mapc
6784 (lambda (x)
6785 (when (string-match
6786 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6787 (symbol-name (car x)))
6788 (setq var (car x) val (nth 1 x))
6789 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6790 org-local-vars)
6791 (org-set-local 'orgstruct-is-++ t))))
6793 (defvar orgstruct-is-++ nil
6794 "Is orgstruct-mode in ++ version in the current-buffer?")
6795 (make-variable-buffer-local 'orgstruct-is-++)
6797 ;;;###autoload
6798 (defun turn-on-orgstruct++ ()
6799 "Unconditionally turn on `orgstruct++-mode'."
6800 (orgstruct++-mode 1))
6802 (defun orgstruct-error ()
6803 "Error when there is no default binding for a structure key."
6804 (interactive)
6805 (error "This key has no function outside structure elements"))
6807 (defun orgstruct-setup ()
6808 "Setup orgstruct keymaps."
6809 (let ((nfunc 0)
6810 (bindings
6811 (list
6812 '([(meta up)] org-metaup)
6813 '([(meta down)] org-metadown)
6814 '([(meta left)] org-metaleft)
6815 '([(meta right)] org-metaright)
6816 '([(meta shift up)] org-shiftmetaup)
6817 '([(meta shift down)] org-shiftmetadown)
6818 '([(meta shift left)] org-shiftmetaleft)
6819 '([(meta shift right)] org-shiftmetaright)
6820 '([(shift up)] org-shiftup)
6821 '([(shift down)] org-shiftdown)
6822 '([(shift left)] org-shiftleft)
6823 '([(shift right)] org-shiftright)
6824 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6825 '("\M-q" fill-paragraph)
6826 '("\C-c^" org-sort)
6827 '("\C-c-" org-cycle-list-bullet)))
6828 elt key fun cmd)
6829 (while (setq elt (pop bindings))
6830 (setq nfunc (1+ nfunc))
6831 (setq key (org-key (car elt))
6832 fun (nth 1 elt)
6833 cmd (orgstruct-make-binding fun nfunc key))
6834 (org-defkey orgstruct-mode-map key cmd))
6836 ;; Special treatment needed for TAB and RET
6837 (org-defkey orgstruct-mode-map [(tab)]
6838 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6839 (org-defkey orgstruct-mode-map "\C-i"
6840 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6842 (org-defkey orgstruct-mode-map "\M-\C-m"
6843 (orgstruct-make-binding 'org-insert-heading 105
6844 "\M-\C-m" [(meta return)]))
6845 (org-defkey orgstruct-mode-map [(meta return)]
6846 (orgstruct-make-binding 'org-insert-heading 106
6847 [(meta return)] "\M-\C-m"))
6849 (org-defkey orgstruct-mode-map [(shift meta return)]
6850 (orgstruct-make-binding 'org-insert-todo-heading 107
6851 [(meta return)] "\M-\C-m"))
6853 (unless org-local-vars
6854 (setq org-local-vars (org-get-local-variables)))
6858 (defun orgstruct-make-binding (fun n &rest keys)
6859 "Create a function for binding in the structure minor mode.
6860 FUN is the command to call inside a table. N is used to create a unique
6861 command name. KEYS are keys that should be checked in for a command
6862 to execute outside of tables."
6863 (eval
6864 (list 'defun
6865 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6866 '(arg)
6867 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6868 "Outside of structure, run the binding of `"
6869 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6870 "'.")
6871 '(interactive "p")
6872 (list 'if
6873 `(org-context-p 'headline 'item
6874 (and orgstruct-is-++
6875 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
6876 'item-body))
6877 (list 'org-run-like-in-org-mode (list 'quote fun))
6878 (list 'let '(orgstruct-mode)
6879 (list 'call-interactively
6880 (append '(or)
6881 (mapcar (lambda (k)
6882 (list 'key-binding k))
6883 keys)
6884 '('orgstruct-error))))))))
6886 (defun org-context-p (&rest contexts)
6887 "Check if local context is any of CONTEXTS.
6888 Possible values in the list of contexts are `table', `headline', and `item'."
6889 (let ((pos (point)))
6890 (goto-char (point-at-bol))
6891 (prog1 (or (and (memq 'table contexts)
6892 (looking-at "[ \t]*|"))
6893 (and (memq 'headline contexts)
6894 ;;????????? (looking-at "\\*+"))
6895 (looking-at outline-regexp))
6896 (and (memq 'item contexts)
6897 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
6898 (and (memq 'item-body contexts)
6899 (org-in-item-p)))
6900 (goto-char pos))))
6902 (defun org-get-local-variables ()
6903 "Return a list of all local variables in an org-mode buffer."
6904 (let (varlist)
6905 (with-current-buffer (get-buffer-create "*Org tmp*")
6906 (erase-buffer)
6907 (org-mode)
6908 (setq varlist (buffer-local-variables)))
6909 (kill-buffer "*Org tmp*")
6910 (delq nil
6911 (mapcar
6912 (lambda (x)
6913 (setq x
6914 (if (symbolp x)
6915 (list x)
6916 (list (car x) (list 'quote (cdr x)))))
6917 (if (string-match
6918 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6919 (symbol-name (car x)))
6920 x nil))
6921 varlist))))
6923 ;;;###autoload
6924 (defun org-run-like-in-org-mode (cmd)
6925 "Run a command, pretending that the current buffer is in Org-mode.
6926 This will temporarily bind local variables that are typically bound in
6927 Org-mode to the values they have in Org-mode, and then interactively
6928 call CMD."
6929 (org-load-modules-maybe)
6930 (unless org-local-vars
6931 (setq org-local-vars (org-get-local-variables)))
6932 (eval (list 'let org-local-vars
6933 (list 'call-interactively (list 'quote cmd)))))
6935 ;;;; Archiving
6937 (defun org-get-category (&optional pos)
6938 "Get the category applying to position POS."
6939 (get-text-property (or pos (point)) 'org-category))
6941 (defun org-refresh-category-properties ()
6942 "Refresh category text properties in the buffer."
6943 (let ((def-cat (cond
6944 ((null org-category)
6945 (if buffer-file-name
6946 (file-name-sans-extension
6947 (file-name-nondirectory buffer-file-name))
6948 "???"))
6949 ((symbolp org-category) (symbol-name org-category))
6950 (t org-category)))
6951 beg end cat pos optionp)
6952 (org-unmodified
6953 (save-excursion
6954 (save-restriction
6955 (widen)
6956 (goto-char (point-min))
6957 (put-text-property (point) (point-max) 'org-category def-cat)
6958 (while (re-search-forward
6959 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6960 (setq pos (match-end 0)
6961 optionp (equal (char-after (match-beginning 0)) ?#)
6962 cat (org-trim (match-string 2)))
6963 (if optionp
6964 (setq beg (point-at-bol) end (point-max))
6965 (org-back-to-heading t)
6966 (setq beg (point) end (org-end-of-subtree t t)))
6967 (put-text-property beg end 'org-category cat)
6968 (goto-char pos)))))))
6971 ;;;; Link Stuff
6973 ;;; Link abbreviations
6975 (defun org-link-expand-abbrev (link)
6976 "Apply replacements as defined in `org-link-abbrev-alist."
6977 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6978 (let* ((key (match-string 1 link))
6979 (as (or (assoc key org-link-abbrev-alist-local)
6980 (assoc key org-link-abbrev-alist)))
6981 (tag (and (match-end 2) (match-string 3 link)))
6982 rpl)
6983 (if (not as)
6984 link
6985 (setq rpl (cdr as))
6986 (cond
6987 ((symbolp rpl) (funcall rpl tag))
6988 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6989 ((string-match "%h" rpl)
6990 (replace-match (url-hexify-string (or tag "")) t t rpl))
6991 (t (concat rpl tag)))))
6992 link))
6994 ;;; Storing and inserting links
6996 (defvar org-insert-link-history nil
6997 "Minibuffer history for links inserted with `org-insert-link'.")
6999 (defvar org-stored-links nil
7000 "Contains the links stored with `org-store-link'.")
7002 (defvar org-store-link-plist nil
7003 "Plist with info about the most recently link created with `org-store-link'.")
7005 (defvar org-link-protocols nil
7006 "Link protocols added to Org-mode using `org-add-link-type'.")
7008 (defvar org-store-link-functions nil
7009 "List of functions that are called to create and store a link.
7010 Each function will be called in turn until one returns a non-nil
7011 value. Each function should check if it is responsible for creating
7012 this link (for example by looking at the major mode).
7013 If not, it must exit and return nil.
7014 If yes, it should return a non-nil value after a calling
7015 `org-store-link-props' with a list of properties and values.
7016 Special properties are:
7018 :type The link prefix. like \"http\". This must be given.
7019 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7020 This is obligatory as well.
7021 :description Optional default description for the second pair
7022 of brackets in an Org-mode link. The user can still change
7023 this when inserting this link into an Org-mode buffer.
7025 In addition to these, any additional properties can be specified
7026 and then used in remember templates.")
7028 (defun org-add-link-type (type &optional follow export)
7029 "Add TYPE to the list of `org-link-types'.
7030 Re-compute all regular expressions depending on `org-link-types'
7032 FOLLOW and EXPORT are two functions.
7034 FOLLOW should take the link path as the single argument and do whatever
7035 is necessary to follow the link, for example find a file or display
7036 a mail message.
7038 EXPORT should format the link path for export to one of the export formats.
7039 It should be a function accepting three arguments:
7041 path the path of the link, the text after the prefix (like \"http:\")
7042 desc the description of the link, if any, nil if there was no description
7043 format the export format, a symbol like `html' or `latex'.
7045 The function may use the FORMAT information to return different values
7046 depending on the format. The return value will be put literally into
7047 the exported file.
7048 Org-mode has a built-in default for exporting links. If you are happy with
7049 this default, there is no need to define an export function for the link
7050 type. For a simple example of an export function, see `org-bbdb.el'."
7051 (add-to-list 'org-link-types type t)
7052 (org-make-link-regexps)
7053 (if (assoc type org-link-protocols)
7054 (setcdr (assoc type org-link-protocols) (list follow export))
7055 (push (list type follow export) org-link-protocols)))
7057 ;;;###autoload
7058 (defun org-store-link (arg)
7059 "\\<org-mode-map>Store an org-link to the current location.
7060 This link is added to `org-stored-links' and can later be inserted
7061 into an org-buffer with \\[org-insert-link].
7063 For some link types, a prefix arg is interpreted:
7064 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7065 For file links, arg negates `org-context-in-file-links'."
7066 (interactive "P")
7067 (org-load-modules-maybe)
7068 (setq org-store-link-plist nil) ; reset
7069 (let (link cpltxt desc description search txt custom-id)
7070 (cond
7072 ((run-hook-with-args-until-success 'org-store-link-functions)
7073 (setq link (plist-get org-store-link-plist :link)
7074 desc (or (plist-get org-store-link-plist :description) link)))
7076 ((equal (buffer-name) "*Org Edit Src Example*")
7077 (let (label gc)
7078 (while (or (not label)
7079 (save-excursion
7080 (save-restriction
7081 (widen)
7082 (goto-char (point-min))
7083 (re-search-forward
7084 (regexp-quote (format org-coderef-label-format label))
7085 nil t))))
7086 (when label (message "Label exists already") (sit-for 2))
7087 (setq label (read-string "Code line label: " label)))
7088 (end-of-line 1)
7089 (setq link (format org-coderef-label-format label))
7090 (setq gc (- 79 (length link)))
7091 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7092 (insert link)
7093 (setq link (concat "(" label ")") desc nil)))
7095 ((eq major-mode 'calendar-mode)
7096 (let ((cd (calendar-cursor-to-date)))
7097 (setq link
7098 (format-time-string
7099 (car org-time-stamp-formats)
7100 (apply 'encode-time
7101 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7102 nil nil nil))))
7103 (org-store-link-props :type "calendar" :date cd)))
7105 ((eq major-mode 'w3-mode)
7106 (setq cpltxt (if (and (buffer-name)
7107 (not (string-match "Untitled" (buffer-name))))
7108 (buffer-name)
7109 (url-view-url t))
7110 link (org-make-link (url-view-url t)))
7111 (org-store-link-props :type "w3" :url (url-view-url t)))
7113 ((eq major-mode 'w3m-mode)
7114 (setq cpltxt (or w3m-current-title w3m-current-url)
7115 link (org-make-link w3m-current-url))
7116 (org-store-link-props :type "w3m" :url (url-view-url t)))
7118 ((setq search (run-hook-with-args-until-success
7119 'org-create-file-search-functions))
7120 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7121 "::" search))
7122 (setq cpltxt (or description link)))
7124 ((eq major-mode 'image-mode)
7125 (setq cpltxt (concat "file:"
7126 (abbreviate-file-name buffer-file-name))
7127 link (org-make-link cpltxt))
7128 (org-store-link-props :type "image" :file buffer-file-name))
7130 ((eq major-mode 'dired-mode)
7131 ;; link to the file in the current line
7132 (setq cpltxt (concat "file:"
7133 (abbreviate-file-name
7134 (expand-file-name
7135 (dired-get-filename nil t))))
7136 link (org-make-link cpltxt)))
7138 ((and buffer-file-name (org-mode-p))
7139 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7140 (cond
7141 ((org-in-regexp "<<\\(.*?\\)>>")
7142 (setq cpltxt
7143 (concat "file:"
7144 (abbreviate-file-name buffer-file-name)
7145 "::" (match-string 1))
7146 link (org-make-link cpltxt)))
7147 ((and (featurep 'org-id)
7148 (or (eq org-link-to-org-use-id t)
7149 (and (eq org-link-to-org-use-id 'create-if-interactive)
7150 (interactive-p))
7151 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7152 (interactive-p)
7153 (not custom-id))
7154 (and org-link-to-org-use-id
7155 (condition-case nil
7156 (org-entry-get nil "ID")
7157 (error nil)))))
7158 ;; We can make a link using the ID.
7159 (setq link (condition-case nil
7160 (prog1 (org-id-store-link)
7161 (setq desc (plist-get org-store-link-plist
7162 :description)))
7163 (error
7164 ;; probably before first headline, link to file only
7165 (concat "file:"
7166 (abbreviate-file-name buffer-file-name))))))
7168 ;; Just link to current headline
7169 (setq cpltxt (concat "file:"
7170 (abbreviate-file-name buffer-file-name)))
7171 ;; Add a context search string
7172 (when (org-xor org-context-in-file-links arg)
7173 (setq txt (cond
7174 ((org-on-heading-p) nil)
7175 ((org-region-active-p)
7176 (buffer-substring (region-beginning) (region-end)))
7177 (t nil)))
7178 (when (or (null txt) (string-match "\\S-" txt))
7179 (setq cpltxt
7180 (concat cpltxt "::"
7181 (condition-case nil
7182 (org-make-org-heading-search-string txt)
7183 (error "")))
7184 desc "NONE")))
7185 (if (string-match "::\\'" cpltxt)
7186 (setq cpltxt (substring cpltxt 0 -2)))
7187 (setq link (org-make-link cpltxt)))))
7189 ((buffer-file-name (buffer-base-buffer))
7190 ;; Just link to this file here.
7191 (setq cpltxt (concat "file:"
7192 (abbreviate-file-name
7193 (buffer-file-name (buffer-base-buffer)))))
7194 ;; Add a context string
7195 (when (org-xor org-context-in-file-links arg)
7196 (setq txt (if (org-region-active-p)
7197 (buffer-substring (region-beginning) (region-end))
7198 (buffer-substring (point-at-bol) (point-at-eol))))
7199 ;; Only use search option if there is some text.
7200 (when (string-match "\\S-" txt)
7201 (setq cpltxt
7202 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7203 desc "NONE")))
7204 (setq link (org-make-link cpltxt)))
7206 ((interactive-p)
7207 (error "Cannot link to a buffer which is not visiting a file"))
7209 (t (setq link nil)))
7211 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7212 (setq link (or link cpltxt)
7213 desc (or desc cpltxt))
7214 (if (equal desc "NONE") (setq desc nil))
7216 (if (and (interactive-p) link)
7217 (progn
7218 (setq org-stored-links
7219 (cons (list link desc) org-stored-links))
7220 (message "Stored: %s" (or desc link))
7221 (when custom-id
7222 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7223 "::#" custom-id))
7224 (setq org-stored-links
7225 (cons (list link desc) org-stored-links))))
7226 (and link (org-make-link-string link desc)))))
7228 (defun org-store-link-props (&rest plist)
7229 "Store link properties, extract names and addresses."
7230 (let (x adr)
7231 (when (setq x (plist-get plist :from))
7232 (setq adr (mail-extract-address-components x))
7233 (setq plist (plist-put plist :fromname (car adr)))
7234 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7235 (when (setq x (plist-get plist :to))
7236 (setq adr (mail-extract-address-components x))
7237 (setq plist (plist-put plist :toname (car adr)))
7238 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7239 (let ((from (plist-get plist :from))
7240 (to (plist-get plist :to)))
7241 (when (and from to org-from-is-user-regexp)
7242 (setq plist
7243 (plist-put plist :fromto
7244 (if (string-match org-from-is-user-regexp from)
7245 (concat "to %t")
7246 (concat "from %f"))))))
7247 (setq org-store-link-plist plist))
7249 (defun org-add-link-props (&rest plist)
7250 "Add these properties to the link property list."
7251 (let (key value)
7252 (while plist
7253 (setq key (pop plist) value (pop plist))
7254 (setq org-store-link-plist
7255 (plist-put org-store-link-plist key value)))))
7257 (defun org-email-link-description (&optional fmt)
7258 "Return the description part of an email link.
7259 This takes information from `org-store-link-plist' and formats it
7260 according to FMT (default from `org-email-link-description-format')."
7261 (setq fmt (or fmt org-email-link-description-format))
7262 (let* ((p org-store-link-plist)
7263 (to (plist-get p :toaddress))
7264 (from (plist-get p :fromaddress))
7265 (table
7266 (list
7267 (cons "%c" (plist-get p :fromto))
7268 (cons "%F" (plist-get p :from))
7269 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7270 (cons "%T" (plist-get p :to))
7271 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7272 (cons "%s" (plist-get p :subject))
7273 (cons "%m" (plist-get p :message-id)))))
7274 (when (string-match "%c" fmt)
7275 ;; Check if the user wrote this message
7276 (if (and org-from-is-user-regexp from to
7277 (save-match-data (string-match org-from-is-user-regexp from)))
7278 (setq fmt (replace-match "to %t" t t fmt))
7279 (setq fmt (replace-match "from %f" t t fmt))))
7280 (org-replace-escapes fmt table)))
7282 (defun org-make-org-heading-search-string (&optional string heading)
7283 "Make search string for STRING or current headline."
7284 (interactive)
7285 (let ((s (or string (org-get-heading))))
7286 (unless (and string (not heading))
7287 ;; We are using a headline, clean up garbage in there.
7288 (if (string-match org-todo-regexp s)
7289 (setq s (replace-match "" t t s)))
7290 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7291 (setq s (replace-match "" t t s)))
7292 (setq s (org-trim s))
7293 (if (string-match (concat "^\\(" org-quote-string "\\|"
7294 org-comment-string "\\)") s)
7295 (setq s (replace-match "" t t s)))
7296 (while (string-match org-ts-regexp s)
7297 (setq s (replace-match "" t t s))))
7298 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7299 (setq s (replace-match " " t t s)))
7300 (or string (setq s (concat "*" s))) ; Add * for headlines
7301 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7303 (defun org-make-link (&rest strings)
7304 "Concatenate STRINGS."
7305 (apply 'concat strings))
7307 (defun org-make-link-string (link &optional description)
7308 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7309 (unless (string-match "\\S-" link)
7310 (error "Empty link"))
7311 (when (stringp description)
7312 ;; Remove brackets from the description, they are fatal.
7313 (while (string-match "\\[" description)
7314 (setq description (replace-match "{" t t description)))
7315 (while (string-match "\\]" description)
7316 (setq description (replace-match "}" t t description))))
7317 (when (equal (org-link-escape link) description)
7318 ;; No description needed, it is identical
7319 (setq description nil))
7320 (when (and (not description)
7321 (not (equal link (org-link-escape link))))
7322 (setq description (org-extract-attributes link)))
7323 (concat "[[" (org-link-escape link) "]"
7324 (if description (concat "[" description "]") "")
7325 "]"))
7327 (defconst org-link-escape-chars
7328 '((?\ . "%20")
7329 (?\[ . "%5B")
7330 (?\] . "%5D")
7331 (?\340 . "%E0") ; `a
7332 (?\342 . "%E2") ; ^a
7333 (?\347 . "%E7") ; ,c
7334 (?\350 . "%E8") ; `e
7335 (?\351 . "%E9") ; 'e
7336 (?\352 . "%EA") ; ^e
7337 (?\356 . "%EE") ; ^i
7338 (?\364 . "%F4") ; ^o
7339 (?\371 . "%F9") ; `u
7340 (?\373 . "%FB") ; ^u
7341 (?\; . "%3B")
7342 (?? . "%3F")
7343 (?= . "%3D")
7344 (?+ . "%2B")
7346 "Association list of escapes for some characters problematic in links.
7347 This is the list that is used for internal purposes.")
7349 (defvar org-url-encoding-use-url-hexify nil)
7351 (defconst org-link-escape-chars-browser
7352 '((?\ . "%20")) ; 32 for the SPC char
7353 "Association list of escapes for some characters problematic in links.
7354 This is the list that is used before handing over to the browser.")
7356 (defun org-link-escape (text &optional table)
7357 "Escape characters in TEXT that are problematic for links."
7358 (if org-url-encoding-use-url-hexify
7359 (url-hexify-string text)
7360 (setq table (or table org-link-escape-chars))
7361 (when text
7362 (let ((re (mapconcat (lambda (x) (regexp-quote
7363 (char-to-string (car x))))
7364 table "\\|")))
7365 (while (string-match re text)
7366 (setq text
7367 (replace-match
7368 (cdr (assoc (string-to-char (match-string 0 text))
7369 table))
7370 t t text)))
7371 text))))
7373 (defun org-link-unescape (text &optional table)
7374 "Reverse the action of `org-link-escape'."
7375 (if org-url-encoding-use-url-hexify
7376 (url-unhex-string text)
7377 (setq table (or table org-link-escape-chars))
7378 (when text
7379 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7380 table "\\|")))
7381 (while (string-match re text)
7382 (setq text
7383 (replace-match
7384 (char-to-string (car (rassoc (match-string 0 text) table)))
7385 t t text)))
7386 text))))
7388 (defun org-xor (a b)
7389 "Exclusive or."
7390 (if a (not b) b))
7392 (defun org-fixup-message-id-for-http (s)
7393 "Replace special characters in a message id, so it can be used in an http query."
7394 (while (string-match "<" s)
7395 (setq s (replace-match "%3C" t t s)))
7396 (while (string-match ">" s)
7397 (setq s (replace-match "%3E" t t s)))
7398 (while (string-match "@" s)
7399 (setq s (replace-match "%40" t t s)))
7402 ;;;###autoload
7403 (defun org-insert-link-global ()
7404 "Insert a link like Org-mode does.
7405 This command can be called in any mode to insert a link in Org-mode syntax."
7406 (interactive)
7407 (org-load-modules-maybe)
7408 (org-run-like-in-org-mode 'org-insert-link))
7410 (defun org-insert-link (&optional complete-file link-location)
7411 "Insert a link. At the prompt, enter the link.
7413 Completion can be used to insert any of the link protocol prefixes like
7414 http or ftp in use.
7416 The history can be used to select a link previously stored with
7417 `org-store-link'. When the empty string is entered (i.e. if you just
7418 press RET at the prompt), the link defaults to the most recently
7419 stored link. As SPC triggers completion in the minibuffer, you need to
7420 use M-SPC or C-q SPC to force the insertion of a space character.
7422 You will also be prompted for a description, and if one is given, it will
7423 be displayed in the buffer instead of the link.
7425 If there is already a link at point, this command will allow you to edit link
7426 and description parts.
7428 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7429 be selected using completion. The path to the file will be relative to the
7430 current directory if the file is in the current directory or a subdirectory.
7431 Otherwise, the link will be the absolute path as completed in the minibuffer
7432 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7433 option `org-link-file-path-type'.
7435 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7436 the current directory or below.
7438 With three \\[universal-argument] prefixes, negate the meaning of
7439 `org-keep-stored-link-after-insertion'.
7441 If `org-make-link-description-function' is non-nil, this function will be
7442 called with the link target, and the result will be the default
7443 link description.
7445 If the LINK-LOCATION parameter is non-nil, this value will be
7446 used as the link location instead of reading one interactively."
7447 (interactive "P")
7448 (let* ((wcf (current-window-configuration))
7449 (region (if (org-region-active-p)
7450 (buffer-substring (region-beginning) (region-end))))
7451 (remove (and region (list (region-beginning) (region-end))))
7452 (desc region)
7453 tmphist ; byte-compile incorrectly complains about this
7454 (link link-location)
7455 entry file all-prefixes)
7456 (cond
7457 (link-location) ; specified by arg, just use it.
7458 ((org-in-regexp org-bracket-link-regexp 1)
7459 ;; We do have a link at point, and we are going to edit it.
7460 (setq remove (list (match-beginning 0) (match-end 0)))
7461 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7462 (setq link (read-string "Link: "
7463 (org-link-unescape
7464 (org-match-string-no-properties 1)))))
7465 ((or (org-in-regexp org-angle-link-re)
7466 (org-in-regexp org-plain-link-re))
7467 ;; Convert to bracket link
7468 (setq remove (list (match-beginning 0) (match-end 0))
7469 link (read-string "Link: "
7470 (org-remove-angle-brackets (match-string 0)))))
7471 ((member complete-file '((4) (16)))
7472 ;; Completing read for file names.
7473 (setq link (org-file-complete-link complete-file)))
7475 ;; Read link, with completion for stored links.
7476 (with-output-to-temp-buffer "*Org Links*"
7477 (princ "Insert a link.
7478 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
7479 (when org-stored-links
7480 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7481 (princ (mapconcat
7482 (lambda (x)
7483 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7484 (reverse org-stored-links) "\n"))))
7485 (let ((cw (selected-window)))
7486 (select-window (get-buffer-window "*Org Links*"))
7487 (setq truncate-lines t)
7488 (unless (pos-visible-in-window-p (point-max))
7489 (org-fit-window-to-buffer))
7490 (and (window-live-p cw) (select-window cw)))
7491 ;; Fake a link history, containing the stored links.
7492 (setq tmphist (append (mapcar 'car org-stored-links)
7493 org-insert-link-history))
7494 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
7495 (mapcar 'car org-link-abbrev-alist)
7496 org-link-types))
7497 (unwind-protect
7498 (progn
7499 (setq link
7500 (let ((org-completion-use-ido nil))
7501 (org-completing-read
7502 "Link: "
7503 (mapcar (lambda (x) (list (concat x ":")))
7504 all-prefixes)
7505 nil nil nil
7506 'tmphist
7507 (or (car (car org-stored-links))))))
7508 (if (or (member link all-prefixes)
7509 (and (equal ":" (substring link -1))
7510 (member (substring link 0 -1) all-prefixes)
7511 (setq link (substring link 0 -1))))
7512 (setq link (org-link-try-special-completion link))))
7513 (set-window-configuration wcf)
7514 (kill-buffer "*Org Links*"))
7515 (setq entry (assoc link org-stored-links))
7516 (or entry (push link org-insert-link-history))
7517 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7518 (not org-keep-stored-link-after-insertion))
7519 (setq org-stored-links (delq (assoc link org-stored-links)
7520 org-stored-links)))
7521 (setq desc (or desc (nth 1 entry)))))
7523 (if (string-match org-plain-link-re link)
7524 ;; URL-like link, normalize the use of angular brackets.
7525 (setq link (org-make-link (org-remove-angle-brackets link))))
7527 ;; Check if we are linking to the current file with a search option
7528 ;; If yes, simplify the link by using only the search option.
7529 (when (and buffer-file-name
7530 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7531 (let* ((path (match-string 1 link))
7532 (case-fold-search nil)
7533 (search (match-string 2 link)))
7534 (save-match-data
7535 (if (equal (file-truename buffer-file-name) (file-truename path))
7536 ;; We are linking to this same file, with a search option
7537 (setq link search)))))
7539 ;; Check if we can/should use a relative path. If yes, simplify the link
7540 (when (string-match "^file:\\(.*\\)" link)
7541 (let* ((path (match-string 1 link))
7542 (origpath path)
7543 (case-fold-search nil))
7544 (cond
7545 ((or (eq org-link-file-path-type 'absolute)
7546 (equal complete-file '(16)))
7547 (setq path (abbreviate-file-name (expand-file-name path))))
7548 ((eq org-link-file-path-type 'noabbrev)
7549 (setq path (expand-file-name path)))
7550 ((eq org-link-file-path-type 'relative)
7551 (setq path (file-relative-name path)))
7553 (save-match-data
7554 (if (string-match (concat "^" (regexp-quote
7555 (file-name-as-directory
7556 (expand-file-name "."))))
7557 (expand-file-name path))
7558 ;; We are linking a file with relative path name.
7559 (setq path (substring (expand-file-name path)
7560 (match-end 0)))
7561 (setq path (abbreviate-file-name (expand-file-name path)))))))
7562 (setq link (concat "file:" path))
7563 (if (equal desc origpath)
7564 (setq desc path))))
7566 (if org-make-link-description-function
7567 (setq desc (funcall org-make-link-description-function link desc)))
7569 (setq desc (read-string "Description: " desc))
7570 (unless (string-match "\\S-" desc) (setq desc nil))
7571 (if remove (apply 'delete-region remove))
7572 (insert (org-make-link-string link desc))))
7574 (defun org-link-try-special-completion (type)
7575 "If there is completion support for link type TAPE, offer it."
7576 (let ((fun (intern (concat "org-" type "-complete-link"))))
7577 (if (functionp fun)
7578 (funcall fun)
7579 (read-string "Link (no completion support): " (concat type ":")))))
7581 (defun org-file-complete-link (&optional arg)
7582 "Create a file link using completion."
7583 (let (file link)
7584 (setq file (read-file-name "File: "))
7585 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7586 (pwd1 (file-name-as-directory (abbreviate-file-name
7587 (expand-file-name ".")))))
7588 (cond
7589 ((equal arg '(16))
7590 (setq link (org-make-link
7591 "file:"
7592 (abbreviate-file-name (expand-file-name file)))))
7593 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7594 (setq link (org-make-link "file:" (match-string 1 file))))
7595 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7596 (expand-file-name file))
7597 (setq link (org-make-link
7598 "file:" (match-string 1 (expand-file-name file)))))
7599 (t (setq link (org-make-link "file:" file)))))
7600 link))
7602 (defun org-completing-read (&rest args)
7603 "Completing-read with SPACE being a normal character."
7604 (let ((minibuffer-local-completion-map
7605 (copy-keymap minibuffer-local-completion-map)))
7606 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7607 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7608 (apply 'org-ido-completing-read args)))
7610 (defun org-completing-read-no-ido (&rest args)
7611 (let (org-completion-use-ido)
7612 (apply 'org-completing-read args)))
7614 (defun org-ido-completing-read (&rest args)
7615 "Completing-read using `ido-mode' speedups if available"
7616 (if (and org-completion-use-ido
7617 (fboundp 'ido-completing-read)
7618 (boundp 'ido-mode) ido-mode
7619 (listp (second args)))
7620 (let ((ido-enter-matching-directory nil))
7621 (apply 'ido-completing-read (concat (car args))
7622 (mapcar (lambda (x) (car x)) (nth 1 args))
7623 (cddr args)))
7624 (apply 'completing-read args)))
7626 (defun org-extract-attributes (s)
7627 "Extract the attributes cookie from a string and set as text property."
7628 (let (a attr (start 0) key value)
7629 (save-match-data
7630 (when (string-match "{{\\([^}]+\\)}}$" s)
7631 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7632 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7633 (setq key (match-string 1 a) value (match-string 2 a)
7634 start (match-end 0)
7635 attr (plist-put attr (intern key) value))))
7636 (org-add-props s nil 'org-attr attr))
7639 (defun org-extract-attributes-from-string (tag)
7640 (let (key value attr)
7641 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
7642 (setq key (match-string 1 tag) value (match-string 2 tag)
7643 tag (replace-match "" t t tag)
7644 attr (plist-put attr (intern key) value)))
7645 (cons tag attr)))
7647 (defun org-attributes-to-string (plist)
7648 "Format a property list into an HTML attribute list."
7649 (let ((s "") key value)
7650 (while plist
7651 (setq key (pop plist) value (pop plist))
7652 (and value
7653 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7656 ;;; Opening/following a link
7658 (defvar org-link-search-failed nil)
7660 (defun org-next-link ()
7661 "Move forward to the next link.
7662 If the link is in hidden text, expose it."
7663 (interactive)
7664 (when (and org-link-search-failed (eq this-command last-command))
7665 (goto-char (point-min))
7666 (message "Link search wrapped back to beginning of buffer"))
7667 (setq org-link-search-failed nil)
7668 (let* ((pos (point))
7669 (ct (org-context))
7670 (a (assoc :link ct)))
7671 (if a (goto-char (nth 2 a)))
7672 (if (re-search-forward org-any-link-re nil t)
7673 (progn
7674 (goto-char (match-beginning 0))
7675 (if (org-invisible-p) (org-show-context)))
7676 (goto-char pos)
7677 (setq org-link-search-failed t)
7678 (error "No further link found"))))
7680 (defun org-previous-link ()
7681 "Move backward to the previous link.
7682 If the link is in hidden text, expose it."
7683 (interactive)
7684 (when (and org-link-search-failed (eq this-command last-command))
7685 (goto-char (point-max))
7686 (message "Link search wrapped back to end of buffer"))
7687 (setq org-link-search-failed nil)
7688 (let* ((pos (point))
7689 (ct (org-context))
7690 (a (assoc :link ct)))
7691 (if a (goto-char (nth 1 a)))
7692 (if (re-search-backward org-any-link-re nil t)
7693 (progn
7694 (goto-char (match-beginning 0))
7695 (if (org-invisible-p) (org-show-context)))
7696 (goto-char pos)
7697 (setq org-link-search-failed t)
7698 (error "No further link found"))))
7700 (defun org-translate-link (s)
7701 "Translate a link string if a translation function has been defined."
7702 (if (and org-link-translation-function
7703 (fboundp org-link-translation-function)
7704 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7705 (progn
7706 (setq s (funcall org-link-translation-function
7707 (match-string 1) (match-string 2)))
7708 (concat (car s) ":" (cdr s)))
7711 (defun org-translate-link-from-planner (type path)
7712 "Translate a link from Emacs Planner syntax so that Org can follow it.
7713 This is still an experimental function, your mileage may vary."
7714 (cond
7715 ((member type '("http" "https" "news" "ftp"))
7716 ;; standard Internet links are the same.
7717 nil)
7718 ((and (equal type "irc") (string-match "^//" path))
7719 ;; Planner has two / at the beginning of an irc link, we have 1.
7720 ;; We should have zero, actually....
7721 (setq path (substring path 1)))
7722 ((and (equal type "lisp") (string-match "^/" path))
7723 ;; Planner has a slash, we do not.
7724 (setq type "elisp" path (substring path 1)))
7725 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7726 ;; A typical message link. Planner has the id after the fina slash,
7727 ;; we separate it with a hash mark
7728 (setq path (concat (match-string 1 path) "#"
7729 (org-remove-angle-brackets (match-string 2 path)))))
7731 (cons type path))
7733 (defun org-find-file-at-mouse (ev)
7734 "Open file link or URL at mouse."
7735 (interactive "e")
7736 (mouse-set-point ev)
7737 (org-open-at-point 'in-emacs))
7739 (defun org-open-at-mouse (ev)
7740 "Open file link or URL at mouse."
7741 (interactive "e")
7742 (mouse-set-point ev)
7743 (if (eq major-mode 'org-agenda-mode)
7744 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7745 (org-open-at-point))
7747 (defvar org-window-config-before-follow-link nil
7748 "The window configuration before following a link.
7749 This is saved in case the need arises to restore it.")
7751 (defvar org-open-link-marker (make-marker)
7752 "Marker pointing to the location where `org-open-at-point; was called.")
7754 ;;;###autoload
7755 (defun org-open-at-point-global ()
7756 "Follow a link like Org-mode does.
7757 This command can be called in any mode to follow a link that has
7758 Org-mode syntax."
7759 (interactive)
7760 (org-run-like-in-org-mode 'org-open-at-point))
7762 ;;;###autoload
7763 (defun org-open-link-from-string (s &optional arg)
7764 "Open a link in the string S, as if it was in Org-mode."
7765 (interactive "sLink: \nP")
7766 (let ((reference-buffer (current-buffer)))
7767 (with-temp-buffer
7768 (let ((org-inhibit-startup t))
7769 (org-mode)
7770 (insert s)
7771 (goto-char (point-min))
7772 (org-open-at-point arg reference-buffer)))))
7774 (defun org-open-at-point (&optional in-emacs reference-buffer)
7775 "Open link at or after point.
7776 If there is no link at point, this function will search forward up to
7777 the end of the current line.
7778 Normally, files will be opened by an appropriate application. If the
7779 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7780 With a double prefix argument, try to open outside of Emacs, in the
7781 application the system uses for this file type."
7782 (interactive "P")
7783 (org-load-modules-maybe)
7784 (move-marker org-open-link-marker (point))
7785 (setq org-window-config-before-follow-link (current-window-configuration))
7786 (org-remove-occur-highlights nil nil t)
7787 (cond
7788 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7789 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7790 (org-footnote-action))
7792 (let (type path link line search (pos (point)))
7793 (catch 'match
7794 (save-excursion
7795 (skip-chars-forward "^]\n\r")
7796 (when (org-in-regexp org-bracket-link-regexp)
7797 (setq link (org-extract-attributes
7798 (org-link-unescape (org-match-string-no-properties 1))))
7799 (while (string-match " *\n *" link)
7800 (setq link (replace-match " " t t link)))
7801 (setq link (org-link-expand-abbrev link))
7802 (cond
7803 ((or (file-name-absolute-p link)
7804 (string-match "^\\.\\.?/" link))
7805 (setq type "file" path link))
7806 ((string-match org-link-re-with-space3 link)
7807 (setq type (match-string 1 link) path (match-string 2 link)))
7808 (t (setq type "thisfile" path link)))
7809 (throw 'match t)))
7811 (when (get-text-property (point) 'org-linked-text)
7812 (setq type "thisfile"
7813 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7814 (1+ (point)) (point))
7815 path (buffer-substring
7816 (previous-single-property-change pos 'org-linked-text)
7817 (next-single-property-change pos 'org-linked-text)))
7818 (throw 'match t))
7820 (save-excursion
7821 (when (or (org-in-regexp org-angle-link-re)
7822 (org-in-regexp org-plain-link-re))
7823 (setq type (match-string 1) path (match-string 2))
7824 (throw 'match t)))
7825 (save-excursion
7826 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7827 (setq type "tags"
7828 path (match-string 1))
7829 (while (string-match ":" path)
7830 (setq path (replace-match "+" t t path)))
7831 (throw 'match t)))
7832 (when (org-in-regexp "<\\([^><\n]+\\)>")
7833 (setq type "tree-match"
7834 path (match-string 1))
7835 (throw 'match t)))
7836 (unless path
7837 (error "No link found"))
7839 ;; switch back to reference buffer
7840 ;; needed when if called in a temporary buffer through
7841 ;; org-open-link-from-string
7842 (and reference-buffer (switch-to-buffer reference-buffer))
7844 ;; Remove any trailing spaces in path
7845 (if (string-match " +\\'" path)
7846 (setq path (replace-match "" t t path)))
7847 (if (and org-link-translation-function
7848 (fboundp org-link-translation-function))
7849 ;; Check if we need to translate the link
7850 (let ((tmp (funcall org-link-translation-function type path)))
7851 (setq type (car tmp) path (cdr tmp))))
7853 (cond
7855 ((assoc type org-link-protocols)
7856 (funcall (nth 1 (assoc type org-link-protocols)) path))
7858 ((equal type "mailto")
7859 (let ((cmd (car org-link-mailto-program))
7860 (args (cdr org-link-mailto-program)) args1
7861 (address path) (subject "") a)
7862 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7863 (setq address (match-string 1 path)
7864 subject (org-link-escape (match-string 2 path))))
7865 (while args
7866 (cond
7867 ((not (stringp (car args))) (push (pop args) args1))
7868 (t (setq a (pop args))
7869 (if (string-match "%a" a)
7870 (setq a (replace-match address t t a)))
7871 (if (string-match "%s" a)
7872 (setq a (replace-match subject t t a)))
7873 (push a args1))))
7874 (apply cmd (nreverse args1))))
7876 ((member type '("http" "https" "ftp" "news"))
7877 (browse-url (concat type ":" (org-link-escape
7878 path org-link-escape-chars-browser))))
7880 ((member type '("message"))
7881 (browse-url (concat type ":" path)))
7883 ((string= type "tags")
7884 (org-tags-view in-emacs path))
7885 ((string= type "thisfile")
7886 (if in-emacs
7887 (switch-to-buffer-other-window
7888 (org-get-buffer-for-internal-link (current-buffer)))
7889 (org-mark-ring-push))
7890 (let ((cmd `(org-link-search
7891 ,path
7892 ,(cond ((equal in-emacs '(4)) 'occur)
7893 ((equal in-emacs '(16)) 'org-occur)
7894 (t nil))
7895 ,pos)))
7896 (condition-case nil (eval cmd)
7897 (error (progn (widen) (eval cmd))))))
7899 ((string= type "tree-match")
7900 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7902 ((string= type "file")
7903 (if (string-match "::\\([0-9]+\\)\\'" path)
7904 (setq line (string-to-number (match-string 1 path))
7905 path (substring path 0 (match-beginning 0)))
7906 (if (string-match "::\\(.+\\)\\'" path)
7907 (setq search (match-string 1 path)
7908 path (substring path 0 (match-beginning 0)))))
7909 (if (string-match "[*?{]" (file-name-nondirectory path))
7910 (dired path)
7911 (org-open-file path in-emacs line search)))
7913 ((string= type "news")
7914 (require 'org-gnus)
7915 (org-gnus-follow-link path))
7917 ((string= type "shell")
7918 (let ((cmd path))
7919 (if (or (not org-confirm-shell-link-function)
7920 (funcall org-confirm-shell-link-function
7921 (format "Execute \"%s\" in shell? "
7922 (org-add-props cmd nil
7923 'face 'org-warning))))
7924 (progn
7925 (message "Executing %s" cmd)
7926 (shell-command cmd))
7927 (error "Abort"))))
7929 ((string= type "elisp")
7930 (let ((cmd path))
7931 (if (or (not org-confirm-elisp-link-function)
7932 (funcall org-confirm-elisp-link-function
7933 (format "Execute \"%s\" as elisp? "
7934 (org-add-props cmd nil
7935 'face 'org-warning))))
7936 (message "%s => %s" cmd
7937 (if (equal (string-to-char cmd) ?\()
7938 (eval (read cmd))
7939 (call-interactively (read cmd))))
7940 (error "Abort"))))
7943 (browse-url-at-point))))))
7944 (move-marker org-open-link-marker nil)
7945 (run-hook-with-args 'org-follow-link-hook))
7947 ;;;; Time estimates
7949 (defun org-get-effort (&optional pom)
7950 "Get the effort estimate for the current entry."
7951 (org-entry-get pom org-effort-property))
7953 ;;; File search
7955 (defvar org-create-file-search-functions nil
7956 "List of functions to construct the right search string for a file link.
7957 These functions are called in turn with point at the location to
7958 which the link should point.
7960 A function in the hook should first test if it would like to
7961 handle this file type, for example by checking the major-mode or
7962 the file extension. If it decides not to handle this file, it
7963 should just return nil to give other functions a chance. If it
7964 does handle the file, it must return the search string to be used
7965 when following the link. The search string will be part of the
7966 file link, given after a double colon, and `org-open-at-point'
7967 will automatically search for it. If special measures must be
7968 taken to make the search successful, another function should be
7969 added to the companion hook `org-execute-file-search-functions',
7970 which see.
7972 A function in this hook may also use `setq' to set the variable
7973 `description' to provide a suggestion for the descriptive text to
7974 be used for this link when it gets inserted into an Org-mode
7975 buffer with \\[org-insert-link].")
7977 (defvar org-execute-file-search-functions nil
7978 "List of functions to execute a file search triggered by a link.
7980 Functions added to this hook must accept a single argument, the
7981 search string that was part of the file link, the part after the
7982 double colon. The function must first check if it would like to
7983 handle this search, for example by checking the major-mode or the
7984 file extension. If it decides not to handle this search, it
7985 should just return nil to give other functions a chance. If it
7986 does handle the search, it must return a non-nil value to keep
7987 other functions from trying.
7989 Each function can access the current prefix argument through the
7990 variable `current-prefix-argument'. Note that a single prefix is
7991 used to force opening a link in Emacs, so it may be good to only
7992 use a numeric or double prefix to guide the search function.
7994 In case this is needed, a function in this hook can also restore
7995 the window configuration before `org-open-at-point' was called using:
7997 (set-window-configuration org-window-config-before-follow-link)")
7999 (defun org-link-search (s &optional type avoid-pos)
8000 "Search for a link search option.
8001 If S is surrounded by forward slashes, it is interpreted as a
8002 regular expression. In org-mode files, this will create an `org-occur'
8003 sparse tree. In ordinary files, `occur' will be used to list matches.
8004 If the current buffer is in `dired-mode', grep will be used to search
8005 in all files. If AVOID-POS is given, ignore matches near that position."
8006 (let ((case-fold-search t)
8007 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8008 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8009 (append '(("") (" ") ("\t") ("\n"))
8010 org-emphasis-alist)
8011 "\\|") "\\)"))
8012 (pos (point))
8013 (pre nil) (post nil)
8014 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8015 (cond
8016 ;; First check if there are any special
8017 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8018 ;; Now try the builtin stuff
8019 ((and (equal (string-to-char s0) ?#)
8020 (> (length s0) 1)
8021 (save-excursion
8022 (goto-char (point-min))
8023 (and
8024 (re-search-forward
8025 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8026 (setq type 'dedicated
8027 pos (match-beginning 0))))
8028 ;; There is an exact target for this
8029 (goto-char pos)
8030 (org-back-to-heading t)))
8031 ((save-excursion
8032 (goto-char (point-min))
8033 (and
8034 (re-search-forward
8035 (concat "<<" (regexp-quote s0) ">>") nil t)
8036 (setq type 'dedicated
8037 pos (match-beginning 0))))
8038 ;; There is an exact target for this
8039 (goto-char pos))
8040 ((and (string-match "^(\\(.*\\))$" s0)
8041 (save-excursion
8042 (goto-char (point-min))
8043 (and
8044 (re-search-forward
8045 (concat "[^[]" (regexp-quote
8046 (format org-coderef-label-format
8047 (match-string 1 s0))))
8048 nil t)
8049 (setq type 'dedicated
8050 pos (1+ (match-beginning 0))))))
8051 ;; There is a coderef target for this
8052 (goto-char pos))
8053 ((string-match "^/\\(.*\\)/$" s)
8054 ;; A regular expression
8055 (cond
8056 ((org-mode-p)
8057 (org-occur (match-string 1 s)))
8058 ;;((eq major-mode 'dired-mode)
8059 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8060 (t (org-do-occur (match-string 1 s)))))
8062 ;; A normal search strings
8063 (when (equal (string-to-char s) ?*)
8064 ;; Anchor on headlines, post may include tags.
8065 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8066 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8067 s (substring s 1)))
8068 (remove-text-properties
8069 0 (length s)
8070 '(face nil mouse-face nil keymap nil fontified nil) s)
8071 ;; Make a series of regular expressions to find a match
8072 (setq words (org-split-string s "[ \n\r\t]+")
8074 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8075 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8076 "\\)" markers)
8077 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8078 re2a (concat "[ \t\r\n]" re2a_)
8079 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8080 re4 (concat "[^a-zA-Z_]" re4_)
8082 re1 (concat pre re2 post)
8083 re3 (concat pre (if pre re4_ re4) post)
8084 re5 (concat pre ".*" re4)
8085 re2 (concat pre re2)
8086 re2a (concat pre (if pre re2a_ re2a))
8087 re4 (concat pre (if pre re4_ re4))
8088 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8089 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8090 re5 "\\)"
8092 (cond
8093 ((eq type 'org-occur) (org-occur reall))
8094 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8095 (t (goto-char (point-min))
8096 (setq type 'fuzzy)
8097 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8098 (org-search-not-self 1 re1 nil t)
8099 (org-search-not-self 1 re2 nil t)
8100 (org-search-not-self 1 re2a nil t)
8101 (org-search-not-self 1 re3 nil t)
8102 (org-search-not-self 1 re4 nil t)
8103 (org-search-not-self 1 re5 nil t)
8105 (goto-char (match-beginning 1))
8106 (goto-char pos)
8107 (error "No match")))))
8109 ;; Normal string-search
8110 (goto-char (point-min))
8111 (if (search-forward s nil t)
8112 (goto-char (match-beginning 0))
8113 (error "No match"))))
8114 (and (org-mode-p) (org-show-context 'link-search))
8115 type))
8117 (defun org-search-not-self (group &rest args)
8118 "Execute `re-search-forward', but only accept matches that do not
8119 enclose the position of `org-open-link-marker'."
8120 (let ((m org-open-link-marker))
8121 (catch 'exit
8122 (while (apply 're-search-forward args)
8123 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8124 (goto-char (match-end group))
8125 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8126 (> (match-beginning 0) (marker-position m))
8127 (< (match-end 0) (marker-position m)))
8128 (save-match-data
8129 (or (not (org-in-regexp
8130 org-bracket-link-analytic-regexp 1))
8131 (not (match-end 4)) ; no description
8132 (and (<= (match-beginning 4) (point))
8133 (>= (match-end 4) (point))))))
8134 (throw 'exit (point))))))))
8136 (defun org-get-buffer-for-internal-link (buffer)
8137 "Return a buffer to be used for displaying the link target of internal links."
8138 (cond
8139 ((not org-display-internal-link-with-indirect-buffer)
8140 buffer)
8141 ((string-match "(Clone)$" (buffer-name buffer))
8142 (message "Buffer is already a clone, not making another one")
8143 ;; we also do not modify visibility in this case
8144 buffer)
8145 (t ; make a new indirect buffer for displaying the link
8146 (let* ((bn (buffer-name buffer))
8147 (ibn (concat bn "(Clone)"))
8148 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8149 (with-current-buffer ib (org-overview))
8150 ib))))
8152 (defun org-do-occur (regexp &optional cleanup)
8153 "Call the Emacs command `occur'.
8154 If CLEANUP is non-nil, remove the printout of the regular expression
8155 in the *Occur* buffer. This is useful if the regex is long and not useful
8156 to read."
8157 (occur regexp)
8158 (when cleanup
8159 (let ((cwin (selected-window)) win beg end)
8160 (when (setq win (get-buffer-window "*Occur*"))
8161 (select-window win))
8162 (goto-char (point-min))
8163 (when (re-search-forward "match[a-z]+" nil t)
8164 (setq beg (match-end 0))
8165 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8166 (setq end (1- (match-beginning 0)))))
8167 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8168 (goto-char (point-min))
8169 (select-window cwin))))
8171 ;;; The mark ring for links jumps
8173 (defvar org-mark-ring nil
8174 "Mark ring for positions before jumps in Org-mode.")
8175 (defvar org-mark-ring-last-goto nil
8176 "Last position in the mark ring used to go back.")
8177 ;; Fill and close the ring
8178 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8179 (loop for i from 1 to org-mark-ring-length do
8180 (push (make-marker) org-mark-ring))
8181 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8182 org-mark-ring)
8184 (defun org-mark-ring-push (&optional pos buffer)
8185 "Put the current position or POS into the mark ring and rotate it."
8186 (interactive)
8187 (setq pos (or pos (point)))
8188 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8189 (move-marker (car org-mark-ring)
8190 (or pos (point))
8191 (or buffer (current-buffer)))
8192 (message "%s"
8193 (substitute-command-keys
8194 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8196 (defun org-mark-ring-goto (&optional n)
8197 "Jump to the previous position in the mark ring.
8198 With prefix arg N, jump back that many stored positions. When
8199 called several times in succession, walk through the entire ring.
8200 Org-mode commands jumping to a different position in the current file,
8201 or to another Org-mode file, automatically push the old position
8202 onto the ring."
8203 (interactive "p")
8204 (let (p m)
8205 (if (eq last-command this-command)
8206 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8207 (setq p org-mark-ring))
8208 (setq org-mark-ring-last-goto p)
8209 (setq m (car p))
8210 (switch-to-buffer (marker-buffer m))
8211 (goto-char m)
8212 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8214 (defun org-remove-angle-brackets (s)
8215 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8216 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8218 (defun org-add-angle-brackets (s)
8219 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8220 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8222 (defun org-remove-double-quotes (s)
8223 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8224 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8227 ;;; Following specific links
8229 (defun org-follow-timestamp-link ()
8230 (cond
8231 ((org-at-date-range-p t)
8232 (let ((org-agenda-start-on-weekday)
8233 (t1 (match-string 1))
8234 (t2 (match-string 2)))
8235 (setq t1 (time-to-days (org-time-string-to-time t1))
8236 t2 (time-to-days (org-time-string-to-time t2)))
8237 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8238 ((org-at-timestamp-p t)
8239 (org-agenda-list nil (time-to-days (org-time-string-to-time
8240 (substring (match-string 1) 0 10)))
8242 (t (error "This should not happen"))))
8245 ;;; Following file links
8246 (defvar org-wait nil)
8247 (defun org-open-file (path &optional in-emacs line search)
8248 "Open the file at PATH.
8249 First, this expands any special file name abbreviations. Then the
8250 configuration variable `org-file-apps' is checked if it contains an
8251 entry for this file type, and if yes, the corresponding command is launched.
8253 If no application is found, Emacs simply visits the file.
8255 With optional prefix argument IN-EMACS, Emacs will visit the file.
8256 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8257 and o use an external application to visit the file.
8259 Optional LINE specifies a line to go to, optional SEARCH a string to
8260 search for. If LINE or SEARCH is given, the file will always be
8261 opened in Emacs.
8262 If the file does not exist, an error is thrown."
8263 (setq in-emacs (or in-emacs line search))
8264 (let* ((file (if (equal path "")
8265 buffer-file-name
8266 (substitute-in-file-name (expand-file-name path))))
8267 (apps (append org-file-apps (org-default-apps)))
8268 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8269 (dirp (if remp nil (file-directory-p file)))
8270 (file (if (and dirp org-open-directory-means-index-dot-org)
8271 (concat (file-name-as-directory file) "index.org")
8272 file))
8273 (a-m-a-p (assq 'auto-mode apps))
8274 (dfile (downcase file))
8275 (old-buffer (current-buffer))
8276 (old-pos (point))
8277 (old-mode major-mode)
8278 ext cmd)
8279 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8280 (setq ext (match-string 1 dfile))
8281 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8282 (setq ext (match-string 1 dfile))))
8283 (cond
8284 ((equal in-emacs '(16))
8285 (setq cmd (cdr (assoc 'system apps))))
8286 (in-emacs (setq cmd 'emacs))
8288 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8289 (and dirp (cdr (assoc 'directory apps)))
8290 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8291 'string-match)
8292 (cdr (assoc ext apps))
8293 (cdr (assoc t apps))))))
8294 (when (eq cmd 'system)
8295 (setq cmd (cdr (assoc 'system apps))))
8296 (when (eq cmd 'default)
8297 (setq cmd (cdr (assoc t apps))))
8298 (when (eq cmd 'mailcap)
8299 (require 'mailcap)
8300 (mailcap-parse-mailcaps)
8301 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8302 (command (mailcap-mime-info mime-type)))
8303 (if (stringp command)
8304 (setq cmd command)
8305 (setq cmd 'emacs))))
8306 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8307 (not (file-exists-p file))
8308 (not org-open-non-existing-files))
8309 (error "No such file: %s" file))
8310 (cond
8311 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8312 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8313 (while (string-match "['\"]%s['\"]" cmd)
8314 (setq cmd (replace-match "%s" t t cmd)))
8315 (while (string-match "%s" cmd)
8316 (setq cmd (replace-match
8317 (save-match-data
8318 (shell-quote-argument
8319 (convert-standard-filename file)))
8320 t t cmd)))
8321 (save-window-excursion
8322 (start-process-shell-command cmd nil cmd)
8323 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8325 ((or (stringp cmd)
8326 (eq cmd 'emacs))
8327 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8328 (widen)
8329 (if line (goto-line line)
8330 (if search (org-link-search search))))
8331 ((consp cmd)
8332 (let ((file (convert-standard-filename file)))
8333 (eval cmd)))
8334 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8335 (and (org-mode-p) (eq old-mode 'org-mode)
8336 (or (not (equal old-buffer (current-buffer)))
8337 (not (equal old-pos (point))))
8338 (org-mark-ring-push old-pos old-buffer))))
8340 (defun org-default-apps ()
8341 "Return the default applications for this operating system."
8342 (cond
8343 ((eq system-type 'darwin)
8344 org-file-apps-defaults-macosx)
8345 ((eq system-type 'windows-nt)
8346 org-file-apps-defaults-windowsnt)
8347 (t org-file-apps-defaults-gnu)))
8349 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8350 "Convert extensions to regular expressions in the cars of LIST.
8351 Also, weed out any non-string entries, because the return value is used
8352 only for regexp matching.
8353 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8354 point to the symbol `emacs', indicating that the file should
8355 be opened in Emacs."
8356 (append
8357 (delq nil
8358 (mapcar (lambda (x)
8359 (if (not (stringp (car x)))
8361 (if (string-match "\\W" (car x))
8363 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8364 list))
8365 (if add-auto-mode
8366 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8368 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8369 (defun org-file-remote-p (file)
8370 "Test whether FILE specifies a location on a remote system.
8371 Return non-nil if the location is indeed remote.
8373 For example, the filename \"/user@host:/foo\" specifies a location
8374 on the system \"/user@host:\"."
8375 (cond ((fboundp 'file-remote-p)
8376 (file-remote-p file))
8377 ((fboundp 'tramp-handle-file-remote-p)
8378 (tramp-handle-file-remote-p file))
8379 ((and (boundp 'ange-ftp-name-format)
8380 (string-match (car ange-ftp-name-format) file))
8382 (t nil)))
8385 ;;;; Refiling
8387 (defun org-get-org-file ()
8388 "Read a filename, with default directory `org-directory'."
8389 (let ((default (or org-default-notes-file remember-data-file)))
8390 (read-file-name (format "File name [%s]: " default)
8391 (file-name-as-directory org-directory)
8392 default)))
8394 (defun org-notes-order-reversed-p ()
8395 "Check if the current file should receive notes in reversed order."
8396 (cond
8397 ((not org-reverse-note-order) nil)
8398 ((eq t org-reverse-note-order) t)
8399 ((not (listp org-reverse-note-order)) nil)
8400 (t (catch 'exit
8401 (let ((all org-reverse-note-order)
8402 entry)
8403 (while (setq entry (pop all))
8404 (if (string-match (car entry) buffer-file-name)
8405 (throw 'exit (cdr entry))))
8406 nil)))))
8408 (defvar org-refile-target-table nil
8409 "The list of refile targets, created by `org-refile'.")
8411 (defvar org-agenda-new-buffers nil
8412 "Buffers created to visit agenda files.")
8414 (defun org-get-refile-targets (&optional default-buffer)
8415 "Produce a table with refile targets."
8416 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
8417 targets txt re files f desc descre fast-path-p level pos0)
8418 (message "Getting targets...")
8419 (with-current-buffer (or default-buffer (current-buffer))
8420 (while (setq entry (pop entries))
8421 (setq files (car entry) desc (cdr entry))
8422 (setq fast-path-p nil)
8423 (cond
8424 ((null files) (setq files (list (current-buffer))))
8425 ((eq files 'org-agenda-files)
8426 (setq files (org-agenda-files 'unrestricted)))
8427 ((and (symbolp files) (fboundp files))
8428 (setq files (funcall files)))
8429 ((and (symbolp files) (boundp files))
8430 (setq files (symbol-value files))))
8431 (if (stringp files) (setq files (list files)))
8432 (cond
8433 ((eq (car desc) :tag)
8434 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8435 ((eq (car desc) :todo)
8436 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8437 ((eq (car desc) :regexp)
8438 (setq descre (cdr desc)))
8439 ((eq (car desc) :level)
8440 (setq descre (concat "^\\*\\{" (number-to-string
8441 (if org-odd-levels-only
8442 (1- (* 2 (cdr desc)))
8443 (cdr desc)))
8444 "\\}[ \t]")))
8445 ((eq (car desc) :maxlevel)
8446 (setq fast-path-p t)
8447 (setq descre (concat "^\\*\\{1," (number-to-string
8448 (if org-odd-levels-only
8449 (1- (* 2 (cdr desc)))
8450 (cdr desc)))
8451 "\\}[ \t]")))
8452 (t (error "Bad refiling target description %s" desc)))
8453 (while (setq f (pop files))
8454 (save-excursion
8455 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
8456 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8457 (setq f (expand-file-name f))
8458 (if (eq org-refile-use-outline-path 'file)
8459 (push (list (file-name-nondirectory f) f nil nil) targets))
8460 (save-excursion
8461 (save-restriction
8462 (widen)
8463 (goto-char (point-min))
8464 (while (re-search-forward descre nil t)
8465 (goto-char (setq pos0 (point-at-bol)))
8466 (catch 'next
8467 (when org-refile-target-verify-function
8468 (save-match-data
8469 (or (funcall org-refile-target-verify-function)
8470 (throw 'next t))))
8471 (when (looking-at org-complex-heading-regexp)
8472 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8473 txt (org-link-display-format (match-string 4))
8474 re (concat "^" (regexp-quote
8475 (buffer-substring (match-beginning 1)
8476 (match-end 4)))))
8477 (if (match-end 5) (setq re (concat re "[ \t]+"
8478 (regexp-quote
8479 (match-string 5)))))
8480 (setq re (concat re "[ \t]*$"))
8481 (when org-refile-use-outline-path
8482 (setq txt (mapconcat 'org-protect-slash
8483 (append
8484 (if (eq org-refile-use-outline-path 'file)
8485 (list (file-name-nondirectory
8486 (buffer-file-name (buffer-base-buffer))))
8487 (if (eq org-refile-use-outline-path 'full-file-path)
8488 (list (buffer-file-name (buffer-base-buffer)))))
8489 (org-get-outline-path fast-path-p level txt)
8490 (list txt))
8491 "/")))
8492 (push (list txt f re (point)) targets)))
8493 (when (= (point) pos0)
8494 ;; verification function has not moved point
8495 (goto-char (point-at-eol))))))))))
8496 (message "Getting targets...done")
8497 (nreverse targets)))
8499 (defun org-protect-slash (s)
8500 (while (string-match "/" s)
8501 (setq s (replace-match "\\" t t s)))
8504 (defvar org-olpa (make-vector 20 nil))
8506 (defun org-get-outline-path (&optional fastp level heading)
8507 "Return the outline path to the current entry, as a list."
8508 (if fastp
8509 (progn
8510 (if (> level 19)
8511 (error "Outline path failure, more than 19 levels."))
8512 (loop for i from level upto 19 do
8513 (aset org-olpa i nil))
8514 (prog1
8515 (delq nil (append org-olpa nil))
8516 (aset org-olpa level heading)))
8517 (let (rtn)
8518 (save-excursion
8519 (while (org-up-heading-safe)
8520 (when (looking-at org-complex-heading-regexp)
8521 (push (org-match-string-no-properties 4) rtn)))
8522 rtn))))
8524 (defvar org-refile-history nil
8525 "History for refiling operations.")
8527 (defvar org-after-refile-insert-hook nil
8528 "Hook run after `org-refile' has inserted its stuff at the new location.
8529 Note that this is still *before* the stuff will be removed from
8530 the *old* location.")
8532 (defun org-refile (&optional goto default-buffer)
8533 "Move the entry at point to another heading.
8534 The list of target headings is compiled using the information in
8535 `org-refile-targets', which see. This list is created before each use
8536 and will therefore always be up-to-date.
8538 At the target location, the entry is filed as a subitem of the target heading.
8539 Depending on `org-reverse-note-order', the new subitem will either be the
8540 first or the last subitem.
8542 If there is an active region, all entries in that region will be moved.
8543 However, the region must fulfil the requirement that the first heading
8544 is the first one sets the top-level of the moved text - at most siblings
8545 below it are allowed.
8547 With prefix arg GOTO, the command will only visit the target location,
8548 not actually move anything.
8549 With a double prefix `C-u C-u', go to the location where the last refiling
8550 operation has put the subtree.
8552 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
8553 (interactive "P")
8554 (let* ((cbuf (current-buffer))
8555 (regionp (org-region-active-p))
8556 (region-start (and regionp (region-beginning)))
8557 (region-end (and regionp (region-end)))
8558 (region-length (and regionp (- region-end region-start)))
8559 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8560 pos it nbuf file re level reversed)
8561 (when regionp (goto-char region-start)
8562 (unless (org-kill-is-subtree-p
8563 (buffer-substring region-start region-end))
8564 (error "The region is not a (sequence of) subtree(s)")))
8565 (if (equal goto '(16))
8566 (org-refile-goto-last-stored)
8567 (when (setq it (org-refile-get-location
8568 (if goto "Goto: " "Refile to: ") default-buffer
8569 org-refile-allow-creating-parent-nodes))
8570 (setq file (nth 1 it)
8571 re (nth 2 it)
8572 pos (nth 3 it))
8573 (if (and (not goto)
8575 (equal (buffer-file-name) file)
8576 (if regionp
8577 (and (>= pos region-start)
8578 (<= pos region-end))
8579 (and (>= pos (point))
8580 (< pos (save-excursion
8581 (org-end-of-subtree t t))))))
8582 (error "Cannot refile to position inside the tree or region"))
8584 (setq nbuf (or (find-buffer-visiting file)
8585 (find-file-noselect file)))
8586 (if goto
8587 (progn
8588 (switch-to-buffer nbuf)
8589 (goto-char pos)
8590 (org-show-context 'org-goto))
8591 (if regionp
8592 (progn
8593 (kill-new (buffer-substring region-start region-end))
8594 (org-save-markers-in-region region-start region-end))
8595 (org-copy-subtree 1 nil t))
8596 (save-excursion
8597 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8598 (find-file-noselect file))))
8599 (setq reversed (org-notes-order-reversed-p))
8600 (save-excursion
8601 (save-restriction
8602 (widen)
8603 (if pos
8604 (progn
8605 (goto-char pos)
8606 (looking-at outline-regexp)
8607 (setq level (org-get-valid-level (funcall outline-level) 1))
8608 (goto-char
8609 (if reversed
8610 (or (outline-next-heading) (point-max))
8611 (or (save-excursion (outline-get-next-sibling))
8612 (org-end-of-subtree t t)
8613 (point-max)))))
8614 (setq level 1)
8615 (if (not reversed)
8616 (goto-char (point-max))
8617 (goto-char (point-min))
8618 (or (outline-next-heading) (goto-char (point-max)))))
8619 (if (not (bolp)) (newline))
8620 (bookmark-set "org-refile-last-stored")
8621 (org-paste-subtree level)
8622 (run-hooks 'org-after-refile-insert-hook))))
8623 (if regionp
8624 (delete-region (point) (+ (point) region-length))
8625 (org-cut-subtree))
8626 (setq org-markers-to-move nil)
8627 (message "Refiled to \"%s\"" (car it))))))
8628 (org-reveal))
8630 (defun org-refile-goto-last-stored ()
8631 "Go to the location where the last refile was stored."
8632 (interactive)
8633 (bookmark-jump "org-refile-last-stored")
8634 (message "This is the location of the last refile"))
8636 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
8637 "Prompt the user for a refile location, using PROMPT."
8638 (let ((org-refile-targets org-refile-targets)
8639 (org-refile-use-outline-path org-refile-use-outline-path))
8640 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8641 (unless org-refile-target-table
8642 (error "No refile targets"))
8643 (let* ((cbuf (current-buffer))
8644 (partial-completion-mode nil)
8645 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8646 (cfunc (if (and org-refile-use-outline-path
8647 org-outline-path-complete-in-steps)
8648 'org-olpath-completing-read
8649 'org-ido-completing-read))
8650 (extra (if org-refile-use-outline-path "/" ""))
8651 (filename (and cfn (expand-file-name cfn)))
8652 (tbl (mapcar
8653 (lambda (x)
8654 (if (and (not (member org-refile-use-outline-path
8655 '(file full-file-path)))
8656 (not (equal filename (nth 1 x))))
8657 (cons (concat (car x) extra " ("
8658 (file-name-nondirectory (nth 1 x)) ")")
8659 (cdr x))
8660 (cons (concat (car x) extra) (cdr x))))
8661 org-refile-target-table))
8662 (completion-ignore-case t)
8663 pa answ parent-target child parent)
8664 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
8665 nil 'org-refile-history))
8666 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
8667 (if pa
8669 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
8670 (setq parent (match-string 1 answ)
8671 child (match-string 2 answ))
8672 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
8673 (when (and parent-target
8674 (or (eq new-nodes t)
8675 (and (eq new-nodes 'confirm)
8676 (y-or-n-p (format "Create new node \"%s\"? " child)))))
8677 (org-refile-new-child parent-target child))))))
8679 (defun org-refile-new-child (parent-target child)
8680 "Use refile target PARENT-TARGET to add new CHILD below it."
8681 (unless parent-target
8682 (error "Cannot find parent for new node"))
8683 (let ((file (nth 1 parent-target))
8684 (pos (nth 3 parent-target))
8685 level)
8686 (with-current-buffer (or (find-buffer-visiting file)
8687 (find-file-noselect file))
8688 (save-excursion
8689 (save-restriction
8690 (widen)
8691 (if pos
8692 (goto-char pos)
8693 (goto-char (point-max))
8694 (if (not (bolp)) (newline)))
8695 (when (looking-at outline-regexp)
8696 (setq level (funcall outline-level))
8697 (org-end-of-subtree t t))
8698 (org-back-over-empty-lines)
8699 (insert "\n" (make-string
8700 (if pos (org-get-valid-level level 1) 1) ?*)
8701 " " child "\n")
8702 (beginning-of-line 0)
8703 (list (concat (car parent-target) "/" child) file "" (point)))))))
8705 (defun org-olpath-completing-read (prompt collection &rest args)
8706 "Read an outline path like a file name."
8707 (let ((thetable collection)
8708 (org-completion-use-ido nil)) ; does not work with ido.
8709 (apply
8710 'org-ido-completing-read prompt
8711 (lambda (string predicate &optional flag)
8712 (let (rtn r f (l (length string)))
8713 (cond
8714 ((eq flag nil)
8715 ;; try completion
8716 (try-completion string thetable))
8717 ((eq flag t)
8718 ;; all-completions
8719 (setq rtn (all-completions string thetable predicate))
8720 (mapcar
8721 (lambda (x)
8722 (setq r (substring x l))
8723 (if (string-match " ([^)]*)$" x)
8724 (setq f (match-string 0 x))
8725 (setq f ""))
8726 (if (string-match "/" r)
8727 (concat string (substring r 0 (match-end 0)) f)
8729 rtn))
8730 ((eq flag 'lambda)
8731 ;; exact match?
8732 (assoc string thetable)))
8734 args)))
8736 ;;;; Dynamic blocks
8738 (defun org-find-dblock (name)
8739 "Find the first dynamic block with name NAME in the buffer.
8740 If not found, stay at current position and return nil."
8741 (let (pos)
8742 (save-excursion
8743 (goto-char (point-min))
8744 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8745 nil t)
8746 (match-beginning 0))))
8747 (if pos (goto-char pos))
8748 pos))
8750 (defconst org-dblock-start-re
8751 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8752 "Matches the startline of a dynamic block, with parameters.")
8754 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8755 "Matches the end of a dynamic block.")
8757 (defun org-create-dblock (plist)
8758 "Create a dynamic block section, with parameters taken from PLIST.
8759 PLIST must contain a :name entry which is used as name of the block."
8760 (unless (bolp) (newline))
8761 (let ((name (plist-get plist :name)))
8762 (insert "#+BEGIN: " name)
8763 (while plist
8764 (if (eq (car plist) :name)
8765 (setq plist (cddr plist))
8766 (insert " " (prin1-to-string (pop plist)))))
8767 (insert "\n\n#+END:\n")
8768 (beginning-of-line -2)))
8770 (defun org-prepare-dblock ()
8771 "Prepare dynamic block for refresh.
8772 This empties the block, puts the cursor at the insert position and returns
8773 the property list including an extra property :name with the block name."
8774 (unless (looking-at org-dblock-start-re)
8775 (error "Not at a dynamic block"))
8776 (let* ((begdel (1+ (match-end 0)))
8777 (name (org-no-properties (match-string 1)))
8778 (params (append (list :name name)
8779 (read (concat "(" (match-string 3) ")")))))
8780 (unless (re-search-forward org-dblock-end-re nil t)
8781 (error "Dynamic block not terminated"))
8782 (setq params
8783 (append params
8784 (list :content (buffer-substring
8785 begdel (match-beginning 0)))))
8786 (delete-region begdel (match-beginning 0))
8787 (goto-char begdel)
8788 (open-line 1)
8789 params))
8791 (defun org-map-dblocks (&optional command)
8792 "Apply COMMAND to all dynamic blocks in the current buffer.
8793 If COMMAND is not given, use `org-update-dblock'."
8794 (let ((cmd (or command 'org-update-dblock))
8795 pos)
8796 (save-excursion
8797 (goto-char (point-min))
8798 (while (re-search-forward org-dblock-start-re nil t)
8799 (goto-char (setq pos (match-beginning 0)))
8800 (condition-case nil
8801 (funcall cmd)
8802 (error (message "Error during update of dynamic block")))
8803 (goto-char pos)
8804 (unless (re-search-forward org-dblock-end-re nil t)
8805 (error "Dynamic block not terminated"))))))
8807 (defun org-dblock-update (&optional arg)
8808 "User command for updating dynamic blocks.
8809 Update the dynamic block at point. With prefix ARG, update all dynamic
8810 blocks in the buffer."
8811 (interactive "P")
8812 (if arg
8813 (org-update-all-dblocks)
8814 (or (looking-at org-dblock-start-re)
8815 (org-beginning-of-dblock))
8816 (org-update-dblock)))
8818 (defun org-update-dblock ()
8819 "Update the dynamic block at point
8820 This means to empty the block, parse for parameters and then call
8821 the correct writing function."
8822 (save-window-excursion
8823 (let* ((pos (point))
8824 (line (org-current-line))
8825 (params (org-prepare-dblock))
8826 (name (plist-get params :name))
8827 (cmd (intern (concat "org-dblock-write:" name))))
8828 (message "Updating dynamic block `%s' at line %d..." name line)
8829 (funcall cmd params)
8830 (message "Updating dynamic block `%s' at line %d...done" name line)
8831 (goto-char pos))))
8833 (defun org-beginning-of-dblock ()
8834 "Find the beginning of the dynamic block at point.
8835 Error if there is no such block at point."
8836 (let ((pos (point))
8837 beg)
8838 (end-of-line 1)
8839 (if (and (re-search-backward org-dblock-start-re nil t)
8840 (setq beg (match-beginning 0))
8841 (re-search-forward org-dblock-end-re nil t)
8842 (> (match-end 0) pos))
8843 (goto-char beg)
8844 (goto-char pos)
8845 (error "Not in a dynamic block"))))
8847 (defun org-update-all-dblocks ()
8848 "Update all dynamic blocks in the buffer.
8849 This function can be used in a hook."
8850 (when (org-mode-p)
8851 (org-map-dblocks 'org-update-dblock)))
8854 ;;;; Completion
8856 (defconst org-additional-option-like-keywords
8857 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8858 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8859 "LATEX_HEADER:"
8860 "BEGIN_EXAMPLE" "END_EXAMPLE"
8861 "BEGIN_QUOTE" "END_QUOTE"
8862 "BEGIN_VERSE" "END_VERSE"
8863 "BEGIN_CENTER" "END_CENTER"
8864 "BEGIN_SRC" "END_SRC"
8865 "CATEGORY" "COLUMNS"
8866 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
8868 (defcustom org-structure-template-alist
8870 ("s" "#+begin_src ?\n\n#+end_src"
8871 "<src lang=\"?\">\n\n</src>")
8872 ("e" "#+begin_example\n?\n#+end_example"
8873 "<example>\n?\n</example>")
8874 ("q" "#+begin_quote\n?\n#+end_quote"
8875 "<quote>\n?\n</quote>")
8876 ("v" "#+begin_verse\n?\n#+end_verse"
8877 "<verse>\n?\n/verse>")
8878 ("c" "#+begin_center\n?\n#+end_center"
8879 "<center>\n?\n/center>")
8880 ("l" "#+begin_latex\n?\n#+end_latex"
8881 "<literal style=\"latex\">\n?\n</literal>")
8882 ("L" "#+latex: "
8883 "<literal style=\"latex\">?</literal>")
8884 ("h" "#+begin_html\n?\n#+end_html"
8885 "<literal style=\"html\">\n?\n</literal>")
8886 ("H" "#+html: "
8887 "<literal style=\"html\">?</literal>")
8888 ("a" "#+begin_ascii\n?\n#+end_ascii")
8889 ("A" "#+ascii: ")
8890 ("i" "#+include %file ?"
8891 "<include file=%file markup=\"?\">")
8893 "Structure completion elements.
8894 This is a list of abbreviation keys and values. The value gets inserted
8895 it you type @samp{.} followed by the key and then the completion key,
8896 usually `M-TAB'. %file will be replaced by a file name after prompting
8897 for the file using completion.
8898 There are two templates for each key, the first uses the original Org syntax,
8899 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8900 the default when the /org-mtags.el/ module has been loaded. See also the
8901 variable `org-mtags-prefer-muse-templates'.
8902 This is an experimental feature, it is undecided if it is going to stay in."
8903 :group 'org-completion
8904 :type '(repeat
8905 (string :tag "Key")
8906 (string :tag "Template")
8907 (string :tag "Muse Template")))
8909 (defun org-try-structure-completion ()
8910 "Try to complete a structure template before point.
8911 This looks for strings like \"<e\" on an otherwise empty line and
8912 expands them."
8913 (let ((l (buffer-substring (point-at-bol) (point)))
8915 (when (and (looking-at "[ \t]*$")
8916 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8917 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8918 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8919 (match-beginning 1)) a)
8920 t)))
8922 (defun org-complete-expand-structure-template (start cell)
8923 "Expand a structure template."
8924 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8925 (rpl (nth (if musep 2 1) cell)))
8926 (delete-region start (point))
8927 (when (string-match "\\`#\\+" rpl)
8928 (cond
8929 ((bolp))
8930 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8931 (delete-region (point-at-bol) (point)))
8932 (t (newline))))
8933 (setq start (point))
8934 (if (string-match "%file" rpl)
8935 (setq rpl (replace-match
8936 (concat
8937 "\""
8938 (save-match-data
8939 (abbreviate-file-name (read-file-name "Include file: ")))
8940 "\"")
8941 t t rpl)))
8942 (insert rpl)
8943 (if (re-search-backward "\\?" start t) (delete-char 1))))
8946 (defun org-complete (&optional arg)
8947 "Perform completion on word at point.
8948 At the beginning of a headline, this completes TODO keywords as given in
8949 `org-todo-keywords'.
8950 If the current word is preceded by a backslash, completes the TeX symbols
8951 that are supported for HTML support.
8952 If the current word is preceded by \"#+\", completes special words for
8953 setting file options.
8954 In the line after \"#+STARTUP:, complete valid keywords.\"
8955 At all other locations, this simply calls the value of
8956 `org-completion-fallback-command'."
8957 (interactive "P")
8958 (org-without-partial-completion
8959 (catch 'exit
8960 (let* ((a nil)
8961 (end (point))
8962 (beg1 (save-excursion
8963 (skip-chars-backward (org-re "[:alnum:]_@"))
8964 (point)))
8965 (beg (save-excursion
8966 (skip-chars-backward "a-zA-Z0-9_:$")
8967 (point)))
8968 (confirm (lambda (x) (stringp (car x))))
8969 (searchhead (equal (char-before beg) ?*))
8970 (struct
8971 (when (and (member (char-before beg1) '(?. ?<))
8972 (setq a (assoc (buffer-substring beg1 (point))
8973 org-structure-template-alist)))
8974 (org-complete-expand-structure-template (1- beg1) a)
8975 (throw 'exit t)))
8976 (tag (and (equal (char-before beg1) ?:)
8977 (equal (char-after (point-at-bol)) ?*)))
8978 (prop (and (equal (char-before beg1) ?:)
8979 (not (equal (char-after (point-at-bol)) ?*))))
8980 (texp (equal (char-before beg) ?\\))
8981 (link (equal (char-before beg) ?\[))
8982 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8983 beg)
8984 "#+"))
8985 (startup (string-match "^#\\+STARTUP:.*"
8986 (buffer-substring (point-at-bol) (point))))
8987 (completion-ignore-case opt)
8988 (type nil)
8989 (tbl nil)
8990 (table (cond
8991 (opt
8992 (setq type :opt)
8993 (require 'org-exp)
8994 (append
8995 (mapcar
8996 (lambda (x)
8997 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8998 (cons (match-string 2 x) (match-string 1 x)))
8999 (org-split-string (org-get-current-options) "\n"))
9000 (mapcar 'list org-additional-option-like-keywords)))
9001 (startup
9002 (setq type :startup)
9003 org-startup-options)
9004 (link (append org-link-abbrev-alist-local
9005 org-link-abbrev-alist))
9006 (texp
9007 (setq type :tex)
9008 org-html-entities)
9009 ((string-match "\\`\\*+[ \t]+\\'"
9010 (buffer-substring (point-at-bol) beg))
9011 (setq type :todo)
9012 (mapcar 'list org-todo-keywords-1))
9013 (searchhead
9014 (setq type :searchhead)
9015 (save-excursion
9016 (goto-char (point-min))
9017 (while (re-search-forward org-todo-line-regexp nil t)
9018 (push (list
9019 (org-make-org-heading-search-string
9020 (match-string 3) t))
9021 tbl)))
9022 tbl)
9023 (tag (setq type :tag beg beg1)
9024 (or org-tag-alist (org-get-buffer-tags)))
9025 (prop (setq type :prop beg beg1)
9026 (mapcar 'list (org-buffer-property-keys nil t t)))
9027 (t (progn
9028 (call-interactively org-completion-fallback-command)
9029 (throw 'exit nil)))))
9030 (pattern (buffer-substring-no-properties beg end))
9031 (completion (try-completion pattern table confirm)))
9032 (cond ((eq completion t)
9033 (if (not (assoc (upcase pattern) table))
9034 (message "Already complete")
9035 (if (and (equal type :opt)
9036 (not (member (car (assoc (upcase pattern) table))
9037 org-additional-option-like-keywords)))
9038 (insert (substring (cdr (assoc (upcase pattern) table))
9039 (length pattern)))
9040 (if (memq type '(:tag :prop)) (insert ":")))))
9041 ((null completion)
9042 (message "Can't find completion for \"%s\"" pattern)
9043 (ding))
9044 ((not (string= pattern completion))
9045 (delete-region beg end)
9046 (if (string-match " +$" completion)
9047 (setq completion (replace-match "" t t completion)))
9048 (insert completion)
9049 (if (get-buffer-window "*Completions*")
9050 (delete-window (get-buffer-window "*Completions*")))
9051 (if (assoc completion table)
9052 (if (eq type :todo) (insert " ")
9053 (if (memq type '(:tag :prop)) (insert ":"))))
9054 (if (and (equal type :opt) (assoc completion table))
9055 (message "%s" (substitute-command-keys
9056 "Press \\[org-complete] again to insert example settings"))))
9058 (message "Making completion list...")
9059 (let ((list (sort (all-completions pattern table confirm)
9060 'string<)))
9061 (with-output-to-temp-buffer "*Completions*"
9062 (condition-case nil
9063 ;; Protection needed for XEmacs and emacs 21
9064 (display-completion-list list pattern)
9065 (error (display-completion-list list)))))
9066 (message "Making completion list...%s" "done")))))))
9068 ;;;; TODO, DEADLINE, Comments
9070 (defun org-toggle-comment ()
9071 "Change the COMMENT state of an entry."
9072 (interactive)
9073 (save-excursion
9074 (org-back-to-heading)
9075 (let (case-fold-search)
9076 (if (looking-at (concat outline-regexp
9077 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9078 (replace-match "" t t nil 1)
9079 (if (looking-at outline-regexp)
9080 (progn
9081 (goto-char (match-end 0))
9082 (insert org-comment-string " ")))))))
9084 (defvar org-last-todo-state-is-todo nil
9085 "This is non-nil when the last TODO state change led to a TODO state.
9086 If the last change removed the TODO tag or switched to DONE, then
9087 this is nil.")
9089 (defvar org-setting-tags nil) ; dynamically skipped
9091 (defun org-parse-local-options (string var)
9092 "Parse STRING for startup setting relevant for variable VAR."
9093 (let ((rtn (symbol-value var))
9094 e opts)
9095 (save-match-data
9096 (if (or (not string) (not (string-match "\\S-" string)))
9098 (setq opts (delq nil (mapcar (lambda (x)
9099 (setq e (assoc x org-startup-options))
9100 (if (eq (nth 1 e) var) e nil))
9101 (org-split-string string "[ \t]+"))))
9102 (if (not opts)
9104 (setq rtn nil)
9105 (while (setq e (pop opts))
9106 (if (not (nth 3 e))
9107 (setq rtn (nth 2 e))
9108 (if (not (listp rtn)) (setq rtn nil))
9109 (push (nth 2 e) rtn)))
9110 rtn)))))
9112 (defvar org-todo-setup-filter-hook nil
9113 "Hook for functions that pre-filter todo specs.
9115 Each function takes a todo spec and returns either `nil' or the spec
9116 transformed into canonical form." )
9118 (defvar org-todo-get-default-hook nil
9119 "Hook for functions that get a default item for todo.
9121 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9122 `nil' or a string to be used for the todo mark." )
9124 (defvar org-agenda-headline-snapshot-before-repeat)
9125 (defun org-todo (&optional arg)
9126 "Change the TODO state of an item.
9127 The state of an item is given by a keyword at the start of the heading,
9128 like
9129 *** TODO Write paper
9130 *** DONE Call mom
9132 The different keywords are specified in the variable `org-todo-keywords'.
9133 By default the available states are \"TODO\" and \"DONE\".
9134 So for this example: when the item starts with TODO, it is changed to DONE.
9135 When it starts with DONE, the DONE is removed. And when neither TODO nor
9136 DONE are present, add TODO at the beginning of the heading.
9138 With C-u prefix arg, use completion to determine the new state.
9139 With numeric prefix arg, switch to that state.
9140 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9141 With a tripple C-u prefix, circumvent any state blocking.
9143 For calling through lisp, arg is also interpreted in the following way:
9144 'none -> empty state
9145 \"\"(empty string) -> switch to empty state
9146 'done -> switch to DONE
9147 'nextset -> switch to the next set of keywords
9148 'previousset -> switch to the previous set of keywords
9149 \"WAITING\" -> switch to the specified keyword, but only if it
9150 really is a member of `org-todo-keywords'."
9151 (interactive "P")
9152 (if (equal arg '(16)) (setq arg 'nextset))
9153 (let ((org-blocker-hook org-blocker-hook)
9154 (case-fold-search nil))
9155 (when (equal arg '(64))
9156 (setq arg nil org-blocker-hook nil))
9157 (when (and org-blocker-hook
9158 (org-entry-get nil "NOBLOCKING"))
9159 (setq org-blocker-hook nil))
9160 (save-excursion
9161 (catch 'exit
9162 (org-back-to-heading)
9163 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9164 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9165 (looking-at " *"))
9166 (let* ((match-data (match-data))
9167 (startpos (point-at-bol))
9168 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9169 (org-log-done org-log-done)
9170 (org-log-repeat org-log-repeat)
9171 (org-todo-log-states org-todo-log-states)
9172 (this (match-string 1))
9173 (hl-pos (match-beginning 0))
9174 (head (org-get-todo-sequence-head this))
9175 (ass (assoc head org-todo-kwd-alist))
9176 (interpret (nth 1 ass))
9177 (done-word (nth 3 ass))
9178 (final-done-word (nth 4 ass))
9179 (last-state (or this ""))
9180 (completion-ignore-case t)
9181 (member (member this org-todo-keywords-1))
9182 (tail (cdr member))
9183 (state (cond
9184 ((and org-todo-key-trigger
9185 (or (and (equal arg '(4))
9186 (eq org-use-fast-todo-selection 'prefix))
9187 (and (not arg) org-use-fast-todo-selection
9188 (not (eq org-use-fast-todo-selection
9189 'prefix)))))
9190 ;; Use fast selection
9191 (org-fast-todo-selection))
9192 ((and (equal arg '(4))
9193 (or (not org-use-fast-todo-selection)
9194 (not org-todo-key-trigger)))
9195 ;; Read a state with completion
9196 (org-ido-completing-read
9197 "State: " (mapcar (lambda(x) (list x))
9198 org-todo-keywords-1)
9199 nil t))
9200 ((eq arg 'right)
9201 (if this
9202 (if tail (car tail) nil)
9203 (car org-todo-keywords-1)))
9204 ((eq arg 'left)
9205 (if (equal member org-todo-keywords-1)
9207 (if this
9208 (nth (- (length org-todo-keywords-1)
9209 (length tail) 2)
9210 org-todo-keywords-1)
9211 (org-last org-todo-keywords-1))))
9212 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9213 (setq arg nil))) ; hack to fall back to cycling
9214 (arg
9215 ;; user or caller requests a specific state
9216 (cond
9217 ((equal arg "") nil)
9218 ((eq arg 'none) nil)
9219 ((eq arg 'done) (or done-word (car org-done-keywords)))
9220 ((eq arg 'nextset)
9221 (or (car (cdr (member head org-todo-heads)))
9222 (car org-todo-heads)))
9223 ((eq arg 'previousset)
9224 (let ((org-todo-heads (reverse org-todo-heads)))
9225 (or (car (cdr (member head org-todo-heads)))
9226 (car org-todo-heads))))
9227 ((car (member arg org-todo-keywords-1)))
9228 ((nth (1- (prefix-numeric-value arg))
9229 org-todo-keywords-1))))
9230 ((null member) (or head (car org-todo-keywords-1)))
9231 ((equal this final-done-word) nil) ;; -> make empty
9232 ((null tail) nil) ;; -> first entry
9233 ((memq interpret '(type priority))
9234 (if (eq this-command last-command)
9235 (car tail)
9236 (if (> (length tail) 0)
9237 (or done-word (car org-done-keywords))
9238 nil)))
9240 (car tail))))
9241 (state (or
9242 (run-hook-with-args-until-success
9243 'org-todo-get-default-hook state last-state)
9244 state))
9245 (next (if state (concat " " state " ") " "))
9246 (change-plist (list :type 'todo-state-change :from this :to state
9247 :position startpos))
9248 dolog now-done-p)
9249 (when org-blocker-hook
9250 (setq org-last-todo-state-is-todo
9251 (not (member this org-done-keywords)))
9252 (unless (save-excursion
9253 (save-match-data
9254 (run-hook-with-args-until-failure
9255 'org-blocker-hook change-plist)))
9256 (if (interactive-p)
9257 (error "TODO state change from %s to %s blocked" this state)
9258 ;; fail silently
9259 (message "TODO state change from %s to %s blocked" this state)
9260 (throw 'exit nil))))
9261 (store-match-data match-data)
9262 (replace-match next t t)
9263 (unless (pos-visible-in-window-p hl-pos)
9264 (message "TODO state changed to %s" (org-trim next)))
9265 (unless head
9266 (setq head (org-get-todo-sequence-head state)
9267 ass (assoc head org-todo-kwd-alist)
9268 interpret (nth 1 ass)
9269 done-word (nth 3 ass)
9270 final-done-word (nth 4 ass)))
9271 (when (memq arg '(nextset previousset))
9272 (message "Keyword-Set %d/%d: %s"
9273 (- (length org-todo-sets) -1
9274 (length (memq (assoc state org-todo-sets) org-todo-sets)))
9275 (length org-todo-sets)
9276 (mapconcat 'identity (assoc state org-todo-sets) " ")))
9277 (setq org-last-todo-state-is-todo
9278 (not (member state org-done-keywords)))
9279 (setq now-done-p (and (member state org-done-keywords)
9280 (not (member this org-done-keywords))))
9281 (and logging (org-local-logging logging))
9282 (when (and (or org-todo-log-states org-log-done)
9283 (not (memq arg '(nextset previousset))))
9284 ;; we need to look at recording a time and note
9285 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
9286 (nth 2 (assoc this org-todo-log-states))))
9287 (when (and state
9288 (member state org-not-done-keywords)
9289 (not (member this org-not-done-keywords)))
9290 ;; This is now a todo state and was not one before
9291 ;; If there was a CLOSED time stamp, get rid of it.
9292 (org-add-planning-info nil nil 'closed))
9293 (when (and now-done-p org-log-done)
9294 ;; It is now done, and it was not done before
9295 (org-add-planning-info 'closed (org-current-time))
9296 (if (and (not dolog) (eq 'note org-log-done))
9297 (org-add-log-setup 'done state this 'findpos 'note)))
9298 (when (and state dolog)
9299 ;; This is a non-nil state, and we need to log it
9300 (org-add-log-setup 'state state this 'findpos dolog)))
9301 ;; Fixup tag positioning
9302 (org-todo-trigger-tag-changes state)
9303 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
9304 (when org-provide-todo-statistics
9305 (org-update-parent-todo-statistics))
9306 (run-hooks 'org-after-todo-state-change-hook)
9307 (if (and arg (not (member state org-done-keywords)))
9308 (setq head (org-get-todo-sequence-head state)))
9309 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9310 ;; Do we need to trigger a repeat?
9311 (when now-done-p
9312 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
9313 ;; This is for the agenda, take a snapshot of the headline.
9314 (save-match-data
9315 (setq org-agenda-headline-snapshot-before-repeat
9316 (org-get-heading))))
9317 (org-auto-repeat-maybe state))
9318 ;; Fixup cursor location if close to the keyword
9319 (if (and (outline-on-heading-p)
9320 (not (bolp))
9321 (save-excursion (beginning-of-line 1)
9322 (looking-at org-todo-line-regexp))
9323 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9324 (progn
9325 (goto-char (or (match-end 2) (match-end 1)))
9326 (and (looking-at " ") (just-one-space))))
9327 (when org-trigger-hook
9328 (save-excursion
9329 (run-hook-with-args 'org-trigger-hook change-plist))))))))
9331 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
9332 "Block turning an entry into a TODO, using the hierarchy.
9333 This checks whether the current task should be blocked from state
9334 changes. Such blocking occurs when:
9336 1. The task has children which are not all in a completed state.
9338 2. A task has a parent with the property :ORDERED:, and there
9339 are siblings prior to the current task with incomplete
9340 status.
9342 3. The parent of the task is blocked because it has siblings that should
9343 be done first, or is child of a block grandparent TODO entry."
9345 (catch 'dont-block
9346 ;; If this is not a todo state change, or if this entry is already DONE,
9347 ;; do not block
9348 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9349 (member (plist-get change-plist :from)
9350 (cons 'done org-done-keywords))
9351 (member (plist-get change-plist :to)
9352 (cons 'todo org-not-done-keywords)))
9353 (throw 'dont-block t))
9354 ;; If this task has children, and any are undone, it's blocked
9355 (save-excursion
9356 (org-back-to-heading t)
9357 (let ((this-level (funcall outline-level)))
9358 (outline-next-heading)
9359 (let ((child-level (funcall outline-level)))
9360 (while (and (not (eobp))
9361 (> child-level this-level))
9362 ;; this todo has children, check whether they are all
9363 ;; completed
9364 (if (and (not (org-entry-is-done-p))
9365 (org-entry-is-todo-p))
9366 (throw 'dont-block nil))
9367 (outline-next-heading)
9368 (setq child-level (funcall outline-level))))))
9369 ;; Otherwise, if the task's parent has the :ORDERED: property, and
9370 ;; any previous siblings are undone, it's blocked
9371 (save-excursion
9372 (org-back-to-heading t)
9373 (let* ((pos (point))
9374 (parent-pos (and (org-up-heading-safe) (point))))
9375 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9376 (when (and (org-entry-get (point) "ORDERED")
9377 (forward-line 1)
9378 (re-search-forward org-not-done-heading-regexp pos t))
9379 (throw 'dont-block nil)) ; block, there is an older sibling not done.
9380 ;; Search further up the hierarchy, to see if an anchestor is blocked
9381 (while t
9382 (goto-char parent-pos)
9383 (if (not (looking-at org-not-done-heading-regexp))
9384 (throw 'dont-block t)) ; do not block, parent is not a TODO
9385 (setq pos (point))
9386 (setq parent-pos (and (org-up-heading-safe) (point)))
9387 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9388 (when (and (org-entry-get (point) "ORDERED")
9389 (forward-line 1)
9390 (re-search-forward org-not-done-heading-regexp pos t))
9391 (throw 'dont-block nil))))))) ; block, older sibling not done.
9393 (defcustom org-track-ordered-property-with-tag nil
9394 "Should the ORDERED property also be shown as a tag?
9395 The ORDERED property decides if an entry should require subtasks to be
9396 completed in sequence. Since a property is not very visible, setting
9397 this option means that toggling the ORDERED property with the command
9398 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
9399 not relevant for the behavior, but it makes things more visible.
9401 Note that toggling the tag with tags commands will not change the property
9402 and therefore not influence behavior!
9404 This can be t, meaning the tag ORDERED should be used, It can also be a
9405 string to select a different tag for this task."
9406 :group 'org-todo
9407 :type '(choice
9408 (const :tag "No tracking" nil)
9409 (const :tag "Track with ORDERED tag" t)
9410 (string :tag "Use other tag")))
9412 (defun org-toggle-ordered-property ()
9413 "Toggle the ORDERED property of the current entry.
9414 For better visibility, you can track the value of this property with a tag.
9415 See variable `org-track-ordered-property-with-tag'."
9416 (interactive)
9417 (let* ((t1 org-track-ordered-property-with-tag)
9418 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
9419 (save-excursion
9420 (org-back-to-heading)
9421 (if (org-entry-get nil "ORDERED")
9422 (progn
9423 (org-delete-property "ORDERED")
9424 (and tag (org-toggle-tag tag 'off))
9425 (message "Subtasks can be completed in arbitrary order"))
9426 (org-entry-put nil "ORDERED" "t")
9427 (and tag (org-toggle-tag tag 'on))
9428 (message "Subtasks must be completed in sequence")))))
9430 (defvar org-blocked-by-checkboxes) ; dynamically scoped
9431 (defun org-block-todo-from-checkboxes (change-plist)
9432 "Block turning an entry into a TODO, using checkboxes.
9433 This checks whether the current task should be blocked from state
9434 changes because there are uncheckd boxes in this entry."
9435 (catch 'dont-block
9436 ;; If this is not a todo state change, or if this entry is already DONE,
9437 ;; do not block
9438 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9439 (member (plist-get change-plist :from)
9440 (cons 'done org-done-keywords))
9441 (member (plist-get change-plist :to)
9442 (cons 'todo org-not-done-keywords)))
9443 (throw 'dont-block t))
9444 ;; If this task has checkboxes that are not checked, it's blocked
9445 (save-excursion
9446 (org-back-to-heading t)
9447 (let ((beg (point)) end)
9448 (outline-next-heading)
9449 (setq end (point))
9450 (goto-char beg)
9451 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
9452 end t)
9453 (progn
9454 (if (boundp 'org-blocked-by-checkboxes)
9455 (setq org-blocked-by-checkboxes t))
9456 (throw 'dont-block nil)))))
9457 t)) ; do not block
9459 (defvar org-entry-property-inherited-from) ;; defined below
9460 (defun org-update-parent-todo-statistics ()
9461 "Update any statistics cookie in the parent of the current headline.
9462 When `org-hierarchical-todo-statistics' is nil, statistics will cover
9463 the entire subtree and this will travel up the hierarchy and update
9464 statistics everywhere."
9465 (interactive)
9466 (let* ((lim 0) prop
9467 (recursive (or (not org-hierarchical-todo-statistics)
9468 (string-match
9469 "\\<recursive\\>"
9470 (or (setq prop (org-entry-get
9471 nil "COOKIE_DATA" 'inherit)) ""))))
9472 (lim (or (and prop (marker-position
9473 org-entry-property-inherited-from))
9474 lim))
9475 (first t)
9476 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
9477 level ltoggle l1
9478 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
9479 (catch 'exit
9480 (save-excursion
9481 (beginning-of-line 1)
9482 (if (org-at-heading-p)
9483 (setq ltoggle (funcall outline-level))
9484 (error "This should not happen"))
9485 (while (and (setq level (org-up-heading-safe))
9486 (or recursive first)
9487 (>= (point) lim))
9488 (setq first nil)
9489 (unless (and level
9490 (not (string-match
9491 "\\<checkbox\\>"
9492 (downcase
9493 (or (org-entry-get
9494 nil "COOKIE_DATA")
9495 "")))))
9496 (throw 'exit nil))
9497 (while (re-search-forward box-re (point-at-eol) t)
9498 (setq cnt-all 0 cnt-done 0 cookie-present t)
9499 (setq is-percent (match-end 2))
9500 (save-match-data
9501 (unless (outline-next-heading) (throw 'exit nil))
9502 (while (and (looking-at org-complex-heading-regexp)
9503 (> (setq l1 (length (match-string 1))) level))
9504 (setq kwd (and (or recursive (= l1 ltoggle))
9505 (match-string 2)))
9506 (and kwd (setq cnt-all (1+ cnt-all)))
9507 (and (member kwd org-done-keywords)
9508 (setq cnt-done (1+ cnt-done)))
9509 (outline-next-heading)))
9510 (replace-match
9511 (if is-percent
9512 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
9513 (format "[%d/%d]" cnt-done cnt-all)))))
9514 (when cookie-present
9515 (run-hook-with-args 'org-after-todo-statistics-hook
9516 cnt-done (- cnt-all cnt-done)))))
9517 (run-hooks 'org-todo-statistics-hook)))
9519 (defvar org-after-todo-statistics-hook nil
9520 "Hook that is called after a TODO statistics cookie has been updated.
9521 Each function is called with two arguments: the number of not-done entries
9522 and the number of done entries.
9524 For example, the following function, when added to this hook, will switch
9525 an entry to DONE when all children are done, and back to TODO when new
9526 entries are set to a TODO status. Note that this hook is only called
9527 when there is a statistics cookie in the headline!
9529 (defun org-summary-todo (n-done n-not-done)
9530 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
9531 (let (org-log-done org-log-states) ; turn off logging
9532 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
9535 (defvar org-todo-statistics-hook nil
9536 "Hook that is run whenever Org thinks TODO statistics should be updated.
9537 This hook runs even if there is no statisics cookie present, in which case
9538 `org-after-todo-statistics-hook' would not run.")
9540 (defun org-todo-trigger-tag-changes (state)
9541 "Apply the changes defined in `org-todo-state-tags-triggers'."
9542 (let ((l org-todo-state-tags-triggers)
9543 changes)
9544 (when (or (not state) (equal state ""))
9545 (setq changes (append changes (cdr (assoc "" l)))))
9546 (when (and (stringp state) (> (length state) 0))
9547 (setq changes (append changes (cdr (assoc state l)))))
9548 (when (member state org-not-done-keywords)
9549 (setq changes (append changes (cdr (assoc 'todo l)))))
9550 (when (member state org-done-keywords)
9551 (setq changes (append changes (cdr (assoc 'done l)))))
9552 (dolist (c changes)
9553 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
9555 (defun org-local-logging (value)
9556 "Get logging settings from a property VALUE."
9557 (let* (words w a)
9558 ;; directly set the variables, they are already local.
9559 (setq org-log-done nil
9560 org-log-repeat nil
9561 org-todo-log-states nil)
9562 (setq words (org-split-string value))
9563 (while (setq w (pop words))
9564 (cond
9565 ((setq a (assoc w org-startup-options))
9566 (and (member (nth 1 a) '(org-log-done org-log-repeat))
9567 (set (nth 1 a) (nth 2 a))))
9568 ((setq a (org-extract-log-state-settings w))
9569 (and (member (car a) org-todo-keywords-1)
9570 (push a org-todo-log-states)))))))
9572 (defun org-get-todo-sequence-head (kwd)
9573 "Return the head of the TODO sequence to which KWD belongs.
9574 If KWD is not set, check if there is a text property remembering the
9575 right sequence."
9576 (let (p)
9577 (cond
9578 ((not kwd)
9579 (or (get-text-property (point-at-bol) 'org-todo-head)
9580 (progn
9581 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
9582 nil (point-at-eol)))
9583 (get-text-property p 'org-todo-head))))
9584 ((not (member kwd org-todo-keywords-1))
9585 (car org-todo-keywords-1))
9586 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
9588 (defun org-fast-todo-selection ()
9589 "Fast TODO keyword selection with single keys.
9590 Returns the new TODO keyword, or nil if no state change should occur."
9591 (let* ((fulltable org-todo-key-alist)
9592 (done-keywords org-done-keywords) ;; needed for the faces.
9593 (maxlen (apply 'max (mapcar
9594 (lambda (x)
9595 (if (stringp (car x)) (string-width (car x)) 0))
9596 fulltable)))
9597 (expert nil)
9598 (fwidth (+ maxlen 3 1 3))
9599 (ncol (/ (- (window-width) 4) fwidth))
9600 tg cnt e c tbl
9601 groups ingroup)
9602 (save-excursion
9603 (save-window-excursion
9604 (if expert
9605 (set-buffer (get-buffer-create " *Org todo*"))
9606 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
9607 (erase-buffer)
9608 (org-set-local 'org-done-keywords done-keywords)
9609 (setq tbl fulltable cnt 0)
9610 (while (setq e (pop tbl))
9611 (cond
9612 ((equal e '(:startgroup))
9613 (push '() groups) (setq ingroup t)
9614 (when (not (= cnt 0))
9615 (setq cnt 0)
9616 (insert "\n"))
9617 (insert "{ "))
9618 ((equal e '(:endgroup))
9619 (setq ingroup nil cnt 0)
9620 (insert "}\n"))
9621 ((equal e '(:newline))
9622 (when (not (= cnt 0))
9623 (setq cnt 0)
9624 (insert "\n")
9625 (setq e (car tbl))
9626 (while (equal (car tbl) '(:newline))
9627 (insert "\n")
9628 (setq tbl (cdr tbl)))))
9630 (setq tg (car e) c (cdr e))
9631 (if ingroup (push tg (car groups)))
9632 (setq tg (org-add-props tg nil 'face
9633 (org-get-todo-face tg)))
9634 (if (and (= cnt 0) (not ingroup)) (insert " "))
9635 (insert "[" c "] " tg (make-string
9636 (- fwidth 4 (length tg)) ?\ ))
9637 (when (= (setq cnt (1+ cnt)) ncol)
9638 (insert "\n")
9639 (if ingroup (insert " "))
9640 (setq cnt 0)))))
9641 (insert "\n")
9642 (goto-char (point-min))
9643 (if (not expert) (org-fit-window-to-buffer))
9644 (message "[a-z..]:Set [SPC]:clear")
9645 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9646 (cond
9647 ((or (= c ?\C-g)
9648 (and (= c ?q) (not (rassoc c fulltable))))
9649 (setq quit-flag t))
9650 ((= c ?\ ) nil)
9651 ((setq e (rassoc c fulltable) tg (car e))
9653 (t (setq quit-flag t)))))))
9655 (defun org-entry-is-todo-p ()
9656 (member (org-get-todo-state) org-not-done-keywords))
9658 (defun org-entry-is-done-p ()
9659 (member (org-get-todo-state) org-done-keywords))
9661 (defun org-get-todo-state ()
9662 (save-excursion
9663 (org-back-to-heading t)
9664 (and (looking-at org-todo-line-regexp)
9665 (match-end 2)
9666 (match-string 2))))
9668 (defun org-at-date-range-p (&optional inactive-ok)
9669 "Is the cursor inside a date range?"
9670 (interactive)
9671 (save-excursion
9672 (catch 'exit
9673 (let ((pos (point)))
9674 (skip-chars-backward "^[<\r\n")
9675 (skip-chars-backward "<[")
9676 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9677 (>= (match-end 0) pos)
9678 (throw 'exit t))
9679 (skip-chars-backward "^<[\r\n")
9680 (skip-chars-backward "<[")
9681 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9682 (>= (match-end 0) pos)
9683 (throw 'exit t)))
9684 nil)))
9686 (defun org-get-repeat ()
9687 "Check if there is a deadline/schedule with repeater in this entry."
9688 (save-match-data
9689 (save-excursion
9690 (org-back-to-heading t)
9691 (if (re-search-forward
9692 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9693 (match-string 1)))))
9695 (defvar org-last-changed-timestamp)
9696 (defvar org-last-inserted-timestamp)
9697 (defvar org-log-post-message)
9698 (defvar org-log-note-purpose)
9699 (defvar org-log-note-how)
9700 (defvar org-log-note-extra)
9701 (defun org-auto-repeat-maybe (done-word)
9702 "Check if the current headline contains a repeated deadline/schedule.
9703 If yes, set TODO state back to what it was and change the base date
9704 of repeating deadline/scheduled time stamps to new date.
9705 This function is run automatically after each state change to a DONE state."
9706 ;; last-state is dynamically scoped into this function
9707 (let* ((repeat (org-get-repeat))
9708 (aa (assoc last-state org-todo-kwd-alist))
9709 (interpret (nth 1 aa))
9710 (head (nth 2 aa))
9711 (whata '(("d" . day) ("m" . month) ("y" . year)))
9712 (msg "Entry repeats: ")
9713 (org-log-done nil)
9714 (org-todo-log-states nil)
9715 (nshiftmax 10) (nshift 0)
9716 re type n what ts time)
9717 (when repeat
9718 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9719 (org-todo (if (eq interpret 'type) last-state head))
9720 (when org-log-repeat
9721 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9722 (memq 'org-add-log-note post-command-hook))
9723 ;; OK, we are already setup for some record
9724 (if (eq org-log-repeat 'note)
9725 ;; make sure we take a note, not only a time stamp
9726 (setq org-log-note-how 'note))
9727 ;; Set up for taking a record
9728 (org-add-log-setup 'state (or done-word (car org-done-keywords))
9729 last-state
9730 'findpos org-log-repeat)))
9731 (org-back-to-heading t)
9732 (org-add-planning-info nil nil 'closed)
9733 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9734 org-deadline-time-regexp "\\)\\|\\("
9735 org-ts-regexp "\\)"))
9736 (while (re-search-forward
9737 re (save-excursion (outline-next-heading) (point)) t)
9738 (setq type (if (match-end 1) org-scheduled-string
9739 (if (match-end 3) org-deadline-string "Plain:"))
9740 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
9741 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
9742 (setq n (string-to-number (match-string 2 ts))
9743 what (match-string 3 ts))
9744 (if (equal what "w") (setq n (* n 7) what "d"))
9745 ;; Preparation, see if we need to modify the start date for the change
9746 (when (match-end 1)
9747 (setq time (save-match-data (org-time-string-to-time ts)))
9748 (cond
9749 ((equal (match-string 1 ts) ".")
9750 ;; Shift starting date to today
9751 (org-timestamp-change
9752 (- (time-to-days (current-time)) (time-to-days time))
9753 'day))
9754 ((equal (match-string 1 ts) "+")
9755 (while (or (= nshift 0)
9756 (<= (time-to-days time) (time-to-days (current-time))))
9757 (when (= (incf nshift) nshiftmax)
9758 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
9759 (error "Abort")))
9760 (org-timestamp-change n (cdr (assoc what whata)))
9761 (org-at-timestamp-p t)
9762 (setq ts (match-string 1))
9763 (setq time (save-match-data (org-time-string-to-time ts))))
9764 (org-timestamp-change (- n) (cdr (assoc what whata)))
9765 ;; rematch, so that we have everything in place for the real shift
9766 (org-at-timestamp-p t)
9767 (setq ts (match-string 1))
9768 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
9769 (org-timestamp-change n (cdr (assoc what whata)))
9770 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
9771 (setq org-log-post-message msg)
9772 (message "%s" msg))))
9774 (defun org-show-todo-tree (arg)
9775 "Make a compact tree which shows all headlines marked with TODO.
9776 The tree will show the lines where the regexp matches, and all higher
9777 headlines above the match.
9778 With a \\[universal-argument] prefix, also show the DONE entries.
9779 With a numeric prefix N, construct a sparse tree for the Nth element
9780 of `org-todo-keywords-1'."
9781 (interactive "P")
9782 (let ((case-fold-search nil)
9783 (kwd-re
9784 (cond ((null arg) org-not-done-regexp)
9785 ((equal arg '(4))
9786 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
9787 (mapcar 'list org-todo-keywords-1))))
9788 (concat "\\("
9789 (mapconcat 'identity (org-split-string kwd "|") "\\|")
9790 "\\)\\>")))
9791 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
9792 (regexp-quote (nth (1- (prefix-numeric-value arg))
9793 org-todo-keywords-1)))
9794 (t (error "Invalid prefix argument: %s" arg)))))
9795 (message "%d TODO entries found"
9796 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
9798 (defun org-deadline (&optional remove time)
9799 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
9800 With argument REMOVE, remove any deadline from the item.
9801 When TIME is set, it should be an internal time specification, and the
9802 scheduling will use the corresponding date."
9803 (interactive "P")
9804 (if remove
9805 (progn
9806 (org-remove-timestamp-with-keyword org-deadline-string)
9807 (message "Item no longer has a deadline."))
9808 (if (org-get-repeat)
9809 (error "Cannot change deadline on task with repeater, please do that by hand")
9810 (org-add-planning-info 'deadline time 'closed)
9811 (message "Deadline on %s" org-last-inserted-timestamp))))
9813 (defun org-schedule (&optional remove time)
9814 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
9815 With argument REMOVE, remove any scheduling date from the item.
9816 When TIME is set, it should be an internal time specification, and the
9817 scheduling will use the corresponding date."
9818 (interactive "P")
9819 (if remove
9820 (progn
9821 (org-remove-timestamp-with-keyword org-scheduled-string)
9822 (message "Item is no longer scheduled."))
9823 (if (org-get-repeat)
9824 (error "Cannot reschedule task with repeater, please do that by hand")
9825 (org-add-planning-info 'scheduled time 'closed)
9826 (message "Scheduled to %s" org-last-inserted-timestamp))))
9828 (defun org-get-scheduled-time (pom &optional inherit)
9829 "Get the scheduled time as a time tuple, of a format suitable
9830 for calling org-schedule with, or if there is no scheduling,
9831 returns nil."
9832 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
9833 (when time
9834 (apply 'encode-time (org-parse-time-string time)))))
9836 (defun org-get-deadline-time (pom &optional inherit)
9837 "Get the deadine as a time tuple, of a format suitable for
9838 calling org-deadlin with, or if there is no scheduling, returns
9839 nil."
9840 (let ((time (org-entry-get pom "DEADLINE" inherit)))
9841 (when time
9842 (apply 'encode-time (org-parse-time-string time)))))
9844 (defun org-remove-timestamp-with-keyword (keyword)
9845 "Remove all time stamps with KEYWORD in the current entry."
9846 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
9847 beg)
9848 (save-excursion
9849 (org-back-to-heading t)
9850 (setq beg (point))
9851 (org-end-of-subtree t t)
9852 (while (re-search-backward re beg t)
9853 (replace-match "")
9854 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9855 (equal (char-before) ?\ ))
9856 (backward-delete-char 1)
9857 (if (string-match "^[ \t]*$" (buffer-substring
9858 (point-at-bol) (point-at-eol)))
9859 (delete-region (point-at-bol)
9860 (min (point-max) (1+ (point-at-eol))))))))))
9862 (defun org-add-planning-info (what &optional time &rest remove)
9863 "Insert new timestamp with keyword in the line directly after the headline.
9864 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9865 If non is given, the user is prompted for a date.
9866 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9867 be removed."
9868 (interactive)
9869 (let (org-time-was-given org-end-time-was-given ts
9870 end default-time default-input)
9872 (catch 'exit
9873 (when (and (not time) (memq what '(scheduled deadline)))
9874 ;; Try to get a default date/time from existing timestamp
9875 (save-excursion
9876 (org-back-to-heading t)
9877 (setq end (save-excursion (outline-next-heading) (point)))
9878 (when (re-search-forward (if (eq what 'scheduled)
9879 org-scheduled-time-regexp
9880 org-deadline-time-regexp)
9881 end t)
9882 (setq ts (match-string 1)
9883 default-time
9884 (apply 'encode-time (org-parse-time-string ts))
9885 default-input (and ts (org-get-compact-tod ts))))))
9886 (when what
9887 ;; If necessary, get the time from the user
9888 (setq time (or time (org-read-date nil 'to-time nil nil
9889 default-time default-input))))
9891 (when (and org-insert-labeled-timestamps-at-point
9892 (member what '(scheduled deadline)))
9893 (insert
9894 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9895 (org-insert-time-stamp time org-time-was-given
9896 nil nil nil (list org-end-time-was-given))
9897 (setq what nil))
9898 (save-excursion
9899 (save-restriction
9900 (let (col list elt ts buffer-invisibility-spec)
9901 (org-back-to-heading t)
9902 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9903 (goto-char (match-end 1))
9904 (setq col (current-column))
9905 (goto-char (match-end 0))
9906 (if (eobp) (insert "\n") (forward-char 1))
9907 (when (and (not what)
9908 (not (looking-at
9909 (concat "[ \t]*"
9910 org-keyword-time-not-clock-regexp))))
9911 ;; Nothing to add, nothing to remove...... :-)
9912 (throw 'exit nil))
9913 (if (and (not (looking-at outline-regexp))
9914 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9915 "[^\r\n]*"))
9916 (not (equal (match-string 1) org-clock-string)))
9917 (narrow-to-region (match-beginning 0) (match-end 0))
9918 (insert-before-markers "\n")
9919 (backward-char 1)
9920 (narrow-to-region (point) (point))
9921 (and org-adapt-indentation (org-indent-to-column col)))
9922 ;; Check if we have to remove something.
9923 (setq list (cons what remove))
9924 (while list
9925 (setq elt (pop list))
9926 (goto-char (point-min))
9927 (when (or (and (eq elt 'scheduled)
9928 (re-search-forward org-scheduled-time-regexp nil t))
9929 (and (eq elt 'deadline)
9930 (re-search-forward org-deadline-time-regexp nil t))
9931 (and (eq elt 'closed)
9932 (re-search-forward org-closed-time-regexp nil t)))
9933 (replace-match "")
9934 (if (looking-at "--+<[^>]+>") (replace-match ""))
9935 (if (looking-at " +") (replace-match ""))))
9936 (goto-char (point-max))
9937 (when what
9938 (insert
9939 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9940 (cond ((eq what 'scheduled) org-scheduled-string)
9941 ((eq what 'deadline) org-deadline-string)
9942 ((eq what 'closed) org-closed-string))
9943 " ")
9944 (setq ts (org-insert-time-stamp
9945 time
9946 (or org-time-was-given
9947 (and (eq what 'closed) org-log-done-with-time))
9948 (eq what 'closed)
9949 nil nil (list org-end-time-was-given)))
9950 (end-of-line 1))
9951 (goto-char (point-min))
9952 (widen)
9953 (if (and (looking-at "[ \t]+\n")
9954 (equal (char-before) ?\n))
9955 (delete-region (1- (point)) (point-at-eol)))
9956 ts))))))
9958 (defvar org-log-note-marker (make-marker))
9959 (defvar org-log-note-purpose nil)
9960 (defvar org-log-note-state nil)
9961 (defvar org-log-note-previous-state nil)
9962 (defvar org-log-note-how nil)
9963 (defvar org-log-note-extra nil)
9964 (defvar org-log-note-window-configuration nil)
9965 (defvar org-log-note-return-to (make-marker))
9966 (defvar org-log-post-message nil
9967 "Message to be displayed after a log note has been stored.
9968 The auto-repeater uses this.")
9970 (defun org-add-note ()
9971 "Add a note to the current entry.
9972 This is done in the same way as adding a state change note."
9973 (interactive)
9974 (org-add-log-setup 'note nil nil 'findpos nil))
9976 (defvar org-property-end-re)
9977 (defun org-add-log-setup (&optional purpose state prev-state
9978 findpos how &optional extra)
9979 "Set up the post command hook to take a note.
9980 If this is about to TODO state change, the new state is expected in STATE.
9981 When FINDPOS is non-nil, find the correct position for the note in
9982 the current entry. If not, assume that it can be inserted at point.
9983 HOW is an indicator what kind of note should be created.
9984 EXTRA is additional text that will be inserted into the notes buffer."
9985 (let* ((org-log-into-drawer (org-log-into-drawer))
9986 (drawer (cond ((stringp org-log-into-drawer)
9987 org-log-into-drawer)
9988 (org-log-into-drawer "LOGBOOK")
9989 (t nil))))
9990 (save-restriction
9991 (save-excursion
9992 (when findpos
9993 (org-back-to-heading t)
9994 (narrow-to-region (point) (save-excursion
9995 (outline-next-heading) (point)))
9996 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9997 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9998 "[^\r\n]*\\)?"))
9999 (goto-char (match-end 0))
10000 (cond
10001 (drawer
10002 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
10003 nil t)
10004 (progn
10005 (goto-char (match-end 0))
10006 (or org-log-states-order-reversed
10007 (and (re-search-forward org-property-end-re nil t)
10008 (goto-char (1- (match-beginning 0))))))
10009 (insert "\n:" drawer ":\n:END:")
10010 (beginning-of-line 0)
10011 (org-indent-line-function)
10012 (beginning-of-line 2)
10013 (org-indent-line-function)
10014 (end-of-line 0)))
10015 ((and org-log-state-notes-insert-after-drawers
10016 (save-excursion
10017 (forward-line) (looking-at org-drawer-regexp)))
10018 (forward-line)
10019 (while (looking-at org-drawer-regexp)
10020 (goto-char (match-end 0))
10021 (re-search-forward org-property-end-re (point-max) t)
10022 (forward-line))
10023 (forward-line -1)))
10024 (unless org-log-states-order-reversed
10025 (and (= (char-after) ?\n) (forward-char 1))
10026 (org-skip-over-state-notes)
10027 (skip-chars-backward " \t\n\r")))
10028 (move-marker org-log-note-marker (point))
10029 (setq org-log-note-purpose purpose
10030 org-log-note-state state
10031 org-log-note-previous-state prev-state
10032 org-log-note-how how
10033 org-log-note-extra extra)
10034 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
10036 (defun org-skip-over-state-notes ()
10037 "Skip past the list of State notes in an entry."
10038 (if (looking-at "\n[ \t]*- State") (forward-char 1))
10039 (while (looking-at "[ \t]*- State")
10040 (condition-case nil
10041 (org-next-item)
10042 (error (org-end-of-item)))))
10044 (defun org-add-log-note (&optional purpose)
10045 "Pop up a window for taking a note, and add this note later at point."
10046 (remove-hook 'post-command-hook 'org-add-log-note)
10047 (setq org-log-note-window-configuration (current-window-configuration))
10048 (delete-other-windows)
10049 (move-marker org-log-note-return-to (point))
10050 (switch-to-buffer (marker-buffer org-log-note-marker))
10051 (goto-char org-log-note-marker)
10052 (org-switch-to-buffer-other-window "*Org Note*")
10053 (erase-buffer)
10054 (if (memq org-log-note-how '(time state))
10055 (let (current-prefix-arg) (org-store-log-note))
10056 (let ((org-inhibit-startup t)) (org-mode))
10057 (insert (format "# Insert note for %s.
10058 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10059 (cond
10060 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10061 ((eq org-log-note-purpose 'done) "closed todo item")
10062 ((eq org-log-note-purpose 'state)
10063 (format "state change from \"%s\" to \"%s\""
10064 (or org-log-note-previous-state "")
10065 (or org-log-note-state "")))
10066 ((eq org-log-note-purpose 'note)
10067 "this entry")
10068 (t (error "This should not happen")))))
10069 (if org-log-note-extra (insert org-log-note-extra))
10070 (org-set-local 'org-finish-function 'org-store-log-note)))
10072 (defvar org-note-abort nil) ; dynamically scoped
10073 (defun org-store-log-note ()
10074 "Finish taking a log note, and insert it to where it belongs."
10075 (let ((txt (buffer-string))
10076 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10077 lines ind)
10078 (kill-buffer (current-buffer))
10079 (while (string-match "\\`#.*\n[ \t\n]*" txt)
10080 (setq txt (replace-match "" t t txt)))
10081 (if (string-match "\\s-+\\'" txt)
10082 (setq txt (replace-match "" t t txt)))
10083 (setq lines (org-split-string txt "\n"))
10084 (when (and note (string-match "\\S-" note))
10085 (setq note
10086 (org-replace-escapes
10087 note
10088 (list (cons "%u" (user-login-name))
10089 (cons "%U" user-full-name)
10090 (cons "%t" (format-time-string
10091 (org-time-stamp-format 'long 'inactive)
10092 (current-time)))
10093 (cons "%s" (if org-log-note-state
10094 (concat "\"" org-log-note-state "\"")
10095 ""))
10096 (cons "%S" (if org-log-note-previous-state
10097 (concat "\"" org-log-note-previous-state "\"")
10098 "\"\"")))))
10099 (if lines (setq note (concat note " \\\\")))
10100 (push note lines))
10101 (when (or current-prefix-arg org-note-abort)
10102 (when org-log-into-drawer
10103 (org-remove-empty-drawer-at
10104 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
10105 org-log-note-marker))
10106 (setq lines nil))
10107 (when lines
10108 (save-excursion
10109 (set-buffer (marker-buffer org-log-note-marker))
10110 (save-excursion
10111 (goto-char org-log-note-marker)
10112 (move-marker org-log-note-marker nil)
10113 (end-of-line 1)
10114 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
10115 (insert "- " (pop lines))
10116 (org-indent-line-function)
10117 (beginning-of-line 1)
10118 (looking-at "[ \t]*")
10119 (setq ind (concat (match-string 0) " "))
10120 (end-of-line 1)
10121 (while lines (insert "\n" ind (pop lines)))
10122 (message "Note stored")
10123 (org-back-to-heading t)
10124 (org-cycle-hide-drawers 'children)))))
10125 (set-window-configuration org-log-note-window-configuration)
10126 (with-current-buffer (marker-buffer org-log-note-return-to)
10127 (goto-char org-log-note-return-to))
10128 (move-marker org-log-note-return-to nil)
10129 (and org-log-post-message (message "%s" org-log-post-message)))
10131 (defun org-remove-empty-drawer-at (drawer pos)
10132 "Remove an emptyr DARWER drawer at position POS.
10133 POS may also be a marker."
10134 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
10135 (save-excursion
10136 (save-restriction
10137 (widen)
10138 (goto-char pos)
10139 (if (org-in-regexp
10140 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
10141 (replace-match ""))))))
10143 (defun org-sparse-tree (&optional arg)
10144 "Create a sparse tree, prompt for the details.
10145 This command can create sparse trees. You first need to select the type
10146 of match used to create the tree:
10148 t Show entries with a specific TODO keyword.
10149 m Show entries selected by a tags/property match.
10150 p Enter a property name and its value (both with completion on existing
10151 names/values) and show entries with that property.
10152 r Show entries matching a regular expression.
10153 d Show deadlines due within `org-deadline-warning-days'.
10154 b Show deadlines and scheduled items before a date.
10155 a Show deadlines and scheduled items after a date."
10156 (interactive "P")
10157 (let (ans kwd value)
10158 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
10159 (setq ans (read-char-exclusive))
10160 (cond
10161 ((equal ans ?d)
10162 (call-interactively 'org-check-deadlines))
10163 ((equal ans ?b)
10164 (call-interactively 'org-check-before-date))
10165 ((equal ans ?a)
10166 (call-interactively 'org-check-after-date))
10167 ((equal ans ?t)
10168 (org-show-todo-tree '(4)))
10169 ((member ans '(?T ?m))
10170 (call-interactively 'org-match-sparse-tree))
10171 ((member ans '(?p ?P))
10172 (setq kwd (org-ido-completing-read "Property: "
10173 (mapcar 'list (org-buffer-property-keys))))
10174 (setq value (org-ido-completing-read "Value: "
10175 (mapcar 'list (org-property-values kwd))))
10176 (unless (string-match "\\`{.*}\\'" value)
10177 (setq value (concat "\"" value "\"")))
10178 (org-match-sparse-tree arg (concat kwd "=" value)))
10179 ((member ans '(?r ?R ?/))
10180 (call-interactively 'org-occur))
10181 (t (error "No such sparse tree command \"%c\"" ans)))))
10183 (defvar org-occur-highlights nil
10184 "List of overlays used for occur matches.")
10185 (make-variable-buffer-local 'org-occur-highlights)
10186 (defvar org-occur-parameters nil
10187 "Parameters of the active org-occur calls.
10188 This is a list, each call to org-occur pushes as cons cell,
10189 containing the regular expression and the callback, onto the list.
10190 The list can contain several entries if `org-occur' has been called
10191 several time with the KEEP-PREVIOUS argument. Otherwise, this list
10192 will only contain one set of parameters. When the highlights are
10193 removed (for example with `C-c C-c', or with the next edit (depending
10194 on `org-remove-highlights-with-change'), this variable is emptied
10195 as well.")
10196 (make-variable-buffer-local 'org-occur-parameters)
10198 (defun org-occur (regexp &optional keep-previous callback)
10199 "Make a compact tree which shows all matches of REGEXP.
10200 The tree will show the lines where the regexp matches, and all higher
10201 headlines above the match. It will also show the heading after the match,
10202 to make sure editing the matching entry is easy.
10203 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
10204 call to `org-occur' will be kept, to allow stacking of calls to this
10205 command.
10206 If CALLBACK is non-nil, it is a function which is called to confirm
10207 that the match should indeed be shown."
10208 (interactive "sRegexp: \nP")
10209 (unless keep-previous
10210 (org-remove-occur-highlights nil nil t))
10211 (push (cons regexp callback) org-occur-parameters)
10212 (let ((cnt 0))
10213 (save-excursion
10214 (goto-char (point-min))
10215 (if (or (not keep-previous) ; do not want to keep
10216 (not org-occur-highlights)) ; no previous matches
10217 ;; hide everything
10218 (org-overview))
10219 (while (re-search-forward regexp nil t)
10220 (when (or (not callback)
10221 (save-match-data (funcall callback)))
10222 (setq cnt (1+ cnt))
10223 (when org-highlight-sparse-tree-matches
10224 (org-highlight-new-match (match-beginning 0) (match-end 0)))
10225 (org-show-context 'occur-tree))))
10226 (when org-remove-highlights-with-change
10227 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10228 nil 'local))
10229 (unless org-sparse-tree-open-archived-trees
10230 (org-hide-archived-subtrees (point-min) (point-max)))
10231 (run-hooks 'org-occur-hook)
10232 (if (interactive-p)
10233 (message "%d match(es) for regexp %s" cnt regexp))
10234 cnt))
10236 (defun org-show-context (&optional key)
10237 "Make sure point and context and visible.
10238 How much context is shown depends upon the variables
10239 `org-show-hierarchy-above', `org-show-following-heading'. and
10240 `org-show-siblings'."
10241 (let ((heading-p (org-on-heading-p t))
10242 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
10243 (following-p (org-get-alist-option org-show-following-heading key))
10244 (entry-p (org-get-alist-option org-show-entry-below key))
10245 (siblings-p (org-get-alist-option org-show-siblings key)))
10246 (catch 'exit
10247 ;; Show heading or entry text
10248 (if (and heading-p (not entry-p))
10249 (org-flag-heading nil) ; only show the heading
10250 (and (or entry-p (org-invisible-p) (org-invisible-p2))
10251 (org-show-hidden-entry))) ; show entire entry
10252 (when following-p
10253 ;; Show next sibling, or heading below text
10254 (save-excursion
10255 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10256 (org-flag-heading nil))))
10257 (when siblings-p (org-show-siblings))
10258 (when hierarchy-p
10259 ;; show all higher headings, possibly with siblings
10260 (save-excursion
10261 (while (and (condition-case nil
10262 (progn (org-up-heading-all 1) t)
10263 (error nil))
10264 (not (bobp)))
10265 (org-flag-heading nil)
10266 (when siblings-p (org-show-siblings))))))))
10268 (defun org-reveal (&optional siblings)
10269 "Show current entry, hierarchy above it, and the following headline.
10270 This can be used to show a consistent set of context around locations
10271 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10272 not t for the search context.
10274 With optional argument SIBLINGS, on each level of the hierarchy all
10275 siblings are shown. This repairs the tree structure to what it would
10276 look like when opened with hierarchical calls to `org-cycle'."
10277 (interactive "P")
10278 (let ((org-show-hierarchy-above t)
10279 (org-show-following-heading t)
10280 (org-show-siblings (if siblings t org-show-siblings)))
10281 (org-show-context nil)))
10283 (defun org-highlight-new-match (beg end)
10284 "Highlight from BEG to END and mark the highlight is an occur headline."
10285 (let ((ov (org-make-overlay beg end)))
10286 (org-overlay-put ov 'face 'secondary-selection)
10287 (push ov org-occur-highlights)))
10289 (defun org-remove-occur-highlights (&optional beg end noremove)
10290 "Remove the occur highlights from the buffer.
10291 BEG and END are ignored. If NOREMOVE is nil, remove this function
10292 from the `before-change-functions' in the current buffer."
10293 (interactive)
10294 (unless org-inhibit-highlight-removal
10295 (mapc 'org-delete-overlay org-occur-highlights)
10296 (setq org-occur-highlights nil)
10297 (setq org-occur-parameters nil)
10298 (unless noremove
10299 (remove-hook 'before-change-functions
10300 'org-remove-occur-highlights 'local))))
10302 ;;;; Priorities
10304 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
10305 "Regular expression matching the priority indicator.")
10307 (defvar org-remove-priority-next-time nil)
10309 (defun org-priority-up ()
10310 "Increase the priority of the current item."
10311 (interactive)
10312 (org-priority 'up))
10314 (defun org-priority-down ()
10315 "Decrease the priority of the current item."
10316 (interactive)
10317 (org-priority 'down))
10319 (defun org-priority (&optional action)
10320 "Change the priority of an item by ARG.
10321 ACTION can be `set', `up', `down', or a character."
10322 (interactive)
10323 (unless org-enable-priority-commands
10324 (error "Priority commands are disabled"))
10325 (setq action (or action 'set))
10326 (let (current new news have remove)
10327 (save-excursion
10328 (org-back-to-heading t)
10329 (if (looking-at org-priority-regexp)
10330 (setq current (string-to-char (match-string 2))
10331 have t)
10332 (setq current org-default-priority))
10333 (cond
10334 ((or (eq action 'set)
10335 (if (featurep 'xemacs) (characterp action) (integerp action)))
10336 (if (not (eq action 'set))
10337 (setq new action)
10338 (message "Priority %c-%c, SPC to remove: "
10339 org-highest-priority org-lowest-priority)
10340 (setq new (read-char-exclusive)))
10341 (if (and (= (upcase org-highest-priority) org-highest-priority)
10342 (= (upcase org-lowest-priority) org-lowest-priority))
10343 (setq new (upcase new)))
10344 (cond ((equal new ?\ ) (setq remove t))
10345 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
10346 (error "Priority must be between `%c' and `%c'"
10347 org-highest-priority org-lowest-priority))))
10348 ((eq action 'up)
10349 (if (and (not have) (eq last-command this-command))
10350 (setq new org-lowest-priority)
10351 (setq new (if (and org-priority-start-cycle-with-default (not have))
10352 org-default-priority (1- current)))))
10353 ((eq action 'down)
10354 (if (and (not have) (eq last-command this-command))
10355 (setq new org-highest-priority)
10356 (setq new (if (and org-priority-start-cycle-with-default (not have))
10357 org-default-priority (1+ current)))))
10358 (t (error "Invalid action")))
10359 (if (or (< (upcase new) org-highest-priority)
10360 (> (upcase new) org-lowest-priority))
10361 (setq remove t))
10362 (setq news (format "%c" new))
10363 (if have
10364 (if remove
10365 (replace-match "" t t nil 1)
10366 (replace-match news t t nil 2))
10367 (if remove
10368 (error "No priority cookie found in line")
10369 (let ((case-fold-search nil))
10370 (looking-at org-todo-line-regexp))
10371 (if (match-end 2)
10372 (progn
10373 (goto-char (match-end 2))
10374 (insert " [#" news "]"))
10375 (goto-char (match-beginning 3))
10376 (insert "[#" news "] ")))))
10377 (org-preserve-lc (org-set-tags nil 'align))
10378 (if remove
10379 (message "Priority removed")
10380 (message "Priority of current item set to %s" news))))
10383 (defun org-get-priority (s)
10384 "Find priority cookie and return priority."
10385 (save-match-data
10386 (if (not (string-match org-priority-regexp s))
10387 (* 1000 (- org-lowest-priority org-default-priority))
10388 (* 1000 (- org-lowest-priority
10389 (string-to-char (match-string 2 s)))))))
10391 ;;;; Tags
10393 (defvar org-agenda-archives-mode)
10394 (defvar org-map-continue-from nil
10395 "Position from where mapping should continue.
10396 Can be set byt the action argument to `org-scan-tag's and `org-map-entries'.")
10398 (defvar org-scanner-tags nil
10399 "The current tag list while the tags scanner is running.")
10400 (defvar org-trust-scanner-tags nil
10401 "Should `org-get-tags-at' use the tags fro the scanner.
10402 This is for internal dynamical scoping only.
10403 When this is non-nil, the function `org-get-tags-at' will return the value
10404 of `org-scanner-tags' instead of building the list by itself. This
10405 can lead to large speed-ups when the tags scanner is used in a file with
10406 many entries, and when the list of tags is retrieved, for example to
10407 obtain a list of properties. Building the tags list for each entry in such
10408 a file becomes an N^2 operation - but with this variable set, it scales
10409 as N.")
10411 (defun org-scan-tags (action matcher &optional todo-only)
10412 "Scan headline tags with inheritance and produce output ACTION.
10414 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
10415 or `agenda' to produce an entry list for an agenda view. It can also be
10416 a Lisp form or a function that should be called at each matched headline, in
10417 this case the return value is a list of all return values from these calls.
10419 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
10420 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
10421 only lines with a TODO keyword are included in the output."
10422 (require 'org-agenda)
10423 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
10424 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
10425 (org-re
10426 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
10427 (props (list 'face 'default
10428 'done-face 'org-agenda-done
10429 'undone-face 'default
10430 'mouse-face 'highlight
10431 'org-not-done-regexp org-not-done-regexp
10432 'org-todo-regexp org-todo-regexp
10433 'keymap org-agenda-keymap
10434 'help-echo
10435 (format "mouse-2 or RET jump to org file %s"
10436 (abbreviate-file-name
10437 (or (buffer-file-name (buffer-base-buffer))
10438 (buffer-name (buffer-base-buffer)))))))
10439 (case-fold-search nil)
10440 (org-map-continue-from nil)
10441 lspos tags tags-list
10442 (tags-alist (list (cons 0 org-file-tags)))
10443 (llast 0) rtn rtn1 level category i txt
10444 todo marker entry priority)
10445 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
10446 (setq action (list 'lambda nil action)))
10447 (save-excursion
10448 (goto-char (point-min))
10449 (when (eq action 'sparse-tree)
10450 (org-overview)
10451 (org-remove-occur-highlights))
10452 (while (re-search-forward re nil t)
10453 (catch :skip
10454 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
10455 tags (if (match-end 4) (org-match-string-no-properties 4)))
10456 (goto-char (setq lspos (match-beginning 0)))
10457 (setq level (org-reduced-level (funcall outline-level))
10458 category (org-get-category))
10459 (setq i llast llast level)
10460 ;; remove tag lists from same and sublevels
10461 (while (>= i level)
10462 (when (setq entry (assoc i tags-alist))
10463 (setq tags-alist (delete entry tags-alist)))
10464 (setq i (1- i)))
10465 ;; add the next tags
10466 (when tags
10467 (setq tags (org-split-string tags ":")
10468 tags-alist
10469 (cons (cons level tags) tags-alist)))
10470 ;; compile tags for current headline
10471 (setq tags-list
10472 (if org-use-tag-inheritance
10473 (apply 'append (mapcar 'cdr (reverse tags-alist)))
10474 tags)
10475 org-scanner-tags tags-list)
10476 (when org-use-tag-inheritance
10477 (setcdr (car tags-alist)
10478 (mapcar (lambda (x)
10479 (setq x (copy-sequence x))
10480 (org-add-prop-inherited x))
10481 (cdar tags-alist))))
10482 (when (and tags org-use-tag-inheritance
10483 (or (not (eq t org-use-tag-inheritance))
10484 org-tags-exclude-from-inheritance))
10485 ;; selective inheritance, remove uninherited ones
10486 (setcdr (car tags-alist)
10487 (org-remove-uniherited-tags (cdar tags-alist))))
10488 (when (and (or (not todo-only)
10489 (and (member todo org-not-done-keywords)
10490 (or (not org-agenda-tags-todo-honor-ignore-options)
10491 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
10492 (let ((case-fold-search t)) (eval matcher))
10494 (not (member org-archive-tag tags-list))
10495 ;; we have an archive tag, should we use this anyway?
10496 (or (not org-agenda-skip-archived-trees)
10497 (and (eq action 'agenda) org-agenda-archives-mode))))
10498 (unless (eq action 'sparse-tree) (org-agenda-skip))
10500 ;; select this headline
10502 (cond
10503 ((eq action 'sparse-tree)
10504 (and org-highlight-sparse-tree-matches
10505 (org-get-heading) (match-end 0)
10506 (org-highlight-new-match
10507 (match-beginning 0) (match-beginning 1)))
10508 (org-show-context 'tags-tree))
10509 ((eq action 'agenda)
10510 (setq txt (org-format-agenda-item
10512 (concat
10513 (if (eq org-tags-match-list-sublevels 'indented)
10514 (make-string (1- level) ?.) "")
10515 (org-get-heading))
10516 category
10517 tags-list
10519 priority (org-get-priority txt))
10520 (goto-char lspos)
10521 (setq marker (org-agenda-new-marker))
10522 (org-add-props txt props
10523 'org-marker marker 'org-hd-marker marker 'org-category category
10524 'todo-state todo
10525 'priority priority 'type "tagsmatch")
10526 (push txt rtn))
10527 ((functionp action)
10528 (setq org-map-continue-from nil)
10529 (save-excursion
10530 (setq rtn1 (funcall action))
10531 (push rtn1 rtn)))
10532 (t (error "Invalid action")))
10534 ;; if we are to skip sublevels, jump to end of subtree
10535 (unless org-tags-match-list-sublevels
10536 (org-end-of-subtree t)
10537 (backward-char 1))))
10538 ;; Get the correct position from where to continue
10539 (if org-map-continue-from
10540 (goto-char org-map-continue-from)
10541 (and (= (point) lspos) (end-of-line 1)))))
10542 (when (and (eq action 'sparse-tree)
10543 (not org-sparse-tree-open-archived-trees))
10544 (org-hide-archived-subtrees (point-min) (point-max)))
10545 (nreverse rtn)))
10547 (defun org-remove-uniherited-tags (tags)
10548 "Remove all tags that are not inherited from the list TAGS."
10549 (cond
10550 ((eq org-use-tag-inheritance t)
10551 (if org-tags-exclude-from-inheritance
10552 (org-delete-all org-tags-exclude-from-inheritance tags)
10553 tags))
10554 ((not org-use-tag-inheritance) nil)
10555 ((stringp org-use-tag-inheritance)
10556 (delq nil (mapcar
10557 (lambda (x)
10558 (if (and (string-match org-use-tag-inheritance x)
10559 (not (member x org-tags-exclude-from-inheritance)))
10560 x nil))
10561 tags)))
10562 ((listp org-use-tag-inheritance)
10563 (delq nil (mapcar
10564 (lambda (x)
10565 (if (member x org-use-tag-inheritance) x nil))
10566 tags)))))
10568 (defvar todo-only) ;; dynamically scoped
10570 (defun org-match-sparse-tree (&optional todo-only match)
10571 "Create a sparse tree according to tags string MATCH.
10572 MATCH can contain positive and negative selection of tags, like
10573 \"+WORK+URGENT-WITHBOSS\".
10574 If optional argument TODO-ONLY is non-nil, only select lines that are
10575 also TODO lines."
10576 (interactive "P")
10577 (org-prepare-agenda-buffers (list (current-buffer)))
10578 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
10580 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
10582 (defvar org-cached-props nil)
10583 (defun org-cached-entry-get (pom property)
10584 (if (or (eq t org-use-property-inheritance)
10585 (and (stringp org-use-property-inheritance)
10586 (string-match org-use-property-inheritance property))
10587 (and (listp org-use-property-inheritance)
10588 (member property org-use-property-inheritance)))
10589 ;; Caching is not possible, check it directly
10590 (org-entry-get pom property 'inherit)
10591 ;; Get all properties, so that we can do complicated checks easily
10592 (cdr (assoc property (or org-cached-props
10593 (setq org-cached-props
10594 (org-entry-properties pom)))))))
10596 (defun org-global-tags-completion-table (&optional files)
10597 "Return the list of all tags in all agenda buffer/files."
10598 (save-excursion
10599 (org-uniquify
10600 (delq nil
10601 (apply 'append
10602 (mapcar
10603 (lambda (file)
10604 (set-buffer (find-file-noselect file))
10605 (append (org-get-buffer-tags)
10606 (mapcar (lambda (x) (if (stringp (car-safe x))
10607 (list (car-safe x)) nil))
10608 org-tag-alist)))
10609 (if (and files (car files))
10610 files
10611 (org-agenda-files))))))))
10613 (defun org-make-tags-matcher (match)
10614 "Create the TAGS//TODO matcher form for the selection string MATCH."
10615 ;; todo-only is scoped dynamically into this function, and the function
10616 ;; may change it if the matcher asks for it.
10617 (unless match
10618 ;; Get a new match request, with completion
10619 (let ((org-last-tags-completion-table
10620 (org-global-tags-completion-table)))
10621 (setq match (org-completing-read-no-ido
10622 "Match: " 'org-tags-completion-function nil nil nil
10623 'org-tags-history))))
10625 ;; Parse the string and create a lisp form
10626 (let ((match0 match)
10627 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
10628 minus tag mm
10629 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
10630 orterms term orlist re-p str-p level-p level-op time-p
10631 prop-p pn pv po cat-p gv rest)
10632 (if (string-match "/+" match)
10633 ;; match contains also a todo-matching request
10634 (progn
10635 (setq tagsmatch (substring match 0 (match-beginning 0))
10636 todomatch (substring match (match-end 0)))
10637 (if (string-match "^!" todomatch)
10638 (setq todo-only t todomatch (substring todomatch 1)))
10639 (if (string-match "^\\s-*$" todomatch)
10640 (setq todomatch nil)))
10641 ;; only matching tags
10642 (setq tagsmatch match todomatch nil))
10644 ;; Make the tags matcher
10645 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10646 (setq tagsmatcher t)
10647 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10648 (while (setq term (pop orterms))
10649 (while (and (equal (substring term -1) "\\") orterms)
10650 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10651 (while (string-match re term)
10652 (setq rest (substring term (match-end 0))
10653 minus (and (match-end 1)
10654 (equal (match-string 1 term) "-"))
10655 tag (match-string 2 term)
10656 re-p (equal (string-to-char tag) ?{)
10657 level-p (match-end 4)
10658 prop-p (match-end 5)
10659 mm (cond
10660 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10661 (level-p
10662 (setq level-op (org-op-to-function (match-string 3 term)))
10663 `(,level-op level ,(string-to-number
10664 (match-string 4 term))))
10665 (prop-p
10666 (setq pn (match-string 5 term)
10667 po (match-string 6 term)
10668 pv (match-string 7 term)
10669 cat-p (equal pn "CATEGORY")
10670 re-p (equal (string-to-char pv) ?{)
10671 str-p (equal (string-to-char pv) ?\")
10672 time-p (save-match-data
10673 (string-match "^\"[[<].*[]>]\"$" pv))
10674 pv (if (or re-p str-p) (substring pv 1 -1) pv))
10675 (if time-p (setq pv (org-matcher-time pv)))
10676 (setq po (org-op-to-function po (if time-p 'time str-p)))
10677 (cond
10678 ((equal pn "CATEGORY")
10679 (setq gv '(get-text-property (point) 'org-category)))
10680 ((equal pn "TODO")
10681 (setq gv 'todo))
10683 (setq gv `(org-cached-entry-get nil ,pn))))
10684 (if re-p
10685 (if (eq po 'org<>)
10686 `(not (string-match ,pv (or ,gv "")))
10687 `(string-match ,pv (or ,gv "")))
10688 (if str-p
10689 `(,po (or ,gv "") ,pv)
10690 `(,po (string-to-number (or ,gv ""))
10691 ,(string-to-number pv) ))))
10692 (t `(member ,tag tags-list)))
10693 mm (if minus (list 'not mm) mm)
10694 term rest)
10695 (push mm tagsmatcher))
10696 (push (if (> (length tagsmatcher) 1)
10697 (cons 'and tagsmatcher)
10698 (car tagsmatcher))
10699 orlist)
10700 (setq tagsmatcher nil))
10701 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
10702 (setq tagsmatcher
10703 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
10704 ;; Make the todo matcher
10705 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10706 (setq todomatcher t)
10707 (setq orterms (org-split-string todomatch "|") orlist nil)
10708 (while (setq term (pop orterms))
10709 (while (string-match re term)
10710 (setq minus (and (match-end 1)
10711 (equal (match-string 1 term) "-"))
10712 kwd (match-string 2 term)
10713 re-p (equal (string-to-char kwd) ?{)
10714 term (substring term (match-end 0))
10715 mm (if re-p
10716 `(string-match ,(substring kwd 1 -1) todo)
10717 (list 'equal 'todo kwd))
10718 mm (if minus (list 'not mm) mm))
10719 (push mm todomatcher))
10720 (push (if (> (length todomatcher) 1)
10721 (cons 'and todomatcher)
10722 (car todomatcher))
10723 orlist)
10724 (setq todomatcher nil))
10725 (setq todomatcher (if (> (length orlist) 1)
10726 (cons 'or orlist) (car orlist))))
10728 ;; Return the string and lisp forms of the matcher
10729 (setq matcher (if todomatcher
10730 (list 'and tagsmatcher todomatcher)
10731 tagsmatcher))
10732 (cons match0 matcher)))
10734 (defun org-op-to-function (op &optional stringp)
10735 "Turn an operator into the appropriate function."
10736 (setq op
10737 (cond
10738 ((equal op "<" ) '(< string< org-time<))
10739 ((equal op ">" ) '(> org-string> org-time>))
10740 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
10741 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
10742 ((member op '("=" "==")) '(= string= org-time=))
10743 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
10744 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
10746 (defun org<> (a b) (not (= a b)))
10747 (defun org-string<= (a b) (or (string= a b) (string< a b)))
10748 (defun org-string>= (a b) (not (string< a b)))
10749 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
10750 (defun org-string<> (a b) (not (string= a b)))
10751 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
10752 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
10753 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
10754 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
10755 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
10756 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
10757 (defun org-2ft (s)
10758 "Convert S to a floating point time.
10759 If S is already a number, just return it. If it is a string, parse
10760 it as a time string and apply `float-time' to it. If S is nil, just return 0."
10761 (cond
10762 ((numberp s) s)
10763 ((stringp s)
10764 (condition-case nil
10765 (float-time (apply 'encode-time (org-parse-time-string s)))
10766 (error 0.)))
10767 (t 0.)))
10769 (defun org-time-today ()
10770 "Time in seconds today at 0:00.
10771 Returns the float number of seconds since the beginning of the
10772 epoch to the beginning of today (00:00)."
10773 (float-time (apply 'encode-time
10774 (append '(0 0 0) (nthcdr 3 (decode-time))))))
10776 (defun org-matcher-time (s)
10777 "Interpret a time comparison value."
10778 (save-match-data
10779 (cond
10780 ((string= s "<now>") (float-time))
10781 ((string= s "<today>") (org-time-today))
10782 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
10783 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
10784 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
10785 (+ (org-time-today)
10786 (* (string-to-number (match-string 1 s))
10787 (cdr (assoc (match-string 2 s)
10788 '(("d" . 86400.0) ("w" . 604800.0)
10789 ("m" . 2678400.0) ("y" . 31557600.0)))))))
10790 (t (org-2ft s)))))
10792 (defun org-match-any-p (re list)
10793 "Does re match any element of list?"
10794 (setq list (mapcar (lambda (x) (string-match re x)) list))
10795 (delq nil list))
10797 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
10798 (defvar org-tags-overlay (org-make-overlay 1 1))
10799 (org-detach-overlay org-tags-overlay)
10801 (defun org-get-local-tags-at (&optional pos)
10802 "Get a list of tags defined in the current headline."
10803 (org-get-tags-at pos 'local))
10805 (defun org-get-local-tags ()
10806 "Get a list of tags defined in the current headline."
10807 (org-get-tags-at nil 'local))
10809 (defun org-get-tags-at (&optional pos local)
10810 "Get a list of all headline tags applicable at POS.
10811 POS defaults to point. If tags are inherited, the list contains
10812 the targets in the same sequence as the headlines appear, i.e.
10813 the tags of the current headline come last.
10814 When LOCAL is non-nil, only return tags from the current headline,
10815 ignore inherited ones."
10816 (interactive)
10817 (if (and org-trust-scanner-tags
10818 (or (not pos) (equal pos (point)))
10819 (not local))
10820 org-scanner-tags
10821 (let (tags ltags lastpos parent)
10822 (save-excursion
10823 (save-restriction
10824 (widen)
10825 (goto-char (or pos (point)))
10826 (save-match-data
10827 (catch 'done
10828 (condition-case nil
10829 (progn
10830 (org-back-to-heading t)
10831 (while (not (equal lastpos (point)))
10832 (setq lastpos (point))
10833 (when (looking-at
10834 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
10835 (setq ltags (org-split-string
10836 (org-match-string-no-properties 1) ":"))
10837 (when parent
10838 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
10839 (setq tags (append
10840 (if parent
10841 (org-remove-uniherited-tags ltags)
10842 ltags)
10843 tags)))
10844 (or org-use-tag-inheritance (throw 'done t))
10845 (if local (throw 'done t))
10846 (or (org-up-heading-safe) (error nil))
10847 (setq parent t)))
10848 (error nil)))))
10849 (append (org-remove-uniherited-tags org-file-tags) tags)))))
10851 (defun org-add-prop-inherited (s)
10852 (add-text-properties 0 (length s) '(inherited t) s)
10855 (defun org-toggle-tag (tag &optional onoff)
10856 "Toggle the tag TAG for the current line.
10857 If ONOFF is `on' or `off', don't toggle but set to this state."
10858 (let (res current)
10859 (save-excursion
10860 (org-back-to-heading t)
10861 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
10862 (point-at-eol) t)
10863 (progn
10864 (setq current (match-string 1))
10865 (replace-match ""))
10866 (setq current ""))
10867 (setq current (nreverse (org-split-string current ":")))
10868 (cond
10869 ((eq onoff 'on)
10870 (setq res t)
10871 (or (member tag current) (push tag current)))
10872 ((eq onoff 'off)
10873 (or (not (member tag current)) (setq current (delete tag current))))
10874 (t (if (member tag current)
10875 (setq current (delete tag current))
10876 (setq res t)
10877 (push tag current))))
10878 (end-of-line 1)
10879 (if current
10880 (progn
10881 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
10882 (org-set-tags nil t))
10883 (delete-horizontal-space))
10884 (run-hooks 'org-after-tags-change-hook))
10885 res))
10887 (defun org-align-tags-here (to-col)
10888 ;; Assumes that this is a headline
10889 (let ((pos (point)) (col (current-column)) ncol tags-l p)
10890 (beginning-of-line 1)
10891 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10892 (< pos (match-beginning 2)))
10893 (progn
10894 (setq tags-l (- (match-end 2) (match-beginning 2)))
10895 (goto-char (match-beginning 1))
10896 (insert " ")
10897 (delete-region (point) (1+ (match-beginning 2)))
10898 (setq ncol (max (1+ (current-column))
10899 (1+ col)
10900 (if (> to-col 0)
10901 to-col
10902 (- (abs to-col) tags-l))))
10903 (setq p (point))
10904 (insert (make-string (- ncol (current-column)) ?\ ))
10905 (setq ncol (current-column))
10906 (when indent-tabs-mode (tabify p (point-at-eol)))
10907 (org-move-to-column (min ncol col) t))
10908 (goto-char pos))))
10910 (defun org-set-tags-command (&optional arg just-align)
10911 "Call the set-tags command for the current entry."
10912 (interactive "P")
10913 (if (org-on-heading-p)
10914 (org-set-tags arg just-align)
10915 (save-excursion
10916 (org-back-to-heading t)
10917 (org-set-tags arg just-align))))
10919 (defun org-set-tags (&optional arg just-align)
10920 "Set the tags for the current headline.
10921 With prefix ARG, realign all tags in headings in the current buffer."
10922 (interactive "P")
10923 (let* ((re (concat "^" outline-regexp))
10924 (current (org-get-tags-string))
10925 (col (current-column))
10926 (org-setting-tags t)
10927 table current-tags inherited-tags ; computed below when needed
10928 tags p0 c0 c1 rpl)
10929 (if arg
10930 (save-excursion
10931 (goto-char (point-min))
10932 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
10933 (while (re-search-forward re nil t)
10934 (org-set-tags nil t)
10935 (end-of-line 1)))
10936 (message "All tags realigned to column %d" org-tags-column))
10937 (if just-align
10938 (setq tags current)
10939 ;; Get a new set of tags from the user
10940 (save-excursion
10941 (setq table (append org-tag-persistent-alist
10942 (or org-tag-alist (org-get-buffer-tags)))
10943 org-last-tags-completion-table table
10944 current-tags (org-split-string current ":")
10945 inherited-tags (nreverse
10946 (nthcdr (length current-tags)
10947 (nreverse (org-get-tags-at))))
10948 tags
10949 (if (or (eq t org-use-fast-tag-selection)
10950 (and org-use-fast-tag-selection
10951 (delq nil (mapcar 'cdr table))))
10952 (org-fast-tag-selection
10953 current-tags inherited-tags table
10954 (if org-fast-tag-selection-include-todo org-todo-key-alist))
10955 (let ((org-add-colon-after-tag-completion t))
10956 (org-trim
10957 (org-without-partial-completion
10958 (org-ido-completing-read "Tags: " 'org-tags-completion-function
10959 nil nil current 'org-tags-history)))))))
10960 (while (string-match "[-+&]+" tags)
10961 ;; No boolean logic, just a list
10962 (setq tags (replace-match ":" t t tags))))
10964 (if (string-match "\\`[\t ]*\\'" tags)
10965 (setq tags "")
10966 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
10967 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
10969 ;; Insert new tags at the correct column
10970 (beginning-of-line 1)
10971 (cond
10972 ((and (equal current "") (equal tags "")))
10973 ((re-search-forward
10974 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10975 (point-at-eol) t)
10976 (if (equal tags "")
10977 (setq rpl "")
10978 (goto-char (match-beginning 0))
10979 (setq c0 (current-column) p0 (point)
10980 c1 (max (1+ c0) (if (> org-tags-column 0)
10981 org-tags-column
10982 (- (- org-tags-column) (length tags))))
10983 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10984 (replace-match rpl t t)
10985 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
10986 tags)
10987 (t (error "Tags alignment failed")))
10988 (org-move-to-column col)
10989 (unless just-align
10990 (run-hooks 'org-after-tags-change-hook)))))
10992 (defun org-change-tag-in-region (beg end tag off)
10993 "Add or remove TAG for each entry in the region.
10994 This works in the agenda, and also in an org-mode buffer."
10995 (interactive
10996 (list (region-beginning) (region-end)
10997 (let ((org-last-tags-completion-table
10998 (if (org-mode-p)
10999 (org-get-buffer-tags)
11000 (org-global-tags-completion-table))))
11001 (org-ido-completing-read
11002 "Tag: " 'org-tags-completion-function nil nil nil
11003 'org-tags-history))
11004 (progn
11005 (message "[s]et or [r]emove? ")
11006 (equal (read-char-exclusive) ?r))))
11007 (if (fboundp 'deactivate-mark) (deactivate-mark))
11008 (let ((agendap (equal major-mode 'org-agenda-mode))
11009 l1 l2 m buf pos newhead (cnt 0))
11010 (goto-char end)
11011 (setq l2 (1- (org-current-line)))
11012 (goto-char beg)
11013 (setq l1 (org-current-line))
11014 (loop for l from l1 to l2 do
11015 (goto-line l)
11016 (setq m (get-text-property (point) 'org-hd-marker))
11017 (when (or (and (org-mode-p) (org-on-heading-p))
11018 (and agendap m))
11019 (setq buf (if agendap (marker-buffer m) (current-buffer))
11020 pos (if agendap m (point)))
11021 (with-current-buffer buf
11022 (save-excursion
11023 (save-restriction
11024 (goto-char pos)
11025 (setq cnt (1+ cnt))
11026 (org-toggle-tag tag (if off 'off 'on))
11027 (setq newhead (org-get-heading)))))
11028 (and agendap (org-agenda-change-all-lines newhead m))))
11029 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
11031 (defun org-tags-completion-function (string predicate &optional flag)
11032 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
11033 (confirm (lambda (x) (stringp (car x)))))
11034 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
11035 (setq s1 (match-string 1 string)
11036 s2 (match-string 2 string))
11037 (setq s1 "" s2 string))
11038 (cond
11039 ((eq flag nil)
11040 ;; try completion
11041 (setq rtn (try-completion s2 ctable confirm))
11042 (if (stringp rtn)
11043 (setq rtn
11044 (concat s1 s2 (substring rtn (length s2))
11045 (if (and org-add-colon-after-tag-completion
11046 (assoc rtn ctable))
11047 ":" ""))))
11048 rtn)
11049 ((eq flag t)
11050 ;; all-completions
11051 (all-completions s2 ctable confirm)
11053 ((eq flag 'lambda)
11054 ;; exact match?
11055 (assoc s2 ctable)))
11058 (defun org-fast-tag-insert (kwd tags face &optional end)
11059 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
11060 (insert (format "%-12s" (concat kwd ":"))
11061 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
11062 (or end "")))
11064 (defun org-fast-tag-show-exit (flag)
11065 (save-excursion
11066 (goto-line 3)
11067 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
11068 (replace-match ""))
11069 (when flag
11070 (end-of-line 1)
11071 (org-move-to-column (- (window-width) 19) t)
11072 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
11074 (defun org-set-current-tags-overlay (current prefix)
11075 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
11076 (if (featurep 'xemacs)
11077 (org-overlay-display org-tags-overlay (concat prefix s)
11078 'secondary-selection)
11079 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
11080 (org-overlay-display org-tags-overlay (concat prefix s)))))
11082 (defun org-fast-tag-selection (current inherited table &optional todo-table)
11083 "Fast tag selection with single keys.
11084 CURRENT is the current list of tags in the headline, INHERITED is the
11085 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
11086 possibly with grouping information. TODO-TABLE is a similar table with
11087 TODO keywords, should these have keys assigned to them.
11088 If the keys are nil, a-z are automatically assigned.
11089 Returns the new tags string, or nil to not change the current settings."
11090 (let* ((fulltable (append table todo-table))
11091 (maxlen (apply 'max (mapcar
11092 (lambda (x)
11093 (if (stringp (car x)) (string-width (car x)) 0))
11094 fulltable)))
11095 (buf (current-buffer))
11096 (expert (eq org-fast-tag-selection-single-key 'expert))
11097 (buffer-tags nil)
11098 (fwidth (+ maxlen 3 1 3))
11099 (ncol (/ (- (window-width) 4) fwidth))
11100 (i-face 'org-done)
11101 (c-face 'org-todo)
11102 tg cnt e c char c1 c2 ntable tbl rtn
11103 ov-start ov-end ov-prefix
11104 (exit-after-next org-fast-tag-selection-single-key)
11105 (done-keywords org-done-keywords)
11106 groups ingroup)
11107 (save-excursion
11108 (beginning-of-line 1)
11109 (if (looking-at
11110 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11111 (setq ov-start (match-beginning 1)
11112 ov-end (match-end 1)
11113 ov-prefix "")
11114 (setq ov-start (1- (point-at-eol))
11115 ov-end (1+ ov-start))
11116 (skip-chars-forward "^\n\r")
11117 (setq ov-prefix
11118 (concat
11119 (buffer-substring (1- (point)) (point))
11120 (if (> (current-column) org-tags-column)
11122 (make-string (- org-tags-column (current-column)) ?\ ))))))
11123 (org-move-overlay org-tags-overlay ov-start ov-end)
11124 (save-window-excursion
11125 (if expert
11126 (set-buffer (get-buffer-create " *Org tags*"))
11127 (delete-other-windows)
11128 (split-window-vertically)
11129 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
11130 (erase-buffer)
11131 (org-set-local 'org-done-keywords done-keywords)
11132 (org-fast-tag-insert "Inherited" inherited i-face "\n")
11133 (org-fast-tag-insert "Current" current c-face "\n\n")
11134 (org-fast-tag-show-exit exit-after-next)
11135 (org-set-current-tags-overlay current ov-prefix)
11136 (setq tbl fulltable char ?a cnt 0)
11137 (while (setq e (pop tbl))
11138 (cond
11139 ((equal e '(:startgroup))
11140 (push '() groups) (setq ingroup t)
11141 (when (not (= cnt 0))
11142 (setq cnt 0)
11143 (insert "\n"))
11144 (insert "{ "))
11145 ((equal e '(:endgroup))
11146 (setq ingroup nil cnt 0)
11147 (insert "}\n"))
11148 ((equal e '(:newline))
11149 (when (not (= cnt 0))
11150 (setq cnt 0)
11151 (insert "\n")
11152 (setq e (car tbl))
11153 (while (equal (car tbl) '(:newline))
11154 (insert "\n")
11155 (setq tbl (cdr tbl)))))
11157 (setq tg (car e) c2 nil)
11158 (if (cdr e)
11159 (setq c (cdr e))
11160 ;; automatically assign a character.
11161 (setq c1 (string-to-char
11162 (downcase (substring
11163 tg (if (= (string-to-char tg) ?@) 1 0)))))
11164 (if (or (rassoc c1 ntable) (rassoc c1 table))
11165 (while (or (rassoc char ntable) (rassoc char table))
11166 (setq char (1+ char)))
11167 (setq c2 c1))
11168 (setq c (or c2 char)))
11169 (if ingroup (push tg (car groups)))
11170 (setq tg (org-add-props tg nil 'face
11171 (cond
11172 ((not (assoc tg table))
11173 (org-get-todo-face tg))
11174 ((member tg current) c-face)
11175 ((member tg inherited) i-face)
11176 (t nil))))
11177 (if (and (= cnt 0) (not ingroup)) (insert " "))
11178 (insert "[" c "] " tg (make-string
11179 (- fwidth 4 (length tg)) ?\ ))
11180 (push (cons tg c) ntable)
11181 (when (= (setq cnt (1+ cnt)) ncol)
11182 (insert "\n")
11183 (if ingroup (insert " "))
11184 (setq cnt 0)))))
11185 (setq ntable (nreverse ntable))
11186 (insert "\n")
11187 (goto-char (point-min))
11188 (if (not expert) (org-fit-window-to-buffer))
11189 (setq rtn
11190 (catch 'exit
11191 (while t
11192 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
11193 (if groups " [!] no groups" " [!]groups")
11194 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
11195 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11196 (cond
11197 ((= c ?\r) (throw 'exit t))
11198 ((= c ?!)
11199 (setq groups (not groups))
11200 (goto-char (point-min))
11201 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
11202 ((= c ?\C-c)
11203 (if (not expert)
11204 (org-fast-tag-show-exit
11205 (setq exit-after-next (not exit-after-next)))
11206 (setq expert nil)
11207 (delete-other-windows)
11208 (split-window-vertically)
11209 (org-switch-to-buffer-other-window " *Org tags*")
11210 (org-fit-window-to-buffer)))
11211 ((or (= c ?\C-g)
11212 (and (= c ?q) (not (rassoc c ntable))))
11213 (org-detach-overlay org-tags-overlay)
11214 (setq quit-flag t))
11215 ((= c ?\ )
11216 (setq current nil)
11217 (if exit-after-next (setq exit-after-next 'now)))
11218 ((= c ?\t)
11219 (condition-case nil
11220 (setq tg (org-ido-completing-read
11221 "Tag: "
11222 (or buffer-tags
11223 (with-current-buffer buf
11224 (org-get-buffer-tags)))))
11225 (quit (setq tg "")))
11226 (when (string-match "\\S-" tg)
11227 (add-to-list 'buffer-tags (list tg))
11228 (if (member tg current)
11229 (setq current (delete tg current))
11230 (push tg current)))
11231 (if exit-after-next (setq exit-after-next 'now)))
11232 ((setq e (rassoc c todo-table) tg (car e))
11233 (with-current-buffer buf
11234 (save-excursion (org-todo tg)))
11235 (if exit-after-next (setq exit-after-next 'now)))
11236 ((setq e (rassoc c ntable) tg (car e))
11237 (if (member tg current)
11238 (setq current (delete tg current))
11239 (loop for g in groups do
11240 (if (member tg g)
11241 (mapc (lambda (x)
11242 (setq current (delete x current)))
11243 g)))
11244 (push tg current))
11245 (if exit-after-next (setq exit-after-next 'now))))
11247 ;; Create a sorted list
11248 (setq current
11249 (sort current
11250 (lambda (a b)
11251 (assoc b (cdr (memq (assoc a ntable) ntable))))))
11252 (if (eq exit-after-next 'now) (throw 'exit t))
11253 (goto-char (point-min))
11254 (beginning-of-line 2)
11255 (delete-region (point) (point-at-eol))
11256 (org-fast-tag-insert "Current" current c-face)
11257 (org-set-current-tags-overlay current ov-prefix)
11258 (while (re-search-forward
11259 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
11260 (setq tg (match-string 1))
11261 (add-text-properties
11262 (match-beginning 1) (match-end 1)
11263 (list 'face
11264 (cond
11265 ((member tg current) c-face)
11266 ((member tg inherited) i-face)
11267 (t (get-text-property (match-beginning 1) 'face))))))
11268 (goto-char (point-min)))))
11269 (org-detach-overlay org-tags-overlay)
11270 (if rtn
11271 (mapconcat 'identity current ":")
11272 nil))))
11274 (defun org-get-tags-string ()
11275 "Get the TAGS string in the current headline."
11276 (unless (org-on-heading-p t)
11277 (error "Not on a heading"))
11278 (save-excursion
11279 (beginning-of-line 1)
11280 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11281 (org-match-string-no-properties 1)
11282 "")))
11284 (defun org-get-tags ()
11285 "Get the list of tags specified in the current headline."
11286 (org-split-string (org-get-tags-string) ":"))
11288 (defun org-get-buffer-tags ()
11289 "Get a table of all tags used in the buffer, for completion."
11290 (let (tags)
11291 (save-excursion
11292 (goto-char (point-min))
11293 (while (re-search-forward
11294 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
11295 (when (equal (char-after (point-at-bol 0)) ?*)
11296 (mapc (lambda (x) (add-to-list 'tags x))
11297 (org-split-string (org-match-string-no-properties 1) ":")))))
11298 (mapcar 'list tags)))
11300 ;;;; The mapping API
11302 ;;;###autoload
11303 (defun org-map-entries (func &optional match scope &rest skip)
11304 "Call FUNC at each headline selected by MATCH in SCOPE.
11306 FUNC is a function or a lisp form. The function will be called without
11307 arguments, with the cursor positioned at the beginning of the headline.
11308 The return values of all calls to the function will be collected and
11309 returned as a list.
11311 The call to FUNC will be wrapped into a save-excursion form, so FUNC
11312 does not need to preserve point. After evaluaton, the cursor will be
11313 moved to the end of the line (presumably of the headline of the
11314 processed entry) and search continues from there. Under some
11315 circumstances, this may not produce the wanted results. For example,
11316 if you have removed (e.g. archived) the current (sub)tree it could
11317 mean that the next entry will be skipped entirely. In such cases, you
11318 can specify the position from where search should continue by making
11319 FUNC set the variable `org-map-continue-from' to the desired buffer
11320 position.
11322 MATCH is a tags/property/todo match as it is used in the agenda tags view.
11323 Only headlines that are matched by this query will be considered during
11324 the iteration. When MATCH is nil or t, all headlines will be
11325 visited by the iteration.
11327 SCOPE determines the scope of this command. It can be any of:
11329 nil The current buffer, respecting the restriction if any
11330 tree The subtree started with the entry at point
11331 file The current buffer, without restriction
11332 file-with-archives
11333 The current buffer, and any archives associated with it
11334 agenda All agenda files
11335 agenda-with-archives
11336 All agenda files with any archive files associated with them
11337 \(file1 file2 ...)
11338 If this is a list, all files in the list will be scanned
11340 The remaining args are treated as settings for the skipping facilities of
11341 the scanner. The following items can be given here:
11343 archive skip trees with the archive tag.
11344 comment skip trees with the COMMENT keyword
11345 function or Emacs Lisp form:
11346 will be used as value for `org-agenda-skip-function', so whenever
11347 the the function returns t, FUNC will not be called for that
11348 entry and search will continue from the point where the
11349 function leaves it.
11351 If your function needs to retrieve the tags including inherited tags
11352 at the *current* entry, you can use the value of the variable
11353 `org-scanner-tags' which will be much faster than getting the value
11354 with `org-get-tags-at'. If your function gets properties with
11355 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
11356 to t around the call to `org-entry-properties' to get the same speedup.
11357 Note that if your function moves around to retrieve tags and properties at
11358 a *different* entry, you cannot use these techniques."
11359 (let* ((org-agenda-archives-mode nil) ; just to make sure
11360 (org-agenda-skip-archived-trees (memq 'archive skip))
11361 (org-agenda-skip-comment-trees (memq 'comment skip))
11362 (org-agenda-skip-function
11363 (car (org-delete-all '(comment archive) skip)))
11364 (org-tags-match-list-sublevels t)
11365 matcher file res
11366 org-todo-keywords-for-agenda
11367 org-done-keywords-for-agenda
11368 org-todo-keyword-alist-for-agenda
11369 org-tag-alist-for-agenda)
11371 (cond
11372 ((eq match t) (setq matcher t))
11373 ((eq match nil) (setq matcher t))
11374 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
11376 (save-excursion
11377 (save-restriction
11378 (when (eq scope 'tree)
11379 (org-back-to-heading t)
11380 (org-narrow-to-subtree)
11381 (setq scope nil))
11383 (if (not scope)
11384 (progn
11385 (org-prepare-agenda-buffers
11386 (list (buffer-file-name (current-buffer))))
11387 (setq res (org-scan-tags func matcher)))
11388 ;; Get the right scope
11389 (cond
11390 ((and scope (listp scope) (symbolp (car scope)))
11391 (setq scope (eval scope)))
11392 ((eq scope 'agenda)
11393 (setq scope (org-agenda-files t)))
11394 ((eq scope 'agenda-with-archives)
11395 (setq scope (org-agenda-files t))
11396 (setq scope (org-add-archive-files scope)))
11397 ((eq scope 'file)
11398 (setq scope (list (buffer-file-name))))
11399 ((eq scope 'file-with-archives)
11400 (setq scope (org-add-archive-files (list (buffer-file-name))))))
11401 (org-prepare-agenda-buffers scope)
11402 (while (setq file (pop scope))
11403 (with-current-buffer (org-find-base-buffer-visiting file)
11404 (save-excursion
11405 (save-restriction
11406 (widen)
11407 (goto-char (point-min))
11408 (setq res (append res (org-scan-tags func matcher))))))))))
11409 res))
11411 ;;;; Properties
11413 ;;; Setting and retrieving properties
11415 (defconst org-special-properties
11416 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
11417 "TIMESTAMP" "TIMESTAMP_IA")
11418 "The special properties valid in Org-mode.
11420 These are properties that are not defined in the property drawer,
11421 but in some other way.")
11423 (defconst org-default-properties
11424 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
11425 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
11426 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
11427 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
11428 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER")
11429 "Some properties that are used by Org-mode for various purposes.
11430 Being in this list makes sure that they are offered for completion.")
11432 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
11433 "Regular expression matching the first line of a property drawer.")
11435 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
11436 "Regular expression matching the first line of a property drawer.")
11438 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
11439 "Regular expression matching the first line of a property drawer.")
11441 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
11442 "Regular expression matching the first line of a property drawer.")
11444 (defconst org-property-drawer-re
11445 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
11446 org-property-end-re "\\)\n?")
11447 "Matches an entire property drawer.")
11449 (defconst org-clock-drawer-re
11450 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
11451 org-property-end-re "\\)\n?")
11452 "Matches an entire clock drawer.")
11454 (defun org-property-action ()
11455 "Do an action on properties."
11456 (interactive)
11457 (let (c)
11458 (org-at-property-p)
11459 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
11460 (setq c (read-char-exclusive))
11461 (cond
11462 ((equal c ?s)
11463 (call-interactively 'org-set-property))
11464 ((equal c ?d)
11465 (call-interactively 'org-delete-property))
11466 ((equal c ?D)
11467 (call-interactively 'org-delete-property-globally))
11468 ((equal c ?c)
11469 (call-interactively 'org-compute-property-at-point))
11470 (t (error "No such property action %c" c)))))
11472 (defun org-at-property-p ()
11473 "Is the cursor in a property line?"
11474 ;; FIXME: Does not check if we are actually in the drawer.
11475 ;; FIXME: also returns true on any drawers.....
11476 ;; This is used by C-c C-c for property action.
11477 (save-excursion
11478 (beginning-of-line 1)
11479 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
11481 (defun org-get-property-block (&optional beg end force)
11482 "Return the (beg . end) range of the body of the property drawer.
11483 BEG and END can be beginning and end of subtree, if not given
11484 they will be found.
11485 If the drawer does not exist and FORCE is non-nil, create the drawer."
11486 (catch 'exit
11487 (save-excursion
11488 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
11489 (end (or end (progn (outline-next-heading) (point)))))
11490 (goto-char beg)
11491 (if (re-search-forward org-property-start-re end t)
11492 (setq beg (1+ (match-end 0)))
11493 (if force
11494 (save-excursion
11495 (org-insert-property-drawer)
11496 (setq end (progn (outline-next-heading) (point))))
11497 (throw 'exit nil))
11498 (goto-char beg)
11499 (if (re-search-forward org-property-start-re end t)
11500 (setq beg (1+ (match-end 0)))))
11501 (if (re-search-forward org-property-end-re end t)
11502 (setq end (match-beginning 0))
11503 (or force (throw 'exit nil))
11504 (goto-char beg)
11505 (setq end beg)
11506 (org-indent-line-function)
11507 (insert ":END:\n"))
11508 (cons beg end)))))
11510 (defun org-entry-properties (&optional pom which)
11511 "Get all properties of the entry at point-or-marker POM.
11512 This includes the TODO keyword, the tags, time strings for deadline,
11513 scheduled, and clocking, and any additional properties defined in the
11514 entry. The return value is an alist, keys may occur multiple times
11515 if the property key was used several times.
11516 POM may also be nil, in which case the current entry is used.
11517 If WHICH is nil or `all', get all properties. If WHICH is
11518 `special' or `standard', only get that subclass."
11519 (setq which (or which 'all))
11520 (org-with-point-at pom
11521 (let ((clockstr (substring org-clock-string 0 -1))
11522 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
11523 beg end range props sum-props key value string clocksum)
11524 (save-excursion
11525 (when (condition-case nil
11526 (and (org-mode-p) (org-back-to-heading t))
11527 (error nil))
11528 (setq beg (point))
11529 (setq sum-props (get-text-property (point) 'org-summaries))
11530 (setq clocksum (get-text-property (point) :org-clock-minutes))
11531 (outline-next-heading)
11532 (setq end (point))
11533 (when (memq which '(all special))
11534 ;; Get the special properties, like TODO and tags
11535 (goto-char beg)
11536 (when (and (looking-at org-todo-line-regexp) (match-end 2))
11537 (push (cons "TODO" (org-match-string-no-properties 2)) props))
11538 (when (looking-at org-priority-regexp)
11539 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
11540 (when (and (setq value (org-get-tags-string))
11541 (string-match "\\S-" value))
11542 (push (cons "TAGS" value) props))
11543 (when (setq value (org-get-tags-at))
11544 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
11545 props))
11546 (while (re-search-forward org-maybe-keyword-time-regexp end t)
11547 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
11548 string (if (equal key clockstr)
11549 (org-no-properties
11550 (org-trim
11551 (buffer-substring
11552 (match-beginning 3) (goto-char (point-at-eol)))))
11553 (substring (org-match-string-no-properties 3) 1 -1)))
11554 (unless key
11555 (if (= (char-after (match-beginning 3)) ?\[)
11556 (setq key "TIMESTAMP_IA")
11557 (setq key "TIMESTAMP")))
11558 (when (or (equal key clockstr) (not (assoc key props)))
11559 (push (cons key string) props)))
11563 (when (memq which '(all standard))
11564 ;; Get the standard properties, like :PROP: ...
11565 (setq range (org-get-property-block beg end))
11566 (when range
11567 (goto-char (car range))
11568 (while (re-search-forward
11569 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
11570 (cdr range) t)
11571 (setq key (org-match-string-no-properties 1)
11572 value (org-trim (or (org-match-string-no-properties 2) "")))
11573 (unless (member key excluded)
11574 (push (cons key (or value "")) props)))))
11575 (if clocksum
11576 (push (cons "CLOCKSUM"
11577 (org-columns-number-to-string (/ (float clocksum) 60.)
11578 'add_times))
11579 props))
11580 (unless (assoc "CATEGORY" props)
11581 (setq value (or (org-get-category)
11582 (progn (org-refresh-category-properties)
11583 (org-get-category))))
11584 (push (cons "CATEGORY" value) props))
11585 (append sum-props (nreverse props)))))))
11587 (defun org-entry-get (pom property &optional inherit)
11588 "Get value of PROPERTY for entry at point-or-marker POM.
11589 If INHERIT is non-nil and the entry does not have the property,
11590 then also check higher levels of the hierarchy.
11591 If INHERIT is the symbol `selective', use inheritance only if the setting
11592 in `org-use-property-inheritance' selects PROPERTY for inheritance.
11593 If the property is present but empty, the return value is the empty string.
11594 If the property is not present at all, nil is returned."
11595 (org-with-point-at pom
11596 (if (and inherit (if (eq inherit 'selective)
11597 (org-property-inherit-p property)
11599 (org-entry-get-with-inheritance property)
11600 (if (member property org-special-properties)
11601 ;; We need a special property. Use brute force, get all properties.
11602 (cdr (assoc property (org-entry-properties nil 'special)))
11603 (let ((range (org-get-property-block)))
11604 (if (and range
11605 (goto-char (car range))
11606 (re-search-forward
11607 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
11608 (cdr range) t))
11609 ;; Found the property, return it.
11610 (if (match-end 1)
11611 (org-match-string-no-properties 1)
11612 "")))))))
11614 (defun org-property-or-variable-value (var &optional inherit)
11615 "Check if there is a property fixing the value of VAR.
11616 If yes, return this value. If not, return the current value of the variable."
11617 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
11618 (if (and prop (stringp prop) (string-match "\\S-" prop))
11619 (read prop)
11620 (symbol-value var))))
11622 (defun org-entry-delete (pom property)
11623 "Delete the property PROPERTY from entry at point-or-marker POM."
11624 (org-with-point-at pom
11625 (if (member property org-special-properties)
11626 nil ; cannot delete these properties.
11627 (let ((range (org-get-property-block)))
11628 (if (and range
11629 (goto-char (car range))
11630 (re-search-forward
11631 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
11632 (cdr range) t))
11633 (progn
11634 (delete-region (match-beginning 0) (1+ (point-at-eol)))
11636 nil)))))
11638 ;; Multi-values properties are properties that contain multiple values
11639 ;; These values are assumed to be single words, separated by whitespace.
11640 (defun org-entry-add-to-multivalued-property (pom property value)
11641 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
11642 (let* ((old (org-entry-get pom property))
11643 (values (and old (org-split-string old "[ \t]"))))
11644 (setq value (org-entry-protect-space value))
11645 (unless (member value values)
11646 (setq values (cons value values))
11647 (org-entry-put pom property
11648 (mapconcat 'identity values " ")))))
11650 (defun org-entry-remove-from-multivalued-property (pom property value)
11651 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
11652 (let* ((old (org-entry-get pom property))
11653 (values (and old (org-split-string old "[ \t]"))))
11654 (setq value (org-entry-protect-space value))
11655 (when (member value values)
11656 (setq values (delete value values))
11657 (org-entry-put pom property
11658 (mapconcat 'identity values " ")))))
11660 (defun org-entry-member-in-multivalued-property (pom property value)
11661 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
11662 (let* ((old (org-entry-get pom property))
11663 (values (and old (org-split-string old "[ \t]"))))
11664 (setq value (org-entry-protect-space value))
11665 (member value values)))
11667 (defun org-entry-get-multivalued-property (pom property)
11668 "Return a list of values in a multivalued property."
11669 (let* ((value (org-entry-get pom property))
11670 (values (and value (org-split-string value "[ \t]"))))
11671 (mapcar 'org-entry-restore-space values)))
11673 (defun org-entry-put-multivalued-property (pom property &rest values)
11674 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
11675 VALUES should be a list of strings. Spaces will be protected."
11676 (org-entry-put pom property
11677 (mapconcat 'org-entry-protect-space values " "))
11678 (let* ((value (org-entry-get pom property))
11679 (values (and value (org-split-string value "[ \t]"))))
11680 (mapcar 'org-entry-restore-space values)))
11682 (defun org-entry-protect-space (s)
11683 "Protect spaces and newline in string S."
11684 (while (string-match " " s)
11685 (setq s (replace-match "%20" t t s)))
11686 (while (string-match "\n" s)
11687 (setq s (replace-match "%0A" t t s)))
11690 (defun org-entry-restore-space (s)
11691 "Restore spaces and newline in string S."
11692 (while (string-match "%20" s)
11693 (setq s (replace-match " " t t s)))
11694 (while (string-match "%0A" s)
11695 (setq s (replace-match "\n" t t s)))
11698 (defvar org-entry-property-inherited-from (make-marker)
11699 "Marker pointing to the entry from where a property was inherited.
11700 Each call to `org-entry-get-with-inheritance' will set this marker to the
11701 location of the entry where the inheritance search matched. If there was
11702 no match, the marker will point nowhere.
11703 Note that also `org-entry-get' calls this function, if the INHERIT flag
11704 is set.")
11706 (defun org-entry-get-with-inheritance (property)
11707 "Get entry property, and search higher levels if not present."
11708 (move-marker org-entry-property-inherited-from nil)
11709 (let (tmp)
11710 (save-excursion
11711 (save-restriction
11712 (widen)
11713 (catch 'ex
11714 (while t
11715 (when (setq tmp (org-entry-get nil property))
11716 (org-back-to-heading t)
11717 (move-marker org-entry-property-inherited-from (point))
11718 (throw 'ex tmp))
11719 (or (org-up-heading-safe) (throw 'ex nil)))))
11720 (or tmp
11721 (cdr (assoc property org-file-properties))
11722 (cdr (assoc property org-global-properties))
11723 (cdr (assoc property org-global-properties-fixed))))))
11725 (defun org-entry-put (pom property value)
11726 "Set PROPERTY to VALUE for entry at point-or-marker POM."
11727 (org-with-point-at pom
11728 (org-back-to-heading t)
11729 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
11730 range)
11731 (cond
11732 ((equal property "TODO")
11733 (when (and (stringp value) (string-match "\\S-" value)
11734 (not (member value org-todo-keywords-1)))
11735 (error "\"%s\" is not a valid TODO state" value))
11736 (if (or (not value)
11737 (not (string-match "\\S-" value)))
11738 (setq value 'none))
11739 (org-todo value)
11740 (org-set-tags nil 'align))
11741 ((equal property "PRIORITY")
11742 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
11743 (string-to-char value) ?\ ))
11744 (org-set-tags nil 'align))
11745 ((equal property "SCHEDULED")
11746 (if (re-search-forward org-scheduled-time-regexp end t)
11747 (cond
11748 ((eq value 'earlier) (org-timestamp-change -1 'day))
11749 ((eq value 'later) (org-timestamp-change 1 'day))
11750 (t (call-interactively 'org-schedule)))
11751 (call-interactively 'org-schedule)))
11752 ((equal property "DEADLINE")
11753 (if (re-search-forward org-deadline-time-regexp end t)
11754 (cond
11755 ((eq value 'earlier) (org-timestamp-change -1 'day))
11756 ((eq value 'later) (org-timestamp-change 1 'day))
11757 (t (call-interactively 'org-deadline)))
11758 (call-interactively 'org-deadline)))
11759 ((member property org-special-properties)
11760 (error "The %s property can not yet be set with `org-entry-put'"
11761 property))
11762 (t ; a non-special property
11763 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
11764 (setq range (org-get-property-block beg end 'force))
11765 (goto-char (car range))
11766 (if (re-search-forward
11767 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
11768 (progn
11769 (delete-region (match-beginning 1) (match-end 1))
11770 (goto-char (match-beginning 1)))
11771 (goto-char (cdr range))
11772 (insert "\n")
11773 (backward-char 1)
11774 (org-indent-line-function)
11775 (insert ":" property ":"))
11776 (and value (insert " " value))
11777 (org-indent-line-function)))))))
11779 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
11780 "Get all property keys in the current buffer.
11781 With INCLUDE-SPECIALS, also list the special properties that reflect things
11782 like tags and TODO state.
11783 With INCLUDE-DEFAULTS, also include properties that has special meaning
11784 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
11785 With INCLUDE-COLUMNS, also include property names given in COLUMN
11786 formats in the current buffer."
11787 (let (rtn range cfmt s p)
11788 (save-excursion
11789 (save-restriction
11790 (widen)
11791 (goto-char (point-min))
11792 (while (re-search-forward org-property-start-re nil t)
11793 (setq range (org-get-property-block))
11794 (goto-char (car range))
11795 (while (re-search-forward
11796 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
11797 (cdr range) t)
11798 (add-to-list 'rtn (org-match-string-no-properties 1)))
11799 (outline-next-heading))))
11801 (when include-specials
11802 (setq rtn (append org-special-properties rtn)))
11804 (when include-defaults
11805 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
11807 (when include-columns
11808 (save-excursion
11809 (save-restriction
11810 (widen)
11811 (goto-char (point-min))
11812 (while (re-search-forward
11813 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
11814 nil t)
11815 (setq cfmt (match-string 2) s 0)
11816 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
11817 cfmt s)
11818 (setq s (match-end 0)
11819 p (match-string 1 cfmt))
11820 (unless (or (equal p "ITEM")
11821 (member p org-special-properties))
11822 (add-to-list 'rtn (match-string 1 cfmt))))))))
11824 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
11826 (defun org-property-values (key)
11827 "Return a list of all values of property KEY."
11828 (save-excursion
11829 (save-restriction
11830 (widen)
11831 (goto-char (point-min))
11832 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
11833 values)
11834 (while (re-search-forward re nil t)
11835 (add-to-list 'values (org-trim (match-string 1))))
11836 (delete "" values)))))
11838 (defun org-insert-property-drawer ()
11839 "Insert a property drawer into the current entry."
11840 (interactive)
11841 (org-back-to-heading t)
11842 (looking-at outline-regexp)
11843 (let ((indent (- (match-end 0)(match-beginning 0)))
11844 (beg (point))
11845 (re (concat "^[ \t]*" org-keyword-time-regexp))
11846 end hiddenp)
11847 (outline-next-heading)
11848 (setq end (point))
11849 (goto-char beg)
11850 (while (re-search-forward re end t))
11851 (setq hiddenp (org-invisible-p))
11852 (end-of-line 1)
11853 (and (equal (char-after) ?\n) (forward-char 1))
11854 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
11855 (if (member (match-string 1) '("CLOCK:" ":END:"))
11856 ;; just skip this line
11857 (beginning-of-line 2)
11858 ;; Drawer start, find the end
11859 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
11860 (beginning-of-line 1)))
11861 (org-skip-over-state-notes)
11862 (skip-chars-backward " \t\n\r")
11863 (if (eq (char-before) ?*) (forward-char 1))
11864 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
11865 (beginning-of-line 0)
11866 (org-indent-to-column indent)
11867 (beginning-of-line 2)
11868 (org-indent-to-column indent)
11869 (beginning-of-line 0)
11870 (if hiddenp
11871 (save-excursion
11872 (org-back-to-heading t)
11873 (hide-entry))
11874 (org-flag-drawer t))))
11876 (defun org-set-property (property value)
11877 "In the current entry, set PROPERTY to VALUE.
11878 When called interactively, this will prompt for a property name, offering
11879 completion on existing and default properties. And then it will prompt
11880 for a value, offering completion either on allowed values (via an inherited
11881 xxx_ALL property) or on existing values in other instances of this property
11882 in the current file."
11883 (interactive
11884 (let* ((completion-ignore-case t)
11885 (keys (org-buffer-property-keys nil t t))
11886 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
11887 (prop (if (member prop0 keys)
11888 prop0
11889 (or (cdr (assoc (downcase prop0)
11890 (mapcar (lambda (x) (cons (downcase x) x))
11891 keys)))
11892 prop0)))
11893 (cur (org-entry-get nil prop))
11894 (allowed (org-property-get-allowed-values nil prop 'table))
11895 (existing (mapcar 'list (org-property-values prop)))
11896 (val (if allowed
11897 (org-completing-read "Value: " allowed nil 'req-match)
11898 (let (org-completion-use-ido)
11899 (org-completing-read
11900 (concat "Value" (if (and cur (string-match "\\S-" cur))
11901 (concat "[" cur "]") "")
11902 ": ")
11903 existing nil nil "" nil cur)))))
11904 (list prop (if (equal val "") cur val))))
11905 (unless (equal (org-entry-get nil property) value)
11906 (org-entry-put nil property value)))
11908 (defun org-delete-property (property)
11909 "In the current entry, delete PROPERTY."
11910 (interactive
11911 (let* ((completion-ignore-case t)
11912 (prop (org-ido-completing-read
11913 "Property: " (org-entry-properties nil 'standard))))
11914 (list prop)))
11915 (message "Property %s %s" property
11916 (if (org-entry-delete nil property)
11917 "deleted"
11918 "was not present in the entry")))
11920 (defun org-delete-property-globally (property)
11921 "Remove PROPERTY globally, from all entries."
11922 (interactive
11923 (let* ((completion-ignore-case t)
11924 (prop (org-ido-completing-read
11925 "Globally remove property: "
11926 (mapcar 'list (org-buffer-property-keys)))))
11927 (list prop)))
11928 (save-excursion
11929 (save-restriction
11930 (widen)
11931 (goto-char (point-min))
11932 (let ((cnt 0))
11933 (while (re-search-forward
11934 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
11935 nil t)
11936 (setq cnt (1+ cnt))
11937 (replace-match ""))
11938 (message "Property \"%s\" removed from %d entries" property cnt)))))
11940 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
11942 (defun org-compute-property-at-point ()
11943 "Compute the property at point.
11944 This looks for an enclosing column format, extracts the operator and
11945 then applies it to the property in the column format's scope."
11946 (interactive)
11947 (unless (org-at-property-p)
11948 (error "Not at a property"))
11949 (let ((prop (org-match-string-no-properties 2)))
11950 (org-columns-get-format-and-top-level)
11951 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
11952 (error "No operator defined for property %s" prop))
11953 (org-columns-compute prop)))
11955 (defun org-property-get-allowed-values (pom property &optional table)
11956 "Get allowed values for the property PROPERTY.
11957 When TABLE is non-nil, return an alist that can directly be used for
11958 completion."
11959 (let (vals)
11960 (cond
11961 ((equal property "TODO")
11962 (setq vals (org-with-point-at pom
11963 (append org-todo-keywords-1 '("")))))
11964 ((equal property "PRIORITY")
11965 (let ((n org-lowest-priority))
11966 (while (>= n org-highest-priority)
11967 (push (char-to-string n) vals)
11968 (setq n (1- n)))))
11969 ((member property org-special-properties))
11971 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
11973 (when (and vals (string-match "\\S-" vals))
11974 (setq vals (car (read-from-string (concat "(" vals ")"))))
11975 (setq vals (mapcar (lambda (x)
11976 (cond ((stringp x) x)
11977 ((numberp x) (number-to-string x))
11978 ((symbolp x) (symbol-name x))
11979 (t "???")))
11980 vals)))))
11981 (if table (mapcar 'list vals) vals)))
11983 (defun org-property-previous-allowed-value (&optional previous)
11984 "Switch to the next allowed value for this property."
11985 (interactive)
11986 (org-property-next-allowed-value t))
11988 (defun org-property-next-allowed-value (&optional previous)
11989 "Switch to the next allowed value for this property."
11990 (interactive)
11991 (unless (org-at-property-p)
11992 (error "Not at a property"))
11993 (let* ((key (match-string 2))
11994 (value (match-string 3))
11995 (allowed (or (org-property-get-allowed-values (point) key)
11996 (and (member value '("[ ]" "[-]" "[X]"))
11997 '("[ ]" "[X]"))))
11998 nval)
11999 (unless allowed
12000 (error "Allowed values for this property have not been defined"))
12001 (if previous (setq allowed (reverse allowed)))
12002 (if (member value allowed)
12003 (setq nval (car (cdr (member value allowed)))))
12004 (setq nval (or nval (car allowed)))
12005 (if (equal nval value)
12006 (error "Only one allowed value for this property"))
12007 (org-at-property-p)
12008 (replace-match (concat " :" key ": " nval) t t)
12009 (org-indent-line-function)
12010 (beginning-of-line 1)
12011 (skip-chars-forward " \t")))
12013 (defun org-find-entry-with-id (ident)
12014 "Locate the entry that contains the ID property with exact value IDENT.
12015 IDENT can be a string, a symbol or a number, this function will search for
12016 the string representation of it.
12017 Return the position where this entry starts, or nil if there is no such entry."
12018 (interactive "sID: ")
12019 (let ((id (cond
12020 ((stringp ident) ident)
12021 ((symbol-name ident) (symbol-name ident))
12022 ((numberp ident) (number-to-string ident))
12023 (t (error "IDENT %s must be a string, symbol or number" ident))))
12024 (case-fold-search nil))
12025 (save-excursion
12026 (save-restriction
12027 (widen)
12028 (goto-char (point-min))
12029 (when (re-search-forward
12030 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
12031 nil t)
12032 (org-back-to-heading)
12033 (point))))))
12035 ;;;; Timestamps
12037 (defvar org-last-changed-timestamp nil)
12038 (defvar org-last-inserted-timestamp nil
12039 "The last time stamp inserted with `org-insert-time-stamp'.")
12040 (defvar org-time-was-given) ; dynamically scoped parameter
12041 (defvar org-end-time-was-given) ; dynamically scoped parameter
12042 (defvar org-ts-what) ; dynamically scoped parameter
12044 (defun org-time-stamp (arg &optional inactive)
12045 "Prompt for a date/time and insert a time stamp.
12046 If the user specifies a time like HH:MM, or if this command is called
12047 with a prefix argument, the time stamp will contain date and time.
12048 Otherwise, only the date will be included. All parts of a date not
12049 specified by the user will be filled in from the current date/time.
12050 So if you press just return without typing anything, the time stamp
12051 will represent the current date/time. If there is already a timestamp
12052 at the cursor, it will be modified."
12053 (interactive "P")
12054 (let* ((ts nil)
12055 (default-time
12056 ;; Default time is either today, or, when entering a range,
12057 ;; the range start.
12058 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
12059 (save-excursion
12060 (re-search-backward
12061 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
12062 (- (point) 20) t)))
12063 (apply 'encode-time (org-parse-time-string (match-string 1)))
12064 (current-time)))
12065 (default-input (and ts (org-get-compact-tod ts)))
12066 org-time-was-given org-end-time-was-given time)
12067 (cond
12068 ((and (org-at-timestamp-p t)
12069 (memq last-command '(org-time-stamp org-time-stamp-inactive))
12070 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
12071 (insert "--")
12072 (setq time (let ((this-command this-command))
12073 (org-read-date arg 'totime nil nil
12074 default-time default-input)))
12075 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
12076 ((org-at-timestamp-p t)
12077 (setq time (let ((this-command this-command))
12078 (org-read-date arg 'totime nil nil default-time default-input)))
12079 (when (org-at-timestamp-p t) ; just to get the match data
12080 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
12081 (replace-match "")
12082 (setq org-last-changed-timestamp
12083 (org-insert-time-stamp
12084 time (or org-time-was-given arg)
12085 inactive nil nil (list org-end-time-was-given))))
12086 (message "Timestamp updated"))
12088 (setq time (let ((this-command this-command))
12089 (org-read-date arg 'totime nil nil default-time default-input)))
12090 (org-insert-time-stamp time (or org-time-was-given arg) inactive
12091 nil nil (list org-end-time-was-given))))))
12093 ;; FIXME: can we use this for something else, like computing time differences?
12094 (defun org-get-compact-tod (s)
12095 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
12096 (let* ((t1 (match-string 1 s))
12097 (h1 (string-to-number (match-string 2 s)))
12098 (m1 (string-to-number (match-string 3 s)))
12099 (t2 (and (match-end 4) (match-string 5 s)))
12100 (h2 (and t2 (string-to-number (match-string 6 s))))
12101 (m2 (and t2 (string-to-number (match-string 7 s))))
12102 dh dm)
12103 (if (not t2)
12105 (setq dh (- h2 h1) dm (- m2 m1))
12106 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
12107 (concat t1 "+" (number-to-string dh)
12108 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
12110 (defun org-time-stamp-inactive (&optional arg)
12111 "Insert an inactive time stamp.
12112 An inactive time stamp is enclosed in square brackets instead of angle
12113 brackets. It is inactive in the sense that it does not trigger agenda entries,
12114 does not link to the calendar and cannot be changed with the S-cursor keys.
12115 So these are more for recording a certain time/date."
12116 (interactive "P")
12117 (org-time-stamp arg 'inactive))
12119 (defvar org-date-ovl (org-make-overlay 1 1))
12120 (org-overlay-put org-date-ovl 'face 'org-warning)
12121 (org-detach-overlay org-date-ovl)
12123 (defvar org-ans1) ; dynamically scoped parameter
12124 (defvar org-ans2) ; dynamically scoped parameter
12126 (defvar org-plain-time-of-day-regexp) ; defined below
12128 (defvar org-overriding-default-time nil) ; dynamically scoped
12129 (defvar org-read-date-overlay nil)
12130 (defvar org-dcst nil) ; dynamically scoped
12131 (defvar org-read-date-history nil)
12133 (defun org-read-date (&optional with-time to-time from-string prompt
12134 default-time default-input)
12135 "Read a date, possibly a time, and make things smooth for the user.
12136 The prompt will suggest to enter an ISO date, but you can also enter anything
12137 which will at least partially be understood by `parse-time-string'.
12138 Unrecognized parts of the date will default to the current day, month, year,
12139 hour and minute. If this command is called to replace a timestamp at point,
12140 of to enter the second timestamp of a range, the default time is taken from the
12141 existing stamp. For example,
12142 3-2-5 --> 2003-02-05
12143 feb 15 --> currentyear-02-15
12144 sep 12 9 --> 2009-09-12
12145 12:45 --> today 12:45
12146 22 sept 0:34 --> currentyear-09-22 0:34
12147 12 --> currentyear-currentmonth-12
12148 Fri --> nearest Friday (today or later)
12149 etc.
12151 Furthermore you can specify a relative date by giving, as the *first* thing
12152 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
12153 change in days weeks, months, years.
12154 With a single plus or minus, the date is relative to today. With a double
12155 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
12156 +4d --> four days from today
12157 +4 --> same as above
12158 +2w --> two weeks from today
12159 ++5 --> five days from default date
12161 The function understands only English month and weekday abbreviations,
12162 but this can be configured with the variables `parse-time-months' and
12163 `parse-time-weekdays'.
12165 While prompting, a calendar is popped up - you can also select the
12166 date with the mouse (button 1). The calendar shows a period of three
12167 months. To scroll it to other months, use the keys `>' and `<'.
12168 If you don't like the calendar, turn it off with
12169 \(setq org-read-date-popup-calendar nil)
12171 With optional argument TO-TIME, the date will immediately be converted
12172 to an internal time.
12173 With an optional argument WITH-TIME, the prompt will suggest to also
12174 insert a time. Note that when WITH-TIME is not set, you can still
12175 enter a time, and this function will inform the calling routine about
12176 this change. The calling routine may then choose to change the format
12177 used to insert the time stamp into the buffer to include the time.
12178 With optional argument FROM-STRING, read from this string instead from
12179 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
12180 the time/date that is used for everything that is not specified by the
12181 user."
12182 (require 'parse-time)
12183 (let* ((org-time-stamp-rounding-minutes
12184 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
12185 (org-dcst org-display-custom-times)
12186 (ct (org-current-time))
12187 (def (or org-overriding-default-time default-time ct))
12188 (defdecode (decode-time def))
12189 (dummy (progn
12190 (when (< (nth 2 defdecode) org-extend-today-until)
12191 (setcar (nthcdr 2 defdecode) -1)
12192 (setcar (nthcdr 1 defdecode) 59)
12193 (setq def (apply 'encode-time defdecode)
12194 defdecode (decode-time def)))))
12195 (calendar-move-hook nil)
12196 (calendar-view-diary-initially-flag nil)
12197 (view-diary-entries-initially nil)
12198 (calendar-view-holidays-initially-flag nil)
12199 (view-calendar-holidays-initially nil)
12200 (timestr (format-time-string
12201 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
12202 (prompt (concat (if prompt (concat prompt " ") "")
12203 (format "Date+time [%s]: " timestr)))
12204 ans (org-ans0 "") org-ans1 org-ans2 final)
12206 (cond
12207 (from-string (setq ans from-string))
12208 (org-read-date-popup-calendar
12209 (save-excursion
12210 (save-window-excursion
12211 (calendar)
12212 (calendar-forward-day (- (time-to-days def)
12213 (calendar-absolute-from-gregorian
12214 (calendar-current-date))))
12215 (org-eval-in-calendar nil t)
12216 (let* ((old-map (current-local-map))
12217 (map (copy-keymap calendar-mode-map))
12218 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12219 (org-defkey map (kbd "RET") 'org-calendar-select)
12220 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
12221 'org-calendar-select-mouse)
12222 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
12223 'org-calendar-select-mouse)
12224 (org-defkey minibuffer-local-map [(meta shift left)]
12225 (lambda () (interactive)
12226 (org-eval-in-calendar '(calendar-backward-month 1))))
12227 (org-defkey minibuffer-local-map [(meta shift right)]
12228 (lambda () (interactive)
12229 (org-eval-in-calendar '(calendar-forward-month 1))))
12230 (org-defkey minibuffer-local-map [(meta shift up)]
12231 (lambda () (interactive)
12232 (org-eval-in-calendar '(calendar-backward-year 1))))
12233 (org-defkey minibuffer-local-map [(meta shift down)]
12234 (lambda () (interactive)
12235 (org-eval-in-calendar '(calendar-forward-year 1))))
12236 (org-defkey minibuffer-local-map [(shift up)]
12237 (lambda () (interactive)
12238 (org-eval-in-calendar '(calendar-backward-week 1))))
12239 (org-defkey minibuffer-local-map [(shift down)]
12240 (lambda () (interactive)
12241 (org-eval-in-calendar '(calendar-forward-week 1))))
12242 (org-defkey minibuffer-local-map [(shift left)]
12243 (lambda () (interactive)
12244 (org-eval-in-calendar '(calendar-backward-day 1))))
12245 (org-defkey minibuffer-local-map [(shift right)]
12246 (lambda () (interactive)
12247 (org-eval-in-calendar '(calendar-forward-day 1))))
12248 (org-defkey minibuffer-local-map ">"
12249 (lambda () (interactive)
12250 (org-eval-in-calendar '(scroll-calendar-left 1))))
12251 (org-defkey minibuffer-local-map "<"
12252 (lambda () (interactive)
12253 (org-eval-in-calendar '(scroll-calendar-right 1))))
12254 (run-hooks 'org-read-date-minibuffer-setup-hook)
12255 (unwind-protect
12256 (progn
12257 (use-local-map map)
12258 (add-hook 'post-command-hook 'org-read-date-display)
12259 (setq org-ans0 (read-string prompt default-input
12260 'org-read-date-history nil))
12261 ;; org-ans0: from prompt
12262 ;; org-ans1: from mouse click
12263 ;; org-ans2: from calendar motion
12264 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
12265 (remove-hook 'post-command-hook 'org-read-date-display)
12266 (use-local-map old-map)
12267 (when org-read-date-overlay
12268 (org-delete-overlay org-read-date-overlay)
12269 (setq org-read-date-overlay nil)))))))
12271 (t ; Naked prompt only
12272 (unwind-protect
12273 (setq ans (read-string prompt default-input
12274 'org-read-date-history timestr))
12275 (when org-read-date-overlay
12276 (org-delete-overlay org-read-date-overlay)
12277 (setq org-read-date-overlay nil)))))
12279 (setq final (org-read-date-analyze ans def defdecode))
12281 (if to-time
12282 (apply 'encode-time final)
12283 (if (and (boundp 'org-time-was-given) org-time-was-given)
12284 (format "%04d-%02d-%02d %02d:%02d"
12285 (nth 5 final) (nth 4 final) (nth 3 final)
12286 (nth 2 final) (nth 1 final))
12287 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
12288 (defvar def)
12289 (defvar defdecode)
12290 (defvar with-time)
12291 (defun org-read-date-display ()
12292 "Display the current date prompt interpretation in the minibuffer."
12293 (when org-read-date-display-live
12294 (when org-read-date-overlay
12295 (org-delete-overlay org-read-date-overlay))
12296 (let ((p (point)))
12297 (end-of-line 1)
12298 (while (not (equal (buffer-substring
12299 (max (point-min) (- (point) 4)) (point))
12300 " "))
12301 (insert " "))
12302 (goto-char p))
12303 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
12304 " " (or org-ans1 org-ans2)))
12305 (org-end-time-was-given nil)
12306 (f (org-read-date-analyze ans def defdecode))
12307 (fmts (if org-dcst
12308 org-time-stamp-custom-formats
12309 org-time-stamp-formats))
12310 (fmt (if (or with-time
12311 (and (boundp 'org-time-was-given) org-time-was-given))
12312 (cdr fmts)
12313 (car fmts)))
12314 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
12315 (when (and org-end-time-was-given
12316 (string-match org-plain-time-of-day-regexp txt))
12317 (setq txt (concat (substring txt 0 (match-end 0)) "-"
12318 org-end-time-was-given
12319 (substring txt (match-end 0)))))
12320 (setq org-read-date-overlay
12321 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
12322 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
12324 (defun org-read-date-analyze (ans def defdecode)
12325 "Analyse the combined answer of the date prompt."
12326 ;; FIXME: cleanup and comment
12327 (let (delta deltan deltaw deltadef year month day
12328 hour minute second wday pm h2 m2 tl wday1
12329 iso-year iso-weekday iso-week iso-year iso-date)
12331 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
12332 (setq ans "+0"))
12334 (when (setq delta (org-read-date-get-relative ans (current-time) def))
12335 (setq ans (replace-match "" t t ans)
12336 deltan (car delta)
12337 deltaw (nth 1 delta)
12338 deltadef (nth 2 delta)))
12340 ;; Check if there is an iso week date in there
12341 ;; If yes, sore the info and postpone interpreting it until the rest
12342 ;; of the parsing is done
12343 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
12344 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
12345 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
12346 iso-week (string-to-number (match-string 2 ans)))
12347 (setq ans (replace-match "" t t ans)))
12349 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
12350 (when (string-match
12351 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
12352 (setq year (if (match-end 2)
12353 (string-to-number (match-string 2 ans))
12354 (string-to-number (format-time-string "%Y")))
12355 month (string-to-number (match-string 3 ans))
12356 day (string-to-number (match-string 4 ans)))
12357 (if (< year 100) (setq year (+ 2000 year)))
12358 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
12359 t nil ans)))
12360 ;; Help matching am/pm times, because `parse-time-string' does not do that.
12361 ;; If there is a time with am/pm, and *no* time without it, we convert
12362 ;; so that matching will be successful.
12363 (loop for i from 1 to 2 do ; twice, for end time as well
12364 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
12365 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
12366 (setq hour (string-to-number (match-string 1 ans))
12367 minute (if (match-end 3)
12368 (string-to-number (match-string 3 ans))
12370 pm (equal ?p
12371 (string-to-char (downcase (match-string 4 ans)))))
12372 (if (and (= hour 12) (not pm))
12373 (setq hour 0)
12374 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
12375 (setq ans (replace-match (format "%02d:%02d" hour minute)
12376 t t ans))))
12378 ;; Check if a time range is given as a duration
12379 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
12380 (setq hour (string-to-number (match-string 1 ans))
12381 h2 (+ hour (string-to-number (match-string 3 ans)))
12382 minute (string-to-number (match-string 2 ans))
12383 m2 (+ minute (if (match-end 5) (string-to-number
12384 (match-string 5 ans))0)))
12385 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
12386 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
12387 t t ans)))
12389 ;; Check if there is a time range
12390 (when (boundp 'org-end-time-was-given)
12391 (setq org-time-was-given nil)
12392 (when (and (string-match org-plain-time-of-day-regexp ans)
12393 (match-end 8))
12394 (setq org-end-time-was-given (match-string 8 ans))
12395 (setq ans (concat (substring ans 0 (match-beginning 7))
12396 (substring ans (match-end 7))))))
12398 (setq tl (parse-time-string ans)
12399 day (or (nth 3 tl) (nth 3 defdecode))
12400 month (or (nth 4 tl)
12401 (if (and org-read-date-prefer-future
12402 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
12403 (1+ (nth 4 defdecode))
12404 (nth 4 defdecode)))
12405 year (or (nth 5 tl)
12406 (if (and org-read-date-prefer-future
12407 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
12408 (1+ (nth 5 defdecode))
12409 (nth 5 defdecode)))
12410 hour (or (nth 2 tl) (nth 2 defdecode))
12411 minute (or (nth 1 tl) (nth 1 defdecode))
12412 second (or (nth 0 tl) 0)
12413 wday (nth 6 tl))
12415 ;; Special date definitions below
12416 (cond
12417 (iso-week
12418 ;; There was an iso week
12419 (setq year (or iso-year year)
12420 day (or iso-weekday wday 1)
12421 wday nil ; to make sure that the trigger below does not match
12422 iso-date (calendar-gregorian-from-absolute
12423 (calendar-absolute-from-iso
12424 (list iso-week day year))))
12425 ; FIXME: Should we also push ISO weeks into the future?
12426 ; (when (and org-read-date-prefer-future
12427 ; (not iso-year)
12428 ; (< (calendar-absolute-from-gregorian iso-date)
12429 ; (time-to-days (current-time))))
12430 ; (setq year (1+ year)
12431 ; iso-date (calendar-gregorian-from-absolute
12432 ; (calendar-absolute-from-iso
12433 ; (list iso-week day year)))))
12434 (setq month (car iso-date)
12435 year (nth 2 iso-date)
12436 day (nth 1 iso-date)))
12437 (deltan
12438 (unless deltadef
12439 (let ((now (decode-time (current-time))))
12440 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
12441 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
12442 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
12443 ((equal deltaw "m") (setq month (+ month deltan)))
12444 ((equal deltaw "y") (setq year (+ year deltan)))))
12445 ((and wday (not (nth 3 tl)))
12446 ;; Weekday was given, but no day, so pick that day in the week
12447 ;; on or after the derived date.
12448 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
12449 (unless (equal wday wday1)
12450 (setq day (+ day (% (- wday wday1 -7) 7))))))
12451 (if (and (boundp 'org-time-was-given)
12452 (nth 2 tl))
12453 (setq org-time-was-given t))
12454 (if (< year 100) (setq year (+ 2000 year)))
12455 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
12456 (list second minute hour day month year)))
12458 (defvar parse-time-weekdays)
12460 (defun org-read-date-get-relative (s today default)
12461 "Check string S for special relative date string.
12462 TODAY and DEFAULT are internal times, for today and for a default.
12463 Return shift list (N what def-flag)
12464 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
12465 N is the number of WHATs to shift.
12466 DEF-FLAG is t when a double ++ or -- indicates shift relative to
12467 the DEFAULT date rather than TODAY."
12468 (when (and
12469 (string-match
12470 (concat
12471 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
12472 "\\([0-9]+\\)?"
12473 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
12474 "\\([ \t]\\|$\\)") s)
12475 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
12476 (let* ((dir (if (> (match-end 1) (match-beginning 1))
12477 (string-to-char (substring (match-string 1 s) -1))
12478 ?+))
12479 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
12480 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
12481 (what (if (match-end 3) (match-string 3 s) "d"))
12482 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
12483 (date (if rel default today))
12484 (wday (nth 6 (decode-time date)))
12485 delta)
12486 (if wday1
12487 (progn
12488 (setq delta (mod (+ 7 (- wday1 wday)) 7))
12489 (if (= dir ?-) (setq delta (- delta 7)))
12490 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
12491 (list delta "d" rel))
12492 (list (* n (if (= dir ?-) -1 1)) what rel)))))
12494 (defun org-eval-in-calendar (form &optional keepdate)
12495 "Eval FORM in the calendar window and return to current window.
12496 Also, store the cursor date in variable org-ans2."
12497 (let ((sw (selected-window)))
12498 (select-window (get-buffer-window "*Calendar*"))
12499 (eval form)
12500 (when (and (not keepdate) (calendar-cursor-to-date))
12501 (let* ((date (calendar-cursor-to-date))
12502 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12503 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
12504 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
12505 (select-window sw)))
12507 (defun org-calendar-select ()
12508 "Return to `org-read-date' with the date currently selected.
12509 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12510 (interactive)
12511 (when (calendar-cursor-to-date)
12512 (let* ((date (calendar-cursor-to-date))
12513 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12514 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12515 (if (active-minibuffer-window) (exit-minibuffer))))
12517 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
12518 "Insert a date stamp for the date given by the internal TIME.
12519 WITH-HM means, use the stamp format that includes the time of the day.
12520 INACTIVE means use square brackets instead of angular ones, so that the
12521 stamp will not contribute to the agenda.
12522 PRE and POST are optional strings to be inserted before and after the
12523 stamp.
12524 The command returns the inserted time stamp."
12525 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
12526 stamp)
12527 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
12528 (insert-before-markers (or pre ""))
12529 (insert-before-markers (setq stamp (format-time-string fmt time)))
12530 (when (listp extra)
12531 (setq extra (car extra))
12532 (if (and (stringp extra)
12533 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
12534 (setq extra (format "-%02d:%02d"
12535 (string-to-number (match-string 1 extra))
12536 (string-to-number (match-string 2 extra))))
12537 (setq extra nil)))
12538 (when extra
12539 (backward-char 1)
12540 (insert-before-markers extra)
12541 (forward-char 1))
12542 (insert-before-markers (or post ""))
12543 (setq org-last-inserted-timestamp stamp)))
12545 (defun org-toggle-time-stamp-overlays ()
12546 "Toggle the use of custom time stamp formats."
12547 (interactive)
12548 (setq org-display-custom-times (not org-display-custom-times))
12549 (unless org-display-custom-times
12550 (let ((p (point-min)) (bmp (buffer-modified-p)))
12551 (while (setq p (next-single-property-change p 'display))
12552 (if (and (get-text-property p 'display)
12553 (eq (get-text-property p 'face) 'org-date))
12554 (remove-text-properties
12555 p (setq p (next-single-property-change p 'display))
12556 '(display t))))
12557 (set-buffer-modified-p bmp)))
12558 (if (featurep 'xemacs)
12559 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12560 (org-restart-font-lock)
12561 (setq org-table-may-need-update t)
12562 (if org-display-custom-times
12563 (message "Time stamps are overlayed with custom format")
12564 (message "Time stamp overlays removed")))
12566 (defun org-display-custom-time (beg end)
12567 "Overlay modified time stamp format over timestamp between BEG and END."
12568 (let* ((ts (buffer-substring beg end))
12569 t1 w1 with-hm tf time str w2 (off 0))
12570 (save-match-data
12571 (setq t1 (org-parse-time-string ts t))
12572 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
12573 (setq off (- (match-end 0) (match-beginning 0)))))
12574 (setq end (- end off))
12575 (setq w1 (- end beg)
12576 with-hm (and (nth 1 t1) (nth 2 t1))
12577 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
12578 time (org-fix-decoded-time t1)
12579 str (org-add-props
12580 (format-time-string
12581 (substring tf 1 -1) (apply 'encode-time time))
12582 nil 'mouse-face 'highlight)
12583 w2 (length str))
12584 (if (not (= w2 w1))
12585 (add-text-properties (1+ beg) (+ 2 beg)
12586 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12587 (if (featurep 'xemacs)
12588 (progn
12589 (put-text-property beg end 'invisible t)
12590 (put-text-property beg end 'end-glyph (make-glyph str)))
12591 (put-text-property beg end 'display str))))
12593 (defun org-translate-time (string)
12594 "Translate all timestamps in STRING to custom format.
12595 But do this only if the variable `org-display-custom-times' is set."
12596 (when org-display-custom-times
12597 (save-match-data
12598 (let* ((start 0)
12599 (re org-ts-regexp-both)
12600 t1 with-hm inactive tf time str beg end)
12601 (while (setq start (string-match re string start))
12602 (setq beg (match-beginning 0)
12603 end (match-end 0)
12604 t1 (save-match-data
12605 (org-parse-time-string (substring string beg end) t))
12606 with-hm (and (nth 1 t1) (nth 2 t1))
12607 inactive (equal (substring string beg (1+ beg)) "[")
12608 tf (funcall (if with-hm 'cdr 'car)
12609 org-time-stamp-custom-formats)
12610 time (org-fix-decoded-time t1)
12611 str (format-time-string
12612 (concat
12613 (if inactive "[" "<") (substring tf 1 -1)
12614 (if inactive "]" ">"))
12615 (apply 'encode-time time))
12616 string (replace-match str t t string)
12617 start (+ start (length str)))))))
12618 string)
12620 (defun org-fix-decoded-time (time)
12621 "Set 0 instead of nil for the first 6 elements of time.
12622 Don't touch the rest."
12623 (let ((n 0))
12624 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12626 (defun org-days-to-time (timestamp-string)
12627 "Difference between TIMESTAMP-STRING and now in days."
12628 (- (time-to-days (org-time-string-to-time timestamp-string))
12629 (time-to-days (current-time))))
12631 (defun org-deadline-close (timestamp-string &optional ndays)
12632 "Is the time in TIMESTAMP-STRING close to the current date?"
12633 (setq ndays (or ndays (org-get-wdays timestamp-string)))
12634 (and (< (org-days-to-time timestamp-string) ndays)
12635 (not (org-entry-is-done-p))))
12637 (defun org-get-wdays (ts)
12638 "Get the deadline lead time appropriate for timestring TS."
12639 (cond
12640 ((<= org-deadline-warning-days 0)
12641 ;; 0 or negative, enforce this value no matter what
12642 (- org-deadline-warning-days))
12643 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
12644 ;; lead time is specified.
12645 (floor (* (string-to-number (match-string 1 ts))
12646 (cdr (assoc (match-string 2 ts)
12647 '(("d" . 1) ("w" . 7)
12648 ("m" . 30.4) ("y" . 365.25)))))))
12649 ;; go for the default.
12650 (t org-deadline-warning-days)))
12652 (defun org-calendar-select-mouse (ev)
12653 "Return to `org-read-date' with the date currently selected.
12654 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12655 (interactive "e")
12656 (mouse-set-point ev)
12657 (when (calendar-cursor-to-date)
12658 (let* ((date (calendar-cursor-to-date))
12659 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12660 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12661 (if (active-minibuffer-window) (exit-minibuffer))))
12663 (defun org-check-deadlines (ndays)
12664 "Check if there are any deadlines due or past due.
12665 A deadline is considered due if it happens within `org-deadline-warning-days'
12666 days from today's date. If the deadline appears in an entry marked DONE,
12667 it is not shown. The prefix arg NDAYS can be used to test that many
12668 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12669 (interactive "P")
12670 (let* ((org-warn-days
12671 (cond
12672 ((equal ndays '(4)) 100000)
12673 (ndays (prefix-numeric-value ndays))
12674 (t (abs org-deadline-warning-days))))
12675 (case-fold-search nil)
12676 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12677 (callback
12678 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12680 (message "%d deadlines past-due or due within %d days"
12681 (org-occur regexp nil callback)
12682 org-warn-days)))
12684 (defun org-check-before-date (date)
12685 "Check if there are deadlines or scheduled entries before DATE."
12686 (interactive (list (org-read-date)))
12687 (let ((case-fold-search nil)
12688 (regexp (concat "\\<\\(" org-deadline-string
12689 "\\|" org-scheduled-string
12690 "\\) *<\\([^>]+\\)>"))
12691 (callback
12692 (lambda () (time-less-p
12693 (org-time-string-to-time (match-string 2))
12694 (org-time-string-to-time date)))))
12695 (message "%d entries before %s"
12696 (org-occur regexp nil callback) date)))
12698 (defun org-check-after-date (date)
12699 "Check if there are deadlines or scheduled entries after DATE."
12700 (interactive (list (org-read-date)))
12701 (let ((case-fold-search nil)
12702 (regexp (concat "\\<\\(" org-deadline-string
12703 "\\|" org-scheduled-string
12704 "\\) *<\\([^>]+\\)>"))
12705 (callback
12706 (lambda () (not
12707 (time-less-p
12708 (org-time-string-to-time (match-string 2))
12709 (org-time-string-to-time date))))))
12710 (message "%d entries after %s"
12711 (org-occur regexp nil callback) date)))
12713 (defun org-evaluate-time-range (&optional to-buffer)
12714 "Evaluate a time range by computing the difference between start and end.
12715 Normally the result is just printed in the echo area, but with prefix arg
12716 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12717 If the time range is actually in a table, the result is inserted into the
12718 next column.
12719 For time difference computation, a year is assumed to be exactly 365
12720 days in order to avoid rounding problems."
12721 (interactive "P")
12723 (org-clock-update-time-maybe)
12724 (save-excursion
12725 (unless (org-at-date-range-p t)
12726 (goto-char (point-at-bol))
12727 (re-search-forward org-tr-regexp-both (point-at-eol) t))
12728 (if (not (org-at-date-range-p t))
12729 (error "Not at a time-stamp range, and none found in current line")))
12730 (let* ((ts1 (match-string 1))
12731 (ts2 (match-string 2))
12732 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12733 (match-end (match-end 0))
12734 (time1 (org-time-string-to-time ts1))
12735 (time2 (org-time-string-to-time ts2))
12736 (t1 (time-to-seconds time1))
12737 (t2 (time-to-seconds time2))
12738 (diff (abs (- t2 t1)))
12739 (negative (< (- t2 t1) 0))
12740 ;; (ys (floor (* 365 24 60 60)))
12741 (ds (* 24 60 60))
12742 (hs (* 60 60))
12743 (fy "%dy %dd %02d:%02d")
12744 (fy1 "%dy %dd")
12745 (fd "%dd %02d:%02d")
12746 (fd1 "%dd")
12747 (fh "%02d:%02d")
12748 y d h m align)
12749 (if havetime
12750 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12752 d (floor (/ diff ds)) diff (mod diff ds)
12753 h (floor (/ diff hs)) diff (mod diff hs)
12754 m (floor (/ diff 60)))
12755 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12757 d (floor (+ (/ diff ds) 0.5))
12758 h 0 m 0))
12759 (if (not to-buffer)
12760 (message "%s" (org-make-tdiff-string y d h m))
12761 (if (org-at-table-p)
12762 (progn
12763 (goto-char match-end)
12764 (setq align t)
12765 (and (looking-at " *|") (goto-char (match-end 0))))
12766 (goto-char match-end))
12767 (if (looking-at
12768 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12769 (replace-match ""))
12770 (if negative (insert " -"))
12771 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12772 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12773 (insert " " (format fh h m))))
12774 (if align (org-table-align))
12775 (message "Time difference inserted")))))
12777 (defun org-make-tdiff-string (y d h m)
12778 (let ((fmt "")
12779 (l nil))
12780 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12781 l (push y l)))
12782 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12783 l (push d l)))
12784 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12785 l (push h l)))
12786 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12787 l (push m l)))
12788 (apply 'format fmt (nreverse l))))
12790 (defun org-time-string-to-time (s)
12791 (apply 'encode-time (org-parse-time-string s)))
12793 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
12794 "Convert a time stamp to an absolute day number.
12795 If there is a specifyer for a cyclic time stamp, get the closest date to
12796 DAYNR.
12797 PREFER and SHOW-ALL are passed through to `org-closest-date'."
12798 (cond
12799 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
12800 (if (org-diary-sexp-entry (match-string 1 s) "" date)
12801 daynr
12802 (+ daynr 1000)))
12803 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
12804 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
12805 (time-to-days (current-time))) (match-string 0 s)
12806 prefer show-all))
12807 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
12809 (defun org-days-to-iso-week (days)
12810 "Return the iso week number."
12811 (require 'cal-iso)
12812 (car (calendar-iso-from-absolute days)))
12814 (defun org-small-year-to-year (year)
12815 "Convert 2-digit years into 4-digit years.
12816 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
12817 The year 2000 cannot be abbreviated. Any year larger than 99
12818 is returned unchanged."
12819 (if (< year 38)
12820 (setq year (+ 2000 year))
12821 (if (< year 100)
12822 (setq year (+ 1900 year))))
12823 year)
12825 (defun org-time-from-absolute (d)
12826 "Return the time corresponding to date D.
12827 D may be an absolute day number, or a calendar-type list (month day year)."
12828 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
12829 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
12831 (defun org-calendar-holiday ()
12832 "List of holidays, for Diary display in Org-mode."
12833 (require 'holidays)
12834 (let ((hl (funcall
12835 (if (fboundp 'calendar-check-holidays)
12836 'calendar-check-holidays 'check-calendar-holidays) date)))
12837 (if hl (mapconcat 'identity hl "; "))))
12839 (defun org-diary-sexp-entry (sexp entry date)
12840 "Process a SEXP diary ENTRY for DATE."
12841 (require 'diary-lib)
12842 (let ((result (if calendar-debug-sexp
12843 (let ((stack-trace-on-error t))
12844 (eval (car (read-from-string sexp))))
12845 (condition-case nil
12846 (eval (car (read-from-string sexp)))
12847 (error
12848 (beep)
12849 (message "Bad sexp at line %d in %s: %s"
12850 (org-current-line)
12851 (buffer-file-name) sexp)
12852 (sleep-for 2))))))
12853 (cond ((stringp result) result)
12854 ((and (consp result)
12855 (stringp (cdr result))) (cdr result))
12856 (result entry)
12857 (t nil))))
12859 (defun org-diary-to-ical-string (frombuf)
12860 "Get iCalendar entries from diary entries in buffer FROMBUF.
12861 This uses the icalendar.el library."
12862 (let* ((tmpdir (if (featurep 'xemacs)
12863 (temp-directory)
12864 temporary-file-directory))
12865 (tmpfile (make-temp-name
12866 (expand-file-name "orgics" tmpdir)))
12867 buf rtn b e)
12868 (save-excursion
12869 (set-buffer frombuf)
12870 (icalendar-export-region (point-min) (point-max) tmpfile)
12871 (setq buf (find-buffer-visiting tmpfile))
12872 (set-buffer buf)
12873 (goto-char (point-min))
12874 (if (re-search-forward "^BEGIN:VEVENT" nil t)
12875 (setq b (match-beginning 0)))
12876 (goto-char (point-max))
12877 (if (re-search-backward "^END:VEVENT" nil t)
12878 (setq e (match-end 0)))
12879 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
12880 (kill-buffer buf)
12881 (delete-file tmpfile)
12882 rtn))
12884 (defun org-closest-date (start current change prefer show-all)
12885 "Find the date closest to CURRENT that is consistent with START and CHANGE.
12886 When PREFER is `past' return a date that is either CURRENT or past.
12887 When PREFER is `future', return a date that is either CURRENT or future.
12888 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
12889 ;; Make the proper lists from the dates
12890 (catch 'exit
12891 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
12892 dn dw sday cday n1 n2 n0
12893 d m y y1 y2 date1 date2 nmonths nm ny m2)
12895 (setq start (org-date-to-gregorian start)
12896 current (org-date-to-gregorian
12897 (if show-all
12898 current
12899 (time-to-days (current-time))))
12900 sday (calendar-absolute-from-gregorian start)
12901 cday (calendar-absolute-from-gregorian current))
12903 (if (<= cday sday) (throw 'exit sday))
12905 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
12906 (setq dn (string-to-number (match-string 1 change))
12907 dw (cdr (assoc (match-string 2 change) a1)))
12908 (error "Invalid change specifyer: %s" change))
12909 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
12910 (cond
12911 ((eq dw 'day)
12912 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
12913 n2 (+ n1 dn)))
12914 ((eq dw 'year)
12915 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
12916 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
12917 (setq date1 (list m d y1)
12918 n1 (calendar-absolute-from-gregorian date1)
12919 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
12920 n2 (calendar-absolute-from-gregorian date2)))
12921 ((eq dw 'month)
12922 ;; approx number of month between the two dates
12923 (setq nmonths (floor (/ (- cday sday) 30.436875)))
12924 ;; How often does dn fit in there?
12925 (setq d (nth 1 start) m (car start) y (nth 2 start)
12926 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
12927 m (+ m nm)
12928 ny (floor (/ m 12))
12929 y (+ y ny)
12930 m (- m (* ny 12)))
12931 (while (> m 12) (setq m (- m 12) y (1+ y)))
12932 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
12933 (setq m2 (+ m dn) y2 y)
12934 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12935 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
12936 (while (<= n2 cday)
12937 (setq n1 n2 m m2 y y2)
12938 (setq m2 (+ m dn) y2 y)
12939 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12940 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
12941 ;; Make sure n1 is the earlier date
12942 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
12943 (if show-all
12944 (cond
12945 ((eq prefer 'past) n1)
12946 ((eq prefer 'future) (if (= cday n1) n1 n2))
12947 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
12948 (cond
12949 ((eq prefer 'past) n1)
12950 ((eq prefer 'future) (if (= cday n1) n1 n2))
12951 (t (if (= cday n1) n1 n2)))))))
12953 (defun org-date-to-gregorian (date)
12954 "Turn any specification of DATE into a gregorian date for the calendar."
12955 (cond ((integerp date) (calendar-gregorian-from-absolute date))
12956 ((and (listp date) (= (length date) 3)) date)
12957 ((stringp date)
12958 (setq date (org-parse-time-string date))
12959 (list (nth 4 date) (nth 3 date) (nth 5 date)))
12960 ((listp date)
12961 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
12963 (defun org-parse-time-string (s &optional nodefault)
12964 "Parse the standard Org-mode time string.
12965 This should be a lot faster than the normal `parse-time-string'.
12966 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12967 hour and minute fields will be nil if not given."
12968 (if (string-match org-ts-regexp0 s)
12969 (list 0
12970 (if (or (match-beginning 8) (not nodefault))
12971 (string-to-number (or (match-string 8 s) "0")))
12972 (if (or (match-beginning 7) (not nodefault))
12973 (string-to-number (or (match-string 7 s) "0")))
12974 (string-to-number (match-string 4 s))
12975 (string-to-number (match-string 3 s))
12976 (string-to-number (match-string 2 s))
12977 nil nil nil)
12978 (make-list 9 0)))
12980 (defun org-timestamp-up (&optional arg)
12981 "Increase the date item at the cursor by one.
12982 If the cursor is on the year, change the year. If it is on the month or
12983 the day, change that.
12984 With prefix ARG, change by that many units."
12985 (interactive "p")
12986 (org-timestamp-change (prefix-numeric-value arg)))
12988 (defun org-timestamp-down (&optional arg)
12989 "Decrease the date item at the cursor by one.
12990 If the cursor is on the year, change the year. If it is on the month or
12991 the day, change that.
12992 With prefix ARG, change by that many units."
12993 (interactive "p")
12994 (org-timestamp-change (- (prefix-numeric-value arg))))
12996 (defun org-timestamp-up-day (&optional arg)
12997 "Increase the date in the time stamp by one day.
12998 With prefix ARG, change that many days."
12999 (interactive "p")
13000 (if (and (not (org-at-timestamp-p t))
13001 (org-on-heading-p))
13002 (org-todo 'up)
13003 (org-timestamp-change (prefix-numeric-value arg) 'day)))
13005 (defun org-timestamp-down-day (&optional arg)
13006 "Decrease the date in the time stamp by one day.
13007 With prefix ARG, change that many days."
13008 (interactive "p")
13009 (if (and (not (org-at-timestamp-p t))
13010 (org-on-heading-p))
13011 (org-todo 'down)
13012 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
13014 (defun org-at-timestamp-p (&optional inactive-ok)
13015 "Determine if the cursor is in or at a timestamp."
13016 (interactive)
13017 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
13018 (pos (point))
13019 (ans (or (looking-at tsr)
13020 (save-excursion
13021 (skip-chars-backward "^[<\n\r\t")
13022 (if (> (point) (point-min)) (backward-char 1))
13023 (and (looking-at tsr)
13024 (> (- (match-end 0) pos) -1))))))
13025 (and ans
13026 (boundp 'org-ts-what)
13027 (setq org-ts-what
13028 (cond
13029 ((= pos (match-beginning 0)) 'bracket)
13030 ((= pos (1- (match-end 0))) 'bracket)
13031 ((org-pos-in-match-range pos 2) 'year)
13032 ((org-pos-in-match-range pos 3) 'month)
13033 ((org-pos-in-match-range pos 7) 'hour)
13034 ((org-pos-in-match-range pos 8) 'minute)
13035 ((or (org-pos-in-match-range pos 4)
13036 (org-pos-in-match-range pos 5)) 'day)
13037 ((and (> pos (or (match-end 8) (match-end 5)))
13038 (< pos (match-end 0)))
13039 (- pos (or (match-end 8) (match-end 5))))
13040 (t 'day))))
13041 ans))
13043 (defun org-toggle-timestamp-type ()
13044 "Toggle the type (<active> or [inactive]) of a time stamp."
13045 (interactive)
13046 (when (org-at-timestamp-p t)
13047 (let ((beg (match-beginning 0)) (end (match-end 0))
13048 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
13049 (save-excursion
13050 (goto-char beg)
13051 (while (re-search-forward "[][<>]" end t)
13052 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
13053 t t)))
13054 (message "Timestamp is now %sactive"
13055 (if (equal (char-after beg) ?<) "" "in")))))
13057 (defun org-timestamp-change (n &optional what)
13058 "Change the date in the time stamp at point.
13059 The date will be changed by N times WHAT. WHAT can be `day', `month',
13060 `year', `minute', `second'. If WHAT is not given, the cursor position
13061 in the timestamp determines what will be changed."
13062 (let ((pos (point))
13063 with-hm inactive
13064 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
13065 org-ts-what
13066 extra rem
13067 ts time time0)
13068 (if (not (org-at-timestamp-p t))
13069 (error "Not at a timestamp"))
13070 (if (and (not what) (eq org-ts-what 'bracket))
13071 (org-toggle-timestamp-type)
13072 (if (and (not what) (not (eq org-ts-what 'day))
13073 org-display-custom-times
13074 (get-text-property (point) 'display)
13075 (not (get-text-property (1- (point)) 'display)))
13076 (setq org-ts-what 'day))
13077 (setq org-ts-what (or what org-ts-what)
13078 inactive (= (char-after (match-beginning 0)) ?\[)
13079 ts (match-string 0))
13080 (replace-match "")
13081 (if (string-match
13082 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
13084 (setq extra (match-string 1 ts)))
13085 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
13086 (setq with-hm t))
13087 (setq time0 (org-parse-time-string ts))
13088 (when (and (eq org-ts-what 'minute)
13089 (eq current-prefix-arg nil))
13090 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
13091 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
13092 (setcar (cdr time0) (+ (nth 1 time0)
13093 (if (> n 0) (- rem) (- dm rem))))))
13094 (setq time
13095 (encode-time (or (car time0) 0)
13096 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
13097 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
13098 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
13099 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
13100 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
13101 (nthcdr 6 time0)))
13102 (when (and (member org-ts-what '(hour minute))
13103 extra
13104 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
13105 (setq extra (org-modify-ts-extra
13106 extra
13107 (if (eq org-ts-what 'hour) 2 5)
13108 n dm)))
13109 (when (integerp org-ts-what)
13110 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
13111 (if (eq what 'calendar)
13112 (let ((cal-date (org-get-date-from-calendar)))
13113 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
13114 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
13115 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
13116 (setcar time0 (or (car time0) 0))
13117 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
13118 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
13119 (setq time (apply 'encode-time time0))))
13120 (setq org-last-changed-timestamp
13121 (org-insert-time-stamp time with-hm inactive nil nil extra))
13122 (org-clock-update-time-maybe)
13123 (goto-char pos)
13124 ;; Try to recenter the calendar window, if any
13125 (if (and org-calendar-follow-timestamp-change
13126 (get-buffer-window "*Calendar*" t)
13127 (memq org-ts-what '(day month year)))
13128 (org-recenter-calendar (time-to-days time))))))
13130 (defun org-modify-ts-extra (s pos n dm)
13131 "Change the different parts of the lead-time and repeat fields in timestamp."
13132 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
13133 ng h m new rem)
13134 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
13135 (cond
13136 ((or (org-pos-in-match-range pos 2)
13137 (org-pos-in-match-range pos 3))
13138 (setq m (string-to-number (match-string 3 s))
13139 h (string-to-number (match-string 2 s)))
13140 (if (org-pos-in-match-range pos 2)
13141 (setq h (+ h n))
13142 (setq n (* dm (org-no-warnings (signum n))))
13143 (when (not (= 0 (setq rem (% m dm))))
13144 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
13145 (setq m (+ m n)))
13146 (if (< m 0) (setq m (+ m 60) h (1- h)))
13147 (if (> m 59) (setq m (- m 60) h (1+ h)))
13148 (setq h (min 24 (max 0 h)))
13149 (setq ng 1 new (format "-%02d:%02d" h m)))
13150 ((org-pos-in-match-range pos 6)
13151 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
13152 ((org-pos-in-match-range pos 5)
13153 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
13155 ((org-pos-in-match-range pos 9)
13156 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
13157 ((org-pos-in-match-range pos 8)
13158 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
13160 (when ng
13161 (setq s (concat
13162 (substring s 0 (match-beginning ng))
13164 (substring s (match-end ng))))))
13167 (defun org-recenter-calendar (date)
13168 "If the calendar is visible, recenter it to DATE."
13169 (let* ((win (selected-window))
13170 (cwin (get-buffer-window "*Calendar*" t))
13171 (calendar-move-hook nil))
13172 (when cwin
13173 (select-window cwin)
13174 (calendar-goto-date (if (listp date) date
13175 (calendar-gregorian-from-absolute date)))
13176 (select-window win))))
13178 (defun org-goto-calendar (&optional arg)
13179 "Go to the Emacs calendar at the current date.
13180 If there is a time stamp in the current line, go to that date.
13181 A prefix ARG can be used to force the current date."
13182 (interactive "P")
13183 (let ((tsr org-ts-regexp) diff
13184 (calendar-move-hook nil)
13185 (calendar-view-holidays-initially-flag nil)
13186 (view-calendar-holidays-initially nil)
13187 (calendar-view-diary-initially-flag nil)
13188 (view-diary-entries-initially nil))
13189 (if (or (org-at-timestamp-p)
13190 (save-excursion
13191 (beginning-of-line 1)
13192 (looking-at (concat ".*" tsr))))
13193 (let ((d1 (time-to-days (current-time)))
13194 (d2 (time-to-days
13195 (org-time-string-to-time (match-string 1)))))
13196 (setq diff (- d2 d1))))
13197 (calendar)
13198 (calendar-goto-today)
13199 (if (and diff (not arg)) (calendar-forward-day diff))))
13201 (defun org-get-date-from-calendar ()
13202 "Return a list (month day year) of date at point in calendar."
13203 (with-current-buffer "*Calendar*"
13204 (save-match-data
13205 (calendar-cursor-to-date))))
13207 (defun org-date-from-calendar ()
13208 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
13209 If there is already a time stamp at the cursor position, update it."
13210 (interactive)
13211 (if (org-at-timestamp-p t)
13212 (org-timestamp-change 0 'calendar)
13213 (let ((cal-date (org-get-date-from-calendar)))
13214 (org-insert-time-stamp
13215 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
13217 (defun org-minutes-to-hh:mm-string (m)
13218 "Compute H:MM from a number of minutes."
13219 (let ((h (/ m 60)))
13220 (setq m (- m (* 60 h)))
13221 (format org-time-clocksum-format h m)))
13223 (defun org-hh:mm-string-to-minutes (s)
13224 "Convert a string H:MM to a number of minutes."
13225 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
13226 (+ (* (string-to-number (match-string 1 s)) 60)
13227 (string-to-number (match-string 2 s)))
13230 ;;;; Files
13232 (defun org-save-all-org-buffers ()
13233 "Save all Org-mode buffers without user confirmation."
13234 (interactive)
13235 (message "Saving all Org-mode buffers...")
13236 (save-some-buffers t 'org-mode-p)
13237 (when (featurep 'org-id) (org-id-locations-save))
13238 (message "Saving all Org-mode buffers... done"))
13240 (defun org-revert-all-org-buffers ()
13241 "Revert all Org-mode buffers.
13242 Prompt for confirmation when there are unsaved changes.
13243 Be sure you know what you are doing before letting this function
13244 overwrite your changes.
13246 This function is useful in a setup where one tracks org files
13247 with a version control system, to revert on one machine after pulling
13248 changes from another. I believe the procedure must be like this:
13250 1. M-x org-save-all-org-buffers
13251 2. Pull changes from the other machine, resolve conflicts
13252 3. M-x org-revert-all-org-buffers"
13253 (interactive)
13254 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
13255 (error "Abort"))
13256 (save-excursion
13257 (save-window-excursion
13258 (mapc
13259 (lambda (b)
13260 (when (and (with-current-buffer b (org-mode-p))
13261 (with-current-buffer b buffer-file-name))
13262 (switch-to-buffer b)
13263 (revert-buffer t 'no-confirm)))
13264 (buffer-list))
13265 (when (and (featurep 'org-id) org-id-track-globally)
13266 (org-id-locations-load)))))
13268 ;;;; Agenda files
13270 ;;;###autoload
13271 (defun org-iswitchb (&optional arg)
13272 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
13273 With a prefix argument, restrict available to files.
13274 With two prefix arguments, restrict available buffers to agenda files.
13276 Due to some yet unresolved reason, the global function
13277 `iswitchb-mode' needs to be active for this function to work."
13278 (interactive "P")
13279 (require 'iswitchb)
13280 (let ((enabled iswitchb-mode) blist)
13281 (or enabled (iswitchb-mode 1))
13282 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13283 ((equal arg '(16)) (org-buffer-list 'agenda))
13284 (t (org-buffer-list))))
13285 (unwind-protect
13286 (let ((iswitchb-make-buflist-hook
13287 (lambda ()
13288 (setq iswitchb-temp-buflist
13289 (mapcar 'buffer-name blist)))))
13290 (switch-to-buffer
13291 (iswitchb-read-buffer
13292 "Switch-to: " nil t))
13293 (or enabled (iswitchb-mode -1))))))
13295 ;;;###autoload
13296 (defun org-ido-switchb (&optional arg)
13297 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
13298 With a prefix argument, restrict available to files.
13299 With two prefix arguments, restrict available buffers to agenda files."
13300 (interactive "P")
13301 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13302 ((equal arg '(16)) (org-buffer-list 'agenda))
13303 (t (org-buffer-list)))))
13304 (switch-to-buffer
13305 (org-ido-completing-read "Org buffer: "
13306 (mapcar 'list (mapcar 'buffer-name blist))
13307 nil t))))
13309 (defun org-buffer-list (&optional predicate exclude-tmp)
13310 "Return a list of Org buffers.
13311 PREDICATE can be `export', `files' or `agenda'.
13313 export restrict the list to Export buffers.
13314 files restrict the list to buffers visiting Org files.
13315 agenda restrict the list to buffers visiting agenda files.
13317 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
13318 (let* ((bfn nil)
13319 (agenda-files (and (eq predicate 'agenda)
13320 (mapcar 'file-truename (org-agenda-files t))))
13321 (filter
13322 (cond
13323 ((eq predicate 'files)
13324 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
13325 ((eq predicate 'export)
13326 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
13327 ((eq predicate 'agenda)
13328 (lambda (b)
13329 (with-current-buffer b
13330 (and (eq major-mode 'org-mode)
13331 (setq bfn (buffer-file-name b))
13332 (member (file-truename bfn) agenda-files)))))
13333 (t (lambda (b) (with-current-buffer b
13334 (or (eq major-mode 'org-mode)
13335 (string-match "\*Org .*Export"
13336 (buffer-name b)))))))))
13337 (delq nil
13338 (mapcar
13339 (lambda(b)
13340 (if (and (funcall filter b)
13341 (or (not exclude-tmp)
13342 (not (string-match "tmp" (buffer-name b)))))
13344 nil))
13345 (buffer-list)))))
13347 (defun org-agenda-files (&optional unrestricted archives)
13348 "Get the list of agenda files.
13349 Optional UNRESTRICTED means return the full list even if a restriction
13350 is currently in place.
13351 When ARCHIVES is t, include all archive files hat are really being
13352 used by the agenda files. If ARCHIVE is `ifmode', do this only if
13353 `org-agenda-archives-mode' is t."
13354 (let ((files
13355 (cond
13356 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
13357 ((stringp org-agenda-files) (org-read-agenda-file-list))
13358 ((listp org-agenda-files) org-agenda-files)
13359 (t (error "Invalid value of `org-agenda-files'")))))
13360 (setq files (apply 'append
13361 (mapcar (lambda (f)
13362 (if (file-directory-p f)
13363 (directory-files
13364 f t org-agenda-file-regexp)
13365 (list f)))
13366 files)))
13367 (when org-agenda-skip-unavailable-files
13368 (setq files (delq nil
13369 (mapcar (function
13370 (lambda (file)
13371 (and (file-readable-p file) file)))
13372 files))))
13373 (when (or (eq archives t)
13374 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
13375 (setq files (org-add-archive-files files)))
13376 files))
13378 (defun org-edit-agenda-file-list ()
13379 "Edit the list of agenda files.
13380 Depending on setup, this either uses customize to edit the variable
13381 `org-agenda-files', or it visits the file that is holding the list. In the
13382 latter case, the buffer is set up in a way that saving it automatically kills
13383 the buffer and restores the previous window configuration."
13384 (interactive)
13385 (if (stringp org-agenda-files)
13386 (let ((cw (current-window-configuration)))
13387 (find-file org-agenda-files)
13388 (org-set-local 'org-window-configuration cw)
13389 (org-add-hook 'after-save-hook
13390 (lambda ()
13391 (set-window-configuration
13392 (prog1 org-window-configuration
13393 (kill-buffer (current-buffer))))
13394 (org-install-agenda-files-menu)
13395 (message "New agenda file list installed"))
13396 nil 'local)
13397 (message "%s" (substitute-command-keys
13398 "Edit list and finish with \\[save-buffer]")))
13399 (customize-variable 'org-agenda-files)))
13401 (defun org-store-new-agenda-file-list (list)
13402 "Set new value for the agenda file list and save it correctly."
13403 (if (stringp org-agenda-files)
13404 (let ((f org-agenda-files) b)
13405 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
13406 (with-temp-file f
13407 (insert (mapconcat 'identity list "\n") "\n")))
13408 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
13409 (setq org-agenda-files list)
13410 (customize-save-variable 'org-agenda-files org-agenda-files))))
13412 (defun org-read-agenda-file-list ()
13413 "Read the list of agenda files from a file."
13414 (when (file-directory-p org-agenda-files)
13415 (error "`org-agenda-files' cannot be a single directory"))
13416 (when (stringp org-agenda-files)
13417 (with-temp-buffer
13418 (insert-file-contents org-agenda-files)
13419 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
13422 ;;;###autoload
13423 (defun org-cycle-agenda-files ()
13424 "Cycle through the files in `org-agenda-files'.
13425 If the current buffer visits an agenda file, find the next one in the list.
13426 If the current buffer does not, find the first agenda file."
13427 (interactive)
13428 (let* ((fs (org-agenda-files t))
13429 (files (append fs (list (car fs))))
13430 (tcf (if buffer-file-name (file-truename buffer-file-name)))
13431 file)
13432 (unless files (error "No agenda files"))
13433 (catch 'exit
13434 (while (setq file (pop files))
13435 (if (equal (file-truename file) tcf)
13436 (when (car files)
13437 (find-file (car files))
13438 (throw 'exit t))))
13439 (find-file (car fs)))
13440 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
13442 (defun org-agenda-file-to-front (&optional to-end)
13443 "Move/add the current file to the top of the agenda file list.
13444 If the file is not present in the list, it is added to the front. If it is
13445 present, it is moved there. With optional argument TO-END, add/move to the
13446 end of the list."
13447 (interactive "P")
13448 (let ((org-agenda-skip-unavailable-files nil)
13449 (file-alist (mapcar (lambda (x)
13450 (cons (file-truename x) x))
13451 (org-agenda-files t)))
13452 (ctf (file-truename buffer-file-name))
13453 x had)
13454 (setq x (assoc ctf file-alist) had x)
13456 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
13457 (if to-end
13458 (setq file-alist (append (delq x file-alist) (list x)))
13459 (setq file-alist (cons x (delq x file-alist))))
13460 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
13461 (org-install-agenda-files-menu)
13462 (message "File %s to %s of agenda file list"
13463 (if had "moved" "added") (if to-end "end" "front"))))
13465 (defun org-remove-file (&optional file)
13466 "Remove current file from the list of files in variable `org-agenda-files'.
13467 These are the files which are being checked for agenda entries.
13468 Optional argument FILE means, use this file instead of the current."
13469 (interactive)
13470 (let* ((org-agenda-skip-unavailable-files nil)
13471 (file (or file buffer-file-name))
13472 (true-file (file-truename file))
13473 (afile (abbreviate-file-name file))
13474 (files (delq nil (mapcar
13475 (lambda (x)
13476 (if (equal true-file
13477 (file-truename x))
13478 nil x))
13479 (org-agenda-files t)))))
13480 (if (not (= (length files) (length (org-agenda-files t))))
13481 (progn
13482 (org-store-new-agenda-file-list files)
13483 (org-install-agenda-files-menu)
13484 (message "Removed file: %s" afile))
13485 (message "File was not in list: %s (not removed)" afile))))
13487 (defun org-file-menu-entry (file)
13488 (vector file (list 'find-file file) t))
13490 (defun org-check-agenda-file (file)
13491 "Make sure FILE exists. If not, ask user what to do."
13492 (when (not (file-exists-p file))
13493 (message "non-existent file %s. [R]emove from list or [A]bort?"
13494 (abbreviate-file-name file))
13495 (let ((r (downcase (read-char-exclusive))))
13496 (cond
13497 ((equal r ?r)
13498 (org-remove-file file)
13499 (throw 'nextfile t))
13500 (t (error "Abort"))))))
13502 (defun org-get-agenda-file-buffer (file)
13503 "Get a buffer visiting FILE. If the buffer needs to be created, add
13504 it to the list of buffers which might be released later."
13505 (let ((buf (org-find-base-buffer-visiting file)))
13506 (if buf
13507 buf ; just return it
13508 ;; Make a new buffer and remember it
13509 (setq buf (find-file-noselect file))
13510 (if buf (push buf org-agenda-new-buffers))
13511 buf)))
13513 (defun org-release-buffers (blist)
13514 "Release all buffers in list, asking the user for confirmation when needed.
13515 When a buffer is unmodified, it is just killed. When modified, it is saved
13516 \(if the user agrees) and then killed."
13517 (let (buf file)
13518 (while (setq buf (pop blist))
13519 (setq file (buffer-file-name buf))
13520 (when (and (buffer-modified-p buf)
13521 file
13522 (y-or-n-p (format "Save file %s? " file)))
13523 (with-current-buffer buf (save-buffer)))
13524 (kill-buffer buf))))
13526 (defun org-prepare-agenda-buffers (files)
13527 "Create buffers for all agenda files, protect archived trees and comments."
13528 (interactive)
13529 (let ((pa '(:org-archived t))
13530 (pc '(:org-comment t))
13531 (pall '(:org-archived t :org-comment t))
13532 (inhibit-read-only t)
13533 (rea (concat ":" org-archive-tag ":"))
13534 bmp file re)
13535 (save-excursion
13536 (save-restriction
13537 (while (setq file (pop files))
13538 (catch 'nextfile
13539 (if (bufferp file)
13540 (set-buffer file)
13541 (org-check-agenda-file file)
13542 (set-buffer (org-get-agenda-file-buffer file)))
13543 (widen)
13544 (setq bmp (buffer-modified-p))
13545 (org-refresh-category-properties)
13546 (setq org-todo-keywords-for-agenda
13547 (append org-todo-keywords-for-agenda org-todo-keywords-1))
13548 (setq org-done-keywords-for-agenda
13549 (append org-done-keywords-for-agenda org-done-keywords))
13550 (setq org-todo-keyword-alist-for-agenda
13551 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
13552 (setq org-tag-alist-for-agenda
13553 (append org-tag-alist-for-agenda org-tag-alist))
13555 (save-excursion
13556 (remove-text-properties (point-min) (point-max) pall)
13557 (when org-agenda-skip-archived-trees
13558 (goto-char (point-min))
13559 (while (re-search-forward rea nil t)
13560 (if (org-on-heading-p t)
13561 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
13562 (goto-char (point-min))
13563 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
13564 (while (re-search-forward re nil t)
13565 (add-text-properties
13566 (match-beginning 0) (org-end-of-subtree t) pc)))
13567 (set-buffer-modified-p bmp)))))
13568 (setq org-todo-keyword-alist-for-agenda
13569 (org-uniquify org-todo-keyword-alist-for-agenda)
13570 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
13572 ;;;; Embedded LaTeX
13574 (defvar org-cdlatex-mode-map (make-sparse-keymap)
13575 "Keymap for the minor `org-cdlatex-mode'.")
13577 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
13578 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
13579 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
13580 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
13581 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
13583 (defvar org-cdlatex-texmathp-advice-is-done nil
13584 "Flag remembering if we have applied the advice to texmathp already.")
13586 (define-minor-mode org-cdlatex-mode
13587 "Toggle the minor `org-cdlatex-mode'.
13588 This mode supports entering LaTeX environment and math in LaTeX fragments
13589 in Org-mode.
13590 \\{org-cdlatex-mode-map}"
13591 nil " OCDL" nil
13592 (when org-cdlatex-mode (require 'cdlatex))
13593 (unless org-cdlatex-texmathp-advice-is-done
13594 (setq org-cdlatex-texmathp-advice-is-done t)
13595 (defadvice texmathp (around org-math-always-on activate)
13596 "Always return t in org-mode buffers.
13597 This is because we want to insert math symbols without dollars even outside
13598 the LaTeX math segments. If Orgmode thinks that point is actually inside
13599 an embedded LaTeX fragment, let texmathp do its job.
13600 \\[org-cdlatex-mode-map]"
13601 (interactive)
13602 (let (p)
13603 (cond
13604 ((not (org-mode-p)) ad-do-it)
13605 ((eq this-command 'cdlatex-math-symbol)
13606 (setq ad-return-value t
13607 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
13609 (let ((p (org-inside-LaTeX-fragment-p)))
13610 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
13611 (setq ad-return-value t
13612 texmathp-why '("Org-mode embedded math" . 0))
13613 (if p ad-do-it)))))))))
13615 (defun turn-on-org-cdlatex ()
13616 "Unconditionally turn on `org-cdlatex-mode'."
13617 (org-cdlatex-mode 1))
13619 (defun org-inside-LaTeX-fragment-p ()
13620 "Test if point is inside a LaTeX fragment.
13621 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
13622 sequence appearing also before point.
13623 Even though the matchers for math are configurable, this function assumes
13624 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
13625 delimiters are skipped when they have been removed by customization.
13626 The return value is nil, or a cons cell with the delimiter and
13627 and the position of this delimiter.
13629 This function does a reasonably good job, but can locally be fooled by
13630 for example currency specifications. For example it will assume being in
13631 inline math after \"$22.34\". The LaTeX fragment formatter will only format
13632 fragments that are properly closed, but during editing, we have to live
13633 with the uncertainty caused by missing closing delimiters. This function
13634 looks only before point, not after."
13635 (catch 'exit
13636 (let ((pos (point))
13637 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
13638 (lim (progn
13639 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
13640 (point)))
13641 dd-on str (start 0) m re)
13642 (goto-char pos)
13643 (when dodollar
13644 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
13645 re (nth 1 (assoc "$" org-latex-regexps)))
13646 (while (string-match re str start)
13647 (cond
13648 ((= (match-end 0) (length str))
13649 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
13650 ((= (match-end 0) (- (length str) 5))
13651 (throw 'exit nil))
13652 (t (setq start (match-end 0))))))
13653 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
13654 (goto-char pos)
13655 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
13656 (and (match-beginning 2) (throw 'exit nil))
13657 ;; count $$
13658 (while (re-search-backward "\\$\\$" lim t)
13659 (setq dd-on (not dd-on)))
13660 (goto-char pos)
13661 (if dd-on (cons "$$" m))))))
13664 (defun org-try-cdlatex-tab ()
13665 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
13666 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
13667 - inside a LaTeX fragment, or
13668 - after the first word in a line, where an abbreviation expansion could
13669 insert a LaTeX environment."
13670 (when org-cdlatex-mode
13671 (cond
13672 ((save-excursion
13673 (skip-chars-backward "a-zA-Z0-9*")
13674 (skip-chars-backward " \t")
13675 (bolp))
13676 (cdlatex-tab) t)
13677 ((org-inside-LaTeX-fragment-p)
13678 (cdlatex-tab) t)
13679 (t nil))))
13681 (defun org-cdlatex-underscore-caret (&optional arg)
13682 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
13683 Revert to the normal definition outside of these fragments."
13684 (interactive "P")
13685 (if (org-inside-LaTeX-fragment-p)
13686 (call-interactively 'cdlatex-sub-superscript)
13687 (let (org-cdlatex-mode)
13688 (call-interactively (key-binding (vector last-input-event))))))
13690 (defun org-cdlatex-math-modify (&optional arg)
13691 "Execute `cdlatex-math-modify' in LaTeX fragments.
13692 Revert to the normal definition outside of these fragments."
13693 (interactive "P")
13694 (if (org-inside-LaTeX-fragment-p)
13695 (call-interactively 'cdlatex-math-modify)
13696 (let (org-cdlatex-mode)
13697 (call-interactively (key-binding (vector last-input-event))))))
13699 (defvar org-latex-fragment-image-overlays nil
13700 "List of overlays carrying the images of latex fragments.")
13701 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
13703 (defun org-remove-latex-fragment-image-overlays ()
13704 "Remove all overlays with LaTeX fragment images in current buffer."
13705 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
13706 (setq org-latex-fragment-image-overlays nil))
13708 (defun org-preview-latex-fragment (&optional subtree)
13709 "Preview the LaTeX fragment at point, or all locally or globally.
13710 If the cursor is in a LaTeX fragment, create the image and overlay
13711 it over the source code. If there is no fragment at point, display
13712 all fragments in the current text, from one headline to the next. With
13713 prefix SUBTREE, display all fragments in the current subtree. With a
13714 double prefix `C-u C-u', or when the cursor is before the first headline,
13715 display all fragments in the buffer.
13716 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
13717 (interactive "P")
13718 (org-remove-latex-fragment-image-overlays)
13719 (save-excursion
13720 (save-restriction
13721 (let (beg end at msg)
13722 (cond
13723 ((or (equal subtree '(16))
13724 (not (save-excursion
13725 (re-search-backward (concat "^" outline-regexp) nil t))))
13726 (setq beg (point-min) end (point-max)
13727 msg "Creating images for buffer...%s"))
13728 ((equal subtree '(4))
13729 (org-back-to-heading)
13730 (setq beg (point) end (org-end-of-subtree t)
13731 msg "Creating images for subtree...%s"))
13733 (if (setq at (org-inside-LaTeX-fragment-p))
13734 (goto-char (max (point-min) (- (cdr at) 2)))
13735 (org-back-to-heading))
13736 (setq beg (point) end (progn (outline-next-heading) (point))
13737 msg (if at "Creating image...%s"
13738 "Creating images for entry...%s"))))
13739 (message msg "")
13740 (narrow-to-region beg end)
13741 (goto-char beg)
13742 (org-format-latex
13743 (concat "ltxpng/" (file-name-sans-extension
13744 (file-name-nondirectory
13745 buffer-file-name)))
13746 default-directory 'overlays msg at 'forbuffer)
13747 (message msg "done. Use `C-c C-c' to remove images.")))))
13749 (defvar org-latex-regexps
13750 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
13751 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
13752 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
13753 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13754 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13755 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
13756 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
13757 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
13758 "Regular expressions for matching embedded LaTeX.")
13760 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
13761 "Replace LaTeX fragments with links to an image, and produce images."
13762 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
13763 (let* ((prefixnodir (file-name-nondirectory prefix))
13764 (absprefix (expand-file-name prefix dir))
13765 (todir (file-name-directory absprefix))
13766 (opt org-format-latex-options)
13767 (matchers (plist-get opt :matchers))
13768 (re-list org-latex-regexps)
13769 (cnt 0) txt link beg end re e checkdir
13770 executables-checked
13771 m n block linkfile movefile ov)
13772 ;; Check if there are old images files with this prefix, and remove them
13773 (when (file-directory-p todir)
13774 (mapc 'delete-file
13775 (directory-files
13776 todir 'full
13777 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
13778 ;; Check the different regular expressions
13779 (while (setq e (pop re-list))
13780 (setq m (car e) re (nth 1 e) n (nth 2 e)
13781 block (if (nth 3 e) "\n\n" ""))
13782 (when (member m matchers)
13783 (goto-char (point-min))
13784 (while (re-search-forward re nil t)
13785 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
13786 (not (get-text-property (match-beginning n)
13787 'org-protected)))
13788 (setq txt (match-string n)
13789 beg (match-beginning n) end (match-end n)
13790 cnt (1+ cnt)
13791 linkfile (format "%s_%04d.png" prefix cnt)
13792 movefile (format "%s_%04d.png" absprefix cnt)
13793 link (concat block "[[file:" linkfile "]]" block))
13794 (if msg (message msg cnt))
13795 (goto-char beg)
13796 (unless checkdir ; make sure the directory exists
13797 (setq checkdir t)
13798 (or (file-directory-p todir) (make-directory todir)))
13800 (unless executables-checked
13801 (org-check-external-command
13802 "latex" "needed to convert LaTeX fragments to images")
13803 (org-check-external-command
13804 "dvipng" "needed to convert LaTeX fragments to images")
13805 (setq executables-checked t))
13807 (org-create-formula-image
13808 txt movefile opt forbuffer)
13809 (if overlays
13810 (progn
13811 (setq ov (org-make-overlay beg end))
13812 (if (featurep 'xemacs)
13813 (progn
13814 (org-overlay-put ov 'invisible t)
13815 (org-overlay-put
13816 ov 'end-glyph
13817 (make-glyph (vector 'png :file movefile))))
13818 (org-overlay-put
13819 ov 'display
13820 (list 'image :type 'png :file movefile :ascent 'center)))
13821 (push ov org-latex-fragment-image-overlays)
13822 (goto-char end))
13823 (delete-region beg end)
13824 (insert link))))))))
13826 ;; This function borrows from Ganesh Swami's latex2png.el
13827 (defun org-create-formula-image (string tofile options buffer)
13828 (let* ((tmpdir (if (featurep 'xemacs)
13829 (temp-directory)
13830 temporary-file-directory))
13831 (texfilebase (make-temp-name
13832 (expand-file-name "orgtex" tmpdir)))
13833 (texfile (concat texfilebase ".tex"))
13834 (dvifile (concat texfilebase ".dvi"))
13835 (pngfile (concat texfilebase ".png"))
13836 (fnh (if (featurep 'xemacs)
13837 (font-height (get-face-font 'default))
13838 (face-attribute 'default :height nil)))
13839 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
13840 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
13841 (fg (or (plist-get options (if buffer :foreground :html-foreground))
13842 "Black"))
13843 (bg (or (plist-get options (if buffer :background :html-background))
13844 "Transparent")))
13845 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
13846 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
13847 (with-temp-file texfile
13848 (insert org-format-latex-header
13849 "\n\\begin{document}\n" string "\n\\end{document}\n"))
13850 (let ((dir default-directory))
13851 (condition-case nil
13852 (progn
13853 (cd tmpdir)
13854 (call-process "latex" nil nil nil texfile))
13855 (error nil))
13856 (cd dir))
13857 (if (not (file-exists-p dvifile))
13858 (progn (message "Failed to create dvi file from %s" texfile) nil)
13859 (condition-case nil
13860 (call-process "dvipng" nil nil nil
13861 "-E" "-fg" fg "-bg" bg
13862 "-D" dpi
13863 ;;"-x" scale "-y" scale
13864 "-T" "tight"
13865 "-o" pngfile
13866 dvifile)
13867 (error nil))
13868 (if (not (file-exists-p pngfile))
13869 (progn (message "Failed to create png file from %s" texfile) nil)
13870 ;; Use the requested file name and clean up
13871 (copy-file pngfile tofile 'replace)
13872 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
13873 (delete-file (concat texfilebase e)))
13874 pngfile))))
13876 (defun org-dvipng-color (attr)
13877 "Return an rgb color specification for dvipng."
13878 (apply 'format "rgb %s %s %s"
13879 (mapcar 'org-normalize-color
13880 (color-values (face-attribute 'default attr nil)))))
13882 (defun org-normalize-color (value)
13883 "Return string to be used as color value for an RGB component."
13884 (format "%g" (/ value 65535.0)))
13886 ;;;; Key bindings
13888 ;; Make `C-c C-x' a prefix key
13889 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
13891 ;; TAB key with modifiers
13892 (org-defkey org-mode-map "\C-i" 'org-cycle)
13893 (org-defkey org-mode-map [(tab)] 'org-cycle)
13894 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
13895 (org-defkey org-mode-map [(meta tab)] 'org-complete)
13896 (org-defkey org-mode-map "\M-\t" 'org-complete)
13897 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
13898 ;; The following line is necessary under Suse GNU/Linux
13899 (unless (featurep 'xemacs)
13900 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
13901 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
13902 (define-key org-mode-map [backtab] 'org-shifttab)
13904 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
13905 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
13906 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
13908 ;; Cursor keys with modifiers
13909 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
13910 (org-defkey org-mode-map [(meta right)] 'org-metaright)
13911 (org-defkey org-mode-map [(meta up)] 'org-metaup)
13912 (org-defkey org-mode-map [(meta down)] 'org-metadown)
13914 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
13915 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
13916 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
13917 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
13919 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
13920 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
13921 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
13922 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
13924 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
13925 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
13927 ;;; Extra keys for tty access.
13928 ;; We only set them when really needed because otherwise the
13929 ;; menus don't show the simple keys
13931 (when (or org-use-extra-keys
13932 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
13933 (not window-system))
13934 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
13935 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
13936 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
13937 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
13938 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
13939 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
13940 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
13941 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
13942 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
13943 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
13944 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
13945 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
13946 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
13947 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
13948 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
13949 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
13950 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
13951 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
13952 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
13953 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
13954 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
13955 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
13957 ;; All the other keys
13959 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
13960 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
13961 (if (boundp 'narrow-map)
13962 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
13963 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
13964 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
13965 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
13966 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
13967 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
13968 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
13969 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
13970 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
13971 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
13972 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
13973 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
13974 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
13975 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
13976 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
13977 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
13978 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
13979 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
13980 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
13981 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
13982 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
13983 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
13984 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
13985 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
13986 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
13987 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
13988 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
13989 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
13990 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
13991 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
13992 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
13993 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
13994 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
13995 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
13996 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
13997 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
13998 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
13999 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
14000 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
14001 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
14002 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
14003 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14004 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
14005 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
14006 (org-defkey org-mode-map "\C-c^" 'org-sort)
14007 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
14008 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
14009 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
14010 (org-defkey org-mode-map "\C-m" 'org-return)
14011 (org-defkey org-mode-map "\C-j" 'org-return-indent)
14012 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
14013 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
14014 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
14015 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
14016 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
14017 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
14018 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
14019 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
14020 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
14021 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
14022 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
14023 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
14024 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
14025 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
14026 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
14027 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
14029 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
14030 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
14031 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
14032 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
14034 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
14035 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
14036 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
14037 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
14038 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
14039 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
14040 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
14041 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
14042 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
14043 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
14044 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
14045 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
14046 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
14048 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
14049 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
14050 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
14051 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
14053 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
14055 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
14057 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
14058 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
14060 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
14063 (when (featurep 'xemacs)
14064 (org-defkey org-mode-map 'button3 'popup-mode-menu))
14067 (defvar org-self-insert-command-undo-counter 0)
14069 (defvar org-table-auto-blank-field) ; defined in org-table.el
14070 (defun org-self-insert-command (N)
14071 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
14072 If the cursor is in a table looking at whitespace, the whitespace is
14073 overwritten, and the table is not marked as requiring realignment."
14074 (interactive "p")
14075 (if (and
14076 (org-table-p)
14077 (progn
14078 ;; check if we blank the field, and if that triggers align
14079 (and (featurep 'org-table) org-table-auto-blank-field
14080 (member last-command
14081 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
14082 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
14083 ;; got extra space, this field does not determine column width
14084 (let (org-table-may-need-update) (org-table-blank-field))
14085 ;; no extra space, this field may determine column width
14086 (org-table-blank-field)))
14088 (eq N 1)
14089 (looking-at "[^|\n]* |"))
14090 (let (org-table-may-need-update)
14091 (goto-char (1- (match-end 0)))
14092 (delete-backward-char 1)
14093 (goto-char (match-beginning 0))
14094 (self-insert-command N))
14095 (setq org-table-may-need-update t)
14096 (self-insert-command N)
14097 (org-fix-tags-on-the-fly)
14098 (if org-self-insert-cluster-for-undo
14099 (if (not (eq last-command 'org-self-insert-command))
14100 (setq org-self-insert-command-undo-counter 1)
14101 (if (>= org-self-insert-command-undo-counter 20)
14102 (setq org-self-insert-command-undo-counter 1)
14103 (and (> org-self-insert-command-undo-counter 0)
14104 buffer-undo-list
14105 (not (cadr buffer-undo-list)) ; remove nil entry
14106 (setcdr buffer-undo-list (cddr buffer-undo-list)))
14107 (setq org-self-insert-command-undo-counter
14108 (1+ org-self-insert-command-undo-counter)))))))
14110 (defun org-fix-tags-on-the-fly ()
14111 (when (and (equal (char-after (point-at-bol)) ?*)
14112 (org-on-heading-p))
14113 (org-align-tags-here org-tags-column)))
14115 (defun org-delete-backward-char (N)
14116 "Like `delete-backward-char', insert whitespace at field end in tables.
14117 When deleting backwards, in tables this function will insert whitespace in
14118 front of the next \"|\" separator, to keep the table aligned. The table will
14119 still be marked for re-alignment if the field did fill the entire column,
14120 because, in this case the deletion might narrow the column."
14121 (interactive "p")
14122 (if (and (org-table-p)
14123 (eq N 1)
14124 (string-match "|" (buffer-substring (point-at-bol) (point)))
14125 (looking-at ".*?|"))
14126 (let ((pos (point))
14127 (noalign (looking-at "[^|\n\r]* |"))
14128 (c org-table-may-need-update))
14129 (backward-delete-char N)
14130 (skip-chars-forward "^|")
14131 (insert " ")
14132 (goto-char (1- pos))
14133 ;; noalign: if there were two spaces at the end, this field
14134 ;; does not determine the width of the column.
14135 (if noalign (setq org-table-may-need-update c)))
14136 (backward-delete-char N)
14137 (org-fix-tags-on-the-fly)))
14139 (defun org-delete-char (N)
14140 "Like `delete-char', but insert whitespace at field end in tables.
14141 When deleting characters, in tables this function will insert whitespace in
14142 front of the next \"|\" separator, to keep the table aligned. The table will
14143 still be marked for re-alignment if the field did fill the entire column,
14144 because, in this case the deletion might narrow the column."
14145 (interactive "p")
14146 (if (and (org-table-p)
14147 (not (bolp))
14148 (not (= (char-after) ?|))
14149 (eq N 1))
14150 (if (looking-at ".*?|")
14151 (let ((pos (point))
14152 (noalign (looking-at "[^|\n\r]* |"))
14153 (c org-table-may-need-update))
14154 (replace-match (concat
14155 (substring (match-string 0) 1 -1)
14156 " |"))
14157 (goto-char pos)
14158 ;; noalign: if there were two spaces at the end, this field
14159 ;; does not determine the width of the column.
14160 (if noalign (setq org-table-may-need-update c)))
14161 (delete-char N))
14162 (delete-char N)
14163 (org-fix-tags-on-the-fly)))
14165 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
14166 (put 'org-self-insert-command 'delete-selection t)
14167 (put 'orgtbl-self-insert-command 'delete-selection t)
14168 (put 'org-delete-char 'delete-selection 'supersede)
14169 (put 'org-delete-backward-char 'delete-selection 'supersede)
14170 (put 'org-yank 'delete-selection 'yank)
14172 ;; Make `flyspell-mode' delay after some commands
14173 (put 'org-self-insert-command 'flyspell-delayed t)
14174 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
14175 (put 'org-delete-char 'flyspell-delayed t)
14176 (put 'org-delete-backward-char 'flyspell-delayed t)
14178 ;; Make pabbrev-mode expand after org-mode commands
14179 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
14180 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
14182 ;; How to do this: Measure non-white length of current string
14183 ;; If equal to column width, we should realign.
14185 (defun org-remap (map &rest commands)
14186 "In MAP, remap the functions given in COMMANDS.
14187 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
14188 (let (new old)
14189 (while commands
14190 (setq old (pop commands) new (pop commands))
14191 (if (fboundp 'command-remapping)
14192 (org-defkey map (vector 'remap old) new)
14193 (substitute-key-definition old new map global-map)))))
14195 (when (eq org-enable-table-editor 'optimized)
14196 ;; If the user wants maximum table support, we need to hijack
14197 ;; some standard editing functions
14198 (org-remap org-mode-map
14199 'self-insert-command 'org-self-insert-command
14200 'delete-char 'org-delete-char
14201 'delete-backward-char 'org-delete-backward-char)
14202 (org-defkey org-mode-map "|" 'org-force-self-insert))
14204 (defvar org-ctrl-c-ctrl-c-hook nil
14205 "Hook for functions attaching themselves to `C-c C-c'.
14206 This can be used to add additional functionality to the C-c C-c key which
14207 executes context-dependent commands.
14208 Each function will be called with no arguments. The function must check
14209 if the context is appropriate for it to act. If yes, it should do its
14210 thing and then return a non-nil value. If the context is wrong,
14211 just do nothing and return nil.")
14213 (defvar org-tab-first-hook nil
14214 "Hook for functions to attach themselves to TAB.
14215 See `org-ctrl-c-ctrl-c-hook' for more information.
14216 This hook runs as the first action when TAB is pressed, even before
14217 `org-cycle' messes around with the `outline-regexp' to cater for
14218 inline tasks and plain list item folding.
14219 If any function in this hook returns t, not other actions like table
14220 field motion visibility cycling will be done.")
14222 (defvar org-tab-after-check-for-table-hook nil
14223 "Hook for functions to attach themselves to TAB.
14224 See `org-ctrl-c-ctrl-c-hook' for more information.
14225 This hook runs after it has been established that the cursor is not in a
14226 table, but before checking if the cursor is in a headline or if global cycling
14227 should be done.
14228 If any function in this hook returns t, not other actions like visibility
14229 cycling will be done.")
14231 (defvar org-tab-after-check-for-cycling-hook nil
14232 "Hook for functions to attach themselves to TAB.
14233 See `org-ctrl-c-ctrl-c-hook' for more information.
14234 This hook runs after it has been established that not table field motion and
14235 not visibility should be done because of current context. This is probably
14236 the place where a package like yasnippets can hook in.")
14238 (defvar org-metaleft-hook nil
14239 "Hook for functions attaching themselves to `M-left'.
14240 See `org-ctrl-c-ctrl-c-hook' for more information.")
14241 (defvar org-metaright-hook nil
14242 "Hook for functions attaching themselves to `M-right'.
14243 See `org-ctrl-c-ctrl-c-hook' for more information.")
14244 (defvar org-metaup-hook nil
14245 "Hook for functions attaching themselves to `M-up'.
14246 See `org-ctrl-c-ctrl-c-hook' for more information.")
14247 (defvar org-metadown-hook nil
14248 "Hook for functions attaching themselves to `M-down'.
14249 See `org-ctrl-c-ctrl-c-hook' for more information.")
14250 (defvar org-shiftmetaleft-hook nil
14251 "Hook for functions attaching themselves to `M-S-left'.
14252 See `org-ctrl-c-ctrl-c-hook' for more information.")
14253 (defvar org-shiftmetaright-hook nil
14254 "Hook for functions attaching themselves to `M-S-right'.
14255 See `org-ctrl-c-ctrl-c-hook' for more information.")
14256 (defvar org-shiftmetaup-hook nil
14257 "Hook for functions attaching themselves to `M-S-up'.
14258 See `org-ctrl-c-ctrl-c-hook' for more information.")
14259 (defvar org-shiftmetadown-hook nil
14260 "Hook for functions attaching themselves to `M-S-down'.
14261 See `org-ctrl-c-ctrl-c-hook' for more information.")
14262 (defvar org-metareturn-hook nil
14263 "Hook for functions attaching themselves to `M-RET'.
14264 See `org-ctrl-c-ctrl-c-hook' for more information.")
14266 (defun org-modifier-cursor-error ()
14267 "Throw an error, a modified cursor command was applied in wrong context."
14268 (error "This command is active in special context like tables, headlines or items"))
14270 (defun org-shiftselect-error ()
14271 "Throw an error because Shift-Cursor command was applied in wrong context."
14272 (if (and (boundp 'shift-select-mode) shift-select-mode)
14273 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
14274 (error "This command works only in special context like headlines or timestamps.")))
14276 (defun org-call-for-shift-select (cmd)
14277 (let ((this-command-keys-shift-translated t))
14278 (call-interactively cmd)))
14280 (defun org-shifttab (&optional arg)
14281 "Global visibility cycling or move to previous table field.
14282 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
14283 on context.
14284 See the individual commands for more information."
14285 (interactive "P")
14286 (cond
14287 ((org-at-table-p) (call-interactively 'org-table-previous-field))
14288 ((integerp arg)
14289 (message "Content view to level: %d" arg)
14290 (org-content (prefix-numeric-value arg))
14291 (setq org-cycle-global-status 'overview))
14292 (t (call-interactively 'org-global-cycle))))
14294 (defun org-shiftmetaleft ()
14295 "Promote subtree or delete table column.
14296 Calls `org-promote-subtree', `org-outdent-item',
14297 or `org-table-delete-column', depending on context.
14298 See the individual commands for more information."
14299 (interactive)
14300 (cond
14301 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
14302 ((org-at-table-p) (call-interactively 'org-table-delete-column))
14303 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
14304 ((org-at-item-p) (call-interactively 'org-outdent-item))
14305 (t (org-modifier-cursor-error))))
14307 (defun org-shiftmetaright ()
14308 "Demote subtree or insert table column.
14309 Calls `org-demote-subtree', `org-indent-item',
14310 or `org-table-insert-column', depending on context.
14311 See the individual commands for more information."
14312 (interactive)
14313 (cond
14314 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
14315 ((org-at-table-p) (call-interactively 'org-table-insert-column))
14316 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
14317 ((org-at-item-p) (call-interactively 'org-indent-item))
14318 (t (org-modifier-cursor-error))))
14320 (defun org-shiftmetaup (&optional arg)
14321 "Move subtree up or kill table row.
14322 Calls `org-move-subtree-up' or `org-table-kill-row' or
14323 `org-move-item-up' depending on context. See the individual commands
14324 for more information."
14325 (interactive "P")
14326 (cond
14327 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
14328 ((org-at-table-p) (call-interactively 'org-table-kill-row))
14329 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14330 ((org-at-item-p) (call-interactively 'org-move-item-up))
14331 (t (org-modifier-cursor-error))))
14333 (defun org-shiftmetadown (&optional arg)
14334 "Move subtree down or insert table row.
14335 Calls `org-move-subtree-down' or `org-table-insert-row' or
14336 `org-move-item-down', depending on context. See the individual
14337 commands for more information."
14338 (interactive "P")
14339 (cond
14340 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
14341 ((org-at-table-p) (call-interactively 'org-table-insert-row))
14342 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14343 ((org-at-item-p) (call-interactively 'org-move-item-down))
14344 (t (org-modifier-cursor-error))))
14346 (defun org-metaleft (&optional arg)
14347 "Promote heading or move table column to left.
14348 Calls `org-do-promote' or `org-table-move-column', depending on context.
14349 With no specific context, calls the Emacs default `backward-word'.
14350 See the individual commands for more information."
14351 (interactive "P")
14352 (cond
14353 ((run-hook-with-args-until-success 'org-metaleft-hook))
14354 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
14355 ((or (org-on-heading-p)
14356 (and (org-region-active-p)
14357 (save-excursion
14358 (goto-char (region-beginning))
14359 (org-on-heading-p))))
14360 (call-interactively 'org-do-promote))
14361 ((or (org-at-item-p)
14362 (and (org-region-active-p)
14363 (save-excursion
14364 (goto-char (region-beginning))
14365 (org-at-item-p))))
14366 (call-interactively 'org-outdent-item))
14367 (t (call-interactively 'backward-word))))
14369 (defun org-metaright (&optional arg)
14370 "Demote subtree or move table column to right.
14371 Calls `org-do-demote' or `org-table-move-column', depending on context.
14372 With no specific context, calls the Emacs default `forward-word'.
14373 See the individual commands for more information."
14374 (interactive "P")
14375 (cond
14376 ((run-hook-with-args-until-success 'org-metaright-hook))
14377 ((org-at-table-p) (call-interactively 'org-table-move-column))
14378 ((or (org-on-heading-p)
14379 (and (org-region-active-p)
14380 (save-excursion
14381 (goto-char (region-beginning))
14382 (org-on-heading-p))))
14383 (call-interactively 'org-do-demote))
14384 ((or (org-at-item-p)
14385 (and (org-region-active-p)
14386 (save-excursion
14387 (goto-char (region-beginning))
14388 (org-at-item-p))))
14389 (call-interactively 'org-indent-item))
14390 (t (call-interactively 'forward-word))))
14392 (defun org-metaup (&optional arg)
14393 "Move subtree up or move table row up.
14394 Calls `org-move-subtree-up' or `org-table-move-row' or
14395 `org-move-item-up', depending on context. See the individual commands
14396 for more information."
14397 (interactive "P")
14398 (cond
14399 ((run-hook-with-args-until-success 'org-metaup-hook))
14400 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
14401 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14402 ((org-at-item-p) (call-interactively 'org-move-item-up))
14403 (t (transpose-lines 1) (beginning-of-line -1))))
14405 (defun org-metadown (&optional arg)
14406 "Move subtree down or move table row down.
14407 Calls `org-move-subtree-down' or `org-table-move-row' or
14408 `org-move-item-down', depending on context. See the individual
14409 commands for more information."
14410 (interactive "P")
14411 (cond
14412 ((run-hook-with-args-until-success 'org-metadown-hook))
14413 ((org-at-table-p) (call-interactively 'org-table-move-row))
14414 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14415 ((org-at-item-p) (call-interactively 'org-move-item-down))
14416 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
14418 (defun org-shiftup (&optional arg)
14419 "Increase item in timestamp or increase priority of current headline.
14420 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
14421 depending on context. See the individual commands for more information."
14422 (interactive "P")
14423 (cond
14424 ((and org-support-shift-select (org-region-active-p))
14425 (org-call-for-shift-select 'previous-line))
14426 ((org-at-timestamp-p t)
14427 (call-interactively (if org-edit-timestamp-down-means-later
14428 'org-timestamp-down 'org-timestamp-up)))
14429 ((and (not (eq org-support-shift-select 'always))
14430 org-enable-priority-commands
14431 (org-on-heading-p))
14432 (call-interactively 'org-priority-up))
14433 ((and (not org-support-shift-select) (org-at-item-p))
14434 (call-interactively 'org-previous-item))
14435 ((org-clocktable-try-shift 'up arg))
14436 (org-support-shift-select
14437 (org-call-for-shift-select 'previous-line))
14438 (t (org-shiftselect-error))))
14440 (defun org-shiftdown (&optional arg)
14441 "Decrease item in timestamp or decrease priority of current headline.
14442 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
14443 depending on context. See the individual commands for more information."
14444 (interactive "P")
14445 (cond
14446 ((and org-support-shift-select (org-region-active-p))
14447 (org-call-for-shift-select 'next-line))
14448 ((org-at-timestamp-p t)
14449 (call-interactively (if org-edit-timestamp-down-means-later
14450 'org-timestamp-up 'org-timestamp-down)))
14451 ((and (not (eq org-support-shift-select 'always))
14452 org-enable-priority-commands
14453 (org-on-heading-p))
14454 (call-interactively 'org-priority-down))
14455 ((and (not org-support-shift-select) (org-at-item-p))
14456 (call-interactively 'org-next-item))
14457 ((org-clocktable-try-shift 'down arg))
14458 (org-support-shift-select
14459 (org-call-for-shift-select 'next-line))
14460 (t (org-shiftselect-error))))
14462 (defun org-shiftright (&optional arg)
14463 "Cycle the thing at point or in the current line, depending on context.
14464 Depending on context, this does one of the following:
14466 - switch a timestamp at point one day into the future
14467 - on a headline, switch to the next TODO keyword.
14468 - on an item, switch entire list to the next bullet type
14469 - on a property line, switch to the next allowed value
14470 - on a clocktable definition line, move time block into the future"
14471 (interactive "P")
14472 (cond
14473 ((and org-support-shift-select (org-region-active-p))
14474 (org-call-for-shift-select 'forward-char))
14475 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
14476 ((and (not (eq org-support-shift-select 'always))
14477 (org-on-heading-p))
14478 (org-call-with-arg 'org-todo 'right))
14479 ((or (and org-support-shift-select
14480 (not (eq org-support-shift-select 'always))
14481 (org-at-item-bullet-p))
14482 (and (not org-support-shift-select) (org-at-item-p)))
14483 (org-call-with-arg 'org-cycle-list-bullet nil))
14484 ((and (not (eq org-support-shift-select 'always))
14485 (org-at-property-p))
14486 (call-interactively 'org-property-next-allowed-value))
14487 ((org-clocktable-try-shift 'right arg))
14488 (org-support-shift-select
14489 (org-call-for-shift-select 'forward-char))
14490 (t (org-shiftselect-error))))
14492 (defun org-shiftleft (&optional arg)
14493 "Cycle the thing at point or in the current line, depending on context.
14494 Depending on context, this does one of the following:
14496 - switch a timestamp at point one day into the past
14497 - on a headline, switch to the previous TODO keyword.
14498 - on an item, switch entire list to the previous bullet type
14499 - on a property line, switch to the previous allowed value
14500 - on a clocktable definition line, move time block into the past"
14501 (interactive "P")
14502 (cond
14503 ((and org-support-shift-select (org-region-active-p))
14504 (org-call-for-shift-select 'backward-char))
14505 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
14506 ((and (not (eq org-support-shift-select 'always))
14507 (org-on-heading-p))
14508 (org-call-with-arg 'org-todo 'left))
14509 ((or (and org-support-shift-select
14510 (not (eq org-support-shift-select 'always))
14511 (org-at-item-bullet-p))
14512 (and (not org-support-shift-select) (org-at-item-p)))
14513 (org-call-with-arg 'org-cycle-list-bullet 'previous))
14514 ((and (not (eq org-support-shift-select 'always))
14515 (org-at-property-p))
14516 (call-interactively 'org-property-previous-allowed-value))
14517 ((org-clocktable-try-shift 'left arg))
14518 (org-support-shift-select
14519 (org-call-for-shift-select 'backward-char))
14520 (t (org-shiftselect-error))))
14522 (defun org-shiftcontrolright ()
14523 "Switch to next TODO set."
14524 (interactive)
14525 (cond
14526 ((and org-support-shift-select (org-region-active-p))
14527 (org-call-for-shift-select 'forward-word))
14528 ((and (not (eq org-support-shift-select 'always))
14529 (org-on-heading-p))
14530 (org-call-with-arg 'org-todo 'nextset))
14531 (org-support-shift-select
14532 (org-call-for-shift-select 'forward-word))
14533 (t (org-shiftselect-error))))
14535 (defun org-shiftcontrolleft ()
14536 "Switch to previous TODO set."
14537 (interactive)
14538 (cond
14539 ((and org-support-shift-select (org-region-active-p))
14540 (org-call-for-shift-select 'backward-word))
14541 ((and (not (eq org-support-shift-select 'always))
14542 (org-on-heading-p))
14543 (org-call-with-arg 'org-todo 'previousset))
14544 (org-support-shift-select
14545 (org-call-for-shift-select 'backward-word))
14546 (t (org-shiftselect-error))))
14548 (defun org-ctrl-c-ret ()
14549 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
14550 (interactive)
14551 (cond
14552 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
14553 (t (call-interactively 'org-insert-heading))))
14555 (defun org-copy-special ()
14556 "Copy region in table or copy current subtree.
14557 Calls `org-table-copy' or `org-copy-subtree', depending on context.
14558 See the individual commands for more information."
14559 (interactive)
14560 (call-interactively
14561 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
14563 (defun org-cut-special ()
14564 "Cut region in table or cut current subtree.
14565 Calls `org-table-copy' or `org-cut-subtree', depending on context.
14566 See the individual commands for more information."
14567 (interactive)
14568 (call-interactively
14569 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
14571 (defun org-paste-special (arg)
14572 "Paste rectangular region into table, or past subtree relative to level.
14573 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
14574 See the individual commands for more information."
14575 (interactive "P")
14576 (if (org-at-table-p)
14577 (org-table-paste-rectangle)
14578 (org-paste-subtree arg)))
14580 (defun org-edit-special ()
14581 "Call a special editor for the stuff at point.
14582 When at a table, call the formula editor with `org-table-edit-formulas'.
14583 When at the first line of an src example, call `org-edit-src-code'.
14584 When in an #+include line, visit the include file. Otherwise call
14585 `ffap' to visit the file at point."
14586 (interactive)
14587 (cond
14588 ((org-at-table-p)
14589 (call-interactively 'org-table-edit-formulas))
14590 ((save-excursion
14591 (beginning-of-line 1)
14592 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
14593 (find-file (org-trim (match-string 1))))
14594 ((org-edit-src-code))
14595 ((org-edit-fixed-width-region))
14596 (t (call-interactively 'ffap))))
14599 (defun org-ctrl-c-ctrl-c (&optional arg)
14600 "Set tags in headline, or update according to changed information at point.
14602 This command does many different things, depending on context:
14604 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
14605 this is what we do.
14607 - If the cursor is in a headline, prompt for tags and insert them
14608 into the current line, aligned to `org-tags-column'. When called
14609 with prefix arg, realign all tags in the current buffer.
14611 - If the cursor is in one of the special #+KEYWORD lines, this
14612 triggers scanning the buffer for these lines and updating the
14613 information.
14615 - If the cursor is inside a table, realign the table. This command
14616 works even if the automatic table editor has been turned off.
14618 - If the cursor is on a #+TBLFM line, re-apply the formulas to
14619 the entire table.
14621 - If the cursor is at a footnote reference or definition, jump to
14622 the corresponding definition or references, respectively.
14624 - If the cursor is a the beginning of a dynamic block, update it.
14626 - If the cursor is inside a table created by the table.el package,
14627 activate that table.
14629 - If the current buffer is a remember buffer, close note and file
14630 it. A prefix argument of 1 files to the default location
14631 without further interaction. A prefix argument of 2 files to
14632 the currently clocking task.
14634 - If the cursor is on a <<<target>>>, update radio targets and corresponding
14635 links in this buffer.
14637 - If the cursor is on a numbered item in a plain list, renumber the
14638 ordered list.
14640 - If the cursor is on a checkbox, toggle it."
14641 (interactive "P")
14642 (let ((org-enable-table-editor t))
14643 (cond
14644 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
14645 org-occur-highlights
14646 org-latex-fragment-image-overlays)
14647 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
14648 (org-remove-occur-highlights)
14649 (org-remove-latex-fragment-image-overlays)
14650 (message "Temporary highlights/overlays removed from current buffer"))
14651 ((and (local-variable-p 'org-finish-function (current-buffer))
14652 (fboundp org-finish-function))
14653 (funcall org-finish-function))
14654 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
14655 ((org-at-property-p)
14656 (call-interactively 'org-property-action))
14657 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
14658 ((org-on-heading-p) (call-interactively 'org-set-tags))
14659 ((org-at-table.el-p)
14660 (require 'table)
14661 (beginning-of-line 1)
14662 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
14663 (call-interactively 'table-recognize-table))
14664 ((org-at-table-p)
14665 (org-table-maybe-eval-formula)
14666 (if arg
14667 (call-interactively 'org-table-recalculate)
14668 (org-table-maybe-recalculate-line))
14669 (call-interactively 'org-table-align))
14670 ((or (org-footnote-at-reference-p)
14671 (org-footnote-at-definition-p))
14672 (call-interactively 'org-footnote-action))
14673 ((org-at-item-checkbox-p)
14674 (call-interactively 'org-toggle-checkbox))
14675 ((org-at-item-p)
14676 (if arg
14677 (call-interactively 'org-toggle-checkbox)
14678 (call-interactively 'org-maybe-renumber-ordered-list)))
14679 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
14680 ;; Dynamic block
14681 (beginning-of-line 1)
14682 (save-excursion (org-update-dblock)))
14683 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
14684 (cond
14685 ((equal (match-string 1) "TBLFM")
14686 ;; Recalculate the table before this line
14687 (save-excursion
14688 (beginning-of-line 1)
14689 (skip-chars-backward " \r\n\t")
14690 (if (org-at-table-p)
14691 (org-call-with-arg 'org-table-recalculate t))))
14693 ; (org-set-regexps-and-options)
14694 ; (org-restart-font-lock)
14695 (let ((org-inhibit-startup t)) (org-mode-restart))
14696 (message "Local setup has been refreshed"))))
14697 (t (error "C-c C-c can do nothing useful at this location.")))))
14699 (defun org-mode-restart ()
14700 "Restart Org-mode, to scan again for special lines.
14701 Also updates the keyword regular expressions."
14702 (interactive)
14703 (org-mode)
14704 (message "Org-mode restarted"))
14706 (defun org-kill-note-or-show-branches ()
14707 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
14708 (interactive)
14709 (if (not org-finish-function)
14710 (call-interactively 'show-branches)
14711 (let ((org-note-abort t))
14712 (funcall org-finish-function))))
14714 (defun org-return (&optional indent)
14715 "Goto next table row or insert a newline.
14716 Calls `org-table-next-row' or `newline', depending on context.
14717 See the individual commands for more information."
14718 (interactive)
14719 (cond
14720 ((bobp) (if indent (newline-and-indent) (newline)))
14721 ((org-at-table-p)
14722 (org-table-justify-field-maybe)
14723 (call-interactively 'org-table-next-row))
14724 ((and org-return-follows-link
14725 (eq (get-text-property (point) 'face) 'org-link))
14726 (call-interactively 'org-open-at-point))
14727 ((and (org-at-heading-p)
14728 (looking-at
14729 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
14730 (org-show-entry)
14731 (end-of-line 1)
14732 (newline))
14733 (t (if indent (newline-and-indent) (newline)))))
14735 (defun org-return-indent ()
14736 "Goto next table row or insert a newline and indent.
14737 Calls `org-table-next-row' or `newline-and-indent', depending on
14738 context. See the individual commands for more information."
14739 (interactive)
14740 (org-return t))
14742 (defun org-ctrl-c-star ()
14743 "Compute table, or change heading status of lines.
14744 Calls `org-table-recalculate' or `org-toggle-heading',
14745 depending on context."
14746 (interactive)
14747 (cond
14748 ((org-at-table-p)
14749 (call-interactively 'org-table-recalculate))
14751 ;; Convert all lines in region to list items
14752 (call-interactively 'org-toggle-heading))))
14754 (defun org-ctrl-c-minus ()
14755 "Insert separator line in table or modify bullet status of line.
14756 Also turns a plain line or a region of lines into list items.
14757 Calls `org-table-insert-hline', `org-toggle-item', or
14758 `org-cycle-list-bullet', depending on context."
14759 (interactive)
14760 (cond
14761 ((org-at-table-p)
14762 (call-interactively 'org-table-insert-hline))
14763 ((org-region-active-p)
14764 (call-interactively 'org-toggle-item))
14765 ((org-in-item-p)
14766 (call-interactively 'org-cycle-list-bullet))
14768 (call-interactively 'org-toggle-item))))
14770 (defun org-toggle-item ()
14771 "Convert headings or normal lines to items, items to normal lines.
14772 If there is no active region, only the current line is considered.
14774 If the first line in the region is a headline, convert all headlines to items.
14776 If the first line in the region is an item, convert all items to normal lines.
14778 If the first line is normal text, add an item bullet to each line."
14779 (interactive)
14780 (let (l2 l beg end)
14781 (if (org-region-active-p)
14782 (setq beg (region-beginning) end (region-end))
14783 (setq beg (point-at-bol)
14784 end (min (1+ (point-at-eol)) (point-max))))
14785 (save-excursion
14786 (goto-char end)
14787 (setq l2 (org-current-line))
14788 (goto-char beg)
14789 (beginning-of-line 1)
14790 (setq l (1- (org-current-line)))
14791 (if (org-at-item-p)
14792 ;; We already have items, de-itemize
14793 (while (< (setq l (1+ l)) l2)
14794 (when (org-at-item-p)
14795 (goto-char (match-beginning 2))
14796 (delete-region (match-beginning 2) (match-end 2))
14797 (and (looking-at "[ \t]+") (replace-match "")))
14798 (beginning-of-line 2))
14799 (if (org-on-heading-p)
14800 ;; Headings, convert to items
14801 (while (< (setq l (1+ l)) l2)
14802 (if (looking-at org-outline-regexp)
14803 (replace-match "- " t t))
14804 (beginning-of-line 2))
14805 ;; normal lines, turn them into items
14806 (while (< (setq l (1+ l)) l2)
14807 (unless (org-at-item-p)
14808 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14809 (replace-match "\\1- \\2")))
14810 (beginning-of-line 2)))))))
14812 (defun org-toggle-heading (&optional nstars)
14813 "Convert headings to normal text, or items or text to headings.
14814 If there is no active region, only the current line is considered.
14816 If the first line is a heading, remove the stars from all headlines
14817 in the region.
14819 If the first line is a plain list item, turn all plain list items into
14820 headings.
14822 If the first line is a normal line, turn each and every line in the region
14823 into a heading.
14825 When converting a line into a heading, the number of stars is chosen
14826 such that the lines become children of the current entry. However, when
14827 a prefix argument is given, its value determines the number of stars to add."
14828 (interactive "P")
14829 (let (l2 l itemp beg end)
14830 (if (org-region-active-p)
14831 (setq beg (region-beginning) end (region-end))
14832 (setq beg (point-at-bol)
14833 end (min (1+ (point-at-eol)) (point-max))))
14834 (save-excursion
14835 (goto-char end)
14836 (setq l2 (org-current-line))
14837 (goto-char beg)
14838 (beginning-of-line 1)
14839 (setq l (1- (org-current-line)))
14840 (if (org-on-heading-p)
14841 ;; We already have headlines, de-star them
14842 (while (< (setq l (1+ l)) l2)
14843 (when (org-on-heading-p t)
14844 (and (looking-at outline-regexp) (replace-match "")))
14845 (beginning-of-line 2))
14846 (setq itemp (org-at-item-p))
14847 (let* ((stars
14848 (if nstars
14849 (make-string (prefix-numeric-value current-prefix-arg)
14851 (save-excursion
14852 (re-search-backward org-complex-heading-regexp nil t)
14853 (or (match-string 1) ""))))
14854 (add-stars (cond (nstars "")
14855 ((equal stars "") "*")
14856 (org-odd-levels-only "**")
14857 (t "*")))
14858 (rpl (concat stars add-stars " ")))
14859 (while (< (setq l (1+ l)) l2)
14860 (if itemp
14861 (and (org-at-item-p) (replace-match rpl t t))
14862 (unless (org-on-heading-p)
14863 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14864 (replace-match (concat rpl (match-string 2))))))
14865 (beginning-of-line 2)))))))
14867 (defun org-meta-return (&optional arg)
14868 "Insert a new heading or wrap a region in a table.
14869 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
14870 See the individual commands for more information."
14871 (interactive "P")
14872 (cond
14873 ((run-hook-with-args-until-success 'org-metareturn-hook))
14874 ((org-at-table-p)
14875 (call-interactively 'org-table-wrap-region))
14876 (t (call-interactively 'org-insert-heading))))
14878 ;;; Menu entries
14880 ;; Define the Org-mode menus
14881 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
14882 '("Tbl"
14883 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
14884 ["Next Field" org-cycle (org-at-table-p)]
14885 ["Previous Field" org-shifttab (org-at-table-p)]
14886 ["Next Row" org-return (org-at-table-p)]
14887 "--"
14888 ["Blank Field" org-table-blank-field (org-at-table-p)]
14889 ["Edit Field" org-table-edit-field (org-at-table-p)]
14890 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
14891 "--"
14892 ("Column"
14893 ["Move Column Left" org-metaleft (org-at-table-p)]
14894 ["Move Column Right" org-metaright (org-at-table-p)]
14895 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
14896 ["Insert Column" org-shiftmetaright (org-at-table-p)])
14897 ("Row"
14898 ["Move Row Up" org-metaup (org-at-table-p)]
14899 ["Move Row Down" org-metadown (org-at-table-p)]
14900 ["Delete Row" org-shiftmetaup (org-at-table-p)]
14901 ["Insert Row" org-shiftmetadown (org-at-table-p)]
14902 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
14903 "--"
14904 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
14905 ("Rectangle"
14906 ["Copy Rectangle" org-copy-special (org-at-table-p)]
14907 ["Cut Rectangle" org-cut-special (org-at-table-p)]
14908 ["Paste Rectangle" org-paste-special (org-at-table-p)]
14909 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
14910 "--"
14911 ("Calculate"
14912 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
14913 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
14914 ["Edit Formulas" org-edit-special (org-at-table-p)]
14915 "--"
14916 ["Recalculate line" org-table-recalculate (org-at-table-p)]
14917 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
14918 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
14919 "--"
14920 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
14921 "--"
14922 ["Sum Column/Rectangle" org-table-sum
14923 (or (org-at-table-p) (org-region-active-p))]
14924 ["Which Column?" org-table-current-column (org-at-table-p)])
14925 ["Debug Formulas"
14926 org-table-toggle-formula-debugger
14927 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
14928 ["Show Col/Row Numbers"
14929 org-table-toggle-coordinate-overlays
14930 :style toggle
14931 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
14932 "--"
14933 ["Create" org-table-create (and (not (org-at-table-p))
14934 org-enable-table-editor)]
14935 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
14936 ["Import from File" org-table-import (not (org-at-table-p))]
14937 ["Export to File" org-table-export (org-at-table-p)]
14938 "--"
14939 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
14941 (easy-menu-define org-org-menu org-mode-map "Org menu"
14942 '("Org"
14943 ("Show/Hide"
14944 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
14945 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
14946 ["Sparse Tree..." org-sparse-tree t]
14947 ["Reveal Context" org-reveal t]
14948 ["Show All" show-all t]
14949 "--"
14950 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
14951 "--"
14952 ["New Heading" org-insert-heading t]
14953 ("Navigate Headings"
14954 ["Up" outline-up-heading t]
14955 ["Next" outline-next-visible-heading t]
14956 ["Previous" outline-previous-visible-heading t]
14957 ["Next Same Level" outline-forward-same-level t]
14958 ["Previous Same Level" outline-backward-same-level t]
14959 "--"
14960 ["Jump" org-goto t])
14961 ("Edit Structure"
14962 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
14963 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
14964 "--"
14965 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
14966 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
14967 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
14968 "--"
14969 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
14970 "--"
14971 ["Promote Heading" org-metaleft (not (org-at-table-p))]
14972 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
14973 ["Demote Heading" org-metaright (not (org-at-table-p))]
14974 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
14975 "--"
14976 ["Sort Region/Children" org-sort (not (org-at-table-p))]
14977 "--"
14978 ["Convert to odd levels" org-convert-to-odd-levels t]
14979 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
14980 ("Editing"
14981 ["Emphasis..." org-emphasize t]
14982 ["Edit Source Example" org-edit-special t]
14983 "--"
14984 ["Footnote new/jump" org-footnote-action t]
14985 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
14986 ("Archive"
14987 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
14988 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
14989 ; :active t :keys "C-u C-c C-x C-a"]
14990 ["Sparse trees open ARCHIVE trees"
14991 (setq org-sparse-tree-open-archived-trees
14992 (not org-sparse-tree-open-archived-trees))
14993 :style toggle :selected org-sparse-tree-open-archived-trees]
14994 ["Cycling opens ARCHIVE trees"
14995 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
14996 :style toggle :selected org-cycle-open-archived-trees]
14997 "--"
14998 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
14999 ["Move Subtree to Archive" org-advertized-archive-subtree t]
15000 ; ["Check and Move Children" (org-archive-subtree '(4))
15001 ; :active t :keys "C-u C-c C-x C-s"]
15003 "--"
15004 ("Hyperlinks"
15005 ["Store Link (Global)" org-store-link t]
15006 ["Insert Link" org-insert-link t]
15007 ["Follow Link" org-open-at-point t]
15008 "--"
15009 ["Next link" org-next-link t]
15010 ["Previous link" org-previous-link t]
15011 "--"
15012 ["Descriptive Links"
15013 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
15014 :style radio
15015 :selected (member '(org-link) buffer-invisibility-spec)]
15016 ["Literal Links"
15017 (progn
15018 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
15019 :style radio
15020 :selected (not (member '(org-link) buffer-invisibility-spec))])
15021 "--"
15022 ("TODO Lists"
15023 ["TODO/DONE/-" org-todo t]
15024 ("Select keyword"
15025 ["Next keyword" org-shiftright (org-on-heading-p)]
15026 ["Previous keyword" org-shiftleft (org-on-heading-p)]
15027 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
15028 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
15029 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
15030 ["Show TODO Tree" org-show-todo-tree t]
15031 ["Global TODO list" org-todo-list t]
15032 "--"
15033 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
15034 :selected org-enforce-todo-dependencies :style toggle :active t]
15035 "Settings for tree at point"
15036 ["Do Children sequentially" org-toggle-ordered-property :style radio
15037 :selected (ignore-errors (org-entry-get nil "ORDERED"))
15038 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15039 ["Do Children parallel" org-toggle-ordered-property :style radio
15040 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
15041 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15042 "--"
15043 ["Set Priority" org-priority t]
15044 ["Priority Up" org-shiftup t]
15045 ["Priority Down" org-shiftdown t]
15046 "--"
15047 ["Get news from all feeds" org-feed-update-all t]
15048 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
15049 ["Customize feeds" (customize-variable 'org-feed-alist) t])
15050 ("TAGS and Properties"
15051 ["Set Tags" org-set-tags-command t]
15052 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
15053 "--"
15054 ["Set property" org-set-property t]
15055 ["Column view of properties" org-columns t]
15056 ["Insert Column View DBlock" org-insert-columns-dblock t])
15057 ("Dates and Scheduling"
15058 ["Timestamp" org-time-stamp t]
15059 ["Timestamp (inactive)" org-time-stamp-inactive t]
15060 ("Change Date"
15061 ["1 Day Later" org-shiftright t]
15062 ["1 Day Earlier" org-shiftleft t]
15063 ["1 ... Later" org-shiftup t]
15064 ["1 ... Earlier" org-shiftdown t])
15065 ["Compute Time Range" org-evaluate-time-range t]
15066 ["Schedule Item" org-schedule t]
15067 ["Deadline" org-deadline t]
15068 "--"
15069 ["Custom time format" org-toggle-time-stamp-overlays
15070 :style radio :selected org-display-custom-times]
15071 "--"
15072 ["Goto Calendar" org-goto-calendar t]
15073 ["Date from Calendar" org-date-from-calendar t]
15074 "--"
15075 ["Start/Restart Timer" org-timer-start t]
15076 ["Pause/Continue Timer" org-timer-pause-or-continue t]
15077 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
15078 ["Insert Timer String" org-timer t]
15079 ["Insert Timer Item" org-timer-item t])
15080 ("Logging work"
15081 ["Clock in" org-clock-in t]
15082 ["Clock out" org-clock-out t]
15083 ["Clock cancel" org-clock-cancel t]
15084 ["Goto running clock" org-clock-goto t]
15085 ["Display times" org-clock-display t]
15086 ["Create clock table" org-clock-report t]
15087 "--"
15088 ["Record DONE time"
15089 (progn (setq org-log-done (not org-log-done))
15090 (message "Switching to %s will %s record a timestamp"
15091 (car org-done-keywords)
15092 (if org-log-done "automatically" "not")))
15093 :style toggle :selected org-log-done])
15094 "--"
15095 ["Agenda Command..." org-agenda t]
15096 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
15097 ("File List for Agenda")
15098 ("Special views current file"
15099 ["TODO Tree" org-show-todo-tree t]
15100 ["Check Deadlines" org-check-deadlines t]
15101 ["Timeline" org-timeline t]
15102 ["Tags/Property tree" org-match-sparse-tree t])
15103 "--"
15104 ["Export/Publish..." org-export t]
15105 ("LaTeX"
15106 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
15107 :selected org-cdlatex-mode]
15108 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
15109 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
15110 ["Modify math symbol" org-cdlatex-math-modify
15111 (org-inside-LaTeX-fragment-p)]
15112 ["Insert citation" org-reftex-citation t]
15113 "--"
15114 ["Export LaTeX fragments as images"
15115 (if (featurep 'org-exp)
15116 (setq org-export-with-LaTeX-fragments
15117 (not org-export-with-LaTeX-fragments))
15118 (require 'org-exp))
15119 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
15120 org-export-with-LaTeX-fragments)])
15121 "--"
15122 ("Documentation"
15123 ["Show Version" org-version t]
15124 ["Info Documentation" org-info t])
15125 ("Customize"
15126 ["Browse Org Group" org-customize t]
15127 "--"
15128 ["Expand This Menu" org-create-customize-menu
15129 (fboundp 'customize-menu-create)])
15130 "--"
15131 ("Refresh/Reload"
15132 ["Refresh setup current buffer" org-mode-restart t]
15133 ["Reload Org (after update)" org-reload t]
15134 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
15137 (defun org-info (&optional node)
15138 "Read documentation for Org-mode in the info system.
15139 With optional NODE, go directly to that node."
15140 (interactive)
15141 (info (format "(org)%s" (or node ""))))
15143 (defun org-install-agenda-files-menu ()
15144 (let ((bl (buffer-list)))
15145 (save-excursion
15146 (while bl
15147 (set-buffer (pop bl))
15148 (if (org-mode-p) (setq bl nil)))
15149 (when (org-mode-p)
15150 (easy-menu-change
15151 '("Org") "File List for Agenda"
15152 (append
15153 (list
15154 ["Edit File List" (org-edit-agenda-file-list) t]
15155 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
15156 ["Remove Current File from List" org-remove-file t]
15157 ["Cycle through agenda files" org-cycle-agenda-files t]
15158 ["Occur in all agenda files" org-occur-in-agenda-files t]
15159 "--")
15160 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
15162 ;;;; Documentation
15164 ;;;###autoload
15165 (defun org-require-autoloaded-modules ()
15166 (interactive)
15167 (mapc 'require
15168 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
15169 org-docbook org-exp org-html org-icalendar
15170 org-id org-latex
15171 org-publish org-remember org-table
15172 org-timer org-xoxo)))
15174 ;;;###autoload
15175 (defun org-reload (&optional uncompiled)
15176 "Reload all org lisp files.
15177 With prefix arg UNCOMPILED, load the uncompiled versions."
15178 (interactive "P")
15179 (require 'find-func)
15180 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
15181 (dir-org (file-name-directory (org-find-library-name "org")))
15182 (dir-org-contrib (ignore-errors
15183 (file-name-directory
15184 (org-find-library-name "org-contribdir"))))
15185 (files
15186 (append (directory-files dir-org t file-re)
15187 (and dir-org-contrib
15188 (directory-files dir-org-contrib t file-re))))
15189 (remove-re (concat (if (featurep 'xemacs)
15190 "org-colview" "org-colview-xemacs")
15191 "\\'")))
15192 (setq files (mapcar 'file-name-sans-extension files))
15193 (setq files (mapcar
15194 (lambda (x) (if (string-match remove-re x) nil x))
15195 files))
15196 (setq files (delq nil files))
15197 (mapc
15198 (lambda (f)
15199 (when (featurep (intern (file-name-nondirectory f)))
15200 (if (and (not uncompiled)
15201 (file-exists-p (concat f ".elc")))
15202 (load (concat f ".elc") nil nil t)
15203 (load (concat f ".el") nil nil t))))
15204 files))
15205 (org-version))
15207 ;;;###autoload
15208 (defun org-customize ()
15209 "Call the customize function with org as argument."
15210 (interactive)
15211 (org-load-modules-maybe)
15212 (org-require-autoloaded-modules)
15213 (customize-browse 'org))
15215 (defun org-create-customize-menu ()
15216 "Create a full customization menu for Org-mode, insert it into the menu."
15217 (interactive)
15218 (org-load-modules-maybe)
15219 (org-require-autoloaded-modules)
15220 (if (fboundp 'customize-menu-create)
15221 (progn
15222 (easy-menu-change
15223 '("Org") "Customize"
15224 `(["Browse Org group" org-customize t]
15225 "--"
15226 ,(customize-menu-create 'org)
15227 ["Set" Custom-set t]
15228 ["Save" Custom-save t]
15229 ["Reset to Current" Custom-reset-current t]
15230 ["Reset to Saved" Custom-reset-saved t]
15231 ["Reset to Standard Settings" Custom-reset-standard t]))
15232 (message "\"Org\"-menu now contains full customization menu"))
15233 (error "Cannot expand menu (outdated version of cus-edit.el)")))
15235 ;;;; Miscellaneous stuff
15237 ;;; Generally useful functions
15239 (defun org-find-text-property-in-string (prop s)
15240 "Return the first non-nil value of property PROP in string S."
15241 (or (get-text-property 0 prop s)
15242 (get-text-property (or (next-single-property-change 0 prop s) 0)
15243 prop s)))
15245 (defun org-display-warning (message) ;; Copied from Emacs-Muse
15246 "Display the given MESSAGE as a warning."
15247 (if (fboundp 'display-warning)
15248 (display-warning 'org message
15249 (if (featurep 'xemacs)
15250 'warning
15251 :warning))
15252 (let ((buf (get-buffer-create "*Org warnings*")))
15253 (with-current-buffer buf
15254 (goto-char (point-max))
15255 (insert "Warning (Org): " message)
15256 (unless (bolp)
15257 (newline)))
15258 (display-buffer buf)
15259 (sit-for 0))))
15261 (defun org-goto-marker-or-bmk (marker &optional bookmark)
15262 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
15263 (if (and marker (marker-buffer marker)
15264 (buffer-live-p (marker-buffer marker)))
15265 (progn
15266 (switch-to-buffer (marker-buffer marker))
15267 (if (or (> marker (point-max)) (< marker (point-min)))
15268 (widen))
15269 (goto-char marker)
15270 (org-show-context 'org-goto))
15271 (if bookmark
15272 (bookmark-jump bookmark)
15273 (error "Cannot find location"))))
15275 (defun org-quote-csv-field (s)
15276 "Quote field for inclusion in CSV material."
15277 (if (string-match "[\",]" s)
15278 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
15281 (defun org-plist-delete (plist property)
15282 "Delete PROPERTY from PLIST.
15283 This is in contrast to merely setting it to 0."
15284 (let (p)
15285 (while plist
15286 (if (not (eq property (car plist)))
15287 (setq p (plist-put p (car plist) (nth 1 plist))))
15288 (setq plist (cddr plist)))
15291 (defun org-force-self-insert (N)
15292 "Needed to enforce self-insert under remapping."
15293 (interactive "p")
15294 (self-insert-command N))
15296 (defun org-string-width (s)
15297 "Compute width of string, ignoring invisible characters.
15298 This ignores character with invisibility property `org-link', and also
15299 characters with property `org-cwidth', because these will become invisible
15300 upon the next fontification round."
15301 (let (b l)
15302 (when (or (eq t buffer-invisibility-spec)
15303 (assq 'org-link buffer-invisibility-spec))
15304 (while (setq b (text-property-any 0 (length s)
15305 'invisible 'org-link s))
15306 (setq s (concat (substring s 0 b)
15307 (substring s (or (next-single-property-change
15308 b 'invisible s) (length s)))))))
15309 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
15310 (setq s (concat (substring s 0 b)
15311 (substring s (or (next-single-property-change
15312 b 'org-cwidth s) (length s))))))
15313 (setq l (string-width s) b -1)
15314 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
15315 (setq l (- l (get-text-property b 'org-dwidth-n s))))
15318 (defun org-get-indentation (&optional line)
15319 "Get the indentation of the current line, interpreting tabs.
15320 When LINE is given, assume it represents a line and compute its indentation."
15321 (if line
15322 (if (string-match "^ *" (org-remove-tabs line))
15323 (match-end 0))
15324 (save-excursion
15325 (beginning-of-line 1)
15326 (skip-chars-forward " \t")
15327 (current-column))))
15329 (defun org-remove-tabs (s &optional width)
15330 "Replace tabulators in S with spaces.
15331 Assumes that s is a single line, starting in column 0."
15332 (setq width (or width tab-width))
15333 (while (string-match "\t" s)
15334 (setq s (replace-match
15335 (make-string
15336 (- (* width (/ (+ (match-beginning 0) width) width))
15337 (match-beginning 0)) ?\ )
15338 t t s)))
15341 (defun org-fix-indentation (line ind)
15342 "Fix indentation in LINE.
15343 IND is a cons cell with target and minimum indentation.
15344 If the current indentation in LINE is smaller than the minimum,
15345 leave it alone. If it is larger than ind, set it to the target."
15346 (let* ((l (org-remove-tabs line))
15347 (i (org-get-indentation l))
15348 (i1 (car ind)) (i2 (cdr ind)))
15349 (if (>= i i2) (setq l (substring line i2)))
15350 (if (> i1 0)
15351 (concat (make-string i1 ?\ ) l)
15352 l)))
15354 (defun org-base-buffer (buffer)
15355 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
15356 (if (not buffer)
15357 buffer
15358 (or (buffer-base-buffer buffer)
15359 buffer)))
15361 (defun org-trim (s)
15362 "Remove whitespace at beginning and end of string."
15363 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
15364 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
15367 (defun org-wrap (string &optional width lines)
15368 "Wrap string to either a number of lines, or a width in characters.
15369 If WIDTH is non-nil, the string is wrapped to that width, however many lines
15370 that costs. If there is a word longer than WIDTH, the text is actually
15371 wrapped to the length of that word.
15372 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
15373 many lines, whatever width that takes.
15374 The return value is a list of lines, without newlines at the end."
15375 (let* ((words (org-split-string string "[ \t\n]+"))
15376 (maxword (apply 'max (mapcar 'org-string-width words)))
15377 w ll)
15378 (cond (width
15379 (org-do-wrap words (max maxword width)))
15380 (lines
15381 (setq w maxword)
15382 (setq ll (org-do-wrap words maxword))
15383 (if (<= (length ll) lines)
15385 (setq ll words)
15386 (while (> (length ll) lines)
15387 (setq w (1+ w))
15388 (setq ll (org-do-wrap words w)))
15389 ll))
15390 (t (error "Cannot wrap this")))))
15392 (defun org-do-wrap (words width)
15393 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
15394 (let (lines line)
15395 (while words
15396 (setq line (pop words))
15397 (while (and words (< (+ (length line) (length (car words))) width))
15398 (setq line (concat line " " (pop words))))
15399 (setq lines (push line lines)))
15400 (nreverse lines)))
15402 (defun org-split-string (string &optional separators)
15403 "Splits STRING into substrings at SEPARATORS.
15404 No empty strings are returned if there are matches at the beginning
15405 and end of string."
15406 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
15407 (start 0)
15408 notfirst
15409 (list nil))
15410 (while (and (string-match rexp string
15411 (if (and notfirst
15412 (= start (match-beginning 0))
15413 (< start (length string)))
15414 (1+ start) start))
15415 (< (match-beginning 0) (length string)))
15416 (setq notfirst t)
15417 (or (eq (match-beginning 0) 0)
15418 (and (eq (match-beginning 0) (match-end 0))
15419 (eq (match-beginning 0) start))
15420 (setq list
15421 (cons (substring string start (match-beginning 0))
15422 list)))
15423 (setq start (match-end 0)))
15424 (or (eq start (length string))
15425 (setq list
15426 (cons (substring string start)
15427 list)))
15428 (nreverse list)))
15430 (defun org-uuidgen-p (s)
15431 "Is S an ID created by UUIDGEN?"
15432 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
15434 (defun org-context ()
15435 "Return a list of contexts of the current cursor position.
15436 If several contexts apply, all are returned.
15437 Each context entry is a list with a symbol naming the context, and
15438 two positions indicating start and end of the context. Possible
15439 contexts are:
15441 :headline anywhere in a headline
15442 :headline-stars on the leading stars in a headline
15443 :todo-keyword on a TODO keyword (including DONE) in a headline
15444 :tags on the TAGS in a headline
15445 :priority on the priority cookie in a headline
15446 :item on the first line of a plain list item
15447 :item-bullet on the bullet/number of a plain list item
15448 :checkbox on the checkbox in a plain list item
15449 :table in an org-mode table
15450 :table-special on a special filed in a table
15451 :table-table in a table.el table
15452 :link on a hyperlink
15453 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
15454 :target on a <<target>>
15455 :radio-target on a <<<radio-target>>>
15456 :latex-fragment on a LaTeX fragment
15457 :latex-preview on a LaTeX fragment with overlayed preview image
15459 This function expects the position to be visible because it uses font-lock
15460 faces as a help to recognize the following contexts: :table-special, :link,
15461 and :keyword."
15462 (let* ((f (get-text-property (point) 'face))
15463 (faces (if (listp f) f (list f)))
15464 (p (point)) clist o)
15465 ;; First the large context
15466 (cond
15467 ((org-on-heading-p t)
15468 (push (list :headline (point-at-bol) (point-at-eol)) clist)
15469 (when (progn
15470 (beginning-of-line 1)
15471 (looking-at org-todo-line-tags-regexp))
15472 (push (org-point-in-group p 1 :headline-stars) clist)
15473 (push (org-point-in-group p 2 :todo-keyword) clist)
15474 (push (org-point-in-group p 4 :tags) clist))
15475 (goto-char p)
15476 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
15477 (if (looking-at "\\[#[A-Z0-9]\\]")
15478 (push (org-point-in-group p 0 :priority) clist)))
15480 ((org-at-item-p)
15481 (push (org-point-in-group p 2 :item-bullet) clist)
15482 (push (list :item (point-at-bol)
15483 (save-excursion (org-end-of-item) (point)))
15484 clist)
15485 (and (org-at-item-checkbox-p)
15486 (push (org-point-in-group p 0 :checkbox) clist)))
15488 ((org-at-table-p)
15489 (push (list :table (org-table-begin) (org-table-end)) clist)
15490 (if (memq 'org-formula faces)
15491 (push (list :table-special
15492 (previous-single-property-change p 'face)
15493 (next-single-property-change p 'face)) clist)))
15494 ((org-at-table-p 'any)
15495 (push (list :table-table) clist)))
15496 (goto-char p)
15498 ;; Now the small context
15499 (cond
15500 ((org-at-timestamp-p)
15501 (push (org-point-in-group p 0 :timestamp) clist))
15502 ((memq 'org-link faces)
15503 (push (list :link
15504 (previous-single-property-change p 'face)
15505 (next-single-property-change p 'face)) clist))
15506 ((memq 'org-special-keyword faces)
15507 (push (list :keyword
15508 (previous-single-property-change p 'face)
15509 (next-single-property-change p 'face)) clist))
15510 ((org-on-target-p)
15511 (push (org-point-in-group p 0 :target) clist)
15512 (goto-char (1- (match-beginning 0)))
15513 (if (looking-at org-radio-target-regexp)
15514 (push (org-point-in-group p 0 :radio-target) clist))
15515 (goto-char p))
15516 ((setq o (car (delq nil
15517 (mapcar
15518 (lambda (x)
15519 (if (memq x org-latex-fragment-image-overlays) x))
15520 (org-overlays-at (point))))))
15521 (push (list :latex-fragment
15522 (org-overlay-start o) (org-overlay-end o)) clist)
15523 (push (list :latex-preview
15524 (org-overlay-start o) (org-overlay-end o)) clist))
15525 ((org-inside-LaTeX-fragment-p)
15526 ;; FIXME: positions wrong.
15527 (push (list :latex-fragment (point) (point)) clist)))
15529 (setq clist (nreverse (delq nil clist)))
15530 clist))
15532 ;; FIXME: Compare with at-regexp-p Do we need both?
15533 (defun org-in-regexp (re &optional nlines visually)
15534 "Check if point is inside a match of regexp.
15535 Normally only the current line is checked, but you can include NLINES extra
15536 lines both before and after point into the search.
15537 If VISUALLY is set, require that the cursor is not after the match but
15538 really on, so that the block visually is on the match."
15539 (catch 'exit
15540 (let ((pos (point))
15541 (eol (point-at-eol (+ 1 (or nlines 0))))
15542 (inc (if visually 1 0)))
15543 (save-excursion
15544 (beginning-of-line (- 1 (or nlines 0)))
15545 (while (re-search-forward re eol t)
15546 (if (and (<= (match-beginning 0) pos)
15547 (>= (+ inc (match-end 0)) pos))
15548 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
15550 (defun org-at-regexp-p (regexp)
15551 "Is point inside a match of REGEXP in the current line?"
15552 (catch 'exit
15553 (save-excursion
15554 (let ((pos (point)) (end (point-at-eol)))
15555 (beginning-of-line 1)
15556 (while (re-search-forward regexp end t)
15557 (if (and (<= (match-beginning 0) pos)
15558 (>= (match-end 0) pos))
15559 (throw 'exit t)))
15560 nil))))
15562 (defun org-occur-in-agenda-files (regexp &optional nlines)
15563 "Call `multi-occur' with buffers for all agenda files."
15564 (interactive "sOrg-files matching: \np")
15565 (let* ((files (org-agenda-files))
15566 (tnames (mapcar 'file-truename files))
15567 (extra org-agenda-text-search-extra-files)
15569 (when (eq (car extra) 'agenda-archives)
15570 (setq extra (cdr extra))
15571 (setq files (org-add-archive-files files)))
15572 (while (setq f (pop extra))
15573 (unless (member (file-truename f) tnames)
15574 (add-to-list 'files f 'append)
15575 (add-to-list 'tnames (file-truename f) 'append)))
15576 (multi-occur
15577 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
15578 regexp)))
15580 (if (boundp 'occur-mode-find-occurrence-hook)
15581 ;; Emacs 23
15582 (add-hook 'occur-mode-find-occurrence-hook
15583 (lambda ()
15584 (when (org-mode-p)
15585 (org-reveal))))
15586 ;; Emacs 22
15587 (defadvice occur-mode-goto-occurrence
15588 (after org-occur-reveal activate)
15589 (and (org-mode-p) (org-reveal)))
15590 (defadvice occur-mode-goto-occurrence-other-window
15591 (after org-occur-reveal activate)
15592 (and (org-mode-p) (org-reveal)))
15593 (defadvice occur-mode-display-occurrence
15594 (after org-occur-reveal activate)
15595 (when (org-mode-p)
15596 (let ((pos (occur-mode-find-occurrence)))
15597 (with-current-buffer (marker-buffer pos)
15598 (save-excursion
15599 (goto-char pos)
15600 (org-reveal)))))))
15602 (defun org-uniquify (list)
15603 "Remove duplicate elements from LIST."
15604 (let (res)
15605 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
15606 res))
15608 (defun org-delete-all (elts list)
15609 "Remove all elements in ELTS from LIST."
15610 (while elts
15611 (setq list (delete (pop elts) list)))
15612 list)
15614 (defun org-back-over-empty-lines ()
15615 "Move backwards over whitespace, to the beginning of the first empty line.
15616 Returns the number of empty lines passed."
15617 (let ((pos (point)))
15618 (skip-chars-backward " \t\n\r")
15619 (beginning-of-line 2)
15620 (goto-char (min (point) pos))
15621 (count-lines (point) pos)))
15623 (defun org-skip-whitespace ()
15624 (skip-chars-forward " \t\n\r"))
15626 (defun org-point-in-group (point group &optional context)
15627 "Check if POINT is in match-group GROUP.
15628 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
15629 match. If the match group does ot exist or point is not inside it,
15630 return nil."
15631 (and (match-beginning group)
15632 (>= point (match-beginning group))
15633 (<= point (match-end group))
15634 (if context
15635 (list context (match-beginning group) (match-end group))
15636 t)))
15638 (defun org-switch-to-buffer-other-window (&rest args)
15639 "Switch to buffer in a second window on the current frame.
15640 In particular, do not allow pop-up frames."
15641 (let (pop-up-frames special-display-buffer-names special-display-regexps
15642 special-display-function)
15643 (apply 'switch-to-buffer-other-window args)))
15645 (defun org-combine-plists (&rest plists)
15646 "Create a single property list from all plists in PLISTS.
15647 The process starts by copying the first list, and then setting properties
15648 from the other lists. Settings in the last list are the most significant
15649 ones and overrule settings in the other lists."
15650 (let ((rtn (copy-sequence (pop plists)))
15651 p v ls)
15652 (while plists
15653 (setq ls (pop plists))
15654 (while ls
15655 (setq p (pop ls) v (pop ls))
15656 (setq rtn (plist-put rtn p v))))
15657 rtn))
15659 (defun org-move-line-down (arg)
15660 "Move the current line down. With prefix argument, move it past ARG lines."
15661 (interactive "p")
15662 (let ((col (current-column))
15663 beg end pos)
15664 (beginning-of-line 1) (setq beg (point))
15665 (beginning-of-line 2) (setq end (point))
15666 (beginning-of-line (+ 1 arg))
15667 (setq pos (move-marker (make-marker) (point)))
15668 (insert (delete-and-extract-region beg end))
15669 (goto-char pos)
15670 (org-move-to-column col)))
15672 (defun org-move-line-up (arg)
15673 "Move the current line up. With prefix argument, move it past ARG lines."
15674 (interactive "p")
15675 (let ((col (current-column))
15676 beg end pos)
15677 (beginning-of-line 1) (setq beg (point))
15678 (beginning-of-line 2) (setq end (point))
15679 (beginning-of-line (- arg))
15680 (setq pos (move-marker (make-marker) (point)))
15681 (insert (delete-and-extract-region beg end))
15682 (goto-char pos)
15683 (org-move-to-column col)))
15685 (defun org-replace-escapes (string table)
15686 "Replace %-escapes in STRING with values in TABLE.
15687 TABLE is an association list with keys like \"%a\" and string values.
15688 The sequences in STRING may contain normal field width and padding information,
15689 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
15690 so values can contain further %-escapes if they are define later in TABLE."
15691 (let ((case-fold-search nil)
15692 e re rpl)
15693 (while (setq e (pop table))
15694 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
15695 (while (string-match re string)
15696 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
15697 (cdr e)))
15698 (setq string (replace-match rpl t t string))))
15699 string))
15702 (defun org-sublist (list start end)
15703 "Return a section of LIST, from START to END.
15704 Counting starts at 1."
15705 (let (rtn (c start))
15706 (setq list (nthcdr (1- start) list))
15707 (while (and list (<= c end))
15708 (push (pop list) rtn)
15709 (setq c (1+ c)))
15710 (nreverse rtn)))
15712 (defun org-find-base-buffer-visiting (file)
15713 "Like `find-buffer-visiting' but always return the base buffer and
15714 not an indirect buffer."
15715 (let ((buf (or (get-file-buffer file)
15716 (find-buffer-visiting file))))
15717 (if buf
15718 (or (buffer-base-buffer buf) buf)
15719 nil)))
15721 (defun org-image-file-name-regexp (&optional extensions)
15722 "Return regexp matching the file names of images.
15723 If EXTENSIONS is given, only match these."
15724 (if (and (not extensions) (fboundp 'image-file-name-regexp))
15725 (image-file-name-regexp)
15726 (let ((image-file-name-extensions
15727 (or extensions
15728 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
15729 "xbm" "xpm" "pbm" "pgm" "ppm"))))
15730 (concat "\\."
15731 (regexp-opt (nconc (mapcar 'upcase
15732 image-file-name-extensions)
15733 image-file-name-extensions)
15735 "\\'"))))
15737 (defun org-file-image-p (file &optional extensions)
15738 "Return non-nil if FILE is an image."
15739 (save-match-data
15740 (string-match (org-image-file-name-regexp extensions) file)))
15742 (defun org-get-cursor-date ()
15743 "Return the date at cursor in as a time.
15744 This works in the calendar and in the agenda, anywhere else it just
15745 returns the current time."
15746 (let (date day defd)
15747 (cond
15748 ((eq major-mode 'calendar-mode)
15749 (setq date (calendar-cursor-to-date)
15750 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15751 ((eq major-mode 'org-agenda-mode)
15752 (setq day (get-text-property (point) 'day))
15753 (if day
15754 (setq date (calendar-gregorian-from-absolute day)
15755 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
15756 (nth 2 date))))))
15757 (or defd (current-time))))
15759 (defvar org-agenda-action-marker (make-marker)
15760 "Marker pointing to the entry for the next agenda action.")
15762 (defun org-mark-entry-for-agenda-action ()
15763 "Mark the current entry as target of an agenda action.
15764 Agenda actions are actions executed from the agenda with the key `k',
15765 which make use of the date at the cursor."
15766 (interactive)
15767 (move-marker org-agenda-action-marker
15768 (save-excursion (org-back-to-heading t) (point))
15769 (current-buffer))
15770 (message
15771 "Entry marked for action; press `k' at desired date in agenda or calendar"))
15773 ;;; Paragraph filling stuff.
15774 ;; We want this to be just right, so use the full arsenal.
15776 (defun org-indent-line-function ()
15777 "Indent line like previous, but further if previous was headline or item."
15778 (interactive)
15779 (let* ((pos (point))
15780 (itemp (org-at-item-p))
15781 (org-drawer-regexp (or org-drawer-regexp "\000"))
15782 column bpos bcol tpos tcol bullet btype bullet-type)
15783 ;; Find the previous relevant line
15784 (beginning-of-line 1)
15785 (cond
15786 ((looking-at "#") (setq column 0))
15787 ((looking-at "\\*+ ") (setq column 0))
15788 ((and (looking-at "[ \t]*:END:")
15789 (save-excursion (re-search-backward org-drawer-regexp nil t)))
15790 (save-excursion
15791 (goto-char (1- (match-beginning 1)))
15792 (setq column (current-column))))
15794 (beginning-of-line 0)
15795 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
15796 (not (looking-at "[ \t]*:END:"))
15797 (not (looking-at org-drawer-regexp)))
15798 (beginning-of-line 0))
15799 (cond
15800 ((looking-at "\\*+[ \t]+")
15801 (if (not org-adapt-indentation)
15802 (setq column 0)
15803 (goto-char (match-end 0))
15804 (setq column (current-column))))
15805 ((looking-at org-drawer-regexp)
15806 (goto-char (1- (match-beginning 1)))
15807 (setq column (current-column)))
15808 ((looking-at "\\([ \t]*\\):END:")
15809 (goto-char (match-end 1))
15810 (setq column (current-column)))
15811 ((org-in-item-p)
15812 (org-beginning-of-item)
15813 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
15814 (setq bpos (match-beginning 1) tpos (match-end 0)
15815 bcol (progn (goto-char bpos) (current-column))
15816 tcol (progn (goto-char tpos) (current-column))
15817 bullet (match-string 1)
15818 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
15819 (if (> tcol (+ bcol org-description-max-indent))
15820 (setq tcol (+ bcol 5)))
15821 (if (not itemp)
15822 (setq column tcol)
15823 (goto-char pos)
15824 (beginning-of-line 1)
15825 (if (looking-at "\\S-")
15826 (progn
15827 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
15828 (setq bullet (match-string 1)
15829 btype (if (string-match "[0-9]" bullet) "n" bullet))
15830 (setq column (if (equal btype bullet-type) bcol tcol)))
15831 (setq column (org-get-indentation)))))
15832 (t (setq column (org-get-indentation))))))
15833 (goto-char pos)
15834 (if (<= (current-column) (current-indentation))
15835 (org-indent-line-to column)
15836 (save-excursion (org-indent-line-to column)))
15837 (setq column (current-column))
15838 (beginning-of-line 1)
15839 (if (looking-at
15840 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
15841 (replace-match (concat "\\1" (format org-property-format
15842 (match-string 2) (match-string 3)))
15843 t nil))
15844 (org-move-to-column column)))
15846 (defun org-set-autofill-regexps ()
15847 (interactive)
15848 ;; In the paragraph separator we include headlines, because filling
15849 ;; text in a line directly attached to a headline would otherwise
15850 ;; fill the headline as well.
15851 (org-set-local 'comment-start-skip "^#+[ \t]*")
15852 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
15853 ;; The paragraph starter includes hand-formatted lists.
15854 (org-set-local 'paragraph-start
15855 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
15856 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
15857 ;; But only if the user has not turned off tables or fixed-width regions
15858 (org-set-local
15859 'auto-fill-inhibit-regexp
15860 (concat "\\*+ \\|#\\+"
15861 "\\|[ \t]*" org-keyword-time-regexp
15862 (if (or org-enable-table-editor org-enable-fixed-width-editor)
15863 (concat
15864 "\\|[ \t]*["
15865 (if org-enable-table-editor "|" "")
15866 (if org-enable-fixed-width-editor ":" "")
15867 "]"))))
15868 ;; We use our own fill-paragraph function, to make sure that tables
15869 ;; and fixed-width regions are not wrapped. That function will pass
15870 ;; through to `fill-paragraph' when appropriate.
15871 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
15872 ; Adaptive filling: To get full control, first make sure that
15873 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
15874 (org-set-local 'adaptive-fill-regexp "\000")
15875 (org-set-local 'adaptive-fill-function
15876 'org-adaptive-fill-function)
15877 (org-set-local
15878 'align-mode-rules-list
15879 '((org-in-buffer-settings
15880 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
15881 (modes . '(org-mode))))))
15883 (defun org-fill-paragraph (&optional justify)
15884 "Re-align a table, pass through to fill-paragraph if no table."
15885 (let ((table-p (org-at-table-p))
15886 (table.el-p (org-at-table.el-p)))
15887 (cond ((and (equal (char-after (point-at-bol)) ?*)
15888 (save-excursion (goto-char (point-at-bol))
15889 (looking-at outline-regexp)))
15890 t) ; skip headlines
15891 (table.el-p t) ; skip table.el tables
15892 (table-p (org-table-align) t) ; align org-mode tables
15893 (t nil)))) ; call paragraph-fill
15895 ;; For reference, this is the default value of adaptive-fill-regexp
15896 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
15898 (defun org-adaptive-fill-function ()
15899 "Return a fill prefix for org-mode files.
15900 In particular, this makes sure hanging paragraphs for hand-formatted lists
15901 work correctly."
15902 (cond ((looking-at "#[ \t]+")
15903 (match-string 0))
15904 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
15905 (save-excursion
15906 (if (> (match-end 1) (+ (match-beginning 1)
15907 org-description-max-indent))
15908 (goto-char (+ (match-beginning 1) 5))
15909 (goto-char (match-end 0)))
15910 (make-string (current-column) ?\ )))
15911 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
15912 (save-excursion
15913 (goto-char (match-end 0))
15914 (make-string (current-column) ?\ )))
15915 (t nil)))
15917 ;;; Other stuff.
15919 (defun org-toggle-fixed-width-section (arg)
15920 "Toggle the fixed-width export.
15921 If there is no active region, the QUOTE keyword at the current headline is
15922 inserted or removed. When present, it causes the text between this headline
15923 and the next to be exported as fixed-width text, and unmodified.
15924 If there is an active region, this command adds or removes a colon as the
15925 first character of this line. If the first character of a line is a colon,
15926 this line is also exported in fixed-width font."
15927 (interactive "P")
15928 (let* ((cc 0)
15929 (regionp (org-region-active-p))
15930 (beg (if regionp (region-beginning) (point)))
15931 (end (if regionp (region-end)))
15932 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
15933 (case-fold-search nil)
15934 (re "[ \t]*\\(: \\)")
15935 off)
15936 (if regionp
15937 (save-excursion
15938 (goto-char beg)
15939 (setq cc (current-column))
15940 (beginning-of-line 1)
15941 (setq off (looking-at re))
15942 (while (> nlines 0)
15943 (setq nlines (1- nlines))
15944 (beginning-of-line 1)
15945 (cond
15946 (arg
15947 (org-move-to-column cc t)
15948 (insert ": \n")
15949 (forward-line -1))
15950 ((and off (looking-at re))
15951 (replace-match "" t t nil 1))
15952 ((not off) (org-move-to-column cc t) (insert ": ")))
15953 (forward-line 1)))
15954 (save-excursion
15955 (org-back-to-heading)
15956 (if (looking-at (concat outline-regexp
15957 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
15958 (replace-match "" t t nil 1)
15959 (if (looking-at outline-regexp)
15960 (progn
15961 (goto-char (match-end 0))
15962 (insert org-quote-string " "))))))))
15964 (defun org-reftex-citation ()
15965 "Use reftex-citation to insert a citation into the buffer.
15966 This looks for a line like
15968 #+BIBLIOGRAPHY: foo plain option:-d
15970 and derives from it that foo.bib is the bbliography file relevant
15971 for this document. It then installs the necessary environment for RefTeX
15972 to work in this buffer and calls `reftex-citation' to insert a citation
15973 into the buffer.
15975 Export of such citations to both LaTeX and HTML is handled by the contributed
15976 package org-exp-bibtex by Taru Karttunen."
15977 (interactive)
15978 (let ((reftex-docstruct-symbol 'rds)
15979 (reftex-cite-format "\\cite{%l}")
15980 rds bib)
15981 (save-excursion
15982 (save-restriction
15983 (widen)
15984 (let ((case-fold-search t)
15985 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
15986 (if (not (save-excursion
15987 (or (re-search-forward re nil t)
15988 (re-search-backward re nil t))))
15989 (error "No bibliography defined in file")
15990 (setq bib (concat (match-string 1) ".bib")
15991 rds (list (list 'bib bib)))))))
15992 (call-interactively 'reftex-citation)))
15994 ;;;; Functions extending outline functionality
15996 (defun org-beginning-of-line (&optional arg)
15997 "Go to the beginning of the current line. If that is invisible, continue
15998 to a visible line beginning. This makes the function of C-a more intuitive.
15999 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16000 first attempt, and only move to after the tags when the cursor is already
16001 beyond the end of the headline."
16002 (interactive "P")
16003 (let ((pos (point))
16004 (special (if (consp org-special-ctrl-a/e)
16005 (car org-special-ctrl-a/e)
16006 org-special-ctrl-a/e))
16007 refpos)
16008 (beginning-of-line 1)
16009 (if (and arg (fboundp 'move-beginning-of-line))
16010 (call-interactively 'move-beginning-of-line)
16011 (if (bobp)
16013 (backward-char 1)
16014 (if (org-invisible-p)
16015 (while (and (not (bobp)) (org-invisible-p))
16016 (backward-char 1)
16017 (beginning-of-line 1))
16018 (forward-char 1))))
16019 (when special
16020 (cond
16021 ((and (looking-at org-complex-heading-regexp)
16022 (= (char-after (match-end 1)) ?\ ))
16023 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
16024 (point-at-eol)))
16025 (goto-char
16026 (if (eq special t)
16027 (cond ((> pos refpos) refpos)
16028 ((= pos (point)) refpos)
16029 (t (point)))
16030 (cond ((> pos (point)) (point))
16031 ((not (eq last-command this-command)) (point))
16032 (t refpos)))))
16033 ((org-at-item-p)
16034 (goto-char
16035 (if (eq special t)
16036 (cond ((> pos (match-end 4)) (match-end 4))
16037 ((= pos (point)) (match-end 4))
16038 (t (point)))
16039 (cond ((> pos (point)) (point))
16040 ((not (eq last-command this-command)) (point))
16041 (t (match-end 4))))))))
16042 (org-no-warnings
16043 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16045 (defun org-end-of-line (&optional arg)
16046 "Go to the end of the line.
16047 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16048 first attempt, and only move to after the tags when the cursor is already
16049 beyond the end of the headline."
16050 (interactive "P")
16051 (let ((special (if (consp org-special-ctrl-a/e)
16052 (cdr org-special-ctrl-a/e)
16053 org-special-ctrl-a/e)))
16054 (if (or (not special)
16055 (not (org-on-heading-p))
16056 arg)
16057 (call-interactively (if (fboundp 'move-end-of-line)
16058 'move-end-of-line
16059 'end-of-line))
16060 (let ((pos (point)))
16061 (beginning-of-line 1)
16062 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
16063 (if (eq special t)
16064 (if (or (< pos (match-beginning 1))
16065 (= pos (match-end 0)))
16066 (goto-char (match-beginning 1))
16067 (goto-char (match-end 0)))
16068 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
16069 (goto-char (match-end 0))
16070 (goto-char (match-beginning 1))))
16071 (call-interactively (if (fboundp 'move-end-of-line)
16072 'move-end-of-line
16073 'end-of-line)))))
16074 (org-no-warnings
16075 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16077 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
16078 (define-key org-mode-map "\C-e" 'org-end-of-line)
16080 (defun org-backward-sentence (&optional arg)
16081 "Go to beginning of sentence, or beginning of table field.
16082 This will call `backward-sentence' or `org-table-beginning-of-field',
16083 depending on context."
16084 (interactive "P")
16085 (cond
16086 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
16087 (t (call-interactively 'backward-sentence))))
16089 (defun org-forward-sentence (&optional arg)
16090 "Go to end of sentence, or end of table field.
16091 This will call `forward-sentence' or `org-table-end-of-field',
16092 depending on context."
16093 (interactive "P")
16094 (cond
16095 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
16096 (t (call-interactively 'forward-sentence))))
16098 (define-key org-mode-map "\M-a" 'org-backward-sentence)
16099 (define-key org-mode-map "\M-e" 'org-forward-sentence)
16101 (defun org-kill-line (&optional arg)
16102 "Kill line, to tags or end of line."
16103 (interactive "P")
16104 (cond
16105 ((or (not org-special-ctrl-k)
16106 (bolp)
16107 (not (org-on-heading-p)))
16108 (call-interactively 'kill-line))
16109 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
16110 (kill-region (point) (match-beginning 1))
16111 (org-set-tags nil t))
16112 (t (kill-region (point) (point-at-eol)))))
16114 (define-key org-mode-map "\C-k" 'org-kill-line)
16116 (defun org-yank (&optional arg)
16117 "Yank. If the kill is a subtree, treat it specially.
16118 This command will look at the current kill and check if is a single
16119 subtree, or a series of subtrees[1]. If it passes the test, and if the
16120 cursor is at the beginning of a line or after the stars of a currently
16121 empty headline, then the yank is handled specially. How exactly depends
16122 on the value of the following variables, both set by default.
16124 org-yank-folded-subtrees
16125 When set, the subtree(s) will be folded after insertion, but only
16126 if doing so would now swallow text after the yanked text.
16128 org-yank-adjusted-subtrees
16129 When set, the subtree will be promoted or demoted in order to
16130 fit into the local outline tree structure, which means that the level
16131 will be adjusted so that it becomes the smaller one of the two
16132 *visible* surrounding headings.
16134 Any prefix to this command will cause `yank' to be called directly with
16135 no special treatment. In particular, a simple `C-u' prefix will just
16136 plainly yank the text as it is.
16138 \[1] The test checks if the first non-white line is a heading
16139 and if there are no other headings with fewer stars."
16140 (interactive "P")
16141 (org-yank-generic 'yank arg))
16143 (defun org-yank-generic (command arg)
16144 "Perform some yank-like command.
16146 This function implements the behavior described in the `org-yank'
16147 documentation. However, it has been generalized to work for any
16148 interactive command with similar behavior."
16150 ;; pretend to be command COMMAND
16151 (setq this-command command)
16153 (if arg
16154 (call-interactively command)
16156 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
16157 (and (org-kill-is-subtree-p)
16158 (or (bolp)
16159 (and (looking-at "[ \t]*$")
16160 (string-match
16161 "\\`\\*+\\'"
16162 (buffer-substring (point-at-bol) (point)))))))
16163 swallowp)
16164 (cond
16165 ((and subtreep org-yank-folded-subtrees)
16166 (let ((beg (point))
16167 end)
16168 (if (and subtreep org-yank-adjusted-subtrees)
16169 (org-paste-subtree nil nil 'for-yank)
16170 (call-interactively command))
16172 (setq end (point))
16173 (goto-char beg)
16174 (when (and (bolp) subtreep
16175 (not (setq swallowp
16176 (org-yank-folding-would-swallow-text beg end))))
16177 (or (looking-at outline-regexp)
16178 (re-search-forward (concat "^" outline-regexp) end t))
16179 (while (and (< (point) end) (looking-at outline-regexp))
16180 (hide-subtree)
16181 (org-cycle-show-empty-lines 'folded)
16182 (condition-case nil
16183 (outline-forward-same-level 1)
16184 (error (goto-char end)))))
16185 (when swallowp
16186 (message
16187 "Inserted text not folded because that would swallow text"))
16189 (goto-char end)
16190 (skip-chars-forward " \t\n\r")
16191 (beginning-of-line 1)
16192 (push-mark beg 'nomsg)))
16193 ((and subtreep org-yank-adjusted-subtrees)
16194 (let ((beg (point-at-bol)))
16195 (org-paste-subtree nil nil 'for-yank)
16196 (push-mark beg 'nomsg)))
16198 (call-interactively command))))))
16200 (defun org-yank-folding-would-swallow-text (beg end)
16201 "Would hide-subtree at BEG swallow any text after END?"
16202 (let (level)
16203 (save-excursion
16204 (goto-char beg)
16205 (when (or (looking-at outline-regexp)
16206 (re-search-forward (concat "^" outline-regexp) end t))
16207 (setq level (org-outline-level)))
16208 (goto-char end)
16209 (skip-chars-forward " \t\r\n\v\f")
16210 (if (or (eobp)
16211 (and (bolp) (looking-at org-outline-regexp)
16212 (<= (org-outline-level) level)))
16213 nil ; Nothing would be swallowed
16214 t)))) ; something would swallow
16216 (define-key org-mode-map "\C-y" 'org-yank)
16218 (defun org-invisible-p ()
16219 "Check if point is at a character currently not visible."
16220 ;; Early versions of noutline don't have `outline-invisible-p'.
16221 (if (fboundp 'outline-invisible-p)
16222 (outline-invisible-p)
16223 (get-char-property (point) 'invisible)))
16225 (defun org-invisible-p2 ()
16226 "Check if point is at a character currently not visible."
16227 (save-excursion
16228 (if (and (eolp) (not (bobp))) (backward-char 1))
16229 ;; Early versions of noutline don't have `outline-invisible-p'.
16230 (if (fboundp 'outline-invisible-p)
16231 (outline-invisible-p)
16232 (get-char-property (point) 'invisible))))
16234 (defun org-back-to-heading (&optional invisible-ok)
16235 "Call `outline-back-to-heading', but provide a better error message."
16236 (condition-case nil
16237 (outline-back-to-heading invisible-ok)
16238 (error (error "Before first headline at position %d in buffer %s"
16239 (point) (current-buffer)))))
16241 (defun org-before-first-heading-p ()
16242 "Before first heading?"
16243 (save-excursion
16244 (null (re-search-backward "^\\*+ " nil t))))
16246 (defalias 'org-on-heading-p 'outline-on-heading-p)
16247 (defalias 'org-at-heading-p 'outline-on-heading-p)
16248 (defun org-at-heading-or-item-p ()
16249 (or (org-on-heading-p) (org-at-item-p)))
16251 (defun org-on-target-p ()
16252 (or (org-in-regexp org-radio-target-regexp)
16253 (org-in-regexp org-target-regexp)))
16255 (defun org-up-heading-all (arg)
16256 "Move to the heading line of which the present line is a subheading.
16257 This function considers both visible and invisible heading lines.
16258 With argument, move up ARG levels."
16259 (if (fboundp 'outline-up-heading-all)
16260 (outline-up-heading-all arg) ; emacs 21 version of outline.el
16261 (outline-up-heading arg t))) ; emacs 22 version of outline.el
16263 (defun org-up-heading-safe ()
16264 "Move to the heading line of which the present line is a subheading.
16265 This version will not throw an error. It will return the level of the
16266 headline found, or nil if no higher level is found.
16268 Also, this function will be a lot faster than `outline-up-heading',
16269 because it relies on stars being the outline starters. This can really
16270 make a significant difference in outlines with very many siblings."
16271 (let (start-level re)
16272 (org-back-to-heading t)
16273 (setq start-level (funcall outline-level))
16274 (if (equal start-level 1)
16276 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
16277 (if (re-search-backward re nil t)
16278 (funcall outline-level)))))
16280 (defun org-first-sibling-p ()
16281 "Is this heading the first child of its parents?"
16282 (interactive)
16283 (let ((re (concat "^" outline-regexp))
16284 level l)
16285 (unless (org-at-heading-p t)
16286 (error "Not at a heading"))
16287 (setq level (funcall outline-level))
16288 (save-excursion
16289 (if (not (re-search-backward re nil t))
16291 (setq l (funcall outline-level))
16292 (< l level)))))
16294 (defun org-goto-sibling (&optional previous)
16295 "Goto the next sibling, even if it is invisible.
16296 When PREVIOUS is set, go to the previous sibling instead. Returns t
16297 when a sibling was found. When none is found, return nil and don't
16298 move point."
16299 (let ((fun (if previous 're-search-backward 're-search-forward))
16300 (pos (point))
16301 (re (concat "^" outline-regexp))
16302 level l)
16303 (when (condition-case nil (org-back-to-heading t) (error nil))
16304 (setq level (funcall outline-level))
16305 (catch 'exit
16306 (or previous (forward-char 1))
16307 (while (funcall fun re nil t)
16308 (setq l (funcall outline-level))
16309 (when (< l level) (goto-char pos) (throw 'exit nil))
16310 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
16311 (goto-char pos)
16312 nil))))
16314 (defun org-show-siblings ()
16315 "Show all siblings of the current headline."
16316 (save-excursion
16317 (while (org-goto-sibling) (org-flag-heading nil)))
16318 (save-excursion
16319 (while (org-goto-sibling 'previous)
16320 (org-flag-heading nil))))
16322 (defun org-show-hidden-entry ()
16323 "Show an entry where even the heading is hidden."
16324 (save-excursion
16325 (org-show-entry)))
16327 (defun org-flag-heading (flag &optional entry)
16328 "Flag the current heading. FLAG non-nil means make invisible.
16329 When ENTRY is non-nil, show the entire entry."
16330 (save-excursion
16331 (org-back-to-heading t)
16332 ;; Check if we should show the entire entry
16333 (if entry
16334 (progn
16335 (org-show-entry)
16336 (save-excursion
16337 (and (outline-next-heading)
16338 (org-flag-heading nil))))
16339 (outline-flag-region (max (point-min) (1- (point)))
16340 (save-excursion (outline-end-of-heading) (point))
16341 flag))))
16343 (defun org-forward-same-level (arg)
16344 "Move forward to the ARG'th subheading at same level as this one.
16345 Stop at the first and last subheadings of a superior heading.
16346 This is like outline-forward-same-level, but invisible headings are ok."
16347 (interactive "p")
16348 (org-back-to-heading t)
16349 (while (> arg 0)
16350 (let ((point-to-move-to (save-excursion
16351 (org-get-next-sibling))))
16352 (if point-to-move-to
16353 (progn
16354 (goto-char point-to-move-to)
16355 (setq arg (1- arg)))
16356 (progn
16357 (setq arg 0)
16358 (error "No following same-level heading"))))))
16360 (defun org-get-next-sibling ()
16361 "Move to next heading of the same level, and return point.
16362 If there is no such heading, return nil.
16363 This is like outline-next-sibling, but invisible headings are ok."
16364 (let ((level (funcall outline-level)))
16365 (outline-next-heading)
16366 (while (and (not (eobp)) (> (funcall outline-level) level))
16367 (outline-next-heading))
16368 (if (or (eobp) (< (funcall outline-level) level))
16370 (point))))
16372 (defun org-end-of-subtree (&optional invisible-OK to-heading)
16373 ;; This contains an exact copy of the original function, but it uses
16374 ;; `org-back-to-heading', to make it work also in invisible
16375 ;; trees. And is uses an invisible-OK argument.
16376 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
16377 ;; Furthermore, when used inside Org, finding the end of a large subtree
16378 ;; with many children and grandchildren etc, this can be much faster
16379 ;; than the outline version.
16380 (org-back-to-heading invisible-OK)
16381 (let ((first t)
16382 (level (funcall outline-level)))
16383 (if (and (org-mode-p) (< level 1000))
16384 ;; A true heading (not a plain list item), in Org-mode
16385 ;; This means we can easily find the end by looking
16386 ;; only for the right number of stars. Using a regexp to do
16387 ;; this is so much faster than using a Lisp loop.
16388 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
16389 (forward-char 1)
16390 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
16391 ;; something else, do it the slow way
16392 (while (and (not (eobp))
16393 (or first (> (funcall outline-level) level)))
16394 (setq first nil)
16395 (outline-next-heading)))
16396 (unless to-heading
16397 (if (memq (preceding-char) '(?\n ?\^M))
16398 (progn
16399 ;; Go to end of line before heading
16400 (forward-char -1)
16401 (if (memq (preceding-char) '(?\n ?\^M))
16402 ;; leave blank line before heading
16403 (forward-char -1))))))
16404 (point))
16406 (defun org-show-subtree ()
16407 "Show everything after this heading at deeper levels."
16408 (outline-flag-region
16409 (point)
16410 (save-excursion
16411 (outline-end-of-subtree) (outline-next-heading) (point))
16412 nil))
16414 (defun org-show-entry ()
16415 "Show the body directly following this heading.
16416 Show the heading too, if it is currently invisible."
16417 (interactive)
16418 (save-excursion
16419 (condition-case nil
16420 (progn
16421 (org-back-to-heading t)
16422 (outline-flag-region
16423 (max (point-min) (1- (point)))
16424 (save-excursion
16425 (if (re-search-forward
16426 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
16427 (match-beginning 1)
16428 (point-max)))
16429 nil))
16430 (error nil))))
16432 (defun org-make-options-regexp (kwds &optional extra)
16433 "Make a regular expression for keyword lines."
16434 (concat
16436 "#?[ \t]*\\+\\("
16437 (mapconcat 'regexp-quote kwds "\\|")
16438 (if extra (concat "\\|" extra))
16439 "\\):[ \t]*"
16440 "\\(.+\\)"))
16442 ;; Make isearch reveal the necessary context
16443 (defun org-isearch-end ()
16444 "Reveal context after isearch exits."
16445 (when isearch-success ; only if search was successful
16446 (if (featurep 'xemacs)
16447 ;; Under XEmacs, the hook is run in the correct place,
16448 ;; we directly show the context.
16449 (org-show-context 'isearch)
16450 ;; In Emacs the hook runs *before* restoring the overlays.
16451 ;; So we have to use a one-time post-command-hook to do this.
16452 ;; (Emacs 22 has a special variable, see function `org-mode')
16453 (unless (and (boundp 'isearch-mode-end-hook-quit)
16454 isearch-mode-end-hook-quit)
16455 ;; Only when the isearch was not quitted.
16456 (org-add-hook 'post-command-hook 'org-isearch-post-command
16457 'append 'local)))))
16459 (defun org-isearch-post-command ()
16460 "Remove self from hook, and show context."
16461 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
16462 (org-show-context 'isearch))
16465 ;;;; Integration with and fixes for other packages
16467 ;;; Imenu support
16469 (defvar org-imenu-markers nil
16470 "All markers currently used by Imenu.")
16471 (make-variable-buffer-local 'org-imenu-markers)
16473 (defun org-imenu-new-marker (&optional pos)
16474 "Return a new marker for use by Imenu, and remember the marker."
16475 (let ((m (make-marker)))
16476 (move-marker m (or pos (point)))
16477 (push m org-imenu-markers)
16480 (defun org-imenu-get-tree ()
16481 "Produce the index for Imenu."
16482 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
16483 (setq org-imenu-markers nil)
16484 (let* ((n org-imenu-depth)
16485 (re (concat "^" outline-regexp))
16486 (subs (make-vector (1+ n) nil))
16487 (last-level 0)
16488 m level head)
16489 (save-excursion
16490 (save-restriction
16491 (widen)
16492 (goto-char (point-max))
16493 (while (re-search-backward re nil t)
16494 (setq level (org-reduced-level (funcall outline-level)))
16495 (when (<= level n)
16496 (looking-at org-complex-heading-regexp)
16497 (setq head (org-link-display-format
16498 (org-match-string-no-properties 4))
16499 m (org-imenu-new-marker))
16500 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
16501 (if (>= level last-level)
16502 (push (cons head m) (aref subs level))
16503 (push (cons head (aref subs (1+ level))) (aref subs level))
16504 (loop for i from (1+ level) to n do (aset subs i nil)))
16505 (setq last-level level)))))
16506 (aref subs 1)))
16508 (eval-after-load "imenu"
16509 '(progn
16510 (add-hook 'imenu-after-jump-hook
16511 (lambda ()
16512 (if (eq major-mode 'org-mode)
16513 (org-show-context 'org-goto))))))
16515 (defun org-link-display-format (link)
16516 "Replace a link with either the description, or the link target
16517 if no description is present"
16518 (save-match-data
16519 (if (string-match org-bracket-link-analytic-regexp link)
16520 (replace-match (or (match-string 5 link)
16521 (concat (match-string 1 link)
16522 (match-string 3 link)))
16523 nil nil link)
16524 link)))
16526 ;; Speedbar support
16528 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
16529 "Overlay marking the agenda restriction line in speedbar.")
16530 (org-overlay-put org-speedbar-restriction-lock-overlay
16531 'face 'org-agenda-restriction-lock)
16532 (org-overlay-put org-speedbar-restriction-lock-overlay
16533 'help-echo "Agendas are currently limited to this item.")
16534 (org-detach-overlay org-speedbar-restriction-lock-overlay)
16536 (defun org-speedbar-set-agenda-restriction ()
16537 "Restrict future agenda commands to the location at point in speedbar.
16538 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
16539 (interactive)
16540 (require 'org-agenda)
16541 (let (p m tp np dir txt)
16542 (cond
16543 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16544 'org-imenu t))
16545 (setq m (get-text-property p 'org-imenu-marker))
16546 (save-excursion
16547 (save-restriction
16548 (set-buffer (marker-buffer m))
16549 (goto-char m)
16550 (org-agenda-set-restriction-lock 'subtree))))
16551 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16552 'speedbar-function 'speedbar-find-file))
16553 (setq tp (previous-single-property-change
16554 (1+ p) 'speedbar-function)
16555 np (next-single-property-change
16556 tp 'speedbar-function)
16557 dir (speedbar-line-directory)
16558 txt (buffer-substring-no-properties (or tp (point-min))
16559 (or np (point-max))))
16560 (save-excursion
16561 (save-restriction
16562 (set-buffer (find-file-noselect
16563 (let ((default-directory dir))
16564 (expand-file-name txt))))
16565 (unless (org-mode-p)
16566 (error "Cannot restrict to non-Org-mode file"))
16567 (org-agenda-set-restriction-lock 'file))))
16568 (t (error "Don't know how to restrict Org-mode's agenda")))
16569 (org-move-overlay org-speedbar-restriction-lock-overlay
16570 (point-at-bol) (point-at-eol))
16571 (setq current-prefix-arg nil)
16572 (org-agenda-maybe-redo)))
16574 (eval-after-load "speedbar"
16575 '(progn
16576 (speedbar-add-supported-extension ".org")
16577 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
16578 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
16579 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
16580 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16581 (add-hook 'speedbar-visiting-tag-hook
16582 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
16585 ;;; Fixes and Hacks for problems with other packages
16587 ;; Make flyspell not check words in links, to not mess up our keymap
16588 (defun org-mode-flyspell-verify ()
16589 "Don't let flyspell put overlays at active buttons."
16590 (not (get-text-property (point) 'keymap)))
16592 ;; Make `bookmark-jump' show the jump location if it was hidden.
16593 (eval-after-load "bookmark"
16594 '(if (boundp 'bookmark-after-jump-hook)
16595 ;; We can use the hook
16596 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
16597 ;; Hook not available, use advice
16598 (defadvice bookmark-jump (after org-make-visible activate)
16599 "Make the position visible."
16600 (org-bookmark-jump-unhide))))
16602 ;; Make sure saveplace show the location if it was hidden
16603 (eval-after-load "saveplace"
16604 '(defadvice save-place-find-file-hook (after org-make-visible activate)
16605 "Make the position visible."
16606 (org-bookmark-jump-unhide)))
16608 (defun org-bookmark-jump-unhide ()
16609 "Unhide the current position, to show the bookmark location."
16610 (and (org-mode-p)
16611 (or (org-invisible-p)
16612 (save-excursion (goto-char (max (point-min) (1- (point))))
16613 (org-invisible-p)))
16614 (org-show-context 'bookmark-jump)))
16616 ;; Make session.el ignore our circular variable
16617 (eval-after-load "session"
16618 '(add-to-list 'session-globals-exclude 'org-mark-ring))
16620 ;;;; Experimental code
16622 (defun org-closed-in-range ()
16623 "Sparse tree of items closed in a certain time range.
16624 Still experimental, may disappear in the future."
16625 (interactive)
16626 ;; Get the time interval from the user.
16627 (let* ((time1 (time-to-seconds
16628 (org-read-date nil 'to-time nil "Starting date: ")))
16629 (time2 (time-to-seconds
16630 (org-read-date nil 'to-time nil "End date:")))
16631 ;; callback function
16632 (callback (lambda ()
16633 (let ((time
16634 (time-to-seconds
16635 (apply 'encode-time
16636 (org-parse-time-string
16637 (match-string 1))))))
16638 ;; check if time in interval
16639 (and (>= time time1) (<= time time2))))))
16640 ;; make tree, check each match with the callback
16641 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
16643 ;;;; Finish up
16645 (provide 'org)
16647 (run-hooks 'org-load-hook)
16649 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
16651 ;;; org.el ends here