Docs: minor improvements
[org-mode.git] / lisp / org.el
blobcb5ded436adb991606ea23f2cd94701ac4a16c82
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.23trans
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.23trans"
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 " irc: Links to IRC/ERC chat sessions" org-irc)
171 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
172 (const :tag " mew Links to Mew folders/messages" org-mew)
173 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
174 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
175 (const :tag " vm: Links to VM folders/messages" org-vm)
176 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
177 (const :tag " w3m: Special cut/past from w3m to Org." org-w3m)
178 (const :tag " mouse: Additional mouse support" org-mouse)
180 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
181 (const :tag "C annotation-helper: Call Remember directly from Browser" org-annotation-helper)
182 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
183 (const :tag "C browser-url: Store link, directly from Browser" org-browser-url)
184 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
185 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
186 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
187 (const :tag "C eval: Include command output as text" org-eval)
188 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
189 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
190 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
191 (const :tag "C exp-blocks: Pre-process blocks for export" org-exp-blocks)
192 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
193 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
194 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
195 (const :tag "C mtags: Support for muse-like tags" org-mtags)
196 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
197 (const :tag "C R: Computation using the R language" org-R)
198 (const :tag "C registry: A registry for Org links" org-registry)
199 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
200 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
201 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
202 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
203 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
205 (defcustom org-support-shift-select nil
206 "Non-nil means, make shift-cursor commands select text when possible.
208 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
209 selecting a region, or enlarge thusly regions started in this way.
210 In Org-mode, in special contexts, these same keys are used for other
211 purposes, important enough to compete with shift selection. Org tries
212 to balance these needs by supporting `shift-select-mode' outside these
213 special contexts, under control of this variable.
215 The default of this variable is nil, to avoid confusing behavior. Shifted
216 cursor keys will then execute Org commands in the following contexts:
217 - on a headline, changing TODO state (left/right) and priority (up/down)
218 - on a time stamp, changing the time
219 - in a plain list item, changing the bullet type
220 - in a property definition line, switching between allowed values
221 - in the BEGIN line of a clock table (changing the time block).
222 Outside these contexts, the commands will throw an error.
224 When this variable is t and the cursor is not in a special context,
225 Org-mode will support shift-selection for making and enlarging regions.
226 To make this more effective, the bullet cycling will no longer happen
227 anywhere in an item line, but only if the cursor is exactly on the bullet.
229 If you set this variable to the symbol `always', then the keys
230 will not be special in headlines, property lines, and item lines, to make
231 shift selection work there as well. If this is what you want, you can
232 use the following alternative commands: `C-c C-t' and `C-c ,' to
233 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
234 TODO sets, `C-c -' to cycle item bullet types, and properties can be
235 edited by hand or in column view.
237 However, when the cursor is on a timestamp, shift-cursor commands
238 will still edit the time stamp - this is just too good to give up.
240 XEmacs user should have this variable set to nil, because shift-select-mode
241 is Emacs 23 only."
242 :group 'org
243 :type '(choice
244 (const :tag "Never" nil)
245 (const :tag "When outside special context" t)
246 (const :tag "Everywhere except timestamps" always)))
248 (defgroup org-startup nil
249 "Options concerning startup of Org-mode."
250 :tag "Org Startup"
251 :group 'org)
253 (defcustom org-startup-folded t
254 "Non-nil means, entering Org-mode will switch to OVERVIEW.
255 This can also be configured on a per-file basis by adding one of
256 the following lines anywhere in the buffer:
258 #+STARTUP: fold
259 #+STARTUP: nofold
260 #+STARTUP: content"
261 :group 'org-startup
262 :type '(choice
263 (const :tag "nofold: show all" nil)
264 (const :tag "fold: overview" t)
265 (const :tag "content: all headlines" content)))
267 (defcustom org-startup-truncated t
268 "Non-nil means, entering Org-mode will set `truncate-lines'.
269 This is useful since some lines containing links can be very long and
270 uninteresting. Also tables look terrible when wrapped."
271 :group 'org-startup
272 :type 'boolean)
274 (defcustom org-startup-align-all-tables nil
275 "Non-nil means, align all tables when visiting a file.
276 This is useful when the column width in tables is forced with <N> cookies
277 in table fields. Such tables will look correct only after the first re-align.
278 This can also be configured on a per-file basis by adding one of
279 the following lines anywhere in the buffer:
280 #+STARTUP: align
281 #+STARTUP: noalign"
282 :group 'org-startup
283 :type 'boolean)
285 (defcustom org-insert-mode-line-in-empty-file nil
286 "Non-nil means insert the first line setting Org-mode in empty files.
287 When the function `org-mode' is called interactively in an empty file, this
288 normally means that the file name does not automatically trigger Org-mode.
289 To ensure that the file will always be in Org-mode in the future, a
290 line enforcing Org-mode will be inserted into the buffer, if this option
291 has been set."
292 :group 'org-startup
293 :type 'boolean)
295 (defcustom org-replace-disputed-keys nil
296 "Non-nil means use alternative key bindings for some keys.
297 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
298 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
299 If you want to use Org-mode together with one of these other modes,
300 or more generally if you would like to move some Org-mode commands to
301 other keys, set this variable and configure the keys with the variable
302 `org-disputed-keys'.
304 This option is only relevant at load-time of Org-mode, and must be set
305 *before* org.el is loaded. Changing it requires a restart of Emacs to
306 become effective."
307 :group 'org-startup
308 :type 'boolean)
310 (defcustom org-use-extra-keys nil
311 "Non-nil means use extra key sequence definitions for certain
312 commands. This happens automatically if you run XEmacs or if
313 window-system is nil. This variable lets you do the same
314 manually. You must set it before loading org.
316 Example: on Carbon Emacs 22 running graphically, with an external
317 keyboard on a Powerbook, the default way of setting M-left might
318 not work for either Alt or ESC. Setting this variable will make
319 it work for ESC."
320 :group 'org-startup
321 :type 'boolean)
323 (if (fboundp 'defvaralias)
324 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
326 (defcustom org-disputed-keys
327 '(([(shift up)] . [(meta p)])
328 ([(shift down)] . [(meta n)])
329 ([(shift left)] . [(meta -)])
330 ([(shift right)] . [(meta +)])
331 ([(control shift right)] . [(meta shift +)])
332 ([(control shift left)] . [(meta shift -)]))
333 "Keys for which Org-mode and other modes compete.
334 This is an alist, cars are the default keys, second element specifies
335 the alternative to use when `org-replace-disputed-keys' is t.
337 Keys can be specified in any syntax supported by `define-key'.
338 The value of this option takes effect only at Org-mode's startup,
339 therefore you'll have to restart Emacs to apply it after changing."
340 :group 'org-startup
341 :type 'alist)
343 (defun org-key (key)
344 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
345 Or return the original if not disputed."
346 (if org-replace-disputed-keys
347 (let* ((nkey (key-description key))
348 (x (org-find-if (lambda (x)
349 (equal (key-description (car x)) nkey))
350 org-disputed-keys)))
351 (if x (cdr x) key))
352 key))
354 (defun org-find-if (predicate seq)
355 (catch 'exit
356 (while seq
357 (if (funcall predicate (car seq))
358 (throw 'exit (car seq))
359 (pop seq)))))
361 (defun org-defkey (keymap key def)
362 "Define a key, possibly translated, as returned by `org-key'."
363 (define-key keymap (org-key key) def))
365 (defcustom org-ellipsis nil
366 "The ellipsis to use in the Org-mode outline.
367 When nil, just use the standard three dots. When a string, use that instead,
368 When a face, use the standard 3 dots, but with the specified face.
369 The change affects only Org-mode (which will then use its own display table).
370 Changing this requires executing `M-x org-mode' in a buffer to become
371 effective."
372 :group 'org-startup
373 :type '(choice (const :tag "Default" nil)
374 (face :tag "Face" :value org-warning)
375 (string :tag "String" :value "...#")))
377 (defvar org-display-table nil
378 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
380 (defgroup org-keywords nil
381 "Keywords in Org-mode."
382 :tag "Org Keywords"
383 :group 'org)
385 (defcustom org-deadline-string "DEADLINE:"
386 "String to mark deadline entries.
387 A deadline is this string, followed by a time stamp. Should be a word,
388 terminated by a colon. You can insert a schedule keyword and
389 a timestamp with \\[org-deadline].
390 Changes become only effective after restarting Emacs."
391 :group 'org-keywords
392 :type 'string)
394 (defcustom org-scheduled-string "SCHEDULED:"
395 "String to mark scheduled TODO entries.
396 A schedule is this string, followed by a time stamp. Should be a word,
397 terminated by a colon. You can insert a schedule keyword and
398 a timestamp with \\[org-schedule].
399 Changes become only effective after restarting Emacs."
400 :group 'org-keywords
401 :type 'string)
403 (defcustom org-closed-string "CLOSED:"
404 "String used as the prefix for timestamps logging closing a TODO entry."
405 :group 'org-keywords
406 :type 'string)
408 (defcustom org-clock-string "CLOCK:"
409 "String used as prefix for timestamps clocking work hours on an item."
410 :group 'org-keywords
411 :type 'string)
413 (defcustom org-comment-string "COMMENT"
414 "Entries starting with this keyword will never be exported.
415 An entry can be toggled between COMMENT and normal with
416 \\[org-toggle-comment].
417 Changes become only effective after restarting Emacs."
418 :group 'org-keywords
419 :type 'string)
421 (defcustom org-quote-string "QUOTE"
422 "Entries starting with this keyword will be exported in fixed-width font.
423 Quoting applies only to the text in the entry following the headline, and does
424 not extend beyond the next headline, even if that is lower level.
425 An entry can be toggled between QUOTE and normal with
426 \\[org-toggle-fixed-width-section]."
427 :group 'org-keywords
428 :type 'string)
430 (defconst org-repeat-re
431 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
432 "Regular expression for specifying repeated events.
433 After a match, group 1 contains the repeat expression.")
435 (defgroup org-structure nil
436 "Options concerning the general structure of Org-mode files."
437 :tag "Org Structure"
438 :group 'org)
440 (defgroup org-reveal-location nil
441 "Options about how to make context of a location visible."
442 :tag "Org Reveal Location"
443 :group 'org-structure)
445 (defconst org-context-choice
446 '(choice
447 (const :tag "Always" t)
448 (const :tag "Never" nil)
449 (repeat :greedy t :tag "Individual contexts"
450 (cons
451 (choice :tag "Context"
452 (const agenda)
453 (const org-goto)
454 (const occur-tree)
455 (const tags-tree)
456 (const link-search)
457 (const mark-goto)
458 (const bookmark-jump)
459 (const isearch)
460 (const default))
461 (boolean))))
462 "Contexts for the reveal options.")
464 (defcustom org-show-hierarchy-above '((default . t))
465 "Non-nil means, show full hierarchy when revealing a location.
466 Org-mode often shows locations in an org-mode file which might have
467 been invisible before. When this is set, the hierarchy of headings
468 above the exposed location is shown.
469 Turning this off for example for sparse trees makes them very compact.
470 Instead of t, this can also be an alist specifying this option for different
471 contexts. Valid contexts are
472 agenda when exposing an entry from the agenda
473 org-goto when using the command `org-goto' on key C-c C-j
474 occur-tree when using the command `org-occur' on key C-c /
475 tags-tree when constructing a sparse tree based on tags matches
476 link-search when exposing search matches associated with a link
477 mark-goto when exposing the jump goal of a mark
478 bookmark-jump when exposing a bookmark location
479 isearch when exiting from an incremental search
480 default default for all contexts not set explicitly"
481 :group 'org-reveal-location
482 :type org-context-choice)
484 (defcustom org-show-following-heading '((default . nil))
485 "Non-nil means, show following heading when revealing a location.
486 Org-mode often shows locations in an org-mode file which might have
487 been invisible before. When this is set, the heading following the
488 match is shown.
489 Turning this off for example for sparse trees makes them very compact,
490 but makes it harder to edit the location of the match. In such a case,
491 use the command \\[org-reveal] to show more context.
492 Instead of t, this can also be an alist specifying this option for different
493 contexts. See `org-show-hierarchy-above' for valid contexts."
494 :group 'org-reveal-location
495 :type org-context-choice)
497 (defcustom org-show-siblings '((default . nil) (isearch t))
498 "Non-nil means, show all sibling heading when revealing a location.
499 Org-mode often shows locations in an org-mode file which might have
500 been invisible before. When this is set, the sibling of the current entry
501 heading are all made visible. If `org-show-hierarchy-above' is t,
502 the same happens on each level of the hierarchy above the current entry.
504 By default this is on for the isearch context, off for all other contexts.
505 Turning this off for example for sparse trees makes them very compact,
506 but makes it harder to edit the location of the match. In such a case,
507 use the command \\[org-reveal] to show more context.
508 Instead of t, this can also be an alist specifying this option for different
509 contexts. See `org-show-hierarchy-above' for valid contexts."
510 :group 'org-reveal-location
511 :type org-context-choice)
513 (defcustom org-show-entry-below '((default . nil))
514 "Non-nil means, show the entry below a headline when revealing a location.
515 Org-mode often shows locations in an org-mode file which might have
516 been invisible before. When this is set, the text below the headline that is
517 exposed is also shown.
519 By default this is off for all contexts.
520 Instead of t, this can also be an alist specifying this option for different
521 contexts. See `org-show-hierarchy-above' for valid contexts."
522 :group 'org-reveal-location
523 :type org-context-choice)
525 (defcustom org-indirect-buffer-display 'other-window
526 "How should indirect tree buffers be displayed?
527 This applies to indirect buffers created with the commands
528 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
529 Valid values are:
530 current-window Display in the current window
531 other-window Just display in another window.
532 dedicated-frame Create one new frame, and re-use it each time.
533 new-frame Make a new frame each time. Note that in this case
534 previously-made indirect buffers are kept, and you need to
535 kill these buffers yourself."
536 :group 'org-structure
537 :group 'org-agenda-windows
538 :type '(choice
539 (const :tag "In current window" current-window)
540 (const :tag "In current frame, other window" other-window)
541 (const :tag "Each time a new frame" new-frame)
542 (const :tag "One dedicated frame" dedicated-frame)))
544 (defgroup org-cycle nil
545 "Options concerning visibility cycling in Org-mode."
546 :tag "Org Cycle"
547 :group 'org-structure)
549 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
550 "Names of drawers. Drawers are not opened by cycling on the headline above.
551 Drawers only open with a TAB on the drawer line itself. A drawer looks like
552 this:
553 :DRAWERNAME:
554 .....
555 :END:
556 The drawer \"PROPERTIES\" is special for capturing properties through
557 the property API.
559 Drawers can be defined on the per-file basis with a line like:
561 #+DRAWERS: HIDDEN STATE PROPERTIES"
562 :group 'org-structure
563 :type '(repeat (string :tag "Drawer Name")))
565 (defcustom org-cycle-global-at-bob nil
566 "Cycle globally if cursor is at beginning of buffer and not at a headline.
567 This makes it possible to do global cycling without having to use S-TAB or
568 C-u TAB. For this special case to work, the first line of the buffer
569 must not be a headline - it may be empty or some other text. When used in
570 this way, `org-cycle-hook' is disables temporarily, to make sure the
571 cursor stays at the beginning of the buffer.
572 When this option is nil, don't do anything special at the beginning
573 of the buffer."
574 :group 'org-cycle
575 :type 'boolean)
577 (defcustom org-cycle-emulate-tab t
578 "Where should `org-cycle' emulate TAB.
579 nil Never
580 white Only in completely white lines
581 whitestart Only at the beginning of lines, before the first non-white char
582 t Everywhere except in headlines
583 exc-hl-bol Everywhere except at the start of a headline
584 If TAB is used in a place where it does not emulate TAB, the current subtree
585 visibility is cycled."
586 :group 'org-cycle
587 :type '(choice (const :tag "Never" nil)
588 (const :tag "Only in completely white lines" white)
589 (const :tag "Before first char in a line" whitestart)
590 (const :tag "Everywhere except in headlines" t)
591 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
594 (defcustom org-cycle-separator-lines 2
595 "Number of empty lines needed to keep an empty line between collapsed trees.
596 If you leave an empty line between the end of a subtree and the following
597 headline, this empty line is hidden when the subtree is folded.
598 Org-mode will leave (exactly) one empty line visible if the number of
599 empty lines is equal or larger to the number given in this variable.
600 So the default 2 means, at least 2 empty lines after the end of a subtree
601 are needed to produce free space between a collapsed subtree and the
602 following headline.
604 Special case: when 0, never leave empty lines in collapsed view."
605 :group 'org-cycle
606 :type 'integer)
607 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
609 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
610 org-cycle-hide-drawers
611 org-cycle-show-empty-lines
612 org-optimize-window-after-visibility-change)
613 "Hook that is run after `org-cycle' has changed the buffer visibility.
614 The function(s) in this hook must accept a single argument which indicates
615 the new state that was set by the most recent `org-cycle' command. The
616 argument is a symbol. After a global state change, it can have the values
617 `overview', `content', or `all'. After a local state change, it can have
618 the values `folded', `children', or `subtree'."
619 :group 'org-cycle
620 :type 'hook)
622 (defgroup org-edit-structure nil
623 "Options concerning structure editing in Org-mode."
624 :tag "Org Edit Structure"
625 :group 'org-structure)
627 (defcustom org-odd-levels-only nil
628 "Non-nil means, skip even levels and only use odd levels for the outline.
629 This has the effect that two stars are being added/taken away in
630 promotion/demotion commands. It also influences how levels are
631 handled by the exporters.
632 Changing it requires restart of `font-lock-mode' to become effective
633 for fontification also in regions already fontified.
634 You may also set this on a per-file basis by adding one of the following
635 lines to the buffer:
637 #+STARTUP: odd
638 #+STARTUP: oddeven"
639 :group 'org-edit-structure
640 :group 'org-font-lock
641 :type 'boolean)
643 (defcustom org-adapt-indentation t
644 "Non-nil means, adapt indentation when promoting and demoting.
645 When this is set and the *entire* text in an entry is indented, the
646 indentation is increased by one space in a demotion command, and
647 decreased by one in a promotion command. If any line in the entry
648 body starts at column 0, indentation is not changed at all."
649 :group 'org-edit-structure
650 :type 'boolean)
652 (defcustom org-special-ctrl-a/e nil
653 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
655 When t, `C-a' will bring back the cursor to the beginning of the
656 headline text, i.e. after the stars and after a possible TODO keyword.
657 In an item, this will be the position after the bullet.
658 When the cursor is already at that position, another `C-a' will bring
659 it to the beginning of the line.
661 `C-e' will jump to the end of the headline, ignoring the presence of tags
662 in the headline. A second `C-e' will then jump to the true end of the
663 line, after any tags.
665 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
666 and only a directly following, identical keypress will bring the cursor
667 to the special positions.
669 This may also be a cons cell where the behavior for `C-a' and `C-e' is
670 set separately."
671 :group 'org-edit-structure
672 :type '(choice
673 (const :tag "off" nil)
674 (const :tag "after stars/bullet and before tags first" t)
675 (const :tag "true line boundary first" reversed)
676 (cons :tag "Set C-a and C-e separately"
677 (choice :tag "Special C-a"
678 (const :tag "off" nil)
679 (const :tag "after stars/bullet first" t)
680 (const :tag "before stars/bullet first" reversed))
681 (choice :tag "Special C-e"
682 (const :tag "off" nil)
683 (const :tag "before tags first" t)
684 (const :tag "after tags first" reversed)))))
685 (if (fboundp 'defvaralias)
686 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
688 (defcustom org-special-ctrl-k nil
689 "Non-nil means `C-k' will behave specially in headlines.
690 When nil, `C-k' will call the default `kill-line' command.
691 When t, the following will happen while the cursor is in the headline:
693 - When the cursor is at the beginning of a headline, kill the entire
694 line and possible the folded subtree below the line.
695 - When in the middle of the headline text, kill the headline up to the tags.
696 - When after the headline text, kill the tags."
697 :group 'org-edit-structure
698 :type 'boolean)
700 (defcustom org-yank-folded-subtrees t
701 "Non-nil means, when yanking subtrees, fold them.
702 If the kill is a single subtree, or a sequence of subtrees, i.e. if
703 it starts with a heading and all other headings in it are either children
704 or siblings, then fold all the subtrees. However, do this only if no
705 text after the yank would be swallowed into a folded tree by this action."
706 :group 'org-edit-structure
707 :type 'boolean)
709 (defcustom org-yank-adjusted-subtrees nil
710 "Non-nil means, when yanking subtrees, adjust the level.
711 With this setting, `org-paste-subtree' is used to insert the subtree, see
712 this function for details."
713 :group 'org-edit-structure
714 :type 'boolean)
716 (defcustom org-M-RET-may-split-line '((default . t))
717 "Non-nil means, M-RET will split the line at the cursor position.
718 When nil, it will go to the end of the line before making a
719 new line.
720 You may also set this option in a different way for different
721 contexts. Valid contexts are:
723 headline when creating a new headline
724 item when creating a new item
725 table in a table field
726 default the value to be used for all contexts not explicitly
727 customized"
728 :group 'org-structure
729 :group 'org-table
730 :type '(choice
731 (const :tag "Always" t)
732 (const :tag "Never" nil)
733 (repeat :greedy t :tag "Individual contexts"
734 (cons
735 (choice :tag "Context"
736 (const headline)
737 (const item)
738 (const table)
739 (const default))
740 (boolean)))))
743 (defcustom org-insert-heading-respect-content nil
744 "Non-nil means, insert new headings after the current subtree.
745 When nil, the new heading is created directly after the current line.
746 The commands \\[org-insert-heading-respect-content] and
747 \\[org-insert-todo-heading-respect-content] turn this variable on
748 for the duration of the command."
749 :group 'org-structure
750 :type 'boolean)
752 (defcustom org-blank-before-new-entry '((heading . auto)
753 (plain-list-item . auto))
754 "Should `org-insert-heading' leave a blank line before new heading/item?
755 The value is an alist, with `heading' and `plain-list-item' as car,
756 and a boolean flag as cdr. For plain lists, if the variable
757 `org-empty-line-terminates-plain-lists' is set, the setting here
758 is ignored and no empty line is inserted, to keep the list in tact."
759 :group 'org-edit-structure
760 :type '(list
761 (cons (const heading)
762 (choice (const :tag "Never" nil)
763 (const :tag "Always" t)
764 (const :tag "Auto" auto)))
765 (cons (const plain-list-item)
766 (choice (const :tag "Never" nil)
767 (const :tag "Always" t)
768 (const :tag "Auto" auto)))))
770 (defcustom org-insert-heading-hook nil
771 "Hook being run after inserting a new heading."
772 :group 'org-edit-structure
773 :type 'hook)
775 (defcustom org-enable-fixed-width-editor t
776 "Non-nil means, lines starting with \":\" are treated as fixed-width.
777 This currently only means, they are never auto-wrapped.
778 When nil, such lines will be treated like ordinary lines.
779 See also the QUOTE keyword."
780 :group 'org-edit-structure
781 :type 'boolean)
783 (defcustom org-edit-src-region-extra nil
784 "Additional regexps to identify regions for editing with `org-edit-src-code'.
785 For examples see the function `org-edit-src-find-region-and-lang'.
786 The regular expression identifying the begin marker should end with a newline,
787 and the regexp marking the end line should start with a newline, to make sure
788 there are kept outside the narrowed region."
789 :group 'org-edit-structure
790 :type '(repeat
791 (list
792 (regexp :tag "begin regexp")
793 (regexp :tag "end regexp")
794 (choice :tag "language"
795 (string :tag "specify")
796 (integer :tag "from match group")
797 (const :tag "from `lang' element")
798 (const :tag "from `style' element")))))
800 (defcustom org-coderef-label-format "(ref:%s)"
801 "The default coderef format.
802 This format string will be used to search for coderef labels in literal
803 examples (EXAMPLE and SRC blocks). The format can be overwritten
804 an individual literal example with the -f option, like
806 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
808 #+END_SRC
810 If you want to use this for HTML export, make sure that the format does
811 not introduce special font-locking, and avoid the HTML special
812 characters `<', `>', and `&'. The reason for this restriction is that
813 the labels are searched for only after htmlize has done its job."
814 :group 'org-edit-structure ; FIXME this is not in the right group
815 :type 'string)
817 (defcustom org-edit-fixed-width-region-mode 'artist-mode
818 "The mode that should be used to edit fixed-width regions.
819 These are the regions where each line starts with a colon."
820 :group 'org-edit-structure
821 :type '(choice
822 (const artist-mode)
823 (const picture-mode)
824 (const fundamental-mode)
825 (function :tag "Other (specify)")))
827 (defcustom org-goto-auto-isearch t
828 "Non-nil means, typing characters in org-goto starts incremental search."
829 :group 'org-edit-structure
830 :type 'boolean)
832 (defgroup org-sparse-trees nil
833 "Options concerning sparse trees in Org-mode."
834 :tag "Org Sparse Trees"
835 :group 'org-structure)
837 (defcustom org-highlight-sparse-tree-matches t
838 "Non-nil means, highlight all matches that define a sparse tree.
839 The highlights will automatically disappear the next time the buffer is
840 changed by an edit command."
841 :group 'org-sparse-trees
842 :type 'boolean)
844 (defcustom org-remove-highlights-with-change t
845 "Non-nil means, any change to the buffer will remove temporary highlights.
846 Such highlights are created by `org-occur' and `org-clock-display'.
847 When nil, `C-c C-c needs to be used to get rid of the highlights.
848 The highlights created by `org-preview-latex-fragment' always need
849 `C-c C-c' to be removed."
850 :group 'org-sparse-trees
851 :group 'org-time
852 :type 'boolean)
855 (defcustom org-occur-hook '(org-first-headline-recenter)
856 "Hook that is run after `org-occur' has constructed a sparse tree.
857 This can be used to recenter the window to show as much of the structure
858 as possible."
859 :group 'org-sparse-trees
860 :type 'hook)
862 (defgroup org-imenu-and-speedbar nil
863 "Options concerning imenu and speedbar in Org-mode."
864 :tag "Org Imenu and Speedbar"
865 :group 'org-structure)
867 (defcustom org-imenu-depth 2
868 "The maximum level for Imenu access to Org-mode headlines.
869 This also applied for speedbar access."
870 :group 'org-imenu-and-speedbar
871 :type 'number)
873 (defgroup org-table nil
874 "Options concerning tables in Org-mode."
875 :tag "Org Table"
876 :group 'org)
878 (defcustom org-enable-table-editor 'optimized
879 "Non-nil means, lines starting with \"|\" are handled by the table editor.
880 When nil, such lines will be treated like ordinary lines.
882 When equal to the symbol `optimized', the table editor will be optimized to
883 do the following:
884 - Automatic overwrite mode in front of whitespace in table fields.
885 This makes the structure of the table stay in tact as long as the edited
886 field does not exceed the column width.
887 - Minimize the number of realigns. Normally, the table is aligned each time
888 TAB or RET are pressed to move to another field. With optimization this
889 happens only if changes to a field might have changed the column width.
890 Optimization requires replacing the functions `self-insert-command',
891 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
892 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
893 very good at guessing when a re-align will be necessary, but you can always
894 force one with \\[org-ctrl-c-ctrl-c].
896 If you would like to use the optimized version in Org-mode, but the
897 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
899 This variable can be used to turn on and off the table editor during a session,
900 but in order to toggle optimization, a restart is required.
902 See also the variable `org-table-auto-blank-field'."
903 :group 'org-table
904 :type '(choice
905 (const :tag "off" nil)
906 (const :tag "on" t)
907 (const :tag "on, optimized" optimized)))
909 (defcustom org-self-insert-cluster-for-undo t
910 "Non-nil means cluster self-insert commands for undo when possible.
911 If this is set, then, like in the Emacs command loop, 20 consequtive
912 characters will be undone together.
913 This is configurable, because there is some impact on typing performance."
914 :group 'org-table
915 :type 'boolean)
917 (defcustom org-table-tab-recognizes-table.el t
918 "Non-nil means, TAB will automatically notice a table.el table.
919 When it sees such a table, it moves point into it and - if necessary -
920 calls `table-recognize-table'."
921 :group 'org-table-editing
922 :type 'boolean)
924 (defgroup org-link nil
925 "Options concerning links in Org-mode."
926 :tag "Org Link"
927 :group 'org)
929 (defvar org-link-abbrev-alist-local nil
930 "Buffer-local version of `org-link-abbrev-alist', which see.
931 The value of this is taken from the #+LINK lines.")
932 (make-variable-buffer-local 'org-link-abbrev-alist-local)
934 (defcustom org-link-abbrev-alist nil
935 "Alist of link abbreviations.
936 The car of each element is a string, to be replaced at the start of a link.
937 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
938 links in Org-mode buffers can have an optional tag after a double colon, e.g.
940 [[linkkey:tag][description]]
942 The 'linkkey' must be a word word, starting with a letter, followed
943 by letters, numbers, '-' or '_'.
945 If REPLACE is a string, the tag will simply be appended to create the link.
946 If the string contains \"%s\", the tag will be inserted there. Alternatively,
947 the placeholder \"%h\" will cause a url-encoded version of the tag to
948 be inserted at that point (see the function `url-hexify-string').
950 REPLACE may also be a function that will be called with the tag as the
951 only argument to create the link, which should be returned as a string.
953 See the manual for examples."
954 :group 'org-link
955 :type '(repeat
956 (cons
957 (string :tag "Protocol")
958 (choice
959 (string :tag "Format")
960 (function)))))
962 (defcustom org-descriptive-links t
963 "Non-nil means, hide link part and only show description of bracket links.
964 Bracket links are like [[link][description]]. This variable sets the initial
965 state in new org-mode buffers. The setting can then be toggled on a
966 per-buffer basis from the Org->Hyperlinks menu."
967 :group 'org-link
968 :type 'boolean)
970 (defcustom org-link-file-path-type 'adaptive
971 "How the path name in file links should be stored.
972 Valid values are:
974 relative Relative to the current directory, i.e. the directory of the file
975 into which the link is being inserted.
976 absolute Absolute path, if possible with ~ for home directory.
977 noabbrev Absolute path, no abbreviation of home directory.
978 adaptive Use relative path for files in the current directory and sub-
979 directories of it. For other files, use an absolute path."
980 :group 'org-link
981 :type '(choice
982 (const relative)
983 (const absolute)
984 (const noabbrev)
985 (const adaptive)))
987 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
988 "Types of links that should be activated in Org-mode files.
989 This is a list of symbols, each leading to the activation of a certain link
990 type. In principle, it does not hurt to turn on most link types - there may
991 be a small gain when turning off unused link types. The types are:
993 bracket The recommended [[link][description]] or [[link]] links with hiding.
994 angular Links in angular brackets that may contain whitespace like
995 <bbdb:Carsten Dominik>.
996 plain Plain links in normal text, no whitespace, like http://google.com.
997 radio Text that is matched by a radio target, see manual for details.
998 tag Tag settings in a headline (link to tag search).
999 date Time stamps (link to calendar).
1000 footnote Footnote labels.
1002 Changing this variable requires a restart of Emacs to become effective."
1003 :group 'org-link
1004 :type '(set :greedy t
1005 (const :tag "Double bracket links (new style)" bracket)
1006 (const :tag "Angular bracket links (old style)" angular)
1007 (const :tag "Plain text links" plain)
1008 (const :tag "Radio target matches" radio)
1009 (const :tag "Tags" tag)
1010 (const :tag "Timestamps" date)
1011 (const :tag "Footnotes" footnote)))
1013 (defcustom org-make-link-description-function nil
1014 "Function to use to generate link descriptions from links. If
1015 nil the link location will be used. This function must take two
1016 parameters; the first is the link and the second the description
1017 org-insert-link has generated, and should return the description
1018 to use."
1019 :group 'org-link
1020 :type 'function)
1022 (defgroup org-link-store nil
1023 "Options concerning storing links in Org-mode."
1024 :tag "Org Store Link"
1025 :group 'org-link)
1027 (defcustom org-email-link-description-format "Email %c: %.30s"
1028 "Format of the description part of a link to an email or usenet message.
1029 The following %-escapes will be replaced by corresponding information:
1031 %F full \"From\" field
1032 %f name, taken from \"From\" field, address if no name
1033 %T full \"To\" field
1034 %t first name in \"To\" field, address if no name
1035 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1036 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1037 %s subject
1038 %m message-id.
1040 You may use normal field width specification between the % and the letter.
1041 This is for example useful to limit the length of the subject.
1043 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1044 :group 'org-link-store
1045 :type 'string)
1047 (defcustom org-from-is-user-regexp
1048 (let (r1 r2)
1049 (when (and user-mail-address (not (string= user-mail-address "")))
1050 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1051 (when (and user-full-name (not (string= user-full-name "")))
1052 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1053 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1054 "Regexp matched against the \"From:\" header of an email or usenet message.
1055 It should match if the message is from the user him/herself."
1056 :group 'org-link-store
1057 :type 'regexp)
1059 (defcustom org-link-to-org-use-id 'create-if-interactive
1060 "Non-nil means, storing a link to an Org file will use entry IDs.
1062 Note that before this variable is even considered, org-id must be loaded,
1063 to please customize `org-modules' and turn it on.
1065 The variable can have the following values:
1067 t Create an ID if needed to make a link to the current entry.
1069 create-if-interactive
1070 If `org-store-link' is called directly (interactively, as a user
1071 command), do create an ID to support the link. But when doing the
1072 job for remember, only use the ID if it already exists. The
1073 purpose of this setting is to avoid proliferation of unwanted
1074 IDs, just because you happen to be in an Org file when you
1075 call `org-remember' that automatically and preemptively
1076 creates a link. If you do want to get an ID link in a remember
1077 template to an entry not having an ID, create it first by
1078 explicitly creating a link to it, using `C-c C-l' first.
1080 use-existing
1081 Use existing ID, do not create one.
1083 nil Never use an ID to make a link, instead link using a text search for
1084 the headline text."
1085 :group 'org-link-store
1086 :type '(choice
1087 (const :tag "Create ID to make link" t)
1088 (const :tag "Create if string link interactively"
1089 'create-if-interactive)
1090 (const :tag "Only use existing" 'use-existing)
1091 (const :tag "Do not use ID to create link" nil)))
1093 (defcustom org-context-in-file-links t
1094 "Non-nil means, file links from `org-store-link' contain context.
1095 A search string will be added to the file name with :: as separator and
1096 used to find the context when the link is activated by the command
1097 `org-open-at-point'.
1098 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1099 negates this setting for the duration of the command."
1100 :group 'org-link-store
1101 :type 'boolean)
1103 (defcustom org-keep-stored-link-after-insertion nil
1104 "Non-nil means, keep link in list for entire session.
1106 The command `org-store-link' adds a link pointing to the current
1107 location to an internal list. These links accumulate during a session.
1108 The command `org-insert-link' can be used to insert links into any
1109 Org-mode file (offering completion for all stored links). When this
1110 option is nil, every link which has been inserted once using \\[org-insert-link]
1111 will be removed from the list, to make completing the unused links
1112 more efficient."
1113 :group 'org-link-store
1114 :type 'boolean)
1116 (defgroup org-link-follow nil
1117 "Options concerning following links in Org-mode."
1118 :tag "Org Follow Link"
1119 :group 'org-link)
1121 (defcustom org-link-translation-function nil
1122 "Function to translate links with different syntax to Org syntax.
1123 This can be used to translate links created for example by the Planner
1124 or emacs-wiki packages to Org syntax.
1125 The function must accept two parameters, a TYPE containing the link
1126 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1127 which is everything after the link protocol. It should return a cons
1128 with possibly modified values of type and path.
1129 Org contains a function for this, so if you set this variable to
1130 `org-translate-link-from-planner', you should be able follow many
1131 links created by planner."
1132 :group 'org-link-follow
1133 :type 'function)
1135 (defcustom org-follow-link-hook nil
1136 "Hook that is run after a link has been followed."
1137 :group 'org-link-follow
1138 :type 'hook)
1140 (defcustom org-tab-follows-link nil
1141 "Non-nil means, on links TAB will follow the link.
1142 Needs to be set before org.el is loaded.
1143 This really should not be used, it does not make sense, and the
1144 implementation is bad."
1145 :group 'org-link-follow
1146 :type 'boolean)
1148 (defcustom org-return-follows-link nil
1149 "Non-nil means, on links RET will follow the link.
1150 Needs to be set before org.el is loaded."
1151 :group 'org-link-follow
1152 :type 'boolean)
1154 (defcustom org-mouse-1-follows-link
1155 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1156 "Non-nil means, mouse-1 on a link will follow the link.
1157 A longer mouse click will still set point. Does not work on XEmacs.
1158 Needs to be set before org.el is loaded."
1159 :group 'org-link-follow
1160 :type 'boolean)
1162 (defcustom org-mark-ring-length 4
1163 "Number of different positions to be recorded in the ring
1164 Changing this requires a restart of Emacs to work correctly."
1165 :group 'org-link-follow
1166 :type 'integer)
1168 (defcustom org-link-frame-setup
1169 '((vm . vm-visit-folder-other-frame)
1170 (gnus . gnus-other-frame)
1171 (file . find-file-other-window))
1172 "Setup the frame configuration for following links.
1173 When following a link with Emacs, it may often be useful to display
1174 this link in another window or frame. This variable can be used to
1175 set this up for the different types of links.
1176 For VM, use any of
1177 `vm-visit-folder'
1178 `vm-visit-folder-other-frame'
1179 For Gnus, use any of
1180 `gnus'
1181 `gnus-other-frame'
1182 `org-gnus-no-new-news'
1183 For FILE, use any of
1184 `find-file'
1185 `find-file-other-window'
1186 `find-file-other-frame'
1187 For the calendar, use the variable `calendar-setup'.
1188 For BBDB, it is currently only possible to display the matches in
1189 another window."
1190 :group 'org-link-follow
1191 :type '(list
1192 (cons (const vm)
1193 (choice
1194 (const vm-visit-folder)
1195 (const vm-visit-folder-other-window)
1196 (const vm-visit-folder-other-frame)))
1197 (cons (const gnus)
1198 (choice
1199 (const gnus)
1200 (const gnus-other-frame)
1201 (const org-gnus-no-new-news)))
1202 (cons (const file)
1203 (choice
1204 (const find-file)
1205 (const find-file-other-window)
1206 (const find-file-other-frame)))))
1208 (defcustom org-display-internal-link-with-indirect-buffer nil
1209 "Non-nil means, use indirect buffer to display infile links.
1210 Activating internal links (from one location in a file to another location
1211 in the same file) normally just jumps to the location. When the link is
1212 activated with a C-u prefix (or with mouse-3), the link is displayed in
1213 another window. When this option is set, the other window actually displays
1214 an indirect buffer clone of the current buffer, to avoid any visibility
1215 changes to the current buffer."
1216 :group 'org-link-follow
1217 :type 'boolean)
1219 (defcustom org-open-non-existing-files nil
1220 "Non-nil means, `org-open-file' will open non-existing files.
1221 When nil, an error will be generated."
1222 :group 'org-link-follow
1223 :type 'boolean)
1225 (defcustom org-open-directory-means-index-dot-org nil
1226 "Non-nil means, a link to a directory really means to index.org.
1227 When nil, following a directory link will run dired or open a finder/explorer
1228 window on that directory."
1229 :group 'org-link-follow
1230 :type 'boolean)
1232 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1233 "Function and arguments to call for following mailto links.
1234 This is a list with the first element being a lisp function, and the
1235 remaining elements being arguments to the function. In string arguments,
1236 %a will be replaced by the address, and %s will be replaced by the subject
1237 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1238 :group 'org-link-follow
1239 :type '(choice
1240 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1241 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1242 (const :tag "message-mail" (message-mail "%a" "%s"))
1243 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1245 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1246 "Non-nil means, ask for confirmation before executing shell links.
1247 Shell links can be dangerous: just think about a link
1249 [[shell:rm -rf ~/*][Google Search]]
1251 This link would show up in your Org-mode document as \"Google Search\",
1252 but really it would remove your entire home directory.
1253 Therefore we advise against setting this variable to nil.
1254 Just change it to `y-or-n-p' of you want to confirm with a
1255 single keystroke rather than having to type \"yes\"."
1256 :group 'org-link-follow
1257 :type '(choice
1258 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1259 (const :tag "with y-or-n (faster)" y-or-n-p)
1260 (const :tag "no confirmation (dangerous)" nil)))
1262 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1263 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1264 Elisp links can be dangerous: just think about a link
1266 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1268 This link would show up in your Org-mode document as \"Google Search\",
1269 but really it would remove your entire home directory.
1270 Therefore we advise against setting this variable to nil.
1271 Just change it to `y-or-n-p' of you want to confirm with a
1272 single keystroke rather than having to type \"yes\"."
1273 :group 'org-link-follow
1274 :type '(choice
1275 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1276 (const :tag "with y-or-n (faster)" y-or-n-p)
1277 (const :tag "no confirmation (dangerous)" nil)))
1279 (defconst org-file-apps-defaults-gnu
1280 '((remote . emacs)
1281 (system . mailcap)
1282 (t . mailcap))
1283 "Default file applications on a UNIX or GNU/Linux system.
1284 See `org-file-apps'.")
1286 (defconst org-file-apps-defaults-macosx
1287 '((remote . emacs)
1288 (t . "open %s")
1289 (system . "open %s")
1290 ("ps.gz" . "gv %s")
1291 ("eps.gz" . "gv %s")
1292 ("dvi" . "xdvi %s")
1293 ("fig" . "xfig %s"))
1294 "Default file applications on a MacOS X system.
1295 The system \"open\" is known as a default, but we use X11 applications
1296 for some files for which the OS does not have a good default.
1297 See `org-file-apps'.")
1299 (defconst org-file-apps-defaults-windowsnt
1300 (list
1301 '(remote . emacs)
1302 (cons t
1303 (list (if (featurep 'xemacs)
1304 'mswindows-shell-execute
1305 'w32-shell-execute)
1306 "open" 'file))
1307 (cons 'system
1308 (list (if (featurep 'xemacs)
1309 'mswindows-shell-execute
1310 'w32-shell-execute)
1311 "open" 'file)))
1312 "Default file applications on a Windows NT system.
1313 The system \"open\" is used for most files.
1314 See `org-file-apps'.")
1316 (defcustom org-file-apps
1318 (auto-mode . emacs)
1319 ("\\.x?html?\\'" . default)
1320 ("\\.pdf\\'" . default)
1322 "External applications for opening `file:path' items in a document.
1323 Org-mode uses system defaults for different file types, but
1324 you can use this variable to set the application for a given file
1325 extension. The entries in this list are cons cells where the car identifies
1326 files and the cdr the corresponding command. Possible values for the
1327 file identifier are
1328 \"regex\" Regular expression matched against the file name. For backward
1329 compatibility, this can also be a string with only alphanumeric
1330 characters, which is then interpreted as an extension.
1331 `directory' Matches a directory
1332 `remote' Matches a remote file, accessible through tramp or efs.
1333 Remote files most likely should be visited through Emacs
1334 because external applications cannot handle such paths.
1335 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1336 so all files Emacs knows how to handle. Using this with
1337 command `emacs' will open most files in Emacs. Beware that this
1338 will also open html files inside Emacs, unless you add
1339 (\"html\" . default) to the list as well.
1340 t Default for files not matched by any of the other options.
1341 `system' The system command to open files, like `open' on Windows
1342 and Mac OS X, and mailcap under GNU/Linux. This is the command
1343 that will be selected if you call `C-c C-o' with a double
1344 `C-u C-u' prefix.
1346 Possible values for the command are:
1347 `emacs' The file will be visited by the current Emacs process.
1348 `default' Use the default application for this file type, which is the
1349 association for t in the list, most likely in the system-specific
1350 part.
1351 This can be used to overrule an unwanted setting in the
1352 system-specific variable.
1353 `system' Use the system command for opening files, like \"open\".
1354 This command is specified by the entry whose car is `system'.
1355 Most likely, the system-specific version of this variable
1356 does define this command, but you can overrule/replace it
1357 here.
1358 string A command to be executed by a shell; %s will be replaced
1359 by the path to the file.
1360 sexp A Lisp form which will be evaluated. The file path will
1361 be available in the Lisp variable `file'.
1362 For more examples, see the system specific constants
1363 `org-file-apps-defaults-macosx'
1364 `org-file-apps-defaults-windowsnt'
1365 `org-file-apps-defaults-gnu'."
1366 :group 'org-link-follow
1367 :type '(repeat
1368 (cons (choice :value ""
1369 (string :tag "Extension")
1370 (const :tag "System command to open files" system)
1371 (const :tag "Default for unrecognized files" t)
1372 (const :tag "Remote file" remote)
1373 (const :tag "Links to a directory" directory)
1374 (const :tag "Any files that have Emacs modes"
1375 auto-mode))
1376 (choice :value ""
1377 (const :tag "Visit with Emacs" emacs)
1378 (const :tag "Use default" default)
1379 (const :tag "Use the system command" system)
1380 (string :tag "Command")
1381 (sexp :tag "Lisp form")))))
1383 (defgroup org-refile nil
1384 "Options concerning refiling entries in Org-mode."
1385 :tag "Org Refile"
1386 :group 'org)
1388 (defcustom org-directory "~/org"
1389 "Directory with org files.
1390 This is just a default location to look for Org files. There is no need
1391 at all to put your files into this directory. It is only used in the
1392 following situations:
1394 1. When a remember template specifies a target file that is not an
1395 absolute path. The path will then be interpreted relative to
1396 `org-directory'
1397 2. When a remember note is filed away in an interactive way (when exiting the
1398 note buffer with `C-1 C-c C-c'. The the user is prompted for an org file,
1399 with `org-directory' as the default path."
1400 :group 'org-refile
1401 :group 'org-remember
1402 :type 'directory)
1404 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1405 "Default target for storing notes.
1406 Used by the hooks for remember.el. This can be a string, or nil to mean
1407 the value of `remember-data-file'.
1408 You can set this on a per-template basis with the variable
1409 `org-remember-templates'."
1410 :group 'org-refile
1411 :group 'org-remember
1412 :type '(choice
1413 (const :tag "Default from remember-data-file" nil)
1414 file))
1416 (defcustom org-goto-interface 'outline
1417 "The default interface to be used for `org-goto'.
1418 Allowed values are:
1419 outline The interface shows an outline of the relevant file
1420 and the correct heading is found by moving through
1421 the outline or by searching with incremental search.
1422 outline-path-completion Headlines in the current buffer are offered via
1423 completion. This is the interface also used by
1424 the refile command."
1425 :group 'org-refile
1426 :type '(choice
1427 (const :tag "Outline" outline)
1428 (const :tag "Outline-path-completion" outline-path-completion)))
1430 (defcustom org-goto-max-level 5
1431 "Maximum level to be considered when running org-goto with refile interface."
1432 :group 'org-refile
1433 :type 'number)
1435 (defcustom org-reverse-note-order nil
1436 "Non-nil means, store new notes at the beginning of a file or entry.
1437 When nil, new notes will be filed to the end of a file or entry.
1438 This can also be a list with cons cells of regular expressions that
1439 are matched against file names, and values."
1440 :group 'org-remember
1441 :group 'org-refile
1442 :type '(choice
1443 (const :tag "Reverse always" t)
1444 (const :tag "Reverse never" nil)
1445 (repeat :tag "By file name regexp"
1446 (cons regexp boolean))))
1448 (defcustom org-refile-targets nil
1449 "Targets for refiling entries with \\[org-refile].
1450 This is list of cons cells. Each cell contains:
1451 - a specification of the files to be considered, either a list of files,
1452 or a symbol whose function or variable value will be used to retrieve
1453 a file name or a list of file names. If you use `org-agenda-files' for
1454 that, all agenda files will be scanned for targets. Nil means, consider
1455 headings in the current buffer.
1456 - A specification of how to find candidate refile targets. This may be
1457 any of:
1458 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1459 This tag has to be present in all target headlines, inheritance will
1460 not be considered.
1461 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1462 todo keyword.
1463 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1464 headlines that are refiling targets.
1465 - a cons cell (:level . N). Any headline of level N is considered a target.
1466 Note that, when `org-odd-levels-only' is set, level corresponds to
1467 order in hierarchy, not to the number of stars.
1468 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1469 Note that, when `org-odd-levels-only' is set, level corresponds to
1470 order in hierarchy, not to the number of stars.
1472 When this variable is nil, all top-level headlines in the current buffer
1473 are used, equivalent to the value `((nil . (:level . 1))'."
1474 :group 'org-refile
1475 :type '(repeat
1476 (cons
1477 (choice :value org-agenda-files
1478 (const :tag "All agenda files" org-agenda-files)
1479 (const :tag "Current buffer" nil)
1480 (function) (variable) (file))
1481 (choice :tag "Identify target headline by"
1482 (cons :tag "Specific tag" (const :value :tag) (string))
1483 (cons :tag "TODO keyword" (const :value :todo) (string))
1484 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1485 (cons :tag "Level number" (const :value :level) (integer))
1486 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1488 (defcustom org-refile-use-outline-path nil
1489 "Non-nil means, provide refile targets as paths.
1490 So a level 3 headline will be available as level1/level2/level3.
1491 When the value is `file', also include the file name (without directory)
1492 into the path. When `full-file-path', include the full file path."
1493 :group 'org-refile
1494 :type '(choice
1495 (const :tag "Not" nil)
1496 (const :tag "Yes" t)
1497 (const :tag "Start with file name" file)
1498 (const :tag "Start with full file path" full-file-path)))
1500 (defcustom org-outline-path-complete-in-steps t
1501 "Non-nil means, complete the outline path in hierarchical steps.
1502 When Org-mode uses the refile interface to select an outline path
1503 \(see variable `org-refile-use-outline-path'), the completion of
1504 the path can be done is a single go, or if can be done in steps down
1505 the headline hierarchy. Going in steps is probably the best if you
1506 do not use a special completion package like `ido' or `icicles'.
1507 However, when using these packages, going in one step can be very
1508 fast, while still showing the whole path to the entry."
1509 :group 'org-refile
1510 :type 'boolean)
1512 (defgroup org-todo nil
1513 "Options concerning TODO items in Org-mode."
1514 :tag "Org TODO"
1515 :group 'org)
1517 (defgroup org-progress nil
1518 "Options concerning Progress logging in Org-mode."
1519 :tag "Org Progress"
1520 :group 'org-time)
1522 (defvar org-todo-interpretation-widgets
1524 (:tag "Sequence (cycling hits every state)" sequence)
1525 (:tag "Type (cycling directly to DONE)" type))
1526 "The available interpretation symbols for customizing
1527 `org-todo-keywords'.
1528 Interested libraries should add to this list.")
1530 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1531 "List of TODO entry keyword sequences and their interpretation.
1532 \\<org-mode-map>This is a list of sequences.
1534 Each sequence starts with a symbol, either `sequence' or `type',
1535 indicating if the keywords should be interpreted as a sequence of
1536 action steps, or as different types of TODO items. The first
1537 keywords are states requiring action - these states will select a headline
1538 for inclusion into the global TODO list Org-mode produces. If one of
1539 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1540 signify that no further action is necessary. If \"|\" is not found,
1541 the last keyword is treated as the only DONE state of the sequence.
1543 The command \\[org-todo] cycles an entry through these states, and one
1544 additional state where no keyword is present. For details about this
1545 cycling, see the manual.
1547 TODO keywords and interpretation can also be set on a per-file basis with
1548 the special #+SEQ_TODO and #+TYP_TODO lines.
1550 Each keyword can optionally specify a character for fast state selection
1551 \(in combination with the variable `org-use-fast-todo-selection')
1552 and specifiers for state change logging, using the same syntax
1553 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1554 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1555 indicates to record a time stamp each time this state is selected.
1557 Each keyword may also specify if a timestamp or a note should be
1558 recorded when entering or leaving the state, by adding additional
1559 characters in the parenthesis after the keyword. This looks like this:
1560 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1561 record only the time of the state change. With X and Y being either
1562 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1563 Y when leaving the state if and only if the *target* state does not
1564 define X. You may omit any of the fast-selection key or X or /Y,
1565 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1567 For backward compatibility, this variable may also be just a list
1568 of keywords - in this case the interpretation (sequence or type) will be
1569 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1570 :group 'org-todo
1571 :group 'org-keywords
1572 :type '(choice
1573 (repeat :tag "Old syntax, just keywords"
1574 (string :tag "Keyword"))
1575 (repeat :tag "New syntax"
1576 (cons
1577 (choice
1578 :tag "Interpretation"
1579 ;;Quick and dirty way to see
1580 ;;`org-todo-interpretations'. This takes the
1581 ;;place of item arguments
1582 :convert-widget
1583 (lambda (widget)
1584 (widget-put widget
1585 :args (mapcar
1586 #'(lambda (x)
1587 (widget-convert
1588 (cons 'const x)))
1589 org-todo-interpretation-widgets))
1590 widget))
1591 (repeat
1592 (string :tag "Keyword"))))))
1594 (defvar org-todo-keywords-1 nil
1595 "All TODO and DONE keywords active in a buffer.")
1596 (make-variable-buffer-local 'org-todo-keywords-1)
1597 (defvar org-todo-keywords-for-agenda nil)
1598 (defvar org-done-keywords-for-agenda nil)
1599 (defvar org-todo-keyword-alist-for-agenda nil)
1600 (defvar org-tag-alist-for-agenda nil)
1601 (defvar org-agenda-contributing-files nil)
1602 (defvar org-not-done-keywords nil)
1603 (make-variable-buffer-local 'org-not-done-keywords)
1604 (defvar org-done-keywords nil)
1605 (make-variable-buffer-local 'org-done-keywords)
1606 (defvar org-todo-heads nil)
1607 (make-variable-buffer-local 'org-todo-heads)
1608 (defvar org-todo-sets nil)
1609 (make-variable-buffer-local 'org-todo-sets)
1610 (defvar org-todo-log-states nil)
1611 (make-variable-buffer-local 'org-todo-log-states)
1612 (defvar org-todo-kwd-alist nil)
1613 (make-variable-buffer-local 'org-todo-kwd-alist)
1614 (defvar org-todo-key-alist nil)
1615 (make-variable-buffer-local 'org-todo-key-alist)
1616 (defvar org-todo-key-trigger nil)
1617 (make-variable-buffer-local 'org-todo-key-trigger)
1619 (defcustom org-todo-interpretation 'sequence
1620 "Controls how TODO keywords are interpreted.
1621 This variable is in principle obsolete and is only used for
1622 backward compatibility, if the interpretation of todo keywords is
1623 not given already in `org-todo-keywords'. See that variable for
1624 more information."
1625 :group 'org-todo
1626 :group 'org-keywords
1627 :type '(choice (const sequence)
1628 (const type)))
1630 (defcustom org-use-fast-todo-selection t
1631 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1632 This variable describes if and under what circumstances the cycling
1633 mechanism for TODO keywords will be replaced by a single-key, direct
1634 selection scheme.
1636 When nil, fast selection is never used.
1638 When the symbol `prefix', it will be used when `org-todo' is called with
1639 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1640 in an agenda buffer.
1642 When t, fast selection is used by default. In this case, the prefix
1643 argument forces cycling instead.
1645 In all cases, the special interface is only used if access keys have actually
1646 been assigned by the user, i.e. if keywords in the configuration are followed
1647 by a letter in parenthesis, like TODO(t)."
1648 :group 'org-todo
1649 :type '(choice
1650 (const :tag "Never" nil)
1651 (const :tag "By default" t)
1652 (const :tag "Only with C-u C-c C-t" prefix)))
1654 (defcustom org-provide-todo-statistics t
1655 "Non-nil means, update todo statistics after insert and toggle.
1656 When this is set, todo statistics is updated in the parent of the current
1657 entry each time a todo state is changed."
1658 :group 'org-todo
1659 :type 'boolean)
1661 (defcustom org-after-todo-state-change-hook nil
1662 "Hook which is run after the state of a TODO item was changed.
1663 The new state (a string with a TODO keyword, or nil) is available in the
1664 Lisp variable `state'."
1665 :group 'org-todo
1666 :type 'hook)
1668 (defvar org-blocker-hook nil
1669 "Hook for functions that are allowed to block a state change.
1671 Each function gets as its single argument a property list, see
1672 `org-trigger-hook' for more information about this list.
1674 If any of the functions in this hook returns nil, the state change
1675 is blocked.")
1677 (defvar org-trigger-hook nil
1678 "Hook for functions that are triggered by a state change.
1680 Each function gets as its single argument a property list with at least
1681 the following elements:
1683 (:type type-of-change :position pos-at-entry-start
1684 :from old-state :to new-state)
1686 Depending on the type, more properties may be present.
1688 This mechanism is currently implemented for:
1690 TODO state changes
1691 ------------------
1692 :type todo-state-change
1693 :from previous state (keyword as a string), or nil, or a symbol
1694 'todo' or 'done', to indicate the general type of state.
1695 :to new state, like in :from")
1697 (defcustom org-enforce-todo-dependencies nil
1698 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1699 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1700 be blocked if any prior sibling is not yet done.
1701 This variable needs to be set before org.el is loaded, and you need to
1702 restart Emacs after a change to make the change effective. The only way
1703 to change is while Emacs is running is through the customize interface."
1704 :set (lambda (var val)
1705 (set var val)
1706 (if val
1707 (add-hook 'org-blocker-hook
1708 'org-block-todo-from-children-or-siblings)
1709 (remove-hook 'org-blocker-hook
1710 'org-block-todo-from-children-or-siblings)))
1711 :group 'org-todo
1712 :type 'boolean)
1714 (defcustom org-enforce-todo-checkbox-dependencies nil
1715 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1716 When this is nil, checkboxes have no influence on switching TODO states.
1717 When non-nil, you first need to check off all check boxes before the TODO
1718 entry can be switched to DONE.
1719 This variable needs to be set before org.el is loaded, and you need to
1720 restart Emacs after a change to make the change effective. The only way
1721 to change is while Emacs is running is through the customize interface."
1722 :set (lambda (var val)
1723 (set var val)
1724 (if val
1725 (add-hook 'org-blocker-hook
1726 'org-block-todo-from-checkboxes)
1727 (remove-hook 'org-blocker-hook
1728 'org-block-todo-from-checkboxes)))
1729 :group 'org-todo
1730 :type 'boolean)
1732 (defcustom org-todo-state-tags-triggers nil
1733 "Tag changes that should be triggered by TODO state changes.
1734 This is a list. Each entry is
1736 (state-change (tag . flag) .......)
1738 State-change can be a string with a state, and empty string to indicate the
1739 state that has no TODO keyword, or it can be one of the symbols `todo'
1740 or `done', meaning any not-done or done state, respectively."
1741 :group 'org-todo
1742 :group 'org-tags
1743 :type '(repeat
1744 (cons (choice :tag "When changing to"
1745 (const :tag "Not-done state" todo)
1746 (const :tag "Done state" done)
1747 (string :tag "State"))
1748 (repeat
1749 (cons :tag "Tag action"
1750 (string :tag "Tag")
1751 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1753 (defcustom org-log-done nil
1754 "Information to record when a task moves to the DONE state.
1756 Possible values are:
1758 nil Don't add anything, just change the keyword
1759 time Add a time stamp to the task
1760 note Prompt a closing note and add it with template `org-log-note-headings'
1762 This option can also be set with on a per-file-basis with
1764 #+STARTUP: nologdone
1765 #+STARTUP: logdone
1766 #+STARTUP: lognotedone
1768 You can have local logging settings for a subtree by setting the LOGGING
1769 property to one or more of these keywords."
1770 :group 'org-todo
1771 :group 'org-progress
1772 :type '(choice
1773 (const :tag "No logging" nil)
1774 (const :tag "Record CLOSED timestamp" time)
1775 (const :tag "Record CLOSED timestamp with closing note." note)))
1777 ;; Normalize old uses of org-log-done.
1778 (cond
1779 ((eq org-log-done t) (setq org-log-done 'time))
1780 ((and (listp org-log-done) (memq 'done org-log-done))
1781 (setq org-log-done 'note)))
1783 (defcustom org-log-note-clock-out nil
1784 "Non-nil means, record a note when clocking out of an item.
1785 This can also be configured on a per-file basis by adding one of
1786 the following lines anywhere in the buffer:
1788 #+STARTUP: lognoteclock-out
1789 #+STARTUP: nolognoteclock-out"
1790 :group 'org-todo
1791 :group 'org-progress
1792 :type 'boolean)
1794 (defcustom org-log-done-with-time t
1795 "Non-nil means, the CLOSED time stamp will contain date and time.
1796 When nil, only the date will be recorded."
1797 :group 'org-progress
1798 :type 'boolean)
1800 (defcustom org-log-note-headings
1801 '((done . "CLOSING NOTE %t")
1802 (state . "State %-12s from %-12S %t")
1803 (note . "Note taken on %t")
1804 (clock-out . ""))
1805 "Headings for notes added to entries.
1806 The value is an alist, with the car being a symbol indicating the note
1807 context, and the cdr is the heading to be used. The heading may also be the
1808 empty string.
1809 %t in the heading will be replaced by a time stamp.
1810 %s will be replaced by the new TODO state, in double quotes.
1811 %S will be replaced by the old TODO state, in double quotes.
1812 %u will be replaced by the user name.
1813 %U will be replaced by the full user name."
1814 :group 'org-todo
1815 :group 'org-progress
1816 :type '(list :greedy t
1817 (cons (const :tag "Heading when closing an item" done) string)
1818 (cons (const :tag
1819 "Heading when changing todo state (todo sequence only)"
1820 state) string)
1821 (cons (const :tag "Heading when just taking a note" note) string)
1822 (cons (const :tag "Heading when clocking out" clock-out) string)))
1824 (unless (assq 'note org-log-note-headings)
1825 (push '(note . "%t") org-log-note-headings))
1827 (defcustom org-log-into-drawer nil
1828 "Non-nil means, insert state change notes and time stamps into a drawer.
1829 When nil, state changes notes will be inserted after the headline and
1830 any scheduling and clock lines, but not inside a drawer.
1832 The value of this variable should be the name of the drawer to use.
1833 LOGBOOK is proposed at the default drawer for this purpose, you can
1834 also set this to a string to define the drawer of your choice.
1836 A value of t is also allowed, representing \"LOGBOOK\".
1838 If this variable is set, `org-log-state-notes-insert-after-drawers'
1839 will be ognored."
1840 :group 'org-todo
1841 :group 'org-progress
1842 :type '(choice
1843 (const :tag "Not into a drawer" nil)
1844 (const :tag "LOGBOOK" t)
1845 (string :tag "Other")))
1847 (if (fboundp 'defvaralias)
1848 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
1850 (defcustom org-log-state-notes-insert-after-drawers nil
1851 "Non-nil means, insert state change notes after any drawers in entry.
1852 Only the drawers that *immediately* follow the headline and the
1853 deadline/scheduled line are skipped.
1854 When nil, insert notes right after the heading and perhaps the line
1855 with deadline/scheduling if present.
1857 This variable will have no effect if `org-log-into-drawer' is
1858 set."
1859 :group 'org-todo
1860 :group 'org-progress
1861 :type 'boolean)
1863 (defcustom org-log-states-order-reversed t
1864 "Non-nil means, the latest state change note will be directly after heading.
1865 When nil, the notes will be orderer according to time."
1866 :group 'org-todo
1867 :group 'org-progress
1868 :type 'boolean)
1870 (defcustom org-log-repeat 'time
1871 "Non-nil means, record moving through the DONE state when triggering repeat.
1872 An auto-repeating tasks is immediately switched back to TODO when marked
1873 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1874 the TODO keyword definition, or recording a closing note by setting
1875 `org-log-done', there will be no record of the task moving through DONE.
1876 This variable forces taking a note anyway. Possible values are:
1878 nil Don't force a record
1879 time Record a time stamp
1880 note Record a note
1882 This option can also be set with on a per-file-basis with
1884 #+STARTUP: logrepeat
1885 #+STARTUP: lognoterepeat
1886 #+STARTUP: nologrepeat
1888 You can have local logging settings for a subtree by setting the LOGGING
1889 property to one or more of these keywords."
1890 :group 'org-todo
1891 :group 'org-progress
1892 :type '(choice
1893 (const :tag "Don't force a record" nil)
1894 (const :tag "Force recording the DONE state" time)
1895 (const :tag "Force recording a note with the DONE state" note)))
1898 (defgroup org-priorities nil
1899 "Priorities in Org-mode."
1900 :tag "Org Priorities"
1901 :group 'org-todo)
1903 (defcustom org-highest-priority ?A
1904 "The highest priority of TODO items. A character like ?A, ?B etc.
1905 Must have a smaller ASCII number than `org-lowest-priority'."
1906 :group 'org-priorities
1907 :type 'character)
1909 (defcustom org-lowest-priority ?C
1910 "The lowest priority of TODO items. A character like ?A, ?B etc.
1911 Must have a larger ASCII number than `org-highest-priority'."
1912 :group 'org-priorities
1913 :type 'character)
1915 (defcustom org-default-priority ?B
1916 "The default priority of TODO items.
1917 This is the priority an item get if no explicit priority is given."
1918 :group 'org-priorities
1919 :type 'character)
1921 (defcustom org-priority-start-cycle-with-default t
1922 "Non-nil means, start with default priority when starting to cycle.
1923 When this is nil, the first step in the cycle will be (depending on the
1924 command used) one higher or lower that the default priority."
1925 :group 'org-priorities
1926 :type 'boolean)
1928 (defgroup org-time nil
1929 "Options concerning time stamps and deadlines in Org-mode."
1930 :tag "Org Time"
1931 :group 'org)
1933 (defcustom org-insert-labeled-timestamps-at-point nil
1934 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1935 When nil, these labeled time stamps are forces into the second line of an
1936 entry, just after the headline. When scheduling from the global TODO list,
1937 the time stamp will always be forced into the second line."
1938 :group 'org-time
1939 :type 'boolean)
1941 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1942 "Formats for `format-time-string' which are used for time stamps.
1943 It is not recommended to change this constant.")
1945 (defcustom org-time-stamp-rounding-minutes '(0 5)
1946 "Number of minutes to round time stamps to.
1947 These are two values, the first applies when first creating a time stamp.
1948 The second applies when changing it with the commands `S-up' and `S-down'.
1949 When changing the time stamp, this means that it will change in steps
1950 of N minutes, as given by the second value.
1952 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1953 numbers should be factors of 60, so for example 5, 10, 15.
1955 When this is larger than 1, you can still force an exact time-stamp by using
1956 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1957 and by using a prefix arg to `S-up/down' to specify the exact number
1958 of minutes to shift."
1959 :group 'org-time
1960 :get '(lambda (var) ; Make sure all entries have 5 elements
1961 (if (integerp (default-value var))
1962 (list (default-value var) 5)
1963 (default-value var)))
1964 :type '(list
1965 (integer :tag "when inserting times")
1966 (integer :tag "when modifying times")))
1968 ;; Normalize old customizations of this variable.
1969 (when (integerp org-time-stamp-rounding-minutes)
1970 (setq org-time-stamp-rounding-minutes
1971 (list org-time-stamp-rounding-minutes
1972 org-time-stamp-rounding-minutes)))
1974 (defcustom org-display-custom-times nil
1975 "Non-nil means, overlay custom formats over all time stamps.
1976 The formats are defined through the variable `org-time-stamp-custom-formats'.
1977 To turn this on on a per-file basis, insert anywhere in the file:
1978 #+STARTUP: customtime"
1979 :group 'org-time
1980 :set 'set-default
1981 :type 'sexp)
1982 (make-variable-buffer-local 'org-display-custom-times)
1984 (defcustom org-time-stamp-custom-formats
1985 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1986 "Custom formats for time stamps. See `format-time-string' for the syntax.
1987 These are overlayed over the default ISO format if the variable
1988 `org-display-custom-times' is set. Time like %H:%M should be at the
1989 end of the second format."
1990 :group 'org-time
1991 :type 'sexp)
1993 (defun org-time-stamp-format (&optional long inactive)
1994 "Get the right format for a time string."
1995 (let ((f (if long (cdr org-time-stamp-formats)
1996 (car org-time-stamp-formats))))
1997 (if inactive
1998 (concat "[" (substring f 1 -1) "]")
1999 f)))
2001 (defcustom org-time-clocksum-format "%d:%02d"
2002 "The format string used when creating CLOCKSUM lines, or when
2003 org-mode generates a time duration."
2004 :group 'org-time
2005 :type 'string)
2007 (defcustom org-deadline-warning-days 14
2008 "No. of days before expiration during which a deadline becomes active.
2009 This variable governs the display in sparse trees and in the agenda.
2010 When 0 or negative, it means use this number (the absolute value of it)
2011 even if a deadline has a different individual lead time specified."
2012 :group 'org-time
2013 :group 'org-agenda-daily/weekly
2014 :type 'number)
2016 (defcustom org-read-date-prefer-future t
2017 "Non-nil means, assume future for incomplete date input from user.
2018 This affects the following situations:
2019 1. The user gives a day, but no month.
2020 For example, if today is the 15th, and you enter \"3\", Org-mode will
2021 read this as the third of *next* month. However, if you enter \"17\",
2022 it will be considered as *this* month.
2023 2. The user gives a month but not a year.
2024 For example, if it is april and you enter \"feb 2\", this will be read
2025 as feb 2, *next* year. \"May 5\", however, will be this year.
2027 Currently this does not work for ISO week specifications.
2029 When this option is nil, the current month and year will always be used
2030 as defaults."
2031 :group 'org-time
2032 :type 'boolean)
2034 (defcustom org-read-date-display-live t
2035 "Non-nil means, display current interpretation of date prompt live.
2036 This display will be in an overlay, in the minibuffer."
2037 :group 'org-time
2038 :type 'boolean)
2040 (defcustom org-read-date-popup-calendar t
2041 "Non-nil means, pop up a calendar when prompting for a date.
2042 In the calendar, the date can be selected with mouse-1. However, the
2043 minibuffer will also be active, and you can simply enter the date as well.
2044 When nil, only the minibuffer will be available."
2045 :group 'org-time
2046 :type 'boolean)
2047 (if (fboundp 'defvaralias)
2048 (defvaralias 'org-popup-calendar-for-date-prompt
2049 'org-read-date-popup-calendar))
2051 (defcustom org-extend-today-until 0
2052 "The hour when your day really ends. Must be an integer.
2053 This has influence for the following applications:
2054 - When switching the agenda to \"today\". It it is still earlier than
2055 the time given here, the day recognized as TODAY is actually yesterday.
2056 - When a date is read from the user and it is still before the time given
2057 here, the current date and time will be assumed to be yesterday, 23:59.
2058 Also, timestamps inserted in remember templates follow this rule.
2060 IMPORTANT: This is a feature whose implementation is and likely will
2061 remain incomplete. Really, it is only here because past midnight seems to
2062 be the favorite working time of John Wiegley :-)"
2063 :group 'org-time
2064 :type 'number)
2066 (defcustom org-edit-timestamp-down-means-later nil
2067 "Non-nil means, S-down will increase the time in a time stamp.
2068 When nil, S-up will increase."
2069 :group 'org-time
2070 :type 'boolean)
2072 (defcustom org-calendar-follow-timestamp-change t
2073 "Non-nil means, make the calendar window follow timestamp changes.
2074 When a timestamp is modified and the calendar window is visible, it will be
2075 moved to the new date."
2076 :group 'org-time
2077 :type 'boolean)
2079 (defgroup org-tags nil
2080 "Options concerning tags in Org-mode."
2081 :tag "Org Tags"
2082 :group 'org)
2084 (defcustom org-tag-alist nil
2085 "List of tags allowed in Org-mode files.
2086 When this list is nil, Org-mode will base TAG input on what is already in the
2087 buffer.
2088 The value of this variable is an alist, the car of each entry must be a
2089 keyword as a string, the cdr may be a character that is used to select
2090 that tag through the fast-tag-selection interface.
2091 See the manual for details."
2092 :group 'org-tags
2093 :type '(repeat
2094 (choice
2095 (cons (string :tag "Tag name")
2096 (character :tag "Access char"))
2097 (const :tag "Start radio group" (:startgroup))
2098 (const :tag "End radio group" (:endgroup))
2099 (const :tag "New line" (:newline)))))
2101 (defcustom org-tag-persistent-alist nil
2102 "List of tags that will always appear in all Org-mode files.
2103 This is in addition to any in buffer settings or customizations
2104 of `org-tag-alist'.
2105 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2106 The value of this variable is an alist, the car of each entry must be a
2107 keyword as a string, the cdr may be a character that is used to select
2108 that tag through the fast-tag-selection interface.
2109 See the manual for details.
2110 To disable these tags on a per-file basis, insert anywhere in the file:
2111 #+STARTUP: noptag"
2112 :group 'org-tags
2113 :type '(repeat
2114 (choice
2115 (cons (string :tag "Tag name")
2116 (character :tag "Access char"))
2117 (const :tag "Start radio group" (:startgroup))
2118 (const :tag "End radio group" (:endgroup))
2119 (const :tag "New line" (:newline)))))
2121 (defvar org-file-tags nil
2122 "List of tags that can be inherited by all entries in the file.
2123 The tags will be inherited if the variable `org-use-tag-inheritance'
2124 says they should be.
2125 This variable is populated from #+TAG lines.")
2127 (defcustom org-use-fast-tag-selection 'auto
2128 "Non-nil means, use fast tag selection scheme.
2129 This is a special interface to select and deselect tags with single keys.
2130 When nil, fast selection is never used.
2131 When the symbol `auto', fast selection is used if and only if selection
2132 characters for tags have been configured, either through the variable
2133 `org-tag-alist' or through a #+TAGS line in the buffer.
2134 When t, fast selection is always used and selection keys are assigned
2135 automatically if necessary."
2136 :group 'org-tags
2137 :type '(choice
2138 (const :tag "Always" t)
2139 (const :tag "Never" nil)
2140 (const :tag "When selection characters are configured" 'auto)))
2142 (defcustom org-fast-tag-selection-single-key nil
2143 "Non-nil means, fast tag selection exits after first change.
2144 When nil, you have to press RET to exit it.
2145 During fast tag selection, you can toggle this flag with `C-c'.
2146 This variable can also have the value `expert'. In this case, the window
2147 displaying the tags menu is not even shown, until you press C-c again."
2148 :group 'org-tags
2149 :type '(choice
2150 (const :tag "No" nil)
2151 (const :tag "Yes" t)
2152 (const :tag "Expert" expert)))
2154 (defvar org-fast-tag-selection-include-todo nil
2155 "Non-nil means, fast tags selection interface will also offer TODO states.
2156 This is an undocumented feature, you should not rely on it.")
2158 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2159 "The column to which tags should be indented in a headline.
2160 If this number is positive, it specifies the column. If it is negative,
2161 it means that the tags should be flushright to that column. For example,
2162 -80 works well for a normal 80 character screen."
2163 :group 'org-tags
2164 :type 'integer)
2166 (defcustom org-auto-align-tags t
2167 "Non-nil means, realign tags after pro/demotion of TODO state change.
2168 These operations change the length of a headline and therefore shift
2169 the tags around. With this options turned on, after each such operation
2170 the tags are again aligned to `org-tags-column'."
2171 :group 'org-tags
2172 :type 'boolean)
2174 (defcustom org-use-tag-inheritance t
2175 "Non-nil means, tags in levels apply also for sublevels.
2176 When nil, only the tags directly given in a specific line apply there.
2177 This may also be a list of tags that should be inherited, or a regexp that
2178 matches tags that should be inherited. Additional control is possible
2179 with the variable `org-tags-exclude-from-inheritance' which gives an
2180 explicit list of tags to be excluded from inheritance., even if the value of
2181 `org-use-tag-inheritance' would select it for inheritance.
2183 If this option is t, a match early-on in a tree can lead to a large
2184 number of matches in the subtree when constructing the agenda or creating
2185 a sparse tree. If you only want to see the first match in a tree during
2186 a search, check out the variable `org-tags-match-list-sublevels'."
2187 :group 'org-tags
2188 :type '(choice
2189 (const :tag "Not" nil)
2190 (const :tag "Always" t)
2191 (repeat :tag "Specific tags" (string :tag "Tag"))
2192 (regexp :tag "Tags matched by regexp")))
2194 (defcustom org-tags-exclude-from-inheritance nil
2195 "List of tags that should never be inherited.
2196 This is a way to exclude a few tags from inheritance. For way to do
2197 the opposite, to actively allow inheritance for selected tags,
2198 see the variable `org-use-tag-inheritance'."
2199 :group 'org-tags
2200 :type '(repeat (string :tag "Tag")))
2202 (defun org-tag-inherit-p (tag)
2203 "Check if TAG is one that should be inherited."
2204 (cond
2205 ((member tag org-tags-exclude-from-inheritance) nil)
2206 ((eq org-use-tag-inheritance t) t)
2207 ((not org-use-tag-inheritance) nil)
2208 ((stringp org-use-tag-inheritance)
2209 (string-match org-use-tag-inheritance tag))
2210 ((listp org-use-tag-inheritance)
2211 (member tag org-use-tag-inheritance))
2212 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2214 (defcustom org-tags-match-list-sublevels t
2215 "Non-nil means list also sublevels of headlines matching tag search.
2216 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2217 the sublevels of a headline matching a tag search often also match
2218 the same search. Listing all of them can create very long lists.
2219 Setting this variable to nil causes subtrees of a match to be skipped.
2220 This option is off by default, because inheritance in on. If you turn
2221 inheritance off, you very likely want to turn this option on.
2223 As a special case, if the tag search is restricted to TODO items, the
2224 value of this variable is ignored and sublevels are always checked, to
2225 make sure all corresponding TODO items find their way into the list.
2227 This variable is semi-obsolete and probably should always be true. It
2228 is better to limit inheritance to certain tags using the variables
2229 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2230 :group 'org-tags
2231 :type 'boolean)
2233 (defvar org-tags-history nil
2234 "History of minibuffer reads for tags.")
2235 (defvar org-last-tags-completion-table nil
2236 "The last used completion table for tags.")
2237 (defvar org-after-tags-change-hook nil
2238 "Hook that is run after the tags in a line have changed.")
2240 (defgroup org-properties nil
2241 "Options concerning properties in Org-mode."
2242 :tag "Org Properties"
2243 :group 'org)
2245 (defcustom org-property-format "%-10s %s"
2246 "How property key/value pairs should be formatted by `indent-line'.
2247 When `indent-line' hits a property definition, it will format the line
2248 according to this format, mainly to make sure that the values are
2249 lined-up with respect to each other."
2250 :group 'org-properties
2251 :type 'string)
2253 (defcustom org-use-property-inheritance nil
2254 "Non-nil means, properties apply also for sublevels.
2256 This setting is chiefly used during property searches. Turning it on can
2257 cause significant overhead when doing a search, which is why it is not
2258 on by default.
2260 When nil, only the properties directly given in the current entry count.
2261 When t, every property is inherited. The value may also be a list of
2262 properties that should have inheritance, or a regular expression matching
2263 properties that should be inherited.
2265 However, note that some special properties use inheritance under special
2266 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2267 and the properties ending in \"_ALL\" when they are used as descriptor
2268 for valid values of a property.
2270 Note for programmers:
2271 When querying an entry with `org-entry-get', you can control if inheritance
2272 should be used. By default, `org-entry-get' looks only at the local
2273 properties. You can request inheritance by setting the inherit argument
2274 to t (to force inheritance) or to `selective' (to respect the setting
2275 in this variable)."
2276 :group 'org-properties
2277 :type '(choice
2278 (const :tag "Not" nil)
2279 (const :tag "Always" t)
2280 (repeat :tag "Specific properties" (string :tag "Property"))
2281 (regexp :tag "Properties matched by regexp")))
2283 (defun org-property-inherit-p (property)
2284 "Check if PROPERTY is one that should be inherited."
2285 (cond
2286 ((eq org-use-property-inheritance t) t)
2287 ((not org-use-property-inheritance) nil)
2288 ((stringp org-use-property-inheritance)
2289 (string-match org-use-property-inheritance property))
2290 ((listp org-use-property-inheritance)
2291 (member property org-use-property-inheritance))
2292 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2294 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2295 "The default column format, if no other format has been defined.
2296 This variable can be set on the per-file basis by inserting a line
2298 #+COLUMNS: %25ITEM ....."
2299 :group 'org-properties
2300 :type 'string)
2302 (defcustom org-columns-ellipses ".."
2303 "The ellipses to be used when a field in column view is truncated.
2304 When this is the empty string, as many characters as possible are shown,
2305 but then there will be no visual indication that the field has been truncated.
2306 When this is a string of length N, the last N characters of a truncated
2307 field are replaced by this string. If the column is narrower than the
2308 ellipses string, only part of the ellipses string will be shown."
2309 :group 'org-properties
2310 :type 'string)
2312 (defcustom org-columns-modify-value-for-display-function nil
2313 "Function that modifies values for display in column view.
2314 For example, it can be used to cut out a certain part from a time stamp.
2315 The function must take 2 arguments:
2317 column-title The title of the column (*not* the property name)
2318 value The value that should be modified.
2320 The function should return the value that should be displayed,
2321 or nil if the normal value should be used."
2322 :group 'org-properties
2323 :type 'function)
2325 (defcustom org-effort-property "Effort"
2326 "The property that is being used to keep track of effort estimates.
2327 Effort estimates given in this property need to have the format H:MM."
2328 :group 'org-properties
2329 :group 'org-progress
2330 :type '(string :tag "Property"))
2332 (defconst org-global-properties-fixed
2333 '(("VISIBILITY_ALL" . "folded children content all"))
2334 "List of property/value pairs that can be inherited by any entry.
2336 These are fixed values, for the preset properties. The user variable
2337 that can be used to add to this list is `org-global-properties'.
2339 The entries in this list are cons cells where the car is a property
2340 name and cdr is a string with the value. If the value represents
2341 multiple items like an \"_ALL\" property, separate the items by
2342 spaces.")
2344 (defcustom org-global-properties nil
2345 "List of property/value pairs that can be inherited by any entry.
2347 This list will be combined with the constant `org-global-properties-fixed'.
2349 The entries in this list are cons cells where the car is a property
2350 name and cdr is a string with the value.
2352 You can set buffer-local values for the same purpose in the variable
2353 `org-file-properties' this by adding lines like
2355 #+PROPERTY: NAME VALUE"
2356 :group 'org-properties
2357 :type '(repeat
2358 (cons (string :tag "Property")
2359 (string :tag "Value"))))
2361 (defvar org-file-properties nil
2362 "List of property/value pairs that can be inherited by any entry.
2363 Valid for the current buffer.
2364 This variable is populated from #+PROPERTY lines.")
2365 (make-variable-buffer-local 'org-file-properties)
2367 (defgroup org-agenda nil
2368 "Options concerning agenda views in Org-mode."
2369 :tag "Org Agenda"
2370 :group 'org)
2372 (defvar org-category nil
2373 "Variable used by org files to set a category for agenda display.
2374 Such files should use a file variable to set it, for example
2376 # -*- mode: org; org-category: \"ELisp\"
2378 or contain a special line
2380 #+CATEGORY: ELisp
2382 If the file does not specify a category, then file's base name
2383 is used instead.")
2384 (make-variable-buffer-local 'org-category)
2385 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2387 (defcustom org-agenda-files nil
2388 "The files to be used for agenda display.
2389 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2390 \\[org-remove-file]. You can also use customize to edit the list.
2392 If an entry is a directory, all files in that directory that are matched by
2393 `org-agenda-file-regexp' will be part of the file list.
2395 If the value of the variable is not a list but a single file name, then
2396 the list of agenda files is actually stored and maintained in that file, one
2397 agenda file per line."
2398 :group 'org-agenda
2399 :type '(choice
2400 (repeat :tag "List of files and directories" file)
2401 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2403 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2404 "Regular expression to match files for `org-agenda-files'.
2405 If any element in the list in that variable contains a directory instead
2406 of a normal file, all files in that directory that are matched by this
2407 regular expression will be included."
2408 :group 'org-agenda
2409 :type 'regexp)
2411 (defcustom org-agenda-text-search-extra-files nil
2412 "List of extra files to be searched by text search commands.
2413 These files will be search in addition to the agenda files by the
2414 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2415 Note that these files will only be searched for text search commands,
2416 not for the other agenda views like todo lists, tag searches or the weekly
2417 agenda. This variable is intended to list notes and possibly archive files
2418 that should also be searched by these two commands.
2419 In fact, if the first element in the list is the symbol `agenda-archives',
2420 than all archive files of all agenda files will be added to the search
2421 scope."
2422 :group 'org-agenda
2423 :type '(set :greedy t
2424 (const :tag "Agenda Archives" agenda-archives)
2425 (repeat :inline t (file))))
2427 (if (fboundp 'defvaralias)
2428 (defvaralias 'org-agenda-multi-occur-extra-files
2429 'org-agenda-text-search-extra-files))
2431 (defcustom org-agenda-skip-unavailable-files nil
2432 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2433 A nil value means to remove them, after a query, from the list."
2434 :group 'org-agenda
2435 :type 'boolean)
2437 (defcustom org-calendar-to-agenda-key [?c]
2438 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2439 The command `org-calendar-goto-agenda' will be bound to this key. The
2440 default is the character `c' because then `c' can be used to switch back and
2441 forth between agenda and calendar."
2442 :group 'org-agenda
2443 :type 'sexp)
2445 (defcustom org-calendar-agenda-action-key [?k]
2446 "The key to be installed in `calendar-mode-map' for agenda-action.
2447 The command `org-agenda-action' will be bound to this key. The
2448 default is the character `k' because we use the same key in the agenda."
2449 :group 'org-agenda
2450 :type 'sexp)
2452 (eval-after-load "calendar"
2453 '(progn
2454 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2455 'org-calendar-goto-agenda)
2456 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2457 'org-agenda-action)))
2459 (defgroup org-latex nil
2460 "Options for embedding LaTeX code into Org-mode."
2461 :tag "Org LaTeX"
2462 :group 'org)
2464 (defcustom org-format-latex-options
2465 '(:foreground default :background default :scale 1.0
2466 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2467 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2468 "Options for creating images from LaTeX fragments.
2469 This is a property list with the following properties:
2470 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2471 `default' means use the foreground of the default face.
2472 :background the background color, or \"Transparent\".
2473 `default' means use the background of the default face.
2474 :scale a scaling factor for the size of the images.
2475 :html-foreground, :html-background, :html-scale
2476 the same numbers for HTML export.
2477 :matchers a list indicating which matchers should be used to
2478 find LaTeX fragments. Valid members of this list are:
2479 \"begin\" find environments
2480 \"$1\" find single characters surrounded by $.$
2481 \"$\" find math expressions surrounded by $...$
2482 \"$$\" find math expressions surrounded by $$....$$
2483 \"\\(\" find math expressions surrounded by \\(...\\)
2484 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2485 :group 'org-latex
2486 :type 'plist)
2488 (defcustom org-format-latex-header "\\documentclass{article}
2489 \\usepackage{fullpage} % do not remove
2490 \\usepackage{amssymb}
2491 \\usepackage[usenames]{color}
2492 \\usepackage{amsmath}
2493 \\usepackage{latexsym}
2494 \\usepackage[mathscr]{eucal}
2495 \\pagestyle{empty} % do not remove"
2496 "The document header used for processing LaTeX fragments."
2497 :group 'org-latex
2498 :type 'string)
2501 (defgroup org-font-lock nil
2502 "Font-lock settings for highlighting in Org-mode."
2503 :tag "Org Font Lock"
2504 :group 'org)
2506 (defcustom org-level-color-stars-only nil
2507 "Non-nil means fontify only the stars in each headline.
2508 When nil, the entire headline is fontified.
2509 Changing it requires restart of `font-lock-mode' to become effective
2510 also in regions already fontified."
2511 :group 'org-font-lock
2512 :type 'boolean)
2514 (defcustom org-hide-leading-stars nil
2515 "Non-nil means, hide the first N-1 stars in a headline.
2516 This works by using the face `org-hide' for these stars. This
2517 face is white for a light background, and black for a dark
2518 background. You may have to customize the face `org-hide' to
2519 make this work.
2520 Changing it requires restart of `font-lock-mode' to become effective
2521 also in regions already fontified.
2522 You may also set this on a per-file basis by adding one of the following
2523 lines to the buffer:
2525 #+STARTUP: hidestars
2526 #+STARTUP: showstars"
2527 :group 'org-font-lock
2528 :type 'boolean)
2530 (defcustom org-fontify-done-headline nil
2531 "Non-nil means, change the face of a headline if it is marked DONE.
2532 Normally, only the TODO/DONE keyword indicates the state of a headline.
2533 When this is non-nil, the headline after the keyword is set to the
2534 `org-headline-done' as an additional indication."
2535 :group 'org-font-lock
2536 :type 'boolean)
2538 (defcustom org-fontify-emphasized-text t
2539 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2540 Changing this variable requires a restart of Emacs to take effect."
2541 :group 'org-font-lock
2542 :type 'boolean)
2544 (defcustom org-highlight-latex-fragments-and-specials nil
2545 "Non-nil means, fontify what is treated specially by the exporters."
2546 :group 'org-font-lock
2547 :type 'boolean)
2549 (defcustom org-hide-emphasis-markers nil
2550 "Non-nil mean font-lock should hide the emphasis marker characters."
2551 :group 'org-font-lock
2552 :type 'boolean)
2554 (defvar org-emph-re nil
2555 "Regular expression for matching emphasis.")
2556 (defvar org-verbatim-re nil
2557 "Regular expression for matching verbatim text.")
2558 (defvar org-emphasis-regexp-components) ; defined just below
2559 (defvar org-emphasis-alist) ; defined just below
2560 (defun org-set-emph-re (var val)
2561 "Set variable and compute the emphasis regular expression."
2562 (set var val)
2563 (when (and (boundp 'org-emphasis-alist)
2564 (boundp 'org-emphasis-regexp-components)
2565 org-emphasis-alist org-emphasis-regexp-components)
2566 (let* ((e org-emphasis-regexp-components)
2567 (pre (car e))
2568 (post (nth 1 e))
2569 (border (nth 2 e))
2570 (body (nth 3 e))
2571 (nl (nth 4 e))
2572 (body1 (concat body "*?"))
2573 (markers (mapconcat 'car org-emphasis-alist ""))
2574 (vmarkers (mapconcat
2575 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2576 org-emphasis-alist "")))
2577 ;; make sure special characters appear at the right position in the class
2578 (if (string-match "\\^" markers)
2579 (setq markers (concat (replace-match "" t t markers) "^")))
2580 (if (string-match "-" markers)
2581 (setq markers (concat (replace-match "" t t markers) "-")))
2582 (if (string-match "\\^" vmarkers)
2583 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2584 (if (string-match "-" vmarkers)
2585 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2586 (if (> nl 0)
2587 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2588 (int-to-string nl) "\\}")))
2589 ;; Make the regexp
2590 (setq org-emph-re
2591 (concat "\\([" pre "]\\|^\\)"
2592 "\\("
2593 "\\([" markers "]\\)"
2594 "\\("
2595 "[^" border "]\\|"
2596 "[^" border "]"
2597 body1
2598 "[^" border "]"
2599 "\\)"
2600 "\\3\\)"
2601 "\\([" post "]\\|$\\)"))
2602 (setq org-verbatim-re
2603 (concat "\\([" pre "]\\|^\\)"
2604 "\\("
2605 "\\([" vmarkers "]\\)"
2606 "\\("
2607 "[^" border "]\\|"
2608 "[^" border "]"
2609 body1
2610 "[^" border "]"
2611 "\\)"
2612 "\\3\\)"
2613 "\\([" post "]\\|$\\)")))))
2615 (defcustom org-emphasis-regexp-components
2616 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2617 "Components used to build the regular expression for emphasis.
2618 This is a list with 6 entries. Terminology: In an emphasis string
2619 like \" *strong word* \", we call the initial space PREMATCH, the final
2620 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2621 and \"trong wor\" is the body. The different components in this variable
2622 specify what is allowed/forbidden in each part:
2624 pre Chars allowed as prematch. Beginning of line will be allowed too.
2625 post Chars allowed as postmatch. End of line will be allowed too.
2626 border The chars *forbidden* as border characters.
2627 body-regexp A regexp like \".\" to match a body character. Don't use
2628 non-shy groups here, and don't allow newline here.
2629 newline The maximum number of newlines allowed in an emphasis exp.
2631 Use customize to modify this, or restart Emacs after changing it."
2632 :group 'org-font-lock
2633 :set 'org-set-emph-re
2634 :type '(list
2635 (sexp :tag "Allowed chars in pre ")
2636 (sexp :tag "Allowed chars in post ")
2637 (sexp :tag "Forbidden chars in border ")
2638 (sexp :tag "Regexp for body ")
2639 (integer :tag "number of newlines allowed")
2640 (option (boolean :tag "Please ignore this button"))))
2642 (defcustom org-emphasis-alist
2643 `(("*" bold "<b>" "</b>")
2644 ("/" italic "<i>" "</i>")
2645 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2646 ("=" org-code "<code>" "</code>" verbatim)
2647 ("~" org-verbatim "<code>" "</code>" verbatim)
2648 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2649 "<del>" "</del>")
2651 "Special syntax for emphasized text.
2652 Text starting and ending with a special character will be emphasized, for
2653 example *bold*, _underlined_ and /italic/. This variable sets the marker
2654 characters, the face to be used by font-lock for highlighting in Org-mode
2655 Emacs buffers, and the HTML tags to be used for this.
2656 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
2657 Use customize to modify this, or restart Emacs after changing it."
2658 :group 'org-font-lock
2659 :set 'org-set-emph-re
2660 :type '(repeat
2661 (list
2662 (string :tag "Marker character")
2663 (choice
2664 (face :tag "Font-lock-face")
2665 (plist :tag "Face property list"))
2666 (string :tag "HTML start tag")
2667 (string :tag "HTML end tag")
2668 (option (const verbatim)))))
2670 ;;; Miscellaneous options
2672 (defgroup org-completion nil
2673 "Completion in Org-mode."
2674 :tag "Org Completion"
2675 :group 'org)
2677 (defcustom org-completion-use-ido nil
2678 "Non-nil means, use ido completion wherever possible.
2679 Note that `ido-mode' must be active for this variable to be relevant.
2680 If you decide to turn this variable on, you might well want to turn off
2681 `org-outline-path-complete-in-steps'."
2682 :group 'org-completion
2683 :type 'boolean)
2685 (defcustom org-completion-fallback-command 'hippie-expand
2686 "The expansion command called by \\[org-complete] in normal context.
2687 Normal means, no org-mode-specific context."
2688 :group 'org-completion
2689 :type 'function)
2691 ;;; Functions and variables from ther packages
2692 ;; Declared here to avoid compiler warnings
2694 ;; XEmacs only
2695 (defvar outline-mode-menu-heading)
2696 (defvar outline-mode-menu-show)
2697 (defvar outline-mode-menu-hide)
2698 (defvar zmacs-regions) ; XEmacs regions
2700 ;; Emacs only
2701 (defvar mark-active)
2703 ;; Various packages
2704 (declare-function find-library-name "find-func" (library))
2705 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2706 (declare-function calendar-forward-day "cal-move" (arg))
2707 (declare-function calendar-goto-date "cal-move" (date))
2708 (declare-function calendar-goto-today "cal-move" ())
2709 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2710 (defvar calc-embedded-close-formula)
2711 (defvar calc-embedded-open-formula)
2712 (declare-function cdlatex-tab "ext:cdlatex" ())
2713 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2714 (defvar font-lock-unfontify-region-function)
2715 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2716 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2717 (defvar iswitchb-temp-buflist)
2718 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2719 (defvar org-agenda-tags-todo-honor-ignore-options)
2720 (declare-function org-agenda-skip "org-agenda" ())
2721 (declare-function org-format-agenda-item "org-agenda"
2722 (extra txt &optional category tags dotime noprefix remove-re))
2723 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2724 (declare-function org-agenda-change-all-lines "org-agenda"
2725 (newhead hdmarker &optional fixface just-this))
2726 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2727 (declare-function org-agenda-maybe-redo "org-agenda" ())
2728 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2729 (beg end))
2730 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2731 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2732 "org-agenda" (&optional end))
2734 (declare-function parse-time-string "parse-time" (string))
2735 (declare-function remember "remember" (&optional initial))
2736 (declare-function remember-buffer-desc "remember" ())
2737 (declare-function remember-finalize "remember" ())
2738 (defvar remember-save-after-remembering)
2739 (defvar remember-data-file)
2740 (defvar remember-register)
2741 (defvar remember-buffer)
2742 (defvar remember-handler-functions)
2743 (defvar remember-annotation-functions)
2744 (defvar texmathp-why)
2745 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2746 (declare-function table--at-cell-p "table" (position &optional object at-column))
2748 (defvar w3m-current-url)
2749 (defvar w3m-current-title)
2751 (defvar org-latex-regexps)
2753 ;;; Autoload and prepare some org modules
2755 ;; Some table stuff that needs to be defined here, because it is used
2756 ;; by the functions setting up org-mode or checking for table context.
2758 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2759 "Detects an org-type or table-type table.")
2760 (defconst org-table-line-regexp "^[ \t]*|"
2761 "Detects an org-type table line.")
2762 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2763 "Detects an org-type table line.")
2764 (defconst org-table-hline-regexp "^[ \t]*|-"
2765 "Detects an org-type table hline.")
2766 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2767 "Detects a table-type table hline.")
2768 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2769 "Searching from within a table (any type) this finds the first line
2770 outside the table.")
2772 ;; Autoload the functions in org-table.el that are needed by functions here.
2774 (eval-and-compile
2775 (org-autoload "org-table"
2776 '(org-table-align org-table-begin org-table-blank-field
2777 org-table-convert org-table-convert-region org-table-copy-down
2778 org-table-copy-region org-table-create
2779 org-table-create-or-convert-from-region
2780 org-table-create-with-table.el org-table-current-dline
2781 org-table-cut-region org-table-delete-column org-table-edit-field
2782 org-table-edit-formulas org-table-end org-table-eval-formula
2783 org-table-export org-table-field-info
2784 org-table-get-stored-formulas org-table-goto-column
2785 org-table-hline-and-move org-table-import org-table-insert-column
2786 org-table-insert-hline org-table-insert-row org-table-iterate
2787 org-table-justify-field-maybe org-table-kill-row
2788 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2789 org-table-move-column org-table-move-column-left
2790 org-table-move-column-right org-table-move-row
2791 org-table-move-row-down org-table-move-row-up
2792 org-table-next-field org-table-next-row org-table-paste-rectangle
2793 org-table-previous-field org-table-recalculate
2794 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2795 org-table-toggle-coordinate-overlays
2796 org-table-toggle-formula-debugger org-table-wrap-region
2797 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2799 (defun org-at-table-p (&optional table-type)
2800 "Return t if the cursor is inside an org-type table.
2801 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2802 (if org-enable-table-editor
2803 (save-excursion
2804 (beginning-of-line 1)
2805 (looking-at (if table-type org-table-any-line-regexp
2806 org-table-line-regexp)))
2807 nil))
2808 (defsubst org-table-p () (org-at-table-p))
2810 (defun org-at-table.el-p ()
2811 "Return t if and only if we are at a table.el table."
2812 (and (org-at-table-p 'any)
2813 (save-excursion
2814 (goto-char (org-table-begin 'any))
2815 (looking-at org-table1-hline-regexp))))
2816 (defun org-table-recognize-table.el ()
2817 "If there is a table.el table nearby, recognize it and move into it."
2818 (if org-table-tab-recognizes-table.el
2819 (if (org-at-table.el-p)
2820 (progn
2821 (beginning-of-line 1)
2822 (if (looking-at org-table-dataline-regexp)
2824 (if (looking-at org-table1-hline-regexp)
2825 (progn
2826 (beginning-of-line 2)
2827 (if (looking-at org-table-any-border-regexp)
2828 (beginning-of-line -1)))))
2829 (if (re-search-forward "|" (org-table-end t) t)
2830 (progn
2831 (require 'table)
2832 (if (table--at-cell-p (point))
2834 (message "recognizing table.el table...")
2835 (table-recognize-table)
2836 (message "recognizing table.el table...done")))
2837 (error "This should not happen..."))
2839 nil)
2840 nil))
2842 (defun org-at-table-hline-p ()
2843 "Return t if the cursor is inside a hline in a table."
2844 (if org-enable-table-editor
2845 (save-excursion
2846 (beginning-of-line 1)
2847 (looking-at org-table-hline-regexp))
2848 nil))
2850 (defvar org-table-clean-did-remove-column nil)
2852 (defun org-table-map-tables (function)
2853 "Apply FUNCTION to the start of all tables in the buffer."
2854 (save-excursion
2855 (save-restriction
2856 (widen)
2857 (goto-char (point-min))
2858 (while (re-search-forward org-table-any-line-regexp nil t)
2859 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2860 (beginning-of-line 1)
2861 (if (looking-at org-table-line-regexp)
2862 (save-excursion (funcall function)))
2863 (re-search-forward org-table-any-border-regexp nil 1))))
2864 (message "Mapping tables: done"))
2866 ;; Declare and autoload functions from org-exp.el
2868 (declare-function org-default-export-plist "org-exp")
2869 (declare-function org-infile-export-plist "org-exp")
2870 (declare-function org-get-current-options "org-exp")
2871 (eval-and-compile
2872 (org-autoload "org-exp"
2873 '(org-export org-export-as-ascii org-export-visible
2874 org-insert-export-options-template org-export-as-html-and-open
2875 org-export-as-html-batch org-export-as-html-to-buffer
2876 org-replace-region-by-html org-export-region-as-html
2877 org-export-as-html org-export-icalendar-this-file
2878 org-export-icalendar-all-agenda-files
2879 org-table-clean-before-export
2880 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2882 ;; Declare and autoload functions from org-agenda.el
2884 (eval-and-compile
2885 (org-autoload "org-agenda"
2886 '(org-agenda org-agenda-list org-search-view
2887 org-todo-list org-tags-view org-agenda-list-stuck-projects
2888 org-diary org-agenda-to-appt
2889 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
2891 ;; Autoload org-remember
2893 (eval-and-compile
2894 (org-autoload "org-remember"
2895 '(org-remember-insinuate org-remember-annotation
2896 org-remember-apply-template org-remember org-remember-handler)))
2898 ;; Autoload org-clock.el
2901 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2902 (beg end))
2903 (declare-function org-clock-update-mode-line "org-clock" ())
2904 (defvar org-clock-start-time)
2905 (defvar org-clock-marker (make-marker)
2906 "Marker recording the last clock-in.")
2908 (eval-and-compile
2909 (org-autoload
2910 "org-clock"
2911 '(org-clock-in org-clock-out org-clock-cancel
2912 org-clock-goto org-clock-sum org-clock-display
2913 org-clock-remove-overlays org-clock-report
2914 org-clocktable-shift org-dblock-write:clocktable
2915 org-get-clocktable)))
2917 (defun org-clock-update-time-maybe ()
2918 "If this is a CLOCK line, update it and return t.
2919 Otherwise, return nil."
2920 (interactive)
2921 (save-excursion
2922 (beginning-of-line 1)
2923 (skip-chars-forward " \t")
2924 (when (looking-at org-clock-string)
2925 (let ((re (concat "[ \t]*" org-clock-string
2926 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2927 "\\([ \t]*=>.*\\)?\\)?"))
2928 ts te h m s neg)
2929 (cond
2930 ((not (looking-at re))
2931 nil)
2932 ((not (match-end 2))
2933 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2934 (> org-clock-marker (point))
2935 (<= org-clock-marker (point-at-eol)))
2936 ;; The clock is running here
2937 (setq org-clock-start-time
2938 (apply 'encode-time
2939 (org-parse-time-string (match-string 1))))
2940 (org-clock-update-mode-line)))
2942 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2943 (end-of-line 1)
2944 (setq ts (match-string 1)
2945 te (match-string 3))
2946 (setq s (- (time-to-seconds
2947 (apply 'encode-time (org-parse-time-string te)))
2948 (time-to-seconds
2949 (apply 'encode-time (org-parse-time-string ts))))
2950 neg (< s 0)
2951 s (abs s)
2952 h (floor (/ s 3600))
2953 s (- s (* 3600 h))
2954 m (floor (/ s 60))
2955 s (- s (* 60 s)))
2956 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2957 t))))))
2959 (defun org-check-running-clock ()
2960 "Check if the current buffer contains the running clock.
2961 If yes, offer to stop it and to save the buffer with the changes."
2962 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2963 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2964 (buffer-name))))
2965 (org-clock-out)
2966 (when (y-or-n-p "Save changed buffer?")
2967 (save-buffer))))
2969 (defun org-clocktable-try-shift (dir n)
2970 "Check if this line starts a clock table, if yes, shift the time block."
2971 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2972 (org-clocktable-shift dir n)))
2974 ;; Autoload org-timer.el
2976 ;(declare-function org-timer "org-timer")
2978 (eval-and-compile
2979 (org-autoload
2980 "org-timer"
2981 '(org-timer-start org-timer org-timer-item
2982 org-timer-change-times-in-region)))
2985 ;; Autoload archiving code
2986 ;; The stuff that is needed for cycling and tags has to be defined here.
2988 (defgroup org-archive nil
2989 "Options concerning archiving in Org-mode."
2990 :tag "Org Archive"
2991 :group 'org-structure)
2993 (defcustom org-archive-location "%s_archive::"
2994 "The location where subtrees should be archived.
2996 The value of this variable is a string, consisting of two parts,
2997 separated by a double-colon. The first part is a filename and
2998 the second part is a headline.
3000 When the filename is omitted, archiving happens in the same file.
3001 %s in the filename will be replaced by the current file
3002 name (without the directory part). Archiving to a different file
3003 is useful to keep archived entries from contributing to the
3004 Org-mode Agenda.
3006 The archived entries will be filed as subtrees of the specified
3007 headline. When the headline is omitted, the subtrees are simply
3008 filed away at the end of the file, as top-level entries. Also in
3009 the heading you can use %s to represent the file name, this can be
3010 useful when using the same archive for a number of different files.
3012 Here are a few examples:
3013 \"%s_archive::\"
3014 If the current file is Projects.org, archive in file
3015 Projects.org_archive, as top-level trees. This is the default.
3017 \"::* Archived Tasks\"
3018 Archive in the current file, under the top-level headline
3019 \"* Archived Tasks\".
3021 \"~/org/archive.org::\"
3022 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3024 \"~/org/archive.org::From %s\"
3025 Archive in file ~/org/archive.org (absolute path), und headlines
3026 \"From FILENAME\" where file name is the current file name.
3028 \"basement::** Finished Tasks\"
3029 Archive in file ./basement (relative path), as level 3 trees
3030 below the level 2 heading \"** Finished Tasks\".
3032 You may set this option on a per-file basis by adding to the buffer a
3033 line like
3035 #+ARCHIVE: basement::** Finished Tasks
3037 You may also define it locally for a subtree by setting an ARCHIVE property
3038 in the entry. If such a property is found in an entry, or anywhere up
3039 the hierarchy, it will be used."
3040 :group 'org-archive
3041 :type 'string)
3043 (defcustom org-archive-tag "ARCHIVE"
3044 "The tag that marks a subtree as archived.
3045 An archived subtree does not open during visibility cycling, and does
3046 not contribute to the agenda listings.
3047 After changing this, font-lock must be restarted in the relevant buffers to
3048 get the proper fontification."
3049 :group 'org-archive
3050 :group 'org-keywords
3051 :type 'string)
3053 (defcustom org-agenda-skip-archived-trees t
3054 "Non-nil means, the agenda will skip any items located in archived trees.
3055 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3056 variable is no longer recommended, you should leave it at the value t.
3057 Instead, use the key `v' to cycle the archives-mode in the agenda."
3058 :group 'org-archive
3059 :group 'org-agenda-skip
3060 :type 'boolean)
3062 (defcustom org-cycle-open-archived-trees nil
3063 "Non-nil means, `org-cycle' will open archived trees.
3064 An archived tree is a tree marked with the tag ARCHIVE.
3065 When nil, archived trees will stay folded. You can still open them with
3066 normal outline commands like `show-all', but not with the cycling commands."
3067 :group 'org-archive
3068 :group 'org-cycle
3069 :type 'boolean)
3071 (defcustom org-sparse-tree-open-archived-trees nil
3072 "Non-nil means sparse tree construction shows matches in archived trees.
3073 When nil, matches in these trees are highlighted, but the trees are kept in
3074 collapsed state."
3075 :group 'org-archive
3076 :group 'org-sparse-trees
3077 :type 'boolean)
3079 (defun org-cycle-hide-archived-subtrees (state)
3080 "Re-hide all archived subtrees after a visibility state change."
3081 (when (and (not org-cycle-open-archived-trees)
3082 (not (memq state '(overview folded))))
3083 (save-excursion
3084 (let* ((globalp (memq state '(contents all)))
3085 (beg (if globalp (point-min) (point)))
3086 (end (if globalp (point-max) (org-end-of-subtree t))))
3087 (org-hide-archived-subtrees beg end)
3088 (goto-char beg)
3089 (if (looking-at (concat ".*:" org-archive-tag ":"))
3090 (message "%s" (substitute-command-keys
3091 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3093 (defun org-force-cycle-archived ()
3094 "Cycle subtree even if it is archived."
3095 (interactive)
3096 (setq this-command 'org-cycle)
3097 (let ((org-cycle-open-archived-trees t))
3098 (call-interactively 'org-cycle)))
3100 (defun org-hide-archived-subtrees (beg end)
3101 "Re-hide all archived subtrees after a visibility state change."
3102 (save-excursion
3103 (let* ((re (concat ":" org-archive-tag ":")))
3104 (goto-char beg)
3105 (while (re-search-forward re end t)
3106 (and (org-on-heading-p) (hide-subtree))
3107 (org-end-of-subtree t)))))
3109 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3111 (eval-and-compile
3112 (org-autoload "org-archive"
3113 '(org-add-archive-files org-archive-subtree
3114 org-archive-to-archive-sibling org-toggle-archive-tag)))
3116 ;; Autoload Column View Code
3118 (declare-function org-columns-number-to-string "org-colview")
3119 (declare-function org-columns-get-format-and-top-level "org-colview")
3120 (declare-function org-columns-compute "org-colview")
3122 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3123 '(org-columns-number-to-string org-columns-get-format-and-top-level
3124 org-columns-compute org-agenda-columns org-columns-remove-overlays
3125 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3127 ;; Autoload ID code
3129 (declare-function org-id-store-link "org-id")
3130 (declare-function org-id-locations-load "org-id")
3131 (declare-function org-id-locations-save "org-id")
3132 (defvar org-id-track-globally)
3133 (org-autoload "org-id"
3134 '(org-id-get-create org-id-new org-id-copy org-id-get
3135 org-id-get-with-outline-path-completion
3136 org-id-get-with-outline-drilling
3137 org-id-goto org-id-find org-id-store-link))
3139 ;; Autoload Plotting Code
3141 (org-autoload "org-plot"
3142 '(org-plot/gnuplot))
3144 ;;; Variables for pre-computed regular expressions, all buffer local
3146 (defvar org-drawer-regexp nil
3147 "Matches first line of a hidden block.")
3148 (make-variable-buffer-local 'org-drawer-regexp)
3149 (defvar org-todo-regexp nil
3150 "Matches any of the TODO state keywords.")
3151 (make-variable-buffer-local 'org-todo-regexp)
3152 (defvar org-not-done-regexp nil
3153 "Matches any of the TODO state keywords except the last one.")
3154 (make-variable-buffer-local 'org-not-done-regexp)
3155 (defvar org-todo-line-regexp nil
3156 "Matches a headline and puts TODO state into group 2 if present.")
3157 (make-variable-buffer-local 'org-todo-line-regexp)
3158 (defvar org-complex-heading-regexp nil
3159 "Matches a headline and puts everything into groups:
3160 group 1: the stars
3161 group 2: The todo keyword, maybe
3162 group 3: Priority cookie
3163 group 4: True headline
3164 group 5: Tags")
3165 (make-variable-buffer-local 'org-complex-heading-regexp)
3166 (defvar org-todo-line-tags-regexp nil
3167 "Matches a headline and puts TODO state into group 2 if present.
3168 Also put tags into group 4 if tags are present.")
3169 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3170 (defvar org-nl-done-regexp nil
3171 "Matches newline followed by a headline with the DONE keyword.")
3172 (make-variable-buffer-local 'org-nl-done-regexp)
3173 (defvar org-looking-at-done-regexp nil
3174 "Matches the DONE keyword a point.")
3175 (make-variable-buffer-local 'org-looking-at-done-regexp)
3176 (defvar org-ds-keyword-length 12
3177 "Maximum length of the Deadline and SCHEDULED keywords.")
3178 (make-variable-buffer-local 'org-ds-keyword-length)
3179 (defvar org-deadline-regexp nil
3180 "Matches the DEADLINE keyword.")
3181 (make-variable-buffer-local 'org-deadline-regexp)
3182 (defvar org-deadline-time-regexp nil
3183 "Matches the DEADLINE keyword together with a time stamp.")
3184 (make-variable-buffer-local 'org-deadline-time-regexp)
3185 (defvar org-deadline-line-regexp nil
3186 "Matches the DEADLINE keyword and the rest of the line.")
3187 (make-variable-buffer-local 'org-deadline-line-regexp)
3188 (defvar org-scheduled-regexp nil
3189 "Matches the SCHEDULED keyword.")
3190 (make-variable-buffer-local 'org-scheduled-regexp)
3191 (defvar org-scheduled-time-regexp nil
3192 "Matches the SCHEDULED keyword together with a time stamp.")
3193 (make-variable-buffer-local 'org-scheduled-time-regexp)
3194 (defvar org-closed-time-regexp nil
3195 "Matches the CLOSED keyword together with a time stamp.")
3196 (make-variable-buffer-local 'org-closed-time-regexp)
3198 (defvar org-keyword-time-regexp nil
3199 "Matches any of the 4 keywords, together with the time stamp.")
3200 (make-variable-buffer-local 'org-keyword-time-regexp)
3201 (defvar org-keyword-time-not-clock-regexp nil
3202 "Matches any of the 3 keywords, together with the time stamp.")
3203 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3204 (defvar org-maybe-keyword-time-regexp nil
3205 "Matches a timestamp, possibly preceeded by a keyword.")
3206 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3207 (defvar org-planning-or-clock-line-re nil
3208 "Matches a line with planning or clock info.")
3209 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3211 (defconst org-plain-time-of-day-regexp
3212 (concat
3213 "\\(\\<[012]?[0-9]"
3214 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3215 "\\(--?"
3216 "\\(\\<[012]?[0-9]"
3217 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3218 "\\)?")
3219 "Regular expression to match a plain time or time range.
3220 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3221 groups carry important information:
3222 0 the full match
3223 1 the first time, range or not
3224 8 the second time, if it is a range.")
3226 (defconst org-plain-time-extension-regexp
3227 (concat
3228 "\\(\\<[012]?[0-9]"
3229 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3230 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3231 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3232 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3233 groups carry important information:
3234 0 the full match
3235 7 hours of duration
3236 9 minutes of duration")
3238 (defconst org-stamp-time-of-day-regexp
3239 (concat
3240 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3241 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3242 "\\(--?"
3243 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3244 "Regular expression to match a timestamp time or time range.
3245 After a match, the following groups carry important information:
3246 0 the full match
3247 1 date plus weekday, for backreferencing to make sure both times on same day
3248 2 the first time, range or not
3249 4 the second time, if it is a range.")
3251 (defconst org-startup-options
3252 '(("fold" org-startup-folded t)
3253 ("overview" org-startup-folded t)
3254 ("nofold" org-startup-folded nil)
3255 ("showall" org-startup-folded nil)
3256 ("content" org-startup-folded content)
3257 ("hidestars" org-hide-leading-stars t)
3258 ("showstars" org-hide-leading-stars nil)
3259 ("odd" org-odd-levels-only t)
3260 ("oddeven" org-odd-levels-only nil)
3261 ("align" org-startup-align-all-tables t)
3262 ("noalign" org-startup-align-all-tables nil)
3263 ("customtime" org-display-custom-times t)
3264 ("logdone" org-log-done time)
3265 ("lognotedone" org-log-done note)
3266 ("nologdone" org-log-done nil)
3267 ("lognoteclock-out" org-log-note-clock-out t)
3268 ("nolognoteclock-out" org-log-note-clock-out nil)
3269 ("logrepeat" org-log-repeat state)
3270 ("lognoterepeat" org-log-repeat note)
3271 ("nologrepeat" org-log-repeat nil)
3272 ("fninline" org-footnote-define-inline t)
3273 ("nofninline" org-footnote-define-inline nil)
3274 ("fnlocal" org-footnote-section nil)
3275 ("fnauto" org-footnote-auto-label t)
3276 ("fnprompt" org-footnote-auto-label nil)
3277 ("fnconfirm" org-footnote-auto-label confirm)
3278 ("fnplain" org-footnote-auto-label plain)
3279 ("constcgs" constants-unit-system cgs)
3280 ("constSI" constants-unit-system SI)
3281 ("noptag" org-tag-persistent-alist nil))
3282 "Variable associated with STARTUP options for org-mode.
3283 Each element is a list of three items: The startup options as written
3284 in the #+STARTUP line, the corresponding variable, and the value to
3285 set this variable to if the option is found. An optional forth element PUSH
3286 means to push this value onto the list in the variable.")
3288 (defun org-set-regexps-and-options ()
3289 "Precompute regular expressions for current buffer."
3290 (when (org-mode-p)
3291 (org-set-local 'org-todo-kwd-alist nil)
3292 (org-set-local 'org-todo-key-alist nil)
3293 (org-set-local 'org-todo-key-trigger nil)
3294 (org-set-local 'org-todo-keywords-1 nil)
3295 (org-set-local 'org-done-keywords nil)
3296 (org-set-local 'org-todo-heads nil)
3297 (org-set-local 'org-todo-sets nil)
3298 (org-set-local 'org-todo-log-states nil)
3299 (org-set-local 'org-file-properties nil)
3300 (org-set-local 'org-file-tags nil)
3301 (let ((re (org-make-options-regexp
3302 '("CATEGORY" "TODO" "COLUMNS"
3303 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3304 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3305 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3306 (splitre "[ \t]+")
3307 kwds kws0 kwsa key log value cat arch tags const links hw dws
3308 tail sep kws1 prio props ftags drawers
3309 ext-setup-or-nil setup-contents (start 0))
3310 (save-excursion
3311 (save-restriction
3312 (widen)
3313 (goto-char (point-min))
3314 (while (or (and ext-setup-or-nil
3315 (string-match re ext-setup-or-nil start)
3316 (setq start (match-end 0)))
3317 (and (setq ext-setup-or-nil nil start 0)
3318 (re-search-forward re nil t)))
3319 (setq key (upcase (match-string 1 ext-setup-or-nil))
3320 value (org-match-string-no-properties 2 ext-setup-or-nil))
3321 (cond
3322 ((equal key "CATEGORY")
3323 (if (string-match "[ \t]+$" value)
3324 (setq value (replace-match "" t t value)))
3325 (setq cat value))
3326 ((member key '("SEQ_TODO" "TODO"))
3327 (push (cons 'sequence (org-split-string value splitre)) kwds))
3328 ((equal key "TYP_TODO")
3329 (push (cons 'type (org-split-string value splitre)) kwds))
3330 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3331 ;; general TODO-like setup
3332 (push (cons (intern (downcase (match-string 1 key)))
3333 (org-split-string value splitre)) kwds))
3334 ((equal key "TAGS")
3335 (setq tags (append tags (if tags '("\\n") nil)
3336 (org-split-string value splitre))))
3337 ((equal key "COLUMNS")
3338 (org-set-local 'org-columns-default-format value))
3339 ((equal key "LINK")
3340 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3341 (push (cons (match-string 1 value)
3342 (org-trim (match-string 2 value)))
3343 links)))
3344 ((equal key "PRIORITIES")
3345 (setq prio (org-split-string value " +")))
3346 ((equal key "PROPERTY")
3347 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3348 (push (cons (match-string 1 value) (match-string 2 value))
3349 props)))
3350 ((equal key "FILETAGS")
3351 (when (string-match "\\S-" value)
3352 (setq ftags
3353 (append
3354 ftags
3355 (apply 'append
3356 (mapcar (lambda (x) (org-split-string x ":"))
3357 (org-split-string value)))))))
3358 ((equal key "DRAWERS")
3359 (setq drawers (org-split-string value splitre)))
3360 ((equal key "CONSTANTS")
3361 (setq const (append const (org-split-string value splitre))))
3362 ((equal key "STARTUP")
3363 (let ((opts (org-split-string value splitre))
3364 l var val)
3365 (while (setq l (pop opts))
3366 (when (setq l (assoc l org-startup-options))
3367 (setq var (nth 1 l) val (nth 2 l))
3368 (if (not (nth 3 l))
3369 (set (make-local-variable var) val)
3370 (if (not (listp (symbol-value var)))
3371 (set (make-local-variable var) nil))
3372 (set (make-local-variable var) (symbol-value var))
3373 (add-to-list var val))))))
3374 ((equal key "ARCHIVE")
3375 (string-match " *$" value)
3376 (setq arch (replace-match "" t t value))
3377 (remove-text-properties 0 (length arch)
3378 '(face t fontified t) arch))
3379 ((equal key "SETUPFILE")
3380 (setq setup-contents (org-file-contents
3381 (expand-file-name
3382 (org-remove-double-quotes value))
3383 'noerror))
3384 (if (not ext-setup-or-nil)
3385 (setq ext-setup-or-nil setup-contents start 0)
3386 (setq ext-setup-or-nil
3387 (concat (substring ext-setup-or-nil 0 start)
3388 "\n" setup-contents "\n"
3389 (substring ext-setup-or-nil start)))))
3390 ))))
3391 (when cat
3392 (org-set-local 'org-category (intern cat))
3393 (push (cons "CATEGORY" cat) props))
3394 (when prio
3395 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3396 (setq prio (mapcar 'string-to-char prio))
3397 (org-set-local 'org-highest-priority (nth 0 prio))
3398 (org-set-local 'org-lowest-priority (nth 1 prio))
3399 (org-set-local 'org-default-priority (nth 2 prio)))
3400 (and props (org-set-local 'org-file-properties (nreverse props)))
3401 (and ftags (org-set-local 'org-file-tags ftags))
3402 (and drawers (org-set-local 'org-drawers drawers))
3403 (and arch (org-set-local 'org-archive-location arch))
3404 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3405 ;; Process the TODO keywords
3406 (unless kwds
3407 ;; Use the global values as if they had been given locally.
3408 (setq kwds (default-value 'org-todo-keywords))
3409 (if (stringp (car kwds))
3410 (setq kwds (list (cons org-todo-interpretation
3411 (default-value 'org-todo-keywords)))))
3412 (setq kwds (reverse kwds)))
3413 (setq kwds (nreverse kwds))
3414 (let (inter kws kw)
3415 (while (setq kws (pop kwds))
3416 (let ((kws (or
3417 (run-hook-with-args-until-success
3418 'org-todo-setup-filter-hook kws)
3419 kws)))
3420 (setq inter (pop kws) sep (member "|" kws)
3421 kws0 (delete "|" (copy-sequence kws))
3422 kwsa nil
3423 kws1 (mapcar
3424 (lambda (x)
3425 ;; 1 2
3426 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3427 (progn
3428 (setq kw (match-string 1 x)
3429 key (and (match-end 2) (match-string 2 x))
3430 log (org-extract-log-state-settings x))
3431 (push (cons kw (and key (string-to-char key))) kwsa)
3432 (and log (push log org-todo-log-states))
3434 (error "Invalid TODO keyword %s" x)))
3435 kws0)
3436 kwsa (if kwsa (append '((:startgroup))
3437 (nreverse kwsa)
3438 '((:endgroup))))
3439 hw (car kws1)
3440 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3441 tail (list inter hw (car dws) (org-last dws))))
3442 (add-to-list 'org-todo-heads hw 'append)
3443 (push kws1 org-todo-sets)
3444 (setq org-done-keywords (append org-done-keywords dws nil))
3445 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3446 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3447 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3448 (setq org-todo-sets (nreverse org-todo-sets)
3449 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3450 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3451 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3452 ;; Process the constants
3453 (when const
3454 (let (e cst)
3455 (while (setq e (pop const))
3456 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3457 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3458 (setq org-table-formula-constants-local cst)))
3460 ;; Process the tags.
3461 (when tags
3462 (let (e tgs)
3463 (while (setq e (pop tags))
3464 (cond
3465 ((equal e "{") (push '(:startgroup) tgs))
3466 ((equal e "}") (push '(:endgroup) tgs))
3467 ((equal e "\\n") (push '(:newline) tgs))
3468 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3469 (push (cons (match-string 1 e)
3470 (string-to-char (match-string 2 e)))
3471 tgs))
3472 (t (push (list e) tgs))))
3473 (org-set-local 'org-tag-alist nil)
3474 (while (setq e (pop tgs))
3475 (or (and (stringp (car e))
3476 (assoc (car e) org-tag-alist))
3477 (push e org-tag-alist)))))
3479 ;; Compute the regular expressions and other local variables
3480 (if (not org-done-keywords)
3481 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3482 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3483 (length org-scheduled-string)
3484 (length org-clock-string)
3485 (length org-closed-string)))
3486 org-drawer-regexp
3487 (concat "^[ \t]*:\\("
3488 (mapconcat 'regexp-quote org-drawers "\\|")
3489 "\\):[ \t]*$")
3490 org-not-done-keywords
3491 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3492 org-todo-regexp
3493 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3494 "\\|") "\\)\\>")
3495 org-not-done-regexp
3496 (concat "\\<\\("
3497 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3498 "\\)\\>")
3499 org-todo-line-regexp
3500 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3501 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3502 "\\)\\>\\)?[ \t]*\\(.*\\)")
3503 org-complex-heading-regexp
3504 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3505 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3506 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3507 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3508 org-nl-done-regexp
3509 (concat "\n\\*+[ \t]+"
3510 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3511 "\\)" "\\>")
3512 org-todo-line-tags-regexp
3513 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3514 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3515 (org-re
3516 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3517 org-looking-at-done-regexp
3518 (concat "^" "\\(?:"
3519 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3520 "\\>")
3521 org-deadline-regexp (concat "\\<" org-deadline-string)
3522 org-deadline-time-regexp
3523 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3524 org-deadline-line-regexp
3525 (concat "\\<\\(" org-deadline-string "\\).*")
3526 org-scheduled-regexp
3527 (concat "\\<" org-scheduled-string)
3528 org-scheduled-time-regexp
3529 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3530 org-closed-time-regexp
3531 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3532 org-keyword-time-regexp
3533 (concat "\\<\\(" org-scheduled-string
3534 "\\|" org-deadline-string
3535 "\\|" org-closed-string
3536 "\\|" org-clock-string "\\)"
3537 " *[[<]\\([^]>]+\\)[]>]")
3538 org-keyword-time-not-clock-regexp
3539 (concat "\\<\\(" org-scheduled-string
3540 "\\|" org-deadline-string
3541 "\\|" org-closed-string
3542 "\\)"
3543 " *[[<]\\([^]>]+\\)[]>]")
3544 org-maybe-keyword-time-regexp
3545 (concat "\\(\\<\\(" org-scheduled-string
3546 "\\|" org-deadline-string
3547 "\\|" org-closed-string
3548 "\\|" org-clock-string "\\)\\)?"
3549 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3550 org-planning-or-clock-line-re
3551 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3552 "\\|" org-deadline-string
3553 "\\|" org-closed-string "\\|" org-clock-string
3554 "\\)\\>\\)")
3556 (org-compute-latex-and-specials-regexp)
3557 (org-set-font-lock-defaults))))
3559 (defun org-file-contents (file &optional noerror)
3560 "Return the contents of FILE, as a string."
3561 (if (or (not file)
3562 (not (file-readable-p file)))
3563 (if noerror
3564 (progn
3565 (message "Cannot read file %s" file)
3566 (ding) (sit-for 2)
3568 (error "Cannot read file %s" file))
3569 (with-temp-buffer
3570 (insert-file-contents file)
3571 (buffer-string))))
3573 (defun org-extract-log-state-settings (x)
3574 "Extract the log state setting from a TODO keyword string.
3575 This will extract info from a string like \"WAIT(w@/!)\"."
3576 (let (kw key log1 log2)
3577 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3578 (setq kw (match-string 1 x)
3579 key (and (match-end 2) (match-string 2 x))
3580 log1 (and (match-end 3) (match-string 3 x))
3581 log2 (and (match-end 4) (match-string 4 x)))
3582 (and (or log1 log2)
3583 (list kw
3584 (and log1 (if (equal log1 "!") 'time 'note))
3585 (and log2 (if (equal log2 "!") 'time 'note)))))))
3587 (defun org-remove-keyword-keys (list)
3588 "Remove a pair of parenthesis at the end of each string in LIST."
3589 (mapcar (lambda (x)
3590 (if (string-match "(.*)$" x)
3591 (substring x 0 (match-beginning 0))
3593 list))
3595 ;; FIXME: this could be done much better, using second characters etc.
3596 (defun org-assign-fast-keys (alist)
3597 "Assign fast keys to a keyword-key alist.
3598 Respect keys that are already there."
3599 (let (new e k c c1 c2 (char ?a))
3600 (while (setq e (pop alist))
3601 (cond
3602 ((equal e '(:startgroup)) (push e new))
3603 ((equal e '(:endgroup)) (push e new))
3604 ((equal e '(:newline)) (push e new))
3606 (setq k (car e) c2 nil)
3607 (if (cdr e)
3608 (setq c (cdr e))
3609 ;; automatically assign a character.
3610 (setq c1 (string-to-char
3611 (downcase (substring
3612 k (if (= (string-to-char k) ?@) 1 0)))))
3613 (if (or (rassoc c1 new) (rassoc c1 alist))
3614 (while (or (rassoc char new) (rassoc char alist))
3615 (setq char (1+ char)))
3616 (setq c2 c1))
3617 (setq c (or c2 char)))
3618 (push (cons k c) new))))
3619 (nreverse new)))
3621 ;;; Some variables used in various places
3623 (defvar org-window-configuration nil
3624 "Used in various places to store a window configuration.")
3625 (defvar org-finish-function nil
3626 "Function to be called when `C-c C-c' is used.
3627 This is for getting out of special buffers like remember.")
3630 ;; FIXME: Occasionally check by commenting these, to make sure
3631 ;; no other functions uses these, forgetting to let-bind them.
3632 (defvar entry)
3633 (defvar state)
3634 (defvar last-state)
3635 (defvar date)
3636 (defvar description)
3638 ;; Defined somewhere in this file, but used before definition.
3639 (defvar org-html-entities)
3640 (defvar org-struct-menu)
3641 (defvar org-org-menu)
3642 (defvar org-tbl-menu)
3643 (defvar org-agenda-keymap)
3645 ;;;; Define the Org-mode
3647 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3648 (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."))
3651 ;; We use a before-change function to check if a table might need
3652 ;; an update.
3653 (defvar org-table-may-need-update t
3654 "Indicates that a table might need an update.
3655 This variable is set by `org-before-change-function'.
3656 `org-table-align' sets it back to nil.")
3657 (defun org-before-change-function (beg end)
3658 "Every change indicates that a table might need an update."
3659 (setq org-table-may-need-update t))
3660 (defvar org-mode-map)
3661 (defvar org-mode-hook nil
3662 "Mode hook for Org-mode, run after the mode was turned on.")
3663 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3664 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3665 (defvar org-table-buffer-is-an nil)
3666 (defconst org-outline-regexp "\\*+ ")
3668 ;;;###autoload
3669 (define-derived-mode org-mode outline-mode "Org"
3670 "Outline-based notes management and organizer, alias
3671 \"Carsten's outline-mode for keeping track of everything.\"
3673 Org-mode develops organizational tasks around a NOTES file which
3674 contains information about projects as plain text. Org-mode is
3675 implemented on top of outline-mode, which is ideal to keep the content
3676 of large files well structured. It supports ToDo items, deadlines and
3677 time stamps, which magically appear in the diary listing of the Emacs
3678 calendar. Tables are easily created with a built-in table editor.
3679 Plain text URL-like links connect to websites, emails (VM), Usenet
3680 messages (Gnus), BBDB entries, and any files related to the project.
3681 For printing and sharing of notes, an Org-mode file (or a part of it)
3682 can be exported as a structured ASCII or HTML file.
3684 The following commands are available:
3686 \\{org-mode-map}"
3688 ;; Get rid of Outline menus, they are not needed
3689 ;; Need to do this here because define-derived-mode sets up
3690 ;; the keymap so late. Still, it is a waste to call this each time
3691 ;; we switch another buffer into org-mode.
3692 (if (featurep 'xemacs)
3693 (when (boundp 'outline-mode-menu-heading)
3694 ;; Assume this is Greg's port, it used easymenu
3695 (easy-menu-remove outline-mode-menu-heading)
3696 (easy-menu-remove outline-mode-menu-show)
3697 (easy-menu-remove outline-mode-menu-hide))
3698 (define-key org-mode-map [menu-bar headings] 'undefined)
3699 (define-key org-mode-map [menu-bar hide] 'undefined)
3700 (define-key org-mode-map [menu-bar show] 'undefined))
3702 (org-load-modules-maybe)
3703 (easy-menu-add org-org-menu)
3704 (easy-menu-add org-tbl-menu)
3705 (org-install-agenda-files-menu)
3706 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3707 (org-add-to-invisibility-spec '(org-cwidth))
3708 (when (featurep 'xemacs)
3709 (org-set-local 'line-move-ignore-invisible t))
3710 (org-set-local 'outline-regexp org-outline-regexp)
3711 (org-set-local 'outline-level 'org-outline-level)
3712 (when (and org-ellipsis
3713 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3714 (fboundp 'make-glyph-code))
3715 (unless org-display-table
3716 (setq org-display-table (make-display-table)))
3717 (set-display-table-slot
3718 org-display-table 4
3719 (vconcat (mapcar
3720 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3721 org-ellipsis)))
3722 (if (stringp org-ellipsis) org-ellipsis "..."))))
3723 (setq buffer-display-table org-display-table))
3724 (org-set-regexps-and-options)
3725 (when (and org-tag-faces (not org-tags-special-faces-re))
3726 ;; tag faces set outside customize.... force initialization.
3727 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3728 ;; Calc embedded
3729 (org-set-local 'calc-embedded-open-mode "# ")
3730 (modify-syntax-entry ?# "<")
3731 (modify-syntax-entry ?@ "w")
3732 (if org-startup-truncated (setq truncate-lines t))
3733 (org-set-local 'font-lock-unfontify-region-function
3734 'org-unfontify-region)
3735 ;; Activate before-change-function
3736 (org-set-local 'org-table-may-need-update t)
3737 (org-add-hook 'before-change-functions 'org-before-change-function nil
3738 'local)
3739 ;; Check for running clock before killing a buffer
3740 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3741 ;; Paragraphs and auto-filling
3742 (org-set-autofill-regexps)
3743 (setq indent-line-function 'org-indent-line-function)
3744 (org-update-radio-target-regexp)
3745 ;; Make sure dependence stuff works reliably, even for users who set it
3746 ;; too late :-(
3747 (if org-enforce-todo-dependencies
3748 (add-hook 'org-blocker-hook
3749 'org-block-todo-from-children-or-siblings)
3750 (remove-hook 'org-blocker-hook
3751 'org-block-todo-from-children-or-siblings))
3752 (if org-enforce-todo-checkbox-dependencies
3753 (add-hook 'org-blocker-hook
3754 'org-block-todo-from-checkboxes)
3755 (remove-hook 'org-blocker-hook
3756 'org-block-todo-from-checkboxes))
3758 ;; Comment characters
3759 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3760 (org-set-local 'comment-padding " ")
3762 ;; Align options lines
3763 (org-set-local
3764 'align-mode-rules-list
3765 '((org-in-buffer-settings
3766 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3767 (modes . '(org-mode)))))
3769 ;; Imenu
3770 (org-set-local 'imenu-create-index-function
3771 'org-imenu-get-tree)
3773 ;; Make isearch reveal context
3774 (if (or (featurep 'xemacs)
3775 (not (boundp 'outline-isearch-open-invisible-function)))
3776 ;; Emacs 21 and XEmacs make use of the hook
3777 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3778 ;; Emacs 22 deals with this through a special variable
3779 (org-set-local 'outline-isearch-open-invisible-function
3780 (lambda (&rest ignore) (org-show-context 'isearch))))
3782 ;; If empty file that did not turn on org-mode automatically, make it to.
3783 (if (and org-insert-mode-line-in-empty-file
3784 (interactive-p)
3785 (= (point-min) (point-max)))
3786 (insert "# -*- mode: org -*-\n\n"))
3788 (unless org-inhibit-startup
3789 (when org-startup-align-all-tables
3790 (let ((bmp (buffer-modified-p)))
3791 (org-table-map-tables 'org-table-align)
3792 (set-buffer-modified-p bmp)))
3793 (org-set-startup-visibility)))
3795 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3797 (defun org-current-time ()
3798 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3799 (if (> (car org-time-stamp-rounding-minutes) 1)
3800 (let ((r (car org-time-stamp-rounding-minutes))
3801 (time (decode-time)))
3802 (apply 'encode-time
3803 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3804 (nthcdr 2 time))))
3805 (current-time)))
3807 ;;;; Font-Lock stuff, including the activators
3809 (defvar org-mouse-map (make-sparse-keymap))
3810 (org-defkey org-mouse-map
3811 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3812 (org-defkey org-mouse-map
3813 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3814 (when org-mouse-1-follows-link
3815 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3816 (when org-tab-follows-link
3817 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3818 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3820 (require 'font-lock)
3822 (defconst org-non-link-chars "]\t\n\r<>")
3823 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3824 "shell" "elisp"))
3825 (defvar org-link-types-re nil
3826 "Matches a link that has a url-like prefix like \"http:\"")
3827 (defvar org-link-re-with-space nil
3828 "Matches a link with spaces, optional angular brackets around it.")
3829 (defvar org-link-re-with-space2 nil
3830 "Matches a link with spaces, optional angular brackets around it.")
3831 (defvar org-link-re-with-space3 nil
3832 "Matches a link with spaces, only for internal part in bracket links.")
3833 (defvar org-angle-link-re nil
3834 "Matches link with angular brackets, spaces are allowed.")
3835 (defvar org-plain-link-re nil
3836 "Matches plain link, without spaces.")
3837 (defvar org-bracket-link-regexp nil
3838 "Matches a link in double brackets.")
3839 (defvar org-bracket-link-analytic-regexp nil
3840 "Regular expression used to analyze links.
3841 Here is what the match groups contain after a match:
3842 1: http:
3843 2: http
3844 3: path
3845 4: [desc]
3846 5: desc")
3847 (defvar org-bracket-link-analytic-regexp++ nil
3848 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3849 (defvar org-any-link-re nil
3850 "Regular expression matching any link.")
3852 (defun org-make-link-regexps ()
3853 "Update the link regular expressions.
3854 This should be called after the variable `org-link-types' has changed."
3855 (setq org-link-types-re
3856 (concat
3857 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3858 org-link-re-with-space
3859 (concat
3860 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3861 "\\([^" org-non-link-chars " ]"
3862 "[^" org-non-link-chars "]*"
3863 "[^" org-non-link-chars " ]\\)>?")
3864 org-link-re-with-space2
3865 (concat
3866 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3867 "\\([^" org-non-link-chars " ]"
3868 "[^\t\n\r]*"
3869 "[^" org-non-link-chars " ]\\)>?")
3870 org-link-re-with-space3
3871 (concat
3872 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3873 "\\([^" org-non-link-chars " ]"
3874 "[^\t\n\r]*\\)")
3875 org-angle-link-re
3876 (concat
3877 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3878 "\\([^" org-non-link-chars " ]"
3879 "[^" org-non-link-chars "]*"
3880 "\\)>")
3881 org-plain-link-re
3882 (concat
3883 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3884 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3885 org-bracket-link-regexp
3886 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3887 org-bracket-link-analytic-regexp
3888 (concat
3889 "\\[\\["
3890 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3891 "\\([^]]+\\)"
3892 "\\]"
3893 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3894 "\\]")
3895 org-bracket-link-analytic-regexp++
3896 (concat
3897 "\\[\\["
3898 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
3899 "\\([^]]+\\)"
3900 "\\]"
3901 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3902 "\\]")
3903 org-any-link-re
3904 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3905 org-angle-link-re "\\)\\|\\("
3906 org-plain-link-re "\\)")))
3908 (org-make-link-regexps)
3910 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3911 "Regular expression for fast time stamp matching.")
3912 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3913 "Regular expression for fast time stamp matching.")
3914 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3915 "Regular expression matching time strings for analysis.
3916 This one does not require the space after the date, so it can be used
3917 on a string that terminates immediately after the date.")
3918 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3919 "Regular expression matching time strings for analysis.")
3920 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3921 "Regular expression matching time stamps, with groups.")
3922 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3923 "Regular expression matching time stamps (also [..]), with groups.")
3924 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3925 "Regular expression matching a time stamp range.")
3926 (defconst org-tr-regexp-both
3927 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3928 "Regular expression matching a time stamp range.")
3929 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3930 org-ts-regexp "\\)?")
3931 "Regular expression matching a time stamp or time stamp range.")
3932 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3933 org-ts-regexp-both "\\)?")
3934 "Regular expression matching a time stamp or time stamp range.
3935 The time stamps may be either active or inactive.")
3937 (defvar org-emph-face nil)
3939 (defun org-do-emphasis-faces (limit)
3940 "Run through the buffer and add overlays to links."
3941 (let (rtn)
3942 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3943 (if (not (= (char-after (match-beginning 3))
3944 (char-after (match-beginning 4))))
3945 (progn
3946 (setq rtn t)
3947 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3948 'face
3949 (nth 1 (assoc (match-string 3)
3950 org-emphasis-alist)))
3951 (add-text-properties (match-beginning 2) (match-end 2)
3952 '(font-lock-multiline t))
3953 (when org-hide-emphasis-markers
3954 (add-text-properties (match-end 4) (match-beginning 5)
3955 '(invisible org-link))
3956 (add-text-properties (match-beginning 3) (match-end 3)
3957 '(invisible org-link)))))
3958 (backward-char 1))
3959 rtn))
3961 (defun org-emphasize (&optional char)
3962 "Insert or change an emphasis, i.e. a font like bold or italic.
3963 If there is an active region, change that region to a new emphasis.
3964 If there is no region, just insert the marker characters and position
3965 the cursor between them.
3966 CHAR should be either the marker character, or the first character of the
3967 HTML tag associated with that emphasis. If CHAR is a space, the means
3968 to remove the emphasis of the selected region.
3969 If char is not given (for example in an interactive call) it
3970 will be prompted for."
3971 (interactive)
3972 (let ((eal org-emphasis-alist) e det
3973 (erc org-emphasis-regexp-components)
3974 (prompt "")
3975 (string "") beg end move tag c s)
3976 (if (org-region-active-p)
3977 (setq beg (region-beginning) end (region-end)
3978 string (buffer-substring beg end))
3979 (setq move t))
3981 (while (setq e (pop eal))
3982 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3983 c (aref tag 0))
3984 (push (cons c (string-to-char (car e))) det)
3985 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3986 (substring tag 1)))))
3987 (setq det (nreverse det))
3988 (unless char
3989 (message "%s" (concat "Emphasis marker or tag:" prompt))
3990 (setq char (read-char-exclusive)))
3991 (setq char (or (cdr (assoc char det)) char))
3992 (if (equal char ?\ )
3993 (setq s "" move nil)
3994 (unless (assoc (char-to-string char) org-emphasis-alist)
3995 (error "No such emphasis marker: \"%c\"" char))
3996 (setq s (char-to-string char)))
3997 (while (and (> (length string) 1)
3998 (equal (substring string 0 1) (substring string -1))
3999 (assoc (substring string 0 1) org-emphasis-alist))
4000 (setq string (substring string 1 -1)))
4001 (setq string (concat s string s))
4002 (if beg (delete-region beg end))
4003 (unless (or (bolp)
4004 (string-match (concat "[" (nth 0 erc) "\n]")
4005 (char-to-string (char-before (point)))))
4006 (insert " "))
4007 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4008 (char-to-string (char-after (point))))
4009 (insert " ") (backward-char 1))
4010 (insert string)
4011 (and move (backward-char 1))))
4013 (defconst org-nonsticky-props
4014 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4017 (defun org-activate-plain-links (limit)
4018 "Run through the buffer and add overlays to links."
4019 (catch 'exit
4020 (let (f)
4021 (while (re-search-forward org-plain-link-re limit t)
4022 (setq f (get-text-property (match-beginning 0) 'face))
4023 (if (or (eq f 'org-tag)
4024 (and (listp f) (memq 'org-tag f)))
4026 (add-text-properties (match-beginning 0) (match-end 0)
4027 (list 'mouse-face 'highlight
4028 'rear-nonsticky org-nonsticky-props
4029 'keymap org-mouse-map
4031 (throw 'exit t))))))
4033 (defun org-activate-code (limit)
4034 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4035 (progn
4036 (remove-text-properties (match-beginning 0) (match-end 0)
4037 '(display t invisible t intangible t))
4038 t)))
4040 (defun org-activate-angle-links (limit)
4041 "Run through the buffer and add overlays to links."
4042 (if (re-search-forward org-angle-link-re limit t)
4043 (progn
4044 (add-text-properties (match-beginning 0) (match-end 0)
4045 (list 'mouse-face 'highlight
4046 'rear-nonsticky org-nonsticky-props
4047 'keymap org-mouse-map
4049 t)))
4051 (defun org-activate-footnote-links (limit)
4052 "Run through the buffer and add overlays to links."
4053 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4054 limit t)
4055 (progn
4056 (add-text-properties (match-beginning 2) (match-end 2)
4057 (list 'mouse-face 'highlight
4058 'rear-nonsticky org-nonsticky-props
4059 'keymap org-mouse-map
4060 'help-echo
4061 (if (= (point-at-bol) (match-beginning 2))
4062 "Footnote definition"
4063 "Footnote reference")
4065 t)))
4067 (defun org-activate-bracket-links (limit)
4068 "Run through the buffer and add overlays to bracketed links."
4069 (if (re-search-forward org-bracket-link-regexp limit t)
4070 (let* ((help (concat "LINK: "
4071 (org-match-string-no-properties 1)))
4072 ;; FIXME: above we should remove the escapes.
4073 ;; but that requires another match, protecting match data,
4074 ;; a lot of overhead for font-lock.
4075 (ip (org-maybe-intangible
4076 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
4077 'keymap org-mouse-map 'mouse-face 'highlight
4078 'font-lock-multiline t 'help-echo help)))
4079 (vp (list 'rear-nonsticky org-nonsticky-props
4080 'keymap org-mouse-map 'mouse-face 'highlight
4081 ' font-lock-multiline t 'help-echo help)))
4082 ;; We need to remove the invisible property here. Table narrowing
4083 ;; may have made some of this invisible.
4084 (remove-text-properties (match-beginning 0) (match-end 0)
4085 '(invisible nil))
4086 (if (match-end 3)
4087 (progn
4088 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4089 (add-text-properties (match-beginning 3) (match-end 3) vp)
4090 (add-text-properties (match-end 3) (match-end 0) ip))
4091 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4092 (add-text-properties (match-beginning 1) (match-end 1) vp)
4093 (add-text-properties (match-end 1) (match-end 0) ip))
4094 t)))
4096 (defun org-activate-dates (limit)
4097 "Run through the buffer and add overlays to dates."
4098 (if (re-search-forward org-tsr-regexp-both limit t)
4099 (progn
4100 (add-text-properties (match-beginning 0) (match-end 0)
4101 (list 'mouse-face 'highlight
4102 'rear-nonsticky org-nonsticky-props
4103 'keymap org-mouse-map))
4104 (when org-display-custom-times
4105 (if (match-end 3)
4106 (org-display-custom-time (match-beginning 3) (match-end 3)))
4107 (org-display-custom-time (match-beginning 1) (match-end 1)))
4108 t)))
4110 (defvar org-target-link-regexp nil
4111 "Regular expression matching radio targets in plain text.")
4112 (make-variable-buffer-local 'org-target-link-regexp)
4113 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4114 "Regular expression matching a link target.")
4115 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4116 "Regular expression matching a radio target.")
4117 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4118 "Regular expression matching any target.")
4120 (defun org-activate-target-links (limit)
4121 "Run through the buffer and add overlays to target matches."
4122 (when org-target-link-regexp
4123 (let ((case-fold-search t))
4124 (if (re-search-forward org-target-link-regexp limit t)
4125 (progn
4126 (add-text-properties (match-beginning 0) (match-end 0)
4127 (list 'mouse-face 'highlight
4128 'rear-nonsticky org-nonsticky-props
4129 'keymap org-mouse-map
4130 'help-echo "Radio target link"
4131 'org-linked-text t))
4132 t)))))
4134 (defun org-update-radio-target-regexp ()
4135 "Find all radio targets in this file and update the regular expression."
4136 (interactive)
4137 (when (memq 'radio org-activate-links)
4138 (setq org-target-link-regexp
4139 (org-make-target-link-regexp (org-all-targets 'radio)))
4140 (org-restart-font-lock)))
4142 (defun org-hide-wide-columns (limit)
4143 (let (s e)
4144 (setq s (text-property-any (point) (or limit (point-max))
4145 'org-cwidth t))
4146 (when s
4147 (setq e (next-single-property-change s 'org-cwidth))
4148 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4149 (goto-char e)
4150 t)))
4152 (defvar org-latex-and-specials-regexp nil
4153 "Regular expression for highlighting export special stuff.")
4154 (defvar org-match-substring-regexp)
4155 (defvar org-match-substring-with-braces-regexp)
4156 (defvar org-export-html-special-string-regexps)
4158 (defun org-compute-latex-and-specials-regexp ()
4159 "Compute regular expression for stuff treated specially by exporters."
4160 (if (not org-highlight-latex-fragments-and-specials)
4161 (org-set-local 'org-latex-and-specials-regexp nil)
4162 (require 'org-exp)
4163 (let*
4164 ((matchers (plist-get org-format-latex-options :matchers))
4165 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4166 org-latex-regexps)))
4167 (options (org-combine-plists (org-default-export-plist)
4168 (org-infile-export-plist)))
4169 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4170 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4171 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4172 (org-export-html-expand (plist-get options :expand-quoted-html))
4173 (org-export-with-special-strings (plist-get options :special-strings))
4174 (re-sub
4175 (cond
4176 ((equal org-export-with-sub-superscripts '{})
4177 (list org-match-substring-with-braces-regexp))
4178 (org-export-with-sub-superscripts
4179 (list org-match-substring-regexp))
4180 (t nil)))
4181 (re-latex
4182 (if org-export-with-LaTeX-fragments
4183 (mapcar (lambda (x) (nth 1 x)) latexs)))
4184 (re-macros
4185 (if org-export-with-TeX-macros
4186 (list (concat "\\\\"
4187 (regexp-opt
4188 (append (mapcar 'car org-html-entities)
4189 (if (boundp 'org-latex-entities)
4190 org-latex-entities nil))
4191 'words))) ; FIXME
4193 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4194 (re-special (if org-export-with-special-strings
4195 (mapcar (lambda (x) (car x))
4196 org-export-html-special-string-regexps)))
4197 (re-rest
4198 (delq nil
4199 (list
4200 (if org-export-html-expand "@<[^>\n]+>")
4201 ))))
4202 (org-set-local
4203 'org-latex-and-specials-regexp
4204 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4205 re-rest) "\\|")))))
4207 (defun org-do-latex-and-special-faces (limit)
4208 "Run through the buffer and add overlays to links."
4209 (when org-latex-and-specials-regexp
4210 (let (rtn d)
4211 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4212 limit t))
4213 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4214 'face))
4215 '(org-code org-verbatim underline)))
4216 (progn
4217 (setq rtn t
4218 d (cond ((member (char-after (1+ (match-beginning 0)))
4219 '(?_ ?^)) 1)
4220 (t 0)))
4221 (font-lock-prepend-text-property
4222 (+ d (match-beginning 0)) (match-end 0)
4223 'face 'org-latex-and-export-specials)
4224 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4225 '(font-lock-multiline t)))))
4226 rtn)))
4228 (defun org-restart-font-lock ()
4229 "Restart font-lock-mode, to force refontification."
4230 (when (and (boundp 'font-lock-mode) font-lock-mode)
4231 (font-lock-mode -1)
4232 (font-lock-mode 1)))
4234 (defun org-all-targets (&optional radio)
4235 "Return a list of all targets in this file.
4236 With optional argument RADIO, only find radio targets."
4237 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4238 rtn)
4239 (save-excursion
4240 (goto-char (point-min))
4241 (while (re-search-forward re nil t)
4242 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4243 rtn)))
4245 (defun org-make-target-link-regexp (targets)
4246 "Make regular expression matching all strings in TARGETS.
4247 The regular expression finds the targets also if there is a line break
4248 between words."
4249 (and targets
4250 (concat
4251 "\\<\\("
4252 (mapconcat
4253 (lambda (x)
4254 (while (string-match " +" x)
4255 (setq x (replace-match "\\s-+" t t x)))
4257 targets
4258 "\\|")
4259 "\\)\\>")))
4261 (defun org-activate-tags (limit)
4262 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4263 (progn
4264 (add-text-properties (match-beginning 1) (match-end 1)
4265 (list 'mouse-face 'highlight
4266 'rear-nonsticky org-nonsticky-props
4267 'keymap org-mouse-map))
4268 t)))
4270 (defun org-outline-level ()
4271 (save-excursion
4272 (looking-at outline-regexp)
4273 (if (match-beginning 1)
4274 (+ (org-get-string-indentation (match-string 1)) 1000)
4275 (1- (- (match-end 0) (match-beginning 0))))))
4277 (defvar org-font-lock-keywords nil)
4279 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4280 "Regular expression matching a property line.")
4282 (defvar org-font-lock-hook nil
4283 "Functions to be called for special font lock stuff.")
4285 (defun org-font-lock-hook (limit)
4286 (run-hook-with-args 'org-font-lock-hook limit))
4288 (defun org-set-font-lock-defaults ()
4289 (let* ((em org-fontify-emphasized-text)
4290 (lk org-activate-links)
4291 (org-font-lock-extra-keywords
4292 (list
4293 ;; Call the hook
4294 '(org-font-lock-hook)
4295 ;; Headlines
4296 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4297 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4298 ;; Table lines
4299 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4300 (1 'org-table t))
4301 ;; Table internals
4302 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4303 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4304 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4305 ;; Drawers
4306 (list org-drawer-regexp '(0 'org-special-keyword t))
4307 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4308 ;; Properties
4309 (list org-property-re
4310 '(1 'org-special-keyword t)
4311 '(3 'org-property-value t))
4312 (if org-format-transports-properties-p
4313 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4314 ;; Links
4315 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4316 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4317 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4318 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4319 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4320 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4321 (if (memq 'footnote lk) '(org-activate-footnote-links
4322 (2 'org-footnote t)))
4323 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4324 '(org-hide-wide-columns (0 nil append))
4325 ;; TODO lines
4326 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4327 '(1 (org-get-todo-face 1) t))
4328 ;; DONE
4329 (if org-fontify-done-headline
4330 (list (concat "^[*]+ +\\<\\("
4331 (mapconcat 'regexp-quote org-done-keywords "\\|")
4332 "\\)\\(.*\\)")
4333 '(2 'org-headline-done t))
4334 nil)
4335 ;; Priorities
4336 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
4337 ;; Tags
4338 '(org-font-lock-add-tag-faces)
4339 ;; Special keywords
4340 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4341 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4342 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4343 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4344 ;; Emphasis
4345 (if em
4346 (if (featurep 'xemacs)
4347 '(org-do-emphasis-faces (0 nil append))
4348 '(org-do-emphasis-faces)))
4349 ;; Checkboxes
4350 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4351 2 'bold prepend)
4352 (if org-provide-checkbox-statistics
4353 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4354 (0 (org-get-checkbox-statistics-face) t)))
4355 ;; Description list items
4356 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4357 2 'bold prepend)
4358 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4359 '(1 'org-archived prepend))
4360 ;; Specials
4361 '(org-do-latex-and-special-faces)
4362 ;; Code
4363 '(org-activate-code (1 'org-code t))
4364 ;; COMMENT
4365 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4366 "\\|" org-quote-string "\\)\\>")
4367 '(1 'org-special-keyword t))
4368 '("^#.*" (0 'font-lock-comment-face t))
4370 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4371 ;; Now set the full font-lock-keywords
4372 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4373 (org-set-local 'font-lock-defaults
4374 '(org-font-lock-keywords t nil nil backward-paragraph))
4375 (kill-local-variable 'font-lock-keywords) nil))
4377 (defvar org-m nil)
4378 (defvar org-l nil)
4379 (defvar org-f nil)
4380 (defun org-get-level-face (n)
4381 "Get the right face for match N in font-lock matching of headlines."
4382 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4383 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4384 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4385 (cond
4386 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4387 ((eq n 2) org-f)
4388 (t (if org-level-color-stars-only nil org-f))))
4390 (defun org-get-todo-face (kwd)
4391 "Get the right face for a TODO keyword KWD.
4392 If KWD is a number, get the corresponding match group."
4393 (if (numberp kwd) (setq kwd (match-string kwd)))
4394 (or (cdr (assoc kwd org-todo-keyword-faces))
4395 (and (member kwd org-done-keywords) 'org-done)
4396 'org-todo))
4398 (defun org-font-lock-add-tag-faces (limit)
4399 "Add the special tag faces."
4400 (when (and org-tag-faces org-tags-special-faces-re)
4401 (while (re-search-forward org-tags-special-faces-re limit t)
4402 (add-text-properties (match-beginning 1) (match-end 1)
4403 (list 'face (org-get-tag-face 1)
4404 'font-lock-fontified t))
4405 (backward-char 1))))
4407 (defun org-get-tag-face (kwd)
4408 "Get the right face for a TODO keyword KWD.
4409 If KWD is a number, get the corresponding match group."
4410 (if (numberp kwd) (setq kwd (match-string kwd)))
4411 (or (cdr (assoc kwd org-tag-faces))
4412 'org-tag))
4414 (defun org-unfontify-region (beg end &optional maybe_loudly)
4415 "Remove fontification and activation overlays from links."
4416 (font-lock-default-unfontify-region beg end)
4417 (let* ((buffer-undo-list t)
4418 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4419 (inhibit-modification-hooks t)
4420 deactivate-mark buffer-file-name buffer-file-truename)
4421 (remove-text-properties beg end
4422 '(mouse-face t keymap t org-linked-text t
4423 invisible t intangible t))))
4425 ;;;; Visibility cycling, including org-goto and indirect buffer
4427 ;;; Cycling
4429 (defvar org-cycle-global-status nil)
4430 (make-variable-buffer-local 'org-cycle-global-status)
4431 (defvar org-cycle-subtree-status nil)
4432 (make-variable-buffer-local 'org-cycle-subtree-status)
4434 ;;;###autoload
4435 (defun org-cycle (&optional arg)
4436 "Visibility cycling for Org-mode.
4438 - When this function is called with a prefix argument, rotate the entire
4439 buffer through 3 states (global cycling)
4440 1. OVERVIEW: Show only top-level headlines.
4441 2. CONTENTS: Show all headlines of all levels, but no body text.
4442 3. SHOW ALL: Show everything.
4443 When called with two C-u C-u prefixes, switch to the startup visibility,
4444 determined by the variable `org-startup-folded', and by any VISIBILITY
4445 properties in the buffer.
4446 When called with three C-u C-u C-u prefixed, show the entire buffer,
4447 including drawers.
4449 - When point is at the beginning of a headline, rotate the subtree started
4450 by this line through 3 different states (local cycling)
4451 1. FOLDED: Only the main headline is shown.
4452 2. CHILDREN: The main headline and the direct children are shown.
4453 From this state, you can move to one of the children
4454 and zoom in further.
4455 3. SUBTREE: Show the entire subtree, including body text.
4457 - When there is a numeric prefix, go up to a heading with level ARG, do
4458 a `show-subtree' and return to the previous cursor position. If ARG
4459 is negative, go up that many levels.
4461 - When point is not at the beginning of a headline, execute the global
4462 binding for TAB, which is re-indenting the line. See the option
4463 `org-cycle-emulate-tab' for details.
4465 - Special case: if point is at the beginning of the buffer and there is
4466 no headline in line 1, this function will act as if called with prefix arg.
4467 But only if also the variable `org-cycle-global-at-bob' is t."
4468 (interactive "P")
4469 (org-load-modules-maybe)
4470 (let* ((outline-regexp
4471 (if (and (org-mode-p) org-cycle-include-plain-lists)
4472 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4473 outline-regexp))
4474 (bob-special (and org-cycle-global-at-bob (bobp)
4475 (not (looking-at outline-regexp))))
4476 (org-cycle-hook
4477 (if bob-special
4478 (delq 'org-optimize-window-after-visibility-change
4479 (copy-sequence org-cycle-hook))
4480 org-cycle-hook))
4481 (pos (point)))
4483 (if (or bob-special (equal arg '(4)))
4484 ;; special case: use global cycling
4485 (setq arg t))
4487 (cond
4489 ((equal arg '(16))
4490 (org-set-startup-visibility)
4491 (message "Startup visibility, plus VISIBILITY properties"))
4493 ((equal arg '(64))
4494 (show-all)
4495 (message "Entire buffer visible, including drawers"))
4497 ((org-at-table-p 'any)
4498 ;; Enter the table or move to the next field in the table
4499 (or (org-table-recognize-table.el)
4500 (progn
4501 (if arg (org-table-edit-field t)
4502 (org-table-justify-field-maybe)
4503 (call-interactively 'org-table-next-field)))))
4505 ((eq arg t) ;; Global cycling
4507 (cond
4508 ((and (eq last-command this-command)
4509 (eq org-cycle-global-status 'overview))
4510 ;; We just created the overview - now do table of contents
4511 ;; This can be slow in very large buffers, so indicate action
4512 (message "CONTENTS...")
4513 (org-content)
4514 (message "CONTENTS...done")
4515 (setq org-cycle-global-status 'contents)
4516 (run-hook-with-args 'org-cycle-hook 'contents))
4518 ((and (eq last-command this-command)
4519 (eq org-cycle-global-status 'contents))
4520 ;; We just showed the table of contents - now show everything
4521 (show-all)
4522 (message "SHOW ALL")
4523 (setq org-cycle-global-status 'all)
4524 (run-hook-with-args 'org-cycle-hook 'all))
4527 ;; Default action: go to overview
4528 (org-overview)
4529 (message "OVERVIEW")
4530 (setq org-cycle-global-status 'overview)
4531 (run-hook-with-args 'org-cycle-hook 'overview))))
4533 ((and org-drawers org-drawer-regexp
4534 (save-excursion
4535 (beginning-of-line 1)
4536 (looking-at org-drawer-regexp)))
4537 ;; Toggle block visibility
4538 (org-flag-drawer
4539 (not (get-char-property (match-end 0) 'invisible))))
4541 ((integerp arg)
4542 ;; Show-subtree, ARG levels up from here.
4543 (save-excursion
4544 (org-back-to-heading)
4545 (outline-up-heading (if (< arg 0) (- arg)
4546 (- (funcall outline-level) arg)))
4547 (org-show-subtree)))
4549 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4550 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4551 ;; At a heading: rotate between three different views
4552 (org-back-to-heading)
4553 (let ((goal-column 0) eoh eol eos)
4554 ;; First, some boundaries
4555 (save-excursion
4556 (org-back-to-heading)
4557 (save-excursion
4558 (beginning-of-line 2)
4559 (while (and (not (eobp)) ;; this is like `next-line'
4560 (get-char-property (1- (point)) 'invisible))
4561 (beginning-of-line 2)) (setq eol (point)))
4562 (outline-end-of-heading) (setq eoh (point))
4563 (org-end-of-subtree t)
4564 (unless (eobp)
4565 (skip-chars-forward " \t\n")
4566 (beginning-of-line 1) ; in case this is an item
4568 (setq eos (1- (point))))
4569 ;; Find out what to do next and set `this-command'
4570 (cond
4571 ((= eos eoh)
4572 ;; Nothing is hidden behind this heading
4573 (message "EMPTY ENTRY")
4574 (setq org-cycle-subtree-status nil)
4575 (save-excursion
4576 (goto-char eos)
4577 (outline-next-heading)
4578 (if (org-invisible-p) (org-flag-heading nil))))
4579 ((or (>= eol eos)
4580 (not (string-match "\\S-" (buffer-substring eol eos))))
4581 ;; Entire subtree is hidden in one line: open it
4582 (org-show-entry)
4583 (show-children)
4584 (message "CHILDREN")
4585 (save-excursion
4586 (goto-char eos)
4587 (outline-next-heading)
4588 (if (org-invisible-p) (org-flag-heading nil)))
4589 (setq org-cycle-subtree-status 'children)
4590 (run-hook-with-args 'org-cycle-hook 'children))
4591 ((and (eq last-command this-command)
4592 (eq org-cycle-subtree-status 'children))
4593 ;; We just showed the children, now show everything.
4594 (org-show-subtree)
4595 (message "SUBTREE")
4596 (setq org-cycle-subtree-status 'subtree)
4597 (run-hook-with-args 'org-cycle-hook 'subtree))
4599 ;; Default action: hide the subtree.
4600 (hide-subtree)
4601 (message "FOLDED")
4602 (setq org-cycle-subtree-status 'folded)
4603 (run-hook-with-args 'org-cycle-hook 'folded)))))
4605 ;; TAB emulation and template completion
4606 (buffer-read-only (org-back-to-heading))
4608 ((org-try-structure-completion))
4610 ((org-try-cdlatex-tab))
4612 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4613 (or (not (bolp))
4614 (not (looking-at outline-regexp))))
4615 (call-interactively (global-key-binding "\t")))
4617 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4618 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4619 (or (and (eq org-cycle-emulate-tab 'white)
4620 (= (match-end 0) (point-at-eol)))
4621 (and (eq org-cycle-emulate-tab 'whitestart)
4622 (>= (match-end 0) pos))))
4624 (eq org-cycle-emulate-tab t))
4625 (call-interactively (global-key-binding "\t")))
4627 (t (save-excursion
4628 (org-back-to-heading)
4629 (org-cycle))))))
4631 ;;;###autoload
4632 (defun org-global-cycle (&optional arg)
4633 "Cycle the global visibility. For details see `org-cycle'.
4634 With C-u prefix arg, switch to startup visibility.
4635 With a numeric prefix, show all headlines up to that level."
4636 (interactive "P")
4637 (let ((org-cycle-include-plain-lists
4638 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4639 (cond
4640 ((integerp arg)
4641 (show-all)
4642 (hide-sublevels arg)
4643 (setq org-cycle-global-status 'contents))
4644 ((equal arg '(4))
4645 (org-set-startup-visibility)
4646 (message "Startup visibility, plus VISIBILITY properties."))
4648 (org-cycle '(4))))))
4650 (defun org-set-startup-visibility ()
4651 "Set the visibility required by startup options and properties."
4652 (cond
4653 ((eq org-startup-folded t)
4654 (org-cycle '(4)))
4655 ((eq org-startup-folded 'content)
4656 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4657 (org-cycle '(4)) (org-cycle '(4)))))
4658 (org-set-visibility-according-to-property 'no-cleanup)
4659 (org-cycle-hide-archived-subtrees 'all)
4660 (org-cycle-hide-drawers 'all)
4661 (org-cycle-show-empty-lines 'all))
4663 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4664 "Switch subtree visibilities according to :VISIBILITY: property."
4665 (interactive)
4666 (let (org-show-entry-below state)
4667 (save-excursion
4668 (goto-char (point-min))
4669 (while (re-search-forward
4670 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4671 nil t)
4672 (setq state (match-string 1))
4673 (save-excursion
4674 (org-back-to-heading t)
4675 (hide-subtree)
4676 (org-reveal)
4677 (cond
4678 ((equal state '("fold" "folded"))
4679 (hide-subtree))
4680 ((equal state "children")
4681 (org-show-hidden-entry)
4682 (show-children))
4683 ((equal state "content")
4684 (save-excursion
4685 (save-restriction
4686 (org-narrow-to-subtree)
4687 (org-content))))
4688 ((member state '("all" "showall"))
4689 (show-subtree)))))
4690 (unless no-cleanup
4691 (org-cycle-hide-archived-subtrees 'all)
4692 (org-cycle-hide-drawers 'all)
4693 (org-cycle-show-empty-lines 'all)))))
4695 (defun org-overview ()
4696 "Switch to overview mode, showing only top-level headlines.
4697 Really, this shows all headlines with level equal or greater than the level
4698 of the first headline in the buffer. This is important, because if the
4699 first headline is not level one, then (hide-sublevels 1) gives confusing
4700 results."
4701 (interactive)
4702 (let ((level (save-excursion
4703 (goto-char (point-min))
4704 (if (re-search-forward (concat "^" outline-regexp) nil t)
4705 (progn
4706 (goto-char (match-beginning 0))
4707 (funcall outline-level))))))
4708 (and level (hide-sublevels level))))
4710 (defun org-content (&optional arg)
4711 "Show all headlines in the buffer, like a table of contents.
4712 With numerical argument N, show content up to level N."
4713 (interactive "P")
4714 (save-excursion
4715 ;; Visit all headings and show their offspring
4716 (and (integerp arg) (org-overview))
4717 (goto-char (point-max))
4718 (catch 'exit
4719 (while (and (progn (condition-case nil
4720 (outline-previous-visible-heading 1)
4721 (error (goto-char (point-min))))
4723 (looking-at outline-regexp))
4724 (if (integerp arg)
4725 (show-children (1- arg))
4726 (show-branches))
4727 (if (bobp) (throw 'exit nil))))))
4730 (defun org-optimize-window-after-visibility-change (state)
4731 "Adjust the window after a change in outline visibility.
4732 This function is the default value of the hook `org-cycle-hook'."
4733 (when (get-buffer-window (current-buffer))
4734 (cond
4735 ((eq state 'content) nil)
4736 ((eq state 'all) nil)
4737 ((eq state 'folded) nil)
4738 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4739 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4741 (defun org-compact-display-after-subtree-move ()
4742 "Show a compacter version of the tree of the entry's parent."
4743 (save-excursion
4744 (if (org-up-heading-safe)
4745 (progn
4746 (hide-subtree)
4747 (show-entry)
4748 (show-children)
4749 (org-cycle-show-empty-lines 'children)
4750 (org-cycle-hide-drawers 'children))
4751 (org-overview))))
4753 (defun org-cycle-show-empty-lines (state)
4754 "Show empty lines above all visible headlines.
4755 The region to be covered depends on STATE when called through
4756 `org-cycle-hook'. Lisp program can use t for STATE to get the
4757 entire buffer covered. Note that an empty line is only shown if there
4758 are at least `org-cycle-separator-lines' empty lines before the headline."
4759 (when (> org-cycle-separator-lines 0)
4760 (save-excursion
4761 (let* ((n org-cycle-separator-lines)
4762 (re (cond
4763 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4764 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4765 (t (let ((ns (number-to-string (- n 2))))
4766 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4767 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4768 beg end)
4769 (cond
4770 ((memq state '(overview contents t))
4771 (setq beg (point-min) end (point-max)))
4772 ((memq state '(children folded))
4773 (setq beg (point) end (progn (org-end-of-subtree t t)
4774 (beginning-of-line 2)
4775 (point)))))
4776 (when beg
4777 (goto-char beg)
4778 (while (re-search-forward re end t)
4779 (if (not (get-char-property (match-end 1) 'invisible))
4780 (outline-flag-region
4781 (match-beginning 1) (match-end 1) nil)))))))
4782 ;; Never hide empty lines at the end of the file.
4783 (save-excursion
4784 (goto-char (point-max))
4785 (outline-previous-heading)
4786 (outline-end-of-heading)
4787 (if (and (looking-at "[ \t\n]+")
4788 (= (match-end 0) (point-max)))
4789 (outline-flag-region (point) (match-end 0) nil))))
4791 (defun org-show-empty-lines-in-parent ()
4792 "Move to the parent and re-show empty lines before visible headlines."
4793 (save-excursion
4794 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4795 (org-cycle-show-empty-lines context))))
4797 (defun org-cycle-hide-drawers (state)
4798 "Re-hide all drawers after a visibility state change."
4799 (when (and (org-mode-p)
4800 (not (memq state '(overview folded))))
4801 (save-excursion
4802 (let* ((globalp (memq state '(contents all)))
4803 (beg (if globalp (point-min) (point)))
4804 (end (if globalp (point-max) (org-end-of-subtree t))))
4805 (goto-char beg)
4806 (while (re-search-forward org-drawer-regexp end t)
4807 (org-flag-drawer t))))))
4809 (defun org-flag-drawer (flag)
4810 (save-excursion
4811 (beginning-of-line 1)
4812 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4813 (let ((b (match-end 0))
4814 (outline-regexp org-outline-regexp))
4815 (if (re-search-forward
4816 "^[ \t]*:END:"
4817 (save-excursion (outline-next-heading) (point)) t)
4818 (outline-flag-region b (point-at-eol) flag)
4819 (error ":END: line missing"))))))
4821 (defun org-subtree-end-visible-p ()
4822 "Is the end of the current subtree visible?"
4823 (pos-visible-in-window-p
4824 (save-excursion (org-end-of-subtree t) (point))))
4826 (defun org-first-headline-recenter (&optional N)
4827 "Move cursor to the first headline and recenter the headline.
4828 Optional argument N means, put the headline into the Nth line of the window."
4829 (goto-char (point-min))
4830 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4831 (beginning-of-line)
4832 (recenter (prefix-numeric-value N))))
4834 ;;; Org-goto
4836 (defvar org-goto-window-configuration nil)
4837 (defvar org-goto-marker nil)
4838 (defvar org-goto-map
4839 (let ((map (make-sparse-keymap)))
4840 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4841 (while (setq cmd (pop cmds))
4842 (substitute-key-definition cmd cmd map global-map)))
4843 (suppress-keymap map)
4844 (org-defkey map "\C-m" 'org-goto-ret)
4845 (org-defkey map [(return)] 'org-goto-ret)
4846 (org-defkey map [(left)] 'org-goto-left)
4847 (org-defkey map [(right)] 'org-goto-right)
4848 (org-defkey map [(control ?g)] 'org-goto-quit)
4849 (org-defkey map "\C-i" 'org-cycle)
4850 (org-defkey map [(tab)] 'org-cycle)
4851 (org-defkey map [(down)] 'outline-next-visible-heading)
4852 (org-defkey map [(up)] 'outline-previous-visible-heading)
4853 (if org-goto-auto-isearch
4854 (if (fboundp 'define-key-after)
4855 (define-key-after map [t] 'org-goto-local-auto-isearch)
4856 nil)
4857 (org-defkey map "q" 'org-goto-quit)
4858 (org-defkey map "n" 'outline-next-visible-heading)
4859 (org-defkey map "p" 'outline-previous-visible-heading)
4860 (org-defkey map "f" 'outline-forward-same-level)
4861 (org-defkey map "b" 'outline-backward-same-level)
4862 (org-defkey map "u" 'outline-up-heading))
4863 (org-defkey map "/" 'org-occur)
4864 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4865 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4866 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4867 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4868 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4869 map))
4871 (defconst org-goto-help
4872 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4873 RET=jump to location [Q]uit and return to previous location
4874 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4876 (defvar org-goto-start-pos) ; dynamically scoped parameter
4878 ;; FIXME: Docstring doe not mention both interfaces
4879 (defun org-goto (&optional alternative-interface)
4880 "Look up a different location in the current file, keeping current visibility.
4882 When you want look-up or go to a different location in a document, the
4883 fastest way is often to fold the entire buffer and then dive into the tree.
4884 This method has the disadvantage, that the previous location will be folded,
4885 which may not be what you want.
4887 This command works around this by showing a copy of the current buffer
4888 in an indirect buffer, in overview mode. You can dive into the tree in
4889 that copy, use org-occur and incremental search to find a location.
4890 When pressing RET or `Q', the command returns to the original buffer in
4891 which the visibility is still unchanged. After RET is will also jump to
4892 the location selected in the indirect buffer and expose the
4893 the headline hierarchy above."
4894 (interactive "P")
4895 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
4896 (org-refile-use-outline-path t)
4897 (interface
4898 (if (not alternative-interface)
4899 org-goto-interface
4900 (if (eq org-goto-interface 'outline)
4901 'outline-path-completion
4902 'outline)))
4903 (org-goto-start-pos (point))
4904 (selected-point
4905 (if (eq interface 'outline)
4906 (car (org-get-location (current-buffer) org-goto-help))
4907 (nth 3 (org-refile-get-location "Goto: ")))))
4908 (if selected-point
4909 (progn
4910 (org-mark-ring-push org-goto-start-pos)
4911 (goto-char selected-point)
4912 (if (or (org-invisible-p) (org-invisible-p2))
4913 (org-show-context 'org-goto)))
4914 (message "Quit"))))
4916 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4917 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4918 (defvar org-goto-local-auto-isearch-map) ; defined below
4920 (defun org-get-location (buf help)
4921 "Let the user select a location in the Org-mode buffer BUF.
4922 This function uses a recursive edit. It returns the selected position
4923 or nil."
4924 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4925 (isearch-hide-immediately nil)
4926 (isearch-search-fun-function
4927 (lambda () 'org-goto-local-search-headings))
4928 (org-goto-selected-point org-goto-exit-command))
4929 (save-excursion
4930 (save-window-excursion
4931 (delete-other-windows)
4932 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4933 (switch-to-buffer
4934 (condition-case nil
4935 (make-indirect-buffer (current-buffer) "*org-goto*")
4936 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4937 (with-output-to-temp-buffer "*Help*"
4938 (princ help))
4939 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4940 (setq buffer-read-only nil)
4941 (let ((org-startup-truncated t)
4942 (org-startup-folded nil)
4943 (org-startup-align-all-tables nil))
4944 (org-mode)
4945 (org-overview))
4946 (setq buffer-read-only t)
4947 (if (and (boundp 'org-goto-start-pos)
4948 (integer-or-marker-p org-goto-start-pos))
4949 (let ((org-show-hierarchy-above t)
4950 (org-show-siblings t)
4951 (org-show-following-heading t))
4952 (goto-char org-goto-start-pos)
4953 (and (org-invisible-p) (org-show-context)))
4954 (goto-char (point-min)))
4955 (let (org-special-ctrl-a/e) (org-beginning-of-line))
4956 (message "Select location and press RET")
4957 (use-local-map org-goto-map)
4958 (recursive-edit)
4960 (kill-buffer "*org-goto*")
4961 (cons org-goto-selected-point org-goto-exit-command)))
4963 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4964 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4965 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4966 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4968 (defun org-goto-local-search-headings (string bound noerror)
4969 "Search and make sure that any matches are in headlines."
4970 (catch 'return
4971 (while (if isearch-forward
4972 (search-forward string bound noerror)
4973 (search-backward string bound noerror))
4974 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4975 (and (member :headline context)
4976 (not (member :tags context))))
4977 (throw 'return (point))))))
4979 (defun org-goto-local-auto-isearch ()
4980 "Start isearch."
4981 (interactive)
4982 (goto-char (point-min))
4983 (let ((keys (this-command-keys)))
4984 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4985 (isearch-mode t)
4986 (isearch-process-search-char (string-to-char keys)))))
4988 (defun org-goto-ret (&optional arg)
4989 "Finish `org-goto' by going to the new location."
4990 (interactive "P")
4991 (setq org-goto-selected-point (point)
4992 org-goto-exit-command 'return)
4993 (throw 'exit nil))
4995 (defun org-goto-left ()
4996 "Finish `org-goto' by going to the new location."
4997 (interactive)
4998 (if (org-on-heading-p)
4999 (progn
5000 (beginning-of-line 1)
5001 (setq org-goto-selected-point (point)
5002 org-goto-exit-command 'left)
5003 (throw 'exit nil))
5004 (error "Not on a heading")))
5006 (defun org-goto-right ()
5007 "Finish `org-goto' by going to the new location."
5008 (interactive)
5009 (if (org-on-heading-p)
5010 (progn
5011 (setq org-goto-selected-point (point)
5012 org-goto-exit-command 'right)
5013 (throw 'exit nil))
5014 (error "Not on a heading")))
5016 (defun org-goto-quit ()
5017 "Finish `org-goto' without cursor motion."
5018 (interactive)
5019 (setq org-goto-selected-point nil)
5020 (setq org-goto-exit-command 'quit)
5021 (throw 'exit nil))
5023 ;;; Indirect buffer display of subtrees
5025 (defvar org-indirect-dedicated-frame nil
5026 "This is the frame being used for indirect tree display.")
5027 (defvar org-last-indirect-buffer nil)
5029 (defun org-tree-to-indirect-buffer (&optional arg)
5030 "Create indirect buffer and narrow it to current subtree.
5031 With numerical prefix ARG, go up to this level and then take that tree.
5032 If ARG is negative, go up that many levels.
5033 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5034 indirect buffer previously made with this command, to avoid proliferation of
5035 indirect buffers. However, when you call the command with a `C-u' prefix, or
5036 when `org-indirect-buffer-display' is `new-frame', the last buffer
5037 is kept so that you can work with several indirect buffers at the same time.
5038 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5039 requests that a new frame be made for the new buffer, so that the dedicated
5040 frame is not changed."
5041 (interactive "P")
5042 (let ((cbuf (current-buffer))
5043 (cwin (selected-window))
5044 (pos (point))
5045 beg end level heading ibuf)
5046 (save-excursion
5047 (org-back-to-heading t)
5048 (when (numberp arg)
5049 (setq level (org-outline-level))
5050 (if (< arg 0) (setq arg (+ level arg)))
5051 (while (> (setq level (org-outline-level)) arg)
5052 (outline-up-heading 1 t)))
5053 (setq beg (point)
5054 heading (org-get-heading))
5055 (org-end-of-subtree t) (setq end (point)))
5056 (if (and (buffer-live-p org-last-indirect-buffer)
5057 (not (eq org-indirect-buffer-display 'new-frame))
5058 (not arg))
5059 (kill-buffer org-last-indirect-buffer))
5060 (setq ibuf (org-get-indirect-buffer cbuf)
5061 org-last-indirect-buffer ibuf)
5062 (cond
5063 ((or (eq org-indirect-buffer-display 'new-frame)
5064 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5065 (select-frame (make-frame))
5066 (delete-other-windows)
5067 (switch-to-buffer ibuf)
5068 (org-set-frame-title heading))
5069 ((eq org-indirect-buffer-display 'dedicated-frame)
5070 (raise-frame
5071 (select-frame (or (and org-indirect-dedicated-frame
5072 (frame-live-p org-indirect-dedicated-frame)
5073 org-indirect-dedicated-frame)
5074 (setq org-indirect-dedicated-frame (make-frame)))))
5075 (delete-other-windows)
5076 (switch-to-buffer ibuf)
5077 (org-set-frame-title (concat "Indirect: " heading)))
5078 ((eq org-indirect-buffer-display 'current-window)
5079 (switch-to-buffer ibuf))
5080 ((eq org-indirect-buffer-display 'other-window)
5081 (pop-to-buffer ibuf))
5082 (t (error "Invalid value.")))
5083 (if (featurep 'xemacs)
5084 (save-excursion (org-mode) (turn-on-font-lock)))
5085 (narrow-to-region beg end)
5086 (show-all)
5087 (goto-char pos)
5088 (and (window-live-p cwin) (select-window cwin))))
5090 (defun org-get-indirect-buffer (&optional buffer)
5091 (setq buffer (or buffer (current-buffer)))
5092 (let ((n 1) (base (buffer-name buffer)) bname)
5093 (while (buffer-live-p
5094 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5095 (setq n (1+ n)))
5096 (condition-case nil
5097 (make-indirect-buffer buffer bname 'clone)
5098 (error (make-indirect-buffer buffer bname)))))
5100 (defun org-set-frame-title (title)
5101 "Set the title of the current frame to the string TITLE."
5102 ;; FIXME: how to name a single frame in XEmacs???
5103 (unless (featurep 'xemacs)
5104 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5106 ;;;; Structure editing
5108 ;;; Inserting headlines
5110 (defun org-previous-line-empty-p ()
5111 (save-excursion
5112 (and (not (bobp))
5113 (or (beginning-of-line 0) t)
5114 (save-match-data
5115 (looking-at "[ \t]*$")))))
5117 (defun org-insert-heading (&optional force-heading)
5118 "Insert a new heading or item with same depth at point.
5119 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5120 If point is at the beginning of a headline, insert a sibling before the
5121 current headline. If point is not at the beginning, do not split the line,
5122 but create the new headline after the current line."
5123 (interactive "P")
5124 (if (= (buffer-size) 0)
5125 (insert "\n* ")
5126 (when (or force-heading (not (org-insert-item)))
5127 (let* ((empty-line-p nil)
5128 (head (save-excursion
5129 (condition-case nil
5130 (progn
5131 (org-back-to-heading)
5132 (setq empty-line-p (org-previous-line-empty-p))
5133 (match-string 0))
5134 (error "*"))))
5135 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5136 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5137 pos hide-previous previous-pos)
5138 (cond
5139 ((and (org-on-heading-p) (bolp)
5140 (or (bobp)
5141 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5142 ;; insert before the current line
5143 (open-line (if blank 2 1)))
5144 ((and (bolp)
5145 (or (bobp)
5146 (save-excursion
5147 (backward-char 1) (not (org-invisible-p)))))
5148 ;; insert right here
5149 nil)
5151 ;; somewhere in the line
5152 (save-excursion
5153 (setq previous-pos (point-at-bol))
5154 (end-of-line)
5155 (setq hide-previous (org-invisible-p)))
5156 (and org-insert-heading-respect-content (org-show-subtree))
5157 (let ((split
5158 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5159 (save-excursion
5160 (let ((p (point)))
5161 (goto-char (point-at-bol))
5162 (and (looking-at org-complex-heading-regexp)
5163 (> p (match-beginning 4)))))))
5164 tags pos)
5165 (cond
5166 (org-insert-heading-respect-content
5167 (org-end-of-subtree nil t)
5168 (or (bolp) (newline))
5169 (or (org-previous-line-empty-p)
5170 (and blank (newline)))
5171 (open-line 1))
5172 ((org-on-heading-p)
5173 (when hide-previous
5174 (show-children)
5175 (org-show-entry))
5176 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5177 (setq tags (and (match-end 2) (match-string 2)))
5178 (and (match-end 1)
5179 (delete-region (match-beginning 1) (match-end 1)))
5180 (setq pos (point-at-bol))
5181 (or split (end-of-line 1))
5182 (delete-horizontal-space)
5183 (newline (if blank 2 1))
5184 (when tags
5185 (save-excursion
5186 (goto-char pos)
5187 (end-of-line 1)
5188 (insert " " tags)
5189 (org-set-tags nil 'align))))
5191 (or split (end-of-line 1))
5192 (newline (if blank 2 1)))))))
5193 (insert head) (just-one-space)
5194 (setq pos (point))
5195 (end-of-line 1)
5196 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5197 (when (and org-insert-heading-respect-content hide-previous)
5198 (save-excursion
5199 (goto-char previous-pos)
5200 (hide-subtree)))
5201 (run-hooks 'org-insert-heading-hook)))))
5203 (defun org-get-heading (&optional no-tags)
5204 "Return the heading of the current entry, without the stars."
5205 (save-excursion
5206 (org-back-to-heading t)
5207 (if (looking-at
5208 (if no-tags
5209 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5210 "\\*+[ \t]+\\([^\r\n]*\\)"))
5211 (match-string 1) "")))
5213 (defun org-heading-components ()
5214 "Return the components of the current heading.
5215 This is a list with the following elements:
5216 - the level as an integer
5217 - the reduced level, different if `org-odd-levels-only' is set.
5218 - the TODO keyword, or nil
5219 - the priority character, like ?A, or nil if no priority is given
5220 - the headline text itself, or the tags string if no headline text
5221 - the tags string, or nil."
5222 (save-excursion
5223 (org-back-to-heading t)
5224 (if (looking-at org-complex-heading-regexp)
5225 (list (length (match-string 1))
5226 (org-reduced-level (length (match-string 1)))
5227 (org-match-string-no-properties 2)
5228 (and (match-end 3) (aref (match-string 3) 2))
5229 (org-match-string-no-properties 4)
5230 (org-match-string-no-properties 5)))))
5232 (defun org-insert-heading-after-current ()
5233 "Insert a new heading with same level as current, after current subtree."
5234 (interactive)
5235 (org-back-to-heading)
5236 (org-insert-heading)
5237 (org-move-subtree-down)
5238 (end-of-line 1))
5240 (defun org-insert-heading-respect-content ()
5241 (interactive)
5242 (let ((org-insert-heading-respect-content t))
5243 (org-insert-heading t)))
5245 (defun org-insert-todo-heading-respect-content (&optional force-state)
5246 (interactive "P")
5247 (let ((org-insert-heading-respect-content t))
5248 (org-insert-todo-heading force-state t)))
5250 (defun org-insert-todo-heading (arg &optional force-heading)
5251 "Insert a new heading with the same level and TODO state as current heading.
5252 If the heading has no TODO state, or if the state is DONE, use the first
5253 state (TODO by default). Also with prefix arg, force first state."
5254 (interactive "P")
5255 (when (or force-heading (not (org-insert-item 'checkbox)))
5256 (org-insert-heading force-heading)
5257 (save-excursion
5258 (org-back-to-heading)
5259 (outline-previous-heading)
5260 (looking-at org-todo-line-regexp))
5261 (let*
5262 ((new-mark-x
5263 (if (or arg
5264 (not (match-beginning 2))
5265 (member (match-string 2) org-done-keywords))
5266 (car org-todo-keywords-1)
5267 (match-string 2)))
5268 (new-mark
5270 (run-hook-with-args-until-success
5271 'org-todo-get-default-hook new-mark-x nil)
5272 new-mark-x)))
5273 (insert new-mark " "))
5274 (when org-provide-todo-statistics
5275 (org-update-parent-todo-statistics))))
5277 (defun org-insert-subheading (arg)
5278 "Insert a new subheading and demote it.
5279 Works for outline headings and for plain lists alike."
5280 (interactive "P")
5281 (org-insert-heading arg)
5282 (cond
5283 ((org-on-heading-p) (org-do-demote))
5284 ((org-at-item-p) (org-indent-item 1))))
5286 (defun org-insert-todo-subheading (arg)
5287 "Insert a new subheading with TODO keyword or checkbox and demote it.
5288 Works for outline headings and for plain lists alike."
5289 (interactive "P")
5290 (org-insert-todo-heading arg)
5291 (cond
5292 ((org-on-heading-p) (org-do-demote))
5293 ((org-at-item-p) (org-indent-item 1))))
5295 ;;; Promotion and Demotion
5297 (defun org-promote-subtree ()
5298 "Promote the entire subtree.
5299 See also `org-promote'."
5300 (interactive)
5301 (save-excursion
5302 (org-map-tree 'org-promote))
5303 (org-fix-position-after-promote))
5305 (defun org-demote-subtree ()
5306 "Demote the entire subtree. See `org-demote'.
5307 See also `org-promote'."
5308 (interactive)
5309 (save-excursion
5310 (org-map-tree 'org-demote))
5311 (org-fix-position-after-promote))
5314 (defun org-do-promote ()
5315 "Promote the current heading higher up the tree.
5316 If the region is active in `transient-mark-mode', promote all headings
5317 in the region."
5318 (interactive)
5319 (save-excursion
5320 (if (org-region-active-p)
5321 (org-map-region 'org-promote (region-beginning) (region-end))
5322 (org-promote)))
5323 (org-fix-position-after-promote))
5325 (defun org-do-demote ()
5326 "Demote the current heading lower down the tree.
5327 If the region is active in `transient-mark-mode', demote all headings
5328 in the region."
5329 (interactive)
5330 (save-excursion
5331 (if (org-region-active-p)
5332 (org-map-region 'org-demote (region-beginning) (region-end))
5333 (org-demote)))
5334 (org-fix-position-after-promote))
5336 (defun org-fix-position-after-promote ()
5337 "Make sure that after pro/demotion cursor position is right."
5338 (let ((pos (point)))
5339 (when (save-excursion
5340 (beginning-of-line 1)
5341 (looking-at org-todo-line-regexp)
5342 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5343 (cond ((eobp) (insert " "))
5344 ((eolp) (insert " "))
5345 ((equal (char-after) ?\ ) (forward-char 1))))))
5347 (defun org-reduced-level (l)
5348 "Compute the effective level of a heading.
5349 This takes into account the setting of `org-odd-levels-only'."
5350 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5352 (defun org-get-valid-level (level &optional change)
5353 "Rectify a level change under the influence of `org-odd-levels-only'
5354 LEVEL is a current level, CHANGE is by how much the level should be
5355 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5356 even level numbers will become the next higher odd number."
5357 (if org-odd-levels-only
5358 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5359 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5360 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5361 (max 1 (+ level change))))
5363 (if (boundp 'define-obsolete-function-alias)
5364 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5365 (define-obsolete-function-alias 'org-get-legal-level
5366 'org-get-valid-level)
5367 (define-obsolete-function-alias 'org-get-legal-level
5368 'org-get-valid-level "23.1")))
5370 (defun org-promote ()
5371 "Promote the current heading higher up the tree.
5372 If the region is active in `transient-mark-mode', promote all headings
5373 in the region."
5374 (org-back-to-heading t)
5375 (let* ((level (save-match-data (funcall outline-level)))
5376 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5377 (diff (abs (- level (length up-head) -1))))
5378 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5379 (replace-match up-head nil t)
5380 ;; Fixup tag positioning
5381 (and org-auto-align-tags (org-set-tags nil t))
5382 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5384 (defun org-demote ()
5385 "Demote the current heading lower down the tree.
5386 If the region is active in `transient-mark-mode', demote all headings
5387 in the region."
5388 (org-back-to-heading t)
5389 (let* ((level (save-match-data (funcall outline-level)))
5390 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5391 (diff (abs (- level (length down-head) -1))))
5392 (replace-match down-head nil t)
5393 ;; Fixup tag positioning
5394 (and org-auto-align-tags (org-set-tags nil t))
5395 (if org-adapt-indentation (org-fixup-indentation diff))))
5397 (defun org-map-tree (fun)
5398 "Call FUN for every heading underneath the current one."
5399 (org-back-to-heading)
5400 (let ((level (funcall outline-level)))
5401 (save-excursion
5402 (funcall fun)
5403 (while (and (progn
5404 (outline-next-heading)
5405 (> (funcall outline-level) level))
5406 (not (eobp)))
5407 (funcall fun)))))
5409 (defun org-map-region (fun beg end)
5410 "Call FUN for every heading between BEG and END."
5411 (let ((org-ignore-region t))
5412 (save-excursion
5413 (setq end (copy-marker end))
5414 (goto-char beg)
5415 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5416 (< (point) end))
5417 (funcall fun))
5418 (while (and (progn
5419 (outline-next-heading)
5420 (< (point) end))
5421 (not (eobp)))
5422 (funcall fun)))))
5424 (defun org-fixup-indentation (diff)
5425 "Change the indentation in the current entry by DIFF
5426 However, if any line in the current entry has no indentation, or if it
5427 would end up with no indentation after the change, nothing at all is done."
5428 (save-excursion
5429 (let ((end (save-excursion (outline-next-heading)
5430 (point-marker)))
5431 (prohibit (if (> diff 0)
5432 "^\\S-"
5433 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5434 col)
5435 (unless (save-excursion (end-of-line 1)
5436 (re-search-forward prohibit end t))
5437 (while (and (< (point) end)
5438 (re-search-forward "^[ \t]+" end t))
5439 (goto-char (match-end 0))
5440 (setq col (current-column))
5441 (if (< diff 0) (replace-match ""))
5442 (org-indent-to-column (+ diff col))))
5443 (move-marker end nil))))
5445 (defun org-convert-to-odd-levels ()
5446 "Convert an org-mode file with all levels allowed to one with odd levels.
5447 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5448 level 5 etc."
5449 (interactive)
5450 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5451 (let ((org-odd-levels-only nil) n)
5452 (save-excursion
5453 (goto-char (point-min))
5454 (while (re-search-forward "^\\*\\*+ " nil t)
5455 (setq n (- (length (match-string 0)) 2))
5456 (while (>= (setq n (1- n)) 0)
5457 (org-demote))
5458 (end-of-line 1))))))
5461 (defun org-convert-to-oddeven-levels ()
5462 "Convert an org-mode file with only odd levels to one with odd and even levels.
5463 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5464 section with an even level, conversion would destroy the structure of the file. An error
5465 is signaled in this case."
5466 (interactive)
5467 (goto-char (point-min))
5468 ;; First check if there are no even levels
5469 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5470 (org-show-context t)
5471 (error "Not all levels are odd in this file. Conversion not possible."))
5472 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5473 (let ((org-odd-levels-only nil) n)
5474 (save-excursion
5475 (goto-char (point-min))
5476 (while (re-search-forward "^\\*\\*+ " nil t)
5477 (setq n (/ (1- (length (match-string 0))) 2))
5478 (while (>= (setq n (1- n)) 0)
5479 (org-promote))
5480 (end-of-line 1))))))
5482 (defun org-tr-level (n)
5483 "Make N odd if required."
5484 (if org-odd-levels-only (1+ (/ n 2)) n))
5486 ;;; Vertical tree motion, cutting and pasting of subtrees
5488 (defun org-move-subtree-up (&optional arg)
5489 "Move the current subtree up past ARG headlines of the same level."
5490 (interactive "p")
5491 (org-move-subtree-down (- (prefix-numeric-value arg))))
5493 (defun org-move-subtree-down (&optional arg)
5494 "Move the current subtree down past ARG headlines of the same level."
5495 (interactive "p")
5496 (setq arg (prefix-numeric-value arg))
5497 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5498 'outline-get-last-sibling))
5499 (ins-point (make-marker))
5500 (cnt (abs arg))
5501 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5502 ;; Select the tree
5503 (org-back-to-heading)
5504 (setq beg0 (point))
5505 (save-excursion
5506 (setq ne-beg (org-back-over-empty-lines))
5507 (setq beg (point)))
5508 (save-match-data
5509 (save-excursion (outline-end-of-heading)
5510 (setq folded (org-invisible-p)))
5511 (outline-end-of-subtree))
5512 (outline-next-heading)
5513 (setq ne-end (org-back-over-empty-lines))
5514 (setq end (point))
5515 (goto-char beg0)
5516 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5517 ;; include less whitespace
5518 (save-excursion
5519 (goto-char beg)
5520 (forward-line (- ne-beg ne-end))
5521 (setq beg (point))))
5522 ;; Find insertion point, with error handling
5523 (while (> cnt 0)
5524 (or (and (funcall movfunc) (looking-at outline-regexp))
5525 (progn (goto-char beg0)
5526 (error "Cannot move past superior level or buffer limit")))
5527 (setq cnt (1- cnt)))
5528 (if (> arg 0)
5529 ;; Moving forward - still need to move over subtree
5530 (progn (org-end-of-subtree t t)
5531 (save-excursion
5532 (org-back-over-empty-lines)
5533 (or (bolp) (newline)))))
5534 (setq ne-ins (org-back-over-empty-lines))
5535 (move-marker ins-point (point))
5536 (setq txt (buffer-substring beg end))
5537 (org-save-markers-in-region beg end)
5538 (delete-region beg end)
5539 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5540 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5541 (let ((bbb (point)))
5542 (insert-before-markers txt)
5543 (org-reinstall-markers-in-region bbb)
5544 (move-marker ins-point bbb))
5545 (or (bolp) (insert "\n"))
5546 (setq ins-end (point))
5547 (goto-char ins-point)
5548 (org-skip-whitespace)
5549 (when (and (< arg 0)
5550 (org-first-sibling-p)
5551 (> ne-ins ne-beg))
5552 ;; Move whitespace back to beginning
5553 (save-excursion
5554 (goto-char ins-end)
5555 (let ((kill-whole-line t))
5556 (kill-line (- ne-ins ne-beg)) (point)))
5557 (insert (make-string (- ne-ins ne-beg) ?\n)))
5558 (move-marker ins-point nil)
5559 (org-compact-display-after-subtree-move)
5560 (org-show-empty-lines-in-parent)
5561 (unless folded
5562 (org-show-entry)
5563 (show-children)
5564 (org-cycle-hide-drawers 'children))))
5566 (defvar org-subtree-clip ""
5567 "Clipboard for cut and paste of subtrees.
5568 This is actually only a copy of the kill, because we use the normal kill
5569 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5571 (defvar org-subtree-clip-folded nil
5572 "Was the last copied subtree folded?
5573 This is used to fold the tree back after pasting.")
5575 (defun org-cut-subtree (&optional n)
5576 "Cut the current subtree into the clipboard.
5577 With prefix arg N, cut this many sequential subtrees.
5578 This is a short-hand for marking the subtree and then cutting it."
5579 (interactive "p")
5580 (org-copy-subtree n 'cut))
5582 (defun org-copy-subtree (&optional n cut force-store-markers)
5583 "Cut the current subtree into the clipboard.
5584 With prefix arg N, cut this many sequential subtrees.
5585 This is a short-hand for marking the subtree and then copying it.
5586 If CUT is non-nil, actually cut the subtree.
5587 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5588 of some markers in the region, even if CUT is non-nil. This is
5589 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5590 (interactive "p")
5591 (let (beg end folded (beg0 (point)))
5592 (if (interactive-p)
5593 (org-back-to-heading nil) ; take what looks like a subtree
5594 (org-back-to-heading t)) ; take what is really there
5595 (org-back-over-empty-lines)
5596 (setq beg (point))
5597 (skip-chars-forward " \t\r\n")
5598 (save-match-data
5599 (save-excursion (outline-end-of-heading)
5600 (setq folded (org-invisible-p)))
5601 (condition-case nil
5602 (outline-forward-same-level (1- n))
5603 (error nil))
5604 (org-end-of-subtree t t))
5605 (org-back-over-empty-lines)
5606 (setq end (point))
5607 (goto-char beg0)
5608 (when (> end beg)
5609 (setq org-subtree-clip-folded folded)
5610 (when (or cut force-store-markers)
5611 (org-save-markers-in-region beg end))
5612 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5613 (setq org-subtree-clip (current-kill 0))
5614 (message "%s: Subtree(s) with %d characters"
5615 (if cut "Cut" "Copied")
5616 (length org-subtree-clip)))))
5618 (defun org-paste-subtree (&optional level tree for-yank)
5619 "Paste the clipboard as a subtree, with modification of headline level.
5620 The entire subtree is promoted or demoted in order to match a new headline
5621 level.
5623 If the cursor is at the beginning of a headline, the same level as
5624 that headline is used to paste the tree
5626 If not, the new level is derived from the *visible* headings
5627 before and after the insertion point, and taken to be the inferior headline
5628 level of the two. So if the previous visible heading is level 3 and the
5629 next is level 4 (or vice versa), level 4 will be used for insertion.
5630 This makes sure that the subtree remains an independent subtree and does
5631 not swallow low level entries.
5633 You can also force a different level, either by using a numeric prefix
5634 argument, or by inserting the heading marker by hand. For example, if the
5635 cursor is after \"*****\", then the tree will be shifted to level 5.
5637 If optional TREE is given, use this text instead of the kill ring.
5639 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5640 move back over whitespace before inserting, and move point to the end of
5641 the inserted text when done."
5642 (interactive "P")
5643 (unless (org-kill-is-subtree-p tree)
5644 (error "%s"
5645 (substitute-command-keys
5646 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5647 (let* ((visp (not (org-invisible-p)))
5648 (txt (or tree (and kill-ring (current-kill 0))))
5649 (^re (concat "^\\(" outline-regexp "\\)"))
5650 (re (concat "\\(" outline-regexp "\\)"))
5651 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5653 (old-level (if (string-match ^re txt)
5654 (- (match-end 0) (match-beginning 0) 1)
5655 -1))
5656 (force-level (cond (level (prefix-numeric-value level))
5657 ((and (looking-at "[ \t]*$")
5658 (string-match
5659 ^re_ (buffer-substring
5660 (point-at-bol) (point))))
5661 (- (match-end 1) (match-beginning 1)))
5662 ((and (bolp)
5663 (looking-at org-outline-regexp))
5664 (- (match-end 0) (point) 1))
5665 (t nil)))
5666 (previous-level (save-excursion
5667 (condition-case nil
5668 (progn
5669 (outline-previous-visible-heading 1)
5670 (if (looking-at re)
5671 (- (match-end 0) (match-beginning 0) 1)
5673 (error 1))))
5674 (next-level (save-excursion
5675 (condition-case nil
5676 (progn
5677 (or (looking-at outline-regexp)
5678 (outline-next-visible-heading 1))
5679 (if (looking-at re)
5680 (- (match-end 0) (match-beginning 0) 1)
5682 (error 1))))
5683 (new-level (or force-level (max previous-level next-level)))
5684 (shift (if (or (= old-level -1)
5685 (= new-level -1)
5686 (= old-level new-level))
5688 (- new-level old-level)))
5689 (delta (if (> shift 0) -1 1))
5690 (func (if (> shift 0) 'org-demote 'org-promote))
5691 (org-odd-levels-only nil)
5692 beg end newend)
5693 ;; Remove the forced level indicator
5694 (if force-level
5695 (delete-region (point-at-bol) (point)))
5696 ;; Paste
5697 (beginning-of-line 1)
5698 (unless for-yank (org-back-over-empty-lines))
5699 (setq beg (point))
5700 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5701 (insert-before-markers txt)
5702 (unless (string-match "\n\\'" txt) (insert "\n"))
5703 (setq newend (point))
5704 (org-reinstall-markers-in-region beg)
5705 (setq end (point))
5706 (goto-char beg)
5707 (skip-chars-forward " \t\n\r")
5708 (setq beg (point))
5709 (if (and (org-invisible-p) visp)
5710 (save-excursion (outline-show-heading)))
5711 ;; Shift if necessary
5712 (unless (= shift 0)
5713 (save-restriction
5714 (narrow-to-region beg end)
5715 (while (not (= shift 0))
5716 (org-map-region func (point-min) (point-max))
5717 (setq shift (+ delta shift)))
5718 (goto-char (point-min))
5719 (setq newend (point-max))))
5720 (when (or (interactive-p) for-yank)
5721 (message "Clipboard pasted as level %d subtree" new-level))
5722 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5723 kill-ring
5724 (eq org-subtree-clip (current-kill 0))
5725 org-subtree-clip-folded)
5726 ;; The tree was folded before it was killed/copied
5727 (hide-subtree))
5728 (and for-yank (goto-char newend))))
5730 (defun org-kill-is-subtree-p (&optional txt)
5731 "Check if the current kill is an outline subtree, or a set of trees.
5732 Returns nil if kill does not start with a headline, or if the first
5733 headline level is not the largest headline level in the tree.
5734 So this will actually accept several entries of equal levels as well,
5735 which is OK for `org-paste-subtree'.
5736 If optional TXT is given, check this string instead of the current kill."
5737 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5738 (start-level (and kill
5739 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5740 org-outline-regexp "\\)")
5741 kill)
5742 (- (match-end 2) (match-beginning 2) 1)))
5743 (re (concat "^" org-outline-regexp))
5744 (start (1+ (or (match-beginning 2) -1))))
5745 (if (not start-level)
5746 (progn
5747 nil) ;; does not even start with a heading
5748 (catch 'exit
5749 (while (setq start (string-match re kill (1+ start)))
5750 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5751 (throw 'exit nil)))
5752 t))))
5754 (defvar org-markers-to-move nil
5755 "Markers that should be moved with a cut-and-paste operation.
5756 Those markers are stored together with their positions relative to
5757 the start of the region.")
5759 (defun org-save-markers-in-region (beg end)
5760 "Check markers in region.
5761 If these markers are between BEG and END, record their position relative
5762 to BEG, so that after moving the block of text, we can put the markers back
5763 into place.
5764 This function gets called just before an entry or tree gets cut from the
5765 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5766 called immediately, to move the markers with the entries."
5767 (setq org-markers-to-move nil)
5768 (when (featurep 'org-clock)
5769 (org-clock-save-markers-for-cut-and-paste beg end))
5770 (when (featurep 'org-agenda)
5771 (org-agenda-save-markers-for-cut-and-paste beg end)))
5773 (defun org-check-and-save-marker (marker beg end)
5774 "Check if MARKER is between BEG and END.
5775 If yes, remember the marker and the distance to BEG."
5776 (when (and (marker-buffer marker)
5777 (equal (marker-buffer marker) (current-buffer)))
5778 (if (and (>= marker beg) (< marker end))
5779 (push (cons marker (- marker beg)) org-markers-to-move))))
5781 (defun org-reinstall-markers-in-region (beg)
5782 "Move all remembered markers to their position relative to BEG."
5783 (mapc (lambda (x)
5784 (move-marker (car x) (+ beg (cdr x))))
5785 org-markers-to-move)
5786 (setq org-markers-to-move nil))
5788 (defun org-narrow-to-subtree ()
5789 "Narrow buffer to the current subtree."
5790 (interactive)
5791 (save-excursion
5792 (save-match-data
5793 (narrow-to-region
5794 (progn (org-back-to-heading) (point))
5795 (progn (org-end-of-subtree t) (point))))))
5798 ;;; Outline Sorting
5800 (defun org-sort (with-case)
5801 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5802 Optional argument WITH-CASE means sort case-sensitively.
5803 With a double prefix argument, also remove duplicate entries."
5804 (interactive "P")
5805 (if (org-at-table-p)
5806 (org-call-with-arg 'org-table-sort-lines with-case)
5807 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5809 (defun org-sort-remove-invisible (s)
5810 (remove-text-properties 0 (length s) org-rm-props s)
5811 (while (string-match org-bracket-link-regexp s)
5812 (setq s (replace-match (if (match-end 2)
5813 (match-string 3 s)
5814 (match-string 1 s)) t t s)))
5817 (defvar org-priority-regexp) ; defined later in the file
5819 (defun org-sort-entries-or-items
5820 (&optional with-case sorting-type getkey-func compare-func property)
5821 "Sort entries on a certain level of an outline tree.
5822 If there is an active region, the entries in the region are sorted.
5823 Else, if the cursor is before the first entry, sort the top-level items.
5824 Else, the children of the entry at point are sorted.
5826 Sorting can be alphabetically, numerically, and by date/time as given by
5827 the first time stamp in the entry. The command prompts for the sorting
5828 type unless it has been given to the function through the SORTING-TYPE
5829 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5830 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5831 called with point at the beginning of the record. It must return either
5832 a string or a number that should serve as the sorting key for that record.
5834 Comparing entries ignores case by default. However, with an optional argument
5835 WITH-CASE, the sorting considers case as well."
5836 (interactive "P")
5837 (let ((case-func (if with-case 'identity 'downcase))
5838 start beg end stars re re2
5839 txt what tmp plain-list-p)
5840 ;; Find beginning and end of region to sort
5841 (cond
5842 ((org-region-active-p)
5843 ;; we will sort the region
5844 (setq end (region-end)
5845 what "region")
5846 (goto-char (region-beginning))
5847 (if (not (org-on-heading-p)) (outline-next-heading))
5848 (setq start (point)))
5849 ((org-at-item-p)
5850 ;; we will sort this plain list
5851 (org-beginning-of-item-list) (setq start (point))
5852 (org-end-of-item-list) (setq end (point))
5853 (goto-char start)
5854 (setq plain-list-p t
5855 what "plain list"))
5856 ((or (org-on-heading-p)
5857 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5858 ;; we will sort the children of the current headline
5859 (org-back-to-heading)
5860 (setq start (point)
5861 end (progn (org-end-of-subtree t t)
5862 (org-back-over-empty-lines)
5863 (point))
5864 what "children")
5865 (goto-char start)
5866 (show-subtree)
5867 (outline-next-heading))
5869 ;; we will sort the top-level entries in this file
5870 (goto-char (point-min))
5871 (or (org-on-heading-p) (outline-next-heading))
5872 (setq start (point) end (point-max) what "top-level")
5873 (goto-char start)
5874 (show-all)))
5876 (setq beg (point))
5877 (if (>= beg end) (error "Nothing to sort"))
5879 (unless plain-list-p
5880 (looking-at "\\(\\*+\\)")
5881 (setq stars (match-string 1)
5882 re (concat "^" (regexp-quote stars) " +")
5883 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5884 txt (buffer-substring beg end))
5885 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5886 (if (and (not (equal stars "*")) (string-match re2 txt))
5887 (error "Region to sort contains a level above the first entry")))
5889 (unless sorting-type
5890 (message
5891 (if plain-list-p
5892 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5893 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty todo[o]rder [f]unc A/N/T/P/O/F means reversed:")
5894 what)
5895 (setq sorting-type (read-char-exclusive))
5897 (and (= (downcase sorting-type) ?f)
5898 (setq getkey-func
5899 (org-ido-completing-read "Sort using function: "
5900 obarray 'fboundp t nil nil))
5901 (setq getkey-func (intern getkey-func)))
5903 (and (= (downcase sorting-type) ?r)
5904 (setq property
5905 (org-ido-completing-read "Property: "
5906 (mapcar 'list (org-buffer-property-keys t))
5907 nil t))))
5909 (message "Sorting entries...")
5911 (save-restriction
5912 (narrow-to-region start end)
5914 (let ((dcst (downcase sorting-type))
5915 (now (current-time)))
5916 (sort-subr
5917 (/= dcst sorting-type)
5918 ;; This function moves to the beginning character of the "record" to
5919 ;; be sorted.
5920 (if plain-list-p
5921 (lambda nil
5922 (if (org-at-item-p) t (goto-char (point-max))))
5923 (lambda nil
5924 (if (re-search-forward re nil t)
5925 (goto-char (match-beginning 0))
5926 (goto-char (point-max)))))
5927 ;; This function moves to the last character of the "record" being
5928 ;; sorted.
5929 (if plain-list-p
5930 'org-end-of-item
5931 (lambda nil
5932 (save-match-data
5933 (condition-case nil
5934 (outline-forward-same-level 1)
5935 (error
5936 (goto-char (point-max)))))))
5938 ;; This function returns the value that gets sorted against.
5939 (if plain-list-p
5940 (lambda nil
5941 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5942 (cond
5943 ((= dcst ?n)
5944 (string-to-number (buffer-substring (match-end 0)
5945 (point-at-eol))))
5946 ((= dcst ?a)
5947 (buffer-substring (match-end 0) (point-at-eol)))
5948 ((= dcst ?t)
5949 (if (re-search-forward org-ts-regexp
5950 (point-at-eol) t)
5951 (org-time-string-to-time (match-string 0))
5952 now))
5953 ((= dcst ?f)
5954 (if getkey-func
5955 (progn
5956 (setq tmp (funcall getkey-func))
5957 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5958 tmp)
5959 (error "Invalid key function `%s'" getkey-func)))
5960 (t (error "Invalid sorting type `%c'" sorting-type)))))
5961 (lambda nil
5962 (cond
5963 ((= dcst ?n)
5964 (if (looking-at org-complex-heading-regexp)
5965 (string-to-number (match-string 4))
5966 nil))
5967 ((= dcst ?a)
5968 (if (looking-at org-complex-heading-regexp)
5969 (funcall case-func (match-string 4))
5970 nil))
5971 ((= dcst ?t)
5972 (if (re-search-forward org-ts-regexp
5973 (save-excursion
5974 (forward-line 2)
5975 (point)) t)
5976 (org-time-string-to-time (match-string 0))
5977 now))
5978 ((= dcst ?p)
5979 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5980 (string-to-char (match-string 2))
5981 org-default-priority))
5982 ((= dcst ?r)
5983 (or (org-entry-get nil property) ""))
5984 ((= dcst ?o)
5985 (if (looking-at org-complex-heading-regexp)
5986 (- 9999 (length (member (match-string 2)
5987 org-todo-keywords-1)))))
5988 ((= dcst ?f)
5989 (if getkey-func
5990 (progn
5991 (setq tmp (funcall getkey-func))
5992 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5993 tmp)
5994 (error "Invalid key function `%s'" getkey-func)))
5995 (t (error "Invalid sorting type `%c'" sorting-type)))))
5997 (cond
5998 ((= dcst ?a) 'string<)
5999 ((= dcst ?t) 'time-less-p)
6000 ((= dcst ?f) compare-func)
6001 (t nil)))))
6002 (message "Sorting entries...done")))
6004 (defun org-do-sort (table what &optional with-case sorting-type)
6005 "Sort TABLE of WHAT according to SORTING-TYPE.
6006 The user will be prompted for the SORTING-TYPE if the call to this
6007 function does not specify it. WHAT is only for the prompt, to indicate
6008 what is being sorted. The sorting key will be extracted from
6009 the car of the elements of the table.
6010 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6011 (unless sorting-type
6012 (message
6013 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6014 what)
6015 (setq sorting-type (read-char-exclusive)))
6016 (let ((dcst (downcase sorting-type))
6017 extractfun comparefun)
6018 ;; Define the appropriate functions
6019 (cond
6020 ((= dcst ?n)
6021 (setq extractfun 'string-to-number
6022 comparefun (if (= dcst sorting-type) '< '>)))
6023 ((= dcst ?a)
6024 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6025 (lambda(x) (downcase (org-sort-remove-invisible x))))
6026 comparefun (if (= dcst sorting-type)
6027 'string<
6028 (lambda (a b) (and (not (string< a b))
6029 (not (string= a b)))))))
6030 ((= dcst ?t)
6031 (setq extractfun
6032 (lambda (x)
6033 (if (or (string-match org-ts-regexp x)
6034 (string-match org-ts-regexp-both x))
6035 (time-to-seconds
6036 (org-time-string-to-time (match-string 0 x)))
6038 comparefun (if (= dcst sorting-type) '< '>)))
6039 (t (error "Invalid sorting type `%c'" sorting-type)))
6041 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6042 table)
6043 (lambda (a b) (funcall comparefun (car a) (car b))))))
6045 ;;; Editing source examples
6047 (defvar org-exit-edit-mode-map (make-sparse-keymap))
6048 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
6049 (defvar org-edit-src-force-single-line nil)
6050 (defvar org-edit-src-from-org-mode nil)
6051 (defvar org-edit-src-picture nil)
6053 (define-minor-mode org-exit-edit-mode
6054 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
6056 (defun org-edit-src-code ()
6057 "Edit the source code example at point.
6058 An indirect buffer is created, and that buffer is then narrowed to the
6059 example at point and switched to the correct language mode. When done,
6060 exit by killing the buffer with \\[org-edit-src-exit]."
6061 (interactive)
6062 (let ((line (org-current-line))
6063 (case-fold-search t)
6064 (msg (substitute-command-keys
6065 "Edit, then exit with C-c ' (C-c and single quote)"))
6066 (info (org-edit-src-find-region-and-lang))
6067 (org-mode-p (eq major-mode 'org-mode))
6068 beg end lang lang-f single lfmt)
6069 (if (not info)
6071 (setq beg (nth 0 info)
6072 end (nth 1 info)
6073 lang (nth 2 info)
6074 single (nth 3 info)
6075 lfmt (nth 4 info)
6076 lang-f (intern (concat lang "-mode")))
6077 (unless (functionp lang-f)
6078 (error "No such language mode: %s" lang-f))
6079 (goto-line line)
6080 (if (get-buffer "*Org Edit Src Example*")
6081 (kill-buffer "*Org Edit Src Example*"))
6082 (switch-to-buffer (make-indirect-buffer (current-buffer)
6083 "*Org Edit Src Example*"))
6084 (narrow-to-region beg end)
6085 (remove-text-properties beg end '(display nil invisible nil
6086 intangible nil))
6087 (let ((org-inhibit-startup t))
6088 (funcall lang-f))
6089 (set (make-local-variable 'org-edit-src-force-single-line) single)
6090 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6091 (when lfmt
6092 (set (make-local-variable 'org-coderef-label-format) lfmt))
6093 (when org-mode-p
6094 (goto-char (point-min))
6095 (while (re-search-forward "^," nil t)
6096 (replace-match "")))
6097 (goto-line line)
6098 (org-exit-edit-mode)
6099 (org-set-local 'header-line-format msg)
6100 (message "%s" msg)
6101 t)))
6103 (defun org-edit-fixed-width-region ()
6104 "Edit the fixed-width ascii drawing at point.
6105 This must be a region where each line starts with a colon followed by
6106 a space character.
6107 An indirect buffer is created, and that buffer is then narrowed to the
6108 example at point and switched to artist-mode. When done,
6109 exit by killing the buffer with \\[org-edit-src-exit]."
6110 (interactive)
6111 (let ((line (org-current-line))
6112 (case-fold-search t)
6113 (msg (substitute-command-keys
6114 "Edit, then exit with C-c ' (C-c and single quote)"))
6115 (org-mode-p (eq major-mode 'org-mode))
6116 beg end)
6117 (beginning-of-line 1)
6118 (if (looking-at "[ \t]*[^:\n \t]")
6120 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
6121 (setq beg (point) end beg)
6122 (save-excursion
6123 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
6124 (setq beg (point-at-bol 2))
6125 (setq beg (point))))
6126 (save-excursion
6127 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
6128 (setq end (1- (match-beginning 0)))
6129 (setq end (point))))
6130 (goto-line line))
6131 (if (get-buffer "*Org Edit Picture*")
6132 (kill-buffer "*Org Edit Picture*"))
6133 (switch-to-buffer (make-indirect-buffer (current-buffer)
6134 "*Org Edit Picture*"))
6135 (narrow-to-region beg end)
6136 (remove-text-properties beg end '(display nil invisible nil
6137 intangible nil))
6138 (when (fboundp 'font-lock-unfontify-region)
6139 (font-lock-unfontify-region (point-min) (point-max)))
6140 (cond
6141 ((eq org-edit-fixed-width-region-mode 'artist-mode)
6142 (fundamental-mode)
6143 (artist-mode 1))
6144 (t (funcall org-edit-fixed-width-region-mode)))
6145 (set (make-local-variable 'org-edit-src-force-single-line) nil)
6146 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6147 (set (make-local-variable 'org-edit-src-picture) t)
6148 (goto-char (point-min))
6149 (while (re-search-forward "^[ \t]*: ?" nil t)
6150 (replace-match ""))
6151 (goto-line line)
6152 (org-exit-edit-mode)
6153 (org-set-local 'header-line-format msg)
6154 (message "%s" msg)
6155 t)))
6158 (defun org-edit-src-find-region-and-lang ()
6159 "Find the region and language for a local edit.
6160 Return a list with beginning and end of the region, a string representing
6161 the language, a switch telling of the content should be in a single line."
6162 (let ((re-list
6163 (append
6164 org-edit-src-region-extra
6166 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
6167 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
6168 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
6169 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
6170 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
6171 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
6172 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
6173 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
6174 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
6175 ("^#\\+html:" "\n" "html" single-line)
6176 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
6177 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
6178 ("^#\\+latex:" "\n" "latex" single-line)
6179 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
6180 ("^#\\+ascii:" "\n" "ascii" single-line)
6182 (pos (point))
6183 re1 re2 single beg end lang lfmt match-re1)
6184 (catch 'exit
6185 (while (setq entry (pop re-list))
6186 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
6187 single (nth 3 entry))
6188 (save-excursion
6189 (if (or (looking-at re1)
6190 (re-search-backward re1 nil t))
6191 (progn
6192 (setq match-re1 (match-string 0))
6193 (setq beg (match-end 0)
6194 lang (org-edit-src-get-lang lang)
6195 lfmt (org-edit-src-get-label-format match-re1))
6196 (if (and (re-search-forward re2 nil t)
6197 (>= (match-end 0) pos))
6198 (throw 'exit (list beg (match-beginning 0)
6199 lang single lfmt))))
6200 (if (or (looking-at re2)
6201 (re-search-forward re2 nil t))
6202 (progn
6203 (setq end (match-beginning 0))
6204 (if (and (re-search-backward re1 nil t)
6205 (<= (match-beginning 0) pos))
6206 (progn
6207 (setq lfmt (org-edit-src-get-label-format
6208 (match-string 0)))
6209 (throw 'exit
6210 (list (match-end 0) end
6211 (org-edit-src-get-lang lang)
6212 single lfmt))))))))))))
6214 (defun org-edit-src-get-lang (lang)
6215 "Extract the src language."
6216 (let ((m (match-string 0)))
6217 (cond
6218 ((stringp lang) lang)
6219 ((integerp lang) (match-string lang))
6220 ((and (eq lang 'lang)
6221 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
6222 (match-string 1 m))
6223 ((and (eq lang 'style)
6224 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
6225 (match-string 1 m))
6226 (t "fundamental"))))
6228 (defun org-edit-src-get-label-format (s)
6229 "Extract the label format."
6230 (save-match-data
6231 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
6232 (match-string 1 s))))
6234 (defun org-edit-src-exit ()
6235 "Exit special edit and protect problematic lines."
6236 (interactive)
6237 (unless (buffer-base-buffer (current-buffer))
6238 (error "This is not an indirect buffer, something is wrong..."))
6239 (unless (> (point-min) 1)
6240 (error "This buffer is not narrowed, something is wrong..."))
6241 (goto-char (point-min))
6242 (if (looking-at "[ \t\n]*\n") (replace-match ""))
6243 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
6244 (when (org-bound-and-true-p org-edit-src-force-single-line)
6245 (goto-char (point-min))
6246 (while (re-search-forward "\n" nil t)
6247 (replace-match " "))
6248 (goto-char (point-min))
6249 (if (looking-at "\\s-*") (replace-match " "))
6250 (if (re-search-forward "\\s-+\\'" nil t)
6251 (replace-match "")))
6252 (when (org-bound-and-true-p org-edit-src-from-org-mode)
6253 (goto-char (point-min))
6254 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
6255 (replace-match ",\\1"))
6256 (when font-lock-mode
6257 (font-lock-unfontify-region (point-min) (point-max)))
6258 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6259 (when (org-bound-and-true-p org-edit-src-picture)
6260 (untabify (point-min) (point-max))
6261 (goto-char (point-min))
6262 (while (re-search-forward "^" nil t)
6263 (replace-match ": "))
6264 (when font-lock-mode
6265 (font-lock-unfontify-region (point-min) (point-max)))
6266 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6267 (kill-buffer (current-buffer))
6268 (and (org-mode-p) (org-restart-font-lock)))
6271 ;;; The orgstruct minor mode
6273 ;; Define a minor mode which can be used in other modes in order to
6274 ;; integrate the org-mode structure editing commands.
6276 ;; This is really a hack, because the org-mode structure commands use
6277 ;; keys which normally belong to the major mode. Here is how it
6278 ;; works: The minor mode defines all the keys necessary to operate the
6279 ;; structure commands, but wraps the commands into a function which
6280 ;; tests if the cursor is currently at a headline or a plain list
6281 ;; item. If that is the case, the structure command is used,
6282 ;; temporarily setting many Org-mode variables like regular
6283 ;; expressions for filling etc. However, when any of those keys is
6284 ;; used at a different location, function uses `key-binding' to look
6285 ;; up if the key has an associated command in another currently active
6286 ;; keymap (minor modes, major mode, global), and executes that
6287 ;; command. There might be problems if any of the keys is otherwise
6288 ;; used as a prefix key.
6290 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6291 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6292 ;; addresses this by checking explicitly for both bindings.
6294 (defvar orgstruct-mode-map (make-sparse-keymap)
6295 "Keymap for the minor `orgstruct-mode'.")
6297 (defvar org-local-vars nil
6298 "List of local variables, for use by `orgstruct-mode'")
6300 ;;;###autoload
6301 (define-minor-mode orgstruct-mode
6302 "Toggle the minor more `orgstruct-mode'.
6303 This mode is for using Org-mode structure commands in other modes.
6304 The following key behave as if Org-mode was active, if the cursor
6305 is on a headline, or on a plain list item (both in the definition
6306 of Org-mode).
6308 M-up Move entry/item up
6309 M-down Move entry/item down
6310 M-left Promote
6311 M-right Demote
6312 M-S-up Move entry/item up
6313 M-S-down Move entry/item down
6314 M-S-left Promote subtree
6315 M-S-right Demote subtree
6316 M-q Fill paragraph and items like in Org-mode
6317 C-c ^ Sort entries
6318 C-c - Cycle list bullet
6319 TAB Cycle item visibility
6320 M-RET Insert new heading/item
6321 S-M-RET Insert new TODO heading / Checkbox item
6322 C-c C-c Set tags / toggle checkbox"
6323 nil " OrgStruct" nil
6324 (org-load-modules-maybe)
6325 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6327 ;;;###autoload
6328 (defun turn-on-orgstruct ()
6329 "Unconditionally turn on `orgstruct-mode'."
6330 (orgstruct-mode 1))
6332 (defun orgstruct++-mode (&optional arg)
6333 "Toggle `orgstruct-mode', the enhanced version of it.
6334 In addition to setting orgstruct-mode, this also exports all indentation and
6335 autofilling variables from org-mode into the buffer. It will also
6336 recognize item context in multiline items.
6337 Note that turning off orgstruct-mode will *not* remove the
6338 indentation/paragraph settings. This can only be done by refreshing the
6339 major mode, for example with \[normal-mode]."
6340 (interactive "P")
6341 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6342 (if (< arg 1)
6343 (orgstruct-mode -1)
6344 (orgstruct-mode 1)
6345 (let (var val)
6346 (mapc
6347 (lambda (x)
6348 (when (string-match
6349 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6350 (symbol-name (car x)))
6351 (setq var (car x) val (nth 1 x))
6352 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6353 org-local-vars)
6354 (org-set-local 'orgstruct-is-++ t))))
6356 (defvar orgstruct-is-++ nil
6357 "Is orgstruct-mode in ++ version in the current-buffer?")
6358 (make-variable-buffer-local 'orgstruct-is-++)
6360 ;;;###autoload
6361 (defun turn-on-orgstruct++ ()
6362 "Unconditionally turn on `orgstruct++-mode'."
6363 (orgstruct++-mode 1))
6365 (defun orgstruct-error ()
6366 "Error when there is no default binding for a structure key."
6367 (interactive)
6368 (error "This key has no function outside structure elements"))
6370 (defun orgstruct-setup ()
6371 "Setup orgstruct keymaps."
6372 (let ((nfunc 0)
6373 (bindings
6374 (list
6375 '([(meta up)] org-metaup)
6376 '([(meta down)] org-metadown)
6377 '([(meta left)] org-metaleft)
6378 '([(meta right)] org-metaright)
6379 '([(meta shift up)] org-shiftmetaup)
6380 '([(meta shift down)] org-shiftmetadown)
6381 '([(meta shift left)] org-shiftmetaleft)
6382 '([(meta shift right)] org-shiftmetaright)
6383 '([(shift up)] org-shiftup)
6384 '([(shift down)] org-shiftdown)
6385 '([(shift left)] org-shiftleft)
6386 '([(shift right)] org-shiftright)
6387 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6388 '("\M-q" fill-paragraph)
6389 '("\C-c^" org-sort)
6390 '("\C-c-" org-cycle-list-bullet)))
6391 elt key fun cmd)
6392 (while (setq elt (pop bindings))
6393 (setq nfunc (1+ nfunc))
6394 (setq key (org-key (car elt))
6395 fun (nth 1 elt)
6396 cmd (orgstruct-make-binding fun nfunc key))
6397 (org-defkey orgstruct-mode-map key cmd))
6399 ;; Special treatment needed for TAB and RET
6400 (org-defkey orgstruct-mode-map [(tab)]
6401 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6402 (org-defkey orgstruct-mode-map "\C-i"
6403 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6405 (org-defkey orgstruct-mode-map "\M-\C-m"
6406 (orgstruct-make-binding 'org-insert-heading 105
6407 "\M-\C-m" [(meta return)]))
6408 (org-defkey orgstruct-mode-map [(meta return)]
6409 (orgstruct-make-binding 'org-insert-heading 106
6410 [(meta return)] "\M-\C-m"))
6412 (org-defkey orgstruct-mode-map [(shift meta return)]
6413 (orgstruct-make-binding 'org-insert-todo-heading 107
6414 [(meta return)] "\M-\C-m"))
6416 (unless org-local-vars
6417 (setq org-local-vars (org-get-local-variables)))
6421 (defun orgstruct-make-binding (fun n &rest keys)
6422 "Create a function for binding in the structure minor mode.
6423 FUN is the command to call inside a table. N is used to create a unique
6424 command name. KEYS are keys that should be checked in for a command
6425 to execute outside of tables."
6426 (eval
6427 (list 'defun
6428 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6429 '(arg)
6430 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6431 "Outside of structure, run the binding of `"
6432 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6433 "'.")
6434 '(interactive "p")
6435 (list 'if
6436 `(org-context-p 'headline 'item
6437 (and orgstruct-is-++
6438 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
6439 'item-body))
6440 (list 'org-run-like-in-org-mode (list 'quote fun))
6441 (list 'let '(orgstruct-mode)
6442 (list 'call-interactively
6443 (append '(or)
6444 (mapcar (lambda (k)
6445 (list 'key-binding k))
6446 keys)
6447 '('orgstruct-error))))))))
6449 (defun org-context-p (&rest contexts)
6450 "Check if local context is any of CONTEXTS.
6451 Possible values in the list of contexts are `table', `headline', and `item'."
6452 (let ((pos (point)))
6453 (goto-char (point-at-bol))
6454 (prog1 (or (and (memq 'table contexts)
6455 (looking-at "[ \t]*|"))
6456 (and (memq 'headline contexts)
6457 ;;????????? (looking-at "\\*+"))
6458 (looking-at outline-regexp))
6459 (and (memq 'item contexts)
6460 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
6461 (and (memq 'item-body contexts)
6462 (org-in-item-p)))
6463 (goto-char pos))))
6465 (defun org-get-local-variables ()
6466 "Return a list of all local variables in an org-mode buffer."
6467 (let (varlist)
6468 (with-current-buffer (get-buffer-create "*Org tmp*")
6469 (erase-buffer)
6470 (org-mode)
6471 (setq varlist (buffer-local-variables)))
6472 (kill-buffer "*Org tmp*")
6473 (delq nil
6474 (mapcar
6475 (lambda (x)
6476 (setq x
6477 (if (symbolp x)
6478 (list x)
6479 (list (car x) (list 'quote (cdr x)))))
6480 (if (string-match
6481 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6482 (symbol-name (car x)))
6483 x nil))
6484 varlist))))
6486 ;;;###autoload
6487 (defun org-run-like-in-org-mode (cmd)
6488 "Run a command, pretending that the current buffer is in Org-mode.
6489 This will temporarily bind local variables that are typically bound in
6490 Org-mode to the values they have in Org-mode, and then interactively
6491 call CMD."
6492 (org-load-modules-maybe)
6493 (unless org-local-vars
6494 (setq org-local-vars (org-get-local-variables)))
6495 (eval (list 'let org-local-vars
6496 (list 'call-interactively (list 'quote cmd)))))
6498 ;;;; Archiving
6500 (defun org-get-category (&optional pos)
6501 "Get the category applying to position POS."
6502 (get-text-property (or pos (point)) 'org-category))
6504 (defun org-refresh-category-properties ()
6505 "Refresh category text properties in the buffer."
6506 (let ((def-cat (cond
6507 ((null org-category)
6508 (if buffer-file-name
6509 (file-name-sans-extension
6510 (file-name-nondirectory buffer-file-name))
6511 "???"))
6512 ((symbolp org-category) (symbol-name org-category))
6513 (t org-category)))
6514 beg end cat pos optionp)
6515 (org-unmodified
6516 (save-excursion
6517 (save-restriction
6518 (widen)
6519 (goto-char (point-min))
6520 (put-text-property (point) (point-max) 'org-category def-cat)
6521 (while (re-search-forward
6522 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6523 (setq pos (match-end 0)
6524 optionp (equal (char-after (match-beginning 0)) ?#)
6525 cat (org-trim (match-string 2)))
6526 (if optionp
6527 (setq beg (point-at-bol) end (point-max))
6528 (org-back-to-heading t)
6529 (setq beg (point) end (org-end-of-subtree t t)))
6530 (put-text-property beg end 'org-category cat)
6531 (goto-char pos)))))))
6534 ;;;; Link Stuff
6536 ;;; Link abbreviations
6538 (defun org-link-expand-abbrev (link)
6539 "Apply replacements as defined in `org-link-abbrev-alist."
6540 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6541 (let* ((key (match-string 1 link))
6542 (as (or (assoc key org-link-abbrev-alist-local)
6543 (assoc key org-link-abbrev-alist)))
6544 (tag (and (match-end 2) (match-string 3 link)))
6545 rpl)
6546 (if (not as)
6547 link
6548 (setq rpl (cdr as))
6549 (cond
6550 ((symbolp rpl) (funcall rpl tag))
6551 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6552 ((string-match "%h" rpl)
6553 (replace-match (url-hexify-string (or tag "")) t t rpl))
6554 (t (concat rpl tag)))))
6555 link))
6557 ;;; Storing and inserting links
6559 (defvar org-insert-link-history nil
6560 "Minibuffer history for links inserted with `org-insert-link'.")
6562 (defvar org-stored-links nil
6563 "Contains the links stored with `org-store-link'.")
6565 (defvar org-store-link-plist nil
6566 "Plist with info about the most recently link created with `org-store-link'.")
6568 (defvar org-link-protocols nil
6569 "Link protocols added to Org-mode using `org-add-link-type'.")
6571 (defvar org-store-link-functions nil
6572 "List of functions that are called to create and store a link.
6573 Each function will be called in turn until one returns a non-nil
6574 value. Each function should check if it is responsible for creating
6575 this link (for example by looking at the major mode).
6576 If not, it must exit and return nil.
6577 If yes, it should return a non-nil value after a calling
6578 `org-store-link-props' with a list of properties and values.
6579 Special properties are:
6581 :type The link prefix. like \"http\". This must be given.
6582 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6583 This is obligatory as well.
6584 :description Optional default description for the second pair
6585 of brackets in an Org-mode link. The user can still change
6586 this when inserting this link into an Org-mode buffer.
6588 In addition to these, any additional properties can be specified
6589 and then used in remember templates.")
6591 (defun org-add-link-type (type &optional follow export)
6592 "Add TYPE to the list of `org-link-types'.
6593 Re-compute all regular expressions depending on `org-link-types'
6595 FOLLOW and EXPORT are two functions.
6597 FOLLOW should take the link path as the single argument and do whatever
6598 is necessary to follow the link, for example find a file or display
6599 a mail message.
6601 EXPORT should format the link path for export to one of the export formats.
6602 It should be a function accepting three arguments:
6604 path the path of the link, the text after the prefix (like \"http:\")
6605 desc the description of the link, if any, nil if there was no description
6606 format the export format, a symbol like `html' or `latex'.
6608 The function may use the FORMAT information to return different values
6609 depending on the format. The return value will be put literally into
6610 the exported file.
6611 Org-mode has a built-in default for exporting links. If you are happy with
6612 this default, there is no need to define an export function for the link
6613 type. For a simple example of an export function, see `org-bbdb.el'."
6614 (add-to-list 'org-link-types type t)
6615 (org-make-link-regexps)
6616 (if (assoc type org-link-protocols)
6617 (setcdr (assoc type org-link-protocols) (list follow export))
6618 (push (list type follow export) org-link-protocols)))
6620 ;;;###autoload
6621 (defun org-store-link (arg)
6622 "\\<org-mode-map>Store an org-link to the current location.
6623 This link is added to `org-stored-links' and can later be inserted
6624 into an org-buffer with \\[org-insert-link].
6626 For some link types, a prefix arg is interpreted:
6627 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6628 For file links, arg negates `org-context-in-file-links'."
6629 (interactive "P")
6630 (org-load-modules-maybe)
6631 (setq org-store-link-plist nil) ; reset
6632 (let (link cpltxt desc description search txt)
6633 (cond
6635 ((run-hook-with-args-until-success 'org-store-link-functions)
6636 (setq link (plist-get org-store-link-plist :link)
6637 desc (or (plist-get org-store-link-plist :description) link)))
6639 ((equal (buffer-name) "*Org Edit Src Example*")
6640 (let (label gc)
6641 (while (or (not label)
6642 (save-excursion
6643 (save-restriction
6644 (widen)
6645 (goto-char (point-min))
6646 (re-search-forward
6647 (regexp-quote (format org-coderef-label-format label))
6648 nil t))))
6649 (when label (message "Label exists already") (sit-for 2))
6650 (setq label (read-string "Code line label: " label)))
6651 (end-of-line 1)
6652 (setq link (format org-coderef-label-format label))
6653 (setq gc (- 79 (length link)))
6654 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6655 (insert link)
6656 (setq link (concat "(" label ")") desc nil)))
6658 ((eq major-mode 'calendar-mode)
6659 (let ((cd (calendar-cursor-to-date)))
6660 (setq link
6661 (format-time-string
6662 (car org-time-stamp-formats)
6663 (apply 'encode-time
6664 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6665 nil nil nil))))
6666 (org-store-link-props :type "calendar" :date cd)))
6668 ((eq major-mode 'w3-mode)
6669 (setq cpltxt (url-view-url t)
6670 link (org-make-link cpltxt))
6671 (org-store-link-props :type "w3" :url (url-view-url t)))
6673 ((eq major-mode 'w3m-mode)
6674 (setq cpltxt (or w3m-current-title w3m-current-url)
6675 link (org-make-link w3m-current-url))
6676 (org-store-link-props :type "w3m" :url (url-view-url t)))
6678 ((setq search (run-hook-with-args-until-success
6679 'org-create-file-search-functions))
6680 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6681 "::" search))
6682 (setq cpltxt (or description link)))
6684 ((eq major-mode 'image-mode)
6685 (setq cpltxt (concat "file:"
6686 (abbreviate-file-name buffer-file-name))
6687 link (org-make-link cpltxt))
6688 (org-store-link-props :type "image" :file buffer-file-name))
6690 ((eq major-mode 'dired-mode)
6691 ;; link to the file in the current line
6692 (setq cpltxt (concat "file:"
6693 (abbreviate-file-name
6694 (expand-file-name
6695 (dired-get-filename nil t))))
6696 link (org-make-link cpltxt)))
6698 ((and buffer-file-name (org-mode-p))
6699 (cond
6700 ((org-in-regexp "<<\\(.*?\\)>>")
6701 (setq cpltxt
6702 (concat "file:"
6703 (abbreviate-file-name buffer-file-name)
6704 "::" (match-string 1))
6705 link (org-make-link cpltxt)))
6706 ((and (featurep 'org-id)
6707 (or (eq org-link-to-org-use-id t)
6708 (and (eq org-link-to-org-use-id 'create-if-interactive)
6709 (interactive-p))
6710 (and org-link-to-org-use-id
6711 (condition-case nil
6712 (org-entry-get nil "ID")
6713 (error nil)))))
6714 ;; We can make a link using the ID.
6715 (setq link (condition-case nil
6716 (prog1 (org-id-store-link)
6717 (setq desc (plist-get org-store-link-plist
6718 :description)))
6719 (error
6720 ;; probably before first headline, link to file only
6721 (concat "file:"
6722 (abbreviate-file-name buffer-file-name))))))
6724 ;; Just link to current headline
6725 (setq cpltxt (concat "file:"
6726 (abbreviate-file-name buffer-file-name)))
6727 ;; Add a context search string
6728 (when (org-xor org-context-in-file-links arg)
6729 (setq txt (cond
6730 ((org-on-heading-p) nil)
6731 ((org-region-active-p)
6732 (buffer-substring (region-beginning) (region-end)))
6733 (t nil)))
6734 (when (or (null txt) (string-match "\\S-" txt))
6735 (setq cpltxt
6736 (concat cpltxt "::"
6737 (condition-case nil
6738 (org-make-org-heading-search-string txt)
6739 (error "")))
6740 desc "NONE")))
6741 (if (string-match "::\\'" cpltxt)
6742 (setq cpltxt (substring cpltxt 0 -2)))
6743 (setq link (org-make-link cpltxt)))))
6745 ((buffer-file-name (buffer-base-buffer))
6746 ;; Just link to this file here.
6747 (setq cpltxt (concat "file:"
6748 (abbreviate-file-name
6749 (buffer-file-name (buffer-base-buffer)))))
6750 ;; Add a context string
6751 (when (org-xor org-context-in-file-links arg)
6752 (setq txt (if (org-region-active-p)
6753 (buffer-substring (region-beginning) (region-end))
6754 (buffer-substring (point-at-bol) (point-at-eol))))
6755 ;; Only use search option if there is some text.
6756 (when (string-match "\\S-" txt)
6757 (setq cpltxt
6758 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6759 desc "NONE")))
6760 (setq link (org-make-link cpltxt)))
6762 ((interactive-p)
6763 (error "Cannot link to a buffer which is not visiting a file"))
6765 (t (setq link nil)))
6767 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6768 (setq link (or link cpltxt)
6769 desc (or desc cpltxt))
6770 (if (equal desc "NONE") (setq desc nil))
6772 (if (and (interactive-p) link)
6773 (progn
6774 (setq org-stored-links
6775 (cons (list link desc) org-stored-links))
6776 (message "Stored: %s" (or desc link)))
6777 (and link (org-make-link-string link desc)))))
6779 (defun org-store-link-props (&rest plist)
6780 "Store link properties, extract names and addresses."
6781 (let (x adr)
6782 (when (setq x (plist-get plist :from))
6783 (setq adr (mail-extract-address-components x))
6784 (setq plist (plist-put plist :fromname (car adr)))
6785 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6786 (when (setq x (plist-get plist :to))
6787 (setq adr (mail-extract-address-components x))
6788 (setq plist (plist-put plist :toname (car adr)))
6789 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6790 (let ((from (plist-get plist :from))
6791 (to (plist-get plist :to)))
6792 (when (and from to org-from-is-user-regexp)
6793 (setq plist
6794 (plist-put plist :fromto
6795 (if (string-match org-from-is-user-regexp from)
6796 (concat "to %t")
6797 (concat "from %f"))))))
6798 (setq org-store-link-plist plist))
6800 (defun org-add-link-props (&rest plist)
6801 "Add these properties to the link property list."
6802 (let (key value)
6803 (while plist
6804 (setq key (pop plist) value (pop plist))
6805 (setq org-store-link-plist
6806 (plist-put org-store-link-plist key value)))))
6808 (defun org-email-link-description (&optional fmt)
6809 "Return the description part of an email link.
6810 This takes information from `org-store-link-plist' and formats it
6811 according to FMT (default from `org-email-link-description-format')."
6812 (setq fmt (or fmt org-email-link-description-format))
6813 (let* ((p org-store-link-plist)
6814 (to (plist-get p :toaddress))
6815 (from (plist-get p :fromaddress))
6816 (table
6817 (list
6818 (cons "%c" (plist-get p :fromto))
6819 (cons "%F" (plist-get p :from))
6820 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6821 (cons "%T" (plist-get p :to))
6822 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6823 (cons "%s" (plist-get p :subject))
6824 (cons "%m" (plist-get p :message-id)))))
6825 (when (string-match "%c" fmt)
6826 ;; Check if the user wrote this message
6827 (if (and org-from-is-user-regexp from to
6828 (save-match-data (string-match org-from-is-user-regexp from)))
6829 (setq fmt (replace-match "to %t" t t fmt))
6830 (setq fmt (replace-match "from %f" t t fmt))))
6831 (org-replace-escapes fmt table)))
6833 (defun org-make-org-heading-search-string (&optional string heading)
6834 "Make search string for STRING or current headline."
6835 (interactive)
6836 (let ((s (or string (org-get-heading))))
6837 (unless (and string (not heading))
6838 ;; We are using a headline, clean up garbage in there.
6839 (if (string-match org-todo-regexp s)
6840 (setq s (replace-match "" t t s)))
6841 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6842 (setq s (replace-match "" t t s)))
6843 (setq s (org-trim s))
6844 (if (string-match (concat "^\\(" org-quote-string "\\|"
6845 org-comment-string "\\)") s)
6846 (setq s (replace-match "" t t s)))
6847 (while (string-match org-ts-regexp s)
6848 (setq s (replace-match "" t t s))))
6849 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6850 (setq s (replace-match " " t t s)))
6851 (or string (setq s (concat "*" s))) ; Add * for headlines
6852 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6854 (defun org-make-link (&rest strings)
6855 "Concatenate STRINGS."
6856 (apply 'concat strings))
6858 (defun org-make-link-string (link &optional description)
6859 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6860 (unless (string-match "\\S-" link)
6861 (error "Empty link"))
6862 (when (stringp description)
6863 ;; Remove brackets from the description, they are fatal.
6864 (while (string-match "\\[" description)
6865 (setq description (replace-match "{" t t description)))
6866 (while (string-match "\\]" description)
6867 (setq description (replace-match "}" t t description))))
6868 (when (equal (org-link-escape link) description)
6869 ;; No description needed, it is identical
6870 (setq description nil))
6871 (when (and (not description)
6872 (not (equal link (org-link-escape link))))
6873 (setq description (org-extract-attributes link)))
6874 (concat "[[" (org-link-escape link) "]"
6875 (if description (concat "[" description "]") "")
6876 "]"))
6878 (defconst org-link-escape-chars
6879 '((?\ . "%20")
6880 (?\[ . "%5B")
6881 (?\] . "%5D")
6882 (?\340 . "%E0") ; `a
6883 (?\342 . "%E2") ; ^a
6884 (?\347 . "%E7") ; ,c
6885 (?\350 . "%E8") ; `e
6886 (?\351 . "%E9") ; 'e
6887 (?\352 . "%EA") ; ^e
6888 (?\356 . "%EE") ; ^i
6889 (?\364 . "%F4") ; ^o
6890 (?\371 . "%F9") ; `u
6891 (?\373 . "%FB") ; ^u
6892 (?\; . "%3B")
6893 (?? . "%3F")
6894 (?= . "%3D")
6895 (?+ . "%2B")
6897 "Association list of escapes for some characters problematic in links.
6898 This is the list that is used for internal purposes.")
6900 (defconst org-link-escape-chars-browser
6901 '((?\ . "%20")) ; 32 for the SPC char
6902 "Association list of escapes for some characters problematic in links.
6903 This is the list that is used before handing over to the browser.")
6905 (defun org-link-escape (text &optional table)
6906 "Escape characters in TEXT that are problematic for links."
6907 (setq table (or table org-link-escape-chars))
6908 (when text
6909 (let ((re (mapconcat (lambda (x) (regexp-quote
6910 (char-to-string (car x))))
6911 table "\\|")))
6912 (while (string-match re text)
6913 (setq text
6914 (replace-match
6915 (cdr (assoc (string-to-char (match-string 0 text))
6916 table))
6917 t t text)))
6918 text)))
6920 (defun org-link-unescape (text &optional table)
6921 "Reverse the action of `org-link-escape'."
6922 (setq table (or table org-link-escape-chars))
6923 (when text
6924 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6925 table "\\|")))
6926 (while (string-match re text)
6927 (setq text
6928 (replace-match
6929 (char-to-string (car (rassoc (match-string 0 text) table)))
6930 t t text)))
6931 text)))
6933 (defun org-xor (a b)
6934 "Exclusive or."
6935 (if a (not b) b))
6937 (defun org-fixup-message-id-for-http (s)
6938 "Replace special characters in a message id, so it can be used in an http query."
6939 (while (string-match "<" s)
6940 (setq s (replace-match "%3C" t t s)))
6941 (while (string-match ">" s)
6942 (setq s (replace-match "%3E" t t s)))
6943 (while (string-match "@" s)
6944 (setq s (replace-match "%40" t t s)))
6947 ;;;###autoload
6948 (defun org-insert-link-global ()
6949 "Insert a link like Org-mode does.
6950 This command can be called in any mode to insert a link in Org-mode syntax."
6951 (interactive)
6952 (org-load-modules-maybe)
6953 (org-run-like-in-org-mode 'org-insert-link))
6955 (defun org-insert-link (&optional complete-file link-location)
6956 "Insert a link. At the prompt, enter the link.
6958 Completion can be used to insert any of the link protocol prefixes like
6959 http or ftp in use.
6961 The history can be used to select a link previously stored with
6962 `org-store-link'. When the empty string is entered (i.e. if you just
6963 press RET at the prompt), the link defaults to the most recently
6964 stored link. As SPC triggers completion in the minibuffer, you need to
6965 use M-SPC or C-q SPC to force the insertion of a space character.
6967 You will also be prompted for a description, and if one is given, it will
6968 be displayed in the buffer instead of the link.
6970 If there is already a link at point, this command will allow you to edit link
6971 and description parts.
6973 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6974 be selected using completion. The path to the file will be relative to the
6975 current directory if the file is in the current directory or a subdirectory.
6976 Otherwise, the link will be the absolute path as completed in the minibuffer
6977 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6978 option `org-link-file-path-type'.
6980 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6981 the current directory or below.
6983 With three \\[universal-argument] prefixes, negate the meaning of
6984 `org-keep-stored-link-after-insertion'.
6986 If `org-make-link-description-function' is non-nil, this function will be
6987 called with the link target, and the result will be the default
6988 link description.
6990 If the LINK-LOCATION parameter is non-nil, this value will be
6991 used as the link location instead of reading one interactively."
6992 (interactive "P")
6993 (let* ((wcf (current-window-configuration))
6994 (region (if (org-region-active-p)
6995 (buffer-substring (region-beginning) (region-end))))
6996 (remove (and region (list (region-beginning) (region-end))))
6997 (desc region)
6998 tmphist ; byte-compile incorrectly complains about this
6999 (link link-location)
7000 entry file)
7001 (cond
7002 (link-location) ; specified by arg, just use it.
7003 ((org-in-regexp org-bracket-link-regexp 1)
7004 ;; We do have a link at point, and we are going to edit it.
7005 (setq remove (list (match-beginning 0) (match-end 0)))
7006 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7007 (setq link (read-string "Link: "
7008 (org-link-unescape
7009 (org-match-string-no-properties 1)))))
7010 ((or (org-in-regexp org-angle-link-re)
7011 (org-in-regexp org-plain-link-re))
7012 ;; Convert to bracket link
7013 (setq remove (list (match-beginning 0) (match-end 0))
7014 link (read-string "Link: "
7015 (org-remove-angle-brackets (match-string 0)))))
7016 ((member complete-file '((4) (16)))
7017 ;; Completing read for file names.
7018 (setq file (read-file-name "File: "))
7019 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7020 (pwd1 (file-name-as-directory (abbreviate-file-name
7021 (expand-file-name ".")))))
7022 (cond
7023 ((equal complete-file '(16))
7024 (setq link (org-make-link
7025 "file:"
7026 (abbreviate-file-name (expand-file-name file)))))
7027 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7028 (setq link (org-make-link "file:" (match-string 1 file))))
7029 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7030 (expand-file-name file))
7031 (setq link (org-make-link
7032 "file:" (match-string 1 (expand-file-name file)))))
7033 (t (setq link (org-make-link "file:" file))))))
7035 ;; Read link, with completion for stored links.
7036 (with-output-to-temp-buffer "*Org Links*"
7037 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
7038 (when org-stored-links
7039 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7040 (princ (mapconcat
7041 (lambda (x)
7042 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7043 (reverse org-stored-links) "\n"))))
7044 (let ((cw (selected-window)))
7045 (select-window (get-buffer-window "*Org Links*"))
7046 (setq truncate-lines t)
7047 (org-fit-window-to-buffer)
7048 (select-window cw))
7049 ;; Fake a link history, containing the stored links.
7050 (setq tmphist (append (mapcar 'car org-stored-links)
7051 org-insert-link-history))
7052 (unwind-protect
7053 (setq link
7054 (let ((org-completion-use-ido nil))
7055 (org-completing-read
7056 "Link: "
7057 (append
7058 (mapcar (lambda (x) (list (concat (car x) ":")))
7059 (append org-link-abbrev-alist-local org-link-abbrev-alist))
7060 (mapcar (lambda (x) (list (concat x ":")))
7061 org-link-types))
7062 nil nil nil
7063 'tmphist
7064 (or (car (car org-stored-links))))))
7065 (set-window-configuration wcf)
7066 (kill-buffer "*Org Links*"))
7067 (setq entry (assoc link org-stored-links))
7068 (or entry (push link org-insert-link-history))
7069 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7070 (not org-keep-stored-link-after-insertion))
7071 (setq org-stored-links (delq (assoc link org-stored-links)
7072 org-stored-links)))
7073 (setq desc (or desc (nth 1 entry)))))
7075 (if (string-match org-plain-link-re link)
7076 ;; URL-like link, normalize the use of angular brackets.
7077 (setq link (org-make-link (org-remove-angle-brackets link))))
7079 ;; Check if we are linking to the current file with a search option
7080 ;; If yes, simplify the link by using only the search option.
7081 (when (and buffer-file-name
7082 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7083 (let* ((path (match-string 1 link))
7084 (case-fold-search nil)
7085 (search (match-string 2 link)))
7086 (save-match-data
7087 (if (equal (file-truename buffer-file-name) (file-truename path))
7088 ;; We are linking to this same file, with a search option
7089 (setq link search)))))
7091 ;; Check if we can/should use a relative path. If yes, simplify the link
7092 (when (string-match "^file:\\(.*\\)" link)
7093 (let* ((path (match-string 1 link))
7094 (origpath path)
7095 (case-fold-search nil))
7096 (cond
7097 ((or (eq org-link-file-path-type 'absolute)
7098 (equal complete-file '(16)))
7099 (setq path (abbreviate-file-name (expand-file-name path))))
7100 ((eq org-link-file-path-type 'noabbrev)
7101 (setq path (expand-file-name path)))
7102 ((eq org-link-file-path-type 'relative)
7103 (setq path (file-relative-name path)))
7105 (save-match-data
7106 (if (string-match (concat "^" (regexp-quote
7107 (file-name-as-directory
7108 (expand-file-name "."))))
7109 (expand-file-name path))
7110 ;; We are linking a file with relative path name.
7111 (setq path (substring (expand-file-name path)
7112 (match-end 0)))
7113 (setq path (abbreviate-file-name (expand-file-name path)))))))
7114 (setq link (concat "file:" path))
7115 (if (equal desc origpath)
7116 (setq desc path))))
7118 (if org-make-link-description-function
7119 (setq desc (funcall org-make-link-description-function link desc)))
7121 (setq desc (read-string "Description: " desc))
7122 (unless (string-match "\\S-" desc) (setq desc nil))
7123 (if remove (apply 'delete-region remove))
7124 (insert (org-make-link-string link desc))))
7126 (defun org-completing-read (&rest args)
7127 "Completing-read with SPACE being a normal character."
7128 (let ((minibuffer-local-completion-map
7129 (copy-keymap minibuffer-local-completion-map)))
7130 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7131 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7132 (apply 'org-ido-completing-read args)))
7134 (defun org-completing-read-no-ido (&rest args)
7135 (let (org-completion-use-ido)
7136 (apply 'org-completing-read args)))
7138 (defun org-ido-completing-read (&rest args)
7139 "Completing-read using `ido-mode' speedups if available"
7140 (if (and org-completion-use-ido
7141 (fboundp 'ido-completing-read)
7142 (boundp 'ido-mode) ido-mode
7143 (listp (second args)))
7144 (let ((ido-enter-matching-directory nil))
7145 (apply 'ido-completing-read (concat (car args))
7146 (mapcar (lambda (x) (car x)) (nth 1 args))
7147 (cddr args)))
7148 (apply 'completing-read args)))
7151 (defun org-extract-attributes (s)
7152 "Extract the attributes cookie from a string and set as text property."
7153 (let (a attr (start 0) key value)
7154 (save-match-data
7155 (when (string-match "{{\\([^}]+\\)}}$" s)
7156 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7157 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7158 (setq key (match-string 1 a) value (match-string 2 a)
7159 start (match-end 0)
7160 attr (plist-put attr (intern key) value))))
7161 (org-add-props s nil 'org-attr attr))
7164 (defun org-attributes-to-string (plist)
7165 "Format a property list into an HTML attribute list."
7166 (let ((s "") key value)
7167 (while plist
7168 (setq key (pop plist) value (pop plist))
7169 (and value
7170 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7173 ;;; Opening/following a link
7175 (defvar org-link-search-failed nil)
7177 (defun org-next-link ()
7178 "Move forward to the next link.
7179 If the link is in hidden text, expose it."
7180 (interactive)
7181 (when (and org-link-search-failed (eq this-command last-command))
7182 (goto-char (point-min))
7183 (message "Link search wrapped back to beginning of buffer"))
7184 (setq org-link-search-failed nil)
7185 (let* ((pos (point))
7186 (ct (org-context))
7187 (a (assoc :link ct)))
7188 (if a (goto-char (nth 2 a)))
7189 (if (re-search-forward org-any-link-re nil t)
7190 (progn
7191 (goto-char (match-beginning 0))
7192 (if (org-invisible-p) (org-show-context)))
7193 (goto-char pos)
7194 (setq org-link-search-failed t)
7195 (error "No further link found"))))
7197 (defun org-previous-link ()
7198 "Move backward to the previous link.
7199 If the link is in hidden text, expose it."
7200 (interactive)
7201 (when (and org-link-search-failed (eq this-command last-command))
7202 (goto-char (point-max))
7203 (message "Link search wrapped back to end of buffer"))
7204 (setq org-link-search-failed nil)
7205 (let* ((pos (point))
7206 (ct (org-context))
7207 (a (assoc :link ct)))
7208 (if a (goto-char (nth 1 a)))
7209 (if (re-search-backward org-any-link-re nil t)
7210 (progn
7211 (goto-char (match-beginning 0))
7212 (if (org-invisible-p) (org-show-context)))
7213 (goto-char pos)
7214 (setq org-link-search-failed t)
7215 (error "No further link found"))))
7217 (defun org-translate-link (s)
7218 "Translate a link string if a translation function has been defined."
7219 (if (and org-link-translation-function
7220 (fboundp org-link-translation-function)
7221 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7222 (progn
7223 (setq s (funcall org-link-translation-function
7224 (match-string 1) (match-string 2)))
7225 (concat (car s) ":" (cdr s)))
7228 (defun org-translate-link-from-planner (type path)
7229 "Translate a link from Emacs Planner syntax so that Org can follow it.
7230 This is still an experimental function, your mileage may vary."
7231 (cond
7232 ((member type '("http" "https" "news" "ftp"))
7233 ;; standard Internet links are the same.
7234 nil)
7235 ((and (equal type "irc") (string-match "^//" path))
7236 ;; Planner has two / at the beginning of an irc link, we have 1.
7237 ;; We should have zero, actually....
7238 (setq path (substring path 1)))
7239 ((and (equal type "lisp") (string-match "^/" path))
7240 ;; Planner has a slash, we do not.
7241 (setq type "elisp" path (substring path 1)))
7242 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7243 ;; A typical message link. Planner has the id after the fina slash,
7244 ;; we separate it with a hash mark
7245 (setq path (concat (match-string 1 path) "#"
7246 (org-remove-angle-brackets (match-string 2 path)))))
7248 (cons type path))
7250 (defun org-find-file-at-mouse (ev)
7251 "Open file link or URL at mouse."
7252 (interactive "e")
7253 (mouse-set-point ev)
7254 (org-open-at-point 'in-emacs))
7256 (defun org-open-at-mouse (ev)
7257 "Open file link or URL at mouse."
7258 (interactive "e")
7259 (mouse-set-point ev)
7260 (if (eq major-mode 'org-agenda-mode)
7261 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7262 (org-open-at-point))
7264 (defvar org-window-config-before-follow-link nil
7265 "The window configuration before following a link.
7266 This is saved in case the need arises to restore it.")
7268 (defvar org-open-link-marker (make-marker)
7269 "Marker pointing to the location where `org-open-at-point; was called.")
7271 ;;;###autoload
7272 (defun org-open-at-point-global ()
7273 "Follow a link like Org-mode does.
7274 This command can be called in any mode to follow a link that has
7275 Org-mode syntax."
7276 (interactive)
7277 (org-run-like-in-org-mode 'org-open-at-point))
7279 ;;;###autoload
7280 (defun org-open-link-from-string (s &optional arg)
7281 "Open a link in the string S, as if it was in Org-mode."
7282 (interactive "sLink: \nP")
7283 (with-temp-buffer
7284 (let ((org-inhibit-startup t))
7285 (org-mode)
7286 (insert s)
7287 (goto-char (point-min))
7288 (org-open-at-point arg))))
7290 (defun org-open-at-point (&optional in-emacs)
7291 "Open link at or after point.
7292 If there is no link at point, this function will search forward up to
7293 the end of the current subtree.
7294 Normally, files will be opened by an appropriate application. If the
7295 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7296 With a double prefix argument, try to open outside of Emacs, in the
7297 application the system uses for this file type."
7298 (interactive "P")
7299 (org-load-modules-maybe)
7300 (move-marker org-open-link-marker (point))
7301 (setq org-window-config-before-follow-link (current-window-configuration))
7302 (org-remove-occur-highlights nil nil t)
7303 (cond
7304 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7305 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7306 (org-footnote-action))
7308 (let (type path link line search (pos (point)))
7309 (catch 'match
7310 (save-excursion
7311 (skip-chars-forward "^]\n\r")
7312 (when (org-in-regexp org-bracket-link-regexp)
7313 (setq link (org-extract-attributes
7314 (org-link-unescape (org-match-string-no-properties 1))))
7315 (while (string-match " *\n *" link)
7316 (setq link (replace-match " " t t link)))
7317 (setq link (org-link-expand-abbrev link))
7318 (cond
7319 ((or (file-name-absolute-p link)
7320 (string-match "^\\.\\.?/" link))
7321 (setq type "file" path link))
7322 ((string-match org-link-re-with-space3 link)
7323 (setq type (match-string 1 link) path (match-string 2 link)))
7324 (t (setq type "thisfile" path link)))
7325 (throw 'match t)))
7327 (when (get-text-property (point) 'org-linked-text)
7328 (setq type "thisfile"
7329 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7330 (1+ (point)) (point))
7331 path (buffer-substring
7332 (previous-single-property-change pos 'org-linked-text)
7333 (next-single-property-change pos 'org-linked-text)))
7334 (throw 'match t))
7336 (save-excursion
7337 (when (or (org-in-regexp org-angle-link-re)
7338 (org-in-regexp org-plain-link-re))
7339 (setq type (match-string 1) path (match-string 2))
7340 (throw 'match t)))
7341 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7342 (setq type "tree-match"
7343 path (match-string 1))
7344 (throw 'match t))
7345 (save-excursion
7346 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7347 (setq type "tags"
7348 path (match-string 1))
7349 (while (string-match ":" path)
7350 (setq path (replace-match "+" t t path)))
7351 (throw 'match t))))
7352 (unless path
7353 (error "No link found"))
7354 ;; Remove any trailing spaces in path
7355 (if (string-match " +\\'" path)
7356 (setq path (replace-match "" t t path)))
7357 (if (and org-link-translation-function
7358 (fboundp org-link-translation-function))
7359 ;; Check if we need to translate the link
7360 (let ((tmp (funcall org-link-translation-function type path)))
7361 (setq type (car tmp) path (cdr tmp))))
7363 (cond
7365 ((assoc type org-link-protocols)
7366 (funcall (nth 1 (assoc type org-link-protocols)) path))
7368 ((equal type "mailto")
7369 (let ((cmd (car org-link-mailto-program))
7370 (args (cdr org-link-mailto-program)) args1
7371 (address path) (subject "") a)
7372 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7373 (setq address (match-string 1 path)
7374 subject (org-link-escape (match-string 2 path))))
7375 (while args
7376 (cond
7377 ((not (stringp (car args))) (push (pop args) args1))
7378 (t (setq a (pop args))
7379 (if (string-match "%a" a)
7380 (setq a (replace-match address t t a)))
7381 (if (string-match "%s" a)
7382 (setq a (replace-match subject t t a)))
7383 (push a args1))))
7384 (apply cmd (nreverse args1))))
7386 ((member type '("http" "https" "ftp" "news"))
7387 (browse-url (concat type ":" (org-link-escape
7388 path org-link-escape-chars-browser))))
7390 ((member type '("message"))
7391 (browse-url (concat type ":" path)))
7393 ((string= type "tags")
7394 (org-tags-view in-emacs path))
7395 ((string= type "thisfile")
7396 (if in-emacs
7397 (switch-to-buffer-other-window
7398 (org-get-buffer-for-internal-link (current-buffer)))
7399 (org-mark-ring-push))
7400 (let ((cmd `(org-link-search
7401 ,path
7402 ,(cond ((equal in-emacs '(4)) 'occur)
7403 ((equal in-emacs '(16)) 'org-occur)
7404 (t nil))
7405 ,pos)))
7406 (condition-case nil (eval cmd)
7407 (error (progn (widen) (eval cmd))))))
7409 ((string= type "tree-match")
7410 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7412 ((string= type "file")
7413 (if (string-match "::\\([0-9]+\\)\\'" path)
7414 (setq line (string-to-number (match-string 1 path))
7415 path (substring path 0 (match-beginning 0)))
7416 (if (string-match "::\\(.+\\)\\'" path)
7417 (setq search (match-string 1 path)
7418 path (substring path 0 (match-beginning 0)))))
7419 (if (string-match "[*?{]" (file-name-nondirectory path))
7420 (dired path)
7421 (org-open-file path in-emacs line search)))
7423 ((string= type "news")
7424 (require 'org-gnus)
7425 (org-gnus-follow-link path))
7427 ((string= type "shell")
7428 (let ((cmd path))
7429 (if (or (not org-confirm-shell-link-function)
7430 (funcall org-confirm-shell-link-function
7431 (format "Execute \"%s\" in shell? "
7432 (org-add-props cmd nil
7433 'face 'org-warning))))
7434 (progn
7435 (message "Executing %s" cmd)
7436 (shell-command cmd))
7437 (error "Abort"))))
7439 ((string= type "elisp")
7440 (let ((cmd path))
7441 (if (or (not org-confirm-elisp-link-function)
7442 (funcall org-confirm-elisp-link-function
7443 (format "Execute \"%s\" as elisp? "
7444 (org-add-props cmd nil
7445 'face 'org-warning))))
7446 (message "%s => %s" cmd
7447 (if (equal (string-to-char cmd) ?\()
7448 (eval (read cmd))
7449 (call-interactively (read cmd))))
7450 (error "Abort"))))
7453 (browse-url-at-point))))))
7454 (move-marker org-open-link-marker nil)
7455 (run-hook-with-args 'org-follow-link-hook))
7457 ;;;; Time estimates
7459 (defun org-get-effort (&optional pom)
7460 "Get the effort estimate for the current entry."
7461 (org-entry-get pom org-effort-property))
7463 ;;; File search
7465 (defvar org-create-file-search-functions nil
7466 "List of functions to construct the right search string for a file link.
7467 These functions are called in turn with point at the location to
7468 which the link should point.
7470 A function in the hook should first test if it would like to
7471 handle this file type, for example by checking the major-mode or
7472 the file extension. If it decides not to handle this file, it
7473 should just return nil to give other functions a chance. If it
7474 does handle the file, it must return the search string to be used
7475 when following the link. The search string will be part of the
7476 file link, given after a double colon, and `org-open-at-point'
7477 will automatically search for it. If special measures must be
7478 taken to make the search successful, another function should be
7479 added to the companion hook `org-execute-file-search-functions',
7480 which see.
7482 A function in this hook may also use `setq' to set the variable
7483 `description' to provide a suggestion for the descriptive text to
7484 be used for this link when it gets inserted into an Org-mode
7485 buffer with \\[org-insert-link].")
7487 (defvar org-execute-file-search-functions nil
7488 "List of functions to execute a file search triggered by a link.
7490 Functions added to this hook must accept a single argument, the
7491 search string that was part of the file link, the part after the
7492 double colon. The function must first check if it would like to
7493 handle this search, for example by checking the major-mode or the
7494 file extension. If it decides not to handle this search, it
7495 should just return nil to give other functions a chance. If it
7496 does handle the search, it must return a non-nil value to keep
7497 other functions from trying.
7499 Each function can access the current prefix argument through the
7500 variable `current-prefix-argument'. Note that a single prefix is
7501 used to force opening a link in Emacs, so it may be good to only
7502 use a numeric or double prefix to guide the search function.
7504 In case this is needed, a function in this hook can also restore
7505 the window configuration before `org-open-at-point' was called using:
7507 (set-window-configuration org-window-config-before-follow-link)")
7509 (defun org-link-search (s &optional type avoid-pos)
7510 "Search for a link search option.
7511 If S is surrounded by forward slashes, it is interpreted as a
7512 regular expression. In org-mode files, this will create an `org-occur'
7513 sparse tree. In ordinary files, `occur' will be used to list matches.
7514 If the current buffer is in `dired-mode', grep will be used to search
7515 in all files. If AVOID-POS is given, ignore matches near that position."
7516 (let ((case-fold-search t)
7517 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7518 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7519 (append '(("") (" ") ("\t") ("\n"))
7520 org-emphasis-alist)
7521 "\\|") "\\)"))
7522 (pos (point))
7523 (pre nil) (post nil)
7524 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7525 (cond
7526 ;; First check if there are any special
7527 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7528 ;; Now try the builtin stuff
7529 ((save-excursion
7530 (goto-char (point-min))
7531 (and
7532 (re-search-forward
7533 (concat "<<" (regexp-quote s0) ">>") nil t)
7534 (setq type 'dedicated
7535 pos (match-beginning 0))))
7536 ;; There is an exact target for this
7537 (goto-char pos))
7538 ((and (string-match "^(\\(.*\\))$" s0)
7539 (save-excursion
7540 (goto-char (point-min))
7541 (and
7542 (re-search-forward
7543 (concat "[^[]" (regexp-quote
7544 (format org-coderef-label-format
7545 (match-string 1 s0))))
7546 nil t)
7547 (setq type 'dedicated
7548 pos (1+ (match-beginning 0))))))
7549 ;; There is a coderef target for this
7550 (goto-char pos))
7551 ((string-match "^/\\(.*\\)/$" s)
7552 ;; A regular expression
7553 (cond
7554 ((org-mode-p)
7555 (org-occur (match-string 1 s)))
7556 ;;((eq major-mode 'dired-mode)
7557 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7558 (t (org-do-occur (match-string 1 s)))))
7560 ;; A normal search strings
7561 (when (equal (string-to-char s) ?*)
7562 ;; Anchor on headlines, post may include tags.
7563 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7564 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7565 s (substring s 1)))
7566 (remove-text-properties
7567 0 (length s)
7568 '(face nil mouse-face nil keymap nil fontified nil) s)
7569 ;; Make a series of regular expressions to find a match
7570 (setq words (org-split-string s "[ \n\r\t]+")
7572 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7573 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7574 "\\)" markers)
7575 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7576 re2a (concat "[ \t\r\n]" re2a_)
7577 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7578 re4 (concat "[^a-zA-Z_]" re4_)
7580 re1 (concat pre re2 post)
7581 re3 (concat pre (if pre re4_ re4) post)
7582 re5 (concat pre ".*" re4)
7583 re2 (concat pre re2)
7584 re2a (concat pre (if pre re2a_ re2a))
7585 re4 (concat pre (if pre re4_ re4))
7586 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7587 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7588 re5 "\\)"
7590 (cond
7591 ((eq type 'org-occur) (org-occur reall))
7592 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7593 (t (goto-char (point-min))
7594 (setq type 'fuzzy)
7595 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7596 (org-search-not-self 1 re1 nil t)
7597 (org-search-not-self 1 re2 nil t)
7598 (org-search-not-self 1 re2a nil t)
7599 (org-search-not-self 1 re3 nil t)
7600 (org-search-not-self 1 re4 nil t)
7601 (org-search-not-self 1 re5 nil t)
7603 (goto-char (match-beginning 1))
7604 (goto-char pos)
7605 (error "No match")))))
7607 ;; Normal string-search
7608 (goto-char (point-min))
7609 (if (search-forward s nil t)
7610 (goto-char (match-beginning 0))
7611 (error "No match"))))
7612 (and (org-mode-p) (org-show-context 'link-search))
7613 type))
7615 (defun org-search-not-self (group &rest args)
7616 "Execute `re-search-forward', but only accept matches that do not
7617 enclose the position of `org-open-link-marker'."
7618 (let ((m org-open-link-marker))
7619 (catch 'exit
7620 (while (apply 're-search-forward args)
7621 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7622 (goto-char (match-end group))
7623 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7624 (> (match-beginning 0) (marker-position m))
7625 (< (match-end 0) (marker-position m)))
7626 (save-match-data
7627 (or (not (org-in-regexp
7628 org-bracket-link-analytic-regexp 1))
7629 (not (match-end 4)) ; no description
7630 (and (<= (match-beginning 4) (point))
7631 (>= (match-end 4) (point))))))
7632 (throw 'exit (point))))))))
7634 (defun org-get-buffer-for-internal-link (buffer)
7635 "Return a buffer to be used for displaying the link target of internal links."
7636 (cond
7637 ((not org-display-internal-link-with-indirect-buffer)
7638 buffer)
7639 ((string-match "(Clone)$" (buffer-name buffer))
7640 (message "Buffer is already a clone, not making another one")
7641 ;; we also do not modify visibility in this case
7642 buffer)
7643 (t ; make a new indirect buffer for displaying the link
7644 (let* ((bn (buffer-name buffer))
7645 (ibn (concat bn "(Clone)"))
7646 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7647 (with-current-buffer ib (org-overview))
7648 ib))))
7650 (defun org-do-occur (regexp &optional cleanup)
7651 "Call the Emacs command `occur'.
7652 If CLEANUP is non-nil, remove the printout of the regular expression
7653 in the *Occur* buffer. This is useful if the regex is long and not useful
7654 to read."
7655 (occur regexp)
7656 (when cleanup
7657 (let ((cwin (selected-window)) win beg end)
7658 (when (setq win (get-buffer-window "*Occur*"))
7659 (select-window win))
7660 (goto-char (point-min))
7661 (when (re-search-forward "match[a-z]+" nil t)
7662 (setq beg (match-end 0))
7663 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7664 (setq end (1- (match-beginning 0)))))
7665 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7666 (goto-char (point-min))
7667 (select-window cwin))))
7669 ;;; The mark ring for links jumps
7671 (defvar org-mark-ring nil
7672 "Mark ring for positions before jumps in Org-mode.")
7673 (defvar org-mark-ring-last-goto nil
7674 "Last position in the mark ring used to go back.")
7675 ;; Fill and close the ring
7676 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7677 (loop for i from 1 to org-mark-ring-length do
7678 (push (make-marker) org-mark-ring))
7679 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7680 org-mark-ring)
7682 (defun org-mark-ring-push (&optional pos buffer)
7683 "Put the current position or POS into the mark ring and rotate it."
7684 (interactive)
7685 (setq pos (or pos (point)))
7686 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7687 (move-marker (car org-mark-ring)
7688 (or pos (point))
7689 (or buffer (current-buffer)))
7690 (message "%s"
7691 (substitute-command-keys
7692 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7694 (defun org-mark-ring-goto (&optional n)
7695 "Jump to the previous position in the mark ring.
7696 With prefix arg N, jump back that many stored positions. When
7697 called several times in succession, walk through the entire ring.
7698 Org-mode commands jumping to a different position in the current file,
7699 or to another Org-mode file, automatically push the old position
7700 onto the ring."
7701 (interactive "p")
7702 (let (p m)
7703 (if (eq last-command this-command)
7704 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7705 (setq p org-mark-ring))
7706 (setq org-mark-ring-last-goto p)
7707 (setq m (car p))
7708 (switch-to-buffer (marker-buffer m))
7709 (goto-char m)
7710 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7712 (defun org-remove-angle-brackets (s)
7713 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7714 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7716 (defun org-add-angle-brackets (s)
7717 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7718 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7720 (defun org-remove-double-quotes (s)
7721 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7722 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7725 ;;; Following specific links
7727 (defun org-follow-timestamp-link ()
7728 (cond
7729 ((org-at-date-range-p t)
7730 (let ((org-agenda-start-on-weekday)
7731 (t1 (match-string 1))
7732 (t2 (match-string 2)))
7733 (setq t1 (time-to-days (org-time-string-to-time t1))
7734 t2 (time-to-days (org-time-string-to-time t2)))
7735 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7736 ((org-at-timestamp-p t)
7737 (org-agenda-list nil (time-to-days (org-time-string-to-time
7738 (substring (match-string 1) 0 10)))
7740 (t (error "This should not happen"))))
7743 ;;; Following file links
7744 (defvar org-wait nil)
7745 (defun org-open-file (path &optional in-emacs line search)
7746 "Open the file at PATH.
7747 First, this expands any special file name abbreviations. Then the
7748 configuration variable `org-file-apps' is checked if it contains an
7749 entry for this file type, and if yes, the corresponding command is launched.
7751 If no application is found, Emacs simply visits the file.
7753 With optional prefix argument IN-EMACS, Emacs will visit the file.
7754 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7755 and o use an external application to visit the file.
7757 Optional LINE specifies a line to go to, optional SEARCH a string to
7758 search for. If LINE or SEARCH is given, the file will always be
7759 opened in Emacs.
7760 If the file does not exist, an error is thrown."
7761 (setq in-emacs (or in-emacs line search))
7762 (let* ((file (if (equal path "")
7763 buffer-file-name
7764 (substitute-in-file-name (expand-file-name path))))
7765 (apps (append org-file-apps (org-default-apps)))
7766 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7767 (dirp (if remp nil (file-directory-p file)))
7768 (file (if (and dirp org-open-directory-means-index-dot-org)
7769 (concat (file-name-as-directory file) "index.org")
7770 file))
7771 (a-m-a-p (assq 'auto-mode apps))
7772 (dfile (downcase file))
7773 (old-buffer (current-buffer))
7774 (old-pos (point))
7775 (old-mode major-mode)
7776 ext cmd)
7777 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7778 (setq ext (match-string 1 dfile))
7779 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7780 (setq ext (match-string 1 dfile))))
7781 (cond
7782 ((equal in-emacs '(16))
7783 (setq cmd (cdr (assoc 'system apps))))
7784 (in-emacs (setq cmd 'emacs))
7786 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7787 (and dirp (cdr (assoc 'directory apps)))
7788 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7789 'string-match)
7790 (cdr (assoc ext apps))
7791 (cdr (assoc t apps))))))
7792 (when (eq cmd 'system)
7793 (setq cmd (cdr (assoc 'system apps))))
7794 (when (eq cmd 'default)
7795 (setq cmd (cdr (assoc t apps))))
7796 (when (eq cmd 'mailcap)
7797 (require 'mailcap)
7798 (mailcap-parse-mailcaps)
7799 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7800 (command (mailcap-mime-info mime-type)))
7801 (if (stringp command)
7802 (setq cmd command)
7803 (setq cmd 'emacs))))
7804 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7805 (not (file-exists-p file))
7806 (not org-open-non-existing-files))
7807 (error "No such file: %s" file))
7808 (cond
7809 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7810 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7811 (while (string-match "['\"]%s['\"]" cmd)
7812 (setq cmd (replace-match "%s" t t cmd)))
7813 (while (string-match "%s" cmd)
7814 (setq cmd (replace-match
7815 (save-match-data
7816 (shell-quote-argument
7817 (convert-standard-filename file)))
7818 t t cmd)))
7819 (save-window-excursion
7820 (start-process-shell-command cmd nil cmd)
7821 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7823 ((or (stringp cmd)
7824 (eq cmd 'emacs))
7825 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7826 (widen)
7827 (if line (goto-line line)
7828 (if search (org-link-search search))))
7829 ((consp cmd)
7830 (let ((file (convert-standard-filename file)))
7831 (eval cmd)))
7832 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7833 (and (org-mode-p) (eq old-mode 'org-mode)
7834 (or (not (equal old-buffer (current-buffer)))
7835 (not (equal old-pos (point))))
7836 (org-mark-ring-push old-pos old-buffer))))
7838 (defun org-default-apps ()
7839 "Return the default applications for this operating system."
7840 (cond
7841 ((eq system-type 'darwin)
7842 org-file-apps-defaults-macosx)
7843 ((eq system-type 'windows-nt)
7844 org-file-apps-defaults-windowsnt)
7845 (t org-file-apps-defaults-gnu)))
7847 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7848 "Convert extensions to regular expressions in the cars of LIST.
7849 Also, weed out any non-string entries, because the return value is used
7850 only for regexp matching.
7851 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7852 point to the symbol `emacs', indicating that the file should
7853 be opened in Emacs."
7854 (append
7855 (delq nil
7856 (mapcar (lambda (x)
7857 (if (not (stringp (car x)))
7859 (if (string-match "\\W" (car x))
7861 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7862 list))
7863 (if add-auto-mode
7864 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7866 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7867 (defun org-file-remote-p (file)
7868 "Test whether FILE specifies a location on a remote system.
7869 Return non-nil if the location is indeed remote.
7871 For example, the filename \"/user@host:/foo\" specifies a location
7872 on the system \"/user@host:\"."
7873 (cond ((fboundp 'file-remote-p)
7874 (file-remote-p file))
7875 ((fboundp 'tramp-handle-file-remote-p)
7876 (tramp-handle-file-remote-p file))
7877 ((and (boundp 'ange-ftp-name-format)
7878 (string-match (car ange-ftp-name-format) file))
7880 (t nil)))
7883 ;;;; Refiling
7885 (defun org-get-org-file ()
7886 "Read a filename, with default directory `org-directory'."
7887 (let ((default (or org-default-notes-file remember-data-file)))
7888 (read-file-name (format "File name [%s]: " default)
7889 (file-name-as-directory org-directory)
7890 default)))
7892 (defun org-notes-order-reversed-p ()
7893 "Check if the current file should receive notes in reversed order."
7894 (cond
7895 ((not org-reverse-note-order) nil)
7896 ((eq t org-reverse-note-order) t)
7897 ((not (listp org-reverse-note-order)) nil)
7898 (t (catch 'exit
7899 (let ((all org-reverse-note-order)
7900 entry)
7901 (while (setq entry (pop all))
7902 (if (string-match (car entry) buffer-file-name)
7903 (throw 'exit (cdr entry))))
7904 nil)))))
7906 (defvar org-refile-target-table nil
7907 "The list of refile targets, created by `org-refile'.")
7909 (defvar org-agenda-new-buffers nil
7910 "Buffers created to visit agenda files.")
7912 (defun org-get-refile-targets (&optional default-buffer)
7913 "Produce a table with refile targets."
7914 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7915 targets txt re files f desc descre fast-path-p level)
7916 (message "Getting targets...")
7917 (with-current-buffer (or default-buffer (current-buffer))
7918 (while (setq entry (pop entries))
7919 (setq files (car entry) desc (cdr entry))
7920 (setq fast-path-p nil)
7921 (cond
7922 ((null files) (setq files (list (current-buffer))))
7923 ((eq files 'org-agenda-files)
7924 (setq files (org-agenda-files 'unrestricted)))
7925 ((and (symbolp files) (fboundp files))
7926 (setq files (funcall files)))
7927 ((and (symbolp files) (boundp files))
7928 (setq files (symbol-value files))))
7929 (if (stringp files) (setq files (list files)))
7930 (cond
7931 ((eq (car desc) :tag)
7932 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7933 ((eq (car desc) :todo)
7934 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7935 ((eq (car desc) :regexp)
7936 (setq descre (cdr desc)))
7937 ((eq (car desc) :level)
7938 (setq descre (concat "^\\*\\{" (number-to-string
7939 (if org-odd-levels-only
7940 (1- (* 2 (cdr desc)))
7941 (cdr desc)))
7942 "\\}[ \t]")))
7943 ((eq (car desc) :maxlevel)
7944 (setq fast-path-p t)
7945 (setq descre (concat "^\\*\\{1," (number-to-string
7946 (if org-odd-levels-only
7947 (1- (* 2 (cdr desc)))
7948 (cdr desc)))
7949 "\\}[ \t]")))
7950 (t (error "Bad refiling target description %s" desc)))
7951 (while (setq f (pop files))
7952 (save-excursion
7953 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7954 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7955 (setq f (expand-file-name f))
7956 (save-excursion
7957 (save-restriction
7958 (widen)
7959 (goto-char (point-min))
7960 (while (re-search-forward descre nil t)
7961 (goto-char (point-at-bol))
7962 (when (looking-at org-complex-heading-regexp)
7963 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
7964 txt (org-link-display-format (match-string 4))
7965 re (concat "^" (regexp-quote
7966 (buffer-substring (match-beginning 1)
7967 (match-end 4)))))
7968 (if (match-end 5) (setq re (concat re "[ \t]+"
7969 (regexp-quote
7970 (match-string 5)))))
7971 (setq re (concat re "[ \t]*$"))
7972 (when org-refile-use-outline-path
7973 (setq txt (mapconcat 'org-protect-slash
7974 (append
7975 (if (eq org-refile-use-outline-path 'file)
7976 (list (file-name-nondirectory
7977 (buffer-file-name (buffer-base-buffer))))
7978 (if (eq org-refile-use-outline-path 'full-file-path)
7979 (list (buffer-file-name (buffer-base-buffer)))))
7980 (org-get-outline-path fast-path-p level txt)
7981 (list txt))
7982 "/")))
7983 (push (list txt f re (point)) targets))
7984 (goto-char (point-at-eol))))))))
7985 (message "Getting targets...done")
7986 (nreverse targets))))
7988 (defun org-protect-slash (s)
7989 (while (string-match "/" s)
7990 (setq s (replace-match "\\" t t s)))
7993 (defvar org-olpa (make-vector 20 nil))
7995 (defun org-get-outline-path (&optional fastp level heading)
7996 "Return the outline path to the current entry, as a list."
7997 (if fastp
7998 (progn
7999 (if (> level 19)
8000 (error "Outline path failure, more than 19 levels."))
8001 (loop for i from level upto 19 do
8002 (aset org-olpa i nil))
8003 (prog1
8004 (delq nil (append org-olpa nil))
8005 (aset org-olpa level heading)))
8006 (let (rtn)
8007 (save-excursion
8008 (while (org-up-heading-safe)
8009 (when (looking-at org-complex-heading-regexp)
8010 (push (org-match-string-no-properties 4) rtn)))
8011 rtn))))
8013 (defvar org-refile-history nil
8014 "History for refiling operations.")
8016 (defun org-refile (&optional goto default-buffer)
8017 "Move the entry at point to another heading.
8018 The list of target headings is compiled using the information in
8019 `org-refile-targets', which see. This list is created before each use
8020 and will therefore always be up-to-date.
8022 At the target location, the entry is filed as a subitem of the target heading.
8023 Depending on `org-reverse-note-order', the new subitem will either be the
8024 first or the last subitem.
8026 If there is an active region, all entries in that region will be moved.
8027 However, the region must fulfil the requirement that the first heading
8028 is the first one sets the top-level of the moved text - at most siblings
8029 below it are allowed.
8031 With prefix arg GOTO, the command will only visit the target location,
8032 not actually move anything.
8033 With a double prefix `C-u C-u', go to the location where the last refiling
8034 operation has put the subtree."
8035 (interactive "P")
8036 (let* ((cbuf (current-buffer))
8037 (regionp (org-region-active-p))
8038 (region-start (and regionp (region-beginning)))
8039 (region-end (and regionp (region-end)))
8040 (region-length (and regionp (- region-end region-start)))
8041 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8042 pos it nbuf file re level reversed)
8043 (when regionp (goto-char region-start)
8044 (unless (org-kill-is-subtree-p
8045 (buffer-substring region-start region-end))
8046 (error "The region is not a (sequence of) subtree(s)")))
8047 (if (equal goto '(16))
8048 (org-refile-goto-last-stored)
8049 (when (setq it (org-refile-get-location
8050 (if goto "Goto: " "Refile to: ") default-buffer))
8051 (setq file (nth 1 it)
8052 re (nth 2 it)
8053 pos (nth 3 it))
8054 (if (and (equal (buffer-file-name) file)
8055 (if regionp
8056 (and (>= pos region-start)
8057 (<= pos region-end))
8058 (and (>= pos (point))
8059 (< pos (save-excursion
8060 (org-end-of-subtree t t))))))
8061 (error "Cannot refile to position inside the tree or region"))
8063 (setq nbuf (or (find-buffer-visiting file)
8064 (find-file-noselect file)))
8065 (if goto
8066 (progn
8067 (switch-to-buffer nbuf)
8068 (goto-char pos)
8069 (org-show-context 'org-goto))
8070 (if regionp
8071 (progn
8072 (kill-new (buffer-substring region-start region-end))
8073 (org-save-markers-in-region region-start region-end))
8074 (org-copy-subtree 1 nil t))
8075 (save-excursion
8076 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8077 (find-file-noselect file))))
8078 (setq reversed (org-notes-order-reversed-p))
8079 (save-excursion
8080 (save-restriction
8081 (widen)
8082 (goto-char pos)
8083 (looking-at outline-regexp)
8084 (setq level (org-get-valid-level (funcall outline-level) 1))
8085 (goto-char
8086 (if reversed
8087 (or (outline-next-heading) (point-max))
8088 (or (save-excursion (outline-get-next-sibling))
8089 (org-end-of-subtree t t)
8090 (point-max))))
8091 (if (not (bolp)) (newline))
8092 (bookmark-set "org-refile-last-stored")
8093 (org-paste-subtree level))))
8094 (if regionp
8095 (delete-region (point) (+ (point) region-length))
8096 (org-cut-subtree))
8097 (setq org-markers-to-move nil)
8098 (message "Refiled to \"%s\"" (car it)))))))
8100 (defun org-refile-goto-last-stored ()
8101 "Go to the location where the last refile was stored."
8102 (interactive)
8103 (bookmark-jump "org-refile-last-stored")
8104 (message "This is the location of the last refile"))
8106 (defun org-refile-get-location (&optional prompt default-buffer)
8107 "Prompt the user for a refile location, using PROMPT."
8108 (let ((org-refile-targets org-refile-targets)
8109 (org-refile-use-outline-path org-refile-use-outline-path))
8110 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8111 (unless org-refile-target-table
8112 (error "No refile targets"))
8113 (let* ((cbuf (current-buffer))
8114 (partial-completion-mode nil)
8115 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8116 (cfunc (if (and org-refile-use-outline-path
8117 org-outline-path-complete-in-steps)
8118 'org-olpath-completing-read
8119 'org-ido-completing-read))
8120 (extra (if org-refile-use-outline-path "/" ""))
8121 (filename (and cfn (expand-file-name cfn)))
8122 (tbl (mapcar
8123 (lambda (x)
8124 (if (not (equal filename (nth 1 x)))
8125 (cons (concat (car x) extra " ("
8126 (file-name-nondirectory (nth 1 x)) ")")
8127 (cdr x))
8128 (cons (concat (car x) extra) (cdr x))))
8129 org-refile-target-table))
8130 (completion-ignore-case t))
8131 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
8132 tbl)))
8134 (defun org-olpath-completing-read (prompt collection &rest args)
8135 "Read an outline path like a file name."
8136 (let ((thetable collection)
8137 (org-completion-use-ido nil)) ; does not work with ido.
8138 (apply
8139 'org-ido-completing-read prompt
8140 (lambda (string predicate &optional flag)
8141 (let (rtn r f (l (length string)))
8142 (cond
8143 ((eq flag nil)
8144 ;; try completion
8145 (try-completion string thetable))
8146 ((eq flag t)
8147 ;; all-completions
8148 (setq rtn (all-completions string thetable predicate))
8149 (mapcar
8150 (lambda (x)
8151 (setq r (substring x l))
8152 (if (string-match " ([^)]*)$" x)
8153 (setq f (match-string 0 x))
8154 (setq f ""))
8155 (if (string-match "/" r)
8156 (concat string (substring r 0 (match-end 0)) f)
8158 rtn))
8159 ((eq flag 'lambda)
8160 ;; exact match?
8161 (assoc string thetable)))
8163 args)))
8165 ;;;; Dynamic blocks
8167 (defun org-find-dblock (name)
8168 "Find the first dynamic block with name NAME in the buffer.
8169 If not found, stay at current position and return nil."
8170 (let (pos)
8171 (save-excursion
8172 (goto-char (point-min))
8173 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8174 nil t)
8175 (match-beginning 0))))
8176 (if pos (goto-char pos))
8177 pos))
8179 (defconst org-dblock-start-re
8180 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8181 "Matches the startline of a dynamic block, with parameters.")
8183 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8184 "Matches the end of a dynamic block.")
8186 (defun org-create-dblock (plist)
8187 "Create a dynamic block section, with parameters taken from PLIST.
8188 PLIST must contain a :name entry which is used as name of the block."
8189 (unless (bolp) (newline))
8190 (let ((name (plist-get plist :name)))
8191 (insert "#+BEGIN: " name)
8192 (while plist
8193 (if (eq (car plist) :name)
8194 (setq plist (cddr plist))
8195 (insert " " (prin1-to-string (pop plist)))))
8196 (insert "\n\n#+END:\n")
8197 (beginning-of-line -2)))
8199 (defun org-prepare-dblock ()
8200 "Prepare dynamic block for refresh.
8201 This empties the block, puts the cursor at the insert position and returns
8202 the property list including an extra property :name with the block name."
8203 (unless (looking-at org-dblock-start-re)
8204 (error "Not at a dynamic block"))
8205 (let* ((begdel (1+ (match-end 0)))
8206 (name (org-no-properties (match-string 1)))
8207 (params (append (list :name name)
8208 (read (concat "(" (match-string 3) ")")))))
8209 (unless (re-search-forward org-dblock-end-re nil t)
8210 (error "Dynamic block not terminated"))
8211 (setq params
8212 (append params
8213 (list :content (buffer-substring
8214 begdel (match-beginning 0)))))
8215 (delete-region begdel (match-beginning 0))
8216 (goto-char begdel)
8217 (open-line 1)
8218 params))
8220 (defun org-map-dblocks (&optional command)
8221 "Apply COMMAND to all dynamic blocks in the current buffer.
8222 If COMMAND is not given, use `org-update-dblock'."
8223 (let ((cmd (or command 'org-update-dblock))
8224 pos)
8225 (save-excursion
8226 (goto-char (point-min))
8227 (while (re-search-forward org-dblock-start-re nil t)
8228 (goto-char (setq pos (match-beginning 0)))
8229 (condition-case nil
8230 (funcall cmd)
8231 (error (message "Error during update of dynamic block")))
8232 (goto-char pos)
8233 (unless (re-search-forward org-dblock-end-re nil t)
8234 (error "Dynamic block not terminated"))))))
8236 (defun org-dblock-update (&optional arg)
8237 "User command for updating dynamic blocks.
8238 Update the dynamic block at point. With prefix ARG, update all dynamic
8239 blocks in the buffer."
8240 (interactive "P")
8241 (if arg
8242 (org-update-all-dblocks)
8243 (or (looking-at org-dblock-start-re)
8244 (org-beginning-of-dblock))
8245 (org-update-dblock)))
8247 (defun org-update-dblock ()
8248 "Update the dynamic block at point
8249 This means to empty the block, parse for parameters and then call
8250 the correct writing function."
8251 (save-window-excursion
8252 (let* ((pos (point))
8253 (line (org-current-line))
8254 (params (org-prepare-dblock))
8255 (name (plist-get params :name))
8256 (cmd (intern (concat "org-dblock-write:" name))))
8257 (message "Updating dynamic block `%s' at line %d..." name line)
8258 (funcall cmd params)
8259 (message "Updating dynamic block `%s' at line %d...done" name line)
8260 (goto-char pos))))
8262 (defun org-beginning-of-dblock ()
8263 "Find the beginning of the dynamic block at point.
8264 Error if there is no such block at point."
8265 (let ((pos (point))
8266 beg)
8267 (end-of-line 1)
8268 (if (and (re-search-backward org-dblock-start-re nil t)
8269 (setq beg (match-beginning 0))
8270 (re-search-forward org-dblock-end-re nil t)
8271 (> (match-end 0) pos))
8272 (goto-char beg)
8273 (goto-char pos)
8274 (error "Not in a dynamic block"))))
8276 (defun org-update-all-dblocks ()
8277 "Update all dynamic blocks in the buffer.
8278 This function can be used in a hook."
8279 (when (org-mode-p)
8280 (org-map-dblocks 'org-update-dblock)))
8283 ;;;; Completion
8285 (defconst org-additional-option-like-keywords
8286 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8287 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8288 "BEGIN_EXAMPLE" "END_EXAMPLE"
8289 "BEGIN_QUOTE" "END_QUOTE"
8290 "BEGIN_VERSE" "END_VERSE"
8291 "BEGIN_SRC" "END_SRC"
8292 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
8294 (defcustom org-structure-template-alist
8296 ("s" "#+begin_src ?\n\n#+end_src"
8297 "<src lang=\"?\">\n\n</src>")
8298 ("e" "#+begin_example\n?\n#+end_example"
8299 "<example>\n?\n</example>")
8300 ("q" "#+begin_quote\n?\n#+end_quote"
8301 "<quote>\n?\n</quote>")
8302 ("v" "#+begin_verse\n?\n#+end_verse"
8303 "<verse>\n?\n/verse>")
8304 ("l" "#+begin_latex\n?\n#+end_latex"
8305 "<literal style=\"latex\">\n?\n</literal>")
8306 ("L" "#+latex: "
8307 "<literal style=\"latex\">?</literal>")
8308 ("h" "#+begin_html\n?\n#+end_html"
8309 "<literal style=\"html\">\n?\n</literal>")
8310 ("H" "#+html: "
8311 "<literal style=\"html\">?</literal>")
8312 ("a" "#+begin_ascii\n?\n#+end_ascii")
8313 ("A" "#+ascii: ")
8314 ("i" "#+include %file ?"
8315 "<include file=%file markup=\"?\">")
8317 "Structure completion elements.
8318 This is a list of abbreviation keys and values. The value gets inserted
8319 it you type @samp{.} followed by the key and then the completion key,
8320 usually `M-TAB'. %file will be replaced by a file name after prompting
8321 for the file using completion.
8322 There are two templates for each key, the first uses the original Org syntax,
8323 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8324 the default when the /org-mtags.el/ module has been loaded. See also the
8325 variable `org-mtags-prefer-muse-templates'.
8326 This is an experimental feature, it is undecided if it is going to stay in."
8327 :group 'org-completion
8328 :type '(repeat
8329 (string :tag "Key")
8330 (string :tag "Template")
8331 (string :tag "Muse Template")))
8333 (defun org-try-structure-completion ()
8334 "Try to complete a structure template before point.
8335 This looks for strings like \"<e\" on an otherwise empty line and
8336 expands them."
8337 (let ((l (buffer-substring (point-at-bol) (point)))
8339 (when (and (looking-at "[ \t]*$")
8340 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8341 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8342 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8343 (match-beginning 1)) a)
8344 t)))
8346 (defun org-complete-expand-structure-template (start cell)
8347 "Expand a structure template."
8348 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8349 (rpl (nth (if musep 2 1) cell)))
8350 (delete-region start (point))
8351 (when (string-match "\\`#\\+" rpl)
8352 (cond
8353 ((bolp))
8354 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8355 (delete-region (point-at-bol) (point)))
8356 (t (newline))))
8357 (setq start (point))
8358 (if (string-match "%file" rpl)
8359 (setq rpl (replace-match
8360 (concat
8361 "\""
8362 (save-match-data
8363 (abbreviate-file-name (read-file-name "Include file: ")))
8364 "\"")
8365 t t rpl)))
8366 (insert rpl)
8367 (if (re-search-backward "\\?" start t) (delete-char 1))))
8370 (defun org-complete (&optional arg)
8371 "Perform completion on word at point.
8372 At the beginning of a headline, this completes TODO keywords as given in
8373 `org-todo-keywords'.
8374 If the current word is preceded by a backslash, completes the TeX symbols
8375 that are supported for HTML support.
8376 If the current word is preceded by \"#+\", completes special words for
8377 setting file options.
8378 In the line after \"#+STARTUP:, complete valid keywords.\"
8379 At all other locations, this simply calls the value of
8380 `org-completion-fallback-command'."
8381 (interactive "P")
8382 (org-without-partial-completion
8383 (catch 'exit
8384 (let* ((a nil)
8385 (end (point))
8386 (beg1 (save-excursion
8387 (skip-chars-backward (org-re "[:alnum:]_@"))
8388 (point)))
8389 (beg (save-excursion
8390 (skip-chars-backward "a-zA-Z0-9_:$")
8391 (point)))
8392 (confirm (lambda (x) (stringp (car x))))
8393 (searchhead (equal (char-before beg) ?*))
8394 (struct
8395 (when (and (member (char-before beg1) '(?. ?<))
8396 (setq a (assoc (buffer-substring beg1 (point))
8397 org-structure-template-alist)))
8398 (org-complete-expand-structure-template (1- beg1) a)
8399 (throw 'exit t)))
8400 (tag (and (equal (char-before beg1) ?:)
8401 (equal (char-after (point-at-bol)) ?*)))
8402 (prop (and (equal (char-before beg1) ?:)
8403 (not (equal (char-after (point-at-bol)) ?*))))
8404 (texp (equal (char-before beg) ?\\))
8405 (link (equal (char-before beg) ?\[))
8406 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8407 beg)
8408 "#+"))
8409 (startup (string-match "^#\\+STARTUP:.*"
8410 (buffer-substring (point-at-bol) (point))))
8411 (completion-ignore-case opt)
8412 (type nil)
8413 (tbl nil)
8414 (table (cond
8415 (opt
8416 (setq type :opt)
8417 (require 'org-exp)
8418 (append
8419 (mapcar
8420 (lambda (x)
8421 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8422 (cons (match-string 2 x) (match-string 1 x)))
8423 (org-split-string (org-get-current-options) "\n"))
8424 (mapcar 'list org-additional-option-like-keywords)))
8425 (startup
8426 (setq type :startup)
8427 org-startup-options)
8428 (link (append org-link-abbrev-alist-local
8429 org-link-abbrev-alist))
8430 (texp
8431 (setq type :tex)
8432 org-html-entities)
8433 ((string-match "\\`\\*+[ \t]+\\'"
8434 (buffer-substring (point-at-bol) beg))
8435 (setq type :todo)
8436 (mapcar 'list org-todo-keywords-1))
8437 (searchhead
8438 (setq type :searchhead)
8439 (save-excursion
8440 (goto-char (point-min))
8441 (while (re-search-forward org-todo-line-regexp nil t)
8442 (push (list
8443 (org-make-org-heading-search-string
8444 (match-string 3) t))
8445 tbl)))
8446 tbl)
8447 (tag (setq type :tag beg beg1)
8448 (or org-tag-alist (org-get-buffer-tags)))
8449 (prop (setq type :prop beg beg1)
8450 (mapcar 'list (org-buffer-property-keys nil t t)))
8451 (t (progn
8452 (call-interactively org-completion-fallback-command)
8453 (throw 'exit nil)))))
8454 (pattern (buffer-substring-no-properties beg end))
8455 (completion (try-completion pattern table confirm)))
8456 (cond ((eq completion t)
8457 (if (not (assoc (upcase pattern) table))
8458 (message "Already complete")
8459 (if (and (equal type :opt)
8460 (not (member (car (assoc (upcase pattern) table))
8461 org-additional-option-like-keywords)))
8462 (insert (substring (cdr (assoc (upcase pattern) table))
8463 (length pattern)))
8464 (if (memq type '(:tag :prop)) (insert ":")))))
8465 ((null completion)
8466 (message "Can't find completion for \"%s\"" pattern)
8467 (ding))
8468 ((not (string= pattern completion))
8469 (delete-region beg end)
8470 (if (string-match " +$" completion)
8471 (setq completion (replace-match "" t t completion)))
8472 (insert completion)
8473 (if (get-buffer-window "*Completions*")
8474 (delete-window (get-buffer-window "*Completions*")))
8475 (if (assoc completion table)
8476 (if (eq type :todo) (insert " ")
8477 (if (memq type '(:tag :prop)) (insert ":"))))
8478 (if (and (equal type :opt) (assoc completion table))
8479 (message "%s" (substitute-command-keys
8480 "Press \\[org-complete] again to insert example settings"))))
8482 (message "Making completion list...")
8483 (let ((list (sort (all-completions pattern table confirm)
8484 'string<)))
8485 (with-output-to-temp-buffer "*Completions*"
8486 (condition-case nil
8487 ;; Protection needed for XEmacs and emacs 21
8488 (display-completion-list list pattern)
8489 (error (display-completion-list list)))))
8490 (message "Making completion list...%s" "done")))))))
8492 ;;;; TODO, DEADLINE, Comments
8494 (defun org-toggle-comment ()
8495 "Change the COMMENT state of an entry."
8496 (interactive)
8497 (save-excursion
8498 (org-back-to-heading)
8499 (let (case-fold-search)
8500 (if (looking-at (concat outline-regexp
8501 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8502 (replace-match "" t t nil 1)
8503 (if (looking-at outline-regexp)
8504 (progn
8505 (goto-char (match-end 0))
8506 (insert org-comment-string " ")))))))
8508 (defvar org-last-todo-state-is-todo nil
8509 "This is non-nil when the last TODO state change led to a TODO state.
8510 If the last change removed the TODO tag or switched to DONE, then
8511 this is nil.")
8513 (defvar org-setting-tags nil) ; dynamically skipped
8515 (defun org-parse-local-options (string var)
8516 "Parse STRING for startup setting relevant for variable VAR."
8517 (let ((rtn (symbol-value var))
8518 e opts)
8519 (save-match-data
8520 (if (or (not string) (not (string-match "\\S-" string)))
8522 (setq opts (delq nil (mapcar (lambda (x)
8523 (setq e (assoc x org-startup-options))
8524 (if (eq (nth 1 e) var) e nil))
8525 (org-split-string string "[ \t]+"))))
8526 (if (not opts)
8528 (setq rtn nil)
8529 (while (setq e (pop opts))
8530 (if (not (nth 3 e))
8531 (setq rtn (nth 2 e))
8532 (if (not (listp rtn)) (setq rtn nil))
8533 (push (nth 2 e) rtn)))
8534 rtn)))))
8536 (defvar org-todo-setup-filter-hook nil
8537 "Hook for functions that pre-filter todo specs.
8539 Each function takes a todo spec and returns either `nil' or the spec
8540 transformed into canonical form." )
8542 (defvar org-todo-get-default-hook nil
8543 "Hook for functions that get a default item for todo.
8545 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
8546 `nil' or a string to be used for the todo mark." )
8548 (defvar org-agenda-headline-snapshot-before-repeat)
8549 (defun org-todo (&optional arg)
8550 "Change the TODO state of an item.
8551 The state of an item is given by a keyword at the start of the heading,
8552 like
8553 *** TODO Write paper
8554 *** DONE Call mom
8556 The different keywords are specified in the variable `org-todo-keywords'.
8557 By default the available states are \"TODO\" and \"DONE\".
8558 So for this example: when the item starts with TODO, it is changed to DONE.
8559 When it starts with DONE, the DONE is removed. And when neither TODO nor
8560 DONE are present, add TODO at the beginning of the heading.
8562 With C-u prefix arg, use completion to determine the new state.
8563 With numeric prefix arg, switch to that state.
8564 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
8565 With a tripple C-u prefix, circumvent any state blocking.
8567 For calling through lisp, arg is also interpreted in the following way:
8568 'none -> empty state
8569 \"\"(empty string) -> switch to empty state
8570 'done -> switch to DONE
8571 'nextset -> switch to the next set of keywords
8572 'previousset -> switch to the previous set of keywords
8573 \"WAITING\" -> switch to the specified keyword, but only if it
8574 really is a member of `org-todo-keywords'."
8575 (interactive "P")
8576 (if (equal arg '(16)) (setq arg 'nextset))
8577 (let ((org-blocker-hook org-blocker-hook))
8578 (when (equal arg '(64))
8579 (setq arg nil org-blocker-hook nil))
8580 (save-excursion
8581 (catch 'exit
8582 (org-back-to-heading)
8583 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8584 (or (looking-at (concat " +" org-todo-regexp " *"))
8585 (looking-at " *"))
8586 (let* ((match-data (match-data))
8587 (startpos (point-at-bol))
8588 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8589 (org-log-done org-log-done)
8590 (org-log-repeat org-log-repeat)
8591 (org-todo-log-states org-todo-log-states)
8592 (this (match-string 1))
8593 (hl-pos (match-beginning 0))
8594 (head (org-get-todo-sequence-head this))
8595 (ass (assoc head org-todo-kwd-alist))
8596 (interpret (nth 1 ass))
8597 (done-word (nth 3 ass))
8598 (final-done-word (nth 4 ass))
8599 (last-state (or this ""))
8600 (completion-ignore-case t)
8601 (member (member this org-todo-keywords-1))
8602 (tail (cdr member))
8603 (state (cond
8604 ((and org-todo-key-trigger
8605 (or (and (equal arg '(4))
8606 (eq org-use-fast-todo-selection 'prefix))
8607 (and (not arg) org-use-fast-todo-selection
8608 (not (eq org-use-fast-todo-selection
8609 'prefix)))))
8610 ;; Use fast selection
8611 (org-fast-todo-selection))
8612 ((and (equal arg '(4))
8613 (or (not org-use-fast-todo-selection)
8614 (not org-todo-key-trigger)))
8615 ;; Read a state with completion
8616 (org-ido-completing-read
8617 "State: " (mapcar (lambda(x) (list x))
8618 org-todo-keywords-1)
8619 nil t))
8620 ((eq arg 'right)
8621 (if this
8622 (if tail (car tail) nil)
8623 (car org-todo-keywords-1)))
8624 ((eq arg 'left)
8625 (if (equal member org-todo-keywords-1)
8627 (if this
8628 (nth (- (length org-todo-keywords-1)
8629 (length tail) 2)
8630 org-todo-keywords-1)
8631 (org-last org-todo-keywords-1))))
8632 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8633 (setq arg nil))) ; hack to fall back to cycling
8634 (arg
8635 ;; user or caller requests a specific state
8636 (cond
8637 ((equal arg "") nil)
8638 ((eq arg 'none) nil)
8639 ((eq arg 'done) (or done-word (car org-done-keywords)))
8640 ((eq arg 'nextset)
8641 (or (car (cdr (member head org-todo-heads)))
8642 (car org-todo-heads)))
8643 ((eq arg 'previousset)
8644 (let ((org-todo-heads (reverse org-todo-heads)))
8645 (or (car (cdr (member head org-todo-heads)))
8646 (car org-todo-heads))))
8647 ((car (member arg org-todo-keywords-1)))
8648 ((nth (1- (prefix-numeric-value arg))
8649 org-todo-keywords-1))))
8650 ((null member) (or head (car org-todo-keywords-1)))
8651 ((equal this final-done-word) nil) ;; -> make empty
8652 ((null tail) nil) ;; -> first entry
8653 ((memq interpret '(type priority))
8654 (if (eq this-command last-command)
8655 (car tail)
8656 (if (> (length tail) 0)
8657 (or done-word (car org-done-keywords))
8658 nil)))
8660 (car tail))))
8661 (state (or
8662 (run-hook-with-args-until-success
8663 'org-todo-get-default-hook state last-state)
8664 state))
8665 (next (if state (concat " " state " ") " "))
8666 (change-plist (list :type 'todo-state-change :from this :to state
8667 :position startpos))
8668 dolog now-done-p)
8669 (when org-blocker-hook
8670 (setq org-last-todo-state-is-todo
8671 (not (member this org-done-keywords)))
8672 (unless (save-excursion
8673 (save-match-data
8674 (run-hook-with-args-until-failure
8675 'org-blocker-hook change-plist)))
8676 (if (interactive-p)
8677 (error "TODO state change from %s to %s blocked" this state)
8678 ;; fail silently
8679 (message "TODO state change from %s to %s blocked" this state)
8680 (throw 'exit nil))))
8681 (store-match-data match-data)
8682 (replace-match next t t)
8683 (unless (pos-visible-in-window-p hl-pos)
8684 (message "TODO state changed to %s" (org-trim next)))
8685 (unless head
8686 (setq head (org-get-todo-sequence-head state)
8687 ass (assoc head org-todo-kwd-alist)
8688 interpret (nth 1 ass)
8689 done-word (nth 3 ass)
8690 final-done-word (nth 4 ass)))
8691 (when (memq arg '(nextset previousset))
8692 (message "Keyword-Set %d/%d: %s"
8693 (- (length org-todo-sets) -1
8694 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8695 (length org-todo-sets)
8696 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8697 (setq org-last-todo-state-is-todo
8698 (not (member state org-done-keywords)))
8699 (setq now-done-p (and (member state org-done-keywords)
8700 (not (member this org-done-keywords))))
8701 (and logging (org-local-logging logging))
8702 (when (and (or org-todo-log-states org-log-done)
8703 (not (memq arg '(nextset previousset))))
8704 ;; we need to look at recording a time and note
8705 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8706 (nth 2 (assoc this org-todo-log-states))))
8707 (when (and state
8708 (member state org-not-done-keywords)
8709 (not (member this org-not-done-keywords)))
8710 ;; This is now a todo state and was not one before
8711 ;; If there was a CLOSED time stamp, get rid of it.
8712 (org-add-planning-info nil nil 'closed))
8713 (when (and now-done-p org-log-done)
8714 ;; It is now done, and it was not done before
8715 (org-add-planning-info 'closed (org-current-time))
8716 (if (and (not dolog) (eq 'note org-log-done))
8717 (org-add-log-setup 'done state this 'findpos 'note)))
8718 (when (and state dolog)
8719 ;; This is a non-nil state, and we need to log it
8720 (org-add-log-setup 'state state this 'findpos dolog)))
8721 ;; Fixup tag positioning
8722 (org-todo-trigger-tag-changes state)
8723 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8724 (when org-provide-todo-statistics
8725 (org-update-parent-todo-statistics))
8726 (run-hooks 'org-after-todo-state-change-hook)
8727 (if (and arg (not (member state org-done-keywords)))
8728 (setq head (org-get-todo-sequence-head state)))
8729 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8730 ;; Do we need to trigger a repeat?
8731 (when now-done-p
8732 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8733 ;; This is for the agenda, take a snapshot of the headline.
8734 (save-match-data
8735 (setq org-agenda-headline-snapshot-before-repeat
8736 (org-get-heading))))
8737 (org-auto-repeat-maybe state))
8738 ;; Fixup cursor location if close to the keyword
8739 (if (and (outline-on-heading-p)
8740 (not (bolp))
8741 (save-excursion (beginning-of-line 1)
8742 (looking-at org-todo-line-regexp))
8743 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8744 (progn
8745 (goto-char (or (match-end 2) (match-end 1)))
8746 (just-one-space)))
8747 (when org-trigger-hook
8748 (save-excursion
8749 (run-hook-with-args 'org-trigger-hook change-plist))))))))
8751 (defun org-block-todo-from-children-or-siblings (change-plist)
8752 "Block turning an entry into a TODO, using the hierarchy.
8753 This checks whether the current task should be blocked from state
8754 changes. Such blocking occurs when:
8756 1. The task has children which are not all in a completed state.
8758 2. A task has a parent with the property :ORDERED:, and there
8759 are siblings prior to the current task with incomplete
8760 status."
8761 (catch 'dont-block
8762 ;; If this is not a todo state change, or if this entry is already DONE,
8763 ;; do not block
8764 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8765 (member (plist-get change-plist :from)
8766 (cons 'done org-done-keywords))
8767 (member (plist-get change-plist :to)
8768 (cons 'todo org-not-done-keywords)))
8769 (throw 'dont-block t))
8770 ;; If this task has children, and any are undone, it's blocked
8771 (save-excursion
8772 (org-back-to-heading t)
8773 (let ((this-level (funcall outline-level)))
8774 (outline-next-heading)
8775 (let ((child-level (funcall outline-level)))
8776 (while (and (not (eobp))
8777 (> child-level this-level))
8778 ;; this todo has children, check whether they are all
8779 ;; completed
8780 (if (and (not (org-entry-is-done-p))
8781 (org-entry-is-todo-p))
8782 (throw 'dont-block nil))
8783 (outline-next-heading)
8784 (setq child-level (funcall outline-level))))))
8785 ;; Otherwise, if the task's parent has the :ORDERED: property, and
8786 ;; any previous siblings are undone, it's blocked
8787 (save-excursion
8788 (org-back-to-heading t)
8789 (when (save-excursion
8790 (ignore-errors
8791 (org-up-heading-all 1)
8792 (org-entry-get (point) "ORDERED")))
8793 (let* ((this-level (funcall outline-level))
8794 (current-level this-level))
8795 (while (and (not (bobp))
8796 (= current-level this-level))
8797 (outline-previous-heading)
8798 (setq current-level (funcall outline-level))
8799 (if (= current-level this-level)
8800 ;; this todo has children, check whether they are all
8801 ;; completed
8802 (if (and (not (org-entry-is-done-p))
8803 (org-entry-is-todo-p))
8804 (throw 'dont-block nil)))))))
8805 t)) ; don't block
8807 (defcustom org-track-ordered-property-with-tag nil
8808 "Should the ORDERED property also be shown as a tag?
8809 The ORDERED property decides if an entry should require subtasks to be
8810 completed in sequence. Since a property is not very visible, setting
8811 this option means that toggling the ORDERED property with the command
8812 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
8813 not relevant for the behavior, but it makes things more visible.
8815 Note that toggling the tag with tags commands will not change the property
8816 and therefore not influence behavior!
8818 This can be t, meaning the tag ORDERED should be used, It can also be a
8819 string to select a different tag for this task."
8820 :group 'org-todo
8821 :type '(choice
8822 (const :tag "No tracking" nil)
8823 (const :tag "Track with ORDERED tag" t)
8824 (string :tag "Use other tag")))
8826 (defun org-toggle-ordered-property ()
8827 "Toggle the ORDERED property of the current entry.
8828 For better visibility, you can track the value of this property with a tag.
8829 See variable `org-track-ordered-property-with-tag'."
8830 (interactive)
8831 (let* ((t1 org-track-ordered-property-with-tag)
8832 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
8833 (save-excursion
8834 (org-back-to-heading)
8835 (if (org-entry-get nil "ORDERED")
8836 (progn
8837 (org-delete-property "ORDERED")
8838 (and tag (org-toggle-tag tag 'off))
8839 (message "Subtasks can be completed in arbitrary order"))
8840 (org-entry-put nil "ORDERED" "t")
8841 (and tag (org-toggle-tag tag 'on))
8842 (message "Subtasks must be completed in sequence")))))
8844 (defvar org-blocked-by-checkboxes) ; dynamically scoped
8845 (defun org-block-todo-from-checkboxes (change-plist)
8846 "Block turning an entry into a TODO, using checkboxes.
8847 This checks whether the current task should be blocked from state
8848 changes because there are uncheckd boxes in this entry."
8849 (catch 'dont-block
8850 ;; If this is not a todo state change, or if this entry is already DONE,
8851 ;; do not block
8852 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8853 (member (plist-get change-plist :from)
8854 (cons 'done org-done-keywords))
8855 (member (plist-get change-plist :to)
8856 (cons 'todo org-not-done-keywords)))
8857 (throw 'dont-block t))
8858 ;; If this task has checkboxes that are not checked, it's blocked
8859 (save-excursion
8860 (org-back-to-heading t)
8861 (let ((beg (point)) end)
8862 (outline-next-heading)
8863 (setq end (point))
8864 (goto-char beg)
8865 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
8866 end t)
8867 (progn
8868 (if (boundp 'org-blocked-by-checkboxes)
8869 (setq org-blocked-by-checkboxes t))
8870 (throw 'dont-block nil)))))
8871 t)) ; do not block
8873 (defun org-update-parent-todo-statistics ()
8874 "Update any statistics cookie in the parent of the current headline."
8875 (interactive)
8876 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8877 level (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
8878 (catch 'exit
8879 (save-excursion
8880 (setq level (org-up-heading-safe))
8881 (unless level
8882 (throw 'exit nil))
8883 (while (re-search-forward box-re (point-at-eol) t)
8884 (setq cnt-all 0 cnt-done 0 cookie-present t)
8885 (setq is-percent (match-end 2))
8886 (save-match-data
8887 (unless (outline-next-heading) (throw 'exit nil))
8888 (while (looking-at org-todo-line-regexp)
8889 (setq kwd (match-string 2))
8890 (and kwd (setq cnt-all (1+ cnt-all)))
8891 (and (member kwd org-done-keywords)
8892 (setq cnt-done (1+ cnt-done)))
8893 (condition-case nil
8894 (org-forward-same-level 1)
8895 (error (end-of-line 1)))))
8896 (replace-match
8897 (if is-percent
8898 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8899 (format "[%d/%d]" cnt-done cnt-all))))
8900 (when cookie-present
8901 (run-hook-with-args 'org-after-todo-statistics-hook
8902 cnt-done (- cnt-all cnt-done)))))))
8904 (defvar org-after-todo-statistics-hook nil
8905 "Hook that is called after a TODO statistics cookie has been updated.
8906 Each function is called with two arguments: the number of not-done entries
8907 and the number of done entries.
8909 For example, the following function, when added to this hook, will switch
8910 an entry to DONE when all children are done, and back to TODO when new
8911 entries are set to a TODO status. Note that this hook is only called
8912 when there is a statistics cookie in the headline!
8914 (defun org-summary-todo (n-done n-not-done)
8915 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8916 (let (org-log-done org-log-states) ; turn off logging
8917 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8920 (defun org-todo-trigger-tag-changes (state)
8921 "Apply the changes defined in `org-todo-state-tags-triggers'."
8922 (let ((l org-todo-state-tags-triggers)
8923 changes)
8924 (when (or (not state) (equal state ""))
8925 (setq changes (append changes (cdr (assoc "" l)))))
8926 (when (and (stringp state) (> (length state) 0))
8927 (setq changes (append changes (cdr (assoc state l)))))
8928 (when (member state org-not-done-keywords)
8929 (setq changes (append changes (cdr (assoc 'todo l)))))
8930 (when (member state org-done-keywords)
8931 (setq changes (append changes (cdr (assoc 'done l)))))
8932 (dolist (c changes)
8933 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8935 (defun org-local-logging (value)
8936 "Get logging settings from a property VALUE."
8937 (let* (words w a)
8938 ;; directly set the variables, they are already local.
8939 (setq org-log-done nil
8940 org-log-repeat nil
8941 org-todo-log-states nil)
8942 (setq words (org-split-string value))
8943 (while (setq w (pop words))
8944 (cond
8945 ((setq a (assoc w org-startup-options))
8946 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8947 (set (nth 1 a) (nth 2 a))))
8948 ((setq a (org-extract-log-state-settings w))
8949 (and (member (car a) org-todo-keywords-1)
8950 (push a org-todo-log-states)))))))
8952 (defun org-get-todo-sequence-head (kwd)
8953 "Return the head of the TODO sequence to which KWD belongs.
8954 If KWD is not set, check if there is a text property remembering the
8955 right sequence."
8956 (let (p)
8957 (cond
8958 ((not kwd)
8959 (or (get-text-property (point-at-bol) 'org-todo-head)
8960 (progn
8961 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8962 nil (point-at-eol)))
8963 (get-text-property p 'org-todo-head))))
8964 ((not (member kwd org-todo-keywords-1))
8965 (car org-todo-keywords-1))
8966 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8968 (defun org-fast-todo-selection ()
8969 "Fast TODO keyword selection with single keys.
8970 Returns the new TODO keyword, or nil if no state change should occur."
8971 (let* ((fulltable org-todo-key-alist)
8972 (done-keywords org-done-keywords) ;; needed for the faces.
8973 (maxlen (apply 'max (mapcar
8974 (lambda (x)
8975 (if (stringp (car x)) (string-width (car x)) 0))
8976 fulltable)))
8977 (expert nil)
8978 (fwidth (+ maxlen 3 1 3))
8979 (ncol (/ (- (window-width) 4) fwidth))
8980 tg cnt e c tbl
8981 groups ingroup)
8982 (save-excursion
8983 (save-window-excursion
8984 (if expert
8985 (set-buffer (get-buffer-create " *Org todo*"))
8986 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8987 (erase-buffer)
8988 (org-set-local 'org-done-keywords done-keywords)
8989 (setq tbl fulltable cnt 0)
8990 (while (setq e (pop tbl))
8991 (cond
8992 ((equal e '(:startgroup))
8993 (push '() groups) (setq ingroup t)
8994 (when (not (= cnt 0))
8995 (setq cnt 0)
8996 (insert "\n"))
8997 (insert "{ "))
8998 ((equal e '(:endgroup))
8999 (setq ingroup nil cnt 0)
9000 (insert "}\n"))
9001 ((equal e '(:newline))
9002 (when (not (= cnt 0))
9003 (setq cnt 0)
9004 (insert "\n")
9005 (setq e (car tbl))
9006 (while (equal (car tbl) '(:newline))
9007 (insert "\n")
9008 (setq tbl (cdr tbl)))))
9010 (setq tg (car e) c (cdr e))
9011 (if ingroup (push tg (car groups)))
9012 (setq tg (org-add-props tg nil 'face
9013 (org-get-todo-face tg)))
9014 (if (and (= cnt 0) (not ingroup)) (insert " "))
9015 (insert "[" c "] " tg (make-string
9016 (- fwidth 4 (length tg)) ?\ ))
9017 (when (= (setq cnt (1+ cnt)) ncol)
9018 (insert "\n")
9019 (if ingroup (insert " "))
9020 (setq cnt 0)))))
9021 (insert "\n")
9022 (goto-char (point-min))
9023 (if (not expert) (org-fit-window-to-buffer))
9024 (message "[a-z..]:Set [SPC]:clear")
9025 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9026 (cond
9027 ((or (= c ?\C-g)
9028 (and (= c ?q) (not (rassoc c fulltable))))
9029 (setq quit-flag t))
9030 ((= c ?\ ) nil)
9031 ((setq e (rassoc c fulltable) tg (car e))
9033 (t (setq quit-flag t)))))))
9035 (defun org-entry-is-todo-p ()
9036 (member (org-get-todo-state) org-not-done-keywords))
9038 (defun org-entry-is-done-p ()
9039 (member (org-get-todo-state) org-done-keywords))
9041 (defun org-get-todo-state ()
9042 (save-excursion
9043 (org-back-to-heading t)
9044 (and (looking-at org-todo-line-regexp)
9045 (match-end 2)
9046 (match-string 2))))
9048 (defun org-at-date-range-p (&optional inactive-ok)
9049 "Is the cursor inside a date range?"
9050 (interactive)
9051 (save-excursion
9052 (catch 'exit
9053 (let ((pos (point)))
9054 (skip-chars-backward "^[<\r\n")
9055 (skip-chars-backward "<[")
9056 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9057 (>= (match-end 0) pos)
9058 (throw 'exit t))
9059 (skip-chars-backward "^<[\r\n")
9060 (skip-chars-backward "<[")
9061 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9062 (>= (match-end 0) pos)
9063 (throw 'exit t)))
9064 nil)))
9066 (defun org-get-repeat ()
9067 "Check if there is a deadline/schedule with repeater in this entry."
9068 (save-match-data
9069 (save-excursion
9070 (org-back-to-heading t)
9071 (if (re-search-forward
9072 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9073 (match-string 1)))))
9075 (defvar org-last-changed-timestamp)
9076 (defvar org-last-inserted-timestamp)
9077 (defvar org-log-post-message)
9078 (defvar org-log-note-purpose)
9079 (defvar org-log-note-how)
9080 (defvar org-log-note-extra)
9081 (defun org-auto-repeat-maybe (done-word)
9082 "Check if the current headline contains a repeated deadline/schedule.
9083 If yes, set TODO state back to what it was and change the base date
9084 of repeating deadline/scheduled time stamps to new date.
9085 This function is run automatically after each state change to a DONE state."
9086 ;; last-state is dynamically scoped into this function
9087 (let* ((repeat (org-get-repeat))
9088 (aa (assoc last-state org-todo-kwd-alist))
9089 (interpret (nth 1 aa))
9090 (head (nth 2 aa))
9091 (whata '(("d" . day) ("m" . month) ("y" . year)))
9092 (msg "Entry repeats: ")
9093 (org-log-done nil)
9094 (org-todo-log-states nil)
9095 (nshiftmax 10) (nshift 0)
9096 re type n what ts time)
9097 (when repeat
9098 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9099 (org-todo (if (eq interpret 'type) last-state head))
9100 (when org-log-repeat
9101 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9102 (memq 'org-add-log-note post-command-hook))
9103 ;; OK, we are already setup for some record
9104 (if (eq org-log-repeat 'note)
9105 ;; make sure we take a note, not only a time stamp
9106 (setq org-log-note-how 'note))
9107 ;; Set up for taking a record
9108 (org-add-log-setup 'state (or done-word (car org-done-keywords))
9109 last-state
9110 'findpos org-log-repeat)))
9111 (org-back-to-heading t)
9112 (org-add-planning-info nil nil 'closed)
9113 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9114 org-deadline-time-regexp "\\)\\|\\("
9115 org-ts-regexp "\\)"))
9116 (while (re-search-forward
9117 re (save-excursion (outline-next-heading) (point)) t)
9118 (setq type (if (match-end 1) org-scheduled-string
9119 (if (match-end 3) org-deadline-string "Plain:"))
9120 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
9121 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
9122 (setq n (string-to-number (match-string 2 ts))
9123 what (match-string 3 ts))
9124 (if (equal what "w") (setq n (* n 7) what "d"))
9125 ;; Preparation, see if we need to modify the start date for the change
9126 (when (match-end 1)
9127 (setq time (save-match-data (org-time-string-to-time ts)))
9128 (cond
9129 ((equal (match-string 1 ts) ".")
9130 ;; Shift starting date to today
9131 (org-timestamp-change
9132 (- (time-to-days (current-time)) (time-to-days time))
9133 'day))
9134 ((equal (match-string 1 ts) "+")
9135 (while (or (= nshift 0)
9136 (<= (time-to-days time) (time-to-days (current-time))))
9137 (when (= (incf nshift) nshiftmax)
9138 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
9139 (error "Abort")))
9140 (org-timestamp-change n (cdr (assoc what whata)))
9141 (org-at-timestamp-p t)
9142 (setq ts (match-string 1))
9143 (setq time (save-match-data (org-time-string-to-time ts))))
9144 (org-timestamp-change (- n) (cdr (assoc what whata)))
9145 ;; rematch, so that we have everything in place for the real shift
9146 (org-at-timestamp-p t)
9147 (setq ts (match-string 1))
9148 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
9149 (org-timestamp-change n (cdr (assoc what whata)))
9150 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
9151 (setq org-log-post-message msg)
9152 (message "%s" msg))))
9154 (defun org-show-todo-tree (arg)
9155 "Make a compact tree which shows all headlines marked with TODO.
9156 The tree will show the lines where the regexp matches, and all higher
9157 headlines above the match.
9158 With a \\[universal-argument] prefix, also show the DONE entries.
9159 With a numeric prefix N, construct a sparse tree for the Nth element
9160 of `org-todo-keywords-1'."
9161 (interactive "P")
9162 (let ((case-fold-search nil)
9163 (kwd-re
9164 (cond ((null arg) org-not-done-regexp)
9165 ((equal arg '(4))
9166 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
9167 (mapcar 'list org-todo-keywords-1))))
9168 (concat "\\("
9169 (mapconcat 'identity (org-split-string kwd "|") "\\|")
9170 "\\)\\>")))
9171 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
9172 (regexp-quote (nth (1- (prefix-numeric-value arg))
9173 org-todo-keywords-1)))
9174 (t (error "Invalid prefix argument: %s" arg)))))
9175 (message "%d TODO entries found"
9176 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
9178 (defun org-deadline (&optional remove time)
9179 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
9180 With argument REMOVE, remove any deadline from the item.
9181 When TIME is set, it should be an internal time specification, and the
9182 scheduling will use the corresponding date."
9183 (interactive "P")
9184 (if remove
9185 (progn
9186 (org-remove-timestamp-with-keyword org-deadline-string)
9187 (message "Item no longer has a deadline."))
9188 (if (org-get-repeat)
9189 (error "Cannot change deadline on task with repeater, please do that by hand")
9190 (org-add-planning-info 'deadline time 'closed)
9191 (message "Deadline on %s" org-last-inserted-timestamp))))
9193 (defun org-schedule (&optional remove time)
9194 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
9195 With argument REMOVE, remove any scheduling date from the item.
9196 When TIME is set, it should be an internal time specification, and the
9197 scheduling will use the corresponding date."
9198 (interactive "P")
9199 (if remove
9200 (progn
9201 (org-remove-timestamp-with-keyword org-scheduled-string)
9202 (message "Item is no longer scheduled."))
9203 (if (org-get-repeat)
9204 (error "Cannot reschedule task with repeater, please do that by hand")
9205 (org-add-planning-info 'scheduled time 'closed)
9206 (message "Scheduled to %s" org-last-inserted-timestamp))))
9208 (defun org-get-scheduled-time (pom &optional inherit)
9209 "Get the scheduled time as a time tuple, of a format suitable
9210 for calling org-schedule with, or if there is no scheduling,
9211 returns nil."
9212 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
9213 (when time
9214 (apply 'encode-time (org-parse-time-string time)))))
9216 (defun org-get-deadline-time (pom &optional inherit)
9217 "Get the deadine as a time tuple, of a format suitable for
9218 calling org-deadlin with, or if there is no scheduling, returns
9219 nil."
9220 (let ((time (org-entry-get pom "DEADLINE" inherit)))
9221 (when time
9222 (apply 'encode-time (org-parse-time-string time)))))
9224 (defun org-remove-timestamp-with-keyword (keyword)
9225 "Remove all time stamps with KEYWORD in the current entry."
9226 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
9227 beg)
9228 (save-excursion
9229 (org-back-to-heading t)
9230 (setq beg (point))
9231 (org-end-of-subtree t t)
9232 (while (re-search-backward re beg t)
9233 (replace-match "")
9234 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9235 (equal (char-before) ?\ ))
9236 (backward-delete-char 1)
9237 (if (string-match "^[ \t]*$" (buffer-substring
9238 (point-at-bol) (point-at-eol)))
9239 (delete-region (point-at-bol)
9240 (min (point-max) (1+ (point-at-eol))))))))))
9242 (defun org-add-planning-info (what &optional time &rest remove)
9243 "Insert new timestamp with keyword in the line directly after the headline.
9244 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9245 If non is given, the user is prompted for a date.
9246 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9247 be removed."
9248 (interactive)
9249 (let (org-time-was-given org-end-time-was-given ts
9250 end default-time default-input)
9252 (catch 'exit
9253 (when (and (not time) (memq what '(scheduled deadline)))
9254 ;; Try to get a default date/time from existing timestamp
9255 (save-excursion
9256 (org-back-to-heading t)
9257 (setq end (save-excursion (outline-next-heading) (point)))
9258 (when (re-search-forward (if (eq what 'scheduled)
9259 org-scheduled-time-regexp
9260 org-deadline-time-regexp)
9261 end t)
9262 (setq ts (match-string 1)
9263 default-time
9264 (apply 'encode-time (org-parse-time-string ts))
9265 default-input (and ts (org-get-compact-tod ts))))))
9266 (when what
9267 ;; If necessary, get the time from the user
9268 (setq time (or time (org-read-date nil 'to-time nil nil
9269 default-time default-input))))
9271 (when (and org-insert-labeled-timestamps-at-point
9272 (member what '(scheduled deadline)))
9273 (insert
9274 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9275 (org-insert-time-stamp time org-time-was-given
9276 nil nil nil (list org-end-time-was-given))
9277 (setq what nil))
9278 (save-excursion
9279 (save-restriction
9280 (let (col list elt ts buffer-invisibility-spec)
9281 (org-back-to-heading t)
9282 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9283 (goto-char (match-end 1))
9284 (setq col (current-column))
9285 (goto-char (match-end 0))
9286 (if (eobp) (insert "\n") (forward-char 1))
9287 (when (and (not what)
9288 (not (looking-at org-keyword-time-not-clock-regexp)))
9289 ;; Nothing to add, nothing to remove...... :-)
9290 (throw 'exit nil))
9291 (if (and (not (looking-at outline-regexp))
9292 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9293 "[^\r\n]*"))
9294 (not (equal (match-string 1) org-clock-string)))
9295 (narrow-to-region (match-beginning 0) (match-end 0))
9296 (insert-before-markers "\n")
9297 (backward-char 1)
9298 (narrow-to-region (point) (point))
9299 (and org-adapt-indentation (org-indent-to-column col)))
9300 ;; Check if we have to remove something.
9301 (setq list (cons what remove))
9302 (while list
9303 (setq elt (pop list))
9304 (goto-char (point-min))
9305 (when (or (and (eq elt 'scheduled)
9306 (re-search-forward org-scheduled-time-regexp nil t))
9307 (and (eq elt 'deadline)
9308 (re-search-forward org-deadline-time-regexp nil t))
9309 (and (eq elt 'closed)
9310 (re-search-forward org-closed-time-regexp nil t)))
9311 (replace-match "")
9312 (if (looking-at "--+<[^>]+>") (replace-match ""))
9313 (if (looking-at " +") (replace-match ""))))
9314 (goto-char (point-max))
9315 (when what
9316 (insert
9317 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9318 (cond ((eq what 'scheduled) org-scheduled-string)
9319 ((eq what 'deadline) org-deadline-string)
9320 ((eq what 'closed) org-closed-string))
9321 " ")
9322 (setq ts (org-insert-time-stamp
9323 time
9324 (or org-time-was-given
9325 (and (eq what 'closed) org-log-done-with-time))
9326 (eq what 'closed)
9327 nil nil (list org-end-time-was-given)))
9328 (end-of-line 1))
9329 (goto-char (point-min))
9330 (widen)
9331 (if (and (looking-at "[ \t]+\n")
9332 (equal (char-before) ?\n))
9333 (delete-region (1- (point)) (point-at-eol)))
9334 ts))))))
9336 (defvar org-log-note-marker (make-marker))
9337 (defvar org-log-note-purpose nil)
9338 (defvar org-log-note-state nil)
9339 (defvar org-log-note-previous-state nil)
9340 (defvar org-log-note-how nil)
9341 (defvar org-log-note-extra nil)
9342 (defvar org-log-note-window-configuration nil)
9343 (defvar org-log-note-return-to (make-marker))
9344 (defvar org-log-post-message nil
9345 "Message to be displayed after a log note has been stored.
9346 The auto-repeater uses this.")
9348 (defun org-add-note ()
9349 "Add a note to the current entry.
9350 This is done in the same way as adding a state change note."
9351 (interactive)
9352 (org-add-log-setup 'note nil nil 'findpos nil))
9354 (defvar org-property-end-re)
9355 (defun org-add-log-setup (&optional purpose state prev-state
9356 findpos how &optional extra)
9357 "Set up the post command hook to take a note.
9358 If this is about to TODO state change, the new state is expected in STATE.
9359 When FINDPOS is non-nil, find the correct position for the note in
9360 the current entry. If not, assume that it can be inserted at point.
9361 HOW is an indicator what kind of note should be created.
9362 EXTRA is additional text that will be inserted into the notes buffer."
9363 (let ((drawer (cond ((stringp org-log-into-drawer)
9364 org-log-into-drawer)
9365 (org-log-into-drawer "LOGBOOK")
9366 (t nil))))
9367 (save-restriction
9368 (save-excursion
9369 (when findpos
9370 (org-back-to-heading t)
9371 (narrow-to-region (point) (save-excursion
9372 (outline-next-heading) (point)))
9373 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9374 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9375 "[^\r\n]*\\)?"))
9376 (goto-char (match-end 0))
9377 (cond
9378 (drawer
9379 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
9380 nil t)
9381 (progn
9382 (goto-char (match-end 0))
9383 (or org-log-states-order-reversed
9384 (and (re-search-forward org-property-end-re nil t)
9385 (goto-char (1- (match-beginning 0))))))
9386 (insert "\n:" drawer ":\n:END:")
9387 (beginning-of-line 0)
9388 (org-indent-line-function)
9389 (beginning-of-line 2)
9390 (org-indent-line-function)
9391 (end-of-line 0)))
9392 ((and org-log-state-notes-insert-after-drawers
9393 (save-excursion
9394 (forward-line) (looking-at org-drawer-regexp)))
9395 (forward-line)
9396 (while (looking-at org-drawer-regexp)
9397 (goto-char (match-end 0))
9398 (re-search-forward org-property-end-re (point-max) t)
9399 (forward-line))
9400 (forward-line -1)))
9401 (unless org-log-states-order-reversed
9402 (and (= (char-after) ?\n) (forward-char 1))
9403 (org-skip-over-state-notes)
9404 (skip-chars-backward " \t\n\r")))
9405 (move-marker org-log-note-marker (point))
9406 (setq org-log-note-purpose purpose
9407 org-log-note-state state
9408 org-log-note-previous-state prev-state
9409 org-log-note-how how
9410 org-log-note-extra extra)
9411 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
9413 (defun org-skip-over-state-notes ()
9414 "Skip past the list of State notes in an entry."
9415 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9416 (while (looking-at "[ \t]*- State")
9417 (condition-case nil
9418 (org-next-item)
9419 (error (org-end-of-item)))))
9421 (defun org-add-log-note (&optional purpose)
9422 "Pop up a window for taking a note, and add this note later at point."
9423 (remove-hook 'post-command-hook 'org-add-log-note)
9424 (setq org-log-note-window-configuration (current-window-configuration))
9425 (delete-other-windows)
9426 (move-marker org-log-note-return-to (point))
9427 (switch-to-buffer (marker-buffer org-log-note-marker))
9428 (goto-char org-log-note-marker)
9429 (org-switch-to-buffer-other-window "*Org Note*")
9430 (erase-buffer)
9431 (if (memq org-log-note-how '(time state))
9432 (let (current-prefix-arg) (org-store-log-note))
9433 (let ((org-inhibit-startup t)) (org-mode))
9434 (insert (format "# Insert note for %s.
9435 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9436 (cond
9437 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9438 ((eq org-log-note-purpose 'done) "closed todo item")
9439 ((eq org-log-note-purpose 'state)
9440 (format "state change from \"%s\" to \"%s\""
9441 (or org-log-note-previous-state "")
9442 (or org-log-note-state "")))
9443 ((eq org-log-note-purpose 'note)
9444 "this entry")
9445 (t (error "This should not happen")))))
9446 (if org-log-note-extra (insert org-log-note-extra))
9447 (org-set-local 'org-finish-function 'org-store-log-note)))
9449 (defvar org-note-abort nil) ; dynamically scoped
9450 (defun org-store-log-note ()
9451 "Finish taking a log note, and insert it to where it belongs."
9452 (let ((txt (buffer-string))
9453 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9454 lines ind)
9455 (kill-buffer (current-buffer))
9456 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9457 (setq txt (replace-match "" t t txt)))
9458 (if (string-match "\\s-+\\'" txt)
9459 (setq txt (replace-match "" t t txt)))
9460 (setq lines (org-split-string txt "\n"))
9461 (when (and note (string-match "\\S-" note))
9462 (setq note
9463 (org-replace-escapes
9464 note
9465 (list (cons "%u" (user-login-name))
9466 (cons "%U" user-full-name)
9467 (cons "%t" (format-time-string
9468 (org-time-stamp-format 'long 'inactive)
9469 (current-time)))
9470 (cons "%s" (if org-log-note-state
9471 (concat "\"" org-log-note-state "\"")
9472 ""))
9473 (cons "%S" (if org-log-note-previous-state
9474 (concat "\"" org-log-note-previous-state "\"")
9475 "\"\"")))))
9476 (if lines (setq note (concat note " \\\\")))
9477 (push note lines))
9478 (when (or current-prefix-arg org-note-abort) (setq lines nil))
9479 (when lines
9480 (save-excursion
9481 (set-buffer (marker-buffer org-log-note-marker))
9482 (save-excursion
9483 (goto-char org-log-note-marker)
9484 (move-marker org-log-note-marker nil)
9485 (end-of-line 1)
9486 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9487 (insert "- " (pop lines))
9488 (org-indent-line-function)
9489 (beginning-of-line 1)
9490 (looking-at "[ \t]*")
9491 (setq ind (concat (match-string 0) " "))
9492 (end-of-line 1)
9493 (while lines (insert "\n" ind (pop lines)))
9494 (message "Note stored")
9495 (org-back-to-heading t)
9496 (org-cycle-hide-drawers 'children)))))
9497 (set-window-configuration org-log-note-window-configuration)
9498 (with-current-buffer (marker-buffer org-log-note-return-to)
9499 (goto-char org-log-note-return-to))
9500 (move-marker org-log-note-return-to nil)
9501 (and org-log-post-message (message "%s" org-log-post-message)))
9503 (defun org-sparse-tree (&optional arg)
9504 "Create a sparse tree, prompt for the details.
9505 This command can create sparse trees. You first need to select the type
9506 of match used to create the tree:
9508 t Show entries with a specific TODO keyword.
9509 T Show entries selected by a tags match.
9510 p Enter a property name and its value (both with completion on existing
9511 names/values) and show entries with that property.
9512 r Show entries matching a regular expression
9513 d Show deadlines due within `org-deadline-warning-days'."
9514 (interactive "P")
9515 (let (ans kwd value)
9516 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
9517 (setq ans (read-char-exclusive))
9518 (cond
9519 ((equal ans ?d)
9520 (call-interactively 'org-check-deadlines))
9521 ((equal ans ?b)
9522 (call-interactively 'org-check-before-date))
9523 ((equal ans ?t)
9524 (org-show-todo-tree '(4)))
9525 ((equal ans ?T)
9526 (call-interactively 'org-tags-sparse-tree))
9527 ((member ans '(?p ?P))
9528 (setq kwd (org-ido-completing-read "Property: "
9529 (mapcar 'list (org-buffer-property-keys))))
9530 (setq value (org-ido-completing-read "Value: "
9531 (mapcar 'list (org-property-values kwd))))
9532 (unless (string-match "\\`{.*}\\'" value)
9533 (setq value (concat "\"" value "\"")))
9534 (org-tags-sparse-tree arg (concat kwd "=" value)))
9535 ((member ans '(?r ?R ?/))
9536 (call-interactively 'org-occur))
9537 (t (error "No such sparse tree command \"%c\"" ans)))))
9539 (defvar org-occur-highlights nil
9540 "List of overlays used for occur matches.")
9541 (make-variable-buffer-local 'org-occur-highlights)
9542 (defvar org-occur-parameters nil
9543 "Parameters of the active org-occur calls.
9544 This is a list, each call to org-occur pushes as cons cell,
9545 containing the regular expression and the callback, onto the list.
9546 The list can contain several entries if `org-occur' has been called
9547 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9548 will only contain one set of parameters. When the highlights are
9549 removed (for example with `C-c C-c', or with the next edit (depending
9550 on `org-remove-highlights-with-change'), this variable is emptied
9551 as well.")
9552 (make-variable-buffer-local 'org-occur-parameters)
9554 (defun org-occur (regexp &optional keep-previous callback)
9555 "Make a compact tree which shows all matches of REGEXP.
9556 The tree will show the lines where the regexp matches, and all higher
9557 headlines above the match. It will also show the heading after the match,
9558 to make sure editing the matching entry is easy.
9559 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9560 call to `org-occur' will be kept, to allow stacking of calls to this
9561 command.
9562 If CALLBACK is non-nil, it is a function which is called to confirm
9563 that the match should indeed be shown."
9564 (interactive "sRegexp: \nP")
9565 (unless keep-previous
9566 (org-remove-occur-highlights nil nil t))
9567 (push (cons regexp callback) org-occur-parameters)
9568 (let ((cnt 0))
9569 (save-excursion
9570 (goto-char (point-min))
9571 (if (or (not keep-previous) ; do not want to keep
9572 (not org-occur-highlights)) ; no previous matches
9573 ;; hide everything
9574 (org-overview))
9575 (while (re-search-forward regexp nil t)
9576 (when (or (not callback)
9577 (save-match-data (funcall callback)))
9578 (setq cnt (1+ cnt))
9579 (when org-highlight-sparse-tree-matches
9580 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9581 (org-show-context 'occur-tree))))
9582 (when org-remove-highlights-with-change
9583 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9584 nil 'local))
9585 (unless org-sparse-tree-open-archived-trees
9586 (org-hide-archived-subtrees (point-min) (point-max)))
9587 (run-hooks 'org-occur-hook)
9588 (if (interactive-p)
9589 (message "%d match(es) for regexp %s" cnt regexp))
9590 cnt))
9592 (defun org-show-context (&optional key)
9593 "Make sure point and context and visible.
9594 How much context is shown depends upon the variables
9595 `org-show-hierarchy-above', `org-show-following-heading'. and
9596 `org-show-siblings'."
9597 (let ((heading-p (org-on-heading-p t))
9598 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9599 (following-p (org-get-alist-option org-show-following-heading key))
9600 (entry-p (org-get-alist-option org-show-entry-below key))
9601 (siblings-p (org-get-alist-option org-show-siblings key)))
9602 (catch 'exit
9603 ;; Show heading or entry text
9604 (if (and heading-p (not entry-p))
9605 (org-flag-heading nil) ; only show the heading
9606 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9607 (org-show-hidden-entry))) ; show entire entry
9608 (when following-p
9609 ;; Show next sibling, or heading below text
9610 (save-excursion
9611 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9612 (org-flag-heading nil))))
9613 (when siblings-p (org-show-siblings))
9614 (when hierarchy-p
9615 ;; show all higher headings, possibly with siblings
9616 (save-excursion
9617 (while (and (condition-case nil
9618 (progn (org-up-heading-all 1) t)
9619 (error nil))
9620 (not (bobp)))
9621 (org-flag-heading nil)
9622 (when siblings-p (org-show-siblings))))))))
9624 (defun org-reveal (&optional siblings)
9625 "Show current entry, hierarchy above it, and the following headline.
9626 This can be used to show a consistent set of context around locations
9627 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9628 not t for the search context.
9630 With optional argument SIBLINGS, on each level of the hierarchy all
9631 siblings are shown. This repairs the tree structure to what it would
9632 look like when opened with hierarchical calls to `org-cycle'."
9633 (interactive "P")
9634 (let ((org-show-hierarchy-above t)
9635 (org-show-following-heading t)
9636 (org-show-siblings (if siblings t org-show-siblings)))
9637 (org-show-context nil)))
9639 (defun org-highlight-new-match (beg end)
9640 "Highlight from BEG to END and mark the highlight is an occur headline."
9641 (let ((ov (org-make-overlay beg end)))
9642 (org-overlay-put ov 'face 'secondary-selection)
9643 (push ov org-occur-highlights)))
9645 (defun org-remove-occur-highlights (&optional beg end noremove)
9646 "Remove the occur highlights from the buffer.
9647 BEG and END are ignored. If NOREMOVE is nil, remove this function
9648 from the `before-change-functions' in the current buffer."
9649 (interactive)
9650 (unless org-inhibit-highlight-removal
9651 (mapc 'org-delete-overlay org-occur-highlights)
9652 (setq org-occur-highlights nil)
9653 (setq org-occur-parameters nil)
9654 (unless noremove
9655 (remove-hook 'before-change-functions
9656 'org-remove-occur-highlights 'local))))
9658 ;;;; Priorities
9660 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9661 "Regular expression matching the priority indicator.")
9663 (defvar org-remove-priority-next-time nil)
9665 (defun org-priority-up ()
9666 "Increase the priority of the current item."
9667 (interactive)
9668 (org-priority 'up))
9670 (defun org-priority-down ()
9671 "Decrease the priority of the current item."
9672 (interactive)
9673 (org-priority 'down))
9675 (defun org-priority (&optional action)
9676 "Change the priority of an item by ARG.
9677 ACTION can be `set', `up', `down', or a character."
9678 (interactive)
9679 (setq action (or action 'set))
9680 (let (current new news have remove)
9681 (save-excursion
9682 (org-back-to-heading t)
9683 (if (looking-at org-priority-regexp)
9684 (setq current (string-to-char (match-string 2))
9685 have t)
9686 (setq current org-default-priority))
9687 (cond
9688 ((or (eq action 'set)
9689 (if (featurep 'xemacs) (characterp action) (integerp action)))
9690 (if (not (eq action 'set))
9691 (setq new action)
9692 (message "Priority %c-%c, SPC to remove: "
9693 org-highest-priority org-lowest-priority)
9694 (setq new (read-char-exclusive)))
9695 (if (and (= (upcase org-highest-priority) org-highest-priority)
9696 (= (upcase org-lowest-priority) org-lowest-priority))
9697 (setq new (upcase new)))
9698 (cond ((equal new ?\ ) (setq remove t))
9699 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9700 (error "Priority must be between `%c' and `%c'"
9701 org-highest-priority org-lowest-priority))))
9702 ((eq action 'up)
9703 (if (and (not have) (eq last-command this-command))
9704 (setq new org-lowest-priority)
9705 (setq new (if (and org-priority-start-cycle-with-default (not have))
9706 org-default-priority (1- current)))))
9707 ((eq action 'down)
9708 (if (and (not have) (eq last-command this-command))
9709 (setq new org-highest-priority)
9710 (setq new (if (and org-priority-start-cycle-with-default (not have))
9711 org-default-priority (1+ current)))))
9712 (t (error "Invalid action")))
9713 (if (or (< (upcase new) org-highest-priority)
9714 (> (upcase new) org-lowest-priority))
9715 (setq remove t))
9716 (setq news (format "%c" new))
9717 (if have
9718 (if remove
9719 (replace-match "" t t nil 1)
9720 (replace-match news t t nil 2))
9721 (if remove
9722 (error "No priority cookie found in line")
9723 (looking-at org-todo-line-regexp)
9724 (if (match-end 2)
9725 (progn
9726 (goto-char (match-end 2))
9727 (insert " [#" news "]"))
9728 (goto-char (match-beginning 3))
9729 (insert "[#" news "] ")))))
9730 (org-preserve-lc (org-set-tags nil 'align))
9731 (if remove
9732 (message "Priority removed")
9733 (message "Priority of current item set to %s" news))))
9736 (defun org-get-priority (s)
9737 "Find priority cookie and return priority."
9738 (save-match-data
9739 (if (not (string-match org-priority-regexp s))
9740 (* 1000 (- org-lowest-priority org-default-priority))
9741 (* 1000 (- org-lowest-priority
9742 (string-to-char (match-string 2 s)))))))
9744 ;;;; Tags
9746 (defvar org-agenda-archives-mode)
9747 (defun org-scan-tags (action matcher &optional todo-only)
9748 "Scan headline tags with inheritance and produce output ACTION.
9750 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9751 or `agenda' to produce an entry list for an agenda view. It can also be
9752 a Lisp form or a function that should be called at each matched headline, in
9753 this case the return value is a list of all return values from these calls.
9755 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9756 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9757 only lines with a TODO keyword are included in the output."
9758 (require 'org-agenda)
9759 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9760 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9761 (org-re
9762 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9763 (props (list 'face 'default
9764 'done-face 'org-done
9765 'undone-face 'default
9766 'mouse-face 'highlight
9767 'org-not-done-regexp org-not-done-regexp
9768 'org-todo-regexp org-todo-regexp
9769 'keymap org-agenda-keymap
9770 'help-echo
9771 (format "mouse-2 or RET jump to org file %s"
9772 (abbreviate-file-name
9773 (or (buffer-file-name (buffer-base-buffer))
9774 (buffer-name (buffer-base-buffer)))))))
9775 (case-fold-search nil)
9776 lspos tags tags-list
9777 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9778 (llast 0) rtn rtn1 level category i txt
9779 todo marker entry priority)
9780 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9781 (setq action (list 'lambda nil action)))
9782 (save-excursion
9783 (goto-char (point-min))
9784 (when (eq action 'sparse-tree)
9785 (org-overview)
9786 (org-remove-occur-highlights))
9787 (while (re-search-forward re nil t)
9788 (catch :skip
9789 (setq todo (if (match-end 1) (match-string 2))
9790 tags (if (match-end 4) (match-string 4)))
9791 (goto-char (setq lspos (1+ (match-beginning 0))))
9792 (setq level (org-reduced-level (funcall outline-level))
9793 category (org-get-category))
9794 (setq i llast llast level)
9795 ;; remove tag lists from same and sublevels
9796 (while (>= i level)
9797 (when (setq entry (assoc i tags-alist))
9798 (setq tags-alist (delete entry tags-alist)))
9799 (setq i (1- i)))
9800 ;; add the next tags
9801 (when tags
9802 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9803 tags-alist
9804 (cons (cons level tags) tags-alist)))
9805 ;; compile tags for current headline
9806 (setq tags-list
9807 (if org-use-tag-inheritance
9808 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9809 tags))
9810 (when org-use-tag-inheritance
9811 (setcdr (car tags-alist)
9812 (mapcar (lambda (x)
9813 (setq x (copy-sequence x))
9814 (org-add-prop-inherited x))
9815 (cdar tags-alist))))
9816 (when (and tags org-use-tag-inheritance
9817 (not (eq t org-use-tag-inheritance)))
9818 ;; selective inheritance, remove uninherited ones
9819 (setcdr (car tags-alist)
9820 (org-remove-uniherited-tags (cdar tags-alist))))
9821 (when (and (or (not todo-only)
9822 (and (member todo org-not-done-keywords)
9823 (or (not org-agenda-tags-todo-honor-ignore-options)
9824 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
9825 (let ((case-fold-search t)) (eval matcher))
9827 (not (member org-archive-tag tags-list))
9828 ;; we have an archive tag, should we use this anyway?
9829 (or (not org-agenda-skip-archived-trees)
9830 (and (eq action 'agenda) org-agenda-archives-mode))))
9831 (unless (eq action 'sparse-tree) (org-agenda-skip))
9833 ;; select this headline
9835 (cond
9836 ((eq action 'sparse-tree)
9837 (and org-highlight-sparse-tree-matches
9838 (org-get-heading) (match-end 0)
9839 (org-highlight-new-match
9840 (match-beginning 0) (match-beginning 1)))
9841 (org-show-context 'tags-tree))
9842 ((eq action 'agenda)
9843 (setq txt (org-format-agenda-item
9845 (concat
9846 (if org-tags-match-list-sublevels
9847 (make-string (1- level) ?.) "")
9848 (org-get-heading))
9849 category (org-get-tags-at))
9850 priority (org-get-priority txt))
9851 (goto-char lspos)
9852 (setq marker (org-agenda-new-marker))
9853 (org-add-props txt props
9854 'org-marker marker 'org-hd-marker marker 'org-category category
9855 'todo-state todo
9856 'priority priority 'type "tagsmatch")
9857 (push txt rtn))
9858 ((functionp action)
9859 (save-excursion
9860 (setq rtn1 (funcall action))
9861 (push rtn1 rtn))
9862 (goto-char (point-at-eol)))
9863 (t (error "Invalid action")))
9865 ;; if we are to skip sublevels, jump to end of subtree
9866 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9867 (when (and (eq action 'sparse-tree)
9868 (not org-sparse-tree-open-archived-trees))
9869 (org-hide-archived-subtrees (point-min) (point-max)))
9870 (nreverse rtn)))
9872 (defun org-remove-uniherited-tags (tags)
9873 "Remove all tags that are not inherited from the list TAGS."
9874 (cond
9875 ((eq org-use-tag-inheritance t)
9876 (if org-tags-exclude-from-inheritance
9877 (org-delete-all org-tags-exclude-from-inheritance tags)
9878 tags))
9879 ((not org-use-tag-inheritance) nil)
9880 ((stringp org-use-tag-inheritance)
9881 (delq nil (mapcar
9882 (lambda (x)
9883 (if (and (string-match org-use-tag-inheritance x)
9884 (not (member x org-tags-exclude-from-inheritance)))
9885 x nil))
9886 tags)))
9887 ((listp org-use-tag-inheritance)
9888 (delq nil (mapcar
9889 (lambda (x)
9890 (if (member x org-use-tag-inheritance) x nil))
9891 tags)))))
9893 (defvar todo-only) ;; dynamically scoped
9895 (defun org-tags-sparse-tree (&optional todo-only match)
9896 "Create a sparse tree according to tags string MATCH.
9897 MATCH can contain positive and negative selection of tags, like
9898 \"+WORK+URGENT-WITHBOSS\".
9899 If optional argument TODO-ONLY is non-nil, only select lines that are
9900 also TODO lines."
9901 (interactive "P")
9902 (org-prepare-agenda-buffers (list (current-buffer)))
9903 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9905 (defvar org-cached-props nil)
9906 (defun org-cached-entry-get (pom property)
9907 (if (or (eq t org-use-property-inheritance)
9908 (and (stringp org-use-property-inheritance)
9909 (string-match org-use-property-inheritance property))
9910 (and (listp org-use-property-inheritance)
9911 (member property org-use-property-inheritance)))
9912 ;; Caching is not possible, check it directly
9913 (org-entry-get pom property 'inherit)
9914 ;; Get all properties, so that we can do complicated checks easily
9915 (cdr (assoc property (or org-cached-props
9916 (setq org-cached-props
9917 (org-entry-properties pom)))))))
9919 (defun org-global-tags-completion-table (&optional files)
9920 "Return the list of all tags in all agenda buffer/files."
9921 (save-excursion
9922 (org-uniquify
9923 (delq nil
9924 (apply 'append
9925 (mapcar
9926 (lambda (file)
9927 (set-buffer (find-file-noselect file))
9928 (append (org-get-buffer-tags)
9929 (mapcar (lambda (x) (if (stringp (car-safe x))
9930 (list (car-safe x)) nil))
9931 org-tag-alist)))
9932 (if (and files (car files))
9933 files
9934 (org-agenda-files))))))))
9936 (defun org-make-tags-matcher (match)
9937 "Create the TAGS//TODO matcher form for the selection string MATCH."
9938 ;; todo-only is scoped dynamically into this function, and the function
9939 ;; may change it if the matcher asks for it.
9940 (unless match
9941 ;; Get a new match request, with completion
9942 (let ((org-last-tags-completion-table
9943 (org-global-tags-completion-table)))
9944 (setq match (org-completing-read-no-ido
9945 "Match: " 'org-tags-completion-function nil nil nil
9946 'org-tags-history))))
9948 ;; Parse the string and create a lisp form
9949 (let ((match0 match)
9950 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9951 minus tag mm
9952 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9953 orterms term orlist re-p str-p level-p level-op time-p
9954 prop-p pn pv po cat-p gv rest)
9955 (if (string-match "/+" match)
9956 ;; match contains also a todo-matching request
9957 (progn
9958 (setq tagsmatch (substring match 0 (match-beginning 0))
9959 todomatch (substring match (match-end 0)))
9960 (if (string-match "^!" todomatch)
9961 (setq todo-only t todomatch (substring todomatch 1)))
9962 (if (string-match "^\\s-*$" todomatch)
9963 (setq todomatch nil)))
9964 ;; only matching tags
9965 (setq tagsmatch match todomatch nil))
9967 ;; Make the tags matcher
9968 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9969 (setq tagsmatcher t)
9970 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9971 (while (setq term (pop orterms))
9972 (while (and (equal (substring term -1) "\\") orterms)
9973 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9974 (while (string-match re term)
9975 (setq rest (substring term (match-end 0))
9976 minus (and (match-end 1)
9977 (equal (match-string 1 term) "-"))
9978 tag (match-string 2 term)
9979 re-p (equal (string-to-char tag) ?{)
9980 level-p (match-end 4)
9981 prop-p (match-end 5)
9982 mm (cond
9983 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9984 (level-p
9985 (setq level-op (org-op-to-function (match-string 3 term)))
9986 `(,level-op level ,(string-to-number
9987 (match-string 4 term))))
9988 (prop-p
9989 (setq pn (match-string 5 term)
9990 po (match-string 6 term)
9991 pv (match-string 7 term)
9992 cat-p (equal pn "CATEGORY")
9993 re-p (equal (string-to-char pv) ?{)
9994 str-p (equal (string-to-char pv) ?\")
9995 time-p (save-match-data
9996 (string-match "^\"[[<].*[]>]\"$" pv))
9997 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9998 (if time-p (setq pv (org-matcher-time pv)))
9999 (setq po (org-op-to-function po (if time-p 'time str-p)))
10000 (cond
10001 ((equal pn "CATEGORY")
10002 (setq gv '(get-text-property (point) 'org-category)))
10003 ((equal pn "TODO")
10004 (setq gv 'todo))
10006 (setq gv `(org-cached-entry-get nil ,pn))))
10007 (if re-p
10008 (if (eq po 'org<>)
10009 `(not (string-match ,pv (or ,gv "")))
10010 `(string-match ,pv (or ,gv "")))
10011 (if str-p
10012 `(,po (or ,gv "") ,pv)
10013 `(,po (string-to-number (or ,gv ""))
10014 ,(string-to-number pv) ))))
10015 (t `(member ,(downcase tag) tags-list)))
10016 mm (if minus (list 'not mm) mm)
10017 term rest)
10018 (push mm tagsmatcher))
10019 (push (if (> (length tagsmatcher) 1)
10020 (cons 'and tagsmatcher)
10021 (car tagsmatcher))
10022 orlist)
10023 (setq tagsmatcher nil))
10024 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
10025 (setq tagsmatcher
10026 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
10027 ;; Make the todo matcher
10028 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10029 (setq todomatcher t)
10030 (setq orterms (org-split-string todomatch "|") orlist nil)
10031 (while (setq term (pop orterms))
10032 (while (string-match re term)
10033 (setq minus (and (match-end 1)
10034 (equal (match-string 1 term) "-"))
10035 kwd (match-string 2 term)
10036 re-p (equal (string-to-char kwd) ?{)
10037 term (substring term (match-end 0))
10038 mm (if re-p
10039 `(string-match ,(substring kwd 1 -1) todo)
10040 (list 'equal 'todo kwd))
10041 mm (if minus (list 'not mm) mm))
10042 (push mm todomatcher))
10043 (push (if (> (length todomatcher) 1)
10044 (cons 'and todomatcher)
10045 (car todomatcher))
10046 orlist)
10047 (setq todomatcher nil))
10048 (setq todomatcher (if (> (length orlist) 1)
10049 (cons 'or orlist) (car orlist))))
10051 ;; Return the string and lisp forms of the matcher
10052 (setq matcher (if todomatcher
10053 (list 'and tagsmatcher todomatcher)
10054 tagsmatcher))
10055 (cons match0 matcher)))
10057 (defun org-op-to-function (op &optional stringp)
10058 "Turn an operator into the appropriate function."
10059 (setq op
10060 (cond
10061 ((equal op "<" ) '(< string< org-time<))
10062 ((equal op ">" ) '(> org-string> org-time>))
10063 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
10064 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
10065 ((member op '("=" "==")) '(= string= org-time=))
10066 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
10067 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
10069 (defun org<> (a b) (not (= a b)))
10070 (defun org-string<= (a b) (or (string= a b) (string< a b)))
10071 (defun org-string>= (a b) (not (string< a b)))
10072 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
10073 (defun org-string<> (a b) (not (string= a b)))
10074 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
10075 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
10076 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
10077 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
10078 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
10079 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
10080 (defun org-2ft (s)
10081 "Convert S to a floating point time.
10082 If S is already a number, just return it. If it is a string, parse
10083 it as a time string and apply `float-time' to it. If S is nil, just return 0."
10084 (cond
10085 ((numberp s) s)
10086 ((stringp s)
10087 (condition-case nil
10088 (float-time (apply 'encode-time (org-parse-time-string s)))
10089 (error 0.)))
10090 (t 0.)))
10092 (defun org-time-today ()
10093 "Time in seconds today at 0:00.
10094 Returns the float number of seconds since the beginning of the
10095 epoch to the beginning of today (00:00)."
10096 (float-time (apply 'encode-time
10097 (append '(0 0 0) (nthcdr 3 (decode-time))))))
10099 (defun org-matcher-time (s)
10100 "Interpret a time comparison value."
10101 (save-match-data
10102 (cond
10103 ((string= s "<now>") (float-time))
10104 ((string= s "<today>") (org-time-today))
10105 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
10106 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
10107 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
10108 (+ (org-time-today)
10109 (* (string-to-number (match-string 1 s))
10110 (cdr (assoc (match-string 2 s)
10111 '(("d" . 86400.0) ("w" . 604800.0)
10112 ("m" . 2678400.0) ("y" . 31557600.0)))))))
10113 (t (org-2ft s)))))
10115 (defun org-match-any-p (re list)
10116 "Does re match any element of list?"
10117 (setq list (mapcar (lambda (x) (string-match re x)) list))
10118 (delq nil list))
10120 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
10121 (defvar org-tags-overlay (org-make-overlay 1 1))
10122 (org-detach-overlay org-tags-overlay)
10124 (defun org-get-local-tags-at (&optional pos)
10125 "Get a list of tags defined in the current headline."
10126 (org-get-tags-at pos 'local))
10128 (defun org-get-local-tags ()
10129 "Get a list of tags defined in the current headline."
10130 (org-get-tags-at nil 'local))
10132 (defun org-get-tags-at (&optional pos local)
10133 "Get a list of all headline tags applicable at POS.
10134 POS defaults to point. If tags are inherited, the list contains
10135 the targets in the same sequence as the headlines appear, i.e.
10136 the tags of the current headline come last.
10137 When LOCAL is non-nil, only return tags from the current headline,
10138 ignore inherited ones."
10139 (interactive)
10140 (let (tags ltags lastpos parent)
10141 (save-excursion
10142 (save-restriction
10143 (widen)
10144 (goto-char (or pos (point)))
10145 (save-match-data
10146 (catch 'done
10147 (condition-case nil
10148 (progn
10149 (org-back-to-heading t)
10150 (while (not (equal lastpos (point)))
10151 (setq lastpos (point))
10152 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
10153 (setq ltags (org-split-string
10154 (org-match-string-no-properties 1) ":"))
10155 (when parent
10156 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
10157 (setq tags (append
10158 (if parent
10159 (org-remove-uniherited-tags ltags)
10160 ltags)
10161 tags)))
10162 (or org-use-tag-inheritance (throw 'done t))
10163 (if local (throw 'done t))
10164 (org-up-heading-all 1)
10165 (setq parent t)))
10166 (error nil)))))
10167 (append (org-remove-uniherited-tags org-file-tags) tags))))
10169 (defun org-add-prop-inherited (s)
10170 (add-text-properties 0 (length s) '(inherited t) s)
10173 (defun org-toggle-tag (tag &optional onoff)
10174 "Toggle the tag TAG for the current line.
10175 If ONOFF is `on' or `off', don't toggle but set to this state."
10176 (let (res current)
10177 (save-excursion
10178 (org-back-to-heading t)
10179 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
10180 (point-at-eol) t)
10181 (progn
10182 (setq current (match-string 1))
10183 (replace-match ""))
10184 (setq current ""))
10185 (setq current (nreverse (org-split-string current ":")))
10186 (cond
10187 ((eq onoff 'on)
10188 (setq res t)
10189 (or (member tag current) (push tag current)))
10190 ((eq onoff 'off)
10191 (or (not (member tag current)) (setq current (delete tag current))))
10192 (t (if (member tag current)
10193 (setq current (delete tag current))
10194 (setq res t)
10195 (push tag current))))
10196 (end-of-line 1)
10197 (if current
10198 (progn
10199 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
10200 (org-set-tags nil t))
10201 (delete-horizontal-space))
10202 (run-hooks 'org-after-tags-change-hook))
10203 res))
10205 (defun org-align-tags-here (to-col)
10206 ;; Assumes that this is a headline
10207 (let ((pos (point)) (col (current-column)) ncol tags-l p)
10208 (beginning-of-line 1)
10209 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10210 (< pos (match-beginning 2)))
10211 (progn
10212 (setq tags-l (- (match-end 2) (match-beginning 2)))
10213 (goto-char (match-beginning 1))
10214 (insert " ")
10215 (delete-region (point) (1+ (match-beginning 2)))
10216 (setq ncol (max (1+ (current-column))
10217 (1+ col)
10218 (if (> to-col 0)
10219 to-col
10220 (- (abs to-col) tags-l))))
10221 (setq p (point))
10222 (insert (make-string (- ncol (current-column)) ?\ ))
10223 (setq ncol (current-column))
10224 (when indent-tabs-mode (tabify p (point-at-eol)))
10225 (org-move-to-column (min ncol col) t))
10226 (goto-char pos))))
10228 (defun org-set-tags-command (&optional arg just-align)
10229 "Call the set-tags command for the current entry."
10230 (interactive "P")
10231 (if (org-on-heading-p)
10232 (org-set-tags arg just-align)
10233 (save-excursion
10234 (org-back-to-heading t)
10235 (org-set-tags arg just-align))))
10237 (defun org-set-tags (&optional arg just-align)
10238 "Set the tags for the current headline.
10239 With prefix ARG, realign all tags in headings in the current buffer."
10240 (interactive "P")
10241 (let* ((re (concat "^" outline-regexp))
10242 (current (org-get-tags-string))
10243 (col (current-column))
10244 (org-setting-tags t)
10245 table current-tags inherited-tags ; computed below when needed
10246 tags p0 c0 c1 rpl)
10247 (if arg
10248 (save-excursion
10249 (goto-char (point-min))
10250 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
10251 (while (re-search-forward re nil t)
10252 (org-set-tags nil t)
10253 (end-of-line 1)))
10254 (message "All tags realigned to column %d" org-tags-column))
10255 (if just-align
10256 (setq tags current)
10257 ;; Get a new set of tags from the user
10258 (save-excursion
10259 (setq table (append org-tag-persistent-alist
10260 (or org-tag-alist (org-get-buffer-tags)))
10261 org-last-tags-completion-table table
10262 current-tags (org-split-string current ":")
10263 inherited-tags (nreverse
10264 (nthcdr (length current-tags)
10265 (nreverse (org-get-tags-at))))
10266 tags
10267 (if (or (eq t org-use-fast-tag-selection)
10268 (and org-use-fast-tag-selection
10269 (delq nil (mapcar 'cdr table))))
10270 (org-fast-tag-selection
10271 current-tags inherited-tags table
10272 (if org-fast-tag-selection-include-todo org-todo-key-alist))
10273 (let ((org-add-colon-after-tag-completion t))
10274 (org-trim
10275 (org-without-partial-completion
10276 (org-ido-completing-read "Tags: " 'org-tags-completion-function
10277 nil nil current 'org-tags-history)))))))
10278 (while (string-match "[-+&]+" tags)
10279 ;; No boolean logic, just a list
10280 (setq tags (replace-match ":" t t tags))))
10282 (if (string-match "\\`[\t ]*\\'" tags)
10283 (setq tags "")
10284 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
10285 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
10287 ;; Insert new tags at the correct column
10288 (beginning-of-line 1)
10289 (cond
10290 ((and (equal current "") (equal tags "")))
10291 ((re-search-forward
10292 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10293 (point-at-eol) t)
10294 (if (equal tags "")
10295 (setq rpl "")
10296 (goto-char (match-beginning 0))
10297 (setq c0 (current-column) p0 (point)
10298 c1 (max (1+ c0) (if (> org-tags-column 0)
10299 org-tags-column
10300 (- (- org-tags-column) (length tags))))
10301 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10302 (replace-match rpl t t)
10303 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
10304 tags)
10305 (t (error "Tags alignment failed")))
10306 (org-move-to-column col)
10307 (unless just-align
10308 (run-hooks 'org-after-tags-change-hook)))))
10310 (defun org-change-tag-in-region (beg end tag off)
10311 "Add or remove TAG for each entry in the region.
10312 This works in the agenda, and also in an org-mode buffer."
10313 (interactive
10314 (list (region-beginning) (region-end)
10315 (let ((org-last-tags-completion-table
10316 (if (org-mode-p)
10317 (org-get-buffer-tags)
10318 (org-global-tags-completion-table))))
10319 (org-ido-completing-read
10320 "Tag: " 'org-tags-completion-function nil nil nil
10321 'org-tags-history))
10322 (progn
10323 (message "[s]et or [r]emove? ")
10324 (equal (read-char-exclusive) ?r))))
10325 (if (fboundp 'deactivate-mark) (deactivate-mark))
10326 (let ((agendap (equal major-mode 'org-agenda-mode))
10327 l1 l2 m buf pos newhead (cnt 0))
10328 (goto-char end)
10329 (setq l2 (1- (org-current-line)))
10330 (goto-char beg)
10331 (setq l1 (org-current-line))
10332 (loop for l from l1 to l2 do
10333 (goto-line l)
10334 (setq m (get-text-property (point) 'org-hd-marker))
10335 (when (or (and (org-mode-p) (org-on-heading-p))
10336 (and agendap m))
10337 (setq buf (if agendap (marker-buffer m) (current-buffer))
10338 pos (if agendap m (point)))
10339 (with-current-buffer buf
10340 (save-excursion
10341 (save-restriction
10342 (goto-char pos)
10343 (setq cnt (1+ cnt))
10344 (org-toggle-tag tag (if off 'off 'on))
10345 (setq newhead (org-get-heading)))))
10346 (and agendap (org-agenda-change-all-lines newhead m))))
10347 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
10349 (defun org-tags-completion-function (string predicate &optional flag)
10350 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10351 (confirm (lambda (x) (stringp (car x)))))
10352 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10353 (setq s1 (match-string 1 string)
10354 s2 (match-string 2 string))
10355 (setq s1 "" s2 string))
10356 (cond
10357 ((eq flag nil)
10358 ;; try completion
10359 (setq rtn (try-completion s2 ctable confirm))
10360 (if (stringp rtn)
10361 (setq rtn
10362 (concat s1 s2 (substring rtn (length s2))
10363 (if (and org-add-colon-after-tag-completion
10364 (assoc rtn ctable))
10365 ":" ""))))
10366 rtn)
10367 ((eq flag t)
10368 ;; all-completions
10369 (all-completions s2 ctable confirm)
10371 ((eq flag 'lambda)
10372 ;; exact match?
10373 (assoc s2 ctable)))
10376 (defun org-fast-tag-insert (kwd tags face &optional end)
10377 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
10378 (insert (format "%-12s" (concat kwd ":"))
10379 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
10380 (or end "")))
10382 (defun org-fast-tag-show-exit (flag)
10383 (save-excursion
10384 (goto-line 3)
10385 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
10386 (replace-match ""))
10387 (when flag
10388 (end-of-line 1)
10389 (org-move-to-column (- (window-width) 19) t)
10390 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
10392 (defun org-set-current-tags-overlay (current prefix)
10393 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
10394 (if (featurep 'xemacs)
10395 (org-overlay-display org-tags-overlay (concat prefix s)
10396 'secondary-selection)
10397 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
10398 (org-overlay-display org-tags-overlay (concat prefix s)))))
10400 (defun org-fast-tag-selection (current inherited table &optional todo-table)
10401 "Fast tag selection with single keys.
10402 CURRENT is the current list of tags in the headline, INHERITED is the
10403 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
10404 possibly with grouping information. TODO-TABLE is a similar table with
10405 TODO keywords, should these have keys assigned to them.
10406 If the keys are nil, a-z are automatically assigned.
10407 Returns the new tags string, or nil to not change the current settings."
10408 (let* ((fulltable (append table todo-table))
10409 (maxlen (apply 'max (mapcar
10410 (lambda (x)
10411 (if (stringp (car x)) (string-width (car x)) 0))
10412 fulltable)))
10413 (buf (current-buffer))
10414 (expert (eq org-fast-tag-selection-single-key 'expert))
10415 (buffer-tags nil)
10416 (fwidth (+ maxlen 3 1 3))
10417 (ncol (/ (- (window-width) 4) fwidth))
10418 (i-face 'org-done)
10419 (c-face 'org-todo)
10420 tg cnt e c char c1 c2 ntable tbl rtn
10421 ov-start ov-end ov-prefix
10422 (exit-after-next org-fast-tag-selection-single-key)
10423 (done-keywords org-done-keywords)
10424 groups ingroup)
10425 (save-excursion
10426 (beginning-of-line 1)
10427 (if (looking-at
10428 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10429 (setq ov-start (match-beginning 1)
10430 ov-end (match-end 1)
10431 ov-prefix "")
10432 (setq ov-start (1- (point-at-eol))
10433 ov-end (1+ ov-start))
10434 (skip-chars-forward "^\n\r")
10435 (setq ov-prefix
10436 (concat
10437 (buffer-substring (1- (point)) (point))
10438 (if (> (current-column) org-tags-column)
10440 (make-string (- org-tags-column (current-column)) ?\ ))))))
10441 (org-move-overlay org-tags-overlay ov-start ov-end)
10442 (save-window-excursion
10443 (if expert
10444 (set-buffer (get-buffer-create " *Org tags*"))
10445 (delete-other-windows)
10446 (split-window-vertically)
10447 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
10448 (erase-buffer)
10449 (org-set-local 'org-done-keywords done-keywords)
10450 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10451 (org-fast-tag-insert "Current" current c-face "\n\n")
10452 (org-fast-tag-show-exit exit-after-next)
10453 (org-set-current-tags-overlay current ov-prefix)
10454 (setq tbl fulltable char ?a cnt 0)
10455 (while (setq e (pop tbl))
10456 (cond
10457 ((equal e '(:startgroup))
10458 (push '() groups) (setq ingroup t)
10459 (when (not (= cnt 0))
10460 (setq cnt 0)
10461 (insert "\n"))
10462 (insert "{ "))
10463 ((equal e '(:endgroup))
10464 (setq ingroup nil cnt 0)
10465 (insert "}\n"))
10466 ((equal e '(:newline))
10467 (when (not (= cnt 0))
10468 (setq cnt 0)
10469 (insert "\n")
10470 (setq e (car tbl))
10471 (while (equal (car tbl) '(:newline))
10472 (insert "\n")
10473 (setq tbl (cdr tbl)))))
10475 (setq tg (car e) c2 nil)
10476 (if (cdr e)
10477 (setq c (cdr e))
10478 ;; automatically assign a character.
10479 (setq c1 (string-to-char
10480 (downcase (substring
10481 tg (if (= (string-to-char tg) ?@) 1 0)))))
10482 (if (or (rassoc c1 ntable) (rassoc c1 table))
10483 (while (or (rassoc char ntable) (rassoc char table))
10484 (setq char (1+ char)))
10485 (setq c2 c1))
10486 (setq c (or c2 char)))
10487 (if ingroup (push tg (car groups)))
10488 (setq tg (org-add-props tg nil 'face
10489 (cond
10490 ((not (assoc tg table))
10491 (org-get-todo-face tg))
10492 ((member tg current) c-face)
10493 ((member tg inherited) i-face)
10494 (t nil))))
10495 (if (and (= cnt 0) (not ingroup)) (insert " "))
10496 (insert "[" c "] " tg (make-string
10497 (- fwidth 4 (length tg)) ?\ ))
10498 (push (cons tg c) ntable)
10499 (when (= (setq cnt (1+ cnt)) ncol)
10500 (insert "\n")
10501 (if ingroup (insert " "))
10502 (setq cnt 0)))))
10503 (setq ntable (nreverse ntable))
10504 (insert "\n")
10505 (goto-char (point-min))
10506 (if (not expert) (org-fit-window-to-buffer))
10507 (setq rtn
10508 (catch 'exit
10509 (while t
10510 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10511 (if groups " [!] no groups" " [!]groups")
10512 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10513 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10514 (cond
10515 ((= c ?\r) (throw 'exit t))
10516 ((= c ?!)
10517 (setq groups (not groups))
10518 (goto-char (point-min))
10519 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10520 ((= c ?\C-c)
10521 (if (not expert)
10522 (org-fast-tag-show-exit
10523 (setq exit-after-next (not exit-after-next)))
10524 (setq expert nil)
10525 (delete-other-windows)
10526 (split-window-vertically)
10527 (org-switch-to-buffer-other-window " *Org tags*")
10528 (org-fit-window-to-buffer)))
10529 ((or (= c ?\C-g)
10530 (and (= c ?q) (not (rassoc c ntable))))
10531 (org-detach-overlay org-tags-overlay)
10532 (setq quit-flag t))
10533 ((= c ?\ )
10534 (setq current nil)
10535 (if exit-after-next (setq exit-after-next 'now)))
10536 ((= c ?\t)
10537 (condition-case nil
10538 (setq tg (org-ido-completing-read
10539 "Tag: "
10540 (or buffer-tags
10541 (with-current-buffer buf
10542 (org-get-buffer-tags)))))
10543 (quit (setq tg "")))
10544 (when (string-match "\\S-" tg)
10545 (add-to-list 'buffer-tags (list tg))
10546 (if (member tg current)
10547 (setq current (delete tg current))
10548 (push tg current)))
10549 (if exit-after-next (setq exit-after-next 'now)))
10550 ((setq e (rassoc c todo-table) tg (car e))
10551 (with-current-buffer buf
10552 (save-excursion (org-todo tg)))
10553 (if exit-after-next (setq exit-after-next 'now)))
10554 ((setq e (rassoc c ntable) tg (car e))
10555 (if (member tg current)
10556 (setq current (delete tg current))
10557 (loop for g in groups do
10558 (if (member tg g)
10559 (mapc (lambda (x)
10560 (setq current (delete x current)))
10561 g)))
10562 (push tg current))
10563 (if exit-after-next (setq exit-after-next 'now))))
10565 ;; Create a sorted list
10566 (setq current
10567 (sort current
10568 (lambda (a b)
10569 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10570 (if (eq exit-after-next 'now) (throw 'exit t))
10571 (goto-char (point-min))
10572 (beginning-of-line 2)
10573 (delete-region (point) (point-at-eol))
10574 (org-fast-tag-insert "Current" current c-face)
10575 (org-set-current-tags-overlay current ov-prefix)
10576 (while (re-search-forward
10577 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10578 (setq tg (match-string 1))
10579 (add-text-properties
10580 (match-beginning 1) (match-end 1)
10581 (list 'face
10582 (cond
10583 ((member tg current) c-face)
10584 ((member tg inherited) i-face)
10585 (t (get-text-property (match-beginning 1) 'face))))))
10586 (goto-char (point-min)))))
10587 (org-detach-overlay org-tags-overlay)
10588 (if rtn
10589 (mapconcat 'identity current ":")
10590 nil))))
10592 (defun org-get-tags-string ()
10593 "Get the TAGS string in the current headline."
10594 (unless (org-on-heading-p t)
10595 (error "Not on a heading"))
10596 (save-excursion
10597 (beginning-of-line 1)
10598 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10599 (org-match-string-no-properties 1)
10600 "")))
10602 (defun org-get-tags ()
10603 "Get the list of tags specified in the current headline."
10604 (org-split-string (org-get-tags-string) ":"))
10606 (defun org-get-buffer-tags ()
10607 "Get a table of all tags used in the buffer, for completion."
10608 (let (tags)
10609 (save-excursion
10610 (goto-char (point-min))
10611 (while (re-search-forward
10612 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10613 (when (equal (char-after (point-at-bol 0)) ?*)
10614 (mapc (lambda (x) (add-to-list 'tags x))
10615 (org-split-string (org-match-string-no-properties 1) ":")))))
10616 (mapcar 'list tags)))
10618 ;;;; The mapping API
10620 ;;;###autoload
10621 (defun org-map-entries (func &optional match scope &rest skip)
10622 "Call FUNC at each headline selected by MATCH in SCOPE.
10624 FUNC is a function or a lisp form. The function will be called without
10625 arguments, with the cursor positioned at the beginning of the headline.
10626 The return values of all calls to the function will be collected and
10627 returned as a list.
10629 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10630 Only headlines that are matched by this query will be considered during
10631 the iteration. When MATCH is nil or t, all headlines will be
10632 visited by the iteration.
10634 SCOPE determines the scope of this command. It can be any of:
10636 nil The current buffer, respecting the restriction if any
10637 tree The subtree started with the entry at point
10638 file The current buffer, without restriction
10639 file-with-archives
10640 The current buffer, and any archives associated with it
10641 agenda All agenda files
10642 agenda-with-archives
10643 All agenda files with any archive files associated with them
10644 \(file1 file2 ...)
10645 If this is a list, all files in the list will be scanned
10647 The remaining args are treated as settings for the skipping facilities of
10648 the scanner. The following items can be given here:
10650 archive skip trees with the archive tag.
10651 comment skip trees with the COMMENT keyword
10652 function or Emacs Lisp form:
10653 will be used as value for `org-agenda-skip-function', so whenever
10654 the the function returns t, FUNC will not be called for that
10655 entry and search will continue from the point where the
10656 function leaves it."
10657 (let* ((org-agenda-archives-mode nil) ; just to make sure
10658 (org-agenda-skip-archived-trees (memq 'archive skip))
10659 (org-agenda-skip-comment-trees (memq 'comment skip))
10660 (org-agenda-skip-function
10661 (car (org-delete-all '(comment archive) skip)))
10662 (org-tags-match-list-sublevels t)
10663 matcher file res
10664 org-todo-keywords-for-agenda
10665 org-done-keywords-for-agenda
10666 org-todo-keyword-alist-for-agenda
10667 org-tag-alist-for-agenda)
10669 (cond
10670 ((eq match t) (setq matcher t))
10671 ((eq match nil) (setq matcher t))
10672 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10674 (save-excursion
10675 (save-restriction
10676 (when (eq scope 'tree)
10677 (org-back-to-heading t)
10678 (org-narrow-to-subtree)
10679 (setq scope nil))
10681 (if (not scope)
10682 (progn
10683 (org-prepare-agenda-buffers
10684 (list (buffer-file-name (current-buffer))))
10685 (setq res (org-scan-tags func matcher)))
10686 ;; Get the right scope
10687 (cond
10688 ((and scope (listp scope) (symbolp (car scope)))
10689 (setq scope (eval scope)))
10690 ((eq scope 'agenda)
10691 (setq scope (org-agenda-files t)))
10692 ((eq scope 'agenda-with-archives)
10693 (setq scope (org-agenda-files t))
10694 (setq scope (org-add-archive-files scope)))
10695 ((eq scope 'file)
10696 (setq scope (list (buffer-file-name))))
10697 ((eq scope 'file-with-archives)
10698 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10699 (org-prepare-agenda-buffers scope)
10700 (while (setq file (pop scope))
10701 (with-current-buffer (org-find-base-buffer-visiting file)
10702 (save-excursion
10703 (save-restriction
10704 (widen)
10705 (goto-char (point-min))
10706 (setq res (append res (org-scan-tags func matcher))))))))))
10707 res))
10709 ;;;; Properties
10711 ;;; Setting and retrieving properties
10713 (defconst org-special-properties
10714 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10715 "TIMESTAMP" "TIMESTAMP_IA")
10716 "The special properties valid in Org-mode.
10718 These are properties that are not defined in the property drawer,
10719 but in some other way.")
10721 (defconst org-default-properties
10722 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10723 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10724 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10725 "EXPORT_FILE_NAME" "EXPORT_TITLE" "ORDERED")
10726 "Some properties that are used by Org-mode for various purposes.
10727 Being in this list makes sure that they are offered for completion.")
10729 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10730 "Regular expression matching the first line of a property drawer.")
10732 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10733 "Regular expression matching the first line of a property drawer.")
10735 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10736 "Regular expression matching the first line of a property drawer.")
10738 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10739 "Regular expression matching the first line of a property drawer.")
10741 (defconst org-property-drawer-re
10742 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10743 org-property-end-re "\\)\n?")
10744 "Matches an entire property drawer.")
10746 (defconst org-clock-drawer-re
10747 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10748 org-property-end-re "\\)\n?")
10749 "Matches an entire clock drawer.")
10751 (defun org-property-action ()
10752 "Do an action on properties."
10753 (interactive)
10754 (let (c)
10755 (org-at-property-p)
10756 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10757 (setq c (read-char-exclusive))
10758 (cond
10759 ((equal c ?s)
10760 (call-interactively 'org-set-property))
10761 ((equal c ?d)
10762 (call-interactively 'org-delete-property))
10763 ((equal c ?D)
10764 (call-interactively 'org-delete-property-globally))
10765 ((equal c ?c)
10766 (call-interactively 'org-compute-property-at-point))
10767 (t (error "No such property action %c" c)))))
10769 (defun org-at-property-p ()
10770 "Is the cursor in a property line?"
10771 ;; FIXME: Does not check if we are actually in the drawer.
10772 ;; FIXME: also returns true on any drawers.....
10773 ;; This is used by C-c C-c for property action.
10774 (save-excursion
10775 (beginning-of-line 1)
10776 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10778 (defun org-get-property-block (&optional beg end force)
10779 "Return the (beg . end) range of the body of the property drawer.
10780 BEG and END can be beginning and end of subtree, if not given
10781 they will be found.
10782 If the drawer does not exist and FORCE is non-nil, create the drawer."
10783 (catch 'exit
10784 (save-excursion
10785 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10786 (end (or end (progn (outline-next-heading) (point)))))
10787 (goto-char beg)
10788 (if (re-search-forward org-property-start-re end t)
10789 (setq beg (1+ (match-end 0)))
10790 (if force
10791 (save-excursion
10792 (org-insert-property-drawer)
10793 (setq end (progn (outline-next-heading) (point))))
10794 (throw 'exit nil))
10795 (goto-char beg)
10796 (if (re-search-forward org-property-start-re end t)
10797 (setq beg (1+ (match-end 0)))))
10798 (if (re-search-forward org-property-end-re end t)
10799 (setq end (match-beginning 0))
10800 (or force (throw 'exit nil))
10801 (goto-char beg)
10802 (setq end beg)
10803 (org-indent-line-function)
10804 (insert ":END:\n"))
10805 (cons beg end)))))
10807 (defun org-entry-properties (&optional pom which)
10808 "Get all properties of the entry at point-or-marker POM.
10809 This includes the TODO keyword, the tags, time strings for deadline,
10810 scheduled, and clocking, and any additional properties defined in the
10811 entry. The return value is an alist, keys may occur multiple times
10812 if the property key was used several times.
10813 POM may also be nil, in which case the current entry is used.
10814 If WHICH is nil or `all', get all properties. If WHICH is
10815 `special' or `standard', only get that subclass."
10816 (setq which (or which 'all))
10817 (org-with-point-at pom
10818 (let ((clockstr (substring org-clock-string 0 -1))
10819 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10820 beg end range props sum-props key value string clocksum)
10821 (save-excursion
10822 (when (condition-case nil
10823 (and (org-mode-p) (org-back-to-heading t))
10824 (error nil))
10825 (setq beg (point))
10826 (setq sum-props (get-text-property (point) 'org-summaries))
10827 (setq clocksum (get-text-property (point) :org-clock-minutes))
10828 (outline-next-heading)
10829 (setq end (point))
10830 (when (memq which '(all special))
10831 ;; Get the special properties, like TODO and tags
10832 (goto-char beg)
10833 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10834 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10835 (when (looking-at org-priority-regexp)
10836 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10837 (when (and (setq value (org-get-tags-string))
10838 (string-match "\\S-" value))
10839 (push (cons "TAGS" value) props))
10840 (when (setq value (org-get-tags-at))
10841 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10842 props))
10843 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10844 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10845 string (if (equal key clockstr)
10846 (org-no-properties
10847 (org-trim
10848 (buffer-substring
10849 (match-beginning 3) (goto-char (point-at-eol)))))
10850 (substring (org-match-string-no-properties 3) 1 -1)))
10851 (unless key
10852 (if (= (char-after (match-beginning 3)) ?\[)
10853 (setq key "TIMESTAMP_IA")
10854 (setq key "TIMESTAMP")))
10855 (when (or (equal key clockstr) (not (assoc key props)))
10856 (push (cons key string) props)))
10860 (when (memq which '(all standard))
10861 ;; Get the standard properties, like :PORP: ...
10862 (setq range (org-get-property-block beg end))
10863 (when range
10864 (goto-char (car range))
10865 (while (re-search-forward
10866 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10867 (cdr range) t)
10868 (setq key (org-match-string-no-properties 1)
10869 value (org-trim (or (org-match-string-no-properties 2) "")))
10870 (unless (member key excluded)
10871 (push (cons key (or value "")) props)))))
10872 (if clocksum
10873 (push (cons "CLOCKSUM"
10874 (org-columns-number-to-string (/ (float clocksum) 60.)
10875 'add_times))
10876 props))
10877 (unless (assoc "CATEGORY" props)
10878 (setq value (or (org-get-category)
10879 (progn (org-refresh-category-properties)
10880 (org-get-category))))
10881 (push (cons "CATEGORY" value) props))
10882 (append sum-props (nreverse props)))))))
10884 (defun org-entry-get (pom property &optional inherit)
10885 "Get value of PROPERTY for entry at point-or-marker POM.
10886 If INHERIT is non-nil and the entry does not have the property,
10887 then also check higher levels of the hierarchy.
10888 If INHERIT is the symbol `selective', use inheritance only if the setting
10889 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10890 If the property is present but empty, the return value is the empty string.
10891 If the property is not present at all, nil is returned."
10892 (org-with-point-at pom
10893 (if (and inherit (if (eq inherit 'selective)
10894 (org-property-inherit-p property)
10896 (org-entry-get-with-inheritance property)
10897 (if (member property org-special-properties)
10898 ;; We need a special property. Use brute force, get all properties.
10899 (cdr (assoc property (org-entry-properties nil 'special)))
10900 (let ((range (org-get-property-block)))
10901 (if (and range
10902 (goto-char (car range))
10903 (re-search-forward
10904 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10905 (cdr range) t))
10906 ;; Found the property, return it.
10907 (if (match-end 1)
10908 (org-match-string-no-properties 1)
10909 "")))))))
10911 (defun org-property-or-variable-value (var &optional inherit)
10912 "Check if there is a property fixing the value of VAR.
10913 If yes, return this value. If not, return the current value of the variable."
10914 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10915 (if (and prop (stringp prop) (string-match "\\S-" prop))
10916 (read prop)
10917 (symbol-value var))))
10919 (defun org-entry-delete (pom property)
10920 "Delete the property PROPERTY from entry at point-or-marker POM."
10921 (org-with-point-at pom
10922 (if (member property org-special-properties)
10923 nil ; cannot delete these properties.
10924 (let ((range (org-get-property-block)))
10925 (if (and range
10926 (goto-char (car range))
10927 (re-search-forward
10928 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10929 (cdr range) t))
10930 (progn
10931 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10933 nil)))))
10935 ;; Multi-values properties are properties that contain multiple values
10936 ;; These values are assumed to be single words, separated by whitespace.
10937 (defun org-entry-add-to-multivalued-property (pom property value)
10938 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10939 (let* ((old (org-entry-get pom property))
10940 (values (and old (org-split-string old "[ \t]"))))
10941 (setq value (org-entry-protect-space value))
10942 (unless (member value values)
10943 (setq values (cons value values))
10944 (org-entry-put pom property
10945 (mapconcat 'identity values " ")))))
10947 (defun org-entry-remove-from-multivalued-property (pom property value)
10948 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10949 (let* ((old (org-entry-get pom property))
10950 (values (and old (org-split-string old "[ \t]"))))
10951 (setq value (org-entry-protect-space value))
10952 (when (member value values)
10953 (setq values (delete value values))
10954 (org-entry-put pom property
10955 (mapconcat 'identity values " ")))))
10957 (defun org-entry-member-in-multivalued-property (pom property value)
10958 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10959 (let* ((old (org-entry-get pom property))
10960 (values (and old (org-split-string old "[ \t]"))))
10961 (setq value (org-entry-protect-space value))
10962 (member value values)))
10964 (defun org-entry-get-multivalued-property (pom property)
10965 "Return a list of values in a multivalued property."
10966 (let* ((value (org-entry-get pom property))
10967 (values (and value (org-split-string value "[ \t]"))))
10968 (mapcar 'org-entry-restore-space values)))
10970 (defun org-entry-put-multivalued-property (pom property &rest values)
10971 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10972 VALUES should be a list of strings. Spaces will be protected."
10973 (org-entry-put pom property
10974 (mapconcat 'org-entry-protect-space values " "))
10975 (let* ((value (org-entry-get pom property))
10976 (values (and value (org-split-string value "[ \t]"))))
10977 (mapcar 'org-entry-restore-space values)))
10979 (defun org-entry-protect-space (s)
10980 "Protect spaces and newline in string S."
10981 (while (string-match " " s)
10982 (setq s (replace-match "%20" t t s)))
10983 (while (string-match "\n" s)
10984 (setq s (replace-match "%0A" t t s)))
10987 (defun org-entry-restore-space (s)
10988 "Restore spaces and newline in string S."
10989 (while (string-match "%20" s)
10990 (setq s (replace-match " " t t s)))
10991 (while (string-match "%0A" s)
10992 (setq s (replace-match "\n" t t s)))
10995 (defvar org-entry-property-inherited-from (make-marker)
10996 "Marker pointing to the entry from where a property was inherited.
10997 Each call to `org-entry-get-with-inheritance' will set this marker to the
10998 location of the entry where the inheritance search matched. If there was
10999 no match, the marker will point nowhere.
11000 Note that also `org-entry-get' calls this function, if the INHERIT flag
11001 is set.")
11003 (defun org-entry-get-with-inheritance (property)
11004 "Get entry property, and search higher levels if not present."
11005 (move-marker org-entry-property-inherited-from nil)
11006 (let (tmp)
11007 (save-excursion
11008 (save-restriction
11009 (widen)
11010 (catch 'ex
11011 (while t
11012 (when (setq tmp (org-entry-get nil property))
11013 (org-back-to-heading t)
11014 (move-marker org-entry-property-inherited-from (point))
11015 (throw 'ex tmp))
11016 (or (org-up-heading-safe) (throw 'ex nil)))))
11017 (or tmp
11018 (cdr (assoc property org-file-properties))
11019 (cdr (assoc property org-global-properties))
11020 (cdr (assoc property org-global-properties-fixed))))))
11022 (defun org-entry-put (pom property value)
11023 "Set PROPERTY to VALUE for entry at point-or-marker POM."
11024 (org-with-point-at pom
11025 (org-back-to-heading t)
11026 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
11027 range)
11028 (cond
11029 ((equal property "TODO")
11030 (when (and (stringp value) (string-match "\\S-" value)
11031 (not (member value org-todo-keywords-1)))
11032 (error "\"%s\" is not a valid TODO state" value))
11033 (if (or (not value)
11034 (not (string-match "\\S-" value)))
11035 (setq value 'none))
11036 (org-todo value)
11037 (org-set-tags nil 'align))
11038 ((equal property "PRIORITY")
11039 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
11040 (string-to-char value) ?\ ))
11041 (org-set-tags nil 'align))
11042 ((equal property "SCHEDULED")
11043 (if (re-search-forward org-scheduled-time-regexp end t)
11044 (cond
11045 ((eq value 'earlier) (org-timestamp-change -1 'day))
11046 ((eq value 'later) (org-timestamp-change 1 'day))
11047 (t (call-interactively 'org-schedule)))
11048 (call-interactively 'org-schedule)))
11049 ((equal property "DEADLINE")
11050 (if (re-search-forward org-deadline-time-regexp end t)
11051 (cond
11052 ((eq value 'earlier) (org-timestamp-change -1 'day))
11053 ((eq value 'later) (org-timestamp-change 1 'day))
11054 (t (call-interactively 'org-deadline)))
11055 (call-interactively 'org-deadline)))
11056 ((member property org-special-properties)
11057 (error "The %s property can not yet be set with `org-entry-put'"
11058 property))
11059 (t ; a non-special property
11060 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
11061 (setq range (org-get-property-block beg end 'force))
11062 (goto-char (car range))
11063 (if (re-search-forward
11064 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
11065 (progn
11066 (delete-region (match-beginning 1) (match-end 1))
11067 (goto-char (match-beginning 1)))
11068 (goto-char (cdr range))
11069 (insert "\n")
11070 (backward-char 1)
11071 (org-indent-line-function)
11072 (insert ":" property ":"))
11073 (and value (insert " " value))
11074 (org-indent-line-function)))))))
11076 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
11077 "Get all property keys in the current buffer.
11078 With INCLUDE-SPECIALS, also list the special properties that reflect things
11079 like tags and TODO state.
11080 With INCLUDE-DEFAULTS, also include properties that has special meaning
11081 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
11082 With INCLUDE-COLUMNS, also include property names given in COLUMN
11083 formats in the current buffer."
11084 (let (rtn range cfmt s p)
11085 (save-excursion
11086 (save-restriction
11087 (widen)
11088 (goto-char (point-min))
11089 (while (re-search-forward org-property-start-re nil t)
11090 (setq range (org-get-property-block))
11091 (goto-char (car range))
11092 (while (re-search-forward
11093 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
11094 (cdr range) t)
11095 (add-to-list 'rtn (org-match-string-no-properties 1)))
11096 (outline-next-heading))))
11098 (when include-specials
11099 (setq rtn (append org-special-properties rtn)))
11101 (when include-defaults
11102 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
11104 (when include-columns
11105 (save-excursion
11106 (save-restriction
11107 (widen)
11108 (goto-char (point-min))
11109 (while (re-search-forward
11110 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
11111 nil t)
11112 (setq cfmt (match-string 2) s 0)
11113 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
11114 cfmt s)
11115 (setq s (match-end 0)
11116 p (match-string 1 cfmt))
11117 (unless (or (equal p "ITEM")
11118 (member p org-special-properties))
11119 (add-to-list 'rtn (match-string 1 cfmt))))))))
11121 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
11123 (defun org-property-values (key)
11124 "Return a list of all values of property KEY."
11125 (save-excursion
11126 (save-restriction
11127 (widen)
11128 (goto-char (point-min))
11129 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
11130 values)
11131 (while (re-search-forward re nil t)
11132 (add-to-list 'values (org-trim (match-string 1))))
11133 (delete "" values)))))
11135 (defun org-insert-property-drawer ()
11136 "Insert a property drawer into the current entry."
11137 (interactive)
11138 (org-back-to-heading t)
11139 (looking-at outline-regexp)
11140 (let ((indent (- (match-end 0)(match-beginning 0)))
11141 (beg (point))
11142 (re (concat "^[ \t]*" org-keyword-time-regexp))
11143 end hiddenp)
11144 (outline-next-heading)
11145 (setq end (point))
11146 (goto-char beg)
11147 (while (re-search-forward re end t))
11148 (setq hiddenp (org-invisible-p))
11149 (end-of-line 1)
11150 (and (equal (char-after) ?\n) (forward-char 1))
11151 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
11152 (if (member (match-string 1) '("CLOCK:" ":END:"))
11153 ;; just skip this line
11154 (beginning-of-line 2)
11155 ;; Drawer start, find the end
11156 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
11157 (beginning-of-line 1)))
11158 (org-skip-over-state-notes)
11159 (skip-chars-backward " \t\n\r")
11160 (if (eq (char-before) ?*) (forward-char 1))
11161 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
11162 (beginning-of-line 0)
11163 (org-indent-to-column indent)
11164 (beginning-of-line 2)
11165 (org-indent-to-column indent)
11166 (beginning-of-line 0)
11167 (if hiddenp
11168 (save-excursion
11169 (org-back-to-heading t)
11170 (hide-entry))
11171 (org-flag-drawer t))))
11173 (defun org-set-property (property value)
11174 "In the current entry, set PROPERTY to VALUE.
11175 When called interactively, this will prompt for a property name, offering
11176 completion on existing and default properties. And then it will prompt
11177 for a value, offering completion either on allowed values (via an inherited
11178 xxx_ALL property) or on existing values in other instances of this property
11179 in the current file."
11180 (interactive
11181 (let* ((completion-ignore-case t)
11182 (keys (org-buffer-property-keys nil t t))
11183 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
11184 (prop (if (member prop0 keys)
11185 prop0
11186 (or (cdr (assoc (downcase prop0)
11187 (mapcar (lambda (x) (cons (downcase x) x))
11188 keys)))
11189 prop0)))
11190 (cur (org-entry-get nil prop))
11191 (allowed (org-property-get-allowed-values nil prop 'table))
11192 (existing (mapcar 'list (org-property-values prop)))
11193 (val (if allowed
11194 (org-completing-read "Value: " allowed nil 'req-match)
11195 (let (org-completion-use-ido)
11196 (org-completing-read
11197 (concat "Value" (if (and cur (string-match "\\S-" cur))
11198 (concat "[" cur "]") "")
11199 ": ")
11200 existing nil nil "" nil cur)))))
11201 (list prop (if (equal val "") cur val))))
11202 (unless (equal (org-entry-get nil property) value)
11203 (org-entry-put nil property value)))
11205 (defun org-delete-property (property)
11206 "In the current entry, delete PROPERTY."
11207 (interactive
11208 (let* ((completion-ignore-case t)
11209 (prop (org-ido-completing-read
11210 "Property: " (org-entry-properties nil 'standard))))
11211 (list prop)))
11212 (message "Property %s %s" property
11213 (if (org-entry-delete nil property)
11214 "deleted"
11215 "was not present in the entry")))
11217 (defun org-delete-property-globally (property)
11218 "Remove PROPERTY globally, from all entries."
11219 (interactive
11220 (let* ((completion-ignore-case t)
11221 (prop (org-ido-completing-read
11222 "Globally remove property: "
11223 (mapcar 'list (org-buffer-property-keys)))))
11224 (list prop)))
11225 (save-excursion
11226 (save-restriction
11227 (widen)
11228 (goto-char (point-min))
11229 (let ((cnt 0))
11230 (while (re-search-forward
11231 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
11232 nil t)
11233 (setq cnt (1+ cnt))
11234 (replace-match ""))
11235 (message "Property \"%s\" removed from %d entries" property cnt)))))
11237 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
11239 (defun org-compute-property-at-point ()
11240 "Compute the property at point.
11241 This looks for an enclosing column format, extracts the operator and
11242 then applies it to the property in the column format's scope."
11243 (interactive)
11244 (unless (org-at-property-p)
11245 (error "Not at a property"))
11246 (let ((prop (org-match-string-no-properties 2)))
11247 (org-columns-get-format-and-top-level)
11248 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
11249 (error "No operator defined for property %s" prop))
11250 (org-columns-compute prop)))
11252 (defun org-property-get-allowed-values (pom property &optional table)
11253 "Get allowed values for the property PROPERTY.
11254 When TABLE is non-nil, return an alist that can directly be used for
11255 completion."
11256 (let (vals)
11257 (cond
11258 ((equal property "TODO")
11259 (setq vals (org-with-point-at pom
11260 (append org-todo-keywords-1 '("")))))
11261 ((equal property "PRIORITY")
11262 (let ((n org-lowest-priority))
11263 (while (>= n org-highest-priority)
11264 (push (char-to-string n) vals)
11265 (setq n (1- n)))))
11266 ((member property org-special-properties))
11268 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
11270 (when (and vals (string-match "\\S-" vals))
11271 (setq vals (car (read-from-string (concat "(" vals ")"))))
11272 (setq vals (mapcar (lambda (x)
11273 (cond ((stringp x) x)
11274 ((numberp x) (number-to-string x))
11275 ((symbolp x) (symbol-name x))
11276 (t "???")))
11277 vals)))))
11278 (if table (mapcar 'list vals) vals)))
11280 (defun org-property-previous-allowed-value (&optional previous)
11281 "Switch to the next allowed value for this property."
11282 (interactive)
11283 (org-property-next-allowed-value t))
11285 (defun org-property-next-allowed-value (&optional previous)
11286 "Switch to the next allowed value for this property."
11287 (interactive)
11288 (unless (org-at-property-p)
11289 (error "Not at a property"))
11290 (let* ((key (match-string 2))
11291 (value (match-string 3))
11292 (allowed (or (org-property-get-allowed-values (point) key)
11293 (and (member value '("[ ]" "[-]" "[X]"))
11294 '("[ ]" "[X]"))))
11295 nval)
11296 (unless allowed
11297 (error "Allowed values for this property have not been defined"))
11298 (if previous (setq allowed (reverse allowed)))
11299 (if (member value allowed)
11300 (setq nval (car (cdr (member value allowed)))))
11301 (setq nval (or nval (car allowed)))
11302 (if (equal nval value)
11303 (error "Only one allowed value for this property"))
11304 (org-at-property-p)
11305 (replace-match (concat " :" key ": " nval) t t)
11306 (org-indent-line-function)
11307 (beginning-of-line 1)
11308 (skip-chars-forward " \t")))
11310 (defun org-find-entry-with-id (ident)
11311 "Locate the entry that contains the ID property with exact value IDENT.
11312 IDENT can be a string, a symbol or a number, this function will search for
11313 the string representation of it.
11314 Return the position where this entry starts, or nil if there is no such entry."
11315 (interactive "sID: ")
11316 (let ((id (cond
11317 ((stringp ident) ident)
11318 ((symbol-name ident) (symbol-name ident))
11319 ((numberp ident) (number-to-string ident))
11320 (t (error "IDENT %s must be a string, symbol or number" ident))))
11321 (case-fold-search nil))
11322 (save-excursion
11323 (save-restriction
11324 (widen)
11325 (goto-char (point-min))
11326 (when (re-search-forward
11327 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
11328 nil t)
11329 (org-back-to-heading)
11330 (point))))))
11332 ;;;; Timestamps
11334 (defvar org-last-changed-timestamp nil)
11335 (defvar org-last-inserted-timestamp nil
11336 "The last time stamp inserted with `org-insert-time-stamp'.")
11337 (defvar org-time-was-given) ; dynamically scoped parameter
11338 (defvar org-end-time-was-given) ; dynamically scoped parameter
11339 (defvar org-ts-what) ; dynamically scoped parameter
11341 (defun org-time-stamp (arg &optional inactive)
11342 "Prompt for a date/time and insert a time stamp.
11343 If the user specifies a time like HH:MM, or if this command is called
11344 with a prefix argument, the time stamp will contain date and time.
11345 Otherwise, only the date will be included. All parts of a date not
11346 specified by the user will be filled in from the current date/time.
11347 So if you press just return without typing anything, the time stamp
11348 will represent the current date/time. If there is already a timestamp
11349 at the cursor, it will be modified."
11350 (interactive "P")
11351 (let* ((ts nil)
11352 (default-time
11353 ;; Default time is either today, or, when entering a range,
11354 ;; the range start.
11355 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
11356 (save-excursion
11357 (re-search-backward
11358 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
11359 (- (point) 20) t)))
11360 (apply 'encode-time (org-parse-time-string (match-string 1)))
11361 (current-time)))
11362 (default-input (and ts (org-get-compact-tod ts)))
11363 org-time-was-given org-end-time-was-given time)
11364 (cond
11365 ((and (org-at-timestamp-p t)
11366 (memq last-command '(org-time-stamp org-time-stamp-inactive))
11367 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
11368 (insert "--")
11369 (setq time (let ((this-command this-command))
11370 (org-read-date arg 'totime nil nil
11371 default-time default-input)))
11372 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
11373 ((org-at-timestamp-p t)
11374 (setq time (let ((this-command this-command))
11375 (org-read-date arg 'totime nil nil default-time default-input)))
11376 (when (org-at-timestamp-p t) ; just to get the match data
11377 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
11378 (replace-match "")
11379 (setq org-last-changed-timestamp
11380 (org-insert-time-stamp
11381 time (or org-time-was-given arg)
11382 inactive nil nil (list org-end-time-was-given))))
11383 (message "Timestamp updated"))
11385 (setq time (let ((this-command this-command))
11386 (org-read-date arg 'totime nil nil default-time default-input)))
11387 (org-insert-time-stamp time (or org-time-was-given arg) inactive
11388 nil nil (list org-end-time-was-given))))))
11390 ;; FIXME: can we use this for something else, like computing time differences?
11391 (defun org-get-compact-tod (s)
11392 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
11393 (let* ((t1 (match-string 1 s))
11394 (h1 (string-to-number (match-string 2 s)))
11395 (m1 (string-to-number (match-string 3 s)))
11396 (t2 (and (match-end 4) (match-string 5 s)))
11397 (h2 (and t2 (string-to-number (match-string 6 s))))
11398 (m2 (and t2 (string-to-number (match-string 7 s))))
11399 dh dm)
11400 (if (not t2)
11402 (setq dh (- h2 h1) dm (- m2 m1))
11403 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
11404 (concat t1 "+" (number-to-string dh)
11405 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
11407 (defun org-time-stamp-inactive (&optional arg)
11408 "Insert an inactive time stamp.
11409 An inactive time stamp is enclosed in square brackets instead of angle
11410 brackets. It is inactive in the sense that it does not trigger agenda entries,
11411 does not link to the calendar and cannot be changed with the S-cursor keys.
11412 So these are more for recording a certain time/date."
11413 (interactive "P")
11414 (org-time-stamp arg 'inactive))
11416 (defvar org-date-ovl (org-make-overlay 1 1))
11417 (org-overlay-put org-date-ovl 'face 'org-warning)
11418 (org-detach-overlay org-date-ovl)
11420 (defvar org-ans1) ; dynamically scoped parameter
11421 (defvar org-ans2) ; dynamically scoped parameter
11423 (defvar org-plain-time-of-day-regexp) ; defined below
11425 (defvar org-overriding-default-time nil) ; dynamically scoped
11426 (defvar org-read-date-overlay nil)
11427 (defvar org-dcst nil) ; dynamically scoped
11429 (defun org-read-date (&optional with-time to-time from-string prompt
11430 default-time default-input)
11431 "Read a date, possibly a time, and make things smooth for the user.
11432 The prompt will suggest to enter an ISO date, but you can also enter anything
11433 which will at least partially be understood by `parse-time-string'.
11434 Unrecognized parts of the date will default to the current day, month, year,
11435 hour and minute. If this command is called to replace a timestamp at point,
11436 of to enter the second timestamp of a range, the default time is taken from the
11437 existing stamp. For example,
11438 3-2-5 --> 2003-02-05
11439 feb 15 --> currentyear-02-15
11440 sep 12 9 --> 2009-09-12
11441 12:45 --> today 12:45
11442 22 sept 0:34 --> currentyear-09-22 0:34
11443 12 --> currentyear-currentmonth-12
11444 Fri --> nearest Friday (today or later)
11445 etc.
11447 Furthermore you can specify a relative date by giving, as the *first* thing
11448 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
11449 change in days weeks, months, years.
11450 With a single plus or minus, the date is relative to today. With a double
11451 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
11452 +4d --> four days from today
11453 +4 --> same as above
11454 +2w --> two weeks from today
11455 ++5 --> five days from default date
11457 The function understands only English month and weekday abbreviations,
11458 but this can be configured with the variables `parse-time-months' and
11459 `parse-time-weekdays'.
11461 While prompting, a calendar is popped up - you can also select the
11462 date with the mouse (button 1). The calendar shows a period of three
11463 months. To scroll it to other months, use the keys `>' and `<'.
11464 If you don't like the calendar, turn it off with
11465 \(setq org-read-date-popup-calendar nil)
11467 With optional argument TO-TIME, the date will immediately be converted
11468 to an internal time.
11469 With an optional argument WITH-TIME, the prompt will suggest to also
11470 insert a time. Note that when WITH-TIME is not set, you can still
11471 enter a time, and this function will inform the calling routine about
11472 this change. The calling routine may then choose to change the format
11473 used to insert the time stamp into the buffer to include the time.
11474 With optional argument FROM-STRING, read from this string instead from
11475 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
11476 the time/date that is used for everything that is not specified by the
11477 user."
11478 (require 'parse-time)
11479 (let* ((org-time-stamp-rounding-minutes
11480 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
11481 (org-dcst org-display-custom-times)
11482 (ct (org-current-time))
11483 (def (or org-overriding-default-time default-time ct))
11484 (defdecode (decode-time def))
11485 (dummy (progn
11486 (when (< (nth 2 defdecode) org-extend-today-until)
11487 (setcar (nthcdr 2 defdecode) -1)
11488 (setcar (nthcdr 1 defdecode) 59)
11489 (setq def (apply 'encode-time defdecode)
11490 defdecode (decode-time def)))))
11491 (calendar-move-hook nil)
11492 (calendar-view-diary-initially-flag nil)
11493 (view-diary-entries-initially nil)
11494 (calendar-view-holidays-initially-flag nil)
11495 (view-calendar-holidays-initially nil)
11496 (timestr (format-time-string
11497 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
11498 (prompt (concat (if prompt (concat prompt " ") "")
11499 (format "Date+time [%s]: " timestr)))
11500 ans (org-ans0 "") org-ans1 org-ans2 final)
11502 (cond
11503 (from-string (setq ans from-string))
11504 (org-read-date-popup-calendar
11505 (save-excursion
11506 (save-window-excursion
11507 (calendar)
11508 (calendar-forward-day (- (time-to-days def)
11509 (calendar-absolute-from-gregorian
11510 (calendar-current-date))))
11511 (org-eval-in-calendar nil t)
11512 (let* ((old-map (current-local-map))
11513 (map (copy-keymap calendar-mode-map))
11514 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11515 (org-defkey map (kbd "RET") 'org-calendar-select)
11516 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11517 'org-calendar-select-mouse)
11518 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11519 'org-calendar-select-mouse)
11520 (org-defkey minibuffer-local-map [(meta shift left)]
11521 (lambda () (interactive)
11522 (org-eval-in-calendar '(calendar-backward-month 1))))
11523 (org-defkey minibuffer-local-map [(meta shift right)]
11524 (lambda () (interactive)
11525 (org-eval-in-calendar '(calendar-forward-month 1))))
11526 (org-defkey minibuffer-local-map [(meta shift up)]
11527 (lambda () (interactive)
11528 (org-eval-in-calendar '(calendar-backward-year 1))))
11529 (org-defkey minibuffer-local-map [(meta shift down)]
11530 (lambda () (interactive)
11531 (org-eval-in-calendar '(calendar-forward-year 1))))
11532 (org-defkey minibuffer-local-map [(shift up)]
11533 (lambda () (interactive)
11534 (org-eval-in-calendar '(calendar-backward-week 1))))
11535 (org-defkey minibuffer-local-map [(shift down)]
11536 (lambda () (interactive)
11537 (org-eval-in-calendar '(calendar-forward-week 1))))
11538 (org-defkey minibuffer-local-map [(shift left)]
11539 (lambda () (interactive)
11540 (org-eval-in-calendar '(calendar-backward-day 1))))
11541 (org-defkey minibuffer-local-map [(shift right)]
11542 (lambda () (interactive)
11543 (org-eval-in-calendar '(calendar-forward-day 1))))
11544 (org-defkey minibuffer-local-map ">"
11545 (lambda () (interactive)
11546 (org-eval-in-calendar '(scroll-calendar-left 1))))
11547 (org-defkey minibuffer-local-map "<"
11548 (lambda () (interactive)
11549 (org-eval-in-calendar '(scroll-calendar-right 1))))
11550 (unwind-protect
11551 (progn
11552 (use-local-map map)
11553 (add-hook 'post-command-hook 'org-read-date-display)
11554 (setq org-ans0 (read-string prompt default-input nil nil))
11555 ;; org-ans0: from prompt
11556 ;; org-ans1: from mouse click
11557 ;; org-ans2: from calendar motion
11558 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11559 (remove-hook 'post-command-hook 'org-read-date-display)
11560 (use-local-map old-map)
11561 (when org-read-date-overlay
11562 (org-delete-overlay org-read-date-overlay)
11563 (setq org-read-date-overlay nil)))))))
11565 (t ; Naked prompt only
11566 (unwind-protect
11567 (setq ans (read-string prompt default-input nil timestr))
11568 (when org-read-date-overlay
11569 (org-delete-overlay org-read-date-overlay)
11570 (setq org-read-date-overlay nil)))))
11572 (setq final (org-read-date-analyze ans def defdecode))
11574 (if to-time
11575 (apply 'encode-time final)
11576 (if (and (boundp 'org-time-was-given) org-time-was-given)
11577 (format "%04d-%02d-%02d %02d:%02d"
11578 (nth 5 final) (nth 4 final) (nth 3 final)
11579 (nth 2 final) (nth 1 final))
11580 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11581 (defvar def)
11582 (defvar defdecode)
11583 (defvar with-time)
11584 (defun org-read-date-display ()
11585 "Display the current date prompt interpretation in the minibuffer."
11586 (when org-read-date-display-live
11587 (when org-read-date-overlay
11588 (org-delete-overlay org-read-date-overlay))
11589 (let ((p (point)))
11590 (end-of-line 1)
11591 (while (not (equal (buffer-substring
11592 (max (point-min) (- (point) 4)) (point))
11593 " "))
11594 (insert " "))
11595 (goto-char p))
11596 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11597 " " (or org-ans1 org-ans2)))
11598 (org-end-time-was-given nil)
11599 (f (org-read-date-analyze ans def defdecode))
11600 (fmts (if org-dcst
11601 org-time-stamp-custom-formats
11602 org-time-stamp-formats))
11603 (fmt (if (or with-time
11604 (and (boundp 'org-time-was-given) org-time-was-given))
11605 (cdr fmts)
11606 (car fmts)))
11607 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11608 (when (and org-end-time-was-given
11609 (string-match org-plain-time-of-day-regexp txt))
11610 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11611 org-end-time-was-given
11612 (substring txt (match-end 0)))))
11613 (setq org-read-date-overlay
11614 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11615 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11617 (defun org-read-date-analyze (ans def defdecode)
11618 "Analyse the combined answer of the date prompt."
11619 ;; FIXME: cleanup and comment
11620 (let (delta deltan deltaw deltadef year month day
11621 hour minute second wday pm h2 m2 tl wday1
11622 iso-year iso-weekday iso-week iso-year iso-date)
11624 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11625 (setq ans "+0"))
11627 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11628 (setq ans (replace-match "" t t ans)
11629 deltan (car delta)
11630 deltaw (nth 1 delta)
11631 deltadef (nth 2 delta)))
11633 ;; Check if there is an iso week date in there
11634 ;; If yes, sore the info and postpone interpreting it until the rest
11635 ;; of the parsing is done
11636 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11637 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11638 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11639 iso-week (string-to-number (match-string 2 ans)))
11640 (setq ans (replace-match "" t t ans)))
11642 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11643 (when (string-match
11644 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11645 (setq year (if (match-end 2)
11646 (string-to-number (match-string 2 ans))
11647 (string-to-number (format-time-string "%Y")))
11648 month (string-to-number (match-string 3 ans))
11649 day (string-to-number (match-string 4 ans)))
11650 (if (< year 100) (setq year (+ 2000 year)))
11651 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11652 t nil ans)))
11653 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11654 ;; If there is a time with am/pm, and *no* time without it, we convert
11655 ;; so that matching will be successful.
11656 (loop for i from 1 to 2 do ; twice, for end time as well
11657 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11658 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11659 (setq hour (string-to-number (match-string 1 ans))
11660 minute (if (match-end 3)
11661 (string-to-number (match-string 3 ans))
11663 pm (equal ?p
11664 (string-to-char (downcase (match-string 4 ans)))))
11665 (if (and (= hour 12) (not pm))
11666 (setq hour 0)
11667 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11668 (setq ans (replace-match (format "%02d:%02d" hour minute)
11669 t t ans))))
11671 ;; Check if a time range is given as a duration
11672 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11673 (setq hour (string-to-number (match-string 1 ans))
11674 h2 (+ hour (string-to-number (match-string 3 ans)))
11675 minute (string-to-number (match-string 2 ans))
11676 m2 (+ minute (if (match-end 5) (string-to-number
11677 (match-string 5 ans))0)))
11678 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11679 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11680 t t ans)))
11682 ;; Check if there is a time range
11683 (when (boundp 'org-end-time-was-given)
11684 (setq org-time-was-given nil)
11685 (when (and (string-match org-plain-time-of-day-regexp ans)
11686 (match-end 8))
11687 (setq org-end-time-was-given (match-string 8 ans))
11688 (setq ans (concat (substring ans 0 (match-beginning 7))
11689 (substring ans (match-end 7))))))
11691 (setq tl (parse-time-string ans)
11692 day (or (nth 3 tl) (nth 3 defdecode))
11693 month (or (nth 4 tl)
11694 (if (and org-read-date-prefer-future
11695 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11696 (1+ (nth 4 defdecode))
11697 (nth 4 defdecode)))
11698 year (or (nth 5 tl)
11699 (if (and org-read-date-prefer-future
11700 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11701 (1+ (nth 5 defdecode))
11702 (nth 5 defdecode)))
11703 hour (or (nth 2 tl) (nth 2 defdecode))
11704 minute (or (nth 1 tl) (nth 1 defdecode))
11705 second (or (nth 0 tl) 0)
11706 wday (nth 6 tl))
11708 ;; Special date definitions below
11709 (cond
11710 (iso-week
11711 ;; There was an iso week
11712 (setq year (or iso-year year)
11713 day (or iso-weekday wday 1)
11714 wday nil ; to make sure that the trigger below does not match
11715 iso-date (calendar-gregorian-from-absolute
11716 (calendar-absolute-from-iso
11717 (list iso-week day year))))
11718 ; FIXME: Should we also push ISO weeks into the future?
11719 ; (when (and org-read-date-prefer-future
11720 ; (not iso-year)
11721 ; (< (calendar-absolute-from-gregorian iso-date)
11722 ; (time-to-days (current-time))))
11723 ; (setq year (1+ year)
11724 ; iso-date (calendar-gregorian-from-absolute
11725 ; (calendar-absolute-from-iso
11726 ; (list iso-week day year)))))
11727 (setq month (car iso-date)
11728 year (nth 2 iso-date)
11729 day (nth 1 iso-date)))
11730 (deltan
11731 (unless deltadef
11732 (let ((now (decode-time (current-time))))
11733 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11734 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11735 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11736 ((equal deltaw "m") (setq month (+ month deltan)))
11737 ((equal deltaw "y") (setq year (+ year deltan)))))
11738 ((and wday (not (nth 3 tl)))
11739 ;; Weekday was given, but no day, so pick that day in the week
11740 ;; on or after the derived date.
11741 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11742 (unless (equal wday wday1)
11743 (setq day (+ day (% (- wday wday1 -7) 7))))))
11744 (if (and (boundp 'org-time-was-given)
11745 (nth 2 tl))
11746 (setq org-time-was-given t))
11747 (if (< year 100) (setq year (+ 2000 year)))
11748 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11749 (list second minute hour day month year)))
11751 (defvar parse-time-weekdays)
11753 (defun org-read-date-get-relative (s today default)
11754 "Check string S for special relative date string.
11755 TODAY and DEFAULT are internal times, for today and for a default.
11756 Return shift list (N what def-flag)
11757 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11758 N is the number of WHATs to shift.
11759 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11760 the DEFAULT date rather than TODAY."
11761 (when (and
11762 (string-match
11763 (concat
11764 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11765 "\\([0-9]+\\)?"
11766 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11767 "\\([ \t]\\|$\\)") s)
11768 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11769 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11770 (string-to-char (substring (match-string 1 s) -1))
11771 ?+))
11772 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11773 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11774 (what (if (match-end 3) (match-string 3 s) "d"))
11775 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11776 (date (if rel default today))
11777 (wday (nth 6 (decode-time date)))
11778 delta)
11779 (if wday1
11780 (progn
11781 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11782 (if (= dir ?-) (setq delta (- delta 7)))
11783 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11784 (list delta "d" rel))
11785 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11787 (defun org-eval-in-calendar (form &optional keepdate)
11788 "Eval FORM in the calendar window and return to current window.
11789 Also, store the cursor date in variable org-ans2."
11790 (let ((sw (selected-window)))
11791 (select-window (get-buffer-window "*Calendar*"))
11792 (eval form)
11793 (when (and (not keepdate) (calendar-cursor-to-date))
11794 (let* ((date (calendar-cursor-to-date))
11795 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11796 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11797 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11798 (select-window sw)))
11800 (defun org-calendar-select ()
11801 "Return to `org-read-date' with the date currently selected.
11802 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11803 (interactive)
11804 (when (calendar-cursor-to-date)
11805 (let* ((date (calendar-cursor-to-date))
11806 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11807 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11808 (if (active-minibuffer-window) (exit-minibuffer))))
11810 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11811 "Insert a date stamp for the date given by the internal TIME.
11812 WITH-HM means, use the stamp format that includes the time of the day.
11813 INACTIVE means use square brackets instead of angular ones, so that the
11814 stamp will not contribute to the agenda.
11815 PRE and POST are optional strings to be inserted before and after the
11816 stamp.
11817 The command returns the inserted time stamp."
11818 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11819 stamp)
11820 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11821 (insert-before-markers (or pre ""))
11822 (insert-before-markers (setq stamp (format-time-string fmt time)))
11823 (when (listp extra)
11824 (setq extra (car extra))
11825 (if (and (stringp extra)
11826 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11827 (setq extra (format "-%02d:%02d"
11828 (string-to-number (match-string 1 extra))
11829 (string-to-number (match-string 2 extra))))
11830 (setq extra nil)))
11831 (when extra
11832 (backward-char 1)
11833 (insert-before-markers extra)
11834 (forward-char 1))
11835 (insert-before-markers (or post ""))
11836 (setq org-last-inserted-timestamp stamp)))
11838 (defun org-toggle-time-stamp-overlays ()
11839 "Toggle the use of custom time stamp formats."
11840 (interactive)
11841 (setq org-display-custom-times (not org-display-custom-times))
11842 (unless org-display-custom-times
11843 (let ((p (point-min)) (bmp (buffer-modified-p)))
11844 (while (setq p (next-single-property-change p 'display))
11845 (if (and (get-text-property p 'display)
11846 (eq (get-text-property p 'face) 'org-date))
11847 (remove-text-properties
11848 p (setq p (next-single-property-change p 'display))
11849 '(display t))))
11850 (set-buffer-modified-p bmp)))
11851 (if (featurep 'xemacs)
11852 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11853 (org-restart-font-lock)
11854 (setq org-table-may-need-update t)
11855 (if org-display-custom-times
11856 (message "Time stamps are overlayed with custom format")
11857 (message "Time stamp overlays removed")))
11859 (defun org-display-custom-time (beg end)
11860 "Overlay modified time stamp format over timestamp between BEG and END."
11861 (let* ((ts (buffer-substring beg end))
11862 t1 w1 with-hm tf time str w2 (off 0))
11863 (save-match-data
11864 (setq t1 (org-parse-time-string ts t))
11865 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11866 (setq off (- (match-end 0) (match-beginning 0)))))
11867 (setq end (- end off))
11868 (setq w1 (- end beg)
11869 with-hm (and (nth 1 t1) (nth 2 t1))
11870 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11871 time (org-fix-decoded-time t1)
11872 str (org-add-props
11873 (format-time-string
11874 (substring tf 1 -1) (apply 'encode-time time))
11875 nil 'mouse-face 'highlight)
11876 w2 (length str))
11877 (if (not (= w2 w1))
11878 (add-text-properties (1+ beg) (+ 2 beg)
11879 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11880 (if (featurep 'xemacs)
11881 (progn
11882 (put-text-property beg end 'invisible t)
11883 (put-text-property beg end 'end-glyph (make-glyph str)))
11884 (put-text-property beg end 'display str))))
11886 (defun org-translate-time (string)
11887 "Translate all timestamps in STRING to custom format.
11888 But do this only if the variable `org-display-custom-times' is set."
11889 (when org-display-custom-times
11890 (save-match-data
11891 (let* ((start 0)
11892 (re org-ts-regexp-both)
11893 t1 with-hm inactive tf time str beg end)
11894 (while (setq start (string-match re string start))
11895 (setq beg (match-beginning 0)
11896 end (match-end 0)
11897 t1 (save-match-data
11898 (org-parse-time-string (substring string beg end) t))
11899 with-hm (and (nth 1 t1) (nth 2 t1))
11900 inactive (equal (substring string beg (1+ beg)) "[")
11901 tf (funcall (if with-hm 'cdr 'car)
11902 org-time-stamp-custom-formats)
11903 time (org-fix-decoded-time t1)
11904 str (format-time-string
11905 (concat
11906 (if inactive "[" "<") (substring tf 1 -1)
11907 (if inactive "]" ">"))
11908 (apply 'encode-time time))
11909 string (replace-match str t t string)
11910 start (+ start (length str)))))))
11911 string)
11913 (defun org-fix-decoded-time (time)
11914 "Set 0 instead of nil for the first 6 elements of time.
11915 Don't touch the rest."
11916 (let ((n 0))
11917 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11919 (defun org-days-to-time (timestamp-string)
11920 "Difference between TIMESTAMP-STRING and now in days."
11921 (- (time-to-days (org-time-string-to-time timestamp-string))
11922 (time-to-days (current-time))))
11924 (defun org-deadline-close (timestamp-string &optional ndays)
11925 "Is the time in TIMESTAMP-STRING close to the current date?"
11926 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11927 (and (< (org-days-to-time timestamp-string) ndays)
11928 (not (org-entry-is-done-p))))
11930 (defun org-get-wdays (ts)
11931 "Get the deadline lead time appropriate for timestring TS."
11932 (cond
11933 ((<= org-deadline-warning-days 0)
11934 ;; 0 or negative, enforce this value no matter what
11935 (- org-deadline-warning-days))
11936 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
11937 ;; lead time is specified.
11938 (floor (* (string-to-number (match-string 1 ts))
11939 (cdr (assoc (match-string 2 ts)
11940 '(("d" . 1) ("w" . 7)
11941 ("m" . 30.4) ("y" . 365.25)))))))
11942 ;; go for the default.
11943 (t org-deadline-warning-days)))
11945 (defun org-calendar-select-mouse (ev)
11946 "Return to `org-read-date' with the date currently selected.
11947 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11948 (interactive "e")
11949 (mouse-set-point ev)
11950 (when (calendar-cursor-to-date)
11951 (let* ((date (calendar-cursor-to-date))
11952 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11953 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11954 (if (active-minibuffer-window) (exit-minibuffer))))
11956 (defun org-check-deadlines (ndays)
11957 "Check if there are any deadlines due or past due.
11958 A deadline is considered due if it happens within `org-deadline-warning-days'
11959 days from today's date. If the deadline appears in an entry marked DONE,
11960 it is not shown. The prefix arg NDAYS can be used to test that many
11961 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11962 (interactive "P")
11963 (let* ((org-warn-days
11964 (cond
11965 ((equal ndays '(4)) 100000)
11966 (ndays (prefix-numeric-value ndays))
11967 (t (abs org-deadline-warning-days))))
11968 (case-fold-search nil)
11969 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11970 (callback
11971 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11973 (message "%d deadlines past-due or due within %d days"
11974 (org-occur regexp nil callback)
11975 org-warn-days)))
11977 (defun org-check-before-date (date)
11978 "Check if there are deadlines or scheduled entries before DATE."
11979 (interactive (list (org-read-date)))
11980 (let ((case-fold-search nil)
11981 (regexp (concat "\\<\\(" org-deadline-string
11982 "\\|" org-scheduled-string
11983 "\\) *<\\([^>]+\\)>"))
11984 (callback
11985 (lambda () (time-less-p
11986 (org-time-string-to-time (match-string 2))
11987 (org-time-string-to-time date)))))
11988 (message "%d entries before %s"
11989 (org-occur regexp nil callback) date)))
11991 (defun org-evaluate-time-range (&optional to-buffer)
11992 "Evaluate a time range by computing the difference between start and end.
11993 Normally the result is just printed in the echo area, but with prefix arg
11994 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11995 If the time range is actually in a table, the result is inserted into the
11996 next column.
11997 For time difference computation, a year is assumed to be exactly 365
11998 days in order to avoid rounding problems."
11999 (interactive "P")
12001 (org-clock-update-time-maybe)
12002 (save-excursion
12003 (unless (org-at-date-range-p t)
12004 (goto-char (point-at-bol))
12005 (re-search-forward org-tr-regexp-both (point-at-eol) t))
12006 (if (not (org-at-date-range-p t))
12007 (error "Not at a time-stamp range, and none found in current line")))
12008 (let* ((ts1 (match-string 1))
12009 (ts2 (match-string 2))
12010 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12011 (match-end (match-end 0))
12012 (time1 (org-time-string-to-time ts1))
12013 (time2 (org-time-string-to-time ts2))
12014 (t1 (time-to-seconds time1))
12015 (t2 (time-to-seconds time2))
12016 (diff (abs (- t2 t1)))
12017 (negative (< (- t2 t1) 0))
12018 ;; (ys (floor (* 365 24 60 60)))
12019 (ds (* 24 60 60))
12020 (hs (* 60 60))
12021 (fy "%dy %dd %02d:%02d")
12022 (fy1 "%dy %dd")
12023 (fd "%dd %02d:%02d")
12024 (fd1 "%dd")
12025 (fh "%02d:%02d")
12026 y d h m align)
12027 (if havetime
12028 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12030 d (floor (/ diff ds)) diff (mod diff ds)
12031 h (floor (/ diff hs)) diff (mod diff hs)
12032 m (floor (/ diff 60)))
12033 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12035 d (floor (+ (/ diff ds) 0.5))
12036 h 0 m 0))
12037 (if (not to-buffer)
12038 (message "%s" (org-make-tdiff-string y d h m))
12039 (if (org-at-table-p)
12040 (progn
12041 (goto-char match-end)
12042 (setq align t)
12043 (and (looking-at " *|") (goto-char (match-end 0))))
12044 (goto-char match-end))
12045 (if (looking-at
12046 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12047 (replace-match ""))
12048 (if negative (insert " -"))
12049 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12050 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12051 (insert " " (format fh h m))))
12052 (if align (org-table-align))
12053 (message "Time difference inserted")))))
12055 (defun org-make-tdiff-string (y d h m)
12056 (let ((fmt "")
12057 (l nil))
12058 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12059 l (push y l)))
12060 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12061 l (push d l)))
12062 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12063 l (push h l)))
12064 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12065 l (push m l)))
12066 (apply 'format fmt (nreverse l))))
12068 (defun org-time-string-to-time (s)
12069 (apply 'encode-time (org-parse-time-string s)))
12071 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
12072 "Convert a time stamp to an absolute day number.
12073 If there is a specifyer for a cyclic time stamp, get the closest date to
12074 DAYNR.
12075 PREFER and SHOW-ALL are passed through to `org-closest-date'."
12076 (cond
12077 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
12078 (if (org-diary-sexp-entry (match-string 1 s) "" date)
12079 daynr
12080 (+ daynr 1000)))
12081 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
12082 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
12083 (time-to-days (current-time))) (match-string 0 s)
12084 prefer show-all))
12085 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
12087 (defun org-days-to-iso-week (days)
12088 "Return the iso week number."
12089 (require 'cal-iso)
12090 (car (calendar-iso-from-absolute days)))
12092 (defun org-small-year-to-year (year)
12093 "Convert 2-digit years into 4-digit years.
12094 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
12095 The year 2000 cannot be abbreviated. Any year larger than 99
12096 is returned unchanged."
12097 (if (< year 38)
12098 (setq year (+ 2000 year))
12099 (if (< year 100)
12100 (setq year (+ 1900 year))))
12101 year)
12103 (defun org-time-from-absolute (d)
12104 "Return the time corresponding to date D.
12105 D may be an absolute day number, or a calendar-type list (month day year)."
12106 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
12107 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
12109 (defun org-calendar-holiday ()
12110 "List of holidays, for Diary display in Org-mode."
12111 (require 'holidays)
12112 (let ((hl (funcall
12113 (if (fboundp 'calendar-check-holidays)
12114 'calendar-check-holidays 'check-calendar-holidays) date)))
12115 (if hl (mapconcat 'identity hl "; "))))
12117 (defun org-diary-sexp-entry (sexp entry date)
12118 "Process a SEXP diary ENTRY for DATE."
12119 (require 'diary-lib)
12120 (let ((result (if calendar-debug-sexp
12121 (let ((stack-trace-on-error t))
12122 (eval (car (read-from-string sexp))))
12123 (condition-case nil
12124 (eval (car (read-from-string sexp)))
12125 (error
12126 (beep)
12127 (message "Bad sexp at line %d in %s: %s"
12128 (org-current-line)
12129 (buffer-file-name) sexp)
12130 (sleep-for 2))))))
12131 (cond ((stringp result) result)
12132 ((and (consp result)
12133 (stringp (cdr result))) (cdr result))
12134 (result entry)
12135 (t nil))))
12137 (defun org-diary-to-ical-string (frombuf)
12138 "Get iCalendar entries from diary entries in buffer FROMBUF.
12139 This uses the icalendar.el library."
12140 (let* ((tmpdir (if (featurep 'xemacs)
12141 (temp-directory)
12142 temporary-file-directory))
12143 (tmpfile (make-temp-name
12144 (expand-file-name "orgics" tmpdir)))
12145 buf rtn b e)
12146 (save-excursion
12147 (set-buffer frombuf)
12148 (icalendar-export-region (point-min) (point-max) tmpfile)
12149 (setq buf (find-buffer-visiting tmpfile))
12150 (set-buffer buf)
12151 (goto-char (point-min))
12152 (if (re-search-forward "^BEGIN:VEVENT" nil t)
12153 (setq b (match-beginning 0)))
12154 (goto-char (point-max))
12155 (if (re-search-backward "^END:VEVENT" nil t)
12156 (setq e (match-end 0)))
12157 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
12158 (kill-buffer buf)
12159 (delete-file tmpfile)
12160 rtn))
12162 (defun org-closest-date (start current change prefer show-all)
12163 "Find the date closest to CURRENT that is consistent with START and CHANGE.
12164 When PREFER is `past' return a date that is either CURRENT or past.
12165 When PREFER is `future', return a date that is either CURRENT or future.
12166 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
12167 ;; Make the proper lists from the dates
12168 (catch 'exit
12169 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
12170 dn dw sday cday n1 n2 n0
12171 d m y y1 y2 date1 date2 nmonths nm ny m2)
12173 (setq start (org-date-to-gregorian start)
12174 current (org-date-to-gregorian
12175 (if show-all
12176 current
12177 (time-to-days (current-time))))
12178 sday (calendar-absolute-from-gregorian start)
12179 cday (calendar-absolute-from-gregorian current))
12181 (if (<= cday sday) (throw 'exit sday))
12183 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
12184 (setq dn (string-to-number (match-string 1 change))
12185 dw (cdr (assoc (match-string 2 change) a1)))
12186 (error "Invalid change specifyer: %s" change))
12187 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
12188 (cond
12189 ((eq dw 'day)
12190 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
12191 n2 (+ n1 dn)))
12192 ((eq dw 'year)
12193 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
12194 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
12195 (setq date1 (list m d y1)
12196 n1 (calendar-absolute-from-gregorian date1)
12197 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
12198 n2 (calendar-absolute-from-gregorian date2)))
12199 ((eq dw 'month)
12200 ;; approx number of month between the two dates
12201 (setq nmonths (floor (/ (- cday sday) 30.436875)))
12202 ;; How often does dn fit in there?
12203 (setq d (nth 1 start) m (car start) y (nth 2 start)
12204 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
12205 m (+ m nm)
12206 ny (floor (/ m 12))
12207 y (+ y ny)
12208 m (- m (* ny 12)))
12209 (while (> m 12) (setq m (- m 12) y (1+ y)))
12210 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
12211 (setq m2 (+ m dn) y2 y)
12212 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12213 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
12214 (while (<= n2 cday)
12215 (setq n1 n2 m m2 y y2)
12216 (setq m2 (+ m dn) y2 y)
12217 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12218 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
12219 ;; Make sure n1 is the earlier date
12220 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
12221 (if show-all
12222 (cond
12223 ((eq prefer 'past) n1)
12224 ((eq prefer 'future) (if (= cday n1) n1 n2))
12225 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
12226 (cond
12227 ((eq prefer 'past) n1)
12228 ((eq prefer 'future) (if (= cday n1) n1 n2))
12229 (t (if (= cday n1) n1 n2)))))))
12231 (defun org-date-to-gregorian (date)
12232 "Turn any specification of DATE into a gregorian date for the calendar."
12233 (cond ((integerp date) (calendar-gregorian-from-absolute date))
12234 ((and (listp date) (= (length date) 3)) date)
12235 ((stringp date)
12236 (setq date (org-parse-time-string date))
12237 (list (nth 4 date) (nth 3 date) (nth 5 date)))
12238 ((listp date)
12239 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
12241 (defun org-parse-time-string (s &optional nodefault)
12242 "Parse the standard Org-mode time string.
12243 This should be a lot faster than the normal `parse-time-string'.
12244 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12245 hour and minute fields will be nil if not given."
12246 (if (string-match org-ts-regexp0 s)
12247 (list 0
12248 (if (or (match-beginning 8) (not nodefault))
12249 (string-to-number (or (match-string 8 s) "0")))
12250 (if (or (match-beginning 7) (not nodefault))
12251 (string-to-number (or (match-string 7 s) "0")))
12252 (string-to-number (match-string 4 s))
12253 (string-to-number (match-string 3 s))
12254 (string-to-number (match-string 2 s))
12255 nil nil nil)
12256 (make-list 9 0)))
12258 (defun org-timestamp-up (&optional arg)
12259 "Increase the date item at the cursor by one.
12260 If the cursor is on the year, change the year. If it is on the month or
12261 the day, change that.
12262 With prefix ARG, change by that many units."
12263 (interactive "p")
12264 (org-timestamp-change (prefix-numeric-value arg)))
12266 (defun org-timestamp-down (&optional arg)
12267 "Decrease the date item at the cursor by one.
12268 If the cursor is on the year, change the year. If it is on the month or
12269 the day, change that.
12270 With prefix ARG, change by that many units."
12271 (interactive "p")
12272 (org-timestamp-change (- (prefix-numeric-value arg))))
12274 (defun org-timestamp-up-day (&optional arg)
12275 "Increase the date in the time stamp by one day.
12276 With prefix ARG, change that many days."
12277 (interactive "p")
12278 (if (and (not (org-at-timestamp-p t))
12279 (org-on-heading-p))
12280 (org-todo 'up)
12281 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12283 (defun org-timestamp-down-day (&optional arg)
12284 "Decrease the date in the time stamp by one day.
12285 With prefix ARG, change that many days."
12286 (interactive "p")
12287 (if (and (not (org-at-timestamp-p t))
12288 (org-on-heading-p))
12289 (org-todo 'down)
12290 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12292 (defun org-at-timestamp-p (&optional inactive-ok)
12293 "Determine if the cursor is in or at a timestamp."
12294 (interactive)
12295 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12296 (pos (point))
12297 (ans (or (looking-at tsr)
12298 (save-excursion
12299 (skip-chars-backward "^[<\n\r\t")
12300 (if (> (point) (point-min)) (backward-char 1))
12301 (and (looking-at tsr)
12302 (> (- (match-end 0) pos) -1))))))
12303 (and ans
12304 (boundp 'org-ts-what)
12305 (setq org-ts-what
12306 (cond
12307 ((= pos (match-beginning 0)) 'bracket)
12308 ((= pos (1- (match-end 0))) 'bracket)
12309 ((org-pos-in-match-range pos 2) 'year)
12310 ((org-pos-in-match-range pos 3) 'month)
12311 ((org-pos-in-match-range pos 7) 'hour)
12312 ((org-pos-in-match-range pos 8) 'minute)
12313 ((or (org-pos-in-match-range pos 4)
12314 (org-pos-in-match-range pos 5)) 'day)
12315 ((and (> pos (or (match-end 8) (match-end 5)))
12316 (< pos (match-end 0)))
12317 (- pos (or (match-end 8) (match-end 5))))
12318 (t 'day))))
12319 ans))
12321 (defun org-toggle-timestamp-type ()
12322 "Toggle the type (<active> or [inactive]) of a time stamp."
12323 (interactive)
12324 (when (org-at-timestamp-p t)
12325 (let ((beg (match-beginning 0)) (end (match-end 0))
12326 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
12327 (save-excursion
12328 (goto-char beg)
12329 (while (re-search-forward "[][<>]" end t)
12330 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
12331 t t)))
12332 (message "Timestamp is now %sactive"
12333 (if (equal (char-after beg) ?<) "" "in")))))
12335 (defun org-timestamp-change (n &optional what)
12336 "Change the date in the time stamp at point.
12337 The date will be changed by N times WHAT. WHAT can be `day', `month',
12338 `year', `minute', `second'. If WHAT is not given, the cursor position
12339 in the timestamp determines what will be changed."
12340 (let ((pos (point))
12341 with-hm inactive
12342 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
12343 org-ts-what
12344 extra rem
12345 ts time time0)
12346 (if (not (org-at-timestamp-p t))
12347 (error "Not at a timestamp"))
12348 (if (and (not what) (eq org-ts-what 'bracket))
12349 (org-toggle-timestamp-type)
12350 (if (and (not what) (not (eq org-ts-what 'day))
12351 org-display-custom-times
12352 (get-text-property (point) 'display)
12353 (not (get-text-property (1- (point)) 'display)))
12354 (setq org-ts-what 'day))
12355 (setq org-ts-what (or what org-ts-what)
12356 inactive (= (char-after (match-beginning 0)) ?\[)
12357 ts (match-string 0))
12358 (replace-match "")
12359 (if (string-match
12360 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
12362 (setq extra (match-string 1 ts)))
12363 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
12364 (setq with-hm t))
12365 (setq time0 (org-parse-time-string ts))
12366 (when (and (eq org-ts-what 'minute)
12367 (eq current-prefix-arg nil))
12368 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
12369 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
12370 (setcar (cdr time0) (+ (nth 1 time0)
12371 (if (> n 0) (- rem) (- dm rem))))))
12372 (setq time
12373 (encode-time (or (car time0) 0)
12374 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
12375 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
12376 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
12377 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
12378 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
12379 (nthcdr 6 time0)))
12380 (when (integerp org-ts-what)
12381 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
12382 (if (eq what 'calendar)
12383 (let ((cal-date (org-get-date-from-calendar)))
12384 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12385 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12386 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12387 (setcar time0 (or (car time0) 0))
12388 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12389 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
12390 (setq time (apply 'encode-time time0))))
12391 (setq org-last-changed-timestamp
12392 (org-insert-time-stamp time with-hm inactive nil nil extra))
12393 (org-clock-update-time-maybe)
12394 (goto-char pos)
12395 ;; Try to recenter the calendar window, if any
12396 (if (and org-calendar-follow-timestamp-change
12397 (get-buffer-window "*Calendar*" t)
12398 (memq org-ts-what '(day month year)))
12399 (org-recenter-calendar (time-to-days time))))))
12401 (defun org-modify-ts-extra (s pos n dm)
12402 "Change the different parts of the lead-time and repeat fields in timestamp."
12403 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
12404 ng h m new rem)
12405 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
12406 (cond
12407 ((or (org-pos-in-match-range pos 2)
12408 (org-pos-in-match-range pos 3))
12409 (setq m (string-to-number (match-string 3 s))
12410 h (string-to-number (match-string 2 s)))
12411 (if (org-pos-in-match-range pos 2)
12412 (setq h (+ h n))
12413 (setq n (* dm (org-no-warnings (signum n))))
12414 (when (not (= 0 (setq rem (% m dm))))
12415 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
12416 (setq m (+ m n)))
12417 (if (< m 0) (setq m (+ m 60) h (1- h)))
12418 (if (> m 59) (setq m (- m 60) h (1+ h)))
12419 (setq h (min 24 (max 0 h)))
12420 (setq ng 1 new (format "-%02d:%02d" h m)))
12421 ((org-pos-in-match-range pos 6)
12422 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
12423 ((org-pos-in-match-range pos 5)
12424 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
12426 ((org-pos-in-match-range pos 9)
12427 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
12428 ((org-pos-in-match-range pos 8)
12429 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
12431 (when ng
12432 (setq s (concat
12433 (substring s 0 (match-beginning ng))
12435 (substring s (match-end ng))))))
12438 (defun org-recenter-calendar (date)
12439 "If the calendar is visible, recenter it to DATE."
12440 (let* ((win (selected-window))
12441 (cwin (get-buffer-window "*Calendar*" t))
12442 (calendar-move-hook nil))
12443 (when cwin
12444 (select-window cwin)
12445 (calendar-goto-date (if (listp date) date
12446 (calendar-gregorian-from-absolute date)))
12447 (select-window win))))
12449 (defun org-goto-calendar (&optional arg)
12450 "Go to the Emacs calendar at the current date.
12451 If there is a time stamp in the current line, go to that date.
12452 A prefix ARG can be used to force the current date."
12453 (interactive "P")
12454 (let ((tsr org-ts-regexp) diff
12455 (calendar-move-hook nil)
12456 (calendar-view-holidays-initially-flag nil)
12457 (view-calendar-holidays-initially nil)
12458 (calendar-view-diary-initially-flag nil)
12459 (view-diary-entries-initially nil))
12460 (if (or (org-at-timestamp-p)
12461 (save-excursion
12462 (beginning-of-line 1)
12463 (looking-at (concat ".*" tsr))))
12464 (let ((d1 (time-to-days (current-time)))
12465 (d2 (time-to-days
12466 (org-time-string-to-time (match-string 1)))))
12467 (setq diff (- d2 d1))))
12468 (calendar)
12469 (calendar-goto-today)
12470 (if (and diff (not arg)) (calendar-forward-day diff))))
12472 (defun org-get-date-from-calendar ()
12473 "Return a list (month day year) of date at point in calendar."
12474 (with-current-buffer "*Calendar*"
12475 (save-match-data
12476 (calendar-cursor-to-date))))
12478 (defun org-date-from-calendar ()
12479 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12480 If there is already a time stamp at the cursor position, update it."
12481 (interactive)
12482 (if (org-at-timestamp-p t)
12483 (org-timestamp-change 0 'calendar)
12484 (let ((cal-date (org-get-date-from-calendar)))
12485 (org-insert-time-stamp
12486 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
12488 (defun org-minutes-to-hh:mm-string (m)
12489 "Compute H:MM from a number of minutes."
12490 (let ((h (/ m 60)))
12491 (setq m (- m (* 60 h)))
12492 (format org-time-clocksum-format h m)))
12494 (defun org-hh:mm-string-to-minutes (s)
12495 "Convert a string H:MM to a number of minutes."
12496 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
12497 (+ (* (string-to-number (match-string 1 s)) 60)
12498 (string-to-number (match-string 2 s)))
12501 ;;;; Files
12503 (defun org-save-all-org-buffers ()
12504 "Save all Org-mode buffers without user confirmation."
12505 (interactive)
12506 (message "Saving all Org-mode buffers...")
12507 (save-some-buffers t 'org-mode-p)
12508 (when (featurep 'org-id) (org-id-locations-save))
12509 (message "Saving all Org-mode buffers... done"))
12511 (defun org-revert-all-org-buffers ()
12512 "Revert all Org-mode buffers.
12513 Prompt for confirmation when there are unsaved changes.
12514 Be sure you know what you are doing before letting this function
12515 overwrite your changes.
12517 This function is useful in a setup where one tracks org files
12518 with a version control system, to revert on one machine after pulling
12519 changes from another. I believe the procedure must be like this:
12521 1. M-x org-save-all-org-buffers
12522 2. Pull changes from the other machine, resolve conflicts
12523 3. M-x org-revert-all-org-buffers"
12524 (interactive)
12525 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
12526 (error "Abort"))
12527 (save-excursion
12528 (save-window-excursion
12529 (mapc
12530 (lambda (b)
12531 (when (and (with-current-buffer b (org-mode-p))
12532 (with-current-buffer b buffer-file-name))
12533 (switch-to-buffer b)
12534 (revert-buffer t 'no-confirm)))
12535 (buffer-list))
12536 (when (and (featurep 'org-id) org-id-track-globally)
12537 (org-id-locations-load)))))
12539 ;;;; Agenda files
12541 ;;;###autoload
12542 (defun org-iswitchb (&optional arg)
12543 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
12544 With a prefix argument, restrict available to files.
12545 With two prefix arguments, restrict available buffers to agenda files.
12547 Due to some yet unresolved reason, the global function
12548 `iswitchb-mode' needs to be active for this function to work."
12549 (interactive "P")
12550 (require 'iswitchb)
12551 (let ((enabled iswitchb-mode) blist)
12552 (or enabled (iswitchb-mode 1))
12553 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12554 ((equal arg '(16)) (org-buffer-list 'agenda))
12555 (t (org-buffer-list))))
12556 (unwind-protect
12557 (let ((iswitchb-make-buflist-hook
12558 (lambda ()
12559 (setq iswitchb-temp-buflist
12560 (mapcar 'buffer-name blist)))))
12561 (switch-to-buffer
12562 (iswitchb-read-buffer
12563 "Switch-to: " nil t))
12564 (or enabled (iswitchb-mode -1))))))
12566 ;;;###autoload
12567 (defun org-ido-switchb (&optional arg)
12568 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
12569 With a prefix argument, restrict available to files.
12570 With two prefix arguments, restrict available buffers to agenda files."
12571 (interactive "P")
12572 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12573 ((equal arg '(16)) (org-buffer-list 'agenda))
12574 (t (org-buffer-list)))))
12575 (switch-to-buffer
12576 (org-ido-completing-read "Org buffer: "
12577 (mapcar 'buffer-name blist)
12578 nil t))))
12580 (defun org-buffer-list (&optional predicate exclude-tmp)
12581 "Return a list of Org buffers.
12582 PREDICATE can be `export', `files' or `agenda'.
12584 export restrict the list to Export buffers.
12585 files restrict the list to buffers visiting Org files.
12586 agenda restrict the list to buffers visiting agenda files.
12588 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12589 (let* ((bfn nil)
12590 (agenda-files (and (eq predicate 'agenda)
12591 (mapcar 'file-truename (org-agenda-files t))))
12592 (filter
12593 (cond
12594 ((eq predicate 'files)
12595 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12596 ((eq predicate 'export)
12597 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12598 ((eq predicate 'agenda)
12599 (lambda (b)
12600 (with-current-buffer b
12601 (and (eq major-mode 'org-mode)
12602 (setq bfn (buffer-file-name b))
12603 (member (file-truename bfn) agenda-files)))))
12604 (t (lambda (b) (with-current-buffer b
12605 (or (eq major-mode 'org-mode)
12606 (string-match "\*Org .*Export"
12607 (buffer-name b)))))))))
12608 (delq nil
12609 (mapcar
12610 (lambda(b)
12611 (if (and (funcall filter b)
12612 (or (not exclude-tmp)
12613 (not (string-match "tmp" (buffer-name b)))))
12615 nil))
12616 (buffer-list)))))
12618 (defun org-agenda-files (&optional unrestricted archives)
12619 "Get the list of agenda files.
12620 Optional UNRESTRICTED means return the full list even if a restriction
12621 is currently in place.
12622 When ARCHIVES is t, include all archive files hat are really being
12623 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12624 `org-agenda-archives-mode' is t."
12625 (let ((files
12626 (cond
12627 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12628 ((stringp org-agenda-files) (org-read-agenda-file-list))
12629 ((listp org-agenda-files) org-agenda-files)
12630 (t (error "Invalid value of `org-agenda-files'")))))
12631 (setq files (apply 'append
12632 (mapcar (lambda (f)
12633 (if (file-directory-p f)
12634 (directory-files
12635 f t org-agenda-file-regexp)
12636 (list f)))
12637 files)))
12638 (when org-agenda-skip-unavailable-files
12639 (setq files (delq nil
12640 (mapcar (function
12641 (lambda (file)
12642 (and (file-readable-p file) file)))
12643 files))))
12644 (when (or (eq archives t)
12645 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12646 (setq files (org-add-archive-files files)))
12647 files))
12649 (defun org-edit-agenda-file-list ()
12650 "Edit the list of agenda files.
12651 Depending on setup, this either uses customize to edit the variable
12652 `org-agenda-files', or it visits the file that is holding the list. In the
12653 latter case, the buffer is set up in a way that saving it automatically kills
12654 the buffer and restores the previous window configuration."
12655 (interactive)
12656 (if (stringp org-agenda-files)
12657 (let ((cw (current-window-configuration)))
12658 (find-file org-agenda-files)
12659 (org-set-local 'org-window-configuration cw)
12660 (org-add-hook 'after-save-hook
12661 (lambda ()
12662 (set-window-configuration
12663 (prog1 org-window-configuration
12664 (kill-buffer (current-buffer))))
12665 (org-install-agenda-files-menu)
12666 (message "New agenda file list installed"))
12667 nil 'local)
12668 (message "%s" (substitute-command-keys
12669 "Edit list and finish with \\[save-buffer]")))
12670 (customize-variable 'org-agenda-files)))
12672 (defun org-store-new-agenda-file-list (list)
12673 "Set new value for the agenda file list and save it correctly."
12674 (if (stringp org-agenda-files)
12675 (let ((f org-agenda-files) b)
12676 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12677 (with-temp-file f
12678 (insert (mapconcat 'identity list "\n") "\n")))
12679 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12680 (setq org-agenda-files list)
12681 (customize-save-variable 'org-agenda-files org-agenda-files))))
12683 (defun org-read-agenda-file-list ()
12684 "Read the list of agenda files from a file."
12685 (when (file-directory-p org-agenda-files)
12686 (error "`org-agenda-files' cannot be a single directory"))
12687 (when (stringp org-agenda-files)
12688 (with-temp-buffer
12689 (insert-file-contents org-agenda-files)
12690 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12693 ;;;###autoload
12694 (defun org-cycle-agenda-files ()
12695 "Cycle through the files in `org-agenda-files'.
12696 If the current buffer visits an agenda file, find the next one in the list.
12697 If the current buffer does not, find the first agenda file."
12698 (interactive)
12699 (let* ((fs (org-agenda-files t))
12700 (files (append fs (list (car fs))))
12701 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12702 file)
12703 (unless files (error "No agenda files"))
12704 (catch 'exit
12705 (while (setq file (pop files))
12706 (if (equal (file-truename file) tcf)
12707 (when (car files)
12708 (find-file (car files))
12709 (throw 'exit t))))
12710 (find-file (car fs)))
12711 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12713 (defun org-agenda-file-to-front (&optional to-end)
12714 "Move/add the current file to the top of the agenda file list.
12715 If the file is not present in the list, it is added to the front. If it is
12716 present, it is moved there. With optional argument TO-END, add/move to the
12717 end of the list."
12718 (interactive "P")
12719 (let ((org-agenda-skip-unavailable-files nil)
12720 (file-alist (mapcar (lambda (x)
12721 (cons (file-truename x) x))
12722 (org-agenda-files t)))
12723 (ctf (file-truename buffer-file-name))
12724 x had)
12725 (setq x (assoc ctf file-alist) had x)
12727 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12728 (if to-end
12729 (setq file-alist (append (delq x file-alist) (list x)))
12730 (setq file-alist (cons x (delq x file-alist))))
12731 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12732 (org-install-agenda-files-menu)
12733 (message "File %s to %s of agenda file list"
12734 (if had "moved" "added") (if to-end "end" "front"))))
12736 (defun org-remove-file (&optional file)
12737 "Remove current file from the list of files in variable `org-agenda-files'.
12738 These are the files which are being checked for agenda entries.
12739 Optional argument FILE means, use this file instead of the current."
12740 (interactive)
12741 (let* ((org-agenda-skip-unavailable-files nil)
12742 (file (or file buffer-file-name))
12743 (true-file (file-truename file))
12744 (afile (abbreviate-file-name file))
12745 (files (delq nil (mapcar
12746 (lambda (x)
12747 (if (equal true-file
12748 (file-truename x))
12749 nil x))
12750 (org-agenda-files t)))))
12751 (if (not (= (length files) (length (org-agenda-files t))))
12752 (progn
12753 (org-store-new-agenda-file-list files)
12754 (org-install-agenda-files-menu)
12755 (message "Removed file: %s" afile))
12756 (message "File was not in list: %s (not removed)" afile))))
12758 (defun org-file-menu-entry (file)
12759 (vector file (list 'find-file file) t))
12761 (defun org-check-agenda-file (file)
12762 "Make sure FILE exists. If not, ask user what to do."
12763 (when (not (file-exists-p file))
12764 (message "non-existent file %s. [R]emove from list or [A]bort?"
12765 (abbreviate-file-name file))
12766 (let ((r (downcase (read-char-exclusive))))
12767 (cond
12768 ((equal r ?r)
12769 (org-remove-file file)
12770 (throw 'nextfile t))
12771 (t (error "Abort"))))))
12773 (defun org-get-agenda-file-buffer (file)
12774 "Get a buffer visiting FILE. If the buffer needs to be created, add
12775 it to the list of buffers which might be released later."
12776 (let ((buf (org-find-base-buffer-visiting file)))
12777 (if buf
12778 buf ; just return it
12779 ;; Make a new buffer and remember it
12780 (setq buf (find-file-noselect file))
12781 (if buf (push buf org-agenda-new-buffers))
12782 buf)))
12784 (defun org-release-buffers (blist)
12785 "Release all buffers in list, asking the user for confirmation when needed.
12786 When a buffer is unmodified, it is just killed. When modified, it is saved
12787 \(if the user agrees) and then killed."
12788 (let (buf file)
12789 (while (setq buf (pop blist))
12790 (setq file (buffer-file-name buf))
12791 (when (and (buffer-modified-p buf)
12792 file
12793 (y-or-n-p (format "Save file %s? " file)))
12794 (with-current-buffer buf (save-buffer)))
12795 (kill-buffer buf))))
12797 (defun org-prepare-agenda-buffers (files)
12798 "Create buffers for all agenda files, protect archived trees and comments."
12799 (interactive)
12800 (let ((pa '(:org-archived t))
12801 (pc '(:org-comment t))
12802 (pall '(:org-archived t :org-comment t))
12803 (inhibit-read-only t)
12804 (rea (concat ":" org-archive-tag ":"))
12805 bmp file re)
12806 (save-excursion
12807 (save-restriction
12808 (while (setq file (pop files))
12809 (if (bufferp file)
12810 (set-buffer file)
12811 (org-check-agenda-file file)
12812 (set-buffer (org-get-agenda-file-buffer file)))
12813 (widen)
12814 (setq bmp (buffer-modified-p))
12815 (org-refresh-category-properties)
12816 (setq org-todo-keywords-for-agenda
12817 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12818 (setq org-done-keywords-for-agenda
12819 (append org-done-keywords-for-agenda org-done-keywords))
12820 (setq org-todo-keyword-alist-for-agenda
12821 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12822 (setq org-tag-alist-for-agenda
12823 (append org-tag-alist-for-agenda org-tag-alist))
12825 (save-excursion
12826 (remove-text-properties (point-min) (point-max) pall)
12827 (when org-agenda-skip-archived-trees
12828 (goto-char (point-min))
12829 (while (re-search-forward rea nil t)
12830 (if (org-on-heading-p t)
12831 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12832 (goto-char (point-min))
12833 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12834 (while (re-search-forward re nil t)
12835 (add-text-properties
12836 (match-beginning 0) (org-end-of-subtree t) pc)))
12837 (set-buffer-modified-p bmp))))
12838 (setq org-todo-keyword-alist-for-agenda
12839 (org-uniquify org-todo-keyword-alist-for-agenda)
12840 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12842 ;;;; Embedded LaTeX
12844 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12845 "Keymap for the minor `org-cdlatex-mode'.")
12847 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12848 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12849 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12850 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12851 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12853 (defvar org-cdlatex-texmathp-advice-is-done nil
12854 "Flag remembering if we have applied the advice to texmathp already.")
12856 (define-minor-mode org-cdlatex-mode
12857 "Toggle the minor `org-cdlatex-mode'.
12858 This mode supports entering LaTeX environment and math in LaTeX fragments
12859 in Org-mode.
12860 \\{org-cdlatex-mode-map}"
12861 nil " OCDL" nil
12862 (when org-cdlatex-mode (require 'cdlatex))
12863 (unless org-cdlatex-texmathp-advice-is-done
12864 (setq org-cdlatex-texmathp-advice-is-done t)
12865 (defadvice texmathp (around org-math-always-on activate)
12866 "Always return t in org-mode buffers.
12867 This is because we want to insert math symbols without dollars even outside
12868 the LaTeX math segments. If Orgmode thinks that point is actually inside
12869 an embedded LaTeX fragment, let texmathp do its job.
12870 \\[org-cdlatex-mode-map]"
12871 (interactive)
12872 (let (p)
12873 (cond
12874 ((not (org-mode-p)) ad-do-it)
12875 ((eq this-command 'cdlatex-math-symbol)
12876 (setq ad-return-value t
12877 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12879 (let ((p (org-inside-LaTeX-fragment-p)))
12880 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12881 (setq ad-return-value t
12882 texmathp-why '("Org-mode embedded math" . 0))
12883 (if p ad-do-it)))))))))
12885 (defun turn-on-org-cdlatex ()
12886 "Unconditionally turn on `org-cdlatex-mode'."
12887 (org-cdlatex-mode 1))
12889 (defun org-inside-LaTeX-fragment-p ()
12890 "Test if point is inside a LaTeX fragment.
12891 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12892 sequence appearing also before point.
12893 Even though the matchers for math are configurable, this function assumes
12894 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12895 delimiters are skipped when they have been removed by customization.
12896 The return value is nil, or a cons cell with the delimiter and
12897 and the position of this delimiter.
12899 This function does a reasonably good job, but can locally be fooled by
12900 for example currency specifications. For example it will assume being in
12901 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12902 fragments that are properly closed, but during editing, we have to live
12903 with the uncertainty caused by missing closing delimiters. This function
12904 looks only before point, not after."
12905 (catch 'exit
12906 (let ((pos (point))
12907 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12908 (lim (progn
12909 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12910 (point)))
12911 dd-on str (start 0) m re)
12912 (goto-char pos)
12913 (when dodollar
12914 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12915 re (nth 1 (assoc "$" org-latex-regexps)))
12916 (while (string-match re str start)
12917 (cond
12918 ((= (match-end 0) (length str))
12919 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12920 ((= (match-end 0) (- (length str) 5))
12921 (throw 'exit nil))
12922 (t (setq start (match-end 0))))))
12923 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12924 (goto-char pos)
12925 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12926 (and (match-beginning 2) (throw 'exit nil))
12927 ;; count $$
12928 (while (re-search-backward "\\$\\$" lim t)
12929 (setq dd-on (not dd-on)))
12930 (goto-char pos)
12931 (if dd-on (cons "$$" m))))))
12934 (defun org-try-cdlatex-tab ()
12935 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12936 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12937 - inside a LaTeX fragment, or
12938 - after the first word in a line, where an abbreviation expansion could
12939 insert a LaTeX environment."
12940 (when org-cdlatex-mode
12941 (cond
12942 ((save-excursion
12943 (skip-chars-backward "a-zA-Z0-9*")
12944 (skip-chars-backward " \t")
12945 (bolp))
12946 (cdlatex-tab) t)
12947 ((org-inside-LaTeX-fragment-p)
12948 (cdlatex-tab) t)
12949 (t nil))))
12951 (defun org-cdlatex-underscore-caret (&optional arg)
12952 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12953 Revert to the normal definition outside of these fragments."
12954 (interactive "P")
12955 (if (org-inside-LaTeX-fragment-p)
12956 (call-interactively 'cdlatex-sub-superscript)
12957 (let (org-cdlatex-mode)
12958 (call-interactively (key-binding (vector last-input-event))))))
12960 (defun org-cdlatex-math-modify (&optional arg)
12961 "Execute `cdlatex-math-modify' in LaTeX fragments.
12962 Revert to the normal definition outside of these fragments."
12963 (interactive "P")
12964 (if (org-inside-LaTeX-fragment-p)
12965 (call-interactively 'cdlatex-math-modify)
12966 (let (org-cdlatex-mode)
12967 (call-interactively (key-binding (vector last-input-event))))))
12969 (defvar org-latex-fragment-image-overlays nil
12970 "List of overlays carrying the images of latex fragments.")
12971 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12973 (defun org-remove-latex-fragment-image-overlays ()
12974 "Remove all overlays with LaTeX fragment images in current buffer."
12975 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12976 (setq org-latex-fragment-image-overlays nil))
12978 (defun org-preview-latex-fragment (&optional subtree)
12979 "Preview the LaTeX fragment at point, or all locally or globally.
12980 If the cursor is in a LaTeX fragment, create the image and overlay
12981 it over the source code. If there is no fragment at point, display
12982 all fragments in the current text, from one headline to the next. With
12983 prefix SUBTREE, display all fragments in the current subtree. With a
12984 double prefix `C-u C-u', or when the cursor is before the first headline,
12985 display all fragments in the buffer.
12986 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12987 (interactive "P")
12988 (org-remove-latex-fragment-image-overlays)
12989 (save-excursion
12990 (save-restriction
12991 (let (beg end at msg)
12992 (cond
12993 ((or (equal subtree '(16))
12994 (not (save-excursion
12995 (re-search-backward (concat "^" outline-regexp) nil t))))
12996 (setq beg (point-min) end (point-max)
12997 msg "Creating images for buffer...%s"))
12998 ((equal subtree '(4))
12999 (org-back-to-heading)
13000 (setq beg (point) end (org-end-of-subtree t)
13001 msg "Creating images for subtree...%s"))
13003 (if (setq at (org-inside-LaTeX-fragment-p))
13004 (goto-char (max (point-min) (- (cdr at) 2)))
13005 (org-back-to-heading))
13006 (setq beg (point) end (progn (outline-next-heading) (point))
13007 msg (if at "Creating image...%s"
13008 "Creating images for entry...%s"))))
13009 (message msg "")
13010 (narrow-to-region beg end)
13011 (goto-char beg)
13012 (org-format-latex
13013 (concat "ltxpng/" (file-name-sans-extension
13014 (file-name-nondirectory
13015 buffer-file-name)))
13016 default-directory 'overlays msg at 'forbuffer)
13017 (message msg "done. Use `C-c C-c' to remove images.")))))
13019 (defvar org-latex-regexps
13020 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
13021 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
13022 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
13023 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13024 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13025 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
13026 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
13027 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
13028 "Regular expressions for matching embedded LaTeX.")
13030 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
13031 "Replace LaTeX fragments with links to an image, and produce images."
13032 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
13033 (let* ((prefixnodir (file-name-nondirectory prefix))
13034 (absprefix (expand-file-name prefix dir))
13035 (todir (file-name-directory absprefix))
13036 (opt org-format-latex-options)
13037 (matchers (plist-get opt :matchers))
13038 (re-list org-latex-regexps)
13039 (cnt 0) txt link beg end re e checkdir
13040 m n block linkfile movefile ov)
13041 ;; Check if there are old images files with this prefix, and remove them
13042 (when (file-directory-p todir)
13043 (mapc 'delete-file
13044 (directory-files
13045 todir 'full
13046 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
13047 ;; Check the different regular expressions
13048 (while (setq e (pop re-list))
13049 (setq m (car e) re (nth 1 e) n (nth 2 e)
13050 block (if (nth 3 e) "\n\n" ""))
13051 (when (member m matchers)
13052 (goto-char (point-min))
13053 (while (re-search-forward re nil t)
13054 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
13055 (not (get-text-property (match-beginning n)
13056 'org-protected)))
13057 (setq txt (match-string n)
13058 beg (match-beginning n) end (match-end n)
13059 cnt (1+ cnt)
13060 linkfile (format "%s_%04d.png" prefix cnt)
13061 movefile (format "%s_%04d.png" absprefix cnt)
13062 link (concat block "[[file:" linkfile "]]" block))
13063 (if msg (message msg cnt))
13064 (goto-char beg)
13065 (unless checkdir ; make sure the directory exists
13066 (setq checkdir t)
13067 (or (file-directory-p todir) (make-directory todir)))
13068 (org-create-formula-image
13069 txt movefile opt forbuffer)
13070 (if overlays
13071 (progn
13072 (setq ov (org-make-overlay beg end))
13073 (if (featurep 'xemacs)
13074 (progn
13075 (org-overlay-put ov 'invisible t)
13076 (org-overlay-put
13077 ov 'end-glyph
13078 (make-glyph (vector 'png :file movefile))))
13079 (org-overlay-put
13080 ov 'display
13081 (list 'image :type 'png :file movefile :ascent 'center)))
13082 (push ov org-latex-fragment-image-overlays)
13083 (goto-char end))
13084 (delete-region beg end)
13085 (insert link))))))))
13087 ;; This function borrows from Ganesh Swami's latex2png.el
13088 (defun org-create-formula-image (string tofile options buffer)
13089 (let* ((tmpdir (if (featurep 'xemacs)
13090 (temp-directory)
13091 temporary-file-directory))
13092 (texfilebase (make-temp-name
13093 (expand-file-name "orgtex" tmpdir)))
13094 (texfile (concat texfilebase ".tex"))
13095 (dvifile (concat texfilebase ".dvi"))
13096 (pngfile (concat texfilebase ".png"))
13097 (fnh (if (featurep 'xemacs)
13098 (font-height (get-face-font 'default))
13099 (face-attribute 'default :height nil)))
13100 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
13101 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
13102 (fg (or (plist-get options (if buffer :foreground :html-foreground))
13103 "Black"))
13104 (bg (or (plist-get options (if buffer :background :html-background))
13105 "Transparent")))
13106 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
13107 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
13108 (with-temp-file texfile
13109 (insert org-format-latex-header
13110 "\n\\begin{document}\n" string "\n\\end{document}\n"))
13111 (let ((dir default-directory))
13112 (condition-case nil
13113 (progn
13114 (cd tmpdir)
13115 (call-process "latex" nil nil nil texfile))
13116 (error nil))
13117 (cd dir))
13118 (if (not (file-exists-p dvifile))
13119 (progn (message "Failed to create dvi file from %s" texfile) nil)
13120 (condition-case nil
13121 (call-process "dvipng" nil nil nil
13122 "-E" "-fg" fg "-bg" bg
13123 "-D" dpi
13124 ;;"-x" scale "-y" scale
13125 "-T" "tight"
13126 "-o" pngfile
13127 dvifile)
13128 (error nil))
13129 (if (not (file-exists-p pngfile))
13130 (progn (message "Failed to create png file from %s" texfile) nil)
13131 ;; Use the requested file name and clean up
13132 (copy-file pngfile tofile 'replace)
13133 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
13134 (delete-file (concat texfilebase e)))
13135 pngfile))))
13137 (defun org-dvipng-color (attr)
13138 "Return an rgb color specification for dvipng."
13139 (apply 'format "rgb %s %s %s"
13140 (mapcar 'org-normalize-color
13141 (color-values (face-attribute 'default attr nil)))))
13143 (defun org-normalize-color (value)
13144 "Return string to be used as color value for an RGB component."
13145 (format "%g" (/ value 65535.0)))
13147 ;;;; Key bindings
13149 ;; Make `C-c C-x' a prefix key
13150 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
13152 ;; TAB key with modifiers
13153 (org-defkey org-mode-map "\C-i" 'org-cycle)
13154 (org-defkey org-mode-map [(tab)] 'org-cycle)
13155 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
13156 (org-defkey org-mode-map [(meta tab)] 'org-complete)
13157 (org-defkey org-mode-map "\M-\t" 'org-complete)
13158 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
13159 ;; The following line is necessary under Suse GNU/Linux
13160 (unless (featurep 'xemacs)
13161 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
13162 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
13163 (define-key org-mode-map [backtab] 'org-shifttab)
13165 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
13166 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
13167 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
13169 ;; Cursor keys with modifiers
13170 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
13171 (org-defkey org-mode-map [(meta right)] 'org-metaright)
13172 (org-defkey org-mode-map [(meta up)] 'org-metaup)
13173 (org-defkey org-mode-map [(meta down)] 'org-metadown)
13175 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
13176 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
13177 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
13178 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
13180 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
13181 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
13182 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
13183 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
13185 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
13186 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
13188 ;;; Extra keys for tty access.
13189 ;; We only set them when really needed because otherwise the
13190 ;; menus don't show the simple keys
13192 (when (or org-use-extra-keys
13193 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
13194 (not window-system))
13195 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
13196 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
13197 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
13198 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
13199 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
13200 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
13201 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
13202 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
13203 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
13204 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
13205 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
13206 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
13207 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
13208 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
13209 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
13210 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
13211 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
13212 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
13213 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
13214 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
13215 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
13216 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
13218 ;; All the other keys
13220 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
13221 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
13222 (if (boundp 'narrow-map)
13223 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
13224 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
13225 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
13226 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
13227 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
13228 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
13229 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
13230 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
13231 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
13232 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
13233 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
13234 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
13235 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
13236 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
13237 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
13238 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
13239 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
13240 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
13241 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
13242 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
13243 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
13244 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
13245 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
13246 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
13247 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
13248 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
13249 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
13250 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
13251 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
13252 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
13253 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
13254 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
13255 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
13256 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
13257 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
13258 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
13259 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
13260 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
13261 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
13262 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
13263 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13264 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
13265 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
13266 (org-defkey org-mode-map "\C-c^" 'org-sort)
13267 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
13268 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
13269 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
13270 (org-defkey org-mode-map "\C-m" 'org-return)
13271 (org-defkey org-mode-map "\C-j" 'org-return-indent)
13272 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
13273 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
13274 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
13275 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
13276 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
13277 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
13278 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
13279 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
13280 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
13281 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
13282 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
13283 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
13284 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
13285 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
13286 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
13287 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
13289 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
13290 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
13291 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
13292 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
13294 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
13295 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
13296 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
13297 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
13298 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
13299 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
13300 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
13301 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
13302 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
13303 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
13304 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
13305 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
13306 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
13308 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
13309 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
13310 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
13311 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
13313 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
13315 (define-key org-mode-map "\C-c\C-xr" 'org-reload)
13317 (when (featurep 'xemacs)
13318 (org-defkey org-mode-map 'button3 'popup-mode-menu))
13321 (defvar org-self-insert-command-undo-counter 0)
13323 (defvar org-table-auto-blank-field) ; defined in org-table.el
13324 (defun org-self-insert-command (N)
13325 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13326 If the cursor is in a table looking at whitespace, the whitespace is
13327 overwritten, and the table is not marked as requiring realignment."
13328 (interactive "p")
13329 (if (and
13330 (org-table-p)
13331 (progn
13332 ;; check if we blank the field, and if that triggers align
13333 (and (featurep 'org-table) org-table-auto-blank-field
13334 (member last-command
13335 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
13336 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
13337 ;; got extra space, this field does not determine column width
13338 (let (org-table-may-need-update) (org-table-blank-field))
13339 ;; no extra space, this field may determine column width
13340 (org-table-blank-field)))
13342 (eq N 1)
13343 (looking-at "[^|\n]* |"))
13344 (let (org-table-may-need-update)
13345 (goto-char (1- (match-end 0)))
13346 (delete-backward-char 1)
13347 (goto-char (match-beginning 0))
13348 (self-insert-command N))
13349 (setq org-table-may-need-update t)
13350 (self-insert-command N)
13351 (org-fix-tags-on-the-fly)
13352 (if org-self-insert-cluster-for-undo
13353 (if (not (eq last-command 'org-self-insert-command))
13354 (setq org-self-insert-command-undo-counter 1)
13355 (if (>= org-self-insert-command-undo-counter 20)
13356 (setq org-self-insert-command-undo-counter 1)
13357 (and (> org-self-insert-command-undo-counter 0)
13358 buffer-undo-list
13359 (not (cadr buffer-undo-list)) ; remove nil entry
13360 (setcdr buffer-undo-list (cddr buffer-undo-list)))
13361 (setq org-self-insert-command-undo-counter
13362 (1+ org-self-insert-command-undo-counter)))))))
13364 (defun org-fix-tags-on-the-fly ()
13365 (when (and (equal (char-after (point-at-bol)) ?*)
13366 (org-on-heading-p))
13367 (org-align-tags-here org-tags-column)))
13369 (defun org-delete-backward-char (N)
13370 "Like `delete-backward-char', insert whitespace at field end in tables.
13371 When deleting backwards, in tables this function will insert whitespace in
13372 front of the next \"|\" separator, to keep the table aligned. The table will
13373 still be marked for re-alignment if the field did fill the entire column,
13374 because, in this case the deletion might narrow the column."
13375 (interactive "p")
13376 (if (and (org-table-p)
13377 (eq N 1)
13378 (string-match "|" (buffer-substring (point-at-bol) (point)))
13379 (looking-at ".*?|"))
13380 (let ((pos (point))
13381 (noalign (looking-at "[^|\n\r]* |"))
13382 (c org-table-may-need-update))
13383 (backward-delete-char N)
13384 (skip-chars-forward "^|")
13385 (insert " ")
13386 (goto-char (1- pos))
13387 ;; noalign: if there were two spaces at the end, this field
13388 ;; does not determine the width of the column.
13389 (if noalign (setq org-table-may-need-update c)))
13390 (backward-delete-char N)
13391 (org-fix-tags-on-the-fly)))
13393 (defun org-delete-char (N)
13394 "Like `delete-char', but insert whitespace at field end in tables.
13395 When deleting characters, in tables this function will insert whitespace in
13396 front of the next \"|\" separator, to keep the table aligned. The table will
13397 still be marked for re-alignment if the field did fill the entire column,
13398 because, in this case the deletion might narrow the column."
13399 (interactive "p")
13400 (if (and (org-table-p)
13401 (not (bolp))
13402 (not (= (char-after) ?|))
13403 (eq N 1))
13404 (if (looking-at ".*?|")
13405 (let ((pos (point))
13406 (noalign (looking-at "[^|\n\r]* |"))
13407 (c org-table-may-need-update))
13408 (replace-match (concat
13409 (substring (match-string 0) 1 -1)
13410 " |"))
13411 (goto-char pos)
13412 ;; noalign: if there were two spaces at the end, this field
13413 ;; does not determine the width of the column.
13414 (if noalign (setq org-table-may-need-update c)))
13415 (delete-char N))
13416 (delete-char N)
13417 (org-fix-tags-on-the-fly)))
13419 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
13420 (put 'org-self-insert-command 'delete-selection t)
13421 (put 'orgtbl-self-insert-command 'delete-selection t)
13422 (put 'org-delete-char 'delete-selection 'supersede)
13423 (put 'org-delete-backward-char 'delete-selection 'supersede)
13424 (put 'org-yank 'delete-selection 'yank)
13426 ;; Make `flyspell-mode' delay after some commands
13427 (put 'org-self-insert-command 'flyspell-delayed t)
13428 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
13429 (put 'org-delete-char 'flyspell-delayed t)
13430 (put 'org-delete-backward-char 'flyspell-delayed t)
13432 ;; Make pabbrev-mode expand after org-mode commands
13433 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
13434 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
13436 ;; How to do this: Measure non-white length of current string
13437 ;; If equal to column width, we should realign.
13439 (defun org-remap (map &rest commands)
13440 "In MAP, remap the functions given in COMMANDS.
13441 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
13442 (let (new old)
13443 (while commands
13444 (setq old (pop commands) new (pop commands))
13445 (if (fboundp 'command-remapping)
13446 (org-defkey map (vector 'remap old) new)
13447 (substitute-key-definition old new map global-map)))))
13449 (when (eq org-enable-table-editor 'optimized)
13450 ;; If the user wants maximum table support, we need to hijack
13451 ;; some standard editing functions
13452 (org-remap org-mode-map
13453 'self-insert-command 'org-self-insert-command
13454 'delete-char 'org-delete-char
13455 'delete-backward-char 'org-delete-backward-char)
13456 (org-defkey org-mode-map "|" 'org-force-self-insert))
13458 (defvar org-ctrl-c-ctrl-c-hook nil
13459 "Hook for functions attaching themselves to `C-c C-c'.
13460 This can be used to add additional functionality to the C-c C-c key which
13461 executes context-dependent commands.
13462 Each function will be called with no arguments. The function must check
13463 if the context is appropriate for it to act. If yes, it should do its
13464 thing and then return a non-nil value. If the context is wrong,
13465 just do nothing.")
13467 (defvar org-metaleft-hook nil
13468 "Hook for functions attaching themselves to `M-left'.
13469 See `org-ctrl-c-ctrl-c-hook' for more information.")
13470 (defvar org-metaright-hook nil
13471 "Hook for functions attaching themselves to `M-right'.
13472 See `org-ctrl-c-ctrl-c-hook' for more information.")
13473 (defvar org-metaup-hook nil
13474 "Hook for functions attaching themselves to `M-up'.
13475 See `org-ctrl-c-ctrl-c-hook' for more information.")
13476 (defvar org-metadown-hook nil
13477 "Hook for functions attaching themselves to `M-down'.
13478 See `org-ctrl-c-ctrl-c-hook' for more information.")
13479 (defvar org-shiftmetaleft-hook nil
13480 "Hook for functions attaching themselves to `M-S-left'.
13481 See `org-ctrl-c-ctrl-c-hook' for more information.")
13482 (defvar org-shiftmetaright-hook nil
13483 "Hook for functions attaching themselves to `M-S-right'.
13484 See `org-ctrl-c-ctrl-c-hook' for more information.")
13485 (defvar org-shiftmetaup-hook nil
13486 "Hook for functions attaching themselves to `M-S-up'.
13487 See `org-ctrl-c-ctrl-c-hook' for more information.")
13488 (defvar org-shiftmetadown-hook nil
13489 "Hook for functions attaching themselves to `M-S-down'.
13490 See `org-ctrl-c-ctrl-c-hook' for more information.")
13491 (defvar org-metareturn-hook nil
13492 "Hook for functions attaching themselves to `M-RET'.
13493 See `org-ctrl-c-ctrl-c-hook' for more information.")
13495 (defun org-modifier-cursor-error ()
13496 "Throw an error, a modified cursor command was applied in wrong context."
13497 (error "This command is active in special context like tables, headlines or items"))
13499 (defun org-shiftselect-error ()
13500 "Throw an error because Shift-Cursor command was applied in wrong context."
13501 (if (and (boundp 'shift-select-mode) shift-select-mode)
13502 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
13503 (error "This command works only in special context like headlines or timestamps.")))
13505 (defun org-call-for-shift-select (cmd)
13506 (let ((this-command-keys-shift-translated t))
13507 (call-interactively cmd)))
13509 (defun org-shifttab (&optional arg)
13510 "Global visibility cycling or move to previous table field.
13511 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
13512 on context.
13513 See the individual commands for more information."
13514 (interactive "P")
13515 (cond
13516 ((org-at-table-p) (call-interactively 'org-table-previous-field))
13517 ((integerp arg)
13518 (message "Content view to level: %d" arg)
13519 (org-content (prefix-numeric-value arg))
13520 (setq org-cycle-global-status 'overview))
13521 (t (call-interactively 'org-global-cycle))))
13523 (defun org-shiftmetaleft ()
13524 "Promote subtree or delete table column.
13525 Calls `org-promote-subtree', `org-outdent-item',
13526 or `org-table-delete-column', depending on context.
13527 See the individual commands for more information."
13528 (interactive)
13529 (cond
13530 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
13531 ((org-at-table-p) (call-interactively 'org-table-delete-column))
13532 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
13533 ((org-at-item-p) (call-interactively 'org-outdent-item))
13534 (t (org-modifier-cursor-error))))
13536 (defun org-shiftmetaright ()
13537 "Demote subtree or insert table column.
13538 Calls `org-demote-subtree', `org-indent-item',
13539 or `org-table-insert-column', depending on context.
13540 See the individual commands for more information."
13541 (interactive)
13542 (cond
13543 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
13544 ((org-at-table-p) (call-interactively 'org-table-insert-column))
13545 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
13546 ((org-at-item-p) (call-interactively 'org-indent-item))
13547 (t (org-modifier-cursor-error))))
13549 (defun org-shiftmetaup (&optional arg)
13550 "Move subtree up or kill table row.
13551 Calls `org-move-subtree-up' or `org-table-kill-row' or
13552 `org-move-item-up' depending on context. See the individual commands
13553 for more information."
13554 (interactive "P")
13555 (cond
13556 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
13557 ((org-at-table-p) (call-interactively 'org-table-kill-row))
13558 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13559 ((org-at-item-p) (call-interactively 'org-move-item-up))
13560 (t (org-modifier-cursor-error))))
13562 (defun org-shiftmetadown (&optional arg)
13563 "Move subtree down or insert table row.
13564 Calls `org-move-subtree-down' or `org-table-insert-row' or
13565 `org-move-item-down', depending on context. See the individual
13566 commands for more information."
13567 (interactive "P")
13568 (cond
13569 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
13570 ((org-at-table-p) (call-interactively 'org-table-insert-row))
13571 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13572 ((org-at-item-p) (call-interactively 'org-move-item-down))
13573 (t (org-modifier-cursor-error))))
13575 (defun org-metaleft (&optional arg)
13576 "Promote heading or move table column to left.
13577 Calls `org-do-promote' or `org-table-move-column', depending on context.
13578 With no specific context, calls the Emacs default `backward-word'.
13579 See the individual commands for more information."
13580 (interactive "P")
13581 (cond
13582 ((run-hook-with-args-until-success 'org-metaleft-hook))
13583 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
13584 ((or (org-on-heading-p)
13585 (and (org-region-active-p)
13586 (save-excursion
13587 (goto-char (region-beginning))
13588 (org-on-heading-p))))
13589 (call-interactively 'org-do-promote))
13590 ((or (org-at-item-p)
13591 (and (org-region-active-p)
13592 (save-excursion
13593 (goto-char (region-beginning))
13594 (org-at-item-p))))
13595 (call-interactively 'org-outdent-item))
13596 (t (call-interactively 'backward-word))))
13598 (defun org-metaright (&optional arg)
13599 "Demote subtree or move table column to right.
13600 Calls `org-do-demote' or `org-table-move-column', depending on context.
13601 With no specific context, calls the Emacs default `forward-word'.
13602 See the individual commands for more information."
13603 (interactive "P")
13604 (cond
13605 ((run-hook-with-args-until-success 'org-metaright-hook))
13606 ((org-at-table-p) (call-interactively 'org-table-move-column))
13607 ((or (org-on-heading-p)
13608 (and (org-region-active-p)
13609 (save-excursion
13610 (goto-char (region-beginning))
13611 (org-on-heading-p))))
13612 (call-interactively 'org-do-demote))
13613 ((or (org-at-item-p)
13614 (and (org-region-active-p)
13615 (save-excursion
13616 (goto-char (region-beginning))
13617 (org-at-item-p))))
13618 (call-interactively 'org-indent-item))
13619 (t (call-interactively 'forward-word))))
13621 (defun org-metaup (&optional arg)
13622 "Move subtree up or move table row up.
13623 Calls `org-move-subtree-up' or `org-table-move-row' or
13624 `org-move-item-up', depending on context. See the individual commands
13625 for more information."
13626 (interactive "P")
13627 (cond
13628 ((run-hook-with-args-until-success 'org-metaup-hook))
13629 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
13630 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13631 ((org-at-item-p) (call-interactively 'org-move-item-up))
13632 (t (transpose-lines 1) (beginning-of-line -1))))
13634 (defun org-metadown (&optional arg)
13635 "Move subtree down or move table row down.
13636 Calls `org-move-subtree-down' or `org-table-move-row' or
13637 `org-move-item-down', depending on context. See the individual
13638 commands for more information."
13639 (interactive "P")
13640 (cond
13641 ((run-hook-with-args-until-success 'org-metadown-hook))
13642 ((org-at-table-p) (call-interactively 'org-table-move-row))
13643 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13644 ((org-at-item-p) (call-interactively 'org-move-item-down))
13645 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
13647 (defun org-shiftup (&optional arg)
13648 "Increase item in timestamp or increase priority of current headline.
13649 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
13650 depending on context. See the individual commands for more information."
13651 (interactive "P")
13652 (cond
13653 ((and org-support-shift-select (org-region-active-p))
13654 (org-call-for-shift-select 'previous-line))
13655 ((org-at-timestamp-p t)
13656 (call-interactively (if org-edit-timestamp-down-means-later
13657 'org-timestamp-down 'org-timestamp-up)))
13658 ((and (not (eq org-support-shift-select 'always))
13659 (org-on-heading-p))
13660 (call-interactively 'org-priority-up))
13661 ((and (not org-support-shift-select) (org-at-item-p))
13662 (call-interactively 'org-previous-item))
13663 ((org-clocktable-try-shift 'up arg))
13664 (org-support-shift-select
13665 (org-call-for-shift-select 'previous-line))
13666 (t (org-shiftselect-error))))
13668 (defun org-shiftdown (&optional arg)
13669 "Decrease item in timestamp or decrease priority of current headline.
13670 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
13671 depending on context. See the individual commands for more information."
13672 (interactive "P")
13673 (cond
13674 ((and org-support-shift-select (org-region-active-p))
13675 (org-call-for-shift-select 'next-line))
13676 ((org-at-timestamp-p t)
13677 (call-interactively (if org-edit-timestamp-down-means-later
13678 'org-timestamp-up 'org-timestamp-down)))
13679 ((and (not (eq org-support-shift-select 'always))
13680 (org-on-heading-p))
13681 (call-interactively 'org-priority-down))
13682 ((and (not org-support-shift-select) (org-at-item-p))
13683 (call-interactively 'org-next-item))
13684 ((org-clocktable-try-shift 'down arg))
13685 (org-support-shift-select
13686 (org-call-for-shift-select 'next-line))
13687 (t (org-shiftselect-error))))
13689 (defun org-shiftright (&optional arg)
13690 "Cycle the thing at point or in the current line, depending on context.
13691 Depending on context, this does one of the following:
13693 - switch a timestamp at point one day into the future
13694 - on a headline, switch to the next TODO keyword.
13695 - on an item, switch entire list to the next bullet type
13696 - on a property line, switch to the next allowed value
13697 - on a clocktable definition line, move time block into the future"
13698 (interactive "P")
13699 (cond
13700 ((and org-support-shift-select (org-region-active-p))
13701 (org-call-for-shift-select 'forward-char))
13702 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
13703 ((and (not (eq org-support-shift-select 'always))
13704 (org-on-heading-p))
13705 (org-call-with-arg 'org-todo 'right))
13706 ((or (and org-support-shift-select
13707 (not (eq org-support-shift-select 'always))
13708 (org-at-item-bullet-p))
13709 (and (not org-support-shift-select) (org-at-item-p)))
13710 (org-call-with-arg 'org-cycle-list-bullet nil))
13711 ((and (not (eq org-support-shift-select 'always))
13712 (org-at-property-p))
13713 (call-interactively 'org-property-next-allowed-value))
13714 ((org-clocktable-try-shift 'right arg))
13715 (org-support-shift-select
13716 (org-call-for-shift-select 'forward-char))
13717 (t (org-shiftselect-error))))
13719 (defun org-shiftleft (&optional arg)
13720 "Cycle the thing at point or in the current line, depending on context.
13721 Depending on context, this does one of the following:
13723 - switch a timestamp at point one day into the past
13724 - on a headline, switch to the previous TODO keyword.
13725 - on an item, switch entire list to the previous bullet type
13726 - on a property line, switch to the previous allowed value
13727 - on a clocktable definition line, move time block into the past"
13728 (interactive "P")
13729 (cond
13730 ((and org-support-shift-select (org-region-active-p))
13731 (org-call-for-shift-select 'backward-char))
13732 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
13733 ((and (not (eq org-support-shift-select 'always))
13734 (org-on-heading-p))
13735 (org-call-with-arg 'org-todo 'left))
13736 ((or (and org-support-shift-select
13737 (not (eq org-support-shift-select 'always))
13738 (org-at-item-bullet-p))
13739 (and (not org-support-shift-select) (org-at-item-p)))
13740 (org-call-with-arg 'org-cycle-list-bullet 'previous))
13741 ((and (not (eq org-support-shift-select 'always))
13742 (org-at-property-p))
13743 (call-interactively 'org-property-previous-allowed-value))
13744 ((org-clocktable-try-shift 'left arg))
13745 (org-support-shift-select
13746 (org-call-for-shift-select 'backward-char))
13747 (t (org-shiftselect-error))))
13749 (defun org-shiftcontrolright ()
13750 "Switch to next TODO set."
13751 (interactive)
13752 (cond
13753 ((and org-support-shift-select (org-region-active-p))
13754 (org-call-for-shift-select 'forward-word))
13755 ((and (not (eq org-support-shift-select 'always))
13756 (org-on-heading-p))
13757 (org-call-with-arg 'org-todo 'nextset))
13758 (org-support-shift-select
13759 (org-call-for-shift-select 'forward-word))
13760 (t (org-shiftselect-error))))
13762 (defun org-shiftcontrolleft ()
13763 "Switch to previous TODO set."
13764 (interactive)
13765 (cond
13766 ((and org-support-shift-select (org-region-active-p))
13767 (org-call-for-shift-select 'backward-word))
13768 ((and (not (eq org-support-shift-select 'always))
13769 (org-on-heading-p))
13770 (org-call-with-arg 'org-todo 'previousset))
13771 (org-support-shift-select
13772 (org-call-for-shift-select 'backward-word))
13773 (t (org-shiftselect-error))))
13775 (defun org-ctrl-c-ret ()
13776 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
13777 (interactive)
13778 (cond
13779 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
13780 (t (call-interactively 'org-insert-heading))))
13782 (defun org-copy-special ()
13783 "Copy region in table or copy current subtree.
13784 Calls `org-table-copy' or `org-copy-subtree', depending on context.
13785 See the individual commands for more information."
13786 (interactive)
13787 (call-interactively
13788 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
13790 (defun org-cut-special ()
13791 "Cut region in table or cut current subtree.
13792 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13793 See the individual commands for more information."
13794 (interactive)
13795 (call-interactively
13796 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13798 (defun org-paste-special (arg)
13799 "Paste rectangular region into table, or past subtree relative to level.
13800 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13801 See the individual commands for more information."
13802 (interactive "P")
13803 (if (org-at-table-p)
13804 (org-table-paste-rectangle)
13805 (org-paste-subtree arg)))
13807 (defun org-edit-special ()
13808 "Call a special editor for the stuff at point.
13809 When at a table, call the formula editor with `org-table-edit-formulas'.
13810 When at the first line of an src example, call `org-edit-src-code'.
13811 When in an #+include line, visit the include file. Otherwise call
13812 `ffap' to visit the file at point."
13813 (interactive)
13814 (cond
13815 ((org-at-table-p)
13816 (call-interactively 'org-table-edit-formulas))
13817 ((save-excursion
13818 (beginning-of-line 1)
13819 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
13820 (find-file (org-trim (match-string 1))))
13821 ((org-edit-src-code))
13822 ((org-edit-fixed-width-region))
13823 (t (call-interactively 'ffap))))
13826 (defun org-ctrl-c-ctrl-c (&optional arg)
13827 "Set tags in headline, or update according to changed information at point.
13829 This command does many different things, depending on context:
13831 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
13832 this is what we do.
13834 - If the cursor is in a headline, prompt for tags and insert them
13835 into the current line, aligned to `org-tags-column'. When called
13836 with prefix arg, realign all tags in the current buffer.
13838 - If the cursor is in one of the special #+KEYWORD lines, this
13839 triggers scanning the buffer for these lines and updating the
13840 information.
13842 - If the cursor is inside a table, realign the table. This command
13843 works even if the automatic table editor has been turned off.
13845 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13846 the entire table.
13848 - If the cursor is at a footnote reference or definition, jump to
13849 the corresponding definition or references, respectively.
13851 - If the cursor is a the beginning of a dynamic block, update it.
13853 - If the cursor is inside a table created by the table.el package,
13854 activate that table.
13856 - If the current buffer is a remember buffer, close note and file
13857 it. A prefix argument of 1 files to the default location
13858 without further interaction. A prefix argument of 2 files to
13859 the currently clocking task.
13861 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13862 links in this buffer.
13864 - If the cursor is on a numbered item in a plain list, renumber the
13865 ordered list.
13867 - If the cursor is on a checkbox, toggle it."
13868 (interactive "P")
13869 (let ((org-enable-table-editor t))
13870 (cond
13871 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
13872 org-occur-highlights
13873 org-latex-fragment-image-overlays)
13874 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
13875 (org-remove-occur-highlights)
13876 (org-remove-latex-fragment-image-overlays)
13877 (message "Temporary highlights/overlays removed from current buffer"))
13878 ((and (local-variable-p 'org-finish-function (current-buffer))
13879 (fboundp org-finish-function))
13880 (funcall org-finish-function))
13881 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
13882 ((org-at-property-p)
13883 (call-interactively 'org-property-action))
13884 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13885 ((org-on-heading-p) (call-interactively 'org-set-tags))
13886 ((org-at-table.el-p)
13887 (require 'table)
13888 (beginning-of-line 1)
13889 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13890 (call-interactively 'table-recognize-table))
13891 ((org-at-table-p)
13892 (org-table-maybe-eval-formula)
13893 (if arg
13894 (call-interactively 'org-table-recalculate)
13895 (org-table-maybe-recalculate-line))
13896 (call-interactively 'org-table-align))
13897 ((or (org-footnote-at-reference-p)
13898 (org-footnote-at-definition-p))
13899 (call-interactively 'org-footnote-action))
13900 ((org-at-item-checkbox-p)
13901 (call-interactively 'org-toggle-checkbox))
13902 ((org-at-item-p)
13903 (if arg
13904 (call-interactively 'org-toggle-checkbox)
13905 (call-interactively 'org-maybe-renumber-ordered-list)))
13906 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13907 ;; Dynamic block
13908 (beginning-of-line 1)
13909 (save-excursion (org-update-dblock)))
13910 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13911 (cond
13912 ((equal (match-string 1) "TBLFM")
13913 ;; Recalculate the table before this line
13914 (save-excursion
13915 (beginning-of-line 1)
13916 (skip-chars-backward " \r\n\t")
13917 (if (org-at-table-p)
13918 (org-call-with-arg 'org-table-recalculate t))))
13920 ; (org-set-regexps-and-options)
13921 ; (org-restart-font-lock)
13922 (let ((org-inhibit-startup t)) (org-mode-restart))
13923 (message "Local setup has been refreshed"))))
13924 (t (error "C-c C-c can do nothing useful at this location.")))))
13926 (defun org-mode-restart ()
13927 "Restart Org-mode, to scan again for special lines.
13928 Also updates the keyword regular expressions."
13929 (interactive)
13930 (org-mode)
13931 (message "Org-mode restarted"))
13933 (defun org-kill-note-or-show-branches ()
13934 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13935 (interactive)
13936 (if (not org-finish-function)
13937 (call-interactively 'show-branches)
13938 (let ((org-note-abort t))
13939 (funcall org-finish-function))))
13941 (defun org-return (&optional indent)
13942 "Goto next table row or insert a newline.
13943 Calls `org-table-next-row' or `newline', depending on context.
13944 See the individual commands for more information."
13945 (interactive)
13946 (cond
13947 ((bobp) (if indent (newline-and-indent) (newline)))
13948 ((org-at-table-p)
13949 (org-table-justify-field-maybe)
13950 (call-interactively 'org-table-next-row))
13951 ((and org-return-follows-link
13952 (eq (get-text-property (point) 'face) 'org-link))
13953 (call-interactively 'org-open-at-point))
13954 ((and (org-at-heading-p)
13955 (looking-at
13956 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13957 (org-show-entry)
13958 (end-of-line 1)
13959 (newline))
13960 (t (if indent (newline-and-indent) (newline)))))
13962 (defun org-return-indent ()
13963 "Goto next table row or insert a newline and indent.
13964 Calls `org-table-next-row' or `newline-and-indent', depending on
13965 context. See the individual commands for more information."
13966 (interactive)
13967 (org-return t))
13969 (defun org-ctrl-c-star ()
13970 "Compute table, or change heading status of lines.
13971 Calls `org-table-recalculate' or `org-toggle-heading',
13972 depending on context."
13973 (interactive)
13974 (cond
13975 ((org-at-table-p)
13976 (call-interactively 'org-table-recalculate))
13978 ;; Convert all lines in region to list items
13979 (call-interactively 'org-toggle-heading))))
13981 (defun org-ctrl-c-minus ()
13982 "Insert separator line in table or modify bullet status of line.
13983 Also turns a plain line or a region of lines into list items.
13984 Calls `org-table-insert-hline', `org-toggle-item', or
13985 `org-cycle-list-bullet', depending on context."
13986 (interactive)
13987 (cond
13988 ((org-at-table-p)
13989 (call-interactively 'org-table-insert-hline))
13990 ((org-region-active-p)
13991 (call-interactively 'org-toggle-item))
13992 ((org-in-item-p)
13993 (call-interactively 'org-cycle-list-bullet))
13995 (call-interactively 'org-toggle-item))))
13997 (defun org-toggle-item ()
13998 "Convert headings or normal lines to items, items to normal lines.
13999 If there is no active region, only the current line is considered.
14001 If the first line in the region is a headline, convert all headlines to items.
14003 If the first line in the region is an item, convert all items to normal lines.
14005 If the first line is normal text, add an item bullet to each line."
14006 (interactive)
14007 (let (l2 l beg end)
14008 (if (org-region-active-p)
14009 (setq beg (region-beginning) end (region-end))
14010 (setq beg (point-at-bol)
14011 end (min (1+ (point-at-eol)) (point-max))))
14012 (save-excursion
14013 (goto-char end)
14014 (setq l2 (org-current-line))
14015 (goto-char beg)
14016 (beginning-of-line 1)
14017 (setq l (1- (org-current-line)))
14018 (if (org-at-item-p)
14019 ;; We already have items, de-itemize
14020 (while (< (setq l (1+ l)) l2)
14021 (when (org-at-item-p)
14022 (goto-char (match-beginning 2))
14023 (delete-region (match-beginning 2) (match-end 2))
14024 (and (looking-at "[ \t]+") (replace-match "")))
14025 (beginning-of-line 2))
14026 (if (org-on-heading-p)
14027 ;; Headings, convert to items
14028 (while (< (setq l (1+ l)) l2)
14029 (if (looking-at org-outline-regexp)
14030 (replace-match "- " t t))
14031 (beginning-of-line 2))
14032 ;; normal lines, turn them into items
14033 (while (< (setq l (1+ l)) l2)
14034 (unless (org-at-item-p)
14035 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14036 (replace-match "\\1- \\2")))
14037 (beginning-of-line 2)))))))
14039 (defun org-toggle-heading (&optional nstars)
14040 "Convert headings to normal text, or items or text to headings.
14041 If there is no active region, only the current line is considered.
14043 If the first line is a heading, remove the stars from all headlines
14044 in the region.
14046 If the first line is a plain list item, turn all plain list items into
14047 headings.
14049 If the first line is a normal line, turn each and every line in the region
14050 into a heading.
14052 When converting a line into a heading, the number of stars is chosen
14053 such that the lines become children of the current entry. However, when
14054 a prefix argument is given, its value determines the number of stars to add."
14055 (interactive "P")
14056 (let (l2 l itemp beg end)
14057 (if (org-region-active-p)
14058 (setq beg (region-beginning) end (region-end))
14059 (setq beg (point-at-bol)
14060 end (min (1+ (point-at-eol)) (point-max))))
14061 (save-excursion
14062 (goto-char end)
14063 (setq l2 (org-current-line))
14064 (goto-char beg)
14065 (beginning-of-line 1)
14066 (setq l (1- (org-current-line)))
14067 (if (org-on-heading-p)
14068 ;; We already have headlines, de-star them
14069 (while (< (setq l (1+ l)) l2)
14070 (when (org-on-heading-p t)
14071 (and (looking-at outline-regexp) (replace-match "")))
14072 (beginning-of-line 2))
14073 (setq itemp (org-at-item-p))
14074 (let* ((stars
14075 (if nstars
14076 (make-string (prefix-numeric-value current-prefix-arg)
14078 (save-excursion
14079 (re-search-backward org-complex-heading-regexp nil t)
14080 (or (match-string 1) "*"))))
14081 (add-stars (if nstars "" (if org-odd-levels-only "**" "*")))
14082 (rpl (concat stars add-stars " ")))
14083 (while (< (setq l (1+ l)) l2)
14084 (if itemp
14085 (and (org-at-item-p) (replace-match rpl t t))
14086 (unless (org-on-heading-p)
14087 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14088 (replace-match (concat rpl (match-string 2))))))
14089 (beginning-of-line 2)))))))
14091 (defun org-meta-return (&optional arg)
14092 "Insert a new heading or wrap a region in a table.
14093 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
14094 See the individual commands for more information."
14095 (interactive "P")
14096 (cond
14097 ((run-hook-with-args-until-success 'org-metareturn-hook))
14098 ((org-at-table-p)
14099 (call-interactively 'org-table-wrap-region))
14100 (t (call-interactively 'org-insert-heading))))
14102 ;;; Menu entries
14104 ;; Define the Org-mode menus
14105 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
14106 '("Tbl"
14107 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
14108 ["Next Field" org-cycle (org-at-table-p)]
14109 ["Previous Field" org-shifttab (org-at-table-p)]
14110 ["Next Row" org-return (org-at-table-p)]
14111 "--"
14112 ["Blank Field" org-table-blank-field (org-at-table-p)]
14113 ["Edit Field" org-table-edit-field (org-at-table-p)]
14114 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
14115 "--"
14116 ("Column"
14117 ["Move Column Left" org-metaleft (org-at-table-p)]
14118 ["Move Column Right" org-metaright (org-at-table-p)]
14119 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
14120 ["Insert Column" org-shiftmetaright (org-at-table-p)])
14121 ("Row"
14122 ["Move Row Up" org-metaup (org-at-table-p)]
14123 ["Move Row Down" org-metadown (org-at-table-p)]
14124 ["Delete Row" org-shiftmetaup (org-at-table-p)]
14125 ["Insert Row" org-shiftmetadown (org-at-table-p)]
14126 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
14127 "--"
14128 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
14129 ("Rectangle"
14130 ["Copy Rectangle" org-copy-special (org-at-table-p)]
14131 ["Cut Rectangle" org-cut-special (org-at-table-p)]
14132 ["Paste Rectangle" org-paste-special (org-at-table-p)]
14133 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
14134 "--"
14135 ("Calculate"
14136 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
14137 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
14138 ["Edit Formulas" org-edit-special (org-at-table-p)]
14139 "--"
14140 ["Recalculate line" org-table-recalculate (org-at-table-p)]
14141 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
14142 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
14143 "--"
14144 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
14145 "--"
14146 ["Sum Column/Rectangle" org-table-sum
14147 (or (org-at-table-p) (org-region-active-p))]
14148 ["Which Column?" org-table-current-column (org-at-table-p)])
14149 ["Debug Formulas"
14150 org-table-toggle-formula-debugger
14151 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
14152 ["Show Col/Row Numbers"
14153 org-table-toggle-coordinate-overlays
14154 :style toggle
14155 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
14156 "--"
14157 ["Create" org-table-create (and (not (org-at-table-p))
14158 org-enable-table-editor)]
14159 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
14160 ["Import from File" org-table-import (not (org-at-table-p))]
14161 ["Export to File" org-table-export (org-at-table-p)]
14162 "--"
14163 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
14165 (easy-menu-define org-org-menu org-mode-map "Org menu"
14166 '("Org"
14167 ("Show/Hide"
14168 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
14169 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
14170 ["Sparse Tree..." org-sparse-tree t]
14171 ["Reveal Context" org-reveal t]
14172 ["Show All" show-all t]
14173 "--"
14174 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
14175 "--"
14176 ["New Heading" org-insert-heading t]
14177 ("Navigate Headings"
14178 ["Up" outline-up-heading t]
14179 ["Next" outline-next-visible-heading t]
14180 ["Previous" outline-previous-visible-heading t]
14181 ["Next Same Level" outline-forward-same-level t]
14182 ["Previous Same Level" outline-backward-same-level t]
14183 "--"
14184 ["Jump" org-goto t])
14185 ("Edit Structure"
14186 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
14187 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
14188 "--"
14189 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
14190 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
14191 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
14192 "--"
14193 ["Promote Heading" org-metaleft (not (org-at-table-p))]
14194 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
14195 ["Demote Heading" org-metaright (not (org-at-table-p))]
14196 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
14197 "--"
14198 ["Sort Region/Children" org-sort (not (org-at-table-p))]
14199 "--"
14200 ["Convert to odd levels" org-convert-to-odd-levels t]
14201 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
14202 ("Editing"
14203 ["Emphasis..." org-emphasize t]
14204 ["Edit Source Example" org-edit-special t]
14205 "--"
14206 ["Footnote new/jump" org-footnote-action t]
14207 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
14208 ("Archive"
14209 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
14210 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
14211 ; :active t :keys "C-u C-c C-x C-a"]
14212 ["Sparse trees open ARCHIVE trees"
14213 (setq org-sparse-tree-open-archived-trees
14214 (not org-sparse-tree-open-archived-trees))
14215 :style toggle :selected org-sparse-tree-open-archived-trees]
14216 ["Cycling opens ARCHIVE trees"
14217 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
14218 :style toggle :selected org-cycle-open-archived-trees]
14219 "--"
14220 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
14221 ["Move Subtree to Archive" org-advertized-archive-subtree t]
14222 ; ["Check and Move Children" (org-archive-subtree '(4))
14223 ; :active t :keys "C-u C-c C-x C-s"]
14225 "--"
14226 ("TODO Lists"
14227 ["TODO/DONE/-" org-todo t]
14228 ("Select keyword"
14229 ["Next keyword" org-shiftright (org-on-heading-p)]
14230 ["Previous keyword" org-shiftleft (org-on-heading-p)]
14231 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
14232 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
14233 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
14234 ["Show TODO Tree" org-show-todo-tree t]
14235 ["Global TODO list" org-todo-list t]
14236 "--"
14237 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
14238 :selected org-enforce-todo-dependencies :style toggle :active t]
14239 "Settings for tree at point"
14240 ["Do Children sequentially" org-toggle-ordered-property :style radio
14241 :selected (ignore-errors (org-entry-get nil "ORDERED"))
14242 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14243 ["Do Children parallel" org-toggle-ordered-property :style radio
14244 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
14245 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14246 "--"
14247 ["Set Priority" org-priority t]
14248 ["Priority Up" org-shiftup t]
14249 ["Priority Down" org-shiftdown t])
14250 ("TAGS and Properties"
14251 ["Set Tags" org-set-tags-command t]
14252 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
14253 "--"
14254 ["Set property" org-set-property t]
14255 ["Column view of properties" org-columns t]
14256 ["Insert Column View DBlock" org-insert-columns-dblock t])
14257 ("Dates and Scheduling"
14258 ["Timestamp" org-time-stamp t]
14259 ["Timestamp (inactive)" org-time-stamp-inactive t]
14260 ("Change Date"
14261 ["1 Day Later" org-shiftright t]
14262 ["1 Day Earlier" org-shiftleft t]
14263 ["1 ... Later" org-shiftup t]
14264 ["1 ... Earlier" org-shiftdown t])
14265 ["Compute Time Range" org-evaluate-time-range t]
14266 ["Schedule Item" org-schedule t]
14267 ["Deadline" org-deadline t]
14268 "--"
14269 ["Custom time format" org-toggle-time-stamp-overlays
14270 :style radio :selected org-display-custom-times]
14271 "--"
14272 ["Goto Calendar" org-goto-calendar t]
14273 ["Date from Calendar" org-date-from-calendar t]
14274 "--"
14275 ["Start/Restart Timer" org-timer-start t]
14276 ["Pause/Continue Timer" org-timer-pause-or-continue t]
14277 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
14278 ["Insert Timer String" org-timer t]
14279 ["Insert Timer Item" org-timer-item t])
14280 ("Logging work"
14281 ["Clock in" org-clock-in t]
14282 ["Clock out" org-clock-out t]
14283 ["Clock cancel" org-clock-cancel t]
14284 ["Goto running clock" org-clock-goto t]
14285 ["Display times" org-clock-display t]
14286 ["Create clock table" org-clock-report t]
14287 "--"
14288 ["Record DONE time"
14289 (progn (setq org-log-done (not org-log-done))
14290 (message "Switching to %s will %s record a timestamp"
14291 (car org-done-keywords)
14292 (if org-log-done "automatically" "not")))
14293 :style toggle :selected org-log-done])
14294 "--"
14295 ["Agenda Command..." org-agenda t]
14296 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
14297 ("File List for Agenda")
14298 ("Special views current file"
14299 ["TODO Tree" org-show-todo-tree t]
14300 ["Check Deadlines" org-check-deadlines t]
14301 ["Timeline" org-timeline t]
14302 ["Tags Tree" org-tags-sparse-tree t])
14303 "--"
14304 ("Hyperlinks"
14305 ["Store Link (Global)" org-store-link t]
14306 ["Insert Link" org-insert-link t]
14307 ["Follow Link" org-open-at-point t]
14308 "--"
14309 ["Next link" org-next-link t]
14310 ["Previous link" org-previous-link t]
14311 "--"
14312 ["Descriptive Links"
14313 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
14314 :style radio
14315 :selected (member '(org-link) buffer-invisibility-spec)]
14316 ["Literal Links"
14317 (progn
14318 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
14319 :style radio
14320 :selected (not (member '(org-link) buffer-invisibility-spec))])
14321 "--"
14322 ["Export/Publish..." org-export t]
14323 ("LaTeX"
14324 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
14325 :selected org-cdlatex-mode]
14326 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
14327 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
14328 ["Modify math symbol" org-cdlatex-math-modify
14329 (org-inside-LaTeX-fragment-p)]
14330 ["Export LaTeX fragments as images"
14331 (if (featurep 'org-exp)
14332 (setq org-export-with-LaTeX-fragments
14333 (not org-export-with-LaTeX-fragments))
14334 (require 'org-exp))
14335 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
14336 org-export-with-LaTeX-fragments)])
14337 "--"
14338 ("Documentation"
14339 ["Show Version" org-version t]
14340 ["Info Documentation" org-info t])
14341 ("Customize"
14342 ["Browse Org Group" org-customize t]
14343 "--"
14344 ["Expand This Menu" org-create-customize-menu
14345 (fboundp 'customize-menu-create)])
14346 "--"
14347 ("Refresh/Reload"
14348 ["Refresh setup current buffer" org-mode-restart t]
14349 ["Reload Org (after update)" org-reload t]
14350 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
14353 (defun org-info (&optional node)
14354 "Read documentation for Org-mode in the info system.
14355 With optional NODE, go directly to that node."
14356 (interactive)
14357 (info (format "(org)%s" (or node ""))))
14359 (defun org-install-agenda-files-menu ()
14360 (let ((bl (buffer-list)))
14361 (save-excursion
14362 (while bl
14363 (set-buffer (pop bl))
14364 (if (org-mode-p) (setq bl nil)))
14365 (when (org-mode-p)
14366 (easy-menu-change
14367 '("Org") "File List for Agenda"
14368 (append
14369 (list
14370 ["Edit File List" (org-edit-agenda-file-list) t]
14371 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
14372 ["Remove Current File from List" org-remove-file t]
14373 ["Cycle through agenda files" org-cycle-agenda-files t]
14374 ["Occur in all agenda files" org-occur-in-agenda-files t]
14375 "--")
14376 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
14378 ;;;; Documentation
14380 ;;;###autoload
14381 (defun org-require-autoloaded-modules ()
14382 (interactive)
14383 (mapc 'require
14384 '(org-agenda org-archive org-attach org-clock org-colview
14385 org-exp org-id org-export-latex org-publish
14386 org-remember org-table org-timer)))
14388 ;;;###autoload
14389 (defun org-reload (&optional uncompiled)
14390 "Reload all org lisp files.
14391 With prefix arg UNCOMPILED, load the uncompiled versions."
14392 (interactive "P")
14393 (require 'find-func)
14394 (let* ((dir (file-name-directory (find-library-name "org")))
14395 (files (directory-files dir t "\\.el\\'"))
14396 (remove-re (concat (if (featurep 'xemacs)
14397 "org-colview" "org-colview-xemacs")
14398 "\\'")))
14399 (setq files (mapcar 'file-name-sans-extension files))
14400 (setq files (mapcar
14401 (lambda (x) (if (string-match remove-re x) nil x))
14402 files))
14403 (setq files (delq nil files))
14404 (mapc
14405 (lambda (f)
14406 (if (and (not uncompiled)
14407 (file-exists-p (concat f ".elc")))
14408 (load (concat f ".elc") nil nil t)
14409 (load (concat f ".el") nil nil t)))
14410 files)))
14412 ;;;###autoload
14413 (defun org-customize ()
14414 "Call the customize function with org as argument."
14415 (interactive)
14416 (org-load-modules-maybe)
14417 (org-require-autoloaded-modules)
14418 (customize-browse 'org))
14420 (defun org-create-customize-menu ()
14421 "Create a full customization menu for Org-mode, insert it into the menu."
14422 (interactive)
14423 (org-load-modules-maybe)
14424 (org-require-autoloaded-modules)
14425 (if (fboundp 'customize-menu-create)
14426 (progn
14427 (easy-menu-change
14428 '("Org") "Customize"
14429 `(["Browse Org group" org-customize t]
14430 "--"
14431 ,(customize-menu-create 'org)
14432 ["Set" Custom-set t]
14433 ["Save" Custom-save t]
14434 ["Reset to Current" Custom-reset-current t]
14435 ["Reset to Saved" Custom-reset-saved t]
14436 ["Reset to Standard Settings" Custom-reset-standard t]))
14437 (message "\"Org\"-menu now contains full customization menu"))
14438 (error "Cannot expand menu (outdated version of cus-edit.el)")))
14440 ;;;; Miscellaneous stuff
14442 ;;; Generally useful functions
14444 (defun org-find-text-property-in-string (prop s)
14445 "Return the first non-nil value of property PROP in string S."
14446 (or (get-text-property 0 prop s)
14447 (get-text-property (or (next-single-property-change 0 prop s) 0)
14448 prop s)))
14450 (defun org-display-warning (message) ;; Copied from Emacs-Muse
14451 "Display the given MESSAGE as a warning."
14452 (if (fboundp 'display-warning)
14453 (display-warning 'org message
14454 (if (featurep 'xemacs)
14455 'warning
14456 :warning))
14457 (let ((buf (get-buffer-create "*Org warnings*")))
14458 (with-current-buffer buf
14459 (goto-char (point-max))
14460 (insert "Warning (Org): " message)
14461 (unless (bolp)
14462 (newline)))
14463 (display-buffer buf)
14464 (sit-for 0))))
14466 (defun org-goto-marker-or-bmk (marker &optional bookmark)
14467 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
14468 (if (and marker (marker-buffer marker)
14469 (buffer-live-p (marker-buffer marker)))
14470 (progn
14471 (switch-to-buffer (marker-buffer marker))
14472 (if (or (> marker (point-max)) (< marker (point-min)))
14473 (widen))
14474 (goto-char marker)
14475 (org-show-context 'org-goto))
14476 (if bookmark
14477 (bookmark-jump bookmark)
14478 (error "Cannot find location"))))
14480 (defun org-quote-csv-field (s)
14481 "Quote field for inclusion in CSV material."
14482 (if (string-match "[\",]" s)
14483 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
14486 (defun org-plist-delete (plist property)
14487 "Delete PROPERTY from PLIST.
14488 This is in contrast to merely setting it to 0."
14489 (let (p)
14490 (while plist
14491 (if (not (eq property (car plist)))
14492 (setq p (plist-put p (car plist) (nth 1 plist))))
14493 (setq plist (cddr plist)))
14496 (defun org-force-self-insert (N)
14497 "Needed to enforce self-insert under remapping."
14498 (interactive "p")
14499 (self-insert-command N))
14501 (defun org-string-width (s)
14502 "Compute width of string, ignoring invisible characters.
14503 This ignores character with invisibility property `org-link', and also
14504 characters with property `org-cwidth', because these will become invisible
14505 upon the next fontification round."
14506 (let (b l)
14507 (when (or (eq t buffer-invisibility-spec)
14508 (assq 'org-link buffer-invisibility-spec))
14509 (while (setq b (text-property-any 0 (length s)
14510 'invisible 'org-link s))
14511 (setq s (concat (substring s 0 b)
14512 (substring s (or (next-single-property-change
14513 b 'invisible s) (length s)))))))
14514 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
14515 (setq s (concat (substring s 0 b)
14516 (substring s (or (next-single-property-change
14517 b 'org-cwidth s) (length s))))))
14518 (setq l (string-width s) b -1)
14519 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
14520 (setq l (- l (get-text-property b 'org-dwidth-n s))))
14523 (defun org-get-indentation (&optional line)
14524 "Get the indentation of the current line, interpreting tabs.
14525 When LINE is given, assume it represents a line and compute its indentation."
14526 (if line
14527 (if (string-match "^ *" (org-remove-tabs line))
14528 (match-end 0))
14529 (save-excursion
14530 (beginning-of-line 1)
14531 (skip-chars-forward " \t")
14532 (current-column))))
14534 (defun org-remove-tabs (s &optional width)
14535 "Replace tabulators in S with spaces.
14536 Assumes that s is a single line, starting in column 0."
14537 (setq width (or width tab-width))
14538 (while (string-match "\t" s)
14539 (setq s (replace-match
14540 (make-string
14541 (- (* width (/ (+ (match-beginning 0) width) width))
14542 (match-beginning 0)) ?\ )
14543 t t s)))
14546 (defun org-fix-indentation (line ind)
14547 "Fix indentation in LINE.
14548 IND is a cons cell with target and minimum indentation.
14549 If the current indentation in LINE is smaller than the minimum,
14550 leave it alone. If it is larger than ind, set it to the target."
14551 (let* ((l (org-remove-tabs line))
14552 (i (org-get-indentation l))
14553 (i1 (car ind)) (i2 (cdr ind)))
14554 (if (>= i i2) (setq l (substring line i2)))
14555 (if (> i1 0)
14556 (concat (make-string i1 ?\ ) l)
14557 l)))
14559 (defun org-base-buffer (buffer)
14560 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
14561 (if (not buffer)
14562 buffer
14563 (or (buffer-base-buffer buffer)
14564 buffer)))
14566 (defun org-trim (s)
14567 "Remove whitespace at beginning and end of string."
14568 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
14569 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
14572 (defun org-wrap (string &optional width lines)
14573 "Wrap string to either a number of lines, or a width in characters.
14574 If WIDTH is non-nil, the string is wrapped to that width, however many lines
14575 that costs. If there is a word longer than WIDTH, the text is actually
14576 wrapped to the length of that word.
14577 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
14578 many lines, whatever width that takes.
14579 The return value is a list of lines, without newlines at the end."
14580 (let* ((words (org-split-string string "[ \t\n]+"))
14581 (maxword (apply 'max (mapcar 'org-string-width words)))
14582 w ll)
14583 (cond (width
14584 (org-do-wrap words (max maxword width)))
14585 (lines
14586 (setq w maxword)
14587 (setq ll (org-do-wrap words maxword))
14588 (if (<= (length ll) lines)
14590 (setq ll words)
14591 (while (> (length ll) lines)
14592 (setq w (1+ w))
14593 (setq ll (org-do-wrap words w)))
14594 ll))
14595 (t (error "Cannot wrap this")))))
14597 (defun org-do-wrap (words width)
14598 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
14599 (let (lines line)
14600 (while words
14601 (setq line (pop words))
14602 (while (and words (< (+ (length line) (length (car words))) width))
14603 (setq line (concat line " " (pop words))))
14604 (setq lines (push line lines)))
14605 (nreverse lines)))
14607 (defun org-split-string (string &optional separators)
14608 "Splits STRING into substrings at SEPARATORS.
14609 No empty strings are returned if there are matches at the beginning
14610 and end of string."
14611 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
14612 (start 0)
14613 notfirst
14614 (list nil))
14615 (while (and (string-match rexp string
14616 (if (and notfirst
14617 (= start (match-beginning 0))
14618 (< start (length string)))
14619 (1+ start) start))
14620 (< (match-beginning 0) (length string)))
14621 (setq notfirst t)
14622 (or (eq (match-beginning 0) 0)
14623 (and (eq (match-beginning 0) (match-end 0))
14624 (eq (match-beginning 0) start))
14625 (setq list
14626 (cons (substring string start (match-beginning 0))
14627 list)))
14628 (setq start (match-end 0)))
14629 (or (eq start (length string))
14630 (setq list
14631 (cons (substring string start)
14632 list)))
14633 (nreverse list)))
14635 (defun org-context ()
14636 "Return a list of contexts of the current cursor position.
14637 If several contexts apply, all are returned.
14638 Each context entry is a list with a symbol naming the context, and
14639 two positions indicating start and end of the context. Possible
14640 contexts are:
14642 :headline anywhere in a headline
14643 :headline-stars on the leading stars in a headline
14644 :todo-keyword on a TODO keyword (including DONE) in a headline
14645 :tags on the TAGS in a headline
14646 :priority on the priority cookie in a headline
14647 :item on the first line of a plain list item
14648 :item-bullet on the bullet/number of a plain list item
14649 :checkbox on the checkbox in a plain list item
14650 :table in an org-mode table
14651 :table-special on a special filed in a table
14652 :table-table in a table.el table
14653 :link on a hyperlink
14654 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
14655 :target on a <<target>>
14656 :radio-target on a <<<radio-target>>>
14657 :latex-fragment on a LaTeX fragment
14658 :latex-preview on a LaTeX fragment with overlayed preview image
14660 This function expects the position to be visible because it uses font-lock
14661 faces as a help to recognize the following contexts: :table-special, :link,
14662 and :keyword."
14663 (let* ((f (get-text-property (point) 'face))
14664 (faces (if (listp f) f (list f)))
14665 (p (point)) clist o)
14666 ;; First the large context
14667 (cond
14668 ((org-on-heading-p t)
14669 (push (list :headline (point-at-bol) (point-at-eol)) clist)
14670 (when (progn
14671 (beginning-of-line 1)
14672 (looking-at org-todo-line-tags-regexp))
14673 (push (org-point-in-group p 1 :headline-stars) clist)
14674 (push (org-point-in-group p 2 :todo-keyword) clist)
14675 (push (org-point-in-group p 4 :tags) clist))
14676 (goto-char p)
14677 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
14678 (if (looking-at "\\[#[A-Z0-9]\\]")
14679 (push (org-point-in-group p 0 :priority) clist)))
14681 ((org-at-item-p)
14682 (push (org-point-in-group p 2 :item-bullet) clist)
14683 (push (list :item (point-at-bol)
14684 (save-excursion (org-end-of-item) (point)))
14685 clist)
14686 (and (org-at-item-checkbox-p)
14687 (push (org-point-in-group p 0 :checkbox) clist)))
14689 ((org-at-table-p)
14690 (push (list :table (org-table-begin) (org-table-end)) clist)
14691 (if (memq 'org-formula faces)
14692 (push (list :table-special
14693 (previous-single-property-change p 'face)
14694 (next-single-property-change p 'face)) clist)))
14695 ((org-at-table-p 'any)
14696 (push (list :table-table) clist)))
14697 (goto-char p)
14699 ;; Now the small context
14700 (cond
14701 ((org-at-timestamp-p)
14702 (push (org-point-in-group p 0 :timestamp) clist))
14703 ((memq 'org-link faces)
14704 (push (list :link
14705 (previous-single-property-change p 'face)
14706 (next-single-property-change p 'face)) clist))
14707 ((memq 'org-special-keyword faces)
14708 (push (list :keyword
14709 (previous-single-property-change p 'face)
14710 (next-single-property-change p 'face)) clist))
14711 ((org-on-target-p)
14712 (push (org-point-in-group p 0 :target) clist)
14713 (goto-char (1- (match-beginning 0)))
14714 (if (looking-at org-radio-target-regexp)
14715 (push (org-point-in-group p 0 :radio-target) clist))
14716 (goto-char p))
14717 ((setq o (car (delq nil
14718 (mapcar
14719 (lambda (x)
14720 (if (memq x org-latex-fragment-image-overlays) x))
14721 (org-overlays-at (point))))))
14722 (push (list :latex-fragment
14723 (org-overlay-start o) (org-overlay-end o)) clist)
14724 (push (list :latex-preview
14725 (org-overlay-start o) (org-overlay-end o)) clist))
14726 ((org-inside-LaTeX-fragment-p)
14727 ;; FIXME: positions wrong.
14728 (push (list :latex-fragment (point) (point)) clist)))
14730 (setq clist (nreverse (delq nil clist)))
14731 clist))
14733 ;; FIXME: Compare with at-regexp-p Do we need both?
14734 (defun org-in-regexp (re &optional nlines visually)
14735 "Check if point is inside a match of regexp.
14736 Normally only the current line is checked, but you can include NLINES extra
14737 lines both before and after point into the search.
14738 If VISUALLY is set, require that the cursor is not after the match but
14739 really on, so that the block visually is on the match."
14740 (catch 'exit
14741 (let ((pos (point))
14742 (eol (point-at-eol (+ 1 (or nlines 0))))
14743 (inc (if visually 1 0)))
14744 (save-excursion
14745 (beginning-of-line (- 1 (or nlines 0)))
14746 (while (re-search-forward re eol t)
14747 (if (and (<= (match-beginning 0) pos)
14748 (>= (+ inc (match-end 0)) pos))
14749 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
14751 (defun org-at-regexp-p (regexp)
14752 "Is point inside a match of REGEXP in the current line?"
14753 (catch 'exit
14754 (save-excursion
14755 (let ((pos (point)) (end (point-at-eol)))
14756 (beginning-of-line 1)
14757 (while (re-search-forward regexp end t)
14758 (if (and (<= (match-beginning 0) pos)
14759 (>= (match-end 0) pos))
14760 (throw 'exit t)))
14761 nil))))
14763 (defun org-occur-in-agenda-files (regexp &optional nlines)
14764 "Call `multi-occur' with buffers for all agenda files."
14765 (interactive "sOrg-files matching: \np")
14766 (let* ((files (org-agenda-files))
14767 (tnames (mapcar 'file-truename files))
14768 (extra org-agenda-text-search-extra-files)
14770 (when (eq (car extra) 'agenda-archives)
14771 (setq extra (cdr extra))
14772 (setq files (org-add-archive-files files)))
14773 (while (setq f (pop extra))
14774 (unless (member (file-truename f) tnames)
14775 (add-to-list 'files f 'append)
14776 (add-to-list 'tnames (file-truename f) 'append)))
14777 (multi-occur
14778 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
14779 regexp)))
14781 (if (boundp 'occur-mode-find-occurrence-hook)
14782 ;; Emacs 23
14783 (add-hook 'occur-mode-find-occurrence-hook
14784 (lambda ()
14785 (when (org-mode-p)
14786 (org-reveal))))
14787 ;; Emacs 22
14788 (defadvice occur-mode-goto-occurrence
14789 (after org-occur-reveal activate)
14790 (and (org-mode-p) (org-reveal)))
14791 (defadvice occur-mode-goto-occurrence-other-window
14792 (after org-occur-reveal activate)
14793 (and (org-mode-p) (org-reveal)))
14794 (defadvice occur-mode-display-occurrence
14795 (after org-occur-reveal activate)
14796 (when (org-mode-p)
14797 (let ((pos (occur-mode-find-occurrence)))
14798 (with-current-buffer (marker-buffer pos)
14799 (save-excursion
14800 (goto-char pos)
14801 (org-reveal)))))))
14803 (defun org-uniquify (list)
14804 "Remove duplicate elements from LIST."
14805 (let (res)
14806 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
14807 res))
14809 (defun org-delete-all (elts list)
14810 "Remove all elements in ELTS from LIST."
14811 (while elts
14812 (setq list (delete (pop elts) list)))
14813 list)
14815 (defun org-back-over-empty-lines ()
14816 "Move backwards over whitespace, to the beginning of the first empty line.
14817 Returns the number of empty lines passed."
14818 (let ((pos (point)))
14819 (skip-chars-backward " \t\n\r")
14820 (beginning-of-line 2)
14821 (goto-char (min (point) pos))
14822 (count-lines (point) pos)))
14824 (defun org-skip-whitespace ()
14825 (skip-chars-forward " \t\n\r"))
14827 (defun org-point-in-group (point group &optional context)
14828 "Check if POINT is in match-group GROUP.
14829 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
14830 match. If the match group does ot exist or point is not inside it,
14831 return nil."
14832 (and (match-beginning group)
14833 (>= point (match-beginning group))
14834 (<= point (match-end group))
14835 (if context
14836 (list context (match-beginning group) (match-end group))
14837 t)))
14839 (defun org-switch-to-buffer-other-window (&rest args)
14840 "Switch to buffer in a second window on the current frame.
14841 In particular, do not allow pop-up frames."
14842 (let (pop-up-frames special-display-buffer-names special-display-regexps
14843 special-display-function)
14844 (apply 'switch-to-buffer-other-window args)))
14846 (defun org-combine-plists (&rest plists)
14847 "Create a single property list from all plists in PLISTS.
14848 The process starts by copying the first list, and then setting properties
14849 from the other lists. Settings in the last list are the most significant
14850 ones and overrule settings in the other lists."
14851 (let ((rtn (copy-sequence (pop plists)))
14852 p v ls)
14853 (while plists
14854 (setq ls (pop plists))
14855 (while ls
14856 (setq p (pop ls) v (pop ls))
14857 (setq rtn (plist-put rtn p v))))
14858 rtn))
14860 (defun org-move-line-down (arg)
14861 "Move the current line down. With prefix argument, move it past ARG lines."
14862 (interactive "p")
14863 (let ((col (current-column))
14864 beg end pos)
14865 (beginning-of-line 1) (setq beg (point))
14866 (beginning-of-line 2) (setq end (point))
14867 (beginning-of-line (+ 1 arg))
14868 (setq pos (move-marker (make-marker) (point)))
14869 (insert (delete-and-extract-region beg end))
14870 (goto-char pos)
14871 (org-move-to-column col)))
14873 (defun org-move-line-up (arg)
14874 "Move the current line up. With prefix argument, move it past ARG lines."
14875 (interactive "p")
14876 (let ((col (current-column))
14877 beg end pos)
14878 (beginning-of-line 1) (setq beg (point))
14879 (beginning-of-line 2) (setq end (point))
14880 (beginning-of-line (- arg))
14881 (setq pos (move-marker (make-marker) (point)))
14882 (insert (delete-and-extract-region beg end))
14883 (goto-char pos)
14884 (org-move-to-column col)))
14886 (defun org-replace-escapes (string table)
14887 "Replace %-escapes in STRING with values in TABLE.
14888 TABLE is an association list with keys like \"%a\" and string values.
14889 The sequences in STRING may contain normal field width and padding information,
14890 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
14891 so values can contain further %-escapes if they are define later in TABLE."
14892 (let ((case-fold-search nil)
14893 e re rpl)
14894 (while (setq e (pop table))
14895 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
14896 (while (string-match re string)
14897 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
14898 (cdr e)))
14899 (setq string (replace-match rpl t t string))))
14900 string))
14903 (defun org-sublist (list start end)
14904 "Return a section of LIST, from START to END.
14905 Counting starts at 1."
14906 (let (rtn (c start))
14907 (setq list (nthcdr (1- start) list))
14908 (while (and list (<= c end))
14909 (push (pop list) rtn)
14910 (setq c (1+ c)))
14911 (nreverse rtn)))
14913 (defun org-find-base-buffer-visiting (file)
14914 "Like `find-buffer-visiting' but alway return the base buffer and
14915 not an indirect buffer."
14916 (let ((buf (find-buffer-visiting file)))
14917 (if buf
14918 (or (buffer-base-buffer buf) buf)
14919 nil)))
14921 (defun org-image-file-name-regexp (&optional extensions)
14922 "Return regexp matching the file names of images.
14923 If EXTENSIONS is given, only match these."
14924 (if (and (not extensions) (fboundp 'image-file-name-regexp))
14925 (image-file-name-regexp)
14926 (let ((image-file-name-extensions
14927 (or extensions
14928 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
14929 "xbm" "xpm" "pbm" "pgm" "ppm"))))
14930 (concat "\\."
14931 (regexp-opt (nconc (mapcar 'upcase
14932 image-file-name-extensions)
14933 image-file-name-extensions)
14935 "\\'"))))
14937 (defun org-file-image-p (file &optional extensions)
14938 "Return non-nil if FILE is an image."
14939 (save-match-data
14940 (string-match (org-image-file-name-regexp extensions) file)))
14942 (defun org-get-cursor-date ()
14943 "Return the date at cursor in as a time.
14944 This works in the calendar and in the agenda, anywhere else it just
14945 returns the current time."
14946 (let (date day defd)
14947 (cond
14948 ((eq major-mode 'calendar-mode)
14949 (setq date (calendar-cursor-to-date)
14950 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14951 ((eq major-mode 'org-agenda-mode)
14952 (setq day (get-text-property (point) 'day))
14953 (if day
14954 (setq date (calendar-gregorian-from-absolute day)
14955 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
14956 (nth 2 date))))))
14957 (or defd (current-time))))
14959 (defvar org-agenda-action-marker (make-marker)
14960 "Marker pointing to the entry for the next agenda action.")
14962 (defun org-mark-entry-for-agenda-action ()
14963 "Mark the current entry as target of an agenda action.
14964 Agenda actions are actions executed from the agenda with the key `k',
14965 which make use of the date at the cursor."
14966 (interactive)
14967 (move-marker org-agenda-action-marker
14968 (save-excursion (org-back-to-heading t) (point))
14969 (current-buffer))
14970 (message
14971 "Entry marked for action; press `k' at desired date in agenda or calendar"))
14973 ;;; Paragraph filling stuff.
14974 ;; We want this to be just right, so use the full arsenal.
14976 (defun org-indent-line-function ()
14977 "Indent line like previous, but further if previous was headline or item."
14978 (interactive)
14979 (let* ((pos (point))
14980 (itemp (org-at-item-p))
14981 (org-drawer-regexp (or org-drawer-regexp "\000"))
14982 column bpos bcol tpos tcol bullet btype bullet-type)
14983 ;; Find the previous relevant line
14984 (beginning-of-line 1)
14985 (cond
14986 ((looking-at "#") (setq column 0))
14987 ((looking-at "\\*+ ") (setq column 0))
14988 ((and (looking-at "[ \t]*:END:")
14989 (save-excursion (re-search-backward org-drawer-regexp nil t)))
14990 (save-excursion
14991 (goto-char (1- (match-beginning 1)))
14992 (setq column (current-column))))
14994 (beginning-of-line 0)
14995 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
14996 (not (looking-at "[ \t]*:END:"))
14997 (not (looking-at org-drawer-regexp)))
14998 (beginning-of-line 0))
14999 (cond
15000 ((looking-at "\\*+[ \t]+")
15001 (if (not org-adapt-indentation)
15002 (setq column 0)
15003 (goto-char (match-end 0))
15004 (setq column (current-column))))
15005 ((looking-at org-drawer-regexp)
15006 (goto-char (1- (match-beginning 1)))
15007 (setq column (current-column)))
15008 ((looking-at "\\([ \t]*\\):END:")
15009 (goto-char (match-end 1))
15010 (setq column (current-column)))
15011 ((org-in-item-p)
15012 (org-beginning-of-item)
15013 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
15014 (setq bpos (match-beginning 1) tpos (match-end 0)
15015 bcol (progn (goto-char bpos) (current-column))
15016 tcol (progn (goto-char tpos) (current-column))
15017 bullet (match-string 1)
15018 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
15019 (if (> tcol (+ bcol org-description-max-indent))
15020 (setq tcol (+ bcol 5)))
15021 (if (not itemp)
15022 (setq column tcol)
15023 (goto-char pos)
15024 (beginning-of-line 1)
15025 (if (looking-at "\\S-")
15026 (progn
15027 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
15028 (setq bullet (match-string 1)
15029 btype (if (string-match "[0-9]" bullet) "n" bullet))
15030 (setq column (if (equal btype bullet-type) bcol tcol)))
15031 (setq column (org-get-indentation)))))
15032 (t (setq column (org-get-indentation))))))
15033 (goto-char pos)
15034 (if (<= (current-column) (current-indentation))
15035 (org-indent-line-to column)
15036 (save-excursion (org-indent-line-to column)))
15037 (setq column (current-column))
15038 (beginning-of-line 1)
15039 (if (looking-at
15040 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
15041 (replace-match (concat "\\1" (format org-property-format
15042 (match-string 2) (match-string 3)))
15043 t nil))
15044 (org-move-to-column column)))
15046 (defun org-set-autofill-regexps ()
15047 (interactive)
15048 ;; In the paragraph separator we include headlines, because filling
15049 ;; text in a line directly attached to a headline would otherwise
15050 ;; fill the headline as well.
15051 (org-set-local 'comment-start-skip "^#+[ \t]*")
15052 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
15053 ;; The paragraph starter includes hand-formatted lists.
15054 (org-set-local 'paragraph-start
15055 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
15056 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
15057 ;; But only if the user has not turned off tables or fixed-width regions
15058 (org-set-local
15059 'auto-fill-inhibit-regexp
15060 (concat "\\*+ \\|#\\+"
15061 "\\|[ \t]*" org-keyword-time-regexp
15062 (if (or org-enable-table-editor org-enable-fixed-width-editor)
15063 (concat
15064 "\\|[ \t]*["
15065 (if org-enable-table-editor "|" "")
15066 (if org-enable-fixed-width-editor ":" "")
15067 "]"))))
15068 ;; We use our own fill-paragraph function, to make sure that tables
15069 ;; and fixed-width regions are not wrapped. That function will pass
15070 ;; through to `fill-paragraph' when appropriate.
15071 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
15072 ; Adaptive filling: To get full control, first make sure that
15073 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
15074 (org-set-local 'adaptive-fill-regexp "\000")
15075 (org-set-local 'adaptive-fill-function
15076 'org-adaptive-fill-function)
15077 (org-set-local
15078 'align-mode-rules-list
15079 '((org-in-buffer-settings
15080 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
15081 (modes . '(org-mode))))))
15083 (defun org-fill-paragraph (&optional justify)
15084 "Re-align a table, pass through to fill-paragraph if no table."
15085 (let ((table-p (org-at-table-p))
15086 (table.el-p (org-at-table.el-p)))
15087 (cond ((and (equal (char-after (point-at-bol)) ?*)
15088 (save-excursion (goto-char (point-at-bol))
15089 (looking-at outline-regexp)))
15090 t) ; skip headlines
15091 (table.el-p t) ; skip table.el tables
15092 (table-p (org-table-align) t) ; align org-mode tables
15093 (t nil)))) ; call paragraph-fill
15095 ;; For reference, this is the default value of adaptive-fill-regexp
15096 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
15098 (defun org-adaptive-fill-function ()
15099 "Return a fill prefix for org-mode files.
15100 In particular, this makes sure hanging paragraphs for hand-formatted lists
15101 work correctly."
15102 (cond ((looking-at "#[ \t]+")
15103 (match-string 0))
15104 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
15105 (save-excursion
15106 (if (> (match-end 1) (+ (match-beginning 1)
15107 org-description-max-indent))
15108 (goto-char (+ (match-beginning 1) 5))
15109 (goto-char (match-end 0)))
15110 (make-string (current-column) ?\ )))
15111 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
15112 (save-excursion
15113 (goto-char (match-end 0))
15114 (make-string (current-column) ?\ )))
15115 (t nil)))
15117 ;;; Other stuff.
15119 (defun org-toggle-fixed-width-section (arg)
15120 "Toggle the fixed-width export.
15121 If there is no active region, the QUOTE keyword at the current headline is
15122 inserted or removed. When present, it causes the text between this headline
15123 and the next to be exported as fixed-width text, and unmodified.
15124 If there is an active region, this command adds or removes a colon as the
15125 first character of this line. If the first character of a line is a colon,
15126 this line is also exported in fixed-width font."
15127 (interactive "P")
15128 (let* ((cc 0)
15129 (regionp (org-region-active-p))
15130 (beg (if regionp (region-beginning) (point)))
15131 (end (if regionp (region-end)))
15132 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
15133 (case-fold-search nil)
15134 (re "[ \t]*\\(:\\)")
15135 off)
15136 (if regionp
15137 (save-excursion
15138 (goto-char beg)
15139 (setq cc (current-column))
15140 (beginning-of-line 1)
15141 (setq off (looking-at re))
15142 (while (> nlines 0)
15143 (setq nlines (1- nlines))
15144 (beginning-of-line 1)
15145 (cond
15146 (arg
15147 (org-move-to-column cc t)
15148 (insert ":\n")
15149 (forward-line -1))
15150 ((and off (looking-at re))
15151 (replace-match "" t t nil 1))
15152 ((not off) (org-move-to-column cc t) (insert ":")))
15153 (forward-line 1)))
15154 (save-excursion
15155 (org-back-to-heading)
15156 (if (looking-at (concat outline-regexp
15157 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
15158 (replace-match "" t t nil 1)
15159 (if (looking-at outline-regexp)
15160 (progn
15161 (goto-char (match-end 0))
15162 (insert org-quote-string " "))))))))
15164 ;;;; Functions extending outline functionality
15166 (defun org-beginning-of-line (&optional arg)
15167 "Go to the beginning of the current line. If that is invisible, continue
15168 to a visible line beginning. This makes the function of C-a more intuitive.
15169 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15170 first attempt, and only move to after the tags when the cursor is already
15171 beyond the end of the headline."
15172 (interactive "P")
15173 (let ((pos (point))
15174 (special (if (consp org-special-ctrl-a/e)
15175 (car org-special-ctrl-a/e)
15176 org-special-ctrl-a/e))
15177 refpos)
15178 (beginning-of-line 1)
15179 (if (and arg (fboundp 'move-beginning-of-line))
15180 (call-interactively 'move-beginning-of-line)
15181 (if (bobp)
15183 (backward-char 1)
15184 (if (org-invisible-p)
15185 (while (and (not (bobp)) (org-invisible-p))
15186 (backward-char 1)
15187 (beginning-of-line 1))
15188 (forward-char 1))))
15189 (when special
15190 (cond
15191 ((and (looking-at org-complex-heading-regexp)
15192 (= (char-after (match-end 1)) ?\ ))
15193 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
15194 (point-at-eol)))
15195 (goto-char
15196 (if (eq special t)
15197 (cond ((> pos refpos) refpos)
15198 ((= pos (point)) refpos)
15199 (t (point)))
15200 (cond ((> pos (point)) (point))
15201 ((not (eq last-command this-command)) (point))
15202 (t refpos)))))
15203 ((org-at-item-p)
15204 (goto-char
15205 (if (eq special t)
15206 (cond ((> pos (match-end 4)) (match-end 4))
15207 ((= pos (point)) (match-end 4))
15208 (t (point)))
15209 (cond ((> pos (point)) (point))
15210 ((not (eq last-command this-command)) (point))
15211 (t (match-end 4))))))))
15212 (org-no-warnings
15213 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15215 (defun org-end-of-line (&optional arg)
15216 "Go to the end of the line.
15217 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15218 first attempt, and only move to after the tags when the cursor is already
15219 beyond the end of the headline."
15220 (interactive "P")
15221 (let ((special (if (consp org-special-ctrl-a/e)
15222 (cdr org-special-ctrl-a/e)
15223 org-special-ctrl-a/e)))
15224 (if (or (not special)
15225 (not (org-on-heading-p))
15226 arg)
15227 (call-interactively (if (fboundp 'move-end-of-line)
15228 'move-end-of-line
15229 'end-of-line))
15230 (let ((pos (point)))
15231 (beginning-of-line 1)
15232 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15233 (if (eq special t)
15234 (if (or (< pos (match-beginning 1))
15235 (= pos (match-end 0)))
15236 (goto-char (match-beginning 1))
15237 (goto-char (match-end 0)))
15238 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
15239 (goto-char (match-end 0))
15240 (goto-char (match-beginning 1))))
15241 (call-interactively (if (fboundp 'move-end-of-line)
15242 'move-end-of-line
15243 'end-of-line)))))
15244 (org-no-warnings
15245 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15247 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
15248 (define-key org-mode-map "\C-e" 'org-end-of-line)
15250 (defun org-kill-line (&optional arg)
15251 "Kill line, to tags or end of line."
15252 (interactive "P")
15253 (cond
15254 ((or (not org-special-ctrl-k)
15255 (bolp)
15256 (not (org-on-heading-p)))
15257 (call-interactively 'kill-line))
15258 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
15259 (kill-region (point) (match-beginning 1))
15260 (org-set-tags nil t))
15261 (t (kill-region (point) (point-at-eol)))))
15263 (define-key org-mode-map "\C-k" 'org-kill-line)
15265 (defun org-yank (&optional arg)
15266 "Yank. If the kill is a subtree, treat it specially.
15267 This command will look at the current kill and check if is a single
15268 subtree, or a series of subtrees[1]. If it passes the test, and if the
15269 cursor is at the beginning of a line or after the stars of a currently
15270 empty headline, then the yank is handled specially. How exactly depends
15271 on the value of the following variables, both set by default.
15273 org-yank-folded-subtrees
15274 When set, the subtree(s) will be folded after insertion, but only
15275 if doing so would now swallow text after the yanked text.
15277 org-yank-adjusted-subtrees
15278 When set, the subtree will be promoted or demoted in order to
15279 fit into the local outline tree structure, which means that the level
15280 will be adjusted so that it becomes the smaller one of the two
15281 *visible* surrounding headings.
15283 Any prefix to this command will cause `yank' to be called directly with
15284 no special treatment. In particular, a simple `C-u' prefix will just
15285 plainly yank the text as it is.
15287 \[1] Basically, the test checks if the first non-white line is a heading
15288 and if there are no other headings with fewer stars."
15289 (interactive "P")
15290 (setq this-command 'yank)
15291 (if arg
15292 (call-interactively 'yank)
15293 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
15294 (and (org-kill-is-subtree-p)
15295 (or (bolp)
15296 (and (looking-at "[ \t]*$")
15297 (string-match
15298 "\\`\\*+\\'"
15299 (buffer-substring (point-at-bol) (point)))))))
15300 swallowp)
15301 (cond
15302 ((and subtreep org-yank-folded-subtrees)
15303 (let ((beg (point))
15304 end)
15305 (if (and subtreep org-yank-adjusted-subtrees)
15306 (org-paste-subtree nil nil 'for-yank)
15307 (call-interactively 'yank))
15308 (setq end (point))
15309 (goto-char beg)
15310 (when (and (bolp) subtreep
15311 (not (setq swallowp
15312 (org-yank-folding-would-swallow-text beg end))))
15313 (or (looking-at outline-regexp)
15314 (re-search-forward (concat "^" outline-regexp) end t))
15315 (while (and (< (point) end) (looking-at outline-regexp))
15316 (hide-subtree)
15317 (org-cycle-show-empty-lines 'folded)
15318 (condition-case nil
15319 (outline-forward-same-level 1)
15320 (error (goto-char end)))))
15321 (when swallowp
15322 (message
15323 "Yanked text not folded because that would swallow text"))
15324 (goto-char end)
15325 (skip-chars-forward " \t\n\r")
15326 (beginning-of-line 1)
15327 (push-mark beg 'nomsg)))
15328 ((and subtreep org-yank-adjusted-subtrees)
15329 (let ((beg (point-at-bol)))
15330 (org-paste-subtree nil nil 'for-yank)
15331 (push-mark beg 'nomsg)))
15333 (call-interactively 'yank))))))
15335 (defun org-yank-folding-would-swallow-text (beg end)
15336 "Would hide-subtree at BEG swallow any text after END?"
15337 (let (level)
15338 (save-excursion
15339 (goto-char beg)
15340 (when (or (looking-at outline-regexp)
15341 (re-search-forward (concat "^" outline-regexp) end t))
15342 (setq level (org-outline-level)))
15343 (goto-char end)
15344 (skip-chars-forward " \t\r\n\v\f")
15345 (if (or (eobp)
15346 (and (bolp) (looking-at org-outline-regexp)
15347 (<= (org-outline-level) level)))
15348 nil ; Nothing would be swallowed
15349 t)))) ; something would swallow
15351 (define-key org-mode-map "\C-y" 'org-yank)
15353 (defun org-invisible-p ()
15354 "Check if point is at a character currently not visible."
15355 ;; Early versions of noutline don't have `outline-invisible-p'.
15356 (if (fboundp 'outline-invisible-p)
15357 (outline-invisible-p)
15358 (get-char-property (point) 'invisible)))
15360 (defun org-invisible-p2 ()
15361 "Check if point is at a character currently not visible."
15362 (save-excursion
15363 (if (and (eolp) (not (bobp))) (backward-char 1))
15364 ;; Early versions of noutline don't have `outline-invisible-p'.
15365 (if (fboundp 'outline-invisible-p)
15366 (outline-invisible-p)
15367 (get-char-property (point) 'invisible))))
15369 (defun org-back-to-heading (&optional invisible-ok)
15370 "Call `outline-back-to-heading', but provide a better error message."
15371 (condition-case nil
15372 (outline-back-to-heading invisible-ok)
15373 (error (error "Before first headline at position %d in buffer %s"
15374 (point) (current-buffer)))))
15376 (defun org-before-first-heading-p ()
15377 "Before first heading?"
15378 (save-excursion
15379 (null (re-search-backward "^\\*+ " nil t))))
15381 (defalias 'org-on-heading-p 'outline-on-heading-p)
15382 (defalias 'org-at-heading-p 'outline-on-heading-p)
15383 (defun org-at-heading-or-item-p ()
15384 (or (org-on-heading-p) (org-at-item-p)))
15386 (defun org-on-target-p ()
15387 (or (org-in-regexp org-radio-target-regexp)
15388 (org-in-regexp org-target-regexp)))
15390 (defun org-up-heading-all (arg)
15391 "Move to the heading line of which the present line is a subheading.
15392 This function considers both visible and invisible heading lines.
15393 With argument, move up ARG levels."
15394 (if (fboundp 'outline-up-heading-all)
15395 (outline-up-heading-all arg) ; emacs 21 version of outline.el
15396 (outline-up-heading arg t))) ; emacs 22 version of outline.el
15398 (defun org-up-heading-safe ()
15399 "Move to the heading line of which the present line is a subheading.
15400 This version will not throw an error. It will return the level of the
15401 headline found, or nil if no higher level is found."
15402 (let (start-level re)
15403 (org-back-to-heading t)
15404 (setq start-level (funcall outline-level))
15405 (if (equal start-level 1)
15407 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
15408 (if (re-search-backward re nil t)
15409 (funcall outline-level)))))
15411 (defun org-first-sibling-p ()
15412 "Is this heading the first child of its parents?"
15413 (interactive)
15414 (let ((re (concat "^" outline-regexp))
15415 level l)
15416 (unless (org-at-heading-p t)
15417 (error "Not at a heading"))
15418 (setq level (funcall outline-level))
15419 (save-excursion
15420 (if (not (re-search-backward re nil t))
15422 (setq l (funcall outline-level))
15423 (< l level)))))
15425 (defun org-goto-sibling (&optional previous)
15426 "Goto the next sibling, even if it is invisible.
15427 When PREVIOUS is set, go to the previous sibling instead. Returns t
15428 when a sibling was found. When none is found, return nil and don't
15429 move point."
15430 (let ((fun (if previous 're-search-backward 're-search-forward))
15431 (pos (point))
15432 (re (concat "^" outline-regexp))
15433 level l)
15434 (when (condition-case nil (org-back-to-heading t) (error nil))
15435 (setq level (funcall outline-level))
15436 (catch 'exit
15437 (or previous (forward-char 1))
15438 (while (funcall fun re nil t)
15439 (setq l (funcall outline-level))
15440 (when (< l level) (goto-char pos) (throw 'exit nil))
15441 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
15442 (goto-char pos)
15443 nil))))
15445 (defun org-show-siblings ()
15446 "Show all siblings of the current headline."
15447 (save-excursion
15448 (while (org-goto-sibling) (org-flag-heading nil)))
15449 (save-excursion
15450 (while (org-goto-sibling 'previous)
15451 (org-flag-heading nil))))
15453 (defun org-show-hidden-entry ()
15454 "Show an entry where even the heading is hidden."
15455 (save-excursion
15456 (org-show-entry)))
15458 (defun org-flag-heading (flag &optional entry)
15459 "Flag the current heading. FLAG non-nil means make invisible.
15460 When ENTRY is non-nil, show the entire entry."
15461 (save-excursion
15462 (org-back-to-heading t)
15463 ;; Check if we should show the entire entry
15464 (if entry
15465 (progn
15466 (org-show-entry)
15467 (save-excursion
15468 (and (outline-next-heading)
15469 (org-flag-heading nil))))
15470 (outline-flag-region (max (point-min) (1- (point)))
15471 (save-excursion (outline-end-of-heading) (point))
15472 flag))))
15474 (defun org-forward-same-level (arg)
15475 "Move forward to the ARG'th subheading at same level as this one.
15476 Stop at the first and last subheadings of a superior heading.
15477 This is like outline-forward-same-level, but invisible headings are ok."
15478 (interactive "p")
15479 (org-back-to-heading t)
15480 (while (> arg 0)
15481 (let ((point-to-move-to (save-excursion
15482 (org-get-next-sibling))))
15483 (if point-to-move-to
15484 (progn
15485 (goto-char point-to-move-to)
15486 (setq arg (1- arg)))
15487 (progn
15488 (setq arg 0)
15489 (error "No following same-level heading"))))))
15491 (defun org-get-next-sibling ()
15492 "Move to next heading of the same level, and return point.
15493 If there is no such heading, return nil.
15494 This is like outline-next-sibling, but invisible headings are ok."
15495 (let ((level (funcall outline-level)))
15496 (outline-next-heading)
15497 (while (and (not (eobp)) (> (funcall outline-level) level))
15498 (outline-next-heading))
15499 (if (or (eobp) (< (funcall outline-level) level))
15501 (point))))
15503 (defun org-end-of-subtree (&optional invisible-OK to-heading)
15504 ;; This is an exact copy of the original function, but it uses
15505 ;; `org-back-to-heading', to make it work also in invisible
15506 ;; trees. And is uses an invisible-OK argument.
15507 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
15508 (org-back-to-heading invisible-OK)
15509 (let ((first t)
15510 (level (funcall outline-level)))
15511 (while (and (not (eobp))
15512 (or first (> (funcall outline-level) level)))
15513 (setq first nil)
15514 (outline-next-heading))
15515 (unless to-heading
15516 (if (memq (preceding-char) '(?\n ?\^M))
15517 (progn
15518 ;; Go to end of line before heading
15519 (forward-char -1)
15520 (if (memq (preceding-char) '(?\n ?\^M))
15521 ;; leave blank line before heading
15522 (forward-char -1))))))
15523 (point))
15525 (defun org-show-subtree ()
15526 "Show everything after this heading at deeper levels."
15527 (outline-flag-region
15528 (point)
15529 (save-excursion
15530 (outline-end-of-subtree) (outline-next-heading) (point))
15531 nil))
15533 (defun org-show-entry ()
15534 "Show the body directly following this heading.
15535 Show the heading too, if it is currently invisible."
15536 (interactive)
15537 (save-excursion
15538 (condition-case nil
15539 (progn
15540 (org-back-to-heading t)
15541 (outline-flag-region
15542 (max (point-min) (1- (point)))
15543 (save-excursion
15544 (if (re-search-forward
15545 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
15546 (match-beginning 1)
15547 (point-max)))
15548 nil))
15549 (error nil))))
15551 (defun org-make-options-regexp (kwds &optional extra)
15552 "Make a regular expression for keyword lines."
15553 (concat
15555 "#?[ \t]*\\+\\("
15556 (mapconcat 'regexp-quote kwds "\\|")
15557 (if extra (concat "\\|" extra))
15558 "\\):[ \t]*"
15559 "\\(.+\\)"))
15561 ;; Make isearch reveal the necessary context
15562 (defun org-isearch-end ()
15563 "Reveal context after isearch exits."
15564 (when isearch-success ; only if search was successful
15565 (if (featurep 'xemacs)
15566 ;; Under XEmacs, the hook is run in the correct place,
15567 ;; we directly show the context.
15568 (org-show-context 'isearch)
15569 ;; In Emacs the hook runs *before* restoring the overlays.
15570 ;; So we have to use a one-time post-command-hook to do this.
15571 ;; (Emacs 22 has a special variable, see function `org-mode')
15572 (unless (and (boundp 'isearch-mode-end-hook-quit)
15573 isearch-mode-end-hook-quit)
15574 ;; Only when the isearch was not quitted.
15575 (org-add-hook 'post-command-hook 'org-isearch-post-command
15576 'append 'local)))))
15578 (defun org-isearch-post-command ()
15579 "Remove self from hook, and show context."
15580 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
15581 (org-show-context 'isearch))
15584 ;;;; Integration with and fixes for other packages
15586 ;;; Imenu support
15588 (defvar org-imenu-markers nil
15589 "All markers currently used by Imenu.")
15590 (make-variable-buffer-local 'org-imenu-markers)
15592 (defun org-imenu-new-marker (&optional pos)
15593 "Return a new marker for use by Imenu, and remember the marker."
15594 (let ((m (make-marker)))
15595 (move-marker m (or pos (point)))
15596 (push m org-imenu-markers)
15599 (defun org-imenu-get-tree ()
15600 "Produce the index for Imenu."
15601 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
15602 (setq org-imenu-markers nil)
15603 (let* ((n org-imenu-depth)
15604 (re (concat "^" outline-regexp))
15605 (subs (make-vector (1+ n) nil))
15606 (last-level 0)
15607 m level head)
15608 (save-excursion
15609 (save-restriction
15610 (widen)
15611 (goto-char (point-max))
15612 (while (re-search-backward re nil t)
15613 (setq level (org-reduced-level (funcall outline-level)))
15614 (when (<= level n)
15615 (looking-at org-complex-heading-regexp)
15616 (setq head (org-link-display-format
15617 (org-match-string-no-properties 4))
15618 m (org-imenu-new-marker))
15619 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
15620 (if (>= level last-level)
15621 (push (cons head m) (aref subs level))
15622 (push (cons head (aref subs (1+ level))) (aref subs level))
15623 (loop for i from (1+ level) to n do (aset subs i nil)))
15624 (setq last-level level)))))
15625 (aref subs 1)))
15627 (eval-after-load "imenu"
15628 '(progn
15629 (add-hook 'imenu-after-jump-hook
15630 (lambda ()
15631 (if (eq major-mode 'org-mode)
15632 (org-show-context 'org-goto))))))
15634 (defun org-link-display-format (link)
15635 "Replace a link with either the description, or the link target
15636 if no description is present"
15637 (save-match-data
15638 (if (string-match org-bracket-link-analytic-regexp link)
15639 (replace-match (or (match-string 5 link)
15640 (concat (match-string 1 link)
15641 (match-string 3 link)))
15642 nil nil link)
15643 link)))
15645 ;; Speedbar support
15647 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
15648 "Overlay marking the agenda restriction line in speedbar.")
15649 (org-overlay-put org-speedbar-restriction-lock-overlay
15650 'face 'org-agenda-restriction-lock)
15651 (org-overlay-put org-speedbar-restriction-lock-overlay
15652 'help-echo "Agendas are currently limited to this item.")
15653 (org-detach-overlay org-speedbar-restriction-lock-overlay)
15655 (defun org-speedbar-set-agenda-restriction ()
15656 "Restrict future agenda commands to the location at point in speedbar.
15657 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
15658 (interactive)
15659 (require 'org-agenda)
15660 (let (p m tp np dir txt)
15661 (cond
15662 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15663 'org-imenu t))
15664 (setq m (get-text-property p 'org-imenu-marker))
15665 (save-excursion
15666 (save-restriction
15667 (set-buffer (marker-buffer m))
15668 (goto-char m)
15669 (org-agenda-set-restriction-lock 'subtree))))
15670 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15671 'speedbar-function 'speedbar-find-file))
15672 (setq tp (previous-single-property-change
15673 (1+ p) 'speedbar-function)
15674 np (next-single-property-change
15675 tp 'speedbar-function)
15676 dir (speedbar-line-directory)
15677 txt (buffer-substring-no-properties (or tp (point-min))
15678 (or np (point-max))))
15679 (save-excursion
15680 (save-restriction
15681 (set-buffer (find-file-noselect
15682 (let ((default-directory dir))
15683 (expand-file-name txt))))
15684 (unless (org-mode-p)
15685 (error "Cannot restrict to non-Org-mode file"))
15686 (org-agenda-set-restriction-lock 'file))))
15687 (t (error "Don't know how to restrict Org-mode's agenda")))
15688 (org-move-overlay org-speedbar-restriction-lock-overlay
15689 (point-at-bol) (point-at-eol))
15690 (setq current-prefix-arg nil)
15691 (org-agenda-maybe-redo)))
15693 (eval-after-load "speedbar"
15694 '(progn
15695 (speedbar-add-supported-extension ".org")
15696 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
15697 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
15698 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
15699 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15700 (add-hook 'speedbar-visiting-tag-hook
15701 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
15704 ;;; Fixes and Hacks for problems with other packages
15706 ;; Make flyspell not check words in links, to not mess up our keymap
15707 (defun org-mode-flyspell-verify ()
15708 "Don't let flyspell put overlays at active buttons."
15709 (not (get-text-property (point) 'keymap)))
15711 ;; Make `bookmark-jump' show the jump location if it was hidden.
15712 (eval-after-load "bookmark"
15713 '(if (boundp 'bookmark-after-jump-hook)
15714 ;; We can use the hook
15715 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
15716 ;; Hook not available, use advice
15717 (defadvice bookmark-jump (after org-make-visible activate)
15718 "Make the position visible."
15719 (org-bookmark-jump-unhide))))
15721 ;; Make sure saveplace show the location if it was hidden
15722 (eval-after-load "saveplace"
15723 '(defadvice save-place-find-file-hook (after org-make-visible activate)
15724 "Make the position visible."
15725 (org-bookmark-jump-unhide)))
15727 (defun org-bookmark-jump-unhide ()
15728 "Unhide the current position, to show the bookmark location."
15729 (and (org-mode-p)
15730 (or (org-invisible-p)
15731 (save-excursion (goto-char (max (point-min) (1- (point))))
15732 (org-invisible-p)))
15733 (org-show-context 'bookmark-jump)))
15735 ;; Make session.el ignore our circular variable
15736 (eval-after-load "session"
15737 '(add-to-list 'session-globals-exclude 'org-mark-ring))
15739 ;;;; Experimental code
15741 (defun org-closed-in-range ()
15742 "Sparse tree of items closed in a certain time range.
15743 Still experimental, may disappear in the future."
15744 (interactive)
15745 ;; Get the time interval from the user.
15746 (let* ((time1 (time-to-seconds
15747 (org-read-date nil 'to-time nil "Starting date: ")))
15748 (time2 (time-to-seconds
15749 (org-read-date nil 'to-time nil "End date:")))
15750 ;; callback function
15751 (callback (lambda ()
15752 (let ((time
15753 (time-to-seconds
15754 (apply 'encode-time
15755 (org-parse-time-string
15756 (match-string 1))))))
15757 ;; check if time in interval
15758 (and (>= time time1) (<= time time2))))))
15759 ;; make tree, check each match with the callback
15760 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
15763 ;;;; Finish up
15765 (provide 'org)
15767 (run-hooks 'org-load-hook)
15769 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
15771 ;;; org.el ends here