Logging: New property LOG_INTO_DRAWER
[org-mode.git] / lisp / org.el
blob5ac5e81e0d787a58b29005ce779147bb8c4b682f
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009
4 ;; Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;; Version: 6.26trans
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum)
76 (require 'calendar))
77 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
78 ;; the file noutline.el being loaded.
79 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
80 ;; We require noutline, which might be provided in outline.el
81 (require 'outline) (require 'noutline)
82 ;; Other stuff we need.
83 (require 'time-date)
84 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
85 (require 'easymenu)
87 (require 'org-macs)
88 (require 'org-compat)
89 (require 'org-faces)
90 (require 'org-list)
91 (require 'org-footnote)
93 ;;;; Customization variables
95 ;;; Version
97 (defconst org-version "6.26trans"
98 "The version number of the file org.el.")
100 (defun org-version (&optional here)
101 "Show the org-mode version in the echo area.
102 With prefix arg HERE, insert it at point."
103 (interactive "P")
104 (let ((version (format "Org-mode version %s" org-version)))
105 (message version)
106 (if here
107 (insert version))))
109 ;;; Compatibility constants
111 ;;; The custom variables
113 (defgroup org nil
114 "Outline-based notes management and organizer."
115 :tag "Org"
116 :group 'outlines
117 :group 'hypermedia
118 :group 'calendar)
120 (defcustom org-load-hook nil
121 "Hook that is run after org.el has been loaded."
122 :group 'org
123 :type 'hook)
125 (defvar org-modules) ; defined below
126 (defvar org-modules-loaded nil
127 "Have the modules been loaded already?")
129 (defun org-load-modules-maybe (&optional force)
130 "Load all extensions listed in `org-modules'."
131 (when (or force (not org-modules-loaded))
132 (mapc (lambda (ext)
133 (condition-case nil (require ext)
134 (error (message "Problems while trying to load feature `%s'" ext))))
135 org-modules)
136 (setq org-modules-loaded t)))
138 (defun org-set-modules (var value)
139 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
140 (set var value)
141 (when (featurep 'org)
142 (org-load-modules-maybe 'force)))
144 (when (org-bound-and-true-p org-modules)
145 (let ((a (member 'org-infojs org-modules)))
146 (and a (setcar a 'org-jsinfo))))
148 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
149 "Modules that should always be loaded together with org.el.
150 If a description starts with <C>, the file is not part of Emacs
151 and loading it will require that you have downloaded and properly installed
152 the org-mode distribution.
154 You can also use this system to load external packages (i.e. neither Org
155 core modules, not modules from the CONTRIB directory). Just add symbols
156 to the end of the list. If the package is called org-xyz.el, then you need
157 to add the symbol `xyz', and the package must have a call to
159 (provide 'org-xyz)"
160 :group 'org
161 :set 'org-set-modules
162 :type
163 '(set :greedy t
164 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
165 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
166 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
167 (const :tag " id: Global IDs for identifying entries" org-id)
168 (const :tag " info: Links to Info nodes" org-info)
169 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
170 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
171 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
172 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
173 (const :tag " mew Links to Mew folders/messages" org-mew)
174 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
175 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
176 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
177 (const :tag " vm: Links to VM folders/messages" org-vm)
178 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
179 (const :tag " w3m: Special cut/paste from w3m to Org." org-w3m)
180 (const :tag " mouse: Additional mouse support" org-mouse)
182 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
183 (const :tag "C annotation-helper: Call Remember directly from Browser (OBSOLETE, use org-protocol)" org-annotation-helper)
184 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
185 (const :tag "C browser-url: Store link, directly from Browser (OBSOLETE, use org-protocol)" org-browser-url)
186 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
187 (const :tag "C collector: Collect properties into tables" org-collector)
188 (const :tag "C depend: TODO dependencies for Org-mode (PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
189 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
190 (const :tag "C eval: Include command output as text" org-eval)
191 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
192 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
193 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
194 (const :tag "C exp-blocks: Pre-process blocks for export" org-exp-blocks)
195 (const :tag "C interactive-query: Interactive modification of tags query (PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
196 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
197 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
198 (const :tag "C mtags: Support for muse-like tags" org-mtags)
199 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
200 (const :tag "C R: Computation using the R language" org-R)
201 (const :tag "C registry: A registry for Org links" org-registry)
202 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
203 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
204 (const :tag "C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
205 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
206 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
207 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
209 (defcustom org-support-shift-select nil
210 "Non-nil means, make shift-cursor commands select text when possible.
212 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
213 selecting a region, or enlarge thusly regions started in this way.
214 In Org-mode, in special contexts, these same keys are used for other
215 purposes, important enough to compete with shift selection. Org tries
216 to balance these needs by supporting `shift-select-mode' outside these
217 special contexts, under control of this variable.
219 The default of this variable is nil, to avoid confusing behavior. Shifted
220 cursor keys will then execute Org commands in the following contexts:
221 - on a headline, changing TODO state (left/right) and priority (up/down)
222 - on a time stamp, changing the time
223 - in a plain list item, changing the bullet type
224 - in a property definition line, switching between allowed values
225 - in the BEGIN line of a clock table (changing the time block).
226 Outside these contexts, the commands will throw an error.
228 When this variable is t and the cursor is not in a special context,
229 Org-mode will support shift-selection for making and enlarging regions.
230 To make this more effective, the bullet cycling will no longer happen
231 anywhere in an item line, but only if the cursor is exactly on the bullet.
233 If you set this variable to the symbol `always', then the keys
234 will not be special in headlines, property lines, and item lines, to make
235 shift selection work there as well. If this is what you want, you can
236 use the following alternative commands: `C-c C-t' and `C-c ,' to
237 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
238 TODO sets, `C-c -' to cycle item bullet types, and properties can be
239 edited by hand or in column view.
241 However, when the cursor is on a timestamp, shift-cursor commands
242 will still edit the time stamp - this is just too good to give up.
244 XEmacs user should have this variable set to nil, because shift-select-mode
245 is Emacs 23 only."
246 :group 'org
247 :type '(choice
248 (const :tag "Never" nil)
249 (const :tag "When outside special context" t)
250 (const :tag "Everywhere except timestamps" always)))
252 (defgroup org-startup nil
253 "Options concerning startup of Org-mode."
254 :tag "Org Startup"
255 :group 'org)
257 (defcustom org-startup-folded t
258 "Non-nil means, entering Org-mode will switch to OVERVIEW.
259 This can also be configured on a per-file basis by adding one of
260 the following lines anywhere in the buffer:
262 #+STARTUP: fold
263 #+STARTUP: nofold
264 #+STARTUP: content"
265 :group 'org-startup
266 :type '(choice
267 (const :tag "nofold: show all" nil)
268 (const :tag "fold: overview" t)
269 (const :tag "content: all headlines" content)))
271 (defcustom org-startup-truncated t
272 "Non-nil means, entering Org-mode will set `truncate-lines'.
273 This is useful since some lines containing links can be very long and
274 uninteresting. Also tables look terrible when wrapped."
275 :group 'org-startup
276 :type 'boolean)
278 (defcustom org-startup-align-all-tables nil
279 "Non-nil means, align all tables when visiting a file.
280 This is useful when the column width in tables is forced with <N> cookies
281 in table fields. Such tables will look correct only after the first re-align.
282 This can also be configured on a per-file basis by adding one of
283 the following lines anywhere in the buffer:
284 #+STARTUP: align
285 #+STARTUP: noalign"
286 :group 'org-startup
287 :type 'boolean)
289 (defcustom org-insert-mode-line-in-empty-file nil
290 "Non-nil means insert the first line setting Org-mode in empty files.
291 When the function `org-mode' is called interactively in an empty file, this
292 normally means that the file name does not automatically trigger Org-mode.
293 To ensure that the file will always be in Org-mode in the future, a
294 line enforcing Org-mode will be inserted into the buffer, if this option
295 has been set."
296 :group 'org-startup
297 :type 'boolean)
299 (defcustom org-replace-disputed-keys nil
300 "Non-nil means use alternative key bindings for some keys.
301 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
302 These keys are also used by other packages like shift-selection-mode'
303 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
304 If you want to use Org-mode together with one of these other modes,
305 or more generally if you would like to move some Org-mode commands to
306 other keys, set this variable and configure the keys with the variable
307 `org-disputed-keys'.
309 This option is only relevant at load-time of Org-mode, and must be set
310 *before* org.el is loaded. Changing it requires a restart of Emacs to
311 become effective."
312 :group 'org-startup
313 :type 'boolean)
315 (defcustom org-use-extra-keys nil
316 "Non-nil means use extra key sequence definitions for certain
317 commands. This happens automatically if you run XEmacs or if
318 window-system is nil. This variable lets you do the same
319 manually. You must set it before loading org.
321 Example: on Carbon Emacs 22 running graphically, with an external
322 keyboard on a Powerbook, the default way of setting M-left might
323 not work for either Alt or ESC. Setting this variable will make
324 it work for ESC."
325 :group 'org-startup
326 :type 'boolean)
328 (if (fboundp 'defvaralias)
329 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
331 (defcustom org-disputed-keys
332 '(([(shift up)] . [(meta p)])
333 ([(shift down)] . [(meta n)])
334 ([(shift left)] . [(meta -)])
335 ([(shift right)] . [(meta +)])
336 ([(control shift right)] . [(meta shift +)])
337 ([(control shift left)] . [(meta shift -)]))
338 "Keys for which Org-mode and other modes compete.
339 This is an alist, cars are the default keys, second element specifies
340 the alternative to use when `org-replace-disputed-keys' is t.
342 Keys can be specified in any syntax supported by `define-key'.
343 The value of this option takes effect only at Org-mode's startup,
344 therefore you'll have to restart Emacs to apply it after changing."
345 :group 'org-startup
346 :type 'alist)
348 (defun org-key (key)
349 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
350 Or return the original if not disputed."
351 (if org-replace-disputed-keys
352 (let* ((nkey (key-description key))
353 (x (org-find-if (lambda (x)
354 (equal (key-description (car x)) nkey))
355 org-disputed-keys)))
356 (if x (cdr x) key))
357 key))
359 (defun org-find-if (predicate seq)
360 (catch 'exit
361 (while seq
362 (if (funcall predicate (car seq))
363 (throw 'exit (car seq))
364 (pop seq)))))
366 (defun org-defkey (keymap key def)
367 "Define a key, possibly translated, as returned by `org-key'."
368 (define-key keymap (org-key key) def))
370 (defcustom org-ellipsis nil
371 "The ellipsis to use in the Org-mode outline.
372 When nil, just use the standard three dots. When a string, use that instead,
373 When a face, use the standard 3 dots, but with the specified face.
374 The change affects only Org-mode (which will then use its own display table).
375 Changing this requires executing `M-x org-mode' in a buffer to become
376 effective."
377 :group 'org-startup
378 :type '(choice (const :tag "Default" nil)
379 (face :tag "Face" :value org-warning)
380 (string :tag "String" :value "...#")))
382 (defvar org-display-table nil
383 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
385 (defgroup org-keywords nil
386 "Keywords in Org-mode."
387 :tag "Org Keywords"
388 :group 'org)
390 (defcustom org-deadline-string "DEADLINE:"
391 "String to mark deadline entries.
392 A deadline is this string, followed by a time stamp. Should be a word,
393 terminated by a colon. You can insert a schedule keyword and
394 a timestamp with \\[org-deadline].
395 Changes become only effective after restarting Emacs."
396 :group 'org-keywords
397 :type 'string)
399 (defcustom org-scheduled-string "SCHEDULED:"
400 "String to mark scheduled TODO entries.
401 A schedule is this string, followed by a time stamp. Should be a word,
402 terminated by a colon. You can insert a schedule keyword and
403 a timestamp with \\[org-schedule].
404 Changes become only effective after restarting Emacs."
405 :group 'org-keywords
406 :type 'string)
408 (defcustom org-closed-string "CLOSED:"
409 "String used as the prefix for timestamps logging closing a TODO entry."
410 :group 'org-keywords
411 :type 'string)
413 (defcustom org-clock-string "CLOCK:"
414 "String used as prefix for timestamps clocking work hours on an item."
415 :group 'org-keywords
416 :type 'string)
418 (defcustom org-comment-string "COMMENT"
419 "Entries starting with this keyword will never be exported.
420 An entry can be toggled between COMMENT and normal with
421 \\[org-toggle-comment].
422 Changes become only effective after restarting Emacs."
423 :group 'org-keywords
424 :type 'string)
426 (defcustom org-quote-string "QUOTE"
427 "Entries starting with this keyword will be exported in fixed-width font.
428 Quoting applies only to the text in the entry following the headline, and does
429 not extend beyond the next headline, even if that is lower level.
430 An entry can be toggled between QUOTE and normal with
431 \\[org-toggle-fixed-width-section]."
432 :group 'org-keywords
433 :type 'string)
435 (defconst org-repeat-re
436 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
437 "Regular expression for specifying repeated events.
438 After a match, group 1 contains the repeat expression.")
440 (defgroup org-structure nil
441 "Options concerning the general structure of Org-mode files."
442 :tag "Org Structure"
443 :group 'org)
445 (defgroup org-reveal-location nil
446 "Options about how to make context of a location visible."
447 :tag "Org Reveal Location"
448 :group 'org-structure)
450 (defconst org-context-choice
451 '(choice
452 (const :tag "Always" t)
453 (const :tag "Never" nil)
454 (repeat :greedy t :tag "Individual contexts"
455 (cons
456 (choice :tag "Context"
457 (const agenda)
458 (const org-goto)
459 (const occur-tree)
460 (const tags-tree)
461 (const link-search)
462 (const mark-goto)
463 (const bookmark-jump)
464 (const isearch)
465 (const default))
466 (boolean))))
467 "Contexts for the reveal options.")
469 (defcustom org-show-hierarchy-above '((default . t))
470 "Non-nil means, show full hierarchy when revealing a location.
471 Org-mode often shows locations in an org-mode file which might have
472 been invisible before. When this is set, the hierarchy of headings
473 above the exposed location is shown.
474 Turning this off for example for sparse trees makes them very compact.
475 Instead of t, this can also be an alist specifying this option for different
476 contexts. Valid contexts are
477 agenda when exposing an entry from the agenda
478 org-goto when using the command `org-goto' on key C-c C-j
479 occur-tree when using the command `org-occur' on key C-c /
480 tags-tree when constructing a sparse tree based on tags matches
481 link-search when exposing search matches associated with a link
482 mark-goto when exposing the jump goal of a mark
483 bookmark-jump when exposing a bookmark location
484 isearch when exiting from an incremental search
485 default default for all contexts not set explicitly"
486 :group 'org-reveal-location
487 :type org-context-choice)
489 (defcustom org-show-following-heading '((default . nil))
490 "Non-nil means, show following heading when revealing a location.
491 Org-mode often shows locations in an org-mode file which might have
492 been invisible before. When this is set, the heading following the
493 match is shown.
494 Turning this off for example for sparse trees makes them very compact,
495 but makes it harder to edit the location of the match. In such a case,
496 use the command \\[org-reveal] to show more context.
497 Instead of t, this can also be an alist specifying this option for different
498 contexts. See `org-show-hierarchy-above' for valid contexts."
499 :group 'org-reveal-location
500 :type org-context-choice)
502 (defcustom org-show-siblings '((default . nil) (isearch t))
503 "Non-nil means, show all sibling heading when revealing a location.
504 Org-mode often shows locations in an org-mode file which might have
505 been invisible before. When this is set, the sibling of the current entry
506 heading are all made visible. If `org-show-hierarchy-above' is t,
507 the same happens on each level of the hierarchy above the current entry.
509 By default this is on for the isearch context, off for all other contexts.
510 Turning this off for example for sparse trees makes them very compact,
511 but makes it harder to edit the location of the match. In such a case,
512 use the command \\[org-reveal] to show more context.
513 Instead of t, this can also be an alist specifying this option for different
514 contexts. See `org-show-hierarchy-above' for valid contexts."
515 :group 'org-reveal-location
516 :type org-context-choice)
518 (defcustom org-show-entry-below '((default . nil))
519 "Non-nil means, show the entry below a headline when revealing a location.
520 Org-mode often shows locations in an org-mode file which might have
521 been invisible before. When this is set, the text below the headline that is
522 exposed is also shown.
524 By default this is off for all contexts.
525 Instead of t, this can also be an alist specifying this option for different
526 contexts. See `org-show-hierarchy-above' for valid contexts."
527 :group 'org-reveal-location
528 :type org-context-choice)
530 (defcustom org-indirect-buffer-display 'other-window
531 "How should indirect tree buffers be displayed?
532 This applies to indirect buffers created with the commands
533 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
534 Valid values are:
535 current-window Display in the current window
536 other-window Just display in another window.
537 dedicated-frame Create one new frame, and re-use it each time.
538 new-frame Make a new frame each time. Note that in this case
539 previously-made indirect buffers are kept, and you need to
540 kill these buffers yourself."
541 :group 'org-structure
542 :group 'org-agenda-windows
543 :type '(choice
544 (const :tag "In current window" current-window)
545 (const :tag "In current frame, other window" other-window)
546 (const :tag "Each time a new frame" new-frame)
547 (const :tag "One dedicated frame" dedicated-frame)))
549 (defgroup org-cycle nil
550 "Options concerning visibility cycling in Org-mode."
551 :tag "Org Cycle"
552 :group 'org-structure)
554 (defcustom org-cycle-max-level nil
555 "Maximum level which should still be subject to visibility cycling.
556 Levels higher than this will, for cycling, be treated as text, not a headline.
557 When `org-odd-levels-only' is set, a value of N in this variable actually
558 means 2N-1 stars as the limiting headline.
559 When nil, cycle all levels.
560 Note that the limiting level of cycling is also influenced by
561 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
562 `org-inlinetask-min-level' is, cycling will be limited to levels one less
563 than its value."
564 :group 'org-cycle
565 :type '(choice
566 (const :tag "No limit" nil)
567 (integer :tag "Maximum level")))
569 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
570 "Names of drawers. Drawers are not opened by cycling on the headline above.
571 Drawers only open with a TAB on the drawer line itself. A drawer looks like
572 this:
573 :DRAWERNAME:
574 .....
575 :END:
576 The drawer \"PROPERTIES\" is special for capturing properties through
577 the property API.
579 Drawers can be defined on the per-file basis with a line like:
581 #+DRAWERS: HIDDEN STATE PROPERTIES"
582 :group 'org-structure
583 :group 'org-cycle
584 :type '(repeat (string :tag "Drawer Name")))
586 (defcustom org-cycle-global-at-bob nil
587 "Cycle globally if cursor is at beginning of buffer and not at a headline.
588 This makes it possible to do global cycling without having to use S-TAB or
589 C-u TAB. For this special case to work, the first line of the buffer
590 must not be a headline - it may be empty or some other text. When used in
591 this way, `org-cycle-hook' is disables temporarily, to make sure the
592 cursor stays at the beginning of the buffer.
593 When this option is nil, don't do anything special at the beginning
594 of the buffer."
595 :group 'org-cycle
596 :type 'boolean)
598 (defcustom org-cycle-emulate-tab t
599 "Where should `org-cycle' emulate TAB.
600 nil Never
601 white Only in completely white lines
602 whitestart Only at the beginning of lines, before the first non-white char
603 t Everywhere except in headlines
604 exc-hl-bol Everywhere except at the start of a headline
605 If TAB is used in a place where it does not emulate TAB, the current subtree
606 visibility is cycled."
607 :group 'org-cycle
608 :type '(choice (const :tag "Never" nil)
609 (const :tag "Only in completely white lines" white)
610 (const :tag "Before first char in a line" whitestart)
611 (const :tag "Everywhere except in headlines" t)
612 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
615 (defcustom org-cycle-separator-lines 2
616 "Number of empty lines needed to keep an empty line between collapsed trees.
617 If you leave an empty line between the end of a subtree and the following
618 headline, this empty line is hidden when the subtree is folded.
619 Org-mode will leave (exactly) one empty line visible if the number of
620 empty lines is equal or larger to the number given in this variable.
621 So the default 2 means, at least 2 empty lines after the end of a subtree
622 are needed to produce free space between a collapsed subtree and the
623 following headline.
625 Special case: when 0, never leave empty lines in collapsed view."
626 :group 'org-cycle
627 :type 'integer)
628 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
630 (defcustom org-pre-cycle-hook nil
631 "Hook that is run before visibility cycling is happening.
632 The function(s) in this hook must accept a single argument which indicates
633 the new state that will be set right after running this hook. The
634 argument is a symbol. Before a global state change, it can have the values
635 `overview', `content', or `all'. Before a local state change, it can have
636 the values `folded', `children', or `subtree'."
637 :group 'org-cycle
638 :type 'hook)
640 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
641 org-cycle-hide-drawers
642 org-cycle-show-empty-lines
643 org-optimize-window-after-visibility-change)
644 "Hook that is run after `org-cycle' has changed the buffer visibility.
645 The function(s) in this hook must accept a single argument which indicates
646 the new state that was set by the most recent `org-cycle' command. The
647 argument is a symbol. After a global state change, it can have the values
648 `overview', `content', or `all'. After a local state change, it can have
649 the values `folded', `children', or `subtree'."
650 :group 'org-cycle
651 :type 'hook)
653 (defgroup org-edit-structure nil
654 "Options concerning structure editing in Org-mode."
655 :tag "Org Edit Structure"
656 :group 'org-structure)
658 (defcustom org-odd-levels-only nil
659 "Non-nil means, skip even levels and only use odd levels for the outline.
660 This has the effect that two stars are being added/taken away in
661 promotion/demotion commands. It also influences how levels are
662 handled by the exporters.
663 Changing it requires restart of `font-lock-mode' to become effective
664 for fontification also in regions already fontified.
665 You may also set this on a per-file basis by adding one of the following
666 lines to the buffer:
668 #+STARTUP: odd
669 #+STARTUP: oddeven"
670 :group 'org-edit-structure
671 :group 'org-font-lock
672 :type 'boolean)
674 (defcustom org-adapt-indentation t
675 "Non-nil means, adapt indentation when promoting and demoting.
676 When this is set and the *entire* text in an entry is indented, the
677 indentation is increased by one space in a demotion command, and
678 decreased by one in a promotion command. If any line in the entry
679 body starts at column 0, indentation is not changed at all."
680 :group 'org-edit-structure
681 :type 'boolean)
683 (defcustom org-special-ctrl-a/e nil
684 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
686 When t, `C-a' will bring back the cursor to the beginning of the
687 headline text, i.e. after the stars and after a possible TODO keyword.
688 In an item, this will be the position after the bullet.
689 When the cursor is already at that position, another `C-a' will bring
690 it to the beginning of the line.
692 `C-e' will jump to the end of the headline, ignoring the presence of tags
693 in the headline. A second `C-e' will then jump to the true end of the
694 line, after any tags.
696 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
697 and only a directly following, identical keypress will bring the cursor
698 to the special positions.
700 This may also be a cons cell where the behavior for `C-a' and `C-e' is
701 set separately."
702 :group 'org-edit-structure
703 :type '(choice
704 (const :tag "off" nil)
705 (const :tag "after stars/bullet and before tags first" t)
706 (const :tag "true line boundary first" reversed)
707 (cons :tag "Set C-a and C-e separately"
708 (choice :tag "Special C-a"
709 (const :tag "off" nil)
710 (const :tag "after stars/bullet first" t)
711 (const :tag "before stars/bullet first" reversed))
712 (choice :tag "Special C-e"
713 (const :tag "off" nil)
714 (const :tag "before tags first" t)
715 (const :tag "after tags first" reversed)))))
716 (if (fboundp 'defvaralias)
717 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
719 (defcustom org-special-ctrl-k nil
720 "Non-nil means `C-k' will behave specially in headlines.
721 When nil, `C-k' will call the default `kill-line' command.
722 When t, the following will happen while the cursor is in the headline:
724 - When the cursor is at the beginning of a headline, kill the entire
725 line and possible the folded subtree below the line.
726 - When in the middle of the headline text, kill the headline up to the tags.
727 - When after the headline text, kill the tags."
728 :group 'org-edit-structure
729 :type 'boolean)
731 (defcustom org-yank-folded-subtrees t
732 "Non-nil means, when yanking subtrees, fold them.
733 If the kill is a single subtree, or a sequence of subtrees, i.e. if
734 it starts with a heading and all other headings in it are either children
735 or siblings, then fold all the subtrees. However, do this only if no
736 text after the yank would be swallowed into a folded tree by this action."
737 :group 'org-edit-structure
738 :type 'boolean)
740 (defcustom org-yank-adjusted-subtrees nil
741 "Non-nil means, when yanking subtrees, adjust the level.
742 With this setting, `org-paste-subtree' is used to insert the subtree, see
743 this function for details."
744 :group 'org-edit-structure
745 :type 'boolean)
747 (defcustom org-M-RET-may-split-line '((default . t))
748 "Non-nil means, M-RET will split the line at the cursor position.
749 When nil, it will go to the end of the line before making a
750 new line.
751 You may also set this option in a different way for different
752 contexts. Valid contexts are:
754 headline when creating a new headline
755 item when creating a new item
756 table in a table field
757 default the value to be used for all contexts not explicitly
758 customized"
759 :group 'org-structure
760 :group 'org-table
761 :type '(choice
762 (const :tag "Always" t)
763 (const :tag "Never" nil)
764 (repeat :greedy t :tag "Individual contexts"
765 (cons
766 (choice :tag "Context"
767 (const headline)
768 (const item)
769 (const table)
770 (const default))
771 (boolean)))))
774 (defcustom org-insert-heading-respect-content nil
775 "Non-nil means, insert new headings after the current subtree.
776 When nil, the new heading is created directly after the current line.
777 The commands \\[org-insert-heading-respect-content] and
778 \\[org-insert-todo-heading-respect-content] turn this variable on
779 for the duration of the command."
780 :group 'org-structure
781 :type 'boolean)
783 (defcustom org-blank-before-new-entry '((heading . auto)
784 (plain-list-item . auto))
785 "Should `org-insert-heading' leave a blank line before new heading/item?
786 The value is an alist, with `heading' and `plain-list-item' as car,
787 and a boolean flag as cdr. For plain lists, if the variable
788 `org-empty-line-terminates-plain-lists' is set, the setting here
789 is ignored and no empty line is inserted, to keep the list in tact."
790 :group 'org-edit-structure
791 :type '(list
792 (cons (const heading)
793 (choice (const :tag "Never" nil)
794 (const :tag "Always" t)
795 (const :tag "Auto" auto)))
796 (cons (const plain-list-item)
797 (choice (const :tag "Never" nil)
798 (const :tag "Always" t)
799 (const :tag "Auto" auto)))))
801 (defcustom org-insert-heading-hook nil
802 "Hook being run after inserting a new heading."
803 :group 'org-edit-structure
804 :type 'hook)
806 (defcustom org-enable-fixed-width-editor t
807 "Non-nil means, lines starting with \":\" are treated as fixed-width.
808 This currently only means, they are never auto-wrapped.
809 When nil, such lines will be treated like ordinary lines.
810 See also the QUOTE keyword."
811 :group 'org-edit-structure
812 :type 'boolean)
814 (defcustom org-edit-src-region-extra nil
815 "Additional regexps to identify regions for editing with `org-edit-src-code'.
816 For examples see the function `org-edit-src-find-region-and-lang'.
817 The regular expression identifying the begin marker should end with a newline,
818 and the regexp marking the end line should start with a newline, to make sure
819 there are kept outside the narrowed region."
820 :group 'org-edit-structure
821 :type '(repeat
822 (list
823 (regexp :tag "begin regexp")
824 (regexp :tag "end regexp")
825 (choice :tag "language"
826 (string :tag "specify")
827 (integer :tag "from match group")
828 (const :tag "from `lang' element")
829 (const :tag "from `style' element")))))
831 (defcustom org-coderef-label-format "(ref:%s)"
832 "The default coderef format.
833 This format string will be used to search for coderef labels in literal
834 examples (EXAMPLE and SRC blocks). The format can be overwritten
835 an individual literal example with the -f option, like
837 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
839 #+END_SRC
841 If you want to use this for HTML export, make sure that the format does
842 not introduce special font-locking, and avoid the HTML special
843 characters `<', `>', and `&'. The reason for this restriction is that
844 the labels are searched for only after htmlize has done its job."
845 :group 'org-edit-structure ; FIXME this is not in the right group
846 :type 'string)
848 (defcustom org-edit-fixed-width-region-mode 'artist-mode
849 "The mode that should be used to edit fixed-width regions.
850 These are the regions where each line starts with a colon."
851 :group 'org-edit-structure
852 :type '(choice
853 (const artist-mode)
854 (const picture-mode)
855 (const fundamental-mode)
856 (function :tag "Other (specify)")))
858 (defcustom org-edit-src-persistent-message t
859 "Non-nil means show persistent exit help message while editing src examples.
860 The message is shown in the header-line, which will be created in the
861 first line of the window showing the editing buffer.
862 When nil, the message will only be shown intermittently in the echo area."
863 :group 'org-edit-structure
864 :type 'boolean)
866 (defcustom org-goto-auto-isearch t
867 "Non-nil means, typing characters in org-goto starts incremental search."
868 :group 'org-edit-structure
869 :type 'boolean)
871 (defgroup org-sparse-trees nil
872 "Options concerning sparse trees in Org-mode."
873 :tag "Org Sparse Trees"
874 :group 'org-structure)
876 (defcustom org-highlight-sparse-tree-matches t
877 "Non-nil means, highlight all matches that define a sparse tree.
878 The highlights will automatically disappear the next time the buffer is
879 changed by an edit command."
880 :group 'org-sparse-trees
881 :type 'boolean)
883 (defcustom org-remove-highlights-with-change t
884 "Non-nil means, any change to the buffer will remove temporary highlights.
885 Such highlights are created by `org-occur' and `org-clock-display'.
886 When nil, `C-c C-c needs to be used to get rid of the highlights.
887 The highlights created by `org-preview-latex-fragment' always need
888 `C-c C-c' to be removed."
889 :group 'org-sparse-trees
890 :group 'org-time
891 :type 'boolean)
894 (defcustom org-occur-hook '(org-first-headline-recenter)
895 "Hook that is run after `org-occur' has constructed a sparse tree.
896 This can be used to recenter the window to show as much of the structure
897 as possible."
898 :group 'org-sparse-trees
899 :type 'hook)
901 (defgroup org-imenu-and-speedbar nil
902 "Options concerning imenu and speedbar in Org-mode."
903 :tag "Org Imenu and Speedbar"
904 :group 'org-structure)
906 (defcustom org-imenu-depth 2
907 "The maximum level for Imenu access to Org-mode headlines.
908 This also applied for speedbar access."
909 :group 'org-imenu-and-speedbar
910 :type 'integer)
912 (defgroup org-table nil
913 "Options concerning tables in Org-mode."
914 :tag "Org Table"
915 :group 'org)
917 (defcustom org-enable-table-editor 'optimized
918 "Non-nil means, lines starting with \"|\" are handled by the table editor.
919 When nil, such lines will be treated like ordinary lines.
921 When equal to the symbol `optimized', the table editor will be optimized to
922 do the following:
923 - Automatic overwrite mode in front of whitespace in table fields.
924 This makes the structure of the table stay in tact as long as the edited
925 field does not exceed the column width.
926 - Minimize the number of realigns. Normally, the table is aligned each time
927 TAB or RET are pressed to move to another field. With optimization this
928 happens only if changes to a field might have changed the column width.
929 Optimization requires replacing the functions `self-insert-command',
930 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
931 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
932 very good at guessing when a re-align will be necessary, but you can always
933 force one with \\[org-ctrl-c-ctrl-c].
935 If you would like to use the optimized version in Org-mode, but the
936 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
938 This variable can be used to turn on and off the table editor during a session,
939 but in order to toggle optimization, a restart is required.
941 See also the variable `org-table-auto-blank-field'."
942 :group 'org-table
943 :type '(choice
944 (const :tag "off" nil)
945 (const :tag "on" t)
946 (const :tag "on, optimized" optimized)))
948 (defcustom org-self-insert-cluster-for-undo t
949 "Non-nil means cluster self-insert commands for undo when possible.
950 If this is set, then, like in the Emacs command loop, 20 consequtive
951 characters will be undone together.
952 This is configurable, because there is some impact on typing performance."
953 :group 'org-table
954 :type 'boolean)
956 (defcustom org-table-tab-recognizes-table.el t
957 "Non-nil means, TAB will automatically notice a table.el table.
958 When it sees such a table, it moves point into it and - if necessary -
959 calls `table-recognize-table'."
960 :group 'org-table-editing
961 :type 'boolean)
963 (defgroup org-link nil
964 "Options concerning links in Org-mode."
965 :tag "Org Link"
966 :group 'org)
968 (defvar org-link-abbrev-alist-local nil
969 "Buffer-local version of `org-link-abbrev-alist', which see.
970 The value of this is taken from the #+LINK lines.")
971 (make-variable-buffer-local 'org-link-abbrev-alist-local)
973 (defcustom org-link-abbrev-alist nil
974 "Alist of link abbreviations.
975 The car of each element is a string, to be replaced at the start of a link.
976 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
977 links in Org-mode buffers can have an optional tag after a double colon, e.g.
979 [[linkkey:tag][description]]
981 The 'linkkey' must be a word word, starting with a letter, followed
982 by letters, numbers, '-' or '_'.
984 If REPLACE is a string, the tag will simply be appended to create the link.
985 If the string contains \"%s\", the tag will be inserted there. Alternatively,
986 the placeholder \"%h\" will cause a url-encoded version of the tag to
987 be inserted at that point (see the function `url-hexify-string').
989 REPLACE may also be a function that will be called with the tag as the
990 only argument to create the link, which should be returned as a string.
992 See the manual for examples."
993 :group 'org-link
994 :type '(repeat
995 (cons
996 (string :tag "Protocol")
997 (choice
998 (string :tag "Format")
999 (function)))))
1001 (defcustom org-descriptive-links t
1002 "Non-nil means, hide link part and only show description of bracket links.
1003 Bracket links are like [[link][description]]. This variable sets the initial
1004 state in new org-mode buffers. The setting can then be toggled on a
1005 per-buffer basis from the Org->Hyperlinks menu."
1006 :group 'org-link
1007 :type 'boolean)
1009 (defcustom org-link-file-path-type 'adaptive
1010 "How the path name in file links should be stored.
1011 Valid values are:
1013 relative Relative to the current directory, i.e. the directory of the file
1014 into which the link is being inserted.
1015 absolute Absolute path, if possible with ~ for home directory.
1016 noabbrev Absolute path, no abbreviation of home directory.
1017 adaptive Use relative path for files in the current directory and sub-
1018 directories of it. For other files, use an absolute path."
1019 :group 'org-link
1020 :type '(choice
1021 (const relative)
1022 (const absolute)
1023 (const noabbrev)
1024 (const adaptive)))
1026 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1027 "Types of links that should be activated in Org-mode files.
1028 This is a list of symbols, each leading to the activation of a certain link
1029 type. In principle, it does not hurt to turn on most link types - there may
1030 be a small gain when turning off unused link types. The types are:
1032 bracket The recommended [[link][description]] or [[link]] links with hiding.
1033 angular Links in angular brackets that may contain whitespace like
1034 <bbdb:Carsten Dominik>.
1035 plain Plain links in normal text, no whitespace, like http://google.com.
1036 radio Text that is matched by a radio target, see manual for details.
1037 tag Tag settings in a headline (link to tag search).
1038 date Time stamps (link to calendar).
1039 footnote Footnote labels.
1041 Changing this variable requires a restart of Emacs to become effective."
1042 :group 'org-link
1043 :type '(set :greedy t
1044 (const :tag "Double bracket links (new style)" bracket)
1045 (const :tag "Angular bracket links (old style)" angular)
1046 (const :tag "Plain text links" plain)
1047 (const :tag "Radio target matches" radio)
1048 (const :tag "Tags" tag)
1049 (const :tag "Timestamps" date)
1050 (const :tag "Footnotes" footnote)))
1052 (defcustom org-make-link-description-function nil
1053 "Function to use to generate link descriptions from links. If
1054 nil the link location will be used. This function must take two
1055 parameters; the first is the link and the second the description
1056 org-insert-link has generated, and should return the description
1057 to use."
1058 :group 'org-link
1059 :type 'function)
1061 (defgroup org-link-store nil
1062 "Options concerning storing links in Org-mode."
1063 :tag "Org Store Link"
1064 :group 'org-link)
1066 (defcustom org-email-link-description-format "Email %c: %.30s"
1067 "Format of the description part of a link to an email or usenet message.
1068 The following %-escapes will be replaced by corresponding information:
1070 %F full \"From\" field
1071 %f name, taken from \"From\" field, address if no name
1072 %T full \"To\" field
1073 %t first name in \"To\" field, address if no name
1074 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1075 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1076 %s subject
1077 %m message-id.
1079 You may use normal field width specification between the % and the letter.
1080 This is for example useful to limit the length of the subject.
1082 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1083 :group 'org-link-store
1084 :type 'string)
1086 (defcustom org-from-is-user-regexp
1087 (let (r1 r2)
1088 (when (and user-mail-address (not (string= user-mail-address "")))
1089 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1090 (when (and user-full-name (not (string= user-full-name "")))
1091 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1092 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1093 "Regexp matched against the \"From:\" header of an email or usenet message.
1094 It should match if the message is from the user him/herself."
1095 :group 'org-link-store
1096 :type 'regexp)
1098 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1099 "Non-nil means, storing a link to an Org file will use entry IDs.
1101 Note that before this variable is even considered, org-id must be loaded,
1102 to please customize `org-modules' and turn it on.
1104 The variable can have the following values:
1106 t Create an ID if needed to make a link to the current entry.
1108 create-if-interactive
1109 If `org-store-link' is called directly (interactively, as a user
1110 command), do create an ID to support the link. But when doing the
1111 job for remember, only use the ID if it already exists. The
1112 purpose of this setting is to avoid proliferation of unwanted
1113 IDs, just because you happen to be in an Org file when you
1114 call `org-remember' that automatically and preemptively
1115 creates a link. If you do want to get an ID link in a remember
1116 template to an entry not having an ID, create it first by
1117 explicitly creating a link to it, using `C-c C-l' first.
1119 use-existing
1120 Use existing ID, do not create one.
1122 nil Never use an ID to make a link, instead link using a text search for
1123 the headline text."
1124 :group 'org-link-store
1125 :type '(choice
1126 (const :tag "Create ID to make link" t)
1127 (const :tag "Create if storing link interactively"
1128 create-if-interactive)
1129 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1130 create-if-interactive-and-no-custom-id)
1131 (const :tag "Only use existing" use-existing)
1132 (const :tag "Do not use ID to create link" nil)))
1134 (defcustom org-context-in-file-links t
1135 "Non-nil means, file links from `org-store-link' contain context.
1136 A search string will be added to the file name with :: as separator and
1137 used to find the context when the link is activated by the command
1138 `org-open-at-point'.
1139 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1140 negates this setting for the duration of the command."
1141 :group 'org-link-store
1142 :type 'boolean)
1144 (defcustom org-keep-stored-link-after-insertion nil
1145 "Non-nil means, keep link in list for entire session.
1147 The command `org-store-link' adds a link pointing to the current
1148 location to an internal list. These links accumulate during a session.
1149 The command `org-insert-link' can be used to insert links into any
1150 Org-mode file (offering completion for all stored links). When this
1151 option is nil, every link which has been inserted once using \\[org-insert-link]
1152 will be removed from the list, to make completing the unused links
1153 more efficient."
1154 :group 'org-link-store
1155 :type 'boolean)
1157 (defgroup org-link-follow nil
1158 "Options concerning following links in Org-mode."
1159 :tag "Org Follow Link"
1160 :group 'org-link)
1162 (defcustom org-link-translation-function nil
1163 "Function to translate links with different syntax to Org syntax.
1164 This can be used to translate links created for example by the Planner
1165 or emacs-wiki packages to Org syntax.
1166 The function must accept two parameters, a TYPE containing the link
1167 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1168 which is everything after the link protocol. It should return a cons
1169 with possibly modified values of type and path.
1170 Org contains a function for this, so if you set this variable to
1171 `org-translate-link-from-planner', you should be able follow many
1172 links created by planner."
1173 :group 'org-link-follow
1174 :type 'function)
1176 (defcustom org-follow-link-hook nil
1177 "Hook that is run after a link has been followed."
1178 :group 'org-link-follow
1179 :type 'hook)
1181 (defcustom org-tab-follows-link nil
1182 "Non-nil means, on links TAB will follow the link.
1183 Needs to be set before org.el is loaded.
1184 This really should not be used, it does not make sense, and the
1185 implementation is bad."
1186 :group 'org-link-follow
1187 :type 'boolean)
1189 (defcustom org-return-follows-link nil
1190 "Non-nil means, on links RET will follow the link.
1191 Needs to be set before org.el is loaded."
1192 :group 'org-link-follow
1193 :type 'boolean)
1195 (defcustom org-mouse-1-follows-link
1196 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1197 "Non-nil means, mouse-1 on a link will follow the link.
1198 A longer mouse click will still set point. Does not work on XEmacs.
1199 Needs to be set before org.el is loaded."
1200 :group 'org-link-follow
1201 :type 'boolean)
1203 (defcustom org-mark-ring-length 4
1204 "Number of different positions to be recorded in the ring
1205 Changing this requires a restart of Emacs to work correctly."
1206 :group 'org-link-follow
1207 :type 'integer)
1209 (defcustom org-link-frame-setup
1210 '((vm . vm-visit-folder-other-frame)
1211 (gnus . gnus-other-frame)
1212 (file . find-file-other-window))
1213 "Setup the frame configuration for following links.
1214 When following a link with Emacs, it may often be useful to display
1215 this link in another window or frame. This variable can be used to
1216 set this up for the different types of links.
1217 For VM, use any of
1218 `vm-visit-folder'
1219 `vm-visit-folder-other-frame'
1220 For Gnus, use any of
1221 `gnus'
1222 `gnus-other-frame'
1223 `org-gnus-no-new-news'
1224 For FILE, use any of
1225 `find-file'
1226 `find-file-other-window'
1227 `find-file-other-frame'
1228 For the calendar, use the variable `calendar-setup'.
1229 For BBDB, it is currently only possible to display the matches in
1230 another window."
1231 :group 'org-link-follow
1232 :type '(list
1233 (cons (const vm)
1234 (choice
1235 (const vm-visit-folder)
1236 (const vm-visit-folder-other-window)
1237 (const vm-visit-folder-other-frame)))
1238 (cons (const gnus)
1239 (choice
1240 (const gnus)
1241 (const gnus-other-frame)
1242 (const org-gnus-no-new-news)))
1243 (cons (const file)
1244 (choice
1245 (const find-file)
1246 (const find-file-other-window)
1247 (const find-file-other-frame)))))
1249 (defcustom org-display-internal-link-with-indirect-buffer nil
1250 "Non-nil means, use indirect buffer to display infile links.
1251 Activating internal links (from one location in a file to another location
1252 in the same file) normally just jumps to the location. When the link is
1253 activated with a C-u prefix (or with mouse-3), the link is displayed in
1254 another window. When this option is set, the other window actually displays
1255 an indirect buffer clone of the current buffer, to avoid any visibility
1256 changes to the current buffer."
1257 :group 'org-link-follow
1258 :type 'boolean)
1260 (defcustom org-open-non-existing-files nil
1261 "Non-nil means, `org-open-file' will open non-existing files.
1262 When nil, an error will be generated."
1263 :group 'org-link-follow
1264 :type 'boolean)
1266 (defcustom org-open-directory-means-index-dot-org nil
1267 "Non-nil means, a link to a directory really means to index.org.
1268 When nil, following a directory link will run dired or open a finder/explorer
1269 window on that directory."
1270 :group 'org-link-follow
1271 :type 'boolean)
1273 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1274 "Function and arguments to call for following mailto links.
1275 This is a list with the first element being a lisp function, and the
1276 remaining elements being arguments to the function. In string arguments,
1277 %a will be replaced by the address, and %s will be replaced by the subject
1278 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1279 :group 'org-link-follow
1280 :type '(choice
1281 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1282 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1283 (const :tag "message-mail" (message-mail "%a" "%s"))
1284 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1286 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1287 "Non-nil means, ask for confirmation before executing shell links.
1288 Shell links can be dangerous: just think about a link
1290 [[shell:rm -rf ~/*][Google Search]]
1292 This link would show up in your Org-mode document as \"Google Search\",
1293 but really it would remove your entire home directory.
1294 Therefore we advise against setting this variable to nil.
1295 Just change it to `y-or-n-p' if you want to confirm with a
1296 single keystroke rather than having to type \"yes\"."
1297 :group 'org-link-follow
1298 :type '(choice
1299 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1300 (const :tag "with y-or-n (faster)" y-or-n-p)
1301 (const :tag "no confirmation (dangerous)" nil)))
1303 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1304 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1305 Elisp links can be dangerous: just think about a link
1307 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1309 This link would show up in your Org-mode document as \"Google Search\",
1310 but really it would remove your entire home directory.
1311 Therefore we advise against setting this variable to nil.
1312 Just change it to `y-or-n-p' if you want to confirm with a
1313 single keystroke rather than having to type \"yes\"."
1314 :group 'org-link-follow
1315 :type '(choice
1316 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1317 (const :tag "with y-or-n (faster)" y-or-n-p)
1318 (const :tag "no confirmation (dangerous)" nil)))
1320 (defconst org-file-apps-defaults-gnu
1321 '((remote . emacs)
1322 (system . mailcap)
1323 (t . mailcap))
1324 "Default file applications on a UNIX or GNU/Linux system.
1325 See `org-file-apps'.")
1327 (defconst org-file-apps-defaults-macosx
1328 '((remote . emacs)
1329 (t . "open %s")
1330 (system . "open %s")
1331 ("ps.gz" . "gv %s")
1332 ("eps.gz" . "gv %s")
1333 ("dvi" . "xdvi %s")
1334 ("fig" . "xfig %s"))
1335 "Default file applications on a MacOS X system.
1336 The system \"open\" is known as a default, but we use X11 applications
1337 for some files for which the OS does not have a good default.
1338 See `org-file-apps'.")
1340 (defconst org-file-apps-defaults-windowsnt
1341 (list
1342 '(remote . emacs)
1343 (cons t
1344 (list (if (featurep 'xemacs)
1345 'mswindows-shell-execute
1346 'w32-shell-execute)
1347 "open" 'file))
1348 (cons 'system
1349 (list (if (featurep 'xemacs)
1350 'mswindows-shell-execute
1351 'w32-shell-execute)
1352 "open" 'file)))
1353 "Default file applications on a Windows NT system.
1354 The system \"open\" is used for most files.
1355 See `org-file-apps'.")
1357 (defcustom org-file-apps
1359 (auto-mode . emacs)
1360 ("\\.x?html?\\'" . default)
1361 ("\\.pdf\\'" . default)
1363 "External applications for opening `file:path' items in a document.
1364 Org-mode uses system defaults for different file types, but
1365 you can use this variable to set the application for a given file
1366 extension. The entries in this list are cons cells where the car identifies
1367 files and the cdr the corresponding command. Possible values for the
1368 file identifier are
1369 \"regex\" Regular expression matched against the file name. For backward
1370 compatibility, this can also be a string with only alphanumeric
1371 characters, which is then interpreted as an extension.
1372 `directory' Matches a directory
1373 `remote' Matches a remote file, accessible through tramp or efs.
1374 Remote files most likely should be visited through Emacs
1375 because external applications cannot handle such paths.
1376 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1377 so all files Emacs knows how to handle. Using this with
1378 command `emacs' will open most files in Emacs. Beware that this
1379 will also open html files inside Emacs, unless you add
1380 (\"html\" . default) to the list as well.
1381 t Default for files not matched by any of the other options.
1382 `system' The system command to open files, like `open' on Windows
1383 and Mac OS X, and mailcap under GNU/Linux. This is the command
1384 that will be selected if you call `C-c C-o' with a double
1385 `C-u C-u' prefix.
1387 Possible values for the command are:
1388 `emacs' The file will be visited by the current Emacs process.
1389 `default' Use the default application for this file type, which is the
1390 association for t in the list, most likely in the system-specific
1391 part.
1392 This can be used to overrule an unwanted setting in the
1393 system-specific variable.
1394 `system' Use the system command for opening files, like \"open\".
1395 This command is specified by the entry whose car is `system'.
1396 Most likely, the system-specific version of this variable
1397 does define this command, but you can overrule/replace it
1398 here.
1399 string A command to be executed by a shell; %s will be replaced
1400 by the path to the file.
1401 sexp A Lisp form which will be evaluated. The file path will
1402 be available in the Lisp variable `file'.
1403 For more examples, see the system specific constants
1404 `org-file-apps-defaults-macosx'
1405 `org-file-apps-defaults-windowsnt'
1406 `org-file-apps-defaults-gnu'."
1407 :group 'org-link-follow
1408 :type '(repeat
1409 (cons (choice :value ""
1410 (string :tag "Extension")
1411 (const :tag "System command to open files" system)
1412 (const :tag "Default for unrecognized files" t)
1413 (const :tag "Remote file" remote)
1414 (const :tag "Links to a directory" directory)
1415 (const :tag "Any files that have Emacs modes"
1416 auto-mode))
1417 (choice :value ""
1418 (const :tag "Visit with Emacs" emacs)
1419 (const :tag "Use default" default)
1420 (const :tag "Use the system command" system)
1421 (string :tag "Command")
1422 (sexp :tag "Lisp form")))))
1424 (defgroup org-refile nil
1425 "Options concerning refiling entries in Org-mode."
1426 :tag "Org Refile"
1427 :group 'org)
1429 (defcustom org-directory "~/org"
1430 "Directory with org files.
1431 This is just a default location to look for Org files. There is no need
1432 at all to put your files into this directory. It is only used in the
1433 following situations:
1435 1. When a remember template specifies a target file that is not an
1436 absolute path. The path will then be interpreted relative to
1437 `org-directory'
1438 2. When a remember note is filed away in an interactive way (when exiting the
1439 note buffer with `C-1 C-c C-c'. The the user is prompted for an org file,
1440 with `org-directory' as the default path."
1441 :group 'org-refile
1442 :group 'org-remember
1443 :type 'directory)
1445 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1446 "Default target for storing notes.
1447 Used by the hooks for remember.el. This can be a string, or nil to mean
1448 the value of `remember-data-file'.
1449 You can set this on a per-template basis with the variable
1450 `org-remember-templates'."
1451 :group 'org-refile
1452 :group 'org-remember
1453 :type '(choice
1454 (const :tag "Default from remember-data-file" nil)
1455 file))
1457 (defcustom org-goto-interface 'outline
1458 "The default interface to be used for `org-goto'.
1459 Allowed values are:
1460 outline The interface shows an outline of the relevant file
1461 and the correct heading is found by moving through
1462 the outline or by searching with incremental search.
1463 outline-path-completion Headlines in the current buffer are offered via
1464 completion. This is the interface also used by
1465 the refile command."
1466 :group 'org-refile
1467 :type '(choice
1468 (const :tag "Outline" outline)
1469 (const :tag "Outline-path-completion" outline-path-completion)))
1471 (defcustom org-goto-max-level 5
1472 "Maximum level to be considered when running org-goto with refile interface."
1473 :group 'org-refile
1474 :type 'integer)
1476 (defcustom org-reverse-note-order nil
1477 "Non-nil means, store new notes at the beginning of a file or entry.
1478 When nil, new notes will be filed to the end of a file or entry.
1479 This can also be a list with cons cells of regular expressions that
1480 are matched against file names, and values."
1481 :group 'org-remember
1482 :group 'org-refile
1483 :type '(choice
1484 (const :tag "Reverse always" t)
1485 (const :tag "Reverse never" nil)
1486 (repeat :tag "By file name regexp"
1487 (cons regexp boolean))))
1489 (defcustom org-refile-targets nil
1490 "Targets for refiling entries with \\[org-refile].
1491 This is list of cons cells. Each cell contains:
1492 - a specification of the files to be considered, either a list of files,
1493 or a symbol whose function or variable value will be used to retrieve
1494 a file name or a list of file names. If you use `org-agenda-files' for
1495 that, all agenda files will be scanned for targets. Nil means, consider
1496 headings in the current buffer.
1497 - A specification of how to find candidate refile targets. This may be
1498 any of:
1499 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1500 This tag has to be present in all target headlines, inheritance will
1501 not be considered.
1502 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1503 todo keyword.
1504 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1505 headlines that are refiling targets.
1506 - a cons cell (:level . N). Any headline of level N is considered a target.
1507 Note that, when `org-odd-levels-only' is set, level corresponds to
1508 order in hierarchy, not to the number of stars.
1509 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1510 Note that, when `org-odd-levels-only' is set, level corresponds to
1511 order in hierarchy, not to the number of stars.
1513 You can set the variable `org-refile-target-verify-function' to a function
1514 to verify each headline found by the simple critery above.
1516 When this variable is nil, all top-level headlines in the current buffer
1517 are used, equivalent to the value `((nil . (:level . 1))'."
1518 :group 'org-refile
1519 :type '(repeat
1520 (cons
1521 (choice :value org-agenda-files
1522 (const :tag "All agenda files" org-agenda-files)
1523 (const :tag "Current buffer" nil)
1524 (function) (variable) (file))
1525 (choice :tag "Identify target headline by"
1526 (cons :tag "Specific tag" (const :value :tag) (string))
1527 (cons :tag "TODO keyword" (const :value :todo) (string))
1528 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1529 (cons :tag "Level number" (const :value :level) (integer))
1530 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1532 (defcustom org-refile-target-verify-function nil
1533 "Function to verify if the headline at point should be a refile target.
1534 The function will be called without arguments, with point at the
1535 beginning of the headline. It should return t and leave point
1536 where it is if the headline is a valid target for refiling.
1538 If the target should not be selected, the function must return nil.
1539 In addition to this, it may move point to a place from where the search
1540 should be continued. For example, the function may decide that the entire
1541 subtree of the current entry should be excluded and move point to the end
1542 of the subtree."
1543 :group 'org-refile
1544 :type 'function)
1546 (defcustom org-refile-use-outline-path nil
1547 "Non-nil means, provide refile targets as paths.
1548 So a level 3 headline will be available as level1/level2/level3.
1550 When the value is `file', also include the file name (without directory)
1551 into the path. In this case, you can also stop the completion after
1552 the file name, to get entries inserted as top level in the file.
1554 When `full-file-path', include the full file path."
1555 :group 'org-refile
1556 :type '(choice
1557 (const :tag "Not" nil)
1558 (const :tag "Yes" t)
1559 (const :tag "Start with file name" file)
1560 (const :tag "Start with full file path" full-file-path)))
1562 (defcustom org-outline-path-complete-in-steps t
1563 "Non-nil means, complete the outline path in hierarchical steps.
1564 When Org-mode uses the refile interface to select an outline path
1565 \(see variable `org-refile-use-outline-path'), the completion of
1566 the path can be done is a single go, or if can be done in steps down
1567 the headline hierarchy. Going in steps is probably the best if you
1568 do not use a special completion package like `ido' or `icicles'.
1569 However, when using these packages, going in one step can be very
1570 fast, while still showing the whole path to the entry."
1571 :group 'org-refile
1572 :type 'boolean)
1574 (defcustom org-refile-allow-creating-parent-nodes nil
1575 "Non-nil means, allow to create new nodes as refile targets.
1576 New nodes are then created by adding \"/new node name\" to the completion
1577 of an existing node. When the value of this variable is `confirm',
1578 new node creation must be confirmed by the user (recommended)
1579 When nil, the completion must match an existing entry.
1581 Note that, if the new heading is not seen by the criteria
1582 listed in `org-refile-targets', multiple instances of the same
1583 heading would be created by trying again to file under the new
1584 heading."
1585 :group 'org-refile
1586 :type '(choice
1587 (const :tag "Never" nil)
1588 (const :tag "Always" t)
1589 (const :tag "Prompt for confirmation" confirm)))
1591 (defgroup org-todo nil
1592 "Options concerning TODO items in Org-mode."
1593 :tag "Org TODO"
1594 :group 'org)
1596 (defgroup org-progress nil
1597 "Options concerning Progress logging in Org-mode."
1598 :tag "Org Progress"
1599 :group 'org-time)
1601 (defvar org-todo-interpretation-widgets
1603 (:tag "Sequence (cycling hits every state)" sequence)
1604 (:tag "Type (cycling directly to DONE)" type))
1605 "The available interpretation symbols for customizing
1606 `org-todo-keywords'.
1607 Interested libraries should add to this list.")
1609 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1610 "List of TODO entry keyword sequences and their interpretation.
1611 \\<org-mode-map>This is a list of sequences.
1613 Each sequence starts with a symbol, either `sequence' or `type',
1614 indicating if the keywords should be interpreted as a sequence of
1615 action steps, or as different types of TODO items. The first
1616 keywords are states requiring action - these states will select a headline
1617 for inclusion into the global TODO list Org-mode produces. If one of
1618 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1619 signify that no further action is necessary. If \"|\" is not found,
1620 the last keyword is treated as the only DONE state of the sequence.
1622 The command \\[org-todo] cycles an entry through these states, and one
1623 additional state where no keyword is present. For details about this
1624 cycling, see the manual.
1626 TODO keywords and interpretation can also be set on a per-file basis with
1627 the special #+SEQ_TODO and #+TYP_TODO lines.
1629 Each keyword can optionally specify a character for fast state selection
1630 \(in combination with the variable `org-use-fast-todo-selection')
1631 and specifiers for state change logging, using the same syntax
1632 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1633 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1634 indicates to record a time stamp each time this state is selected.
1636 Each keyword may also specify if a timestamp or a note should be
1637 recorded when entering or leaving the state, by adding additional
1638 characters in the parenthesis after the keyword. This looks like this:
1639 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1640 record only the time of the state change. With X and Y being either
1641 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1642 Y when leaving the state if and only if the *target* state does not
1643 define X. You may omit any of the fast-selection key or X or /Y,
1644 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1646 For backward compatibility, this variable may also be just a list
1647 of keywords - in this case the interpretation (sequence or type) will be
1648 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1649 :group 'org-todo
1650 :group 'org-keywords
1651 :type '(choice
1652 (repeat :tag "Old syntax, just keywords"
1653 (string :tag "Keyword"))
1654 (repeat :tag "New syntax"
1655 (cons
1656 (choice
1657 :tag "Interpretation"
1658 ;;Quick and dirty way to see
1659 ;;`org-todo-interpretations'. This takes the
1660 ;;place of item arguments
1661 :convert-widget
1662 (lambda (widget)
1663 (widget-put widget
1664 :args (mapcar
1665 #'(lambda (x)
1666 (widget-convert
1667 (cons 'const x)))
1668 org-todo-interpretation-widgets))
1669 widget))
1670 (repeat
1671 (string :tag "Keyword"))))))
1673 (defvar org-todo-keywords-1 nil
1674 "All TODO and DONE keywords active in a buffer.")
1675 (make-variable-buffer-local 'org-todo-keywords-1)
1676 (defvar org-todo-keywords-for-agenda nil)
1677 (defvar org-done-keywords-for-agenda nil)
1678 (defvar org-todo-keyword-alist-for-agenda nil)
1679 (defvar org-tag-alist-for-agenda nil)
1680 (defvar org-agenda-contributing-files nil)
1681 (defvar org-not-done-keywords nil)
1682 (make-variable-buffer-local 'org-not-done-keywords)
1683 (defvar org-done-keywords nil)
1684 (make-variable-buffer-local 'org-done-keywords)
1685 (defvar org-todo-heads nil)
1686 (make-variable-buffer-local 'org-todo-heads)
1687 (defvar org-todo-sets nil)
1688 (make-variable-buffer-local 'org-todo-sets)
1689 (defvar org-todo-log-states nil)
1690 (make-variable-buffer-local 'org-todo-log-states)
1691 (defvar org-todo-kwd-alist nil)
1692 (make-variable-buffer-local 'org-todo-kwd-alist)
1693 (defvar org-todo-key-alist nil)
1694 (make-variable-buffer-local 'org-todo-key-alist)
1695 (defvar org-todo-key-trigger nil)
1696 (make-variable-buffer-local 'org-todo-key-trigger)
1698 (defcustom org-todo-interpretation 'sequence
1699 "Controls how TODO keywords are interpreted.
1700 This variable is in principle obsolete and is only used for
1701 backward compatibility, if the interpretation of todo keywords is
1702 not given already in `org-todo-keywords'. See that variable for
1703 more information."
1704 :group 'org-todo
1705 :group 'org-keywords
1706 :type '(choice (const sequence)
1707 (const type)))
1709 (defcustom org-use-fast-todo-selection t
1710 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1711 This variable describes if and under what circumstances the cycling
1712 mechanism for TODO keywords will be replaced by a single-key, direct
1713 selection scheme.
1715 When nil, fast selection is never used.
1717 When the symbol `prefix', it will be used when `org-todo' is called with
1718 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1719 in an agenda buffer.
1721 When t, fast selection is used by default. In this case, the prefix
1722 argument forces cycling instead.
1724 In all cases, the special interface is only used if access keys have actually
1725 been assigned by the user, i.e. if keywords in the configuration are followed
1726 by a letter in parenthesis, like TODO(t)."
1727 :group 'org-todo
1728 :type '(choice
1729 (const :tag "Never" nil)
1730 (const :tag "By default" t)
1731 (const :tag "Only with C-u C-c C-t" prefix)))
1733 (defcustom org-provide-todo-statistics t
1734 "Non-nil means, update todo statistics after insert and toggle.
1735 When this is set, todo statistics is updated in the parent of the current
1736 entry each time a todo state is changed."
1737 :group 'org-todo
1738 :type 'boolean)
1740 (defcustom org-after-todo-state-change-hook nil
1741 "Hook which is run after the state of a TODO item was changed.
1742 The new state (a string with a TODO keyword, or nil) is available in the
1743 Lisp variable `state'."
1744 :group 'org-todo
1745 :type 'hook)
1747 (defvar org-blocker-hook nil
1748 "Hook for functions that are allowed to block a state change.
1750 Each function gets as its single argument a property list, see
1751 `org-trigger-hook' for more information about this list.
1753 If any of the functions in this hook returns nil, the state change
1754 is blocked.")
1756 (defvar org-trigger-hook nil
1757 "Hook for functions that are triggered by a state change.
1759 Each function gets as its single argument a property list with at least
1760 the following elements:
1762 (:type type-of-change :position pos-at-entry-start
1763 :from old-state :to new-state)
1765 Depending on the type, more properties may be present.
1767 This mechanism is currently implemented for:
1769 TODO state changes
1770 ------------------
1771 :type todo-state-change
1772 :from previous state (keyword as a string), or nil, or a symbol
1773 'todo' or 'done', to indicate the general type of state.
1774 :to new state, like in :from")
1776 (defcustom org-enforce-todo-dependencies nil
1777 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1778 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1779 be blocked if any prior sibling is not yet done.
1780 Finally, if the parent is blocked because of ordered siblings of its own,
1781 the child will also be blocked.
1782 This variable needs to be set before org.el is loaded, and you need to
1783 restart Emacs after a change to make the change effective. The only way
1784 to change is while Emacs is running is through the customize interface."
1785 :set (lambda (var val)
1786 (set var val)
1787 (if val
1788 (add-hook 'org-blocker-hook
1789 'org-block-todo-from-children-or-siblings-or-parent)
1790 (remove-hook 'org-blocker-hook
1791 'org-block-todo-from-children-or-siblings-or-parent)))
1792 :group 'org-todo
1793 :type 'boolean)
1795 (defcustom org-enforce-todo-checkbox-dependencies nil
1796 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1797 When this is nil, checkboxes have no influence on switching TODO states.
1798 When non-nil, you first need to check off all check boxes before the TODO
1799 entry can be switched to DONE.
1800 This variable needs to be set before org.el is loaded, and you need to
1801 restart Emacs after a change to make the change effective. The only way
1802 to change is while Emacs is running is through the customize interface."
1803 :set (lambda (var val)
1804 (set var val)
1805 (if val
1806 (add-hook 'org-blocker-hook
1807 'org-block-todo-from-checkboxes)
1808 (remove-hook 'org-blocker-hook
1809 'org-block-todo-from-checkboxes)))
1810 :group 'org-todo
1811 :type 'boolean)
1813 (defcustom org-todo-state-tags-triggers nil
1814 "Tag changes that should be triggered by TODO state changes.
1815 This is a list. Each entry is
1817 (state-change (tag . flag) .......)
1819 State-change can be a string with a state, and empty string to indicate the
1820 state that has no TODO keyword, or it can be one of the symbols `todo'
1821 or `done', meaning any not-done or done state, respectively."
1822 :group 'org-todo
1823 :group 'org-tags
1824 :type '(repeat
1825 (cons (choice :tag "When changing to"
1826 (const :tag "Not-done state" todo)
1827 (const :tag "Done state" done)
1828 (string :tag "State"))
1829 (repeat
1830 (cons :tag "Tag action"
1831 (string :tag "Tag")
1832 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1834 (defcustom org-log-done nil
1835 "Information to record when a task moves to the DONE state.
1837 Possible values are:
1839 nil Don't add anything, just change the keyword
1840 time Add a time stamp to the task
1841 note Prompt a closing note and add it with template `org-log-note-headings'
1843 This option can also be set with on a per-file-basis with
1845 #+STARTUP: nologdone
1846 #+STARTUP: logdone
1847 #+STARTUP: lognotedone
1849 You can have local logging settings for a subtree by setting the LOGGING
1850 property to one or more of these keywords."
1851 :group 'org-todo
1852 :group 'org-progress
1853 :type '(choice
1854 (const :tag "No logging" nil)
1855 (const :tag "Record CLOSED timestamp" time)
1856 (const :tag "Record CLOSED timestamp with closing note." note)))
1858 ;; Normalize old uses of org-log-done.
1859 (cond
1860 ((eq org-log-done t) (setq org-log-done 'time))
1861 ((and (listp org-log-done) (memq 'done org-log-done))
1862 (setq org-log-done 'note)))
1864 (defcustom org-log-note-clock-out nil
1865 "Non-nil means, record a note when clocking out of an item.
1866 This can also be configured on a per-file basis by adding one of
1867 the following lines anywhere in the buffer:
1869 #+STARTUP: lognoteclock-out
1870 #+STARTUP: nolognoteclock-out"
1871 :group 'org-todo
1872 :group 'org-progress
1873 :type 'boolean)
1875 (defcustom org-log-done-with-time t
1876 "Non-nil means, the CLOSED time stamp will contain date and time.
1877 When nil, only the date will be recorded."
1878 :group 'org-progress
1879 :type 'boolean)
1881 (defcustom org-log-note-headings
1882 '((done . "CLOSING NOTE %t")
1883 (state . "State %-12s from %-12S %t")
1884 (note . "Note taken on %t")
1885 (clock-out . ""))
1886 "Headings for notes added to entries.
1887 The value is an alist, with the car being a symbol indicating the note
1888 context, and the cdr is the heading to be used. The heading may also be the
1889 empty string.
1890 %t in the heading will be replaced by a time stamp.
1891 %s will be replaced by the new TODO state, in double quotes.
1892 %S will be replaced by the old TODO state, in double quotes.
1893 %u will be replaced by the user name.
1894 %U will be replaced by the full user name."
1895 :group 'org-todo
1896 :group 'org-progress
1897 :type '(list :greedy t
1898 (cons (const :tag "Heading when closing an item" done) string)
1899 (cons (const :tag
1900 "Heading when changing todo state (todo sequence only)"
1901 state) string)
1902 (cons (const :tag "Heading when just taking a note" note) string)
1903 (cons (const :tag "Heading when clocking out" clock-out) string)))
1905 (unless (assq 'note org-log-note-headings)
1906 (push '(note . "%t") org-log-note-headings))
1908 (defcustom org-log-into-drawer nil
1909 "Non-nil means, insert state change notes and time stamps into a drawer.
1910 When nil, state changes notes will be inserted after the headline and
1911 any scheduling and clock lines, but not inside a drawer.
1913 The value of this variable should be the name of the drawer to use.
1914 LOGBOOK is proposed at the default drawer for this purpose, you can
1915 also set this to a string to define the drawer of your choice.
1917 A value of t is also allowed, representing \"LOGBOOK\".
1919 If this variable is set, `org-log-state-notes-insert-after-drawers'
1920 will be ignored.
1922 You can set the property LOG_INTO_DRAWER to overrule this setting for
1923 a subtree."
1924 :group 'org-todo
1925 :group 'org-progress
1926 :type '(choice
1927 (const :tag "Not into a drawer" nil)
1928 (const :tag "LOGBOOK" t)
1929 (string :tag "Other")))
1931 (if (fboundp 'defvaralias)
1932 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
1934 (defun org-log-into-drawer ()
1935 "Return the value of `org-log-into-drawer', but let properties overrule.
1936 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
1937 used instead of the default value."
1938 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
1939 (cond
1940 ((or (not p) (equal p "nil")) org-log-into-drawer)
1941 ((equal p "t") "LOGBOOK")
1942 (t p))))
1944 (defcustom org-log-state-notes-insert-after-drawers nil
1945 "Non-nil means, insert state change notes after any drawers in entry.
1946 Only the drawers that *immediately* follow the headline and the
1947 deadline/scheduled line are skipped.
1948 When nil, insert notes right after the heading and perhaps the line
1949 with deadline/scheduling if present.
1951 This variable will have no effect if `org-log-into-drawer' is
1952 set."
1953 :group 'org-todo
1954 :group 'org-progress
1955 :type 'boolean)
1957 (defcustom org-log-states-order-reversed t
1958 "Non-nil means, the latest state change note will be directly after heading.
1959 When nil, the notes will be orderer according to time."
1960 :group 'org-todo
1961 :group 'org-progress
1962 :type 'boolean)
1964 (defcustom org-log-repeat 'time
1965 "Non-nil means, record moving through the DONE state when triggering repeat.
1966 An auto-repeating tasks is immediately switched back to TODO when marked
1967 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1968 the TODO keyword definition, or recording a closing note by setting
1969 `org-log-done', there will be no record of the task moving through DONE.
1970 This variable forces taking a note anyway. Possible values are:
1972 nil Don't force a record
1973 time Record a time stamp
1974 note Record a note
1976 This option can also be set with on a per-file-basis with
1978 #+STARTUP: logrepeat
1979 #+STARTUP: lognoterepeat
1980 #+STARTUP: nologrepeat
1982 You can have local logging settings for a subtree by setting the LOGGING
1983 property to one or more of these keywords."
1984 :group 'org-todo
1985 :group 'org-progress
1986 :type '(choice
1987 (const :tag "Don't force a record" nil)
1988 (const :tag "Force recording the DONE state" time)
1989 (const :tag "Force recording a note with the DONE state" note)))
1992 (defgroup org-priorities nil
1993 "Priorities in Org-mode."
1994 :tag "Org Priorities"
1995 :group 'org-todo)
1997 (defcustom org-highest-priority ?A
1998 "The highest priority of TODO items. A character like ?A, ?B etc.
1999 Must have a smaller ASCII number than `org-lowest-priority'."
2000 :group 'org-priorities
2001 :type 'character)
2003 (defcustom org-lowest-priority ?C
2004 "The lowest priority of TODO items. A character like ?A, ?B etc.
2005 Must have a larger ASCII number than `org-highest-priority'."
2006 :group 'org-priorities
2007 :type 'character)
2009 (defcustom org-default-priority ?B
2010 "The default priority of TODO items.
2011 This is the priority an item get if no explicit priority is given."
2012 :group 'org-priorities
2013 :type 'character)
2015 (defcustom org-priority-start-cycle-with-default t
2016 "Non-nil means, start with default priority when starting to cycle.
2017 When this is nil, the first step in the cycle will be (depending on the
2018 command used) one higher or lower that the default priority."
2019 :group 'org-priorities
2020 :type 'boolean)
2022 (defgroup org-time nil
2023 "Options concerning time stamps and deadlines in Org-mode."
2024 :tag "Org Time"
2025 :group 'org)
2027 (defcustom org-insert-labeled-timestamps-at-point nil
2028 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
2029 When nil, these labeled time stamps are forces into the second line of an
2030 entry, just after the headline. When scheduling from the global TODO list,
2031 the time stamp will always be forced into the second line."
2032 :group 'org-time
2033 :type 'boolean)
2035 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2036 "Formats for `format-time-string' which are used for time stamps.
2037 It is not recommended to change this constant.")
2039 (defcustom org-time-stamp-rounding-minutes '(0 5)
2040 "Number of minutes to round time stamps to.
2041 These are two values, the first applies when first creating a time stamp.
2042 The second applies when changing it with the commands `S-up' and `S-down'.
2043 When changing the time stamp, this means that it will change in steps
2044 of N minutes, as given by the second value.
2046 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2047 numbers should be factors of 60, so for example 5, 10, 15.
2049 When this is larger than 1, you can still force an exact time-stamp by using
2050 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2051 and by using a prefix arg to `S-up/down' to specify the exact number
2052 of minutes to shift."
2053 :group 'org-time
2054 :get '(lambda (var) ; Make sure all entries have 5 elements
2055 (if (integerp (default-value var))
2056 (list (default-value var) 5)
2057 (default-value var)))
2058 :type '(list
2059 (integer :tag "when inserting times")
2060 (integer :tag "when modifying times")))
2062 ;; Normalize old customizations of this variable.
2063 (when (integerp org-time-stamp-rounding-minutes)
2064 (setq org-time-stamp-rounding-minutes
2065 (list org-time-stamp-rounding-minutes
2066 org-time-stamp-rounding-minutes)))
2068 (defcustom org-display-custom-times nil
2069 "Non-nil means, overlay custom formats over all time stamps.
2070 The formats are defined through the variable `org-time-stamp-custom-formats'.
2071 To turn this on on a per-file basis, insert anywhere in the file:
2072 #+STARTUP: customtime"
2073 :group 'org-time
2074 :set 'set-default
2075 :type 'sexp)
2076 (make-variable-buffer-local 'org-display-custom-times)
2078 (defcustom org-time-stamp-custom-formats
2079 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2080 "Custom formats for time stamps. See `format-time-string' for the syntax.
2081 These are overlayed over the default ISO format if the variable
2082 `org-display-custom-times' is set. Time like %H:%M should be at the
2083 end of the second format. The custom formats are also honored by export
2084 commands, if custom time display is turned on at the time of export."
2085 :group 'org-time
2086 :type 'sexp)
2088 (defun org-time-stamp-format (&optional long inactive)
2089 "Get the right format for a time string."
2090 (let ((f (if long (cdr org-time-stamp-formats)
2091 (car org-time-stamp-formats))))
2092 (if inactive
2093 (concat "[" (substring f 1 -1) "]")
2094 f)))
2096 (defcustom org-time-clocksum-format "%d:%02d"
2097 "The format string used when creating CLOCKSUM lines, or when
2098 org-mode generates a time duration."
2099 :group 'org-time
2100 :type 'string)
2102 (defcustom org-deadline-warning-days 14
2103 "No. of days before expiration during which a deadline becomes active.
2104 This variable governs the display in sparse trees and in the agenda.
2105 When 0 or negative, it means use this number (the absolute value of it)
2106 even if a deadline has a different individual lead time specified.
2108 Custom commands can set this variable in the options section."
2109 :group 'org-time
2110 :group 'org-agenda-daily/weekly
2111 :type 'integer)
2113 (defcustom org-read-date-prefer-future t
2114 "Non-nil means, assume future for incomplete date input from user.
2115 This affects the following situations:
2116 1. The user gives a day, but no month.
2117 For example, if today is the 15th, and you enter \"3\", Org-mode will
2118 read this as the third of *next* month. However, if you enter \"17\",
2119 it will be considered as *this* month.
2120 2. The user gives a month but not a year.
2121 For example, if it is april and you enter \"feb 2\", this will be read
2122 as feb 2, *next* year. \"May 5\", however, will be this year.
2124 Currently this does not work for ISO week specifications.
2126 When this option is nil, the current month and year will always be used
2127 as defaults."
2128 :group 'org-time
2129 :type 'boolean)
2131 (defcustom org-read-date-display-live t
2132 "Non-nil means, display current interpretation of date prompt live.
2133 This display will be in an overlay, in the minibuffer."
2134 :group 'org-time
2135 :type 'boolean)
2137 (defcustom org-read-date-popup-calendar t
2138 "Non-nil means, pop up a calendar when prompting for a date.
2139 In the calendar, the date can be selected with mouse-1. However, the
2140 minibuffer will also be active, and you can simply enter the date as well.
2141 When nil, only the minibuffer will be available."
2142 :group 'org-time
2143 :type 'boolean)
2144 (if (fboundp 'defvaralias)
2145 (defvaralias 'org-popup-calendar-for-date-prompt
2146 'org-read-date-popup-calendar))
2148 (defcustom org-read-date-minibuffer-setup-hook nil
2149 "Hook to be used to set up keys for the date/time interface.
2150 Add key definitions to `minibuffer-local-map', which will be a temporary
2151 copy."
2152 :group 'org-time
2153 :type 'hook)
2155 (defcustom org-extend-today-until 0
2156 "The hour when your day really ends. Must be an integer.
2157 This has influence for the following applications:
2158 - When switching the agenda to \"today\". It it is still earlier than
2159 the time given here, the day recognized as TODAY is actually yesterday.
2160 - When a date is read from the user and it is still before the time given
2161 here, the current date and time will be assumed to be yesterday, 23:59.
2162 Also, timestamps inserted in remember templates follow this rule.
2164 IMPORTANT: This is a feature whose implementation is and likely will
2165 remain incomplete. Really, it is only here because past midnight seems to
2166 be the favorite working time of John Wiegley :-)"
2167 :group 'org-time
2168 :type 'integer)
2170 (defcustom org-edit-timestamp-down-means-later nil
2171 "Non-nil means, S-down will increase the time in a time stamp.
2172 When nil, S-up will increase."
2173 :group 'org-time
2174 :type 'boolean)
2176 (defcustom org-calendar-follow-timestamp-change t
2177 "Non-nil means, make the calendar window follow timestamp changes.
2178 When a timestamp is modified and the calendar window is visible, it will be
2179 moved to the new date."
2180 :group 'org-time
2181 :type 'boolean)
2183 (defgroup org-tags nil
2184 "Options concerning tags in Org-mode."
2185 :tag "Org Tags"
2186 :group 'org)
2188 (defcustom org-tag-alist nil
2189 "List of tags allowed in Org-mode files.
2190 When this list is nil, Org-mode will base TAG input on what is already in the
2191 buffer.
2192 The value of this variable is an alist, the car of each entry must be a
2193 keyword as a string, the cdr may be a character that is used to select
2194 that tag through the fast-tag-selection interface.
2195 See the manual for details."
2196 :group 'org-tags
2197 :type '(repeat
2198 (choice
2199 (cons (string :tag "Tag name")
2200 (character :tag "Access char"))
2201 (const :tag "Start radio group" (:startgroup))
2202 (const :tag "End radio group" (:endgroup))
2203 (const :tag "New line" (:newline)))))
2205 (defcustom org-tag-persistent-alist nil
2206 "List of tags that will always appear in all Org-mode files.
2207 This is in addition to any in buffer settings or customizations
2208 of `org-tag-alist'.
2209 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2210 The value of this variable is an alist, the car of each entry must be a
2211 keyword as a string, the cdr may be a character that is used to select
2212 that tag through the fast-tag-selection interface.
2213 See the manual for details.
2214 To disable these tags on a per-file basis, insert anywhere in the file:
2215 #+STARTUP: noptag"
2216 :group 'org-tags
2217 :type '(repeat
2218 (choice
2219 (cons (string :tag "Tag name")
2220 (character :tag "Access char"))
2221 (const :tag "Start radio group" (:startgroup))
2222 (const :tag "End radio group" (:endgroup))
2223 (const :tag "New line" (:newline)))))
2225 (defvar org-file-tags nil
2226 "List of tags that can be inherited by all entries in the file.
2227 The tags will be inherited if the variable `org-use-tag-inheritance'
2228 says they should be.
2229 This variable is populated from #+TAG lines.")
2231 (defcustom org-use-fast-tag-selection 'auto
2232 "Non-nil means, use fast tag selection scheme.
2233 This is a special interface to select and deselect tags with single keys.
2234 When nil, fast selection is never used.
2235 When the symbol `auto', fast selection is used if and only if selection
2236 characters for tags have been configured, either through the variable
2237 `org-tag-alist' or through a #+TAGS line in the buffer.
2238 When t, fast selection is always used and selection keys are assigned
2239 automatically if necessary."
2240 :group 'org-tags
2241 :type '(choice
2242 (const :tag "Always" t)
2243 (const :tag "Never" nil)
2244 (const :tag "When selection characters are configured" 'auto)))
2246 (defcustom org-fast-tag-selection-single-key nil
2247 "Non-nil means, fast tag selection exits after first change.
2248 When nil, you have to press RET to exit it.
2249 During fast tag selection, you can toggle this flag with `C-c'.
2250 This variable can also have the value `expert'. In this case, the window
2251 displaying the tags menu is not even shown, until you press C-c again."
2252 :group 'org-tags
2253 :type '(choice
2254 (const :tag "No" nil)
2255 (const :tag "Yes" t)
2256 (const :tag "Expert" expert)))
2258 (defvar org-fast-tag-selection-include-todo nil
2259 "Non-nil means, fast tags selection interface will also offer TODO states.
2260 This is an undocumented feature, you should not rely on it.")
2262 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2263 "The column to which tags should be indented in a headline.
2264 If this number is positive, it specifies the column. If it is negative,
2265 it means that the tags should be flushright to that column. For example,
2266 -80 works well for a normal 80 character screen."
2267 :group 'org-tags
2268 :type 'integer)
2270 (defcustom org-auto-align-tags t
2271 "Non-nil means, realign tags after pro/demotion of TODO state change.
2272 These operations change the length of a headline and therefore shift
2273 the tags around. With this options turned on, after each such operation
2274 the tags are again aligned to `org-tags-column'."
2275 :group 'org-tags
2276 :type 'boolean)
2278 (defcustom org-use-tag-inheritance t
2279 "Non-nil means, tags in levels apply also for sublevels.
2280 When nil, only the tags directly given in a specific line apply there.
2281 This may also be a list of tags that should be inherited, or a regexp that
2282 matches tags that should be inherited. Additional control is possible
2283 with the variable `org-tags-exclude-from-inheritance' which gives an
2284 explicit list of tags to be excluded from inheritance., even if the value of
2285 `org-use-tag-inheritance' would select it for inheritance.
2287 If this option is t, a match early-on in a tree can lead to a large
2288 number of matches in the subtree when constructing the agenda or creating
2289 a sparse tree. If you only want to see the first match in a tree during
2290 a search, check out the variable `org-tags-match-list-sublevels'."
2291 :group 'org-tags
2292 :type '(choice
2293 (const :tag "Not" nil)
2294 (const :tag "Always" t)
2295 (repeat :tag "Specific tags" (string :tag "Tag"))
2296 (regexp :tag "Tags matched by regexp")))
2298 (defcustom org-tags-exclude-from-inheritance nil
2299 "List of tags that should never be inherited.
2300 This is a way to exclude a few tags from inheritance. For way to do
2301 the opposite, to actively allow inheritance for selected tags,
2302 see the variable `org-use-tag-inheritance'."
2303 :group 'org-tags
2304 :type '(repeat (string :tag "Tag")))
2306 (defun org-tag-inherit-p (tag)
2307 "Check if TAG is one that should be inherited."
2308 (cond
2309 ((member tag org-tags-exclude-from-inheritance) nil)
2310 ((eq org-use-tag-inheritance t) t)
2311 ((not org-use-tag-inheritance) nil)
2312 ((stringp org-use-tag-inheritance)
2313 (string-match org-use-tag-inheritance tag))
2314 ((listp org-use-tag-inheritance)
2315 (member tag org-use-tag-inheritance))
2316 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2318 (defcustom org-tags-match-list-sublevels t
2319 "Non-nil means list also sublevels of headlines matching a search.
2320 This variable applies to tags/property searches, and also to stuck
2321 projects because this search is based on a tags match as well.
2323 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2324 the sublevels of a headline matching a tag search often also match
2325 the same search. Listing all of them can create very long lists.
2326 Setting this variable to nil causes subtrees of a match to be skipped.
2328 As a special case, if the tag search is restricted to TODO items, the
2329 value of this variable is ignored and sublevels are always checked, to
2330 make sure all corresponding TODO items find their way into the list.
2332 This variable is semi-obsolete and probably should always be true. It
2333 is better to limit inheritance to certain tags using the variables
2334 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2335 :group 'org-tags
2336 :type '(choice
2337 (const :tag "No, don't list them" nil)
2338 (const :tag "Yes, do list them" t)
2339 (const :tag "List them, indented with leading dots" indented)))
2341 (defvar org-tags-history nil
2342 "History of minibuffer reads for tags.")
2343 (defvar org-last-tags-completion-table nil
2344 "The last used completion table for tags.")
2345 (defvar org-after-tags-change-hook nil
2346 "Hook that is run after the tags in a line have changed.")
2348 (defgroup org-properties nil
2349 "Options concerning properties in Org-mode."
2350 :tag "Org Properties"
2351 :group 'org)
2353 (defcustom org-property-format "%-10s %s"
2354 "How property key/value pairs should be formatted by `indent-line'.
2355 When `indent-line' hits a property definition, it will format the line
2356 according to this format, mainly to make sure that the values are
2357 lined-up with respect to each other."
2358 :group 'org-properties
2359 :type 'string)
2361 (defcustom org-use-property-inheritance nil
2362 "Non-nil means, properties apply also for sublevels.
2364 This setting is chiefly used during property searches. Turning it on can
2365 cause significant overhead when doing a search, which is why it is not
2366 on by default.
2368 When nil, only the properties directly given in the current entry count.
2369 When t, every property is inherited. The value may also be a list of
2370 properties that should have inheritance, or a regular expression matching
2371 properties that should be inherited.
2373 However, note that some special properties use inheritance under special
2374 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2375 and the properties ending in \"_ALL\" when they are used as descriptor
2376 for valid values of a property.
2378 Note for programmers:
2379 When querying an entry with `org-entry-get', you can control if inheritance
2380 should be used. By default, `org-entry-get' looks only at the local
2381 properties. You can request inheritance by setting the inherit argument
2382 to t (to force inheritance) or to `selective' (to respect the setting
2383 in this variable)."
2384 :group 'org-properties
2385 :type '(choice
2386 (const :tag "Not" nil)
2387 (const :tag "Always" t)
2388 (repeat :tag "Specific properties" (string :tag "Property"))
2389 (regexp :tag "Properties matched by regexp")))
2391 (defun org-property-inherit-p (property)
2392 "Check if PROPERTY is one that should be inherited."
2393 (cond
2394 ((eq org-use-property-inheritance t) t)
2395 ((not org-use-property-inheritance) nil)
2396 ((stringp org-use-property-inheritance)
2397 (string-match org-use-property-inheritance property))
2398 ((listp org-use-property-inheritance)
2399 (member property org-use-property-inheritance))
2400 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2402 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2403 "The default column format, if no other format has been defined.
2404 This variable can be set on the per-file basis by inserting a line
2406 #+COLUMNS: %25ITEM ....."
2407 :group 'org-properties
2408 :type 'string)
2410 (defcustom org-columns-ellipses ".."
2411 "The ellipses to be used when a field in column view is truncated.
2412 When this is the empty string, as many characters as possible are shown,
2413 but then there will be no visual indication that the field has been truncated.
2414 When this is a string of length N, the last N characters of a truncated
2415 field are replaced by this string. If the column is narrower than the
2416 ellipses string, only part of the ellipses string will be shown."
2417 :group 'org-properties
2418 :type 'string)
2420 (defcustom org-columns-modify-value-for-display-function nil
2421 "Function that modifies values for display in column view.
2422 For example, it can be used to cut out a certain part from a time stamp.
2423 The function must take 2 arguments:
2425 column-title The title of the column (*not* the property name)
2426 value The value that should be modified.
2428 The function should return the value that should be displayed,
2429 or nil if the normal value should be used."
2430 :group 'org-properties
2431 :type 'function)
2433 (defcustom org-effort-property "Effort"
2434 "The property that is being used to keep track of effort estimates.
2435 Effort estimates given in this property need to have the format H:MM."
2436 :group 'org-properties
2437 :group 'org-progress
2438 :type '(string :tag "Property"))
2440 (defconst org-global-properties-fixed
2441 '(("VISIBILITY_ALL" . "folded children content all"))
2442 "List of property/value pairs that can be inherited by any entry.
2444 These are fixed values, for the preset properties. The user variable
2445 that can be used to add to this list is `org-global-properties'.
2447 The entries in this list are cons cells where the car is a property
2448 name and cdr is a string with the value. If the value represents
2449 multiple items like an \"_ALL\" property, separate the items by
2450 spaces.")
2452 (defcustom org-global-properties nil
2453 "List of property/value pairs that can be inherited by any entry.
2455 This list will be combined with the constant `org-global-properties-fixed'.
2457 The entries in this list are cons cells where the car is a property
2458 name and cdr is a string with the value.
2460 You can set buffer-local values for the same purpose in the variable
2461 `org-file-properties' this by adding lines like
2463 #+PROPERTY: NAME VALUE"
2464 :group 'org-properties
2465 :type '(repeat
2466 (cons (string :tag "Property")
2467 (string :tag "Value"))))
2469 (defvar org-file-properties nil
2470 "List of property/value pairs that can be inherited by any entry.
2471 Valid for the current buffer.
2472 This variable is populated from #+PROPERTY lines.")
2473 (make-variable-buffer-local 'org-file-properties)
2475 (defgroup org-agenda nil
2476 "Options concerning agenda views in Org-mode."
2477 :tag "Org Agenda"
2478 :group 'org)
2480 (defvar org-category nil
2481 "Variable used by org files to set a category for agenda display.
2482 Such files should use a file variable to set it, for example
2484 # -*- mode: org; org-category: \"ELisp\"
2486 or contain a special line
2488 #+CATEGORY: ELisp
2490 If the file does not specify a category, then file's base name
2491 is used instead.")
2492 (make-variable-buffer-local 'org-category)
2493 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2495 (defcustom org-agenda-files nil
2496 "The files to be used for agenda display.
2497 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2498 \\[org-remove-file]. You can also use customize to edit the list.
2500 If an entry is a directory, all files in that directory that are matched by
2501 `org-agenda-file-regexp' will be part of the file list.
2503 If the value of the variable is not a list but a single file name, then
2504 the list of agenda files is actually stored and maintained in that file, one
2505 agenda file per line."
2506 :group 'org-agenda
2507 :type '(choice
2508 (repeat :tag "List of files and directories" file)
2509 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2511 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2512 "Regular expression to match files for `org-agenda-files'.
2513 If any element in the list in that variable contains a directory instead
2514 of a normal file, all files in that directory that are matched by this
2515 regular expression will be included."
2516 :group 'org-agenda
2517 :type 'regexp)
2519 (defcustom org-agenda-text-search-extra-files nil
2520 "List of extra files to be searched by text search commands.
2521 These files will be search in addition to the agenda files by the
2522 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2523 Note that these files will only be searched for text search commands,
2524 not for the other agenda views like todo lists, tag searches or the weekly
2525 agenda. This variable is intended to list notes and possibly archive files
2526 that should also be searched by these two commands.
2527 In fact, if the first element in the list is the symbol `agenda-archives',
2528 than all archive files of all agenda files will be added to the search
2529 scope."
2530 :group 'org-agenda
2531 :type '(set :greedy t
2532 (const :tag "Agenda Archives" agenda-archives)
2533 (repeat :inline t (file))))
2535 (if (fboundp 'defvaralias)
2536 (defvaralias 'org-agenda-multi-occur-extra-files
2537 'org-agenda-text-search-extra-files))
2539 (defcustom org-agenda-skip-unavailable-files nil
2540 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2541 A nil value means to remove them, after a query, from the list."
2542 :group 'org-agenda
2543 :type 'boolean)
2545 (defcustom org-calendar-to-agenda-key [?c]
2546 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2547 The command `org-calendar-goto-agenda' will be bound to this key. The
2548 default is the character `c' because then `c' can be used to switch back and
2549 forth between agenda and calendar."
2550 :group 'org-agenda
2551 :type 'sexp)
2553 (defcustom org-calendar-agenda-action-key [?k]
2554 "The key to be installed in `calendar-mode-map' for agenda-action.
2555 The command `org-agenda-action' will be bound to this key. The
2556 default is the character `k' because we use the same key in the agenda."
2557 :group 'org-agenda
2558 :type 'sexp)
2560 (eval-after-load "calendar"
2561 '(progn
2562 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2563 'org-calendar-goto-agenda)
2564 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2565 'org-agenda-action)))
2567 (defgroup org-latex nil
2568 "Options for embedding LaTeX code into Org-mode."
2569 :tag "Org LaTeX"
2570 :group 'org)
2572 (defcustom org-format-latex-options
2573 '(:foreground default :background default :scale 1.0
2574 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2575 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2576 "Options for creating images from LaTeX fragments.
2577 This is a property list with the following properties:
2578 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2579 `default' means use the foreground of the default face.
2580 :background the background color, or \"Transparent\".
2581 `default' means use the background of the default face.
2582 :scale a scaling factor for the size of the images.
2583 :html-foreground, :html-background, :html-scale
2584 the same numbers for HTML export.
2585 :matchers a list indicating which matchers should be used to
2586 find LaTeX fragments. Valid members of this list are:
2587 \"begin\" find environments
2588 \"$1\" find single characters surrounded by $.$
2589 \"$\" find math expressions surrounded by $...$
2590 \"$$\" find math expressions surrounded by $$....$$
2591 \"\\(\" find math expressions surrounded by \\(...\\)
2592 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2593 :group 'org-latex
2594 :type 'plist)
2596 (defcustom org-format-latex-header "\\documentclass{article}
2597 \\usepackage{fullpage} % do not remove
2598 \\usepackage{amssymb}
2599 \\usepackage[usenames]{color}
2600 \\usepackage{amsmath}
2601 \\usepackage{latexsym}
2602 \\usepackage[mathscr]{eucal}
2603 \\pagestyle{empty} % do not remove"
2604 "The document header used for processing LaTeX fragments."
2605 :group 'org-latex
2606 :type 'string)
2609 (defgroup org-font-lock nil
2610 "Font-lock settings for highlighting in Org-mode."
2611 :tag "Org Font Lock"
2612 :group 'org)
2614 (defcustom org-level-color-stars-only nil
2615 "Non-nil means fontify only the stars in each headline.
2616 When nil, the entire headline is fontified.
2617 Changing it requires restart of `font-lock-mode' to become effective
2618 also in regions already fontified."
2619 :group 'org-font-lock
2620 :type 'boolean)
2622 (defcustom org-hide-leading-stars nil
2623 "Non-nil means, hide the first N-1 stars in a headline.
2624 This works by using the face `org-hide' for these stars. This
2625 face is white for a light background, and black for a dark
2626 background. You may have to customize the face `org-hide' to
2627 make this work.
2628 Changing it requires restart of `font-lock-mode' to become effective
2629 also in regions already fontified.
2630 You may also set this on a per-file basis by adding one of the following
2631 lines to the buffer:
2633 #+STARTUP: hidestars
2634 #+STARTUP: showstars"
2635 :group 'org-font-lock
2636 :type 'boolean)
2638 (defcustom org-fontify-done-headline nil
2639 "Non-nil means, change the face of a headline if it is marked DONE.
2640 Normally, only the TODO/DONE keyword indicates the state of a headline.
2641 When this is non-nil, the headline after the keyword is set to the
2642 `org-headline-done' as an additional indication."
2643 :group 'org-font-lock
2644 :type 'boolean)
2646 (defcustom org-fontify-emphasized-text t
2647 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2648 Changing this variable requires a restart of Emacs to take effect."
2649 :group 'org-font-lock
2650 :type 'boolean)
2652 (defcustom org-highlight-latex-fragments-and-specials nil
2653 "Non-nil means, fontify what is treated specially by the exporters."
2654 :group 'org-font-lock
2655 :type 'boolean)
2657 (defcustom org-hide-emphasis-markers nil
2658 "Non-nil mean font-lock should hide the emphasis marker characters."
2659 :group 'org-font-lock
2660 :type 'boolean)
2662 (defvar org-emph-re nil
2663 "Regular expression for matching emphasis.")
2664 (defvar org-verbatim-re nil
2665 "Regular expression for matching verbatim text.")
2666 (defvar org-emphasis-regexp-components) ; defined just below
2667 (defvar org-emphasis-alist) ; defined just below
2668 (defun org-set-emph-re (var val)
2669 "Set variable and compute the emphasis regular expression."
2670 (set var val)
2671 (when (and (boundp 'org-emphasis-alist)
2672 (boundp 'org-emphasis-regexp-components)
2673 org-emphasis-alist org-emphasis-regexp-components)
2674 (let* ((e org-emphasis-regexp-components)
2675 (pre (car e))
2676 (post (nth 1 e))
2677 (border (nth 2 e))
2678 (body (nth 3 e))
2679 (nl (nth 4 e))
2680 (body1 (concat body "*?"))
2681 (markers (mapconcat 'car org-emphasis-alist ""))
2682 (vmarkers (mapconcat
2683 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2684 org-emphasis-alist "")))
2685 ;; make sure special characters appear at the right position in the class
2686 (if (string-match "\\^" markers)
2687 (setq markers (concat (replace-match "" t t markers) "^")))
2688 (if (string-match "-" markers)
2689 (setq markers (concat (replace-match "" t t markers) "-")))
2690 (if (string-match "\\^" vmarkers)
2691 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2692 (if (string-match "-" vmarkers)
2693 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2694 (if (> nl 0)
2695 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2696 (int-to-string nl) "\\}")))
2697 ;; Make the regexp
2698 (setq org-emph-re
2699 (concat "\\([" pre "]\\|^\\)"
2700 "\\("
2701 "\\([" markers "]\\)"
2702 "\\("
2703 "[^" border "]\\|"
2704 "[^" border "]"
2705 body1
2706 "[^" border "]"
2707 "\\)"
2708 "\\3\\)"
2709 "\\([" post "]\\|$\\)"))
2710 (setq org-verbatim-re
2711 (concat "\\([" pre "]\\|^\\)"
2712 "\\("
2713 "\\([" vmarkers "]\\)"
2714 "\\("
2715 "[^" border "]\\|"
2716 "[^" border "]"
2717 body1
2718 "[^" border "]"
2719 "\\)"
2720 "\\3\\)"
2721 "\\([" post "]\\|$\\)")))))
2723 (defcustom org-emphasis-regexp-components
2724 '(" \t('\"{" "- \t.,:!?;'\")}" " \t\r\n,\"'" "." 1)
2725 "Components used to build the regular expression for emphasis.
2726 This is a list with 6 entries. Terminology: In an emphasis string
2727 like \" *strong word* \", we call the initial space PREMATCH, the final
2728 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2729 and \"trong wor\" is the body. The different components in this variable
2730 specify what is allowed/forbidden in each part:
2732 pre Chars allowed as prematch. Beginning of line will be allowed too.
2733 post Chars allowed as postmatch. End of line will be allowed too.
2734 border The chars *forbidden* as border characters.
2735 body-regexp A regexp like \".\" to match a body character. Don't use
2736 non-shy groups here, and don't allow newline here.
2737 newline The maximum number of newlines allowed in an emphasis exp.
2739 Use customize to modify this, or restart Emacs after changing it."
2740 :group 'org-font-lock
2741 :set 'org-set-emph-re
2742 :type '(list
2743 (sexp :tag "Allowed chars in pre ")
2744 (sexp :tag "Allowed chars in post ")
2745 (sexp :tag "Forbidden chars in border ")
2746 (sexp :tag "Regexp for body ")
2747 (integer :tag "number of newlines allowed")
2748 (option (boolean :tag "Please ignore this button"))))
2750 (defcustom org-emphasis-alist
2751 `(("*" bold "<b>" "</b>")
2752 ("/" italic "<i>" "</i>")
2753 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2754 ("=" org-code "<code>" "</code>" verbatim)
2755 ("~" org-verbatim "<code>" "</code>" verbatim)
2756 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2757 "<del>" "</del>")
2759 "Special syntax for emphasized text.
2760 Text starting and ending with a special character will be emphasized, for
2761 example *bold*, _underlined_ and /italic/. This variable sets the marker
2762 characters, the face to be used by font-lock for highlighting in Org-mode
2763 Emacs buffers, and the HTML tags to be used for this.
2764 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
2765 Use customize to modify this, or restart Emacs after changing it."
2766 :group 'org-font-lock
2767 :set 'org-set-emph-re
2768 :type '(repeat
2769 (list
2770 (string :tag "Marker character")
2771 (choice
2772 (face :tag "Font-lock-face")
2773 (plist :tag "Face property list"))
2774 (string :tag "HTML start tag")
2775 (string :tag "HTML end tag")
2776 (option (const verbatim)))))
2778 ;;; Miscellaneous options
2780 (defgroup org-completion nil
2781 "Completion in Org-mode."
2782 :tag "Org Completion"
2783 :group 'org)
2785 (defcustom org-completion-use-ido nil
2786 "Non-nil means, use ido completion wherever possible.
2787 Note that `ido-mode' must be active for this variable to be relevant.
2788 If you decide to turn this variable on, you might well want to turn off
2789 `org-outline-path-complete-in-steps'."
2790 :group 'org-completion
2791 :type 'boolean)
2793 (defcustom org-completion-fallback-command 'hippie-expand
2794 "The expansion command called by \\[org-complete] in normal context.
2795 Normal means, no org-mode-specific context."
2796 :group 'org-completion
2797 :type 'function)
2799 ;;; Functions and variables from ther packages
2800 ;; Declared here to avoid compiler warnings
2802 ;; XEmacs only
2803 (defvar outline-mode-menu-heading)
2804 (defvar outline-mode-menu-show)
2805 (defvar outline-mode-menu-hide)
2806 (defvar zmacs-regions) ; XEmacs regions
2808 ;; Emacs only
2809 (defvar mark-active)
2811 ;; Various packages
2812 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2813 (declare-function calendar-forward-day "cal-move" (arg))
2814 (declare-function calendar-goto-date "cal-move" (date))
2815 (declare-function calendar-goto-today "cal-move" ())
2816 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2817 (defvar calc-embedded-close-formula)
2818 (defvar calc-embedded-open-formula)
2819 (declare-function cdlatex-tab "ext:cdlatex" ())
2820 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2821 (defvar font-lock-unfontify-region-function)
2822 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2823 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2824 (defvar iswitchb-temp-buflist)
2825 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2826 (defvar org-agenda-tags-todo-honor-ignore-options)
2827 (declare-function org-agenda-skip "org-agenda" ())
2828 (declare-function org-format-agenda-item "org-agenda"
2829 (extra txt &optional category tags dotime noprefix remove-re))
2830 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2831 (declare-function org-agenda-change-all-lines "org-agenda"
2832 (newhead hdmarker &optional fixface just-this))
2833 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2834 (declare-function org-agenda-maybe-redo "org-agenda" ())
2835 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2836 (beg end))
2837 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2838 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2839 "org-agenda" (&optional end))
2841 (declare-function parse-time-string "parse-time" (string))
2842 (declare-function remember "remember" (&optional initial))
2843 (declare-function remember-buffer-desc "remember" ())
2844 (declare-function remember-finalize "remember" ())
2845 (defvar remember-save-after-remembering)
2846 (defvar remember-data-file)
2847 (defvar remember-register)
2848 (defvar remember-buffer)
2849 (defvar remember-handler-functions)
2850 (defvar remember-annotation-functions)
2851 (defvar texmathp-why)
2852 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2853 (declare-function table--at-cell-p "table" (position &optional object at-column))
2855 (defvar w3m-current-url)
2856 (defvar w3m-current-title)
2858 (defvar org-latex-regexps)
2860 ;;; Autoload and prepare some org modules
2862 ;; Some table stuff that needs to be defined here, because it is used
2863 ;; by the functions setting up org-mode or checking for table context.
2865 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2866 "Detects an org-type or table-type table.")
2867 (defconst org-table-line-regexp "^[ \t]*|"
2868 "Detects an org-type table line.")
2869 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2870 "Detects an org-type table line.")
2871 (defconst org-table-hline-regexp "^[ \t]*|-"
2872 "Detects an org-type table hline.")
2873 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2874 "Detects a table-type table hline.")
2875 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2876 "Searching from within a table (any type) this finds the first line
2877 outside the table.")
2879 ;; Autoload the functions in org-table.el that are needed by functions here.
2881 (eval-and-compile
2882 (org-autoload "org-table"
2883 '(org-table-align org-table-begin org-table-blank-field
2884 org-table-convert org-table-convert-region org-table-copy-down
2885 org-table-copy-region org-table-create
2886 org-table-create-or-convert-from-region
2887 org-table-create-with-table.el org-table-current-dline
2888 org-table-cut-region org-table-delete-column org-table-edit-field
2889 org-table-edit-formulas org-table-end org-table-eval-formula
2890 org-table-export org-table-field-info
2891 org-table-get-stored-formulas org-table-goto-column
2892 org-table-hline-and-move org-table-import org-table-insert-column
2893 org-table-insert-hline org-table-insert-row org-table-iterate
2894 org-table-justify-field-maybe org-table-kill-row
2895 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2896 org-table-move-column org-table-move-column-left
2897 org-table-move-column-right org-table-move-row
2898 org-table-move-row-down org-table-move-row-up
2899 org-table-next-field org-table-next-row org-table-paste-rectangle
2900 org-table-previous-field org-table-recalculate
2901 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2902 org-table-toggle-coordinate-overlays
2903 org-table-toggle-formula-debugger org-table-wrap-region
2904 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2906 (defun org-at-table-p (&optional table-type)
2907 "Return t if the cursor is inside an org-type table.
2908 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2909 (if org-enable-table-editor
2910 (save-excursion
2911 (beginning-of-line 1)
2912 (looking-at (if table-type org-table-any-line-regexp
2913 org-table-line-regexp)))
2914 nil))
2915 (defsubst org-table-p () (org-at-table-p))
2917 (defun org-at-table.el-p ()
2918 "Return t if and only if we are at a table.el table."
2919 (and (org-at-table-p 'any)
2920 (save-excursion
2921 (goto-char (org-table-begin 'any))
2922 (looking-at org-table1-hline-regexp))))
2923 (defun org-table-recognize-table.el ()
2924 "If there is a table.el table nearby, recognize it and move into it."
2925 (if org-table-tab-recognizes-table.el
2926 (if (org-at-table.el-p)
2927 (progn
2928 (beginning-of-line 1)
2929 (if (looking-at org-table-dataline-regexp)
2931 (if (looking-at org-table1-hline-regexp)
2932 (progn
2933 (beginning-of-line 2)
2934 (if (looking-at org-table-any-border-regexp)
2935 (beginning-of-line -1)))))
2936 (if (re-search-forward "|" (org-table-end t) t)
2937 (progn
2938 (require 'table)
2939 (if (table--at-cell-p (point))
2941 (message "recognizing table.el table...")
2942 (table-recognize-table)
2943 (message "recognizing table.el table...done")))
2944 (error "This should not happen..."))
2946 nil)
2947 nil))
2949 (defun org-at-table-hline-p ()
2950 "Return t if the cursor is inside a hline in a table."
2951 (if org-enable-table-editor
2952 (save-excursion
2953 (beginning-of-line 1)
2954 (looking-at org-table-hline-regexp))
2955 nil))
2957 (defvar org-table-clean-did-remove-column nil)
2959 (defun org-table-map-tables (function)
2960 "Apply FUNCTION to the start of all tables in the buffer."
2961 (save-excursion
2962 (save-restriction
2963 (widen)
2964 (goto-char (point-min))
2965 (while (re-search-forward org-table-any-line-regexp nil t)
2966 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2967 (beginning-of-line 1)
2968 (if (looking-at org-table-line-regexp)
2969 (save-excursion (funcall function)))
2970 (re-search-forward org-table-any-border-regexp nil 1))))
2971 (message "Mapping tables: done"))
2973 ;; Declare and autoload functions from org-exp.el & Co
2975 (declare-function org-default-export-plist "org-exp")
2976 (declare-function org-infile-export-plist "org-exp")
2977 (declare-function org-get-current-options "org-exp")
2978 (eval-and-compile
2979 (org-autoload "org-exp"
2980 '(org-export org-export-visible
2981 org-insert-export-options-template
2982 org-table-clean-before-export))
2983 (org-autoload "org-ascii"
2984 '(org-export-as-ascii org-export-ascii-preprocess
2985 org-export-as-ascii-to-buffer org-replace-region-by-ascii
2986 org-export-region-as-ascii))
2987 (org-autoload "org-html"
2988 '(org-export-as-html-and-open
2989 org-export-as-html-batch org-export-as-html-to-buffer
2990 org-replace-region-by-html org-export-region-as-html
2991 org-export-as-html))
2992 (org-autoload "org-icalendar"
2993 '(org-export-icalendar-this-file
2994 org-export-icalendar-all-agenda-files
2995 org-export-icalendar-combine-agenda-files))
2996 (org-autoload "org-xoxo" '(org-export-as-xoxo)))
2998 ;; Declare and autoload functions from org-agenda.el
3000 (eval-and-compile
3001 (org-autoload "org-agenda"
3002 '(org-agenda org-agenda-list org-search-view
3003 org-todo-list org-tags-view org-agenda-list-stuck-projects
3004 org-diary org-agenda-to-appt
3005 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3007 ;; Autoload org-remember
3009 (eval-and-compile
3010 (org-autoload "org-remember"
3011 '(org-remember-insinuate org-remember-annotation
3012 org-remember-apply-template org-remember org-remember-handler)))
3014 ;; Autoload org-clock.el
3017 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3018 (beg end))
3019 (declare-function org-clock-update-mode-line "org-clock" ())
3020 (defvar org-clock-start-time)
3021 (defvar org-clock-marker (make-marker)
3022 "Marker recording the last clock-in.")
3024 (eval-and-compile
3025 (org-autoload
3026 "org-clock"
3027 '(org-clock-in org-clock-out org-clock-cancel
3028 org-clock-goto org-clock-sum org-clock-display
3029 org-clock-remove-overlays org-clock-report
3030 org-clocktable-shift org-dblock-write:clocktable
3031 org-get-clocktable)))
3033 (defun org-clock-update-time-maybe ()
3034 "If this is a CLOCK line, update it and return t.
3035 Otherwise, return nil."
3036 (interactive)
3037 (save-excursion
3038 (beginning-of-line 1)
3039 (skip-chars-forward " \t")
3040 (when (looking-at org-clock-string)
3041 (let ((re (concat "[ \t]*" org-clock-string
3042 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3043 "\\([ \t]*=>.*\\)?\\)?"))
3044 ts te h m s neg)
3045 (cond
3046 ((not (looking-at re))
3047 nil)
3048 ((not (match-end 2))
3049 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3050 (> org-clock-marker (point))
3051 (<= org-clock-marker (point-at-eol)))
3052 ;; The clock is running here
3053 (setq org-clock-start-time
3054 (apply 'encode-time
3055 (org-parse-time-string (match-string 1))))
3056 (org-clock-update-mode-line)))
3058 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3059 (end-of-line 1)
3060 (setq ts (match-string 1)
3061 te (match-string 3))
3062 (setq s (- (time-to-seconds
3063 (apply 'encode-time (org-parse-time-string te)))
3064 (time-to-seconds
3065 (apply 'encode-time (org-parse-time-string ts))))
3066 neg (< s 0)
3067 s (abs s)
3068 h (floor (/ s 3600))
3069 s (- s (* 3600 h))
3070 m (floor (/ s 60))
3071 s (- s (* 60 s)))
3072 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3073 t))))))
3075 (defun org-check-running-clock ()
3076 "Check if the current buffer contains the running clock.
3077 If yes, offer to stop it and to save the buffer with the changes."
3078 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3079 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3080 (buffer-name))))
3081 (org-clock-out)
3082 (when (y-or-n-p "Save changed buffer?")
3083 (save-buffer))))
3085 (defun org-clocktable-try-shift (dir n)
3086 "Check if this line starts a clock table, if yes, shift the time block."
3087 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3088 (org-clocktable-shift dir n)))
3090 ;; Autoload org-timer.el
3092 (eval-and-compile
3093 (org-autoload
3094 "org-timer"
3095 '(org-timer-start org-timer org-timer-item
3096 org-timer-change-times-in-region)))
3098 ;; Autoload org-feed.el
3100 (eval-and-compile
3101 (org-autoload
3102 "org-feed"
3103 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3106 ;; Autoload archiving code
3107 ;; The stuff that is needed for cycling and tags has to be defined here.
3109 (defgroup org-archive nil
3110 "Options concerning archiving in Org-mode."
3111 :tag "Org Archive"
3112 :group 'org-structure)
3114 (defcustom org-archive-location "%s_archive::"
3115 "The location where subtrees should be archived.
3117 The value of this variable is a string, consisting of two parts,
3118 separated by a double-colon. The first part is a filename and
3119 the second part is a headline.
3121 When the filename is omitted, archiving happens in the same file.
3122 %s in the filename will be replaced by the current file
3123 name (without the directory part). Archiving to a different file
3124 is useful to keep archived entries from contributing to the
3125 Org-mode Agenda.
3127 The archived entries will be filed as subtrees of the specified
3128 headline. When the headline is omitted, the subtrees are simply
3129 filed away at the end of the file, as top-level entries. Also in
3130 the heading you can use %s to represent the file name, this can be
3131 useful when using the same archive for a number of different files.
3133 Here are a few examples:
3134 \"%s_archive::\"
3135 If the current file is Projects.org, archive in file
3136 Projects.org_archive, as top-level trees. This is the default.
3138 \"::* Archived Tasks\"
3139 Archive in the current file, under the top-level headline
3140 \"* Archived Tasks\".
3142 \"~/org/archive.org::\"
3143 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3145 \"~/org/archive.org::From %s\"
3146 Archive in file ~/org/archive.org (absolute path), und headlines
3147 \"From FILENAME\" where file name is the current file name.
3149 \"basement::** Finished Tasks\"
3150 Archive in file ./basement (relative path), as level 3 trees
3151 below the level 2 heading \"** Finished Tasks\".
3153 You may set this option on a per-file basis by adding to the buffer a
3154 line like
3156 #+ARCHIVE: basement::** Finished Tasks
3158 You may also define it locally for a subtree by setting an ARCHIVE property
3159 in the entry. If such a property is found in an entry, or anywhere up
3160 the hierarchy, it will be used."
3161 :group 'org-archive
3162 :type 'string)
3164 (defcustom org-archive-tag "ARCHIVE"
3165 "The tag that marks a subtree as archived.
3166 An archived subtree does not open during visibility cycling, and does
3167 not contribute to the agenda listings.
3168 After changing this, font-lock must be restarted in the relevant buffers to
3169 get the proper fontification."
3170 :group 'org-archive
3171 :group 'org-keywords
3172 :type 'string)
3174 (defcustom org-agenda-skip-archived-trees t
3175 "Non-nil means, the agenda will skip any items located in archived trees.
3176 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3177 variable is no longer recommended, you should leave it at the value t.
3178 Instead, use the key `v' to cycle the archives-mode in the agenda."
3179 :group 'org-archive
3180 :group 'org-agenda-skip
3181 :type 'boolean)
3183 (defcustom org-columns-skip-arrchived-trees t
3184 "Non-nil means, irgnore archived trees when creating column view."
3185 :group 'org-archive
3186 :group 'org-properties
3187 :type 'boolean)
3189 (defcustom org-cycle-open-archived-trees nil
3190 "Non-nil means, `org-cycle' will open archived trees.
3191 An archived tree is a tree marked with the tag ARCHIVE.
3192 When nil, archived trees will stay folded. You can still open them with
3193 normal outline commands like `show-all', but not with the cycling commands."
3194 :group 'org-archive
3195 :group 'org-cycle
3196 :type 'boolean)
3198 (defcustom org-sparse-tree-open-archived-trees nil
3199 "Non-nil means sparse tree construction shows matches in archived trees.
3200 When nil, matches in these trees are highlighted, but the trees are kept in
3201 collapsed state."
3202 :group 'org-archive
3203 :group 'org-sparse-trees
3204 :type 'boolean)
3206 (defun org-cycle-hide-archived-subtrees (state)
3207 "Re-hide all archived subtrees after a visibility state change."
3208 (when (and (not org-cycle-open-archived-trees)
3209 (not (memq state '(overview folded))))
3210 (save-excursion
3211 (let* ((globalp (memq state '(contents all)))
3212 (beg (if globalp (point-min) (point)))
3213 (end (if globalp (point-max) (org-end-of-subtree t))))
3214 (org-hide-archived-subtrees beg end)
3215 (goto-char beg)
3216 (if (looking-at (concat ".*:" org-archive-tag ":"))
3217 (message "%s" (substitute-command-keys
3218 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3220 (defun org-force-cycle-archived ()
3221 "Cycle subtree even if it is archived."
3222 (interactive)
3223 (setq this-command 'org-cycle)
3224 (let ((org-cycle-open-archived-trees t))
3225 (call-interactively 'org-cycle)))
3227 (defun org-hide-archived-subtrees (beg end)
3228 "Re-hide all archived subtrees after a visibility state change."
3229 (save-excursion
3230 (let* ((re (concat ":" org-archive-tag ":")))
3231 (goto-char beg)
3232 (while (re-search-forward re end t)
3233 (and (org-on-heading-p) (hide-subtree))
3234 (org-end-of-subtree t)))))
3236 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3238 (eval-and-compile
3239 (org-autoload "org-archive"
3240 '(org-add-archive-files org-archive-subtree
3241 org-archive-to-archive-sibling org-toggle-archive-tag)))
3243 ;; Autoload Column View Code
3245 (declare-function org-columns-number-to-string "org-colview")
3246 (declare-function org-columns-get-format-and-top-level "org-colview")
3247 (declare-function org-columns-compute "org-colview")
3249 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3250 '(org-columns-number-to-string org-columns-get-format-and-top-level
3251 org-columns-compute org-agenda-columns org-columns-remove-overlays
3252 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3254 ;; Autoload ID code
3256 (declare-function org-id-store-link "org-id")
3257 (declare-function org-id-locations-load "org-id")
3258 (declare-function org-id-locations-save "org-id")
3259 (defvar org-id-track-globally)
3260 (org-autoload "org-id"
3261 '(org-id-get-create org-id-new org-id-copy org-id-get
3262 org-id-get-with-outline-path-completion
3263 org-id-get-with-outline-drilling
3264 org-id-goto org-id-find org-id-store-link))
3266 ;; Autoload Plotting Code
3268 (org-autoload "org-plot"
3269 '(org-plot/gnuplot))
3271 ;;; Variables for pre-computed regular expressions, all buffer local
3273 (defvar org-drawer-regexp nil
3274 "Matches first line of a hidden block.")
3275 (make-variable-buffer-local 'org-drawer-regexp)
3276 (defvar org-todo-regexp nil
3277 "Matches any of the TODO state keywords.")
3278 (make-variable-buffer-local 'org-todo-regexp)
3279 (defvar org-not-done-regexp nil
3280 "Matches any of the TODO state keywords except the last one.")
3281 (make-variable-buffer-local 'org-not-done-regexp)
3282 (defvar org-not-done-heading-regexp nil
3283 "Matches a TODO headline that is not done.")
3284 (make-variable-buffer-local 'org-not-done-regexp)
3285 (defvar org-todo-line-regexp nil
3286 "Matches a headline and puts TODO state into group 2 if present.")
3287 (make-variable-buffer-local 'org-todo-line-regexp)
3288 (defvar org-complex-heading-regexp nil
3289 "Matches a headline and puts everything into groups:
3290 group 1: the stars
3291 group 2: The todo keyword, maybe
3292 group 3: Priority cookie
3293 group 4: True headline
3294 group 5: Tags")
3295 (make-variable-buffer-local 'org-complex-heading-regexp)
3296 (defvar org-todo-line-tags-regexp nil
3297 "Matches a headline and puts TODO state into group 2 if present.
3298 Also put tags into group 4 if tags are present.")
3299 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3300 (defvar org-nl-done-regexp nil
3301 "Matches newline followed by a headline with the DONE keyword.")
3302 (make-variable-buffer-local 'org-nl-done-regexp)
3303 (defvar org-looking-at-done-regexp nil
3304 "Matches the DONE keyword a point.")
3305 (make-variable-buffer-local 'org-looking-at-done-regexp)
3306 (defvar org-ds-keyword-length 12
3307 "Maximum length of the Deadline and SCHEDULED keywords.")
3308 (make-variable-buffer-local 'org-ds-keyword-length)
3309 (defvar org-deadline-regexp nil
3310 "Matches the DEADLINE keyword.")
3311 (make-variable-buffer-local 'org-deadline-regexp)
3312 (defvar org-deadline-time-regexp nil
3313 "Matches the DEADLINE keyword together with a time stamp.")
3314 (make-variable-buffer-local 'org-deadline-time-regexp)
3315 (defvar org-deadline-line-regexp nil
3316 "Matches the DEADLINE keyword and the rest of the line.")
3317 (make-variable-buffer-local 'org-deadline-line-regexp)
3318 (defvar org-scheduled-regexp nil
3319 "Matches the SCHEDULED keyword.")
3320 (make-variable-buffer-local 'org-scheduled-regexp)
3321 (defvar org-scheduled-time-regexp nil
3322 "Matches the SCHEDULED keyword together with a time stamp.")
3323 (make-variable-buffer-local 'org-scheduled-time-regexp)
3324 (defvar org-closed-time-regexp nil
3325 "Matches the CLOSED keyword together with a time stamp.")
3326 (make-variable-buffer-local 'org-closed-time-regexp)
3328 (defvar org-keyword-time-regexp nil
3329 "Matches any of the 4 keywords, together with the time stamp.")
3330 (make-variable-buffer-local 'org-keyword-time-regexp)
3331 (defvar org-keyword-time-not-clock-regexp nil
3332 "Matches any of the 3 keywords, together with the time stamp.")
3333 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3334 (defvar org-maybe-keyword-time-regexp nil
3335 "Matches a timestamp, possibly preceeded by a keyword.")
3336 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3337 (defvar org-planning-or-clock-line-re nil
3338 "Matches a line with planning or clock info.")
3339 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3341 (defconst org-plain-time-of-day-regexp
3342 (concat
3343 "\\(\\<[012]?[0-9]"
3344 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3345 "\\(--?"
3346 "\\(\\<[012]?[0-9]"
3347 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3348 "\\)?")
3349 "Regular expression to match a plain time or time range.
3350 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3351 groups carry important information:
3352 0 the full match
3353 1 the first time, range or not
3354 8 the second time, if it is a range.")
3356 (defconst org-plain-time-extension-regexp
3357 (concat
3358 "\\(\\<[012]?[0-9]"
3359 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3360 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3361 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3362 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3363 groups carry important information:
3364 0 the full match
3365 7 hours of duration
3366 9 minutes of duration")
3368 (defconst org-stamp-time-of-day-regexp
3369 (concat
3370 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3371 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3372 "\\(--?"
3373 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3374 "Regular expression to match a timestamp time or time range.
3375 After a match, the following groups carry important information:
3376 0 the full match
3377 1 date plus weekday, for backreferencing to make sure both times on same day
3378 2 the first time, range or not
3379 4 the second time, if it is a range.")
3381 (defconst org-startup-options
3382 '(("fold" org-startup-folded t)
3383 ("overview" org-startup-folded t)
3384 ("nofold" org-startup-folded nil)
3385 ("showall" org-startup-folded nil)
3386 ("content" org-startup-folded content)
3387 ("hidestars" org-hide-leading-stars t)
3388 ("showstars" org-hide-leading-stars nil)
3389 ("odd" org-odd-levels-only t)
3390 ("oddeven" org-odd-levels-only nil)
3391 ("align" org-startup-align-all-tables t)
3392 ("noalign" org-startup-align-all-tables nil)
3393 ("customtime" org-display-custom-times t)
3394 ("logdone" org-log-done time)
3395 ("lognotedone" org-log-done note)
3396 ("nologdone" org-log-done nil)
3397 ("lognoteclock-out" org-log-note-clock-out t)
3398 ("nolognoteclock-out" org-log-note-clock-out nil)
3399 ("logrepeat" org-log-repeat state)
3400 ("lognoterepeat" org-log-repeat note)
3401 ("nologrepeat" org-log-repeat nil)
3402 ("fninline" org-footnote-define-inline t)
3403 ("nofninline" org-footnote-define-inline nil)
3404 ("fnlocal" org-footnote-section nil)
3405 ("fnauto" org-footnote-auto-label t)
3406 ("fnprompt" org-footnote-auto-label nil)
3407 ("fnconfirm" org-footnote-auto-label confirm)
3408 ("fnplain" org-footnote-auto-label plain)
3409 ("constcgs" constants-unit-system cgs)
3410 ("constSI" constants-unit-system SI)
3411 ("noptag" org-tag-persistent-alist nil))
3412 "Variable associated with STARTUP options for org-mode.
3413 Each element is a list of three items: The startup options as written
3414 in the #+STARTUP line, the corresponding variable, and the value to
3415 set this variable to if the option is found. An optional forth element PUSH
3416 means to push this value onto the list in the variable.")
3418 (defun org-set-regexps-and-options ()
3419 "Precompute regular expressions for current buffer."
3420 (when (org-mode-p)
3421 (org-set-local 'org-todo-kwd-alist nil)
3422 (org-set-local 'org-todo-key-alist nil)
3423 (org-set-local 'org-todo-key-trigger nil)
3424 (org-set-local 'org-todo-keywords-1 nil)
3425 (org-set-local 'org-done-keywords nil)
3426 (org-set-local 'org-todo-heads nil)
3427 (org-set-local 'org-todo-sets nil)
3428 (org-set-local 'org-todo-log-states nil)
3429 (org-set-local 'org-file-properties nil)
3430 (org-set-local 'org-file-tags nil)
3431 (let ((re (org-make-options-regexp
3432 '("CATEGORY" "TODO" "COLUMNS"
3433 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3434 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3435 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3436 (splitre "[ \t]+")
3437 kwds kws0 kwsa key log value cat arch tags const links hw dws
3438 tail sep kws1 prio props ftags drawers
3439 ext-setup-or-nil setup-contents (start 0))
3440 (save-excursion
3441 (save-restriction
3442 (widen)
3443 (goto-char (point-min))
3444 (while (or (and ext-setup-or-nil
3445 (string-match re ext-setup-or-nil start)
3446 (setq start (match-end 0)))
3447 (and (setq ext-setup-or-nil nil start 0)
3448 (re-search-forward re nil t)))
3449 (setq key (upcase (match-string 1 ext-setup-or-nil))
3450 value (org-match-string-no-properties 2 ext-setup-or-nil))
3451 (cond
3452 ((equal key "CATEGORY")
3453 (if (string-match "[ \t]+$" value)
3454 (setq value (replace-match "" t t value)))
3455 (setq cat value))
3456 ((member key '("SEQ_TODO" "TODO"))
3457 (push (cons 'sequence (org-split-string value splitre)) kwds))
3458 ((equal key "TYP_TODO")
3459 (push (cons 'type (org-split-string value splitre)) kwds))
3460 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3461 ;; general TODO-like setup
3462 (push (cons (intern (downcase (match-string 1 key)))
3463 (org-split-string value splitre)) kwds))
3464 ((equal key "TAGS")
3465 (setq tags (append tags (if tags '("\\n") nil)
3466 (org-split-string value splitre))))
3467 ((equal key "COLUMNS")
3468 (org-set-local 'org-columns-default-format value))
3469 ((equal key "LINK")
3470 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3471 (push (cons (match-string 1 value)
3472 (org-trim (match-string 2 value)))
3473 links)))
3474 ((equal key "PRIORITIES")
3475 (setq prio (org-split-string value " +")))
3476 ((equal key "PROPERTY")
3477 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3478 (push (cons (match-string 1 value) (match-string 2 value))
3479 props)))
3480 ((equal key "FILETAGS")
3481 (when (string-match "\\S-" value)
3482 (setq ftags
3483 (append
3484 ftags
3485 (apply 'append
3486 (mapcar (lambda (x) (org-split-string x ":"))
3487 (org-split-string value)))))))
3488 ((equal key "DRAWERS")
3489 (setq drawers (org-split-string value splitre)))
3490 ((equal key "CONSTANTS")
3491 (setq const (append const (org-split-string value splitre))))
3492 ((equal key "STARTUP")
3493 (let ((opts (org-split-string value splitre))
3494 l var val)
3495 (while (setq l (pop opts))
3496 (when (setq l (assoc l org-startup-options))
3497 (setq var (nth 1 l) val (nth 2 l))
3498 (if (not (nth 3 l))
3499 (set (make-local-variable var) val)
3500 (if (not (listp (symbol-value var)))
3501 (set (make-local-variable var) nil))
3502 (set (make-local-variable var) (symbol-value var))
3503 (add-to-list var val))))))
3504 ((equal key "ARCHIVE")
3505 (string-match " *$" value)
3506 (setq arch (replace-match "" t t value))
3507 (remove-text-properties 0 (length arch)
3508 '(face t fontified t) arch))
3509 ((equal key "SETUPFILE")
3510 (setq setup-contents (org-file-contents
3511 (expand-file-name
3512 (org-remove-double-quotes value))
3513 'noerror))
3514 (if (not ext-setup-or-nil)
3515 (setq ext-setup-or-nil setup-contents start 0)
3516 (setq ext-setup-or-nil
3517 (concat (substring ext-setup-or-nil 0 start)
3518 "\n" setup-contents "\n"
3519 (substring ext-setup-or-nil start)))))
3520 ))))
3521 (when cat
3522 (org-set-local 'org-category (intern cat))
3523 (push (cons "CATEGORY" cat) props))
3524 (when prio
3525 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3526 (setq prio (mapcar 'string-to-char prio))
3527 (org-set-local 'org-highest-priority (nth 0 prio))
3528 (org-set-local 'org-lowest-priority (nth 1 prio))
3529 (org-set-local 'org-default-priority (nth 2 prio)))
3530 (and props (org-set-local 'org-file-properties (nreverse props)))
3531 (and ftags (org-set-local 'org-file-tags
3532 (mapcar 'org-add-prop-inherited ftags)))
3533 (and drawers (org-set-local 'org-drawers drawers))
3534 (and arch (org-set-local 'org-archive-location arch))
3535 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3536 ;; Process the TODO keywords
3537 (unless kwds
3538 ;; Use the global values as if they had been given locally.
3539 (setq kwds (default-value 'org-todo-keywords))
3540 (if (stringp (car kwds))
3541 (setq kwds (list (cons org-todo-interpretation
3542 (default-value 'org-todo-keywords)))))
3543 (setq kwds (reverse kwds)))
3544 (setq kwds (nreverse kwds))
3545 (let (inter kws kw)
3546 (while (setq kws (pop kwds))
3547 (let ((kws (or
3548 (run-hook-with-args-until-success
3549 'org-todo-setup-filter-hook kws)
3550 kws)))
3551 (setq inter (pop kws) sep (member "|" kws)
3552 kws0 (delete "|" (copy-sequence kws))
3553 kwsa nil
3554 kws1 (mapcar
3555 (lambda (x)
3556 ;; 1 2
3557 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3558 (progn
3559 (setq kw (match-string 1 x)
3560 key (and (match-end 2) (match-string 2 x))
3561 log (org-extract-log-state-settings x))
3562 (push (cons kw (and key (string-to-char key))) kwsa)
3563 (and log (push log org-todo-log-states))
3565 (error "Invalid TODO keyword %s" x)))
3566 kws0)
3567 kwsa (if kwsa (append '((:startgroup))
3568 (nreverse kwsa)
3569 '((:endgroup))))
3570 hw (car kws1)
3571 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3572 tail (list inter hw (car dws) (org-last dws))))
3573 (add-to-list 'org-todo-heads hw 'append)
3574 (push kws1 org-todo-sets)
3575 (setq org-done-keywords (append org-done-keywords dws nil))
3576 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3577 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3578 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3579 (setq org-todo-sets (nreverse org-todo-sets)
3580 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3581 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3582 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3583 ;; Process the constants
3584 (when const
3585 (let (e cst)
3586 (while (setq e (pop const))
3587 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3588 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3589 (setq org-table-formula-constants-local cst)))
3591 ;; Process the tags.
3592 (when tags
3593 (let (e tgs)
3594 (while (setq e (pop tags))
3595 (cond
3596 ((equal e "{") (push '(:startgroup) tgs))
3597 ((equal e "}") (push '(:endgroup) tgs))
3598 ((equal e "\\n") (push '(:newline) tgs))
3599 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3600 (push (cons (match-string 1 e)
3601 (string-to-char (match-string 2 e)))
3602 tgs))
3603 (t (push (list e) tgs))))
3604 (org-set-local 'org-tag-alist nil)
3605 (while (setq e (pop tgs))
3606 (or (and (stringp (car e))
3607 (assoc (car e) org-tag-alist))
3608 (push e org-tag-alist)))))
3610 ;; Compute the regular expressions and other local variables
3611 (if (not org-done-keywords)
3612 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3613 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3614 (length org-scheduled-string)
3615 (length org-clock-string)
3616 (length org-closed-string)))
3617 org-drawer-regexp
3618 (concat "^[ \t]*:\\("
3619 (mapconcat 'regexp-quote org-drawers "\\|")
3620 "\\):[ \t]*$")
3621 org-not-done-keywords
3622 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3623 org-todo-regexp
3624 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3625 "\\|") "\\)\\>")
3626 org-not-done-regexp
3627 (concat "\\<\\("
3628 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3629 "\\)\\>")
3630 org-not-done-heading-regexp
3631 (concat "^\\(\\*+\\)[ \t]+\\("
3632 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3633 "\\)\\>")
3634 org-todo-line-regexp
3635 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3636 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3637 "\\)\\>\\)?[ \t]*\\(.*\\)")
3638 org-complex-heading-regexp
3639 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3640 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3641 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3642 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3643 org-nl-done-regexp
3644 (concat "\n\\*+[ \t]+"
3645 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3646 "\\)" "\\>")
3647 org-todo-line-tags-regexp
3648 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3649 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3650 (org-re
3651 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3652 org-looking-at-done-regexp
3653 (concat "^" "\\(?:"
3654 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3655 "\\>")
3656 org-deadline-regexp (concat "\\<" org-deadline-string)
3657 org-deadline-time-regexp
3658 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3659 org-deadline-line-regexp
3660 (concat "\\<\\(" org-deadline-string "\\).*")
3661 org-scheduled-regexp
3662 (concat "\\<" org-scheduled-string)
3663 org-scheduled-time-regexp
3664 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3665 org-closed-time-regexp
3666 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3667 org-keyword-time-regexp
3668 (concat "\\<\\(" org-scheduled-string
3669 "\\|" org-deadline-string
3670 "\\|" org-closed-string
3671 "\\|" org-clock-string "\\)"
3672 " *[[<]\\([^]>]+\\)[]>]")
3673 org-keyword-time-not-clock-regexp
3674 (concat "\\<\\(" org-scheduled-string
3675 "\\|" org-deadline-string
3676 "\\|" org-closed-string
3677 "\\)"
3678 " *[[<]\\([^]>]+\\)[]>]")
3679 org-maybe-keyword-time-regexp
3680 (concat "\\(\\<\\(" org-scheduled-string
3681 "\\|" org-deadline-string
3682 "\\|" org-closed-string
3683 "\\|" org-clock-string "\\)\\)?"
3684 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3685 org-planning-or-clock-line-re
3686 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3687 "\\|" org-deadline-string
3688 "\\|" org-closed-string "\\|" org-clock-string
3689 "\\)\\>\\)")
3691 (org-compute-latex-and-specials-regexp)
3692 (org-set-font-lock-defaults))))
3694 (defun org-file-contents (file &optional noerror)
3695 "Return the contents of FILE, as a string."
3696 (if (or (not file)
3697 (not (file-readable-p file)))
3698 (if noerror
3699 (progn
3700 (message "Cannot read file %s" file)
3701 (ding) (sit-for 2)
3703 (error "Cannot read file %s" file))
3704 (with-temp-buffer
3705 (insert-file-contents file)
3706 (buffer-string))))
3708 (defun org-extract-log-state-settings (x)
3709 "Extract the log state setting from a TODO keyword string.
3710 This will extract info from a string like \"WAIT(w@/!)\"."
3711 (let (kw key log1 log2)
3712 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3713 (setq kw (match-string 1 x)
3714 key (and (match-end 2) (match-string 2 x))
3715 log1 (and (match-end 3) (match-string 3 x))
3716 log2 (and (match-end 4) (match-string 4 x)))
3717 (and (or log1 log2)
3718 (list kw
3719 (and log1 (if (equal log1 "!") 'time 'note))
3720 (and log2 (if (equal log2 "!") 'time 'note)))))))
3722 (defun org-remove-keyword-keys (list)
3723 "Remove a pair of parenthesis at the end of each string in LIST."
3724 (mapcar (lambda (x)
3725 (if (string-match "(.*)$" x)
3726 (substring x 0 (match-beginning 0))
3728 list))
3730 ;; FIXME: this could be done much better, using second characters etc.
3731 (defun org-assign-fast-keys (alist)
3732 "Assign fast keys to a keyword-key alist.
3733 Respect keys that are already there."
3734 (let (new e k c c1 c2 (char ?a))
3735 (while (setq e (pop alist))
3736 (cond
3737 ((equal e '(:startgroup)) (push e new))
3738 ((equal e '(:endgroup)) (push e new))
3739 ((equal e '(:newline)) (push e new))
3741 (setq k (car e) c2 nil)
3742 (if (cdr e)
3743 (setq c (cdr e))
3744 ;; automatically assign a character.
3745 (setq c1 (string-to-char
3746 (downcase (substring
3747 k (if (= (string-to-char k) ?@) 1 0)))))
3748 (if (or (rassoc c1 new) (rassoc c1 alist))
3749 (while (or (rassoc char new) (rassoc char alist))
3750 (setq char (1+ char)))
3751 (setq c2 c1))
3752 (setq c (or c2 char)))
3753 (push (cons k c) new))))
3754 (nreverse new)))
3756 ;;; Some variables used in various places
3758 (defvar org-window-configuration nil
3759 "Used in various places to store a window configuration.")
3760 (defvar org-finish-function nil
3761 "Function to be called when `C-c C-c' is used.
3762 This is for getting out of special buffers like remember.")
3765 ;; FIXME: Occasionally check by commenting these, to make sure
3766 ;; no other functions uses these, forgetting to let-bind them.
3767 (defvar entry)
3768 (defvar state)
3769 (defvar last-state)
3770 (defvar date)
3771 (defvar description)
3773 ;; Defined somewhere in this file, but used before definition.
3774 (defvar org-html-entities)
3775 (defvar org-struct-menu)
3776 (defvar org-org-menu)
3777 (defvar org-tbl-menu)
3778 (defvar org-agenda-keymap)
3780 ;;;; Define the Org-mode
3782 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3783 (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."))
3786 ;; We use a before-change function to check if a table might need
3787 ;; an update.
3788 (defvar org-table-may-need-update t
3789 "Indicates that a table might need an update.
3790 This variable is set by `org-before-change-function'.
3791 `org-table-align' sets it back to nil.")
3792 (defun org-before-change-function (beg end)
3793 "Every change indicates that a table might need an update."
3794 (setq org-table-may-need-update t))
3795 (defvar org-mode-map)
3796 (defvar org-mode-hook nil
3797 "Mode hook for Org-mode, run after the mode was turned on.")
3798 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3799 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3800 (defvar org-table-buffer-is-an nil)
3801 (defconst org-outline-regexp "\\*+ ")
3803 ;;;###autoload
3804 (define-derived-mode org-mode outline-mode "Org"
3805 "Outline-based notes management and organizer, alias
3806 \"Carsten's outline-mode for keeping track of everything.\"
3808 Org-mode develops organizational tasks around a NOTES file which
3809 contains information about projects as plain text. Org-mode is
3810 implemented on top of outline-mode, which is ideal to keep the content
3811 of large files well structured. It supports ToDo items, deadlines and
3812 time stamps, which magically appear in the diary listing of the Emacs
3813 calendar. Tables are easily created with a built-in table editor.
3814 Plain text URL-like links connect to websites, emails (VM), Usenet
3815 messages (Gnus), BBDB entries, and any files related to the project.
3816 For printing and sharing of notes, an Org-mode file (or a part of it)
3817 can be exported as a structured ASCII or HTML file.
3819 The following commands are available:
3821 \\{org-mode-map}"
3823 ;; Get rid of Outline menus, they are not needed
3824 ;; Need to do this here because define-derived-mode sets up
3825 ;; the keymap so late. Still, it is a waste to call this each time
3826 ;; we switch another buffer into org-mode.
3827 (if (featurep 'xemacs)
3828 (when (boundp 'outline-mode-menu-heading)
3829 ;; Assume this is Greg's port, it used easymenu
3830 (easy-menu-remove outline-mode-menu-heading)
3831 (easy-menu-remove outline-mode-menu-show)
3832 (easy-menu-remove outline-mode-menu-hide))
3833 (define-key org-mode-map [menu-bar headings] 'undefined)
3834 (define-key org-mode-map [menu-bar hide] 'undefined)
3835 (define-key org-mode-map [menu-bar show] 'undefined))
3837 (org-load-modules-maybe)
3838 (easy-menu-add org-org-menu)
3839 (easy-menu-add org-tbl-menu)
3840 (org-install-agenda-files-menu)
3841 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3842 (org-add-to-invisibility-spec '(org-cwidth))
3843 (when (featurep 'xemacs)
3844 (org-set-local 'line-move-ignore-invisible t))
3845 (org-set-local 'outline-regexp org-outline-regexp)
3846 (org-set-local 'outline-level 'org-outline-level)
3847 (when (and org-ellipsis
3848 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3849 (fboundp 'make-glyph-code))
3850 (unless org-display-table
3851 (setq org-display-table (make-display-table)))
3852 (set-display-table-slot
3853 org-display-table 4
3854 (vconcat (mapcar
3855 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3856 org-ellipsis)))
3857 (if (stringp org-ellipsis) org-ellipsis "..."))))
3858 (setq buffer-display-table org-display-table))
3859 (org-set-regexps-and-options)
3860 (when (and org-tag-faces (not org-tags-special-faces-re))
3861 ;; tag faces set outside customize.... force initialization.
3862 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3863 ;; Calc embedded
3864 (org-set-local 'calc-embedded-open-mode "# ")
3865 (modify-syntax-entry ?# "<")
3866 (modify-syntax-entry ?@ "w")
3867 (if org-startup-truncated (setq truncate-lines t))
3868 (org-set-local 'font-lock-unfontify-region-function
3869 'org-unfontify-region)
3870 ;; Activate before-change-function
3871 (org-set-local 'org-table-may-need-update t)
3872 (org-add-hook 'before-change-functions 'org-before-change-function nil
3873 'local)
3874 ;; Check for running clock before killing a buffer
3875 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3876 ;; Paragraphs and auto-filling
3877 (org-set-autofill-regexps)
3878 (setq indent-line-function 'org-indent-line-function)
3879 (org-update-radio-target-regexp)
3880 ;; Make sure dependence stuff works reliably, even for users who set it
3881 ;; too late :-(
3882 (if org-enforce-todo-dependencies
3883 (add-hook 'org-blocker-hook
3884 'org-block-todo-from-children-or-siblings-or-parent)
3885 (remove-hook 'org-blocker-hook
3886 'org-block-todo-from-children-or-siblings-or-parent))
3887 (if org-enforce-todo-checkbox-dependencies
3888 (add-hook 'org-blocker-hook
3889 'org-block-todo-from-checkboxes)
3890 (remove-hook 'org-blocker-hook
3891 'org-block-todo-from-checkboxes))
3893 ;; Comment characters
3894 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3895 (org-set-local 'comment-padding " ")
3897 ;; Align options lines
3898 (org-set-local
3899 'align-mode-rules-list
3900 '((org-in-buffer-settings
3901 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3902 (modes . '(org-mode)))))
3904 ;; Imenu
3905 (org-set-local 'imenu-create-index-function
3906 'org-imenu-get-tree)
3908 ;; Make isearch reveal context
3909 (if (or (featurep 'xemacs)
3910 (not (boundp 'outline-isearch-open-invisible-function)))
3911 ;; Emacs 21 and XEmacs make use of the hook
3912 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3913 ;; Emacs 22 deals with this through a special variable
3914 (org-set-local 'outline-isearch-open-invisible-function
3915 (lambda (&rest ignore) (org-show-context 'isearch))))
3917 ;; If empty file that did not turn on org-mode automatically, make it to.
3918 (if (and org-insert-mode-line-in-empty-file
3919 (interactive-p)
3920 (= (point-min) (point-max)))
3921 (insert "# -*- mode: org -*-\n\n"))
3923 (unless org-inhibit-startup
3924 (when org-startup-align-all-tables
3925 (let ((bmp (buffer-modified-p)))
3926 (org-table-map-tables 'org-table-align)
3927 (set-buffer-modified-p bmp)))
3928 (org-set-startup-visibility)))
3930 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3932 (defun org-current-time ()
3933 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3934 (if (> (car org-time-stamp-rounding-minutes) 1)
3935 (let ((r (car org-time-stamp-rounding-minutes))
3936 (time (decode-time)))
3937 (apply 'encode-time
3938 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3939 (nthcdr 2 time))))
3940 (current-time)))
3942 ;;;; Font-Lock stuff, including the activators
3944 (defvar org-mouse-map (make-sparse-keymap))
3945 (org-defkey org-mouse-map
3946 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3947 (org-defkey org-mouse-map
3948 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3949 (when org-mouse-1-follows-link
3950 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3951 (when org-tab-follows-link
3952 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3953 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3955 (require 'font-lock)
3957 (defconst org-non-link-chars "]\t\n\r<>")
3958 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3959 "shell" "elisp"))
3960 (defvar org-link-types-re nil
3961 "Matches a link that has a url-like prefix like \"http:\"")
3962 (defvar org-link-re-with-space nil
3963 "Matches a link with spaces, optional angular brackets around it.")
3964 (defvar org-link-re-with-space2 nil
3965 "Matches a link with spaces, optional angular brackets around it.")
3966 (defvar org-link-re-with-space3 nil
3967 "Matches a link with spaces, only for internal part in bracket links.")
3968 (defvar org-angle-link-re nil
3969 "Matches link with angular brackets, spaces are allowed.")
3970 (defvar org-plain-link-re nil
3971 "Matches plain link, without spaces.")
3972 (defvar org-bracket-link-regexp nil
3973 "Matches a link in double brackets.")
3974 (defvar org-bracket-link-analytic-regexp nil
3975 "Regular expression used to analyze links.
3976 Here is what the match groups contain after a match:
3977 1: http:
3978 2: http
3979 3: path
3980 4: [desc]
3981 5: desc")
3982 (defvar org-bracket-link-analytic-regexp++ nil
3983 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3984 (defvar org-any-link-re nil
3985 "Regular expression matching any link.")
3987 (defun org-make-link-regexps ()
3988 "Update the link regular expressions.
3989 This should be called after the variable `org-link-types' has changed."
3990 (setq org-link-types-re
3991 (concat
3992 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3993 org-link-re-with-space
3994 (concat
3995 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3996 "\\([^" org-non-link-chars " ]"
3997 "[^" org-non-link-chars "]*"
3998 "[^" org-non-link-chars " ]\\)>?")
3999 org-link-re-with-space2
4000 (concat
4001 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4002 "\\([^" org-non-link-chars " ]"
4003 "[^\t\n\r]*"
4004 "[^" org-non-link-chars " ]\\)>?")
4005 org-link-re-with-space3
4006 (concat
4007 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4008 "\\([^" org-non-link-chars " ]"
4009 "[^\t\n\r]*\\)")
4010 org-angle-link-re
4011 (concat
4012 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4013 "\\([^" org-non-link-chars " ]"
4014 "[^" org-non-link-chars "]*"
4015 "\\)>")
4016 org-plain-link-re
4017 (concat
4018 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4019 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4020 org-bracket-link-regexp
4021 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4022 org-bracket-link-analytic-regexp
4023 (concat
4024 "\\[\\["
4025 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4026 "\\([^]]+\\)"
4027 "\\]"
4028 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4029 "\\]")
4030 org-bracket-link-analytic-regexp++
4031 (concat
4032 "\\[\\["
4033 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4034 "\\([^]]+\\)"
4035 "\\]"
4036 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4037 "\\]")
4038 org-any-link-re
4039 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4040 org-angle-link-re "\\)\\|\\("
4041 org-plain-link-re "\\)")))
4043 (org-make-link-regexps)
4045 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4046 "Regular expression for fast time stamp matching.")
4047 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4048 "Regular expression for fast time stamp matching.")
4049 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4050 "Regular expression matching time strings for analysis.
4051 This one does not require the space after the date, so it can be used
4052 on a string that terminates immediately after the date.")
4053 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4054 "Regular expression matching time strings for analysis.")
4055 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4056 "Regular expression matching time stamps, with groups.")
4057 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4058 "Regular expression matching time stamps (also [..]), with groups.")
4059 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4060 "Regular expression matching a time stamp range.")
4061 (defconst org-tr-regexp-both
4062 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4063 "Regular expression matching a time stamp range.")
4064 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4065 org-ts-regexp "\\)?")
4066 "Regular expression matching a time stamp or time stamp range.")
4067 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4068 org-ts-regexp-both "\\)?")
4069 "Regular expression matching a time stamp or time stamp range.
4070 The time stamps may be either active or inactive.")
4072 (defvar org-emph-face nil)
4074 (defun org-do-emphasis-faces (limit)
4075 "Run through the buffer and add overlays to links."
4076 (let (rtn)
4077 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4078 (if (not (= (char-after (match-beginning 3))
4079 (char-after (match-beginning 4))))
4080 (progn
4081 (setq rtn t)
4082 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4083 'face
4084 (nth 1 (assoc (match-string 3)
4085 org-emphasis-alist)))
4086 (add-text-properties (match-beginning 2) (match-end 2)
4087 '(font-lock-multiline t))
4088 (when org-hide-emphasis-markers
4089 (add-text-properties (match-end 4) (match-beginning 5)
4090 '(invisible org-link))
4091 (add-text-properties (match-beginning 3) (match-end 3)
4092 '(invisible org-link)))))
4093 (backward-char 1))
4094 rtn))
4096 (defun org-emphasize (&optional char)
4097 "Insert or change an emphasis, i.e. a font like bold or italic.
4098 If there is an active region, change that region to a new emphasis.
4099 If there is no region, just insert the marker characters and position
4100 the cursor between them.
4101 CHAR should be either the marker character, or the first character of the
4102 HTML tag associated with that emphasis. If CHAR is a space, the means
4103 to remove the emphasis of the selected region.
4104 If char is not given (for example in an interactive call) it
4105 will be prompted for."
4106 (interactive)
4107 (let ((eal org-emphasis-alist) e det
4108 (erc org-emphasis-regexp-components)
4109 (prompt "")
4110 (string "") beg end move tag c s)
4111 (if (org-region-active-p)
4112 (setq beg (region-beginning) end (region-end)
4113 string (buffer-substring beg end))
4114 (setq move t))
4116 (while (setq e (pop eal))
4117 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4118 c (aref tag 0))
4119 (push (cons c (string-to-char (car e))) det)
4120 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4121 (substring tag 1)))))
4122 (setq det (nreverse det))
4123 (unless char
4124 (message "%s" (concat "Emphasis marker or tag:" prompt))
4125 (setq char (read-char-exclusive)))
4126 (setq char (or (cdr (assoc char det)) char))
4127 (if (equal char ?\ )
4128 (setq s "" move nil)
4129 (unless (assoc (char-to-string char) org-emphasis-alist)
4130 (error "No such emphasis marker: \"%c\"" char))
4131 (setq s (char-to-string char)))
4132 (while (and (> (length string) 1)
4133 (equal (substring string 0 1) (substring string -1))
4134 (assoc (substring string 0 1) org-emphasis-alist))
4135 (setq string (substring string 1 -1)))
4136 (setq string (concat s string s))
4137 (if beg (delete-region beg end))
4138 (unless (or (bolp)
4139 (string-match (concat "[" (nth 0 erc) "\n]")
4140 (char-to-string (char-before (point)))))
4141 (insert " "))
4142 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4143 (char-to-string (char-after (point))))
4144 (insert " ") (backward-char 1))
4145 (insert string)
4146 (and move (backward-char 1))))
4148 (defconst org-nonsticky-props
4149 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4151 (defsubst org-rear-nonsticky-at (pos)
4152 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4154 (defun org-activate-plain-links (limit)
4155 "Run through the buffer and add overlays to links."
4156 (catch 'exit
4157 (let (f)
4158 (while (re-search-forward org-plain-link-re limit t)
4159 (setq f (get-text-property (match-beginning 0) 'face))
4160 (if (or (eq f 'org-tag)
4161 (and (listp f) (memq 'org-tag f)))
4163 (add-text-properties (match-beginning 0) (match-end 0)
4164 (list 'mouse-face 'highlight
4165 'keymap org-mouse-map))
4166 (org-rear-nonsticky-at (match-end 0))
4167 (throw 'exit t))))))
4169 (defun org-activate-code (limit)
4170 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4171 (progn
4172 (remove-text-properties (match-beginning 0) (match-end 0)
4173 '(display t invisible t intangible t))
4174 t)))
4176 (defun org-activate-angle-links (limit)
4177 "Run through the buffer and add overlays to links."
4178 (if (re-search-forward org-angle-link-re limit t)
4179 (progn
4180 (add-text-properties (match-beginning 0) (match-end 0)
4181 (list 'mouse-face 'highlight
4182 'keymap org-mouse-map))
4183 (org-rear-nonsticky-at (match-end 0))
4184 t)))
4186 (defun org-activate-footnote-links (limit)
4187 "Run through the buffer and add overlays to links."
4188 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4189 limit t)
4190 (progn
4191 (add-text-properties (match-beginning 2) (match-end 2)
4192 (list 'mouse-face 'highlight
4193 'keymap org-mouse-map
4194 'help-echo
4195 (if (= (point-at-bol) (match-beginning 2))
4196 "Footnote definition"
4197 "Footnote reference")
4199 (org-rear-nonsticky-at (match-end 2))
4200 t)))
4202 (defun org-activate-bracket-links (limit)
4203 "Run through the buffer and add overlays to bracketed links."
4204 (if (re-search-forward org-bracket-link-regexp limit t)
4205 (let* ((help (concat "LINK: "
4206 (org-match-string-no-properties 1)))
4207 ;; FIXME: above we should remove the escapes.
4208 ;; but that requires another match, protecting match data,
4209 ;; a lot of overhead for font-lock.
4210 (ip (org-maybe-intangible
4211 (list 'invisible 'org-link
4212 'keymap org-mouse-map 'mouse-face 'highlight
4213 'font-lock-multiline t 'help-echo help)))
4214 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4215 'font-lock-multiline t 'help-echo help)))
4216 ;; We need to remove the invisible property here. Table narrowing
4217 ;; may have made some of this invisible.
4218 (remove-text-properties (match-beginning 0) (match-end 0)
4219 '(invisible nil))
4220 (if (match-end 3)
4221 (progn
4222 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4223 (org-rear-nonsticky-at (match-beginning 3))
4224 (add-text-properties (match-beginning 3) (match-end 3) vp)
4225 (org-rear-nonsticky-at (match-end 3))
4226 (add-text-properties (match-end 3) (match-end 0) ip)
4227 (org-rear-nonsticky-at (match-end 0)))
4228 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4229 (org-rear-nonsticky-at (match-beginning 1))
4230 (add-text-properties (match-beginning 1) (match-end 1) vp)
4231 (org-rear-nonsticky-at (match-end 1))
4232 (add-text-properties (match-end 1) (match-end 0) ip)
4233 (org-rear-nonsticky-at (match-end 0)))
4234 t)))
4236 (defun org-activate-dates (limit)
4237 "Run through the buffer and add overlays to dates."
4238 (if (re-search-forward org-tsr-regexp-both limit t)
4239 (progn
4240 (add-text-properties (match-beginning 0) (match-end 0)
4241 (list 'mouse-face 'highlight
4242 'keymap org-mouse-map))
4243 (org-rear-nonsticky-at (match-end 0))
4244 (when org-display-custom-times
4245 (if (match-end 3)
4246 (org-display-custom-time (match-beginning 3) (match-end 3)))
4247 (org-display-custom-time (match-beginning 1) (match-end 1)))
4248 t)))
4250 (defvar org-target-link-regexp nil
4251 "Regular expression matching radio targets in plain text.")
4252 (make-variable-buffer-local 'org-target-link-regexp)
4253 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4254 "Regular expression matching a link target.")
4255 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4256 "Regular expression matching a radio target.")
4257 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4258 "Regular expression matching any target.")
4260 (defun org-activate-target-links (limit)
4261 "Run through the buffer and add overlays to target matches."
4262 (when org-target-link-regexp
4263 (let ((case-fold-search t))
4264 (if (re-search-forward org-target-link-regexp limit t)
4265 (progn
4266 (add-text-properties (match-beginning 0) (match-end 0)
4267 (list 'mouse-face 'highlight
4268 'keymap org-mouse-map
4269 'help-echo "Radio target link"
4270 'org-linked-text t))
4271 (org-rear-nonsticky-at (match-end 0))
4272 t)))))
4274 (defun org-update-radio-target-regexp ()
4275 "Find all radio targets in this file and update the regular expression."
4276 (interactive)
4277 (when (memq 'radio org-activate-links)
4278 (setq org-target-link-regexp
4279 (org-make-target-link-regexp (org-all-targets 'radio)))
4280 (org-restart-font-lock)))
4282 (defun org-hide-wide-columns (limit)
4283 (let (s e)
4284 (setq s (text-property-any (point) (or limit (point-max))
4285 'org-cwidth t))
4286 (when s
4287 (setq e (next-single-property-change s 'org-cwidth))
4288 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4289 (goto-char e)
4290 t)))
4292 (defvar org-latex-and-specials-regexp nil
4293 "Regular expression for highlighting export special stuff.")
4294 (defvar org-match-substring-regexp)
4295 (defvar org-match-substring-with-braces-regexp)
4296 (defvar org-export-html-special-string-regexps)
4298 (defun org-compute-latex-and-specials-regexp ()
4299 "Compute regular expression for stuff treated specially by exporters."
4300 (if (not org-highlight-latex-fragments-and-specials)
4301 (org-set-local 'org-latex-and-specials-regexp nil)
4302 (require 'org-exp)
4303 (let*
4304 ((matchers (plist-get org-format-latex-options :matchers))
4305 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4306 org-latex-regexps)))
4307 (options (org-combine-plists (org-default-export-plist)
4308 (org-infile-export-plist)))
4309 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4310 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4311 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4312 (org-export-html-expand (plist-get options :expand-quoted-html))
4313 (org-export-with-special-strings (plist-get options :special-strings))
4314 (re-sub
4315 (cond
4316 ((equal org-export-with-sub-superscripts '{})
4317 (list org-match-substring-with-braces-regexp))
4318 (org-export-with-sub-superscripts
4319 (list org-match-substring-regexp))
4320 (t nil)))
4321 (re-latex
4322 (if org-export-with-LaTeX-fragments
4323 (mapcar (lambda (x) (nth 1 x)) latexs)))
4324 (re-macros
4325 (if org-export-with-TeX-macros
4326 (list (concat "\\\\"
4327 (regexp-opt
4328 (append (mapcar 'car org-html-entities)
4329 (if (boundp 'org-latex-entities)
4330 org-latex-entities nil))
4331 'words))) ; FIXME
4333 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4334 (re-special (if org-export-with-special-strings
4335 (mapcar (lambda (x) (car x))
4336 org-export-html-special-string-regexps)))
4337 (re-rest
4338 (delq nil
4339 (list
4340 (if org-export-html-expand "@<[^>\n]+>")
4341 ))))
4342 (org-set-local
4343 'org-latex-and-specials-regexp
4344 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4345 re-rest) "\\|")))))
4347 (defun org-do-latex-and-special-faces (limit)
4348 "Run through the buffer and add overlays to links."
4349 (when org-latex-and-specials-regexp
4350 (let (rtn d)
4351 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4352 limit t))
4353 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4354 'face))
4355 '(org-code org-verbatim underline)))
4356 (progn
4357 (setq rtn t
4358 d (cond ((member (char-after (1+ (match-beginning 0)))
4359 '(?_ ?^)) 1)
4360 (t 0)))
4361 (font-lock-prepend-text-property
4362 (+ d (match-beginning 0)) (match-end 0)
4363 'face 'org-latex-and-export-specials)
4364 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4365 '(font-lock-multiline t)))))
4366 rtn)))
4368 (defun org-restart-font-lock ()
4369 "Restart font-lock-mode, to force refontification."
4370 (when (and (boundp 'font-lock-mode) font-lock-mode)
4371 (font-lock-mode -1)
4372 (font-lock-mode 1)))
4374 (defun org-all-targets (&optional radio)
4375 "Return a list of all targets in this file.
4376 With optional argument RADIO, only find radio targets."
4377 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4378 rtn)
4379 (save-excursion
4380 (goto-char (point-min))
4381 (while (re-search-forward re nil t)
4382 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4383 rtn)))
4385 (defun org-make-target-link-regexp (targets)
4386 "Make regular expression matching all strings in TARGETS.
4387 The regular expression finds the targets also if there is a line break
4388 between words."
4389 (and targets
4390 (concat
4391 "\\<\\("
4392 (mapconcat
4393 (lambda (x)
4394 (while (string-match " +" x)
4395 (setq x (replace-match "\\s-+" t t x)))
4397 targets
4398 "\\|")
4399 "\\)\\>")))
4401 (defun org-activate-tags (limit)
4402 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4403 (progn
4404 (add-text-properties (match-beginning 1) (match-end 1)
4405 (list 'mouse-face 'highlight
4406 'keymap org-mouse-map))
4407 (org-rear-nonsticky-at (match-end 1))
4408 t)))
4410 (defun org-outline-level ()
4411 (save-excursion
4412 (looking-at outline-regexp)
4413 (if (match-beginning 1)
4414 (+ (org-get-string-indentation (match-string 1)) 1000)
4415 (1- (- (match-end 0) (match-beginning 0))))))
4417 (defvar org-font-lock-keywords nil)
4419 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4420 "Regular expression matching a property line.")
4422 (defvar org-font-lock-hook nil
4423 "Functions to be called for special font lock stuff.")
4425 (defun org-font-lock-hook (limit)
4426 (run-hook-with-args 'org-font-lock-hook limit))
4428 (defun org-set-font-lock-defaults ()
4429 (let* ((em org-fontify-emphasized-text)
4430 (lk org-activate-links)
4431 (org-font-lock-extra-keywords
4432 (list
4433 ;; Call the hook
4434 '(org-font-lock-hook)
4435 ;; Headlines
4436 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4437 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4438 ;; Table lines
4439 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4440 (1 'org-table t))
4441 ;; Table internals
4442 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4443 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4444 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4445 ;; Drawers
4446 (list org-drawer-regexp '(0 'org-special-keyword t))
4447 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4448 ;; Properties
4449 (list org-property-re
4450 '(1 'org-special-keyword t)
4451 '(3 'org-property-value t))
4452 (if org-format-transports-properties-p
4453 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4454 ;; Links
4455 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4456 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4457 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4458 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4459 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4460 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4461 (if (memq 'footnote lk) '(org-activate-footnote-links
4462 (2 'org-footnote t)))
4463 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4464 '(org-hide-wide-columns (0 nil append))
4465 ;; TODO lines
4466 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4467 '(1 (org-get-todo-face 1) t))
4468 ;; DONE
4469 (if org-fontify-done-headline
4470 (list (concat "^[*]+ +\\<\\("
4471 (mapconcat 'regexp-quote org-done-keywords "\\|")
4472 "\\)\\(.*\\)")
4473 '(2 'org-headline-done t))
4474 nil)
4475 ;; Priorities
4476 '(org-font-lock-add-priority-faces)
4477 ;; Tags
4478 '(org-font-lock-add-tag-faces)
4479 ;; Special keywords
4480 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4481 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4482 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4483 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4484 ;; Emphasis
4485 (if em
4486 (if (featurep 'xemacs)
4487 '(org-do-emphasis-faces (0 nil append))
4488 '(org-do-emphasis-faces)))
4489 ;; Checkboxes
4490 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4491 2 'org-checkbox prepend)
4492 (if org-provide-checkbox-statistics
4493 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4494 (0 (org-get-checkbox-statistics-face) t)))
4495 ;; Description list items
4496 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4497 2 'bold prepend)
4498 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4499 '(1 'org-archived prepend))
4500 ;; Specials
4501 '(org-do-latex-and-special-faces)
4502 ;; Code
4503 '(org-activate-code (1 'org-code t))
4504 ;; COMMENT
4505 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4506 "\\|" org-quote-string "\\)\\>")
4507 '(1 'org-special-keyword t))
4508 '("^#.*" (0 'font-lock-comment-face t))
4510 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4511 ;; Now set the full font-lock-keywords
4512 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4513 (org-set-local 'font-lock-defaults
4514 '(org-font-lock-keywords t nil nil backward-paragraph))
4515 (kill-local-variable 'font-lock-keywords) nil))
4517 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
4518 "Fontify string S like in Org-mode"
4519 (with-temp-buffer
4520 (insert s)
4521 (let ((org-odd-levels-only odd-levels))
4522 (org-mode)
4523 (font-lock-fontify-buffer)
4524 (buffer-string))))
4526 (defvar org-m nil)
4527 (defvar org-l nil)
4528 (defvar org-f nil)
4529 (defun org-get-level-face (n)
4530 "Get the right face for match N in font-lock matching of headlines."
4531 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4532 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4533 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4534 (cond
4535 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4536 ((eq n 2) org-f)
4537 (t (if org-level-color-stars-only nil org-f))))
4539 (defun org-get-todo-face (kwd)
4540 "Get the right face for a TODO keyword KWD.
4541 If KWD is a number, get the corresponding match group."
4542 (if (numberp kwd) (setq kwd (match-string kwd)))
4543 (or (cdr (assoc kwd org-todo-keyword-faces))
4544 (and (member kwd org-done-keywords) 'org-done)
4545 'org-todo))
4547 (defun org-font-lock-add-tag-faces (limit)
4548 "Add the special tag faces."
4549 (when (and org-tag-faces org-tags-special-faces-re)
4550 (while (re-search-forward org-tags-special-faces-re limit t)
4551 (add-text-properties (match-beginning 1) (match-end 1)
4552 (list 'face (org-get-tag-face 1)
4553 'font-lock-fontified t))
4554 (backward-char 1))))
4556 (defun org-font-lock-add-priority-faces (limit)
4557 "Add the special priority faces."
4558 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4559 (add-text-properties
4560 (match-beginning 0) (match-end 0)
4561 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4562 org-priority-faces))
4563 'org-special-keyword)
4564 'font-lock-fontified t))))
4566 (defun org-get-tag-face (kwd)
4567 "Get the right face for a TODO keyword KWD.
4568 If KWD is a number, get the corresponding match group."
4569 (if (numberp kwd) (setq kwd (match-string kwd)))
4570 (or (cdr (assoc kwd org-tag-faces))
4571 'org-tag))
4573 (defun org-unfontify-region (beg end &optional maybe_loudly)
4574 "Remove fontification and activation overlays from links."
4575 (font-lock-default-unfontify-region beg end)
4576 (let* ((buffer-undo-list t)
4577 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4578 (inhibit-modification-hooks t)
4579 deactivate-mark buffer-file-name buffer-file-truename)
4580 (remove-text-properties beg end
4581 '(mouse-face t keymap t org-linked-text t
4582 invisible t intangible t))))
4584 ;;;; Visibility cycling, including org-goto and indirect buffer
4586 ;;; Cycling
4588 (defvar org-cycle-global-status nil)
4589 (make-variable-buffer-local 'org-cycle-global-status)
4590 (defvar org-cycle-subtree-status nil)
4591 (make-variable-buffer-local 'org-cycle-subtree-status)
4593 ;;;###autoload
4595 (defvar org-inlinetask-min-level)
4597 (defun org-cycle (&optional arg)
4598 "TAB-action and visibility cycling for Org-mode.
4600 This is the command invoked in Org-moe by the TAB key. It's main purpose
4601 is outine visibility cycling, but it also invokes other actions
4602 in special contexts.
4604 - When this function is called with a prefix argument, rotate the entire
4605 buffer through 3 states (global cycling)
4606 1. OVERVIEW: Show only top-level headlines.
4607 2. CONTENTS: Show all headlines of all levels, but no body text.
4608 3. SHOW ALL: Show everything.
4609 When called with two `C-u C-u' prefixes, switch to the startup visibility,
4610 determined by the variable `org-startup-folded', and by any VISIBILITY
4611 properties in the buffer.
4612 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
4613 including any drawers.
4615 - When inside a table, re-align the table and move to the next field.
4617 - When point is at the beginning of a headline, rotate the subtree started
4618 by this line through 3 different states (local cycling)
4619 1. FOLDED: Only the main headline is shown.
4620 2. CHILDREN: The main headline and the direct children are shown.
4621 From this state, you can move to one of the children
4622 and zoom in further.
4623 3. SUBTREE: Show the entire subtree, including body text.
4625 - When there is a numeric prefix, go up to a heading with level ARG, do
4626 a `show-subtree' and return to the previous cursor position. If ARG
4627 is negative, go up that many levels.
4629 - When point is not at the beginning of a headline, execute the global
4630 binding for TAB, which is re-indenting the line. See the option
4631 `org-cycle-emulate-tab' for details.
4633 - Special case: if point is at the beginning of the buffer and there is
4634 no headline in line 1, this function will act as if called with prefix arg.
4635 But only if also the variable `org-cycle-global-at-bob' is t."
4636 (interactive "P")
4637 (org-load-modules-maybe)
4638 (unless (run-hook-with-args-until-success 'org-tab-first-hook)
4639 (let* ((limit-level
4640 (or org-cycle-max-level
4641 (and (boundp 'org-inlinetask-min-level)
4642 org-inlinetask-min-level
4643 (1- org-inlinetask-min-level))))
4644 (nstars (and limit-level
4645 (if org-odd-levels-only
4646 (and limit-level (1- (* limit-level 2)))
4647 limit-level)))
4648 (outline-regexp
4649 (cond
4650 ((not (org-mode-p)) outline-regexp)
4651 (org-cycle-include-plain-lists
4652 (concat "\\(?:\\*"
4653 (if nstars (format "\\{1,%d\\}" nstars) "+")
4654 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
4655 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
4656 (bob-special (and org-cycle-global-at-bob (bobp)
4657 (not (looking-at outline-regexp))))
4658 (org-cycle-hook
4659 (if bob-special
4660 (delq 'org-optimize-window-after-visibility-change
4661 (copy-sequence org-cycle-hook))
4662 org-cycle-hook))
4663 (pos (point)))
4665 (if (or bob-special (equal arg '(4)))
4666 ;; special case: use global cycling
4667 (setq arg t))
4669 (cond
4671 ((equal arg '(16))
4672 (org-set-startup-visibility)
4673 (message "Startup visibility, plus VISIBILITY properties"))
4675 ((equal arg '(64))
4676 (show-all)
4677 (message "Entire buffer visible, including drawers"))
4679 ((org-at-table-p 'any)
4680 ;; Enter the table or move to the next field in the table
4681 (or (org-table-recognize-table.el)
4682 (progn
4683 (if arg (org-table-edit-field t)
4684 (org-table-justify-field-maybe)
4685 (call-interactively 'org-table-next-field)))))
4687 ((run-hook-with-args-until-success
4688 'org-tab-after-check-for-table-hook))
4690 ((eq arg t) ;; Global cycling
4691 (org-cycle-internal-global))
4693 ((and org-drawers org-drawer-regexp
4694 (save-excursion
4695 (beginning-of-line 1)
4696 (looking-at org-drawer-regexp)))
4697 ;; Toggle block visibility
4698 (org-flag-drawer
4699 (not (get-char-property (match-end 0) 'invisible))))
4701 ((integerp arg)
4702 ;; Show-subtree, ARG levels up from here.
4703 (save-excursion
4704 (org-back-to-heading)
4705 (outline-up-heading (if (< arg 0) (- arg)
4706 (- (funcall outline-level) arg)))
4707 (org-show-subtree)))
4709 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4710 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4712 (org-cycle-internal-local))
4714 ;; TAB emulation and template completion
4715 (buffer-read-only (org-back-to-heading))
4717 ((run-hook-with-args-until-success
4718 'org-tab-after-check-for-cycling-hook))
4720 ((org-try-structure-completion))
4722 ((org-try-cdlatex-tab))
4724 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4725 (or (not (bolp))
4726 (not (looking-at outline-regexp))))
4727 (call-interactively (global-key-binding "\t")))
4729 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4730 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4731 (or (and (eq org-cycle-emulate-tab 'white)
4732 (= (match-end 0) (point-at-eol)))
4733 (and (eq org-cycle-emulate-tab 'whitestart)
4734 (>= (match-end 0) pos))))
4736 (eq org-cycle-emulate-tab t))
4737 (call-interactively (global-key-binding "\t")))
4739 (t (save-excursion
4740 (org-back-to-heading)
4741 (org-cycle)))))))
4743 (defun org-cycle-internal-global ()
4744 "Do the global cycling action."
4745 (cond
4746 ((and (eq last-command this-command)
4747 (eq org-cycle-global-status 'overview))
4748 ;; We just created the overview - now do table of contents
4749 ;; This can be slow in very large buffers, so indicate action
4750 (run-hook-with-args 'org-pre-cycle-hook 'contents)
4751 (message "CONTENTS...")
4752 (org-content)
4753 (message "CONTENTS...done")
4754 (setq org-cycle-global-status 'contents)
4755 (run-hook-with-args 'org-cycle-hook 'contents))
4757 ((and (eq last-command this-command)
4758 (eq org-cycle-global-status 'contents))
4759 ;; We just showed the table of contents - now show everything
4760 (run-hook-with-args 'org-pre-cycle-hook 'all)
4761 (show-all)
4762 (message "SHOW ALL")
4763 (setq org-cycle-global-status 'all)
4764 (run-hook-with-args 'org-cycle-hook 'all))
4767 ;; Default action: go to overview
4768 (run-hook-with-args 'org-pre-cycle-hook 'overview)
4769 (org-overview)
4770 (message "OVERVIEW")
4771 (setq org-cycle-global-status 'overview)
4772 (run-hook-with-args 'org-cycle-hook 'overview))))
4774 (defun org-cycle-internal-local ()
4775 "Do the local cycling action."
4776 (org-back-to-heading)
4777 (let ((goal-column 0) eoh eol eos)
4778 ;; First, some boundaries
4779 (save-excursion
4780 (org-back-to-heading)
4781 (save-excursion
4782 (beginning-of-line 2)
4783 (while (and (not (eobp)) ;; this is like `next-line'
4784 (get-char-property (1- (point)) 'invisible))
4785 (beginning-of-line 2)) (setq eol (point)))
4786 (outline-end-of-heading) (setq eoh (point))
4787 (org-end-of-subtree t)
4788 (unless (eobp)
4789 (skip-chars-forward " \t\n")
4790 (beginning-of-line 1) ; in case this is an item
4792 (setq eos (1- (point))))
4793 ;; Find out what to do next and set `this-command'
4794 (cond
4795 ((= eos eoh)
4796 ;; Nothing is hidden behind this heading
4797 (run-hook-with-args 'org-pre-cycle-hook 'empty)
4798 (message "EMPTY ENTRY")
4799 (setq org-cycle-subtree-status nil)
4800 (save-excursion
4801 (goto-char eos)
4802 (outline-next-heading)
4803 (if (org-invisible-p) (org-flag-heading nil))))
4804 ((or (>= eol eos)
4805 (not (string-match "\\S-" (buffer-substring eol eos))))
4806 ;; Entire subtree is hidden in one line: open it
4807 (run-hook-with-args 'org-pre-cycle-hook 'children)
4808 (org-show-entry)
4809 (show-children)
4810 (message "CHILDREN")
4811 (save-excursion
4812 (goto-char eos)
4813 (outline-next-heading)
4814 (if (org-invisible-p) (org-flag-heading nil)))
4815 (setq org-cycle-subtree-status 'children)
4816 (run-hook-with-args 'org-cycle-hook 'children))
4817 ((and (eq last-command this-command)
4818 (eq org-cycle-subtree-status 'children))
4819 ;; We just showed the children, now show everything.
4820 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
4821 (org-show-subtree)
4822 (message "SUBTREE")
4823 (setq org-cycle-subtree-status 'subtree)
4824 (run-hook-with-args 'org-cycle-hook 'subtree))
4826 ;; Default action: hide the subtree.
4827 (run-hook-with-args 'org-pre-cycle-hook 'folded)
4828 (hide-subtree)
4829 (message "FOLDED")
4830 (setq org-cycle-subtree-status 'folded)
4831 (run-hook-with-args 'org-cycle-hook 'folded)))))
4833 ;;;###autoload
4834 (defun org-global-cycle (&optional arg)
4835 "Cycle the global visibility. For details see `org-cycle'.
4836 With C-u prefix arg, switch to startup visibility.
4837 With a numeric prefix, show all headlines up to that level."
4838 (interactive "P")
4839 (let ((org-cycle-include-plain-lists
4840 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4841 (cond
4842 ((integerp arg)
4843 (show-all)
4844 (hide-sublevels arg)
4845 (setq org-cycle-global-status 'contents))
4846 ((equal arg '(4))
4847 (org-set-startup-visibility)
4848 (message "Startup visibility, plus VISIBILITY properties."))
4850 (org-cycle '(4))))))
4852 (defun org-set-startup-visibility ()
4853 "Set the visibility required by startup options and properties."
4854 (cond
4855 ((eq org-startup-folded t)
4856 (org-cycle '(4)))
4857 ((eq org-startup-folded 'content)
4858 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4859 (org-cycle '(4)) (org-cycle '(4)))))
4860 (org-set-visibility-according-to-property 'no-cleanup)
4861 (org-cycle-hide-archived-subtrees 'all)
4862 (org-cycle-hide-drawers 'all)
4863 (org-cycle-show-empty-lines 'all))
4865 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4866 "Switch subtree visibilities according to :VISIBILITY: property."
4867 (interactive)
4868 (let (org-show-entry-below state)
4869 (save-excursion
4870 (goto-char (point-min))
4871 (while (re-search-forward
4872 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4873 nil t)
4874 (setq state (match-string 1))
4875 (save-excursion
4876 (org-back-to-heading t)
4877 (hide-subtree)
4878 (org-reveal)
4879 (cond
4880 ((equal state '("fold" "folded"))
4881 (hide-subtree))
4882 ((equal state "children")
4883 (org-show-hidden-entry)
4884 (show-children))
4885 ((equal state "content")
4886 (save-excursion
4887 (save-restriction
4888 (org-narrow-to-subtree)
4889 (org-content))))
4890 ((member state '("all" "showall"))
4891 (show-subtree)))))
4892 (unless no-cleanup
4893 (org-cycle-hide-archived-subtrees 'all)
4894 (org-cycle-hide-drawers 'all)
4895 (org-cycle-show-empty-lines 'all)))))
4897 (defun org-overview ()
4898 "Switch to overview mode, showing only top-level headlines.
4899 Really, this shows all headlines with level equal or greater than the level
4900 of the first headline in the buffer. This is important, because if the
4901 first headline is not level one, then (hide-sublevels 1) gives confusing
4902 results."
4903 (interactive)
4904 (let ((level (save-excursion
4905 (goto-char (point-min))
4906 (if (re-search-forward (concat "^" outline-regexp) nil t)
4907 (progn
4908 (goto-char (match-beginning 0))
4909 (funcall outline-level))))))
4910 (and level (hide-sublevels level))))
4912 (defun org-content (&optional arg)
4913 "Show all headlines in the buffer, like a table of contents.
4914 With numerical argument N, show content up to level N."
4915 (interactive "P")
4916 (save-excursion
4917 ;; Visit all headings and show their offspring
4918 (and (integerp arg) (org-overview))
4919 (goto-char (point-max))
4920 (catch 'exit
4921 (while (and (progn (condition-case nil
4922 (outline-previous-visible-heading 1)
4923 (error (goto-char (point-min))))
4925 (looking-at outline-regexp))
4926 (if (integerp arg)
4927 (show-children (1- arg))
4928 (show-branches))
4929 (if (bobp) (throw 'exit nil))))))
4932 (defun org-optimize-window-after-visibility-change (state)
4933 "Adjust the window after a change in outline visibility.
4934 This function is the default value of the hook `org-cycle-hook'."
4935 (when (get-buffer-window (current-buffer))
4936 (cond
4937 ((eq state 'content) nil)
4938 ((eq state 'all) nil)
4939 ((eq state 'folded) nil)
4940 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4941 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4943 (defun org-compact-display-after-subtree-move ()
4944 "Show a compacter version of the tree of the entry's parent."
4945 (save-excursion
4946 (if (org-up-heading-safe)
4947 (progn
4948 (hide-subtree)
4949 (show-entry)
4950 (show-children)
4951 (org-cycle-show-empty-lines 'children)
4952 (org-cycle-hide-drawers 'children))
4953 (org-overview))))
4955 (defun org-cycle-show-empty-lines (state)
4956 "Show empty lines above all visible headlines.
4957 The region to be covered depends on STATE when called through
4958 `org-cycle-hook'. Lisp program can use t for STATE to get the
4959 entire buffer covered. Note that an empty line is only shown if there
4960 are at least `org-cycle-separator-lines' empty lines before the headline."
4961 (when (> org-cycle-separator-lines 0)
4962 (save-excursion
4963 (let* ((n org-cycle-separator-lines)
4964 (re (cond
4965 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4966 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4967 (t (let ((ns (number-to-string (- n 2))))
4968 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4969 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4970 beg end)
4971 (cond
4972 ((memq state '(overview contents t))
4973 (setq beg (point-min) end (point-max)))
4974 ((memq state '(children folded))
4975 (setq beg (point) end (progn (org-end-of-subtree t t)
4976 (beginning-of-line 2)
4977 (point)))))
4978 (when beg
4979 (goto-char beg)
4980 (while (re-search-forward re end t)
4981 (if (not (get-char-property (match-end 1) 'invisible))
4982 (outline-flag-region
4983 (match-beginning 1) (match-end 1) nil)))))))
4984 ;; Never hide empty lines at the end of the file.
4985 (save-excursion
4986 (goto-char (point-max))
4987 (outline-previous-heading)
4988 (outline-end-of-heading)
4989 (if (and (looking-at "[ \t\n]+")
4990 (= (match-end 0) (point-max)))
4991 (outline-flag-region (point) (match-end 0) nil))))
4993 (defun org-show-empty-lines-in-parent ()
4994 "Move to the parent and re-show empty lines before visible headlines."
4995 (save-excursion
4996 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4997 (org-cycle-show-empty-lines context))))
4999 (defun org-cycle-hide-drawers (state)
5000 "Re-hide all drawers after a visibility state change."
5001 (when (and (org-mode-p)
5002 (not (memq state '(overview folded))))
5003 (save-excursion
5004 (let* ((globalp (memq state '(contents all)))
5005 (beg (if globalp (point-min) (point)))
5006 (end (if globalp (point-max) (org-end-of-subtree t))))
5007 (goto-char beg)
5008 (while (re-search-forward org-drawer-regexp end t)
5009 (org-flag-drawer t))))))
5011 (defun org-flag-drawer (flag)
5012 (save-excursion
5013 (beginning-of-line 1)
5014 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5015 (let ((b (match-end 0))
5016 (outline-regexp org-outline-regexp))
5017 (if (re-search-forward
5018 "^[ \t]*:END:"
5019 (save-excursion (outline-next-heading) (point)) t)
5020 (outline-flag-region b (point-at-eol) flag)
5021 (error ":END: line missing"))))))
5023 (defun org-subtree-end-visible-p ()
5024 "Is the end of the current subtree visible?"
5025 (pos-visible-in-window-p
5026 (save-excursion (org-end-of-subtree t) (point))))
5028 (defun org-first-headline-recenter (&optional N)
5029 "Move cursor to the first headline and recenter the headline.
5030 Optional argument N means, put the headline into the Nth line of the window."
5031 (goto-char (point-min))
5032 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5033 (beginning-of-line)
5034 (recenter (prefix-numeric-value N))))
5036 ;;; Org-goto
5038 (defvar org-goto-window-configuration nil)
5039 (defvar org-goto-marker nil)
5040 (defvar org-goto-map
5041 (let ((map (make-sparse-keymap)))
5042 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5043 (while (setq cmd (pop cmds))
5044 (substitute-key-definition cmd cmd map global-map)))
5045 (suppress-keymap map)
5046 (org-defkey map "\C-m" 'org-goto-ret)
5047 (org-defkey map [(return)] 'org-goto-ret)
5048 (org-defkey map [(left)] 'org-goto-left)
5049 (org-defkey map [(right)] 'org-goto-right)
5050 (org-defkey map [(control ?g)] 'org-goto-quit)
5051 (org-defkey map "\C-i" 'org-cycle)
5052 (org-defkey map [(tab)] 'org-cycle)
5053 (org-defkey map [(down)] 'outline-next-visible-heading)
5054 (org-defkey map [(up)] 'outline-previous-visible-heading)
5055 (if org-goto-auto-isearch
5056 (if (fboundp 'define-key-after)
5057 (define-key-after map [t] 'org-goto-local-auto-isearch)
5058 nil)
5059 (org-defkey map "q" 'org-goto-quit)
5060 (org-defkey map "n" 'outline-next-visible-heading)
5061 (org-defkey map "p" 'outline-previous-visible-heading)
5062 (org-defkey map "f" 'outline-forward-same-level)
5063 (org-defkey map "b" 'outline-backward-same-level)
5064 (org-defkey map "u" 'outline-up-heading))
5065 (org-defkey map "/" 'org-occur)
5066 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5067 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5068 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5069 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5070 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5071 map))
5073 (defconst org-goto-help
5074 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5075 RET=jump to location [Q]uit and return to previous location
5076 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5078 (defvar org-goto-start-pos) ; dynamically scoped parameter
5080 ;; FIXME: Docstring doe not mention both interfaces
5081 (defun org-goto (&optional alternative-interface)
5082 "Look up a different location in the current file, keeping current visibility.
5084 When you want look-up or go to a different location in a document, the
5085 fastest way is often to fold the entire buffer and then dive into the tree.
5086 This method has the disadvantage, that the previous location will be folded,
5087 which may not be what you want.
5089 This command works around this by showing a copy of the current buffer
5090 in an indirect buffer, in overview mode. You can dive into the tree in
5091 that copy, use org-occur and incremental search to find a location.
5092 When pressing RET or `Q', the command returns to the original buffer in
5093 which the visibility is still unchanged. After RET is will also jump to
5094 the location selected in the indirect buffer and expose the
5095 the headline hierarchy above."
5096 (interactive "P")
5097 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5098 (org-refile-use-outline-path t)
5099 (org-refile-target-verify-function nil)
5100 (interface
5101 (if (not alternative-interface)
5102 org-goto-interface
5103 (if (eq org-goto-interface 'outline)
5104 'outline-path-completion
5105 'outline)))
5106 (org-goto-start-pos (point))
5107 (selected-point
5108 (if (eq interface 'outline)
5109 (car (org-get-location (current-buffer) org-goto-help))
5110 (nth 3 (org-refile-get-location "Goto: ")))))
5111 (if selected-point
5112 (progn
5113 (org-mark-ring-push org-goto-start-pos)
5114 (goto-char selected-point)
5115 (if (or (org-invisible-p) (org-invisible-p2))
5116 (org-show-context 'org-goto)))
5117 (message "Quit"))))
5119 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5120 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5121 (defvar org-goto-local-auto-isearch-map) ; defined below
5123 (defun org-get-location (buf help)
5124 "Let the user select a location in the Org-mode buffer BUF.
5125 This function uses a recursive edit. It returns the selected position
5126 or nil."
5127 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5128 (isearch-hide-immediately nil)
5129 (isearch-search-fun-function
5130 (lambda () 'org-goto-local-search-headings))
5131 (org-goto-selected-point org-goto-exit-command))
5132 (save-excursion
5133 (save-window-excursion
5134 (delete-other-windows)
5135 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5136 (switch-to-buffer
5137 (condition-case nil
5138 (make-indirect-buffer (current-buffer) "*org-goto*")
5139 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5140 (with-output-to-temp-buffer "*Help*"
5141 (princ help))
5142 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5143 (setq buffer-read-only nil)
5144 (let ((org-startup-truncated t)
5145 (org-startup-folded nil)
5146 (org-startup-align-all-tables nil))
5147 (org-mode)
5148 (org-overview))
5149 (setq buffer-read-only t)
5150 (if (and (boundp 'org-goto-start-pos)
5151 (integer-or-marker-p org-goto-start-pos))
5152 (let ((org-show-hierarchy-above t)
5153 (org-show-siblings t)
5154 (org-show-following-heading t))
5155 (goto-char org-goto-start-pos)
5156 (and (org-invisible-p) (org-show-context)))
5157 (goto-char (point-min)))
5158 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5159 (message "Select location and press RET")
5160 (use-local-map org-goto-map)
5161 (recursive-edit)
5163 (kill-buffer "*org-goto*")
5164 (cons org-goto-selected-point org-goto-exit-command)))
5166 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5167 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5168 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5169 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5171 (defun org-goto-local-search-headings (string bound noerror)
5172 "Search and make sure that any matches are in headlines."
5173 (catch 'return
5174 (while (if isearch-forward
5175 (search-forward string bound noerror)
5176 (search-backward string bound noerror))
5177 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5178 (and (member :headline context)
5179 (not (member :tags context))))
5180 (throw 'return (point))))))
5182 (defun org-goto-local-auto-isearch ()
5183 "Start isearch."
5184 (interactive)
5185 (goto-char (point-min))
5186 (let ((keys (this-command-keys)))
5187 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5188 (isearch-mode t)
5189 (isearch-process-search-char (string-to-char keys)))))
5191 (defun org-goto-ret (&optional arg)
5192 "Finish `org-goto' by going to the new location."
5193 (interactive "P")
5194 (setq org-goto-selected-point (point)
5195 org-goto-exit-command 'return)
5196 (throw 'exit nil))
5198 (defun org-goto-left ()
5199 "Finish `org-goto' by going to the new location."
5200 (interactive)
5201 (if (org-on-heading-p)
5202 (progn
5203 (beginning-of-line 1)
5204 (setq org-goto-selected-point (point)
5205 org-goto-exit-command 'left)
5206 (throw 'exit nil))
5207 (error "Not on a heading")))
5209 (defun org-goto-right ()
5210 "Finish `org-goto' by going to the new location."
5211 (interactive)
5212 (if (org-on-heading-p)
5213 (progn
5214 (setq org-goto-selected-point (point)
5215 org-goto-exit-command 'right)
5216 (throw 'exit nil))
5217 (error "Not on a heading")))
5219 (defun org-goto-quit ()
5220 "Finish `org-goto' without cursor motion."
5221 (interactive)
5222 (setq org-goto-selected-point nil)
5223 (setq org-goto-exit-command 'quit)
5224 (throw 'exit nil))
5226 ;;; Indirect buffer display of subtrees
5228 (defvar org-indirect-dedicated-frame nil
5229 "This is the frame being used for indirect tree display.")
5230 (defvar org-last-indirect-buffer nil)
5232 (defun org-tree-to-indirect-buffer (&optional arg)
5233 "Create indirect buffer and narrow it to current subtree.
5234 With numerical prefix ARG, go up to this level and then take that tree.
5235 If ARG is negative, go up that many levels.
5236 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5237 indirect buffer previously made with this command, to avoid proliferation of
5238 indirect buffers. However, when you call the command with a `C-u' prefix, or
5239 when `org-indirect-buffer-display' is `new-frame', the last buffer
5240 is kept so that you can work with several indirect buffers at the same time.
5241 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5242 requests that a new frame be made for the new buffer, so that the dedicated
5243 frame is not changed."
5244 (interactive "P")
5245 (let ((cbuf (current-buffer))
5246 (cwin (selected-window))
5247 (pos (point))
5248 beg end level heading ibuf)
5249 (save-excursion
5250 (org-back-to-heading t)
5251 (when (numberp arg)
5252 (setq level (org-outline-level))
5253 (if (< arg 0) (setq arg (+ level arg)))
5254 (while (> (setq level (org-outline-level)) arg)
5255 (outline-up-heading 1 t)))
5256 (setq beg (point)
5257 heading (org-get-heading))
5258 (org-end-of-subtree t) (setq end (point)))
5259 (if (and (buffer-live-p org-last-indirect-buffer)
5260 (not (eq org-indirect-buffer-display 'new-frame))
5261 (not arg))
5262 (kill-buffer org-last-indirect-buffer))
5263 (setq ibuf (org-get-indirect-buffer cbuf)
5264 org-last-indirect-buffer ibuf)
5265 (cond
5266 ((or (eq org-indirect-buffer-display 'new-frame)
5267 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5268 (select-frame (make-frame))
5269 (delete-other-windows)
5270 (switch-to-buffer ibuf)
5271 (org-set-frame-title heading))
5272 ((eq org-indirect-buffer-display 'dedicated-frame)
5273 (raise-frame
5274 (select-frame (or (and org-indirect-dedicated-frame
5275 (frame-live-p org-indirect-dedicated-frame)
5276 org-indirect-dedicated-frame)
5277 (setq org-indirect-dedicated-frame (make-frame)))))
5278 (delete-other-windows)
5279 (switch-to-buffer ibuf)
5280 (org-set-frame-title (concat "Indirect: " heading)))
5281 ((eq org-indirect-buffer-display 'current-window)
5282 (switch-to-buffer ibuf))
5283 ((eq org-indirect-buffer-display 'other-window)
5284 (pop-to-buffer ibuf))
5285 (t (error "Invalid value.")))
5286 (if (featurep 'xemacs)
5287 (save-excursion (org-mode) (turn-on-font-lock)))
5288 (narrow-to-region beg end)
5289 (show-all)
5290 (goto-char pos)
5291 (and (window-live-p cwin) (select-window cwin))))
5293 (defun org-get-indirect-buffer (&optional buffer)
5294 (setq buffer (or buffer (current-buffer)))
5295 (let ((n 1) (base (buffer-name buffer)) bname)
5296 (while (buffer-live-p
5297 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5298 (setq n (1+ n)))
5299 (condition-case nil
5300 (make-indirect-buffer buffer bname 'clone)
5301 (error (make-indirect-buffer buffer bname)))))
5303 (defun org-set-frame-title (title)
5304 "Set the title of the current frame to the string TITLE."
5305 ;; FIXME: how to name a single frame in XEmacs???
5306 (unless (featurep 'xemacs)
5307 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5309 ;;;; Structure editing
5311 ;;; Inserting headlines
5313 (defun org-previous-line-empty-p ()
5314 (save-excursion
5315 (and (not (bobp))
5316 (or (beginning-of-line 0) t)
5317 (save-match-data
5318 (looking-at "[ \t]*$")))))
5320 (defun org-insert-heading (&optional force-heading)
5321 "Insert a new heading or item with same depth at point.
5322 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5323 If point is at the beginning of a headline, insert a sibling before the
5324 current headline. If point is not at the beginning, do not split the line,
5325 but create the new headline after the current line."
5326 (interactive "P")
5327 (if (= (buffer-size) 0)
5328 (insert "\n* ")
5329 (when (or force-heading (not (org-insert-item)))
5330 (let* ((empty-line-p nil)
5331 (head (save-excursion
5332 (condition-case nil
5333 (progn
5334 (org-back-to-heading)
5335 (setq empty-line-p (org-previous-line-empty-p))
5336 (match-string 0))
5337 (error "*"))))
5338 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5339 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5340 pos hide-previous previous-pos)
5341 (cond
5342 ((and (org-on-heading-p) (bolp)
5343 (or (bobp)
5344 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5345 ;; insert before the current line
5346 (open-line (if blank 2 1)))
5347 ((and (bolp)
5348 (or (bobp)
5349 (save-excursion
5350 (backward-char 1) (not (org-invisible-p)))))
5351 ;; insert right here
5352 nil)
5354 ;; somewhere in the line
5355 (save-excursion
5356 (setq previous-pos (point-at-bol))
5357 (end-of-line)
5358 (setq hide-previous (org-invisible-p)))
5359 (and org-insert-heading-respect-content (org-show-subtree))
5360 (let ((split
5361 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5362 (save-excursion
5363 (let ((p (point)))
5364 (goto-char (point-at-bol))
5365 (and (looking-at org-complex-heading-regexp)
5366 (> p (match-beginning 4)))))))
5367 tags pos)
5368 (cond
5369 (org-insert-heading-respect-content
5370 (org-end-of-subtree nil t)
5371 (or (bolp) (newline))
5372 (or (org-previous-line-empty-p)
5373 (and blank (newline)))
5374 (open-line 1))
5375 ((org-on-heading-p)
5376 (when hide-previous
5377 (show-children)
5378 (org-show-entry))
5379 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5380 (setq tags (and (match-end 2) (match-string 2)))
5381 (and (match-end 1)
5382 (delete-region (match-beginning 1) (match-end 1)))
5383 (setq pos (point-at-bol))
5384 (or split (end-of-line 1))
5385 (delete-horizontal-space)
5386 (newline (if blank 2 1))
5387 (when tags
5388 (save-excursion
5389 (goto-char pos)
5390 (end-of-line 1)
5391 (insert " " tags)
5392 (org-set-tags nil 'align))))
5394 (or split (end-of-line 1))
5395 (newline (if blank 2 1)))))))
5396 (insert head) (just-one-space)
5397 (setq pos (point))
5398 (end-of-line 1)
5399 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5400 (when (and org-insert-heading-respect-content hide-previous)
5401 (save-excursion
5402 (goto-char previous-pos)
5403 (hide-subtree)))
5404 (run-hooks 'org-insert-heading-hook)))))
5406 (defun org-get-heading (&optional no-tags)
5407 "Return the heading of the current entry, without the stars."
5408 (save-excursion
5409 (org-back-to-heading t)
5410 (if (looking-at
5411 (if no-tags
5412 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5413 "\\*+[ \t]+\\([^\r\n]*\\)"))
5414 (match-string 1) "")))
5416 (defun org-heading-components ()
5417 "Return the components of the current heading.
5418 This is a list with the following elements:
5419 - the level as an integer
5420 - the reduced level, different if `org-odd-levels-only' is set.
5421 - the TODO keyword, or nil
5422 - the priority character, like ?A, or nil if no priority is given
5423 - the headline text itself, or the tags string if no headline text
5424 - the tags string, or nil."
5425 (save-excursion
5426 (org-back-to-heading t)
5427 (if (looking-at org-complex-heading-regexp)
5428 (list (length (match-string 1))
5429 (org-reduced-level (length (match-string 1)))
5430 (org-match-string-no-properties 2)
5431 (and (match-end 3) (aref (match-string 3) 2))
5432 (org-match-string-no-properties 4)
5433 (org-match-string-no-properties 5)))))
5435 (defun org-get-entry ()
5436 "Get the entry text, after heading, entire subtree."
5437 (save-excursion
5438 (org-back-to-heading t)
5439 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
5441 (defun org-insert-heading-after-current ()
5442 "Insert a new heading with same level as current, after current subtree."
5443 (interactive)
5444 (org-back-to-heading)
5445 (org-insert-heading)
5446 (org-move-subtree-down)
5447 (end-of-line 1))
5449 (defun org-insert-heading-respect-content ()
5450 (interactive)
5451 (let ((org-insert-heading-respect-content t))
5452 (org-insert-heading t)))
5454 (defun org-insert-todo-heading-respect-content (&optional force-state)
5455 (interactive "P")
5456 (let ((org-insert-heading-respect-content t))
5457 (org-insert-todo-heading force-state t)))
5459 (defun org-insert-todo-heading (arg &optional force-heading)
5460 "Insert a new heading with the same level and TODO state as current heading.
5461 If the heading has no TODO state, or if the state is DONE, use the first
5462 state (TODO by default). Also with prefix arg, force first state."
5463 (interactive "P")
5464 (when (or force-heading (not (org-insert-item 'checkbox)))
5465 (org-insert-heading force-heading)
5466 (save-excursion
5467 (org-back-to-heading)
5468 (outline-previous-heading)
5469 (looking-at org-todo-line-regexp))
5470 (let*
5471 ((new-mark-x
5472 (if (or arg
5473 (not (match-beginning 2))
5474 (member (match-string 2) org-done-keywords))
5475 (car org-todo-keywords-1)
5476 (match-string 2)))
5477 (new-mark
5479 (run-hook-with-args-until-success
5480 'org-todo-get-default-hook new-mark-x nil)
5481 new-mark-x)))
5482 (beginning-of-line 1)
5483 (and (looking-at "\\*+ ") (goto-char (match-end 0))
5484 (insert new-mark " ")))
5485 (when org-provide-todo-statistics
5486 (org-update-parent-todo-statistics))))
5488 (defun org-insert-subheading (arg)
5489 "Insert a new subheading and demote it.
5490 Works for outline headings and for plain lists alike."
5491 (interactive "P")
5492 (org-insert-heading arg)
5493 (cond
5494 ((org-on-heading-p) (org-do-demote))
5495 ((org-at-item-p) (org-indent-item 1))))
5497 (defun org-insert-todo-subheading (arg)
5498 "Insert a new subheading with TODO keyword or checkbox and demote it.
5499 Works for outline headings and for plain lists alike."
5500 (interactive "P")
5501 (org-insert-todo-heading arg)
5502 (cond
5503 ((org-on-heading-p) (org-do-demote))
5504 ((org-at-item-p) (org-indent-item 1))))
5506 ;;; Promotion and Demotion
5508 (defun org-promote-subtree ()
5509 "Promote the entire subtree.
5510 See also `org-promote'."
5511 (interactive)
5512 (save-excursion
5513 (org-map-tree 'org-promote))
5514 (org-fix-position-after-promote))
5516 (defun org-demote-subtree ()
5517 "Demote the entire subtree. See `org-demote'.
5518 See also `org-promote'."
5519 (interactive)
5520 (save-excursion
5521 (org-map-tree 'org-demote))
5522 (org-fix-position-after-promote))
5525 (defun org-do-promote ()
5526 "Promote the current heading higher up the tree.
5527 If the region is active in `transient-mark-mode', promote all headings
5528 in the region."
5529 (interactive)
5530 (save-excursion
5531 (if (org-region-active-p)
5532 (org-map-region 'org-promote (region-beginning) (region-end))
5533 (org-promote)))
5534 (org-fix-position-after-promote))
5536 (defun org-do-demote ()
5537 "Demote the current heading lower down the tree.
5538 If the region is active in `transient-mark-mode', demote all headings
5539 in the region."
5540 (interactive)
5541 (save-excursion
5542 (if (org-region-active-p)
5543 (org-map-region 'org-demote (region-beginning) (region-end))
5544 (org-demote)))
5545 (org-fix-position-after-promote))
5547 (defun org-fix-position-after-promote ()
5548 "Make sure that after pro/demotion cursor position is right."
5549 (let ((pos (point)))
5550 (when (save-excursion
5551 (beginning-of-line 1)
5552 (looking-at org-todo-line-regexp)
5553 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5554 (cond ((eobp) (insert " "))
5555 ((eolp) (insert " "))
5556 ((equal (char-after) ?\ ) (forward-char 1))))))
5558 (defun org-reduced-level (l)
5559 "Compute the effective level of a heading.
5560 This takes into account the setting of `org-odd-levels-only'."
5561 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5563 (defun org-get-valid-level (level &optional change)
5564 "Rectify a level change under the influence of `org-odd-levels-only'
5565 LEVEL is a current level, CHANGE is by how much the level should be
5566 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5567 even level numbers will become the next higher odd number."
5568 (if org-odd-levels-only
5569 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5570 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5571 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5572 (max 1 (+ level (or change 0)))))
5574 (if (boundp 'define-obsolete-function-alias)
5575 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5576 (define-obsolete-function-alias 'org-get-legal-level
5577 'org-get-valid-level)
5578 (define-obsolete-function-alias 'org-get-legal-level
5579 'org-get-valid-level "23.1")))
5581 (defun org-promote ()
5582 "Promote the current heading higher up the tree.
5583 If the region is active in `transient-mark-mode', promote all headings
5584 in the region."
5585 (org-back-to-heading t)
5586 (let* ((level (save-match-data (funcall outline-level)))
5587 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5588 (diff (abs (- level (length up-head) -1))))
5589 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5590 (replace-match up-head nil t)
5591 ;; Fixup tag positioning
5592 (and org-auto-align-tags (org-set-tags nil t))
5593 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5595 (defun org-demote ()
5596 "Demote the current heading lower down the tree.
5597 If the region is active in `transient-mark-mode', demote all headings
5598 in the region."
5599 (org-back-to-heading t)
5600 (let* ((level (save-match-data (funcall outline-level)))
5601 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5602 (diff (abs (- level (length down-head) -1))))
5603 (replace-match down-head nil t)
5604 ;; Fixup tag positioning
5605 (and org-auto-align-tags (org-set-tags nil t))
5606 (if org-adapt-indentation (org-fixup-indentation diff))))
5608 (defun org-map-tree (fun)
5609 "Call FUN for every heading underneath the current one."
5610 (org-back-to-heading)
5611 (let ((level (funcall outline-level)))
5612 (save-excursion
5613 (funcall fun)
5614 (while (and (progn
5615 (outline-next-heading)
5616 (> (funcall outline-level) level))
5617 (not (eobp)))
5618 (funcall fun)))))
5620 (defun org-map-region (fun beg end)
5621 "Call FUN for every heading between BEG and END."
5622 (let ((org-ignore-region t))
5623 (save-excursion
5624 (setq end (copy-marker end))
5625 (goto-char beg)
5626 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5627 (< (point) end))
5628 (funcall fun))
5629 (while (and (progn
5630 (outline-next-heading)
5631 (< (point) end))
5632 (not (eobp)))
5633 (funcall fun)))))
5635 (defun org-fixup-indentation (diff)
5636 "Change the indentation in the current entry by DIFF
5637 However, if any line in the current entry has no indentation, or if it
5638 would end up with no indentation after the change, nothing at all is done."
5639 (save-excursion
5640 (let ((end (save-excursion (outline-next-heading)
5641 (point-marker)))
5642 (prohibit (if (> diff 0)
5643 "^\\S-"
5644 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5645 col)
5646 (unless (save-excursion (end-of-line 1)
5647 (re-search-forward prohibit end t))
5648 (while (and (< (point) end)
5649 (re-search-forward "^[ \t]+" end t))
5650 (goto-char (match-end 0))
5651 (setq col (current-column))
5652 (if (< diff 0) (replace-match ""))
5653 (org-indent-to-column (+ diff col))))
5654 (move-marker end nil))))
5656 (defun org-convert-to-odd-levels ()
5657 "Convert an org-mode file with all levels allowed to one with odd levels.
5658 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5659 level 5 etc."
5660 (interactive)
5661 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5662 (let ((org-odd-levels-only nil) n)
5663 (save-excursion
5664 (goto-char (point-min))
5665 (while (re-search-forward "^\\*\\*+ " nil t)
5666 (setq n (- (length (match-string 0)) 2))
5667 (while (>= (setq n (1- n)) 0)
5668 (org-demote))
5669 (end-of-line 1))))))
5672 (defun org-convert-to-oddeven-levels ()
5673 "Convert an org-mode file with only odd levels to one with odd and even levels.
5674 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5675 section with an even level, conversion would destroy the structure of the file. An error
5676 is signaled in this case."
5677 (interactive)
5678 (goto-char (point-min))
5679 ;; First check if there are no even levels
5680 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5681 (org-show-context t)
5682 (error "Not all levels are odd in this file. Conversion not possible."))
5683 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5684 (let ((org-odd-levels-only nil) n)
5685 (save-excursion
5686 (goto-char (point-min))
5687 (while (re-search-forward "^\\*\\*+ " nil t)
5688 (setq n (/ (1- (length (match-string 0))) 2))
5689 (while (>= (setq n (1- n)) 0)
5690 (org-promote))
5691 (end-of-line 1))))))
5693 (defun org-tr-level (n)
5694 "Make N odd if required."
5695 (if org-odd-levels-only (1+ (/ n 2)) n))
5697 ;;; Vertical tree motion, cutting and pasting of subtrees
5699 (defun org-move-subtree-up (&optional arg)
5700 "Move the current subtree up past ARG headlines of the same level."
5701 (interactive "p")
5702 (org-move-subtree-down (- (prefix-numeric-value arg))))
5704 (defun org-move-subtree-down (&optional arg)
5705 "Move the current subtree down past ARG headlines of the same level."
5706 (interactive "p")
5707 (setq arg (prefix-numeric-value arg))
5708 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5709 'outline-get-last-sibling))
5710 (ins-point (make-marker))
5711 (cnt (abs arg))
5712 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5713 ;; Select the tree
5714 (org-back-to-heading)
5715 (setq beg0 (point))
5716 (save-excursion
5717 (setq ne-beg (org-back-over-empty-lines))
5718 (setq beg (point)))
5719 (save-match-data
5720 (save-excursion (outline-end-of-heading)
5721 (setq folded (org-invisible-p)))
5722 (outline-end-of-subtree))
5723 (outline-next-heading)
5724 (setq ne-end (org-back-over-empty-lines))
5725 (setq end (point))
5726 (goto-char beg0)
5727 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5728 ;; include less whitespace
5729 (save-excursion
5730 (goto-char beg)
5731 (forward-line (- ne-beg ne-end))
5732 (setq beg (point))))
5733 ;; Find insertion point, with error handling
5734 (while (> cnt 0)
5735 (or (and (funcall movfunc) (looking-at outline-regexp))
5736 (progn (goto-char beg0)
5737 (error "Cannot move past superior level or buffer limit")))
5738 (setq cnt (1- cnt)))
5739 (if (> arg 0)
5740 ;; Moving forward - still need to move over subtree
5741 (progn (org-end-of-subtree t t)
5742 (save-excursion
5743 (org-back-over-empty-lines)
5744 (or (bolp) (newline)))))
5745 (setq ne-ins (org-back-over-empty-lines))
5746 (move-marker ins-point (point))
5747 (setq txt (buffer-substring beg end))
5748 (org-save-markers-in-region beg end)
5749 (delete-region beg end)
5750 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5751 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5752 (and (not (bolp)) (looking-at "\n") (forward-char 1))
5753 (let ((bbb (point)))
5754 (insert-before-markers txt)
5755 (org-reinstall-markers-in-region bbb)
5756 (move-marker ins-point bbb))
5757 (or (bolp) (insert "\n"))
5758 (setq ins-end (point))
5759 (goto-char ins-point)
5760 (org-skip-whitespace)
5761 (when (and (< arg 0)
5762 (org-first-sibling-p)
5763 (> ne-ins ne-beg))
5764 ;; Move whitespace back to beginning
5765 (save-excursion
5766 (goto-char ins-end)
5767 (let ((kill-whole-line t))
5768 (kill-line (- ne-ins ne-beg)) (point)))
5769 (insert (make-string (- ne-ins ne-beg) ?\n)))
5770 (move-marker ins-point nil)
5771 (org-compact-display-after-subtree-move)
5772 (org-show-empty-lines-in-parent)
5773 (unless folded
5774 (org-show-entry)
5775 (show-children)
5776 (org-cycle-hide-drawers 'children))))
5778 (defvar org-subtree-clip ""
5779 "Clipboard for cut and paste of subtrees.
5780 This is actually only a copy of the kill, because we use the normal kill
5781 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5783 (defvar org-subtree-clip-folded nil
5784 "Was the last copied subtree folded?
5785 This is used to fold the tree back after pasting.")
5787 (defun org-cut-subtree (&optional n)
5788 "Cut the current subtree into the clipboard.
5789 With prefix arg N, cut this many sequential subtrees.
5790 This is a short-hand for marking the subtree and then cutting it."
5791 (interactive "p")
5792 (org-copy-subtree n 'cut))
5794 (defun org-copy-subtree (&optional n cut force-store-markers)
5795 "Cut the current subtree into the clipboard.
5796 With prefix arg N, cut this many sequential subtrees.
5797 This is a short-hand for marking the subtree and then copying it.
5798 If CUT is non-nil, actually cut the subtree.
5799 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5800 of some markers in the region, even if CUT is non-nil. This is
5801 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5802 (interactive "p")
5803 (let (beg end folded (beg0 (point)))
5804 (if (interactive-p)
5805 (org-back-to-heading nil) ; take what looks like a subtree
5806 (org-back-to-heading t)) ; take what is really there
5807 (org-back-over-empty-lines)
5808 (setq beg (point))
5809 (skip-chars-forward " \t\r\n")
5810 (save-match-data
5811 (save-excursion (outline-end-of-heading)
5812 (setq folded (org-invisible-p)))
5813 (condition-case nil
5814 (outline-forward-same-level (1- n))
5815 (error nil))
5816 (org-end-of-subtree t t))
5817 (org-back-over-empty-lines)
5818 (setq end (point))
5819 (goto-char beg0)
5820 (when (> end beg)
5821 (setq org-subtree-clip-folded folded)
5822 (when (or cut force-store-markers)
5823 (org-save-markers-in-region beg end))
5824 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5825 (setq org-subtree-clip (current-kill 0))
5826 (message "%s: Subtree(s) with %d characters"
5827 (if cut "Cut" "Copied")
5828 (length org-subtree-clip)))))
5830 (defun org-paste-subtree (&optional level tree for-yank)
5831 "Paste the clipboard as a subtree, with modification of headline level.
5832 The entire subtree is promoted or demoted in order to match a new headline
5833 level.
5835 If the cursor is at the beginning of a headline, the same level as
5836 that headline is used to paste the tree
5838 If not, the new level is derived from the *visible* headings
5839 before and after the insertion point, and taken to be the inferior headline
5840 level of the two. So if the previous visible heading is level 3 and the
5841 next is level 4 (or vice versa), level 4 will be used for insertion.
5842 This makes sure that the subtree remains an independent subtree and does
5843 not swallow low level entries.
5845 You can also force a different level, either by using a numeric prefix
5846 argument, or by inserting the heading marker by hand. For example, if the
5847 cursor is after \"*****\", then the tree will be shifted to level 5.
5849 If optional TREE is given, use this text instead of the kill ring.
5851 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5852 move back over whitespace before inserting, and move point to the end of
5853 the inserted text when done."
5854 (interactive "P")
5855 (unless (org-kill-is-subtree-p tree)
5856 (error "%s"
5857 (substitute-command-keys
5858 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5859 (let* ((visp (not (org-invisible-p)))
5860 (txt (or tree (and kill-ring (current-kill 0))))
5861 (^re (concat "^\\(" outline-regexp "\\)"))
5862 (re (concat "\\(" outline-regexp "\\)"))
5863 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5865 (old-level (if (string-match ^re txt)
5866 (- (match-end 0) (match-beginning 0) 1)
5867 -1))
5868 (force-level (cond (level (prefix-numeric-value level))
5869 ((and (looking-at "[ \t]*$")
5870 (string-match
5871 ^re_ (buffer-substring
5872 (point-at-bol) (point))))
5873 (- (match-end 1) (match-beginning 1)))
5874 ((and (bolp)
5875 (looking-at org-outline-regexp))
5876 (- (match-end 0) (point) 1))
5877 (t nil)))
5878 (previous-level (save-excursion
5879 (condition-case nil
5880 (progn
5881 (outline-previous-visible-heading 1)
5882 (if (looking-at re)
5883 (- (match-end 0) (match-beginning 0) 1)
5885 (error 1))))
5886 (next-level (save-excursion
5887 (condition-case nil
5888 (progn
5889 (or (looking-at outline-regexp)
5890 (outline-next-visible-heading 1))
5891 (if (looking-at re)
5892 (- (match-end 0) (match-beginning 0) 1)
5894 (error 1))))
5895 (new-level (or force-level (max previous-level next-level)))
5896 (shift (if (or (= old-level -1)
5897 (= new-level -1)
5898 (= old-level new-level))
5900 (- new-level old-level)))
5901 (delta (if (> shift 0) -1 1))
5902 (func (if (> shift 0) 'org-demote 'org-promote))
5903 (org-odd-levels-only nil)
5904 beg end newend)
5905 ;; Remove the forced level indicator
5906 (if force-level
5907 (delete-region (point-at-bol) (point)))
5908 ;; Paste
5909 (beginning-of-line 1)
5910 (unless for-yank (org-back-over-empty-lines))
5911 (setq beg (point))
5912 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5913 (insert-before-markers txt)
5914 (unless (string-match "\n\\'" txt) (insert "\n"))
5915 (setq newend (point))
5916 (org-reinstall-markers-in-region beg)
5917 (setq end (point))
5918 (goto-char beg)
5919 (skip-chars-forward " \t\n\r")
5920 (setq beg (point))
5921 (if (and (org-invisible-p) visp)
5922 (save-excursion (outline-show-heading)))
5923 ;; Shift if necessary
5924 (unless (= shift 0)
5925 (save-restriction
5926 (narrow-to-region beg end)
5927 (while (not (= shift 0))
5928 (org-map-region func (point-min) (point-max))
5929 (setq shift (+ delta shift)))
5930 (goto-char (point-min))
5931 (setq newend (point-max))))
5932 (when (or (interactive-p) for-yank)
5933 (message "Clipboard pasted as level %d subtree" new-level))
5934 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5935 kill-ring
5936 (eq org-subtree-clip (current-kill 0))
5937 org-subtree-clip-folded)
5938 ;; The tree was folded before it was killed/copied
5939 (hide-subtree))
5940 (and for-yank (goto-char newend))))
5942 (defun org-kill-is-subtree-p (&optional txt)
5943 "Check if the current kill is an outline subtree, or a set of trees.
5944 Returns nil if kill does not start with a headline, or if the first
5945 headline level is not the largest headline level in the tree.
5946 So this will actually accept several entries of equal levels as well,
5947 which is OK for `org-paste-subtree'.
5948 If optional TXT is given, check this string instead of the current kill."
5949 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5950 (start-level (and kill
5951 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5952 org-outline-regexp "\\)")
5953 kill)
5954 (- (match-end 2) (match-beginning 2) 1)))
5955 (re (concat "^" org-outline-regexp))
5956 (start (1+ (or (match-beginning 2) -1))))
5957 (if (not start-level)
5958 (progn
5959 nil) ;; does not even start with a heading
5960 (catch 'exit
5961 (while (setq start (string-match re kill (1+ start)))
5962 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5963 (throw 'exit nil)))
5964 t))))
5966 (defvar org-markers-to-move nil
5967 "Markers that should be moved with a cut-and-paste operation.
5968 Those markers are stored together with their positions relative to
5969 the start of the region.")
5971 (defun org-save-markers-in-region (beg end)
5972 "Check markers in region.
5973 If these markers are between BEG and END, record their position relative
5974 to BEG, so that after moving the block of text, we can put the markers back
5975 into place.
5976 This function gets called just before an entry or tree gets cut from the
5977 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5978 called immediately, to move the markers with the entries."
5979 (setq org-markers-to-move nil)
5980 (when (featurep 'org-clock)
5981 (org-clock-save-markers-for-cut-and-paste beg end))
5982 (when (featurep 'org-agenda)
5983 (org-agenda-save-markers-for-cut-and-paste beg end)))
5985 (defun org-check-and-save-marker (marker beg end)
5986 "Check if MARKER is between BEG and END.
5987 If yes, remember the marker and the distance to BEG."
5988 (when (and (marker-buffer marker)
5989 (equal (marker-buffer marker) (current-buffer)))
5990 (if (and (>= marker beg) (< marker end))
5991 (push (cons marker (- marker beg)) org-markers-to-move))))
5993 (defun org-reinstall-markers-in-region (beg)
5994 "Move all remembered markers to their position relative to BEG."
5995 (mapc (lambda (x)
5996 (move-marker (car x) (+ beg (cdr x))))
5997 org-markers-to-move)
5998 (setq org-markers-to-move nil))
6000 (defun org-narrow-to-subtree ()
6001 "Narrow buffer to the current subtree."
6002 (interactive)
6003 (save-excursion
6004 (save-match-data
6005 (narrow-to-region
6006 (progn (org-back-to-heading) (point))
6007 (progn (org-end-of-subtree t) (point))))))
6009 (defun org-clone-subtree-with-time-shift (n &optional shift)
6010 "Clone the task (subtree) at point N times.
6011 The clones will be inserted as siblings.
6013 In interactive use, the user will be prompted for the number of clones
6014 to be produced, and for a time SHIFT, which may be a repeater as used
6015 in time stamps, for example `+3d'.
6017 When a valid repeater is given and the entry contains any time stamps,
6018 the clones will become a sequence in time, with time stamps in the
6019 subtree shifted for each clone produced. If SHIFT is nil or the
6020 empty string, time stamps will be left alone.
6022 If the original subtree did contain time stamps with a repeater,
6023 the following will happen:
6024 - the repeater will be removed in each clone
6025 - an additional clone will be produced, with the current, unshifted
6026 date(s) in the entry.
6027 - the original entry will be placed *after* all the clones, with
6028 repeater intact.
6029 - the start days in the repeater in the original entry will be shifted
6030 to past the last clone.
6031 I this way you can spell out a number of instances of a repeating task,
6032 and still retain the repeater to cover future instances of the task."
6033 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6034 (let (beg end template task
6035 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6036 (if (not (and (integerp n) (> n 0)))
6037 (error "Invalid number of replications %s" n))
6038 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6039 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6040 shift)))
6041 (error "Invalid shift specification %s" shift))
6042 (when doshift
6043 (setq shift-n (string-to-number (match-string 1 shift))
6044 shift-what (cdr (assoc (match-string 2 shift)
6045 '(("d" . day) ("w" . week)
6046 ("m" . month) ("y" . year))))))
6047 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6048 (setq nmin 1 nmax n)
6049 (org-back-to-heading t)
6050 (setq beg (point))
6051 (org-end-of-subtree t t)
6052 (setq end (point))
6053 (setq template (buffer-substring beg end))
6054 (when (and doshift
6055 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6056 (delete-region beg end)
6057 (setq end beg)
6058 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6059 (goto-char end)
6060 (loop for n from nmin to nmax do
6061 (if (not doshift)
6062 (setq task template)
6063 (with-temp-buffer
6064 (insert template)
6065 (org-mode)
6066 (goto-char (point-min))
6067 (while (re-search-forward org-ts-regexp nil t)
6068 (org-timestamp-change (* n shift-n) shift-what))
6069 (unless (= n n-no-remove)
6070 (goto-char (point-min))
6071 (while (re-search-forward org-ts-regexp nil t)
6072 (save-excursion
6073 (goto-char (match-beginning 0))
6074 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6075 (delete-region (match-beginning 1) (match-end 1))))))
6076 (setq task (buffer-string))))
6077 (insert task))
6078 (goto-char beg)))
6080 ;;; Outline Sorting
6082 (defun org-sort (with-case)
6083 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6084 Optional argument WITH-CASE means sort case-sensitively.
6085 With a double prefix argument, also remove duplicate entries."
6086 (interactive "P")
6087 (if (org-at-table-p)
6088 (org-call-with-arg 'org-table-sort-lines with-case)
6089 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6091 (defun org-sort-remove-invisible (s)
6092 (remove-text-properties 0 (length s) org-rm-props s)
6093 (while (string-match org-bracket-link-regexp s)
6094 (setq s (replace-match (if (match-end 2)
6095 (match-string 3 s)
6096 (match-string 1 s)) t t s)))
6099 (defvar org-priority-regexp) ; defined later in the file
6101 (defvar org-after-sorting-entries-or-items-hook nil
6102 "Hook that is run after a bunch of entries or items have been sorted.
6103 When children are sorted, the cursor is in the parent line when this
6104 hook gets called. When a region or a plain list is sorted, the cursor
6105 will be in the first entry of the sorted region/list.")
6107 (defun org-sort-entries-or-items
6108 (&optional with-case sorting-type getkey-func compare-func property)
6109 "Sort entries on a certain level of an outline tree, or plain list items.
6110 If there is an active region, the entries in the region are sorted.
6111 Else, if the cursor is before the first entry, sort the top-level items.
6112 Else, the children of the entry at point are sorted.
6113 If the cursor is at the first item in a plain list, the list items will be
6114 sorted.
6116 Sorting can be alphabetically, numerically, by date/time as given by
6117 a time stamp, by a property or by priority.
6119 The command prompts for the sorting type unless it has been given to the
6120 function through the SORTING-TYPE argument, which needs to a character,
6121 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6122 precise meaning of each character:
6124 n Numerically, by converting the beginning of the entry/item to a number.
6125 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6126 t By date/time, either the first active time stamp in the entry, or, if
6127 none exist, by the first inactive one.
6128 In items, only the first line will be chekced.
6129 s By the scheduled date/time.
6130 d By deadline date/time.
6131 c By creation time, which is assumed to be the first inactive time stamp
6132 at the beginning of a line.
6133 p By priority according to the cookie.
6134 r By the value of a property.
6136 Capital letters will reverse the sort order.
6138 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6139 called with point at the beginning of the record. It must return either
6140 a string or a number that should serve as the sorting key for that record.
6142 Comparing entries ignores case by default. However, with an optional argument
6143 WITH-CASE, the sorting considers case as well."
6144 (interactive "P")
6145 (let ((case-func (if with-case 'identity 'downcase))
6146 start beg end stars re re2
6147 txt what tmp plain-list-p)
6148 ;; Find beginning and end of region to sort
6149 (cond
6150 ((org-region-active-p)
6151 ;; we will sort the region
6152 (setq end (region-end)
6153 what "region")
6154 (goto-char (region-beginning))
6155 (if (not (org-on-heading-p)) (outline-next-heading))
6156 (setq start (point)))
6157 ((org-at-item-p)
6158 ;; we will sort this plain list
6159 (org-beginning-of-item-list) (setq start (point))
6160 (org-end-of-item-list) (setq end (point))
6161 (goto-char start)
6162 (setq plain-list-p t
6163 what "plain list"))
6164 ((or (org-on-heading-p)
6165 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6166 ;; we will sort the children of the current headline
6167 (org-back-to-heading)
6168 (setq start (point)
6169 end (progn (org-end-of-subtree t t)
6170 (org-back-over-empty-lines)
6171 (point))
6172 what "children")
6173 (goto-char start)
6174 (show-subtree)
6175 (outline-next-heading))
6177 ;; we will sort the top-level entries in this file
6178 (goto-char (point-min))
6179 (or (org-on-heading-p) (outline-next-heading))
6180 (setq start (point) end (point-max) what "top-level")
6181 (goto-char start)
6182 (show-all)))
6184 (setq beg (point))
6185 (if (>= beg end) (error "Nothing to sort"))
6187 (unless plain-list-p
6188 (looking-at "\\(\\*+\\)")
6189 (setq stars (match-string 1)
6190 re (concat "^" (regexp-quote stars) " +")
6191 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6192 txt (buffer-substring beg end))
6193 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6194 (if (and (not (equal stars "*")) (string-match re2 txt))
6195 (error "Region to sort contains a level above the first entry")))
6197 (unless sorting-type
6198 (message
6199 (if plain-list-p
6200 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6201 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
6202 [t]ime [s ]cheduled [d]eadline [c]reated
6203 A/N/T/S/D/C/P/O/F means reversed:")
6204 what)
6205 (setq sorting-type (read-char-exclusive))
6207 (and (= (downcase sorting-type) ?f)
6208 (setq getkey-func
6209 (org-ido-completing-read "Sort using function: "
6210 obarray 'fboundp t nil nil))
6211 (setq getkey-func (intern getkey-func)))
6213 (and (= (downcase sorting-type) ?r)
6214 (setq property
6215 (org-ido-completing-read "Property: "
6216 (mapcar 'list (org-buffer-property-keys t))
6217 nil t))))
6219 (message "Sorting entries...")
6221 (save-restriction
6222 (narrow-to-region start end)
6224 (let ((dcst (downcase sorting-type))
6225 (case-fold-search nil)
6226 (now (current-time)))
6227 (sort-subr
6228 (/= dcst sorting-type)
6229 ;; This function moves to the beginning character of the "record" to
6230 ;; be sorted.
6231 (if plain-list-p
6232 (lambda nil
6233 (if (org-at-item-p) t (goto-char (point-max))))
6234 (lambda nil
6235 (if (re-search-forward re nil t)
6236 (goto-char (match-beginning 0))
6237 (goto-char (point-max)))))
6238 ;; This function moves to the last character of the "record" being
6239 ;; sorted.
6240 (if plain-list-p
6241 'org-end-of-item
6242 (lambda nil
6243 (save-match-data
6244 (condition-case nil
6245 (outline-forward-same-level 1)
6246 (error
6247 (goto-char (point-max)))))))
6249 ;; This function returns the value that gets sorted against.
6250 (if plain-list-p
6251 (lambda nil
6252 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6253 (cond
6254 ((= dcst ?n)
6255 (string-to-number (buffer-substring (match-end 0)
6256 (point-at-eol))))
6257 ((= dcst ?a)
6258 (buffer-substring (match-end 0) (point-at-eol)))
6259 ((= dcst ?t)
6260 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
6261 (re-search-forward org-ts-regexp-both
6262 (point-at-eol) t))
6263 (time-to-seconds
6264 (org-time-string-to-time (match-string 0)))
6265 (time-to-seconds now)))
6266 ((= dcst ?f)
6267 (if getkey-func
6268 (progn
6269 (setq tmp (funcall getkey-func))
6270 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6271 tmp)
6272 (error "Invalid key function `%s'" getkey-func)))
6273 (t (error "Invalid sorting type `%c'" sorting-type)))))
6274 (lambda nil
6275 (cond
6276 ((= dcst ?n)
6277 (if (looking-at org-complex-heading-regexp)
6278 (string-to-number (match-string 4))
6279 nil))
6280 ((= dcst ?a)
6281 (if (looking-at org-complex-heading-regexp)
6282 (funcall case-func (match-string 4))
6283 nil))
6284 ((= dcst ?t)
6285 (let ((end (save-excursion (outline-next-heading) (point))))
6286 (if (or (re-search-forward org-ts-regexp end t)
6287 (re-search-forward org-ts-regexp-both end t))
6288 (org-time-string-to-time (match-string 0))
6289 (org-time-string-to-time now))))
6290 ((= dcst ?c)
6291 (let ((end (save-excursion (outline-next-heading) (point))))
6292 (if (re-search-forward
6293 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
6294 end t)
6295 (time-to-seconds (org-time-string-to-time
6296 (match-string 0)))
6297 (time-to-seconds now))))
6298 ((= dcst ?s)
6299 (let ((end (save-excursion (outline-next-heading) (point))))
6300 (if (re-search-forward org-scheduled-time-regexp end t)
6301 (org-time-string-to-time (match-string 1))
6302 (org-time-string-to-time now))))
6303 ((= dcst ?d)
6304 (let ((end (save-excursion (outline-next-heading) (point))))
6305 (if (re-search-forward org-deadline-time-regexp end t)
6306 (org-time-string-to-time (match-string 1))
6307 (org-time-string-to-time now))))
6308 ((= dcst ?p)
6309 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6310 (string-to-char (match-string 2))
6311 org-default-priority))
6312 ((= dcst ?r)
6313 (or (org-entry-get nil property) ""))
6314 ((= dcst ?o)
6315 (if (looking-at org-complex-heading-regexp)
6316 (- 9999 (length (member (match-string 2)
6317 org-todo-keywords-1)))))
6318 ((= dcst ?f)
6319 (if getkey-func
6320 (progn
6321 (setq tmp (funcall getkey-func))
6322 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6323 tmp)
6324 (error "Invalid key function `%s'" getkey-func)))
6325 (t (error "Invalid sorting type `%c'" sorting-type)))))
6327 (cond
6328 ((= dcst ?a) 'string<)
6329 ((= dcst ?t) 'time-less-p)
6330 ((= dcst ?f) compare-func)
6331 ((= dcst ?p) '<)
6332 (t nil)))))
6333 (run-hooks 'org-after-sorting-entries-or-items-hook)
6334 (message "Sorting entries...done")))
6336 (defun org-do-sort (table what &optional with-case sorting-type)
6337 "Sort TABLE of WHAT according to SORTING-TYPE.
6338 The user will be prompted for the SORTING-TYPE if the call to this
6339 function does not specify it. WHAT is only for the prompt, to indicate
6340 what is being sorted. The sorting key will be extracted from
6341 the car of the elements of the table.
6342 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6343 (unless sorting-type
6344 (message
6345 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6346 what)
6347 (setq sorting-type (read-char-exclusive)))
6348 (let ((dcst (downcase sorting-type))
6349 extractfun comparefun)
6350 ;; Define the appropriate functions
6351 (cond
6352 ((= dcst ?n)
6353 (setq extractfun 'string-to-number
6354 comparefun (if (= dcst sorting-type) '< '>)))
6355 ((= dcst ?a)
6356 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6357 (lambda(x) (downcase (org-sort-remove-invisible x))))
6358 comparefun (if (= dcst sorting-type)
6359 'string<
6360 (lambda (a b) (and (not (string< a b))
6361 (not (string= a b)))))))
6362 ((= dcst ?t)
6363 (setq extractfun
6364 (lambda (x)
6365 (if (or (string-match org-ts-regexp x)
6366 (string-match org-ts-regexp-both x))
6367 (time-to-seconds
6368 (org-time-string-to-time (match-string 0 x)))
6370 comparefun (if (= dcst sorting-type) '< '>)))
6371 (t (error "Invalid sorting type `%c'" sorting-type)))
6373 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6374 table)
6375 (lambda (a b) (funcall comparefun (car a) (car b))))))
6377 ;;; Editing source examples
6379 (defvar org-exit-edit-mode-map (make-sparse-keymap))
6380 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
6381 (defvar org-edit-src-force-single-line nil)
6382 (defvar org-edit-src-from-org-mode nil)
6383 (defvar org-edit-src-picture nil)
6384 (defvar org-edit-src-beg-marker nil)
6385 (defvar org-edit-src-end-marker nil)
6387 (define-minor-mode org-exit-edit-mode
6388 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
6390 (defun org-edit-src-code ()
6391 "Edit the source code example at point.
6392 The example is copied to a separate buffer, and that buffer is switched
6393 to the correct language mode. When done, exit with \\[org-edit-src-exit].
6394 This will remove the original code in the Org buffer, and replace it with
6395 the edited version."
6396 (interactive)
6397 (let ((line (org-current-line))
6398 (case-fold-search t)
6399 (msg (substitute-command-keys
6400 "Edit, then exit with C-c ' (C-c and single quote)"))
6401 (info (org-edit-src-find-region-and-lang))
6402 (org-mode-p (eq major-mode 'org-mode))
6403 (beg (make-marker))
6404 (end (make-marker))
6405 ovl lang lang-f single lfmt code begline buffer)
6406 (if (not info)
6408 (setq beg (move-marker beg (nth 0 info))
6409 end (move-marker end (nth 1 info))
6410 code (buffer-substring-no-properties beg end)
6411 lang (nth 2 info)
6412 single (nth 3 info)
6413 lfmt (nth 4 info)
6414 lang-f (intern (concat lang "-mode"))
6415 begline (save-excursion (goto-char beg) (org-current-line)))
6416 (unless (functionp lang-f)
6417 (error "No such language mode: %s" lang-f))
6418 (goto-line line)
6419 (if (and (setq buffer (org-edit-src-find-buffer beg end))
6420 (y-or-n-p "Return to existing edit buffer? [n] will revert changes: "))
6421 (switch-to-buffer buffer)
6422 (when buffer
6423 (with-current-buffer buffer
6424 (if (boundp 'org-edit-src-overlay)
6425 (org-delete-overlay org-edit-src-overlay)))
6426 (kill-buffer buffer))
6427 (setq buffer (generate-new-buffer "*Org Edit Src Example*"))
6428 (setq ovl (org-make-overlay beg end))
6429 (org-overlay-put ovl 'face 'secondary-selection)
6430 (org-overlay-put ovl 'edit-buffer buffer)
6431 (org-overlay-put ovl 'help-echo "Click with mouse-1 to switch to buffer editing this segment")
6432 (org-overlay-put ovl 'face 'secondary-selection)
6433 (org-overlay-put ovl
6434 'keymap
6435 (let ((map (make-sparse-keymap)))
6436 (define-key map [mouse-1] 'org-edit-src-continue)
6437 map))
6438 (org-overlay-put ovl :read-only "Leave me alone")
6439 (switch-to-buffer buffer)
6440 (insert code)
6441 (remove-text-properties (point-min) (point-max)
6442 '(display nil invisible nil intangible nil))
6443 (let ((org-inhibit-startup t))
6444 (funcall lang-f))
6445 (set (make-local-variable 'org-edit-src-force-single-line) single)
6446 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6447 (when lfmt
6448 (set (make-local-variable 'org-coderef-label-format) lfmt))
6449 (when org-mode-p
6450 (goto-char (point-min))
6451 (while (re-search-forward "^," nil t)
6452 (replace-match "")))
6453 (goto-line (1+ (- line begline)))
6454 (org-exit-edit-mode)
6455 (org-set-local 'org-edit-src-beg-marker beg)
6456 (org-set-local 'org-edit-src-end-marker end)
6457 (org-set-local 'org-edit-src-overlay ovl)
6458 (and org-edit-src-persistent-message
6459 (org-set-local 'header-line-format msg)))
6460 (message "%s" msg)
6461 t)))
6463 (defun org-edit-src-continue (e)
6464 (interactive "e")
6465 (mouse-set-point e)
6466 (let ((buf (get-char-property (point) 'edit-buffer)))
6467 (if buf (switch-to-buffer buf)
6468 (error "Something is wrong here"))))
6470 (defun org-edit-src-find-buffer (beg end)
6471 "Find a source editing buffer that is already editing the region BEG to END."
6472 (catch 'exit
6473 (mapc
6474 (lambda (b)
6475 (with-current-buffer b
6476 (if (and (string-match "\\`*Org Edit " (buffer-name))
6477 (local-variable-p 'org-edit-src-beg-marker (current-buffer))
6478 (local-variable-p 'org-edit-src-end-marker (current-buffer))
6479 (equal beg org-edit-src-beg-marker)
6480 (equal end org-edit-src-end-marker))
6481 (throw 'exit (current-buffer)))))
6482 (buffer-list))
6483 nil))
6485 (defun org-edit-fixed-width-region ()
6486 "Edit the fixed-width ascii drawing at point.
6487 This must be a region where each line starts with a colon followed by
6488 a space character.
6489 An new buffer is created and the fixed-width region is copied into it,
6490 and the buffer is switched into `artist-mode' for editing. When done,
6491 exit with \\[org-edit-src-exit]. The edited text will then replace
6492 the fragment in the Org-mode buffer."
6493 (interactive)
6494 (let ((line (org-current-line))
6495 (case-fold-search t)
6496 (msg (substitute-command-keys
6497 "Edit, then exit with C-c ' (C-c and single quote)"))
6498 (org-mode-p (eq major-mode 'org-mode))
6499 (beg (make-marker))
6500 (end (make-marker))
6501 ovl beg1 end1 code begline buffer)
6502 (beginning-of-line 1)
6503 (if (looking-at "[ \t]*[^:\n \t]")
6505 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
6506 (setq beg1 (point) end1 beg1)
6507 (save-excursion
6508 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
6509 (setq beg1 (point-at-bol 2))
6510 (setq beg1 (point))))
6511 (save-excursion
6512 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
6513 (setq end1 (1- (match-beginning 0)))
6514 (setq end1 (point))))
6515 (goto-line line))
6516 (setq beg (move-marker beg beg1)
6517 end (move-marker end end1)
6518 code (buffer-substring-no-properties beg end)
6519 begline (save-excursion (goto-char beg) (org-current-line)))
6520 (if (and (setq buffer (org-edit-src-find-buffer beg end))
6521 (y-or-n-p "Return to existing edit buffer? [n] will revert changes: "))
6522 (switch-to-buffer buffer)
6523 (when buffer
6524 (with-current-buffer buffer
6525 (if (boundp 'org-edit-src-overlay)
6526 (org-delete-overlay org-edit-src-overlay)))
6527 (kill-buffer buffer))
6528 (setq buffer (generate-new-buffer "*Org Edit Src Example*"))
6529 (setq ovl (org-make-overlay beg end))
6530 (org-overlay-put ovl 'face 'secondary-selection)
6531 (org-overlay-put ovl 'edit-buffer buffer)
6532 (org-overlay-put ovl 'help-echo "Click with mouse-1 to switch to buffer editing this segment")
6533 (org-overlay-put ovl 'face 'secondary-selection)
6534 (org-overlay-put ovl
6535 'keymap
6536 (let ((map (make-sparse-keymap)))
6537 (define-key map [mouse-1] 'org-edit-src-continue)
6538 map))
6539 (org-overlay-put ovl :read-only "Leave me alone")
6540 (switch-to-buffer buffer)
6541 (insert code)
6542 (remove-text-properties (point-min) (point-max)
6543 '(display nil invisible nil intangible nil))
6544 (cond
6545 ((eq org-edit-fixed-width-region-mode 'artist-mode)
6546 (fundamental-mode)
6547 (artist-mode 1))
6548 (t (funcall org-edit-fixed-width-region-mode)))
6549 (set (make-local-variable 'org-edit-src-force-single-line) nil)
6550 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6551 (set (make-local-variable 'org-edit-src-picture) t)
6552 (goto-char (point-min))
6553 (while (re-search-forward "^[ \t]*: ?" nil t)
6554 (replace-match ""))
6555 (goto-line (1+ (- line begline)))
6556 (org-exit-edit-mode)
6557 (org-set-local 'org-edit-src-beg-marker beg)
6558 (org-set-local 'org-edit-src-end-marker end)
6559 (org-set-local 'org-edit-src-overlay ovl)
6560 (and org-edit-src-persistent-message
6561 (org-set-local 'header-line-format msg)))
6562 (message "%s" msg)
6563 t)))
6565 (defun org-edit-src-find-region-and-lang ()
6566 "Find the region and language for a local edit.
6567 Return a list with beginning and end of the region, a string representing
6568 the language, a switch telling of the content should be in a single line."
6569 (let ((re-list
6570 (append
6571 org-edit-src-region-extra
6573 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
6574 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
6575 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
6576 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
6577 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
6578 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
6579 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
6580 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
6581 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
6582 ("^#\\+html:" "\n" "html" single-line)
6583 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
6584 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
6585 ("^#\\+latex:" "\n" "latex" single-line)
6586 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
6587 ("^#\\+ascii:" "\n" "ascii" single-line)
6589 (pos (point))
6590 re1 re2 single beg end lang lfmt match-re1)
6591 (catch 'exit
6592 (while (setq entry (pop re-list))
6593 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
6594 single (nth 3 entry))
6595 (save-excursion
6596 (if (or (looking-at re1)
6597 (re-search-backward re1 nil t))
6598 (progn
6599 (setq match-re1 (match-string 0))
6600 (setq beg (match-end 0)
6601 lang (org-edit-src-get-lang lang)
6602 lfmt (org-edit-src-get-label-format match-re1))
6603 (if (and (re-search-forward re2 nil t)
6604 (>= (match-end 0) pos))
6605 (throw 'exit (list beg (match-beginning 0)
6606 lang single lfmt))))
6607 (if (or (looking-at re2)
6608 (re-search-forward re2 nil t))
6609 (progn
6610 (setq end (match-beginning 0))
6611 (if (and (re-search-backward re1 nil t)
6612 (<= (match-beginning 0) pos))
6613 (progn
6614 (setq lfmt (org-edit-src-get-label-format
6615 (match-string 0)))
6616 (throw 'exit
6617 (list (match-end 0) end
6618 (org-edit-src-get-lang lang)
6619 single lfmt))))))))))))
6621 (defun org-edit-src-get-lang (lang)
6622 "Extract the src language."
6623 (let ((m (match-string 0)))
6624 (cond
6625 ((stringp lang) lang)
6626 ((integerp lang) (match-string lang))
6627 ((and (eq lang 'lang)
6628 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
6629 (match-string 1 m))
6630 ((and (eq lang 'style)
6631 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
6632 (match-string 1 m))
6633 (t "fundamental"))))
6635 (defun org-edit-src-get-label-format (s)
6636 "Extract the label format."
6637 (save-match-data
6638 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
6639 (match-string 1 s))))
6641 (defun org-edit-src-exit ()
6642 "Exit special edit and protect problematic lines."
6643 (interactive)
6644 (unless (string-match "\\`*Org Edit " (buffer-name (current-buffer)))
6645 (error "This is not an sub-editing buffer, something is wrong..."))
6646 (let ((line (if (org-bound-and-true-p org-edit-src-force-single-line)
6648 (org-current-line)))
6649 (beg org-edit-src-beg-marker)
6650 (end org-edit-src-end-marker)
6651 (ovl org-edit-src-overlay)
6652 (buffer (current-buffer))
6653 code)
6654 (goto-char (point-min))
6655 (if (looking-at "[ \t\n]*\n") (replace-match ""))
6656 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
6657 (when (org-bound-and-true-p org-edit-src-force-single-line)
6658 (goto-char (point-min))
6659 (while (re-search-forward "\n" nil t)
6660 (replace-match " "))
6661 (goto-char (point-min))
6662 (if (looking-at "\\s-*") (replace-match " "))
6663 (if (re-search-forward "\\s-+\\'" nil t)
6664 (replace-match "")))
6665 (when (org-bound-and-true-p org-edit-src-from-org-mode)
6666 (goto-char (point-min))
6667 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
6668 (replace-match ",\\1"))
6669 (when font-lock-mode
6670 (font-lock-unfontify-region (point-min) (point-max)))
6671 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6672 (when (org-bound-and-true-p org-edit-src-picture)
6673 (untabify (point-min) (point-max))
6674 (goto-char (point-min))
6675 (while (re-search-forward "^" nil t)
6676 (replace-match ": "))
6677 (when font-lock-mode
6678 (font-lock-unfontify-region (point-min) (point-max)))
6679 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6680 (setq code (buffer-string))
6681 (switch-to-buffer (marker-buffer beg))
6682 (kill-buffer buffer)
6683 (goto-char beg)
6684 (org-delete-overlay ovl)
6685 (delete-region beg end)
6686 (insert code)
6687 (goto-char beg)
6688 (goto-line (1- (+ (org-current-line) line)))
6689 (move-marker beg nil)
6690 (move-marker end nil)))
6693 ;;; The orgstruct minor mode
6695 ;; Define a minor mode which can be used in other modes in order to
6696 ;; integrate the org-mode structure editing commands.
6698 ;; This is really a hack, because the org-mode structure commands use
6699 ;; keys which normally belong to the major mode. Here is how it
6700 ;; works: The minor mode defines all the keys necessary to operate the
6701 ;; structure commands, but wraps the commands into a function which
6702 ;; tests if the cursor is currently at a headline or a plain list
6703 ;; item. If that is the case, the structure command is used,
6704 ;; temporarily setting many Org-mode variables like regular
6705 ;; expressions for filling etc. However, when any of those keys is
6706 ;; used at a different location, function uses `key-binding' to look
6707 ;; up if the key has an associated command in another currently active
6708 ;; keymap (minor modes, major mode, global), and executes that
6709 ;; command. There might be problems if any of the keys is otherwise
6710 ;; used as a prefix key.
6712 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6713 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6714 ;; addresses this by checking explicitly for both bindings.
6716 (defvar orgstruct-mode-map (make-sparse-keymap)
6717 "Keymap for the minor `orgstruct-mode'.")
6719 (defvar org-local-vars nil
6720 "List of local variables, for use by `orgstruct-mode'")
6722 ;;;###autoload
6723 (define-minor-mode orgstruct-mode
6724 "Toggle the minor more `orgstruct-mode'.
6725 This mode is for using Org-mode structure commands in other modes.
6726 The following key behave as if Org-mode was active, if the cursor
6727 is on a headline, or on a plain list item (both in the definition
6728 of Org-mode).
6730 M-up Move entry/item up
6731 M-down Move entry/item down
6732 M-left Promote
6733 M-right Demote
6734 M-S-up Move entry/item up
6735 M-S-down Move entry/item down
6736 M-S-left Promote subtree
6737 M-S-right Demote subtree
6738 M-q Fill paragraph and items like in Org-mode
6739 C-c ^ Sort entries
6740 C-c - Cycle list bullet
6741 TAB Cycle item visibility
6742 M-RET Insert new heading/item
6743 S-M-RET Insert new TODO heading / Checkbox item
6744 C-c C-c Set tags / toggle checkbox"
6745 nil " OrgStruct" nil
6746 (org-load-modules-maybe)
6747 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6749 ;;;###autoload
6750 (defun turn-on-orgstruct ()
6751 "Unconditionally turn on `orgstruct-mode'."
6752 (orgstruct-mode 1))
6754 (defun orgstruct++-mode (&optional arg)
6755 "Toggle `orgstruct-mode', the enhanced version of it.
6756 In addition to setting orgstruct-mode, this also exports all indentation and
6757 autofilling variables from org-mode into the buffer. It will also
6758 recognize item context in multiline items.
6759 Note that turning off orgstruct-mode will *not* remove the
6760 indentation/paragraph settings. This can only be done by refreshing the
6761 major mode, for example with \[normal-mode]."
6762 (interactive "P")
6763 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6764 (if (< arg 1)
6765 (orgstruct-mode -1)
6766 (orgstruct-mode 1)
6767 (let (var val)
6768 (mapc
6769 (lambda (x)
6770 (when (string-match
6771 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6772 (symbol-name (car x)))
6773 (setq var (car x) val (nth 1 x))
6774 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6775 org-local-vars)
6776 (org-set-local 'orgstruct-is-++ t))))
6778 (defvar orgstruct-is-++ nil
6779 "Is orgstruct-mode in ++ version in the current-buffer?")
6780 (make-variable-buffer-local 'orgstruct-is-++)
6782 ;;;###autoload
6783 (defun turn-on-orgstruct++ ()
6784 "Unconditionally turn on `orgstruct++-mode'."
6785 (orgstruct++-mode 1))
6787 (defun orgstruct-error ()
6788 "Error when there is no default binding for a structure key."
6789 (interactive)
6790 (error "This key has no function outside structure elements"))
6792 (defun orgstruct-setup ()
6793 "Setup orgstruct keymaps."
6794 (let ((nfunc 0)
6795 (bindings
6796 (list
6797 '([(meta up)] org-metaup)
6798 '([(meta down)] org-metadown)
6799 '([(meta left)] org-metaleft)
6800 '([(meta right)] org-metaright)
6801 '([(meta shift up)] org-shiftmetaup)
6802 '([(meta shift down)] org-shiftmetadown)
6803 '([(meta shift left)] org-shiftmetaleft)
6804 '([(meta shift right)] org-shiftmetaright)
6805 '([(shift up)] org-shiftup)
6806 '([(shift down)] org-shiftdown)
6807 '([(shift left)] org-shiftleft)
6808 '([(shift right)] org-shiftright)
6809 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6810 '("\M-q" fill-paragraph)
6811 '("\C-c^" org-sort)
6812 '("\C-c-" org-cycle-list-bullet)))
6813 elt key fun cmd)
6814 (while (setq elt (pop bindings))
6815 (setq nfunc (1+ nfunc))
6816 (setq key (org-key (car elt))
6817 fun (nth 1 elt)
6818 cmd (orgstruct-make-binding fun nfunc key))
6819 (org-defkey orgstruct-mode-map key cmd))
6821 ;; Special treatment needed for TAB and RET
6822 (org-defkey orgstruct-mode-map [(tab)]
6823 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6824 (org-defkey orgstruct-mode-map "\C-i"
6825 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6827 (org-defkey orgstruct-mode-map "\M-\C-m"
6828 (orgstruct-make-binding 'org-insert-heading 105
6829 "\M-\C-m" [(meta return)]))
6830 (org-defkey orgstruct-mode-map [(meta return)]
6831 (orgstruct-make-binding 'org-insert-heading 106
6832 [(meta return)] "\M-\C-m"))
6834 (org-defkey orgstruct-mode-map [(shift meta return)]
6835 (orgstruct-make-binding 'org-insert-todo-heading 107
6836 [(meta return)] "\M-\C-m"))
6838 (unless org-local-vars
6839 (setq org-local-vars (org-get-local-variables)))
6843 (defun orgstruct-make-binding (fun n &rest keys)
6844 "Create a function for binding in the structure minor mode.
6845 FUN is the command to call inside a table. N is used to create a unique
6846 command name. KEYS are keys that should be checked in for a command
6847 to execute outside of tables."
6848 (eval
6849 (list 'defun
6850 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6851 '(arg)
6852 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6853 "Outside of structure, run the binding of `"
6854 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6855 "'.")
6856 '(interactive "p")
6857 (list 'if
6858 `(org-context-p 'headline 'item
6859 (and orgstruct-is-++
6860 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
6861 'item-body))
6862 (list 'org-run-like-in-org-mode (list 'quote fun))
6863 (list 'let '(orgstruct-mode)
6864 (list 'call-interactively
6865 (append '(or)
6866 (mapcar (lambda (k)
6867 (list 'key-binding k))
6868 keys)
6869 '('orgstruct-error))))))))
6871 (defun org-context-p (&rest contexts)
6872 "Check if local context is any of CONTEXTS.
6873 Possible values in the list of contexts are `table', `headline', and `item'."
6874 (let ((pos (point)))
6875 (goto-char (point-at-bol))
6876 (prog1 (or (and (memq 'table contexts)
6877 (looking-at "[ \t]*|"))
6878 (and (memq 'headline contexts)
6879 ;;????????? (looking-at "\\*+"))
6880 (looking-at outline-regexp))
6881 (and (memq 'item contexts)
6882 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
6883 (and (memq 'item-body contexts)
6884 (org-in-item-p)))
6885 (goto-char pos))))
6887 (defun org-get-local-variables ()
6888 "Return a list of all local variables in an org-mode buffer."
6889 (let (varlist)
6890 (with-current-buffer (get-buffer-create "*Org tmp*")
6891 (erase-buffer)
6892 (org-mode)
6893 (setq varlist (buffer-local-variables)))
6894 (kill-buffer "*Org tmp*")
6895 (delq nil
6896 (mapcar
6897 (lambda (x)
6898 (setq x
6899 (if (symbolp x)
6900 (list x)
6901 (list (car x) (list 'quote (cdr x)))))
6902 (if (string-match
6903 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6904 (symbol-name (car x)))
6905 x nil))
6906 varlist))))
6908 ;;;###autoload
6909 (defun org-run-like-in-org-mode (cmd)
6910 "Run a command, pretending that the current buffer is in Org-mode.
6911 This will temporarily bind local variables that are typically bound in
6912 Org-mode to the values they have in Org-mode, and then interactively
6913 call CMD."
6914 (org-load-modules-maybe)
6915 (unless org-local-vars
6916 (setq org-local-vars (org-get-local-variables)))
6917 (eval (list 'let org-local-vars
6918 (list 'call-interactively (list 'quote cmd)))))
6920 ;;;; Archiving
6922 (defun org-get-category (&optional pos)
6923 "Get the category applying to position POS."
6924 (get-text-property (or pos (point)) 'org-category))
6926 (defun org-refresh-category-properties ()
6927 "Refresh category text properties in the buffer."
6928 (let ((def-cat (cond
6929 ((null org-category)
6930 (if buffer-file-name
6931 (file-name-sans-extension
6932 (file-name-nondirectory buffer-file-name))
6933 "???"))
6934 ((symbolp org-category) (symbol-name org-category))
6935 (t org-category)))
6936 beg end cat pos optionp)
6937 (org-unmodified
6938 (save-excursion
6939 (save-restriction
6940 (widen)
6941 (goto-char (point-min))
6942 (put-text-property (point) (point-max) 'org-category def-cat)
6943 (while (re-search-forward
6944 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6945 (setq pos (match-end 0)
6946 optionp (equal (char-after (match-beginning 0)) ?#)
6947 cat (org-trim (match-string 2)))
6948 (if optionp
6949 (setq beg (point-at-bol) end (point-max))
6950 (org-back-to-heading t)
6951 (setq beg (point) end (org-end-of-subtree t t)))
6952 (put-text-property beg end 'org-category cat)
6953 (goto-char pos)))))))
6956 ;;;; Link Stuff
6958 ;;; Link abbreviations
6960 (defun org-link-expand-abbrev (link)
6961 "Apply replacements as defined in `org-link-abbrev-alist."
6962 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6963 (let* ((key (match-string 1 link))
6964 (as (or (assoc key org-link-abbrev-alist-local)
6965 (assoc key org-link-abbrev-alist)))
6966 (tag (and (match-end 2) (match-string 3 link)))
6967 rpl)
6968 (if (not as)
6969 link
6970 (setq rpl (cdr as))
6971 (cond
6972 ((symbolp rpl) (funcall rpl tag))
6973 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6974 ((string-match "%h" rpl)
6975 (replace-match (url-hexify-string (or tag "")) t t rpl))
6976 (t (concat rpl tag)))))
6977 link))
6979 ;;; Storing and inserting links
6981 (defvar org-insert-link-history nil
6982 "Minibuffer history for links inserted with `org-insert-link'.")
6984 (defvar org-stored-links nil
6985 "Contains the links stored with `org-store-link'.")
6987 (defvar org-store-link-plist nil
6988 "Plist with info about the most recently link created with `org-store-link'.")
6990 (defvar org-link-protocols nil
6991 "Link protocols added to Org-mode using `org-add-link-type'.")
6993 (defvar org-store-link-functions nil
6994 "List of functions that are called to create and store a link.
6995 Each function will be called in turn until one returns a non-nil
6996 value. Each function should check if it is responsible for creating
6997 this link (for example by looking at the major mode).
6998 If not, it must exit and return nil.
6999 If yes, it should return a non-nil value after a calling
7000 `org-store-link-props' with a list of properties and values.
7001 Special properties are:
7003 :type The link prefix. like \"http\". This must be given.
7004 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7005 This is obligatory as well.
7006 :description Optional default description for the second pair
7007 of brackets in an Org-mode link. The user can still change
7008 this when inserting this link into an Org-mode buffer.
7010 In addition to these, any additional properties can be specified
7011 and then used in remember templates.")
7013 (defun org-add-link-type (type &optional follow export)
7014 "Add TYPE to the list of `org-link-types'.
7015 Re-compute all regular expressions depending on `org-link-types'
7017 FOLLOW and EXPORT are two functions.
7019 FOLLOW should take the link path as the single argument and do whatever
7020 is necessary to follow the link, for example find a file or display
7021 a mail message.
7023 EXPORT should format the link path for export to one of the export formats.
7024 It should be a function accepting three arguments:
7026 path the path of the link, the text after the prefix (like \"http:\")
7027 desc the description of the link, if any, nil if there was no description
7028 format the export format, a symbol like `html' or `latex'.
7030 The function may use the FORMAT information to return different values
7031 depending on the format. The return value will be put literally into
7032 the exported file.
7033 Org-mode has a built-in default for exporting links. If you are happy with
7034 this default, there is no need to define an export function for the link
7035 type. For a simple example of an export function, see `org-bbdb.el'."
7036 (add-to-list 'org-link-types type t)
7037 (org-make-link-regexps)
7038 (if (assoc type org-link-protocols)
7039 (setcdr (assoc type org-link-protocols) (list follow export))
7040 (push (list type follow export) org-link-protocols)))
7042 ;;;###autoload
7043 (defun org-store-link (arg)
7044 "\\<org-mode-map>Store an org-link to the current location.
7045 This link is added to `org-stored-links' and can later be inserted
7046 into an org-buffer with \\[org-insert-link].
7048 For some link types, a prefix arg is interpreted:
7049 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7050 For file links, arg negates `org-context-in-file-links'."
7051 (interactive "P")
7052 (org-load-modules-maybe)
7053 (setq org-store-link-plist nil) ; reset
7054 (let (link cpltxt desc description search txt custom-id)
7055 (cond
7057 ((run-hook-with-args-until-success 'org-store-link-functions)
7058 (setq link (plist-get org-store-link-plist :link)
7059 desc (or (plist-get org-store-link-plist :description) link)))
7061 ((equal (buffer-name) "*Org Edit Src Example*")
7062 (let (label gc)
7063 (while (or (not label)
7064 (save-excursion
7065 (save-restriction
7066 (widen)
7067 (goto-char (point-min))
7068 (re-search-forward
7069 (regexp-quote (format org-coderef-label-format label))
7070 nil t))))
7071 (when label (message "Label exists already") (sit-for 2))
7072 (setq label (read-string "Code line label: " label)))
7073 (end-of-line 1)
7074 (setq link (format org-coderef-label-format label))
7075 (setq gc (- 79 (length link)))
7076 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7077 (insert link)
7078 (setq link (concat "(" label ")") desc nil)))
7080 ((eq major-mode 'calendar-mode)
7081 (let ((cd (calendar-cursor-to-date)))
7082 (setq link
7083 (format-time-string
7084 (car org-time-stamp-formats)
7085 (apply 'encode-time
7086 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7087 nil nil nil))))
7088 (org-store-link-props :type "calendar" :date cd)))
7090 ((eq major-mode 'w3-mode)
7091 (setq cpltxt (if (and (buffer-name)
7092 (not (string-match "Untitled" (buffer-name))))
7093 (buffer-name)
7094 (url-view-url t))
7095 link (org-make-link (url-view-url t)))
7096 (org-store-link-props :type "w3" :url (url-view-url t)))
7098 ((eq major-mode 'w3m-mode)
7099 (setq cpltxt (or w3m-current-title w3m-current-url)
7100 link (org-make-link w3m-current-url))
7101 (org-store-link-props :type "w3m" :url (url-view-url t)))
7103 ((setq search (run-hook-with-args-until-success
7104 'org-create-file-search-functions))
7105 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7106 "::" search))
7107 (setq cpltxt (or description link)))
7109 ((eq major-mode 'image-mode)
7110 (setq cpltxt (concat "file:"
7111 (abbreviate-file-name buffer-file-name))
7112 link (org-make-link cpltxt))
7113 (org-store-link-props :type "image" :file buffer-file-name))
7115 ((eq major-mode 'dired-mode)
7116 ;; link to the file in the current line
7117 (setq cpltxt (concat "file:"
7118 (abbreviate-file-name
7119 (expand-file-name
7120 (dired-get-filename nil t))))
7121 link (org-make-link cpltxt)))
7123 ((and buffer-file-name (org-mode-p))
7124 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7125 (cond
7126 ((org-in-regexp "<<\\(.*?\\)>>")
7127 (setq cpltxt
7128 (concat "file:"
7129 (abbreviate-file-name buffer-file-name)
7130 "::" (match-string 1))
7131 link (org-make-link cpltxt)))
7132 ((and (featurep 'org-id)
7133 (or (eq org-link-to-org-use-id t)
7134 (and (eq org-link-to-org-use-id 'create-if-interactive)
7135 (interactive-p))
7136 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7137 (interactive-p)
7138 (not custom-id))
7139 (and org-link-to-org-use-id
7140 (condition-case nil
7141 (org-entry-get nil "ID")
7142 (error nil)))))
7143 ;; We can make a link using the ID.
7144 (setq link (condition-case nil
7145 (prog1 (org-id-store-link)
7146 (setq desc (plist-get org-store-link-plist
7147 :description)))
7148 (error
7149 ;; probably before first headline, link to file only
7150 (concat "file:"
7151 (abbreviate-file-name buffer-file-name))))))
7153 ;; Just link to current headline
7154 (setq cpltxt (concat "file:"
7155 (abbreviate-file-name buffer-file-name)))
7156 ;; Add a context search string
7157 (when (org-xor org-context-in-file-links arg)
7158 (setq txt (cond
7159 ((org-on-heading-p) nil)
7160 ((org-region-active-p)
7161 (buffer-substring (region-beginning) (region-end)))
7162 (t nil)))
7163 (when (or (null txt) (string-match "\\S-" txt))
7164 (setq cpltxt
7165 (concat cpltxt "::"
7166 (condition-case nil
7167 (org-make-org-heading-search-string txt)
7168 (error "")))
7169 desc "NONE")))
7170 (if (string-match "::\\'" cpltxt)
7171 (setq cpltxt (substring cpltxt 0 -2)))
7172 (setq link (org-make-link cpltxt)))))
7174 ((buffer-file-name (buffer-base-buffer))
7175 ;; Just link to this file here.
7176 (setq cpltxt (concat "file:"
7177 (abbreviate-file-name
7178 (buffer-file-name (buffer-base-buffer)))))
7179 ;; Add a context string
7180 (when (org-xor org-context-in-file-links arg)
7181 (setq txt (if (org-region-active-p)
7182 (buffer-substring (region-beginning) (region-end))
7183 (buffer-substring (point-at-bol) (point-at-eol))))
7184 ;; Only use search option if there is some text.
7185 (when (string-match "\\S-" txt)
7186 (setq cpltxt
7187 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7188 desc "NONE")))
7189 (setq link (org-make-link cpltxt)))
7191 ((interactive-p)
7192 (error "Cannot link to a buffer which is not visiting a file"))
7194 (t (setq link nil)))
7196 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7197 (setq link (or link cpltxt)
7198 desc (or desc cpltxt))
7199 (if (equal desc "NONE") (setq desc nil))
7201 (if (and (interactive-p) link)
7202 (progn
7203 (setq org-stored-links
7204 (cons (list link desc) org-stored-links))
7205 (message "Stored: %s" (or desc link))
7206 (when custom-id
7207 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7208 "::#" custom-id))
7209 (setq org-stored-links
7210 (cons (list link desc) org-stored-links))))
7211 (and link (org-make-link-string link desc)))))
7213 (defun org-store-link-props (&rest plist)
7214 "Store link properties, extract names and addresses."
7215 (let (x adr)
7216 (when (setq x (plist-get plist :from))
7217 (setq adr (mail-extract-address-components x))
7218 (setq plist (plist-put plist :fromname (car adr)))
7219 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7220 (when (setq x (plist-get plist :to))
7221 (setq adr (mail-extract-address-components x))
7222 (setq plist (plist-put plist :toname (car adr)))
7223 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7224 (let ((from (plist-get plist :from))
7225 (to (plist-get plist :to)))
7226 (when (and from to org-from-is-user-regexp)
7227 (setq plist
7228 (plist-put plist :fromto
7229 (if (string-match org-from-is-user-regexp from)
7230 (concat "to %t")
7231 (concat "from %f"))))))
7232 (setq org-store-link-plist plist))
7234 (defun org-add-link-props (&rest plist)
7235 "Add these properties to the link property list."
7236 (let (key value)
7237 (while plist
7238 (setq key (pop plist) value (pop plist))
7239 (setq org-store-link-plist
7240 (plist-put org-store-link-plist key value)))))
7242 (defun org-email-link-description (&optional fmt)
7243 "Return the description part of an email link.
7244 This takes information from `org-store-link-plist' and formats it
7245 according to FMT (default from `org-email-link-description-format')."
7246 (setq fmt (or fmt org-email-link-description-format))
7247 (let* ((p org-store-link-plist)
7248 (to (plist-get p :toaddress))
7249 (from (plist-get p :fromaddress))
7250 (table
7251 (list
7252 (cons "%c" (plist-get p :fromto))
7253 (cons "%F" (plist-get p :from))
7254 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7255 (cons "%T" (plist-get p :to))
7256 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7257 (cons "%s" (plist-get p :subject))
7258 (cons "%m" (plist-get p :message-id)))))
7259 (when (string-match "%c" fmt)
7260 ;; Check if the user wrote this message
7261 (if (and org-from-is-user-regexp from to
7262 (save-match-data (string-match org-from-is-user-regexp from)))
7263 (setq fmt (replace-match "to %t" t t fmt))
7264 (setq fmt (replace-match "from %f" t t fmt))))
7265 (org-replace-escapes fmt table)))
7267 (defun org-make-org-heading-search-string (&optional string heading)
7268 "Make search string for STRING or current headline."
7269 (interactive)
7270 (let ((s (or string (org-get-heading))))
7271 (unless (and string (not heading))
7272 ;; We are using a headline, clean up garbage in there.
7273 (if (string-match org-todo-regexp s)
7274 (setq s (replace-match "" t t s)))
7275 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7276 (setq s (replace-match "" t t s)))
7277 (setq s (org-trim s))
7278 (if (string-match (concat "^\\(" org-quote-string "\\|"
7279 org-comment-string "\\)") s)
7280 (setq s (replace-match "" t t s)))
7281 (while (string-match org-ts-regexp s)
7282 (setq s (replace-match "" t t s))))
7283 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7284 (setq s (replace-match " " t t s)))
7285 (or string (setq s (concat "*" s))) ; Add * for headlines
7286 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7288 (defun org-make-link (&rest strings)
7289 "Concatenate STRINGS."
7290 (apply 'concat strings))
7292 (defun org-make-link-string (link &optional description)
7293 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7294 (unless (string-match "\\S-" link)
7295 (error "Empty link"))
7296 (when (stringp description)
7297 ;; Remove brackets from the description, they are fatal.
7298 (while (string-match "\\[" description)
7299 (setq description (replace-match "{" t t description)))
7300 (while (string-match "\\]" description)
7301 (setq description (replace-match "}" t t description))))
7302 (when (equal (org-link-escape link) description)
7303 ;; No description needed, it is identical
7304 (setq description nil))
7305 (when (and (not description)
7306 (not (equal link (org-link-escape link))))
7307 (setq description (org-extract-attributes link)))
7308 (concat "[[" (org-link-escape link) "]"
7309 (if description (concat "[" description "]") "")
7310 "]"))
7312 (defconst org-link-escape-chars
7313 '((?\ . "%20")
7314 (?\[ . "%5B")
7315 (?\] . "%5D")
7316 (?\340 . "%E0") ; `a
7317 (?\342 . "%E2") ; ^a
7318 (?\347 . "%E7") ; ,c
7319 (?\350 . "%E8") ; `e
7320 (?\351 . "%E9") ; 'e
7321 (?\352 . "%EA") ; ^e
7322 (?\356 . "%EE") ; ^i
7323 (?\364 . "%F4") ; ^o
7324 (?\371 . "%F9") ; `u
7325 (?\373 . "%FB") ; ^u
7326 (?\; . "%3B")
7327 (?? . "%3F")
7328 (?= . "%3D")
7329 (?+ . "%2B")
7331 "Association list of escapes for some characters problematic in links.
7332 This is the list that is used for internal purposes.")
7334 (defvar org-url-encoding-use-url-hexify nil)
7336 (defconst org-link-escape-chars-browser
7337 '((?\ . "%20")) ; 32 for the SPC char
7338 "Association list of escapes for some characters problematic in links.
7339 This is the list that is used before handing over to the browser.")
7341 (defun org-link-escape (text &optional table)
7342 "Escape characters in TEXT that are problematic for links."
7343 (if org-url-encoding-use-url-hexify
7344 (url-hexify-string text)
7345 (setq table (or table org-link-escape-chars))
7346 (when text
7347 (let ((re (mapconcat (lambda (x) (regexp-quote
7348 (char-to-string (car x))))
7349 table "\\|")))
7350 (while (string-match re text)
7351 (setq text
7352 (replace-match
7353 (cdr (assoc (string-to-char (match-string 0 text))
7354 table))
7355 t t text)))
7356 text))))
7358 (defun org-link-unescape (text &optional table)
7359 "Reverse the action of `org-link-escape'."
7360 (if org-url-encoding-use-url-hexify
7361 (url-unhex-string text)
7362 (setq table (or table org-link-escape-chars))
7363 (when text
7364 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7365 table "\\|")))
7366 (while (string-match re text)
7367 (setq text
7368 (replace-match
7369 (char-to-string (car (rassoc (match-string 0 text) table)))
7370 t t text)))
7371 text))))
7373 (defun org-xor (a b)
7374 "Exclusive or."
7375 (if a (not b) b))
7377 (defun org-fixup-message-id-for-http (s)
7378 "Replace special characters in a message id, so it can be used in an http query."
7379 (while (string-match "<" s)
7380 (setq s (replace-match "%3C" t t s)))
7381 (while (string-match ">" s)
7382 (setq s (replace-match "%3E" t t s)))
7383 (while (string-match "@" s)
7384 (setq s (replace-match "%40" t t s)))
7387 ;;;###autoload
7388 (defun org-insert-link-global ()
7389 "Insert a link like Org-mode does.
7390 This command can be called in any mode to insert a link in Org-mode syntax."
7391 (interactive)
7392 (org-load-modules-maybe)
7393 (org-run-like-in-org-mode 'org-insert-link))
7395 (defun org-insert-link (&optional complete-file link-location)
7396 "Insert a link. At the prompt, enter the link.
7398 Completion can be used to insert any of the link protocol prefixes like
7399 http or ftp in use.
7401 The history can be used to select a link previously stored with
7402 `org-store-link'. When the empty string is entered (i.e. if you just
7403 press RET at the prompt), the link defaults to the most recently
7404 stored link. As SPC triggers completion in the minibuffer, you need to
7405 use M-SPC or C-q SPC to force the insertion of a space character.
7407 You will also be prompted for a description, and if one is given, it will
7408 be displayed in the buffer instead of the link.
7410 If there is already a link at point, this command will allow you to edit link
7411 and description parts.
7413 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7414 be selected using completion. The path to the file will be relative to the
7415 current directory if the file is in the current directory or a subdirectory.
7416 Otherwise, the link will be the absolute path as completed in the minibuffer
7417 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7418 option `org-link-file-path-type'.
7420 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7421 the current directory or below.
7423 With three \\[universal-argument] prefixes, negate the meaning of
7424 `org-keep-stored-link-after-insertion'.
7426 If `org-make-link-description-function' is non-nil, this function will be
7427 called with the link target, and the result will be the default
7428 link description.
7430 If the LINK-LOCATION parameter is non-nil, this value will be
7431 used as the link location instead of reading one interactively."
7432 (interactive "P")
7433 (let* ((wcf (current-window-configuration))
7434 (region (if (org-region-active-p)
7435 (buffer-substring (region-beginning) (region-end))))
7436 (remove (and region (list (region-beginning) (region-end))))
7437 (desc region)
7438 tmphist ; byte-compile incorrectly complains about this
7439 (link link-location)
7440 entry file all-prefixes)
7441 (cond
7442 (link-location) ; specified by arg, just use it.
7443 ((org-in-regexp org-bracket-link-regexp 1)
7444 ;; We do have a link at point, and we are going to edit it.
7445 (setq remove (list (match-beginning 0) (match-end 0)))
7446 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7447 (setq link (read-string "Link: "
7448 (org-link-unescape
7449 (org-match-string-no-properties 1)))))
7450 ((or (org-in-regexp org-angle-link-re)
7451 (org-in-regexp org-plain-link-re))
7452 ;; Convert to bracket link
7453 (setq remove (list (match-beginning 0) (match-end 0))
7454 link (read-string "Link: "
7455 (org-remove-angle-brackets (match-string 0)))))
7456 ((member complete-file '((4) (16)))
7457 ;; Completing read for file names.
7458 (setq link (org-file-complete-link complete-file)))
7460 ;; Read link, with completion for stored links.
7461 (with-output-to-temp-buffer "*Org Links*"
7462 (princ "Insert a link.
7463 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
7464 (when org-stored-links
7465 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7466 (princ (mapconcat
7467 (lambda (x)
7468 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7469 (reverse org-stored-links) "\n"))))
7470 (let ((cw (selected-window)))
7471 (select-window (get-buffer-window "*Org Links*"))
7472 (setq truncate-lines t)
7473 (unless (pos-visible-in-window-p (point-max))
7474 (org-fit-window-to-buffer))
7475 (and (window-live-p cw) (select-window cw)))
7476 ;; Fake a link history, containing the stored links.
7477 (setq tmphist (append (mapcar 'car org-stored-links)
7478 org-insert-link-history))
7479 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
7480 (mapcar 'car org-link-abbrev-alist)
7481 org-link-types))
7482 (unwind-protect
7483 (progn
7484 (setq link
7485 (let ((org-completion-use-ido nil))
7486 (org-completing-read
7487 "Link: "
7488 (mapcar (lambda (x) (list (concat x ":")))
7489 all-prefixes)
7490 nil nil nil
7491 'tmphist
7492 (or (car (car org-stored-links))))))
7493 (if (or (member link all-prefixes)
7494 (and (equal ":" (substring link -1))
7495 (member (substring link 0 -1) all-prefixes)
7496 (setq link (substring link 0 -1))))
7497 (setq link (org-link-try-special-completion link))))
7498 (set-window-configuration wcf)
7499 (kill-buffer "*Org Links*"))
7500 (setq entry (assoc link org-stored-links))
7501 (or entry (push link org-insert-link-history))
7502 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7503 (not org-keep-stored-link-after-insertion))
7504 (setq org-stored-links (delq (assoc link org-stored-links)
7505 org-stored-links)))
7506 (setq desc (or desc (nth 1 entry)))))
7508 (if (string-match org-plain-link-re link)
7509 ;; URL-like link, normalize the use of angular brackets.
7510 (setq link (org-make-link (org-remove-angle-brackets link))))
7512 ;; Check if we are linking to the current file with a search option
7513 ;; If yes, simplify the link by using only the search option.
7514 (when (and buffer-file-name
7515 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7516 (let* ((path (match-string 1 link))
7517 (case-fold-search nil)
7518 (search (match-string 2 link)))
7519 (save-match-data
7520 (if (equal (file-truename buffer-file-name) (file-truename path))
7521 ;; We are linking to this same file, with a search option
7522 (setq link search)))))
7524 ;; Check if we can/should use a relative path. If yes, simplify the link
7525 (when (string-match "^file:\\(.*\\)" link)
7526 (let* ((path (match-string 1 link))
7527 (origpath path)
7528 (case-fold-search nil))
7529 (cond
7530 ((or (eq org-link-file-path-type 'absolute)
7531 (equal complete-file '(16)))
7532 (setq path (abbreviate-file-name (expand-file-name path))))
7533 ((eq org-link-file-path-type 'noabbrev)
7534 (setq path (expand-file-name path)))
7535 ((eq org-link-file-path-type 'relative)
7536 (setq path (file-relative-name path)))
7538 (save-match-data
7539 (if (string-match (concat "^" (regexp-quote
7540 (file-name-as-directory
7541 (expand-file-name "."))))
7542 (expand-file-name path))
7543 ;; We are linking a file with relative path name.
7544 (setq path (substring (expand-file-name path)
7545 (match-end 0)))
7546 (setq path (abbreviate-file-name (expand-file-name path)))))))
7547 (setq link (concat "file:" path))
7548 (if (equal desc origpath)
7549 (setq desc path))))
7551 (if org-make-link-description-function
7552 (setq desc (funcall org-make-link-description-function link desc)))
7554 (setq desc (read-string "Description: " desc))
7555 (unless (string-match "\\S-" desc) (setq desc nil))
7556 (if remove (apply 'delete-region remove))
7557 (insert (org-make-link-string link desc))))
7559 (defun org-link-try-special-completion (type)
7560 "If there is completion support for link type TAPE, offer it."
7561 (let ((fun (intern (concat "org-" type "-complete-link"))))
7562 (if (functionp fun)
7563 (funcall fun)
7564 (read-string "Link (no completion support): " (concat type ":")))))
7566 (defun org-file-complete-link (&optional arg)
7567 "Create a file link using completion."
7568 (let (file link)
7569 (setq file (read-file-name "File: "))
7570 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7571 (pwd1 (file-name-as-directory (abbreviate-file-name
7572 (expand-file-name ".")))))
7573 (cond
7574 ((equal arg '(16))
7575 (setq link (org-make-link
7576 "file:"
7577 (abbreviate-file-name (expand-file-name file)))))
7578 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7579 (setq link (org-make-link "file:" (match-string 1 file))))
7580 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7581 (expand-file-name file))
7582 (setq link (org-make-link
7583 "file:" (match-string 1 (expand-file-name file)))))
7584 (t (setq link (org-make-link "file:" file)))))
7585 link))
7587 (defun org-completing-read (&rest args)
7588 "Completing-read with SPACE being a normal character."
7589 (let ((minibuffer-local-completion-map
7590 (copy-keymap minibuffer-local-completion-map)))
7591 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7592 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7593 (apply 'org-ido-completing-read args)))
7595 (defun org-completing-read-no-ido (&rest args)
7596 (let (org-completion-use-ido)
7597 (apply 'org-completing-read args)))
7599 (defun org-ido-completing-read (&rest args)
7600 "Completing-read using `ido-mode' speedups if available"
7601 (if (and org-completion-use-ido
7602 (fboundp 'ido-completing-read)
7603 (boundp 'ido-mode) ido-mode
7604 (listp (second args)))
7605 (let ((ido-enter-matching-directory nil))
7606 (apply 'ido-completing-read (concat (car args))
7607 (mapcar (lambda (x) (car x)) (nth 1 args))
7608 (cddr args)))
7609 (apply 'completing-read args)))
7611 (defun org-extract-attributes (s)
7612 "Extract the attributes cookie from a string and set as text property."
7613 (let (a attr (start 0) key value)
7614 (save-match-data
7615 (when (string-match "{{\\([^}]+\\)}}$" s)
7616 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7617 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7618 (setq key (match-string 1 a) value (match-string 2 a)
7619 start (match-end 0)
7620 attr (plist-put attr (intern key) value))))
7621 (org-add-props s nil 'org-attr attr))
7624 (defun org-extract-attributes-from-string (tag)
7625 (let (key value attr)
7626 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
7627 (setq key (match-string 1 tag) value (match-string 2 tag)
7628 tag (replace-match "" t t tag)
7629 attr (plist-put attr (intern key) value)))
7630 (cons tag attr)))
7632 (defun org-attributes-to-string (plist)
7633 "Format a property list into an HTML attribute list."
7634 (let ((s "") key value)
7635 (while plist
7636 (setq key (pop plist) value (pop plist))
7637 (and value
7638 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7641 ;;; Opening/following a link
7643 (defvar org-link-search-failed nil)
7645 (defun org-next-link ()
7646 "Move forward to the next link.
7647 If the link is in hidden text, expose it."
7648 (interactive)
7649 (when (and org-link-search-failed (eq this-command last-command))
7650 (goto-char (point-min))
7651 (message "Link search wrapped back to beginning of buffer"))
7652 (setq org-link-search-failed nil)
7653 (let* ((pos (point))
7654 (ct (org-context))
7655 (a (assoc :link ct)))
7656 (if a (goto-char (nth 2 a)))
7657 (if (re-search-forward org-any-link-re nil t)
7658 (progn
7659 (goto-char (match-beginning 0))
7660 (if (org-invisible-p) (org-show-context)))
7661 (goto-char pos)
7662 (setq org-link-search-failed t)
7663 (error "No further link found"))))
7665 (defun org-previous-link ()
7666 "Move backward to the previous link.
7667 If the link is in hidden text, expose it."
7668 (interactive)
7669 (when (and org-link-search-failed (eq this-command last-command))
7670 (goto-char (point-max))
7671 (message "Link search wrapped back to end of buffer"))
7672 (setq org-link-search-failed nil)
7673 (let* ((pos (point))
7674 (ct (org-context))
7675 (a (assoc :link ct)))
7676 (if a (goto-char (nth 1 a)))
7677 (if (re-search-backward org-any-link-re nil t)
7678 (progn
7679 (goto-char (match-beginning 0))
7680 (if (org-invisible-p) (org-show-context)))
7681 (goto-char pos)
7682 (setq org-link-search-failed t)
7683 (error "No further link found"))))
7685 (defun org-translate-link (s)
7686 "Translate a link string if a translation function has been defined."
7687 (if (and org-link-translation-function
7688 (fboundp org-link-translation-function)
7689 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7690 (progn
7691 (setq s (funcall org-link-translation-function
7692 (match-string 1) (match-string 2)))
7693 (concat (car s) ":" (cdr s)))
7696 (defun org-translate-link-from-planner (type path)
7697 "Translate a link from Emacs Planner syntax so that Org can follow it.
7698 This is still an experimental function, your mileage may vary."
7699 (cond
7700 ((member type '("http" "https" "news" "ftp"))
7701 ;; standard Internet links are the same.
7702 nil)
7703 ((and (equal type "irc") (string-match "^//" path))
7704 ;; Planner has two / at the beginning of an irc link, we have 1.
7705 ;; We should have zero, actually....
7706 (setq path (substring path 1)))
7707 ((and (equal type "lisp") (string-match "^/" path))
7708 ;; Planner has a slash, we do not.
7709 (setq type "elisp" path (substring path 1)))
7710 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7711 ;; A typical message link. Planner has the id after the fina slash,
7712 ;; we separate it with a hash mark
7713 (setq path (concat (match-string 1 path) "#"
7714 (org-remove-angle-brackets (match-string 2 path)))))
7716 (cons type path))
7718 (defun org-find-file-at-mouse (ev)
7719 "Open file link or URL at mouse."
7720 (interactive "e")
7721 (mouse-set-point ev)
7722 (org-open-at-point 'in-emacs))
7724 (defun org-open-at-mouse (ev)
7725 "Open file link or URL at mouse."
7726 (interactive "e")
7727 (mouse-set-point ev)
7728 (if (eq major-mode 'org-agenda-mode)
7729 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7730 (org-open-at-point))
7732 (defvar org-window-config-before-follow-link nil
7733 "The window configuration before following a link.
7734 This is saved in case the need arises to restore it.")
7736 (defvar org-open-link-marker (make-marker)
7737 "Marker pointing to the location where `org-open-at-point; was called.")
7739 ;;;###autoload
7740 (defun org-open-at-point-global ()
7741 "Follow a link like Org-mode does.
7742 This command can be called in any mode to follow a link that has
7743 Org-mode syntax."
7744 (interactive)
7745 (org-run-like-in-org-mode 'org-open-at-point))
7747 ;;;###autoload
7748 (defun org-open-link-from-string (s &optional arg)
7749 "Open a link in the string S, as if it was in Org-mode."
7750 (interactive "sLink: \nP")
7751 (let ((reference-buffer (current-buffer)))
7752 (with-temp-buffer
7753 (let ((org-inhibit-startup t))
7754 (org-mode)
7755 (insert s)
7756 (goto-char (point-min))
7757 (org-open-at-point arg reference-buffer)))))
7759 (defun org-open-at-point (&optional in-emacs reference-buffer)
7760 "Open link at or after point.
7761 If there is no link at point, this function will search forward up to
7762 the end of the current line.
7763 Normally, files will be opened by an appropriate application. If the
7764 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7765 With a double prefix argument, try to open outside of Emacs, in the
7766 application the system uses for this file type."
7767 (interactive "P")
7768 (org-load-modules-maybe)
7769 (move-marker org-open-link-marker (point))
7770 (setq org-window-config-before-follow-link (current-window-configuration))
7771 (org-remove-occur-highlights nil nil t)
7772 (cond
7773 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7774 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7775 (org-footnote-action))
7777 (let (type path link line search (pos (point)))
7778 (catch 'match
7779 (save-excursion
7780 (skip-chars-forward "^]\n\r")
7781 (when (org-in-regexp org-bracket-link-regexp)
7782 (setq link (org-extract-attributes
7783 (org-link-unescape (org-match-string-no-properties 1))))
7784 (while (string-match " *\n *" link)
7785 (setq link (replace-match " " t t link)))
7786 (setq link (org-link-expand-abbrev link))
7787 (cond
7788 ((or (file-name-absolute-p link)
7789 (string-match "^\\.\\.?/" link))
7790 (setq type "file" path link))
7791 ((string-match org-link-re-with-space3 link)
7792 (setq type (match-string 1 link) path (match-string 2 link)))
7793 (t (setq type "thisfile" path link)))
7794 (throw 'match t)))
7796 (when (get-text-property (point) 'org-linked-text)
7797 (setq type "thisfile"
7798 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7799 (1+ (point)) (point))
7800 path (buffer-substring
7801 (previous-single-property-change pos 'org-linked-text)
7802 (next-single-property-change pos 'org-linked-text)))
7803 (throw 'match t))
7805 (save-excursion
7806 (when (or (org-in-regexp org-angle-link-re)
7807 (org-in-regexp org-plain-link-re))
7808 (setq type (match-string 1) path (match-string 2))
7809 (throw 'match t)))
7810 (save-excursion
7811 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7812 (setq type "tags"
7813 path (match-string 1))
7814 (while (string-match ":" path)
7815 (setq path (replace-match "+" t t path)))
7816 (throw 'match t)))
7817 (when (org-in-regexp "<\\([^><\n]+\\)>")
7818 (setq type "tree-match"
7819 path (match-string 1))
7820 (throw 'match t)))
7821 (unless path
7822 (error "No link found"))
7824 ;; switch back to reference buffer
7825 ;; needed when if called in a temporary buffer through
7826 ;; org-open-link-from-string
7827 (and reference-buffer (switch-to-buffer reference-buffer))
7829 ;; Remove any trailing spaces in path
7830 (if (string-match " +\\'" path)
7831 (setq path (replace-match "" t t path)))
7832 (if (and org-link-translation-function
7833 (fboundp org-link-translation-function))
7834 ;; Check if we need to translate the link
7835 (let ((tmp (funcall org-link-translation-function type path)))
7836 (setq type (car tmp) path (cdr tmp))))
7838 (cond
7840 ((assoc type org-link-protocols)
7841 (funcall (nth 1 (assoc type org-link-protocols)) path))
7843 ((equal type "mailto")
7844 (let ((cmd (car org-link-mailto-program))
7845 (args (cdr org-link-mailto-program)) args1
7846 (address path) (subject "") a)
7847 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7848 (setq address (match-string 1 path)
7849 subject (org-link-escape (match-string 2 path))))
7850 (while args
7851 (cond
7852 ((not (stringp (car args))) (push (pop args) args1))
7853 (t (setq a (pop args))
7854 (if (string-match "%a" a)
7855 (setq a (replace-match address t t a)))
7856 (if (string-match "%s" a)
7857 (setq a (replace-match subject t t a)))
7858 (push a args1))))
7859 (apply cmd (nreverse args1))))
7861 ((member type '("http" "https" "ftp" "news"))
7862 (browse-url (concat type ":" (org-link-escape
7863 path org-link-escape-chars-browser))))
7865 ((member type '("message"))
7866 (browse-url (concat type ":" path)))
7868 ((string= type "tags")
7869 (org-tags-view in-emacs path))
7870 ((string= type "thisfile")
7871 (if in-emacs
7872 (switch-to-buffer-other-window
7873 (org-get-buffer-for-internal-link (current-buffer)))
7874 (org-mark-ring-push))
7875 (let ((cmd `(org-link-search
7876 ,path
7877 ,(cond ((equal in-emacs '(4)) 'occur)
7878 ((equal in-emacs '(16)) 'org-occur)
7879 (t nil))
7880 ,pos)))
7881 (condition-case nil (eval cmd)
7882 (error (progn (widen) (eval cmd))))))
7884 ((string= type "tree-match")
7885 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7887 ((string= type "file")
7888 (if (string-match "::\\([0-9]+\\)\\'" path)
7889 (setq line (string-to-number (match-string 1 path))
7890 path (substring path 0 (match-beginning 0)))
7891 (if (string-match "::\\(.+\\)\\'" path)
7892 (setq search (match-string 1 path)
7893 path (substring path 0 (match-beginning 0)))))
7894 (if (string-match "[*?{]" (file-name-nondirectory path))
7895 (dired path)
7896 (org-open-file path in-emacs line search)))
7898 ((string= type "news")
7899 (require 'org-gnus)
7900 (org-gnus-follow-link path))
7902 ((string= type "shell")
7903 (let ((cmd path))
7904 (if (or (not org-confirm-shell-link-function)
7905 (funcall org-confirm-shell-link-function
7906 (format "Execute \"%s\" in shell? "
7907 (org-add-props cmd nil
7908 'face 'org-warning))))
7909 (progn
7910 (message "Executing %s" cmd)
7911 (shell-command cmd))
7912 (error "Abort"))))
7914 ((string= type "elisp")
7915 (let ((cmd path))
7916 (if (or (not org-confirm-elisp-link-function)
7917 (funcall org-confirm-elisp-link-function
7918 (format "Execute \"%s\" as elisp? "
7919 (org-add-props cmd nil
7920 'face 'org-warning))))
7921 (message "%s => %s" cmd
7922 (if (equal (string-to-char cmd) ?\()
7923 (eval (read cmd))
7924 (call-interactively (read cmd))))
7925 (error "Abort"))))
7928 (browse-url-at-point))))))
7929 (move-marker org-open-link-marker nil)
7930 (run-hook-with-args 'org-follow-link-hook))
7932 ;;;; Time estimates
7934 (defun org-get-effort (&optional pom)
7935 "Get the effort estimate for the current entry."
7936 (org-entry-get pom org-effort-property))
7938 ;;; File search
7940 (defvar org-create-file-search-functions nil
7941 "List of functions to construct the right search string for a file link.
7942 These functions are called in turn with point at the location to
7943 which the link should point.
7945 A function in the hook should first test if it would like to
7946 handle this file type, for example by checking the major-mode or
7947 the file extension. If it decides not to handle this file, it
7948 should just return nil to give other functions a chance. If it
7949 does handle the file, it must return the search string to be used
7950 when following the link. The search string will be part of the
7951 file link, given after a double colon, and `org-open-at-point'
7952 will automatically search for it. If special measures must be
7953 taken to make the search successful, another function should be
7954 added to the companion hook `org-execute-file-search-functions',
7955 which see.
7957 A function in this hook may also use `setq' to set the variable
7958 `description' to provide a suggestion for the descriptive text to
7959 be used for this link when it gets inserted into an Org-mode
7960 buffer with \\[org-insert-link].")
7962 (defvar org-execute-file-search-functions nil
7963 "List of functions to execute a file search triggered by a link.
7965 Functions added to this hook must accept a single argument, the
7966 search string that was part of the file link, the part after the
7967 double colon. The function must first check if it would like to
7968 handle this search, for example by checking the major-mode or the
7969 file extension. If it decides not to handle this search, it
7970 should just return nil to give other functions a chance. If it
7971 does handle the search, it must return a non-nil value to keep
7972 other functions from trying.
7974 Each function can access the current prefix argument through the
7975 variable `current-prefix-argument'. Note that a single prefix is
7976 used to force opening a link in Emacs, so it may be good to only
7977 use a numeric or double prefix to guide the search function.
7979 In case this is needed, a function in this hook can also restore
7980 the window configuration before `org-open-at-point' was called using:
7982 (set-window-configuration org-window-config-before-follow-link)")
7984 (defun org-link-search (s &optional type avoid-pos)
7985 "Search for a link search option.
7986 If S is surrounded by forward slashes, it is interpreted as a
7987 regular expression. In org-mode files, this will create an `org-occur'
7988 sparse tree. In ordinary files, `occur' will be used to list matches.
7989 If the current buffer is in `dired-mode', grep will be used to search
7990 in all files. If AVOID-POS is given, ignore matches near that position."
7991 (let ((case-fold-search t)
7992 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7993 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7994 (append '(("") (" ") ("\t") ("\n"))
7995 org-emphasis-alist)
7996 "\\|") "\\)"))
7997 (pos (point))
7998 (pre nil) (post nil)
7999 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8000 (cond
8001 ;; First check if there are any special
8002 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8003 ;; Now try the builtin stuff
8004 ((and (equal (string-to-char s0) ?#)
8005 (> (length s0) 1)
8006 (save-excursion
8007 (goto-char (point-min))
8008 (and
8009 (re-search-forward
8010 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8011 (setq type 'dedicated
8012 pos (match-beginning 0))))
8013 ;; There is an exact target for this
8014 (goto-char pos)
8015 (org-back-to-heading t)))
8016 ((save-excursion
8017 (goto-char (point-min))
8018 (and
8019 (re-search-forward
8020 (concat "<<" (regexp-quote s0) ">>") nil t)
8021 (setq type 'dedicated
8022 pos (match-beginning 0))))
8023 ;; There is an exact target for this
8024 (goto-char pos))
8025 ((and (string-match "^(\\(.*\\))$" s0)
8026 (save-excursion
8027 (goto-char (point-min))
8028 (and
8029 (re-search-forward
8030 (concat "[^[]" (regexp-quote
8031 (format org-coderef-label-format
8032 (match-string 1 s0))))
8033 nil t)
8034 (setq type 'dedicated
8035 pos (1+ (match-beginning 0))))))
8036 ;; There is a coderef target for this
8037 (goto-char pos))
8038 ((string-match "^/\\(.*\\)/$" s)
8039 ;; A regular expression
8040 (cond
8041 ((org-mode-p)
8042 (org-occur (match-string 1 s)))
8043 ;;((eq major-mode 'dired-mode)
8044 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8045 (t (org-do-occur (match-string 1 s)))))
8047 ;; A normal search strings
8048 (when (equal (string-to-char s) ?*)
8049 ;; Anchor on headlines, post may include tags.
8050 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8051 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8052 s (substring s 1)))
8053 (remove-text-properties
8054 0 (length s)
8055 '(face nil mouse-face nil keymap nil fontified nil) s)
8056 ;; Make a series of regular expressions to find a match
8057 (setq words (org-split-string s "[ \n\r\t]+")
8059 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8060 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8061 "\\)" markers)
8062 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8063 re2a (concat "[ \t\r\n]" re2a_)
8064 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8065 re4 (concat "[^a-zA-Z_]" re4_)
8067 re1 (concat pre re2 post)
8068 re3 (concat pre (if pre re4_ re4) post)
8069 re5 (concat pre ".*" re4)
8070 re2 (concat pre re2)
8071 re2a (concat pre (if pre re2a_ re2a))
8072 re4 (concat pre (if pre re4_ re4))
8073 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8074 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8075 re5 "\\)"
8077 (cond
8078 ((eq type 'org-occur) (org-occur reall))
8079 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8080 (t (goto-char (point-min))
8081 (setq type 'fuzzy)
8082 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8083 (org-search-not-self 1 re1 nil t)
8084 (org-search-not-self 1 re2 nil t)
8085 (org-search-not-self 1 re2a nil t)
8086 (org-search-not-self 1 re3 nil t)
8087 (org-search-not-self 1 re4 nil t)
8088 (org-search-not-self 1 re5 nil t)
8090 (goto-char (match-beginning 1))
8091 (goto-char pos)
8092 (error "No match")))))
8094 ;; Normal string-search
8095 (goto-char (point-min))
8096 (if (search-forward s nil t)
8097 (goto-char (match-beginning 0))
8098 (error "No match"))))
8099 (and (org-mode-p) (org-show-context 'link-search))
8100 type))
8102 (defun org-search-not-self (group &rest args)
8103 "Execute `re-search-forward', but only accept matches that do not
8104 enclose the position of `org-open-link-marker'."
8105 (let ((m org-open-link-marker))
8106 (catch 'exit
8107 (while (apply 're-search-forward args)
8108 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8109 (goto-char (match-end group))
8110 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8111 (> (match-beginning 0) (marker-position m))
8112 (< (match-end 0) (marker-position m)))
8113 (save-match-data
8114 (or (not (org-in-regexp
8115 org-bracket-link-analytic-regexp 1))
8116 (not (match-end 4)) ; no description
8117 (and (<= (match-beginning 4) (point))
8118 (>= (match-end 4) (point))))))
8119 (throw 'exit (point))))))))
8121 (defun org-get-buffer-for-internal-link (buffer)
8122 "Return a buffer to be used for displaying the link target of internal links."
8123 (cond
8124 ((not org-display-internal-link-with-indirect-buffer)
8125 buffer)
8126 ((string-match "(Clone)$" (buffer-name buffer))
8127 (message "Buffer is already a clone, not making another one")
8128 ;; we also do not modify visibility in this case
8129 buffer)
8130 (t ; make a new indirect buffer for displaying the link
8131 (let* ((bn (buffer-name buffer))
8132 (ibn (concat bn "(Clone)"))
8133 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8134 (with-current-buffer ib (org-overview))
8135 ib))))
8137 (defun org-do-occur (regexp &optional cleanup)
8138 "Call the Emacs command `occur'.
8139 If CLEANUP is non-nil, remove the printout of the regular expression
8140 in the *Occur* buffer. This is useful if the regex is long and not useful
8141 to read."
8142 (occur regexp)
8143 (when cleanup
8144 (let ((cwin (selected-window)) win beg end)
8145 (when (setq win (get-buffer-window "*Occur*"))
8146 (select-window win))
8147 (goto-char (point-min))
8148 (when (re-search-forward "match[a-z]+" nil t)
8149 (setq beg (match-end 0))
8150 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8151 (setq end (1- (match-beginning 0)))))
8152 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8153 (goto-char (point-min))
8154 (select-window cwin))))
8156 ;;; The mark ring for links jumps
8158 (defvar org-mark-ring nil
8159 "Mark ring for positions before jumps in Org-mode.")
8160 (defvar org-mark-ring-last-goto nil
8161 "Last position in the mark ring used to go back.")
8162 ;; Fill and close the ring
8163 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8164 (loop for i from 1 to org-mark-ring-length do
8165 (push (make-marker) org-mark-ring))
8166 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8167 org-mark-ring)
8169 (defun org-mark-ring-push (&optional pos buffer)
8170 "Put the current position or POS into the mark ring and rotate it."
8171 (interactive)
8172 (setq pos (or pos (point)))
8173 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8174 (move-marker (car org-mark-ring)
8175 (or pos (point))
8176 (or buffer (current-buffer)))
8177 (message "%s"
8178 (substitute-command-keys
8179 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8181 (defun org-mark-ring-goto (&optional n)
8182 "Jump to the previous position in the mark ring.
8183 With prefix arg N, jump back that many stored positions. When
8184 called several times in succession, walk through the entire ring.
8185 Org-mode commands jumping to a different position in the current file,
8186 or to another Org-mode file, automatically push the old position
8187 onto the ring."
8188 (interactive "p")
8189 (let (p m)
8190 (if (eq last-command this-command)
8191 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8192 (setq p org-mark-ring))
8193 (setq org-mark-ring-last-goto p)
8194 (setq m (car p))
8195 (switch-to-buffer (marker-buffer m))
8196 (goto-char m)
8197 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8199 (defun org-remove-angle-brackets (s)
8200 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8201 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8203 (defun org-add-angle-brackets (s)
8204 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8205 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8207 (defun org-remove-double-quotes (s)
8208 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8209 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8212 ;;; Following specific links
8214 (defun org-follow-timestamp-link ()
8215 (cond
8216 ((org-at-date-range-p t)
8217 (let ((org-agenda-start-on-weekday)
8218 (t1 (match-string 1))
8219 (t2 (match-string 2)))
8220 (setq t1 (time-to-days (org-time-string-to-time t1))
8221 t2 (time-to-days (org-time-string-to-time t2)))
8222 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8223 ((org-at-timestamp-p t)
8224 (org-agenda-list nil (time-to-days (org-time-string-to-time
8225 (substring (match-string 1) 0 10)))
8227 (t (error "This should not happen"))))
8230 ;;; Following file links
8231 (defvar org-wait nil)
8232 (defun org-open-file (path &optional in-emacs line search)
8233 "Open the file at PATH.
8234 First, this expands any special file name abbreviations. Then the
8235 configuration variable `org-file-apps' is checked if it contains an
8236 entry for this file type, and if yes, the corresponding command is launched.
8238 If no application is found, Emacs simply visits the file.
8240 With optional prefix argument IN-EMACS, Emacs will visit the file.
8241 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8242 and o use an external application to visit the file.
8244 Optional LINE specifies a line to go to, optional SEARCH a string to
8245 search for. If LINE or SEARCH is given, the file will always be
8246 opened in Emacs.
8247 If the file does not exist, an error is thrown."
8248 (setq in-emacs (or in-emacs line search))
8249 (let* ((file (if (equal path "")
8250 buffer-file-name
8251 (substitute-in-file-name (expand-file-name path))))
8252 (apps (append org-file-apps (org-default-apps)))
8253 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8254 (dirp (if remp nil (file-directory-p file)))
8255 (file (if (and dirp org-open-directory-means-index-dot-org)
8256 (concat (file-name-as-directory file) "index.org")
8257 file))
8258 (a-m-a-p (assq 'auto-mode apps))
8259 (dfile (downcase file))
8260 (old-buffer (current-buffer))
8261 (old-pos (point))
8262 (old-mode major-mode)
8263 ext cmd)
8264 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8265 (setq ext (match-string 1 dfile))
8266 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8267 (setq ext (match-string 1 dfile))))
8268 (cond
8269 ((equal in-emacs '(16))
8270 (setq cmd (cdr (assoc 'system apps))))
8271 (in-emacs (setq cmd 'emacs))
8273 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8274 (and dirp (cdr (assoc 'directory apps)))
8275 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8276 'string-match)
8277 (cdr (assoc ext apps))
8278 (cdr (assoc t apps))))))
8279 (when (eq cmd 'system)
8280 (setq cmd (cdr (assoc 'system apps))))
8281 (when (eq cmd 'default)
8282 (setq cmd (cdr (assoc t apps))))
8283 (when (eq cmd 'mailcap)
8284 (require 'mailcap)
8285 (mailcap-parse-mailcaps)
8286 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8287 (command (mailcap-mime-info mime-type)))
8288 (if (stringp command)
8289 (setq cmd command)
8290 (setq cmd 'emacs))))
8291 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8292 (not (file-exists-p file))
8293 (not org-open-non-existing-files))
8294 (error "No such file: %s" file))
8295 (cond
8296 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8297 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8298 (while (string-match "['\"]%s['\"]" cmd)
8299 (setq cmd (replace-match "%s" t t cmd)))
8300 (while (string-match "%s" cmd)
8301 (setq cmd (replace-match
8302 (save-match-data
8303 (shell-quote-argument
8304 (convert-standard-filename file)))
8305 t t cmd)))
8306 (save-window-excursion
8307 (start-process-shell-command cmd nil cmd)
8308 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8310 ((or (stringp cmd)
8311 (eq cmd 'emacs))
8312 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8313 (widen)
8314 (if line (goto-line line)
8315 (if search (org-link-search search))))
8316 ((consp cmd)
8317 (let ((file (convert-standard-filename file)))
8318 (eval cmd)))
8319 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8320 (and (org-mode-p) (eq old-mode 'org-mode)
8321 (or (not (equal old-buffer (current-buffer)))
8322 (not (equal old-pos (point))))
8323 (org-mark-ring-push old-pos old-buffer))))
8325 (defun org-default-apps ()
8326 "Return the default applications for this operating system."
8327 (cond
8328 ((eq system-type 'darwin)
8329 org-file-apps-defaults-macosx)
8330 ((eq system-type 'windows-nt)
8331 org-file-apps-defaults-windowsnt)
8332 (t org-file-apps-defaults-gnu)))
8334 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8335 "Convert extensions to regular expressions in the cars of LIST.
8336 Also, weed out any non-string entries, because the return value is used
8337 only for regexp matching.
8338 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8339 point to the symbol `emacs', indicating that the file should
8340 be opened in Emacs."
8341 (append
8342 (delq nil
8343 (mapcar (lambda (x)
8344 (if (not (stringp (car x)))
8346 (if (string-match "\\W" (car x))
8348 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8349 list))
8350 (if add-auto-mode
8351 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8353 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8354 (defun org-file-remote-p (file)
8355 "Test whether FILE specifies a location on a remote system.
8356 Return non-nil if the location is indeed remote.
8358 For example, the filename \"/user@host:/foo\" specifies a location
8359 on the system \"/user@host:\"."
8360 (cond ((fboundp 'file-remote-p)
8361 (file-remote-p file))
8362 ((fboundp 'tramp-handle-file-remote-p)
8363 (tramp-handle-file-remote-p file))
8364 ((and (boundp 'ange-ftp-name-format)
8365 (string-match (car ange-ftp-name-format) file))
8367 (t nil)))
8370 ;;;; Refiling
8372 (defun org-get-org-file ()
8373 "Read a filename, with default directory `org-directory'."
8374 (let ((default (or org-default-notes-file remember-data-file)))
8375 (read-file-name (format "File name [%s]: " default)
8376 (file-name-as-directory org-directory)
8377 default)))
8379 (defun org-notes-order-reversed-p ()
8380 "Check if the current file should receive notes in reversed order."
8381 (cond
8382 ((not org-reverse-note-order) nil)
8383 ((eq t org-reverse-note-order) t)
8384 ((not (listp org-reverse-note-order)) nil)
8385 (t (catch 'exit
8386 (let ((all org-reverse-note-order)
8387 entry)
8388 (while (setq entry (pop all))
8389 (if (string-match (car entry) buffer-file-name)
8390 (throw 'exit (cdr entry))))
8391 nil)))))
8393 (defvar org-refile-target-table nil
8394 "The list of refile targets, created by `org-refile'.")
8396 (defvar org-agenda-new-buffers nil
8397 "Buffers created to visit agenda files.")
8399 (defun org-get-refile-targets (&optional default-buffer)
8400 "Produce a table with refile targets."
8401 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
8402 targets txt re files f desc descre fast-path-p level pos0)
8403 (message "Getting targets...")
8404 (with-current-buffer (or default-buffer (current-buffer))
8405 (while (setq entry (pop entries))
8406 (setq files (car entry) desc (cdr entry))
8407 (setq fast-path-p nil)
8408 (cond
8409 ((null files) (setq files (list (current-buffer))))
8410 ((eq files 'org-agenda-files)
8411 (setq files (org-agenda-files 'unrestricted)))
8412 ((and (symbolp files) (fboundp files))
8413 (setq files (funcall files)))
8414 ((and (symbolp files) (boundp files))
8415 (setq files (symbol-value files))))
8416 (if (stringp files) (setq files (list files)))
8417 (cond
8418 ((eq (car desc) :tag)
8419 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8420 ((eq (car desc) :todo)
8421 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8422 ((eq (car desc) :regexp)
8423 (setq descre (cdr desc)))
8424 ((eq (car desc) :level)
8425 (setq descre (concat "^\\*\\{" (number-to-string
8426 (if org-odd-levels-only
8427 (1- (* 2 (cdr desc)))
8428 (cdr desc)))
8429 "\\}[ \t]")))
8430 ((eq (car desc) :maxlevel)
8431 (setq fast-path-p t)
8432 (setq descre (concat "^\\*\\{1," (number-to-string
8433 (if org-odd-levels-only
8434 (1- (* 2 (cdr desc)))
8435 (cdr desc)))
8436 "\\}[ \t]")))
8437 (t (error "Bad refiling target description %s" desc)))
8438 (while (setq f (pop files))
8439 (save-excursion
8440 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
8441 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8442 (setq f (expand-file-name f))
8443 (if (eq org-refile-use-outline-path 'file)
8444 (push (list (file-name-nondirectory f) f nil nil) targets))
8445 (save-excursion
8446 (save-restriction
8447 (widen)
8448 (goto-char (point-min))
8449 (while (re-search-forward descre nil t)
8450 (goto-char (setq pos0 (point-at-bol)))
8451 (catch 'next
8452 (when org-refile-target-verify-function
8453 (save-match-data
8454 (or (funcall org-refile-target-verify-function)
8455 (throw 'next t))))
8456 (when (looking-at org-complex-heading-regexp)
8457 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8458 txt (org-link-display-format (match-string 4))
8459 re (concat "^" (regexp-quote
8460 (buffer-substring (match-beginning 1)
8461 (match-end 4)))))
8462 (if (match-end 5) (setq re (concat re "[ \t]+"
8463 (regexp-quote
8464 (match-string 5)))))
8465 (setq re (concat re "[ \t]*$"))
8466 (when org-refile-use-outline-path
8467 (setq txt (mapconcat 'org-protect-slash
8468 (append
8469 (if (eq org-refile-use-outline-path 'file)
8470 (list (file-name-nondirectory
8471 (buffer-file-name (buffer-base-buffer))))
8472 (if (eq org-refile-use-outline-path 'full-file-path)
8473 (list (buffer-file-name (buffer-base-buffer)))))
8474 (org-get-outline-path fast-path-p level txt)
8475 (list txt))
8476 "/")))
8477 (push (list txt f re (point)) targets)))
8478 (when (= (point) pos0)
8479 ;; verification function has not moved point
8480 (goto-char (point-at-eol))))))))))
8481 (message "Getting targets...done")
8482 (nreverse targets)))
8484 (defun org-protect-slash (s)
8485 (while (string-match "/" s)
8486 (setq s (replace-match "\\" t t s)))
8489 (defvar org-olpa (make-vector 20 nil))
8491 (defun org-get-outline-path (&optional fastp level heading)
8492 "Return the outline path to the current entry, as a list."
8493 (if fastp
8494 (progn
8495 (if (> level 19)
8496 (error "Outline path failure, more than 19 levels."))
8497 (loop for i from level upto 19 do
8498 (aset org-olpa i nil))
8499 (prog1
8500 (delq nil (append org-olpa nil))
8501 (aset org-olpa level heading)))
8502 (let (rtn)
8503 (save-excursion
8504 (while (org-up-heading-safe)
8505 (when (looking-at org-complex-heading-regexp)
8506 (push (org-match-string-no-properties 4) rtn)))
8507 rtn))))
8509 (defvar org-refile-history nil
8510 "History for refiling operations.")
8512 (defvar org-after-refile-insert-hook nil
8513 "Hook run after `org-refile' has inserted its stuff at the new location.
8514 Note that this is still *before* the stuff will be removed from
8515 the *old* location.")
8517 (defun org-refile (&optional goto default-buffer)
8518 "Move the entry at point to another heading.
8519 The list of target headings is compiled using the information in
8520 `org-refile-targets', which see. This list is created before each use
8521 and will therefore always be up-to-date.
8523 At the target location, the entry is filed as a subitem of the target heading.
8524 Depending on `org-reverse-note-order', the new subitem will either be the
8525 first or the last subitem.
8527 If there is an active region, all entries in that region will be moved.
8528 However, the region must fulfil the requirement that the first heading
8529 is the first one sets the top-level of the moved text - at most siblings
8530 below it are allowed.
8532 With prefix arg GOTO, the command will only visit the target location,
8533 not actually move anything.
8534 With a double prefix `C-u C-u', go to the location where the last refiling
8535 operation has put the subtree.
8537 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
8538 (interactive "P")
8539 (let* ((cbuf (current-buffer))
8540 (regionp (org-region-active-p))
8541 (region-start (and regionp (region-beginning)))
8542 (region-end (and regionp (region-end)))
8543 (region-length (and regionp (- region-end region-start)))
8544 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8545 pos it nbuf file re level reversed)
8546 (when regionp (goto-char region-start)
8547 (unless (org-kill-is-subtree-p
8548 (buffer-substring region-start region-end))
8549 (error "The region is not a (sequence of) subtree(s)")))
8550 (if (equal goto '(16))
8551 (org-refile-goto-last-stored)
8552 (when (setq it (org-refile-get-location
8553 (if goto "Goto: " "Refile to: ") default-buffer
8554 org-refile-allow-creating-parent-nodes))
8555 (setq file (nth 1 it)
8556 re (nth 2 it)
8557 pos (nth 3 it))
8558 (if (and (not goto)
8560 (equal (buffer-file-name) file)
8561 (if regionp
8562 (and (>= pos region-start)
8563 (<= pos region-end))
8564 (and (>= pos (point))
8565 (< pos (save-excursion
8566 (org-end-of-subtree t t))))))
8567 (error "Cannot refile to position inside the tree or region"))
8569 (setq nbuf (or (find-buffer-visiting file)
8570 (find-file-noselect file)))
8571 (if goto
8572 (progn
8573 (switch-to-buffer nbuf)
8574 (goto-char pos)
8575 (org-show-context 'org-goto))
8576 (if regionp
8577 (progn
8578 (kill-new (buffer-substring region-start region-end))
8579 (org-save-markers-in-region region-start region-end))
8580 (org-copy-subtree 1 nil t))
8581 (save-excursion
8582 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8583 (find-file-noselect file))))
8584 (setq reversed (org-notes-order-reversed-p))
8585 (save-excursion
8586 (save-restriction
8587 (widen)
8588 (if pos
8589 (progn
8590 (goto-char pos)
8591 (looking-at outline-regexp)
8592 (setq level (org-get-valid-level (funcall outline-level) 1))
8593 (goto-char
8594 (if reversed
8595 (or (outline-next-heading) (point-max))
8596 (or (save-excursion (outline-get-next-sibling))
8597 (org-end-of-subtree t t)
8598 (point-max)))))
8599 (setq level 1)
8600 (if (not reversed)
8601 (goto-char (point-max))
8602 (goto-char (point-min))
8603 (or (outline-next-heading) (goto-char (point-max)))))
8604 (if (not (bolp)) (newline))
8605 (bookmark-set "org-refile-last-stored")
8606 (org-paste-subtree level)
8607 (run-hooks 'org-after-refile-insert-hook))))
8608 (if regionp
8609 (delete-region (point) (+ (point) region-length))
8610 (org-cut-subtree))
8611 (setq org-markers-to-move nil)
8612 (message "Refiled to \"%s\"" (car it))))))
8613 (org-reveal))
8615 (defun org-refile-goto-last-stored ()
8616 "Go to the location where the last refile was stored."
8617 (interactive)
8618 (bookmark-jump "org-refile-last-stored")
8619 (message "This is the location of the last refile"))
8621 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
8622 "Prompt the user for a refile location, using PROMPT."
8623 (let ((org-refile-targets org-refile-targets)
8624 (org-refile-use-outline-path org-refile-use-outline-path))
8625 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8626 (unless org-refile-target-table
8627 (error "No refile targets"))
8628 (let* ((cbuf (current-buffer))
8629 (partial-completion-mode nil)
8630 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8631 (cfunc (if (and org-refile-use-outline-path
8632 org-outline-path-complete-in-steps)
8633 'org-olpath-completing-read
8634 'org-ido-completing-read))
8635 (extra (if org-refile-use-outline-path "/" ""))
8636 (filename (and cfn (expand-file-name cfn)))
8637 (tbl (mapcar
8638 (lambda (x)
8639 (if (and (not (member org-refile-use-outline-path
8640 '(file full-file-path)))
8641 (not (equal filename (nth 1 x))))
8642 (cons (concat (car x) extra " ("
8643 (file-name-nondirectory (nth 1 x)) ")")
8644 (cdr x))
8645 (cons (concat (car x) extra) (cdr x))))
8646 org-refile-target-table))
8647 (completion-ignore-case t)
8648 pa answ parent-target child parent)
8649 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
8650 nil 'org-refile-history))
8651 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
8652 (if pa
8654 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
8655 (setq parent (match-string 1 answ)
8656 child (match-string 2 answ))
8657 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
8658 (when (and parent-target
8659 (or (eq new-nodes t)
8660 (and (eq new-nodes 'confirm)
8661 (y-or-n-p (format "Create new node \"%s\"? " child)))))
8662 (org-refile-new-child parent-target child))))))
8664 (defun org-refile-new-child (parent-target child)
8665 "Use refile target PARENT-TARGET to add new CHILD below it."
8666 (unless parent-target
8667 (error "Cannot find parent for new node"))
8668 (let ((file (nth 1 parent-target))
8669 (pos (nth 3 parent-target))
8670 level)
8671 (with-current-buffer (or (find-buffer-visiting file)
8672 (find-file-noselect file))
8673 (save-excursion
8674 (save-restriction
8675 (widen)
8676 (if pos
8677 (goto-char pos)
8678 (goto-char (point-max))
8679 (if (not (bolp)) (newline)))
8680 (when (looking-at outline-regexp)
8681 (setq level (funcall outline-level))
8682 (org-end-of-subtree t t))
8683 (org-back-over-empty-lines)
8684 (insert "\n" (make-string
8685 (if pos (org-get-valid-level level 1) 1) ?*)
8686 " " child "\n")
8687 (beginning-of-line 0)
8688 (list (concat (car parent-target) "/" child) file "" (point)))))))
8690 (defun org-olpath-completing-read (prompt collection &rest args)
8691 "Read an outline path like a file name."
8692 (let ((thetable collection)
8693 (org-completion-use-ido nil)) ; does not work with ido.
8694 (apply
8695 'org-ido-completing-read prompt
8696 (lambda (string predicate &optional flag)
8697 (let (rtn r f (l (length string)))
8698 (cond
8699 ((eq flag nil)
8700 ;; try completion
8701 (try-completion string thetable))
8702 ((eq flag t)
8703 ;; all-completions
8704 (setq rtn (all-completions string thetable predicate))
8705 (mapcar
8706 (lambda (x)
8707 (setq r (substring x l))
8708 (if (string-match " ([^)]*)$" x)
8709 (setq f (match-string 0 x))
8710 (setq f ""))
8711 (if (string-match "/" r)
8712 (concat string (substring r 0 (match-end 0)) f)
8714 rtn))
8715 ((eq flag 'lambda)
8716 ;; exact match?
8717 (assoc string thetable)))
8719 args)))
8721 ;;;; Dynamic blocks
8723 (defun org-find-dblock (name)
8724 "Find the first dynamic block with name NAME in the buffer.
8725 If not found, stay at current position and return nil."
8726 (let (pos)
8727 (save-excursion
8728 (goto-char (point-min))
8729 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8730 nil t)
8731 (match-beginning 0))))
8732 (if pos (goto-char pos))
8733 pos))
8735 (defconst org-dblock-start-re
8736 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8737 "Matches the startline of a dynamic block, with parameters.")
8739 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8740 "Matches the end of a dynamic block.")
8742 (defun org-create-dblock (plist)
8743 "Create a dynamic block section, with parameters taken from PLIST.
8744 PLIST must contain a :name entry which is used as name of the block."
8745 (unless (bolp) (newline))
8746 (let ((name (plist-get plist :name)))
8747 (insert "#+BEGIN: " name)
8748 (while plist
8749 (if (eq (car plist) :name)
8750 (setq plist (cddr plist))
8751 (insert " " (prin1-to-string (pop plist)))))
8752 (insert "\n\n#+END:\n")
8753 (beginning-of-line -2)))
8755 (defun org-prepare-dblock ()
8756 "Prepare dynamic block for refresh.
8757 This empties the block, puts the cursor at the insert position and returns
8758 the property list including an extra property :name with the block name."
8759 (unless (looking-at org-dblock-start-re)
8760 (error "Not at a dynamic block"))
8761 (let* ((begdel (1+ (match-end 0)))
8762 (name (org-no-properties (match-string 1)))
8763 (params (append (list :name name)
8764 (read (concat "(" (match-string 3) ")")))))
8765 (unless (re-search-forward org-dblock-end-re nil t)
8766 (error "Dynamic block not terminated"))
8767 (setq params
8768 (append params
8769 (list :content (buffer-substring
8770 begdel (match-beginning 0)))))
8771 (delete-region begdel (match-beginning 0))
8772 (goto-char begdel)
8773 (open-line 1)
8774 params))
8776 (defun org-map-dblocks (&optional command)
8777 "Apply COMMAND to all dynamic blocks in the current buffer.
8778 If COMMAND is not given, use `org-update-dblock'."
8779 (let ((cmd (or command 'org-update-dblock))
8780 pos)
8781 (save-excursion
8782 (goto-char (point-min))
8783 (while (re-search-forward org-dblock-start-re nil t)
8784 (goto-char (setq pos (match-beginning 0)))
8785 (condition-case nil
8786 (funcall cmd)
8787 (error (message "Error during update of dynamic block")))
8788 (goto-char pos)
8789 (unless (re-search-forward org-dblock-end-re nil t)
8790 (error "Dynamic block not terminated"))))))
8792 (defun org-dblock-update (&optional arg)
8793 "User command for updating dynamic blocks.
8794 Update the dynamic block at point. With prefix ARG, update all dynamic
8795 blocks in the buffer."
8796 (interactive "P")
8797 (if arg
8798 (org-update-all-dblocks)
8799 (or (looking-at org-dblock-start-re)
8800 (org-beginning-of-dblock))
8801 (org-update-dblock)))
8803 (defun org-update-dblock ()
8804 "Update the dynamic block at point
8805 This means to empty the block, parse for parameters and then call
8806 the correct writing function."
8807 (save-window-excursion
8808 (let* ((pos (point))
8809 (line (org-current-line))
8810 (params (org-prepare-dblock))
8811 (name (plist-get params :name))
8812 (cmd (intern (concat "org-dblock-write:" name))))
8813 (message "Updating dynamic block `%s' at line %d..." name line)
8814 (funcall cmd params)
8815 (message "Updating dynamic block `%s' at line %d...done" name line)
8816 (goto-char pos))))
8818 (defun org-beginning-of-dblock ()
8819 "Find the beginning of the dynamic block at point.
8820 Error if there is no such block at point."
8821 (let ((pos (point))
8822 beg)
8823 (end-of-line 1)
8824 (if (and (re-search-backward org-dblock-start-re nil t)
8825 (setq beg (match-beginning 0))
8826 (re-search-forward org-dblock-end-re nil t)
8827 (> (match-end 0) pos))
8828 (goto-char beg)
8829 (goto-char pos)
8830 (error "Not in a dynamic block"))))
8832 (defun org-update-all-dblocks ()
8833 "Update all dynamic blocks in the buffer.
8834 This function can be used in a hook."
8835 (when (org-mode-p)
8836 (org-map-dblocks 'org-update-dblock)))
8839 ;;;; Completion
8841 (defconst org-additional-option-like-keywords
8842 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8843 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8844 "LATEX_HEADER:"
8845 "BEGIN_EXAMPLE" "END_EXAMPLE"
8846 "BEGIN_QUOTE" "END_QUOTE"
8847 "BEGIN_VERSE" "END_VERSE"
8848 "BEGIN_CENTER" "END_CENTER"
8849 "BEGIN_SRC" "END_SRC"
8850 "CATEGORY" "COLUMNS"
8851 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
8853 (defcustom org-structure-template-alist
8855 ("s" "#+begin_src ?\n\n#+end_src"
8856 "<src lang=\"?\">\n\n</src>")
8857 ("e" "#+begin_example\n?\n#+end_example"
8858 "<example>\n?\n</example>")
8859 ("q" "#+begin_quote\n?\n#+end_quote"
8860 "<quote>\n?\n</quote>")
8861 ("v" "#+begin_verse\n?\n#+end_verse"
8862 "<verse>\n?\n/verse>")
8863 ("c" "#+begin_center\n?\n#+end_center"
8864 "<center>\n?\n/center>")
8865 ("l" "#+begin_latex\n?\n#+end_latex"
8866 "<literal style=\"latex\">\n?\n</literal>")
8867 ("L" "#+latex: "
8868 "<literal style=\"latex\">?</literal>")
8869 ("h" "#+begin_html\n?\n#+end_html"
8870 "<literal style=\"html\">\n?\n</literal>")
8871 ("H" "#+html: "
8872 "<literal style=\"html\">?</literal>")
8873 ("a" "#+begin_ascii\n?\n#+end_ascii")
8874 ("A" "#+ascii: ")
8875 ("i" "#+include %file ?"
8876 "<include file=%file markup=\"?\">")
8878 "Structure completion elements.
8879 This is a list of abbreviation keys and values. The value gets inserted
8880 it you type @samp{.} followed by the key and then the completion key,
8881 usually `M-TAB'. %file will be replaced by a file name after prompting
8882 for the file using completion.
8883 There are two templates for each key, the first uses the original Org syntax,
8884 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8885 the default when the /org-mtags.el/ module has been loaded. See also the
8886 variable `org-mtags-prefer-muse-templates'.
8887 This is an experimental feature, it is undecided if it is going to stay in."
8888 :group 'org-completion
8889 :type '(repeat
8890 (string :tag "Key")
8891 (string :tag "Template")
8892 (string :tag "Muse Template")))
8894 (defun org-try-structure-completion ()
8895 "Try to complete a structure template before point.
8896 This looks for strings like \"<e\" on an otherwise empty line and
8897 expands them."
8898 (let ((l (buffer-substring (point-at-bol) (point)))
8900 (when (and (looking-at "[ \t]*$")
8901 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8902 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8903 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8904 (match-beginning 1)) a)
8905 t)))
8907 (defun org-complete-expand-structure-template (start cell)
8908 "Expand a structure template."
8909 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8910 (rpl (nth (if musep 2 1) cell)))
8911 (delete-region start (point))
8912 (when (string-match "\\`#\\+" rpl)
8913 (cond
8914 ((bolp))
8915 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8916 (delete-region (point-at-bol) (point)))
8917 (t (newline))))
8918 (setq start (point))
8919 (if (string-match "%file" rpl)
8920 (setq rpl (replace-match
8921 (concat
8922 "\""
8923 (save-match-data
8924 (abbreviate-file-name (read-file-name "Include file: ")))
8925 "\"")
8926 t t rpl)))
8927 (insert rpl)
8928 (if (re-search-backward "\\?" start t) (delete-char 1))))
8931 (defun org-complete (&optional arg)
8932 "Perform completion on word at point.
8933 At the beginning of a headline, this completes TODO keywords as given in
8934 `org-todo-keywords'.
8935 If the current word is preceded by a backslash, completes the TeX symbols
8936 that are supported for HTML support.
8937 If the current word is preceded by \"#+\", completes special words for
8938 setting file options.
8939 In the line after \"#+STARTUP:, complete valid keywords.\"
8940 At all other locations, this simply calls the value of
8941 `org-completion-fallback-command'."
8942 (interactive "P")
8943 (org-without-partial-completion
8944 (catch 'exit
8945 (let* ((a nil)
8946 (end (point))
8947 (beg1 (save-excursion
8948 (skip-chars-backward (org-re "[:alnum:]_@"))
8949 (point)))
8950 (beg (save-excursion
8951 (skip-chars-backward "a-zA-Z0-9_:$")
8952 (point)))
8953 (confirm (lambda (x) (stringp (car x))))
8954 (searchhead (equal (char-before beg) ?*))
8955 (struct
8956 (when (and (member (char-before beg1) '(?. ?<))
8957 (setq a (assoc (buffer-substring beg1 (point))
8958 org-structure-template-alist)))
8959 (org-complete-expand-structure-template (1- beg1) a)
8960 (throw 'exit t)))
8961 (tag (and (equal (char-before beg1) ?:)
8962 (equal (char-after (point-at-bol)) ?*)))
8963 (prop (and (equal (char-before beg1) ?:)
8964 (not (equal (char-after (point-at-bol)) ?*))))
8965 (texp (equal (char-before beg) ?\\))
8966 (link (equal (char-before beg) ?\[))
8967 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8968 beg)
8969 "#+"))
8970 (startup (string-match "^#\\+STARTUP:.*"
8971 (buffer-substring (point-at-bol) (point))))
8972 (completion-ignore-case opt)
8973 (type nil)
8974 (tbl nil)
8975 (table (cond
8976 (opt
8977 (setq type :opt)
8978 (require 'org-exp)
8979 (append
8980 (mapcar
8981 (lambda (x)
8982 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8983 (cons (match-string 2 x) (match-string 1 x)))
8984 (org-split-string (org-get-current-options) "\n"))
8985 (mapcar 'list org-additional-option-like-keywords)))
8986 (startup
8987 (setq type :startup)
8988 org-startup-options)
8989 (link (append org-link-abbrev-alist-local
8990 org-link-abbrev-alist))
8991 (texp
8992 (setq type :tex)
8993 org-html-entities)
8994 ((string-match "\\`\\*+[ \t]+\\'"
8995 (buffer-substring (point-at-bol) beg))
8996 (setq type :todo)
8997 (mapcar 'list org-todo-keywords-1))
8998 (searchhead
8999 (setq type :searchhead)
9000 (save-excursion
9001 (goto-char (point-min))
9002 (while (re-search-forward org-todo-line-regexp nil t)
9003 (push (list
9004 (org-make-org-heading-search-string
9005 (match-string 3) t))
9006 tbl)))
9007 tbl)
9008 (tag (setq type :tag beg beg1)
9009 (or org-tag-alist (org-get-buffer-tags)))
9010 (prop (setq type :prop beg beg1)
9011 (mapcar 'list (org-buffer-property-keys nil t t)))
9012 (t (progn
9013 (call-interactively org-completion-fallback-command)
9014 (throw 'exit nil)))))
9015 (pattern (buffer-substring-no-properties beg end))
9016 (completion (try-completion pattern table confirm)))
9017 (cond ((eq completion t)
9018 (if (not (assoc (upcase pattern) table))
9019 (message "Already complete")
9020 (if (and (equal type :opt)
9021 (not (member (car (assoc (upcase pattern) table))
9022 org-additional-option-like-keywords)))
9023 (insert (substring (cdr (assoc (upcase pattern) table))
9024 (length pattern)))
9025 (if (memq type '(:tag :prop)) (insert ":")))))
9026 ((null completion)
9027 (message "Can't find completion for \"%s\"" pattern)
9028 (ding))
9029 ((not (string= pattern completion))
9030 (delete-region beg end)
9031 (if (string-match " +$" completion)
9032 (setq completion (replace-match "" t t completion)))
9033 (insert completion)
9034 (if (get-buffer-window "*Completions*")
9035 (delete-window (get-buffer-window "*Completions*")))
9036 (if (assoc completion table)
9037 (if (eq type :todo) (insert " ")
9038 (if (memq type '(:tag :prop)) (insert ":"))))
9039 (if (and (equal type :opt) (assoc completion table))
9040 (message "%s" (substitute-command-keys
9041 "Press \\[org-complete] again to insert example settings"))))
9043 (message "Making completion list...")
9044 (let ((list (sort (all-completions pattern table confirm)
9045 'string<)))
9046 (with-output-to-temp-buffer "*Completions*"
9047 (condition-case nil
9048 ;; Protection needed for XEmacs and emacs 21
9049 (display-completion-list list pattern)
9050 (error (display-completion-list list)))))
9051 (message "Making completion list...%s" "done")))))))
9053 ;;;; TODO, DEADLINE, Comments
9055 (defun org-toggle-comment ()
9056 "Change the COMMENT state of an entry."
9057 (interactive)
9058 (save-excursion
9059 (org-back-to-heading)
9060 (let (case-fold-search)
9061 (if (looking-at (concat outline-regexp
9062 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9063 (replace-match "" t t nil 1)
9064 (if (looking-at outline-regexp)
9065 (progn
9066 (goto-char (match-end 0))
9067 (insert org-comment-string " ")))))))
9069 (defvar org-last-todo-state-is-todo nil
9070 "This is non-nil when the last TODO state change led to a TODO state.
9071 If the last change removed the TODO tag or switched to DONE, then
9072 this is nil.")
9074 (defvar org-setting-tags nil) ; dynamically skipped
9076 (defun org-parse-local-options (string var)
9077 "Parse STRING for startup setting relevant for variable VAR."
9078 (let ((rtn (symbol-value var))
9079 e opts)
9080 (save-match-data
9081 (if (or (not string) (not (string-match "\\S-" string)))
9083 (setq opts (delq nil (mapcar (lambda (x)
9084 (setq e (assoc x org-startup-options))
9085 (if (eq (nth 1 e) var) e nil))
9086 (org-split-string string "[ \t]+"))))
9087 (if (not opts)
9089 (setq rtn nil)
9090 (while (setq e (pop opts))
9091 (if (not (nth 3 e))
9092 (setq rtn (nth 2 e))
9093 (if (not (listp rtn)) (setq rtn nil))
9094 (push (nth 2 e) rtn)))
9095 rtn)))))
9097 (defvar org-todo-setup-filter-hook nil
9098 "Hook for functions that pre-filter todo specs.
9100 Each function takes a todo spec and returns either `nil' or the spec
9101 transformed into canonical form." )
9103 (defvar org-todo-get-default-hook nil
9104 "Hook for functions that get a default item for todo.
9106 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9107 `nil' or a string to be used for the todo mark." )
9109 (defvar org-agenda-headline-snapshot-before-repeat)
9110 (defun org-todo (&optional arg)
9111 "Change the TODO state of an item.
9112 The state of an item is given by a keyword at the start of the heading,
9113 like
9114 *** TODO Write paper
9115 *** DONE Call mom
9117 The different keywords are specified in the variable `org-todo-keywords'.
9118 By default the available states are \"TODO\" and \"DONE\".
9119 So for this example: when the item starts with TODO, it is changed to DONE.
9120 When it starts with DONE, the DONE is removed. And when neither TODO nor
9121 DONE are present, add TODO at the beginning of the heading.
9123 With C-u prefix arg, use completion to determine the new state.
9124 With numeric prefix arg, switch to that state.
9125 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9126 With a tripple C-u prefix, circumvent any state blocking.
9128 For calling through lisp, arg is also interpreted in the following way:
9129 'none -> empty state
9130 \"\"(empty string) -> switch to empty state
9131 'done -> switch to DONE
9132 'nextset -> switch to the next set of keywords
9133 'previousset -> switch to the previous set of keywords
9134 \"WAITING\" -> switch to the specified keyword, but only if it
9135 really is a member of `org-todo-keywords'."
9136 (interactive "P")
9137 (if (equal arg '(16)) (setq arg 'nextset))
9138 (let ((org-blocker-hook org-blocker-hook)
9139 (case-fold-search nil))
9140 (when (equal arg '(64))
9141 (setq arg nil org-blocker-hook nil))
9142 (when (and org-blocker-hook
9143 (org-entry-get nil "NOBLOCKING"))
9144 (setq org-blocker-hook nil))
9145 (save-excursion
9146 (catch 'exit
9147 (org-back-to-heading)
9148 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9149 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9150 (looking-at " *"))
9151 (let* ((match-data (match-data))
9152 (startpos (point-at-bol))
9153 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9154 (org-log-done org-log-done)
9155 (org-log-repeat org-log-repeat)
9156 (org-todo-log-states org-todo-log-states)
9157 (this (match-string 1))
9158 (hl-pos (match-beginning 0))
9159 (head (org-get-todo-sequence-head this))
9160 (ass (assoc head org-todo-kwd-alist))
9161 (interpret (nth 1 ass))
9162 (done-word (nth 3 ass))
9163 (final-done-word (nth 4 ass))
9164 (last-state (or this ""))
9165 (completion-ignore-case t)
9166 (member (member this org-todo-keywords-1))
9167 (tail (cdr member))
9168 (state (cond
9169 ((and org-todo-key-trigger
9170 (or (and (equal arg '(4))
9171 (eq org-use-fast-todo-selection 'prefix))
9172 (and (not arg) org-use-fast-todo-selection
9173 (not (eq org-use-fast-todo-selection
9174 'prefix)))))
9175 ;; Use fast selection
9176 (org-fast-todo-selection))
9177 ((and (equal arg '(4))
9178 (or (not org-use-fast-todo-selection)
9179 (not org-todo-key-trigger)))
9180 ;; Read a state with completion
9181 (org-ido-completing-read
9182 "State: " (mapcar (lambda(x) (list x))
9183 org-todo-keywords-1)
9184 nil t))
9185 ((eq arg 'right)
9186 (if this
9187 (if tail (car tail) nil)
9188 (car org-todo-keywords-1)))
9189 ((eq arg 'left)
9190 (if (equal member org-todo-keywords-1)
9192 (if this
9193 (nth (- (length org-todo-keywords-1)
9194 (length tail) 2)
9195 org-todo-keywords-1)
9196 (org-last org-todo-keywords-1))))
9197 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9198 (setq arg nil))) ; hack to fall back to cycling
9199 (arg
9200 ;; user or caller requests a specific state
9201 (cond
9202 ((equal arg "") nil)
9203 ((eq arg 'none) nil)
9204 ((eq arg 'done) (or done-word (car org-done-keywords)))
9205 ((eq arg 'nextset)
9206 (or (car (cdr (member head org-todo-heads)))
9207 (car org-todo-heads)))
9208 ((eq arg 'previousset)
9209 (let ((org-todo-heads (reverse org-todo-heads)))
9210 (or (car (cdr (member head org-todo-heads)))
9211 (car org-todo-heads))))
9212 ((car (member arg org-todo-keywords-1)))
9213 ((nth (1- (prefix-numeric-value arg))
9214 org-todo-keywords-1))))
9215 ((null member) (or head (car org-todo-keywords-1)))
9216 ((equal this final-done-word) nil) ;; -> make empty
9217 ((null tail) nil) ;; -> first entry
9218 ((memq interpret '(type priority))
9219 (if (eq this-command last-command)
9220 (car tail)
9221 (if (> (length tail) 0)
9222 (or done-word (car org-done-keywords))
9223 nil)))
9225 (car tail))))
9226 (state (or
9227 (run-hook-with-args-until-success
9228 'org-todo-get-default-hook state last-state)
9229 state))
9230 (next (if state (concat " " state " ") " "))
9231 (change-plist (list :type 'todo-state-change :from this :to state
9232 :position startpos))
9233 dolog now-done-p)
9234 (when org-blocker-hook
9235 (setq org-last-todo-state-is-todo
9236 (not (member this org-done-keywords)))
9237 (unless (save-excursion
9238 (save-match-data
9239 (run-hook-with-args-until-failure
9240 'org-blocker-hook change-plist)))
9241 (if (interactive-p)
9242 (error "TODO state change from %s to %s blocked" this state)
9243 ;; fail silently
9244 (message "TODO state change from %s to %s blocked" this state)
9245 (throw 'exit nil))))
9246 (store-match-data match-data)
9247 (replace-match next t t)
9248 (unless (pos-visible-in-window-p hl-pos)
9249 (message "TODO state changed to %s" (org-trim next)))
9250 (unless head
9251 (setq head (org-get-todo-sequence-head state)
9252 ass (assoc head org-todo-kwd-alist)
9253 interpret (nth 1 ass)
9254 done-word (nth 3 ass)
9255 final-done-word (nth 4 ass)))
9256 (when (memq arg '(nextset previousset))
9257 (message "Keyword-Set %d/%d: %s"
9258 (- (length org-todo-sets) -1
9259 (length (memq (assoc state org-todo-sets) org-todo-sets)))
9260 (length org-todo-sets)
9261 (mapconcat 'identity (assoc state org-todo-sets) " ")))
9262 (setq org-last-todo-state-is-todo
9263 (not (member state org-done-keywords)))
9264 (setq now-done-p (and (member state org-done-keywords)
9265 (not (member this org-done-keywords))))
9266 (and logging (org-local-logging logging))
9267 (when (and (or org-todo-log-states org-log-done)
9268 (not (memq arg '(nextset previousset))))
9269 ;; we need to look at recording a time and note
9270 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
9271 (nth 2 (assoc this org-todo-log-states))))
9272 (when (and state
9273 (member state org-not-done-keywords)
9274 (not (member this org-not-done-keywords)))
9275 ;; This is now a todo state and was not one before
9276 ;; If there was a CLOSED time stamp, get rid of it.
9277 (org-add-planning-info nil nil 'closed))
9278 (when (and now-done-p org-log-done)
9279 ;; It is now done, and it was not done before
9280 (org-add-planning-info 'closed (org-current-time))
9281 (if (and (not dolog) (eq 'note org-log-done))
9282 (org-add-log-setup 'done state this 'findpos 'note)))
9283 (when (and state dolog)
9284 ;; This is a non-nil state, and we need to log it
9285 (org-add-log-setup 'state state this 'findpos dolog)))
9286 ;; Fixup tag positioning
9287 (org-todo-trigger-tag-changes state)
9288 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
9289 (when org-provide-todo-statistics
9290 (org-update-parent-todo-statistics))
9291 (run-hooks 'org-after-todo-state-change-hook)
9292 (if (and arg (not (member state org-done-keywords)))
9293 (setq head (org-get-todo-sequence-head state)))
9294 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9295 ;; Do we need to trigger a repeat?
9296 (when now-done-p
9297 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
9298 ;; This is for the agenda, take a snapshot of the headline.
9299 (save-match-data
9300 (setq org-agenda-headline-snapshot-before-repeat
9301 (org-get-heading))))
9302 (org-auto-repeat-maybe state))
9303 ;; Fixup cursor location if close to the keyword
9304 (if (and (outline-on-heading-p)
9305 (not (bolp))
9306 (save-excursion (beginning-of-line 1)
9307 (looking-at org-todo-line-regexp))
9308 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9309 (progn
9310 (goto-char (or (match-end 2) (match-end 1)))
9311 (and (looking-at " ") (just-one-space))))
9312 (when org-trigger-hook
9313 (save-excursion
9314 (run-hook-with-args 'org-trigger-hook change-plist))))))))
9316 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
9317 "Block turning an entry into a TODO, using the hierarchy.
9318 This checks whether the current task should be blocked from state
9319 changes. Such blocking occurs when:
9321 1. The task has children which are not all in a completed state.
9323 2. A task has a parent with the property :ORDERED:, and there
9324 are siblings prior to the current task with incomplete
9325 status.
9327 3. The parent of the task is blocked because it has siblings that should
9328 be done first, or is child of a block grandparent TODO entry."
9330 (catch 'dont-block
9331 ;; If this is not a todo state change, or if this entry is already DONE,
9332 ;; do not block
9333 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9334 (member (plist-get change-plist :from)
9335 (cons 'done org-done-keywords))
9336 (member (plist-get change-plist :to)
9337 (cons 'todo org-not-done-keywords)))
9338 (throw 'dont-block t))
9339 ;; If this task has children, and any are undone, it's blocked
9340 (save-excursion
9341 (org-back-to-heading t)
9342 (let ((this-level (funcall outline-level)))
9343 (outline-next-heading)
9344 (let ((child-level (funcall outline-level)))
9345 (while (and (not (eobp))
9346 (> child-level this-level))
9347 ;; this todo has children, check whether they are all
9348 ;; completed
9349 (if (and (not (org-entry-is-done-p))
9350 (org-entry-is-todo-p))
9351 (throw 'dont-block nil))
9352 (outline-next-heading)
9353 (setq child-level (funcall outline-level))))))
9354 ;; Otherwise, if the task's parent has the :ORDERED: property, and
9355 ;; any previous siblings are undone, it's blocked
9356 (save-excursion
9357 (org-back-to-heading t)
9358 (let* ((pos (point))
9359 (parent-pos (and (org-up-heading-safe) (point))))
9360 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9361 (when (and (org-entry-get (point) "ORDERED")
9362 (forward-line 1)
9363 (re-search-forward org-not-done-heading-regexp pos t))
9364 (throw 'dont-block nil)) ; block, there is an older sibling not done.
9365 ;; Search further up the hierarchy, to see if an anchestor is blocked
9366 (while t
9367 (goto-char parent-pos)
9368 (if (not (looking-at org-not-done-heading-regexp))
9369 (throw 'dont-block t)) ; do not block, parent is not a TODO
9370 (setq pos (point))
9371 (setq parent-pos (and (org-up-heading-safe) (point)))
9372 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9373 (when (and (org-entry-get (point) "ORDERED")
9374 (forward-line 1)
9375 (re-search-forward org-not-done-heading-regexp pos t))
9376 (throw 'dont-block nil))))))) ; block, older sibling not done.
9378 (defcustom org-track-ordered-property-with-tag nil
9379 "Should the ORDERED property also be shown as a tag?
9380 The ORDERED property decides if an entry should require subtasks to be
9381 completed in sequence. Since a property is not very visible, setting
9382 this option means that toggling the ORDERED property with the command
9383 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
9384 not relevant for the behavior, but it makes things more visible.
9386 Note that toggling the tag with tags commands will not change the property
9387 and therefore not influence behavior!
9389 This can be t, meaning the tag ORDERED should be used, It can also be a
9390 string to select a different tag for this task."
9391 :group 'org-todo
9392 :type '(choice
9393 (const :tag "No tracking" nil)
9394 (const :tag "Track with ORDERED tag" t)
9395 (string :tag "Use other tag")))
9397 (defun org-toggle-ordered-property ()
9398 "Toggle the ORDERED property of the current entry.
9399 For better visibility, you can track the value of this property with a tag.
9400 See variable `org-track-ordered-property-with-tag'."
9401 (interactive)
9402 (let* ((t1 org-track-ordered-property-with-tag)
9403 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
9404 (save-excursion
9405 (org-back-to-heading)
9406 (if (org-entry-get nil "ORDERED")
9407 (progn
9408 (org-delete-property "ORDERED")
9409 (and tag (org-toggle-tag tag 'off))
9410 (message "Subtasks can be completed in arbitrary order"))
9411 (org-entry-put nil "ORDERED" "t")
9412 (and tag (org-toggle-tag tag 'on))
9413 (message "Subtasks must be completed in sequence")))))
9415 (defvar org-blocked-by-checkboxes) ; dynamically scoped
9416 (defun org-block-todo-from-checkboxes (change-plist)
9417 "Block turning an entry into a TODO, using checkboxes.
9418 This checks whether the current task should be blocked from state
9419 changes because there are uncheckd boxes in this entry."
9420 (catch 'dont-block
9421 ;; If this is not a todo state change, or if this entry is already DONE,
9422 ;; do not block
9423 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9424 (member (plist-get change-plist :from)
9425 (cons 'done org-done-keywords))
9426 (member (plist-get change-plist :to)
9427 (cons 'todo org-not-done-keywords)))
9428 (throw 'dont-block t))
9429 ;; If this task has checkboxes that are not checked, it's blocked
9430 (save-excursion
9431 (org-back-to-heading t)
9432 (let ((beg (point)) end)
9433 (outline-next-heading)
9434 (setq end (point))
9435 (goto-char beg)
9436 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
9437 end t)
9438 (progn
9439 (if (boundp 'org-blocked-by-checkboxes)
9440 (setq org-blocked-by-checkboxes t))
9441 (throw 'dont-block nil)))))
9442 t)) ; do not block
9444 (defun org-update-parent-todo-statistics ()
9445 "Update any statistics cookie in the parent of the current headline."
9446 (interactive)
9447 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
9448 level (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
9449 (catch 'exit
9450 (save-excursion
9451 (setq level (org-up-heading-safe))
9452 (unless (and level
9453 (not (equal (downcase
9454 (or (org-entry-get
9455 nil "COOKIE_DATA")
9456 ""))
9457 "checkbox")))
9458 (throw 'exit nil))
9459 (while (re-search-forward box-re (point-at-eol) t)
9460 (setq cnt-all 0 cnt-done 0 cookie-present t)
9461 (setq is-percent (match-end 2))
9462 (save-match-data
9463 (unless (outline-next-heading) (throw 'exit nil))
9464 (while (looking-at org-todo-line-regexp)
9465 (setq kwd (match-string 2))
9466 (and kwd (setq cnt-all (1+ cnt-all)))
9467 (and (member kwd org-done-keywords)
9468 (setq cnt-done (1+ cnt-done)))
9469 (condition-case nil
9470 (org-forward-same-level 1)
9471 (error (end-of-line 1)))))
9472 (replace-match
9473 (if is-percent
9474 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
9475 (format "[%d/%d]" cnt-done cnt-all))))
9476 (when cookie-present
9477 (run-hook-with-args 'org-after-todo-statistics-hook
9478 cnt-done (- cnt-all cnt-done)))))
9479 (run-hooks 'org-todo-statistics-hook)))
9481 (defvar org-after-todo-statistics-hook nil
9482 "Hook that is called after a TODO statistics cookie has been updated.
9483 Each function is called with two arguments: the number of not-done entries
9484 and the number of done entries.
9486 For example, the following function, when added to this hook, will switch
9487 an entry to DONE when all children are done, and back to TODO when new
9488 entries are set to a TODO status. Note that this hook is only called
9489 when there is a statistics cookie in the headline!
9491 (defun org-summary-todo (n-done n-not-done)
9492 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
9493 (let (org-log-done org-log-states) ; turn off logging
9494 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
9497 (defvar org-todo-statistics-hook nil
9498 "Hook that is run whenever Org thinks TODO statistics should be updated.
9499 This hook runs even if there is no statisics cookie present, in which case
9500 `org-after-todo-statistics-hook' would not run.")
9502 (defun org-todo-trigger-tag-changes (state)
9503 "Apply the changes defined in `org-todo-state-tags-triggers'."
9504 (let ((l org-todo-state-tags-triggers)
9505 changes)
9506 (when (or (not state) (equal state ""))
9507 (setq changes (append changes (cdr (assoc "" l)))))
9508 (when (and (stringp state) (> (length state) 0))
9509 (setq changes (append changes (cdr (assoc state l)))))
9510 (when (member state org-not-done-keywords)
9511 (setq changes (append changes (cdr (assoc 'todo l)))))
9512 (when (member state org-done-keywords)
9513 (setq changes (append changes (cdr (assoc 'done l)))))
9514 (dolist (c changes)
9515 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
9517 (defun org-local-logging (value)
9518 "Get logging settings from a property VALUE."
9519 (let* (words w a)
9520 ;; directly set the variables, they are already local.
9521 (setq org-log-done nil
9522 org-log-repeat nil
9523 org-todo-log-states nil)
9524 (setq words (org-split-string value))
9525 (while (setq w (pop words))
9526 (cond
9527 ((setq a (assoc w org-startup-options))
9528 (and (member (nth 1 a) '(org-log-done org-log-repeat))
9529 (set (nth 1 a) (nth 2 a))))
9530 ((setq a (org-extract-log-state-settings w))
9531 (and (member (car a) org-todo-keywords-1)
9532 (push a org-todo-log-states)))))))
9534 (defun org-get-todo-sequence-head (kwd)
9535 "Return the head of the TODO sequence to which KWD belongs.
9536 If KWD is not set, check if there is a text property remembering the
9537 right sequence."
9538 (let (p)
9539 (cond
9540 ((not kwd)
9541 (or (get-text-property (point-at-bol) 'org-todo-head)
9542 (progn
9543 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
9544 nil (point-at-eol)))
9545 (get-text-property p 'org-todo-head))))
9546 ((not (member kwd org-todo-keywords-1))
9547 (car org-todo-keywords-1))
9548 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
9550 (defun org-fast-todo-selection ()
9551 "Fast TODO keyword selection with single keys.
9552 Returns the new TODO keyword, or nil if no state change should occur."
9553 (let* ((fulltable org-todo-key-alist)
9554 (done-keywords org-done-keywords) ;; needed for the faces.
9555 (maxlen (apply 'max (mapcar
9556 (lambda (x)
9557 (if (stringp (car x)) (string-width (car x)) 0))
9558 fulltable)))
9559 (expert nil)
9560 (fwidth (+ maxlen 3 1 3))
9561 (ncol (/ (- (window-width) 4) fwidth))
9562 tg cnt e c tbl
9563 groups ingroup)
9564 (save-excursion
9565 (save-window-excursion
9566 (if expert
9567 (set-buffer (get-buffer-create " *Org todo*"))
9568 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
9569 (erase-buffer)
9570 (org-set-local 'org-done-keywords done-keywords)
9571 (setq tbl fulltable cnt 0)
9572 (while (setq e (pop tbl))
9573 (cond
9574 ((equal e '(:startgroup))
9575 (push '() groups) (setq ingroup t)
9576 (when (not (= cnt 0))
9577 (setq cnt 0)
9578 (insert "\n"))
9579 (insert "{ "))
9580 ((equal e '(:endgroup))
9581 (setq ingroup nil cnt 0)
9582 (insert "}\n"))
9583 ((equal e '(:newline))
9584 (when (not (= cnt 0))
9585 (setq cnt 0)
9586 (insert "\n")
9587 (setq e (car tbl))
9588 (while (equal (car tbl) '(:newline))
9589 (insert "\n")
9590 (setq tbl (cdr tbl)))))
9592 (setq tg (car e) c (cdr e))
9593 (if ingroup (push tg (car groups)))
9594 (setq tg (org-add-props tg nil 'face
9595 (org-get-todo-face tg)))
9596 (if (and (= cnt 0) (not ingroup)) (insert " "))
9597 (insert "[" c "] " tg (make-string
9598 (- fwidth 4 (length tg)) ?\ ))
9599 (when (= (setq cnt (1+ cnt)) ncol)
9600 (insert "\n")
9601 (if ingroup (insert " "))
9602 (setq cnt 0)))))
9603 (insert "\n")
9604 (goto-char (point-min))
9605 (if (not expert) (org-fit-window-to-buffer))
9606 (message "[a-z..]:Set [SPC]:clear")
9607 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9608 (cond
9609 ((or (= c ?\C-g)
9610 (and (= c ?q) (not (rassoc c fulltable))))
9611 (setq quit-flag t))
9612 ((= c ?\ ) nil)
9613 ((setq e (rassoc c fulltable) tg (car e))
9615 (t (setq quit-flag t)))))))
9617 (defun org-entry-is-todo-p ()
9618 (member (org-get-todo-state) org-not-done-keywords))
9620 (defun org-entry-is-done-p ()
9621 (member (org-get-todo-state) org-done-keywords))
9623 (defun org-get-todo-state ()
9624 (save-excursion
9625 (org-back-to-heading t)
9626 (and (looking-at org-todo-line-regexp)
9627 (match-end 2)
9628 (match-string 2))))
9630 (defun org-at-date-range-p (&optional inactive-ok)
9631 "Is the cursor inside a date range?"
9632 (interactive)
9633 (save-excursion
9634 (catch 'exit
9635 (let ((pos (point)))
9636 (skip-chars-backward "^[<\r\n")
9637 (skip-chars-backward "<[")
9638 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9639 (>= (match-end 0) pos)
9640 (throw 'exit t))
9641 (skip-chars-backward "^<[\r\n")
9642 (skip-chars-backward "<[")
9643 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9644 (>= (match-end 0) pos)
9645 (throw 'exit t)))
9646 nil)))
9648 (defun org-get-repeat ()
9649 "Check if there is a deadline/schedule with repeater in this entry."
9650 (save-match-data
9651 (save-excursion
9652 (org-back-to-heading t)
9653 (if (re-search-forward
9654 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9655 (match-string 1)))))
9657 (defvar org-last-changed-timestamp)
9658 (defvar org-last-inserted-timestamp)
9659 (defvar org-log-post-message)
9660 (defvar org-log-note-purpose)
9661 (defvar org-log-note-how)
9662 (defvar org-log-note-extra)
9663 (defun org-auto-repeat-maybe (done-word)
9664 "Check if the current headline contains a repeated deadline/schedule.
9665 If yes, set TODO state back to what it was and change the base date
9666 of repeating deadline/scheduled time stamps to new date.
9667 This function is run automatically after each state change to a DONE state."
9668 ;; last-state is dynamically scoped into this function
9669 (let* ((repeat (org-get-repeat))
9670 (aa (assoc last-state org-todo-kwd-alist))
9671 (interpret (nth 1 aa))
9672 (head (nth 2 aa))
9673 (whata '(("d" . day) ("m" . month) ("y" . year)))
9674 (msg "Entry repeats: ")
9675 (org-log-done nil)
9676 (org-todo-log-states nil)
9677 (nshiftmax 10) (nshift 0)
9678 re type n what ts time)
9679 (when repeat
9680 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9681 (org-todo (if (eq interpret 'type) last-state head))
9682 (when org-log-repeat
9683 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9684 (memq 'org-add-log-note post-command-hook))
9685 ;; OK, we are already setup for some record
9686 (if (eq org-log-repeat 'note)
9687 ;; make sure we take a note, not only a time stamp
9688 (setq org-log-note-how 'note))
9689 ;; Set up for taking a record
9690 (org-add-log-setup 'state (or done-word (car org-done-keywords))
9691 last-state
9692 'findpos org-log-repeat)))
9693 (org-back-to-heading t)
9694 (org-add-planning-info nil nil 'closed)
9695 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9696 org-deadline-time-regexp "\\)\\|\\("
9697 org-ts-regexp "\\)"))
9698 (while (re-search-forward
9699 re (save-excursion (outline-next-heading) (point)) t)
9700 (setq type (if (match-end 1) org-scheduled-string
9701 (if (match-end 3) org-deadline-string "Plain:"))
9702 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
9703 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
9704 (setq n (string-to-number (match-string 2 ts))
9705 what (match-string 3 ts))
9706 (if (equal what "w") (setq n (* n 7) what "d"))
9707 ;; Preparation, see if we need to modify the start date for the change
9708 (when (match-end 1)
9709 (setq time (save-match-data (org-time-string-to-time ts)))
9710 (cond
9711 ((equal (match-string 1 ts) ".")
9712 ;; Shift starting date to today
9713 (org-timestamp-change
9714 (- (time-to-days (current-time)) (time-to-days time))
9715 'day))
9716 ((equal (match-string 1 ts) "+")
9717 (while (or (= nshift 0)
9718 (<= (time-to-days time) (time-to-days (current-time))))
9719 (when (= (incf nshift) nshiftmax)
9720 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
9721 (error "Abort")))
9722 (org-timestamp-change n (cdr (assoc what whata)))
9723 (org-at-timestamp-p t)
9724 (setq ts (match-string 1))
9725 (setq time (save-match-data (org-time-string-to-time ts))))
9726 (org-timestamp-change (- n) (cdr (assoc what whata)))
9727 ;; rematch, so that we have everything in place for the real shift
9728 (org-at-timestamp-p t)
9729 (setq ts (match-string 1))
9730 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
9731 (org-timestamp-change n (cdr (assoc what whata)))
9732 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
9733 (setq org-log-post-message msg)
9734 (message "%s" msg))))
9736 (defun org-show-todo-tree (arg)
9737 "Make a compact tree which shows all headlines marked with TODO.
9738 The tree will show the lines where the regexp matches, and all higher
9739 headlines above the match.
9740 With a \\[universal-argument] prefix, also show the DONE entries.
9741 With a numeric prefix N, construct a sparse tree for the Nth element
9742 of `org-todo-keywords-1'."
9743 (interactive "P")
9744 (let ((case-fold-search nil)
9745 (kwd-re
9746 (cond ((null arg) org-not-done-regexp)
9747 ((equal arg '(4))
9748 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
9749 (mapcar 'list org-todo-keywords-1))))
9750 (concat "\\("
9751 (mapconcat 'identity (org-split-string kwd "|") "\\|")
9752 "\\)\\>")))
9753 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
9754 (regexp-quote (nth (1- (prefix-numeric-value arg))
9755 org-todo-keywords-1)))
9756 (t (error "Invalid prefix argument: %s" arg)))))
9757 (message "%d TODO entries found"
9758 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
9760 (defun org-deadline (&optional remove time)
9761 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
9762 With argument REMOVE, remove any deadline from the item.
9763 When TIME is set, it should be an internal time specification, and the
9764 scheduling will use the corresponding date."
9765 (interactive "P")
9766 (if remove
9767 (progn
9768 (org-remove-timestamp-with-keyword org-deadline-string)
9769 (message "Item no longer has a deadline."))
9770 (if (org-get-repeat)
9771 (error "Cannot change deadline on task with repeater, please do that by hand")
9772 (org-add-planning-info 'deadline time 'closed)
9773 (message "Deadline on %s" org-last-inserted-timestamp))))
9775 (defun org-schedule (&optional remove time)
9776 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
9777 With argument REMOVE, remove any scheduling date from the item.
9778 When TIME is set, it should be an internal time specification, and the
9779 scheduling will use the corresponding date."
9780 (interactive "P")
9781 (if remove
9782 (progn
9783 (org-remove-timestamp-with-keyword org-scheduled-string)
9784 (message "Item is no longer scheduled."))
9785 (if (org-get-repeat)
9786 (error "Cannot reschedule task with repeater, please do that by hand")
9787 (org-add-planning-info 'scheduled time 'closed)
9788 (message "Scheduled to %s" org-last-inserted-timestamp))))
9790 (defun org-get-scheduled-time (pom &optional inherit)
9791 "Get the scheduled time as a time tuple, of a format suitable
9792 for calling org-schedule with, or if there is no scheduling,
9793 returns nil."
9794 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
9795 (when time
9796 (apply 'encode-time (org-parse-time-string time)))))
9798 (defun org-get-deadline-time (pom &optional inherit)
9799 "Get the deadine as a time tuple, of a format suitable for
9800 calling org-deadlin with, or if there is no scheduling, returns
9801 nil."
9802 (let ((time (org-entry-get pom "DEADLINE" inherit)))
9803 (when time
9804 (apply 'encode-time (org-parse-time-string time)))))
9806 (defun org-remove-timestamp-with-keyword (keyword)
9807 "Remove all time stamps with KEYWORD in the current entry."
9808 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
9809 beg)
9810 (save-excursion
9811 (org-back-to-heading t)
9812 (setq beg (point))
9813 (org-end-of-subtree t t)
9814 (while (re-search-backward re beg t)
9815 (replace-match "")
9816 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9817 (equal (char-before) ?\ ))
9818 (backward-delete-char 1)
9819 (if (string-match "^[ \t]*$" (buffer-substring
9820 (point-at-bol) (point-at-eol)))
9821 (delete-region (point-at-bol)
9822 (min (point-max) (1+ (point-at-eol))))))))))
9824 (defun org-add-planning-info (what &optional time &rest remove)
9825 "Insert new timestamp with keyword in the line directly after the headline.
9826 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9827 If non is given, the user is prompted for a date.
9828 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9829 be removed."
9830 (interactive)
9831 (let (org-time-was-given org-end-time-was-given ts
9832 end default-time default-input)
9834 (catch 'exit
9835 (when (and (not time) (memq what '(scheduled deadline)))
9836 ;; Try to get a default date/time from existing timestamp
9837 (save-excursion
9838 (org-back-to-heading t)
9839 (setq end (save-excursion (outline-next-heading) (point)))
9840 (when (re-search-forward (if (eq what 'scheduled)
9841 org-scheduled-time-regexp
9842 org-deadline-time-regexp)
9843 end t)
9844 (setq ts (match-string 1)
9845 default-time
9846 (apply 'encode-time (org-parse-time-string ts))
9847 default-input (and ts (org-get-compact-tod ts))))))
9848 (when what
9849 ;; If necessary, get the time from the user
9850 (setq time (or time (org-read-date nil 'to-time nil nil
9851 default-time default-input))))
9853 (when (and org-insert-labeled-timestamps-at-point
9854 (member what '(scheduled deadline)))
9855 (insert
9856 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9857 (org-insert-time-stamp time org-time-was-given
9858 nil nil nil (list org-end-time-was-given))
9859 (setq what nil))
9860 (save-excursion
9861 (save-restriction
9862 (let (col list elt ts buffer-invisibility-spec)
9863 (org-back-to-heading t)
9864 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9865 (goto-char (match-end 1))
9866 (setq col (current-column))
9867 (goto-char (match-end 0))
9868 (if (eobp) (insert "\n") (forward-char 1))
9869 (when (and (not what)
9870 (not (looking-at
9871 (concat "[ \t]*"
9872 org-keyword-time-not-clock-regexp))))
9873 ;; Nothing to add, nothing to remove...... :-)
9874 (throw 'exit nil))
9875 (if (and (not (looking-at outline-regexp))
9876 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9877 "[^\r\n]*"))
9878 (not (equal (match-string 1) org-clock-string)))
9879 (narrow-to-region (match-beginning 0) (match-end 0))
9880 (insert-before-markers "\n")
9881 (backward-char 1)
9882 (narrow-to-region (point) (point))
9883 (and org-adapt-indentation (org-indent-to-column col)))
9884 ;; Check if we have to remove something.
9885 (setq list (cons what remove))
9886 (while list
9887 (setq elt (pop list))
9888 (goto-char (point-min))
9889 (when (or (and (eq elt 'scheduled)
9890 (re-search-forward org-scheduled-time-regexp nil t))
9891 (and (eq elt 'deadline)
9892 (re-search-forward org-deadline-time-regexp nil t))
9893 (and (eq elt 'closed)
9894 (re-search-forward org-closed-time-regexp nil t)))
9895 (replace-match "")
9896 (if (looking-at "--+<[^>]+>") (replace-match ""))
9897 (if (looking-at " +") (replace-match ""))))
9898 (goto-char (point-max))
9899 (when what
9900 (insert
9901 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9902 (cond ((eq what 'scheduled) org-scheduled-string)
9903 ((eq what 'deadline) org-deadline-string)
9904 ((eq what 'closed) org-closed-string))
9905 " ")
9906 (setq ts (org-insert-time-stamp
9907 time
9908 (or org-time-was-given
9909 (and (eq what 'closed) org-log-done-with-time))
9910 (eq what 'closed)
9911 nil nil (list org-end-time-was-given)))
9912 (end-of-line 1))
9913 (goto-char (point-min))
9914 (widen)
9915 (if (and (looking-at "[ \t]+\n")
9916 (equal (char-before) ?\n))
9917 (delete-region (1- (point)) (point-at-eol)))
9918 ts))))))
9920 (defvar org-log-note-marker (make-marker))
9921 (defvar org-log-note-purpose nil)
9922 (defvar org-log-note-state nil)
9923 (defvar org-log-note-previous-state nil)
9924 (defvar org-log-note-how nil)
9925 (defvar org-log-note-extra nil)
9926 (defvar org-log-note-window-configuration nil)
9927 (defvar org-log-note-return-to (make-marker))
9928 (defvar org-log-post-message nil
9929 "Message to be displayed after a log note has been stored.
9930 The auto-repeater uses this.")
9932 (defun org-add-note ()
9933 "Add a note to the current entry.
9934 This is done in the same way as adding a state change note."
9935 (interactive)
9936 (org-add-log-setup 'note nil nil 'findpos nil))
9938 (defvar org-property-end-re)
9939 (defun org-add-log-setup (&optional purpose state prev-state
9940 findpos how &optional extra)
9941 "Set up the post command hook to take a note.
9942 If this is about to TODO state change, the new state is expected in STATE.
9943 When FINDPOS is non-nil, find the correct position for the note in
9944 the current entry. If not, assume that it can be inserted at point.
9945 HOW is an indicator what kind of note should be created.
9946 EXTRA is additional text that will be inserted into the notes buffer."
9947 (let* ((org-log-into-drawer (org-log-into-drawer))
9948 (drawer (cond ((stringp org-log-into-drawer)
9949 org-log-into-drawer)
9950 (org-log-into-drawer "LOGBOOK")
9951 (t nil))))
9952 (save-restriction
9953 (save-excursion
9954 (when findpos
9955 (org-back-to-heading t)
9956 (narrow-to-region (point) (save-excursion
9957 (outline-next-heading) (point)))
9958 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9959 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9960 "[^\r\n]*\\)?"))
9961 (goto-char (match-end 0))
9962 (cond
9963 (drawer
9964 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
9965 nil t)
9966 (progn
9967 (goto-char (match-end 0))
9968 (or org-log-states-order-reversed
9969 (and (re-search-forward org-property-end-re nil t)
9970 (goto-char (1- (match-beginning 0))))))
9971 (insert "\n:" drawer ":\n:END:")
9972 (beginning-of-line 0)
9973 (org-indent-line-function)
9974 (beginning-of-line 2)
9975 (org-indent-line-function)
9976 (end-of-line 0)))
9977 ((and org-log-state-notes-insert-after-drawers
9978 (save-excursion
9979 (forward-line) (looking-at org-drawer-regexp)))
9980 (forward-line)
9981 (while (looking-at org-drawer-regexp)
9982 (goto-char (match-end 0))
9983 (re-search-forward org-property-end-re (point-max) t)
9984 (forward-line))
9985 (forward-line -1)))
9986 (unless org-log-states-order-reversed
9987 (and (= (char-after) ?\n) (forward-char 1))
9988 (org-skip-over-state-notes)
9989 (skip-chars-backward " \t\n\r")))
9990 (move-marker org-log-note-marker (point))
9991 (setq org-log-note-purpose purpose
9992 org-log-note-state state
9993 org-log-note-previous-state prev-state
9994 org-log-note-how how
9995 org-log-note-extra extra)
9996 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
9998 (defun org-skip-over-state-notes ()
9999 "Skip past the list of State notes in an entry."
10000 (if (looking-at "\n[ \t]*- State") (forward-char 1))
10001 (while (looking-at "[ \t]*- State")
10002 (condition-case nil
10003 (org-next-item)
10004 (error (org-end-of-item)))))
10006 (defun org-add-log-note (&optional purpose)
10007 "Pop up a window for taking a note, and add this note later at point."
10008 (remove-hook 'post-command-hook 'org-add-log-note)
10009 (setq org-log-note-window-configuration (current-window-configuration))
10010 (delete-other-windows)
10011 (move-marker org-log-note-return-to (point))
10012 (switch-to-buffer (marker-buffer org-log-note-marker))
10013 (goto-char org-log-note-marker)
10014 (org-switch-to-buffer-other-window "*Org Note*")
10015 (erase-buffer)
10016 (if (memq org-log-note-how '(time state))
10017 (let (current-prefix-arg) (org-store-log-note))
10018 (let ((org-inhibit-startup t)) (org-mode))
10019 (insert (format "# Insert note for %s.
10020 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10021 (cond
10022 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10023 ((eq org-log-note-purpose 'done) "closed todo item")
10024 ((eq org-log-note-purpose 'state)
10025 (format "state change from \"%s\" to \"%s\""
10026 (or org-log-note-previous-state "")
10027 (or org-log-note-state "")))
10028 ((eq org-log-note-purpose 'note)
10029 "this entry")
10030 (t (error "This should not happen")))))
10031 (if org-log-note-extra (insert org-log-note-extra))
10032 (org-set-local 'org-finish-function 'org-store-log-note)))
10034 (defvar org-note-abort nil) ; dynamically scoped
10035 (defun org-store-log-note ()
10036 "Finish taking a log note, and insert it to where it belongs."
10037 (let ((txt (buffer-string))
10038 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10039 lines ind)
10040 (kill-buffer (current-buffer))
10041 (while (string-match "\\`#.*\n[ \t\n]*" txt)
10042 (setq txt (replace-match "" t t txt)))
10043 (if (string-match "\\s-+\\'" txt)
10044 (setq txt (replace-match "" t t txt)))
10045 (setq lines (org-split-string txt "\n"))
10046 (when (and note (string-match "\\S-" note))
10047 (setq note
10048 (org-replace-escapes
10049 note
10050 (list (cons "%u" (user-login-name))
10051 (cons "%U" user-full-name)
10052 (cons "%t" (format-time-string
10053 (org-time-stamp-format 'long 'inactive)
10054 (current-time)))
10055 (cons "%s" (if org-log-note-state
10056 (concat "\"" org-log-note-state "\"")
10057 ""))
10058 (cons "%S" (if org-log-note-previous-state
10059 (concat "\"" org-log-note-previous-state "\"")
10060 "\"\"")))))
10061 (if lines (setq note (concat note " \\\\")))
10062 (push note lines))
10063 (when (or current-prefix-arg org-note-abort)
10064 (when org-log-into-drawer
10065 (org-remove-empty-drawer-at
10066 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
10067 org-log-note-marker))
10068 (setq lines nil))
10069 (when lines
10070 (save-excursion
10071 (set-buffer (marker-buffer org-log-note-marker))
10072 (save-excursion
10073 (goto-char org-log-note-marker)
10074 (move-marker org-log-note-marker nil)
10075 (end-of-line 1)
10076 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
10077 (insert "- " (pop lines))
10078 (org-indent-line-function)
10079 (beginning-of-line 1)
10080 (looking-at "[ \t]*")
10081 (setq ind (concat (match-string 0) " "))
10082 (end-of-line 1)
10083 (while lines (insert "\n" ind (pop lines)))
10084 (message "Note stored")
10085 (org-back-to-heading t)
10086 (org-cycle-hide-drawers 'children)))))
10087 (set-window-configuration org-log-note-window-configuration)
10088 (with-current-buffer (marker-buffer org-log-note-return-to)
10089 (goto-char org-log-note-return-to))
10090 (move-marker org-log-note-return-to nil)
10091 (and org-log-post-message (message "%s" org-log-post-message)))
10093 (defun org-remove-empty-drawer-at (drawer pos)
10094 "Remove an emptyr DARWER drawer at position POS.
10095 POS may also be a marker."
10096 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
10097 (save-excursion
10098 (save-restriction
10099 (widen)
10100 (goto-char pos)
10101 (if (org-in-regexp
10102 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
10103 (replace-match ""))))))
10105 (defun org-sparse-tree (&optional arg)
10106 "Create a sparse tree, prompt for the details.
10107 This command can create sparse trees. You first need to select the type
10108 of match used to create the tree:
10110 t Show entries with a specific TODO keyword.
10111 m Show entries selected by a tags/property match.
10112 p Enter a property name and its value (both with completion on existing
10113 names/values) and show entries with that property.
10114 r Show entries matching a regular expression.
10115 d Show deadlines due within `org-deadline-warning-days'.
10116 b Show deadlines and scheduled items before a date.
10117 a Show deadlines and scheduled items after a date."
10118 (interactive "P")
10119 (let (ans kwd value)
10120 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
10121 (setq ans (read-char-exclusive))
10122 (cond
10123 ((equal ans ?d)
10124 (call-interactively 'org-check-deadlines))
10125 ((equal ans ?b)
10126 (call-interactively 'org-check-before-date))
10127 ((equal ans ?a)
10128 (call-interactively 'org-check-after-date))
10129 ((equal ans ?t)
10130 (org-show-todo-tree '(4)))
10131 ((member ans '(?T ?m))
10132 (call-interactively 'org-match-sparse-tree))
10133 ((member ans '(?p ?P))
10134 (setq kwd (org-ido-completing-read "Property: "
10135 (mapcar 'list (org-buffer-property-keys))))
10136 (setq value (org-ido-completing-read "Value: "
10137 (mapcar 'list (org-property-values kwd))))
10138 (unless (string-match "\\`{.*}\\'" value)
10139 (setq value (concat "\"" value "\"")))
10140 (org-match-sparse-tree arg (concat kwd "=" value)))
10141 ((member ans '(?r ?R ?/))
10142 (call-interactively 'org-occur))
10143 (t (error "No such sparse tree command \"%c\"" ans)))))
10145 (defvar org-occur-highlights nil
10146 "List of overlays used for occur matches.")
10147 (make-variable-buffer-local 'org-occur-highlights)
10148 (defvar org-occur-parameters nil
10149 "Parameters of the active org-occur calls.
10150 This is a list, each call to org-occur pushes as cons cell,
10151 containing the regular expression and the callback, onto the list.
10152 The list can contain several entries if `org-occur' has been called
10153 several time with the KEEP-PREVIOUS argument. Otherwise, this list
10154 will only contain one set of parameters. When the highlights are
10155 removed (for example with `C-c C-c', or with the next edit (depending
10156 on `org-remove-highlights-with-change'), this variable is emptied
10157 as well.")
10158 (make-variable-buffer-local 'org-occur-parameters)
10160 (defun org-occur (regexp &optional keep-previous callback)
10161 "Make a compact tree which shows all matches of REGEXP.
10162 The tree will show the lines where the regexp matches, and all higher
10163 headlines above the match. It will also show the heading after the match,
10164 to make sure editing the matching entry is easy.
10165 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
10166 call to `org-occur' will be kept, to allow stacking of calls to this
10167 command.
10168 If CALLBACK is non-nil, it is a function which is called to confirm
10169 that the match should indeed be shown."
10170 (interactive "sRegexp: \nP")
10171 (unless keep-previous
10172 (org-remove-occur-highlights nil nil t))
10173 (push (cons regexp callback) org-occur-parameters)
10174 (let ((cnt 0))
10175 (save-excursion
10176 (goto-char (point-min))
10177 (if (or (not keep-previous) ; do not want to keep
10178 (not org-occur-highlights)) ; no previous matches
10179 ;; hide everything
10180 (org-overview))
10181 (while (re-search-forward regexp nil t)
10182 (when (or (not callback)
10183 (save-match-data (funcall callback)))
10184 (setq cnt (1+ cnt))
10185 (when org-highlight-sparse-tree-matches
10186 (org-highlight-new-match (match-beginning 0) (match-end 0)))
10187 (org-show-context 'occur-tree))))
10188 (when org-remove-highlights-with-change
10189 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10190 nil 'local))
10191 (unless org-sparse-tree-open-archived-trees
10192 (org-hide-archived-subtrees (point-min) (point-max)))
10193 (run-hooks 'org-occur-hook)
10194 (if (interactive-p)
10195 (message "%d match(es) for regexp %s" cnt regexp))
10196 cnt))
10198 (defun org-show-context (&optional key)
10199 "Make sure point and context and visible.
10200 How much context is shown depends upon the variables
10201 `org-show-hierarchy-above', `org-show-following-heading'. and
10202 `org-show-siblings'."
10203 (let ((heading-p (org-on-heading-p t))
10204 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
10205 (following-p (org-get-alist-option org-show-following-heading key))
10206 (entry-p (org-get-alist-option org-show-entry-below key))
10207 (siblings-p (org-get-alist-option org-show-siblings key)))
10208 (catch 'exit
10209 ;; Show heading or entry text
10210 (if (and heading-p (not entry-p))
10211 (org-flag-heading nil) ; only show the heading
10212 (and (or entry-p (org-invisible-p) (org-invisible-p2))
10213 (org-show-hidden-entry))) ; show entire entry
10214 (when following-p
10215 ;; Show next sibling, or heading below text
10216 (save-excursion
10217 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10218 (org-flag-heading nil))))
10219 (when siblings-p (org-show-siblings))
10220 (when hierarchy-p
10221 ;; show all higher headings, possibly with siblings
10222 (save-excursion
10223 (while (and (condition-case nil
10224 (progn (org-up-heading-all 1) t)
10225 (error nil))
10226 (not (bobp)))
10227 (org-flag-heading nil)
10228 (when siblings-p (org-show-siblings))))))))
10230 (defun org-reveal (&optional siblings)
10231 "Show current entry, hierarchy above it, and the following headline.
10232 This can be used to show a consistent set of context around locations
10233 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10234 not t for the search context.
10236 With optional argument SIBLINGS, on each level of the hierarchy all
10237 siblings are shown. This repairs the tree structure to what it would
10238 look like when opened with hierarchical calls to `org-cycle'."
10239 (interactive "P")
10240 (let ((org-show-hierarchy-above t)
10241 (org-show-following-heading t)
10242 (org-show-siblings (if siblings t org-show-siblings)))
10243 (org-show-context nil)))
10245 (defun org-highlight-new-match (beg end)
10246 "Highlight from BEG to END and mark the highlight is an occur headline."
10247 (let ((ov (org-make-overlay beg end)))
10248 (org-overlay-put ov 'face 'secondary-selection)
10249 (push ov org-occur-highlights)))
10251 (defun org-remove-occur-highlights (&optional beg end noremove)
10252 "Remove the occur highlights from the buffer.
10253 BEG and END are ignored. If NOREMOVE is nil, remove this function
10254 from the `before-change-functions' in the current buffer."
10255 (interactive)
10256 (unless org-inhibit-highlight-removal
10257 (mapc 'org-delete-overlay org-occur-highlights)
10258 (setq org-occur-highlights nil)
10259 (setq org-occur-parameters nil)
10260 (unless noremove
10261 (remove-hook 'before-change-functions
10262 'org-remove-occur-highlights 'local))))
10264 ;;;; Priorities
10266 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
10267 "Regular expression matching the priority indicator.")
10269 (defvar org-remove-priority-next-time nil)
10271 (defun org-priority-up ()
10272 "Increase the priority of the current item."
10273 (interactive)
10274 (org-priority 'up))
10276 (defun org-priority-down ()
10277 "Decrease the priority of the current item."
10278 (interactive)
10279 (org-priority 'down))
10281 (defun org-priority (&optional action)
10282 "Change the priority of an item by ARG.
10283 ACTION can be `set', `up', `down', or a character."
10284 (interactive)
10285 (setq action (or action 'set))
10286 (let (current new news have remove)
10287 (save-excursion
10288 (org-back-to-heading t)
10289 (if (looking-at org-priority-regexp)
10290 (setq current (string-to-char (match-string 2))
10291 have t)
10292 (setq current org-default-priority))
10293 (cond
10294 ((or (eq action 'set)
10295 (if (featurep 'xemacs) (characterp action) (integerp action)))
10296 (if (not (eq action 'set))
10297 (setq new action)
10298 (message "Priority %c-%c, SPC to remove: "
10299 org-highest-priority org-lowest-priority)
10300 (setq new (read-char-exclusive)))
10301 (if (and (= (upcase org-highest-priority) org-highest-priority)
10302 (= (upcase org-lowest-priority) org-lowest-priority))
10303 (setq new (upcase new)))
10304 (cond ((equal new ?\ ) (setq remove t))
10305 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
10306 (error "Priority must be between `%c' and `%c'"
10307 org-highest-priority org-lowest-priority))))
10308 ((eq action 'up)
10309 (if (and (not have) (eq last-command this-command))
10310 (setq new org-lowest-priority)
10311 (setq new (if (and org-priority-start-cycle-with-default (not have))
10312 org-default-priority (1- current)))))
10313 ((eq action 'down)
10314 (if (and (not have) (eq last-command this-command))
10315 (setq new org-highest-priority)
10316 (setq new (if (and org-priority-start-cycle-with-default (not have))
10317 org-default-priority (1+ current)))))
10318 (t (error "Invalid action")))
10319 (if (or (< (upcase new) org-highest-priority)
10320 (> (upcase new) org-lowest-priority))
10321 (setq remove t))
10322 (setq news (format "%c" new))
10323 (if have
10324 (if remove
10325 (replace-match "" t t nil 1)
10326 (replace-match news t t nil 2))
10327 (if remove
10328 (error "No priority cookie found in line")
10329 (let ((case-fold-search nil))
10330 (looking-at org-todo-line-regexp))
10331 (if (match-end 2)
10332 (progn
10333 (goto-char (match-end 2))
10334 (insert " [#" news "]"))
10335 (goto-char (match-beginning 3))
10336 (insert "[#" news "] ")))))
10337 (org-preserve-lc (org-set-tags nil 'align))
10338 (if remove
10339 (message "Priority removed")
10340 (message "Priority of current item set to %s" news))))
10343 (defun org-get-priority (s)
10344 "Find priority cookie and return priority."
10345 (save-match-data
10346 (if (not (string-match org-priority-regexp s))
10347 (* 1000 (- org-lowest-priority org-default-priority))
10348 (* 1000 (- org-lowest-priority
10349 (string-to-char (match-string 2 s)))))))
10351 ;;;; Tags
10353 (defvar org-agenda-archives-mode)
10354 (defvar org-map-continue-from nil
10355 "Position from where mapping should continue.
10356 Can be set byt the action argument to `org-scan-tag's and `org-map-entries'.")
10358 (defvar org-scanner-tags nil
10359 "The current tag list while the tags scanner is running.")
10360 (defvar org-trust-scanner-tags nil
10361 "Should `org-get-tags-at' use the tags fro the scanner.
10362 This is for internal dynamical scoping only.
10363 When this is non-nil, the function `org-get-tags-at' will return the value
10364 of `org-scanner-tags' instead of building the list by itself. This
10365 can lead to large speed-ups when the tags scanner is used in a file with
10366 many entries, and when the list of tags is retrieved, for example to
10367 obtain a list of properties. Building the tags list for each entry in such
10368 a file becomes an N^2 operation - but with this variable set, it scales
10369 as N.")
10371 (defun org-scan-tags (action matcher &optional todo-only)
10372 "Scan headline tags with inheritance and produce output ACTION.
10374 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
10375 or `agenda' to produce an entry list for an agenda view. It can also be
10376 a Lisp form or a function that should be called at each matched headline, in
10377 this case the return value is a list of all return values from these calls.
10379 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
10380 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
10381 only lines with a TODO keyword are included in the output."
10382 (require 'org-agenda)
10383 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
10384 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
10385 (org-re
10386 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
10387 (props (list 'face 'default
10388 'done-face 'org-agenda-done
10389 'undone-face 'default
10390 'mouse-face 'highlight
10391 'org-not-done-regexp org-not-done-regexp
10392 'org-todo-regexp org-todo-regexp
10393 'keymap org-agenda-keymap
10394 'help-echo
10395 (format "mouse-2 or RET jump to org file %s"
10396 (abbreviate-file-name
10397 (or (buffer-file-name (buffer-base-buffer))
10398 (buffer-name (buffer-base-buffer)))))))
10399 (case-fold-search nil)
10400 (org-map-continue-from nil)
10401 lspos tags tags-list
10402 (tags-alist (list (cons 0 org-file-tags)))
10403 (llast 0) rtn rtn1 level category i txt
10404 todo marker entry priority)
10405 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
10406 (setq action (list 'lambda nil action)))
10407 (save-excursion
10408 (goto-char (point-min))
10409 (when (eq action 'sparse-tree)
10410 (org-overview)
10411 (org-remove-occur-highlights))
10412 (while (re-search-forward re nil t)
10413 (catch :skip
10414 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
10415 tags (if (match-end 4) (org-match-string-no-properties 4)))
10416 (goto-char (setq lspos (match-beginning 0)))
10417 (setq level (org-reduced-level (funcall outline-level))
10418 category (org-get-category))
10419 (setq i llast llast level)
10420 ;; remove tag lists from same and sublevels
10421 (while (>= i level)
10422 (when (setq entry (assoc i tags-alist))
10423 (setq tags-alist (delete entry tags-alist)))
10424 (setq i (1- i)))
10425 ;; add the next tags
10426 (when tags
10427 (setq tags (org-split-string tags ":")
10428 tags-alist
10429 (cons (cons level tags) tags-alist)))
10430 ;; compile tags for current headline
10431 (setq tags-list
10432 (if org-use-tag-inheritance
10433 (apply 'append (mapcar 'cdr (reverse tags-alist)))
10434 tags)
10435 org-scanner-tags tags-list)
10436 (when org-use-tag-inheritance
10437 (setcdr (car tags-alist)
10438 (mapcar (lambda (x)
10439 (setq x (copy-sequence x))
10440 (org-add-prop-inherited x))
10441 (cdar tags-alist))))
10442 (when (and tags org-use-tag-inheritance
10443 (or (not (eq t org-use-tag-inheritance))
10444 org-tags-exclude-from-inheritance))
10445 ;; selective inheritance, remove uninherited ones
10446 (setcdr (car tags-alist)
10447 (org-remove-uniherited-tags (cdar tags-alist))))
10448 (when (and (or (not todo-only)
10449 (and (member todo org-not-done-keywords)
10450 (or (not org-agenda-tags-todo-honor-ignore-options)
10451 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
10452 (let ((case-fold-search t)) (eval matcher))
10454 (not (member org-archive-tag tags-list))
10455 ;; we have an archive tag, should we use this anyway?
10456 (or (not org-agenda-skip-archived-trees)
10457 (and (eq action 'agenda) org-agenda-archives-mode))))
10458 (unless (eq action 'sparse-tree) (org-agenda-skip))
10460 ;; select this headline
10462 (cond
10463 ((eq action 'sparse-tree)
10464 (and org-highlight-sparse-tree-matches
10465 (org-get-heading) (match-end 0)
10466 (org-highlight-new-match
10467 (match-beginning 0) (match-beginning 1)))
10468 (org-show-context 'tags-tree))
10469 ((eq action 'agenda)
10470 (setq txt (org-format-agenda-item
10472 (concat
10473 (if (eq org-tags-match-list-sublevels 'indented)
10474 (make-string (1- level) ?.) "")
10475 (org-get-heading))
10476 category
10477 tags-list
10479 priority (org-get-priority txt))
10480 (goto-char lspos)
10481 (setq marker (org-agenda-new-marker))
10482 (org-add-props txt props
10483 'org-marker marker 'org-hd-marker marker 'org-category category
10484 'todo-state todo
10485 'priority priority 'type "tagsmatch")
10486 (push txt rtn))
10487 ((functionp action)
10488 (setq org-map-continue-from nil)
10489 (save-excursion
10490 (setq rtn1 (funcall action))
10491 (push rtn1 rtn)))
10492 (t (error "Invalid action")))
10494 ;; if we are to skip sublevels, jump to end of subtree
10495 (unless org-tags-match-list-sublevels
10496 (org-end-of-subtree t)
10497 (backward-char 1))))
10498 ;; Get the correct position from where to continue
10499 (if org-map-continue-from
10500 (goto-char org-map-continue-from)
10501 (and (= (point) lspos) (end-of-line 1)))))
10502 (when (and (eq action 'sparse-tree)
10503 (not org-sparse-tree-open-archived-trees))
10504 (org-hide-archived-subtrees (point-min) (point-max)))
10505 (nreverse rtn)))
10507 (defun org-remove-uniherited-tags (tags)
10508 "Remove all tags that are not inherited from the list TAGS."
10509 (cond
10510 ((eq org-use-tag-inheritance t)
10511 (if org-tags-exclude-from-inheritance
10512 (org-delete-all org-tags-exclude-from-inheritance tags)
10513 tags))
10514 ((not org-use-tag-inheritance) nil)
10515 ((stringp org-use-tag-inheritance)
10516 (delq nil (mapcar
10517 (lambda (x)
10518 (if (and (string-match org-use-tag-inheritance x)
10519 (not (member x org-tags-exclude-from-inheritance)))
10520 x nil))
10521 tags)))
10522 ((listp org-use-tag-inheritance)
10523 (delq nil (mapcar
10524 (lambda (x)
10525 (if (member x org-use-tag-inheritance) x nil))
10526 tags)))))
10528 (defvar todo-only) ;; dynamically scoped
10530 (defun org-match-sparse-tree (&optional todo-only match)
10531 "Create a sparse tree according to tags string MATCH.
10532 MATCH can contain positive and negative selection of tags, like
10533 \"+WORK+URGENT-WITHBOSS\".
10534 If optional argument TODO-ONLY is non-nil, only select lines that are
10535 also TODO lines."
10536 (interactive "P")
10537 (org-prepare-agenda-buffers (list (current-buffer)))
10538 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
10540 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
10542 (defvar org-cached-props nil)
10543 (defun org-cached-entry-get (pom property)
10544 (if (or (eq t org-use-property-inheritance)
10545 (and (stringp org-use-property-inheritance)
10546 (string-match org-use-property-inheritance property))
10547 (and (listp org-use-property-inheritance)
10548 (member property org-use-property-inheritance)))
10549 ;; Caching is not possible, check it directly
10550 (org-entry-get pom property 'inherit)
10551 ;; Get all properties, so that we can do complicated checks easily
10552 (cdr (assoc property (or org-cached-props
10553 (setq org-cached-props
10554 (org-entry-properties pom)))))))
10556 (defun org-global-tags-completion-table (&optional files)
10557 "Return the list of all tags in all agenda buffer/files."
10558 (save-excursion
10559 (org-uniquify
10560 (delq nil
10561 (apply 'append
10562 (mapcar
10563 (lambda (file)
10564 (set-buffer (find-file-noselect file))
10565 (append (org-get-buffer-tags)
10566 (mapcar (lambda (x) (if (stringp (car-safe x))
10567 (list (car-safe x)) nil))
10568 org-tag-alist)))
10569 (if (and files (car files))
10570 files
10571 (org-agenda-files))))))))
10573 (defun org-make-tags-matcher (match)
10574 "Create the TAGS//TODO matcher form for the selection string MATCH."
10575 ;; todo-only is scoped dynamically into this function, and the function
10576 ;; may change it if the matcher asks for it.
10577 (unless match
10578 ;; Get a new match request, with completion
10579 (let ((org-last-tags-completion-table
10580 (org-global-tags-completion-table)))
10581 (setq match (org-completing-read-no-ido
10582 "Match: " 'org-tags-completion-function nil nil nil
10583 'org-tags-history))))
10585 ;; Parse the string and create a lisp form
10586 (let ((match0 match)
10587 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
10588 minus tag mm
10589 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
10590 orterms term orlist re-p str-p level-p level-op time-p
10591 prop-p pn pv po cat-p gv rest)
10592 (if (string-match "/+" match)
10593 ;; match contains also a todo-matching request
10594 (progn
10595 (setq tagsmatch (substring match 0 (match-beginning 0))
10596 todomatch (substring match (match-end 0)))
10597 (if (string-match "^!" todomatch)
10598 (setq todo-only t todomatch (substring todomatch 1)))
10599 (if (string-match "^\\s-*$" todomatch)
10600 (setq todomatch nil)))
10601 ;; only matching tags
10602 (setq tagsmatch match todomatch nil))
10604 ;; Make the tags matcher
10605 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10606 (setq tagsmatcher t)
10607 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10608 (while (setq term (pop orterms))
10609 (while (and (equal (substring term -1) "\\") orterms)
10610 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10611 (while (string-match re term)
10612 (setq rest (substring term (match-end 0))
10613 minus (and (match-end 1)
10614 (equal (match-string 1 term) "-"))
10615 tag (match-string 2 term)
10616 re-p (equal (string-to-char tag) ?{)
10617 level-p (match-end 4)
10618 prop-p (match-end 5)
10619 mm (cond
10620 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10621 (level-p
10622 (setq level-op (org-op-to-function (match-string 3 term)))
10623 `(,level-op level ,(string-to-number
10624 (match-string 4 term))))
10625 (prop-p
10626 (setq pn (match-string 5 term)
10627 po (match-string 6 term)
10628 pv (match-string 7 term)
10629 cat-p (equal pn "CATEGORY")
10630 re-p (equal (string-to-char pv) ?{)
10631 str-p (equal (string-to-char pv) ?\")
10632 time-p (save-match-data
10633 (string-match "^\"[[<].*[]>]\"$" pv))
10634 pv (if (or re-p str-p) (substring pv 1 -1) pv))
10635 (if time-p (setq pv (org-matcher-time pv)))
10636 (setq po (org-op-to-function po (if time-p 'time str-p)))
10637 (cond
10638 ((equal pn "CATEGORY")
10639 (setq gv '(get-text-property (point) 'org-category)))
10640 ((equal pn "TODO")
10641 (setq gv 'todo))
10643 (setq gv `(org-cached-entry-get nil ,pn))))
10644 (if re-p
10645 (if (eq po 'org<>)
10646 `(not (string-match ,pv (or ,gv "")))
10647 `(string-match ,pv (or ,gv "")))
10648 (if str-p
10649 `(,po (or ,gv "") ,pv)
10650 `(,po (string-to-number (or ,gv ""))
10651 ,(string-to-number pv) ))))
10652 (t `(member ,tag tags-list)))
10653 mm (if minus (list 'not mm) mm)
10654 term rest)
10655 (push mm tagsmatcher))
10656 (push (if (> (length tagsmatcher) 1)
10657 (cons 'and tagsmatcher)
10658 (car tagsmatcher))
10659 orlist)
10660 (setq tagsmatcher nil))
10661 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
10662 (setq tagsmatcher
10663 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
10664 ;; Make the todo matcher
10665 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10666 (setq todomatcher t)
10667 (setq orterms (org-split-string todomatch "|") orlist nil)
10668 (while (setq term (pop orterms))
10669 (while (string-match re term)
10670 (setq minus (and (match-end 1)
10671 (equal (match-string 1 term) "-"))
10672 kwd (match-string 2 term)
10673 re-p (equal (string-to-char kwd) ?{)
10674 term (substring term (match-end 0))
10675 mm (if re-p
10676 `(string-match ,(substring kwd 1 -1) todo)
10677 (list 'equal 'todo kwd))
10678 mm (if minus (list 'not mm) mm))
10679 (push mm todomatcher))
10680 (push (if (> (length todomatcher) 1)
10681 (cons 'and todomatcher)
10682 (car todomatcher))
10683 orlist)
10684 (setq todomatcher nil))
10685 (setq todomatcher (if (> (length orlist) 1)
10686 (cons 'or orlist) (car orlist))))
10688 ;; Return the string and lisp forms of the matcher
10689 (setq matcher (if todomatcher
10690 (list 'and tagsmatcher todomatcher)
10691 tagsmatcher))
10692 (cons match0 matcher)))
10694 (defun org-op-to-function (op &optional stringp)
10695 "Turn an operator into the appropriate function."
10696 (setq op
10697 (cond
10698 ((equal op "<" ) '(< string< org-time<))
10699 ((equal op ">" ) '(> org-string> org-time>))
10700 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
10701 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
10702 ((member op '("=" "==")) '(= string= org-time=))
10703 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
10704 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
10706 (defun org<> (a b) (not (= a b)))
10707 (defun org-string<= (a b) (or (string= a b) (string< a b)))
10708 (defun org-string>= (a b) (not (string< a b)))
10709 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
10710 (defun org-string<> (a b) (not (string= a b)))
10711 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
10712 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
10713 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
10714 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
10715 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
10716 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
10717 (defun org-2ft (s)
10718 "Convert S to a floating point time.
10719 If S is already a number, just return it. If it is a string, parse
10720 it as a time string and apply `float-time' to it. If S is nil, just return 0."
10721 (cond
10722 ((numberp s) s)
10723 ((stringp s)
10724 (condition-case nil
10725 (float-time (apply 'encode-time (org-parse-time-string s)))
10726 (error 0.)))
10727 (t 0.)))
10729 (defun org-time-today ()
10730 "Time in seconds today at 0:00.
10731 Returns the float number of seconds since the beginning of the
10732 epoch to the beginning of today (00:00)."
10733 (float-time (apply 'encode-time
10734 (append '(0 0 0) (nthcdr 3 (decode-time))))))
10736 (defun org-matcher-time (s)
10737 "Interpret a time comparison value."
10738 (save-match-data
10739 (cond
10740 ((string= s "<now>") (float-time))
10741 ((string= s "<today>") (org-time-today))
10742 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
10743 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
10744 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
10745 (+ (org-time-today)
10746 (* (string-to-number (match-string 1 s))
10747 (cdr (assoc (match-string 2 s)
10748 '(("d" . 86400.0) ("w" . 604800.0)
10749 ("m" . 2678400.0) ("y" . 31557600.0)))))))
10750 (t (org-2ft s)))))
10752 (defun org-match-any-p (re list)
10753 "Does re match any element of list?"
10754 (setq list (mapcar (lambda (x) (string-match re x)) list))
10755 (delq nil list))
10757 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
10758 (defvar org-tags-overlay (org-make-overlay 1 1))
10759 (org-detach-overlay org-tags-overlay)
10761 (defun org-get-local-tags-at (&optional pos)
10762 "Get a list of tags defined in the current headline."
10763 (org-get-tags-at pos 'local))
10765 (defun org-get-local-tags ()
10766 "Get a list of tags defined in the current headline."
10767 (org-get-tags-at nil 'local))
10769 (defun org-get-tags-at (&optional pos local)
10770 "Get a list of all headline tags applicable at POS.
10771 POS defaults to point. If tags are inherited, the list contains
10772 the targets in the same sequence as the headlines appear, i.e.
10773 the tags of the current headline come last.
10774 When LOCAL is non-nil, only return tags from the current headline,
10775 ignore inherited ones."
10776 (interactive)
10777 (if (and org-trust-scanner-tags
10778 (or (not pos) (equal pos (point)))
10779 (not local))
10780 org-scanner-tags
10781 (let (tags ltags lastpos parent)
10782 (save-excursion
10783 (save-restriction
10784 (widen)
10785 (goto-char (or pos (point)))
10786 (save-match-data
10787 (catch 'done
10788 (condition-case nil
10789 (progn
10790 (org-back-to-heading t)
10791 (while (not (equal lastpos (point)))
10792 (setq lastpos (point))
10793 (when (looking-at
10794 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
10795 (setq ltags (org-split-string
10796 (org-match-string-no-properties 1) ":"))
10797 (when parent
10798 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
10799 (setq tags (append
10800 (if parent
10801 (org-remove-uniherited-tags ltags)
10802 ltags)
10803 tags)))
10804 (or org-use-tag-inheritance (throw 'done t))
10805 (if local (throw 'done t))
10806 (or (org-up-heading-safe) (error nil))
10807 (setq parent t)))
10808 (error nil)))))
10809 (append (org-remove-uniherited-tags org-file-tags) tags)))))
10811 (defun org-add-prop-inherited (s)
10812 (add-text-properties 0 (length s) '(inherited t) s)
10815 (defun org-toggle-tag (tag &optional onoff)
10816 "Toggle the tag TAG for the current line.
10817 If ONOFF is `on' or `off', don't toggle but set to this state."
10818 (let (res current)
10819 (save-excursion
10820 (org-back-to-heading t)
10821 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
10822 (point-at-eol) t)
10823 (progn
10824 (setq current (match-string 1))
10825 (replace-match ""))
10826 (setq current ""))
10827 (setq current (nreverse (org-split-string current ":")))
10828 (cond
10829 ((eq onoff 'on)
10830 (setq res t)
10831 (or (member tag current) (push tag current)))
10832 ((eq onoff 'off)
10833 (or (not (member tag current)) (setq current (delete tag current))))
10834 (t (if (member tag current)
10835 (setq current (delete tag current))
10836 (setq res t)
10837 (push tag current))))
10838 (end-of-line 1)
10839 (if current
10840 (progn
10841 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
10842 (org-set-tags nil t))
10843 (delete-horizontal-space))
10844 (run-hooks 'org-after-tags-change-hook))
10845 res))
10847 (defun org-align-tags-here (to-col)
10848 ;; Assumes that this is a headline
10849 (let ((pos (point)) (col (current-column)) ncol tags-l p)
10850 (beginning-of-line 1)
10851 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10852 (< pos (match-beginning 2)))
10853 (progn
10854 (setq tags-l (- (match-end 2) (match-beginning 2)))
10855 (goto-char (match-beginning 1))
10856 (insert " ")
10857 (delete-region (point) (1+ (match-beginning 2)))
10858 (setq ncol (max (1+ (current-column))
10859 (1+ col)
10860 (if (> to-col 0)
10861 to-col
10862 (- (abs to-col) tags-l))))
10863 (setq p (point))
10864 (insert (make-string (- ncol (current-column)) ?\ ))
10865 (setq ncol (current-column))
10866 (when indent-tabs-mode (tabify p (point-at-eol)))
10867 (org-move-to-column (min ncol col) t))
10868 (goto-char pos))))
10870 (defun org-set-tags-command (&optional arg just-align)
10871 "Call the set-tags command for the current entry."
10872 (interactive "P")
10873 (if (org-on-heading-p)
10874 (org-set-tags arg just-align)
10875 (save-excursion
10876 (org-back-to-heading t)
10877 (org-set-tags arg just-align))))
10879 (defun org-set-tags (&optional arg just-align)
10880 "Set the tags for the current headline.
10881 With prefix ARG, realign all tags in headings in the current buffer."
10882 (interactive "P")
10883 (let* ((re (concat "^" outline-regexp))
10884 (current (org-get-tags-string))
10885 (col (current-column))
10886 (org-setting-tags t)
10887 table current-tags inherited-tags ; computed below when needed
10888 tags p0 c0 c1 rpl)
10889 (if arg
10890 (save-excursion
10891 (goto-char (point-min))
10892 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
10893 (while (re-search-forward re nil t)
10894 (org-set-tags nil t)
10895 (end-of-line 1)))
10896 (message "All tags realigned to column %d" org-tags-column))
10897 (if just-align
10898 (setq tags current)
10899 ;; Get a new set of tags from the user
10900 (save-excursion
10901 (setq table (append org-tag-persistent-alist
10902 (or org-tag-alist (org-get-buffer-tags)))
10903 org-last-tags-completion-table table
10904 current-tags (org-split-string current ":")
10905 inherited-tags (nreverse
10906 (nthcdr (length current-tags)
10907 (nreverse (org-get-tags-at))))
10908 tags
10909 (if (or (eq t org-use-fast-tag-selection)
10910 (and org-use-fast-tag-selection
10911 (delq nil (mapcar 'cdr table))))
10912 (org-fast-tag-selection
10913 current-tags inherited-tags table
10914 (if org-fast-tag-selection-include-todo org-todo-key-alist))
10915 (let ((org-add-colon-after-tag-completion t))
10916 (org-trim
10917 (org-without-partial-completion
10918 (org-ido-completing-read "Tags: " 'org-tags-completion-function
10919 nil nil current 'org-tags-history)))))))
10920 (while (string-match "[-+&]+" tags)
10921 ;; No boolean logic, just a list
10922 (setq tags (replace-match ":" t t tags))))
10924 (if (string-match "\\`[\t ]*\\'" tags)
10925 (setq tags "")
10926 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
10927 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
10929 ;; Insert new tags at the correct column
10930 (beginning-of-line 1)
10931 (cond
10932 ((and (equal current "") (equal tags "")))
10933 ((re-search-forward
10934 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10935 (point-at-eol) t)
10936 (if (equal tags "")
10937 (setq rpl "")
10938 (goto-char (match-beginning 0))
10939 (setq c0 (current-column) p0 (point)
10940 c1 (max (1+ c0) (if (> org-tags-column 0)
10941 org-tags-column
10942 (- (- org-tags-column) (length tags))))
10943 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10944 (replace-match rpl t t)
10945 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
10946 tags)
10947 (t (error "Tags alignment failed")))
10948 (org-move-to-column col)
10949 (unless just-align
10950 (run-hooks 'org-after-tags-change-hook)))))
10952 (defun org-change-tag-in-region (beg end tag off)
10953 "Add or remove TAG for each entry in the region.
10954 This works in the agenda, and also in an org-mode buffer."
10955 (interactive
10956 (list (region-beginning) (region-end)
10957 (let ((org-last-tags-completion-table
10958 (if (org-mode-p)
10959 (org-get-buffer-tags)
10960 (org-global-tags-completion-table))))
10961 (org-ido-completing-read
10962 "Tag: " 'org-tags-completion-function nil nil nil
10963 'org-tags-history))
10964 (progn
10965 (message "[s]et or [r]emove? ")
10966 (equal (read-char-exclusive) ?r))))
10967 (if (fboundp 'deactivate-mark) (deactivate-mark))
10968 (let ((agendap (equal major-mode 'org-agenda-mode))
10969 l1 l2 m buf pos newhead (cnt 0))
10970 (goto-char end)
10971 (setq l2 (1- (org-current-line)))
10972 (goto-char beg)
10973 (setq l1 (org-current-line))
10974 (loop for l from l1 to l2 do
10975 (goto-line l)
10976 (setq m (get-text-property (point) 'org-hd-marker))
10977 (when (or (and (org-mode-p) (org-on-heading-p))
10978 (and agendap m))
10979 (setq buf (if agendap (marker-buffer m) (current-buffer))
10980 pos (if agendap m (point)))
10981 (with-current-buffer buf
10982 (save-excursion
10983 (save-restriction
10984 (goto-char pos)
10985 (setq cnt (1+ cnt))
10986 (org-toggle-tag tag (if off 'off 'on))
10987 (setq newhead (org-get-heading)))))
10988 (and agendap (org-agenda-change-all-lines newhead m))))
10989 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
10991 (defun org-tags-completion-function (string predicate &optional flag)
10992 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10993 (confirm (lambda (x) (stringp (car x)))))
10994 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10995 (setq s1 (match-string 1 string)
10996 s2 (match-string 2 string))
10997 (setq s1 "" s2 string))
10998 (cond
10999 ((eq flag nil)
11000 ;; try completion
11001 (setq rtn (try-completion s2 ctable confirm))
11002 (if (stringp rtn)
11003 (setq rtn
11004 (concat s1 s2 (substring rtn (length s2))
11005 (if (and org-add-colon-after-tag-completion
11006 (assoc rtn ctable))
11007 ":" ""))))
11008 rtn)
11009 ((eq flag t)
11010 ;; all-completions
11011 (all-completions s2 ctable confirm)
11013 ((eq flag 'lambda)
11014 ;; exact match?
11015 (assoc s2 ctable)))
11018 (defun org-fast-tag-insert (kwd tags face &optional end)
11019 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
11020 (insert (format "%-12s" (concat kwd ":"))
11021 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
11022 (or end "")))
11024 (defun org-fast-tag-show-exit (flag)
11025 (save-excursion
11026 (goto-line 3)
11027 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
11028 (replace-match ""))
11029 (when flag
11030 (end-of-line 1)
11031 (org-move-to-column (- (window-width) 19) t)
11032 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
11034 (defun org-set-current-tags-overlay (current prefix)
11035 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
11036 (if (featurep 'xemacs)
11037 (org-overlay-display org-tags-overlay (concat prefix s)
11038 'secondary-selection)
11039 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
11040 (org-overlay-display org-tags-overlay (concat prefix s)))))
11042 (defun org-fast-tag-selection (current inherited table &optional todo-table)
11043 "Fast tag selection with single keys.
11044 CURRENT is the current list of tags in the headline, INHERITED is the
11045 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
11046 possibly with grouping information. TODO-TABLE is a similar table with
11047 TODO keywords, should these have keys assigned to them.
11048 If the keys are nil, a-z are automatically assigned.
11049 Returns the new tags string, or nil to not change the current settings."
11050 (let* ((fulltable (append table todo-table))
11051 (maxlen (apply 'max (mapcar
11052 (lambda (x)
11053 (if (stringp (car x)) (string-width (car x)) 0))
11054 fulltable)))
11055 (buf (current-buffer))
11056 (expert (eq org-fast-tag-selection-single-key 'expert))
11057 (buffer-tags nil)
11058 (fwidth (+ maxlen 3 1 3))
11059 (ncol (/ (- (window-width) 4) fwidth))
11060 (i-face 'org-done)
11061 (c-face 'org-todo)
11062 tg cnt e c char c1 c2 ntable tbl rtn
11063 ov-start ov-end ov-prefix
11064 (exit-after-next org-fast-tag-selection-single-key)
11065 (done-keywords org-done-keywords)
11066 groups ingroup)
11067 (save-excursion
11068 (beginning-of-line 1)
11069 (if (looking-at
11070 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11071 (setq ov-start (match-beginning 1)
11072 ov-end (match-end 1)
11073 ov-prefix "")
11074 (setq ov-start (1- (point-at-eol))
11075 ov-end (1+ ov-start))
11076 (skip-chars-forward "^\n\r")
11077 (setq ov-prefix
11078 (concat
11079 (buffer-substring (1- (point)) (point))
11080 (if (> (current-column) org-tags-column)
11082 (make-string (- org-tags-column (current-column)) ?\ ))))))
11083 (org-move-overlay org-tags-overlay ov-start ov-end)
11084 (save-window-excursion
11085 (if expert
11086 (set-buffer (get-buffer-create " *Org tags*"))
11087 (delete-other-windows)
11088 (split-window-vertically)
11089 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
11090 (erase-buffer)
11091 (org-set-local 'org-done-keywords done-keywords)
11092 (org-fast-tag-insert "Inherited" inherited i-face "\n")
11093 (org-fast-tag-insert "Current" current c-face "\n\n")
11094 (org-fast-tag-show-exit exit-after-next)
11095 (org-set-current-tags-overlay current ov-prefix)
11096 (setq tbl fulltable char ?a cnt 0)
11097 (while (setq e (pop tbl))
11098 (cond
11099 ((equal e '(:startgroup))
11100 (push '() groups) (setq ingroup t)
11101 (when (not (= cnt 0))
11102 (setq cnt 0)
11103 (insert "\n"))
11104 (insert "{ "))
11105 ((equal e '(:endgroup))
11106 (setq ingroup nil cnt 0)
11107 (insert "}\n"))
11108 ((equal e '(:newline))
11109 (when (not (= cnt 0))
11110 (setq cnt 0)
11111 (insert "\n")
11112 (setq e (car tbl))
11113 (while (equal (car tbl) '(:newline))
11114 (insert "\n")
11115 (setq tbl (cdr tbl)))))
11117 (setq tg (car e) c2 nil)
11118 (if (cdr e)
11119 (setq c (cdr e))
11120 ;; automatically assign a character.
11121 (setq c1 (string-to-char
11122 (downcase (substring
11123 tg (if (= (string-to-char tg) ?@) 1 0)))))
11124 (if (or (rassoc c1 ntable) (rassoc c1 table))
11125 (while (or (rassoc char ntable) (rassoc char table))
11126 (setq char (1+ char)))
11127 (setq c2 c1))
11128 (setq c (or c2 char)))
11129 (if ingroup (push tg (car groups)))
11130 (setq tg (org-add-props tg nil 'face
11131 (cond
11132 ((not (assoc tg table))
11133 (org-get-todo-face tg))
11134 ((member tg current) c-face)
11135 ((member tg inherited) i-face)
11136 (t nil))))
11137 (if (and (= cnt 0) (not ingroup)) (insert " "))
11138 (insert "[" c "] " tg (make-string
11139 (- fwidth 4 (length tg)) ?\ ))
11140 (push (cons tg c) ntable)
11141 (when (= (setq cnt (1+ cnt)) ncol)
11142 (insert "\n")
11143 (if ingroup (insert " "))
11144 (setq cnt 0)))))
11145 (setq ntable (nreverse ntable))
11146 (insert "\n")
11147 (goto-char (point-min))
11148 (if (not expert) (org-fit-window-to-buffer))
11149 (setq rtn
11150 (catch 'exit
11151 (while t
11152 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
11153 (if groups " [!] no groups" " [!]groups")
11154 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
11155 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11156 (cond
11157 ((= c ?\r) (throw 'exit t))
11158 ((= c ?!)
11159 (setq groups (not groups))
11160 (goto-char (point-min))
11161 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
11162 ((= c ?\C-c)
11163 (if (not expert)
11164 (org-fast-tag-show-exit
11165 (setq exit-after-next (not exit-after-next)))
11166 (setq expert nil)
11167 (delete-other-windows)
11168 (split-window-vertically)
11169 (org-switch-to-buffer-other-window " *Org tags*")
11170 (org-fit-window-to-buffer)))
11171 ((or (= c ?\C-g)
11172 (and (= c ?q) (not (rassoc c ntable))))
11173 (org-detach-overlay org-tags-overlay)
11174 (setq quit-flag t))
11175 ((= c ?\ )
11176 (setq current nil)
11177 (if exit-after-next (setq exit-after-next 'now)))
11178 ((= c ?\t)
11179 (condition-case nil
11180 (setq tg (org-ido-completing-read
11181 "Tag: "
11182 (or buffer-tags
11183 (with-current-buffer buf
11184 (org-get-buffer-tags)))))
11185 (quit (setq tg "")))
11186 (when (string-match "\\S-" tg)
11187 (add-to-list 'buffer-tags (list tg))
11188 (if (member tg current)
11189 (setq current (delete tg current))
11190 (push tg current)))
11191 (if exit-after-next (setq exit-after-next 'now)))
11192 ((setq e (rassoc c todo-table) tg (car e))
11193 (with-current-buffer buf
11194 (save-excursion (org-todo tg)))
11195 (if exit-after-next (setq exit-after-next 'now)))
11196 ((setq e (rassoc c ntable) tg (car e))
11197 (if (member tg current)
11198 (setq current (delete tg current))
11199 (loop for g in groups do
11200 (if (member tg g)
11201 (mapc (lambda (x)
11202 (setq current (delete x current)))
11203 g)))
11204 (push tg current))
11205 (if exit-after-next (setq exit-after-next 'now))))
11207 ;; Create a sorted list
11208 (setq current
11209 (sort current
11210 (lambda (a b)
11211 (assoc b (cdr (memq (assoc a ntable) ntable))))))
11212 (if (eq exit-after-next 'now) (throw 'exit t))
11213 (goto-char (point-min))
11214 (beginning-of-line 2)
11215 (delete-region (point) (point-at-eol))
11216 (org-fast-tag-insert "Current" current c-face)
11217 (org-set-current-tags-overlay current ov-prefix)
11218 (while (re-search-forward
11219 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
11220 (setq tg (match-string 1))
11221 (add-text-properties
11222 (match-beginning 1) (match-end 1)
11223 (list 'face
11224 (cond
11225 ((member tg current) c-face)
11226 ((member tg inherited) i-face)
11227 (t (get-text-property (match-beginning 1) 'face))))))
11228 (goto-char (point-min)))))
11229 (org-detach-overlay org-tags-overlay)
11230 (if rtn
11231 (mapconcat 'identity current ":")
11232 nil))))
11234 (defun org-get-tags-string ()
11235 "Get the TAGS string in the current headline."
11236 (unless (org-on-heading-p t)
11237 (error "Not on a heading"))
11238 (save-excursion
11239 (beginning-of-line 1)
11240 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11241 (org-match-string-no-properties 1)
11242 "")))
11244 (defun org-get-tags ()
11245 "Get the list of tags specified in the current headline."
11246 (org-split-string (org-get-tags-string) ":"))
11248 (defun org-get-buffer-tags ()
11249 "Get a table of all tags used in the buffer, for completion."
11250 (let (tags)
11251 (save-excursion
11252 (goto-char (point-min))
11253 (while (re-search-forward
11254 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
11255 (when (equal (char-after (point-at-bol 0)) ?*)
11256 (mapc (lambda (x) (add-to-list 'tags x))
11257 (org-split-string (org-match-string-no-properties 1) ":")))))
11258 (mapcar 'list tags)))
11260 ;;;; The mapping API
11262 ;;;###autoload
11263 (defun org-map-entries (func &optional match scope &rest skip)
11264 "Call FUNC at each headline selected by MATCH in SCOPE.
11266 FUNC is a function or a lisp form. The function will be called without
11267 arguments, with the cursor positioned at the beginning of the headline.
11268 The return values of all calls to the function will be collected and
11269 returned as a list.
11271 The call to FUNC will be wrapped into a save-excursion form, so FUNC
11272 does not need to preserve point. After evaluaton, the cursor will be
11273 moved to the end of the line (presumably of the headline of the
11274 processed entry) and search continues from there. Under some
11275 circumstances, this may not produce the wanted results. For example,
11276 if you have removed (e.g. archived) the current (sub)tree it could
11277 mean that the next entry will be skipped entirely. In such cases, you
11278 can specify the position from where search should continue by making
11279 FUNC set the variable `org-map-continue-from' to the desired buffer
11280 position.
11282 MATCH is a tags/property/todo match as it is used in the agenda tags view.
11283 Only headlines that are matched by this query will be considered during
11284 the iteration. When MATCH is nil or t, all headlines will be
11285 visited by the iteration.
11287 SCOPE determines the scope of this command. It can be any of:
11289 nil The current buffer, respecting the restriction if any
11290 tree The subtree started with the entry at point
11291 file The current buffer, without restriction
11292 file-with-archives
11293 The current buffer, and any archives associated with it
11294 agenda All agenda files
11295 agenda-with-archives
11296 All agenda files with any archive files associated with them
11297 \(file1 file2 ...)
11298 If this is a list, all files in the list will be scanned
11300 The remaining args are treated as settings for the skipping facilities of
11301 the scanner. The following items can be given here:
11303 archive skip trees with the archive tag.
11304 comment skip trees with the COMMENT keyword
11305 function or Emacs Lisp form:
11306 will be used as value for `org-agenda-skip-function', so whenever
11307 the the function returns t, FUNC will not be called for that
11308 entry and search will continue from the point where the
11309 function leaves it.
11311 If your function needs to retrieve the tags including inherited tags
11312 at the *current* entry, you can use the value of the variable
11313 `org-scanner-tags' which will be much faster than getting the value
11314 with `org-get-tags-at'. If your function gets properties with
11315 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
11316 to t around the call to `org-entry-properties' to get the same speedup.
11317 Note that if your function moves around to retrieve tags and properties at
11318 a *different* entry, you cannot use these techniques."
11319 (let* ((org-agenda-archives-mode nil) ; just to make sure
11320 (org-agenda-skip-archived-trees (memq 'archive skip))
11321 (org-agenda-skip-comment-trees (memq 'comment skip))
11322 (org-agenda-skip-function
11323 (car (org-delete-all '(comment archive) skip)))
11324 (org-tags-match-list-sublevels t)
11325 matcher file res
11326 org-todo-keywords-for-agenda
11327 org-done-keywords-for-agenda
11328 org-todo-keyword-alist-for-agenda
11329 org-tag-alist-for-agenda)
11331 (cond
11332 ((eq match t) (setq matcher t))
11333 ((eq match nil) (setq matcher t))
11334 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
11336 (save-excursion
11337 (save-restriction
11338 (when (eq scope 'tree)
11339 (org-back-to-heading t)
11340 (org-narrow-to-subtree)
11341 (setq scope nil))
11343 (if (not scope)
11344 (progn
11345 (org-prepare-agenda-buffers
11346 (list (buffer-file-name (current-buffer))))
11347 (setq res (org-scan-tags func matcher)))
11348 ;; Get the right scope
11349 (cond
11350 ((and scope (listp scope) (symbolp (car scope)))
11351 (setq scope (eval scope)))
11352 ((eq scope 'agenda)
11353 (setq scope (org-agenda-files t)))
11354 ((eq scope 'agenda-with-archives)
11355 (setq scope (org-agenda-files t))
11356 (setq scope (org-add-archive-files scope)))
11357 ((eq scope 'file)
11358 (setq scope (list (buffer-file-name))))
11359 ((eq scope 'file-with-archives)
11360 (setq scope (org-add-archive-files (list (buffer-file-name))))))
11361 (org-prepare-agenda-buffers scope)
11362 (while (setq file (pop scope))
11363 (with-current-buffer (org-find-base-buffer-visiting file)
11364 (save-excursion
11365 (save-restriction
11366 (widen)
11367 (goto-char (point-min))
11368 (setq res (append res (org-scan-tags func matcher))))))))))
11369 res))
11371 ;;;; Properties
11373 ;;; Setting and retrieving properties
11375 (defconst org-special-properties
11376 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
11377 "TIMESTAMP" "TIMESTAMP_IA")
11378 "The special properties valid in Org-mode.
11380 These are properties that are not defined in the property drawer,
11381 but in some other way.")
11383 (defconst org-default-properties
11384 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
11385 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
11386 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
11387 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
11388 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER")
11389 "Some properties that are used by Org-mode for various purposes.
11390 Being in this list makes sure that they are offered for completion.")
11392 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
11393 "Regular expression matching the first line of a property drawer.")
11395 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
11396 "Regular expression matching the first line of a property drawer.")
11398 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
11399 "Regular expression matching the first line of a property drawer.")
11401 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
11402 "Regular expression matching the first line of a property drawer.")
11404 (defconst org-property-drawer-re
11405 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
11406 org-property-end-re "\\)\n?")
11407 "Matches an entire property drawer.")
11409 (defconst org-clock-drawer-re
11410 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
11411 org-property-end-re "\\)\n?")
11412 "Matches an entire clock drawer.")
11414 (defun org-property-action ()
11415 "Do an action on properties."
11416 (interactive)
11417 (let (c)
11418 (org-at-property-p)
11419 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
11420 (setq c (read-char-exclusive))
11421 (cond
11422 ((equal c ?s)
11423 (call-interactively 'org-set-property))
11424 ((equal c ?d)
11425 (call-interactively 'org-delete-property))
11426 ((equal c ?D)
11427 (call-interactively 'org-delete-property-globally))
11428 ((equal c ?c)
11429 (call-interactively 'org-compute-property-at-point))
11430 (t (error "No such property action %c" c)))))
11432 (defun org-at-property-p ()
11433 "Is the cursor in a property line?"
11434 ;; FIXME: Does not check if we are actually in the drawer.
11435 ;; FIXME: also returns true on any drawers.....
11436 ;; This is used by C-c C-c for property action.
11437 (save-excursion
11438 (beginning-of-line 1)
11439 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
11441 (defun org-get-property-block (&optional beg end force)
11442 "Return the (beg . end) range of the body of the property drawer.
11443 BEG and END can be beginning and end of subtree, if not given
11444 they will be found.
11445 If the drawer does not exist and FORCE is non-nil, create the drawer."
11446 (catch 'exit
11447 (save-excursion
11448 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
11449 (end (or end (progn (outline-next-heading) (point)))))
11450 (goto-char beg)
11451 (if (re-search-forward org-property-start-re end t)
11452 (setq beg (1+ (match-end 0)))
11453 (if force
11454 (save-excursion
11455 (org-insert-property-drawer)
11456 (setq end (progn (outline-next-heading) (point))))
11457 (throw 'exit nil))
11458 (goto-char beg)
11459 (if (re-search-forward org-property-start-re end t)
11460 (setq beg (1+ (match-end 0)))))
11461 (if (re-search-forward org-property-end-re end t)
11462 (setq end (match-beginning 0))
11463 (or force (throw 'exit nil))
11464 (goto-char beg)
11465 (setq end beg)
11466 (org-indent-line-function)
11467 (insert ":END:\n"))
11468 (cons beg end)))))
11470 (defun org-entry-properties (&optional pom which)
11471 "Get all properties of the entry at point-or-marker POM.
11472 This includes the TODO keyword, the tags, time strings for deadline,
11473 scheduled, and clocking, and any additional properties defined in the
11474 entry. The return value is an alist, keys may occur multiple times
11475 if the property key was used several times.
11476 POM may also be nil, in which case the current entry is used.
11477 If WHICH is nil or `all', get all properties. If WHICH is
11478 `special' or `standard', only get that subclass."
11479 (setq which (or which 'all))
11480 (org-with-point-at pom
11481 (let ((clockstr (substring org-clock-string 0 -1))
11482 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
11483 beg end range props sum-props key value string clocksum)
11484 (save-excursion
11485 (when (condition-case nil
11486 (and (org-mode-p) (org-back-to-heading t))
11487 (error nil))
11488 (setq beg (point))
11489 (setq sum-props (get-text-property (point) 'org-summaries))
11490 (setq clocksum (get-text-property (point) :org-clock-minutes))
11491 (outline-next-heading)
11492 (setq end (point))
11493 (when (memq which '(all special))
11494 ;; Get the special properties, like TODO and tags
11495 (goto-char beg)
11496 (when (and (looking-at org-todo-line-regexp) (match-end 2))
11497 (push (cons "TODO" (org-match-string-no-properties 2)) props))
11498 (when (looking-at org-priority-regexp)
11499 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
11500 (when (and (setq value (org-get-tags-string))
11501 (string-match "\\S-" value))
11502 (push (cons "TAGS" value) props))
11503 (when (setq value (org-get-tags-at))
11504 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
11505 props))
11506 (while (re-search-forward org-maybe-keyword-time-regexp end t)
11507 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
11508 string (if (equal key clockstr)
11509 (org-no-properties
11510 (org-trim
11511 (buffer-substring
11512 (match-beginning 3) (goto-char (point-at-eol)))))
11513 (substring (org-match-string-no-properties 3) 1 -1)))
11514 (unless key
11515 (if (= (char-after (match-beginning 3)) ?\[)
11516 (setq key "TIMESTAMP_IA")
11517 (setq key "TIMESTAMP")))
11518 (when (or (equal key clockstr) (not (assoc key props)))
11519 (push (cons key string) props)))
11523 (when (memq which '(all standard))
11524 ;; Get the standard properties, like :PROP: ...
11525 (setq range (org-get-property-block beg end))
11526 (when range
11527 (goto-char (car range))
11528 (while (re-search-forward
11529 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
11530 (cdr range) t)
11531 (setq key (org-match-string-no-properties 1)
11532 value (org-trim (or (org-match-string-no-properties 2) "")))
11533 (unless (member key excluded)
11534 (push (cons key (or value "")) props)))))
11535 (if clocksum
11536 (push (cons "CLOCKSUM"
11537 (org-columns-number-to-string (/ (float clocksum) 60.)
11538 'add_times))
11539 props))
11540 (unless (assoc "CATEGORY" props)
11541 (setq value (or (org-get-category)
11542 (progn (org-refresh-category-properties)
11543 (org-get-category))))
11544 (push (cons "CATEGORY" value) props))
11545 (append sum-props (nreverse props)))))))
11547 (defun org-entry-get (pom property &optional inherit)
11548 "Get value of PROPERTY for entry at point-or-marker POM.
11549 If INHERIT is non-nil and the entry does not have the property,
11550 then also check higher levels of the hierarchy.
11551 If INHERIT is the symbol `selective', use inheritance only if the setting
11552 in `org-use-property-inheritance' selects PROPERTY for inheritance.
11553 If the property is present but empty, the return value is the empty string.
11554 If the property is not present at all, nil is returned."
11555 (org-with-point-at pom
11556 (if (and inherit (if (eq inherit 'selective)
11557 (org-property-inherit-p property)
11559 (org-entry-get-with-inheritance property)
11560 (if (member property org-special-properties)
11561 ;; We need a special property. Use brute force, get all properties.
11562 (cdr (assoc property (org-entry-properties nil 'special)))
11563 (let ((range (org-get-property-block)))
11564 (if (and range
11565 (goto-char (car range))
11566 (re-search-forward
11567 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
11568 (cdr range) t))
11569 ;; Found the property, return it.
11570 (if (match-end 1)
11571 (org-match-string-no-properties 1)
11572 "")))))))
11574 (defun org-property-or-variable-value (var &optional inherit)
11575 "Check if there is a property fixing the value of VAR.
11576 If yes, return this value. If not, return the current value of the variable."
11577 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
11578 (if (and prop (stringp prop) (string-match "\\S-" prop))
11579 (read prop)
11580 (symbol-value var))))
11582 (defun org-entry-delete (pom property)
11583 "Delete the property PROPERTY from entry at point-or-marker POM."
11584 (org-with-point-at pom
11585 (if (member property org-special-properties)
11586 nil ; cannot delete these properties.
11587 (let ((range (org-get-property-block)))
11588 (if (and range
11589 (goto-char (car range))
11590 (re-search-forward
11591 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
11592 (cdr range) t))
11593 (progn
11594 (delete-region (match-beginning 0) (1+ (point-at-eol)))
11596 nil)))))
11598 ;; Multi-values properties are properties that contain multiple values
11599 ;; These values are assumed to be single words, separated by whitespace.
11600 (defun org-entry-add-to-multivalued-property (pom property value)
11601 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
11602 (let* ((old (org-entry-get pom property))
11603 (values (and old (org-split-string old "[ \t]"))))
11604 (setq value (org-entry-protect-space value))
11605 (unless (member value values)
11606 (setq values (cons value values))
11607 (org-entry-put pom property
11608 (mapconcat 'identity values " ")))))
11610 (defun org-entry-remove-from-multivalued-property (pom property value)
11611 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
11612 (let* ((old (org-entry-get pom property))
11613 (values (and old (org-split-string old "[ \t]"))))
11614 (setq value (org-entry-protect-space value))
11615 (when (member value values)
11616 (setq values (delete value values))
11617 (org-entry-put pom property
11618 (mapconcat 'identity values " ")))))
11620 (defun org-entry-member-in-multivalued-property (pom property value)
11621 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
11622 (let* ((old (org-entry-get pom property))
11623 (values (and old (org-split-string old "[ \t]"))))
11624 (setq value (org-entry-protect-space value))
11625 (member value values)))
11627 (defun org-entry-get-multivalued-property (pom property)
11628 "Return a list of values in a multivalued property."
11629 (let* ((value (org-entry-get pom property))
11630 (values (and value (org-split-string value "[ \t]"))))
11631 (mapcar 'org-entry-restore-space values)))
11633 (defun org-entry-put-multivalued-property (pom property &rest values)
11634 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
11635 VALUES should be a list of strings. Spaces will be protected."
11636 (org-entry-put pom property
11637 (mapconcat 'org-entry-protect-space values " "))
11638 (let* ((value (org-entry-get pom property))
11639 (values (and value (org-split-string value "[ \t]"))))
11640 (mapcar 'org-entry-restore-space values)))
11642 (defun org-entry-protect-space (s)
11643 "Protect spaces and newline in string S."
11644 (while (string-match " " s)
11645 (setq s (replace-match "%20" t t s)))
11646 (while (string-match "\n" s)
11647 (setq s (replace-match "%0A" t t s)))
11650 (defun org-entry-restore-space (s)
11651 "Restore spaces and newline in string S."
11652 (while (string-match "%20" s)
11653 (setq s (replace-match " " t t s)))
11654 (while (string-match "%0A" s)
11655 (setq s (replace-match "\n" t t s)))
11658 (defvar org-entry-property-inherited-from (make-marker)
11659 "Marker pointing to the entry from where a property was inherited.
11660 Each call to `org-entry-get-with-inheritance' will set this marker to the
11661 location of the entry where the inheritance search matched. If there was
11662 no match, the marker will point nowhere.
11663 Note that also `org-entry-get' calls this function, if the INHERIT flag
11664 is set.")
11666 (defun org-entry-get-with-inheritance (property)
11667 "Get entry property, and search higher levels if not present."
11668 (move-marker org-entry-property-inherited-from nil)
11669 (let (tmp)
11670 (save-excursion
11671 (save-restriction
11672 (widen)
11673 (catch 'ex
11674 (while t
11675 (when (setq tmp (org-entry-get nil property))
11676 (org-back-to-heading t)
11677 (move-marker org-entry-property-inherited-from (point))
11678 (throw 'ex tmp))
11679 (or (org-up-heading-safe) (throw 'ex nil)))))
11680 (or tmp
11681 (cdr (assoc property org-file-properties))
11682 (cdr (assoc property org-global-properties))
11683 (cdr (assoc property org-global-properties-fixed))))))
11685 (defun org-entry-put (pom property value)
11686 "Set PROPERTY to VALUE for entry at point-or-marker POM."
11687 (org-with-point-at pom
11688 (org-back-to-heading t)
11689 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
11690 range)
11691 (cond
11692 ((equal property "TODO")
11693 (when (and (stringp value) (string-match "\\S-" value)
11694 (not (member value org-todo-keywords-1)))
11695 (error "\"%s\" is not a valid TODO state" value))
11696 (if (or (not value)
11697 (not (string-match "\\S-" value)))
11698 (setq value 'none))
11699 (org-todo value)
11700 (org-set-tags nil 'align))
11701 ((equal property "PRIORITY")
11702 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
11703 (string-to-char value) ?\ ))
11704 (org-set-tags nil 'align))
11705 ((equal property "SCHEDULED")
11706 (if (re-search-forward org-scheduled-time-regexp end t)
11707 (cond
11708 ((eq value 'earlier) (org-timestamp-change -1 'day))
11709 ((eq value 'later) (org-timestamp-change 1 'day))
11710 (t (call-interactively 'org-schedule)))
11711 (call-interactively 'org-schedule)))
11712 ((equal property "DEADLINE")
11713 (if (re-search-forward org-deadline-time-regexp end t)
11714 (cond
11715 ((eq value 'earlier) (org-timestamp-change -1 'day))
11716 ((eq value 'later) (org-timestamp-change 1 'day))
11717 (t (call-interactively 'org-deadline)))
11718 (call-interactively 'org-deadline)))
11719 ((member property org-special-properties)
11720 (error "The %s property can not yet be set with `org-entry-put'"
11721 property))
11722 (t ; a non-special property
11723 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
11724 (setq range (org-get-property-block beg end 'force))
11725 (goto-char (car range))
11726 (if (re-search-forward
11727 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
11728 (progn
11729 (delete-region (match-beginning 1) (match-end 1))
11730 (goto-char (match-beginning 1)))
11731 (goto-char (cdr range))
11732 (insert "\n")
11733 (backward-char 1)
11734 (org-indent-line-function)
11735 (insert ":" property ":"))
11736 (and value (insert " " value))
11737 (org-indent-line-function)))))))
11739 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
11740 "Get all property keys in the current buffer.
11741 With INCLUDE-SPECIALS, also list the special properties that reflect things
11742 like tags and TODO state.
11743 With INCLUDE-DEFAULTS, also include properties that has special meaning
11744 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
11745 With INCLUDE-COLUMNS, also include property names given in COLUMN
11746 formats in the current buffer."
11747 (let (rtn range cfmt s p)
11748 (save-excursion
11749 (save-restriction
11750 (widen)
11751 (goto-char (point-min))
11752 (while (re-search-forward org-property-start-re nil t)
11753 (setq range (org-get-property-block))
11754 (goto-char (car range))
11755 (while (re-search-forward
11756 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
11757 (cdr range) t)
11758 (add-to-list 'rtn (org-match-string-no-properties 1)))
11759 (outline-next-heading))))
11761 (when include-specials
11762 (setq rtn (append org-special-properties rtn)))
11764 (when include-defaults
11765 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
11767 (when include-columns
11768 (save-excursion
11769 (save-restriction
11770 (widen)
11771 (goto-char (point-min))
11772 (while (re-search-forward
11773 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
11774 nil t)
11775 (setq cfmt (match-string 2) s 0)
11776 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
11777 cfmt s)
11778 (setq s (match-end 0)
11779 p (match-string 1 cfmt))
11780 (unless (or (equal p "ITEM")
11781 (member p org-special-properties))
11782 (add-to-list 'rtn (match-string 1 cfmt))))))))
11784 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
11786 (defun org-property-values (key)
11787 "Return a list of all values of property KEY."
11788 (save-excursion
11789 (save-restriction
11790 (widen)
11791 (goto-char (point-min))
11792 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
11793 values)
11794 (while (re-search-forward re nil t)
11795 (add-to-list 'values (org-trim (match-string 1))))
11796 (delete "" values)))))
11798 (defun org-insert-property-drawer ()
11799 "Insert a property drawer into the current entry."
11800 (interactive)
11801 (org-back-to-heading t)
11802 (looking-at outline-regexp)
11803 (let ((indent (- (match-end 0)(match-beginning 0)))
11804 (beg (point))
11805 (re (concat "^[ \t]*" org-keyword-time-regexp))
11806 end hiddenp)
11807 (outline-next-heading)
11808 (setq end (point))
11809 (goto-char beg)
11810 (while (re-search-forward re end t))
11811 (setq hiddenp (org-invisible-p))
11812 (end-of-line 1)
11813 (and (equal (char-after) ?\n) (forward-char 1))
11814 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
11815 (if (member (match-string 1) '("CLOCK:" ":END:"))
11816 ;; just skip this line
11817 (beginning-of-line 2)
11818 ;; Drawer start, find the end
11819 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
11820 (beginning-of-line 1)))
11821 (org-skip-over-state-notes)
11822 (skip-chars-backward " \t\n\r")
11823 (if (eq (char-before) ?*) (forward-char 1))
11824 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
11825 (beginning-of-line 0)
11826 (org-indent-to-column indent)
11827 (beginning-of-line 2)
11828 (org-indent-to-column indent)
11829 (beginning-of-line 0)
11830 (if hiddenp
11831 (save-excursion
11832 (org-back-to-heading t)
11833 (hide-entry))
11834 (org-flag-drawer t))))
11836 (defun org-set-property (property value)
11837 "In the current entry, set PROPERTY to VALUE.
11838 When called interactively, this will prompt for a property name, offering
11839 completion on existing and default properties. And then it will prompt
11840 for a value, offering completion either on allowed values (via an inherited
11841 xxx_ALL property) or on existing values in other instances of this property
11842 in the current file."
11843 (interactive
11844 (let* ((completion-ignore-case t)
11845 (keys (org-buffer-property-keys nil t t))
11846 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
11847 (prop (if (member prop0 keys)
11848 prop0
11849 (or (cdr (assoc (downcase prop0)
11850 (mapcar (lambda (x) (cons (downcase x) x))
11851 keys)))
11852 prop0)))
11853 (cur (org-entry-get nil prop))
11854 (allowed (org-property-get-allowed-values nil prop 'table))
11855 (existing (mapcar 'list (org-property-values prop)))
11856 (val (if allowed
11857 (org-completing-read "Value: " allowed nil 'req-match)
11858 (let (org-completion-use-ido)
11859 (org-completing-read
11860 (concat "Value" (if (and cur (string-match "\\S-" cur))
11861 (concat "[" cur "]") "")
11862 ": ")
11863 existing nil nil "" nil cur)))))
11864 (list prop (if (equal val "") cur val))))
11865 (unless (equal (org-entry-get nil property) value)
11866 (org-entry-put nil property value)))
11868 (defun org-delete-property (property)
11869 "In the current entry, delete PROPERTY."
11870 (interactive
11871 (let* ((completion-ignore-case t)
11872 (prop (org-ido-completing-read
11873 "Property: " (org-entry-properties nil 'standard))))
11874 (list prop)))
11875 (message "Property %s %s" property
11876 (if (org-entry-delete nil property)
11877 "deleted"
11878 "was not present in the entry")))
11880 (defun org-delete-property-globally (property)
11881 "Remove PROPERTY globally, from all entries."
11882 (interactive
11883 (let* ((completion-ignore-case t)
11884 (prop (org-ido-completing-read
11885 "Globally remove property: "
11886 (mapcar 'list (org-buffer-property-keys)))))
11887 (list prop)))
11888 (save-excursion
11889 (save-restriction
11890 (widen)
11891 (goto-char (point-min))
11892 (let ((cnt 0))
11893 (while (re-search-forward
11894 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
11895 nil t)
11896 (setq cnt (1+ cnt))
11897 (replace-match ""))
11898 (message "Property \"%s\" removed from %d entries" property cnt)))))
11900 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
11902 (defun org-compute-property-at-point ()
11903 "Compute the property at point.
11904 This looks for an enclosing column format, extracts the operator and
11905 then applies it to the property in the column format's scope."
11906 (interactive)
11907 (unless (org-at-property-p)
11908 (error "Not at a property"))
11909 (let ((prop (org-match-string-no-properties 2)))
11910 (org-columns-get-format-and-top-level)
11911 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
11912 (error "No operator defined for property %s" prop))
11913 (org-columns-compute prop)))
11915 (defun org-property-get-allowed-values (pom property &optional table)
11916 "Get allowed values for the property PROPERTY.
11917 When TABLE is non-nil, return an alist that can directly be used for
11918 completion."
11919 (let (vals)
11920 (cond
11921 ((equal property "TODO")
11922 (setq vals (org-with-point-at pom
11923 (append org-todo-keywords-1 '("")))))
11924 ((equal property "PRIORITY")
11925 (let ((n org-lowest-priority))
11926 (while (>= n org-highest-priority)
11927 (push (char-to-string n) vals)
11928 (setq n (1- n)))))
11929 ((member property org-special-properties))
11931 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
11933 (when (and vals (string-match "\\S-" vals))
11934 (setq vals (car (read-from-string (concat "(" vals ")"))))
11935 (setq vals (mapcar (lambda (x)
11936 (cond ((stringp x) x)
11937 ((numberp x) (number-to-string x))
11938 ((symbolp x) (symbol-name x))
11939 (t "???")))
11940 vals)))))
11941 (if table (mapcar 'list vals) vals)))
11943 (defun org-property-previous-allowed-value (&optional previous)
11944 "Switch to the next allowed value for this property."
11945 (interactive)
11946 (org-property-next-allowed-value t))
11948 (defun org-property-next-allowed-value (&optional previous)
11949 "Switch to the next allowed value for this property."
11950 (interactive)
11951 (unless (org-at-property-p)
11952 (error "Not at a property"))
11953 (let* ((key (match-string 2))
11954 (value (match-string 3))
11955 (allowed (or (org-property-get-allowed-values (point) key)
11956 (and (member value '("[ ]" "[-]" "[X]"))
11957 '("[ ]" "[X]"))))
11958 nval)
11959 (unless allowed
11960 (error "Allowed values for this property have not been defined"))
11961 (if previous (setq allowed (reverse allowed)))
11962 (if (member value allowed)
11963 (setq nval (car (cdr (member value allowed)))))
11964 (setq nval (or nval (car allowed)))
11965 (if (equal nval value)
11966 (error "Only one allowed value for this property"))
11967 (org-at-property-p)
11968 (replace-match (concat " :" key ": " nval) t t)
11969 (org-indent-line-function)
11970 (beginning-of-line 1)
11971 (skip-chars-forward " \t")))
11973 (defun org-find-entry-with-id (ident)
11974 "Locate the entry that contains the ID property with exact value IDENT.
11975 IDENT can be a string, a symbol or a number, this function will search for
11976 the string representation of it.
11977 Return the position where this entry starts, or nil if there is no such entry."
11978 (interactive "sID: ")
11979 (let ((id (cond
11980 ((stringp ident) ident)
11981 ((symbol-name ident) (symbol-name ident))
11982 ((numberp ident) (number-to-string ident))
11983 (t (error "IDENT %s must be a string, symbol or number" ident))))
11984 (case-fold-search nil))
11985 (save-excursion
11986 (save-restriction
11987 (widen)
11988 (goto-char (point-min))
11989 (when (re-search-forward
11990 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
11991 nil t)
11992 (org-back-to-heading)
11993 (point))))))
11995 ;;;; Timestamps
11997 (defvar org-last-changed-timestamp nil)
11998 (defvar org-last-inserted-timestamp nil
11999 "The last time stamp inserted with `org-insert-time-stamp'.")
12000 (defvar org-time-was-given) ; dynamically scoped parameter
12001 (defvar org-end-time-was-given) ; dynamically scoped parameter
12002 (defvar org-ts-what) ; dynamically scoped parameter
12004 (defun org-time-stamp (arg &optional inactive)
12005 "Prompt for a date/time and insert a time stamp.
12006 If the user specifies a time like HH:MM, or if this command is called
12007 with a prefix argument, the time stamp will contain date and time.
12008 Otherwise, only the date will be included. All parts of a date not
12009 specified by the user will be filled in from the current date/time.
12010 So if you press just return without typing anything, the time stamp
12011 will represent the current date/time. If there is already a timestamp
12012 at the cursor, it will be modified."
12013 (interactive "P")
12014 (let* ((ts nil)
12015 (default-time
12016 ;; Default time is either today, or, when entering a range,
12017 ;; the range start.
12018 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
12019 (save-excursion
12020 (re-search-backward
12021 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
12022 (- (point) 20) t)))
12023 (apply 'encode-time (org-parse-time-string (match-string 1)))
12024 (current-time)))
12025 (default-input (and ts (org-get-compact-tod ts)))
12026 org-time-was-given org-end-time-was-given time)
12027 (cond
12028 ((and (org-at-timestamp-p t)
12029 (memq last-command '(org-time-stamp org-time-stamp-inactive))
12030 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
12031 (insert "--")
12032 (setq time (let ((this-command this-command))
12033 (org-read-date arg 'totime nil nil
12034 default-time default-input)))
12035 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
12036 ((org-at-timestamp-p t)
12037 (setq time (let ((this-command this-command))
12038 (org-read-date arg 'totime nil nil default-time default-input)))
12039 (when (org-at-timestamp-p t) ; just to get the match data
12040 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
12041 (replace-match "")
12042 (setq org-last-changed-timestamp
12043 (org-insert-time-stamp
12044 time (or org-time-was-given arg)
12045 inactive nil nil (list org-end-time-was-given))))
12046 (message "Timestamp updated"))
12048 (setq time (let ((this-command this-command))
12049 (org-read-date arg 'totime nil nil default-time default-input)))
12050 (org-insert-time-stamp time (or org-time-was-given arg) inactive
12051 nil nil (list org-end-time-was-given))))))
12053 ;; FIXME: can we use this for something else, like computing time differences?
12054 (defun org-get-compact-tod (s)
12055 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
12056 (let* ((t1 (match-string 1 s))
12057 (h1 (string-to-number (match-string 2 s)))
12058 (m1 (string-to-number (match-string 3 s)))
12059 (t2 (and (match-end 4) (match-string 5 s)))
12060 (h2 (and t2 (string-to-number (match-string 6 s))))
12061 (m2 (and t2 (string-to-number (match-string 7 s))))
12062 dh dm)
12063 (if (not t2)
12065 (setq dh (- h2 h1) dm (- m2 m1))
12066 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
12067 (concat t1 "+" (number-to-string dh)
12068 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
12070 (defun org-time-stamp-inactive (&optional arg)
12071 "Insert an inactive time stamp.
12072 An inactive time stamp is enclosed in square brackets instead of angle
12073 brackets. It is inactive in the sense that it does not trigger agenda entries,
12074 does not link to the calendar and cannot be changed with the S-cursor keys.
12075 So these are more for recording a certain time/date."
12076 (interactive "P")
12077 (org-time-stamp arg 'inactive))
12079 (defvar org-date-ovl (org-make-overlay 1 1))
12080 (org-overlay-put org-date-ovl 'face 'org-warning)
12081 (org-detach-overlay org-date-ovl)
12083 (defvar org-ans1) ; dynamically scoped parameter
12084 (defvar org-ans2) ; dynamically scoped parameter
12086 (defvar org-plain-time-of-day-regexp) ; defined below
12088 (defvar org-overriding-default-time nil) ; dynamically scoped
12089 (defvar org-read-date-overlay nil)
12090 (defvar org-dcst nil) ; dynamically scoped
12091 (defvar org-read-date-history nil)
12093 (defun org-read-date (&optional with-time to-time from-string prompt
12094 default-time default-input)
12095 "Read a date, possibly a time, and make things smooth for the user.
12096 The prompt will suggest to enter an ISO date, but you can also enter anything
12097 which will at least partially be understood by `parse-time-string'.
12098 Unrecognized parts of the date will default to the current day, month, year,
12099 hour and minute. If this command is called to replace a timestamp at point,
12100 of to enter the second timestamp of a range, the default time is taken from the
12101 existing stamp. For example,
12102 3-2-5 --> 2003-02-05
12103 feb 15 --> currentyear-02-15
12104 sep 12 9 --> 2009-09-12
12105 12:45 --> today 12:45
12106 22 sept 0:34 --> currentyear-09-22 0:34
12107 12 --> currentyear-currentmonth-12
12108 Fri --> nearest Friday (today or later)
12109 etc.
12111 Furthermore you can specify a relative date by giving, as the *first* thing
12112 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
12113 change in days weeks, months, years.
12114 With a single plus or minus, the date is relative to today. With a double
12115 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
12116 +4d --> four days from today
12117 +4 --> same as above
12118 +2w --> two weeks from today
12119 ++5 --> five days from default date
12121 The function understands only English month and weekday abbreviations,
12122 but this can be configured with the variables `parse-time-months' and
12123 `parse-time-weekdays'.
12125 While prompting, a calendar is popped up - you can also select the
12126 date with the mouse (button 1). The calendar shows a period of three
12127 months. To scroll it to other months, use the keys `>' and `<'.
12128 If you don't like the calendar, turn it off with
12129 \(setq org-read-date-popup-calendar nil)
12131 With optional argument TO-TIME, the date will immediately be converted
12132 to an internal time.
12133 With an optional argument WITH-TIME, the prompt will suggest to also
12134 insert a time. Note that when WITH-TIME is not set, you can still
12135 enter a time, and this function will inform the calling routine about
12136 this change. The calling routine may then choose to change the format
12137 used to insert the time stamp into the buffer to include the time.
12138 With optional argument FROM-STRING, read from this string instead from
12139 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
12140 the time/date that is used for everything that is not specified by the
12141 user."
12142 (require 'parse-time)
12143 (let* ((org-time-stamp-rounding-minutes
12144 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
12145 (org-dcst org-display-custom-times)
12146 (ct (org-current-time))
12147 (def (or org-overriding-default-time default-time ct))
12148 (defdecode (decode-time def))
12149 (dummy (progn
12150 (when (< (nth 2 defdecode) org-extend-today-until)
12151 (setcar (nthcdr 2 defdecode) -1)
12152 (setcar (nthcdr 1 defdecode) 59)
12153 (setq def (apply 'encode-time defdecode)
12154 defdecode (decode-time def)))))
12155 (calendar-move-hook nil)
12156 (calendar-view-diary-initially-flag nil)
12157 (view-diary-entries-initially nil)
12158 (calendar-view-holidays-initially-flag nil)
12159 (view-calendar-holidays-initially nil)
12160 (timestr (format-time-string
12161 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
12162 (prompt (concat (if prompt (concat prompt " ") "")
12163 (format "Date+time [%s]: " timestr)))
12164 ans (org-ans0 "") org-ans1 org-ans2 final)
12166 (cond
12167 (from-string (setq ans from-string))
12168 (org-read-date-popup-calendar
12169 (save-excursion
12170 (save-window-excursion
12171 (calendar)
12172 (calendar-forward-day (- (time-to-days def)
12173 (calendar-absolute-from-gregorian
12174 (calendar-current-date))))
12175 (org-eval-in-calendar nil t)
12176 (let* ((old-map (current-local-map))
12177 (map (copy-keymap calendar-mode-map))
12178 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12179 (org-defkey map (kbd "RET") 'org-calendar-select)
12180 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
12181 'org-calendar-select-mouse)
12182 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
12183 'org-calendar-select-mouse)
12184 (org-defkey minibuffer-local-map [(meta shift left)]
12185 (lambda () (interactive)
12186 (org-eval-in-calendar '(calendar-backward-month 1))))
12187 (org-defkey minibuffer-local-map [(meta shift right)]
12188 (lambda () (interactive)
12189 (org-eval-in-calendar '(calendar-forward-month 1))))
12190 (org-defkey minibuffer-local-map [(meta shift up)]
12191 (lambda () (interactive)
12192 (org-eval-in-calendar '(calendar-backward-year 1))))
12193 (org-defkey minibuffer-local-map [(meta shift down)]
12194 (lambda () (interactive)
12195 (org-eval-in-calendar '(calendar-forward-year 1))))
12196 (org-defkey minibuffer-local-map [(shift up)]
12197 (lambda () (interactive)
12198 (org-eval-in-calendar '(calendar-backward-week 1))))
12199 (org-defkey minibuffer-local-map [(shift down)]
12200 (lambda () (interactive)
12201 (org-eval-in-calendar '(calendar-forward-week 1))))
12202 (org-defkey minibuffer-local-map [(shift left)]
12203 (lambda () (interactive)
12204 (org-eval-in-calendar '(calendar-backward-day 1))))
12205 (org-defkey minibuffer-local-map [(shift right)]
12206 (lambda () (interactive)
12207 (org-eval-in-calendar '(calendar-forward-day 1))))
12208 (org-defkey minibuffer-local-map ">"
12209 (lambda () (interactive)
12210 (org-eval-in-calendar '(scroll-calendar-left 1))))
12211 (org-defkey minibuffer-local-map "<"
12212 (lambda () (interactive)
12213 (org-eval-in-calendar '(scroll-calendar-right 1))))
12214 (run-hooks 'org-read-date-minibuffer-setup-hook)
12215 (unwind-protect
12216 (progn
12217 (use-local-map map)
12218 (add-hook 'post-command-hook 'org-read-date-display)
12219 (setq org-ans0 (read-string prompt default-input
12220 'org-read-date-history nil))
12221 ;; org-ans0: from prompt
12222 ;; org-ans1: from mouse click
12223 ;; org-ans2: from calendar motion
12224 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
12225 (remove-hook 'post-command-hook 'org-read-date-display)
12226 (use-local-map old-map)
12227 (when org-read-date-overlay
12228 (org-delete-overlay org-read-date-overlay)
12229 (setq org-read-date-overlay nil)))))))
12231 (t ; Naked prompt only
12232 (unwind-protect
12233 (setq ans (read-string prompt default-input
12234 'org-read-date-history timestr))
12235 (when org-read-date-overlay
12236 (org-delete-overlay org-read-date-overlay)
12237 (setq org-read-date-overlay nil)))))
12239 (setq final (org-read-date-analyze ans def defdecode))
12241 (if to-time
12242 (apply 'encode-time final)
12243 (if (and (boundp 'org-time-was-given) org-time-was-given)
12244 (format "%04d-%02d-%02d %02d:%02d"
12245 (nth 5 final) (nth 4 final) (nth 3 final)
12246 (nth 2 final) (nth 1 final))
12247 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
12248 (defvar def)
12249 (defvar defdecode)
12250 (defvar with-time)
12251 (defun org-read-date-display ()
12252 "Display the current date prompt interpretation in the minibuffer."
12253 (when org-read-date-display-live
12254 (when org-read-date-overlay
12255 (org-delete-overlay org-read-date-overlay))
12256 (let ((p (point)))
12257 (end-of-line 1)
12258 (while (not (equal (buffer-substring
12259 (max (point-min) (- (point) 4)) (point))
12260 " "))
12261 (insert " "))
12262 (goto-char p))
12263 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
12264 " " (or org-ans1 org-ans2)))
12265 (org-end-time-was-given nil)
12266 (f (org-read-date-analyze ans def defdecode))
12267 (fmts (if org-dcst
12268 org-time-stamp-custom-formats
12269 org-time-stamp-formats))
12270 (fmt (if (or with-time
12271 (and (boundp 'org-time-was-given) org-time-was-given))
12272 (cdr fmts)
12273 (car fmts)))
12274 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
12275 (when (and org-end-time-was-given
12276 (string-match org-plain-time-of-day-regexp txt))
12277 (setq txt (concat (substring txt 0 (match-end 0)) "-"
12278 org-end-time-was-given
12279 (substring txt (match-end 0)))))
12280 (setq org-read-date-overlay
12281 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
12282 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
12284 (defun org-read-date-analyze (ans def defdecode)
12285 "Analyse the combined answer of the date prompt."
12286 ;; FIXME: cleanup and comment
12287 (let (delta deltan deltaw deltadef year month day
12288 hour minute second wday pm h2 m2 tl wday1
12289 iso-year iso-weekday iso-week iso-year iso-date)
12291 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
12292 (setq ans "+0"))
12294 (when (setq delta (org-read-date-get-relative ans (current-time) def))
12295 (setq ans (replace-match "" t t ans)
12296 deltan (car delta)
12297 deltaw (nth 1 delta)
12298 deltadef (nth 2 delta)))
12300 ;; Check if there is an iso week date in there
12301 ;; If yes, sore the info and postpone interpreting it until the rest
12302 ;; of the parsing is done
12303 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
12304 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
12305 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
12306 iso-week (string-to-number (match-string 2 ans)))
12307 (setq ans (replace-match "" t t ans)))
12309 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
12310 (when (string-match
12311 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
12312 (setq year (if (match-end 2)
12313 (string-to-number (match-string 2 ans))
12314 (string-to-number (format-time-string "%Y")))
12315 month (string-to-number (match-string 3 ans))
12316 day (string-to-number (match-string 4 ans)))
12317 (if (< year 100) (setq year (+ 2000 year)))
12318 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
12319 t nil ans)))
12320 ;; Help matching am/pm times, because `parse-time-string' does not do that.
12321 ;; If there is a time with am/pm, and *no* time without it, we convert
12322 ;; so that matching will be successful.
12323 (loop for i from 1 to 2 do ; twice, for end time as well
12324 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
12325 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
12326 (setq hour (string-to-number (match-string 1 ans))
12327 minute (if (match-end 3)
12328 (string-to-number (match-string 3 ans))
12330 pm (equal ?p
12331 (string-to-char (downcase (match-string 4 ans)))))
12332 (if (and (= hour 12) (not pm))
12333 (setq hour 0)
12334 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
12335 (setq ans (replace-match (format "%02d:%02d" hour minute)
12336 t t ans))))
12338 ;; Check if a time range is given as a duration
12339 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
12340 (setq hour (string-to-number (match-string 1 ans))
12341 h2 (+ hour (string-to-number (match-string 3 ans)))
12342 minute (string-to-number (match-string 2 ans))
12343 m2 (+ minute (if (match-end 5) (string-to-number
12344 (match-string 5 ans))0)))
12345 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
12346 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
12347 t t ans)))
12349 ;; Check if there is a time range
12350 (when (boundp 'org-end-time-was-given)
12351 (setq org-time-was-given nil)
12352 (when (and (string-match org-plain-time-of-day-regexp ans)
12353 (match-end 8))
12354 (setq org-end-time-was-given (match-string 8 ans))
12355 (setq ans (concat (substring ans 0 (match-beginning 7))
12356 (substring ans (match-end 7))))))
12358 (setq tl (parse-time-string ans)
12359 day (or (nth 3 tl) (nth 3 defdecode))
12360 month (or (nth 4 tl)
12361 (if (and org-read-date-prefer-future
12362 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
12363 (1+ (nth 4 defdecode))
12364 (nth 4 defdecode)))
12365 year (or (nth 5 tl)
12366 (if (and org-read-date-prefer-future
12367 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
12368 (1+ (nth 5 defdecode))
12369 (nth 5 defdecode)))
12370 hour (or (nth 2 tl) (nth 2 defdecode))
12371 minute (or (nth 1 tl) (nth 1 defdecode))
12372 second (or (nth 0 tl) 0)
12373 wday (nth 6 tl))
12375 ;; Special date definitions below
12376 (cond
12377 (iso-week
12378 ;; There was an iso week
12379 (setq year (or iso-year year)
12380 day (or iso-weekday wday 1)
12381 wday nil ; to make sure that the trigger below does not match
12382 iso-date (calendar-gregorian-from-absolute
12383 (calendar-absolute-from-iso
12384 (list iso-week day year))))
12385 ; FIXME: Should we also push ISO weeks into the future?
12386 ; (when (and org-read-date-prefer-future
12387 ; (not iso-year)
12388 ; (< (calendar-absolute-from-gregorian iso-date)
12389 ; (time-to-days (current-time))))
12390 ; (setq year (1+ year)
12391 ; iso-date (calendar-gregorian-from-absolute
12392 ; (calendar-absolute-from-iso
12393 ; (list iso-week day year)))))
12394 (setq month (car iso-date)
12395 year (nth 2 iso-date)
12396 day (nth 1 iso-date)))
12397 (deltan
12398 (unless deltadef
12399 (let ((now (decode-time (current-time))))
12400 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
12401 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
12402 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
12403 ((equal deltaw "m") (setq month (+ month deltan)))
12404 ((equal deltaw "y") (setq year (+ year deltan)))))
12405 ((and wday (not (nth 3 tl)))
12406 ;; Weekday was given, but no day, so pick that day in the week
12407 ;; on or after the derived date.
12408 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
12409 (unless (equal wday wday1)
12410 (setq day (+ day (% (- wday wday1 -7) 7))))))
12411 (if (and (boundp 'org-time-was-given)
12412 (nth 2 tl))
12413 (setq org-time-was-given t))
12414 (if (< year 100) (setq year (+ 2000 year)))
12415 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
12416 (list second minute hour day month year)))
12418 (defvar parse-time-weekdays)
12420 (defun org-read-date-get-relative (s today default)
12421 "Check string S for special relative date string.
12422 TODAY and DEFAULT are internal times, for today and for a default.
12423 Return shift list (N what def-flag)
12424 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
12425 N is the number of WHATs to shift.
12426 DEF-FLAG is t when a double ++ or -- indicates shift relative to
12427 the DEFAULT date rather than TODAY."
12428 (when (and
12429 (string-match
12430 (concat
12431 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
12432 "\\([0-9]+\\)?"
12433 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
12434 "\\([ \t]\\|$\\)") s)
12435 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
12436 (let* ((dir (if (> (match-end 1) (match-beginning 1))
12437 (string-to-char (substring (match-string 1 s) -1))
12438 ?+))
12439 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
12440 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
12441 (what (if (match-end 3) (match-string 3 s) "d"))
12442 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
12443 (date (if rel default today))
12444 (wday (nth 6 (decode-time date)))
12445 delta)
12446 (if wday1
12447 (progn
12448 (setq delta (mod (+ 7 (- wday1 wday)) 7))
12449 (if (= dir ?-) (setq delta (- delta 7)))
12450 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
12451 (list delta "d" rel))
12452 (list (* n (if (= dir ?-) -1 1)) what rel)))))
12454 (defun org-eval-in-calendar (form &optional keepdate)
12455 "Eval FORM in the calendar window and return to current window.
12456 Also, store the cursor date in variable org-ans2."
12457 (let ((sw (selected-window)))
12458 (select-window (get-buffer-window "*Calendar*"))
12459 (eval form)
12460 (when (and (not keepdate) (calendar-cursor-to-date))
12461 (let* ((date (calendar-cursor-to-date))
12462 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12463 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
12464 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
12465 (select-window sw)))
12467 (defun org-calendar-select ()
12468 "Return to `org-read-date' with the date currently selected.
12469 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12470 (interactive)
12471 (when (calendar-cursor-to-date)
12472 (let* ((date (calendar-cursor-to-date))
12473 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12474 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12475 (if (active-minibuffer-window) (exit-minibuffer))))
12477 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
12478 "Insert a date stamp for the date given by the internal TIME.
12479 WITH-HM means, use the stamp format that includes the time of the day.
12480 INACTIVE means use square brackets instead of angular ones, so that the
12481 stamp will not contribute to the agenda.
12482 PRE and POST are optional strings to be inserted before and after the
12483 stamp.
12484 The command returns the inserted time stamp."
12485 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
12486 stamp)
12487 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
12488 (insert-before-markers (or pre ""))
12489 (insert-before-markers (setq stamp (format-time-string fmt time)))
12490 (when (listp extra)
12491 (setq extra (car extra))
12492 (if (and (stringp extra)
12493 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
12494 (setq extra (format "-%02d:%02d"
12495 (string-to-number (match-string 1 extra))
12496 (string-to-number (match-string 2 extra))))
12497 (setq extra nil)))
12498 (when extra
12499 (backward-char 1)
12500 (insert-before-markers extra)
12501 (forward-char 1))
12502 (insert-before-markers (or post ""))
12503 (setq org-last-inserted-timestamp stamp)))
12505 (defun org-toggle-time-stamp-overlays ()
12506 "Toggle the use of custom time stamp formats."
12507 (interactive)
12508 (setq org-display-custom-times (not org-display-custom-times))
12509 (unless org-display-custom-times
12510 (let ((p (point-min)) (bmp (buffer-modified-p)))
12511 (while (setq p (next-single-property-change p 'display))
12512 (if (and (get-text-property p 'display)
12513 (eq (get-text-property p 'face) 'org-date))
12514 (remove-text-properties
12515 p (setq p (next-single-property-change p 'display))
12516 '(display t))))
12517 (set-buffer-modified-p bmp)))
12518 (if (featurep 'xemacs)
12519 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12520 (org-restart-font-lock)
12521 (setq org-table-may-need-update t)
12522 (if org-display-custom-times
12523 (message "Time stamps are overlayed with custom format")
12524 (message "Time stamp overlays removed")))
12526 (defun org-display-custom-time (beg end)
12527 "Overlay modified time stamp format over timestamp between BEG and END."
12528 (let* ((ts (buffer-substring beg end))
12529 t1 w1 with-hm tf time str w2 (off 0))
12530 (save-match-data
12531 (setq t1 (org-parse-time-string ts t))
12532 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
12533 (setq off (- (match-end 0) (match-beginning 0)))))
12534 (setq end (- end off))
12535 (setq w1 (- end beg)
12536 with-hm (and (nth 1 t1) (nth 2 t1))
12537 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
12538 time (org-fix-decoded-time t1)
12539 str (org-add-props
12540 (format-time-string
12541 (substring tf 1 -1) (apply 'encode-time time))
12542 nil 'mouse-face 'highlight)
12543 w2 (length str))
12544 (if (not (= w2 w1))
12545 (add-text-properties (1+ beg) (+ 2 beg)
12546 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12547 (if (featurep 'xemacs)
12548 (progn
12549 (put-text-property beg end 'invisible t)
12550 (put-text-property beg end 'end-glyph (make-glyph str)))
12551 (put-text-property beg end 'display str))))
12553 (defun org-translate-time (string)
12554 "Translate all timestamps in STRING to custom format.
12555 But do this only if the variable `org-display-custom-times' is set."
12556 (when org-display-custom-times
12557 (save-match-data
12558 (let* ((start 0)
12559 (re org-ts-regexp-both)
12560 t1 with-hm inactive tf time str beg end)
12561 (while (setq start (string-match re string start))
12562 (setq beg (match-beginning 0)
12563 end (match-end 0)
12564 t1 (save-match-data
12565 (org-parse-time-string (substring string beg end) t))
12566 with-hm (and (nth 1 t1) (nth 2 t1))
12567 inactive (equal (substring string beg (1+ beg)) "[")
12568 tf (funcall (if with-hm 'cdr 'car)
12569 org-time-stamp-custom-formats)
12570 time (org-fix-decoded-time t1)
12571 str (format-time-string
12572 (concat
12573 (if inactive "[" "<") (substring tf 1 -1)
12574 (if inactive "]" ">"))
12575 (apply 'encode-time time))
12576 string (replace-match str t t string)
12577 start (+ start (length str)))))))
12578 string)
12580 (defun org-fix-decoded-time (time)
12581 "Set 0 instead of nil for the first 6 elements of time.
12582 Don't touch the rest."
12583 (let ((n 0))
12584 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12586 (defun org-days-to-time (timestamp-string)
12587 "Difference between TIMESTAMP-STRING and now in days."
12588 (- (time-to-days (org-time-string-to-time timestamp-string))
12589 (time-to-days (current-time))))
12591 (defun org-deadline-close (timestamp-string &optional ndays)
12592 "Is the time in TIMESTAMP-STRING close to the current date?"
12593 (setq ndays (or ndays (org-get-wdays timestamp-string)))
12594 (and (< (org-days-to-time timestamp-string) ndays)
12595 (not (org-entry-is-done-p))))
12597 (defun org-get-wdays (ts)
12598 "Get the deadline lead time appropriate for timestring TS."
12599 (cond
12600 ((<= org-deadline-warning-days 0)
12601 ;; 0 or negative, enforce this value no matter what
12602 (- org-deadline-warning-days))
12603 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
12604 ;; lead time is specified.
12605 (floor (* (string-to-number (match-string 1 ts))
12606 (cdr (assoc (match-string 2 ts)
12607 '(("d" . 1) ("w" . 7)
12608 ("m" . 30.4) ("y" . 365.25)))))))
12609 ;; go for the default.
12610 (t org-deadline-warning-days)))
12612 (defun org-calendar-select-mouse (ev)
12613 "Return to `org-read-date' with the date currently selected.
12614 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12615 (interactive "e")
12616 (mouse-set-point ev)
12617 (when (calendar-cursor-to-date)
12618 (let* ((date (calendar-cursor-to-date))
12619 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12620 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12621 (if (active-minibuffer-window) (exit-minibuffer))))
12623 (defun org-check-deadlines (ndays)
12624 "Check if there are any deadlines due or past due.
12625 A deadline is considered due if it happens within `org-deadline-warning-days'
12626 days from today's date. If the deadline appears in an entry marked DONE,
12627 it is not shown. The prefix arg NDAYS can be used to test that many
12628 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12629 (interactive "P")
12630 (let* ((org-warn-days
12631 (cond
12632 ((equal ndays '(4)) 100000)
12633 (ndays (prefix-numeric-value ndays))
12634 (t (abs org-deadline-warning-days))))
12635 (case-fold-search nil)
12636 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12637 (callback
12638 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12640 (message "%d deadlines past-due or due within %d days"
12641 (org-occur regexp nil callback)
12642 org-warn-days)))
12644 (defun org-check-before-date (date)
12645 "Check if there are deadlines or scheduled entries before DATE."
12646 (interactive (list (org-read-date)))
12647 (let ((case-fold-search nil)
12648 (regexp (concat "\\<\\(" org-deadline-string
12649 "\\|" org-scheduled-string
12650 "\\) *<\\([^>]+\\)>"))
12651 (callback
12652 (lambda () (time-less-p
12653 (org-time-string-to-time (match-string 2))
12654 (org-time-string-to-time date)))))
12655 (message "%d entries before %s"
12656 (org-occur regexp nil callback) date)))
12658 (defun org-check-after-date (date)
12659 "Check if there are deadlines or scheduled entries after DATE."
12660 (interactive (list (org-read-date)))
12661 (let ((case-fold-search nil)
12662 (regexp (concat "\\<\\(" org-deadline-string
12663 "\\|" org-scheduled-string
12664 "\\) *<\\([^>]+\\)>"))
12665 (callback
12666 (lambda () (not
12667 (time-less-p
12668 (org-time-string-to-time (match-string 2))
12669 (org-time-string-to-time date))))))
12670 (message "%d entries after %s"
12671 (org-occur regexp nil callback) date)))
12673 (defun org-evaluate-time-range (&optional to-buffer)
12674 "Evaluate a time range by computing the difference between start and end.
12675 Normally the result is just printed in the echo area, but with prefix arg
12676 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12677 If the time range is actually in a table, the result is inserted into the
12678 next column.
12679 For time difference computation, a year is assumed to be exactly 365
12680 days in order to avoid rounding problems."
12681 (interactive "P")
12683 (org-clock-update-time-maybe)
12684 (save-excursion
12685 (unless (org-at-date-range-p t)
12686 (goto-char (point-at-bol))
12687 (re-search-forward org-tr-regexp-both (point-at-eol) t))
12688 (if (not (org-at-date-range-p t))
12689 (error "Not at a time-stamp range, and none found in current line")))
12690 (let* ((ts1 (match-string 1))
12691 (ts2 (match-string 2))
12692 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12693 (match-end (match-end 0))
12694 (time1 (org-time-string-to-time ts1))
12695 (time2 (org-time-string-to-time ts2))
12696 (t1 (time-to-seconds time1))
12697 (t2 (time-to-seconds time2))
12698 (diff (abs (- t2 t1)))
12699 (negative (< (- t2 t1) 0))
12700 ;; (ys (floor (* 365 24 60 60)))
12701 (ds (* 24 60 60))
12702 (hs (* 60 60))
12703 (fy "%dy %dd %02d:%02d")
12704 (fy1 "%dy %dd")
12705 (fd "%dd %02d:%02d")
12706 (fd1 "%dd")
12707 (fh "%02d:%02d")
12708 y d h m align)
12709 (if havetime
12710 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12712 d (floor (/ diff ds)) diff (mod diff ds)
12713 h (floor (/ diff hs)) diff (mod diff hs)
12714 m (floor (/ diff 60)))
12715 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12717 d (floor (+ (/ diff ds) 0.5))
12718 h 0 m 0))
12719 (if (not to-buffer)
12720 (message "%s" (org-make-tdiff-string y d h m))
12721 (if (org-at-table-p)
12722 (progn
12723 (goto-char match-end)
12724 (setq align t)
12725 (and (looking-at " *|") (goto-char (match-end 0))))
12726 (goto-char match-end))
12727 (if (looking-at
12728 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12729 (replace-match ""))
12730 (if negative (insert " -"))
12731 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12732 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12733 (insert " " (format fh h m))))
12734 (if align (org-table-align))
12735 (message "Time difference inserted")))))
12737 (defun org-make-tdiff-string (y d h m)
12738 (let ((fmt "")
12739 (l nil))
12740 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12741 l (push y l)))
12742 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12743 l (push d l)))
12744 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12745 l (push h l)))
12746 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12747 l (push m l)))
12748 (apply 'format fmt (nreverse l))))
12750 (defun org-time-string-to-time (s)
12751 (apply 'encode-time (org-parse-time-string s)))
12753 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
12754 "Convert a time stamp to an absolute day number.
12755 If there is a specifyer for a cyclic time stamp, get the closest date to
12756 DAYNR.
12757 PREFER and SHOW-ALL are passed through to `org-closest-date'."
12758 (cond
12759 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
12760 (if (org-diary-sexp-entry (match-string 1 s) "" date)
12761 daynr
12762 (+ daynr 1000)))
12763 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
12764 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
12765 (time-to-days (current-time))) (match-string 0 s)
12766 prefer show-all))
12767 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
12769 (defun org-days-to-iso-week (days)
12770 "Return the iso week number."
12771 (require 'cal-iso)
12772 (car (calendar-iso-from-absolute days)))
12774 (defun org-small-year-to-year (year)
12775 "Convert 2-digit years into 4-digit years.
12776 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
12777 The year 2000 cannot be abbreviated. Any year larger than 99
12778 is returned unchanged."
12779 (if (< year 38)
12780 (setq year (+ 2000 year))
12781 (if (< year 100)
12782 (setq year (+ 1900 year))))
12783 year)
12785 (defun org-time-from-absolute (d)
12786 "Return the time corresponding to date D.
12787 D may be an absolute day number, or a calendar-type list (month day year)."
12788 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
12789 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
12791 (defun org-calendar-holiday ()
12792 "List of holidays, for Diary display in Org-mode."
12793 (require 'holidays)
12794 (let ((hl (funcall
12795 (if (fboundp 'calendar-check-holidays)
12796 'calendar-check-holidays 'check-calendar-holidays) date)))
12797 (if hl (mapconcat 'identity hl "; "))))
12799 (defun org-diary-sexp-entry (sexp entry date)
12800 "Process a SEXP diary ENTRY for DATE."
12801 (require 'diary-lib)
12802 (let ((result (if calendar-debug-sexp
12803 (let ((stack-trace-on-error t))
12804 (eval (car (read-from-string sexp))))
12805 (condition-case nil
12806 (eval (car (read-from-string sexp)))
12807 (error
12808 (beep)
12809 (message "Bad sexp at line %d in %s: %s"
12810 (org-current-line)
12811 (buffer-file-name) sexp)
12812 (sleep-for 2))))))
12813 (cond ((stringp result) result)
12814 ((and (consp result)
12815 (stringp (cdr result))) (cdr result))
12816 (result entry)
12817 (t nil))))
12819 (defun org-diary-to-ical-string (frombuf)
12820 "Get iCalendar entries from diary entries in buffer FROMBUF.
12821 This uses the icalendar.el library."
12822 (let* ((tmpdir (if (featurep 'xemacs)
12823 (temp-directory)
12824 temporary-file-directory))
12825 (tmpfile (make-temp-name
12826 (expand-file-name "orgics" tmpdir)))
12827 buf rtn b e)
12828 (save-excursion
12829 (set-buffer frombuf)
12830 (icalendar-export-region (point-min) (point-max) tmpfile)
12831 (setq buf (find-buffer-visiting tmpfile))
12832 (set-buffer buf)
12833 (goto-char (point-min))
12834 (if (re-search-forward "^BEGIN:VEVENT" nil t)
12835 (setq b (match-beginning 0)))
12836 (goto-char (point-max))
12837 (if (re-search-backward "^END:VEVENT" nil t)
12838 (setq e (match-end 0)))
12839 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
12840 (kill-buffer buf)
12841 (delete-file tmpfile)
12842 rtn))
12844 (defun org-closest-date (start current change prefer show-all)
12845 "Find the date closest to CURRENT that is consistent with START and CHANGE.
12846 When PREFER is `past' return a date that is either CURRENT or past.
12847 When PREFER is `future', return a date that is either CURRENT or future.
12848 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
12849 ;; Make the proper lists from the dates
12850 (catch 'exit
12851 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
12852 dn dw sday cday n1 n2 n0
12853 d m y y1 y2 date1 date2 nmonths nm ny m2)
12855 (setq start (org-date-to-gregorian start)
12856 current (org-date-to-gregorian
12857 (if show-all
12858 current
12859 (time-to-days (current-time))))
12860 sday (calendar-absolute-from-gregorian start)
12861 cday (calendar-absolute-from-gregorian current))
12863 (if (<= cday sday) (throw 'exit sday))
12865 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
12866 (setq dn (string-to-number (match-string 1 change))
12867 dw (cdr (assoc (match-string 2 change) a1)))
12868 (error "Invalid change specifyer: %s" change))
12869 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
12870 (cond
12871 ((eq dw 'day)
12872 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
12873 n2 (+ n1 dn)))
12874 ((eq dw 'year)
12875 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
12876 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
12877 (setq date1 (list m d y1)
12878 n1 (calendar-absolute-from-gregorian date1)
12879 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
12880 n2 (calendar-absolute-from-gregorian date2)))
12881 ((eq dw 'month)
12882 ;; approx number of month between the two dates
12883 (setq nmonths (floor (/ (- cday sday) 30.436875)))
12884 ;; How often does dn fit in there?
12885 (setq d (nth 1 start) m (car start) y (nth 2 start)
12886 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
12887 m (+ m nm)
12888 ny (floor (/ m 12))
12889 y (+ y ny)
12890 m (- m (* ny 12)))
12891 (while (> m 12) (setq m (- m 12) y (1+ y)))
12892 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
12893 (setq m2 (+ m dn) y2 y)
12894 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12895 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
12896 (while (<= n2 cday)
12897 (setq n1 n2 m m2 y y2)
12898 (setq m2 (+ m dn) y2 y)
12899 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12900 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
12901 ;; Make sure n1 is the earlier date
12902 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
12903 (if show-all
12904 (cond
12905 ((eq prefer 'past) n1)
12906 ((eq prefer 'future) (if (= cday n1) n1 n2))
12907 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
12908 (cond
12909 ((eq prefer 'past) n1)
12910 ((eq prefer 'future) (if (= cday n1) n1 n2))
12911 (t (if (= cday n1) n1 n2)))))))
12913 (defun org-date-to-gregorian (date)
12914 "Turn any specification of DATE into a gregorian date for the calendar."
12915 (cond ((integerp date) (calendar-gregorian-from-absolute date))
12916 ((and (listp date) (= (length date) 3)) date)
12917 ((stringp date)
12918 (setq date (org-parse-time-string date))
12919 (list (nth 4 date) (nth 3 date) (nth 5 date)))
12920 ((listp date)
12921 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
12923 (defun org-parse-time-string (s &optional nodefault)
12924 "Parse the standard Org-mode time string.
12925 This should be a lot faster than the normal `parse-time-string'.
12926 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12927 hour and minute fields will be nil if not given."
12928 (if (string-match org-ts-regexp0 s)
12929 (list 0
12930 (if (or (match-beginning 8) (not nodefault))
12931 (string-to-number (or (match-string 8 s) "0")))
12932 (if (or (match-beginning 7) (not nodefault))
12933 (string-to-number (or (match-string 7 s) "0")))
12934 (string-to-number (match-string 4 s))
12935 (string-to-number (match-string 3 s))
12936 (string-to-number (match-string 2 s))
12937 nil nil nil)
12938 (make-list 9 0)))
12940 (defun org-timestamp-up (&optional arg)
12941 "Increase the date item at the cursor by one.
12942 If the cursor is on the year, change the year. If it is on the month or
12943 the day, change that.
12944 With prefix ARG, change by that many units."
12945 (interactive "p")
12946 (org-timestamp-change (prefix-numeric-value arg)))
12948 (defun org-timestamp-down (&optional arg)
12949 "Decrease the date item at the cursor by one.
12950 If the cursor is on the year, change the year. If it is on the month or
12951 the day, change that.
12952 With prefix ARG, change by that many units."
12953 (interactive "p")
12954 (org-timestamp-change (- (prefix-numeric-value arg))))
12956 (defun org-timestamp-up-day (&optional arg)
12957 "Increase the date in the time stamp by one day.
12958 With prefix ARG, change that many days."
12959 (interactive "p")
12960 (if (and (not (org-at-timestamp-p t))
12961 (org-on-heading-p))
12962 (org-todo 'up)
12963 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12965 (defun org-timestamp-down-day (&optional arg)
12966 "Decrease the date in the time stamp by one day.
12967 With prefix ARG, change that many days."
12968 (interactive "p")
12969 (if (and (not (org-at-timestamp-p t))
12970 (org-on-heading-p))
12971 (org-todo 'down)
12972 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12974 (defun org-at-timestamp-p (&optional inactive-ok)
12975 "Determine if the cursor is in or at a timestamp."
12976 (interactive)
12977 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12978 (pos (point))
12979 (ans (or (looking-at tsr)
12980 (save-excursion
12981 (skip-chars-backward "^[<\n\r\t")
12982 (if (> (point) (point-min)) (backward-char 1))
12983 (and (looking-at tsr)
12984 (> (- (match-end 0) pos) -1))))))
12985 (and ans
12986 (boundp 'org-ts-what)
12987 (setq org-ts-what
12988 (cond
12989 ((= pos (match-beginning 0)) 'bracket)
12990 ((= pos (1- (match-end 0))) 'bracket)
12991 ((org-pos-in-match-range pos 2) 'year)
12992 ((org-pos-in-match-range pos 3) 'month)
12993 ((org-pos-in-match-range pos 7) 'hour)
12994 ((org-pos-in-match-range pos 8) 'minute)
12995 ((or (org-pos-in-match-range pos 4)
12996 (org-pos-in-match-range pos 5)) 'day)
12997 ((and (> pos (or (match-end 8) (match-end 5)))
12998 (< pos (match-end 0)))
12999 (- pos (or (match-end 8) (match-end 5))))
13000 (t 'day))))
13001 ans))
13003 (defun org-toggle-timestamp-type ()
13004 "Toggle the type (<active> or [inactive]) of a time stamp."
13005 (interactive)
13006 (when (org-at-timestamp-p t)
13007 (let ((beg (match-beginning 0)) (end (match-end 0))
13008 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
13009 (save-excursion
13010 (goto-char beg)
13011 (while (re-search-forward "[][<>]" end t)
13012 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
13013 t t)))
13014 (message "Timestamp is now %sactive"
13015 (if (equal (char-after beg) ?<) "" "in")))))
13017 (defun org-timestamp-change (n &optional what)
13018 "Change the date in the time stamp at point.
13019 The date will be changed by N times WHAT. WHAT can be `day', `month',
13020 `year', `minute', `second'. If WHAT is not given, the cursor position
13021 in the timestamp determines what will be changed."
13022 (let ((pos (point))
13023 with-hm inactive
13024 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
13025 org-ts-what
13026 extra rem
13027 ts time time0)
13028 (if (not (org-at-timestamp-p t))
13029 (error "Not at a timestamp"))
13030 (if (and (not what) (eq org-ts-what 'bracket))
13031 (org-toggle-timestamp-type)
13032 (if (and (not what) (not (eq org-ts-what 'day))
13033 org-display-custom-times
13034 (get-text-property (point) 'display)
13035 (not (get-text-property (1- (point)) 'display)))
13036 (setq org-ts-what 'day))
13037 (setq org-ts-what (or what org-ts-what)
13038 inactive (= (char-after (match-beginning 0)) ?\[)
13039 ts (match-string 0))
13040 (replace-match "")
13041 (if (string-match
13042 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
13044 (setq extra (match-string 1 ts)))
13045 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
13046 (setq with-hm t))
13047 (setq time0 (org-parse-time-string ts))
13048 (when (and (eq org-ts-what 'minute)
13049 (eq current-prefix-arg nil))
13050 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
13051 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
13052 (setcar (cdr time0) (+ (nth 1 time0)
13053 (if (> n 0) (- rem) (- dm rem))))))
13054 (setq time
13055 (encode-time (or (car time0) 0)
13056 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
13057 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
13058 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
13059 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
13060 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
13061 (nthcdr 6 time0)))
13062 (when (and (member org-ts-what '(hour minute))
13063 extra
13064 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
13065 (setq extra (org-modify-ts-extra
13066 extra
13067 (if (eq org-ts-what 'hour) 2 5)
13068 n dm)))
13069 (when (integerp org-ts-what)
13070 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
13071 (if (eq what 'calendar)
13072 (let ((cal-date (org-get-date-from-calendar)))
13073 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
13074 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
13075 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
13076 (setcar time0 (or (car time0) 0))
13077 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
13078 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
13079 (setq time (apply 'encode-time time0))))
13080 (setq org-last-changed-timestamp
13081 (org-insert-time-stamp time with-hm inactive nil nil extra))
13082 (org-clock-update-time-maybe)
13083 (goto-char pos)
13084 ;; Try to recenter the calendar window, if any
13085 (if (and org-calendar-follow-timestamp-change
13086 (get-buffer-window "*Calendar*" t)
13087 (memq org-ts-what '(day month year)))
13088 (org-recenter-calendar (time-to-days time))))))
13090 (defun org-modify-ts-extra (s pos n dm)
13091 "Change the different parts of the lead-time and repeat fields in timestamp."
13092 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
13093 ng h m new rem)
13094 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
13095 (cond
13096 ((or (org-pos-in-match-range pos 2)
13097 (org-pos-in-match-range pos 3))
13098 (setq m (string-to-number (match-string 3 s))
13099 h (string-to-number (match-string 2 s)))
13100 (if (org-pos-in-match-range pos 2)
13101 (setq h (+ h n))
13102 (setq n (* dm (org-no-warnings (signum n))))
13103 (when (not (= 0 (setq rem (% m dm))))
13104 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
13105 (setq m (+ m n)))
13106 (if (< m 0) (setq m (+ m 60) h (1- h)))
13107 (if (> m 59) (setq m (- m 60) h (1+ h)))
13108 (setq h (min 24 (max 0 h)))
13109 (setq ng 1 new (format "-%02d:%02d" h m)))
13110 ((org-pos-in-match-range pos 6)
13111 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
13112 ((org-pos-in-match-range pos 5)
13113 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
13115 ((org-pos-in-match-range pos 9)
13116 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
13117 ((org-pos-in-match-range pos 8)
13118 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
13120 (when ng
13121 (setq s (concat
13122 (substring s 0 (match-beginning ng))
13124 (substring s (match-end ng))))))
13127 (defun org-recenter-calendar (date)
13128 "If the calendar is visible, recenter it to DATE."
13129 (let* ((win (selected-window))
13130 (cwin (get-buffer-window "*Calendar*" t))
13131 (calendar-move-hook nil))
13132 (when cwin
13133 (select-window cwin)
13134 (calendar-goto-date (if (listp date) date
13135 (calendar-gregorian-from-absolute date)))
13136 (select-window win))))
13138 (defun org-goto-calendar (&optional arg)
13139 "Go to the Emacs calendar at the current date.
13140 If there is a time stamp in the current line, go to that date.
13141 A prefix ARG can be used to force the current date."
13142 (interactive "P")
13143 (let ((tsr org-ts-regexp) diff
13144 (calendar-move-hook nil)
13145 (calendar-view-holidays-initially-flag nil)
13146 (view-calendar-holidays-initially nil)
13147 (calendar-view-diary-initially-flag nil)
13148 (view-diary-entries-initially nil))
13149 (if (or (org-at-timestamp-p)
13150 (save-excursion
13151 (beginning-of-line 1)
13152 (looking-at (concat ".*" tsr))))
13153 (let ((d1 (time-to-days (current-time)))
13154 (d2 (time-to-days
13155 (org-time-string-to-time (match-string 1)))))
13156 (setq diff (- d2 d1))))
13157 (calendar)
13158 (calendar-goto-today)
13159 (if (and diff (not arg)) (calendar-forward-day diff))))
13161 (defun org-get-date-from-calendar ()
13162 "Return a list (month day year) of date at point in calendar."
13163 (with-current-buffer "*Calendar*"
13164 (save-match-data
13165 (calendar-cursor-to-date))))
13167 (defun org-date-from-calendar ()
13168 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
13169 If there is already a time stamp at the cursor position, update it."
13170 (interactive)
13171 (if (org-at-timestamp-p t)
13172 (org-timestamp-change 0 'calendar)
13173 (let ((cal-date (org-get-date-from-calendar)))
13174 (org-insert-time-stamp
13175 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
13177 (defun org-minutes-to-hh:mm-string (m)
13178 "Compute H:MM from a number of minutes."
13179 (let ((h (/ m 60)))
13180 (setq m (- m (* 60 h)))
13181 (format org-time-clocksum-format h m)))
13183 (defun org-hh:mm-string-to-minutes (s)
13184 "Convert a string H:MM to a number of minutes."
13185 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
13186 (+ (* (string-to-number (match-string 1 s)) 60)
13187 (string-to-number (match-string 2 s)))
13190 ;;;; Files
13192 (defun org-save-all-org-buffers ()
13193 "Save all Org-mode buffers without user confirmation."
13194 (interactive)
13195 (message "Saving all Org-mode buffers...")
13196 (save-some-buffers t 'org-mode-p)
13197 (when (featurep 'org-id) (org-id-locations-save))
13198 (message "Saving all Org-mode buffers... done"))
13200 (defun org-revert-all-org-buffers ()
13201 "Revert all Org-mode buffers.
13202 Prompt for confirmation when there are unsaved changes.
13203 Be sure you know what you are doing before letting this function
13204 overwrite your changes.
13206 This function is useful in a setup where one tracks org files
13207 with a version control system, to revert on one machine after pulling
13208 changes from another. I believe the procedure must be like this:
13210 1. M-x org-save-all-org-buffers
13211 2. Pull changes from the other machine, resolve conflicts
13212 3. M-x org-revert-all-org-buffers"
13213 (interactive)
13214 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
13215 (error "Abort"))
13216 (save-excursion
13217 (save-window-excursion
13218 (mapc
13219 (lambda (b)
13220 (when (and (with-current-buffer b (org-mode-p))
13221 (with-current-buffer b buffer-file-name))
13222 (switch-to-buffer b)
13223 (revert-buffer t 'no-confirm)))
13224 (buffer-list))
13225 (when (and (featurep 'org-id) org-id-track-globally)
13226 (org-id-locations-load)))))
13228 ;;;; Agenda files
13230 ;;;###autoload
13231 (defun org-iswitchb (&optional arg)
13232 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
13233 With a prefix argument, restrict available to files.
13234 With two prefix arguments, restrict available buffers to agenda files.
13236 Due to some yet unresolved reason, the global function
13237 `iswitchb-mode' needs to be active for this function to work."
13238 (interactive "P")
13239 (require 'iswitchb)
13240 (let ((enabled iswitchb-mode) blist)
13241 (or enabled (iswitchb-mode 1))
13242 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13243 ((equal arg '(16)) (org-buffer-list 'agenda))
13244 (t (org-buffer-list))))
13245 (unwind-protect
13246 (let ((iswitchb-make-buflist-hook
13247 (lambda ()
13248 (setq iswitchb-temp-buflist
13249 (mapcar 'buffer-name blist)))))
13250 (switch-to-buffer
13251 (iswitchb-read-buffer
13252 "Switch-to: " nil t))
13253 (or enabled (iswitchb-mode -1))))))
13255 ;;;###autoload
13256 (defun org-ido-switchb (&optional arg)
13257 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
13258 With a prefix argument, restrict available to files.
13259 With two prefix arguments, restrict available buffers to agenda files."
13260 (interactive "P")
13261 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13262 ((equal arg '(16)) (org-buffer-list 'agenda))
13263 (t (org-buffer-list)))))
13264 (switch-to-buffer
13265 (org-ido-completing-read "Org buffer: "
13266 (mapcar 'list (mapcar 'buffer-name blist))
13267 nil t))))
13269 (defun org-buffer-list (&optional predicate exclude-tmp)
13270 "Return a list of Org buffers.
13271 PREDICATE can be `export', `files' or `agenda'.
13273 export restrict the list to Export buffers.
13274 files restrict the list to buffers visiting Org files.
13275 agenda restrict the list to buffers visiting agenda files.
13277 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
13278 (let* ((bfn nil)
13279 (agenda-files (and (eq predicate 'agenda)
13280 (mapcar 'file-truename (org-agenda-files t))))
13281 (filter
13282 (cond
13283 ((eq predicate 'files)
13284 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
13285 ((eq predicate 'export)
13286 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
13287 ((eq predicate 'agenda)
13288 (lambda (b)
13289 (with-current-buffer b
13290 (and (eq major-mode 'org-mode)
13291 (setq bfn (buffer-file-name b))
13292 (member (file-truename bfn) agenda-files)))))
13293 (t (lambda (b) (with-current-buffer b
13294 (or (eq major-mode 'org-mode)
13295 (string-match "\*Org .*Export"
13296 (buffer-name b)))))))))
13297 (delq nil
13298 (mapcar
13299 (lambda(b)
13300 (if (and (funcall filter b)
13301 (or (not exclude-tmp)
13302 (not (string-match "tmp" (buffer-name b)))))
13304 nil))
13305 (buffer-list)))))
13307 (defun org-agenda-files (&optional unrestricted archives)
13308 "Get the list of agenda files.
13309 Optional UNRESTRICTED means return the full list even if a restriction
13310 is currently in place.
13311 When ARCHIVES is t, include all archive files hat are really being
13312 used by the agenda files. If ARCHIVE is `ifmode', do this only if
13313 `org-agenda-archives-mode' is t."
13314 (let ((files
13315 (cond
13316 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
13317 ((stringp org-agenda-files) (org-read-agenda-file-list))
13318 ((listp org-agenda-files) org-agenda-files)
13319 (t (error "Invalid value of `org-agenda-files'")))))
13320 (setq files (apply 'append
13321 (mapcar (lambda (f)
13322 (if (file-directory-p f)
13323 (directory-files
13324 f t org-agenda-file-regexp)
13325 (list f)))
13326 files)))
13327 (when org-agenda-skip-unavailable-files
13328 (setq files (delq nil
13329 (mapcar (function
13330 (lambda (file)
13331 (and (file-readable-p file) file)))
13332 files))))
13333 (when (or (eq archives t)
13334 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
13335 (setq files (org-add-archive-files files)))
13336 files))
13338 (defun org-edit-agenda-file-list ()
13339 "Edit the list of agenda files.
13340 Depending on setup, this either uses customize to edit the variable
13341 `org-agenda-files', or it visits the file that is holding the list. In the
13342 latter case, the buffer is set up in a way that saving it automatically kills
13343 the buffer and restores the previous window configuration."
13344 (interactive)
13345 (if (stringp org-agenda-files)
13346 (let ((cw (current-window-configuration)))
13347 (find-file org-agenda-files)
13348 (org-set-local 'org-window-configuration cw)
13349 (org-add-hook 'after-save-hook
13350 (lambda ()
13351 (set-window-configuration
13352 (prog1 org-window-configuration
13353 (kill-buffer (current-buffer))))
13354 (org-install-agenda-files-menu)
13355 (message "New agenda file list installed"))
13356 nil 'local)
13357 (message "%s" (substitute-command-keys
13358 "Edit list and finish with \\[save-buffer]")))
13359 (customize-variable 'org-agenda-files)))
13361 (defun org-store-new-agenda-file-list (list)
13362 "Set new value for the agenda file list and save it correctly."
13363 (if (stringp org-agenda-files)
13364 (let ((f org-agenda-files) b)
13365 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
13366 (with-temp-file f
13367 (insert (mapconcat 'identity list "\n") "\n")))
13368 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
13369 (setq org-agenda-files list)
13370 (customize-save-variable 'org-agenda-files org-agenda-files))))
13372 (defun org-read-agenda-file-list ()
13373 "Read the list of agenda files from a file."
13374 (when (file-directory-p org-agenda-files)
13375 (error "`org-agenda-files' cannot be a single directory"))
13376 (when (stringp org-agenda-files)
13377 (with-temp-buffer
13378 (insert-file-contents org-agenda-files)
13379 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
13382 ;;;###autoload
13383 (defun org-cycle-agenda-files ()
13384 "Cycle through the files in `org-agenda-files'.
13385 If the current buffer visits an agenda file, find the next one in the list.
13386 If the current buffer does not, find the first agenda file."
13387 (interactive)
13388 (let* ((fs (org-agenda-files t))
13389 (files (append fs (list (car fs))))
13390 (tcf (if buffer-file-name (file-truename buffer-file-name)))
13391 file)
13392 (unless files (error "No agenda files"))
13393 (catch 'exit
13394 (while (setq file (pop files))
13395 (if (equal (file-truename file) tcf)
13396 (when (car files)
13397 (find-file (car files))
13398 (throw 'exit t))))
13399 (find-file (car fs)))
13400 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
13402 (defun org-agenda-file-to-front (&optional to-end)
13403 "Move/add the current file to the top of the agenda file list.
13404 If the file is not present in the list, it is added to the front. If it is
13405 present, it is moved there. With optional argument TO-END, add/move to the
13406 end of the list."
13407 (interactive "P")
13408 (let ((org-agenda-skip-unavailable-files nil)
13409 (file-alist (mapcar (lambda (x)
13410 (cons (file-truename x) x))
13411 (org-agenda-files t)))
13412 (ctf (file-truename buffer-file-name))
13413 x had)
13414 (setq x (assoc ctf file-alist) had x)
13416 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
13417 (if to-end
13418 (setq file-alist (append (delq x file-alist) (list x)))
13419 (setq file-alist (cons x (delq x file-alist))))
13420 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
13421 (org-install-agenda-files-menu)
13422 (message "File %s to %s of agenda file list"
13423 (if had "moved" "added") (if to-end "end" "front"))))
13425 (defun org-remove-file (&optional file)
13426 "Remove current file from the list of files in variable `org-agenda-files'.
13427 These are the files which are being checked for agenda entries.
13428 Optional argument FILE means, use this file instead of the current."
13429 (interactive)
13430 (let* ((org-agenda-skip-unavailable-files nil)
13431 (file (or file buffer-file-name))
13432 (true-file (file-truename file))
13433 (afile (abbreviate-file-name file))
13434 (files (delq nil (mapcar
13435 (lambda (x)
13436 (if (equal true-file
13437 (file-truename x))
13438 nil x))
13439 (org-agenda-files t)))))
13440 (if (not (= (length files) (length (org-agenda-files t))))
13441 (progn
13442 (org-store-new-agenda-file-list files)
13443 (org-install-agenda-files-menu)
13444 (message "Removed file: %s" afile))
13445 (message "File was not in list: %s (not removed)" afile))))
13447 (defun org-file-menu-entry (file)
13448 (vector file (list 'find-file file) t))
13450 (defun org-check-agenda-file (file)
13451 "Make sure FILE exists. If not, ask user what to do."
13452 (when (not (file-exists-p file))
13453 (message "non-existent file %s. [R]emove from list or [A]bort?"
13454 (abbreviate-file-name file))
13455 (let ((r (downcase (read-char-exclusive))))
13456 (cond
13457 ((equal r ?r)
13458 (org-remove-file file)
13459 (throw 'nextfile t))
13460 (t (error "Abort"))))))
13462 (defun org-get-agenda-file-buffer (file)
13463 "Get a buffer visiting FILE. If the buffer needs to be created, add
13464 it to the list of buffers which might be released later."
13465 (let ((buf (org-find-base-buffer-visiting file)))
13466 (if buf
13467 buf ; just return it
13468 ;; Make a new buffer and remember it
13469 (setq buf (find-file-noselect file))
13470 (if buf (push buf org-agenda-new-buffers))
13471 buf)))
13473 (defun org-release-buffers (blist)
13474 "Release all buffers in list, asking the user for confirmation when needed.
13475 When a buffer is unmodified, it is just killed. When modified, it is saved
13476 \(if the user agrees) and then killed."
13477 (let (buf file)
13478 (while (setq buf (pop blist))
13479 (setq file (buffer-file-name buf))
13480 (when (and (buffer-modified-p buf)
13481 file
13482 (y-or-n-p (format "Save file %s? " file)))
13483 (with-current-buffer buf (save-buffer)))
13484 (kill-buffer buf))))
13486 (defun org-prepare-agenda-buffers (files)
13487 "Create buffers for all agenda files, protect archived trees and comments."
13488 (interactive)
13489 (let ((pa '(:org-archived t))
13490 (pc '(:org-comment t))
13491 (pall '(:org-archived t :org-comment t))
13492 (inhibit-read-only t)
13493 (rea (concat ":" org-archive-tag ":"))
13494 bmp file re)
13495 (save-excursion
13496 (save-restriction
13497 (while (setq file (pop files))
13498 (catch 'nextfile
13499 (if (bufferp file)
13500 (set-buffer file)
13501 (org-check-agenda-file file)
13502 (set-buffer (org-get-agenda-file-buffer file)))
13503 (widen)
13504 (setq bmp (buffer-modified-p))
13505 (org-refresh-category-properties)
13506 (setq org-todo-keywords-for-agenda
13507 (append org-todo-keywords-for-agenda org-todo-keywords-1))
13508 (setq org-done-keywords-for-agenda
13509 (append org-done-keywords-for-agenda org-done-keywords))
13510 (setq org-todo-keyword-alist-for-agenda
13511 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
13512 (setq org-tag-alist-for-agenda
13513 (append org-tag-alist-for-agenda org-tag-alist))
13515 (save-excursion
13516 (remove-text-properties (point-min) (point-max) pall)
13517 (when org-agenda-skip-archived-trees
13518 (goto-char (point-min))
13519 (while (re-search-forward rea nil t)
13520 (if (org-on-heading-p t)
13521 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
13522 (goto-char (point-min))
13523 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
13524 (while (re-search-forward re nil t)
13525 (add-text-properties
13526 (match-beginning 0) (org-end-of-subtree t) pc)))
13527 (set-buffer-modified-p bmp)))))
13528 (setq org-todo-keyword-alist-for-agenda
13529 (org-uniquify org-todo-keyword-alist-for-agenda)
13530 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
13532 ;;;; Embedded LaTeX
13534 (defvar org-cdlatex-mode-map (make-sparse-keymap)
13535 "Keymap for the minor `org-cdlatex-mode'.")
13537 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
13538 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
13539 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
13540 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
13541 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
13543 (defvar org-cdlatex-texmathp-advice-is-done nil
13544 "Flag remembering if we have applied the advice to texmathp already.")
13546 (define-minor-mode org-cdlatex-mode
13547 "Toggle the minor `org-cdlatex-mode'.
13548 This mode supports entering LaTeX environment and math in LaTeX fragments
13549 in Org-mode.
13550 \\{org-cdlatex-mode-map}"
13551 nil " OCDL" nil
13552 (when org-cdlatex-mode (require 'cdlatex))
13553 (unless org-cdlatex-texmathp-advice-is-done
13554 (setq org-cdlatex-texmathp-advice-is-done t)
13555 (defadvice texmathp (around org-math-always-on activate)
13556 "Always return t in org-mode buffers.
13557 This is because we want to insert math symbols without dollars even outside
13558 the LaTeX math segments. If Orgmode thinks that point is actually inside
13559 an embedded LaTeX fragment, let texmathp do its job.
13560 \\[org-cdlatex-mode-map]"
13561 (interactive)
13562 (let (p)
13563 (cond
13564 ((not (org-mode-p)) ad-do-it)
13565 ((eq this-command 'cdlatex-math-symbol)
13566 (setq ad-return-value t
13567 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
13569 (let ((p (org-inside-LaTeX-fragment-p)))
13570 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
13571 (setq ad-return-value t
13572 texmathp-why '("Org-mode embedded math" . 0))
13573 (if p ad-do-it)))))))))
13575 (defun turn-on-org-cdlatex ()
13576 "Unconditionally turn on `org-cdlatex-mode'."
13577 (org-cdlatex-mode 1))
13579 (defun org-inside-LaTeX-fragment-p ()
13580 "Test if point is inside a LaTeX fragment.
13581 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
13582 sequence appearing also before point.
13583 Even though the matchers for math are configurable, this function assumes
13584 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
13585 delimiters are skipped when they have been removed by customization.
13586 The return value is nil, or a cons cell with the delimiter and
13587 and the position of this delimiter.
13589 This function does a reasonably good job, but can locally be fooled by
13590 for example currency specifications. For example it will assume being in
13591 inline math after \"$22.34\". The LaTeX fragment formatter will only format
13592 fragments that are properly closed, but during editing, we have to live
13593 with the uncertainty caused by missing closing delimiters. This function
13594 looks only before point, not after."
13595 (catch 'exit
13596 (let ((pos (point))
13597 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
13598 (lim (progn
13599 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
13600 (point)))
13601 dd-on str (start 0) m re)
13602 (goto-char pos)
13603 (when dodollar
13604 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
13605 re (nth 1 (assoc "$" org-latex-regexps)))
13606 (while (string-match re str start)
13607 (cond
13608 ((= (match-end 0) (length str))
13609 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
13610 ((= (match-end 0) (- (length str) 5))
13611 (throw 'exit nil))
13612 (t (setq start (match-end 0))))))
13613 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
13614 (goto-char pos)
13615 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
13616 (and (match-beginning 2) (throw 'exit nil))
13617 ;; count $$
13618 (while (re-search-backward "\\$\\$" lim t)
13619 (setq dd-on (not dd-on)))
13620 (goto-char pos)
13621 (if dd-on (cons "$$" m))))))
13624 (defun org-try-cdlatex-tab ()
13625 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
13626 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
13627 - inside a LaTeX fragment, or
13628 - after the first word in a line, where an abbreviation expansion could
13629 insert a LaTeX environment."
13630 (when org-cdlatex-mode
13631 (cond
13632 ((save-excursion
13633 (skip-chars-backward "a-zA-Z0-9*")
13634 (skip-chars-backward " \t")
13635 (bolp))
13636 (cdlatex-tab) t)
13637 ((org-inside-LaTeX-fragment-p)
13638 (cdlatex-tab) t)
13639 (t nil))))
13641 (defun org-cdlatex-underscore-caret (&optional arg)
13642 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
13643 Revert to the normal definition outside of these fragments."
13644 (interactive "P")
13645 (if (org-inside-LaTeX-fragment-p)
13646 (call-interactively 'cdlatex-sub-superscript)
13647 (let (org-cdlatex-mode)
13648 (call-interactively (key-binding (vector last-input-event))))))
13650 (defun org-cdlatex-math-modify (&optional arg)
13651 "Execute `cdlatex-math-modify' in LaTeX fragments.
13652 Revert to the normal definition outside of these fragments."
13653 (interactive "P")
13654 (if (org-inside-LaTeX-fragment-p)
13655 (call-interactively 'cdlatex-math-modify)
13656 (let (org-cdlatex-mode)
13657 (call-interactively (key-binding (vector last-input-event))))))
13659 (defvar org-latex-fragment-image-overlays nil
13660 "List of overlays carrying the images of latex fragments.")
13661 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
13663 (defun org-remove-latex-fragment-image-overlays ()
13664 "Remove all overlays with LaTeX fragment images in current buffer."
13665 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
13666 (setq org-latex-fragment-image-overlays nil))
13668 (defun org-preview-latex-fragment (&optional subtree)
13669 "Preview the LaTeX fragment at point, or all locally or globally.
13670 If the cursor is in a LaTeX fragment, create the image and overlay
13671 it over the source code. If there is no fragment at point, display
13672 all fragments in the current text, from one headline to the next. With
13673 prefix SUBTREE, display all fragments in the current subtree. With a
13674 double prefix `C-u C-u', or when the cursor is before the first headline,
13675 display all fragments in the buffer.
13676 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
13677 (interactive "P")
13678 (org-remove-latex-fragment-image-overlays)
13679 (save-excursion
13680 (save-restriction
13681 (let (beg end at msg)
13682 (cond
13683 ((or (equal subtree '(16))
13684 (not (save-excursion
13685 (re-search-backward (concat "^" outline-regexp) nil t))))
13686 (setq beg (point-min) end (point-max)
13687 msg "Creating images for buffer...%s"))
13688 ((equal subtree '(4))
13689 (org-back-to-heading)
13690 (setq beg (point) end (org-end-of-subtree t)
13691 msg "Creating images for subtree...%s"))
13693 (if (setq at (org-inside-LaTeX-fragment-p))
13694 (goto-char (max (point-min) (- (cdr at) 2)))
13695 (org-back-to-heading))
13696 (setq beg (point) end (progn (outline-next-heading) (point))
13697 msg (if at "Creating image...%s"
13698 "Creating images for entry...%s"))))
13699 (message msg "")
13700 (narrow-to-region beg end)
13701 (goto-char beg)
13702 (org-format-latex
13703 (concat "ltxpng/" (file-name-sans-extension
13704 (file-name-nondirectory
13705 buffer-file-name)))
13706 default-directory 'overlays msg at 'forbuffer)
13707 (message msg "done. Use `C-c C-c' to remove images.")))))
13709 (defvar org-latex-regexps
13710 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
13711 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
13712 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
13713 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13714 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13715 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
13716 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
13717 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
13718 "Regular expressions for matching embedded LaTeX.")
13720 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
13721 "Replace LaTeX fragments with links to an image, and produce images."
13722 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
13723 (let* ((prefixnodir (file-name-nondirectory prefix))
13724 (absprefix (expand-file-name prefix dir))
13725 (todir (file-name-directory absprefix))
13726 (opt org-format-latex-options)
13727 (matchers (plist-get opt :matchers))
13728 (re-list org-latex-regexps)
13729 (cnt 0) txt link beg end re e checkdir
13730 executables-checked
13731 m n block linkfile movefile ov)
13732 ;; Check if there are old images files with this prefix, and remove them
13733 (when (file-directory-p todir)
13734 (mapc 'delete-file
13735 (directory-files
13736 todir 'full
13737 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
13738 ;; Check the different regular expressions
13739 (while (setq e (pop re-list))
13740 (setq m (car e) re (nth 1 e) n (nth 2 e)
13741 block (if (nth 3 e) "\n\n" ""))
13742 (when (member m matchers)
13743 (goto-char (point-min))
13744 (while (re-search-forward re nil t)
13745 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
13746 (not (get-text-property (match-beginning n)
13747 'org-protected)))
13748 (setq txt (match-string n)
13749 beg (match-beginning n) end (match-end n)
13750 cnt (1+ cnt)
13751 linkfile (format "%s_%04d.png" prefix cnt)
13752 movefile (format "%s_%04d.png" absprefix cnt)
13753 link (concat block "[[file:" linkfile "]]" block))
13754 (if msg (message msg cnt))
13755 (goto-char beg)
13756 (unless checkdir ; make sure the directory exists
13757 (setq checkdir t)
13758 (or (file-directory-p todir) (make-directory todir)))
13760 (unless executables-checked
13761 (org-check-external-command
13762 "latex" "needed to convert LaTeX fragments to images")
13763 (org-check-external-command
13764 "dvipng" "needed to convert LaTeX fragments to images")
13765 (setq executables-checked t))
13767 (org-create-formula-image
13768 txt movefile opt forbuffer)
13769 (if overlays
13770 (progn
13771 (setq ov (org-make-overlay beg end))
13772 (if (featurep 'xemacs)
13773 (progn
13774 (org-overlay-put ov 'invisible t)
13775 (org-overlay-put
13776 ov 'end-glyph
13777 (make-glyph (vector 'png :file movefile))))
13778 (org-overlay-put
13779 ov 'display
13780 (list 'image :type 'png :file movefile :ascent 'center)))
13781 (push ov org-latex-fragment-image-overlays)
13782 (goto-char end))
13783 (delete-region beg end)
13784 (insert link))))))))
13786 ;; This function borrows from Ganesh Swami's latex2png.el
13787 (defun org-create-formula-image (string tofile options buffer)
13788 (let* ((tmpdir (if (featurep 'xemacs)
13789 (temp-directory)
13790 temporary-file-directory))
13791 (texfilebase (make-temp-name
13792 (expand-file-name "orgtex" tmpdir)))
13793 (texfile (concat texfilebase ".tex"))
13794 (dvifile (concat texfilebase ".dvi"))
13795 (pngfile (concat texfilebase ".png"))
13796 (fnh (if (featurep 'xemacs)
13797 (font-height (get-face-font 'default))
13798 (face-attribute 'default :height nil)))
13799 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
13800 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
13801 (fg (or (plist-get options (if buffer :foreground :html-foreground))
13802 "Black"))
13803 (bg (or (plist-get options (if buffer :background :html-background))
13804 "Transparent")))
13805 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
13806 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
13807 (with-temp-file texfile
13808 (insert org-format-latex-header
13809 "\n\\begin{document}\n" string "\n\\end{document}\n"))
13810 (let ((dir default-directory))
13811 (condition-case nil
13812 (progn
13813 (cd tmpdir)
13814 (call-process "latex" nil nil nil texfile))
13815 (error nil))
13816 (cd dir))
13817 (if (not (file-exists-p dvifile))
13818 (progn (message "Failed to create dvi file from %s" texfile) nil)
13819 (condition-case nil
13820 (call-process "dvipng" nil nil nil
13821 "-E" "-fg" fg "-bg" bg
13822 "-D" dpi
13823 ;;"-x" scale "-y" scale
13824 "-T" "tight"
13825 "-o" pngfile
13826 dvifile)
13827 (error nil))
13828 (if (not (file-exists-p pngfile))
13829 (progn (message "Failed to create png file from %s" texfile) nil)
13830 ;; Use the requested file name and clean up
13831 (copy-file pngfile tofile 'replace)
13832 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
13833 (delete-file (concat texfilebase e)))
13834 pngfile))))
13836 (defun org-dvipng-color (attr)
13837 "Return an rgb color specification for dvipng."
13838 (apply 'format "rgb %s %s %s"
13839 (mapcar 'org-normalize-color
13840 (color-values (face-attribute 'default attr nil)))))
13842 (defun org-normalize-color (value)
13843 "Return string to be used as color value for an RGB component."
13844 (format "%g" (/ value 65535.0)))
13846 ;;;; Key bindings
13848 ;; Make `C-c C-x' a prefix key
13849 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
13851 ;; TAB key with modifiers
13852 (org-defkey org-mode-map "\C-i" 'org-cycle)
13853 (org-defkey org-mode-map [(tab)] 'org-cycle)
13854 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
13855 (org-defkey org-mode-map [(meta tab)] 'org-complete)
13856 (org-defkey org-mode-map "\M-\t" 'org-complete)
13857 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
13858 ;; The following line is necessary under Suse GNU/Linux
13859 (unless (featurep 'xemacs)
13860 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
13861 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
13862 (define-key org-mode-map [backtab] 'org-shifttab)
13864 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
13865 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
13866 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
13868 ;; Cursor keys with modifiers
13869 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
13870 (org-defkey org-mode-map [(meta right)] 'org-metaright)
13871 (org-defkey org-mode-map [(meta up)] 'org-metaup)
13872 (org-defkey org-mode-map [(meta down)] 'org-metadown)
13874 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
13875 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
13876 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
13877 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
13879 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
13880 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
13881 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
13882 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
13884 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
13885 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
13887 ;;; Extra keys for tty access.
13888 ;; We only set them when really needed because otherwise the
13889 ;; menus don't show the simple keys
13891 (when (or org-use-extra-keys
13892 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
13893 (not window-system))
13894 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
13895 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
13896 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
13897 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
13898 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
13899 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
13900 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
13901 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
13902 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
13903 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
13904 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
13905 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
13906 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
13907 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
13908 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
13909 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
13910 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
13911 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
13912 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
13913 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
13914 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
13915 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
13917 ;; All the other keys
13919 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
13920 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
13921 (if (boundp 'narrow-map)
13922 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
13923 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
13924 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
13925 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
13926 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
13927 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
13928 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
13929 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
13930 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
13931 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
13932 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
13933 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
13934 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
13935 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
13936 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
13937 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
13938 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
13939 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
13940 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
13941 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
13942 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
13943 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
13944 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
13945 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
13946 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
13947 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
13948 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
13949 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
13950 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
13951 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
13952 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
13953 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
13954 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
13955 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
13956 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
13957 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
13958 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
13959 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
13960 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
13961 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
13962 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
13963 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13964 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
13965 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
13966 (org-defkey org-mode-map "\C-c^" 'org-sort)
13967 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
13968 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
13969 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
13970 (org-defkey org-mode-map "\C-m" 'org-return)
13971 (org-defkey org-mode-map "\C-j" 'org-return-indent)
13972 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
13973 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
13974 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
13975 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
13976 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
13977 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
13978 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
13979 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
13980 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
13981 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
13982 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
13983 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
13984 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
13985 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
13986 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
13987 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
13989 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
13990 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
13991 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
13992 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
13994 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
13995 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
13996 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
13997 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
13998 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
13999 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
14000 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
14001 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
14002 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
14003 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
14004 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
14005 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
14006 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
14008 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
14009 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
14010 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
14011 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
14013 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
14015 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
14017 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
14018 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
14020 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
14023 (when (featurep 'xemacs)
14024 (org-defkey org-mode-map 'button3 'popup-mode-menu))
14027 (defvar org-self-insert-command-undo-counter 0)
14029 (defvar org-table-auto-blank-field) ; defined in org-table.el
14030 (defun org-self-insert-command (N)
14031 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
14032 If the cursor is in a table looking at whitespace, the whitespace is
14033 overwritten, and the table is not marked as requiring realignment."
14034 (interactive "p")
14035 (if (and
14036 (org-table-p)
14037 (progn
14038 ;; check if we blank the field, and if that triggers align
14039 (and (featurep 'org-table) org-table-auto-blank-field
14040 (member last-command
14041 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
14042 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
14043 ;; got extra space, this field does not determine column width
14044 (let (org-table-may-need-update) (org-table-blank-field))
14045 ;; no extra space, this field may determine column width
14046 (org-table-blank-field)))
14048 (eq N 1)
14049 (looking-at "[^|\n]* |"))
14050 (let (org-table-may-need-update)
14051 (goto-char (1- (match-end 0)))
14052 (delete-backward-char 1)
14053 (goto-char (match-beginning 0))
14054 (self-insert-command N))
14055 (setq org-table-may-need-update t)
14056 (self-insert-command N)
14057 (org-fix-tags-on-the-fly)
14058 (if org-self-insert-cluster-for-undo
14059 (if (not (eq last-command 'org-self-insert-command))
14060 (setq org-self-insert-command-undo-counter 1)
14061 (if (>= org-self-insert-command-undo-counter 20)
14062 (setq org-self-insert-command-undo-counter 1)
14063 (and (> org-self-insert-command-undo-counter 0)
14064 buffer-undo-list
14065 (not (cadr buffer-undo-list)) ; remove nil entry
14066 (setcdr buffer-undo-list (cddr buffer-undo-list)))
14067 (setq org-self-insert-command-undo-counter
14068 (1+ org-self-insert-command-undo-counter)))))))
14070 (defun org-fix-tags-on-the-fly ()
14071 (when (and (equal (char-after (point-at-bol)) ?*)
14072 (org-on-heading-p))
14073 (org-align-tags-here org-tags-column)))
14075 (defun org-delete-backward-char (N)
14076 "Like `delete-backward-char', insert whitespace at field end in tables.
14077 When deleting backwards, in tables this function will insert whitespace in
14078 front of the next \"|\" separator, to keep the table aligned. The table will
14079 still be marked for re-alignment if the field did fill the entire column,
14080 because, in this case the deletion might narrow the column."
14081 (interactive "p")
14082 (if (and (org-table-p)
14083 (eq N 1)
14084 (string-match "|" (buffer-substring (point-at-bol) (point)))
14085 (looking-at ".*?|"))
14086 (let ((pos (point))
14087 (noalign (looking-at "[^|\n\r]* |"))
14088 (c org-table-may-need-update))
14089 (backward-delete-char N)
14090 (skip-chars-forward "^|")
14091 (insert " ")
14092 (goto-char (1- pos))
14093 ;; noalign: if there were two spaces at the end, this field
14094 ;; does not determine the width of the column.
14095 (if noalign (setq org-table-may-need-update c)))
14096 (backward-delete-char N)
14097 (org-fix-tags-on-the-fly)))
14099 (defun org-delete-char (N)
14100 "Like `delete-char', but insert whitespace at field end in tables.
14101 When deleting characters, in tables this function will insert whitespace in
14102 front of the next \"|\" separator, to keep the table aligned. The table will
14103 still be marked for re-alignment if the field did fill the entire column,
14104 because, in this case the deletion might narrow the column."
14105 (interactive "p")
14106 (if (and (org-table-p)
14107 (not (bolp))
14108 (not (= (char-after) ?|))
14109 (eq N 1))
14110 (if (looking-at ".*?|")
14111 (let ((pos (point))
14112 (noalign (looking-at "[^|\n\r]* |"))
14113 (c org-table-may-need-update))
14114 (replace-match (concat
14115 (substring (match-string 0) 1 -1)
14116 " |"))
14117 (goto-char pos)
14118 ;; noalign: if there were two spaces at the end, this field
14119 ;; does not determine the width of the column.
14120 (if noalign (setq org-table-may-need-update c)))
14121 (delete-char N))
14122 (delete-char N)
14123 (org-fix-tags-on-the-fly)))
14125 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
14126 (put 'org-self-insert-command 'delete-selection t)
14127 (put 'orgtbl-self-insert-command 'delete-selection t)
14128 (put 'org-delete-char 'delete-selection 'supersede)
14129 (put 'org-delete-backward-char 'delete-selection 'supersede)
14130 (put 'org-yank 'delete-selection 'yank)
14132 ;; Make `flyspell-mode' delay after some commands
14133 (put 'org-self-insert-command 'flyspell-delayed t)
14134 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
14135 (put 'org-delete-char 'flyspell-delayed t)
14136 (put 'org-delete-backward-char 'flyspell-delayed t)
14138 ;; Make pabbrev-mode expand after org-mode commands
14139 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
14140 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
14142 ;; How to do this: Measure non-white length of current string
14143 ;; If equal to column width, we should realign.
14145 (defun org-remap (map &rest commands)
14146 "In MAP, remap the functions given in COMMANDS.
14147 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
14148 (let (new old)
14149 (while commands
14150 (setq old (pop commands) new (pop commands))
14151 (if (fboundp 'command-remapping)
14152 (org-defkey map (vector 'remap old) new)
14153 (substitute-key-definition old new map global-map)))))
14155 (when (eq org-enable-table-editor 'optimized)
14156 ;; If the user wants maximum table support, we need to hijack
14157 ;; some standard editing functions
14158 (org-remap org-mode-map
14159 'self-insert-command 'org-self-insert-command
14160 'delete-char 'org-delete-char
14161 'delete-backward-char 'org-delete-backward-char)
14162 (org-defkey org-mode-map "|" 'org-force-self-insert))
14164 (defvar org-ctrl-c-ctrl-c-hook nil
14165 "Hook for functions attaching themselves to `C-c C-c'.
14166 This can be used to add additional functionality to the C-c C-c key which
14167 executes context-dependent commands.
14168 Each function will be called with no arguments. The function must check
14169 if the context is appropriate for it to act. If yes, it should do its
14170 thing and then return a non-nil value. If the context is wrong,
14171 just do nothing and return nil.")
14173 (defvar org-tab-first-hook nil
14174 "Hook for functions to attach themselves to TAB.
14175 See `org-ctrl-c-ctrl-c-hook' for more information.
14176 This hook runs as the first action when TAB is pressed, even before
14177 `org-cycle' messes around with the `outline-regexp' to cater for
14178 inline tasks and plain list item folding.
14179 If any function in this hook returns t, not other actions like table
14180 field motion visibility cycling will be done.")
14182 (defvar org-tab-after-check-for-table-hook nil
14183 "Hook for functions to attach themselves to TAB.
14184 See `org-ctrl-c-ctrl-c-hook' for more information.
14185 This hook runs after it has been established that the cursor is not in a
14186 table, but before checking if the cursor is in a headline or if global cycling
14187 should be done.
14188 If any function in this hook returns t, not other actions like visibility
14189 cycling will be done.")
14191 (defvar org-tab-after-check-for-cycling-hook nil
14192 "Hook for functions to attach themselves to TAB.
14193 See `org-ctrl-c-ctrl-c-hook' for more information.
14194 This hook runs after it has been established that not table field motion and
14195 not visibility should be done because of current context. This is probably
14196 the place where a package like yasnippets can hook in.")
14198 (defvar org-metaleft-hook nil
14199 "Hook for functions attaching themselves to `M-left'.
14200 See `org-ctrl-c-ctrl-c-hook' for more information.")
14201 (defvar org-metaright-hook nil
14202 "Hook for functions attaching themselves to `M-right'.
14203 See `org-ctrl-c-ctrl-c-hook' for more information.")
14204 (defvar org-metaup-hook nil
14205 "Hook for functions attaching themselves to `M-up'.
14206 See `org-ctrl-c-ctrl-c-hook' for more information.")
14207 (defvar org-metadown-hook nil
14208 "Hook for functions attaching themselves to `M-down'.
14209 See `org-ctrl-c-ctrl-c-hook' for more information.")
14210 (defvar org-shiftmetaleft-hook nil
14211 "Hook for functions attaching themselves to `M-S-left'.
14212 See `org-ctrl-c-ctrl-c-hook' for more information.")
14213 (defvar org-shiftmetaright-hook nil
14214 "Hook for functions attaching themselves to `M-S-right'.
14215 See `org-ctrl-c-ctrl-c-hook' for more information.")
14216 (defvar org-shiftmetaup-hook nil
14217 "Hook for functions attaching themselves to `M-S-up'.
14218 See `org-ctrl-c-ctrl-c-hook' for more information.")
14219 (defvar org-shiftmetadown-hook nil
14220 "Hook for functions attaching themselves to `M-S-down'.
14221 See `org-ctrl-c-ctrl-c-hook' for more information.")
14222 (defvar org-metareturn-hook nil
14223 "Hook for functions attaching themselves to `M-RET'.
14224 See `org-ctrl-c-ctrl-c-hook' for more information.")
14226 (defun org-modifier-cursor-error ()
14227 "Throw an error, a modified cursor command was applied in wrong context."
14228 (error "This command is active in special context like tables, headlines or items"))
14230 (defun org-shiftselect-error ()
14231 "Throw an error because Shift-Cursor command was applied in wrong context."
14232 (if (and (boundp 'shift-select-mode) shift-select-mode)
14233 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
14234 (error "This command works only in special context like headlines or timestamps.")))
14236 (defun org-call-for-shift-select (cmd)
14237 (let ((this-command-keys-shift-translated t))
14238 (call-interactively cmd)))
14240 (defun org-shifttab (&optional arg)
14241 "Global visibility cycling or move to previous table field.
14242 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
14243 on context.
14244 See the individual commands for more information."
14245 (interactive "P")
14246 (cond
14247 ((org-at-table-p) (call-interactively 'org-table-previous-field))
14248 ((integerp arg)
14249 (message "Content view to level: %d" arg)
14250 (org-content (prefix-numeric-value arg))
14251 (setq org-cycle-global-status 'overview))
14252 (t (call-interactively 'org-global-cycle))))
14254 (defun org-shiftmetaleft ()
14255 "Promote subtree or delete table column.
14256 Calls `org-promote-subtree', `org-outdent-item',
14257 or `org-table-delete-column', depending on context.
14258 See the individual commands for more information."
14259 (interactive)
14260 (cond
14261 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
14262 ((org-at-table-p) (call-interactively 'org-table-delete-column))
14263 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
14264 ((org-at-item-p) (call-interactively 'org-outdent-item))
14265 (t (org-modifier-cursor-error))))
14267 (defun org-shiftmetaright ()
14268 "Demote subtree or insert table column.
14269 Calls `org-demote-subtree', `org-indent-item',
14270 or `org-table-insert-column', depending on context.
14271 See the individual commands for more information."
14272 (interactive)
14273 (cond
14274 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
14275 ((org-at-table-p) (call-interactively 'org-table-insert-column))
14276 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
14277 ((org-at-item-p) (call-interactively 'org-indent-item))
14278 (t (org-modifier-cursor-error))))
14280 (defun org-shiftmetaup (&optional arg)
14281 "Move subtree up or kill table row.
14282 Calls `org-move-subtree-up' or `org-table-kill-row' or
14283 `org-move-item-up' depending on context. See the individual commands
14284 for more information."
14285 (interactive "P")
14286 (cond
14287 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
14288 ((org-at-table-p) (call-interactively 'org-table-kill-row))
14289 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14290 ((org-at-item-p) (call-interactively 'org-move-item-up))
14291 (t (org-modifier-cursor-error))))
14293 (defun org-shiftmetadown (&optional arg)
14294 "Move subtree down or insert table row.
14295 Calls `org-move-subtree-down' or `org-table-insert-row' or
14296 `org-move-item-down', depending on context. See the individual
14297 commands for more information."
14298 (interactive "P")
14299 (cond
14300 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
14301 ((org-at-table-p) (call-interactively 'org-table-insert-row))
14302 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14303 ((org-at-item-p) (call-interactively 'org-move-item-down))
14304 (t (org-modifier-cursor-error))))
14306 (defun org-metaleft (&optional arg)
14307 "Promote heading or move table column to left.
14308 Calls `org-do-promote' or `org-table-move-column', depending on context.
14309 With no specific context, calls the Emacs default `backward-word'.
14310 See the individual commands for more information."
14311 (interactive "P")
14312 (cond
14313 ((run-hook-with-args-until-success 'org-metaleft-hook))
14314 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
14315 ((or (org-on-heading-p)
14316 (and (org-region-active-p)
14317 (save-excursion
14318 (goto-char (region-beginning))
14319 (org-on-heading-p))))
14320 (call-interactively 'org-do-promote))
14321 ((or (org-at-item-p)
14322 (and (org-region-active-p)
14323 (save-excursion
14324 (goto-char (region-beginning))
14325 (org-at-item-p))))
14326 (call-interactively 'org-outdent-item))
14327 (t (call-interactively 'backward-word))))
14329 (defun org-metaright (&optional arg)
14330 "Demote subtree or move table column to right.
14331 Calls `org-do-demote' or `org-table-move-column', depending on context.
14332 With no specific context, calls the Emacs default `forward-word'.
14333 See the individual commands for more information."
14334 (interactive "P")
14335 (cond
14336 ((run-hook-with-args-until-success 'org-metaright-hook))
14337 ((org-at-table-p) (call-interactively 'org-table-move-column))
14338 ((or (org-on-heading-p)
14339 (and (org-region-active-p)
14340 (save-excursion
14341 (goto-char (region-beginning))
14342 (org-on-heading-p))))
14343 (call-interactively 'org-do-demote))
14344 ((or (org-at-item-p)
14345 (and (org-region-active-p)
14346 (save-excursion
14347 (goto-char (region-beginning))
14348 (org-at-item-p))))
14349 (call-interactively 'org-indent-item))
14350 (t (call-interactively 'forward-word))))
14352 (defun org-metaup (&optional arg)
14353 "Move subtree up or move table row up.
14354 Calls `org-move-subtree-up' or `org-table-move-row' or
14355 `org-move-item-up', depending on context. See the individual commands
14356 for more information."
14357 (interactive "P")
14358 (cond
14359 ((run-hook-with-args-until-success 'org-metaup-hook))
14360 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
14361 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14362 ((org-at-item-p) (call-interactively 'org-move-item-up))
14363 (t (transpose-lines 1) (beginning-of-line -1))))
14365 (defun org-metadown (&optional arg)
14366 "Move subtree down or move table row down.
14367 Calls `org-move-subtree-down' or `org-table-move-row' or
14368 `org-move-item-down', depending on context. See the individual
14369 commands for more information."
14370 (interactive "P")
14371 (cond
14372 ((run-hook-with-args-until-success 'org-metadown-hook))
14373 ((org-at-table-p) (call-interactively 'org-table-move-row))
14374 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14375 ((org-at-item-p) (call-interactively 'org-move-item-down))
14376 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
14378 (defun org-shiftup (&optional arg)
14379 "Increase item in timestamp or increase priority of current headline.
14380 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
14381 depending on context. See the individual commands for more information."
14382 (interactive "P")
14383 (cond
14384 ((and org-support-shift-select (org-region-active-p))
14385 (org-call-for-shift-select 'previous-line))
14386 ((org-at-timestamp-p t)
14387 (call-interactively (if org-edit-timestamp-down-means-later
14388 'org-timestamp-down 'org-timestamp-up)))
14389 ((and (not (eq org-support-shift-select 'always))
14390 (org-on-heading-p))
14391 (call-interactively 'org-priority-up))
14392 ((and (not org-support-shift-select) (org-at-item-p))
14393 (call-interactively 'org-previous-item))
14394 ((org-clocktable-try-shift 'up arg))
14395 (org-support-shift-select
14396 (org-call-for-shift-select 'previous-line))
14397 (t (org-shiftselect-error))))
14399 (defun org-shiftdown (&optional arg)
14400 "Decrease item in timestamp or decrease priority of current headline.
14401 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
14402 depending on context. See the individual commands for more information."
14403 (interactive "P")
14404 (cond
14405 ((and org-support-shift-select (org-region-active-p))
14406 (org-call-for-shift-select 'next-line))
14407 ((org-at-timestamp-p t)
14408 (call-interactively (if org-edit-timestamp-down-means-later
14409 'org-timestamp-up 'org-timestamp-down)))
14410 ((and (not (eq org-support-shift-select 'always))
14411 (org-on-heading-p))
14412 (call-interactively 'org-priority-down))
14413 ((and (not org-support-shift-select) (org-at-item-p))
14414 (call-interactively 'org-next-item))
14415 ((org-clocktable-try-shift 'down arg))
14416 (org-support-shift-select
14417 (org-call-for-shift-select 'next-line))
14418 (t (org-shiftselect-error))))
14420 (defun org-shiftright (&optional arg)
14421 "Cycle the thing at point or in the current line, depending on context.
14422 Depending on context, this does one of the following:
14424 - switch a timestamp at point one day into the future
14425 - on a headline, switch to the next TODO keyword.
14426 - on an item, switch entire list to the next bullet type
14427 - on a property line, switch to the next allowed value
14428 - on a clocktable definition line, move time block into the future"
14429 (interactive "P")
14430 (cond
14431 ((and org-support-shift-select (org-region-active-p))
14432 (org-call-for-shift-select 'forward-char))
14433 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
14434 ((and (not (eq org-support-shift-select 'always))
14435 (org-on-heading-p))
14436 (org-call-with-arg 'org-todo 'right))
14437 ((or (and org-support-shift-select
14438 (not (eq org-support-shift-select 'always))
14439 (org-at-item-bullet-p))
14440 (and (not org-support-shift-select) (org-at-item-p)))
14441 (org-call-with-arg 'org-cycle-list-bullet nil))
14442 ((and (not (eq org-support-shift-select 'always))
14443 (org-at-property-p))
14444 (call-interactively 'org-property-next-allowed-value))
14445 ((org-clocktable-try-shift 'right arg))
14446 (org-support-shift-select
14447 (org-call-for-shift-select 'forward-char))
14448 (t (org-shiftselect-error))))
14450 (defun org-shiftleft (&optional arg)
14451 "Cycle the thing at point or in the current line, depending on context.
14452 Depending on context, this does one of the following:
14454 - switch a timestamp at point one day into the past
14455 - on a headline, switch to the previous TODO keyword.
14456 - on an item, switch entire list to the previous bullet type
14457 - on a property line, switch to the previous allowed value
14458 - on a clocktable definition line, move time block into the past"
14459 (interactive "P")
14460 (cond
14461 ((and org-support-shift-select (org-region-active-p))
14462 (org-call-for-shift-select 'backward-char))
14463 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
14464 ((and (not (eq org-support-shift-select 'always))
14465 (org-on-heading-p))
14466 (org-call-with-arg 'org-todo 'left))
14467 ((or (and org-support-shift-select
14468 (not (eq org-support-shift-select 'always))
14469 (org-at-item-bullet-p))
14470 (and (not org-support-shift-select) (org-at-item-p)))
14471 (org-call-with-arg 'org-cycle-list-bullet 'previous))
14472 ((and (not (eq org-support-shift-select 'always))
14473 (org-at-property-p))
14474 (call-interactively 'org-property-previous-allowed-value))
14475 ((org-clocktable-try-shift 'left arg))
14476 (org-support-shift-select
14477 (org-call-for-shift-select 'backward-char))
14478 (t (org-shiftselect-error))))
14480 (defun org-shiftcontrolright ()
14481 "Switch to next TODO set."
14482 (interactive)
14483 (cond
14484 ((and org-support-shift-select (org-region-active-p))
14485 (org-call-for-shift-select 'forward-word))
14486 ((and (not (eq org-support-shift-select 'always))
14487 (org-on-heading-p))
14488 (org-call-with-arg 'org-todo 'nextset))
14489 (org-support-shift-select
14490 (org-call-for-shift-select 'forward-word))
14491 (t (org-shiftselect-error))))
14493 (defun org-shiftcontrolleft ()
14494 "Switch to previous TODO set."
14495 (interactive)
14496 (cond
14497 ((and org-support-shift-select (org-region-active-p))
14498 (org-call-for-shift-select 'backward-word))
14499 ((and (not (eq org-support-shift-select 'always))
14500 (org-on-heading-p))
14501 (org-call-with-arg 'org-todo 'previousset))
14502 (org-support-shift-select
14503 (org-call-for-shift-select 'backward-word))
14504 (t (org-shiftselect-error))))
14506 (defun org-ctrl-c-ret ()
14507 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
14508 (interactive)
14509 (cond
14510 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
14511 (t (call-interactively 'org-insert-heading))))
14513 (defun org-copy-special ()
14514 "Copy region in table or copy current subtree.
14515 Calls `org-table-copy' or `org-copy-subtree', depending on context.
14516 See the individual commands for more information."
14517 (interactive)
14518 (call-interactively
14519 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
14521 (defun org-cut-special ()
14522 "Cut region in table or cut current subtree.
14523 Calls `org-table-copy' or `org-cut-subtree', depending on context.
14524 See the individual commands for more information."
14525 (interactive)
14526 (call-interactively
14527 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
14529 (defun org-paste-special (arg)
14530 "Paste rectangular region into table, or past subtree relative to level.
14531 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
14532 See the individual commands for more information."
14533 (interactive "P")
14534 (if (org-at-table-p)
14535 (org-table-paste-rectangle)
14536 (org-paste-subtree arg)))
14538 (defun org-edit-special ()
14539 "Call a special editor for the stuff at point.
14540 When at a table, call the formula editor with `org-table-edit-formulas'.
14541 When at the first line of an src example, call `org-edit-src-code'.
14542 When in an #+include line, visit the include file. Otherwise call
14543 `ffap' to visit the file at point."
14544 (interactive)
14545 (cond
14546 ((org-at-table-p)
14547 (call-interactively 'org-table-edit-formulas))
14548 ((save-excursion
14549 (beginning-of-line 1)
14550 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
14551 (find-file (org-trim (match-string 1))))
14552 ((org-edit-src-code))
14553 ((org-edit-fixed-width-region))
14554 (t (call-interactively 'ffap))))
14557 (defun org-ctrl-c-ctrl-c (&optional arg)
14558 "Set tags in headline, or update according to changed information at point.
14560 This command does many different things, depending on context:
14562 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
14563 this is what we do.
14565 - If the cursor is in a headline, prompt for tags and insert them
14566 into the current line, aligned to `org-tags-column'. When called
14567 with prefix arg, realign all tags in the current buffer.
14569 - If the cursor is in one of the special #+KEYWORD lines, this
14570 triggers scanning the buffer for these lines and updating the
14571 information.
14573 - If the cursor is inside a table, realign the table. This command
14574 works even if the automatic table editor has been turned off.
14576 - If the cursor is on a #+TBLFM line, re-apply the formulas to
14577 the entire table.
14579 - If the cursor is at a footnote reference or definition, jump to
14580 the corresponding definition or references, respectively.
14582 - If the cursor is a the beginning of a dynamic block, update it.
14584 - If the cursor is inside a table created by the table.el package,
14585 activate that table.
14587 - If the current buffer is a remember buffer, close note and file
14588 it. A prefix argument of 1 files to the default location
14589 without further interaction. A prefix argument of 2 files to
14590 the currently clocking task.
14592 - If the cursor is on a <<<target>>>, update radio targets and corresponding
14593 links in this buffer.
14595 - If the cursor is on a numbered item in a plain list, renumber the
14596 ordered list.
14598 - If the cursor is on a checkbox, toggle it."
14599 (interactive "P")
14600 (let ((org-enable-table-editor t))
14601 (cond
14602 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
14603 org-occur-highlights
14604 org-latex-fragment-image-overlays)
14605 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
14606 (org-remove-occur-highlights)
14607 (org-remove-latex-fragment-image-overlays)
14608 (message "Temporary highlights/overlays removed from current buffer"))
14609 ((and (local-variable-p 'org-finish-function (current-buffer))
14610 (fboundp org-finish-function))
14611 (funcall org-finish-function))
14612 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
14613 ((org-at-property-p)
14614 (call-interactively 'org-property-action))
14615 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
14616 ((org-on-heading-p) (call-interactively 'org-set-tags))
14617 ((org-at-table.el-p)
14618 (require 'table)
14619 (beginning-of-line 1)
14620 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
14621 (call-interactively 'table-recognize-table))
14622 ((org-at-table-p)
14623 (org-table-maybe-eval-formula)
14624 (if arg
14625 (call-interactively 'org-table-recalculate)
14626 (org-table-maybe-recalculate-line))
14627 (call-interactively 'org-table-align))
14628 ((or (org-footnote-at-reference-p)
14629 (org-footnote-at-definition-p))
14630 (call-interactively 'org-footnote-action))
14631 ((org-at-item-checkbox-p)
14632 (call-interactively 'org-toggle-checkbox))
14633 ((org-at-item-p)
14634 (if arg
14635 (call-interactively 'org-toggle-checkbox)
14636 (call-interactively 'org-maybe-renumber-ordered-list)))
14637 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
14638 ;; Dynamic block
14639 (beginning-of-line 1)
14640 (save-excursion (org-update-dblock)))
14641 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
14642 (cond
14643 ((equal (match-string 1) "TBLFM")
14644 ;; Recalculate the table before this line
14645 (save-excursion
14646 (beginning-of-line 1)
14647 (skip-chars-backward " \r\n\t")
14648 (if (org-at-table-p)
14649 (org-call-with-arg 'org-table-recalculate t))))
14651 ; (org-set-regexps-and-options)
14652 ; (org-restart-font-lock)
14653 (let ((org-inhibit-startup t)) (org-mode-restart))
14654 (message "Local setup has been refreshed"))))
14655 (t (error "C-c C-c can do nothing useful at this location.")))))
14657 (defun org-mode-restart ()
14658 "Restart Org-mode, to scan again for special lines.
14659 Also updates the keyword regular expressions."
14660 (interactive)
14661 (org-mode)
14662 (message "Org-mode restarted"))
14664 (defun org-kill-note-or-show-branches ()
14665 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
14666 (interactive)
14667 (if (not org-finish-function)
14668 (call-interactively 'show-branches)
14669 (let ((org-note-abort t))
14670 (funcall org-finish-function))))
14672 (defun org-return (&optional indent)
14673 "Goto next table row or insert a newline.
14674 Calls `org-table-next-row' or `newline', depending on context.
14675 See the individual commands for more information."
14676 (interactive)
14677 (cond
14678 ((bobp) (if indent (newline-and-indent) (newline)))
14679 ((org-at-table-p)
14680 (org-table-justify-field-maybe)
14681 (call-interactively 'org-table-next-row))
14682 ((and org-return-follows-link
14683 (eq (get-text-property (point) 'face) 'org-link))
14684 (call-interactively 'org-open-at-point))
14685 ((and (org-at-heading-p)
14686 (looking-at
14687 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
14688 (org-show-entry)
14689 (end-of-line 1)
14690 (newline))
14691 (t (if indent (newline-and-indent) (newline)))))
14693 (defun org-return-indent ()
14694 "Goto next table row or insert a newline and indent.
14695 Calls `org-table-next-row' or `newline-and-indent', depending on
14696 context. See the individual commands for more information."
14697 (interactive)
14698 (org-return t))
14700 (defun org-ctrl-c-star ()
14701 "Compute table, or change heading status of lines.
14702 Calls `org-table-recalculate' or `org-toggle-heading',
14703 depending on context."
14704 (interactive)
14705 (cond
14706 ((org-at-table-p)
14707 (call-interactively 'org-table-recalculate))
14709 ;; Convert all lines in region to list items
14710 (call-interactively 'org-toggle-heading))))
14712 (defun org-ctrl-c-minus ()
14713 "Insert separator line in table or modify bullet status of line.
14714 Also turns a plain line or a region of lines into list items.
14715 Calls `org-table-insert-hline', `org-toggle-item', or
14716 `org-cycle-list-bullet', depending on context."
14717 (interactive)
14718 (cond
14719 ((org-at-table-p)
14720 (call-interactively 'org-table-insert-hline))
14721 ((org-region-active-p)
14722 (call-interactively 'org-toggle-item))
14723 ((org-in-item-p)
14724 (call-interactively 'org-cycle-list-bullet))
14726 (call-interactively 'org-toggle-item))))
14728 (defun org-toggle-item ()
14729 "Convert headings or normal lines to items, items to normal lines.
14730 If there is no active region, only the current line is considered.
14732 If the first line in the region is a headline, convert all headlines to items.
14734 If the first line in the region is an item, convert all items to normal lines.
14736 If the first line is normal text, add an item bullet to each line."
14737 (interactive)
14738 (let (l2 l beg end)
14739 (if (org-region-active-p)
14740 (setq beg (region-beginning) end (region-end))
14741 (setq beg (point-at-bol)
14742 end (min (1+ (point-at-eol)) (point-max))))
14743 (save-excursion
14744 (goto-char end)
14745 (setq l2 (org-current-line))
14746 (goto-char beg)
14747 (beginning-of-line 1)
14748 (setq l (1- (org-current-line)))
14749 (if (org-at-item-p)
14750 ;; We already have items, de-itemize
14751 (while (< (setq l (1+ l)) l2)
14752 (when (org-at-item-p)
14753 (goto-char (match-beginning 2))
14754 (delete-region (match-beginning 2) (match-end 2))
14755 (and (looking-at "[ \t]+") (replace-match "")))
14756 (beginning-of-line 2))
14757 (if (org-on-heading-p)
14758 ;; Headings, convert to items
14759 (while (< (setq l (1+ l)) l2)
14760 (if (looking-at org-outline-regexp)
14761 (replace-match "- " t t))
14762 (beginning-of-line 2))
14763 ;; normal lines, turn them into items
14764 (while (< (setq l (1+ l)) l2)
14765 (unless (org-at-item-p)
14766 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14767 (replace-match "\\1- \\2")))
14768 (beginning-of-line 2)))))))
14770 (defun org-toggle-heading (&optional nstars)
14771 "Convert headings to normal text, or items or text to headings.
14772 If there is no active region, only the current line is considered.
14774 If the first line is a heading, remove the stars from all headlines
14775 in the region.
14777 If the first line is a plain list item, turn all plain list items into
14778 headings.
14780 If the first line is a normal line, turn each and every line in the region
14781 into a heading.
14783 When converting a line into a heading, the number of stars is chosen
14784 such that the lines become children of the current entry. However, when
14785 a prefix argument is given, its value determines the number of stars to add."
14786 (interactive "P")
14787 (let (l2 l itemp beg end)
14788 (if (org-region-active-p)
14789 (setq beg (region-beginning) end (region-end))
14790 (setq beg (point-at-bol)
14791 end (min (1+ (point-at-eol)) (point-max))))
14792 (save-excursion
14793 (goto-char end)
14794 (setq l2 (org-current-line))
14795 (goto-char beg)
14796 (beginning-of-line 1)
14797 (setq l (1- (org-current-line)))
14798 (if (org-on-heading-p)
14799 ;; We already have headlines, de-star them
14800 (while (< (setq l (1+ l)) l2)
14801 (when (org-on-heading-p t)
14802 (and (looking-at outline-regexp) (replace-match "")))
14803 (beginning-of-line 2))
14804 (setq itemp (org-at-item-p))
14805 (let* ((stars
14806 (if nstars
14807 (make-string (prefix-numeric-value current-prefix-arg)
14809 (save-excursion
14810 (re-search-backward org-complex-heading-regexp nil t)
14811 (or (match-string 1) ""))))
14812 (add-stars (cond (nstars "")
14813 ((equal stars "") "*")
14814 (org-odd-levels-only "**")
14815 (t "*")))
14816 (rpl (concat stars add-stars " ")))
14817 (while (< (setq l (1+ l)) l2)
14818 (if itemp
14819 (and (org-at-item-p) (replace-match rpl t t))
14820 (unless (org-on-heading-p)
14821 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14822 (replace-match (concat rpl (match-string 2))))))
14823 (beginning-of-line 2)))))))
14825 (defun org-meta-return (&optional arg)
14826 "Insert a new heading or wrap a region in a table.
14827 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
14828 See the individual commands for more information."
14829 (interactive "P")
14830 (cond
14831 ((run-hook-with-args-until-success 'org-metareturn-hook))
14832 ((org-at-table-p)
14833 (call-interactively 'org-table-wrap-region))
14834 (t (call-interactively 'org-insert-heading))))
14836 ;;; Menu entries
14838 ;; Define the Org-mode menus
14839 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
14840 '("Tbl"
14841 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
14842 ["Next Field" org-cycle (org-at-table-p)]
14843 ["Previous Field" org-shifttab (org-at-table-p)]
14844 ["Next Row" org-return (org-at-table-p)]
14845 "--"
14846 ["Blank Field" org-table-blank-field (org-at-table-p)]
14847 ["Edit Field" org-table-edit-field (org-at-table-p)]
14848 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
14849 "--"
14850 ("Column"
14851 ["Move Column Left" org-metaleft (org-at-table-p)]
14852 ["Move Column Right" org-metaright (org-at-table-p)]
14853 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
14854 ["Insert Column" org-shiftmetaright (org-at-table-p)])
14855 ("Row"
14856 ["Move Row Up" org-metaup (org-at-table-p)]
14857 ["Move Row Down" org-metadown (org-at-table-p)]
14858 ["Delete Row" org-shiftmetaup (org-at-table-p)]
14859 ["Insert Row" org-shiftmetadown (org-at-table-p)]
14860 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
14861 "--"
14862 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
14863 ("Rectangle"
14864 ["Copy Rectangle" org-copy-special (org-at-table-p)]
14865 ["Cut Rectangle" org-cut-special (org-at-table-p)]
14866 ["Paste Rectangle" org-paste-special (org-at-table-p)]
14867 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
14868 "--"
14869 ("Calculate"
14870 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
14871 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
14872 ["Edit Formulas" org-edit-special (org-at-table-p)]
14873 "--"
14874 ["Recalculate line" org-table-recalculate (org-at-table-p)]
14875 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
14876 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
14877 "--"
14878 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
14879 "--"
14880 ["Sum Column/Rectangle" org-table-sum
14881 (or (org-at-table-p) (org-region-active-p))]
14882 ["Which Column?" org-table-current-column (org-at-table-p)])
14883 ["Debug Formulas"
14884 org-table-toggle-formula-debugger
14885 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
14886 ["Show Col/Row Numbers"
14887 org-table-toggle-coordinate-overlays
14888 :style toggle
14889 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
14890 "--"
14891 ["Create" org-table-create (and (not (org-at-table-p))
14892 org-enable-table-editor)]
14893 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
14894 ["Import from File" org-table-import (not (org-at-table-p))]
14895 ["Export to File" org-table-export (org-at-table-p)]
14896 "--"
14897 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
14899 (easy-menu-define org-org-menu org-mode-map "Org menu"
14900 '("Org"
14901 ("Show/Hide"
14902 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
14903 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
14904 ["Sparse Tree..." org-sparse-tree t]
14905 ["Reveal Context" org-reveal t]
14906 ["Show All" show-all t]
14907 "--"
14908 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
14909 "--"
14910 ["New Heading" org-insert-heading t]
14911 ("Navigate Headings"
14912 ["Up" outline-up-heading t]
14913 ["Next" outline-next-visible-heading t]
14914 ["Previous" outline-previous-visible-heading t]
14915 ["Next Same Level" outline-forward-same-level t]
14916 ["Previous Same Level" outline-backward-same-level t]
14917 "--"
14918 ["Jump" org-goto t])
14919 ("Edit Structure"
14920 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
14921 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
14922 "--"
14923 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
14924 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
14925 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
14926 "--"
14927 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
14928 "--"
14929 ["Promote Heading" org-metaleft (not (org-at-table-p))]
14930 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
14931 ["Demote Heading" org-metaright (not (org-at-table-p))]
14932 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
14933 "--"
14934 ["Sort Region/Children" org-sort (not (org-at-table-p))]
14935 "--"
14936 ["Convert to odd levels" org-convert-to-odd-levels t]
14937 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
14938 ("Editing"
14939 ["Emphasis..." org-emphasize t]
14940 ["Edit Source Example" org-edit-special t]
14941 "--"
14942 ["Footnote new/jump" org-footnote-action t]
14943 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
14944 ("Archive"
14945 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
14946 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
14947 ; :active t :keys "C-u C-c C-x C-a"]
14948 ["Sparse trees open ARCHIVE trees"
14949 (setq org-sparse-tree-open-archived-trees
14950 (not org-sparse-tree-open-archived-trees))
14951 :style toggle :selected org-sparse-tree-open-archived-trees]
14952 ["Cycling opens ARCHIVE trees"
14953 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
14954 :style toggle :selected org-cycle-open-archived-trees]
14955 "--"
14956 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
14957 ["Move Subtree to Archive" org-advertized-archive-subtree t]
14958 ; ["Check and Move Children" (org-archive-subtree '(4))
14959 ; :active t :keys "C-u C-c C-x C-s"]
14961 "--"
14962 ("Hyperlinks"
14963 ["Store Link (Global)" org-store-link t]
14964 ["Insert Link" org-insert-link t]
14965 ["Follow Link" org-open-at-point t]
14966 "--"
14967 ["Next link" org-next-link t]
14968 ["Previous link" org-previous-link t]
14969 "--"
14970 ["Descriptive Links"
14971 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
14972 :style radio
14973 :selected (member '(org-link) buffer-invisibility-spec)]
14974 ["Literal Links"
14975 (progn
14976 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
14977 :style radio
14978 :selected (not (member '(org-link) buffer-invisibility-spec))])
14979 "--"
14980 ("TODO Lists"
14981 ["TODO/DONE/-" org-todo t]
14982 ("Select keyword"
14983 ["Next keyword" org-shiftright (org-on-heading-p)]
14984 ["Previous keyword" org-shiftleft (org-on-heading-p)]
14985 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
14986 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
14987 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
14988 ["Show TODO Tree" org-show-todo-tree t]
14989 ["Global TODO list" org-todo-list t]
14990 "--"
14991 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
14992 :selected org-enforce-todo-dependencies :style toggle :active t]
14993 "Settings for tree at point"
14994 ["Do Children sequentially" org-toggle-ordered-property :style radio
14995 :selected (ignore-errors (org-entry-get nil "ORDERED"))
14996 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14997 ["Do Children parallel" org-toggle-ordered-property :style radio
14998 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
14999 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15000 "--"
15001 ["Set Priority" org-priority t]
15002 ["Priority Up" org-shiftup t]
15003 ["Priority Down" org-shiftdown t]
15004 "--"
15005 ["Get news from all feeds" org-feed-update-all t]
15006 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
15007 ["Customize feeds" (customize-variable 'org-feed-alist) t])
15008 ("TAGS and Properties"
15009 ["Set Tags" org-set-tags-command t]
15010 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
15011 "--"
15012 ["Set property" org-set-property t]
15013 ["Column view of properties" org-columns t]
15014 ["Insert Column View DBlock" org-insert-columns-dblock t])
15015 ("Dates and Scheduling"
15016 ["Timestamp" org-time-stamp t]
15017 ["Timestamp (inactive)" org-time-stamp-inactive t]
15018 ("Change Date"
15019 ["1 Day Later" org-shiftright t]
15020 ["1 Day Earlier" org-shiftleft t]
15021 ["1 ... Later" org-shiftup t]
15022 ["1 ... Earlier" org-shiftdown t])
15023 ["Compute Time Range" org-evaluate-time-range t]
15024 ["Schedule Item" org-schedule t]
15025 ["Deadline" org-deadline t]
15026 "--"
15027 ["Custom time format" org-toggle-time-stamp-overlays
15028 :style radio :selected org-display-custom-times]
15029 "--"
15030 ["Goto Calendar" org-goto-calendar t]
15031 ["Date from Calendar" org-date-from-calendar t]
15032 "--"
15033 ["Start/Restart Timer" org-timer-start t]
15034 ["Pause/Continue Timer" org-timer-pause-or-continue t]
15035 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
15036 ["Insert Timer String" org-timer t]
15037 ["Insert Timer Item" org-timer-item t])
15038 ("Logging work"
15039 ["Clock in" org-clock-in t]
15040 ["Clock out" org-clock-out t]
15041 ["Clock cancel" org-clock-cancel t]
15042 ["Goto running clock" org-clock-goto t]
15043 ["Display times" org-clock-display t]
15044 ["Create clock table" org-clock-report t]
15045 "--"
15046 ["Record DONE time"
15047 (progn (setq org-log-done (not org-log-done))
15048 (message "Switching to %s will %s record a timestamp"
15049 (car org-done-keywords)
15050 (if org-log-done "automatically" "not")))
15051 :style toggle :selected org-log-done])
15052 "--"
15053 ["Agenda Command..." org-agenda t]
15054 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
15055 ("File List for Agenda")
15056 ("Special views current file"
15057 ["TODO Tree" org-show-todo-tree t]
15058 ["Check Deadlines" org-check-deadlines t]
15059 ["Timeline" org-timeline t]
15060 ["Tags/Property tree" org-match-sparse-tree t])
15061 "--"
15062 ["Export/Publish..." org-export t]
15063 ("LaTeX"
15064 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
15065 :selected org-cdlatex-mode]
15066 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
15067 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
15068 ["Modify math symbol" org-cdlatex-math-modify
15069 (org-inside-LaTeX-fragment-p)]
15070 ["Insert citation" org-reftex-citation t]
15071 "--"
15072 ["Export LaTeX fragments as images"
15073 (if (featurep 'org-exp)
15074 (setq org-export-with-LaTeX-fragments
15075 (not org-export-with-LaTeX-fragments))
15076 (require 'org-exp))
15077 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
15078 org-export-with-LaTeX-fragments)])
15079 "--"
15080 ("Documentation"
15081 ["Show Version" org-version t]
15082 ["Info Documentation" org-info t])
15083 ("Customize"
15084 ["Browse Org Group" org-customize t]
15085 "--"
15086 ["Expand This Menu" org-create-customize-menu
15087 (fboundp 'customize-menu-create)])
15088 "--"
15089 ("Refresh/Reload"
15090 ["Refresh setup current buffer" org-mode-restart t]
15091 ["Reload Org (after update)" org-reload t]
15092 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
15095 (defun org-info (&optional node)
15096 "Read documentation for Org-mode in the info system.
15097 With optional NODE, go directly to that node."
15098 (interactive)
15099 (info (format "(org)%s" (or node ""))))
15101 (defun org-install-agenda-files-menu ()
15102 (let ((bl (buffer-list)))
15103 (save-excursion
15104 (while bl
15105 (set-buffer (pop bl))
15106 (if (org-mode-p) (setq bl nil)))
15107 (when (org-mode-p)
15108 (easy-menu-change
15109 '("Org") "File List for Agenda"
15110 (append
15111 (list
15112 ["Edit File List" (org-edit-agenda-file-list) t]
15113 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
15114 ["Remove Current File from List" org-remove-file t]
15115 ["Cycle through agenda files" org-cycle-agenda-files t]
15116 ["Occur in all agenda files" org-occur-in-agenda-files t]
15117 "--")
15118 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
15120 ;;;; Documentation
15122 ;;;###autoload
15123 (defun org-require-autoloaded-modules ()
15124 (interactive)
15125 (mapc 'require
15126 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
15127 org-docbook org-exp org-html org-icalendar
15128 org-id org-latex
15129 org-publish org-remember org-table
15130 org-timer org-xoxo)))
15132 ;;;###autoload
15133 (defun org-reload (&optional uncompiled)
15134 "Reload all org lisp files.
15135 With prefix arg UNCOMPILED, load the uncompiled versions."
15136 (interactive "P")
15137 (require 'find-func)
15138 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
15139 (dir-org (file-name-directory (org-find-library-name "org")))
15140 (dir-org-contrib (ignore-errors
15141 (file-name-directory
15142 (org-find-library-name "org-contribdir"))))
15143 (files
15144 (append (directory-files dir-org t file-re)
15145 (and dir-org-contrib
15146 (directory-files dir-org-contrib t file-re))))
15147 (remove-re (concat (if (featurep 'xemacs)
15148 "org-colview" "org-colview-xemacs")
15149 "\\'")))
15150 (setq files (mapcar 'file-name-sans-extension files))
15151 (setq files (mapcar
15152 (lambda (x) (if (string-match remove-re x) nil x))
15153 files))
15154 (setq files (delq nil files))
15155 (mapc
15156 (lambda (f)
15157 (when (featurep (intern (file-name-nondirectory f)))
15158 (if (and (not uncompiled)
15159 (file-exists-p (concat f ".elc")))
15160 (load (concat f ".elc") nil nil t)
15161 (load (concat f ".el") nil nil t))))
15162 files))
15163 (org-version))
15165 ;;;###autoload
15166 (defun org-customize ()
15167 "Call the customize function with org as argument."
15168 (interactive)
15169 (org-load-modules-maybe)
15170 (org-require-autoloaded-modules)
15171 (customize-browse 'org))
15173 (defun org-create-customize-menu ()
15174 "Create a full customization menu for Org-mode, insert it into the menu."
15175 (interactive)
15176 (org-load-modules-maybe)
15177 (org-require-autoloaded-modules)
15178 (if (fboundp 'customize-menu-create)
15179 (progn
15180 (easy-menu-change
15181 '("Org") "Customize"
15182 `(["Browse Org group" org-customize t]
15183 "--"
15184 ,(customize-menu-create 'org)
15185 ["Set" Custom-set t]
15186 ["Save" Custom-save t]
15187 ["Reset to Current" Custom-reset-current t]
15188 ["Reset to Saved" Custom-reset-saved t]
15189 ["Reset to Standard Settings" Custom-reset-standard t]))
15190 (message "\"Org\"-menu now contains full customization menu"))
15191 (error "Cannot expand menu (outdated version of cus-edit.el)")))
15193 ;;;; Miscellaneous stuff
15195 ;;; Generally useful functions
15197 (defun org-find-text-property-in-string (prop s)
15198 "Return the first non-nil value of property PROP in string S."
15199 (or (get-text-property 0 prop s)
15200 (get-text-property (or (next-single-property-change 0 prop s) 0)
15201 prop s)))
15203 (defun org-display-warning (message) ;; Copied from Emacs-Muse
15204 "Display the given MESSAGE as a warning."
15205 (if (fboundp 'display-warning)
15206 (display-warning 'org message
15207 (if (featurep 'xemacs)
15208 'warning
15209 :warning))
15210 (let ((buf (get-buffer-create "*Org warnings*")))
15211 (with-current-buffer buf
15212 (goto-char (point-max))
15213 (insert "Warning (Org): " message)
15214 (unless (bolp)
15215 (newline)))
15216 (display-buffer buf)
15217 (sit-for 0))))
15219 (defun org-goto-marker-or-bmk (marker &optional bookmark)
15220 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
15221 (if (and marker (marker-buffer marker)
15222 (buffer-live-p (marker-buffer marker)))
15223 (progn
15224 (switch-to-buffer (marker-buffer marker))
15225 (if (or (> marker (point-max)) (< marker (point-min)))
15226 (widen))
15227 (goto-char marker)
15228 (org-show-context 'org-goto))
15229 (if bookmark
15230 (bookmark-jump bookmark)
15231 (error "Cannot find location"))))
15233 (defun org-quote-csv-field (s)
15234 "Quote field for inclusion in CSV material."
15235 (if (string-match "[\",]" s)
15236 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
15239 (defun org-plist-delete (plist property)
15240 "Delete PROPERTY from PLIST.
15241 This is in contrast to merely setting it to 0."
15242 (let (p)
15243 (while plist
15244 (if (not (eq property (car plist)))
15245 (setq p (plist-put p (car plist) (nth 1 plist))))
15246 (setq plist (cddr plist)))
15249 (defun org-force-self-insert (N)
15250 "Needed to enforce self-insert under remapping."
15251 (interactive "p")
15252 (self-insert-command N))
15254 (defun org-string-width (s)
15255 "Compute width of string, ignoring invisible characters.
15256 This ignores character with invisibility property `org-link', and also
15257 characters with property `org-cwidth', because these will become invisible
15258 upon the next fontification round."
15259 (let (b l)
15260 (when (or (eq t buffer-invisibility-spec)
15261 (assq 'org-link buffer-invisibility-spec))
15262 (while (setq b (text-property-any 0 (length s)
15263 'invisible 'org-link s))
15264 (setq s (concat (substring s 0 b)
15265 (substring s (or (next-single-property-change
15266 b 'invisible s) (length s)))))))
15267 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
15268 (setq s (concat (substring s 0 b)
15269 (substring s (or (next-single-property-change
15270 b 'org-cwidth s) (length s))))))
15271 (setq l (string-width s) b -1)
15272 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
15273 (setq l (- l (get-text-property b 'org-dwidth-n s))))
15276 (defun org-get-indentation (&optional line)
15277 "Get the indentation of the current line, interpreting tabs.
15278 When LINE is given, assume it represents a line and compute its indentation."
15279 (if line
15280 (if (string-match "^ *" (org-remove-tabs line))
15281 (match-end 0))
15282 (save-excursion
15283 (beginning-of-line 1)
15284 (skip-chars-forward " \t")
15285 (current-column))))
15287 (defun org-remove-tabs (s &optional width)
15288 "Replace tabulators in S with spaces.
15289 Assumes that s is a single line, starting in column 0."
15290 (setq width (or width tab-width))
15291 (while (string-match "\t" s)
15292 (setq s (replace-match
15293 (make-string
15294 (- (* width (/ (+ (match-beginning 0) width) width))
15295 (match-beginning 0)) ?\ )
15296 t t s)))
15299 (defun org-fix-indentation (line ind)
15300 "Fix indentation in LINE.
15301 IND is a cons cell with target and minimum indentation.
15302 If the current indentation in LINE is smaller than the minimum,
15303 leave it alone. If it is larger than ind, set it to the target."
15304 (let* ((l (org-remove-tabs line))
15305 (i (org-get-indentation l))
15306 (i1 (car ind)) (i2 (cdr ind)))
15307 (if (>= i i2) (setq l (substring line i2)))
15308 (if (> i1 0)
15309 (concat (make-string i1 ?\ ) l)
15310 l)))
15312 (defun org-base-buffer (buffer)
15313 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
15314 (if (not buffer)
15315 buffer
15316 (or (buffer-base-buffer buffer)
15317 buffer)))
15319 (defun org-trim (s)
15320 "Remove whitespace at beginning and end of string."
15321 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
15322 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
15325 (defun org-wrap (string &optional width lines)
15326 "Wrap string to either a number of lines, or a width in characters.
15327 If WIDTH is non-nil, the string is wrapped to that width, however many lines
15328 that costs. If there is a word longer than WIDTH, the text is actually
15329 wrapped to the length of that word.
15330 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
15331 many lines, whatever width that takes.
15332 The return value is a list of lines, without newlines at the end."
15333 (let* ((words (org-split-string string "[ \t\n]+"))
15334 (maxword (apply 'max (mapcar 'org-string-width words)))
15335 w ll)
15336 (cond (width
15337 (org-do-wrap words (max maxword width)))
15338 (lines
15339 (setq w maxword)
15340 (setq ll (org-do-wrap words maxword))
15341 (if (<= (length ll) lines)
15343 (setq ll words)
15344 (while (> (length ll) lines)
15345 (setq w (1+ w))
15346 (setq ll (org-do-wrap words w)))
15347 ll))
15348 (t (error "Cannot wrap this")))))
15350 (defun org-do-wrap (words width)
15351 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
15352 (let (lines line)
15353 (while words
15354 (setq line (pop words))
15355 (while (and words (< (+ (length line) (length (car words))) width))
15356 (setq line (concat line " " (pop words))))
15357 (setq lines (push line lines)))
15358 (nreverse lines)))
15360 (defun org-split-string (string &optional separators)
15361 "Splits STRING into substrings at SEPARATORS.
15362 No empty strings are returned if there are matches at the beginning
15363 and end of string."
15364 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
15365 (start 0)
15366 notfirst
15367 (list nil))
15368 (while (and (string-match rexp string
15369 (if (and notfirst
15370 (= start (match-beginning 0))
15371 (< start (length string)))
15372 (1+ start) start))
15373 (< (match-beginning 0) (length string)))
15374 (setq notfirst t)
15375 (or (eq (match-beginning 0) 0)
15376 (and (eq (match-beginning 0) (match-end 0))
15377 (eq (match-beginning 0) start))
15378 (setq list
15379 (cons (substring string start (match-beginning 0))
15380 list)))
15381 (setq start (match-end 0)))
15382 (or (eq start (length string))
15383 (setq list
15384 (cons (substring string start)
15385 list)))
15386 (nreverse list)))
15388 (defun org-uuidgen-p (s)
15389 "Is S an ID created by UUIDGEN?"
15390 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
15392 (defun org-context ()
15393 "Return a list of contexts of the current cursor position.
15394 If several contexts apply, all are returned.
15395 Each context entry is a list with a symbol naming the context, and
15396 two positions indicating start and end of the context. Possible
15397 contexts are:
15399 :headline anywhere in a headline
15400 :headline-stars on the leading stars in a headline
15401 :todo-keyword on a TODO keyword (including DONE) in a headline
15402 :tags on the TAGS in a headline
15403 :priority on the priority cookie in a headline
15404 :item on the first line of a plain list item
15405 :item-bullet on the bullet/number of a plain list item
15406 :checkbox on the checkbox in a plain list item
15407 :table in an org-mode table
15408 :table-special on a special filed in a table
15409 :table-table in a table.el table
15410 :link on a hyperlink
15411 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
15412 :target on a <<target>>
15413 :radio-target on a <<<radio-target>>>
15414 :latex-fragment on a LaTeX fragment
15415 :latex-preview on a LaTeX fragment with overlayed preview image
15417 This function expects the position to be visible because it uses font-lock
15418 faces as a help to recognize the following contexts: :table-special, :link,
15419 and :keyword."
15420 (let* ((f (get-text-property (point) 'face))
15421 (faces (if (listp f) f (list f)))
15422 (p (point)) clist o)
15423 ;; First the large context
15424 (cond
15425 ((org-on-heading-p t)
15426 (push (list :headline (point-at-bol) (point-at-eol)) clist)
15427 (when (progn
15428 (beginning-of-line 1)
15429 (looking-at org-todo-line-tags-regexp))
15430 (push (org-point-in-group p 1 :headline-stars) clist)
15431 (push (org-point-in-group p 2 :todo-keyword) clist)
15432 (push (org-point-in-group p 4 :tags) clist))
15433 (goto-char p)
15434 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
15435 (if (looking-at "\\[#[A-Z0-9]\\]")
15436 (push (org-point-in-group p 0 :priority) clist)))
15438 ((org-at-item-p)
15439 (push (org-point-in-group p 2 :item-bullet) clist)
15440 (push (list :item (point-at-bol)
15441 (save-excursion (org-end-of-item) (point)))
15442 clist)
15443 (and (org-at-item-checkbox-p)
15444 (push (org-point-in-group p 0 :checkbox) clist)))
15446 ((org-at-table-p)
15447 (push (list :table (org-table-begin) (org-table-end)) clist)
15448 (if (memq 'org-formula faces)
15449 (push (list :table-special
15450 (previous-single-property-change p 'face)
15451 (next-single-property-change p 'face)) clist)))
15452 ((org-at-table-p 'any)
15453 (push (list :table-table) clist)))
15454 (goto-char p)
15456 ;; Now the small context
15457 (cond
15458 ((org-at-timestamp-p)
15459 (push (org-point-in-group p 0 :timestamp) clist))
15460 ((memq 'org-link faces)
15461 (push (list :link
15462 (previous-single-property-change p 'face)
15463 (next-single-property-change p 'face)) clist))
15464 ((memq 'org-special-keyword faces)
15465 (push (list :keyword
15466 (previous-single-property-change p 'face)
15467 (next-single-property-change p 'face)) clist))
15468 ((org-on-target-p)
15469 (push (org-point-in-group p 0 :target) clist)
15470 (goto-char (1- (match-beginning 0)))
15471 (if (looking-at org-radio-target-regexp)
15472 (push (org-point-in-group p 0 :radio-target) clist))
15473 (goto-char p))
15474 ((setq o (car (delq nil
15475 (mapcar
15476 (lambda (x)
15477 (if (memq x org-latex-fragment-image-overlays) x))
15478 (org-overlays-at (point))))))
15479 (push (list :latex-fragment
15480 (org-overlay-start o) (org-overlay-end o)) clist)
15481 (push (list :latex-preview
15482 (org-overlay-start o) (org-overlay-end o)) clist))
15483 ((org-inside-LaTeX-fragment-p)
15484 ;; FIXME: positions wrong.
15485 (push (list :latex-fragment (point) (point)) clist)))
15487 (setq clist (nreverse (delq nil clist)))
15488 clist))
15490 ;; FIXME: Compare with at-regexp-p Do we need both?
15491 (defun org-in-regexp (re &optional nlines visually)
15492 "Check if point is inside a match of regexp.
15493 Normally only the current line is checked, but you can include NLINES extra
15494 lines both before and after point into the search.
15495 If VISUALLY is set, require that the cursor is not after the match but
15496 really on, so that the block visually is on the match."
15497 (catch 'exit
15498 (let ((pos (point))
15499 (eol (point-at-eol (+ 1 (or nlines 0))))
15500 (inc (if visually 1 0)))
15501 (save-excursion
15502 (beginning-of-line (- 1 (or nlines 0)))
15503 (while (re-search-forward re eol t)
15504 (if (and (<= (match-beginning 0) pos)
15505 (>= (+ inc (match-end 0)) pos))
15506 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
15508 (defun org-at-regexp-p (regexp)
15509 "Is point inside a match of REGEXP in the current line?"
15510 (catch 'exit
15511 (save-excursion
15512 (let ((pos (point)) (end (point-at-eol)))
15513 (beginning-of-line 1)
15514 (while (re-search-forward regexp end t)
15515 (if (and (<= (match-beginning 0) pos)
15516 (>= (match-end 0) pos))
15517 (throw 'exit t)))
15518 nil))))
15520 (defun org-occur-in-agenda-files (regexp &optional nlines)
15521 "Call `multi-occur' with buffers for all agenda files."
15522 (interactive "sOrg-files matching: \np")
15523 (let* ((files (org-agenda-files))
15524 (tnames (mapcar 'file-truename files))
15525 (extra org-agenda-text-search-extra-files)
15527 (when (eq (car extra) 'agenda-archives)
15528 (setq extra (cdr extra))
15529 (setq files (org-add-archive-files files)))
15530 (while (setq f (pop extra))
15531 (unless (member (file-truename f) tnames)
15532 (add-to-list 'files f 'append)
15533 (add-to-list 'tnames (file-truename f) 'append)))
15534 (multi-occur
15535 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
15536 regexp)))
15538 (if (boundp 'occur-mode-find-occurrence-hook)
15539 ;; Emacs 23
15540 (add-hook 'occur-mode-find-occurrence-hook
15541 (lambda ()
15542 (when (org-mode-p)
15543 (org-reveal))))
15544 ;; Emacs 22
15545 (defadvice occur-mode-goto-occurrence
15546 (after org-occur-reveal activate)
15547 (and (org-mode-p) (org-reveal)))
15548 (defadvice occur-mode-goto-occurrence-other-window
15549 (after org-occur-reveal activate)
15550 (and (org-mode-p) (org-reveal)))
15551 (defadvice occur-mode-display-occurrence
15552 (after org-occur-reveal activate)
15553 (when (org-mode-p)
15554 (let ((pos (occur-mode-find-occurrence)))
15555 (with-current-buffer (marker-buffer pos)
15556 (save-excursion
15557 (goto-char pos)
15558 (org-reveal)))))))
15560 (defun org-uniquify (list)
15561 "Remove duplicate elements from LIST."
15562 (let (res)
15563 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
15564 res))
15566 (defun org-delete-all (elts list)
15567 "Remove all elements in ELTS from LIST."
15568 (while elts
15569 (setq list (delete (pop elts) list)))
15570 list)
15572 (defun org-back-over-empty-lines ()
15573 "Move backwards over whitespace, to the beginning of the first empty line.
15574 Returns the number of empty lines passed."
15575 (let ((pos (point)))
15576 (skip-chars-backward " \t\n\r")
15577 (beginning-of-line 2)
15578 (goto-char (min (point) pos))
15579 (count-lines (point) pos)))
15581 (defun org-skip-whitespace ()
15582 (skip-chars-forward " \t\n\r"))
15584 (defun org-point-in-group (point group &optional context)
15585 "Check if POINT is in match-group GROUP.
15586 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
15587 match. If the match group does ot exist or point is not inside it,
15588 return nil."
15589 (and (match-beginning group)
15590 (>= point (match-beginning group))
15591 (<= point (match-end group))
15592 (if context
15593 (list context (match-beginning group) (match-end group))
15594 t)))
15596 (defun org-switch-to-buffer-other-window (&rest args)
15597 "Switch to buffer in a second window on the current frame.
15598 In particular, do not allow pop-up frames."
15599 (let (pop-up-frames special-display-buffer-names special-display-regexps
15600 special-display-function)
15601 (apply 'switch-to-buffer-other-window args)))
15603 (defun org-combine-plists (&rest plists)
15604 "Create a single property list from all plists in PLISTS.
15605 The process starts by copying the first list, and then setting properties
15606 from the other lists. Settings in the last list are the most significant
15607 ones and overrule settings in the other lists."
15608 (let ((rtn (copy-sequence (pop plists)))
15609 p v ls)
15610 (while plists
15611 (setq ls (pop plists))
15612 (while ls
15613 (setq p (pop ls) v (pop ls))
15614 (setq rtn (plist-put rtn p v))))
15615 rtn))
15617 (defun org-move-line-down (arg)
15618 "Move the current line down. With prefix argument, move it past ARG lines."
15619 (interactive "p")
15620 (let ((col (current-column))
15621 beg end pos)
15622 (beginning-of-line 1) (setq beg (point))
15623 (beginning-of-line 2) (setq end (point))
15624 (beginning-of-line (+ 1 arg))
15625 (setq pos (move-marker (make-marker) (point)))
15626 (insert (delete-and-extract-region beg end))
15627 (goto-char pos)
15628 (org-move-to-column col)))
15630 (defun org-move-line-up (arg)
15631 "Move the current line up. With prefix argument, move it past ARG lines."
15632 (interactive "p")
15633 (let ((col (current-column))
15634 beg end pos)
15635 (beginning-of-line 1) (setq beg (point))
15636 (beginning-of-line 2) (setq end (point))
15637 (beginning-of-line (- arg))
15638 (setq pos (move-marker (make-marker) (point)))
15639 (insert (delete-and-extract-region beg end))
15640 (goto-char pos)
15641 (org-move-to-column col)))
15643 (defun org-replace-escapes (string table)
15644 "Replace %-escapes in STRING with values in TABLE.
15645 TABLE is an association list with keys like \"%a\" and string values.
15646 The sequences in STRING may contain normal field width and padding information,
15647 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
15648 so values can contain further %-escapes if they are define later in TABLE."
15649 (let ((case-fold-search nil)
15650 e re rpl)
15651 (while (setq e (pop table))
15652 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
15653 (while (string-match re string)
15654 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
15655 (cdr e)))
15656 (setq string (replace-match rpl t t string))))
15657 string))
15660 (defun org-sublist (list start end)
15661 "Return a section of LIST, from START to END.
15662 Counting starts at 1."
15663 (let (rtn (c start))
15664 (setq list (nthcdr (1- start) list))
15665 (while (and list (<= c end))
15666 (push (pop list) rtn)
15667 (setq c (1+ c)))
15668 (nreverse rtn)))
15670 (defun org-find-base-buffer-visiting (file)
15671 "Like `find-buffer-visiting' but always return the base buffer and
15672 not an indirect buffer."
15673 (let ((buf (or (get-file-buffer file)
15674 (find-buffer-visiting file))))
15675 (if buf
15676 (or (buffer-base-buffer buf) buf)
15677 nil)))
15679 (defun org-image-file-name-regexp (&optional extensions)
15680 "Return regexp matching the file names of images.
15681 If EXTENSIONS is given, only match these."
15682 (if (and (not extensions) (fboundp 'image-file-name-regexp))
15683 (image-file-name-regexp)
15684 (let ((image-file-name-extensions
15685 (or extensions
15686 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
15687 "xbm" "xpm" "pbm" "pgm" "ppm"))))
15688 (concat "\\."
15689 (regexp-opt (nconc (mapcar 'upcase
15690 image-file-name-extensions)
15691 image-file-name-extensions)
15693 "\\'"))))
15695 (defun org-file-image-p (file &optional extensions)
15696 "Return non-nil if FILE is an image."
15697 (save-match-data
15698 (string-match (org-image-file-name-regexp extensions) file)))
15700 (defun org-get-cursor-date ()
15701 "Return the date at cursor in as a time.
15702 This works in the calendar and in the agenda, anywhere else it just
15703 returns the current time."
15704 (let (date day defd)
15705 (cond
15706 ((eq major-mode 'calendar-mode)
15707 (setq date (calendar-cursor-to-date)
15708 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15709 ((eq major-mode 'org-agenda-mode)
15710 (setq day (get-text-property (point) 'day))
15711 (if day
15712 (setq date (calendar-gregorian-from-absolute day)
15713 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
15714 (nth 2 date))))))
15715 (or defd (current-time))))
15717 (defvar org-agenda-action-marker (make-marker)
15718 "Marker pointing to the entry for the next agenda action.")
15720 (defun org-mark-entry-for-agenda-action ()
15721 "Mark the current entry as target of an agenda action.
15722 Agenda actions are actions executed from the agenda with the key `k',
15723 which make use of the date at the cursor."
15724 (interactive)
15725 (move-marker org-agenda-action-marker
15726 (save-excursion (org-back-to-heading t) (point))
15727 (current-buffer))
15728 (message
15729 "Entry marked for action; press `k' at desired date in agenda or calendar"))
15731 ;;; Paragraph filling stuff.
15732 ;; We want this to be just right, so use the full arsenal.
15734 (defun org-indent-line-function ()
15735 "Indent line like previous, but further if previous was headline or item."
15736 (interactive)
15737 (let* ((pos (point))
15738 (itemp (org-at-item-p))
15739 (org-drawer-regexp (or org-drawer-regexp "\000"))
15740 column bpos bcol tpos tcol bullet btype bullet-type)
15741 ;; Find the previous relevant line
15742 (beginning-of-line 1)
15743 (cond
15744 ((looking-at "#") (setq column 0))
15745 ((looking-at "\\*+ ") (setq column 0))
15746 ((and (looking-at "[ \t]*:END:")
15747 (save-excursion (re-search-backward org-drawer-regexp nil t)))
15748 (save-excursion
15749 (goto-char (1- (match-beginning 1)))
15750 (setq column (current-column))))
15752 (beginning-of-line 0)
15753 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
15754 (not (looking-at "[ \t]*:END:"))
15755 (not (looking-at org-drawer-regexp)))
15756 (beginning-of-line 0))
15757 (cond
15758 ((looking-at "\\*+[ \t]+")
15759 (if (not org-adapt-indentation)
15760 (setq column 0)
15761 (goto-char (match-end 0))
15762 (setq column (current-column))))
15763 ((looking-at org-drawer-regexp)
15764 (goto-char (1- (match-beginning 1)))
15765 (setq column (current-column)))
15766 ((looking-at "\\([ \t]*\\):END:")
15767 (goto-char (match-end 1))
15768 (setq column (current-column)))
15769 ((org-in-item-p)
15770 (org-beginning-of-item)
15771 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
15772 (setq bpos (match-beginning 1) tpos (match-end 0)
15773 bcol (progn (goto-char bpos) (current-column))
15774 tcol (progn (goto-char tpos) (current-column))
15775 bullet (match-string 1)
15776 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
15777 (if (> tcol (+ bcol org-description-max-indent))
15778 (setq tcol (+ bcol 5)))
15779 (if (not itemp)
15780 (setq column tcol)
15781 (goto-char pos)
15782 (beginning-of-line 1)
15783 (if (looking-at "\\S-")
15784 (progn
15785 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
15786 (setq bullet (match-string 1)
15787 btype (if (string-match "[0-9]" bullet) "n" bullet))
15788 (setq column (if (equal btype bullet-type) bcol tcol)))
15789 (setq column (org-get-indentation)))))
15790 (t (setq column (org-get-indentation))))))
15791 (goto-char pos)
15792 (if (<= (current-column) (current-indentation))
15793 (org-indent-line-to column)
15794 (save-excursion (org-indent-line-to column)))
15795 (setq column (current-column))
15796 (beginning-of-line 1)
15797 (if (looking-at
15798 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
15799 (replace-match (concat "\\1" (format org-property-format
15800 (match-string 2) (match-string 3)))
15801 t nil))
15802 (org-move-to-column column)))
15804 (defun org-set-autofill-regexps ()
15805 (interactive)
15806 ;; In the paragraph separator we include headlines, because filling
15807 ;; text in a line directly attached to a headline would otherwise
15808 ;; fill the headline as well.
15809 (org-set-local 'comment-start-skip "^#+[ \t]*")
15810 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
15811 ;; The paragraph starter includes hand-formatted lists.
15812 (org-set-local 'paragraph-start
15813 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
15814 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
15815 ;; But only if the user has not turned off tables or fixed-width regions
15816 (org-set-local
15817 'auto-fill-inhibit-regexp
15818 (concat "\\*+ \\|#\\+"
15819 "\\|[ \t]*" org-keyword-time-regexp
15820 (if (or org-enable-table-editor org-enable-fixed-width-editor)
15821 (concat
15822 "\\|[ \t]*["
15823 (if org-enable-table-editor "|" "")
15824 (if org-enable-fixed-width-editor ":" "")
15825 "]"))))
15826 ;; We use our own fill-paragraph function, to make sure that tables
15827 ;; and fixed-width regions are not wrapped. That function will pass
15828 ;; through to `fill-paragraph' when appropriate.
15829 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
15830 ; Adaptive filling: To get full control, first make sure that
15831 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
15832 (org-set-local 'adaptive-fill-regexp "\000")
15833 (org-set-local 'adaptive-fill-function
15834 'org-adaptive-fill-function)
15835 (org-set-local
15836 'align-mode-rules-list
15837 '((org-in-buffer-settings
15838 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
15839 (modes . '(org-mode))))))
15841 (defun org-fill-paragraph (&optional justify)
15842 "Re-align a table, pass through to fill-paragraph if no table."
15843 (let ((table-p (org-at-table-p))
15844 (table.el-p (org-at-table.el-p)))
15845 (cond ((and (equal (char-after (point-at-bol)) ?*)
15846 (save-excursion (goto-char (point-at-bol))
15847 (looking-at outline-regexp)))
15848 t) ; skip headlines
15849 (table.el-p t) ; skip table.el tables
15850 (table-p (org-table-align) t) ; align org-mode tables
15851 (t nil)))) ; call paragraph-fill
15853 ;; For reference, this is the default value of adaptive-fill-regexp
15854 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
15856 (defun org-adaptive-fill-function ()
15857 "Return a fill prefix for org-mode files.
15858 In particular, this makes sure hanging paragraphs for hand-formatted lists
15859 work correctly."
15860 (cond ((looking-at "#[ \t]+")
15861 (match-string 0))
15862 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
15863 (save-excursion
15864 (if (> (match-end 1) (+ (match-beginning 1)
15865 org-description-max-indent))
15866 (goto-char (+ (match-beginning 1) 5))
15867 (goto-char (match-end 0)))
15868 (make-string (current-column) ?\ )))
15869 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
15870 (save-excursion
15871 (goto-char (match-end 0))
15872 (make-string (current-column) ?\ )))
15873 (t nil)))
15875 ;;; Other stuff.
15877 (defun org-toggle-fixed-width-section (arg)
15878 "Toggle the fixed-width export.
15879 If there is no active region, the QUOTE keyword at the current headline is
15880 inserted or removed. When present, it causes the text between this headline
15881 and the next to be exported as fixed-width text, and unmodified.
15882 If there is an active region, this command adds or removes a colon as the
15883 first character of this line. If the first character of a line is a colon,
15884 this line is also exported in fixed-width font."
15885 (interactive "P")
15886 (let* ((cc 0)
15887 (regionp (org-region-active-p))
15888 (beg (if regionp (region-beginning) (point)))
15889 (end (if regionp (region-end)))
15890 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
15891 (case-fold-search nil)
15892 (re "[ \t]*\\(: \\)")
15893 off)
15894 (if regionp
15895 (save-excursion
15896 (goto-char beg)
15897 (setq cc (current-column))
15898 (beginning-of-line 1)
15899 (setq off (looking-at re))
15900 (while (> nlines 0)
15901 (setq nlines (1- nlines))
15902 (beginning-of-line 1)
15903 (cond
15904 (arg
15905 (org-move-to-column cc t)
15906 (insert ": \n")
15907 (forward-line -1))
15908 ((and off (looking-at re))
15909 (replace-match "" t t nil 1))
15910 ((not off) (org-move-to-column cc t) (insert ": ")))
15911 (forward-line 1)))
15912 (save-excursion
15913 (org-back-to-heading)
15914 (if (looking-at (concat outline-regexp
15915 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
15916 (replace-match "" t t nil 1)
15917 (if (looking-at outline-regexp)
15918 (progn
15919 (goto-char (match-end 0))
15920 (insert org-quote-string " "))))))))
15922 (defun org-reftex-citation ()
15923 "Use reftex-citation to insert a citation into the buffer.
15924 This looks for a line like
15926 #+BIBLIOGRAPHY: foo plain option:-d
15928 and derives from it that foo.bib is the bbliography file relevant
15929 for this document. It then installs the necessary environment for RefTeX
15930 to work in this buffer and calls `reftex-citation' to insert a citation
15931 into the buffer.
15933 Export of such citations to both LaTeX and HTML is handled by the contributed
15934 package org-exp-bibtex by Taru Karttunen."
15935 (interactive)
15936 (let ((reftex-docstruct-symbol 'rds)
15937 (reftex-cite-format "\\cite{%l}")
15938 rds bib)
15939 (save-excursion
15940 (save-restriction
15941 (widen)
15942 (let ((case-fold-search t)
15943 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
15944 (if (not (save-excursion
15945 (or (re-search-forward re nil t)
15946 (re-search-backward re nil t))))
15947 (error "No bibliography defined in file")
15948 (setq bib (concat (match-string 1) ".bib")
15949 rds (list (list 'bib bib)))))))
15950 (call-interactively 'reftex-citation)))
15952 ;;;; Functions extending outline functionality
15954 (defun org-beginning-of-line (&optional arg)
15955 "Go to the beginning of the current line. If that is invisible, continue
15956 to a visible line beginning. This makes the function of C-a more intuitive.
15957 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15958 first attempt, and only move to after the tags when the cursor is already
15959 beyond the end of the headline."
15960 (interactive "P")
15961 (let ((pos (point))
15962 (special (if (consp org-special-ctrl-a/e)
15963 (car org-special-ctrl-a/e)
15964 org-special-ctrl-a/e))
15965 refpos)
15966 (beginning-of-line 1)
15967 (if (and arg (fboundp 'move-beginning-of-line))
15968 (call-interactively 'move-beginning-of-line)
15969 (if (bobp)
15971 (backward-char 1)
15972 (if (org-invisible-p)
15973 (while (and (not (bobp)) (org-invisible-p))
15974 (backward-char 1)
15975 (beginning-of-line 1))
15976 (forward-char 1))))
15977 (when special
15978 (cond
15979 ((and (looking-at org-complex-heading-regexp)
15980 (= (char-after (match-end 1)) ?\ ))
15981 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
15982 (point-at-eol)))
15983 (goto-char
15984 (if (eq special t)
15985 (cond ((> pos refpos) refpos)
15986 ((= pos (point)) refpos)
15987 (t (point)))
15988 (cond ((> pos (point)) (point))
15989 ((not (eq last-command this-command)) (point))
15990 (t refpos)))))
15991 ((org-at-item-p)
15992 (goto-char
15993 (if (eq special t)
15994 (cond ((> pos (match-end 4)) (match-end 4))
15995 ((= pos (point)) (match-end 4))
15996 (t (point)))
15997 (cond ((> pos (point)) (point))
15998 ((not (eq last-command this-command)) (point))
15999 (t (match-end 4))))))))
16000 (org-no-warnings
16001 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16003 (defun org-end-of-line (&optional arg)
16004 "Go to the end of the line.
16005 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16006 first attempt, and only move to after the tags when the cursor is already
16007 beyond the end of the headline."
16008 (interactive "P")
16009 (let ((special (if (consp org-special-ctrl-a/e)
16010 (cdr org-special-ctrl-a/e)
16011 org-special-ctrl-a/e)))
16012 (if (or (not special)
16013 (not (org-on-heading-p))
16014 arg)
16015 (call-interactively (if (fboundp 'move-end-of-line)
16016 'move-end-of-line
16017 'end-of-line))
16018 (let ((pos (point)))
16019 (beginning-of-line 1)
16020 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
16021 (if (eq special t)
16022 (if (or (< pos (match-beginning 1))
16023 (= pos (match-end 0)))
16024 (goto-char (match-beginning 1))
16025 (goto-char (match-end 0)))
16026 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
16027 (goto-char (match-end 0))
16028 (goto-char (match-beginning 1))))
16029 (call-interactively (if (fboundp 'move-end-of-line)
16030 'move-end-of-line
16031 'end-of-line)))))
16032 (org-no-warnings
16033 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16035 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
16036 (define-key org-mode-map "\C-e" 'org-end-of-line)
16038 (defun org-backward-sentence (&optional arg)
16039 "Go to beginning of sentence, or beginning of table field.
16040 This will call `backward-sentence' or `org-table-beginning-of-field',
16041 depending on context."
16042 (interactive "P")
16043 (cond
16044 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
16045 (t (call-interactively 'backward-sentence))))
16047 (defun org-forward-sentence (&optional arg)
16048 "Go to end of sentence, or end of table field.
16049 This will call `forward-sentence' or `org-table-end-of-field',
16050 depending on context."
16051 (interactive "P")
16052 (cond
16053 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
16054 (t (call-interactively 'forward-sentence))))
16056 (define-key org-mode-map "\M-a" 'org-backward-sentence)
16057 (define-key org-mode-map "\M-e" 'org-forward-sentence)
16059 (defun org-kill-line (&optional arg)
16060 "Kill line, to tags or end of line."
16061 (interactive "P")
16062 (cond
16063 ((or (not org-special-ctrl-k)
16064 (bolp)
16065 (not (org-on-heading-p)))
16066 (call-interactively 'kill-line))
16067 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
16068 (kill-region (point) (match-beginning 1))
16069 (org-set-tags nil t))
16070 (t (kill-region (point) (point-at-eol)))))
16072 (define-key org-mode-map "\C-k" 'org-kill-line)
16074 (defun org-yank (&optional arg)
16075 "Yank. If the kill is a subtree, treat it specially.
16076 This command will look at the current kill and check if is a single
16077 subtree, or a series of subtrees[1]. If it passes the test, and if the
16078 cursor is at the beginning of a line or after the stars of a currently
16079 empty headline, then the yank is handled specially. How exactly depends
16080 on the value of the following variables, both set by default.
16082 org-yank-folded-subtrees
16083 When set, the subtree(s) will be folded after insertion, but only
16084 if doing so would now swallow text after the yanked text.
16086 org-yank-adjusted-subtrees
16087 When set, the subtree will be promoted or demoted in order to
16088 fit into the local outline tree structure, which means that the level
16089 will be adjusted so that it becomes the smaller one of the two
16090 *visible* surrounding headings.
16092 Any prefix to this command will cause `yank' to be called directly with
16093 no special treatment. In particular, a simple `C-u' prefix will just
16094 plainly yank the text as it is.
16096 \[1] The test checks if the first non-white line is a heading
16097 and if there are no other headings with fewer stars."
16098 (interactive "P")
16099 (org-yank-generic 'yank arg))
16101 (defun org-yank-generic (command arg)
16102 "Perform some yank-like command.
16104 This function implements the behavior described in the `org-yank'
16105 documentation. However, it has been generalized to work for any
16106 interactive command with similar behavior."
16108 ;; pretend to be command COMMAND
16109 (setq this-command command)
16111 (if arg
16112 (call-interactively command)
16114 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
16115 (and (org-kill-is-subtree-p)
16116 (or (bolp)
16117 (and (looking-at "[ \t]*$")
16118 (string-match
16119 "\\`\\*+\\'"
16120 (buffer-substring (point-at-bol) (point)))))))
16121 swallowp)
16122 (cond
16123 ((and subtreep org-yank-folded-subtrees)
16124 (let ((beg (point))
16125 end)
16126 (if (and subtreep org-yank-adjusted-subtrees)
16127 (org-paste-subtree nil nil 'for-yank)
16128 (call-interactively command))
16130 (setq end (point))
16131 (goto-char beg)
16132 (when (and (bolp) subtreep
16133 (not (setq swallowp
16134 (org-yank-folding-would-swallow-text beg end))))
16135 (or (looking-at outline-regexp)
16136 (re-search-forward (concat "^" outline-regexp) end t))
16137 (while (and (< (point) end) (looking-at outline-regexp))
16138 (hide-subtree)
16139 (org-cycle-show-empty-lines 'folded)
16140 (condition-case nil
16141 (outline-forward-same-level 1)
16142 (error (goto-char end)))))
16143 (when swallowp
16144 (message
16145 "Inserted text not folded because that would swallow text"))
16147 (goto-char end)
16148 (skip-chars-forward " \t\n\r")
16149 (beginning-of-line 1)
16150 (push-mark beg 'nomsg)))
16151 ((and subtreep org-yank-adjusted-subtrees)
16152 (let ((beg (point-at-bol)))
16153 (org-paste-subtree nil nil 'for-yank)
16154 (push-mark beg 'nomsg)))
16156 (call-interactively command))))))
16158 (defun org-yank-folding-would-swallow-text (beg end)
16159 "Would hide-subtree at BEG swallow any text after END?"
16160 (let (level)
16161 (save-excursion
16162 (goto-char beg)
16163 (when (or (looking-at outline-regexp)
16164 (re-search-forward (concat "^" outline-regexp) end t))
16165 (setq level (org-outline-level)))
16166 (goto-char end)
16167 (skip-chars-forward " \t\r\n\v\f")
16168 (if (or (eobp)
16169 (and (bolp) (looking-at org-outline-regexp)
16170 (<= (org-outline-level) level)))
16171 nil ; Nothing would be swallowed
16172 t)))) ; something would swallow
16174 (define-key org-mode-map "\C-y" 'org-yank)
16176 (defun org-invisible-p ()
16177 "Check if point is at a character currently not visible."
16178 ;; Early versions of noutline don't have `outline-invisible-p'.
16179 (if (fboundp 'outline-invisible-p)
16180 (outline-invisible-p)
16181 (get-char-property (point) 'invisible)))
16183 (defun org-invisible-p2 ()
16184 "Check if point is at a character currently not visible."
16185 (save-excursion
16186 (if (and (eolp) (not (bobp))) (backward-char 1))
16187 ;; Early versions of noutline don't have `outline-invisible-p'.
16188 (if (fboundp 'outline-invisible-p)
16189 (outline-invisible-p)
16190 (get-char-property (point) 'invisible))))
16192 (defun org-back-to-heading (&optional invisible-ok)
16193 "Call `outline-back-to-heading', but provide a better error message."
16194 (condition-case nil
16195 (outline-back-to-heading invisible-ok)
16196 (error (error "Before first headline at position %d in buffer %s"
16197 (point) (current-buffer)))))
16199 (defun org-before-first-heading-p ()
16200 "Before first heading?"
16201 (save-excursion
16202 (null (re-search-backward "^\\*+ " nil t))))
16204 (defalias 'org-on-heading-p 'outline-on-heading-p)
16205 (defalias 'org-at-heading-p 'outline-on-heading-p)
16206 (defun org-at-heading-or-item-p ()
16207 (or (org-on-heading-p) (org-at-item-p)))
16209 (defun org-on-target-p ()
16210 (or (org-in-regexp org-radio-target-regexp)
16211 (org-in-regexp org-target-regexp)))
16213 (defun org-up-heading-all (arg)
16214 "Move to the heading line of which the present line is a subheading.
16215 This function considers both visible and invisible heading lines.
16216 With argument, move up ARG levels."
16217 (if (fboundp 'outline-up-heading-all)
16218 (outline-up-heading-all arg) ; emacs 21 version of outline.el
16219 (outline-up-heading arg t))) ; emacs 22 version of outline.el
16221 (defun org-up-heading-safe ()
16222 "Move to the heading line of which the present line is a subheading.
16223 This version will not throw an error. It will return the level of the
16224 headline found, or nil if no higher level is found.
16226 Also, this function will be a lot faster than `outline-up-heading',
16227 because it relies on stars being the outline starters. This can really
16228 make a significant difference in outlines with very many siblings."
16229 (let (start-level re)
16230 (org-back-to-heading t)
16231 (setq start-level (funcall outline-level))
16232 (if (equal start-level 1)
16234 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
16235 (if (re-search-backward re nil t)
16236 (funcall outline-level)))))
16238 (defun org-first-sibling-p ()
16239 "Is this heading the first child of its parents?"
16240 (interactive)
16241 (let ((re (concat "^" outline-regexp))
16242 level l)
16243 (unless (org-at-heading-p t)
16244 (error "Not at a heading"))
16245 (setq level (funcall outline-level))
16246 (save-excursion
16247 (if (not (re-search-backward re nil t))
16249 (setq l (funcall outline-level))
16250 (< l level)))))
16252 (defun org-goto-sibling (&optional previous)
16253 "Goto the next sibling, even if it is invisible.
16254 When PREVIOUS is set, go to the previous sibling instead. Returns t
16255 when a sibling was found. When none is found, return nil and don't
16256 move point."
16257 (let ((fun (if previous 're-search-backward 're-search-forward))
16258 (pos (point))
16259 (re (concat "^" outline-regexp))
16260 level l)
16261 (when (condition-case nil (org-back-to-heading t) (error nil))
16262 (setq level (funcall outline-level))
16263 (catch 'exit
16264 (or previous (forward-char 1))
16265 (while (funcall fun re nil t)
16266 (setq l (funcall outline-level))
16267 (when (< l level) (goto-char pos) (throw 'exit nil))
16268 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
16269 (goto-char pos)
16270 nil))))
16272 (defun org-show-siblings ()
16273 "Show all siblings of the current headline."
16274 (save-excursion
16275 (while (org-goto-sibling) (org-flag-heading nil)))
16276 (save-excursion
16277 (while (org-goto-sibling 'previous)
16278 (org-flag-heading nil))))
16280 (defun org-show-hidden-entry ()
16281 "Show an entry where even the heading is hidden."
16282 (save-excursion
16283 (org-show-entry)))
16285 (defun org-flag-heading (flag &optional entry)
16286 "Flag the current heading. FLAG non-nil means make invisible.
16287 When ENTRY is non-nil, show the entire entry."
16288 (save-excursion
16289 (org-back-to-heading t)
16290 ;; Check if we should show the entire entry
16291 (if entry
16292 (progn
16293 (org-show-entry)
16294 (save-excursion
16295 (and (outline-next-heading)
16296 (org-flag-heading nil))))
16297 (outline-flag-region (max (point-min) (1- (point)))
16298 (save-excursion (outline-end-of-heading) (point))
16299 flag))))
16301 (defun org-forward-same-level (arg)
16302 "Move forward to the ARG'th subheading at same level as this one.
16303 Stop at the first and last subheadings of a superior heading.
16304 This is like outline-forward-same-level, but invisible headings are ok."
16305 (interactive "p")
16306 (org-back-to-heading t)
16307 (while (> arg 0)
16308 (let ((point-to-move-to (save-excursion
16309 (org-get-next-sibling))))
16310 (if point-to-move-to
16311 (progn
16312 (goto-char point-to-move-to)
16313 (setq arg (1- arg)))
16314 (progn
16315 (setq arg 0)
16316 (error "No following same-level heading"))))))
16318 (defun org-get-next-sibling ()
16319 "Move to next heading of the same level, and return point.
16320 If there is no such heading, return nil.
16321 This is like outline-next-sibling, but invisible headings are ok."
16322 (let ((level (funcall outline-level)))
16323 (outline-next-heading)
16324 (while (and (not (eobp)) (> (funcall outline-level) level))
16325 (outline-next-heading))
16326 (if (or (eobp) (< (funcall outline-level) level))
16328 (point))))
16330 (defun org-end-of-subtree (&optional invisible-OK to-heading)
16331 ;; This contains an exact copy of the original function, but it uses
16332 ;; `org-back-to-heading', to make it work also in invisible
16333 ;; trees. And is uses an invisible-OK argument.
16334 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
16335 ;; Furthermore, when used inside Org, finding the end of a large subtree
16336 ;; with many children and grandchildren etc, this can be much faster
16337 ;; than the outline version.
16338 (org-back-to-heading invisible-OK)
16339 (let ((first t)
16340 (level (funcall outline-level)))
16341 (if (and (org-mode-p) (< level 1000))
16342 ;; A true heading (not a plain list item), in Org-mode
16343 ;; This means we can easily find the end by looking
16344 ;; only for the right number of stars. Using a regexp to do
16345 ;; this is so much faster than using a Lisp loop.
16346 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
16347 (forward-char 1)
16348 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
16349 ;; something else, do it the slow way
16350 (while (and (not (eobp))
16351 (or first (> (funcall outline-level) level)))
16352 (setq first nil)
16353 (outline-next-heading)))
16354 (unless to-heading
16355 (if (memq (preceding-char) '(?\n ?\^M))
16356 (progn
16357 ;; Go to end of line before heading
16358 (forward-char -1)
16359 (if (memq (preceding-char) '(?\n ?\^M))
16360 ;; leave blank line before heading
16361 (forward-char -1))))))
16362 (point))
16364 (defun org-show-subtree ()
16365 "Show everything after this heading at deeper levels."
16366 (outline-flag-region
16367 (point)
16368 (save-excursion
16369 (outline-end-of-subtree) (outline-next-heading) (point))
16370 nil))
16372 (defun org-show-entry ()
16373 "Show the body directly following this heading.
16374 Show the heading too, if it is currently invisible."
16375 (interactive)
16376 (save-excursion
16377 (condition-case nil
16378 (progn
16379 (org-back-to-heading t)
16380 (outline-flag-region
16381 (max (point-min) (1- (point)))
16382 (save-excursion
16383 (if (re-search-forward
16384 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
16385 (match-beginning 1)
16386 (point-max)))
16387 nil))
16388 (error nil))))
16390 (defun org-make-options-regexp (kwds &optional extra)
16391 "Make a regular expression for keyword lines."
16392 (concat
16394 "#?[ \t]*\\+\\("
16395 (mapconcat 'regexp-quote kwds "\\|")
16396 (if extra (concat "\\|" extra))
16397 "\\):[ \t]*"
16398 "\\(.+\\)"))
16400 ;; Make isearch reveal the necessary context
16401 (defun org-isearch-end ()
16402 "Reveal context after isearch exits."
16403 (when isearch-success ; only if search was successful
16404 (if (featurep 'xemacs)
16405 ;; Under XEmacs, the hook is run in the correct place,
16406 ;; we directly show the context.
16407 (org-show-context 'isearch)
16408 ;; In Emacs the hook runs *before* restoring the overlays.
16409 ;; So we have to use a one-time post-command-hook to do this.
16410 ;; (Emacs 22 has a special variable, see function `org-mode')
16411 (unless (and (boundp 'isearch-mode-end-hook-quit)
16412 isearch-mode-end-hook-quit)
16413 ;; Only when the isearch was not quitted.
16414 (org-add-hook 'post-command-hook 'org-isearch-post-command
16415 'append 'local)))))
16417 (defun org-isearch-post-command ()
16418 "Remove self from hook, and show context."
16419 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
16420 (org-show-context 'isearch))
16423 ;;;; Integration with and fixes for other packages
16425 ;;; Imenu support
16427 (defvar org-imenu-markers nil
16428 "All markers currently used by Imenu.")
16429 (make-variable-buffer-local 'org-imenu-markers)
16431 (defun org-imenu-new-marker (&optional pos)
16432 "Return a new marker for use by Imenu, and remember the marker."
16433 (let ((m (make-marker)))
16434 (move-marker m (or pos (point)))
16435 (push m org-imenu-markers)
16438 (defun org-imenu-get-tree ()
16439 "Produce the index for Imenu."
16440 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
16441 (setq org-imenu-markers nil)
16442 (let* ((n org-imenu-depth)
16443 (re (concat "^" outline-regexp))
16444 (subs (make-vector (1+ n) nil))
16445 (last-level 0)
16446 m level head)
16447 (save-excursion
16448 (save-restriction
16449 (widen)
16450 (goto-char (point-max))
16451 (while (re-search-backward re nil t)
16452 (setq level (org-reduced-level (funcall outline-level)))
16453 (when (<= level n)
16454 (looking-at org-complex-heading-regexp)
16455 (setq head (org-link-display-format
16456 (org-match-string-no-properties 4))
16457 m (org-imenu-new-marker))
16458 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
16459 (if (>= level last-level)
16460 (push (cons head m) (aref subs level))
16461 (push (cons head (aref subs (1+ level))) (aref subs level))
16462 (loop for i from (1+ level) to n do (aset subs i nil)))
16463 (setq last-level level)))))
16464 (aref subs 1)))
16466 (eval-after-load "imenu"
16467 '(progn
16468 (add-hook 'imenu-after-jump-hook
16469 (lambda ()
16470 (if (eq major-mode 'org-mode)
16471 (org-show-context 'org-goto))))))
16473 (defun org-link-display-format (link)
16474 "Replace a link with either the description, or the link target
16475 if no description is present"
16476 (save-match-data
16477 (if (string-match org-bracket-link-analytic-regexp link)
16478 (replace-match (or (match-string 5 link)
16479 (concat (match-string 1 link)
16480 (match-string 3 link)))
16481 nil nil link)
16482 link)))
16484 ;; Speedbar support
16486 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
16487 "Overlay marking the agenda restriction line in speedbar.")
16488 (org-overlay-put org-speedbar-restriction-lock-overlay
16489 'face 'org-agenda-restriction-lock)
16490 (org-overlay-put org-speedbar-restriction-lock-overlay
16491 'help-echo "Agendas are currently limited to this item.")
16492 (org-detach-overlay org-speedbar-restriction-lock-overlay)
16494 (defun org-speedbar-set-agenda-restriction ()
16495 "Restrict future agenda commands to the location at point in speedbar.
16496 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
16497 (interactive)
16498 (require 'org-agenda)
16499 (let (p m tp np dir txt)
16500 (cond
16501 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16502 'org-imenu t))
16503 (setq m (get-text-property p 'org-imenu-marker))
16504 (save-excursion
16505 (save-restriction
16506 (set-buffer (marker-buffer m))
16507 (goto-char m)
16508 (org-agenda-set-restriction-lock 'subtree))))
16509 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16510 'speedbar-function 'speedbar-find-file))
16511 (setq tp (previous-single-property-change
16512 (1+ p) 'speedbar-function)
16513 np (next-single-property-change
16514 tp 'speedbar-function)
16515 dir (speedbar-line-directory)
16516 txt (buffer-substring-no-properties (or tp (point-min))
16517 (or np (point-max))))
16518 (save-excursion
16519 (save-restriction
16520 (set-buffer (find-file-noselect
16521 (let ((default-directory dir))
16522 (expand-file-name txt))))
16523 (unless (org-mode-p)
16524 (error "Cannot restrict to non-Org-mode file"))
16525 (org-agenda-set-restriction-lock 'file))))
16526 (t (error "Don't know how to restrict Org-mode's agenda")))
16527 (org-move-overlay org-speedbar-restriction-lock-overlay
16528 (point-at-bol) (point-at-eol))
16529 (setq current-prefix-arg nil)
16530 (org-agenda-maybe-redo)))
16532 (eval-after-load "speedbar"
16533 '(progn
16534 (speedbar-add-supported-extension ".org")
16535 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
16536 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
16537 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
16538 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16539 (add-hook 'speedbar-visiting-tag-hook
16540 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
16543 ;;; Fixes and Hacks for problems with other packages
16545 ;; Make flyspell not check words in links, to not mess up our keymap
16546 (defun org-mode-flyspell-verify ()
16547 "Don't let flyspell put overlays at active buttons."
16548 (not (get-text-property (point) 'keymap)))
16550 ;; Make `bookmark-jump' show the jump location if it was hidden.
16551 (eval-after-load "bookmark"
16552 '(if (boundp 'bookmark-after-jump-hook)
16553 ;; We can use the hook
16554 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
16555 ;; Hook not available, use advice
16556 (defadvice bookmark-jump (after org-make-visible activate)
16557 "Make the position visible."
16558 (org-bookmark-jump-unhide))))
16560 ;; Make sure saveplace show the location if it was hidden
16561 (eval-after-load "saveplace"
16562 '(defadvice save-place-find-file-hook (after org-make-visible activate)
16563 "Make the position visible."
16564 (org-bookmark-jump-unhide)))
16566 (defun org-bookmark-jump-unhide ()
16567 "Unhide the current position, to show the bookmark location."
16568 (and (org-mode-p)
16569 (or (org-invisible-p)
16570 (save-excursion (goto-char (max (point-min) (1- (point))))
16571 (org-invisible-p)))
16572 (org-show-context 'bookmark-jump)))
16574 ;; Make session.el ignore our circular variable
16575 (eval-after-load "session"
16576 '(add-to-list 'session-globals-exclude 'org-mark-ring))
16578 ;;;; Experimental code
16580 (defun org-closed-in-range ()
16581 "Sparse tree of items closed in a certain time range.
16582 Still experimental, may disappear in the future."
16583 (interactive)
16584 ;; Get the time interval from the user.
16585 (let* ((time1 (time-to-seconds
16586 (org-read-date nil 'to-time nil "Starting date: ")))
16587 (time2 (time-to-seconds
16588 (org-read-date nil 'to-time nil "End date:")))
16589 ;; callback function
16590 (callback (lambda ()
16591 (let ((time
16592 (time-to-seconds
16593 (apply 'encode-time
16594 (org-parse-time-string
16595 (match-string 1))))))
16596 ;; check if time in interval
16597 (and (>= time time1) (<= time time2))))))
16598 ;; make tree, check each match with the callback
16599 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
16601 ;;;; Finish up
16603 (provide 'org)
16605 (run-hooks 'org-load-hook)
16607 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
16609 ;;; org.el ends here