Declare a function.
[org-mode.git] / lisp / org.el
blob53fa1c1fb78ea3624400f1ae1df353cabb4c3c50
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009
4 ;; Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;; Version: 6.27trans
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum)
76 (require 'calendar))
77 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
78 ;; the file noutline.el being loaded.
79 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
80 ;; We require noutline, which might be provided in outline.el
81 (require 'outline) (require 'noutline)
82 ;; Other stuff we need.
83 (require 'time-date)
84 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
85 (require 'easymenu)
87 (require 'org-macs)
88 (require 'org-compat)
89 (require 'org-faces)
90 (require 'org-list)
91 (require 'org-src)
92 (require 'org-footnote)
94 ;;;; Customization variables
96 ;;; Version
98 (defconst org-version "6.27trans"
99 "The version number of the file org.el.")
101 (defun org-version (&optional here)
102 "Show the org-mode version in the echo area.
103 With prefix arg HERE, insert it at point."
104 (interactive "P")
105 (let ((version (format "Org-mode version %s" org-version)))
106 (message version)
107 (if here
108 (insert version))))
110 ;;; Compatibility constants
112 ;;; The custom variables
114 (defgroup org nil
115 "Outline-based notes management and organizer."
116 :tag "Org"
117 :group 'outlines
118 :group 'hypermedia
119 :group 'calendar)
121 (defcustom org-load-hook nil
122 "Hook that is run after org.el has been loaded."
123 :group 'org
124 :type 'hook)
126 (defvar org-modules) ; defined below
127 (defvar org-modules-loaded nil
128 "Have the modules been loaded already?")
130 (defun org-load-modules-maybe (&optional force)
131 "Load all extensions listed in `org-modules'."
132 (when (or force (not org-modules-loaded))
133 (mapc (lambda (ext)
134 (condition-case nil (require ext)
135 (error (message "Problems while trying to load feature `%s'" ext))))
136 org-modules)
137 (setq org-modules-loaded t)))
139 (defun org-set-modules (var value)
140 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
141 (set var value)
142 (when (featurep 'org)
143 (org-load-modules-maybe 'force)))
145 (when (org-bound-and-true-p org-modules)
146 (let ((a (member 'org-infojs org-modules)))
147 (and a (setcar a 'org-jsinfo))))
149 (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)
150 "Modules that should always be loaded together with org.el.
151 If a description starts with <C>, the file is not part of Emacs
152 and loading it will require that you have downloaded and properly installed
153 the org-mode distribution.
155 You can also use this system to load external packages (i.e. neither Org
156 core modules, not modules from the CONTRIB directory). Just add symbols
157 to the end of the list. If the package is called org-xyz.el, then you need
158 to add the symbol `xyz', and the package must have a call to
160 (provide 'org-xyz)"
161 :group 'org
162 :set 'org-set-modules
163 :type
164 '(set :greedy t
165 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
166 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
167 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
168 (const :tag " id: Global IDs for identifying entries" org-id)
169 (const :tag " info: Links to Info nodes" org-info)
170 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
171 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
172 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
173 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
174 (const :tag " mew Links to Mew folders/messages" org-mew)
175 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
176 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
177 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
178 (const :tag " vm: Links to VM folders/messages" org-vm)
179 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
180 (const :tag " w3m: Special cut/paste from w3m to Org." org-w3m)
181 (const :tag " mouse: Additional mouse support" org-mouse)
183 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
184 (const :tag "C annotation-helper: Call Remember directly from Browser (OBSOLETE, use org-protocol)" org-annotation-helper)
185 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
186 (const :tag "C browser-url: Store link, directly from Browser (OBSOLETE, use org-protocol)" org-browser-url)
187 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
188 (const :tag "C collector: Collect properties into tables" org-collector)
189 (const :tag "C depend: TODO dependencies for Org-mode (PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
190 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
191 (const :tag "C eval: Include command output as text" org-eval)
192 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
193 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
194 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
195 (const :tag "C exp-blocks: Pre-process blocks for export" org-exp-blocks)
196 (const :tag "C interactive-query: Interactive modification of tags query (PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
197 (const :tag "C jira Add a jira:ticket protocol to Org" org-jira)
198 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
199 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
200 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
201 (const :tag "C mtags: Support for muse-like tags" org-mtags)
202 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
203 (const :tag "C R: Computation using the R language" org-R)
204 (const :tag "C registry: A registry for Org links" org-registry)
205 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
206 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
207 (const :tag "C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
208 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
209 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
210 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
212 (defcustom org-support-shift-select nil
213 "Non-nil means, make shift-cursor commands select text when possible.
215 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
216 selecting a region, or enlarge thusly regions started in this way.
217 In Org-mode, in special contexts, these same keys are used for other
218 purposes, important enough to compete with shift selection. Org tries
219 to balance these needs by supporting `shift-select-mode' outside these
220 special contexts, under control of this variable.
222 The default of this variable is nil, to avoid confusing behavior. Shifted
223 cursor keys will then execute Org commands in the following contexts:
224 - on a headline, changing TODO state (left/right) and priority (up/down)
225 - on a time stamp, changing the time
226 - in a plain list item, changing the bullet type
227 - in a property definition line, switching between allowed values
228 - in the BEGIN line of a clock table (changing the time block).
229 Outside these contexts, the commands will throw an error.
231 When this variable is t and the cursor is not in a special context,
232 Org-mode will support shift-selection for making and enlarging regions.
233 To make this more effective, the bullet cycling will no longer happen
234 anywhere in an item line, but only if the cursor is exactly on the bullet.
236 If you set this variable to the symbol `always', then the keys
237 will not be special in headlines, property lines, and item lines, to make
238 shift selection work there as well. If this is what you want, you can
239 use the following alternative commands: `C-c C-t' and `C-c ,' to
240 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
241 TODO sets, `C-c -' to cycle item bullet types, and properties can be
242 edited by hand or in column view.
244 However, when the cursor is on a timestamp, shift-cursor commands
245 will still edit the time stamp - this is just too good to give up.
247 XEmacs user should have this variable set to nil, because shift-select-mode
248 is Emacs 23 only."
249 :group 'org
250 :type '(choice
251 (const :tag "Never" nil)
252 (const :tag "When outside special context" t)
253 (const :tag "Everywhere except timestamps" always)))
255 (defgroup org-startup nil
256 "Options concerning startup of Org-mode."
257 :tag "Org Startup"
258 :group 'org)
260 (defcustom org-startup-folded t
261 "Non-nil means, entering Org-mode will switch to OVERVIEW.
262 This can also be configured on a per-file basis by adding one of
263 the following lines anywhere in the buffer:
265 #+STARTUP: fold
266 #+STARTUP: nofold
267 #+STARTUP: content"
268 :group 'org-startup
269 :type '(choice
270 (const :tag "nofold: show all" nil)
271 (const :tag "fold: overview" t)
272 (const :tag "content: all headlines" content)))
274 (defcustom org-startup-truncated t
275 "Non-nil means, entering Org-mode will set `truncate-lines'.
276 This is useful since some lines containing links can be very long and
277 uninteresting. Also tables look terrible when wrapped."
278 :group 'org-startup
279 :type 'boolean)
281 (defcustom org-startup-align-all-tables nil
282 "Non-nil means, align all tables when visiting a file.
283 This is useful when the column width in tables is forced with <N> cookies
284 in table fields. Such tables will look correct only after the first re-align.
285 This can also be configured on a per-file basis by adding one of
286 the following lines anywhere in the buffer:
287 #+STARTUP: align
288 #+STARTUP: noalign"
289 :group 'org-startup
290 :type 'boolean)
292 (defcustom org-insert-mode-line-in-empty-file nil
293 "Non-nil means insert the first line setting Org-mode in empty files.
294 When the function `org-mode' is called interactively in an empty file, this
295 normally means that the file name does not automatically trigger Org-mode.
296 To ensure that the file will always be in Org-mode in the future, a
297 line enforcing Org-mode will be inserted into the buffer, if this option
298 has been set."
299 :group 'org-startup
300 :type 'boolean)
302 (defcustom org-replace-disputed-keys nil
303 "Non-nil means use alternative key bindings for some keys.
304 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
305 These keys are also used by other packages like shift-selection-mode'
306 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
307 If you want to use Org-mode together with one of these other modes,
308 or more generally if you would like to move some Org-mode commands to
309 other keys, set this variable and configure the keys with the variable
310 `org-disputed-keys'.
312 This option is only relevant at load-time of Org-mode, and must be set
313 *before* org.el is loaded. Changing it requires a restart of Emacs to
314 become effective."
315 :group 'org-startup
316 :type 'boolean)
318 (defcustom org-use-extra-keys nil
319 "Non-nil means use extra key sequence definitions for certain
320 commands. This happens automatically if you run XEmacs or if
321 window-system is nil. This variable lets you do the same
322 manually. You must set it before loading org.
324 Example: on Carbon Emacs 22 running graphically, with an external
325 keyboard on a Powerbook, the default way of setting M-left might
326 not work for either Alt or ESC. Setting this variable will make
327 it work for ESC."
328 :group 'org-startup
329 :type 'boolean)
331 (if (fboundp 'defvaralias)
332 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
334 (defcustom org-disputed-keys
335 '(([(shift up)] . [(meta p)])
336 ([(shift down)] . [(meta n)])
337 ([(shift left)] . [(meta -)])
338 ([(shift right)] . [(meta +)])
339 ([(control shift right)] . [(meta shift +)])
340 ([(control shift left)] . [(meta shift -)]))
341 "Keys for which Org-mode and other modes compete.
342 This is an alist, cars are the default keys, second element specifies
343 the alternative to use when `org-replace-disputed-keys' is t.
345 Keys can be specified in any syntax supported by `define-key'.
346 The value of this option takes effect only at Org-mode's startup,
347 therefore you'll have to restart Emacs to apply it after changing."
348 :group 'org-startup
349 :type 'alist)
351 (defun org-key (key)
352 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
353 Or return the original if not disputed."
354 (if org-replace-disputed-keys
355 (let* ((nkey (key-description key))
356 (x (org-find-if (lambda (x)
357 (equal (key-description (car x)) nkey))
358 org-disputed-keys)))
359 (if x (cdr x) key))
360 key))
362 (defun org-find-if (predicate seq)
363 (catch 'exit
364 (while seq
365 (if (funcall predicate (car seq))
366 (throw 'exit (car seq))
367 (pop seq)))))
369 (defun org-defkey (keymap key def)
370 "Define a key, possibly translated, as returned by `org-key'."
371 (define-key keymap (org-key key) def))
373 (defcustom org-ellipsis nil
374 "The ellipsis to use in the Org-mode outline.
375 When nil, just use the standard three dots. When a string, use that instead,
376 When a face, use the standard 3 dots, but with the specified face.
377 The change affects only Org-mode (which will then use its own display table).
378 Changing this requires executing `M-x org-mode' in a buffer to become
379 effective."
380 :group 'org-startup
381 :type '(choice (const :tag "Default" nil)
382 (face :tag "Face" :value org-warning)
383 (string :tag "String" :value "...#")))
385 (defvar org-display-table nil
386 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
388 (defgroup org-keywords nil
389 "Keywords in Org-mode."
390 :tag "Org Keywords"
391 :group 'org)
393 (defcustom org-deadline-string "DEADLINE:"
394 "String to mark deadline entries.
395 A deadline is this string, followed by a time stamp. Should be a word,
396 terminated by a colon. You can insert a schedule keyword and
397 a timestamp with \\[org-deadline].
398 Changes become only effective after restarting Emacs."
399 :group 'org-keywords
400 :type 'string)
402 (defcustom org-scheduled-string "SCHEDULED:"
403 "String to mark scheduled TODO entries.
404 A schedule is this string, followed by a time stamp. Should be a word,
405 terminated by a colon. You can insert a schedule keyword and
406 a timestamp with \\[org-schedule].
407 Changes become only effective after restarting Emacs."
408 :group 'org-keywords
409 :type 'string)
411 (defcustom org-closed-string "CLOSED:"
412 "String used as the prefix for timestamps logging closing a TODO entry."
413 :group 'org-keywords
414 :type 'string)
416 (defcustom org-clock-string "CLOCK:"
417 "String used as prefix for timestamps clocking work hours on an item."
418 :group 'org-keywords
419 :type 'string)
421 (defcustom org-comment-string "COMMENT"
422 "Entries starting with this keyword will never be exported.
423 An entry can be toggled between COMMENT and normal with
424 \\[org-toggle-comment].
425 Changes become only effective after restarting Emacs."
426 :group 'org-keywords
427 :type 'string)
429 (defcustom org-quote-string "QUOTE"
430 "Entries starting with this keyword will be exported in fixed-width font.
431 Quoting applies only to the text in the entry following the headline, and does
432 not extend beyond the next headline, even if that is lower level.
433 An entry can be toggled between QUOTE and normal with
434 \\[org-toggle-fixed-width-section]."
435 :group 'org-keywords
436 :type 'string)
438 (defconst org-repeat-re
439 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
440 "Regular expression for specifying repeated events.
441 After a match, group 1 contains the repeat expression.")
443 (defgroup org-structure nil
444 "Options concerning the general structure of Org-mode files."
445 :tag "Org Structure"
446 :group 'org)
448 (defgroup org-reveal-location nil
449 "Options about how to make context of a location visible."
450 :tag "Org Reveal Location"
451 :group 'org-structure)
453 (defconst org-context-choice
454 '(choice
455 (const :tag "Always" t)
456 (const :tag "Never" nil)
457 (repeat :greedy t :tag "Individual contexts"
458 (cons
459 (choice :tag "Context"
460 (const agenda)
461 (const org-goto)
462 (const occur-tree)
463 (const tags-tree)
464 (const link-search)
465 (const mark-goto)
466 (const bookmark-jump)
467 (const isearch)
468 (const default))
469 (boolean))))
470 "Contexts for the reveal options.")
472 (defcustom org-show-hierarchy-above '((default . t))
473 "Non-nil means, show full hierarchy when revealing a location.
474 Org-mode often shows locations in an org-mode file which might have
475 been invisible before. When this is set, the hierarchy of headings
476 above the exposed location is shown.
477 Turning this off for example for sparse trees makes them very compact.
478 Instead of t, this can also be an alist specifying this option for different
479 contexts. Valid contexts are
480 agenda when exposing an entry from the agenda
481 org-goto when using the command `org-goto' on key C-c C-j
482 occur-tree when using the command `org-occur' on key C-c /
483 tags-tree when constructing a sparse tree based on tags matches
484 link-search when exposing search matches associated with a link
485 mark-goto when exposing the jump goal of a mark
486 bookmark-jump when exposing a bookmark location
487 isearch when exiting from an incremental search
488 default default for all contexts not set explicitly"
489 :group 'org-reveal-location
490 :type org-context-choice)
492 (defcustom org-show-following-heading '((default . nil))
493 "Non-nil means, show following heading when revealing a location.
494 Org-mode often shows locations in an org-mode file which might have
495 been invisible before. When this is set, the heading following the
496 match is shown.
497 Turning this off for example for sparse trees makes them very compact,
498 but makes it harder to edit the location of the match. In such a case,
499 use the command \\[org-reveal] to show more context.
500 Instead of t, this can also be an alist specifying this option for different
501 contexts. See `org-show-hierarchy-above' for valid contexts."
502 :group 'org-reveal-location
503 :type org-context-choice)
505 (defcustom org-show-siblings '((default . nil) (isearch t))
506 "Non-nil means, show all sibling heading when revealing a location.
507 Org-mode often shows locations in an org-mode file which might have
508 been invisible before. When this is set, the sibling of the current entry
509 heading are all made visible. If `org-show-hierarchy-above' is t,
510 the same happens on each level of the hierarchy above the current entry.
512 By default this is on for the isearch context, off for all other contexts.
513 Turning this off for example for sparse trees makes them very compact,
514 but makes it harder to edit the location of the match. In such a case,
515 use the command \\[org-reveal] to show more context.
516 Instead of t, this can also be an alist specifying this option for different
517 contexts. See `org-show-hierarchy-above' for valid contexts."
518 :group 'org-reveal-location
519 :type org-context-choice)
521 (defcustom org-show-entry-below '((default . nil))
522 "Non-nil means, show the entry below a headline when revealing a location.
523 Org-mode often shows locations in an org-mode file which might have
524 been invisible before. When this is set, the text below the headline that is
525 exposed is also shown.
527 By default this is off for all contexts.
528 Instead of t, this can also be an alist specifying this option for different
529 contexts. See `org-show-hierarchy-above' for valid contexts."
530 :group 'org-reveal-location
531 :type org-context-choice)
533 (defcustom org-indirect-buffer-display 'other-window
534 "How should indirect tree buffers be displayed?
535 This applies to indirect buffers created with the commands
536 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
537 Valid values are:
538 current-window Display in the current window
539 other-window Just display in another window.
540 dedicated-frame Create one new frame, and re-use it each time.
541 new-frame Make a new frame each time. Note that in this case
542 previously-made indirect buffers are kept, and you need to
543 kill these buffers yourself."
544 :group 'org-structure
545 :group 'org-agenda-windows
546 :type '(choice
547 (const :tag "In current window" current-window)
548 (const :tag "In current frame, other window" other-window)
549 (const :tag "Each time a new frame" new-frame)
550 (const :tag "One dedicated frame" dedicated-frame)))
552 (defgroup org-cycle nil
553 "Options concerning visibility cycling in Org-mode."
554 :tag "Org Cycle"
555 :group 'org-structure)
557 (defcustom org-cycle-max-level nil
558 "Maximum level which should still be subject to visibility cycling.
559 Levels higher than this will, for cycling, be treated as text, not a headline.
560 When `org-odd-levels-only' is set, a value of N in this variable actually
561 means 2N-1 stars as the limiting headline.
562 When nil, cycle all levels.
563 Note that the limiting level of cycling is also influenced by
564 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
565 `org-inlinetask-min-level' is, cycling will be limited to levels one less
566 than its value."
567 :group 'org-cycle
568 :type '(choice
569 (const :tag "No limit" nil)
570 (integer :tag "Maximum level")))
572 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
573 "Names of drawers. Drawers are not opened by cycling on the headline above.
574 Drawers only open with a TAB on the drawer line itself. A drawer looks like
575 this:
576 :DRAWERNAME:
577 .....
578 :END:
579 The drawer \"PROPERTIES\" is special for capturing properties through
580 the property API.
582 Drawers can be defined on the per-file basis with a line like:
584 #+DRAWERS: HIDDEN STATE PROPERTIES"
585 :group 'org-structure
586 :group 'org-cycle
587 :type '(repeat (string :tag "Drawer Name")))
589 (defcustom org-hide-block-startup nil
590 "Non-nil means, , entering Org-mode will fold all blocks.
591 This can also be set in on a per-file basis with
593 #+STARTUP: hideblocks
594 #+STARTUP: showblocks"
595 :group 'org-startup
596 :group 'org-cycle
597 :type 'boolean)
599 (defcustom org-cycle-global-at-bob nil
600 "Cycle globally if cursor is at beginning of buffer and not at a headline.
601 This makes it possible to do global cycling without having to use S-TAB or
602 C-u TAB. For this special case to work, the first line of the buffer
603 must not be a headline - it may be empty or some other text. When used in
604 this way, `org-cycle-hook' is disables temporarily, to make sure the
605 cursor stays at the beginning of the buffer.
606 When this option is nil, don't do anything special at the beginning
607 of the buffer."
608 :group 'org-cycle
609 :type 'boolean)
611 (defcustom org-cycle-emulate-tab t
612 "Where should `org-cycle' emulate TAB.
613 nil Never
614 white Only in completely white lines
615 whitestart Only at the beginning of lines, before the first non-white char
616 t Everywhere except in headlines
617 exc-hl-bol Everywhere except at the start of a headline
618 If TAB is used in a place where it does not emulate TAB, the current subtree
619 visibility is cycled."
620 :group 'org-cycle
621 :type '(choice (const :tag "Never" nil)
622 (const :tag "Only in completely white lines" white)
623 (const :tag "Before first char in a line" whitestart)
624 (const :tag "Everywhere except in headlines" t)
625 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
628 (defcustom org-cycle-separator-lines 2
629 "Number of empty lines needed to keep an empty line between collapsed trees.
630 If you leave an empty line between the end of a subtree and the following
631 headline, this empty line is hidden when the subtree is folded.
632 Org-mode will leave (exactly) one empty line visible if the number of
633 empty lines is equal or larger to the number given in this variable.
634 So the default 2 means, at least 2 empty lines after the end of a subtree
635 are needed to produce free space between a collapsed subtree and the
636 following headline.
638 Special case: when 0, never leave empty lines in collapsed view."
639 :group 'org-cycle
640 :type 'integer)
641 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
643 (defcustom org-pre-cycle-hook nil
644 "Hook that is run before visibility cycling is happening.
645 The function(s) in this hook must accept a single argument which indicates
646 the new state that will be set right after running this hook. The
647 argument is a symbol. Before a global state change, it can have the values
648 `overview', `content', or `all'. Before a local state change, it can have
649 the values `folded', `children', or `subtree'."
650 :group 'org-cycle
651 :type 'hook)
653 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
654 org-cycle-hide-drawers
655 org-cycle-show-empty-lines
656 org-optimize-window-after-visibility-change)
657 "Hook that is run after `org-cycle' has changed the buffer visibility.
658 The function(s) in this hook must accept a single argument which indicates
659 the new state that was set by the most recent `org-cycle' command. The
660 argument is a symbol. After a global state change, it can have the values
661 `overview', `content', or `all'. After a local state change, it can have
662 the values `folded', `children', or `subtree'."
663 :group 'org-cycle
664 :type 'hook)
666 (defgroup org-edit-structure nil
667 "Options concerning structure editing in Org-mode."
668 :tag "Org Edit Structure"
669 :group 'org-structure)
671 (defcustom org-odd-levels-only nil
672 "Non-nil means, skip even levels and only use odd levels for the outline.
673 This has the effect that two stars are being added/taken away in
674 promotion/demotion commands. It also influences how levels are
675 handled by the exporters.
676 Changing it requires restart of `font-lock-mode' to become effective
677 for fontification also in regions already fontified.
678 You may also set this on a per-file basis by adding one of the following
679 lines to the buffer:
681 #+STARTUP: odd
682 #+STARTUP: oddeven"
683 :group 'org-edit-structure
684 :group 'org-font-lock
685 :type 'boolean)
687 (defcustom org-adapt-indentation t
688 "Non-nil means, adapt indentation when promoting and demoting.
689 When this is set and the *entire* text in an entry is indented, the
690 indentation is increased by one space in a demotion command, and
691 decreased by one in a promotion command. If any line in the entry
692 body starts at column 0, indentation is not changed at all.
694 This variable also influences how property drawers and planning
695 information is inserted. When t, these lines drawers will be inserted
696 indented. When nil, they will not be indented."
697 :group 'org-edit-structure
698 :type 'boolean)
700 (defcustom org-special-ctrl-a/e nil
701 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
703 When t, `C-a' will bring back the cursor to the beginning of the
704 headline text, i.e. after the stars and after a possible TODO keyword.
705 In an item, this will be the position after the bullet.
706 When the cursor is already at that position, another `C-a' will bring
707 it to the beginning of the line.
709 `C-e' will jump to the end of the headline, ignoring the presence of tags
710 in the headline. A second `C-e' will then jump to the true end of the
711 line, after any tags.
713 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
714 and only a directly following, identical keypress will bring the cursor
715 to the special positions.
717 This may also be a cons cell where the behavior for `C-a' and `C-e' is
718 set separately."
719 :group 'org-edit-structure
720 :type '(choice
721 (const :tag "off" nil)
722 (const :tag "after stars/bullet and before tags first" t)
723 (const :tag "true line boundary first" reversed)
724 (cons :tag "Set C-a and C-e separately"
725 (choice :tag "Special C-a"
726 (const :tag "off" nil)
727 (const :tag "after stars/bullet first" t)
728 (const :tag "before stars/bullet first" reversed))
729 (choice :tag "Special C-e"
730 (const :tag "off" nil)
731 (const :tag "before tags first" t)
732 (const :tag "after tags first" reversed)))))
733 (if (fboundp 'defvaralias)
734 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
736 (defcustom org-special-ctrl-k nil
737 "Non-nil means `C-k' will behave specially in headlines.
738 When nil, `C-k' will call the default `kill-line' command.
739 When t, the following will happen while the cursor is in the headline:
741 - When the cursor is at the beginning of a headline, kill the entire
742 line and possible the folded subtree below the line.
743 - When in the middle of the headline text, kill the headline up to the tags.
744 - When after the headline text, kill the tags."
745 :group 'org-edit-structure
746 :type 'boolean)
748 (defcustom org-yank-folded-subtrees t
749 "Non-nil means, when yanking subtrees, fold them.
750 If the kill is a single subtree, or a sequence of subtrees, i.e. if
751 it starts with a heading and all other headings in it are either children
752 or siblings, then fold all the subtrees. However, do this only if no
753 text after the yank would be swallowed into a folded tree by this action."
754 :group 'org-edit-structure
755 :type 'boolean)
757 (defcustom org-yank-adjusted-subtrees nil
758 "Non-nil means, when yanking subtrees, adjust the level.
759 With this setting, `org-paste-subtree' is used to insert the subtree, see
760 this function for details."
761 :group 'org-edit-structure
762 :type 'boolean)
764 (defcustom org-M-RET-may-split-line '((default . t))
765 "Non-nil means, M-RET will split the line at the cursor position.
766 When nil, it will go to the end of the line before making a
767 new line.
768 You may also set this option in a different way for different
769 contexts. Valid contexts are:
771 headline when creating a new headline
772 item when creating a new item
773 table in a table field
774 default the value to be used for all contexts not explicitly
775 customized"
776 :group 'org-structure
777 :group 'org-table
778 :type '(choice
779 (const :tag "Always" t)
780 (const :tag "Never" nil)
781 (repeat :greedy t :tag "Individual contexts"
782 (cons
783 (choice :tag "Context"
784 (const headline)
785 (const item)
786 (const table)
787 (const default))
788 (boolean)))))
791 (defcustom org-insert-heading-respect-content nil
792 "Non-nil means, insert new headings after the current subtree.
793 When nil, the new heading is created directly after the current line.
794 The commands \\[org-insert-heading-respect-content] and
795 \\[org-insert-todo-heading-respect-content] turn this variable on
796 for the duration of the command."
797 :group 'org-structure
798 :type 'boolean)
800 (defcustom org-blank-before-new-entry '((heading . auto)
801 (plain-list-item . auto))
802 "Should `org-insert-heading' leave a blank line before new heading/item?
803 The value is an alist, with `heading' and `plain-list-item' as car,
804 and a boolean flag as cdr. For plain lists, if the variable
805 `org-empty-line-terminates-plain-lists' is set, the setting here
806 is ignored and no empty line is inserted, to keep the list in tact."
807 :group 'org-edit-structure
808 :type '(list
809 (cons (const heading)
810 (choice (const :tag "Never" nil)
811 (const :tag "Always" t)
812 (const :tag "Auto" auto)))
813 (cons (const plain-list-item)
814 (choice (const :tag "Never" nil)
815 (const :tag "Always" t)
816 (const :tag "Auto" auto)))))
818 (defcustom org-insert-heading-hook nil
819 "Hook being run after inserting a new heading."
820 :group 'org-edit-structure
821 :type 'hook)
823 (defcustom org-enable-fixed-width-editor t
824 "Non-nil means, lines starting with \":\" are treated as fixed-width.
825 This currently only means, they are never auto-wrapped.
826 When nil, such lines will be treated like ordinary lines.
827 See also the QUOTE keyword."
828 :group 'org-edit-structure
829 :type 'boolean)
832 (defcustom org-goto-auto-isearch t
833 "Non-nil means, typing characters in org-goto starts incremental search."
834 :group 'org-edit-structure
835 :type 'boolean)
837 (defgroup org-sparse-trees nil
838 "Options concerning sparse trees in Org-mode."
839 :tag "Org Sparse Trees"
840 :group 'org-structure)
842 (defcustom org-highlight-sparse-tree-matches t
843 "Non-nil means, highlight all matches that define a sparse tree.
844 The highlights will automatically disappear the next time the buffer is
845 changed by an edit command."
846 :group 'org-sparse-trees
847 :type 'boolean)
849 (defcustom org-remove-highlights-with-change t
850 "Non-nil means, any change to the buffer will remove temporary highlights.
851 Such highlights are created by `org-occur' and `org-clock-display'.
852 When nil, `C-c C-c needs to be used to get rid of the highlights.
853 The highlights created by `org-preview-latex-fragment' always need
854 `C-c C-c' to be removed."
855 :group 'org-sparse-trees
856 :group 'org-time
857 :type 'boolean)
860 (defcustom org-occur-hook '(org-first-headline-recenter)
861 "Hook that is run after `org-occur' has constructed a sparse tree.
862 This can be used to recenter the window to show as much of the structure
863 as possible."
864 :group 'org-sparse-trees
865 :type 'hook)
867 (defgroup org-imenu-and-speedbar nil
868 "Options concerning imenu and speedbar in Org-mode."
869 :tag "Org Imenu and Speedbar"
870 :group 'org-structure)
872 (defcustom org-imenu-depth 2
873 "The maximum level for Imenu access to Org-mode headlines.
874 This also applied for speedbar access."
875 :group 'org-imenu-and-speedbar
876 :type 'integer)
878 (defgroup org-table nil
879 "Options concerning tables in Org-mode."
880 :tag "Org Table"
881 :group 'org)
883 (defcustom org-enable-table-editor 'optimized
884 "Non-nil means, lines starting with \"|\" are handled by the table editor.
885 When nil, such lines will be treated like ordinary lines.
887 When equal to the symbol `optimized', the table editor will be optimized to
888 do the following:
889 - Automatic overwrite mode in front of whitespace in table fields.
890 This makes the structure of the table stay in tact as long as the edited
891 field does not exceed the column width.
892 - Minimize the number of realigns. Normally, the table is aligned each time
893 TAB or RET are pressed to move to another field. With optimization this
894 happens only if changes to a field might have changed the column width.
895 Optimization requires replacing the functions `self-insert-command',
896 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
897 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
898 very good at guessing when a re-align will be necessary, but you can always
899 force one with \\[org-ctrl-c-ctrl-c].
901 If you would like to use the optimized version in Org-mode, but the
902 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
904 This variable can be used to turn on and off the table editor during a session,
905 but in order to toggle optimization, a restart is required.
907 See also the variable `org-table-auto-blank-field'."
908 :group 'org-table
909 :type '(choice
910 (const :tag "off" nil)
911 (const :tag "on" t)
912 (const :tag "on, optimized" optimized)))
914 (defcustom org-self-insert-cluster-for-undo t
915 "Non-nil means cluster self-insert commands for undo when possible.
916 If this is set, then, like in the Emacs command loop, 20 consequtive
917 characters will be undone together.
918 This is configurable, because there is some impact on typing performance."
919 :group 'org-table
920 :type 'boolean)
922 (defcustom org-table-tab-recognizes-table.el t
923 "Non-nil means, TAB will automatically notice a table.el table.
924 When it sees such a table, it moves point into it and - if necessary -
925 calls `table-recognize-table'."
926 :group 'org-table-editing
927 :type 'boolean)
929 (defgroup org-link nil
930 "Options concerning links in Org-mode."
931 :tag "Org Link"
932 :group 'org)
934 (defvar org-link-abbrev-alist-local nil
935 "Buffer-local version of `org-link-abbrev-alist', which see.
936 The value of this is taken from the #+LINK lines.")
937 (make-variable-buffer-local 'org-link-abbrev-alist-local)
939 (defcustom org-link-abbrev-alist nil
940 "Alist of link abbreviations.
941 The car of each element is a string, to be replaced at the start of a link.
942 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
943 links in Org-mode buffers can have an optional tag after a double colon, e.g.
945 [[linkkey:tag][description]]
947 The 'linkkey' must be a word word, starting with a letter, followed
948 by letters, numbers, '-' or '_'.
950 If REPLACE is a string, the tag will simply be appended to create the link.
951 If the string contains \"%s\", the tag will be inserted there. Alternatively,
952 the placeholder \"%h\" will cause a url-encoded version of the tag to
953 be inserted at that point (see the function `url-hexify-string').
955 REPLACE may also be a function that will be called with the tag as the
956 only argument to create the link, which should be returned as a string.
958 See the manual for examples."
959 :group 'org-link
960 :type '(repeat
961 (cons
962 (string :tag "Protocol")
963 (choice
964 (string :tag "Format")
965 (function)))))
967 (defcustom org-descriptive-links t
968 "Non-nil means, hide link part and only show description of bracket links.
969 Bracket links are like [[link][description]]. This variable sets the initial
970 state in new org-mode buffers. The setting can then be toggled on a
971 per-buffer basis from the Org->Hyperlinks menu."
972 :group 'org-link
973 :type 'boolean)
975 (defcustom org-link-file-path-type 'adaptive
976 "How the path name in file links should be stored.
977 Valid values are:
979 relative Relative to the current directory, i.e. the directory of the file
980 into which the link is being inserted.
981 absolute Absolute path, if possible with ~ for home directory.
982 noabbrev Absolute path, no abbreviation of home directory.
983 adaptive Use relative path for files in the current directory and sub-
984 directories of it. For other files, use an absolute path."
985 :group 'org-link
986 :type '(choice
987 (const relative)
988 (const absolute)
989 (const noabbrev)
990 (const adaptive)))
992 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
993 "Types of links that should be activated in Org-mode files.
994 This is a list of symbols, each leading to the activation of a certain link
995 type. In principle, it does not hurt to turn on most link types - there may
996 be a small gain when turning off unused link types. The types are:
998 bracket The recommended [[link][description]] or [[link]] links with hiding.
999 angular Links in angular brackets that may contain whitespace like
1000 <bbdb:Carsten Dominik>.
1001 plain Plain links in normal text, no whitespace, like http://google.com.
1002 radio Text that is matched by a radio target, see manual for details.
1003 tag Tag settings in a headline (link to tag search).
1004 date Time stamps (link to calendar).
1005 footnote Footnote labels.
1007 Changing this variable requires a restart of Emacs to become effective."
1008 :group 'org-link
1009 :type '(set :greedy t
1010 (const :tag "Double bracket links (new style)" bracket)
1011 (const :tag "Angular bracket links (old style)" angular)
1012 (const :tag "Plain text links" plain)
1013 (const :tag "Radio target matches" radio)
1014 (const :tag "Tags" tag)
1015 (const :tag "Timestamps" date)
1016 (const :tag "Footnotes" footnote)))
1018 (defcustom org-make-link-description-function nil
1019 "Function to use to generate link descriptions from links. If
1020 nil the link location will be used. This function must take two
1021 parameters; the first is the link and the second the description
1022 org-insert-link has generated, and should return the description
1023 to use."
1024 :group 'org-link
1025 :type 'function)
1027 (defgroup org-link-store nil
1028 "Options concerning storing links in Org-mode."
1029 :tag "Org Store Link"
1030 :group 'org-link)
1032 (defcustom org-email-link-description-format "Email %c: %.30s"
1033 "Format of the description part of a link to an email or usenet message.
1034 The following %-escapes will be replaced by corresponding information:
1036 %F full \"From\" field
1037 %f name, taken from \"From\" field, address if no name
1038 %T full \"To\" field
1039 %t first name in \"To\" field, address if no name
1040 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1041 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1042 %s subject
1043 %m message-id.
1045 You may use normal field width specification between the % and the letter.
1046 This is for example useful to limit the length of the subject.
1048 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1049 :group 'org-link-store
1050 :type 'string)
1052 (defcustom org-from-is-user-regexp
1053 (let (r1 r2)
1054 (when (and user-mail-address (not (string= user-mail-address "")))
1055 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1056 (when (and user-full-name (not (string= user-full-name "")))
1057 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1058 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1059 "Regexp matched against the \"From:\" header of an email or usenet message.
1060 It should match if the message is from the user him/herself."
1061 :group 'org-link-store
1062 :type 'regexp)
1064 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1065 "Non-nil means, storing a link to an Org file will use entry IDs.
1067 Note that before this variable is even considered, org-id must be loaded,
1068 to please customize `org-modules' and turn it on.
1070 The variable can have the following values:
1072 t Create an ID if needed to make a link to the current entry.
1074 create-if-interactive
1075 If `org-store-link' is called directly (interactively, as a user
1076 command), do create an ID to support the link. But when doing the
1077 job for remember, only use the ID if it already exists. The
1078 purpose of this setting is to avoid proliferation of unwanted
1079 IDs, just because you happen to be in an Org file when you
1080 call `org-remember' that automatically and preemptively
1081 creates a link. If you do want to get an ID link in a remember
1082 template to an entry not having an ID, create it first by
1083 explicitly creating a link to it, using `C-c C-l' first.
1085 use-existing
1086 Use existing ID, do not create one.
1088 nil Never use an ID to make a link, instead link using a text search for
1089 the headline text."
1090 :group 'org-link-store
1091 :type '(choice
1092 (const :tag "Create ID to make link" t)
1093 (const :tag "Create if storing link interactively"
1094 create-if-interactive)
1095 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1096 create-if-interactive-and-no-custom-id)
1097 (const :tag "Only use existing" use-existing)
1098 (const :tag "Do not use ID to create link" nil)))
1100 (defcustom org-context-in-file-links t
1101 "Non-nil means, file links from `org-store-link' contain context.
1102 A search string will be added to the file name with :: as separator and
1103 used to find the context when the link is activated by the command
1104 `org-open-at-point'.
1105 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1106 negates this setting for the duration of the command."
1107 :group 'org-link-store
1108 :type 'boolean)
1110 (defcustom org-keep-stored-link-after-insertion nil
1111 "Non-nil means, keep link in list for entire session.
1113 The command `org-store-link' adds a link pointing to the current
1114 location to an internal list. These links accumulate during a session.
1115 The command `org-insert-link' can be used to insert links into any
1116 Org-mode file (offering completion for all stored links). When this
1117 option is nil, every link which has been inserted once using \\[org-insert-link]
1118 will be removed from the list, to make completing the unused links
1119 more efficient."
1120 :group 'org-link-store
1121 :type 'boolean)
1123 (defgroup org-link-follow nil
1124 "Options concerning following links in Org-mode."
1125 :tag "Org Follow Link"
1126 :group 'org-link)
1128 (defcustom org-link-translation-function nil
1129 "Function to translate links with different syntax to Org syntax.
1130 This can be used to translate links created for example by the Planner
1131 or emacs-wiki packages to Org syntax.
1132 The function must accept two parameters, a TYPE containing the link
1133 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1134 which is everything after the link protocol. It should return a cons
1135 with possibly modified values of type and path.
1136 Org contains a function for this, so if you set this variable to
1137 `org-translate-link-from-planner', you should be able follow many
1138 links created by planner."
1139 :group 'org-link-follow
1140 :type 'function)
1142 (defcustom org-follow-link-hook nil
1143 "Hook that is run after a link has been followed."
1144 :group 'org-link-follow
1145 :type 'hook)
1147 (defcustom org-tab-follows-link nil
1148 "Non-nil means, on links TAB will follow the link.
1149 Needs to be set before org.el is loaded.
1150 This really should not be used, it does not make sense, and the
1151 implementation is bad."
1152 :group 'org-link-follow
1153 :type 'boolean)
1155 (defcustom org-return-follows-link nil
1156 "Non-nil means, on links RET will follow the link.
1157 Needs to be set before org.el is loaded."
1158 :group 'org-link-follow
1159 :type 'boolean)
1161 (defcustom org-mouse-1-follows-link
1162 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1163 "Non-nil means, mouse-1 on a link will follow the link.
1164 A longer mouse click will still set point. Does not work on XEmacs.
1165 Needs to be set before org.el is loaded."
1166 :group 'org-link-follow
1167 :type 'boolean)
1169 (defcustom org-mark-ring-length 4
1170 "Number of different positions to be recorded in the ring
1171 Changing this requires a restart of Emacs to work correctly."
1172 :group 'org-link-follow
1173 :type 'integer)
1175 (defcustom org-link-frame-setup
1176 '((vm . vm-visit-folder-other-frame)
1177 (gnus . gnus-other-frame)
1178 (file . find-file-other-window))
1179 "Setup the frame configuration for following links.
1180 When following a link with Emacs, it may often be useful to display
1181 this link in another window or frame. This variable can be used to
1182 set this up for the different types of links.
1183 For VM, use any of
1184 `vm-visit-folder'
1185 `vm-visit-folder-other-frame'
1186 For Gnus, use any of
1187 `gnus'
1188 `gnus-other-frame'
1189 `org-gnus-no-new-news'
1190 For FILE, use any of
1191 `find-file'
1192 `find-file-other-window'
1193 `find-file-other-frame'
1194 For the calendar, use the variable `calendar-setup'.
1195 For BBDB, it is currently only possible to display the matches in
1196 another window."
1197 :group 'org-link-follow
1198 :type '(list
1199 (cons (const vm)
1200 (choice
1201 (const vm-visit-folder)
1202 (const vm-visit-folder-other-window)
1203 (const vm-visit-folder-other-frame)))
1204 (cons (const gnus)
1205 (choice
1206 (const gnus)
1207 (const gnus-other-frame)
1208 (const org-gnus-no-new-news)))
1209 (cons (const file)
1210 (choice
1211 (const find-file)
1212 (const find-file-other-window)
1213 (const find-file-other-frame)))))
1215 (defcustom org-display-internal-link-with-indirect-buffer nil
1216 "Non-nil means, use indirect buffer to display infile links.
1217 Activating internal links (from one location in a file to another location
1218 in the same file) normally just jumps to the location. When the link is
1219 activated with a C-u prefix (or with mouse-3), the link is displayed in
1220 another window. When this option is set, the other window actually displays
1221 an indirect buffer clone of the current buffer, to avoid any visibility
1222 changes to the current buffer."
1223 :group 'org-link-follow
1224 :type 'boolean)
1226 (defcustom org-open-non-existing-files nil
1227 "Non-nil means, `org-open-file' will open non-existing files.
1228 When nil, an error will be generated."
1229 :group 'org-link-follow
1230 :type 'boolean)
1232 (defcustom org-open-directory-means-index-dot-org nil
1233 "Non-nil means, a link to a directory really means to index.org.
1234 When nil, following a directory link will run dired or open a finder/explorer
1235 window on that directory."
1236 :group 'org-link-follow
1237 :type 'boolean)
1239 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1240 "Function and arguments to call for following mailto links.
1241 This is a list with the first element being a lisp function, and the
1242 remaining elements being arguments to the function. In string arguments,
1243 %a will be replaced by the address, and %s will be replaced by the subject
1244 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1245 :group 'org-link-follow
1246 :type '(choice
1247 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1248 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1249 (const :tag "message-mail" (message-mail "%a" "%s"))
1250 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1252 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1253 "Non-nil means, ask for confirmation before executing shell links.
1254 Shell links can be dangerous: just think about a link
1256 [[shell:rm -rf ~/*][Google Search]]
1258 This link would show up in your Org-mode document as \"Google Search\",
1259 but really it would remove your entire home directory.
1260 Therefore we advise against setting this variable to nil.
1261 Just change it to `y-or-n-p' if you want to confirm with a
1262 single keystroke rather than having to type \"yes\"."
1263 :group 'org-link-follow
1264 :type '(choice
1265 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1266 (const :tag "with y-or-n (faster)" y-or-n-p)
1267 (const :tag "no confirmation (dangerous)" nil)))
1269 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1270 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1271 Elisp links can be dangerous: just think about a link
1273 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1275 This link would show up in your Org-mode document as \"Google Search\",
1276 but really it would remove your entire home directory.
1277 Therefore we advise against setting this variable to nil.
1278 Just change it to `y-or-n-p' if you want to confirm with a
1279 single keystroke rather than having to type \"yes\"."
1280 :group 'org-link-follow
1281 :type '(choice
1282 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1283 (const :tag "with y-or-n (faster)" y-or-n-p)
1284 (const :tag "no confirmation (dangerous)" nil)))
1286 (defconst org-file-apps-defaults-gnu
1287 '((remote . emacs)
1288 (system . mailcap)
1289 (t . mailcap))
1290 "Default file applications on a UNIX or GNU/Linux system.
1291 See `org-file-apps'.")
1293 (defconst org-file-apps-defaults-macosx
1294 '((remote . emacs)
1295 (t . "open %s")
1296 (system . "open %s")
1297 ("ps.gz" . "gv %s")
1298 ("eps.gz" . "gv %s")
1299 ("dvi" . "xdvi %s")
1300 ("fig" . "xfig %s"))
1301 "Default file applications on a MacOS X system.
1302 The system \"open\" is known as a default, but we use X11 applications
1303 for some files for which the OS does not have a good default.
1304 See `org-file-apps'.")
1306 (defconst org-file-apps-defaults-windowsnt
1307 (list
1308 '(remote . emacs)
1309 (cons t
1310 (list (if (featurep 'xemacs)
1311 'mswindows-shell-execute
1312 'w32-shell-execute)
1313 "open" 'file))
1314 (cons 'system
1315 (list (if (featurep 'xemacs)
1316 'mswindows-shell-execute
1317 'w32-shell-execute)
1318 "open" 'file)))
1319 "Default file applications on a Windows NT system.
1320 The system \"open\" is used for most files.
1321 See `org-file-apps'.")
1323 (defcustom org-file-apps
1325 (auto-mode . emacs)
1326 ("\\.x?html?\\'" . default)
1327 ("\\.pdf\\'" . default)
1329 "External applications for opening `file:path' items in a document.
1330 Org-mode uses system defaults for different file types, but
1331 you can use this variable to set the application for a given file
1332 extension. The entries in this list are cons cells where the car identifies
1333 files and the cdr the corresponding command. Possible values for the
1334 file identifier are
1335 \"regex\" Regular expression matched against the file name. For backward
1336 compatibility, this can also be a string with only alphanumeric
1337 characters, which is then interpreted as an extension.
1338 `directory' Matches a directory
1339 `remote' Matches a remote file, accessible through tramp or efs.
1340 Remote files most likely should be visited through Emacs
1341 because external applications cannot handle such paths.
1342 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1343 so all files Emacs knows how to handle. Using this with
1344 command `emacs' will open most files in Emacs. Beware that this
1345 will also open html files inside Emacs, unless you add
1346 (\"html\" . default) to the list as well.
1347 t Default for files not matched by any of the other options.
1348 `system' The system command to open files, like `open' on Windows
1349 and Mac OS X, and mailcap under GNU/Linux. This is the command
1350 that will be selected if you call `C-c C-o' with a double
1351 `C-u C-u' prefix.
1353 Possible values for the command are:
1354 `emacs' The file will be visited by the current Emacs process.
1355 `default' Use the default application for this file type, which is the
1356 association for t in the list, most likely in the system-specific
1357 part.
1358 This can be used to overrule an unwanted setting in the
1359 system-specific variable.
1360 `system' Use the system command for opening files, like \"open\".
1361 This command is specified by the entry whose car is `system'.
1362 Most likely, the system-specific version of this variable
1363 does define this command, but you can overrule/replace it
1364 here.
1365 string A command to be executed by a shell; %s will be replaced
1366 by the path to the file.
1367 sexp A Lisp form which will be evaluated. The file path will
1368 be available in the Lisp variable `file'.
1369 For more examples, see the system specific constants
1370 `org-file-apps-defaults-macosx'
1371 `org-file-apps-defaults-windowsnt'
1372 `org-file-apps-defaults-gnu'."
1373 :group 'org-link-follow
1374 :type '(repeat
1375 (cons (choice :value ""
1376 (string :tag "Extension")
1377 (const :tag "System command to open files" system)
1378 (const :tag "Default for unrecognized files" t)
1379 (const :tag "Remote file" remote)
1380 (const :tag "Links to a directory" directory)
1381 (const :tag "Any files that have Emacs modes"
1382 auto-mode))
1383 (choice :value ""
1384 (const :tag "Visit with Emacs" emacs)
1385 (const :tag "Use default" default)
1386 (const :tag "Use the system command" system)
1387 (string :tag "Command")
1388 (sexp :tag "Lisp form")))))
1390 (defgroup org-refile nil
1391 "Options concerning refiling entries in Org-mode."
1392 :tag "Org Refile"
1393 :group 'org)
1395 (defcustom org-directory "~/org"
1396 "Directory with org files.
1397 This is just a default location to look for Org files. There is no need
1398 at all to put your files into this directory. It is only used in the
1399 following situations:
1401 1. When a remember template specifies a target file that is not an
1402 absolute path. The path will then be interpreted relative to
1403 `org-directory'
1404 2. When a remember note is filed away in an interactive way (when exiting the
1405 note buffer with `C-1 C-c C-c'. The the user is prompted for an org file,
1406 with `org-directory' as the default path."
1407 :group 'org-refile
1408 :group 'org-remember
1409 :type 'directory)
1411 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1412 "Default target for storing notes.
1413 Used by the hooks for remember.el. This can be a string, or nil to mean
1414 the value of `remember-data-file'.
1415 You can set this on a per-template basis with the variable
1416 `org-remember-templates'."
1417 :group 'org-refile
1418 :group 'org-remember
1419 :type '(choice
1420 (const :tag "Default from remember-data-file" nil)
1421 file))
1423 (defcustom org-goto-interface 'outline
1424 "The default interface to be used for `org-goto'.
1425 Allowed values are:
1426 outline The interface shows an outline of the relevant file
1427 and the correct heading is found by moving through
1428 the outline or by searching with incremental search.
1429 outline-path-completion Headlines in the current buffer are offered via
1430 completion. This is the interface also used by
1431 the refile command."
1432 :group 'org-refile
1433 :type '(choice
1434 (const :tag "Outline" outline)
1435 (const :tag "Outline-path-completion" outline-path-completion)))
1437 (defcustom org-goto-max-level 5
1438 "Maximum level to be considered when running org-goto with refile interface."
1439 :group 'org-refile
1440 :type 'integer)
1442 (defcustom org-reverse-note-order nil
1443 "Non-nil means, store new notes at the beginning of a file or entry.
1444 When nil, new notes will be filed to the end of a file or entry.
1445 This can also be a list with cons cells of regular expressions that
1446 are matched against file names, and values."
1447 :group 'org-remember
1448 :group 'org-refile
1449 :type '(choice
1450 (const :tag "Reverse always" t)
1451 (const :tag "Reverse never" nil)
1452 (repeat :tag "By file name regexp"
1453 (cons regexp boolean))))
1455 (defcustom org-refile-targets nil
1456 "Targets for refiling entries with \\[org-refile].
1457 This is list of cons cells. Each cell contains:
1458 - a specification of the files to be considered, either a list of files,
1459 or a symbol whose function or variable value will be used to retrieve
1460 a file name or a list of file names. If you use `org-agenda-files' for
1461 that, all agenda files will be scanned for targets. Nil means, consider
1462 headings in the current buffer.
1463 - A specification of how to find candidate refile targets. This may be
1464 any of:
1465 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1466 This tag has to be present in all target headlines, inheritance will
1467 not be considered.
1468 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1469 todo keyword.
1470 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1471 headlines that are refiling targets.
1472 - a cons cell (:level . N). Any headline of level N is considered a target.
1473 Note that, when `org-odd-levels-only' is set, level corresponds to
1474 order in hierarchy, not to the number of stars.
1475 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1476 Note that, when `org-odd-levels-only' is set, level corresponds to
1477 order in hierarchy, not to the number of stars.
1479 You can set the variable `org-refile-target-verify-function' to a function
1480 to verify each headline found by the simple critery above.
1482 When this variable is nil, all top-level headlines in the current buffer
1483 are used, equivalent to the value `((nil . (:level . 1))'."
1484 :group 'org-refile
1485 :type '(repeat
1486 (cons
1487 (choice :value org-agenda-files
1488 (const :tag "All agenda files" org-agenda-files)
1489 (const :tag "Current buffer" nil)
1490 (function) (variable) (file))
1491 (choice :tag "Identify target headline by"
1492 (cons :tag "Specific tag" (const :value :tag) (string))
1493 (cons :tag "TODO keyword" (const :value :todo) (string))
1494 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1495 (cons :tag "Level number" (const :value :level) (integer))
1496 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1498 (defcustom org-refile-target-verify-function nil
1499 "Function to verify if the headline at point should be a refile target.
1500 The function will be called without arguments, with point at the
1501 beginning of the headline. It should return t and leave point
1502 where it is if the headline is a valid target for refiling.
1504 If the target should not be selected, the function must return nil.
1505 In addition to this, it may move point to a place from where the search
1506 should be continued. For example, the function may decide that the entire
1507 subtree of the current entry should be excluded and move point to the end
1508 of the subtree."
1509 :group 'org-refile
1510 :type 'function)
1512 (defcustom org-refile-use-outline-path nil
1513 "Non-nil means, provide refile targets as paths.
1514 So a level 3 headline will be available as level1/level2/level3.
1516 When the value is `file', also include the file name (without directory)
1517 into the path. In this case, you can also stop the completion after
1518 the file name, to get entries inserted as top level in the file.
1520 When `full-file-path', include the full file path."
1521 :group 'org-refile
1522 :type '(choice
1523 (const :tag "Not" nil)
1524 (const :tag "Yes" t)
1525 (const :tag "Start with file name" file)
1526 (const :tag "Start with full file path" full-file-path)))
1528 (defcustom org-outline-path-complete-in-steps t
1529 "Non-nil means, complete the outline path in hierarchical steps.
1530 When Org-mode uses the refile interface to select an outline path
1531 \(see variable `org-refile-use-outline-path'), the completion of
1532 the path can be done is a single go, or if can be done in steps down
1533 the headline hierarchy. Going in steps is probably the best if you
1534 do not use a special completion package like `ido' or `icicles'.
1535 However, when using these packages, going in one step can be very
1536 fast, while still showing the whole path to the entry."
1537 :group 'org-refile
1538 :type 'boolean)
1540 (defcustom org-refile-allow-creating-parent-nodes nil
1541 "Non-nil means, allow to create new nodes as refile targets.
1542 New nodes are then created by adding \"/new node name\" to the completion
1543 of an existing node. When the value of this variable is `confirm',
1544 new node creation must be confirmed by the user (recommended)
1545 When nil, the completion must match an existing entry.
1547 Note that, if the new heading is not seen by the criteria
1548 listed in `org-refile-targets', multiple instances of the same
1549 heading would be created by trying again to file under the new
1550 heading."
1551 :group 'org-refile
1552 :type '(choice
1553 (const :tag "Never" nil)
1554 (const :tag "Always" t)
1555 (const :tag "Prompt for confirmation" confirm)))
1557 (defgroup org-todo nil
1558 "Options concerning TODO items in Org-mode."
1559 :tag "Org TODO"
1560 :group 'org)
1562 (defgroup org-progress nil
1563 "Options concerning Progress logging in Org-mode."
1564 :tag "Org Progress"
1565 :group 'org-time)
1567 (defvar org-todo-interpretation-widgets
1569 (:tag "Sequence (cycling hits every state)" sequence)
1570 (:tag "Type (cycling directly to DONE)" type))
1571 "The available interpretation symbols for customizing
1572 `org-todo-keywords'.
1573 Interested libraries should add to this list.")
1575 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1576 "List of TODO entry keyword sequences and their interpretation.
1577 \\<org-mode-map>This is a list of sequences.
1579 Each sequence starts with a symbol, either `sequence' or `type',
1580 indicating if the keywords should be interpreted as a sequence of
1581 action steps, or as different types of TODO items. The first
1582 keywords are states requiring action - these states will select a headline
1583 for inclusion into the global TODO list Org-mode produces. If one of
1584 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1585 signify that no further action is necessary. If \"|\" is not found,
1586 the last keyword is treated as the only DONE state of the sequence.
1588 The command \\[org-todo] cycles an entry through these states, and one
1589 additional state where no keyword is present. For details about this
1590 cycling, see the manual.
1592 TODO keywords and interpretation can also be set on a per-file basis with
1593 the special #+SEQ_TODO and #+TYP_TODO lines.
1595 Each keyword can optionally specify a character for fast state selection
1596 \(in combination with the variable `org-use-fast-todo-selection')
1597 and specifiers for state change logging, using the same syntax
1598 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1599 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1600 indicates to record a time stamp each time this state is selected.
1602 Each keyword may also specify if a timestamp or a note should be
1603 recorded when entering or leaving the state, by adding additional
1604 characters in the parenthesis after the keyword. This looks like this:
1605 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1606 record only the time of the state change. With X and Y being either
1607 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1608 Y when leaving the state if and only if the *target* state does not
1609 define X. You may omit any of the fast-selection key or X or /Y,
1610 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1612 For backward compatibility, this variable may also be just a list
1613 of keywords - in this case the interpretation (sequence or type) will be
1614 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1615 :group 'org-todo
1616 :group 'org-keywords
1617 :type '(choice
1618 (repeat :tag "Old syntax, just keywords"
1619 (string :tag "Keyword"))
1620 (repeat :tag "New syntax"
1621 (cons
1622 (choice
1623 :tag "Interpretation"
1624 ;;Quick and dirty way to see
1625 ;;`org-todo-interpretations'. This takes the
1626 ;;place of item arguments
1627 :convert-widget
1628 (lambda (widget)
1629 (widget-put widget
1630 :args (mapcar
1631 #'(lambda (x)
1632 (widget-convert
1633 (cons 'const x)))
1634 org-todo-interpretation-widgets))
1635 widget))
1636 (repeat
1637 (string :tag "Keyword"))))))
1639 (defvar org-todo-keywords-1 nil
1640 "All TODO and DONE keywords active in a buffer.")
1641 (make-variable-buffer-local 'org-todo-keywords-1)
1642 (defvar org-todo-keywords-for-agenda nil)
1643 (defvar org-done-keywords-for-agenda nil)
1644 (defvar org-todo-keyword-alist-for-agenda nil)
1645 (defvar org-tag-alist-for-agenda nil)
1646 (defvar org-agenda-contributing-files nil)
1647 (defvar org-not-done-keywords nil)
1648 (make-variable-buffer-local 'org-not-done-keywords)
1649 (defvar org-done-keywords nil)
1650 (make-variable-buffer-local 'org-done-keywords)
1651 (defvar org-todo-heads nil)
1652 (make-variable-buffer-local 'org-todo-heads)
1653 (defvar org-todo-sets nil)
1654 (make-variable-buffer-local 'org-todo-sets)
1655 (defvar org-todo-log-states nil)
1656 (make-variable-buffer-local 'org-todo-log-states)
1657 (defvar org-todo-kwd-alist nil)
1658 (make-variable-buffer-local 'org-todo-kwd-alist)
1659 (defvar org-todo-key-alist nil)
1660 (make-variable-buffer-local 'org-todo-key-alist)
1661 (defvar org-todo-key-trigger nil)
1662 (make-variable-buffer-local 'org-todo-key-trigger)
1664 (defcustom org-todo-interpretation 'sequence
1665 "Controls how TODO keywords are interpreted.
1666 This variable is in principle obsolete and is only used for
1667 backward compatibility, if the interpretation of todo keywords is
1668 not given already in `org-todo-keywords'. See that variable for
1669 more information."
1670 :group 'org-todo
1671 :group 'org-keywords
1672 :type '(choice (const sequence)
1673 (const type)))
1675 (defcustom org-use-fast-todo-selection t
1676 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1677 This variable describes if and under what circumstances the cycling
1678 mechanism for TODO keywords will be replaced by a single-key, direct
1679 selection scheme.
1681 When nil, fast selection is never used.
1683 When the symbol `prefix', it will be used when `org-todo' is called with
1684 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1685 in an agenda buffer.
1687 When t, fast selection is used by default. In this case, the prefix
1688 argument forces cycling instead.
1690 In all cases, the special interface is only used if access keys have actually
1691 been assigned by the user, i.e. if keywords in the configuration are followed
1692 by a letter in parenthesis, like TODO(t)."
1693 :group 'org-todo
1694 :type '(choice
1695 (const :tag "Never" nil)
1696 (const :tag "By default" t)
1697 (const :tag "Only with C-u C-c C-t" prefix)))
1699 (defcustom org-provide-todo-statistics t
1700 "Non-nil means, update todo statistics after insert and toggle.
1701 When this is set, todo statistics is updated in the parent of the current
1702 entry each time a todo state is changed."
1703 :group 'org-todo
1704 :type 'boolean)
1706 (defcustom org-hierarchical-todo-statistics t
1707 "Non-nil means, TODO statistics covers just direct children.
1708 When nil, all entries in the subtree are considered.
1709 This has only an effect if `org-provide-todo-statistics' is set."
1710 :group 'org-todo
1711 :type 'boolean)
1713 (defcustom org-after-todo-state-change-hook nil
1714 "Hook which is run after the state of a TODO item was changed.
1715 The new state (a string with a TODO keyword, or nil) is available in the
1716 Lisp variable `state'."
1717 :group 'org-todo
1718 :type 'hook)
1720 (defvar org-blocker-hook nil
1721 "Hook for functions that are allowed to block a state change.
1723 Each function gets as its single argument a property list, see
1724 `org-trigger-hook' for more information about this list.
1726 If any of the functions in this hook returns nil, the state change
1727 is blocked.")
1729 (defvar org-trigger-hook nil
1730 "Hook for functions that are triggered by a state change.
1732 Each function gets as its single argument a property list with at least
1733 the following elements:
1735 (:type type-of-change :position pos-at-entry-start
1736 :from old-state :to new-state)
1738 Depending on the type, more properties may be present.
1740 This mechanism is currently implemented for:
1742 TODO state changes
1743 ------------------
1744 :type todo-state-change
1745 :from previous state (keyword as a string), or nil, or a symbol
1746 'todo' or 'done', to indicate the general type of state.
1747 :to new state, like in :from")
1749 (defcustom org-enforce-todo-dependencies nil
1750 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1751 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1752 be blocked if any prior sibling is not yet done.
1753 Finally, if the parent is blocked because of ordered siblings of its own,
1754 the child will also be blocked.
1755 This variable needs to be set before org.el is loaded, and you need to
1756 restart Emacs after a change to make the change effective. The only way
1757 to change is while Emacs is running is through the customize interface."
1758 :set (lambda (var val)
1759 (set var val)
1760 (if val
1761 (add-hook 'org-blocker-hook
1762 'org-block-todo-from-children-or-siblings-or-parent)
1763 (remove-hook 'org-blocker-hook
1764 'org-block-todo-from-children-or-siblings-or-parent)))
1765 :group 'org-todo
1766 :type 'boolean)
1768 (defcustom org-enforce-todo-checkbox-dependencies nil
1769 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1770 When this is nil, checkboxes have no influence on switching TODO states.
1771 When non-nil, you first need to check off all check boxes before the TODO
1772 entry can be switched to DONE.
1773 This variable needs to be set before org.el is loaded, and you need to
1774 restart Emacs after a change to make the change effective. The only way
1775 to change is while Emacs is running is through the customize interface."
1776 :set (lambda (var val)
1777 (set var val)
1778 (if val
1779 (add-hook 'org-blocker-hook
1780 'org-block-todo-from-checkboxes)
1781 (remove-hook 'org-blocker-hook
1782 'org-block-todo-from-checkboxes)))
1783 :group 'org-todo
1784 :type 'boolean)
1786 (defcustom org-treat-insert-todo-heading-as-state-change nil
1787 "Non-nil means, inserting a TODO heading is treated as state change.
1788 So when the command \\[org-insert-todo-heading] is used, state change
1789 logging will apply if appropriate. When nil, the new TODO item will
1790 be inserted directly, and no logging will take place."
1791 :group 'org-todo
1792 :type 'boolean)
1794 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1795 "Non-nil means, switching TODO states with S-cursor counts as state change.
1796 This is the default behavior. However, setting this to nil allows a
1797 convenient way to select a TODO state and bypass any logging associated
1798 with that."
1799 :group 'org-todo
1800 :type 'boolean)
1802 (defcustom org-todo-state-tags-triggers nil
1803 "Tag changes that should be triggered by TODO state changes.
1804 This is a list. Each entry is
1806 (state-change (tag . flag) .......)
1808 State-change can be a string with a state, and empty string to indicate the
1809 state that has no TODO keyword, or it can be one of the symbols `todo'
1810 or `done', meaning any not-done or done state, respectively."
1811 :group 'org-todo
1812 :group 'org-tags
1813 :type '(repeat
1814 (cons (choice :tag "When changing to"
1815 (const :tag "Not-done state" todo)
1816 (const :tag "Done state" done)
1817 (string :tag "State"))
1818 (repeat
1819 (cons :tag "Tag action"
1820 (string :tag "Tag")
1821 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1823 (defcustom org-log-done nil
1824 "Information to record when a task moves to the DONE state.
1826 Possible values are:
1828 nil Don't add anything, just change the keyword
1829 time Add a time stamp to the task
1830 note Prompt a closing note and add it with template `org-log-note-headings'
1832 This option can also be set with on a per-file-basis with
1834 #+STARTUP: nologdone
1835 #+STARTUP: logdone
1836 #+STARTUP: lognotedone
1838 You can have local logging settings for a subtree by setting the LOGGING
1839 property to one or more of these keywords."
1840 :group 'org-todo
1841 :group 'org-progress
1842 :type '(choice
1843 (const :tag "No logging" nil)
1844 (const :tag "Record CLOSED timestamp" time)
1845 (const :tag "Record CLOSED timestamp with closing note." note)))
1847 ;; Normalize old uses of org-log-done.
1848 (cond
1849 ((eq org-log-done t) (setq org-log-done 'time))
1850 ((and (listp org-log-done) (memq 'done org-log-done))
1851 (setq org-log-done 'note)))
1853 (defcustom org-log-note-clock-out nil
1854 "Non-nil means, record a note when clocking out of an item.
1855 This can also be configured on a per-file basis by adding one of
1856 the following lines anywhere in the buffer:
1858 #+STARTUP: lognoteclock-out
1859 #+STARTUP: nolognoteclock-out"
1860 :group 'org-todo
1861 :group 'org-progress
1862 :type 'boolean)
1864 (defcustom org-log-done-with-time t
1865 "Non-nil means, the CLOSED time stamp will contain date and time.
1866 When nil, only the date will be recorded."
1867 :group 'org-progress
1868 :type 'boolean)
1870 (defcustom org-log-note-headings
1871 '((done . "CLOSING NOTE %t")
1872 (state . "State %-12s from %-12S %t")
1873 (note . "Note taken on %t")
1874 (clock-out . ""))
1875 "Headings for notes added to entries.
1876 The value is an alist, with the car being a symbol indicating the note
1877 context, and the cdr is the heading to be used. The heading may also be the
1878 empty string.
1879 %t in the heading will be replaced by a time stamp.
1880 %s will be replaced by the new TODO state, in double quotes.
1881 %S will be replaced by the old TODO state, in double quotes.
1882 %u will be replaced by the user name.
1883 %U will be replaced by the full user name."
1884 :group 'org-todo
1885 :group 'org-progress
1886 :type '(list :greedy t
1887 (cons (const :tag "Heading when closing an item" done) string)
1888 (cons (const :tag
1889 "Heading when changing todo state (todo sequence only)"
1890 state) string)
1891 (cons (const :tag "Heading when just taking a note" note) string)
1892 (cons (const :tag "Heading when clocking out" clock-out) string)))
1894 (unless (assq 'note org-log-note-headings)
1895 (push '(note . "%t") org-log-note-headings))
1897 (defcustom org-log-into-drawer nil
1898 "Non-nil means, insert state change notes and time stamps into a drawer.
1899 When nil, state changes notes will be inserted after the headline and
1900 any scheduling and clock lines, but not inside a drawer.
1902 The value of this variable should be the name of the drawer to use.
1903 LOGBOOK is proposed at the default drawer for this purpose, you can
1904 also set this to a string to define the drawer of your choice.
1906 A value of t is also allowed, representing \"LOGBOOK\".
1908 If this variable is set, `org-log-state-notes-insert-after-drawers'
1909 will be ignored.
1911 You can set the property LOG_INTO_DRAWER to overrule this setting for
1912 a subtree."
1913 :group 'org-todo
1914 :group 'org-progress
1915 :type '(choice
1916 (const :tag "Not into a drawer" nil)
1917 (const :tag "LOGBOOK" t)
1918 (string :tag "Other")))
1920 (if (fboundp 'defvaralias)
1921 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
1923 (defun org-log-into-drawer ()
1924 "Return the value of `org-log-into-drawer', but let properties overrule.
1925 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
1926 used instead of the default value."
1927 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
1928 (cond
1929 ((or (not p) (equal p "nil")) org-log-into-drawer)
1930 ((equal p "t") "LOGBOOK")
1931 (t p))))
1933 (defcustom org-log-state-notes-insert-after-drawers nil
1934 "Non-nil means, insert state change notes after any drawers in entry.
1935 Only the drawers that *immediately* follow the headline and the
1936 deadline/scheduled line are skipped.
1937 When nil, insert notes right after the heading and perhaps the line
1938 with deadline/scheduling if present.
1940 This variable will have no effect if `org-log-into-drawer' is
1941 set."
1942 :group 'org-todo
1943 :group 'org-progress
1944 :type 'boolean)
1946 (defcustom org-log-states-order-reversed t
1947 "Non-nil means, the latest state change note will be directly after heading.
1948 When nil, the notes will be orderer according to time."
1949 :group 'org-todo
1950 :group 'org-progress
1951 :type 'boolean)
1953 (defcustom org-log-repeat 'time
1954 "Non-nil means, record moving through the DONE state when triggering repeat.
1955 An auto-repeating tasks is immediately switched back to TODO when marked
1956 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1957 the TODO keyword definition, or recording a closing note by setting
1958 `org-log-done', there will be no record of the task moving through DONE.
1959 This variable forces taking a note anyway. Possible values are:
1961 nil Don't force a record
1962 time Record a time stamp
1963 note Record a note
1965 This option can also be set with on a per-file-basis with
1967 #+STARTUP: logrepeat
1968 #+STARTUP: lognoterepeat
1969 #+STARTUP: nologrepeat
1971 You can have local logging settings for a subtree by setting the LOGGING
1972 property to one or more of these keywords."
1973 :group 'org-todo
1974 :group 'org-progress
1975 :type '(choice
1976 (const :tag "Don't force a record" nil)
1977 (const :tag "Force recording the DONE state" time)
1978 (const :tag "Force recording a note with the DONE state" note)))
1981 (defgroup org-priorities nil
1982 "Priorities in Org-mode."
1983 :tag "Org Priorities"
1984 :group 'org-todo)
1986 (defcustom org-enable-priority-commands t
1987 "Non-nil means, priority commands are active.
1988 When nil, these commands will be disabled, so that you never accidentally
1989 set a priority."
1990 :group 'org-priorities
1991 :type 'boolean)
1993 (defcustom org-highest-priority ?A
1994 "The highest priority of TODO items. A character like ?A, ?B etc.
1995 Must have a smaller ASCII number than `org-lowest-priority'."
1996 :group 'org-priorities
1997 :type 'character)
1999 (defcustom org-lowest-priority ?C
2000 "The lowest priority of TODO items. A character like ?A, ?B etc.
2001 Must have a larger ASCII number than `org-highest-priority'."
2002 :group 'org-priorities
2003 :type 'character)
2005 (defcustom org-default-priority ?B
2006 "The default priority of TODO items.
2007 This is the priority an item get if no explicit priority is given."
2008 :group 'org-priorities
2009 :type 'character)
2011 (defcustom org-priority-start-cycle-with-default t
2012 "Non-nil means, start with default priority when starting to cycle.
2013 When this is nil, the first step in the cycle will be (depending on the
2014 command used) one higher or lower that the default priority."
2015 :group 'org-priorities
2016 :type 'boolean)
2018 (defgroup org-time nil
2019 "Options concerning time stamps and deadlines in Org-mode."
2020 :tag "Org Time"
2021 :group 'org)
2023 (defcustom org-insert-labeled-timestamps-at-point nil
2024 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
2025 When nil, these labeled time stamps are forces into the second line of an
2026 entry, just after the headline. When scheduling from the global TODO list,
2027 the time stamp will always be forced into the second line."
2028 :group 'org-time
2029 :type 'boolean)
2031 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2032 "Formats for `format-time-string' which are used for time stamps.
2033 It is not recommended to change this constant.")
2035 (defcustom org-time-stamp-rounding-minutes '(0 5)
2036 "Number of minutes to round time stamps to.
2037 These are two values, the first applies when first creating a time stamp.
2038 The second applies when changing it with the commands `S-up' and `S-down'.
2039 When changing the time stamp, this means that it will change in steps
2040 of N minutes, as given by the second value.
2042 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2043 numbers should be factors of 60, so for example 5, 10, 15.
2045 When this is larger than 1, you can still force an exact time-stamp by using
2046 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2047 and by using a prefix arg to `S-up/down' to specify the exact number
2048 of minutes to shift."
2049 :group 'org-time
2050 :get '(lambda (var) ; Make sure all entries have 5 elements
2051 (if (integerp (default-value var))
2052 (list (default-value var) 5)
2053 (default-value var)))
2054 :type '(list
2055 (integer :tag "when inserting times")
2056 (integer :tag "when modifying times")))
2058 ;; Normalize old customizations of this variable.
2059 (when (integerp org-time-stamp-rounding-minutes)
2060 (setq org-time-stamp-rounding-minutes
2061 (list org-time-stamp-rounding-minutes
2062 org-time-stamp-rounding-minutes)))
2064 (defcustom org-display-custom-times nil
2065 "Non-nil means, overlay custom formats over all time stamps.
2066 The formats are defined through the variable `org-time-stamp-custom-formats'.
2067 To turn this on on a per-file basis, insert anywhere in the file:
2068 #+STARTUP: customtime"
2069 :group 'org-time
2070 :set 'set-default
2071 :type 'sexp)
2072 (make-variable-buffer-local 'org-display-custom-times)
2074 (defcustom org-time-stamp-custom-formats
2075 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2076 "Custom formats for time stamps. See `format-time-string' for the syntax.
2077 These are overlayed over the default ISO format if the variable
2078 `org-display-custom-times' is set. Time like %H:%M should be at the
2079 end of the second format. The custom formats are also honored by export
2080 commands, if custom time display is turned on at the time of export."
2081 :group 'org-time
2082 :type 'sexp)
2084 (defun org-time-stamp-format (&optional long inactive)
2085 "Get the right format for a time string."
2086 (let ((f (if long (cdr org-time-stamp-formats)
2087 (car org-time-stamp-formats))))
2088 (if inactive
2089 (concat "[" (substring f 1 -1) "]")
2090 f)))
2092 (defcustom org-time-clocksum-format "%d:%02d"
2093 "The format string used when creating CLOCKSUM lines, or when
2094 org-mode generates a time duration."
2095 :group 'org-time
2096 :type 'string)
2098 (defcustom org-deadline-warning-days 14
2099 "No. of days before expiration during which a deadline becomes active.
2100 This variable governs the display in sparse trees and in the agenda.
2101 When 0 or negative, it means use this number (the absolute value of it)
2102 even if a deadline has a different individual lead time specified.
2104 Custom commands can set this variable in the options section."
2105 :group 'org-time
2106 :group 'org-agenda-daily/weekly
2107 :type 'integer)
2109 (defcustom org-read-date-prefer-future t
2110 "Non-nil means, assume future for incomplete date input from user.
2111 This affects the following situations:
2112 1. The user gives a day, but no month.
2113 For example, if today is the 15th, and you enter \"3\", Org-mode will
2114 read this as the third of *next* month. However, if you enter \"17\",
2115 it will be considered as *this* month.
2116 2. The user gives a month but not a year.
2117 For example, if it is april and you enter \"feb 2\", this will be read
2118 as feb 2, *next* year. \"May 5\", however, will be this year.
2120 Currently this does not work for ISO week specifications.
2122 When this option is nil, the current month and year will always be used
2123 as defaults."
2124 :group 'org-time
2125 :type 'boolean)
2127 (defcustom org-read-date-display-live t
2128 "Non-nil means, display current interpretation of date prompt live.
2129 This display will be in an overlay, in the minibuffer."
2130 :group 'org-time
2131 :type 'boolean)
2133 (defcustom org-read-date-popup-calendar t
2134 "Non-nil means, pop up a calendar when prompting for a date.
2135 In the calendar, the date can be selected with mouse-1. However, the
2136 minibuffer will also be active, and you can simply enter the date as well.
2137 When nil, only the minibuffer will be available."
2138 :group 'org-time
2139 :type 'boolean)
2140 (if (fboundp 'defvaralias)
2141 (defvaralias 'org-popup-calendar-for-date-prompt
2142 'org-read-date-popup-calendar))
2144 (defcustom org-read-date-minibuffer-setup-hook nil
2145 "Hook to be used to set up keys for the date/time interface.
2146 Add key definitions to `minibuffer-local-map', which will be a temporary
2147 copy."
2148 :group 'org-time
2149 :type 'hook)
2151 (defcustom org-extend-today-until 0
2152 "The hour when your day really ends. Must be an integer.
2153 This has influence for the following applications:
2154 - When switching the agenda to \"today\". It it is still earlier than
2155 the time given here, the day recognized as TODAY is actually yesterday.
2156 - When a date is read from the user and it is still before the time given
2157 here, the current date and time will be assumed to be yesterday, 23:59.
2158 Also, timestamps inserted in remember templates follow this rule.
2160 IMPORTANT: This is a feature whose implementation is and likely will
2161 remain incomplete. Really, it is only here because past midnight seems to
2162 be the favorite working time of John Wiegley :-)"
2163 :group 'org-time
2164 :type 'integer)
2166 (defcustom org-edit-timestamp-down-means-later nil
2167 "Non-nil means, S-down will increase the time in a time stamp.
2168 When nil, S-up will increase."
2169 :group 'org-time
2170 :type 'boolean)
2172 (defcustom org-calendar-follow-timestamp-change t
2173 "Non-nil means, make the calendar window follow timestamp changes.
2174 When a timestamp is modified and the calendar window is visible, it will be
2175 moved to the new date."
2176 :group 'org-time
2177 :type 'boolean)
2179 (defgroup org-tags nil
2180 "Options concerning tags in Org-mode."
2181 :tag "Org Tags"
2182 :group 'org)
2184 (defcustom org-tag-alist nil
2185 "List of tags allowed in Org-mode files.
2186 When this list is nil, Org-mode will base TAG input on what is already in the
2187 buffer.
2188 The value of this variable is an alist, the car of each entry must be a
2189 keyword as a string, the cdr may be a character that is used to select
2190 that tag through the fast-tag-selection interface.
2191 See the manual for details."
2192 :group 'org-tags
2193 :type '(repeat
2194 (choice
2195 (cons (string :tag "Tag name")
2196 (character :tag "Access char"))
2197 (const :tag "Start radio group" (:startgroup))
2198 (const :tag "End radio group" (:endgroup))
2199 (const :tag "New line" (:newline)))))
2201 (defcustom org-tag-persistent-alist nil
2202 "List of tags that will always appear in all Org-mode files.
2203 This is in addition to any in buffer settings or customizations
2204 of `org-tag-alist'.
2205 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2206 The value of this variable is an alist, the car of each entry must be a
2207 keyword as a string, the cdr may be a character that is used to select
2208 that tag through the fast-tag-selection interface.
2209 See the manual for details.
2210 To disable these tags on a per-file basis, insert anywhere in the file:
2211 #+STARTUP: noptag"
2212 :group 'org-tags
2213 :type '(repeat
2214 (choice
2215 (cons (string :tag "Tag name")
2216 (character :tag "Access char"))
2217 (const :tag "Start radio group" (:startgroup))
2218 (const :tag "End radio group" (:endgroup))
2219 (const :tag "New line" (:newline)))))
2221 (defvar org-file-tags nil
2222 "List of tags that can be inherited by all entries in the file.
2223 The tags will be inherited if the variable `org-use-tag-inheritance'
2224 says they should be.
2225 This variable is populated from #+TAG lines.")
2227 (defcustom org-use-fast-tag-selection 'auto
2228 "Non-nil means, use fast tag selection scheme.
2229 This is a special interface to select and deselect tags with single keys.
2230 When nil, fast selection is never used.
2231 When the symbol `auto', fast selection is used if and only if selection
2232 characters for tags have been configured, either through the variable
2233 `org-tag-alist' or through a #+TAGS line in the buffer.
2234 When t, fast selection is always used and selection keys are assigned
2235 automatically if necessary."
2236 :group 'org-tags
2237 :type '(choice
2238 (const :tag "Always" t)
2239 (const :tag "Never" nil)
2240 (const :tag "When selection characters are configured" 'auto)))
2242 (defcustom org-fast-tag-selection-single-key nil
2243 "Non-nil means, fast tag selection exits after first change.
2244 When nil, you have to press RET to exit it.
2245 During fast tag selection, you can toggle this flag with `C-c'.
2246 This variable can also have the value `expert'. In this case, the window
2247 displaying the tags menu is not even shown, until you press C-c again."
2248 :group 'org-tags
2249 :type '(choice
2250 (const :tag "No" nil)
2251 (const :tag "Yes" t)
2252 (const :tag "Expert" expert)))
2254 (defvar org-fast-tag-selection-include-todo nil
2255 "Non-nil means, fast tags selection interface will also offer TODO states.
2256 This is an undocumented feature, you should not rely on it.")
2258 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2259 "The column to which tags should be indented in a headline.
2260 If this number is positive, it specifies the column. If it is negative,
2261 it means that the tags should be flushright to that column. For example,
2262 -80 works well for a normal 80 character screen."
2263 :group 'org-tags
2264 :type 'integer)
2266 (defcustom org-auto-align-tags t
2267 "Non-nil means, realign tags after pro/demotion of TODO state change.
2268 These operations change the length of a headline and therefore shift
2269 the tags around. With this options turned on, after each such operation
2270 the tags are again aligned to `org-tags-column'."
2271 :group 'org-tags
2272 :type 'boolean)
2274 (defcustom org-use-tag-inheritance t
2275 "Non-nil means, tags in levels apply also for sublevels.
2276 When nil, only the tags directly given in a specific line apply there.
2277 This may also be a list of tags that should be inherited, or a regexp that
2278 matches tags that should be inherited. Additional control is possible
2279 with the variable `org-tags-exclude-from-inheritance' which gives an
2280 explicit list of tags to be excluded from inheritance., even if the value of
2281 `org-use-tag-inheritance' would select it for inheritance.
2283 If this option is t, a match early-on in a tree can lead to a large
2284 number of matches in the subtree when constructing the agenda or creating
2285 a sparse tree. If you only want to see the first match in a tree during
2286 a search, check out the variable `org-tags-match-list-sublevels'."
2287 :group 'org-tags
2288 :type '(choice
2289 (const :tag "Not" nil)
2290 (const :tag "Always" t)
2291 (repeat :tag "Specific tags" (string :tag "Tag"))
2292 (regexp :tag "Tags matched by regexp")))
2294 (defcustom org-tags-exclude-from-inheritance nil
2295 "List of tags that should never be inherited.
2296 This is a way to exclude a few tags from inheritance. For way to do
2297 the opposite, to actively allow inheritance for selected tags,
2298 see the variable `org-use-tag-inheritance'."
2299 :group 'org-tags
2300 :type '(repeat (string :tag "Tag")))
2302 (defun org-tag-inherit-p (tag)
2303 "Check if TAG is one that should be inherited."
2304 (cond
2305 ((member tag org-tags-exclude-from-inheritance) nil)
2306 ((eq org-use-tag-inheritance t) t)
2307 ((not org-use-tag-inheritance) nil)
2308 ((stringp org-use-tag-inheritance)
2309 (string-match org-use-tag-inheritance tag))
2310 ((listp org-use-tag-inheritance)
2311 (member tag org-use-tag-inheritance))
2312 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2314 (defcustom org-tags-match-list-sublevels t
2315 "Non-nil means list also sublevels of headlines matching a search.
2316 This variable applies to tags/property searches, and also to stuck
2317 projects because this search is based on a tags match as well.
2319 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2320 the sublevels of a headline matching a tag search often also match
2321 the same search. Listing all of them can create very long lists.
2322 Setting this variable to nil causes subtrees of a match to be skipped.
2324 As a special case, if the tag search is restricted to TODO items, the
2325 value of this variable is ignored and sublevels are always checked, to
2326 make sure all corresponding TODO items find their way into the list.
2328 This variable is semi-obsolete and probably should always be true. It
2329 is better to limit inheritance to certain tags using the variables
2330 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2331 :group 'org-tags
2332 :type '(choice
2333 (const :tag "No, don't list them" nil)
2334 (const :tag "Yes, do list them" t)
2335 (const :tag "List them, indented with leading dots" indented)))
2337 (defvar org-tags-history nil
2338 "History of minibuffer reads for tags.")
2339 (defvar org-last-tags-completion-table nil
2340 "The last used completion table for tags.")
2341 (defvar org-after-tags-change-hook nil
2342 "Hook that is run after the tags in a line have changed.")
2344 (defgroup org-properties nil
2345 "Options concerning properties in Org-mode."
2346 :tag "Org Properties"
2347 :group 'org)
2349 (defcustom org-property-format "%-10s %s"
2350 "How property key/value pairs should be formatted by `indent-line'.
2351 When `indent-line' hits a property definition, it will format the line
2352 according to this format, mainly to make sure that the values are
2353 lined-up with respect to each other."
2354 :group 'org-properties
2355 :type 'string)
2357 (defcustom org-use-property-inheritance nil
2358 "Non-nil means, properties apply also for sublevels.
2360 This setting is chiefly used during property searches. Turning it on can
2361 cause significant overhead when doing a search, which is why it is not
2362 on by default.
2364 When nil, only the properties directly given in the current entry count.
2365 When t, every property is inherited. The value may also be a list of
2366 properties that should have inheritance, or a regular expression matching
2367 properties that should be inherited.
2369 However, note that some special properties use inheritance under special
2370 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2371 and the properties ending in \"_ALL\" when they are used as descriptor
2372 for valid values of a property.
2374 Note for programmers:
2375 When querying an entry with `org-entry-get', you can control if inheritance
2376 should be used. By default, `org-entry-get' looks only at the local
2377 properties. You can request inheritance by setting the inherit argument
2378 to t (to force inheritance) or to `selective' (to respect the setting
2379 in this variable)."
2380 :group 'org-properties
2381 :type '(choice
2382 (const :tag "Not" nil)
2383 (const :tag "Always" t)
2384 (repeat :tag "Specific properties" (string :tag "Property"))
2385 (regexp :tag "Properties matched by regexp")))
2387 (defun org-property-inherit-p (property)
2388 "Check if PROPERTY is one that should be inherited."
2389 (cond
2390 ((eq org-use-property-inheritance t) t)
2391 ((not org-use-property-inheritance) nil)
2392 ((stringp org-use-property-inheritance)
2393 (string-match org-use-property-inheritance property))
2394 ((listp org-use-property-inheritance)
2395 (member property org-use-property-inheritance))
2396 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2398 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2399 "The default column format, if no other format has been defined.
2400 This variable can be set on the per-file basis by inserting a line
2402 #+COLUMNS: %25ITEM ....."
2403 :group 'org-properties
2404 :type 'string)
2406 (defcustom org-columns-ellipses ".."
2407 "The ellipses to be used when a field in column view is truncated.
2408 When this is the empty string, as many characters as possible are shown,
2409 but then there will be no visual indication that the field has been truncated.
2410 When this is a string of length N, the last N characters of a truncated
2411 field are replaced by this string. If the column is narrower than the
2412 ellipses string, only part of the ellipses string will be shown."
2413 :group 'org-properties
2414 :type 'string)
2416 (defcustom org-columns-modify-value-for-display-function nil
2417 "Function that modifies values for display in column view.
2418 For example, it can be used to cut out a certain part from a time stamp.
2419 The function must take 2 arguments:
2421 column-title The title of the column (*not* the property name)
2422 value The value that should be modified.
2424 The function should return the value that should be displayed,
2425 or nil if the normal value should be used."
2426 :group 'org-properties
2427 :type 'function)
2429 (defcustom org-effort-property "Effort"
2430 "The property that is being used to keep track of effort estimates.
2431 Effort estimates given in this property need to have the format H:MM."
2432 :group 'org-properties
2433 :group 'org-progress
2434 :type '(string :tag "Property"))
2436 (defconst org-global-properties-fixed
2437 '(("VISIBILITY_ALL" . "folded children content all")
2438 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2439 "List of property/value pairs that can be inherited by any entry.
2441 These are fixed values, for the preset properties. The user variable
2442 that can be used to add to this list is `org-global-properties'.
2444 The entries in this list are cons cells where the car is a property
2445 name and cdr is a string with the value. If the value represents
2446 multiple items like an \"_ALL\" property, separate the items by
2447 spaces.")
2449 (defcustom org-global-properties nil
2450 "List of property/value pairs that can be inherited by any entry.
2452 This list will be combined with the constant `org-global-properties-fixed'.
2454 The entries in this list are cons cells where the car is a property
2455 name and cdr is a string with the value.
2457 You can set buffer-local values for the same purpose in the variable
2458 `org-file-properties' this by adding lines like
2460 #+PROPERTY: NAME VALUE"
2461 :group 'org-properties
2462 :type '(repeat
2463 (cons (string :tag "Property")
2464 (string :tag "Value"))))
2466 (defvar org-file-properties nil
2467 "List of property/value pairs that can be inherited by any entry.
2468 Valid for the current buffer.
2469 This variable is populated from #+PROPERTY lines.")
2470 (make-variable-buffer-local 'org-file-properties)
2472 (defgroup org-agenda nil
2473 "Options concerning agenda views in Org-mode."
2474 :tag "Org Agenda"
2475 :group 'org)
2477 (defvar org-category nil
2478 "Variable used by org files to set a category for agenda display.
2479 Such files should use a file variable to set it, for example
2481 # -*- mode: org; org-category: \"ELisp\"
2483 or contain a special line
2485 #+CATEGORY: ELisp
2487 If the file does not specify a category, then file's base name
2488 is used instead.")
2489 (make-variable-buffer-local 'org-category)
2490 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2492 (defcustom org-agenda-files nil
2493 "The files to be used for agenda display.
2494 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2495 \\[org-remove-file]. You can also use customize to edit the list.
2497 If an entry is a directory, all files in that directory that are matched by
2498 `org-agenda-file-regexp' will be part of the file list.
2500 If the value of the variable is not a list but a single file name, then
2501 the list of agenda files is actually stored and maintained in that file, one
2502 agenda file per line."
2503 :group 'org-agenda
2504 :type '(choice
2505 (repeat :tag "List of files and directories" file)
2506 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2508 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2509 "Regular expression to match files for `org-agenda-files'.
2510 If any element in the list in that variable contains a directory instead
2511 of a normal file, all files in that directory that are matched by this
2512 regular expression will be included."
2513 :group 'org-agenda
2514 :type 'regexp)
2516 (defcustom org-agenda-text-search-extra-files nil
2517 "List of extra files to be searched by text search commands.
2518 These files will be search in addition to the agenda files by the
2519 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2520 Note that these files will only be searched for text search commands,
2521 not for the other agenda views like todo lists, tag searches or the weekly
2522 agenda. This variable is intended to list notes and possibly archive files
2523 that should also be searched by these two commands.
2524 In fact, if the first element in the list is the symbol `agenda-archives',
2525 than all archive files of all agenda files will be added to the search
2526 scope."
2527 :group 'org-agenda
2528 :type '(set :greedy t
2529 (const :tag "Agenda Archives" agenda-archives)
2530 (repeat :inline t (file))))
2532 (if (fboundp 'defvaralias)
2533 (defvaralias 'org-agenda-multi-occur-extra-files
2534 'org-agenda-text-search-extra-files))
2536 (defcustom org-agenda-skip-unavailable-files nil
2537 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2538 A nil value means to remove them, after a query, from the list."
2539 :group 'org-agenda
2540 :type 'boolean)
2542 (defcustom org-calendar-to-agenda-key [?c]
2543 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2544 The command `org-calendar-goto-agenda' will be bound to this key. The
2545 default is the character `c' because then `c' can be used to switch back and
2546 forth between agenda and calendar."
2547 :group 'org-agenda
2548 :type 'sexp)
2550 (defcustom org-calendar-agenda-action-key [?k]
2551 "The key to be installed in `calendar-mode-map' for agenda-action.
2552 The command `org-agenda-action' will be bound to this key. The
2553 default is the character `k' because we use the same key in the agenda."
2554 :group 'org-agenda
2555 :type 'sexp)
2557 (eval-after-load "calendar"
2558 '(progn
2559 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2560 'org-calendar-goto-agenda)
2561 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2562 'org-agenda-action)))
2564 (defgroup org-latex nil
2565 "Options for embedding LaTeX code into Org-mode."
2566 :tag "Org LaTeX"
2567 :group 'org)
2569 (defcustom org-format-latex-options
2570 '(:foreground default :background default :scale 1.0
2571 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2572 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2573 "Options for creating images from LaTeX fragments.
2574 This is a property list with the following properties:
2575 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2576 `default' means use the foreground of the default face.
2577 :background the background color, or \"Transparent\".
2578 `default' means use the background of the default face.
2579 :scale a scaling factor for the size of the images.
2580 :html-foreground, :html-background, :html-scale
2581 the same numbers for HTML export.
2582 :matchers a list indicating which matchers should be used to
2583 find LaTeX fragments. Valid members of this list are:
2584 \"begin\" find environments
2585 \"$1\" find single characters surrounded by $.$
2586 \"$\" find math expressions surrounded by $...$
2587 \"$$\" find math expressions surrounded by $$....$$
2588 \"\\(\" find math expressions surrounded by \\(...\\)
2589 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2590 :group 'org-latex
2591 :type 'plist)
2593 (defcustom org-format-latex-header "\\documentclass{article}
2594 \\usepackage{fullpage} % do not remove
2595 \\usepackage{amssymb}
2596 \\usepackage[usenames]{color}
2597 \\usepackage{amsmath}
2598 \\usepackage{latexsym}
2599 \\usepackage[mathscr]{eucal}
2600 \\pagestyle{empty} % do not remove"
2601 "The document header used for processing LaTeX fragments."
2602 :group 'org-latex
2603 :type 'string)
2606 (defgroup org-font-lock nil
2607 "Font-lock settings for highlighting in Org-mode."
2608 :tag "Org Font Lock"
2609 :group 'org)
2611 (defcustom org-level-color-stars-only nil
2612 "Non-nil means fontify only the stars in each headline.
2613 When nil, the entire headline is fontified.
2614 Changing it requires restart of `font-lock-mode' to become effective
2615 also in regions already fontified."
2616 :group 'org-font-lock
2617 :type 'boolean)
2619 (defcustom org-hide-leading-stars nil
2620 "Non-nil means, hide the first N-1 stars in a headline.
2621 This works by using the face `org-hide' for these stars. This
2622 face is white for a light background, and black for a dark
2623 background. You may have to customize the face `org-hide' to
2624 make this work.
2625 Changing it requires restart of `font-lock-mode' to become effective
2626 also in regions already fontified.
2627 You may also set this on a per-file basis by adding one of the following
2628 lines to the buffer:
2630 #+STARTUP: hidestars
2631 #+STARTUP: showstars"
2632 :group 'org-font-lock
2633 :type 'boolean)
2635 (defcustom org-fontify-done-headline nil
2636 "Non-nil means, change the face of a headline if it is marked DONE.
2637 Normally, only the TODO/DONE keyword indicates the state of a headline.
2638 When this is non-nil, the headline after the keyword is set to the
2639 `org-headline-done' as an additional indication."
2640 :group 'org-font-lock
2641 :type 'boolean)
2643 (defcustom org-fontify-emphasized-text t
2644 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2645 Changing this variable requires a restart of Emacs to take effect."
2646 :group 'org-font-lock
2647 :type 'boolean)
2649 (defcustom org-highlight-latex-fragments-and-specials nil
2650 "Non-nil means, fontify what is treated specially by the exporters."
2651 :group 'org-font-lock
2652 :type 'boolean)
2654 (defcustom org-hide-emphasis-markers nil
2655 "Non-nil mean font-lock should hide the emphasis marker characters."
2656 :group 'org-font-lock
2657 :type 'boolean)
2659 (defvar org-emph-re nil
2660 "Regular expression for matching emphasis.")
2661 (defvar org-verbatim-re nil
2662 "Regular expression for matching verbatim text.")
2663 (defvar org-emphasis-regexp-components) ; defined just below
2664 (defvar org-emphasis-alist) ; defined just below
2665 (defun org-set-emph-re (var val)
2666 "Set variable and compute the emphasis regular expression."
2667 (set var val)
2668 (when (and (boundp 'org-emphasis-alist)
2669 (boundp 'org-emphasis-regexp-components)
2670 org-emphasis-alist org-emphasis-regexp-components)
2671 (let* ((e org-emphasis-regexp-components)
2672 (pre (car e))
2673 (post (nth 1 e))
2674 (border (nth 2 e))
2675 (body (nth 3 e))
2676 (nl (nth 4 e))
2677 (body1 (concat body "*?"))
2678 (markers (mapconcat 'car org-emphasis-alist ""))
2679 (vmarkers (mapconcat
2680 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2681 org-emphasis-alist "")))
2682 ;; make sure special characters appear at the right position in the class
2683 (if (string-match "\\^" markers)
2684 (setq markers (concat (replace-match "" t t markers) "^")))
2685 (if (string-match "-" markers)
2686 (setq markers (concat (replace-match "" t t markers) "-")))
2687 (if (string-match "\\^" vmarkers)
2688 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2689 (if (string-match "-" vmarkers)
2690 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2691 (if (> nl 0)
2692 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2693 (int-to-string nl) "\\}")))
2694 ;; Make the regexp
2695 (setq org-emph-re
2696 (concat "\\([" pre "]\\|^\\)"
2697 "\\("
2698 "\\([" markers "]\\)"
2699 "\\("
2700 "[^" border "]\\|"
2701 "[^" border "]"
2702 body1
2703 "[^" border "]"
2704 "\\)"
2705 "\\3\\)"
2706 "\\([" post "]\\|$\\)"))
2707 (setq org-verbatim-re
2708 (concat "\\([" pre "]\\|^\\)"
2709 "\\("
2710 "\\([" vmarkers "]\\)"
2711 "\\("
2712 "[^" border "]\\|"
2713 "[^" border "]"
2714 body1
2715 "[^" border "]"
2716 "\\)"
2717 "\\3\\)"
2718 "\\([" post "]\\|$\\)")))))
2720 (defcustom org-emphasis-regexp-components
2721 '(" \t('\"{" "- \t.,:!?;'\")}" " \t\r\n,\"'" "." 1)
2722 "Components used to build the regular expression for emphasis.
2723 This is a list with 6 entries. Terminology: In an emphasis string
2724 like \" *strong word* \", we call the initial space PREMATCH, the final
2725 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2726 and \"trong wor\" is the body. The different components in this variable
2727 specify what is allowed/forbidden in each part:
2729 pre Chars allowed as prematch. Beginning of line will be allowed too.
2730 post Chars allowed as postmatch. End of line will be allowed too.
2731 border The chars *forbidden* as border characters.
2732 body-regexp A regexp like \".\" to match a body character. Don't use
2733 non-shy groups here, and don't allow newline here.
2734 newline The maximum number of newlines allowed in an emphasis exp.
2736 Use customize to modify this, or restart Emacs after changing it."
2737 :group 'org-font-lock
2738 :set 'org-set-emph-re
2739 :type '(list
2740 (sexp :tag "Allowed chars in pre ")
2741 (sexp :tag "Allowed chars in post ")
2742 (sexp :tag "Forbidden chars in border ")
2743 (sexp :tag "Regexp for body ")
2744 (integer :tag "number of newlines allowed")
2745 (option (boolean :tag "Please ignore this button"))))
2747 (defcustom org-emphasis-alist
2748 `(("*" bold "<b>" "</b>")
2749 ("/" italic "<i>" "</i>")
2750 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2751 ("=" org-code "<code>" "</code>" verbatim)
2752 ("~" org-verbatim "<code>" "</code>" verbatim)
2753 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2754 "<del>" "</del>")
2756 "Special syntax for emphasized text.
2757 Text starting and ending with a special character will be emphasized, for
2758 example *bold*, _underlined_ and /italic/. This variable sets the marker
2759 characters, the face to be used by font-lock for highlighting in Org-mode
2760 Emacs buffers, and the HTML tags to be used for this.
2761 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
2762 Use customize to modify this, or restart Emacs after changing it."
2763 :group 'org-font-lock
2764 :set 'org-set-emph-re
2765 :type '(repeat
2766 (list
2767 (string :tag "Marker character")
2768 (choice
2769 (face :tag "Font-lock-face")
2770 (plist :tag "Face property list"))
2771 (string :tag "HTML start tag")
2772 (string :tag "HTML end tag")
2773 (option (const verbatim)))))
2775 ;;; Miscellaneous options
2777 (defgroup org-completion nil
2778 "Completion in Org-mode."
2779 :tag "Org Completion"
2780 :group 'org)
2782 (defcustom org-completion-use-ido nil
2783 "Non-nil means, use ido completion wherever possible.
2784 Note that `ido-mode' must be active for this variable to be relevant.
2785 If you decide to turn this variable on, you might well want to turn off
2786 `org-outline-path-complete-in-steps'."
2787 :group 'org-completion
2788 :type 'boolean)
2790 (defcustom org-completion-fallback-command 'hippie-expand
2791 "The expansion command called by \\[org-complete] in normal context.
2792 Normal means, no org-mode-specific context."
2793 :group 'org-completion
2794 :type 'function)
2796 ;;; Functions and variables from ther packages
2797 ;; Declared here to avoid compiler warnings
2799 ;; XEmacs only
2800 (defvar outline-mode-menu-heading)
2801 (defvar outline-mode-menu-show)
2802 (defvar outline-mode-menu-hide)
2803 (defvar zmacs-regions) ; XEmacs regions
2805 ;; Emacs only
2806 (defvar mark-active)
2808 ;; Various packages
2809 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2810 (declare-function calendar-forward-day "cal-move" (arg))
2811 (declare-function calendar-goto-date "cal-move" (date))
2812 (declare-function calendar-goto-today "cal-move" ())
2813 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2814 (defvar calc-embedded-close-formula)
2815 (defvar calc-embedded-open-formula)
2816 (declare-function cdlatex-tab "ext:cdlatex" ())
2817 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2818 (defvar font-lock-unfontify-region-function)
2819 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2820 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2821 (defvar iswitchb-temp-buflist)
2822 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2823 (defvar org-agenda-tags-todo-honor-ignore-options)
2824 (declare-function org-agenda-skip "org-agenda" ())
2825 (declare-function org-format-agenda-item "org-agenda"
2826 (extra txt &optional category tags dotime noprefix remove-re))
2827 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2828 (declare-function org-agenda-change-all-lines "org-agenda"
2829 (newhead hdmarker &optional fixface just-this))
2830 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2831 (declare-function org-agenda-maybe-redo "org-agenda" ())
2832 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2833 (beg end))
2834 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2835 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2836 "org-agenda" (&optional end))
2838 (declare-function parse-time-string "parse-time" (string))
2839 (declare-function remember "remember" (&optional initial))
2840 (declare-function remember-buffer-desc "remember" ())
2841 (declare-function remember-finalize "remember" ())
2842 (defvar remember-save-after-remembering)
2843 (defvar remember-data-file)
2844 (defvar remember-register)
2845 (defvar remember-buffer)
2846 (defvar remember-handler-functions)
2847 (defvar remember-annotation-functions)
2848 (defvar texmathp-why)
2849 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2850 (declare-function table--at-cell-p "table" (position &optional object at-column))
2852 (defvar w3m-current-url)
2853 (defvar w3m-current-title)
2855 (defvar org-latex-regexps)
2857 ;;; Autoload and prepare some org modules
2859 ;; Some table stuff that needs to be defined here, because it is used
2860 ;; by the functions setting up org-mode or checking for table context.
2862 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2863 "Detects an org-type or table-type table.")
2864 (defconst org-table-line-regexp "^[ \t]*|"
2865 "Detects an org-type table line.")
2866 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2867 "Detects an org-type table line.")
2868 (defconst org-table-hline-regexp "^[ \t]*|-"
2869 "Detects an org-type table hline.")
2870 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2871 "Detects a table-type table hline.")
2872 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2873 "Searching from within a table (any type) this finds the first line
2874 outside the table.")
2876 ;; Autoload the functions in org-table.el that are needed by functions here.
2878 (eval-and-compile
2879 (org-autoload "org-table"
2880 '(org-table-align org-table-begin org-table-blank-field
2881 org-table-convert org-table-convert-region org-table-copy-down
2882 org-table-copy-region org-table-create
2883 org-table-create-or-convert-from-region
2884 org-table-create-with-table.el org-table-current-dline
2885 org-table-cut-region org-table-delete-column org-table-edit-field
2886 org-table-edit-formulas org-table-end org-table-eval-formula
2887 org-table-export org-table-field-info
2888 org-table-get-stored-formulas org-table-goto-column
2889 org-table-hline-and-move org-table-import org-table-insert-column
2890 org-table-insert-hline org-table-insert-row org-table-iterate
2891 org-table-justify-field-maybe org-table-kill-row
2892 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2893 org-table-move-column org-table-move-column-left
2894 org-table-move-column-right org-table-move-row
2895 org-table-move-row-down org-table-move-row-up
2896 org-table-next-field org-table-next-row org-table-paste-rectangle
2897 org-table-previous-field org-table-recalculate
2898 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2899 org-table-toggle-coordinate-overlays
2900 org-table-toggle-formula-debugger org-table-wrap-region
2901 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2903 (defun org-at-table-p (&optional table-type)
2904 "Return t if the cursor is inside an org-type table.
2905 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2906 (if org-enable-table-editor
2907 (save-excursion
2908 (beginning-of-line 1)
2909 (looking-at (if table-type org-table-any-line-regexp
2910 org-table-line-regexp)))
2911 nil))
2912 (defsubst org-table-p () (org-at-table-p))
2914 (defun org-at-table.el-p ()
2915 "Return t if and only if we are at a table.el table."
2916 (and (org-at-table-p 'any)
2917 (save-excursion
2918 (goto-char (org-table-begin 'any))
2919 (looking-at org-table1-hline-regexp))))
2920 (defun org-table-recognize-table.el ()
2921 "If there is a table.el table nearby, recognize it and move into it."
2922 (if org-table-tab-recognizes-table.el
2923 (if (org-at-table.el-p)
2924 (progn
2925 (beginning-of-line 1)
2926 (if (looking-at org-table-dataline-regexp)
2928 (if (looking-at org-table1-hline-regexp)
2929 (progn
2930 (beginning-of-line 2)
2931 (if (looking-at org-table-any-border-regexp)
2932 (beginning-of-line -1)))))
2933 (if (re-search-forward "|" (org-table-end t) t)
2934 (progn
2935 (require 'table)
2936 (if (table--at-cell-p (point))
2938 (message "recognizing table.el table...")
2939 (table-recognize-table)
2940 (message "recognizing table.el table...done")))
2941 (error "This should not happen..."))
2943 nil)
2944 nil))
2946 (defun org-at-table-hline-p ()
2947 "Return t if the cursor is inside a hline in a table."
2948 (if org-enable-table-editor
2949 (save-excursion
2950 (beginning-of-line 1)
2951 (looking-at org-table-hline-regexp))
2952 nil))
2954 (defvar org-table-clean-did-remove-column nil)
2956 (defun org-table-map-tables (function)
2957 "Apply FUNCTION to the start of all tables in the buffer."
2958 (save-excursion
2959 (save-restriction
2960 (widen)
2961 (goto-char (point-min))
2962 (while (re-search-forward org-table-any-line-regexp nil t)
2963 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2964 (beginning-of-line 1)
2965 (if (looking-at org-table-line-regexp)
2966 (save-excursion (funcall function)))
2967 (re-search-forward org-table-any-border-regexp nil 1))))
2968 (message "Mapping tables: done"))
2970 ;; Declare and autoload functions from org-exp.el & Co
2972 (declare-function org-default-export-plist "org-exp")
2973 (declare-function org-infile-export-plist "org-exp")
2974 (declare-function org-get-current-options "org-exp")
2975 (eval-and-compile
2976 (org-autoload "org-exp"
2977 '(org-export org-export-visible
2978 org-insert-export-options-template
2979 org-table-clean-before-export))
2980 (org-autoload "org-ascii"
2981 '(org-export-as-ascii org-export-ascii-preprocess
2982 org-export-as-ascii-to-buffer org-replace-region-by-ascii
2983 org-export-region-as-ascii))
2984 (org-autoload "org-html"
2985 '(org-export-as-html-and-open
2986 org-export-as-html-batch org-export-as-html-to-buffer
2987 org-replace-region-by-html org-export-region-as-html
2988 org-export-as-html))
2989 (org-autoload "org-icalendar"
2990 '(org-export-icalendar-this-file
2991 org-export-icalendar-all-agenda-files
2992 org-export-icalendar-combine-agenda-files))
2993 (org-autoload "org-xoxo" '(org-export-as-xoxo)))
2995 ;; Declare and autoload functions from org-agenda.el
2997 (eval-and-compile
2998 (org-autoload "org-agenda"
2999 '(org-agenda org-agenda-list org-search-view
3000 org-todo-list org-tags-view org-agenda-list-stuck-projects
3001 org-diary org-agenda-to-appt
3002 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3004 ;; Autoload org-remember
3006 (eval-and-compile
3007 (org-autoload "org-remember"
3008 '(org-remember-insinuate org-remember-annotation
3009 org-remember-apply-template org-remember org-remember-handler)))
3011 ;; Autoload org-clock.el
3014 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3015 (beg end))
3016 (declare-function org-clock-update-mode-line "org-clock" ())
3017 (defvar org-clock-start-time)
3018 (defvar org-clock-marker (make-marker)
3019 "Marker recording the last clock-in.")
3021 (eval-and-compile
3022 (org-autoload
3023 "org-clock"
3024 '(org-clock-in org-clock-out org-clock-cancel
3025 org-clock-goto org-clock-sum org-clock-display
3026 org-clock-remove-overlays org-clock-report
3027 org-clocktable-shift org-dblock-write:clocktable
3028 org-get-clocktable)))
3030 (defun org-clock-update-time-maybe ()
3031 "If this is a CLOCK line, update it and return t.
3032 Otherwise, return nil."
3033 (interactive)
3034 (save-excursion
3035 (beginning-of-line 1)
3036 (skip-chars-forward " \t")
3037 (when (looking-at org-clock-string)
3038 (let ((re (concat "[ \t]*" org-clock-string
3039 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3040 "\\([ \t]*=>.*\\)?\\)?"))
3041 ts te h m s neg)
3042 (cond
3043 ((not (looking-at re))
3044 nil)
3045 ((not (match-end 2))
3046 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3047 (> org-clock-marker (point))
3048 (<= org-clock-marker (point-at-eol)))
3049 ;; The clock is running here
3050 (setq org-clock-start-time
3051 (apply 'encode-time
3052 (org-parse-time-string (match-string 1))))
3053 (org-clock-update-mode-line)))
3055 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3056 (end-of-line 1)
3057 (setq ts (match-string 1)
3058 te (match-string 3))
3059 (setq s (- (time-to-seconds
3060 (apply 'encode-time (org-parse-time-string te)))
3061 (time-to-seconds
3062 (apply 'encode-time (org-parse-time-string ts))))
3063 neg (< s 0)
3064 s (abs s)
3065 h (floor (/ s 3600))
3066 s (- s (* 3600 h))
3067 m (floor (/ s 60))
3068 s (- s (* 60 s)))
3069 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3070 t))))))
3072 (defun org-check-running-clock ()
3073 "Check if the current buffer contains the running clock.
3074 If yes, offer to stop it and to save the buffer with the changes."
3075 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3076 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3077 (buffer-name))))
3078 (org-clock-out)
3079 (when (y-or-n-p "Save changed buffer?")
3080 (save-buffer))))
3082 (defun org-clocktable-try-shift (dir n)
3083 "Check if this line starts a clock table, if yes, shift the time block."
3084 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3085 (org-clocktable-shift dir n)))
3087 ;; Autoload org-timer.el
3089 (eval-and-compile
3090 (org-autoload
3091 "org-timer"
3092 '(org-timer-start org-timer org-timer-item
3093 org-timer-change-times-in-region)))
3095 ;; Autoload org-feed.el
3097 (eval-and-compile
3098 (org-autoload
3099 "org-feed"
3100 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3103 ;; Autoload archiving code
3104 ;; The stuff that is needed for cycling and tags has to be defined here.
3106 (defgroup org-archive nil
3107 "Options concerning archiving in Org-mode."
3108 :tag "Org Archive"
3109 :group 'org-structure)
3111 (defcustom org-archive-location "%s_archive::"
3112 "The location where subtrees should be archived.
3114 The value of this variable is a string, consisting of two parts,
3115 separated by a double-colon. The first part is a filename and
3116 the second part is a headline.
3118 When the filename is omitted, archiving happens in the same file.
3119 %s in the filename will be replaced by the current file
3120 name (without the directory part). Archiving to a different file
3121 is useful to keep archived entries from contributing to the
3122 Org-mode Agenda.
3124 The archived entries will be filed as subtrees of the specified
3125 headline. When the headline is omitted, the subtrees are simply
3126 filed away at the end of the file, as top-level entries. Also in
3127 the heading you can use %s to represent the file name, this can be
3128 useful when using the same archive for a number of different files.
3130 Here are a few examples:
3131 \"%s_archive::\"
3132 If the current file is Projects.org, archive in file
3133 Projects.org_archive, as top-level trees. This is the default.
3135 \"::* Archived Tasks\"
3136 Archive in the current file, under the top-level headline
3137 \"* Archived Tasks\".
3139 \"~/org/archive.org::\"
3140 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3142 \"~/org/archive.org::From %s\"
3143 Archive in file ~/org/archive.org (absolute path), und headlines
3144 \"From FILENAME\" where file name is the current file name.
3146 \"basement::** Finished Tasks\"
3147 Archive in file ./basement (relative path), as level 3 trees
3148 below the level 2 heading \"** Finished Tasks\".
3150 You may set this option on a per-file basis by adding to the buffer a
3151 line like
3153 #+ARCHIVE: basement::** Finished Tasks
3155 You may also define it locally for a subtree by setting an ARCHIVE property
3156 in the entry. If such a property is found in an entry, or anywhere up
3157 the hierarchy, it will be used."
3158 :group 'org-archive
3159 :type 'string)
3161 (defcustom org-archive-tag "ARCHIVE"
3162 "The tag that marks a subtree as archived.
3163 An archived subtree does not open during visibility cycling, and does
3164 not contribute to the agenda listings.
3165 After changing this, font-lock must be restarted in the relevant buffers to
3166 get the proper fontification."
3167 :group 'org-archive
3168 :group 'org-keywords
3169 :type 'string)
3171 (defcustom org-agenda-skip-archived-trees t
3172 "Non-nil means, the agenda will skip any items located in archived trees.
3173 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3174 variable is no longer recommended, you should leave it at the value t.
3175 Instead, use the key `v' to cycle the archives-mode in the agenda."
3176 :group 'org-archive
3177 :group 'org-agenda-skip
3178 :type 'boolean)
3180 (defcustom org-columns-skip-arrchived-trees t
3181 "Non-nil means, irgnore archived trees when creating column view."
3182 :group 'org-archive
3183 :group 'org-properties
3184 :type 'boolean)
3186 (defcustom org-cycle-open-archived-trees nil
3187 "Non-nil means, `org-cycle' will open archived trees.
3188 An archived tree is a tree marked with the tag ARCHIVE.
3189 When nil, archived trees will stay folded. You can still open them with
3190 normal outline commands like `show-all', but not with the cycling commands."
3191 :group 'org-archive
3192 :group 'org-cycle
3193 :type 'boolean)
3195 (defcustom org-sparse-tree-open-archived-trees nil
3196 "Non-nil means sparse tree construction shows matches in archived trees.
3197 When nil, matches in these trees are highlighted, but the trees are kept in
3198 collapsed state."
3199 :group 'org-archive
3200 :group 'org-sparse-trees
3201 :type 'boolean)
3203 (defun org-cycle-hide-archived-subtrees (state)
3204 "Re-hide all archived subtrees after a visibility state change."
3205 (when (and (not org-cycle-open-archived-trees)
3206 (not (memq state '(overview folded))))
3207 (save-excursion
3208 (let* ((globalp (memq state '(contents all)))
3209 (beg (if globalp (point-min) (point)))
3210 (end (if globalp (point-max) (org-end-of-subtree t))))
3211 (org-hide-archived-subtrees beg end)
3212 (goto-char beg)
3213 (if (looking-at (concat ".*:" org-archive-tag ":"))
3214 (message "%s" (substitute-command-keys
3215 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3217 (defun org-force-cycle-archived ()
3218 "Cycle subtree even if it is archived."
3219 (interactive)
3220 (setq this-command 'org-cycle)
3221 (let ((org-cycle-open-archived-trees t))
3222 (call-interactively 'org-cycle)))
3224 (defun org-hide-archived-subtrees (beg end)
3225 "Re-hide all archived subtrees after a visibility state change."
3226 (save-excursion
3227 (let* ((re (concat ":" org-archive-tag ":")))
3228 (goto-char beg)
3229 (while (re-search-forward re end t)
3230 (and (org-on-heading-p) (hide-subtree))
3231 (org-end-of-subtree t)))))
3233 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3235 (eval-and-compile
3236 (org-autoload "org-archive"
3237 '(org-add-archive-files org-archive-subtree
3238 org-archive-to-archive-sibling org-toggle-archive-tag)))
3240 ;; Autoload Column View Code
3242 (declare-function org-columns-number-to-string "org-colview")
3243 (declare-function org-columns-get-format-and-top-level "org-colview")
3244 (declare-function org-columns-compute "org-colview")
3246 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3247 '(org-columns-number-to-string org-columns-get-format-and-top-level
3248 org-columns-compute org-agenda-columns org-columns-remove-overlays
3249 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3251 ;; Autoload ID code
3253 (declare-function org-id-store-link "org-id")
3254 (declare-function org-id-locations-load "org-id")
3255 (declare-function org-id-locations-save "org-id")
3256 (defvar org-id-track-globally)
3257 (org-autoload "org-id"
3258 '(org-id-get-create org-id-new org-id-copy org-id-get
3259 org-id-get-with-outline-path-completion
3260 org-id-get-with-outline-drilling
3261 org-id-goto org-id-find org-id-store-link))
3263 ;; Autoload Plotting Code
3265 (org-autoload "org-plot"
3266 '(org-plot/gnuplot))
3268 ;;; Variables for pre-computed regular expressions, all buffer local
3270 (defvar org-drawer-regexp nil
3271 "Matches first line of a hidden block.")
3272 (make-variable-buffer-local 'org-drawer-regexp)
3273 (defvar org-todo-regexp nil
3274 "Matches any of the TODO state keywords.")
3275 (make-variable-buffer-local 'org-todo-regexp)
3276 (defvar org-not-done-regexp nil
3277 "Matches any of the TODO state keywords except the last one.")
3278 (make-variable-buffer-local 'org-not-done-regexp)
3279 (defvar org-not-done-heading-regexp nil
3280 "Matches a TODO headline that is not done.")
3281 (make-variable-buffer-local 'org-not-done-regexp)
3282 (defvar org-todo-line-regexp nil
3283 "Matches a headline and puts TODO state into group 2 if present.")
3284 (make-variable-buffer-local 'org-todo-line-regexp)
3285 (defvar org-complex-heading-regexp nil
3286 "Matches a headline and puts everything into groups:
3287 group 1: the stars
3288 group 2: The todo keyword, maybe
3289 group 3: Priority cookie
3290 group 4: True headline
3291 group 5: Tags")
3292 (make-variable-buffer-local 'org-complex-heading-regexp)
3293 (defvar org-todo-line-tags-regexp nil
3294 "Matches a headline and puts TODO state into group 2 if present.
3295 Also put tags into group 4 if tags are present.")
3296 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3297 (defvar org-nl-done-regexp nil
3298 "Matches newline followed by a headline with the DONE keyword.")
3299 (make-variable-buffer-local 'org-nl-done-regexp)
3300 (defvar org-looking-at-done-regexp nil
3301 "Matches the DONE keyword a point.")
3302 (make-variable-buffer-local 'org-looking-at-done-regexp)
3303 (defvar org-ds-keyword-length 12
3304 "Maximum length of the Deadline and SCHEDULED keywords.")
3305 (make-variable-buffer-local 'org-ds-keyword-length)
3306 (defvar org-deadline-regexp nil
3307 "Matches the DEADLINE keyword.")
3308 (make-variable-buffer-local 'org-deadline-regexp)
3309 (defvar org-deadline-time-regexp nil
3310 "Matches the DEADLINE keyword together with a time stamp.")
3311 (make-variable-buffer-local 'org-deadline-time-regexp)
3312 (defvar org-deadline-line-regexp nil
3313 "Matches the DEADLINE keyword and the rest of the line.")
3314 (make-variable-buffer-local 'org-deadline-line-regexp)
3315 (defvar org-scheduled-regexp nil
3316 "Matches the SCHEDULED keyword.")
3317 (make-variable-buffer-local 'org-scheduled-regexp)
3318 (defvar org-scheduled-time-regexp nil
3319 "Matches the SCHEDULED keyword together with a time stamp.")
3320 (make-variable-buffer-local 'org-scheduled-time-regexp)
3321 (defvar org-closed-time-regexp nil
3322 "Matches the CLOSED keyword together with a time stamp.")
3323 (make-variable-buffer-local 'org-closed-time-regexp)
3325 (defvar org-keyword-time-regexp nil
3326 "Matches any of the 4 keywords, together with the time stamp.")
3327 (make-variable-buffer-local 'org-keyword-time-regexp)
3328 (defvar org-keyword-time-not-clock-regexp nil
3329 "Matches any of the 3 keywords, together with the time stamp.")
3330 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3331 (defvar org-maybe-keyword-time-regexp nil
3332 "Matches a timestamp, possibly preceeded by a keyword.")
3333 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3334 (defvar org-planning-or-clock-line-re nil
3335 "Matches a line with planning or clock info.")
3336 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3338 (defconst org-plain-time-of-day-regexp
3339 (concat
3340 "\\(\\<[012]?[0-9]"
3341 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3342 "\\(--?"
3343 "\\(\\<[012]?[0-9]"
3344 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3345 "\\)?")
3346 "Regular expression to match a plain time or time range.
3347 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3348 groups carry important information:
3349 0 the full match
3350 1 the first time, range or not
3351 8 the second time, if it is a range.")
3353 (defconst org-plain-time-extension-regexp
3354 (concat
3355 "\\(\\<[012]?[0-9]"
3356 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3357 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3358 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3359 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3360 groups carry important information:
3361 0 the full match
3362 7 hours of duration
3363 9 minutes of duration")
3365 (defconst org-stamp-time-of-day-regexp
3366 (concat
3367 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3368 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3369 "\\(--?"
3370 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3371 "Regular expression to match a timestamp time or time range.
3372 After a match, the following groups carry important information:
3373 0 the full match
3374 1 date plus weekday, for backreferencing to make sure both times on same day
3375 2 the first time, range or not
3376 4 the second time, if it is a range.")
3378 (defconst org-startup-options
3379 '(("fold" org-startup-folded t)
3380 ("overview" org-startup-folded t)
3381 ("nofold" org-startup-folded nil)
3382 ("showall" org-startup-folded nil)
3383 ("content" org-startup-folded content)
3384 ("hidestars" org-hide-leading-stars t)
3385 ("showstars" org-hide-leading-stars nil)
3386 ("odd" org-odd-levels-only t)
3387 ("oddeven" org-odd-levels-only nil)
3388 ("align" org-startup-align-all-tables t)
3389 ("noalign" org-startup-align-all-tables nil)
3390 ("customtime" org-display-custom-times t)
3391 ("logdone" org-log-done time)
3392 ("lognotedone" org-log-done note)
3393 ("nologdone" org-log-done nil)
3394 ("lognoteclock-out" org-log-note-clock-out t)
3395 ("nolognoteclock-out" org-log-note-clock-out nil)
3396 ("logrepeat" org-log-repeat state)
3397 ("lognoterepeat" org-log-repeat note)
3398 ("nologrepeat" org-log-repeat nil)
3399 ("fninline" org-footnote-define-inline t)
3400 ("nofninline" org-footnote-define-inline nil)
3401 ("fnlocal" org-footnote-section nil)
3402 ("fnauto" org-footnote-auto-label t)
3403 ("fnprompt" org-footnote-auto-label nil)
3404 ("fnconfirm" org-footnote-auto-label confirm)
3405 ("fnplain" org-footnote-auto-label plain)
3406 ("constcgs" constants-unit-system cgs)
3407 ("constSI" constants-unit-system SI)
3408 ("noptag" org-tag-persistent-alist nil)
3409 ("hideblocks" org-hide-block-startup t)
3410 ("nohideblocks" org-hide-block-startup nil))
3411 "Variable associated with STARTUP options for org-mode.
3412 Each element is a list of three items: The startup options as written
3413 in the #+STARTUP line, the corresponding variable, and the value to
3414 set this variable to if the option is found. An optional forth element PUSH
3415 means to push this value onto the list in the variable.")
3417 (defun org-set-regexps-and-options ()
3418 "Precompute regular expressions for current buffer."
3419 (when (org-mode-p)
3420 (org-set-local 'org-todo-kwd-alist nil)
3421 (org-set-local 'org-todo-key-alist nil)
3422 (org-set-local 'org-todo-key-trigger nil)
3423 (org-set-local 'org-todo-keywords-1 nil)
3424 (org-set-local 'org-done-keywords nil)
3425 (org-set-local 'org-todo-heads nil)
3426 (org-set-local 'org-todo-sets nil)
3427 (org-set-local 'org-todo-log-states nil)
3428 (org-set-local 'org-file-properties nil)
3429 (org-set-local 'org-file-tags nil)
3430 (let ((re (org-make-options-regexp
3431 '("CATEGORY" "TODO" "COLUMNS"
3432 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3433 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3434 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3435 (splitre "[ \t]+")
3436 kwds kws0 kwsa key log value cat arch tags const links hw dws
3437 tail sep kws1 prio props ftags drawers
3438 ext-setup-or-nil setup-contents (start 0))
3439 (save-excursion
3440 (save-restriction
3441 (widen)
3442 (goto-char (point-min))
3443 (while (or (and ext-setup-or-nil
3444 (string-match re ext-setup-or-nil start)
3445 (setq start (match-end 0)))
3446 (and (setq ext-setup-or-nil nil start 0)
3447 (re-search-forward re nil t)))
3448 (setq key (upcase (match-string 1 ext-setup-or-nil))
3449 value (org-match-string-no-properties 2 ext-setup-or-nil))
3450 (cond
3451 ((equal key "CATEGORY")
3452 (if (string-match "[ \t]+$" value)
3453 (setq value (replace-match "" t t value)))
3454 (setq cat value))
3455 ((member key '("SEQ_TODO" "TODO"))
3456 (push (cons 'sequence (org-split-string value splitre)) kwds))
3457 ((equal key "TYP_TODO")
3458 (push (cons 'type (org-split-string value splitre)) kwds))
3459 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3460 ;; general TODO-like setup
3461 (push (cons (intern (downcase (match-string 1 key)))
3462 (org-split-string value splitre)) kwds))
3463 ((equal key "TAGS")
3464 (setq tags (append tags (if tags '("\\n") nil)
3465 (org-split-string value splitre))))
3466 ((equal key "COLUMNS")
3467 (org-set-local 'org-columns-default-format value))
3468 ((equal key "LINK")
3469 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3470 (push (cons (match-string 1 value)
3471 (org-trim (match-string 2 value)))
3472 links)))
3473 ((equal key "PRIORITIES")
3474 (setq prio (org-split-string value " +")))
3475 ((equal key "PROPERTY")
3476 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3477 (push (cons (match-string 1 value) (match-string 2 value))
3478 props)))
3479 ((equal key "FILETAGS")
3480 (when (string-match "\\S-" value)
3481 (setq ftags
3482 (append
3483 ftags
3484 (apply 'append
3485 (mapcar (lambda (x) (org-split-string x ":"))
3486 (org-split-string value)))))))
3487 ((equal key "DRAWERS")
3488 (setq drawers (org-split-string value splitre)))
3489 ((equal key "CONSTANTS")
3490 (setq const (append const (org-split-string value splitre))))
3491 ((equal key "STARTUP")
3492 (let ((opts (org-split-string value splitre))
3493 l var val)
3494 (while (setq l (pop opts))
3495 (when (setq l (assoc l org-startup-options))
3496 (setq var (nth 1 l) val (nth 2 l))
3497 (if (not (nth 3 l))
3498 (set (make-local-variable var) val)
3499 (if (not (listp (symbol-value var)))
3500 (set (make-local-variable var) nil))
3501 (set (make-local-variable var) (symbol-value var))
3502 (add-to-list var val))))))
3503 ((equal key "ARCHIVE")
3504 (string-match " *$" value)
3505 (setq arch (replace-match "" t t value))
3506 (remove-text-properties 0 (length arch)
3507 '(face t fontified t) arch))
3508 ((equal key "SETUPFILE")
3509 (setq setup-contents (org-file-contents
3510 (expand-file-name
3511 (org-remove-double-quotes value))
3512 'noerror))
3513 (if (not ext-setup-or-nil)
3514 (setq ext-setup-or-nil setup-contents start 0)
3515 (setq ext-setup-or-nil
3516 (concat (substring ext-setup-or-nil 0 start)
3517 "\n" setup-contents "\n"
3518 (substring ext-setup-or-nil start)))))
3519 ))))
3520 (when cat
3521 (org-set-local 'org-category (intern cat))
3522 (push (cons "CATEGORY" cat) props))
3523 (when prio
3524 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3525 (setq prio (mapcar 'string-to-char prio))
3526 (org-set-local 'org-highest-priority (nth 0 prio))
3527 (org-set-local 'org-lowest-priority (nth 1 prio))
3528 (org-set-local 'org-default-priority (nth 2 prio)))
3529 (and props (org-set-local 'org-file-properties (nreverse props)))
3530 (and ftags (org-set-local 'org-file-tags
3531 (mapcar 'org-add-prop-inherited ftags)))
3532 (and drawers (org-set-local 'org-drawers drawers))
3533 (and arch (org-set-local 'org-archive-location arch))
3534 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3535 ;; Process the TODO keywords
3536 (unless kwds
3537 ;; Use the global values as if they had been given locally.
3538 (setq kwds (default-value 'org-todo-keywords))
3539 (if (stringp (car kwds))
3540 (setq kwds (list (cons org-todo-interpretation
3541 (default-value 'org-todo-keywords)))))
3542 (setq kwds (reverse kwds)))
3543 (setq kwds (nreverse kwds))
3544 (let (inter kws kw)
3545 (while (setq kws (pop kwds))
3546 (let ((kws (or
3547 (run-hook-with-args-until-success
3548 'org-todo-setup-filter-hook kws)
3549 kws)))
3550 (setq inter (pop kws) sep (member "|" kws)
3551 kws0 (delete "|" (copy-sequence kws))
3552 kwsa nil
3553 kws1 (mapcar
3554 (lambda (x)
3555 ;; 1 2
3556 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3557 (progn
3558 (setq kw (match-string 1 x)
3559 key (and (match-end 2) (match-string 2 x))
3560 log (org-extract-log-state-settings x))
3561 (push (cons kw (and key (string-to-char key))) kwsa)
3562 (and log (push log org-todo-log-states))
3564 (error "Invalid TODO keyword %s" x)))
3565 kws0)
3566 kwsa (if kwsa (append '((:startgroup))
3567 (nreverse kwsa)
3568 '((:endgroup))))
3569 hw (car kws1)
3570 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3571 tail (list inter hw (car dws) (org-last dws))))
3572 (add-to-list 'org-todo-heads hw 'append)
3573 (push kws1 org-todo-sets)
3574 (setq org-done-keywords (append org-done-keywords dws nil))
3575 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3576 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3577 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3578 (setq org-todo-sets (nreverse org-todo-sets)
3579 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3580 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3581 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3582 ;; Process the constants
3583 (when const
3584 (let (e cst)
3585 (while (setq e (pop const))
3586 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3587 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3588 (setq org-table-formula-constants-local cst)))
3590 ;; Process the tags.
3591 (when tags
3592 (let (e tgs)
3593 (while (setq e (pop tags))
3594 (cond
3595 ((equal e "{") (push '(:startgroup) tgs))
3596 ((equal e "}") (push '(:endgroup) tgs))
3597 ((equal e "\\n") (push '(:newline) tgs))
3598 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3599 (push (cons (match-string 1 e)
3600 (string-to-char (match-string 2 e)))
3601 tgs))
3602 (t (push (list e) tgs))))
3603 (org-set-local 'org-tag-alist nil)
3604 (while (setq e (pop tgs))
3605 (or (and (stringp (car e))
3606 (assoc (car e) org-tag-alist))
3607 (push e org-tag-alist)))))
3609 ;; Compute the regular expressions and other local variables
3610 (if (not org-done-keywords)
3611 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3612 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3613 (length org-scheduled-string)
3614 (length org-clock-string)
3615 (length org-closed-string)))
3616 org-drawer-regexp
3617 (concat "^[ \t]*:\\("
3618 (mapconcat 'regexp-quote org-drawers "\\|")
3619 "\\):[ \t]*$")
3620 org-not-done-keywords
3621 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3622 org-todo-regexp
3623 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3624 "\\|") "\\)\\>")
3625 org-not-done-regexp
3626 (concat "\\<\\("
3627 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3628 "\\)\\>")
3629 org-not-done-heading-regexp
3630 (concat "^\\(\\*+\\)[ \t]+\\("
3631 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3632 "\\)\\>")
3633 org-todo-line-regexp
3634 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3635 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3636 "\\)\\>\\)?[ \t]*\\(.*\\)")
3637 org-complex-heading-regexp
3638 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3639 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3640 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3641 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3642 org-nl-done-regexp
3643 (concat "\n\\*+[ \t]+"
3644 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3645 "\\)" "\\>")
3646 org-todo-line-tags-regexp
3647 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3648 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3649 (org-re
3650 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3651 org-looking-at-done-regexp
3652 (concat "^" "\\(?:"
3653 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3654 "\\>")
3655 org-deadline-regexp (concat "\\<" org-deadline-string)
3656 org-deadline-time-regexp
3657 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3658 org-deadline-line-regexp
3659 (concat "\\<\\(" org-deadline-string "\\).*")
3660 org-scheduled-regexp
3661 (concat "\\<" org-scheduled-string)
3662 org-scheduled-time-regexp
3663 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3664 org-closed-time-regexp
3665 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3666 org-keyword-time-regexp
3667 (concat "\\<\\(" org-scheduled-string
3668 "\\|" org-deadline-string
3669 "\\|" org-closed-string
3670 "\\|" org-clock-string "\\)"
3671 " *[[<]\\([^]>]+\\)[]>]")
3672 org-keyword-time-not-clock-regexp
3673 (concat "\\<\\(" org-scheduled-string
3674 "\\|" org-deadline-string
3675 "\\|" org-closed-string
3676 "\\)"
3677 " *[[<]\\([^]>]+\\)[]>]")
3678 org-maybe-keyword-time-regexp
3679 (concat "\\(\\<\\(" org-scheduled-string
3680 "\\|" org-deadline-string
3681 "\\|" org-closed-string
3682 "\\|" org-clock-string "\\)\\)?"
3683 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3684 org-planning-or-clock-line-re
3685 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3686 "\\|" org-deadline-string
3687 "\\|" org-closed-string "\\|" org-clock-string
3688 "\\)\\>\\)")
3690 (org-compute-latex-and-specials-regexp)
3691 (org-set-font-lock-defaults))))
3693 (defun org-file-contents (file &optional noerror)
3694 "Return the contents of FILE, as a string."
3695 (if (or (not file)
3696 (not (file-readable-p file)))
3697 (if noerror
3698 (progn
3699 (message "Cannot read file %s" file)
3700 (ding) (sit-for 2)
3702 (error "Cannot read file %s" file))
3703 (with-temp-buffer
3704 (insert-file-contents file)
3705 (buffer-string))))
3707 (defun org-extract-log-state-settings (x)
3708 "Extract the log state setting from a TODO keyword string.
3709 This will extract info from a string like \"WAIT(w@/!)\"."
3710 (let (kw key log1 log2)
3711 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3712 (setq kw (match-string 1 x)
3713 key (and (match-end 2) (match-string 2 x))
3714 log1 (and (match-end 3) (match-string 3 x))
3715 log2 (and (match-end 4) (match-string 4 x)))
3716 (and (or log1 log2)
3717 (list kw
3718 (and log1 (if (equal log1 "!") 'time 'note))
3719 (and log2 (if (equal log2 "!") 'time 'note)))))))
3721 (defun org-remove-keyword-keys (list)
3722 "Remove a pair of parenthesis at the end of each string in LIST."
3723 (mapcar (lambda (x)
3724 (if (string-match "(.*)$" x)
3725 (substring x 0 (match-beginning 0))
3727 list))
3729 ;; FIXME: this could be done much better, using second characters etc.
3730 (defun org-assign-fast-keys (alist)
3731 "Assign fast keys to a keyword-key alist.
3732 Respect keys that are already there."
3733 (let (new e k c c1 c2 (char ?a))
3734 (while (setq e (pop alist))
3735 (cond
3736 ((equal e '(:startgroup)) (push e new))
3737 ((equal e '(:endgroup)) (push e new))
3738 ((equal e '(:newline)) (push e new))
3740 (setq k (car e) c2 nil)
3741 (if (cdr e)
3742 (setq c (cdr e))
3743 ;; automatically assign a character.
3744 (setq c1 (string-to-char
3745 (downcase (substring
3746 k (if (= (string-to-char k) ?@) 1 0)))))
3747 (if (or (rassoc c1 new) (rassoc c1 alist))
3748 (while (or (rassoc char new) (rassoc char alist))
3749 (setq char (1+ char)))
3750 (setq c2 c1))
3751 (setq c (or c2 char)))
3752 (push (cons k c) new))))
3753 (nreverse new)))
3755 ;;; Some variables used in various places
3757 (defvar org-window-configuration nil
3758 "Used in various places to store a window configuration.")
3759 (defvar org-finish-function nil
3760 "Function to be called when `C-c C-c' is used.
3761 This is for getting out of special buffers like remember.")
3764 ;; FIXME: Occasionally check by commenting these, to make sure
3765 ;; no other functions uses these, forgetting to let-bind them.
3766 (defvar entry)
3767 (defvar last-state)
3768 (defvar date)
3770 ;; Defined somewhere in this file, but used before definition.
3771 (defvar org-html-entities)
3772 (defvar org-struct-menu)
3773 (defvar org-org-menu)
3774 (defvar org-tbl-menu)
3775 (defvar org-agenda-keymap)
3777 ;;;; Define the Org-mode
3779 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3780 (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."))
3783 ;; We use a before-change function to check if a table might need
3784 ;; an update.
3785 (defvar org-table-may-need-update t
3786 "Indicates that a table might need an update.
3787 This variable is set by `org-before-change-function'.
3788 `org-table-align' sets it back to nil.")
3789 (defun org-before-change-function (beg end)
3790 "Every change indicates that a table might need an update."
3791 (setq org-table-may-need-update t))
3792 (defvar org-mode-map)
3793 (defvar org-mode-hook nil
3794 "Mode hook for Org-mode, run after the mode was turned on.")
3795 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3796 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3797 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
3798 (defvar org-table-buffer-is-an nil)
3799 (defconst org-outline-regexp "\\*+ ")
3801 ;;;###autoload
3802 (define-derived-mode org-mode outline-mode "Org"
3803 "Outline-based notes management and organizer, alias
3804 \"Carsten's outline-mode for keeping track of everything.\"
3806 Org-mode develops organizational tasks around a NOTES file which
3807 contains information about projects as plain text. Org-mode is
3808 implemented on top of outline-mode, which is ideal to keep the content
3809 of large files well structured. It supports ToDo items, deadlines and
3810 time stamps, which magically appear in the diary listing of the Emacs
3811 calendar. Tables are easily created with a built-in table editor.
3812 Plain text URL-like links connect to websites, emails (VM), Usenet
3813 messages (Gnus), BBDB entries, and any files related to the project.
3814 For printing and sharing of notes, an Org-mode file (or a part of it)
3815 can be exported as a structured ASCII or HTML file.
3817 The following commands are available:
3819 \\{org-mode-map}"
3821 ;; Get rid of Outline menus, they are not needed
3822 ;; Need to do this here because define-derived-mode sets up
3823 ;; the keymap so late. Still, it is a waste to call this each time
3824 ;; we switch another buffer into org-mode.
3825 (if (featurep 'xemacs)
3826 (when (boundp 'outline-mode-menu-heading)
3827 ;; Assume this is Greg's port, it used easymenu
3828 (easy-menu-remove outline-mode-menu-heading)
3829 (easy-menu-remove outline-mode-menu-show)
3830 (easy-menu-remove outline-mode-menu-hide))
3831 (define-key org-mode-map [menu-bar headings] 'undefined)
3832 (define-key org-mode-map [menu-bar hide] 'undefined)
3833 (define-key org-mode-map [menu-bar show] 'undefined))
3835 (org-load-modules-maybe)
3836 (easy-menu-add org-org-menu)
3837 (easy-menu-add org-tbl-menu)
3838 (org-install-agenda-files-menu)
3839 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3840 (org-add-to-invisibility-spec '(org-cwidth))
3841 (org-add-to-invisibility-spec '(org-hide-block . t))
3842 (when (featurep 'xemacs)
3843 (org-set-local 'line-move-ignore-invisible t))
3844 (org-set-local 'outline-regexp org-outline-regexp)
3845 (org-set-local 'outline-level 'org-outline-level)
3846 (when (and org-ellipsis
3847 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3848 (fboundp 'make-glyph-code))
3849 (unless org-display-table
3850 (setq org-display-table (make-display-table)))
3851 (set-display-table-slot
3852 org-display-table 4
3853 (vconcat (mapcar
3854 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3855 org-ellipsis)))
3856 (if (stringp org-ellipsis) org-ellipsis "..."))))
3857 (setq buffer-display-table org-display-table))
3858 (org-set-regexps-and-options)
3859 (when (and org-tag-faces (not org-tags-special-faces-re))
3860 ;; tag faces set outside customize.... force initialization.
3861 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3862 ;; Calc embedded
3863 (org-set-local 'calc-embedded-open-mode "# ")
3864 (modify-syntax-entry ?# "<")
3865 (modify-syntax-entry ?@ "w")
3866 (if org-startup-truncated (setq truncate-lines t))
3867 (org-set-local 'font-lock-unfontify-region-function
3868 'org-unfontify-region)
3869 ;; Activate before-change-function
3870 (org-set-local 'org-table-may-need-update t)
3871 (org-add-hook 'before-change-functions 'org-before-change-function nil
3872 'local)
3873 ;; Check for running clock before killing a buffer
3874 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3875 ;; Paragraphs and auto-filling
3876 (org-set-autofill-regexps)
3877 (setq indent-line-function 'org-indent-line-function)
3878 (org-update-radio-target-regexp)
3879 ;; Make sure dependence stuff works reliably, even for users who set it
3880 ;; too late :-(
3881 (if org-enforce-todo-dependencies
3882 (add-hook 'org-blocker-hook
3883 'org-block-todo-from-children-or-siblings-or-parent)
3884 (remove-hook 'org-blocker-hook
3885 'org-block-todo-from-children-or-siblings-or-parent))
3886 (if org-enforce-todo-checkbox-dependencies
3887 (add-hook 'org-blocker-hook
3888 'org-block-todo-from-checkboxes)
3889 (remove-hook 'org-blocker-hook
3890 'org-block-todo-from-checkboxes))
3892 ;; Comment characters
3893 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3894 (org-set-local 'comment-padding " ")
3896 ;; Align options lines
3897 (org-set-local
3898 'align-mode-rules-list
3899 '((org-in-buffer-settings
3900 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3901 (modes . '(org-mode)))))
3903 ;; Imenu
3904 (org-set-local 'imenu-create-index-function
3905 'org-imenu-get-tree)
3907 ;; Make isearch reveal context
3908 (if (or (featurep 'xemacs)
3909 (not (boundp 'outline-isearch-open-invisible-function)))
3910 ;; Emacs 21 and XEmacs make use of the hook
3911 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3912 ;; Emacs 22 deals with this through a special variable
3913 (org-set-local 'outline-isearch-open-invisible-function
3914 (lambda (&rest ignore) (org-show-context 'isearch))))
3916 ;; If empty file that did not turn on org-mode automatically, make it to.
3917 (if (and org-insert-mode-line-in-empty-file
3918 (interactive-p)
3919 (= (point-min) (point-max)))
3920 (insert "# -*- mode: org -*-\n\n"))
3922 (unless org-inhibit-startup
3923 (when org-startup-align-all-tables
3924 (let ((bmp (buffer-modified-p)))
3925 (org-table-map-tables 'org-table-align)
3926 (set-buffer-modified-p bmp)))
3927 (org-set-startup-visibility)))
3929 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3931 (defun org-current-time ()
3932 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3933 (if (> (car org-time-stamp-rounding-minutes) 1)
3934 (let ((r (car org-time-stamp-rounding-minutes))
3935 (time (decode-time)))
3936 (apply 'encode-time
3937 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3938 (nthcdr 2 time))))
3939 (current-time)))
3941 ;;;; Font-Lock stuff, including the activators
3943 (defvar org-mouse-map (make-sparse-keymap))
3944 (org-defkey org-mouse-map
3945 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3946 (org-defkey org-mouse-map
3947 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3948 (when org-mouse-1-follows-link
3949 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3950 (when org-tab-follows-link
3951 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3952 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3954 (require 'font-lock)
3956 (defconst org-non-link-chars "]\t\n\r<>")
3957 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3958 "shell" "elisp"))
3959 (defvar org-link-types-re nil
3960 "Matches a link that has a url-like prefix like \"http:\"")
3961 (defvar org-link-re-with-space nil
3962 "Matches a link with spaces, optional angular brackets around it.")
3963 (defvar org-link-re-with-space2 nil
3964 "Matches a link with spaces, optional angular brackets around it.")
3965 (defvar org-link-re-with-space3 nil
3966 "Matches a link with spaces, only for internal part in bracket links.")
3967 (defvar org-angle-link-re nil
3968 "Matches link with angular brackets, spaces are allowed.")
3969 (defvar org-plain-link-re nil
3970 "Matches plain link, without spaces.")
3971 (defvar org-bracket-link-regexp nil
3972 "Matches a link in double brackets.")
3973 (defvar org-bracket-link-analytic-regexp nil
3974 "Regular expression used to analyze links.
3975 Here is what the match groups contain after a match:
3976 1: http:
3977 2: http
3978 3: path
3979 4: [desc]
3980 5: desc")
3981 (defvar org-bracket-link-analytic-regexp++ nil
3982 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3983 (defvar org-any-link-re nil
3984 "Regular expression matching any link.")
3986 (defun org-make-link-regexps ()
3987 "Update the link regular expressions.
3988 This should be called after the variable `org-link-types' has changed."
3989 (setq org-link-types-re
3990 (concat
3991 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3992 org-link-re-with-space
3993 (concat
3994 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3995 "\\([^" org-non-link-chars " ]"
3996 "[^" org-non-link-chars "]*"
3997 "[^" org-non-link-chars " ]\\)>?")
3998 org-link-re-with-space2
3999 (concat
4000 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4001 "\\([^" org-non-link-chars " ]"
4002 "[^\t\n\r]*"
4003 "[^" org-non-link-chars " ]\\)>?")
4004 org-link-re-with-space3
4005 (concat
4006 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4007 "\\([^" org-non-link-chars " ]"
4008 "[^\t\n\r]*\\)")
4009 org-angle-link-re
4010 (concat
4011 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4012 "\\([^" org-non-link-chars " ]"
4013 "[^" org-non-link-chars "]*"
4014 "\\)>")
4015 org-plain-link-re
4016 (concat
4017 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4018 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4019 org-bracket-link-regexp
4020 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4021 org-bracket-link-analytic-regexp
4022 (concat
4023 "\\[\\["
4024 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4025 "\\([^]]+\\)"
4026 "\\]"
4027 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4028 "\\]")
4029 org-bracket-link-analytic-regexp++
4030 (concat
4031 "\\[\\["
4032 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4033 "\\([^]]+\\)"
4034 "\\]"
4035 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4036 "\\]")
4037 org-any-link-re
4038 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4039 org-angle-link-re "\\)\\|\\("
4040 org-plain-link-re "\\)")))
4042 (org-make-link-regexps)
4044 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4045 "Regular expression for fast time stamp matching.")
4046 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4047 "Regular expression for fast time stamp matching.")
4048 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4049 "Regular expression matching time strings for analysis.
4050 This one does not require the space after the date, so it can be used
4051 on a string that terminates immediately after the date.")
4052 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4053 "Regular expression matching time strings for analysis.")
4054 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4055 "Regular expression matching time stamps, with groups.")
4056 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4057 "Regular expression matching time stamps (also [..]), with groups.")
4058 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4059 "Regular expression matching a time stamp range.")
4060 (defconst org-tr-regexp-both
4061 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4062 "Regular expression matching a time stamp range.")
4063 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4064 org-ts-regexp "\\)?")
4065 "Regular expression matching a time stamp or time stamp range.")
4066 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4067 org-ts-regexp-both "\\)?")
4068 "Regular expression matching a time stamp or time stamp range.
4069 The time stamps may be either active or inactive.")
4071 (defvar org-emph-face nil)
4073 (defun org-do-emphasis-faces (limit)
4074 "Run through the buffer and add overlays to links."
4075 (let (rtn a)
4076 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4077 (if (not (= (char-after (match-beginning 3))
4078 (char-after (match-beginning 4))))
4079 (progn
4080 (setq rtn t)
4081 (setq a (assoc (match-string 3) org-emphasis-alist))
4082 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4083 'face
4084 (nth 1 a))
4085 (and (nth 4 a)
4086 (org-remove-flyspell-overlays-in
4087 (match-beginning 0) (match-end 0)))
4088 (add-text-properties (match-beginning 2) (match-end 2)
4089 '(font-lock-multiline t))
4090 (when org-hide-emphasis-markers
4091 (add-text-properties (match-end 4) (match-beginning 5)
4092 '(invisible org-link))
4093 (add-text-properties (match-beginning 3) (match-end 3)
4094 '(invisible org-link)))))
4095 (backward-char 1))
4096 rtn))
4098 (defun org-emphasize (&optional char)
4099 "Insert or change an emphasis, i.e. a font like bold or italic.
4100 If there is an active region, change that region to a new emphasis.
4101 If there is no region, just insert the marker characters and position
4102 the cursor between them.
4103 CHAR should be either the marker character, or the first character of the
4104 HTML tag associated with that emphasis. If CHAR is a space, the means
4105 to remove the emphasis of the selected region.
4106 If char is not given (for example in an interactive call) it
4107 will be prompted for."
4108 (interactive)
4109 (let ((eal org-emphasis-alist) e det
4110 (erc org-emphasis-regexp-components)
4111 (prompt "")
4112 (string "") beg end move tag c s)
4113 (if (org-region-active-p)
4114 (setq beg (region-beginning) end (region-end)
4115 string (buffer-substring beg end))
4116 (setq move t))
4118 (while (setq e (pop eal))
4119 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4120 c (aref tag 0))
4121 (push (cons c (string-to-char (car e))) det)
4122 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4123 (substring tag 1)))))
4124 (setq det (nreverse det))
4125 (unless char
4126 (message "%s" (concat "Emphasis marker or tag:" prompt))
4127 (setq char (read-char-exclusive)))
4128 (setq char (or (cdr (assoc char det)) char))
4129 (if (equal char ?\ )
4130 (setq s "" move nil)
4131 (unless (assoc (char-to-string char) org-emphasis-alist)
4132 (error "No such emphasis marker: \"%c\"" char))
4133 (setq s (char-to-string char)))
4134 (while (and (> (length string) 1)
4135 (equal (substring string 0 1) (substring string -1))
4136 (assoc (substring string 0 1) org-emphasis-alist))
4137 (setq string (substring string 1 -1)))
4138 (setq string (concat s string s))
4139 (if beg (delete-region beg end))
4140 (unless (or (bolp)
4141 (string-match (concat "[" (nth 0 erc) "\n]")
4142 (char-to-string (char-before (point)))))
4143 (insert " "))
4144 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4145 (char-to-string (char-after (point))))
4146 (insert " ") (backward-char 1))
4147 (insert string)
4148 (and move (backward-char 1))))
4150 (defconst org-nonsticky-props
4151 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4153 (defsubst org-rear-nonsticky-at (pos)
4154 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4156 (defun org-activate-plain-links (limit)
4157 "Run through the buffer and add overlays to links."
4158 (catch 'exit
4159 (let (f)
4160 (while (re-search-forward org-plain-link-re limit t)
4161 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4162 (setq f (get-text-property (match-beginning 0) 'face))
4163 (if (or (eq f 'org-tag)
4164 (and (listp f) (memq 'org-tag f)))
4166 (add-text-properties (match-beginning 0) (match-end 0)
4167 (list 'mouse-face 'highlight
4168 'keymap org-mouse-map))
4169 (org-rear-nonsticky-at (match-end 0))
4170 (throw 'exit t))))))
4172 (defun org-activate-code (limit)
4173 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4174 (progn
4175 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4176 (remove-text-properties (match-beginning 0) (match-end 0)
4177 '(display t invisible t intangible t))
4178 t)))
4180 (defun org-fontify-meta-lines-and-blocks (limit)
4181 "Fontify #+ lines and blocks, in the correct ways."
4182 (let ((case-fold-search t))
4183 (if (re-search-forward
4184 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4185 limit t)
4186 (let ((beg (match-beginning 0))
4187 (beg1 (line-beginning-position 2))
4188 (dc1 (downcase (match-string 2)))
4189 (dc3 (downcase (match-string 3)))
4190 end end1 quoting)
4191 (cond
4192 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4193 ;; a single line of backend-specific content
4194 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4195 (remove-text-properties (match-beginning 0) (match-end 0)
4196 '(display t invisible t intangible t))
4197 (add-text-properties (match-beginning 1) (match-end 3)
4198 '(font-lock-fontified t face org-meta-line))
4199 (add-text-properties (match-beginning 6) (match-end 6)
4200 '(font-lock-fontified t face org-block))
4202 ((and (match-end 4) (equal dc3 "begin"))
4203 ;; Truely a block
4204 (setq quoting (member (downcase (match-string 5))
4205 org-protecting-blocks))
4206 (when (re-search-forward
4207 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4208 nil t) ;; on purpose, we look further than LIMIT
4209 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4210 (when quoting
4211 (remove-text-properties beg end
4212 '(display t invisible t intangible t)))
4213 (add-text-properties
4214 beg end
4215 '(font-lock-fontified t font-lock-multiline t))
4216 (add-text-properties beg beg1 '(face org-meta-line))
4217 (add-text-properties end1 end '(face org-meta-line))
4218 (when quoting
4219 (add-text-properties beg1 end1 '(face org-block)))
4221 ((not (member (char-after beg) '(?\ ?\t)))
4222 ;; just any other in-buffer setting, but not indented
4223 (add-text-properties
4224 beg (match-end 0)
4225 '(font-lock-fontified t face org-meta-line))
4227 ((or (member dc1 '("caption:" "label:" "orgtbl:" "tblfm:"))
4228 (and (match-end 4) (equal dc3 "attr")))
4229 (add-text-properties
4230 beg (match-end 0)
4231 '(font-lock-fontified t face org-meta-line))
4233 (t nil))))))
4235 (defun org-activate-angle-links (limit)
4236 "Run through the buffer and add overlays to links."
4237 (if (re-search-forward org-angle-link-re limit t)
4238 (progn
4239 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4240 (add-text-properties (match-beginning 0) (match-end 0)
4241 (list 'mouse-face 'highlight
4242 'keymap org-mouse-map))
4243 (org-rear-nonsticky-at (match-end 0))
4244 t)))
4246 (defun org-activate-footnote-links (limit)
4247 "Run through the buffer and add overlays to links."
4248 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4249 limit t)
4250 (progn
4251 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4252 (add-text-properties (match-beginning 2) (match-end 2)
4253 (list 'mouse-face 'highlight
4254 'keymap org-mouse-map
4255 'help-echo
4256 (if (= (point-at-bol) (match-beginning 2))
4257 "Footnote definition"
4258 "Footnote reference")
4260 (org-rear-nonsticky-at (match-end 2))
4261 t)))
4263 (defun org-activate-bracket-links (limit)
4264 "Run through the buffer and add overlays to bracketed links."
4265 (if (re-search-forward org-bracket-link-regexp limit t)
4266 (let* ((help (concat "LINK: "
4267 (org-match-string-no-properties 1)))
4268 ;; FIXME: above we should remove the escapes.
4269 ;; but that requires another match, protecting match data,
4270 ;; a lot of overhead for font-lock.
4271 (ip (org-maybe-intangible
4272 (list 'invisible 'org-link
4273 'keymap org-mouse-map 'mouse-face 'highlight
4274 'font-lock-multiline t 'help-echo help)))
4275 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4276 'font-lock-multiline t 'help-echo help)))
4277 ;; We need to remove the invisible property here. Table narrowing
4278 ;; may have made some of this invisible.
4279 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4280 (remove-text-properties (match-beginning 0) (match-end 0)
4281 '(invisible nil))
4282 (if (match-end 3)
4283 (progn
4284 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4285 (org-rear-nonsticky-at (match-beginning 3))
4286 (add-text-properties (match-beginning 3) (match-end 3) vp)
4287 (org-rear-nonsticky-at (match-end 3))
4288 (add-text-properties (match-end 3) (match-end 0) ip)
4289 (org-rear-nonsticky-at (match-end 0)))
4290 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4291 (org-rear-nonsticky-at (match-beginning 1))
4292 (add-text-properties (match-beginning 1) (match-end 1) vp)
4293 (org-rear-nonsticky-at (match-end 1))
4294 (add-text-properties (match-end 1) (match-end 0) ip)
4295 (org-rear-nonsticky-at (match-end 0)))
4296 t)))
4298 (defun org-activate-dates (limit)
4299 "Run through the buffer and add overlays to dates."
4300 (if (re-search-forward org-tsr-regexp-both limit t)
4301 (progn
4302 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4303 (add-text-properties (match-beginning 0) (match-end 0)
4304 (list 'mouse-face 'highlight
4305 'keymap org-mouse-map))
4306 (org-rear-nonsticky-at (match-end 0))
4307 (when org-display-custom-times
4308 (if (match-end 3)
4309 (org-display-custom-time (match-beginning 3) (match-end 3)))
4310 (org-display-custom-time (match-beginning 1) (match-end 1)))
4311 t)))
4313 (defvar org-target-link-regexp nil
4314 "Regular expression matching radio targets in plain text.")
4315 (make-variable-buffer-local 'org-target-link-regexp)
4316 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4317 "Regular expression matching a link target.")
4318 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4319 "Regular expression matching a radio target.")
4320 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4321 "Regular expression matching any target.")
4323 (defun org-activate-target-links (limit)
4324 "Run through the buffer and add overlays to target matches."
4325 (when org-target-link-regexp
4326 (let ((case-fold-search t))
4327 (if (re-search-forward org-target-link-regexp limit t)
4328 (progn
4329 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4330 (add-text-properties (match-beginning 0) (match-end 0)
4331 (list 'mouse-face 'highlight
4332 'keymap org-mouse-map
4333 'help-echo "Radio target link"
4334 'org-linked-text t))
4335 (org-rear-nonsticky-at (match-end 0))
4336 t)))))
4338 (defun org-update-radio-target-regexp ()
4339 "Find all radio targets in this file and update the regular expression."
4340 (interactive)
4341 (when (memq 'radio org-activate-links)
4342 (setq org-target-link-regexp
4343 (org-make-target-link-regexp (org-all-targets 'radio)))
4344 (org-restart-font-lock)))
4346 (defun org-hide-wide-columns (limit)
4347 (let (s e)
4348 (setq s (text-property-any (point) (or limit (point-max))
4349 'org-cwidth t))
4350 (when s
4351 (setq e (next-single-property-change s 'org-cwidth))
4352 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4353 (goto-char e)
4354 t)))
4356 (defvar org-latex-and-specials-regexp nil
4357 "Regular expression for highlighting export special stuff.")
4358 (defvar org-match-substring-regexp)
4359 (defvar org-match-substring-with-braces-regexp)
4360 (defvar org-export-html-special-string-regexps)
4362 (defun org-compute-latex-and-specials-regexp ()
4363 "Compute regular expression for stuff treated specially by exporters."
4364 (if (not org-highlight-latex-fragments-and-specials)
4365 (org-set-local 'org-latex-and-specials-regexp nil)
4366 (require 'org-exp)
4367 (let*
4368 ((matchers (plist-get org-format-latex-options :matchers))
4369 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4370 org-latex-regexps)))
4371 (options (org-combine-plists (org-default-export-plist)
4372 (org-infile-export-plist)))
4373 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4374 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4375 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4376 (org-export-html-expand (plist-get options :expand-quoted-html))
4377 (org-export-with-special-strings (plist-get options :special-strings))
4378 (re-sub
4379 (cond
4380 ((equal org-export-with-sub-superscripts '{})
4381 (list org-match-substring-with-braces-regexp))
4382 (org-export-with-sub-superscripts
4383 (list org-match-substring-regexp))
4384 (t nil)))
4385 (re-latex
4386 (if org-export-with-LaTeX-fragments
4387 (mapcar (lambda (x) (nth 1 x)) latexs)))
4388 (re-macros
4389 (if org-export-with-TeX-macros
4390 (list (concat "\\\\"
4391 (regexp-opt
4392 (append (mapcar 'car org-html-entities)
4393 (if (boundp 'org-latex-entities)
4394 (mapcar (lambda (x)
4395 (or (car-safe x) x))
4396 org-latex-entities)
4397 nil))
4398 'words))) ; FIXME
4400 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4401 (re-special (if org-export-with-special-strings
4402 (mapcar (lambda (x) (car x))
4403 org-export-html-special-string-regexps)))
4404 (re-rest
4405 (delq nil
4406 (list
4407 (if org-export-html-expand "@<[^>\n]+>")
4408 ))))
4409 (org-set-local
4410 'org-latex-and-specials-regexp
4411 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4412 re-rest) "\\|")))))
4414 (defun org-do-latex-and-special-faces (limit)
4415 "Run through the buffer and add overlays to links."
4416 (when org-latex-and-specials-regexp
4417 (let (rtn d)
4418 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4419 limit t))
4420 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4421 'face))
4422 '(org-code org-verbatim underline)))
4423 (progn
4424 (setq rtn t
4425 d (cond ((member (char-after (1+ (match-beginning 0)))
4426 '(?_ ?^)) 1)
4427 (t 0)))
4428 (font-lock-prepend-text-property
4429 (+ d (match-beginning 0)) (match-end 0)
4430 'face 'org-latex-and-export-specials)
4431 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4432 '(font-lock-multiline t)))))
4433 rtn)))
4435 (defun org-restart-font-lock ()
4436 "Restart font-lock-mode, to force refontification."
4437 (when (and (boundp 'font-lock-mode) font-lock-mode)
4438 (font-lock-mode -1)
4439 (font-lock-mode 1)))
4441 (defun org-all-targets (&optional radio)
4442 "Return a list of all targets in this file.
4443 With optional argument RADIO, only find radio targets."
4444 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4445 rtn)
4446 (save-excursion
4447 (goto-char (point-min))
4448 (while (re-search-forward re nil t)
4449 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4450 rtn)))
4452 (defun org-make-target-link-regexp (targets)
4453 "Make regular expression matching all strings in TARGETS.
4454 The regular expression finds the targets also if there is a line break
4455 between words."
4456 (and targets
4457 (concat
4458 "\\<\\("
4459 (mapconcat
4460 (lambda (x)
4461 (while (string-match " +" x)
4462 (setq x (replace-match "\\s-+" t t x)))
4464 targets
4465 "\\|")
4466 "\\)\\>")))
4468 (defun org-activate-tags (limit)
4469 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4470 (progn
4471 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4472 (add-text-properties (match-beginning 1) (match-end 1)
4473 (list 'mouse-face 'highlight
4474 'keymap org-mouse-map))
4475 (org-rear-nonsticky-at (match-end 1))
4476 t)))
4478 (defun org-outline-level ()
4479 (save-excursion
4480 (looking-at outline-regexp)
4481 (if (match-beginning 1)
4482 (+ (org-get-string-indentation (match-string 1)) 1000)
4483 (1- (- (match-end 0) (match-beginning 0))))))
4485 (defvar org-font-lock-keywords nil)
4487 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4488 "Regular expression matching a property line.")
4490 (defvar org-font-lock-hook nil
4491 "Functions to be called for special font lock stuff.")
4493 (defun org-font-lock-hook (limit)
4494 (run-hook-with-args 'org-font-lock-hook limit))
4496 (defun org-set-font-lock-defaults ()
4497 (let* ((em org-fontify-emphasized-text)
4498 (lk org-activate-links)
4499 (org-font-lock-extra-keywords
4500 (list
4501 ;; Call the hook
4502 '(org-font-lock-hook)
4503 ;; Headlines
4504 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4505 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4506 ;; Table lines
4507 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4508 (1 'org-table t))
4509 ;; Table internals
4510 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4511 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4512 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4513 ;; Drawers
4514 (list org-drawer-regexp '(0 'org-special-keyword t))
4515 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4516 ;; Properties
4517 (list org-property-re
4518 '(1 'org-special-keyword t)
4519 '(3 'org-property-value t))
4520 (if org-format-transports-properties-p
4521 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4522 ;; Links
4523 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4524 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4525 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4526 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4527 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4528 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4529 (if (memq 'footnote lk) '(org-activate-footnote-links
4530 (2 'org-footnote t)))
4531 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4532 '(org-hide-wide-columns (0 nil append))
4533 ;; TODO lines
4534 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4535 '(1 (org-get-todo-face 1) t))
4536 ;; DONE
4537 (if org-fontify-done-headline
4538 (list (concat "^[*]+ +\\<\\("
4539 (mapconcat 'regexp-quote org-done-keywords "\\|")
4540 "\\)\\(.*\\)")
4541 '(2 'org-headline-done t))
4542 nil)
4543 ;; Priorities
4544 '(org-font-lock-add-priority-faces)
4545 ;; Tags
4546 '(org-font-lock-add-tag-faces)
4547 ;; Special keywords
4548 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4549 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4550 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4551 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4552 ;; Emphasis
4553 (if em
4554 (if (featurep 'xemacs)
4555 '(org-do-emphasis-faces (0 nil append))
4556 '(org-do-emphasis-faces)))
4557 ;; Checkboxes
4558 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4559 2 'org-checkbox prepend)
4560 (if org-provide-checkbox-statistics
4561 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4562 (0 (org-get-checkbox-statistics-face) t)))
4563 ;; Description list items
4564 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4565 2 'bold prepend)
4566 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4567 '(1 'org-archived prepend))
4568 ;; Specials
4569 '(org-do-latex-and-special-faces)
4570 ;; Code
4571 '(org-activate-code (1 'org-code t))
4572 ;; COMMENT
4573 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4574 "\\|" org-quote-string "\\)\\>")
4575 '(1 'org-special-keyword t))
4576 '("^#.*" (0 'font-lock-comment-face t))
4577 ;; Blocks and meta lines
4578 '(org-fontify-meta-lines-and-blocks)
4580 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4581 ;; Now set the full font-lock-keywords
4582 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4583 (org-set-local 'font-lock-defaults
4584 '(org-font-lock-keywords t nil nil backward-paragraph))
4585 (kill-local-variable 'font-lock-keywords) nil))
4587 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
4588 "Fontify string S like in Org-mode"
4589 (with-temp-buffer
4590 (insert s)
4591 (let ((org-odd-levels-only odd-levels))
4592 (org-mode)
4593 (font-lock-fontify-buffer)
4594 (buffer-string))))
4596 (defvar org-m nil)
4597 (defvar org-l nil)
4598 (defvar org-f nil)
4599 (defun org-get-level-face (n)
4600 "Get the right face for match N in font-lock matching of headlines."
4601 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4602 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4603 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4604 (cond
4605 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4606 ((eq n 2) org-f)
4607 (t (if org-level-color-stars-only nil org-f))))
4609 (defun org-get-todo-face (kwd)
4610 "Get the right face for a TODO keyword KWD.
4611 If KWD is a number, get the corresponding match group."
4612 (if (numberp kwd) (setq kwd (match-string kwd)))
4613 (or (cdr (assoc kwd org-todo-keyword-faces))
4614 (and (member kwd org-done-keywords) 'org-done)
4615 'org-todo))
4617 (defun org-font-lock-add-tag-faces (limit)
4618 "Add the special tag faces."
4619 (when (and org-tag-faces org-tags-special-faces-re)
4620 (while (re-search-forward org-tags-special-faces-re limit t)
4621 (add-text-properties (match-beginning 1) (match-end 1)
4622 (list 'face (org-get-tag-face 1)
4623 'font-lock-fontified t))
4624 (backward-char 1))))
4626 (defun org-font-lock-add-priority-faces (limit)
4627 "Add the special priority faces."
4628 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4629 (add-text-properties
4630 (match-beginning 0) (match-end 0)
4631 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4632 org-priority-faces))
4633 'org-special-keyword)
4634 'font-lock-fontified t))))
4636 (defun org-get-tag-face (kwd)
4637 "Get the right face for a TODO keyword KWD.
4638 If KWD is a number, get the corresponding match group."
4639 (if (numberp kwd) (setq kwd (match-string kwd)))
4640 (or (cdr (assoc kwd org-tag-faces))
4641 'org-tag))
4643 (defun org-unfontify-region (beg end &optional maybe_loudly)
4644 "Remove fontification and activation overlays from links."
4645 (font-lock-default-unfontify-region beg end)
4646 (let* ((buffer-undo-list t)
4647 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4648 (inhibit-modification-hooks t)
4649 deactivate-mark buffer-file-name buffer-file-truename)
4650 (remove-text-properties beg end
4651 '(mouse-face t keymap t org-linked-text t
4652 invisible t intangible t))))
4654 ;;;; Visibility cycling, including org-goto and indirect buffer
4656 ;;; Cycling
4658 (defvar org-cycle-global-status nil)
4659 (make-variable-buffer-local 'org-cycle-global-status)
4660 (defvar org-cycle-subtree-status nil)
4661 (make-variable-buffer-local 'org-cycle-subtree-status)
4663 ;;;###autoload
4665 (defvar org-inlinetask-min-level)
4667 (defun org-cycle (&optional arg)
4668 "TAB-action and visibility cycling for Org-mode.
4670 This is the command invoked in Org-moe by the TAB key. It's main purpose
4671 is outine visibility cycling, but it also invokes other actions
4672 in special contexts.
4674 - When this function is called with a prefix argument, rotate the entire
4675 buffer through 3 states (global cycling)
4676 1. OVERVIEW: Show only top-level headlines.
4677 2. CONTENTS: Show all headlines of all levels, but no body text.
4678 3. SHOW ALL: Show everything.
4679 When called with two `C-u C-u' prefixes, switch to the startup visibility,
4680 determined by the variable `org-startup-folded', and by any VISIBILITY
4681 properties in the buffer.
4682 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
4683 including any drawers.
4685 - When inside a table, re-align the table and move to the next field.
4687 - When point is at the beginning of a headline, rotate the subtree started
4688 by this line through 3 different states (local cycling)
4689 1. FOLDED: Only the main headline is shown.
4690 2. CHILDREN: The main headline and the direct children are shown.
4691 From this state, you can move to one of the children
4692 and zoom in further.
4693 3. SUBTREE: Show the entire subtree, including body text.
4695 - When there is a numeric prefix, go up to a heading with level ARG, do
4696 a `show-subtree' and return to the previous cursor position. If ARG
4697 is negative, go up that many levels.
4699 - When point is not at the beginning of a headline, execute the global
4700 binding for TAB, which is re-indenting the line. See the option
4701 `org-cycle-emulate-tab' for details.
4703 - Special case: if point is at the beginning of the buffer and there is
4704 no headline in line 1, this function will act as if called with prefix arg.
4705 But only if also the variable `org-cycle-global-at-bob' is t."
4706 (interactive "P")
4707 (org-load-modules-maybe)
4708 (unless (run-hook-with-args-until-success 'org-tab-first-hook)
4709 (let* ((limit-level
4710 (or org-cycle-max-level
4711 (and (boundp 'org-inlinetask-min-level)
4712 org-inlinetask-min-level
4713 (1- org-inlinetask-min-level))))
4714 (nstars (and limit-level
4715 (if org-odd-levels-only
4716 (and limit-level (1- (* limit-level 2)))
4717 limit-level)))
4718 (outline-regexp
4719 (cond
4720 ((not (org-mode-p)) outline-regexp)
4721 (org-cycle-include-plain-lists
4722 (concat "\\(?:\\*"
4723 (if nstars (format "\\{1,%d\\}" nstars) "+")
4724 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
4725 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
4726 (bob-special (and org-cycle-global-at-bob (bobp)
4727 (not (looking-at outline-regexp))))
4728 (org-cycle-hook
4729 (if bob-special
4730 (delq 'org-optimize-window-after-visibility-change
4731 (copy-sequence org-cycle-hook))
4732 org-cycle-hook))
4733 (pos (point)))
4735 (if (or bob-special (equal arg '(4)))
4736 ;; special case: use global cycling
4737 (setq arg t))
4739 (cond
4741 ((equal arg '(16))
4742 (org-set-startup-visibility)
4743 (message "Startup visibility, plus VISIBILITY properties"))
4745 ((equal arg '(64))
4746 (show-all)
4747 (message "Entire buffer visible, including drawers"))
4749 ((org-at-table-p 'any)
4750 ;; Enter the table or move to the next field in the table
4751 (or (org-table-recognize-table.el)
4752 (progn
4753 (if arg (org-table-edit-field t)
4754 (org-table-justify-field-maybe)
4755 (call-interactively 'org-table-next-field)))))
4757 ((run-hook-with-args-until-success
4758 'org-tab-after-check-for-table-hook))
4760 ((eq arg t) ;; Global cycling
4761 (org-cycle-internal-global))
4763 ((and org-drawers org-drawer-regexp
4764 (save-excursion
4765 (beginning-of-line 1)
4766 (looking-at org-drawer-regexp)))
4767 ;; Toggle block visibility
4768 (org-flag-drawer
4769 (not (get-char-property (match-end 0) 'invisible))))
4771 ((integerp arg)
4772 ;; Show-subtree, ARG levels up from here.
4773 (save-excursion
4774 (org-back-to-heading)
4775 (outline-up-heading (if (< arg 0) (- arg)
4776 (- (funcall outline-level) arg)))
4777 (org-show-subtree)))
4779 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4780 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4782 (org-cycle-internal-local))
4784 ;; TAB emulation and template completion
4785 (buffer-read-only (org-back-to-heading))
4787 ((run-hook-with-args-until-success
4788 'org-tab-after-check-for-cycling-hook))
4790 ((org-try-structure-completion))
4792 ((org-try-cdlatex-tab))
4794 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4795 (or (not (bolp))
4796 (not (looking-at outline-regexp))))
4797 (call-interactively (global-key-binding "\t")))
4799 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4800 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4801 (or (and (eq org-cycle-emulate-tab 'white)
4802 (= (match-end 0) (point-at-eol)))
4803 (and (eq org-cycle-emulate-tab 'whitestart)
4804 (>= (match-end 0) pos))))
4806 (eq org-cycle-emulate-tab t))
4807 (call-interactively (global-key-binding "\t")))
4809 (t (save-excursion
4810 (org-back-to-heading)
4811 (org-cycle)))))))
4813 (defun org-cycle-internal-global ()
4814 "Do the global cycling action."
4815 (cond
4816 ((and (eq last-command this-command)
4817 (eq org-cycle-global-status 'overview))
4818 ;; We just created the overview - now do table of contents
4819 ;; This can be slow in very large buffers, so indicate action
4820 (run-hook-with-args 'org-pre-cycle-hook 'contents)
4821 (message "CONTENTS...")
4822 (org-content)
4823 (message "CONTENTS...done")
4824 (setq org-cycle-global-status 'contents)
4825 (run-hook-with-args 'org-cycle-hook 'contents))
4827 ((and (eq last-command this-command)
4828 (eq org-cycle-global-status 'contents))
4829 ;; We just showed the table of contents - now show everything
4830 (run-hook-with-args 'org-pre-cycle-hook 'all)
4831 (show-all)
4832 (message "SHOW ALL")
4833 (setq org-cycle-global-status 'all)
4834 (run-hook-with-args 'org-cycle-hook 'all))
4837 ;; Default action: go to overview
4838 (run-hook-with-args 'org-pre-cycle-hook 'overview)
4839 (org-overview)
4840 (message "OVERVIEW")
4841 (setq org-cycle-global-status 'overview)
4842 (run-hook-with-args 'org-cycle-hook 'overview))))
4844 (defun org-cycle-internal-local ()
4845 "Do the local cycling action."
4846 (org-back-to-heading)
4847 (let ((goal-column 0) eoh eol eos)
4848 ;; First, some boundaries
4849 (save-excursion
4850 (org-back-to-heading)
4851 (save-excursion
4852 (beginning-of-line 2)
4853 (while (and (not (eobp)) ;; this is like `next-line'
4854 (get-char-property (1- (point)) 'invisible))
4855 (beginning-of-line 2)) (setq eol (point)))
4856 (outline-end-of-heading) (setq eoh (point))
4857 (org-end-of-subtree t)
4858 (unless (eobp)
4859 (skip-chars-forward " \t\n")
4860 (beginning-of-line 1) ; in case this is an item
4862 (setq eos (1- (point))))
4863 ;; Find out what to do next and set `this-command'
4864 (cond
4865 ((= eos eoh)
4866 ;; Nothing is hidden behind this heading
4867 (run-hook-with-args 'org-pre-cycle-hook 'empty)
4868 (message "EMPTY ENTRY")
4869 (setq org-cycle-subtree-status nil)
4870 (save-excursion
4871 (goto-char eos)
4872 (outline-next-heading)
4873 (if (org-invisible-p) (org-flag-heading nil))))
4874 ((or (>= eol eos)
4875 (not (string-match "\\S-" (buffer-substring eol eos))))
4876 ;; Entire subtree is hidden in one line: open it
4877 (run-hook-with-args 'org-pre-cycle-hook 'children)
4878 (org-show-entry)
4879 (show-children)
4880 (message "CHILDREN")
4881 (save-excursion
4882 (goto-char eos)
4883 (outline-next-heading)
4884 (if (org-invisible-p) (org-flag-heading nil)))
4885 (setq org-cycle-subtree-status 'children)
4886 (run-hook-with-args 'org-cycle-hook 'children))
4887 ((and (eq last-command this-command)
4888 (eq org-cycle-subtree-status 'children))
4889 ;; We just showed the children, now show everything.
4890 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
4891 (org-show-subtree)
4892 (message "SUBTREE")
4893 (setq org-cycle-subtree-status 'subtree)
4894 (run-hook-with-args 'org-cycle-hook 'subtree))
4896 ;; Default action: hide the subtree.
4897 (run-hook-with-args 'org-pre-cycle-hook 'folded)
4898 (hide-subtree)
4899 (message "FOLDED")
4900 (setq org-cycle-subtree-status 'folded)
4901 (run-hook-with-args 'org-cycle-hook 'folded)))))
4903 ;;;###autoload
4904 (defun org-global-cycle (&optional arg)
4905 "Cycle the global visibility. For details see `org-cycle'.
4906 With C-u prefix arg, switch to startup visibility.
4907 With a numeric prefix, show all headlines up to that level."
4908 (interactive "P")
4909 (let ((org-cycle-include-plain-lists
4910 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4911 (cond
4912 ((integerp arg)
4913 (show-all)
4914 (hide-sublevels arg)
4915 (setq org-cycle-global-status 'contents))
4916 ((equal arg '(4))
4917 (org-set-startup-visibility)
4918 (message "Startup visibility, plus VISIBILITY properties."))
4920 (org-cycle '(4))))))
4922 (defun org-set-startup-visibility ()
4923 "Set the visibility required by startup options and properties."
4924 (cond
4925 ((eq org-startup-folded t)
4926 (org-cycle '(4)))
4927 ((eq org-startup-folded 'content)
4928 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4929 (org-cycle '(4)) (org-cycle '(4)))))
4930 (if org-hide-block-startup (org-hide-block-all))
4931 (org-set-visibility-according-to-property 'no-cleanup)
4932 (org-cycle-hide-archived-subtrees 'all)
4933 (org-cycle-hide-drawers 'all)
4934 (org-cycle-show-empty-lines 'all))
4936 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4937 "Switch subtree visibilities according to :VISIBILITY: property."
4938 (interactive)
4939 (let (org-show-entry-below state)
4940 (save-excursion
4941 (goto-char (point-min))
4942 (while (re-search-forward
4943 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4944 nil t)
4945 (setq state (match-string 1))
4946 (save-excursion
4947 (org-back-to-heading t)
4948 (hide-subtree)
4949 (org-reveal)
4950 (cond
4951 ((equal state '("fold" "folded"))
4952 (hide-subtree))
4953 ((equal state "children")
4954 (org-show-hidden-entry)
4955 (show-children))
4956 ((equal state "content")
4957 (save-excursion
4958 (save-restriction
4959 (org-narrow-to-subtree)
4960 (org-content))))
4961 ((member state '("all" "showall"))
4962 (show-subtree)))))
4963 (unless no-cleanup
4964 (org-cycle-hide-archived-subtrees 'all)
4965 (org-cycle-hide-drawers 'all)
4966 (org-cycle-show-empty-lines 'all)))))
4968 (defun org-overview ()
4969 "Switch to overview mode, showing only top-level headlines.
4970 Really, this shows all headlines with level equal or greater than the level
4971 of the first headline in the buffer. This is important, because if the
4972 first headline is not level one, then (hide-sublevels 1) gives confusing
4973 results."
4974 (interactive)
4975 (let ((level (save-excursion
4976 (goto-char (point-min))
4977 (if (re-search-forward (concat "^" outline-regexp) nil t)
4978 (progn
4979 (goto-char (match-beginning 0))
4980 (funcall outline-level))))))
4981 (and level (hide-sublevels level))))
4983 (defun org-content (&optional arg)
4984 "Show all headlines in the buffer, like a table of contents.
4985 With numerical argument N, show content up to level N."
4986 (interactive "P")
4987 (save-excursion
4988 ;; Visit all headings and show their offspring
4989 (and (integerp arg) (org-overview))
4990 (goto-char (point-max))
4991 (catch 'exit
4992 (while (and (progn (condition-case nil
4993 (outline-previous-visible-heading 1)
4994 (error (goto-char (point-min))))
4996 (looking-at outline-regexp))
4997 (if (integerp arg)
4998 (show-children (1- arg))
4999 (show-branches))
5000 (if (bobp) (throw 'exit nil))))))
5003 (defun org-optimize-window-after-visibility-change (state)
5004 "Adjust the window after a change in outline visibility.
5005 This function is the default value of the hook `org-cycle-hook'."
5006 (when (get-buffer-window (current-buffer))
5007 (cond
5008 ((eq state 'content) nil)
5009 ((eq state 'all) nil)
5010 ((eq state 'folded) nil)
5011 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5012 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5014 (defun org-compact-display-after-subtree-move ()
5015 "Show a compacter version of the tree of the entry's parent."
5016 (save-excursion
5017 (if (org-up-heading-safe)
5018 (progn
5019 (hide-subtree)
5020 (show-entry)
5021 (show-children)
5022 (org-cycle-show-empty-lines 'children)
5023 (org-cycle-hide-drawers 'children))
5024 (org-overview))))
5026 (defun org-cycle-show-empty-lines (state)
5027 "Show empty lines above all visible headlines.
5028 The region to be covered depends on STATE when called through
5029 `org-cycle-hook'. Lisp program can use t for STATE to get the
5030 entire buffer covered. Note that an empty line is only shown if there
5031 are at least `org-cycle-separator-lines' empty lines before the headline."
5032 (when (> org-cycle-separator-lines 0)
5033 (save-excursion
5034 (let* ((n org-cycle-separator-lines)
5035 (re (cond
5036 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5037 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5038 (t (let ((ns (number-to-string (- n 2))))
5039 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5040 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5041 beg end)
5042 (cond
5043 ((memq state '(overview contents t))
5044 (setq beg (point-min) end (point-max)))
5045 ((memq state '(children folded))
5046 (setq beg (point) end (progn (org-end-of-subtree t t)
5047 (beginning-of-line 2)
5048 (point)))))
5049 (when beg
5050 (goto-char beg)
5051 (while (re-search-forward re end t)
5052 (if (not (get-char-property (match-end 1) 'invisible))
5053 (outline-flag-region
5054 (match-beginning 1) (match-end 1) nil)))))))
5055 ;; Never hide empty lines at the end of the file.
5056 (save-excursion
5057 (goto-char (point-max))
5058 (outline-previous-heading)
5059 (outline-end-of-heading)
5060 (if (and (looking-at "[ \t\n]+")
5061 (= (match-end 0) (point-max)))
5062 (outline-flag-region (point) (match-end 0) nil))))
5064 (defun org-show-empty-lines-in-parent ()
5065 "Move to the parent and re-show empty lines before visible headlines."
5066 (save-excursion
5067 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5068 (org-cycle-show-empty-lines context))))
5070 (defun org-cycle-hide-drawers (state)
5071 "Re-hide all drawers after a visibility state change."
5072 (when (and (org-mode-p)
5073 (not (memq state '(overview folded))))
5074 (save-excursion
5075 (let* ((globalp (memq state '(contents all)))
5076 (beg (if globalp (point-min) (point)))
5077 (end (if globalp (point-max) (org-end-of-subtree t))))
5078 (goto-char beg)
5079 (while (re-search-forward org-drawer-regexp end t)
5080 (org-flag-drawer t))))))
5082 (defun org-flag-drawer (flag)
5083 (save-excursion
5084 (beginning-of-line 1)
5085 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5086 (let ((b (match-end 0))
5087 (outline-regexp org-outline-regexp))
5088 (if (re-search-forward
5089 "^[ \t]*:END:"
5090 (save-excursion (outline-next-heading) (point)) t)
5091 (outline-flag-region b (point-at-eol) flag)
5092 (error ":END: line missing"))))))
5094 (defun org-subtree-end-visible-p ()
5095 "Is the end of the current subtree visible?"
5096 (pos-visible-in-window-p
5097 (save-excursion (org-end-of-subtree t) (point))))
5099 (defun org-first-headline-recenter (&optional N)
5100 "Move cursor to the first headline and recenter the headline.
5101 Optional argument N means, put the headline into the Nth line of the window."
5102 (goto-char (point-min))
5103 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5104 (beginning-of-line)
5105 (recenter (prefix-numeric-value N))))
5107 ;;; Folding of blocks
5109 (defconst org-block-regexp
5111 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5112 "Regular expression for hiding blocks.")
5114 (defvar org-hide-block-overlays nil
5115 "Overays hiding blocks.")
5116 (make-variable-buffer-local 'org-hide-block-overlays)
5118 (defun org-block-map (function &optional start end)
5119 "Call func at the head of all source blocks in the current
5120 buffer. Optional arguments START and END can be used to limit
5121 the range."
5122 (let ((start (or start (point-min)))
5123 (end (or end (point-max))))
5124 (save-excursion
5125 (goto-char start)
5126 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5127 (save-excursion
5128 (save-match-data
5129 (goto-char (match-beginning 0))
5130 (funcall function)))))))
5132 (defun org-hide-block-toggle-all ()
5133 "Toggle the visibility of all blocks in the current buffer."
5134 (org-block-map #'org-hide-block-toggle))
5136 (defun org-hide-block-all ()
5137 "Fold all blocks in the current buffer."
5138 (interactive)
5139 (org-show-block-all)
5140 (org-block-map #'org-hide-block-toggle-maybe))
5142 (defun org-show-block-all ()
5143 "Unfold all blocks in the current buffer."
5144 (mapc 'org-delete-overlay org-hide-block-overlays)
5145 (setq org-hide-block-overlays nil))
5147 (defun org-hide-block-toggle-maybe ()
5148 "Toggle visibility of block at point."
5149 (interactive)
5150 (let ((case-fold-search t))
5151 (if (save-excursion
5152 (beginning-of-line 1)
5153 (looking-at org-block-regexp))
5154 (progn (org-hide-block-toggle)
5155 t) ;; to signal that we took action
5156 nil))) ;; to signal that we did not
5158 (defun org-hide-block-toggle (&optional force)
5159 "Toggle the visibility of the current block."
5160 (interactive)
5161 (save-excursion
5162 (beginning-of-line)
5163 (if (re-search-forward org-block-regexp nil t)
5164 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5165 (end (match-end 0))
5166 ov) ;; end of entire body
5167 (if (memq t (mapcar (lambda (overlay)
5168 (eq (org-overlay-get overlay 'invisible)
5169 'org-hide-block))
5170 (org-overlays-at start)))
5171 (if (or (not force) (eq force 'off))
5172 (mapc (lambda (ov)
5173 (when (member ov org-hide-block-overlays)
5174 (setq org-hide-block-overlays
5175 (delq ov org-hide-block-overlays)))
5176 (when (eq (org-overlay-get ov 'invisible)
5177 'org-hide-block)
5178 (org-delete-overlay ov)))
5179 (org-overlays-at start)))
5180 (setq ov (make-overlay start end))
5181 (org-overlay-put ov 'invisible 'org-hide-block)
5182 (push ov org-hide-block-overlays)))
5183 (error "Not looking at a source block"))))
5185 ;; org-tab-after-check-for-cycling-hook
5186 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5187 ;; Remove overlays when changing major mode
5188 (add-hook 'org-mode-hook
5189 (lambda () (org-add-hook 'change-major-mode-hook
5190 'org-show-block-all 'append 'local)))
5192 ;;; Org-goto
5194 (defvar org-goto-window-configuration nil)
5195 (defvar org-goto-marker nil)
5196 (defvar org-goto-map
5197 (let ((map (make-sparse-keymap)))
5198 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5199 (while (setq cmd (pop cmds))
5200 (substitute-key-definition cmd cmd map global-map)))
5201 (suppress-keymap map)
5202 (org-defkey map "\C-m" 'org-goto-ret)
5203 (org-defkey map [(return)] 'org-goto-ret)
5204 (org-defkey map [(left)] 'org-goto-left)
5205 (org-defkey map [(right)] 'org-goto-right)
5206 (org-defkey map [(control ?g)] 'org-goto-quit)
5207 (org-defkey map "\C-i" 'org-cycle)
5208 (org-defkey map [(tab)] 'org-cycle)
5209 (org-defkey map [(down)] 'outline-next-visible-heading)
5210 (org-defkey map [(up)] 'outline-previous-visible-heading)
5211 (if org-goto-auto-isearch
5212 (if (fboundp 'define-key-after)
5213 (define-key-after map [t] 'org-goto-local-auto-isearch)
5214 nil)
5215 (org-defkey map "q" 'org-goto-quit)
5216 (org-defkey map "n" 'outline-next-visible-heading)
5217 (org-defkey map "p" 'outline-previous-visible-heading)
5218 (org-defkey map "f" 'outline-forward-same-level)
5219 (org-defkey map "b" 'outline-backward-same-level)
5220 (org-defkey map "u" 'outline-up-heading))
5221 (org-defkey map "/" 'org-occur)
5222 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5223 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5224 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5225 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5226 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5227 map))
5229 (defconst org-goto-help
5230 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5231 RET=jump to location [Q]uit and return to previous location
5232 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5234 (defvar org-goto-start-pos) ; dynamically scoped parameter
5236 ;; FIXME: Docstring doe not mention both interfaces
5237 (defun org-goto (&optional alternative-interface)
5238 "Look up a different location in the current file, keeping current visibility.
5240 When you want look-up or go to a different location in a document, the
5241 fastest way is often to fold the entire buffer and then dive into the tree.
5242 This method has the disadvantage, that the previous location will be folded,
5243 which may not be what you want.
5245 This command works around this by showing a copy of the current buffer
5246 in an indirect buffer, in overview mode. You can dive into the tree in
5247 that copy, use org-occur and incremental search to find a location.
5248 When pressing RET or `Q', the command returns to the original buffer in
5249 which the visibility is still unchanged. After RET is will also jump to
5250 the location selected in the indirect buffer and expose the
5251 the headline hierarchy above."
5252 (interactive "P")
5253 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5254 (org-refile-use-outline-path t)
5255 (org-refile-target-verify-function nil)
5256 (interface
5257 (if (not alternative-interface)
5258 org-goto-interface
5259 (if (eq org-goto-interface 'outline)
5260 'outline-path-completion
5261 'outline)))
5262 (org-goto-start-pos (point))
5263 (selected-point
5264 (if (eq interface 'outline)
5265 (car (org-get-location (current-buffer) org-goto-help))
5266 (nth 3 (org-refile-get-location "Goto: ")))))
5267 (if selected-point
5268 (progn
5269 (org-mark-ring-push org-goto-start-pos)
5270 (goto-char selected-point)
5271 (if (or (org-invisible-p) (org-invisible-p2))
5272 (org-show-context 'org-goto)))
5273 (message "Quit"))))
5275 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5276 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5277 (defvar org-goto-local-auto-isearch-map) ; defined below
5279 (defun org-get-location (buf help)
5280 "Let the user select a location in the Org-mode buffer BUF.
5281 This function uses a recursive edit. It returns the selected position
5282 or nil."
5283 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5284 (isearch-hide-immediately nil)
5285 (isearch-search-fun-function
5286 (lambda () 'org-goto-local-search-headings))
5287 (org-goto-selected-point org-goto-exit-command))
5288 (save-excursion
5289 (save-window-excursion
5290 (delete-other-windows)
5291 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5292 (switch-to-buffer
5293 (condition-case nil
5294 (make-indirect-buffer (current-buffer) "*org-goto*")
5295 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5296 (with-output-to-temp-buffer "*Help*"
5297 (princ help))
5298 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5299 (setq buffer-read-only nil)
5300 (let ((org-startup-truncated t)
5301 (org-startup-folded nil)
5302 (org-startup-align-all-tables nil))
5303 (org-mode)
5304 (org-overview))
5305 (setq buffer-read-only t)
5306 (if (and (boundp 'org-goto-start-pos)
5307 (integer-or-marker-p org-goto-start-pos))
5308 (let ((org-show-hierarchy-above t)
5309 (org-show-siblings t)
5310 (org-show-following-heading t))
5311 (goto-char org-goto-start-pos)
5312 (and (org-invisible-p) (org-show-context)))
5313 (goto-char (point-min)))
5314 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5315 (message "Select location and press RET")
5316 (use-local-map org-goto-map)
5317 (recursive-edit)
5319 (kill-buffer "*org-goto*")
5320 (cons org-goto-selected-point org-goto-exit-command)))
5322 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5323 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5324 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5325 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5327 (defun org-goto-local-search-headings (string bound noerror)
5328 "Search and make sure that any matches are in headlines."
5329 (catch 'return
5330 (while (if isearch-forward
5331 (search-forward string bound noerror)
5332 (search-backward string bound noerror))
5333 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5334 (and (member :headline context)
5335 (not (member :tags context))))
5336 (throw 'return (point))))))
5338 (defun org-goto-local-auto-isearch ()
5339 "Start isearch."
5340 (interactive)
5341 (goto-char (point-min))
5342 (let ((keys (this-command-keys)))
5343 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5344 (isearch-mode t)
5345 (isearch-process-search-char (string-to-char keys)))))
5347 (defun org-goto-ret (&optional arg)
5348 "Finish `org-goto' by going to the new location."
5349 (interactive "P")
5350 (setq org-goto-selected-point (point)
5351 org-goto-exit-command 'return)
5352 (throw 'exit nil))
5354 (defun org-goto-left ()
5355 "Finish `org-goto' by going to the new location."
5356 (interactive)
5357 (if (org-on-heading-p)
5358 (progn
5359 (beginning-of-line 1)
5360 (setq org-goto-selected-point (point)
5361 org-goto-exit-command 'left)
5362 (throw 'exit nil))
5363 (error "Not on a heading")))
5365 (defun org-goto-right ()
5366 "Finish `org-goto' by going to the new location."
5367 (interactive)
5368 (if (org-on-heading-p)
5369 (progn
5370 (setq org-goto-selected-point (point)
5371 org-goto-exit-command 'right)
5372 (throw 'exit nil))
5373 (error "Not on a heading")))
5375 (defun org-goto-quit ()
5376 "Finish `org-goto' without cursor motion."
5377 (interactive)
5378 (setq org-goto-selected-point nil)
5379 (setq org-goto-exit-command 'quit)
5380 (throw 'exit nil))
5382 ;;; Indirect buffer display of subtrees
5384 (defvar org-indirect-dedicated-frame nil
5385 "This is the frame being used for indirect tree display.")
5386 (defvar org-last-indirect-buffer nil)
5388 (defun org-tree-to-indirect-buffer (&optional arg)
5389 "Create indirect buffer and narrow it to current subtree.
5390 With numerical prefix ARG, go up to this level and then take that tree.
5391 If ARG is negative, go up that many levels.
5392 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5393 indirect buffer previously made with this command, to avoid proliferation of
5394 indirect buffers. However, when you call the command with a `C-u' prefix, or
5395 when `org-indirect-buffer-display' is `new-frame', the last buffer
5396 is kept so that you can work with several indirect buffers at the same time.
5397 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5398 requests that a new frame be made for the new buffer, so that the dedicated
5399 frame is not changed."
5400 (interactive "P")
5401 (let ((cbuf (current-buffer))
5402 (cwin (selected-window))
5403 (pos (point))
5404 beg end level heading ibuf)
5405 (save-excursion
5406 (org-back-to-heading t)
5407 (when (numberp arg)
5408 (setq level (org-outline-level))
5409 (if (< arg 0) (setq arg (+ level arg)))
5410 (while (> (setq level (org-outline-level)) arg)
5411 (outline-up-heading 1 t)))
5412 (setq beg (point)
5413 heading (org-get-heading))
5414 (org-end-of-subtree t) (setq end (point)))
5415 (if (and (buffer-live-p org-last-indirect-buffer)
5416 (not (eq org-indirect-buffer-display 'new-frame))
5417 (not arg))
5418 (kill-buffer org-last-indirect-buffer))
5419 (setq ibuf (org-get-indirect-buffer cbuf)
5420 org-last-indirect-buffer ibuf)
5421 (cond
5422 ((or (eq org-indirect-buffer-display 'new-frame)
5423 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5424 (select-frame (make-frame))
5425 (delete-other-windows)
5426 (switch-to-buffer ibuf)
5427 (org-set-frame-title heading))
5428 ((eq org-indirect-buffer-display 'dedicated-frame)
5429 (raise-frame
5430 (select-frame (or (and org-indirect-dedicated-frame
5431 (frame-live-p org-indirect-dedicated-frame)
5432 org-indirect-dedicated-frame)
5433 (setq org-indirect-dedicated-frame (make-frame)))))
5434 (delete-other-windows)
5435 (switch-to-buffer ibuf)
5436 (org-set-frame-title (concat "Indirect: " heading)))
5437 ((eq org-indirect-buffer-display 'current-window)
5438 (switch-to-buffer ibuf))
5439 ((eq org-indirect-buffer-display 'other-window)
5440 (pop-to-buffer ibuf))
5441 (t (error "Invalid value.")))
5442 (if (featurep 'xemacs)
5443 (save-excursion (org-mode) (turn-on-font-lock)))
5444 (narrow-to-region beg end)
5445 (show-all)
5446 (goto-char pos)
5447 (and (window-live-p cwin) (select-window cwin))))
5449 (defun org-get-indirect-buffer (&optional buffer)
5450 (setq buffer (or buffer (current-buffer)))
5451 (let ((n 1) (base (buffer-name buffer)) bname)
5452 (while (buffer-live-p
5453 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5454 (setq n (1+ n)))
5455 (condition-case nil
5456 (make-indirect-buffer buffer bname 'clone)
5457 (error (make-indirect-buffer buffer bname)))))
5459 (defun org-set-frame-title (title)
5460 "Set the title of the current frame to the string TITLE."
5461 ;; FIXME: how to name a single frame in XEmacs???
5462 (unless (featurep 'xemacs)
5463 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5465 ;;;; Structure editing
5467 ;;; Inserting headlines
5469 (defun org-previous-line-empty-p ()
5470 (save-excursion
5471 (and (not (bobp))
5472 (or (beginning-of-line 0) t)
5473 (save-match-data
5474 (looking-at "[ \t]*$")))))
5476 (defun org-insert-heading (&optional force-heading)
5477 "Insert a new heading or item with same depth at point.
5478 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5479 If point is at the beginning of a headline, insert a sibling before the
5480 current headline. If point is not at the beginning, do not split the line,
5481 but create the new headline after the current line."
5482 (interactive "P")
5483 (if (= (buffer-size) 0)
5484 (insert "\n* ")
5485 (when (or force-heading (not (org-insert-item)))
5486 (let* ((empty-line-p nil)
5487 (head (save-excursion
5488 (condition-case nil
5489 (progn
5490 (org-back-to-heading)
5491 (setq empty-line-p (org-previous-line-empty-p))
5492 (match-string 0))
5493 (error "*"))))
5494 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5495 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5496 pos hide-previous previous-pos)
5497 (cond
5498 ((and (org-on-heading-p) (bolp)
5499 (or (bobp)
5500 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5501 ;; insert before the current line
5502 (open-line (if blank 2 1)))
5503 ((and (bolp)
5504 (or (bobp)
5505 (save-excursion
5506 (backward-char 1) (not (org-invisible-p)))))
5507 ;; insert right here
5508 nil)
5510 ;; somewhere in the line
5511 (save-excursion
5512 (setq previous-pos (point-at-bol))
5513 (end-of-line)
5514 (setq hide-previous (org-invisible-p)))
5515 (and org-insert-heading-respect-content (org-show-subtree))
5516 (let ((split
5517 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5518 (save-excursion
5519 (let ((p (point)))
5520 (goto-char (point-at-bol))
5521 (and (looking-at org-complex-heading-regexp)
5522 (> p (match-beginning 4)))))))
5523 tags pos)
5524 (cond
5525 (org-insert-heading-respect-content
5526 (org-end-of-subtree nil t)
5527 (or (bolp) (newline))
5528 (or (org-previous-line-empty-p)
5529 (and blank (newline)))
5530 (open-line 1))
5531 ((org-on-heading-p)
5532 (when hide-previous
5533 (show-children)
5534 (org-show-entry))
5535 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5536 (setq tags (and (match-end 2) (match-string 2)))
5537 (and (match-end 1)
5538 (delete-region (match-beginning 1) (match-end 1)))
5539 (setq pos (point-at-bol))
5540 (or split (end-of-line 1))
5541 (delete-horizontal-space)
5542 (newline (if blank 2 1))
5543 (when tags
5544 (save-excursion
5545 (goto-char pos)
5546 (end-of-line 1)
5547 (insert " " tags)
5548 (org-set-tags nil 'align))))
5550 (or split (end-of-line 1))
5551 (newline (if blank 2 1)))))))
5552 (insert head) (just-one-space)
5553 (setq pos (point))
5554 (end-of-line 1)
5555 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5556 (when (and org-insert-heading-respect-content hide-previous)
5557 (save-excursion
5558 (goto-char previous-pos)
5559 (hide-subtree)))
5560 (run-hooks 'org-insert-heading-hook)))))
5562 (defun org-get-heading (&optional no-tags)
5563 "Return the heading of the current entry, without the stars."
5564 (save-excursion
5565 (org-back-to-heading t)
5566 (if (looking-at
5567 (if no-tags
5568 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5569 "\\*+[ \t]+\\([^\r\n]*\\)"))
5570 (match-string 1) "")))
5572 (defun org-heading-components ()
5573 "Return the components of the current heading.
5574 This is a list with the following elements:
5575 - the level as an integer
5576 - the reduced level, different if `org-odd-levels-only' is set.
5577 - the TODO keyword, or nil
5578 - the priority character, like ?A, or nil if no priority is given
5579 - the headline text itself, or the tags string if no headline text
5580 - the tags string, or nil."
5581 (save-excursion
5582 (org-back-to-heading t)
5583 (if (looking-at org-complex-heading-regexp)
5584 (list (length (match-string 1))
5585 (org-reduced-level (length (match-string 1)))
5586 (org-match-string-no-properties 2)
5587 (and (match-end 3) (aref (match-string 3) 2))
5588 (org-match-string-no-properties 4)
5589 (org-match-string-no-properties 5)))))
5591 (defun org-get-entry ()
5592 "Get the entry text, after heading, entire subtree."
5593 (save-excursion
5594 (org-back-to-heading t)
5595 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
5597 (defun org-insert-heading-after-current ()
5598 "Insert a new heading with same level as current, after current subtree."
5599 (interactive)
5600 (org-back-to-heading)
5601 (org-insert-heading)
5602 (org-move-subtree-down)
5603 (end-of-line 1))
5605 (defun org-insert-heading-respect-content ()
5606 (interactive)
5607 (let ((org-insert-heading-respect-content t))
5608 (org-insert-heading t)))
5610 (defun org-insert-todo-heading-respect-content (&optional force-state)
5611 (interactive "P")
5612 (let ((org-insert-heading-respect-content t))
5613 (org-insert-todo-heading force-state t)))
5615 (defun org-insert-todo-heading (arg &optional force-heading)
5616 "Insert a new heading with the same level and TODO state as current heading.
5617 If the heading has no TODO state, or if the state is DONE, use the first
5618 state (TODO by default). Also with prefix arg, force first state."
5619 (interactive "P")
5620 (when (or force-heading (not (org-insert-item 'checkbox)))
5621 (org-insert-heading force-heading)
5622 (save-excursion
5623 (org-back-to-heading)
5624 (outline-previous-heading)
5625 (looking-at org-todo-line-regexp))
5626 (let*
5627 ((new-mark-x
5628 (if (or arg
5629 (not (match-beginning 2))
5630 (member (match-string 2) org-done-keywords))
5631 (car org-todo-keywords-1)
5632 (match-string 2)))
5633 (new-mark
5635 (run-hook-with-args-until-success
5636 'org-todo-get-default-hook new-mark-x nil)
5637 new-mark-x)))
5638 (beginning-of-line 1)
5639 (and (looking-at "\\*+ ") (goto-char (match-end 0))
5640 (if org-treat-insert-todo-heading-as-state-change
5641 (org-todo new-mark)
5642 (insert new-mark " "))))
5643 (when org-provide-todo-statistics
5644 (org-update-parent-todo-statistics))))
5646 (defun org-insert-subheading (arg)
5647 "Insert a new subheading and demote it.
5648 Works for outline headings and for plain lists alike."
5649 (interactive "P")
5650 (org-insert-heading arg)
5651 (cond
5652 ((org-on-heading-p) (org-do-demote))
5653 ((org-at-item-p) (org-indent-item 1))))
5655 (defun org-insert-todo-subheading (arg)
5656 "Insert a new subheading with TODO keyword or checkbox and demote it.
5657 Works for outline headings and for plain lists alike."
5658 (interactive "P")
5659 (org-insert-todo-heading arg)
5660 (cond
5661 ((org-on-heading-p) (org-do-demote))
5662 ((org-at-item-p) (org-indent-item 1))))
5664 ;;; Promotion and Demotion
5666 (defun org-promote-subtree ()
5667 "Promote the entire subtree.
5668 See also `org-promote'."
5669 (interactive)
5670 (save-excursion
5671 (org-map-tree 'org-promote))
5672 (org-fix-position-after-promote))
5674 (defun org-demote-subtree ()
5675 "Demote the entire subtree. See `org-demote'.
5676 See also `org-promote'."
5677 (interactive)
5678 (save-excursion
5679 (org-map-tree 'org-demote))
5680 (org-fix-position-after-promote))
5683 (defun org-do-promote ()
5684 "Promote the current heading higher up the tree.
5685 If the region is active in `transient-mark-mode', promote all headings
5686 in the region."
5687 (interactive)
5688 (save-excursion
5689 (if (org-region-active-p)
5690 (org-map-region 'org-promote (region-beginning) (region-end))
5691 (org-promote)))
5692 (org-fix-position-after-promote))
5694 (defun org-do-demote ()
5695 "Demote the current heading lower down the tree.
5696 If the region is active in `transient-mark-mode', demote all headings
5697 in the region."
5698 (interactive)
5699 (save-excursion
5700 (if (org-region-active-p)
5701 (org-map-region 'org-demote (region-beginning) (region-end))
5702 (org-demote)))
5703 (org-fix-position-after-promote))
5705 (defun org-fix-position-after-promote ()
5706 "Make sure that after pro/demotion cursor position is right."
5707 (let ((pos (point)))
5708 (when (save-excursion
5709 (beginning-of-line 1)
5710 (looking-at org-todo-line-regexp)
5711 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5712 (cond ((eobp) (insert " "))
5713 ((eolp) (insert " "))
5714 ((equal (char-after) ?\ ) (forward-char 1))))))
5716 (defun org-reduced-level (l)
5717 "Compute the effective level of a heading.
5718 This takes into account the setting of `org-odd-levels-only'."
5719 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5721 (defun org-get-valid-level (level &optional change)
5722 "Rectify a level change under the influence of `org-odd-levels-only'
5723 LEVEL is a current level, CHANGE is by how much the level should be
5724 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5725 even level numbers will become the next higher odd number."
5726 (if org-odd-levels-only
5727 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5728 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5729 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5730 (max 1 (+ level (or change 0)))))
5732 (if (boundp 'define-obsolete-function-alias)
5733 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5734 (define-obsolete-function-alias 'org-get-legal-level
5735 'org-get-valid-level)
5736 (define-obsolete-function-alias 'org-get-legal-level
5737 'org-get-valid-level "23.1")))
5739 (defun org-promote ()
5740 "Promote the current heading higher up the tree.
5741 If the region is active in `transient-mark-mode', promote all headings
5742 in the region."
5743 (org-back-to-heading t)
5744 (let* ((level (save-match-data (funcall outline-level)))
5745 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5746 (diff (abs (- level (length up-head) -1))))
5747 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5748 (replace-match up-head nil t)
5749 ;; Fixup tag positioning
5750 (and org-auto-align-tags (org-set-tags nil t))
5751 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5753 (defun org-demote ()
5754 "Demote the current heading lower down the tree.
5755 If the region is active in `transient-mark-mode', demote all headings
5756 in the region."
5757 (org-back-to-heading t)
5758 (let* ((level (save-match-data (funcall outline-level)))
5759 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5760 (diff (abs (- level (length down-head) -1))))
5761 (replace-match down-head nil t)
5762 ;; Fixup tag positioning
5763 (and org-auto-align-tags (org-set-tags nil t))
5764 (if org-adapt-indentation (org-fixup-indentation diff))))
5766 (defun org-map-tree (fun)
5767 "Call FUN for every heading underneath the current one."
5768 (org-back-to-heading)
5769 (let ((level (funcall outline-level)))
5770 (save-excursion
5771 (funcall fun)
5772 (while (and (progn
5773 (outline-next-heading)
5774 (> (funcall outline-level) level))
5775 (not (eobp)))
5776 (funcall fun)))))
5778 (defun org-map-region (fun beg end)
5779 "Call FUN for every heading between BEG and END."
5780 (let ((org-ignore-region t))
5781 (save-excursion
5782 (setq end (copy-marker end))
5783 (goto-char beg)
5784 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5785 (< (point) end))
5786 (funcall fun))
5787 (while (and (progn
5788 (outline-next-heading)
5789 (< (point) end))
5790 (not (eobp)))
5791 (funcall fun)))))
5793 (defun org-fixup-indentation (diff)
5794 "Change the indentation in the current entry by DIFF
5795 However, if any line in the current entry has no indentation, or if it
5796 would end up with no indentation after the change, nothing at all is done."
5797 (save-excursion
5798 (let ((end (save-excursion (outline-next-heading)
5799 (point-marker)))
5800 (prohibit (if (> diff 0)
5801 "^\\S-"
5802 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5803 col)
5804 (unless (save-excursion (end-of-line 1)
5805 (re-search-forward prohibit end t))
5806 (while (and (< (point) end)
5807 (re-search-forward "^[ \t]+" end t))
5808 (goto-char (match-end 0))
5809 (setq col (current-column))
5810 (if (< diff 0) (replace-match ""))
5811 (org-indent-to-column (+ diff col))))
5812 (move-marker end nil))))
5814 (defun org-convert-to-odd-levels ()
5815 "Convert an org-mode file with all levels allowed to one with odd levels.
5816 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5817 level 5 etc."
5818 (interactive)
5819 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5820 (let ((org-odd-levels-only nil) n)
5821 (save-excursion
5822 (goto-char (point-min))
5823 (while (re-search-forward "^\\*\\*+ " nil t)
5824 (setq n (- (length (match-string 0)) 2))
5825 (while (>= (setq n (1- n)) 0)
5826 (org-demote))
5827 (end-of-line 1))))))
5830 (defun org-convert-to-oddeven-levels ()
5831 "Convert an org-mode file with only odd levels to one with odd and even levels.
5832 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5833 section with an even level, conversion would destroy the structure of the file. An error
5834 is signaled in this case."
5835 (interactive)
5836 (goto-char (point-min))
5837 ;; First check if there are no even levels
5838 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5839 (org-show-context t)
5840 (error "Not all levels are odd in this file. Conversion not possible."))
5841 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5842 (let ((org-odd-levels-only nil) n)
5843 (save-excursion
5844 (goto-char (point-min))
5845 (while (re-search-forward "^\\*\\*+ " nil t)
5846 (setq n (/ (1- (length (match-string 0))) 2))
5847 (while (>= (setq n (1- n)) 0)
5848 (org-promote))
5849 (end-of-line 1))))))
5851 (defun org-tr-level (n)
5852 "Make N odd if required."
5853 (if org-odd-levels-only (1+ (/ n 2)) n))
5855 ;;; Vertical tree motion, cutting and pasting of subtrees
5857 (defun org-move-subtree-up (&optional arg)
5858 "Move the current subtree up past ARG headlines of the same level."
5859 (interactive "p")
5860 (org-move-subtree-down (- (prefix-numeric-value arg))))
5862 (defun org-move-subtree-down (&optional arg)
5863 "Move the current subtree down past ARG headlines of the same level."
5864 (interactive "p")
5865 (setq arg (prefix-numeric-value arg))
5866 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5867 'outline-get-last-sibling))
5868 (ins-point (make-marker))
5869 (cnt (abs arg))
5870 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5871 ;; Select the tree
5872 (org-back-to-heading)
5873 (setq beg0 (point))
5874 (save-excursion
5875 (setq ne-beg (org-back-over-empty-lines))
5876 (setq beg (point)))
5877 (save-match-data
5878 (save-excursion (outline-end-of-heading)
5879 (setq folded (org-invisible-p)))
5880 (outline-end-of-subtree))
5881 (outline-next-heading)
5882 (setq ne-end (org-back-over-empty-lines))
5883 (setq end (point))
5884 (goto-char beg0)
5885 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5886 ;; include less whitespace
5887 (save-excursion
5888 (goto-char beg)
5889 (forward-line (- ne-beg ne-end))
5890 (setq beg (point))))
5891 ;; Find insertion point, with error handling
5892 (while (> cnt 0)
5893 (or (and (funcall movfunc) (looking-at outline-regexp))
5894 (progn (goto-char beg0)
5895 (error "Cannot move past superior level or buffer limit")))
5896 (setq cnt (1- cnt)))
5897 (if (> arg 0)
5898 ;; Moving forward - still need to move over subtree
5899 (progn (org-end-of-subtree t t)
5900 (save-excursion
5901 (org-back-over-empty-lines)
5902 (or (bolp) (newline)))))
5903 (setq ne-ins (org-back-over-empty-lines))
5904 (move-marker ins-point (point))
5905 (setq txt (buffer-substring beg end))
5906 (org-save-markers-in-region beg end)
5907 (delete-region beg end)
5908 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5909 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5910 (and (not (bolp)) (looking-at "\n") (forward-char 1))
5911 (let ((bbb (point)))
5912 (insert-before-markers txt)
5913 (org-reinstall-markers-in-region bbb)
5914 (move-marker ins-point bbb))
5915 (or (bolp) (insert "\n"))
5916 (setq ins-end (point))
5917 (goto-char ins-point)
5918 (org-skip-whitespace)
5919 (when (and (< arg 0)
5920 (org-first-sibling-p)
5921 (> ne-ins ne-beg))
5922 ;; Move whitespace back to beginning
5923 (save-excursion
5924 (goto-char ins-end)
5925 (let ((kill-whole-line t))
5926 (kill-line (- ne-ins ne-beg)) (point)))
5927 (insert (make-string (- ne-ins ne-beg) ?\n)))
5928 (move-marker ins-point nil)
5929 (org-compact-display-after-subtree-move)
5930 (org-show-empty-lines-in-parent)
5931 (unless folded
5932 (org-show-entry)
5933 (show-children)
5934 (org-cycle-hide-drawers 'children))))
5936 (defvar org-subtree-clip ""
5937 "Clipboard for cut and paste of subtrees.
5938 This is actually only a copy of the kill, because we use the normal kill
5939 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5941 (defvar org-subtree-clip-folded nil
5942 "Was the last copied subtree folded?
5943 This is used to fold the tree back after pasting.")
5945 (defun org-cut-subtree (&optional n)
5946 "Cut the current subtree into the clipboard.
5947 With prefix arg N, cut this many sequential subtrees.
5948 This is a short-hand for marking the subtree and then cutting it."
5949 (interactive "p")
5950 (org-copy-subtree n 'cut))
5952 (defun org-copy-subtree (&optional n cut force-store-markers)
5953 "Cut the current subtree into the clipboard.
5954 With prefix arg N, cut this many sequential subtrees.
5955 This is a short-hand for marking the subtree and then copying it.
5956 If CUT is non-nil, actually cut the subtree.
5957 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5958 of some markers in the region, even if CUT is non-nil. This is
5959 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5960 (interactive "p")
5961 (let (beg end folded (beg0 (point)))
5962 (if (interactive-p)
5963 (org-back-to-heading nil) ; take what looks like a subtree
5964 (org-back-to-heading t)) ; take what is really there
5965 (org-back-over-empty-lines)
5966 (setq beg (point))
5967 (skip-chars-forward " \t\r\n")
5968 (save-match-data
5969 (save-excursion (outline-end-of-heading)
5970 (setq folded (org-invisible-p)))
5971 (condition-case nil
5972 (outline-forward-same-level (1- n))
5973 (error nil))
5974 (org-end-of-subtree t t))
5975 (org-back-over-empty-lines)
5976 (setq end (point))
5977 (goto-char beg0)
5978 (when (> end beg)
5979 (setq org-subtree-clip-folded folded)
5980 (when (or cut force-store-markers)
5981 (org-save-markers-in-region beg end))
5982 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5983 (setq org-subtree-clip (current-kill 0))
5984 (message "%s: Subtree(s) with %d characters"
5985 (if cut "Cut" "Copied")
5986 (length org-subtree-clip)))))
5988 (defun org-paste-subtree (&optional level tree for-yank)
5989 "Paste the clipboard as a subtree, with modification of headline level.
5990 The entire subtree is promoted or demoted in order to match a new headline
5991 level.
5993 If the cursor is at the beginning of a headline, the same level as
5994 that headline is used to paste the tree
5996 If not, the new level is derived from the *visible* headings
5997 before and after the insertion point, and taken to be the inferior headline
5998 level of the two. So if the previous visible heading is level 3 and the
5999 next is level 4 (or vice versa), level 4 will be used for insertion.
6000 This makes sure that the subtree remains an independent subtree and does
6001 not swallow low level entries.
6003 You can also force a different level, either by using a numeric prefix
6004 argument, or by inserting the heading marker by hand. For example, if the
6005 cursor is after \"*****\", then the tree will be shifted to level 5.
6007 If optional TREE is given, use this text instead of the kill ring.
6009 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6010 move back over whitespace before inserting, and move point to the end of
6011 the inserted text when done."
6012 (interactive "P")
6013 (unless (org-kill-is-subtree-p tree)
6014 (error "%s"
6015 (substitute-command-keys
6016 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6017 (let* ((visp (not (org-invisible-p)))
6018 (txt (or tree (and kill-ring (current-kill 0))))
6019 (^re (concat "^\\(" outline-regexp "\\)"))
6020 (re (concat "\\(" outline-regexp "\\)"))
6021 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6023 (old-level (if (string-match ^re txt)
6024 (- (match-end 0) (match-beginning 0) 1)
6025 -1))
6026 (force-level (cond (level (prefix-numeric-value level))
6027 ((and (looking-at "[ \t]*$")
6028 (string-match
6029 ^re_ (buffer-substring
6030 (point-at-bol) (point))))
6031 (- (match-end 1) (match-beginning 1)))
6032 ((and (bolp)
6033 (looking-at org-outline-regexp))
6034 (- (match-end 0) (point) 1))
6035 (t nil)))
6036 (previous-level (save-excursion
6037 (condition-case nil
6038 (progn
6039 (outline-previous-visible-heading 1)
6040 (if (looking-at re)
6041 (- (match-end 0) (match-beginning 0) 1)
6043 (error 1))))
6044 (next-level (save-excursion
6045 (condition-case nil
6046 (progn
6047 (or (looking-at outline-regexp)
6048 (outline-next-visible-heading 1))
6049 (if (looking-at re)
6050 (- (match-end 0) (match-beginning 0) 1)
6052 (error 1))))
6053 (new-level (or force-level (max previous-level next-level)))
6054 (shift (if (or (= old-level -1)
6055 (= new-level -1)
6056 (= old-level new-level))
6058 (- new-level old-level)))
6059 (delta (if (> shift 0) -1 1))
6060 (func (if (> shift 0) 'org-demote 'org-promote))
6061 (org-odd-levels-only nil)
6062 beg end newend)
6063 ;; Remove the forced level indicator
6064 (if force-level
6065 (delete-region (point-at-bol) (point)))
6066 ;; Paste
6067 (beginning-of-line 1)
6068 (unless for-yank (org-back-over-empty-lines))
6069 (setq beg (point))
6070 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6071 (insert-before-markers txt)
6072 (unless (string-match "\n\\'" txt) (insert "\n"))
6073 (setq newend (point))
6074 (org-reinstall-markers-in-region beg)
6075 (setq end (point))
6076 (goto-char beg)
6077 (skip-chars-forward " \t\n\r")
6078 (setq beg (point))
6079 (if (and (org-invisible-p) visp)
6080 (save-excursion (outline-show-heading)))
6081 ;; Shift if necessary
6082 (unless (= shift 0)
6083 (save-restriction
6084 (narrow-to-region beg end)
6085 (while (not (= shift 0))
6086 (org-map-region func (point-min) (point-max))
6087 (setq shift (+ delta shift)))
6088 (goto-char (point-min))
6089 (setq newend (point-max))))
6090 (when (or (interactive-p) for-yank)
6091 (message "Clipboard pasted as level %d subtree" new-level))
6092 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6093 kill-ring
6094 (eq org-subtree-clip (current-kill 0))
6095 org-subtree-clip-folded)
6096 ;; The tree was folded before it was killed/copied
6097 (hide-subtree))
6098 (and for-yank (goto-char newend))))
6100 (defun org-kill-is-subtree-p (&optional txt)
6101 "Check if the current kill is an outline subtree, or a set of trees.
6102 Returns nil if kill does not start with a headline, or if the first
6103 headline level is not the largest headline level in the tree.
6104 So this will actually accept several entries of equal levels as well,
6105 which is OK for `org-paste-subtree'.
6106 If optional TXT is given, check this string instead of the current kill."
6107 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6108 (start-level (and kill
6109 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6110 org-outline-regexp "\\)")
6111 kill)
6112 (- (match-end 2) (match-beginning 2) 1)))
6113 (re (concat "^" org-outline-regexp))
6114 (start (1+ (or (match-beginning 2) -1))))
6115 (if (not start-level)
6116 (progn
6117 nil) ;; does not even start with a heading
6118 (catch 'exit
6119 (while (setq start (string-match re kill (1+ start)))
6120 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6121 (throw 'exit nil)))
6122 t))))
6124 (defvar org-markers-to-move nil
6125 "Markers that should be moved with a cut-and-paste operation.
6126 Those markers are stored together with their positions relative to
6127 the start of the region.")
6129 (defun org-save-markers-in-region (beg end)
6130 "Check markers in region.
6131 If these markers are between BEG and END, record their position relative
6132 to BEG, so that after moving the block of text, we can put the markers back
6133 into place.
6134 This function gets called just before an entry or tree gets cut from the
6135 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6136 called immediately, to move the markers with the entries."
6137 (setq org-markers-to-move nil)
6138 (when (featurep 'org-clock)
6139 (org-clock-save-markers-for-cut-and-paste beg end))
6140 (when (featurep 'org-agenda)
6141 (org-agenda-save-markers-for-cut-and-paste beg end)))
6143 (defun org-check-and-save-marker (marker beg end)
6144 "Check if MARKER is between BEG and END.
6145 If yes, remember the marker and the distance to BEG."
6146 (when (and (marker-buffer marker)
6147 (equal (marker-buffer marker) (current-buffer)))
6148 (if (and (>= marker beg) (< marker end))
6149 (push (cons marker (- marker beg)) org-markers-to-move))))
6151 (defun org-reinstall-markers-in-region (beg)
6152 "Move all remembered markers to their position relative to BEG."
6153 (mapc (lambda (x)
6154 (move-marker (car x) (+ beg (cdr x))))
6155 org-markers-to-move)
6156 (setq org-markers-to-move nil))
6158 (defun org-narrow-to-subtree ()
6159 "Narrow buffer to the current subtree."
6160 (interactive)
6161 (save-excursion
6162 (save-match-data
6163 (narrow-to-region
6164 (progn (org-back-to-heading) (point))
6165 (progn (org-end-of-subtree t) (point))))))
6167 (defun org-clone-subtree-with-time-shift (n &optional shift)
6168 "Clone the task (subtree) at point N times.
6169 The clones will be inserted as siblings.
6171 In interactive use, the user will be prompted for the number of clones
6172 to be produced, and for a time SHIFT, which may be a repeater as used
6173 in time stamps, for example `+3d'.
6175 When a valid repeater is given and the entry contains any time stamps,
6176 the clones will become a sequence in time, with time stamps in the
6177 subtree shifted for each clone produced. If SHIFT is nil or the
6178 empty string, time stamps will be left alone.
6180 If the original subtree did contain time stamps with a repeater,
6181 the following will happen:
6182 - the repeater will be removed in each clone
6183 - an additional clone will be produced, with the current, unshifted
6184 date(s) in the entry.
6185 - the original entry will be placed *after* all the clones, with
6186 repeater intact.
6187 - the start days in the repeater in the original entry will be shifted
6188 to past the last clone.
6189 I this way you can spell out a number of instances of a repeating task,
6190 and still retain the repeater to cover future instances of the task."
6191 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6192 (let (beg end template task
6193 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6194 (if (not (and (integerp n) (> n 0)))
6195 (error "Invalid number of replications %s" n))
6196 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6197 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6198 shift)))
6199 (error "Invalid shift specification %s" shift))
6200 (when doshift
6201 (setq shift-n (string-to-number (match-string 1 shift))
6202 shift-what (cdr (assoc (match-string 2 shift)
6203 '(("d" . day) ("w" . week)
6204 ("m" . month) ("y" . year))))))
6205 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6206 (setq nmin 1 nmax n)
6207 (org-back-to-heading t)
6208 (setq beg (point))
6209 (org-end-of-subtree t t)
6210 (setq end (point))
6211 (setq template (buffer-substring beg end))
6212 (when (and doshift
6213 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6214 (delete-region beg end)
6215 (setq end beg)
6216 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6217 (goto-char end)
6218 (loop for n from nmin to nmax do
6219 (if (not doshift)
6220 (setq task template)
6221 (with-temp-buffer
6222 (insert template)
6223 (org-mode)
6224 (goto-char (point-min))
6225 (while (re-search-forward org-ts-regexp nil t)
6226 (org-timestamp-change (* n shift-n) shift-what))
6227 (unless (= n n-no-remove)
6228 (goto-char (point-min))
6229 (while (re-search-forward org-ts-regexp nil t)
6230 (save-excursion
6231 (goto-char (match-beginning 0))
6232 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6233 (delete-region (match-beginning 1) (match-end 1))))))
6234 (setq task (buffer-string))))
6235 (insert task))
6236 (goto-char beg)))
6238 ;;; Outline Sorting
6240 (defun org-sort (with-case)
6241 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6242 Optional argument WITH-CASE means sort case-sensitively.
6243 With a double prefix argument, also remove duplicate entries."
6244 (interactive "P")
6245 (if (org-at-table-p)
6246 (org-call-with-arg 'org-table-sort-lines with-case)
6247 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6249 (defun org-sort-remove-invisible (s)
6250 (remove-text-properties 0 (length s) org-rm-props s)
6251 (while (string-match org-bracket-link-regexp s)
6252 (setq s (replace-match (if (match-end 2)
6253 (match-string 3 s)
6254 (match-string 1 s)) t t s)))
6257 (defvar org-priority-regexp) ; defined later in the file
6259 (defvar org-after-sorting-entries-or-items-hook nil
6260 "Hook that is run after a bunch of entries or items have been sorted.
6261 When children are sorted, the cursor is in the parent line when this
6262 hook gets called. When a region or a plain list is sorted, the cursor
6263 will be in the first entry of the sorted region/list.")
6265 (defun org-sort-entries-or-items
6266 (&optional with-case sorting-type getkey-func compare-func property)
6267 "Sort entries on a certain level of an outline tree, or plain list items.
6268 If there is an active region, the entries in the region are sorted.
6269 Else, if the cursor is before the first entry, sort the top-level items.
6270 Else, the children of the entry at point are sorted.
6271 If the cursor is at the first item in a plain list, the list items will be
6272 sorted.
6274 Sorting can be alphabetically, numerically, by date/time as given by
6275 a time stamp, by a property or by priority.
6277 The command prompts for the sorting type unless it has been given to the
6278 function through the SORTING-TYPE argument, which needs to a character,
6279 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6280 precise meaning of each character:
6282 n Numerically, by converting the beginning of the entry/item to a number.
6283 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6284 t By date/time, either the first active time stamp in the entry, or, if
6285 none exist, by the first inactive one.
6286 In items, only the first line will be chekced.
6287 s By the scheduled date/time.
6288 d By deadline date/time.
6289 c By creation time, which is assumed to be the first inactive time stamp
6290 at the beginning of a line.
6291 p By priority according to the cookie.
6292 r By the value of a property.
6294 Capital letters will reverse the sort order.
6296 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6297 called with point at the beginning of the record. It must return either
6298 a string or a number that should serve as the sorting key for that record.
6300 Comparing entries ignores case by default. However, with an optional argument
6301 WITH-CASE, the sorting considers case as well."
6302 (interactive "P")
6303 (let ((case-func (if with-case 'identity 'downcase))
6304 start beg end stars re re2
6305 txt what tmp plain-list-p)
6306 ;; Find beginning and end of region to sort
6307 (cond
6308 ((org-region-active-p)
6309 ;; we will sort the region
6310 (setq end (region-end)
6311 what "region")
6312 (goto-char (region-beginning))
6313 (if (not (org-on-heading-p)) (outline-next-heading))
6314 (setq start (point)))
6315 ((org-at-item-p)
6316 ;; we will sort this plain list
6317 (org-beginning-of-item-list) (setq start (point))
6318 (org-end-of-item-list) (setq end (point))
6319 (goto-char start)
6320 (setq plain-list-p t
6321 what "plain list"))
6322 ((or (org-on-heading-p)
6323 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6324 ;; we will sort the children of the current headline
6325 (org-back-to-heading)
6326 (setq start (point)
6327 end (progn (org-end-of-subtree t t)
6328 (org-back-over-empty-lines)
6329 (point))
6330 what "children")
6331 (goto-char start)
6332 (show-subtree)
6333 (outline-next-heading))
6335 ;; we will sort the top-level entries in this file
6336 (goto-char (point-min))
6337 (or (org-on-heading-p) (outline-next-heading))
6338 (setq start (point) end (point-max) what "top-level")
6339 (goto-char start)
6340 (show-all)))
6342 (setq beg (point))
6343 (if (>= beg end) (error "Nothing to sort"))
6345 (unless plain-list-p
6346 (looking-at "\\(\\*+\\)")
6347 (setq stars (match-string 1)
6348 re (concat "^" (regexp-quote stars) " +")
6349 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6350 txt (buffer-substring beg end))
6351 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6352 (if (and (not (equal stars "*")) (string-match re2 txt))
6353 (error "Region to sort contains a level above the first entry")))
6355 (unless sorting-type
6356 (message
6357 (if plain-list-p
6358 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6359 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
6360 [t]ime [s]cheduled [d]eadline [c]reated
6361 A/N/T/S/D/C/P/O/F means reversed:")
6362 what)
6363 (setq sorting-type (read-char-exclusive))
6365 (and (= (downcase sorting-type) ?f)
6366 (setq getkey-func
6367 (org-ido-completing-read "Sort using function: "
6368 obarray 'fboundp t nil nil))
6369 (setq getkey-func (intern getkey-func)))
6371 (and (= (downcase sorting-type) ?r)
6372 (setq property
6373 (org-ido-completing-read "Property: "
6374 (mapcar 'list (org-buffer-property-keys t))
6375 nil t))))
6377 (message "Sorting entries...")
6379 (save-restriction
6380 (narrow-to-region start end)
6382 (let ((dcst (downcase sorting-type))
6383 (case-fold-search nil)
6384 (now (current-time)))
6385 (sort-subr
6386 (/= dcst sorting-type)
6387 ;; This function moves to the beginning character of the "record" to
6388 ;; be sorted.
6389 (if plain-list-p
6390 (lambda nil
6391 (if (org-at-item-p) t (goto-char (point-max))))
6392 (lambda nil
6393 (if (re-search-forward re nil t)
6394 (goto-char (match-beginning 0))
6395 (goto-char (point-max)))))
6396 ;; This function moves to the last character of the "record" being
6397 ;; sorted.
6398 (if plain-list-p
6399 'org-end-of-item
6400 (lambda nil
6401 (save-match-data
6402 (condition-case nil
6403 (outline-forward-same-level 1)
6404 (error
6405 (goto-char (point-max)))))))
6407 ;; This function returns the value that gets sorted against.
6408 (if plain-list-p
6409 (lambda nil
6410 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6411 (cond
6412 ((= dcst ?n)
6413 (string-to-number (buffer-substring (match-end 0)
6414 (point-at-eol))))
6415 ((= dcst ?a)
6416 (buffer-substring (match-end 0) (point-at-eol)))
6417 ((= dcst ?t)
6418 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
6419 (re-search-forward org-ts-regexp-both
6420 (point-at-eol) t))
6421 (org-time-string-to-seconds (match-string 0))
6422 (time-to-seconds now)))
6423 ((= dcst ?f)
6424 (if getkey-func
6425 (progn
6426 (setq tmp (funcall getkey-func))
6427 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6428 tmp)
6429 (error "Invalid key function `%s'" getkey-func)))
6430 (t (error "Invalid sorting type `%c'" sorting-type)))))
6431 (lambda nil
6432 (cond
6433 ((= dcst ?n)
6434 (if (looking-at org-complex-heading-regexp)
6435 (string-to-number (match-string 4))
6436 nil))
6437 ((= dcst ?a)
6438 (if (looking-at org-complex-heading-regexp)
6439 (funcall case-func (match-string 4))
6440 nil))
6441 ((= dcst ?t)
6442 (let ((end (save-excursion (outline-next-heading) (point))))
6443 (if (or (re-search-forward org-ts-regexp end t)
6444 (re-search-forward org-ts-regexp-both end t))
6445 (org-time-string-to-seconds (match-string 0))
6446 (time-to-seconds now))))
6447 ((= dcst ?c)
6448 (let ((end (save-excursion (outline-next-heading) (point))))
6449 (if (re-search-forward
6450 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
6451 end t)
6452 (org-time-string-to-seconds (match-string 0))
6453 (time-to-seconds now))))
6454 ((= dcst ?s)
6455 (let ((end (save-excursion (outline-next-heading) (point))))
6456 (if (re-search-forward org-scheduled-time-regexp end t)
6457 (org-time-string-to-seconds (match-string 1))
6458 (time-to-seconds now))))
6459 ((= dcst ?d)
6460 (let ((end (save-excursion (outline-next-heading) (point))))
6461 (if (re-search-forward org-deadline-time-regexp end t)
6462 (org-time-string-to-seconds (match-string 1))
6463 (time-to-seconds now))))
6464 ((= dcst ?p)
6465 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6466 (string-to-char (match-string 2))
6467 org-default-priority))
6468 ((= dcst ?r)
6469 (or (org-entry-get nil property) ""))
6470 ((= dcst ?o)
6471 (if (looking-at org-complex-heading-regexp)
6472 (- 9999 (length (member (match-string 2)
6473 org-todo-keywords-1)))))
6474 ((= dcst ?f)
6475 (if getkey-func
6476 (progn
6477 (setq tmp (funcall getkey-func))
6478 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6479 tmp)
6480 (error "Invalid key function `%s'" getkey-func)))
6481 (t (error "Invalid sorting type `%c'" sorting-type)))))
6483 (cond
6484 ((= dcst ?a) 'string<)
6485 ((= dcst ?f) compare-func)
6486 ((member dcst '(?p ?t ?s ?d ?c)) '<)
6487 (t nil)))))
6488 (run-hooks 'org-after-sorting-entries-or-items-hook)
6489 (message "Sorting entries...done")))
6491 (defun org-do-sort (table what &optional with-case sorting-type)
6492 "Sort TABLE of WHAT according to SORTING-TYPE.
6493 The user will be prompted for the SORTING-TYPE if the call to this
6494 function does not specify it. WHAT is only for the prompt, to indicate
6495 what is being sorted. The sorting key will be extracted from
6496 the car of the elements of the table.
6497 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6498 (unless sorting-type
6499 (message
6500 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6501 what)
6502 (setq sorting-type (read-char-exclusive)))
6503 (let ((dcst (downcase sorting-type))
6504 extractfun comparefun)
6505 ;; Define the appropriate functions
6506 (cond
6507 ((= dcst ?n)
6508 (setq extractfun 'string-to-number
6509 comparefun (if (= dcst sorting-type) '< '>)))
6510 ((= dcst ?a)
6511 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6512 (lambda(x) (downcase (org-sort-remove-invisible x))))
6513 comparefun (if (= dcst sorting-type)
6514 'string<
6515 (lambda (a b) (and (not (string< a b))
6516 (not (string= a b)))))))
6517 ((= dcst ?t)
6518 (setq extractfun
6519 (lambda (x)
6520 (if (or (string-match org-ts-regexp x)
6521 (string-match org-ts-regexp-both x))
6522 (time-to-seconds
6523 (org-time-string-to-time (match-string 0 x)))
6525 comparefun (if (= dcst sorting-type) '< '>)))
6526 (t (error "Invalid sorting type `%c'" sorting-type)))
6528 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6529 table)
6530 (lambda (a b) (funcall comparefun (car a) (car b))))))
6533 ;;; The orgstruct minor mode
6535 ;; Define a minor mode which can be used in other modes in order to
6536 ;; integrate the org-mode structure editing commands.
6538 ;; This is really a hack, because the org-mode structure commands use
6539 ;; keys which normally belong to the major mode. Here is how it
6540 ;; works: The minor mode defines all the keys necessary to operate the
6541 ;; structure commands, but wraps the commands into a function which
6542 ;; tests if the cursor is currently at a headline or a plain list
6543 ;; item. If that is the case, the structure command is used,
6544 ;; temporarily setting many Org-mode variables like regular
6545 ;; expressions for filling etc. However, when any of those keys is
6546 ;; used at a different location, function uses `key-binding' to look
6547 ;; up if the key has an associated command in another currently active
6548 ;; keymap (minor modes, major mode, global), and executes that
6549 ;; command. There might be problems if any of the keys is otherwise
6550 ;; used as a prefix key.
6552 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6553 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6554 ;; addresses this by checking explicitly for both bindings.
6556 (defvar orgstruct-mode-map (make-sparse-keymap)
6557 "Keymap for the minor `orgstruct-mode'.")
6559 (defvar org-local-vars nil
6560 "List of local variables, for use by `orgstruct-mode'")
6562 ;;;###autoload
6563 (define-minor-mode orgstruct-mode
6564 "Toggle the minor more `orgstruct-mode'.
6565 This mode is for using Org-mode structure commands in other modes.
6566 The following key behave as if Org-mode was active, if the cursor
6567 is on a headline, or on a plain list item (both in the definition
6568 of Org-mode).
6570 M-up Move entry/item up
6571 M-down Move entry/item down
6572 M-left Promote
6573 M-right Demote
6574 M-S-up Move entry/item up
6575 M-S-down Move entry/item down
6576 M-S-left Promote subtree
6577 M-S-right Demote subtree
6578 M-q Fill paragraph and items like in Org-mode
6579 C-c ^ Sort entries
6580 C-c - Cycle list bullet
6581 TAB Cycle item visibility
6582 M-RET Insert new heading/item
6583 S-M-RET Insert new TODO heading / Checkbox item
6584 C-c C-c Set tags / toggle checkbox"
6585 nil " OrgStruct" nil
6586 (org-load-modules-maybe)
6587 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6589 ;;;###autoload
6590 (defun turn-on-orgstruct ()
6591 "Unconditionally turn on `orgstruct-mode'."
6592 (orgstruct-mode 1))
6594 (defun orgstruct++-mode (&optional arg)
6595 "Toggle `orgstruct-mode', the enhanced version of it.
6596 In addition to setting orgstruct-mode, this also exports all indentation and
6597 autofilling variables from org-mode into the buffer. It will also
6598 recognize item context in multiline items.
6599 Note that turning off orgstruct-mode will *not* remove the
6600 indentation/paragraph settings. This can only be done by refreshing the
6601 major mode, for example with \[normal-mode]."
6602 (interactive "P")
6603 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6604 (if (< arg 1)
6605 (orgstruct-mode -1)
6606 (orgstruct-mode 1)
6607 (let (var val)
6608 (mapc
6609 (lambda (x)
6610 (when (string-match
6611 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6612 (symbol-name (car x)))
6613 (setq var (car x) val (nth 1 x))
6614 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6615 org-local-vars)
6616 (org-set-local 'orgstruct-is-++ t))))
6618 (defvar orgstruct-is-++ nil
6619 "Is orgstruct-mode in ++ version in the current-buffer?")
6620 (make-variable-buffer-local 'orgstruct-is-++)
6622 ;;;###autoload
6623 (defun turn-on-orgstruct++ ()
6624 "Unconditionally turn on `orgstruct++-mode'."
6625 (orgstruct++-mode 1))
6627 (defun orgstruct-error ()
6628 "Error when there is no default binding for a structure key."
6629 (interactive)
6630 (error "This key has no function outside structure elements"))
6632 (defun orgstruct-setup ()
6633 "Setup orgstruct keymaps."
6634 (let ((nfunc 0)
6635 (bindings
6636 (list
6637 '([(meta up)] org-metaup)
6638 '([(meta down)] org-metadown)
6639 '([(meta left)] org-metaleft)
6640 '([(meta right)] org-metaright)
6641 '([(meta shift up)] org-shiftmetaup)
6642 '([(meta shift down)] org-shiftmetadown)
6643 '([(meta shift left)] org-shiftmetaleft)
6644 '([(meta shift right)] org-shiftmetaright)
6645 '([?\e (up)] org-metaup)
6646 '([?\e (down)] org-metadown)
6647 '([?\e (left)] org-metaleft)
6648 '([?\e (right)] org-metaright)
6649 '([?\e (shift up)] org-shiftmetaup)
6650 '([?\e (shift down)] org-shiftmetadown)
6651 '([?\e (shift left)] org-shiftmetaleft)
6652 '([?\e (shift right)] org-shiftmetaright)
6653 '([(shift up)] org-shiftup)
6654 '([(shift down)] org-shiftdown)
6655 '([(shift left)] org-shiftleft)
6656 '([(shift right)] org-shiftright)
6657 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6658 '("\M-q" fill-paragraph)
6659 '("\C-c^" org-sort)
6660 '("\C-c-" org-cycle-list-bullet)))
6661 elt key fun cmd)
6662 (while (setq elt (pop bindings))
6663 (setq nfunc (1+ nfunc))
6664 (setq key (org-key (car elt))
6665 fun (nth 1 elt)
6666 cmd (orgstruct-make-binding fun nfunc key))
6667 (org-defkey orgstruct-mode-map key cmd))
6669 ;; Special treatment needed for TAB and RET
6670 (org-defkey orgstruct-mode-map [(tab)]
6671 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6672 (org-defkey orgstruct-mode-map "\C-i"
6673 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6675 (org-defkey orgstruct-mode-map "\M-\C-m"
6676 (orgstruct-make-binding 'org-insert-heading 105
6677 "\M-\C-m" [(meta return)]))
6678 (org-defkey orgstruct-mode-map [(meta return)]
6679 (orgstruct-make-binding 'org-insert-heading 106
6680 [(meta return)] "\M-\C-m"))
6682 (org-defkey orgstruct-mode-map [(shift meta return)]
6683 (orgstruct-make-binding 'org-insert-todo-heading 107
6684 [(meta return)] "\M-\C-m"))
6686 (org-defkey orgstruct-mode-map "\e\C-m"
6687 (orgstruct-make-binding 'org-insert-heading 108
6688 "\e\C-m" [?\e (return)]))
6689 (org-defkey orgstruct-mode-map [?\e (return)]
6690 (orgstruct-make-binding 'org-insert-heading 109
6691 [?\e (return)] "\e\C-m"))
6692 (org-defkey orgstruct-mode-map [?\e (shift return)]
6693 (orgstruct-make-binding 'org-insert-todo-heading 110
6694 [?\e (return)] "\e\C-m"))
6696 (unless org-local-vars
6697 (setq org-local-vars (org-get-local-variables)))
6701 (defun orgstruct-make-binding (fun n &rest keys)
6702 "Create a function for binding in the structure minor mode.
6703 FUN is the command to call inside a table. N is used to create a unique
6704 command name. KEYS are keys that should be checked in for a command
6705 to execute outside of tables."
6706 (eval
6707 (list 'defun
6708 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6709 '(arg)
6710 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6711 "Outside of structure, run the binding of `"
6712 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6713 "'.")
6714 '(interactive "p")
6715 (list 'if
6716 `(org-context-p 'headline 'item
6717 (and orgstruct-is-++
6718 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
6719 'item-body))
6720 (list 'org-run-like-in-org-mode (list 'quote fun))
6721 (list 'let '(orgstruct-mode)
6722 (list 'call-interactively
6723 (append '(or)
6724 (mapcar (lambda (k)
6725 (list 'key-binding k))
6726 keys)
6727 '('orgstruct-error))))))))
6729 (defun org-context-p (&rest contexts)
6730 "Check if local context is any of CONTEXTS.
6731 Possible values in the list of contexts are `table', `headline', and `item'."
6732 (let ((pos (point)))
6733 (goto-char (point-at-bol))
6734 (prog1 (or (and (memq 'table contexts)
6735 (looking-at "[ \t]*|"))
6736 (and (memq 'headline contexts)
6737 ;;????????? (looking-at "\\*+"))
6738 (looking-at outline-regexp))
6739 (and (memq 'item contexts)
6740 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
6741 (and (memq 'item-body contexts)
6742 (org-in-item-p)))
6743 (goto-char pos))))
6745 (defun org-get-local-variables ()
6746 "Return a list of all local variables in an org-mode buffer."
6747 (let (varlist)
6748 (with-current-buffer (get-buffer-create "*Org tmp*")
6749 (erase-buffer)
6750 (org-mode)
6751 (setq varlist (buffer-local-variables)))
6752 (kill-buffer "*Org tmp*")
6753 (delq nil
6754 (mapcar
6755 (lambda (x)
6756 (setq x
6757 (if (symbolp x)
6758 (list x)
6759 (list (car x) (list 'quote (cdr x)))))
6760 (if (string-match
6761 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6762 (symbol-name (car x)))
6763 x nil))
6764 varlist))))
6766 ;;;###autoload
6767 (defun org-run-like-in-org-mode (cmd)
6768 "Run a command, pretending that the current buffer is in Org-mode.
6769 This will temporarily bind local variables that are typically bound in
6770 Org-mode to the values they have in Org-mode, and then interactively
6771 call CMD."
6772 (org-load-modules-maybe)
6773 (unless org-local-vars
6774 (setq org-local-vars (org-get-local-variables)))
6775 (eval (list 'let org-local-vars
6776 (list 'call-interactively (list 'quote cmd)))))
6778 ;;;; Archiving
6780 (defun org-get-category (&optional pos)
6781 "Get the category applying to position POS."
6782 (get-text-property (or pos (point)) 'org-category))
6784 (defun org-refresh-category-properties ()
6785 "Refresh category text properties in the buffer."
6786 (let ((def-cat (cond
6787 ((null org-category)
6788 (if buffer-file-name
6789 (file-name-sans-extension
6790 (file-name-nondirectory buffer-file-name))
6791 "???"))
6792 ((symbolp org-category) (symbol-name org-category))
6793 (t org-category)))
6794 beg end cat pos optionp)
6795 (org-unmodified
6796 (save-excursion
6797 (save-restriction
6798 (widen)
6799 (goto-char (point-min))
6800 (put-text-property (point) (point-max) 'org-category def-cat)
6801 (while (re-search-forward
6802 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6803 (setq pos (match-end 0)
6804 optionp (equal (char-after (match-beginning 0)) ?#)
6805 cat (org-trim (match-string 2)))
6806 (if optionp
6807 (setq beg (point-at-bol) end (point-max))
6808 (org-back-to-heading t)
6809 (setq beg (point) end (org-end-of-subtree t t)))
6810 (put-text-property beg end 'org-category cat)
6811 (goto-char pos)))))))
6814 ;;;; Link Stuff
6816 ;;; Link abbreviations
6818 (defun org-link-expand-abbrev (link)
6819 "Apply replacements as defined in `org-link-abbrev-alist."
6820 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6821 (let* ((key (match-string 1 link))
6822 (as (or (assoc key org-link-abbrev-alist-local)
6823 (assoc key org-link-abbrev-alist)))
6824 (tag (and (match-end 2) (match-string 3 link)))
6825 rpl)
6826 (if (not as)
6827 link
6828 (setq rpl (cdr as))
6829 (cond
6830 ((symbolp rpl) (funcall rpl tag))
6831 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6832 ((string-match "%h" rpl)
6833 (replace-match (url-hexify-string (or tag "")) t t rpl))
6834 (t (concat rpl tag)))))
6835 link))
6837 ;;; Storing and inserting links
6839 (defvar org-insert-link-history nil
6840 "Minibuffer history for links inserted with `org-insert-link'.")
6842 (defvar org-stored-links nil
6843 "Contains the links stored with `org-store-link'.")
6845 (defvar org-store-link-plist nil
6846 "Plist with info about the most recently link created with `org-store-link'.")
6848 (defvar org-link-protocols nil
6849 "Link protocols added to Org-mode using `org-add-link-type'.")
6851 (defvar org-store-link-functions nil
6852 "List of functions that are called to create and store a link.
6853 Each function will be called in turn until one returns a non-nil
6854 value. Each function should check if it is responsible for creating
6855 this link (for example by looking at the major mode).
6856 If not, it must exit and return nil.
6857 If yes, it should return a non-nil value after a calling
6858 `org-store-link-props' with a list of properties and values.
6859 Special properties are:
6861 :type The link prefix. like \"http\". This must be given.
6862 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6863 This is obligatory as well.
6864 :description Optional default description for the second pair
6865 of brackets in an Org-mode link. The user can still change
6866 this when inserting this link into an Org-mode buffer.
6868 In addition to these, any additional properties can be specified
6869 and then used in remember templates.")
6871 (defun org-add-link-type (type &optional follow export)
6872 "Add TYPE to the list of `org-link-types'.
6873 Re-compute all regular expressions depending on `org-link-types'
6875 FOLLOW and EXPORT are two functions.
6877 FOLLOW should take the link path as the single argument and do whatever
6878 is necessary to follow the link, for example find a file or display
6879 a mail message.
6881 EXPORT should format the link path for export to one of the export formats.
6882 It should be a function accepting three arguments:
6884 path the path of the link, the text after the prefix (like \"http:\")
6885 desc the description of the link, if any, nil if there was no description
6886 format the export format, a symbol like `html' or `latex'.
6888 The function may use the FORMAT information to return different values
6889 depending on the format. The return value will be put literally into
6890 the exported file.
6891 Org-mode has a built-in default for exporting links. If you are happy with
6892 this default, there is no need to define an export function for the link
6893 type. For a simple example of an export function, see `org-bbdb.el'."
6894 (add-to-list 'org-link-types type t)
6895 (org-make-link-regexps)
6896 (if (assoc type org-link-protocols)
6897 (setcdr (assoc type org-link-protocols) (list follow export))
6898 (push (list type follow export) org-link-protocols)))
6900 ;;;###autoload
6901 (defun org-store-link (arg)
6902 "\\<org-mode-map>Store an org-link to the current location.
6903 This link is added to `org-stored-links' and can later be inserted
6904 into an org-buffer with \\[org-insert-link].
6906 For some link types, a prefix arg is interpreted:
6907 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6908 For file links, arg negates `org-context-in-file-links'."
6909 (interactive "P")
6910 (org-load-modules-maybe)
6911 (setq org-store-link-plist nil) ; reset
6912 (let (link cpltxt desc description search txt custom-id)
6913 (cond
6915 ((run-hook-with-args-until-success 'org-store-link-functions)
6916 (setq link (plist-get org-store-link-plist :link)
6917 desc (or (plist-get org-store-link-plist :description) link)))
6919 ((equal (buffer-name) "*Org Edit Src Example*")
6920 (let (label gc)
6921 (while (or (not label)
6922 (save-excursion
6923 (save-restriction
6924 (widen)
6925 (goto-char (point-min))
6926 (re-search-forward
6927 (regexp-quote (format org-coderef-label-format label))
6928 nil t))))
6929 (when label (message "Label exists already") (sit-for 2))
6930 (setq label (read-string "Code line label: " label)))
6931 (end-of-line 1)
6932 (setq link (format org-coderef-label-format label))
6933 (setq gc (- 79 (length link)))
6934 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6935 (insert link)
6936 (setq link (concat "(" label ")") desc nil)))
6938 ((eq major-mode 'calendar-mode)
6939 (let ((cd (calendar-cursor-to-date)))
6940 (setq link
6941 (format-time-string
6942 (car org-time-stamp-formats)
6943 (apply 'encode-time
6944 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6945 nil nil nil))))
6946 (org-store-link-props :type "calendar" :date cd)))
6948 ((eq major-mode 'w3-mode)
6949 (setq cpltxt (if (and (buffer-name)
6950 (not (string-match "Untitled" (buffer-name))))
6951 (buffer-name)
6952 (url-view-url t))
6953 link (org-make-link (url-view-url t)))
6954 (org-store-link-props :type "w3" :url (url-view-url t)))
6956 ((eq major-mode 'w3m-mode)
6957 (setq cpltxt (or w3m-current-title w3m-current-url)
6958 link (org-make-link w3m-current-url))
6959 (org-store-link-props :type "w3m" :url (url-view-url t)))
6961 ((setq search (run-hook-with-args-until-success
6962 'org-create-file-search-functions))
6963 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6964 "::" search))
6965 (setq cpltxt (or description link)))
6967 ((eq major-mode 'image-mode)
6968 (setq cpltxt (concat "file:"
6969 (abbreviate-file-name buffer-file-name))
6970 link (org-make-link cpltxt))
6971 (org-store-link-props :type "image" :file buffer-file-name))
6973 ((eq major-mode 'dired-mode)
6974 ;; link to the file in the current line
6975 (setq cpltxt (concat "file:"
6976 (abbreviate-file-name
6977 (expand-file-name
6978 (dired-get-filename nil t))))
6979 link (org-make-link cpltxt)))
6981 ((and buffer-file-name (org-mode-p))
6982 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
6983 (cond
6984 ((org-in-regexp "<<\\(.*?\\)>>")
6985 (setq cpltxt
6986 (concat "file:"
6987 (abbreviate-file-name buffer-file-name)
6988 "::" (match-string 1))
6989 link (org-make-link cpltxt)))
6990 ((and (featurep 'org-id)
6991 (or (eq org-link-to-org-use-id t)
6992 (and (eq org-link-to-org-use-id 'create-if-interactive)
6993 (interactive-p))
6994 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
6995 (interactive-p)
6996 (not custom-id))
6997 (and org-link-to-org-use-id
6998 (condition-case nil
6999 (org-entry-get nil "ID")
7000 (error nil)))))
7001 ;; We can make a link using the ID.
7002 (setq link (condition-case nil
7003 (prog1 (org-id-store-link)
7004 (setq desc (plist-get org-store-link-plist
7005 :description)))
7006 (error
7007 ;; probably before first headline, link to file only
7008 (concat "file:"
7009 (abbreviate-file-name buffer-file-name))))))
7011 ;; Just link to current headline
7012 (setq cpltxt (concat "file:"
7013 (abbreviate-file-name buffer-file-name)))
7014 ;; Add a context search string
7015 (when (org-xor org-context-in-file-links arg)
7016 (setq txt (cond
7017 ((org-on-heading-p) nil)
7018 ((org-region-active-p)
7019 (buffer-substring (region-beginning) (region-end)))
7020 (t nil)))
7021 (when (or (null txt) (string-match "\\S-" txt))
7022 (setq cpltxt
7023 (concat cpltxt "::"
7024 (condition-case nil
7025 (org-make-org-heading-search-string txt)
7026 (error "")))
7027 desc "NONE")))
7028 (if (string-match "::\\'" cpltxt)
7029 (setq cpltxt (substring cpltxt 0 -2)))
7030 (setq link (org-make-link cpltxt)))))
7032 ((buffer-file-name (buffer-base-buffer))
7033 ;; Just link to this file here.
7034 (setq cpltxt (concat "file:"
7035 (abbreviate-file-name
7036 (buffer-file-name (buffer-base-buffer)))))
7037 ;; Add a context string
7038 (when (org-xor org-context-in-file-links arg)
7039 (setq txt (if (org-region-active-p)
7040 (buffer-substring (region-beginning) (region-end))
7041 (buffer-substring (point-at-bol) (point-at-eol))))
7042 ;; Only use search option if there is some text.
7043 (when (string-match "\\S-" txt)
7044 (setq cpltxt
7045 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7046 desc "NONE")))
7047 (setq link (org-make-link cpltxt)))
7049 ((interactive-p)
7050 (error "Cannot link to a buffer which is not visiting a file"))
7052 (t (setq link nil)))
7054 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7055 (setq link (or link cpltxt)
7056 desc (or desc cpltxt))
7057 (if (equal desc "NONE") (setq desc nil))
7059 (if (and (interactive-p) link)
7060 (progn
7061 (setq org-stored-links
7062 (cons (list link desc) org-stored-links))
7063 (message "Stored: %s" (or desc link))
7064 (when custom-id
7065 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7066 "::#" custom-id))
7067 (setq org-stored-links
7068 (cons (list link desc) org-stored-links))))
7069 (and link (org-make-link-string link desc)))))
7071 (defun org-store-link-props (&rest plist)
7072 "Store link properties, extract names and addresses."
7073 (let (x adr)
7074 (when (setq x (plist-get plist :from))
7075 (setq adr (mail-extract-address-components x))
7076 (setq plist (plist-put plist :fromname (car adr)))
7077 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7078 (when (setq x (plist-get plist :to))
7079 (setq adr (mail-extract-address-components x))
7080 (setq plist (plist-put plist :toname (car adr)))
7081 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7082 (let ((from (plist-get plist :from))
7083 (to (plist-get plist :to)))
7084 (when (and from to org-from-is-user-regexp)
7085 (setq plist
7086 (plist-put plist :fromto
7087 (if (string-match org-from-is-user-regexp from)
7088 (concat "to %t")
7089 (concat "from %f"))))))
7090 (setq org-store-link-plist plist))
7092 (defun org-add-link-props (&rest plist)
7093 "Add these properties to the link property list."
7094 (let (key value)
7095 (while plist
7096 (setq key (pop plist) value (pop plist))
7097 (setq org-store-link-plist
7098 (plist-put org-store-link-plist key value)))))
7100 (defun org-email-link-description (&optional fmt)
7101 "Return the description part of an email link.
7102 This takes information from `org-store-link-plist' and formats it
7103 according to FMT (default from `org-email-link-description-format')."
7104 (setq fmt (or fmt org-email-link-description-format))
7105 (let* ((p org-store-link-plist)
7106 (to (plist-get p :toaddress))
7107 (from (plist-get p :fromaddress))
7108 (table
7109 (list
7110 (cons "%c" (plist-get p :fromto))
7111 (cons "%F" (plist-get p :from))
7112 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7113 (cons "%T" (plist-get p :to))
7114 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7115 (cons "%s" (plist-get p :subject))
7116 (cons "%m" (plist-get p :message-id)))))
7117 (when (string-match "%c" fmt)
7118 ;; Check if the user wrote this message
7119 (if (and org-from-is-user-regexp from to
7120 (save-match-data (string-match org-from-is-user-regexp from)))
7121 (setq fmt (replace-match "to %t" t t fmt))
7122 (setq fmt (replace-match "from %f" t t fmt))))
7123 (org-replace-escapes fmt table)))
7125 (defun org-make-org-heading-search-string (&optional string heading)
7126 "Make search string for STRING or current headline."
7127 (interactive)
7128 (let ((s (or string (org-get-heading))))
7129 (unless (and string (not heading))
7130 ;; We are using a headline, clean up garbage in there.
7131 (if (string-match org-todo-regexp s)
7132 (setq s (replace-match "" t t s)))
7133 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7134 (setq s (replace-match "" t t s)))
7135 (setq s (org-trim s))
7136 (if (string-match (concat "^\\(" org-quote-string "\\|"
7137 org-comment-string "\\)") s)
7138 (setq s (replace-match "" t t s)))
7139 (while (string-match org-ts-regexp s)
7140 (setq s (replace-match "" t t s))))
7141 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7142 (setq s (replace-match " " t t s)))
7143 (or string (setq s (concat "*" s))) ; Add * for headlines
7144 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7146 (defun org-make-link (&rest strings)
7147 "Concatenate STRINGS."
7148 (apply 'concat strings))
7150 (defun org-make-link-string (link &optional description)
7151 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7152 (unless (string-match "\\S-" link)
7153 (error "Empty link"))
7154 (when (stringp description)
7155 ;; Remove brackets from the description, they are fatal.
7156 (while (string-match "\\[" description)
7157 (setq description (replace-match "{" t t description)))
7158 (while (string-match "\\]" description)
7159 (setq description (replace-match "}" t t description))))
7160 (when (equal (org-link-escape link) description)
7161 ;; No description needed, it is identical
7162 (setq description nil))
7163 (when (and (not description)
7164 (not (equal link (org-link-escape link))))
7165 (setq description (org-extract-attributes link)))
7166 (concat "[[" (org-link-escape link) "]"
7167 (if description (concat "[" description "]") "")
7168 "]"))
7170 (defconst org-link-escape-chars
7171 '((?\ . "%20")
7172 (?\[ . "%5B")
7173 (?\] . "%5D")
7174 (?\340 . "%E0") ; `a
7175 (?\342 . "%E2") ; ^a
7176 (?\347 . "%E7") ; ,c
7177 (?\350 . "%E8") ; `e
7178 (?\351 . "%E9") ; 'e
7179 (?\352 . "%EA") ; ^e
7180 (?\356 . "%EE") ; ^i
7181 (?\364 . "%F4") ; ^o
7182 (?\371 . "%F9") ; `u
7183 (?\373 . "%FB") ; ^u
7184 (?\; . "%3B")
7185 (?? . "%3F")
7186 (?= . "%3D")
7187 (?+ . "%2B")
7189 "Association list of escapes for some characters problematic in links.
7190 This is the list that is used for internal purposes.")
7192 (defvar org-url-encoding-use-url-hexify nil)
7194 (defconst org-link-escape-chars-browser
7195 '((?\ . "%20")) ; 32 for the SPC char
7196 "Association list of escapes for some characters problematic in links.
7197 This is the list that is used before handing over to the browser.")
7199 (defun org-link-escape (text &optional table)
7200 "Escape characters in TEXT that are problematic for links."
7201 (if org-url-encoding-use-url-hexify
7202 (url-hexify-string text)
7203 (setq table (or table org-link-escape-chars))
7204 (when text
7205 (let ((re (mapconcat (lambda (x) (regexp-quote
7206 (char-to-string (car x))))
7207 table "\\|")))
7208 (while (string-match re text)
7209 (setq text
7210 (replace-match
7211 (cdr (assoc (string-to-char (match-string 0 text))
7212 table))
7213 t t text)))
7214 text))))
7216 (defun org-link-unescape (text &optional table)
7217 "Reverse the action of `org-link-escape'."
7218 (if org-url-encoding-use-url-hexify
7219 (url-unhex-string text)
7220 (setq table (or table org-link-escape-chars))
7221 (when text
7222 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7223 table "\\|")))
7224 (while (string-match re text)
7225 (setq text
7226 (replace-match
7227 (char-to-string (car (rassoc (match-string 0 text) table)))
7228 t t text)))
7229 text))))
7231 (defun org-xor (a b)
7232 "Exclusive or."
7233 (if a (not b) b))
7235 (defun org-fixup-message-id-for-http (s)
7236 "Replace special characters in a message id, so it can be used in an http query."
7237 (while (string-match "<" s)
7238 (setq s (replace-match "%3C" t t s)))
7239 (while (string-match ">" s)
7240 (setq s (replace-match "%3E" t t s)))
7241 (while (string-match "@" s)
7242 (setq s (replace-match "%40" t t s)))
7245 ;;;###autoload
7246 (defun org-insert-link-global ()
7247 "Insert a link like Org-mode does.
7248 This command can be called in any mode to insert a link in Org-mode syntax."
7249 (interactive)
7250 (org-load-modules-maybe)
7251 (org-run-like-in-org-mode 'org-insert-link))
7253 (defun org-insert-link (&optional complete-file link-location)
7254 "Insert a link. At the prompt, enter the link.
7256 Completion can be used to insert any of the link protocol prefixes like
7257 http or ftp in use.
7259 The history can be used to select a link previously stored with
7260 `org-store-link'. When the empty string is entered (i.e. if you just
7261 press RET at the prompt), the link defaults to the most recently
7262 stored link. As SPC triggers completion in the minibuffer, you need to
7263 use M-SPC or C-q SPC to force the insertion of a space character.
7265 You will also be prompted for a description, and if one is given, it will
7266 be displayed in the buffer instead of the link.
7268 If there is already a link at point, this command will allow you to edit link
7269 and description parts.
7271 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7272 be selected using completion. The path to the file will be relative to the
7273 current directory if the file is in the current directory or a subdirectory.
7274 Otherwise, the link will be the absolute path as completed in the minibuffer
7275 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7276 option `org-link-file-path-type'.
7278 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7279 the current directory or below.
7281 With three \\[universal-argument] prefixes, negate the meaning of
7282 `org-keep-stored-link-after-insertion'.
7284 If `org-make-link-description-function' is non-nil, this function will be
7285 called with the link target, and the result will be the default
7286 link description.
7288 If the LINK-LOCATION parameter is non-nil, this value will be
7289 used as the link location instead of reading one interactively."
7290 (interactive "P")
7291 (let* ((wcf (current-window-configuration))
7292 (region (if (org-region-active-p)
7293 (buffer-substring (region-beginning) (region-end))))
7294 (remove (and region (list (region-beginning) (region-end))))
7295 (desc region)
7296 tmphist ; byte-compile incorrectly complains about this
7297 (link link-location)
7298 entry file all-prefixes)
7299 (cond
7300 (link-location) ; specified by arg, just use it.
7301 ((org-in-regexp org-bracket-link-regexp 1)
7302 ;; We do have a link at point, and we are going to edit it.
7303 (setq remove (list (match-beginning 0) (match-end 0)))
7304 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7305 (setq link (read-string "Link: "
7306 (org-link-unescape
7307 (org-match-string-no-properties 1)))))
7308 ((or (org-in-regexp org-angle-link-re)
7309 (org-in-regexp org-plain-link-re))
7310 ;; Convert to bracket link
7311 (setq remove (list (match-beginning 0) (match-end 0))
7312 link (read-string "Link: "
7313 (org-remove-angle-brackets (match-string 0)))))
7314 ((member complete-file '((4) (16)))
7315 ;; Completing read for file names.
7316 (setq link (org-file-complete-link complete-file)))
7318 ;; Read link, with completion for stored links.
7319 (with-output-to-temp-buffer "*Org Links*"
7320 (princ "Insert a link.
7321 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
7322 (when org-stored-links
7323 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7324 (princ (mapconcat
7325 (lambda (x)
7326 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7327 (reverse org-stored-links) "\n"))))
7328 (let ((cw (selected-window)))
7329 (select-window (get-buffer-window "*Org Links*"))
7330 (setq truncate-lines t)
7331 (unless (pos-visible-in-window-p (point-max))
7332 (org-fit-window-to-buffer))
7333 (and (window-live-p cw) (select-window cw)))
7334 ;; Fake a link history, containing the stored links.
7335 (setq tmphist (append (mapcar 'car org-stored-links)
7336 org-insert-link-history))
7337 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
7338 (mapcar 'car org-link-abbrev-alist)
7339 org-link-types))
7340 (unwind-protect
7341 (progn
7342 (setq link
7343 (let ((org-completion-use-ido nil))
7344 (org-completing-read
7345 "Link: "
7346 (mapcar (lambda (x) (list (concat x ":")))
7347 all-prefixes)
7348 nil nil nil
7349 'tmphist
7350 (or (car (car org-stored-links))))))
7351 (if (or (member link all-prefixes)
7352 (and (equal ":" (substring link -1))
7353 (member (substring link 0 -1) all-prefixes)
7354 (setq link (substring link 0 -1))))
7355 (setq link (org-link-try-special-completion link))))
7356 (set-window-configuration wcf)
7357 (kill-buffer "*Org Links*"))
7358 (setq entry (assoc link org-stored-links))
7359 (or entry (push link org-insert-link-history))
7360 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7361 (not org-keep-stored-link-after-insertion))
7362 (setq org-stored-links (delq (assoc link org-stored-links)
7363 org-stored-links)))
7364 (setq desc (or desc (nth 1 entry)))))
7366 (if (string-match org-plain-link-re link)
7367 ;; URL-like link, normalize the use of angular brackets.
7368 (setq link (org-make-link (org-remove-angle-brackets link))))
7370 ;; Check if we are linking to the current file with a search option
7371 ;; If yes, simplify the link by using only the search option.
7372 (when (and buffer-file-name
7373 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7374 (let* ((path (match-string 1 link))
7375 (case-fold-search nil)
7376 (search (match-string 2 link)))
7377 (save-match-data
7378 (if (equal (file-truename buffer-file-name) (file-truename path))
7379 ;; We are linking to this same file, with a search option
7380 (setq link search)))))
7382 ;; Check if we can/should use a relative path. If yes, simplify the link
7383 (when (string-match "^file:\\(.*\\)" link)
7384 (let* ((path (match-string 1 link))
7385 (origpath path)
7386 (case-fold-search nil))
7387 (cond
7388 ((or (eq org-link-file-path-type 'absolute)
7389 (equal complete-file '(16)))
7390 (setq path (abbreviate-file-name (expand-file-name path))))
7391 ((eq org-link-file-path-type 'noabbrev)
7392 (setq path (expand-file-name path)))
7393 ((eq org-link-file-path-type 'relative)
7394 (setq path (file-relative-name path)))
7396 (save-match-data
7397 (if (string-match (concat "^" (regexp-quote
7398 (file-name-as-directory
7399 (expand-file-name "."))))
7400 (expand-file-name path))
7401 ;; We are linking a file with relative path name.
7402 (setq path (substring (expand-file-name path)
7403 (match-end 0)))
7404 (setq path (abbreviate-file-name (expand-file-name path)))))))
7405 (setq link (concat "file:" path))
7406 (if (equal desc origpath)
7407 (setq desc path))))
7409 (if org-make-link-description-function
7410 (setq desc (funcall org-make-link-description-function link desc)))
7412 (setq desc (read-string "Description: " desc))
7413 (unless (string-match "\\S-" desc) (setq desc nil))
7414 (if remove (apply 'delete-region remove))
7415 (insert (org-make-link-string link desc))))
7417 (defun org-link-try-special-completion (type)
7418 "If there is completion support for link type TAPE, offer it."
7419 (let ((fun (intern (concat "org-" type "-complete-link"))))
7420 (if (functionp fun)
7421 (funcall fun)
7422 (read-string "Link (no completion support): " (concat type ":")))))
7424 (defun org-file-complete-link (&optional arg)
7425 "Create a file link using completion."
7426 (let (file link)
7427 (setq file (read-file-name "File: "))
7428 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7429 (pwd1 (file-name-as-directory (abbreviate-file-name
7430 (expand-file-name ".")))))
7431 (cond
7432 ((equal arg '(16))
7433 (setq link (org-make-link
7434 "file:"
7435 (abbreviate-file-name (expand-file-name file)))))
7436 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7437 (setq link (org-make-link "file:" (match-string 1 file))))
7438 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7439 (expand-file-name file))
7440 (setq link (org-make-link
7441 "file:" (match-string 1 (expand-file-name file)))))
7442 (t (setq link (org-make-link "file:" file)))))
7443 link))
7445 (defun org-completing-read (&rest args)
7446 "Completing-read with SPACE being a normal character."
7447 (let ((minibuffer-local-completion-map
7448 (copy-keymap minibuffer-local-completion-map)))
7449 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7450 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7451 (apply 'org-ido-completing-read args)))
7453 (defun org-completing-read-no-ido (&rest args)
7454 (let (org-completion-use-ido)
7455 (apply 'org-completing-read args)))
7457 (defun org-ido-completing-read (&rest args)
7458 "Completing-read using `ido-mode' speedups if available"
7459 (if (and org-completion-use-ido
7460 (fboundp 'ido-completing-read)
7461 (boundp 'ido-mode) ido-mode
7462 (listp (second args)))
7463 (let ((ido-enter-matching-directory nil))
7464 (apply 'ido-completing-read (concat (car args))
7465 (mapcar (lambda (x) (car x)) (nth 1 args))
7466 (cddr args)))
7467 (apply 'completing-read args)))
7469 (defun org-extract-attributes (s)
7470 "Extract the attributes cookie from a string and set as text property."
7471 (let (a attr (start 0) key value)
7472 (save-match-data
7473 (when (string-match "{{\\([^}]+\\)}}$" s)
7474 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7475 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7476 (setq key (match-string 1 a) value (match-string 2 a)
7477 start (match-end 0)
7478 attr (plist-put attr (intern key) value))))
7479 (org-add-props s nil 'org-attr attr))
7482 (defun org-extract-attributes-from-string (tag)
7483 (let (key value attr)
7484 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
7485 (setq key (match-string 1 tag) value (match-string 2 tag)
7486 tag (replace-match "" t t tag)
7487 attr (plist-put attr (intern key) value)))
7488 (cons tag attr)))
7490 (defun org-attributes-to-string (plist)
7491 "Format a property list into an HTML attribute list."
7492 (let ((s "") key value)
7493 (while plist
7494 (setq key (pop plist) value (pop plist))
7495 (and value
7496 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7499 ;;; Opening/following a link
7501 (defvar org-link-search-failed nil)
7503 (defun org-next-link ()
7504 "Move forward to the next link.
7505 If the link is in hidden text, expose it."
7506 (interactive)
7507 (when (and org-link-search-failed (eq this-command last-command))
7508 (goto-char (point-min))
7509 (message "Link search wrapped back to beginning of buffer"))
7510 (setq org-link-search-failed nil)
7511 (let* ((pos (point))
7512 (ct (org-context))
7513 (a (assoc :link ct)))
7514 (if a (goto-char (nth 2 a)))
7515 (if (re-search-forward org-any-link-re nil t)
7516 (progn
7517 (goto-char (match-beginning 0))
7518 (if (org-invisible-p) (org-show-context)))
7519 (goto-char pos)
7520 (setq org-link-search-failed t)
7521 (error "No further link found"))))
7523 (defun org-previous-link ()
7524 "Move backward to the previous link.
7525 If the link is in hidden text, expose it."
7526 (interactive)
7527 (when (and org-link-search-failed (eq this-command last-command))
7528 (goto-char (point-max))
7529 (message "Link search wrapped back to end of buffer"))
7530 (setq org-link-search-failed nil)
7531 (let* ((pos (point))
7532 (ct (org-context))
7533 (a (assoc :link ct)))
7534 (if a (goto-char (nth 1 a)))
7535 (if (re-search-backward org-any-link-re nil t)
7536 (progn
7537 (goto-char (match-beginning 0))
7538 (if (org-invisible-p) (org-show-context)))
7539 (goto-char pos)
7540 (setq org-link-search-failed t)
7541 (error "No further link found"))))
7543 (defun org-translate-link (s)
7544 "Translate a link string if a translation function has been defined."
7545 (if (and org-link-translation-function
7546 (fboundp org-link-translation-function)
7547 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7548 (progn
7549 (setq s (funcall org-link-translation-function
7550 (match-string 1) (match-string 2)))
7551 (concat (car s) ":" (cdr s)))
7554 (defun org-translate-link-from-planner (type path)
7555 "Translate a link from Emacs Planner syntax so that Org can follow it.
7556 This is still an experimental function, your mileage may vary."
7557 (cond
7558 ((member type '("http" "https" "news" "ftp"))
7559 ;; standard Internet links are the same.
7560 nil)
7561 ((and (equal type "irc") (string-match "^//" path))
7562 ;; Planner has two / at the beginning of an irc link, we have 1.
7563 ;; We should have zero, actually....
7564 (setq path (substring path 1)))
7565 ((and (equal type "lisp") (string-match "^/" path))
7566 ;; Planner has a slash, we do not.
7567 (setq type "elisp" path (substring path 1)))
7568 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7569 ;; A typical message link. Planner has the id after the fina slash,
7570 ;; we separate it with a hash mark
7571 (setq path (concat (match-string 1 path) "#"
7572 (org-remove-angle-brackets (match-string 2 path)))))
7574 (cons type path))
7576 (defun org-find-file-at-mouse (ev)
7577 "Open file link or URL at mouse."
7578 (interactive "e")
7579 (mouse-set-point ev)
7580 (org-open-at-point 'in-emacs))
7582 (defun org-open-at-mouse (ev)
7583 "Open file link or URL at mouse."
7584 (interactive "e")
7585 (mouse-set-point ev)
7586 (if (eq major-mode 'org-agenda-mode)
7587 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7588 (org-open-at-point))
7590 (defvar org-window-config-before-follow-link nil
7591 "The window configuration before following a link.
7592 This is saved in case the need arises to restore it.")
7594 (defvar org-open-link-marker (make-marker)
7595 "Marker pointing to the location where `org-open-at-point; was called.")
7597 ;;;###autoload
7598 (defun org-open-at-point-global ()
7599 "Follow a link like Org-mode does.
7600 This command can be called in any mode to follow a link that has
7601 Org-mode syntax."
7602 (interactive)
7603 (org-run-like-in-org-mode 'org-open-at-point))
7605 ;;;###autoload
7606 (defun org-open-link-from-string (s &optional arg)
7607 "Open a link in the string S, as if it was in Org-mode."
7608 (interactive "sLink: \nP")
7609 (let ((reference-buffer (current-buffer)))
7610 (with-temp-buffer
7611 (let ((org-inhibit-startup t))
7612 (org-mode)
7613 (insert s)
7614 (goto-char (point-min))
7615 (org-open-at-point arg reference-buffer)))))
7617 (defun org-open-at-point (&optional in-emacs reference-buffer)
7618 "Open link at or after point.
7619 If there is no link at point, this function will search forward up to
7620 the end of the current line.
7621 Normally, files will be opened by an appropriate application. If the
7622 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7623 With a double prefix argument, try to open outside of Emacs, in the
7624 application the system uses for this file type."
7625 (interactive "P")
7626 (org-load-modules-maybe)
7627 (move-marker org-open-link-marker (point))
7628 (setq org-window-config-before-follow-link (current-window-configuration))
7629 (org-remove-occur-highlights nil nil t)
7630 (cond
7631 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7632 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7633 (org-footnote-action))
7635 (let (type path link line search (pos (point)))
7636 (catch 'match
7637 (save-excursion
7638 (skip-chars-forward "^]\n\r")
7639 (when (org-in-regexp org-bracket-link-regexp)
7640 (setq link (org-extract-attributes
7641 (org-link-unescape (org-match-string-no-properties 1))))
7642 (while (string-match " *\n *" link)
7643 (setq link (replace-match " " t t link)))
7644 (setq link (org-link-expand-abbrev link))
7645 (cond
7646 ((or (file-name-absolute-p link)
7647 (string-match "^\\.\\.?/" link))
7648 (setq type "file" path link))
7649 ((string-match org-link-re-with-space3 link)
7650 (setq type (match-string 1 link) path (match-string 2 link)))
7651 (t (setq type "thisfile" path link)))
7652 (throw 'match t)))
7654 (when (get-text-property (point) 'org-linked-text)
7655 (setq type "thisfile"
7656 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7657 (1+ (point)) (point))
7658 path (buffer-substring
7659 (previous-single-property-change pos 'org-linked-text)
7660 (next-single-property-change pos 'org-linked-text)))
7661 (throw 'match t))
7663 (save-excursion
7664 (when (or (org-in-regexp org-angle-link-re)
7665 (org-in-regexp org-plain-link-re))
7666 (setq type (match-string 1) path (match-string 2))
7667 (throw 'match t)))
7668 (save-excursion
7669 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7670 (setq type "tags"
7671 path (match-string 1))
7672 (while (string-match ":" path)
7673 (setq path (replace-match "+" t t path)))
7674 (throw 'match t)))
7675 (when (org-in-regexp "<\\([^><\n]+\\)>")
7676 (setq type "tree-match"
7677 path (match-string 1))
7678 (throw 'match t)))
7679 (unless path
7680 (error "No link found"))
7682 ;; switch back to reference buffer
7683 ;; needed when if called in a temporary buffer through
7684 ;; org-open-link-from-string
7685 (and reference-buffer (switch-to-buffer reference-buffer))
7687 ;; Remove any trailing spaces in path
7688 (if (string-match " +\\'" path)
7689 (setq path (replace-match "" t t path)))
7690 (if (and org-link-translation-function
7691 (fboundp org-link-translation-function))
7692 ;; Check if we need to translate the link
7693 (let ((tmp (funcall org-link-translation-function type path)))
7694 (setq type (car tmp) path (cdr tmp))))
7696 (cond
7698 ((assoc type org-link-protocols)
7699 (funcall (nth 1 (assoc type org-link-protocols)) path))
7701 ((equal type "mailto")
7702 (let ((cmd (car org-link-mailto-program))
7703 (args (cdr org-link-mailto-program)) args1
7704 (address path) (subject "") a)
7705 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7706 (setq address (match-string 1 path)
7707 subject (org-link-escape (match-string 2 path))))
7708 (while args
7709 (cond
7710 ((not (stringp (car args))) (push (pop args) args1))
7711 (t (setq a (pop args))
7712 (if (string-match "%a" a)
7713 (setq a (replace-match address t t a)))
7714 (if (string-match "%s" a)
7715 (setq a (replace-match subject t t a)))
7716 (push a args1))))
7717 (apply cmd (nreverse args1))))
7719 ((member type '("http" "https" "ftp" "news"))
7720 (browse-url (concat type ":" (org-link-escape
7721 path org-link-escape-chars-browser))))
7723 ((member type '("message"))
7724 (browse-url (concat type ":" path)))
7726 ((string= type "tags")
7727 (org-tags-view in-emacs path))
7728 ((string= type "thisfile")
7729 (if in-emacs
7730 (switch-to-buffer-other-window
7731 (org-get-buffer-for-internal-link (current-buffer)))
7732 (org-mark-ring-push))
7733 (let ((cmd `(org-link-search
7734 ,path
7735 ,(cond ((equal in-emacs '(4)) 'occur)
7736 ((equal in-emacs '(16)) 'org-occur)
7737 (t nil))
7738 ,pos)))
7739 (condition-case nil (eval cmd)
7740 (error (progn (widen) (eval cmd))))))
7742 ((string= type "tree-match")
7743 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7745 ((string= type "file")
7746 (if (string-match "::\\([0-9]+\\)\\'" path)
7747 (setq line (string-to-number (match-string 1 path))
7748 path (substring path 0 (match-beginning 0)))
7749 (if (string-match "::\\(.+\\)\\'" path)
7750 (setq search (match-string 1 path)
7751 path (substring path 0 (match-beginning 0)))))
7752 (if (string-match "[*?{]" (file-name-nondirectory path))
7753 (dired path)
7754 (org-open-file path in-emacs line search)))
7756 ((string= type "news")
7757 (require 'org-gnus)
7758 (org-gnus-follow-link path))
7760 ((string= type "shell")
7761 (let ((cmd path))
7762 (if (or (not org-confirm-shell-link-function)
7763 (funcall org-confirm-shell-link-function
7764 (format "Execute \"%s\" in shell? "
7765 (org-add-props cmd nil
7766 'face 'org-warning))))
7767 (progn
7768 (message "Executing %s" cmd)
7769 (shell-command cmd))
7770 (error "Abort"))))
7772 ((string= type "elisp")
7773 (let ((cmd path))
7774 (if (or (not org-confirm-elisp-link-function)
7775 (funcall org-confirm-elisp-link-function
7776 (format "Execute \"%s\" as elisp? "
7777 (org-add-props cmd nil
7778 'face 'org-warning))))
7779 (message "%s => %s" cmd
7780 (if (equal (string-to-char cmd) ?\()
7781 (eval (read cmd))
7782 (call-interactively (read cmd))))
7783 (error "Abort"))))
7786 (browse-url-at-point))))))
7787 (move-marker org-open-link-marker nil)
7788 (run-hook-with-args 'org-follow-link-hook))
7790 ;;;; Time estimates
7792 (defun org-get-effort (&optional pom)
7793 "Get the effort estimate for the current entry."
7794 (org-entry-get pom org-effort-property))
7796 ;;; File search
7798 (defvar org-create-file-search-functions nil
7799 "List of functions to construct the right search string for a file link.
7800 These functions are called in turn with point at the location to
7801 which the link should point.
7803 A function in the hook should first test if it would like to
7804 handle this file type, for example by checking the major-mode or
7805 the file extension. If it decides not to handle this file, it
7806 should just return nil to give other functions a chance. If it
7807 does handle the file, it must return the search string to be used
7808 when following the link. The search string will be part of the
7809 file link, given after a double colon, and `org-open-at-point'
7810 will automatically search for it. If special measures must be
7811 taken to make the search successful, another function should be
7812 added to the companion hook `org-execute-file-search-functions',
7813 which see.
7815 A function in this hook may also use `setq' to set the variable
7816 `description' to provide a suggestion for the descriptive text to
7817 be used for this link when it gets inserted into an Org-mode
7818 buffer with \\[org-insert-link].")
7820 (defvar org-execute-file-search-functions nil
7821 "List of functions to execute a file search triggered by a link.
7823 Functions added to this hook must accept a single argument, the
7824 search string that was part of the file link, the part after the
7825 double colon. The function must first check if it would like to
7826 handle this search, for example by checking the major-mode or the
7827 file extension. If it decides not to handle this search, it
7828 should just return nil to give other functions a chance. If it
7829 does handle the search, it must return a non-nil value to keep
7830 other functions from trying.
7832 Each function can access the current prefix argument through the
7833 variable `current-prefix-argument'. Note that a single prefix is
7834 used to force opening a link in Emacs, so it may be good to only
7835 use a numeric or double prefix to guide the search function.
7837 In case this is needed, a function in this hook can also restore
7838 the window configuration before `org-open-at-point' was called using:
7840 (set-window-configuration org-window-config-before-follow-link)")
7842 (defun org-link-search (s &optional type avoid-pos)
7843 "Search for a link search option.
7844 If S is surrounded by forward slashes, it is interpreted as a
7845 regular expression. In org-mode files, this will create an `org-occur'
7846 sparse tree. In ordinary files, `occur' will be used to list matches.
7847 If the current buffer is in `dired-mode', grep will be used to search
7848 in all files. If AVOID-POS is given, ignore matches near that position."
7849 (let ((case-fold-search t)
7850 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7851 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7852 (append '(("") (" ") ("\t") ("\n"))
7853 org-emphasis-alist)
7854 "\\|") "\\)"))
7855 (pos (point))
7856 (pre nil) (post nil)
7857 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7858 (cond
7859 ;; First check if there are any special
7860 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7861 ;; Now try the builtin stuff
7862 ((and (equal (string-to-char s0) ?#)
7863 (> (length s0) 1)
7864 (save-excursion
7865 (goto-char (point-min))
7866 (and
7867 (re-search-forward
7868 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
7869 (setq type 'dedicated
7870 pos (match-beginning 0))))
7871 ;; There is an exact target for this
7872 (goto-char pos)
7873 (org-back-to-heading t)))
7874 ((save-excursion
7875 (goto-char (point-min))
7876 (and
7877 (re-search-forward
7878 (concat "<<" (regexp-quote s0) ">>") nil t)
7879 (setq type 'dedicated
7880 pos (match-beginning 0))))
7881 ;; There is an exact target for this
7882 (goto-char pos))
7883 ((and (string-match "^(\\(.*\\))$" s0)
7884 (save-excursion
7885 (goto-char (point-min))
7886 (and
7887 (re-search-forward
7888 (concat "[^[]" (regexp-quote
7889 (format org-coderef-label-format
7890 (match-string 1 s0))))
7891 nil t)
7892 (setq type 'dedicated
7893 pos (1+ (match-beginning 0))))))
7894 ;; There is a coderef target for this
7895 (goto-char pos))
7896 ((string-match "^/\\(.*\\)/$" s)
7897 ;; A regular expression
7898 (cond
7899 ((org-mode-p)
7900 (org-occur (match-string 1 s)))
7901 ;;((eq major-mode 'dired-mode)
7902 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7903 (t (org-do-occur (match-string 1 s)))))
7905 ;; A normal search strings
7906 (when (equal (string-to-char s) ?*)
7907 ;; Anchor on headlines, post may include tags.
7908 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7909 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7910 s (substring s 1)))
7911 (remove-text-properties
7912 0 (length s)
7913 '(face nil mouse-face nil keymap nil fontified nil) s)
7914 ;; Make a series of regular expressions to find a match
7915 (setq words (org-split-string s "[ \n\r\t]+")
7917 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7918 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7919 "\\)" markers)
7920 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7921 re2a (concat "[ \t\r\n]" re2a_)
7922 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7923 re4 (concat "[^a-zA-Z_]" re4_)
7925 re1 (concat pre re2 post)
7926 re3 (concat pre (if pre re4_ re4) post)
7927 re5 (concat pre ".*" re4)
7928 re2 (concat pre re2)
7929 re2a (concat pre (if pre re2a_ re2a))
7930 re4 (concat pre (if pre re4_ re4))
7931 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7932 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7933 re5 "\\)"
7935 (cond
7936 ((eq type 'org-occur) (org-occur reall))
7937 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7938 (t (goto-char (point-min))
7939 (setq type 'fuzzy)
7940 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7941 (org-search-not-self 1 re1 nil t)
7942 (org-search-not-self 1 re2 nil t)
7943 (org-search-not-self 1 re2a nil t)
7944 (org-search-not-self 1 re3 nil t)
7945 (org-search-not-self 1 re4 nil t)
7946 (org-search-not-self 1 re5 nil t)
7948 (goto-char (match-beginning 1))
7949 (goto-char pos)
7950 (error "No match")))))
7952 ;; Normal string-search
7953 (goto-char (point-min))
7954 (if (search-forward s nil t)
7955 (goto-char (match-beginning 0))
7956 (error "No match"))))
7957 (and (org-mode-p) (org-show-context 'link-search))
7958 type))
7960 (defun org-search-not-self (group &rest args)
7961 "Execute `re-search-forward', but only accept matches that do not
7962 enclose the position of `org-open-link-marker'."
7963 (let ((m org-open-link-marker))
7964 (catch 'exit
7965 (while (apply 're-search-forward args)
7966 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7967 (goto-char (match-end group))
7968 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7969 (> (match-beginning 0) (marker-position m))
7970 (< (match-end 0) (marker-position m)))
7971 (save-match-data
7972 (or (not (org-in-regexp
7973 org-bracket-link-analytic-regexp 1))
7974 (not (match-end 4)) ; no description
7975 (and (<= (match-beginning 4) (point))
7976 (>= (match-end 4) (point))))))
7977 (throw 'exit (point))))))))
7979 (defun org-get-buffer-for-internal-link (buffer)
7980 "Return a buffer to be used for displaying the link target of internal links."
7981 (cond
7982 ((not org-display-internal-link-with-indirect-buffer)
7983 buffer)
7984 ((string-match "(Clone)$" (buffer-name buffer))
7985 (message "Buffer is already a clone, not making another one")
7986 ;; we also do not modify visibility in this case
7987 buffer)
7988 (t ; make a new indirect buffer for displaying the link
7989 (let* ((bn (buffer-name buffer))
7990 (ibn (concat bn "(Clone)"))
7991 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7992 (with-current-buffer ib (org-overview))
7993 ib))))
7995 (defun org-do-occur (regexp &optional cleanup)
7996 "Call the Emacs command `occur'.
7997 If CLEANUP is non-nil, remove the printout of the regular expression
7998 in the *Occur* buffer. This is useful if the regex is long and not useful
7999 to read."
8000 (occur regexp)
8001 (when cleanup
8002 (let ((cwin (selected-window)) win beg end)
8003 (when (setq win (get-buffer-window "*Occur*"))
8004 (select-window win))
8005 (goto-char (point-min))
8006 (when (re-search-forward "match[a-z]+" nil t)
8007 (setq beg (match-end 0))
8008 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8009 (setq end (1- (match-beginning 0)))))
8010 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8011 (goto-char (point-min))
8012 (select-window cwin))))
8014 ;;; The mark ring for links jumps
8016 (defvar org-mark-ring nil
8017 "Mark ring for positions before jumps in Org-mode.")
8018 (defvar org-mark-ring-last-goto nil
8019 "Last position in the mark ring used to go back.")
8020 ;; Fill and close the ring
8021 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8022 (loop for i from 1 to org-mark-ring-length do
8023 (push (make-marker) org-mark-ring))
8024 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8025 org-mark-ring)
8027 (defun org-mark-ring-push (&optional pos buffer)
8028 "Put the current position or POS into the mark ring and rotate it."
8029 (interactive)
8030 (setq pos (or pos (point)))
8031 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8032 (move-marker (car org-mark-ring)
8033 (or pos (point))
8034 (or buffer (current-buffer)))
8035 (message "%s"
8036 (substitute-command-keys
8037 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8039 (defun org-mark-ring-goto (&optional n)
8040 "Jump to the previous position in the mark ring.
8041 With prefix arg N, jump back that many stored positions. When
8042 called several times in succession, walk through the entire ring.
8043 Org-mode commands jumping to a different position in the current file,
8044 or to another Org-mode file, automatically push the old position
8045 onto the ring."
8046 (interactive "p")
8047 (let (p m)
8048 (if (eq last-command this-command)
8049 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8050 (setq p org-mark-ring))
8051 (setq org-mark-ring-last-goto p)
8052 (setq m (car p))
8053 (switch-to-buffer (marker-buffer m))
8054 (goto-char m)
8055 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8057 (defun org-remove-angle-brackets (s)
8058 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8059 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8061 (defun org-add-angle-brackets (s)
8062 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8063 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8065 (defun org-remove-double-quotes (s)
8066 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8067 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8070 ;;; Following specific links
8072 (defun org-follow-timestamp-link ()
8073 (cond
8074 ((org-at-date-range-p t)
8075 (let ((org-agenda-start-on-weekday)
8076 (t1 (match-string 1))
8077 (t2 (match-string 2)))
8078 (setq t1 (time-to-days (org-time-string-to-time t1))
8079 t2 (time-to-days (org-time-string-to-time t2)))
8080 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8081 ((org-at-timestamp-p t)
8082 (org-agenda-list nil (time-to-days (org-time-string-to-time
8083 (substring (match-string 1) 0 10)))
8085 (t (error "This should not happen"))))
8088 ;;; Following file links
8089 (defvar org-wait nil)
8090 (defun org-open-file (path &optional in-emacs line search)
8091 "Open the file at PATH.
8092 First, this expands any special file name abbreviations. Then the
8093 configuration variable `org-file-apps' is checked if it contains an
8094 entry for this file type, and if yes, the corresponding command is launched.
8096 If no application is found, Emacs simply visits the file.
8098 With optional prefix argument IN-EMACS, Emacs will visit the file.
8099 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8100 and o use an external application to visit the file.
8102 Optional LINE specifies a line to go to, optional SEARCH a string to
8103 search for. If LINE or SEARCH is given, the file will always be
8104 opened in Emacs.
8105 If the file does not exist, an error is thrown."
8106 (setq in-emacs (or in-emacs line search))
8107 (let* ((file (if (equal path "")
8108 buffer-file-name
8109 (substitute-in-file-name (expand-file-name path))))
8110 (apps (append org-file-apps (org-default-apps)))
8111 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8112 (dirp (if remp nil (file-directory-p file)))
8113 (file (if (and dirp org-open-directory-means-index-dot-org)
8114 (concat (file-name-as-directory file) "index.org")
8115 file))
8116 (a-m-a-p (assq 'auto-mode apps))
8117 (dfile (downcase file))
8118 (old-buffer (current-buffer))
8119 (old-pos (point))
8120 (old-mode major-mode)
8121 ext cmd)
8122 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8123 (setq ext (match-string 1 dfile))
8124 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8125 (setq ext (match-string 1 dfile))))
8126 (cond
8127 ((equal in-emacs '(16))
8128 (setq cmd (cdr (assoc 'system apps))))
8129 (in-emacs (setq cmd 'emacs))
8131 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8132 (and dirp (cdr (assoc 'directory apps)))
8133 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8134 'string-match)
8135 (cdr (assoc ext apps))
8136 (cdr (assoc t apps))))))
8137 (when (eq cmd 'system)
8138 (setq cmd (cdr (assoc 'system apps))))
8139 (when (eq cmd 'default)
8140 (setq cmd (cdr (assoc t apps))))
8141 (when (eq cmd 'mailcap)
8142 (require 'mailcap)
8143 (mailcap-parse-mailcaps)
8144 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8145 (command (mailcap-mime-info mime-type)))
8146 (if (stringp command)
8147 (setq cmd command)
8148 (setq cmd 'emacs))))
8149 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8150 (not (file-exists-p file))
8151 (not org-open-non-existing-files))
8152 (error "No such file: %s" file))
8153 (cond
8154 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8155 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8156 (while (string-match "['\"]%s['\"]" cmd)
8157 (setq cmd (replace-match "%s" t t cmd)))
8158 (while (string-match "%s" cmd)
8159 (setq cmd (replace-match
8160 (save-match-data
8161 (shell-quote-argument
8162 (convert-standard-filename file)))
8163 t t cmd)))
8164 (save-window-excursion
8165 (start-process-shell-command cmd nil cmd)
8166 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8168 ((or (stringp cmd)
8169 (eq cmd 'emacs))
8170 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8171 (widen)
8172 (if line (goto-line line)
8173 (if search (org-link-search search))))
8174 ((consp cmd)
8175 (let ((file (convert-standard-filename file)))
8176 (eval cmd)))
8177 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8178 (and (org-mode-p) (eq old-mode 'org-mode)
8179 (or (not (equal old-buffer (current-buffer)))
8180 (not (equal old-pos (point))))
8181 (org-mark-ring-push old-pos old-buffer))))
8183 (defun org-default-apps ()
8184 "Return the default applications for this operating system."
8185 (cond
8186 ((eq system-type 'darwin)
8187 org-file-apps-defaults-macosx)
8188 ((eq system-type 'windows-nt)
8189 org-file-apps-defaults-windowsnt)
8190 (t org-file-apps-defaults-gnu)))
8192 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8193 "Convert extensions to regular expressions in the cars of LIST.
8194 Also, weed out any non-string entries, because the return value is used
8195 only for regexp matching.
8196 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8197 point to the symbol `emacs', indicating that the file should
8198 be opened in Emacs."
8199 (append
8200 (delq nil
8201 (mapcar (lambda (x)
8202 (if (not (stringp (car x)))
8204 (if (string-match "\\W" (car x))
8206 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8207 list))
8208 (if add-auto-mode
8209 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8211 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8212 (defun org-file-remote-p (file)
8213 "Test whether FILE specifies a location on a remote system.
8214 Return non-nil if the location is indeed remote.
8216 For example, the filename \"/user@host:/foo\" specifies a location
8217 on the system \"/user@host:\"."
8218 (cond ((fboundp 'file-remote-p)
8219 (file-remote-p file))
8220 ((fboundp 'tramp-handle-file-remote-p)
8221 (tramp-handle-file-remote-p file))
8222 ((and (boundp 'ange-ftp-name-format)
8223 (string-match (car ange-ftp-name-format) file))
8225 (t nil)))
8228 ;;;; Refiling
8230 (defun org-get-org-file ()
8231 "Read a filename, with default directory `org-directory'."
8232 (let ((default (or org-default-notes-file remember-data-file)))
8233 (read-file-name (format "File name [%s]: " default)
8234 (file-name-as-directory org-directory)
8235 default)))
8237 (defun org-notes-order-reversed-p ()
8238 "Check if the current file should receive notes in reversed order."
8239 (cond
8240 ((not org-reverse-note-order) nil)
8241 ((eq t org-reverse-note-order) t)
8242 ((not (listp org-reverse-note-order)) nil)
8243 (t (catch 'exit
8244 (let ((all org-reverse-note-order)
8245 entry)
8246 (while (setq entry (pop all))
8247 (if (string-match (car entry) buffer-file-name)
8248 (throw 'exit (cdr entry))))
8249 nil)))))
8251 (defvar org-refile-target-table nil
8252 "The list of refile targets, created by `org-refile'.")
8254 (defvar org-agenda-new-buffers nil
8255 "Buffers created to visit agenda files.")
8257 (defun org-get-refile-targets (&optional default-buffer)
8258 "Produce a table with refile targets."
8259 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
8260 targets txt re files f desc descre fast-path-p level pos0)
8261 (message "Getting targets...")
8262 (with-current-buffer (or default-buffer (current-buffer))
8263 (while (setq entry (pop entries))
8264 (setq files (car entry) desc (cdr entry))
8265 (setq fast-path-p nil)
8266 (cond
8267 ((null files) (setq files (list (current-buffer))))
8268 ((eq files 'org-agenda-files)
8269 (setq files (org-agenda-files 'unrestricted)))
8270 ((and (symbolp files) (fboundp files))
8271 (setq files (funcall files)))
8272 ((and (symbolp files) (boundp files))
8273 (setq files (symbol-value files))))
8274 (if (stringp files) (setq files (list files)))
8275 (cond
8276 ((eq (car desc) :tag)
8277 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8278 ((eq (car desc) :todo)
8279 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8280 ((eq (car desc) :regexp)
8281 (setq descre (cdr desc)))
8282 ((eq (car desc) :level)
8283 (setq descre (concat "^\\*\\{" (number-to-string
8284 (if org-odd-levels-only
8285 (1- (* 2 (cdr desc)))
8286 (cdr desc)))
8287 "\\}[ \t]")))
8288 ((eq (car desc) :maxlevel)
8289 (setq fast-path-p t)
8290 (setq descre (concat "^\\*\\{1," (number-to-string
8291 (if org-odd-levels-only
8292 (1- (* 2 (cdr desc)))
8293 (cdr desc)))
8294 "\\}[ \t]")))
8295 (t (error "Bad refiling target description %s" desc)))
8296 (while (setq f (pop files))
8297 (save-excursion
8298 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
8299 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8300 (setq f (expand-file-name f))
8301 (if (eq org-refile-use-outline-path 'file)
8302 (push (list (file-name-nondirectory f) f nil nil) targets))
8303 (save-excursion
8304 (save-restriction
8305 (widen)
8306 (goto-char (point-min))
8307 (while (re-search-forward descre nil t)
8308 (goto-char (setq pos0 (point-at-bol)))
8309 (catch 'next
8310 (when org-refile-target-verify-function
8311 (save-match-data
8312 (or (funcall org-refile-target-verify-function)
8313 (throw 'next t))))
8314 (when (looking-at org-complex-heading-regexp)
8315 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8316 txt (org-link-display-format (match-string 4))
8317 re (concat "^" (regexp-quote
8318 (buffer-substring (match-beginning 1)
8319 (match-end 4)))))
8320 (if (match-end 5) (setq re (concat re "[ \t]+"
8321 (regexp-quote
8322 (match-string 5)))))
8323 (setq re (concat re "[ \t]*$"))
8324 (when org-refile-use-outline-path
8325 (setq txt (mapconcat 'org-protect-slash
8326 (append
8327 (if (eq org-refile-use-outline-path 'file)
8328 (list (file-name-nondirectory
8329 (buffer-file-name (buffer-base-buffer))))
8330 (if (eq org-refile-use-outline-path 'full-file-path)
8331 (list (buffer-file-name (buffer-base-buffer)))))
8332 (org-get-outline-path fast-path-p level txt)
8333 (list txt))
8334 "/")))
8335 (push (list txt f re (point)) targets)))
8336 (when (= (point) pos0)
8337 ;; verification function has not moved point
8338 (goto-char (point-at-eol))))))))))
8339 (message "Getting targets...done")
8340 (nreverse targets)))
8342 (defun org-protect-slash (s)
8343 (while (string-match "/" s)
8344 (setq s (replace-match "\\" t t s)))
8347 (defvar org-olpa (make-vector 20 nil))
8349 (defun org-get-outline-path (&optional fastp level heading)
8350 "Return the outline path to the current entry, as a list."
8351 (if fastp
8352 (progn
8353 (if (> level 19)
8354 (error "Outline path failure, more than 19 levels."))
8355 (loop for i from level upto 19 do
8356 (aset org-olpa i nil))
8357 (prog1
8358 (delq nil (append org-olpa nil))
8359 (aset org-olpa level heading)))
8360 (let (rtn)
8361 (save-excursion
8362 (while (org-up-heading-safe)
8363 (when (looking-at org-complex-heading-regexp)
8364 (push (org-match-string-no-properties 4) rtn)))
8365 rtn))))
8367 (defvar org-refile-history nil
8368 "History for refiling operations.")
8370 (defvar org-after-refile-insert-hook nil
8371 "Hook run after `org-refile' has inserted its stuff at the new location.
8372 Note that this is still *before* the stuff will be removed from
8373 the *old* location.")
8375 (defun org-refile (&optional goto default-buffer)
8376 "Move the entry at point to another heading.
8377 The list of target headings is compiled using the information in
8378 `org-refile-targets', which see. This list is created before each use
8379 and will therefore always be up-to-date.
8381 At the target location, the entry is filed as a subitem of the target heading.
8382 Depending on `org-reverse-note-order', the new subitem will either be the
8383 first or the last subitem.
8385 If there is an active region, all entries in that region will be moved.
8386 However, the region must fulfil the requirement that the first heading
8387 is the first one sets the top-level of the moved text - at most siblings
8388 below it are allowed.
8390 With prefix arg GOTO, the command will only visit the target location,
8391 not actually move anything.
8392 With a double prefix `C-u C-u', go to the location where the last refiling
8393 operation has put the subtree.
8395 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
8396 (interactive "P")
8397 (let* ((cbuf (current-buffer))
8398 (regionp (org-region-active-p))
8399 (region-start (and regionp (region-beginning)))
8400 (region-end (and regionp (region-end)))
8401 (region-length (and regionp (- region-end region-start)))
8402 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8403 pos it nbuf file re level reversed)
8404 (when regionp (goto-char region-start)
8405 (unless (org-kill-is-subtree-p
8406 (buffer-substring region-start region-end))
8407 (error "The region is not a (sequence of) subtree(s)")))
8408 (if (equal goto '(16))
8409 (org-refile-goto-last-stored)
8410 (when (setq it (org-refile-get-location
8411 (if goto "Goto: " "Refile to: ") default-buffer
8412 org-refile-allow-creating-parent-nodes))
8413 (setq file (nth 1 it)
8414 re (nth 2 it)
8415 pos (nth 3 it))
8416 (if (and (not goto)
8418 (equal (buffer-file-name) file)
8419 (if regionp
8420 (and (>= pos region-start)
8421 (<= pos region-end))
8422 (and (>= pos (point))
8423 (< pos (save-excursion
8424 (org-end-of-subtree t t))))))
8425 (error "Cannot refile to position inside the tree or region"))
8427 (setq nbuf (or (find-buffer-visiting file)
8428 (find-file-noselect file)))
8429 (if goto
8430 (progn
8431 (switch-to-buffer nbuf)
8432 (goto-char pos)
8433 (org-show-context 'org-goto))
8434 (if regionp
8435 (progn
8436 (kill-new (buffer-substring region-start region-end))
8437 (org-save-markers-in-region region-start region-end))
8438 (org-copy-subtree 1 nil t))
8439 (save-excursion
8440 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8441 (find-file-noselect file))))
8442 (setq reversed (org-notes-order-reversed-p))
8443 (save-excursion
8444 (save-restriction
8445 (widen)
8446 (if pos
8447 (progn
8448 (goto-char pos)
8449 (looking-at outline-regexp)
8450 (setq level (org-get-valid-level (funcall outline-level) 1))
8451 (goto-char
8452 (if reversed
8453 (or (outline-next-heading) (point-max))
8454 (or (save-excursion (outline-get-next-sibling))
8455 (org-end-of-subtree t t)
8456 (point-max)))))
8457 (setq level 1)
8458 (if (not reversed)
8459 (goto-char (point-max))
8460 (goto-char (point-min))
8461 (or (outline-next-heading) (goto-char (point-max)))))
8462 (if (not (bolp)) (newline))
8463 (bookmark-set "org-refile-last-stored")
8464 (org-paste-subtree level)
8465 (run-hooks 'org-after-refile-insert-hook))))
8466 (if regionp
8467 (delete-region (point) (+ (point) region-length))
8468 (org-cut-subtree))
8469 (setq org-markers-to-move nil)
8470 (message "Refiled to \"%s\"" (car it))))))
8471 (org-reveal))
8473 (defun org-refile-goto-last-stored ()
8474 "Go to the location where the last refile was stored."
8475 (interactive)
8476 (bookmark-jump "org-refile-last-stored")
8477 (message "This is the location of the last refile"))
8479 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
8480 "Prompt the user for a refile location, using PROMPT."
8481 (let ((org-refile-targets org-refile-targets)
8482 (org-refile-use-outline-path org-refile-use-outline-path))
8483 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8484 (unless org-refile-target-table
8485 (error "No refile targets"))
8486 (let* ((cbuf (current-buffer))
8487 (partial-completion-mode nil)
8488 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8489 (cfunc (if (and org-refile-use-outline-path
8490 org-outline-path-complete-in-steps)
8491 'org-olpath-completing-read
8492 'org-ido-completing-read))
8493 (extra (if org-refile-use-outline-path "/" ""))
8494 (filename (and cfn (expand-file-name cfn)))
8495 (tbl (mapcar
8496 (lambda (x)
8497 (if (and (not (member org-refile-use-outline-path
8498 '(file full-file-path)))
8499 (not (equal filename (nth 1 x))))
8500 (cons (concat (car x) extra " ("
8501 (file-name-nondirectory (nth 1 x)) ")")
8502 (cdr x))
8503 (cons (concat (car x) extra) (cdr x))))
8504 org-refile-target-table))
8505 (completion-ignore-case t)
8506 pa answ parent-target child parent)
8507 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
8508 nil 'org-refile-history))
8509 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
8510 (if pa
8512 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
8513 (setq parent (match-string 1 answ)
8514 child (match-string 2 answ))
8515 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
8516 (when (and parent-target
8517 (or (eq new-nodes t)
8518 (and (eq new-nodes 'confirm)
8519 (y-or-n-p (format "Create new node \"%s\"? " child)))))
8520 (org-refile-new-child parent-target child))))))
8522 (defun org-refile-new-child (parent-target child)
8523 "Use refile target PARENT-TARGET to add new CHILD below it."
8524 (unless parent-target
8525 (error "Cannot find parent for new node"))
8526 (let ((file (nth 1 parent-target))
8527 (pos (nth 3 parent-target))
8528 level)
8529 (with-current-buffer (or (find-buffer-visiting file)
8530 (find-file-noselect file))
8531 (save-excursion
8532 (save-restriction
8533 (widen)
8534 (if pos
8535 (goto-char pos)
8536 (goto-char (point-max))
8537 (if (not (bolp)) (newline)))
8538 (when (looking-at outline-regexp)
8539 (setq level (funcall outline-level))
8540 (org-end-of-subtree t t))
8541 (org-back-over-empty-lines)
8542 (insert "\n" (make-string
8543 (if pos (org-get-valid-level level 1) 1) ?*)
8544 " " child "\n")
8545 (beginning-of-line 0)
8546 (list (concat (car parent-target) "/" child) file "" (point)))))))
8548 (defun org-olpath-completing-read (prompt collection &rest args)
8549 "Read an outline path like a file name."
8550 (let ((thetable collection)
8551 (org-completion-use-ido nil)) ; does not work with ido.
8552 (apply
8553 'org-ido-completing-read prompt
8554 (lambda (string predicate &optional flag)
8555 (let (rtn r f (l (length string)))
8556 (cond
8557 ((eq flag nil)
8558 ;; try completion
8559 (try-completion string thetable))
8560 ((eq flag t)
8561 ;; all-completions
8562 (setq rtn (all-completions string thetable predicate))
8563 (mapcar
8564 (lambda (x)
8565 (setq r (substring x l))
8566 (if (string-match " ([^)]*)$" x)
8567 (setq f (match-string 0 x))
8568 (setq f ""))
8569 (if (string-match "/" r)
8570 (concat string (substring r 0 (match-end 0)) f)
8572 rtn))
8573 ((eq flag 'lambda)
8574 ;; exact match?
8575 (assoc string thetable)))
8577 args)))
8579 ;;;; Dynamic blocks
8581 (defun org-find-dblock (name)
8582 "Find the first dynamic block with name NAME in the buffer.
8583 If not found, stay at current position and return nil."
8584 (let (pos)
8585 (save-excursion
8586 (goto-char (point-min))
8587 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8588 nil t)
8589 (match-beginning 0))))
8590 (if pos (goto-char pos))
8591 pos))
8593 (defconst org-dblock-start-re
8594 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8595 "Matches the startline of a dynamic block, with parameters.")
8597 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8598 "Matches the end of a dynamic block.")
8600 (defun org-create-dblock (plist)
8601 "Create a dynamic block section, with parameters taken from PLIST.
8602 PLIST must contain a :name entry which is used as name of the block."
8603 (unless (bolp) (newline))
8604 (let ((name (plist-get plist :name)))
8605 (insert "#+BEGIN: " name)
8606 (while plist
8607 (if (eq (car plist) :name)
8608 (setq plist (cddr plist))
8609 (insert " " (prin1-to-string (pop plist)))))
8610 (insert "\n\n#+END:\n")
8611 (beginning-of-line -2)))
8613 (defun org-prepare-dblock ()
8614 "Prepare dynamic block for refresh.
8615 This empties the block, puts the cursor at the insert position and returns
8616 the property list including an extra property :name with the block name."
8617 (unless (looking-at org-dblock-start-re)
8618 (error "Not at a dynamic block"))
8619 (let* ((begdel (1+ (match-end 0)))
8620 (name (org-no-properties (match-string 1)))
8621 (params (append (list :name name)
8622 (read (concat "(" (match-string 3) ")")))))
8623 (unless (re-search-forward org-dblock-end-re nil t)
8624 (error "Dynamic block not terminated"))
8625 (setq params
8626 (append params
8627 (list :content (buffer-substring
8628 begdel (match-beginning 0)))))
8629 (delete-region begdel (match-beginning 0))
8630 (goto-char begdel)
8631 (open-line 1)
8632 params))
8634 (defun org-map-dblocks (&optional command)
8635 "Apply COMMAND to all dynamic blocks in the current buffer.
8636 If COMMAND is not given, use `org-update-dblock'."
8637 (let ((cmd (or command 'org-update-dblock))
8638 pos)
8639 (save-excursion
8640 (goto-char (point-min))
8641 (while (re-search-forward org-dblock-start-re nil t)
8642 (goto-char (setq pos (match-beginning 0)))
8643 (condition-case nil
8644 (funcall cmd)
8645 (error (message "Error during update of dynamic block")))
8646 (goto-char pos)
8647 (unless (re-search-forward org-dblock-end-re nil t)
8648 (error "Dynamic block not terminated"))))))
8650 (defun org-dblock-update (&optional arg)
8651 "User command for updating dynamic blocks.
8652 Update the dynamic block at point. With prefix ARG, update all dynamic
8653 blocks in the buffer."
8654 (interactive "P")
8655 (if arg
8656 (org-update-all-dblocks)
8657 (or (looking-at org-dblock-start-re)
8658 (org-beginning-of-dblock))
8659 (org-update-dblock)))
8661 (defun org-update-dblock ()
8662 "Update the dynamic block at point
8663 This means to empty the block, parse for parameters and then call
8664 the correct writing function."
8665 (save-window-excursion
8666 (let* ((pos (point))
8667 (line (org-current-line))
8668 (params (org-prepare-dblock))
8669 (name (plist-get params :name))
8670 (cmd (intern (concat "org-dblock-write:" name))))
8671 (message "Updating dynamic block `%s' at line %d..." name line)
8672 (funcall cmd params)
8673 (message "Updating dynamic block `%s' at line %d...done" name line)
8674 (goto-char pos))))
8676 (defun org-beginning-of-dblock ()
8677 "Find the beginning of the dynamic block at point.
8678 Error if there is no such block at point."
8679 (let ((pos (point))
8680 beg)
8681 (end-of-line 1)
8682 (if (and (re-search-backward org-dblock-start-re nil t)
8683 (setq beg (match-beginning 0))
8684 (re-search-forward org-dblock-end-re nil t)
8685 (> (match-end 0) pos))
8686 (goto-char beg)
8687 (goto-char pos)
8688 (error "Not in a dynamic block"))))
8690 (defun org-update-all-dblocks ()
8691 "Update all dynamic blocks in the buffer.
8692 This function can be used in a hook."
8693 (when (org-mode-p)
8694 (org-map-dblocks 'org-update-dblock)))
8697 ;;;; Completion
8699 (defconst org-additional-option-like-keywords
8700 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8701 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8702 "LATEX_HEADER:"
8703 "BEGIN_EXAMPLE" "END_EXAMPLE"
8704 "BEGIN_QUOTE" "END_QUOTE"
8705 "BEGIN_VERSE" "END_VERSE"
8706 "BEGIN_CENTER" "END_CENTER"
8707 "BEGIN_SRC" "END_SRC"
8708 "CATEGORY" "COLUMNS"
8709 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
8711 (defcustom org-structure-template-alist
8713 ("s" "#+begin_src ?\n\n#+end_src"
8714 "<src lang=\"?\">\n\n</src>")
8715 ("e" "#+begin_example\n?\n#+end_example"
8716 "<example>\n?\n</example>")
8717 ("q" "#+begin_quote\n?\n#+end_quote"
8718 "<quote>\n?\n</quote>")
8719 ("v" "#+begin_verse\n?\n#+end_verse"
8720 "<verse>\n?\n/verse>")
8721 ("c" "#+begin_center\n?\n#+end_center"
8722 "<center>\n?\n/center>")
8723 ("l" "#+begin_latex\n?\n#+end_latex"
8724 "<literal style=\"latex\">\n?\n</literal>")
8725 ("L" "#+latex: "
8726 "<literal style=\"latex\">?</literal>")
8727 ("h" "#+begin_html\n?\n#+end_html"
8728 "<literal style=\"html\">\n?\n</literal>")
8729 ("H" "#+html: "
8730 "<literal style=\"html\">?</literal>")
8731 ("a" "#+begin_ascii\n?\n#+end_ascii")
8732 ("A" "#+ascii: ")
8733 ("i" "#+include %file ?"
8734 "<include file=%file markup=\"?\">")
8736 "Structure completion elements.
8737 This is a list of abbreviation keys and values. The value gets inserted
8738 it you type @samp{.} followed by the key and then the completion key,
8739 usually `M-TAB'. %file will be replaced by a file name after prompting
8740 for the file using completion.
8741 There are two templates for each key, the first uses the original Org syntax,
8742 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8743 the default when the /org-mtags.el/ module has been loaded. See also the
8744 variable `org-mtags-prefer-muse-templates'.
8745 This is an experimental feature, it is undecided if it is going to stay in."
8746 :group 'org-completion
8747 :type '(repeat
8748 (string :tag "Key")
8749 (string :tag "Template")
8750 (string :tag "Muse Template")))
8752 (defun org-try-structure-completion ()
8753 "Try to complete a structure template before point.
8754 This looks for strings like \"<e\" on an otherwise empty line and
8755 expands them."
8756 (let ((l (buffer-substring (point-at-bol) (point)))
8758 (when (and (looking-at "[ \t]*$")
8759 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8760 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8761 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8762 (match-beginning 1)) a)
8763 t)))
8765 (defun org-complete-expand-structure-template (start cell)
8766 "Expand a structure template."
8767 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8768 (rpl (nth (if musep 2 1) cell))
8769 (ind ""))
8770 (delete-region start (point))
8771 (when (string-match "\\`#\\+" rpl)
8772 (cond
8773 ((bolp))
8774 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8775 (setq ind (buffer-substring (point-at-bol) (point))))
8776 (t (newline))))
8777 (setq start (point))
8778 (if (string-match "%file" rpl)
8779 (setq rpl (replace-match
8780 (concat
8781 "\""
8782 (save-match-data
8783 (abbreviate-file-name (read-file-name "Include file: ")))
8784 "\"")
8785 t t rpl)))
8786 (setq rpl (mapconcat 'identity (split-string rpl "\n")
8787 (concat "\n" ind)))
8788 (insert rpl)
8789 (if (re-search-backward "\\?" start t) (delete-char 1))))
8792 (defun org-complete (&optional arg)
8793 "Perform completion on word at point.
8794 At the beginning of a headline, this completes TODO keywords as given in
8795 `org-todo-keywords'.
8796 If the current word is preceded by a backslash, completes the TeX symbols
8797 that are supported for HTML support.
8798 If the current word is preceded by \"#+\", completes special words for
8799 setting file options.
8800 In the line after \"#+STARTUP:, complete valid keywords.\"
8801 At all other locations, this simply calls the value of
8802 `org-completion-fallback-command'."
8803 (interactive "P")
8804 (org-without-partial-completion
8805 (catch 'exit
8806 (let* ((a nil)
8807 (end (point))
8808 (beg1 (save-excursion
8809 (skip-chars-backward (org-re "[:alnum:]_@"))
8810 (point)))
8811 (beg (save-excursion
8812 (skip-chars-backward "a-zA-Z0-9_:$")
8813 (point)))
8814 (confirm (lambda (x) (stringp (car x))))
8815 (searchhead (equal (char-before beg) ?*))
8816 (struct
8817 (when (and (member (char-before beg1) '(?. ?<))
8818 (setq a (assoc (buffer-substring beg1 (point))
8819 org-structure-template-alist)))
8820 (org-complete-expand-structure-template (1- beg1) a)
8821 (throw 'exit t)))
8822 (tag (and (equal (char-before beg1) ?:)
8823 (equal (char-after (point-at-bol)) ?*)))
8824 (prop (and (equal (char-before beg1) ?:)
8825 (not (equal (char-after (point-at-bol)) ?*))))
8826 (texp (equal (char-before beg) ?\\))
8827 (link (equal (char-before beg) ?\[))
8828 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8829 beg)
8830 "#+"))
8831 (startup (string-match "^#\\+STARTUP:.*"
8832 (buffer-substring (point-at-bol) (point))))
8833 (completion-ignore-case opt)
8834 (type nil)
8835 (tbl nil)
8836 (table (cond
8837 (opt
8838 (setq type :opt)
8839 (require 'org-exp)
8840 (append
8841 (mapcar
8842 (lambda (x)
8843 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8844 (cons (match-string 2 x) (match-string 1 x)))
8845 (org-split-string (org-get-current-options) "\n"))
8846 (mapcar 'list org-additional-option-like-keywords)))
8847 (startup
8848 (setq type :startup)
8849 org-startup-options)
8850 (link (append org-link-abbrev-alist-local
8851 org-link-abbrev-alist))
8852 (texp
8853 (setq type :tex)
8854 org-html-entities)
8855 ((string-match "\\`\\*+[ \t]+\\'"
8856 (buffer-substring (point-at-bol) beg))
8857 (setq type :todo)
8858 (mapcar 'list org-todo-keywords-1))
8859 (searchhead
8860 (setq type :searchhead)
8861 (save-excursion
8862 (goto-char (point-min))
8863 (while (re-search-forward org-todo-line-regexp nil t)
8864 (push (list
8865 (org-make-org-heading-search-string
8866 (match-string 3) t))
8867 tbl)))
8868 tbl)
8869 (tag (setq type :tag beg beg1)
8870 (or org-tag-alist (org-get-buffer-tags)))
8871 (prop (setq type :prop beg beg1)
8872 (mapcar 'list (org-buffer-property-keys nil t t)))
8873 (t (progn
8874 (call-interactively org-completion-fallback-command)
8875 (throw 'exit nil)))))
8876 (pattern (buffer-substring-no-properties beg end))
8877 (completion (try-completion pattern table confirm)))
8878 (cond ((eq completion t)
8879 (if (not (assoc (upcase pattern) table))
8880 (message "Already complete")
8881 (if (and (equal type :opt)
8882 (not (member (car (assoc (upcase pattern) table))
8883 org-additional-option-like-keywords)))
8884 (insert (substring (cdr (assoc (upcase pattern) table))
8885 (length pattern)))
8886 (if (memq type '(:tag :prop)) (insert ":")))))
8887 ((null completion)
8888 (message "Can't find completion for \"%s\"" pattern)
8889 (ding))
8890 ((not (string= pattern completion))
8891 (delete-region beg end)
8892 (if (string-match " +$" completion)
8893 (setq completion (replace-match "" t t completion)))
8894 (insert completion)
8895 (if (get-buffer-window "*Completions*")
8896 (delete-window (get-buffer-window "*Completions*")))
8897 (if (assoc completion table)
8898 (if (eq type :todo) (insert " ")
8899 (if (memq type '(:tag :prop)) (insert ":"))))
8900 (if (and (equal type :opt) (assoc completion table))
8901 (message "%s" (substitute-command-keys
8902 "Press \\[org-complete] again to insert example settings"))))
8904 (message "Making completion list...")
8905 (let ((list (sort (all-completions pattern table confirm)
8906 'string<)))
8907 (with-output-to-temp-buffer "*Completions*"
8908 (condition-case nil
8909 ;; Protection needed for XEmacs and emacs 21
8910 (display-completion-list list pattern)
8911 (error (display-completion-list list)))))
8912 (message "Making completion list...%s" "done")))))))
8914 ;;;; TODO, DEADLINE, Comments
8916 (defun org-toggle-comment ()
8917 "Change the COMMENT state of an entry."
8918 (interactive)
8919 (save-excursion
8920 (org-back-to-heading)
8921 (let (case-fold-search)
8922 (if (looking-at (concat outline-regexp
8923 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8924 (replace-match "" t t nil 1)
8925 (if (looking-at outline-regexp)
8926 (progn
8927 (goto-char (match-end 0))
8928 (insert org-comment-string " ")))))))
8930 (defvar org-last-todo-state-is-todo nil
8931 "This is non-nil when the last TODO state change led to a TODO state.
8932 If the last change removed the TODO tag or switched to DONE, then
8933 this is nil.")
8935 (defvar org-setting-tags nil) ; dynamically skipped
8937 (defun org-parse-local-options (string var)
8938 "Parse STRING for startup setting relevant for variable VAR."
8939 (let ((rtn (symbol-value var))
8940 e opts)
8941 (save-match-data
8942 (if (or (not string) (not (string-match "\\S-" string)))
8944 (setq opts (delq nil (mapcar (lambda (x)
8945 (setq e (assoc x org-startup-options))
8946 (if (eq (nth 1 e) var) e nil))
8947 (org-split-string string "[ \t]+"))))
8948 (if (not opts)
8950 (setq rtn nil)
8951 (while (setq e (pop opts))
8952 (if (not (nth 3 e))
8953 (setq rtn (nth 2 e))
8954 (if (not (listp rtn)) (setq rtn nil))
8955 (push (nth 2 e) rtn)))
8956 rtn)))))
8958 (defvar org-todo-setup-filter-hook nil
8959 "Hook for functions that pre-filter todo specs.
8961 Each function takes a todo spec and returns either `nil' or the spec
8962 transformed into canonical form." )
8964 (defvar org-todo-get-default-hook nil
8965 "Hook for functions that get a default item for todo.
8967 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
8968 `nil' or a string to be used for the todo mark." )
8970 (defvar org-agenda-headline-snapshot-before-repeat)
8972 (defun org-todo (&optional arg)
8973 "Change the TODO state of an item.
8974 The state of an item is given by a keyword at the start of the heading,
8975 like
8976 *** TODO Write paper
8977 *** DONE Call mom
8979 The different keywords are specified in the variable `org-todo-keywords'.
8980 By default the available states are \"TODO\" and \"DONE\".
8981 So for this example: when the item starts with TODO, it is changed to DONE.
8982 When it starts with DONE, the DONE is removed. And when neither TODO nor
8983 DONE are present, add TODO at the beginning of the heading.
8985 With C-u prefix arg, use completion to determine the new state.
8986 With numeric prefix arg, switch to that state.
8987 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
8988 With a tripple C-u prefix, circumvent any state blocking.
8990 For calling through lisp, arg is also interpreted in the following way:
8991 'none -> empty state
8992 \"\"(empty string) -> switch to empty state
8993 'done -> switch to DONE
8994 'nextset -> switch to the next set of keywords
8995 'previousset -> switch to the previous set of keywords
8996 \"WAITING\" -> switch to the specified keyword, but only if it
8997 really is a member of `org-todo-keywords'."
8998 (interactive "P")
8999 (if (equal arg '(16)) (setq arg 'nextset))
9000 (let ((org-blocker-hook org-blocker-hook)
9001 (case-fold-search nil))
9002 (when (equal arg '(64))
9003 (setq arg nil org-blocker-hook nil))
9004 (when (and org-blocker-hook
9005 (org-entry-get nil "NOBLOCKING"))
9006 (setq org-blocker-hook nil))
9007 (save-excursion
9008 (catch 'exit
9009 (org-back-to-heading)
9010 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9011 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9012 (looking-at " *"))
9013 (let* ((match-data (match-data))
9014 (startpos (point-at-bol))
9015 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9016 (org-log-done org-log-done)
9017 (org-log-repeat org-log-repeat)
9018 (org-todo-log-states org-todo-log-states)
9019 (this (match-string 1))
9020 (hl-pos (match-beginning 0))
9021 (head (org-get-todo-sequence-head this))
9022 (ass (assoc head org-todo-kwd-alist))
9023 (interpret (nth 1 ass))
9024 (done-word (nth 3 ass))
9025 (final-done-word (nth 4 ass))
9026 (last-state (or this ""))
9027 (completion-ignore-case t)
9028 (member (member this org-todo-keywords-1))
9029 (tail (cdr member))
9030 (state (cond
9031 ((and org-todo-key-trigger
9032 (or (and (equal arg '(4))
9033 (eq org-use-fast-todo-selection 'prefix))
9034 (and (not arg) org-use-fast-todo-selection
9035 (not (eq org-use-fast-todo-selection
9036 'prefix)))))
9037 ;; Use fast selection
9038 (org-fast-todo-selection))
9039 ((and (equal arg '(4))
9040 (or (not org-use-fast-todo-selection)
9041 (not org-todo-key-trigger)))
9042 ;; Read a state with completion
9043 (org-ido-completing-read
9044 "State: " (mapcar (lambda(x) (list x))
9045 org-todo-keywords-1)
9046 nil t))
9047 ((eq arg 'right)
9048 (if this
9049 (if tail (car tail) nil)
9050 (car org-todo-keywords-1)))
9051 ((eq arg 'left)
9052 (if (equal member org-todo-keywords-1)
9054 (if this
9055 (nth (- (length org-todo-keywords-1)
9056 (length tail) 2)
9057 org-todo-keywords-1)
9058 (org-last org-todo-keywords-1))))
9059 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9060 (setq arg nil))) ; hack to fall back to cycling
9061 (arg
9062 ;; user or caller requests a specific state
9063 (cond
9064 ((equal arg "") nil)
9065 ((eq arg 'none) nil)
9066 ((eq arg 'done) (or done-word (car org-done-keywords)))
9067 ((eq arg 'nextset)
9068 (or (car (cdr (member head org-todo-heads)))
9069 (car org-todo-heads)))
9070 ((eq arg 'previousset)
9071 (let ((org-todo-heads (reverse org-todo-heads)))
9072 (or (car (cdr (member head org-todo-heads)))
9073 (car org-todo-heads))))
9074 ((car (member arg org-todo-keywords-1)))
9075 ((nth (1- (prefix-numeric-value arg))
9076 org-todo-keywords-1))))
9077 ((null member) (or head (car org-todo-keywords-1)))
9078 ((equal this final-done-word) nil) ;; -> make empty
9079 ((null tail) nil) ;; -> first entry
9080 ((memq interpret '(type priority))
9081 (if (eq this-command last-command)
9082 (car tail)
9083 (if (> (length tail) 0)
9084 (or done-word (car org-done-keywords))
9085 nil)))
9087 (car tail))))
9088 (state (or
9089 (run-hook-with-args-until-success
9090 'org-todo-get-default-hook state last-state)
9091 state))
9092 (next (if state (concat " " state " ") " "))
9093 (change-plist (list :type 'todo-state-change :from this :to state
9094 :position startpos))
9095 dolog now-done-p)
9096 (when org-blocker-hook
9097 (setq org-last-todo-state-is-todo
9098 (not (member this org-done-keywords)))
9099 (unless (save-excursion
9100 (save-match-data
9101 (run-hook-with-args-until-failure
9102 'org-blocker-hook change-plist)))
9103 (if (interactive-p)
9104 (error "TODO state change from %s to %s blocked" this state)
9105 ;; fail silently
9106 (message "TODO state change from %s to %s blocked" this state)
9107 (throw 'exit nil))))
9108 (store-match-data match-data)
9109 (replace-match next t t)
9110 (unless (pos-visible-in-window-p hl-pos)
9111 (message "TODO state changed to %s" (org-trim next)))
9112 (unless head
9113 (setq head (org-get-todo-sequence-head state)
9114 ass (assoc head org-todo-kwd-alist)
9115 interpret (nth 1 ass)
9116 done-word (nth 3 ass)
9117 final-done-word (nth 4 ass)))
9118 (when (memq arg '(nextset previousset))
9119 (message "Keyword-Set %d/%d: %s"
9120 (- (length org-todo-sets) -1
9121 (length (memq (assoc state org-todo-sets) org-todo-sets)))
9122 (length org-todo-sets)
9123 (mapconcat 'identity (assoc state org-todo-sets) " ")))
9124 (setq org-last-todo-state-is-todo
9125 (not (member state org-done-keywords)))
9126 (setq now-done-p (and (member state org-done-keywords)
9127 (not (member this org-done-keywords))))
9128 (and logging (org-local-logging logging))
9129 (when (and (or org-todo-log-states org-log-done)
9130 (not org-inhibit-logging)
9131 (not (memq arg '(nextset previousset))))
9132 ;; we need to look at recording a time and note
9133 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
9134 (nth 2 (assoc this org-todo-log-states))))
9135 (when (and state
9136 (member state org-not-done-keywords)
9137 (not (member this org-not-done-keywords)))
9138 ;; This is now a todo state and was not one before
9139 ;; If there was a CLOSED time stamp, get rid of it.
9140 (org-add-planning-info nil nil 'closed))
9141 (when (and now-done-p org-log-done)
9142 ;; It is now done, and it was not done before
9143 (org-add-planning-info 'closed (org-current-time))
9144 (if (and (not dolog) (eq 'note org-log-done))
9145 (org-add-log-setup 'done state this 'findpos 'note)))
9146 (when (and state dolog)
9147 ;; This is a non-nil state, and we need to log it
9148 (org-add-log-setup 'state state this 'findpos dolog)))
9149 ;; Fixup tag positioning
9150 (org-todo-trigger-tag-changes state)
9151 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
9152 (when org-provide-todo-statistics
9153 (org-update-parent-todo-statistics))
9154 (run-hooks 'org-after-todo-state-change-hook)
9155 (if (and arg (not (member state org-done-keywords)))
9156 (setq head (org-get-todo-sequence-head state)))
9157 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9158 ;; Do we need to trigger a repeat?
9159 (when now-done-p
9160 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
9161 ;; This is for the agenda, take a snapshot of the headline.
9162 (save-match-data
9163 (setq org-agenda-headline-snapshot-before-repeat
9164 (org-get-heading))))
9165 (org-auto-repeat-maybe state))
9166 ;; Fixup cursor location if close to the keyword
9167 (if (and (outline-on-heading-p)
9168 (not (bolp))
9169 (save-excursion (beginning-of-line 1)
9170 (looking-at org-todo-line-regexp))
9171 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9172 (progn
9173 (goto-char (or (match-end 2) (match-end 1)))
9174 (and (looking-at " ") (just-one-space))))
9175 (when org-trigger-hook
9176 (save-excursion
9177 (run-hook-with-args 'org-trigger-hook change-plist))))))))
9179 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
9180 "Block turning an entry into a TODO, using the hierarchy.
9181 This checks whether the current task should be blocked from state
9182 changes. Such blocking occurs when:
9184 1. The task has children which are not all in a completed state.
9186 2. A task has a parent with the property :ORDERED:, and there
9187 are siblings prior to the current task with incomplete
9188 status.
9190 3. The parent of the task is blocked because it has siblings that should
9191 be done first, or is child of a block grandparent TODO entry."
9193 (catch 'dont-block
9194 ;; If this is not a todo state change, or if this entry is already DONE,
9195 ;; do not block
9196 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9197 (member (plist-get change-plist :from)
9198 (cons 'done org-done-keywords))
9199 (member (plist-get change-plist :to)
9200 (cons 'todo org-not-done-keywords)))
9201 (throw 'dont-block t))
9202 ;; If this task has children, and any are undone, it's blocked
9203 (save-excursion
9204 (org-back-to-heading t)
9205 (let ((this-level (funcall outline-level)))
9206 (outline-next-heading)
9207 (let ((child-level (funcall outline-level)))
9208 (while (and (not (eobp))
9209 (> child-level this-level))
9210 ;; this todo has children, check whether they are all
9211 ;; completed
9212 (if (and (not (org-entry-is-done-p))
9213 (org-entry-is-todo-p))
9214 (throw 'dont-block nil))
9215 (outline-next-heading)
9216 (setq child-level (funcall outline-level))))))
9217 ;; Otherwise, if the task's parent has the :ORDERED: property, and
9218 ;; any previous siblings are undone, it's blocked
9219 (save-excursion
9220 (org-back-to-heading t)
9221 (let* ((pos (point))
9222 (parent-pos (and (org-up-heading-safe) (point))))
9223 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9224 (when (and (org-entry-get (point) "ORDERED")
9225 (forward-line 1)
9226 (re-search-forward org-not-done-heading-regexp pos t))
9227 (throw 'dont-block nil)) ; block, there is an older sibling not done.
9228 ;; Search further up the hierarchy, to see if an anchestor is blocked
9229 (while t
9230 (goto-char parent-pos)
9231 (if (not (looking-at org-not-done-heading-regexp))
9232 (throw 'dont-block t)) ; do not block, parent is not a TODO
9233 (setq pos (point))
9234 (setq parent-pos (and (org-up-heading-safe) (point)))
9235 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9236 (when (and (org-entry-get (point) "ORDERED")
9237 (forward-line 1)
9238 (re-search-forward org-not-done-heading-regexp pos t))
9239 (throw 'dont-block nil))))))) ; block, older sibling not done.
9241 (defcustom org-track-ordered-property-with-tag nil
9242 "Should the ORDERED property also be shown as a tag?
9243 The ORDERED property decides if an entry should require subtasks to be
9244 completed in sequence. Since a property is not very visible, setting
9245 this option means that toggling the ORDERED property with the command
9246 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
9247 not relevant for the behavior, but it makes things more visible.
9249 Note that toggling the tag with tags commands will not change the property
9250 and therefore not influence behavior!
9252 This can be t, meaning the tag ORDERED should be used, It can also be a
9253 string to select a different tag for this task."
9254 :group 'org-todo
9255 :type '(choice
9256 (const :tag "No tracking" nil)
9257 (const :tag "Track with ORDERED tag" t)
9258 (string :tag "Use other tag")))
9260 (defun org-toggle-ordered-property ()
9261 "Toggle the ORDERED property of the current entry.
9262 For better visibility, you can track the value of this property with a tag.
9263 See variable `org-track-ordered-property-with-tag'."
9264 (interactive)
9265 (let* ((t1 org-track-ordered-property-with-tag)
9266 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
9267 (save-excursion
9268 (org-back-to-heading)
9269 (if (org-entry-get nil "ORDERED")
9270 (progn
9271 (org-delete-property "ORDERED")
9272 (and tag (org-toggle-tag tag 'off))
9273 (message "Subtasks can be completed in arbitrary order"))
9274 (org-entry-put nil "ORDERED" "t")
9275 (and tag (org-toggle-tag tag 'on))
9276 (message "Subtasks must be completed in sequence")))))
9278 (defvar org-blocked-by-checkboxes) ; dynamically scoped
9279 (defun org-block-todo-from-checkboxes (change-plist)
9280 "Block turning an entry into a TODO, using checkboxes.
9281 This checks whether the current task should be blocked from state
9282 changes because there are uncheckd boxes in this entry."
9283 (catch 'dont-block
9284 ;; If this is not a todo state change, or if this entry is already DONE,
9285 ;; do not block
9286 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9287 (member (plist-get change-plist :from)
9288 (cons 'done org-done-keywords))
9289 (member (plist-get change-plist :to)
9290 (cons 'todo org-not-done-keywords)))
9291 (throw 'dont-block t))
9292 ;; If this task has checkboxes that are not checked, it's blocked
9293 (save-excursion
9294 (org-back-to-heading t)
9295 (let ((beg (point)) end)
9296 (outline-next-heading)
9297 (setq end (point))
9298 (goto-char beg)
9299 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
9300 end t)
9301 (progn
9302 (if (boundp 'org-blocked-by-checkboxes)
9303 (setq org-blocked-by-checkboxes t))
9304 (throw 'dont-block nil)))))
9305 t)) ; do not block
9307 (defvar org-entry-property-inherited-from) ;; defined below
9308 (defun org-update-parent-todo-statistics ()
9309 "Update any statistics cookie in the parent of the current headline.
9310 When `org-hierarchical-todo-statistics' is nil, statistics will cover
9311 the entire subtree and this will travel up the hierarchy and update
9312 statistics everywhere."
9313 (interactive)
9314 (let* ((lim 0) prop
9315 (recursive (or (not org-hierarchical-todo-statistics)
9316 (string-match
9317 "\\<recursive\\>"
9318 (or (setq prop (org-entry-get
9319 nil "COOKIE_DATA" 'inherit)) ""))))
9320 (lim (or (and prop (marker-position
9321 org-entry-property-inherited-from))
9322 lim))
9323 (first t)
9324 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
9325 level ltoggle l1
9326 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
9327 (catch 'exit
9328 (save-excursion
9329 (beginning-of-line 1)
9330 (if (org-at-heading-p)
9331 (setq ltoggle (funcall outline-level))
9332 (error "This should not happen"))
9333 (while (and (setq level (org-up-heading-safe))
9334 (or recursive first)
9335 (>= (point) lim))
9336 (setq first nil)
9337 (unless (and level
9338 (not (string-match
9339 "\\<checkbox\\>"
9340 (downcase
9341 (or (org-entry-get
9342 nil "COOKIE_DATA")
9343 "")))))
9344 (throw 'exit nil))
9345 (while (re-search-forward box-re (point-at-eol) t)
9346 (setq cnt-all 0 cnt-done 0 cookie-present t)
9347 (setq is-percent (match-end 2))
9348 (save-match-data
9349 (unless (outline-next-heading) (throw 'exit nil))
9350 (while (and (looking-at org-complex-heading-regexp)
9351 (> (setq l1 (length (match-string 1))) level))
9352 (setq kwd (and (or recursive (= l1 ltoggle))
9353 (match-string 2)))
9354 (and kwd (setq cnt-all (1+ cnt-all)))
9355 (and (member kwd org-done-keywords)
9356 (setq cnt-done (1+ cnt-done)))
9357 (outline-next-heading)))
9358 (replace-match
9359 (if is-percent
9360 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
9361 (format "[%d/%d]" cnt-done cnt-all)))))
9362 (when cookie-present
9363 (run-hook-with-args 'org-after-todo-statistics-hook
9364 cnt-done (- cnt-all cnt-done)))))
9365 (run-hooks 'org-todo-statistics-hook)))
9367 (defvar org-after-todo-statistics-hook nil
9368 "Hook that is called after a TODO statistics cookie has been updated.
9369 Each function is called with two arguments: the number of not-done entries
9370 and the number of done entries.
9372 For example, the following function, when added to this hook, will switch
9373 an entry to DONE when all children are done, and back to TODO when new
9374 entries are set to a TODO status. Note that this hook is only called
9375 when there is a statistics cookie in the headline!
9377 (defun org-summary-todo (n-done n-not-done)
9378 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
9379 (let (org-log-done org-log-states) ; turn off logging
9380 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
9383 (defvar org-todo-statistics-hook nil
9384 "Hook that is run whenever Org thinks TODO statistics should be updated.
9385 This hook runs even if there is no statisics cookie present, in which case
9386 `org-after-todo-statistics-hook' would not run.")
9388 (defun org-todo-trigger-tag-changes (state)
9389 "Apply the changes defined in `org-todo-state-tags-triggers'."
9390 (let ((l org-todo-state-tags-triggers)
9391 changes)
9392 (when (or (not state) (equal state ""))
9393 (setq changes (append changes (cdr (assoc "" l)))))
9394 (when (and (stringp state) (> (length state) 0))
9395 (setq changes (append changes (cdr (assoc state l)))))
9396 (when (member state org-not-done-keywords)
9397 (setq changes (append changes (cdr (assoc 'todo l)))))
9398 (when (member state org-done-keywords)
9399 (setq changes (append changes (cdr (assoc 'done l)))))
9400 (dolist (c changes)
9401 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
9403 (defun org-local-logging (value)
9404 "Get logging settings from a property VALUE."
9405 (let* (words w a)
9406 ;; directly set the variables, they are already local.
9407 (setq org-log-done nil
9408 org-log-repeat nil
9409 org-todo-log-states nil)
9410 (setq words (org-split-string value))
9411 (while (setq w (pop words))
9412 (cond
9413 ((setq a (assoc w org-startup-options))
9414 (and (member (nth 1 a) '(org-log-done org-log-repeat))
9415 (set (nth 1 a) (nth 2 a))))
9416 ((setq a (org-extract-log-state-settings w))
9417 (and (member (car a) org-todo-keywords-1)
9418 (push a org-todo-log-states)))))))
9420 (defun org-get-todo-sequence-head (kwd)
9421 "Return the head of the TODO sequence to which KWD belongs.
9422 If KWD is not set, check if there is a text property remembering the
9423 right sequence."
9424 (let (p)
9425 (cond
9426 ((not kwd)
9427 (or (get-text-property (point-at-bol) 'org-todo-head)
9428 (progn
9429 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
9430 nil (point-at-eol)))
9431 (get-text-property p 'org-todo-head))))
9432 ((not (member kwd org-todo-keywords-1))
9433 (car org-todo-keywords-1))
9434 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
9436 (defun org-fast-todo-selection ()
9437 "Fast TODO keyword selection with single keys.
9438 Returns the new TODO keyword, or nil if no state change should occur."
9439 (let* ((fulltable org-todo-key-alist)
9440 (done-keywords org-done-keywords) ;; needed for the faces.
9441 (maxlen (apply 'max (mapcar
9442 (lambda (x)
9443 (if (stringp (car x)) (string-width (car x)) 0))
9444 fulltable)))
9445 (expert nil)
9446 (fwidth (+ maxlen 3 1 3))
9447 (ncol (/ (- (window-width) 4) fwidth))
9448 tg cnt e c tbl
9449 groups ingroup)
9450 (save-excursion
9451 (save-window-excursion
9452 (if expert
9453 (set-buffer (get-buffer-create " *Org todo*"))
9454 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
9455 (erase-buffer)
9456 (org-set-local 'org-done-keywords done-keywords)
9457 (setq tbl fulltable cnt 0)
9458 (while (setq e (pop tbl))
9459 (cond
9460 ((equal e '(:startgroup))
9461 (push '() groups) (setq ingroup t)
9462 (when (not (= cnt 0))
9463 (setq cnt 0)
9464 (insert "\n"))
9465 (insert "{ "))
9466 ((equal e '(:endgroup))
9467 (setq ingroup nil cnt 0)
9468 (insert "}\n"))
9469 ((equal e '(:newline))
9470 (when (not (= cnt 0))
9471 (setq cnt 0)
9472 (insert "\n")
9473 (setq e (car tbl))
9474 (while (equal (car tbl) '(:newline))
9475 (insert "\n")
9476 (setq tbl (cdr tbl)))))
9478 (setq tg (car e) c (cdr e))
9479 (if ingroup (push tg (car groups)))
9480 (setq tg (org-add-props tg nil 'face
9481 (org-get-todo-face tg)))
9482 (if (and (= cnt 0) (not ingroup)) (insert " "))
9483 (insert "[" c "] " tg (make-string
9484 (- fwidth 4 (length tg)) ?\ ))
9485 (when (= (setq cnt (1+ cnt)) ncol)
9486 (insert "\n")
9487 (if ingroup (insert " "))
9488 (setq cnt 0)))))
9489 (insert "\n")
9490 (goto-char (point-min))
9491 (if (not expert) (org-fit-window-to-buffer))
9492 (message "[a-z..]:Set [SPC]:clear")
9493 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9494 (cond
9495 ((or (= c ?\C-g)
9496 (and (= c ?q) (not (rassoc c fulltable))))
9497 (setq quit-flag t))
9498 ((= c ?\ ) nil)
9499 ((setq e (rassoc c fulltable) tg (car e))
9501 (t (setq quit-flag t)))))))
9503 (defun org-entry-is-todo-p ()
9504 (member (org-get-todo-state) org-not-done-keywords))
9506 (defun org-entry-is-done-p ()
9507 (member (org-get-todo-state) org-done-keywords))
9509 (defun org-get-todo-state ()
9510 (save-excursion
9511 (org-back-to-heading t)
9512 (and (looking-at org-todo-line-regexp)
9513 (match-end 2)
9514 (match-string 2))))
9516 (defun org-at-date-range-p (&optional inactive-ok)
9517 "Is the cursor inside a date range?"
9518 (interactive)
9519 (save-excursion
9520 (catch 'exit
9521 (let ((pos (point)))
9522 (skip-chars-backward "^[<\r\n")
9523 (skip-chars-backward "<[")
9524 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9525 (>= (match-end 0) pos)
9526 (throw 'exit t))
9527 (skip-chars-backward "^<[\r\n")
9528 (skip-chars-backward "<[")
9529 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9530 (>= (match-end 0) pos)
9531 (throw 'exit t)))
9532 nil)))
9534 (defun org-get-repeat ()
9535 "Check if there is a deadline/schedule with repeater in this entry."
9536 (save-match-data
9537 (save-excursion
9538 (org-back-to-heading t)
9539 (if (re-search-forward
9540 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9541 (match-string 1)))))
9543 (defvar org-last-changed-timestamp)
9544 (defvar org-last-inserted-timestamp)
9545 (defvar org-log-post-message)
9546 (defvar org-log-note-purpose)
9547 (defvar org-log-note-how)
9548 (defvar org-log-note-extra)
9549 (defun org-auto-repeat-maybe (done-word)
9550 "Check if the current headline contains a repeated deadline/schedule.
9551 If yes, set TODO state back to what it was and change the base date
9552 of repeating deadline/scheduled time stamps to new date.
9553 This function is run automatically after each state change to a DONE state."
9554 ;; last-state is dynamically scoped into this function
9555 (let* ((repeat (org-get-repeat))
9556 (aa (assoc last-state org-todo-kwd-alist))
9557 (interpret (nth 1 aa))
9558 (head (nth 2 aa))
9559 (whata '(("d" . day) ("m" . month) ("y" . year)))
9560 (msg "Entry repeats: ")
9561 (org-log-done nil)
9562 (org-todo-log-states nil)
9563 (nshiftmax 10) (nshift 0)
9564 re type n what ts time)
9565 (when repeat
9566 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9567 (org-todo (if (eq interpret 'type) last-state head))
9568 (org-entry-put nil "LAST_REPEAT" (format-time-string
9569 (org-time-stamp-format t t)))
9570 (when org-log-repeat
9571 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9572 (memq 'org-add-log-note post-command-hook))
9573 ;; OK, we are already setup for some record
9574 (if (eq org-log-repeat 'note)
9575 ;; make sure we take a note, not only a time stamp
9576 (setq org-log-note-how 'note))
9577 ;; Set up for taking a record
9578 (org-add-log-setup 'state (or done-word (car org-done-keywords))
9579 last-state
9580 'findpos org-log-repeat)))
9581 (org-back-to-heading t)
9582 (org-add-planning-info nil nil 'closed)
9583 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9584 org-deadline-time-regexp "\\)\\|\\("
9585 org-ts-regexp "\\)"))
9586 (while (re-search-forward
9587 re (save-excursion (outline-next-heading) (point)) t)
9588 (setq type (if (match-end 1) org-scheduled-string
9589 (if (match-end 3) org-deadline-string "Plain:"))
9590 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
9591 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
9592 (setq n (string-to-number (match-string 2 ts))
9593 what (match-string 3 ts))
9594 (if (equal what "w") (setq n (* n 7) what "d"))
9595 ;; Preparation, see if we need to modify the start date for the change
9596 (when (match-end 1)
9597 (setq time (save-match-data (org-time-string-to-time ts)))
9598 (cond
9599 ((equal (match-string 1 ts) ".")
9600 ;; Shift starting date to today
9601 (org-timestamp-change
9602 (- (time-to-days (current-time)) (time-to-days time))
9603 'day))
9604 ((equal (match-string 1 ts) "+")
9605 (while (or (= nshift 0)
9606 (<= (time-to-days time) (time-to-days (current-time))))
9607 (when (= (incf nshift) nshiftmax)
9608 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
9609 (error "Abort")))
9610 (org-timestamp-change n (cdr (assoc what whata)))
9611 (org-at-timestamp-p t)
9612 (setq ts (match-string 1))
9613 (setq time (save-match-data (org-time-string-to-time ts))))
9614 (org-timestamp-change (- n) (cdr (assoc what whata)))
9615 ;; rematch, so that we have everything in place for the real shift
9616 (org-at-timestamp-p t)
9617 (setq ts (match-string 1))
9618 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
9619 (org-timestamp-change n (cdr (assoc what whata)))
9620 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
9621 (setq org-log-post-message msg)
9622 (message "%s" msg))))
9624 (defun org-show-todo-tree (arg)
9625 "Make a compact tree which shows all headlines marked with TODO.
9626 The tree will show the lines where the regexp matches, and all higher
9627 headlines above the match.
9628 With a \\[universal-argument] prefix, prompt for a regexp to match.
9629 With a numeric prefix N, construct a sparse tree for the Nth element
9630 of `org-todo-keywords-1'."
9631 (interactive "P")
9632 (let ((case-fold-search nil)
9633 (kwd-re
9634 (cond ((null arg) org-not-done-regexp)
9635 ((equal arg '(4))
9636 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
9637 (mapcar 'list org-todo-keywords-1))))
9638 (concat "\\("
9639 (mapconcat 'identity (org-split-string kwd "|") "\\|")
9640 "\\)\\>")))
9641 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
9642 (regexp-quote (nth (1- (prefix-numeric-value arg))
9643 org-todo-keywords-1)))
9644 (t (error "Invalid prefix argument: %s" arg)))))
9645 (message "%d TODO entries found"
9646 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
9648 (defun org-deadline (&optional remove time)
9649 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
9650 With argument REMOVE, remove any deadline from the item.
9651 When TIME is set, it should be an internal time specification, and the
9652 scheduling will use the corresponding date."
9653 (interactive "P")
9654 (if remove
9655 (progn
9656 (org-remove-timestamp-with-keyword org-deadline-string)
9657 (message "Item no longer has a deadline."))
9658 (if (org-get-repeat)
9659 (error "Cannot change deadline on task with repeater, please do that by hand")
9660 (org-add-planning-info 'deadline time 'closed)
9661 (message "Deadline on %s" org-last-inserted-timestamp))))
9663 (defun org-schedule (&optional remove time)
9664 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
9665 With argument REMOVE, remove any scheduling date from the item.
9666 When TIME is set, it should be an internal time specification, and the
9667 scheduling will use the corresponding date."
9668 (interactive "P")
9669 (if remove
9670 (progn
9671 (org-remove-timestamp-with-keyword org-scheduled-string)
9672 (message "Item is no longer scheduled."))
9673 (if (org-get-repeat)
9674 (error "Cannot reschedule task with repeater, please do that by hand")
9675 (org-add-planning-info 'scheduled time 'closed)
9676 (message "Scheduled to %s" org-last-inserted-timestamp))))
9678 (defun org-get-scheduled-time (pom &optional inherit)
9679 "Get the scheduled time as a time tuple, of a format suitable
9680 for calling org-schedule with, or if there is no scheduling,
9681 returns nil."
9682 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
9683 (when time
9684 (apply 'encode-time (org-parse-time-string time)))))
9686 (defun org-get-deadline-time (pom &optional inherit)
9687 "Get the deadine as a time tuple, of a format suitable for
9688 calling org-deadlin with, or if there is no scheduling, returns
9689 nil."
9690 (let ((time (org-entry-get pom "DEADLINE" inherit)))
9691 (when time
9692 (apply 'encode-time (org-parse-time-string time)))))
9694 (defun org-remove-timestamp-with-keyword (keyword)
9695 "Remove all time stamps with KEYWORD in the current entry."
9696 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
9697 beg)
9698 (save-excursion
9699 (org-back-to-heading t)
9700 (setq beg (point))
9701 (org-end-of-subtree t t)
9702 (while (re-search-backward re beg t)
9703 (replace-match "")
9704 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9705 (equal (char-before) ?\ ))
9706 (backward-delete-char 1)
9707 (if (string-match "^[ \t]*$" (buffer-substring
9708 (point-at-bol) (point-at-eol)))
9709 (delete-region (point-at-bol)
9710 (min (point-max) (1+ (point-at-eol))))))))))
9712 (defun org-add-planning-info (what &optional time &rest remove)
9713 "Insert new timestamp with keyword in the line directly after the headline.
9714 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9715 If non is given, the user is prompted for a date.
9716 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9717 be removed."
9718 (interactive)
9719 (let (org-time-was-given org-end-time-was-given ts
9720 end default-time default-input)
9722 (catch 'exit
9723 (when (and (not time) (memq what '(scheduled deadline)))
9724 ;; Try to get a default date/time from existing timestamp
9725 (save-excursion
9726 (org-back-to-heading t)
9727 (setq end (save-excursion (outline-next-heading) (point)))
9728 (when (re-search-forward (if (eq what 'scheduled)
9729 org-scheduled-time-regexp
9730 org-deadline-time-regexp)
9731 end t)
9732 (setq ts (match-string 1)
9733 default-time
9734 (apply 'encode-time (org-parse-time-string ts))
9735 default-input (and ts (org-get-compact-tod ts))))))
9736 (when what
9737 ;; If necessary, get the time from the user
9738 (setq time (or time (org-read-date nil 'to-time nil nil
9739 default-time default-input))))
9741 (when (and org-insert-labeled-timestamps-at-point
9742 (member what '(scheduled deadline)))
9743 (insert
9744 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9745 (org-insert-time-stamp time org-time-was-given
9746 nil nil nil (list org-end-time-was-given))
9747 (setq what nil))
9748 (save-excursion
9749 (save-restriction
9750 (let (col list elt ts buffer-invisibility-spec)
9751 (org-back-to-heading t)
9752 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9753 (goto-char (match-end 1))
9754 (setq col (current-column))
9755 (goto-char (match-end 0))
9756 (if (eobp) (insert "\n") (forward-char 1))
9757 (when (and (not what)
9758 (not (looking-at
9759 (concat "[ \t]*"
9760 org-keyword-time-not-clock-regexp))))
9761 ;; Nothing to add, nothing to remove...... :-)
9762 (throw 'exit nil))
9763 (if (and (not (looking-at outline-regexp))
9764 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9765 "[^\r\n]*"))
9766 (not (equal (match-string 1) org-clock-string)))
9767 (narrow-to-region (match-beginning 0) (match-end 0))
9768 (insert-before-markers "\n")
9769 (backward-char 1)
9770 (narrow-to-region (point) (point))
9771 (and org-adapt-indentation (org-indent-to-column col)))
9772 ;; Check if we have to remove something.
9773 (setq list (cons what remove))
9774 (while list
9775 (setq elt (pop list))
9776 (goto-char (point-min))
9777 (when (or (and (eq elt 'scheduled)
9778 (re-search-forward org-scheduled-time-regexp nil t))
9779 (and (eq elt 'deadline)
9780 (re-search-forward org-deadline-time-regexp nil t))
9781 (and (eq elt 'closed)
9782 (re-search-forward org-closed-time-regexp nil t)))
9783 (replace-match "")
9784 (if (looking-at "--+<[^>]+>") (replace-match ""))
9785 (if (looking-at " +") (replace-match ""))))
9786 (goto-char (point-max))
9787 (when what
9788 (insert
9789 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9790 (cond ((eq what 'scheduled) org-scheduled-string)
9791 ((eq what 'deadline) org-deadline-string)
9792 ((eq what 'closed) org-closed-string))
9793 " ")
9794 (setq ts (org-insert-time-stamp
9795 time
9796 (or org-time-was-given
9797 (and (eq what 'closed) org-log-done-with-time))
9798 (eq what 'closed)
9799 nil nil (list org-end-time-was-given)))
9800 (end-of-line 1))
9801 (goto-char (point-min))
9802 (widen)
9803 (if (and (looking-at "[ \t]+\n")
9804 (equal (char-before) ?\n))
9805 (delete-region (1- (point)) (point-at-eol)))
9806 ts))))))
9808 (defvar org-log-note-marker (make-marker))
9809 (defvar org-log-note-purpose nil)
9810 (defvar org-log-note-state nil)
9811 (defvar org-log-note-previous-state nil)
9812 (defvar org-log-note-how nil)
9813 (defvar org-log-note-extra nil)
9814 (defvar org-log-note-window-configuration nil)
9815 (defvar org-log-note-return-to (make-marker))
9816 (defvar org-log-post-message nil
9817 "Message to be displayed after a log note has been stored.
9818 The auto-repeater uses this.")
9820 (defun org-add-note ()
9821 "Add a note to the current entry.
9822 This is done in the same way as adding a state change note."
9823 (interactive)
9824 (org-add-log-setup 'note nil nil 'findpos nil))
9826 (defvar org-property-end-re)
9827 (defun org-add-log-setup (&optional purpose state prev-state
9828 findpos how &optional extra)
9829 "Set up the post command hook to take a note.
9830 If this is about to TODO state change, the new state is expected in STATE.
9831 When FINDPOS is non-nil, find the correct position for the note in
9832 the current entry. If not, assume that it can be inserted at point.
9833 HOW is an indicator what kind of note should be created.
9834 EXTRA is additional text that will be inserted into the notes buffer."
9835 (let* ((org-log-into-drawer (org-log-into-drawer))
9836 (drawer (cond ((stringp org-log-into-drawer)
9837 org-log-into-drawer)
9838 (org-log-into-drawer "LOGBOOK")
9839 (t nil))))
9840 (save-restriction
9841 (save-excursion
9842 (when findpos
9843 (org-back-to-heading t)
9844 (narrow-to-region (point) (save-excursion
9845 (outline-next-heading) (point)))
9846 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9847 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9848 "[^\r\n]*\\)?"))
9849 (goto-char (match-end 0))
9850 (cond
9851 (drawer
9852 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
9853 nil t)
9854 (progn
9855 (goto-char (match-end 0))
9856 (or org-log-states-order-reversed
9857 (and (re-search-forward org-property-end-re nil t)
9858 (goto-char (1- (match-beginning 0))))))
9859 (insert "\n:" drawer ":\n:END:")
9860 (beginning-of-line 0)
9861 (org-indent-line-function)
9862 (beginning-of-line 2)
9863 (org-indent-line-function)
9864 (end-of-line 0)))
9865 ((and org-log-state-notes-insert-after-drawers
9866 (save-excursion
9867 (forward-line) (looking-at org-drawer-regexp)))
9868 (forward-line)
9869 (while (looking-at org-drawer-regexp)
9870 (goto-char (match-end 0))
9871 (re-search-forward org-property-end-re (point-max) t)
9872 (forward-line))
9873 (forward-line -1)))
9874 (unless org-log-states-order-reversed
9875 (and (= (char-after) ?\n) (forward-char 1))
9876 (org-skip-over-state-notes)
9877 (skip-chars-backward " \t\n\r")))
9878 (move-marker org-log-note-marker (point))
9879 (setq org-log-note-purpose purpose
9880 org-log-note-state state
9881 org-log-note-previous-state prev-state
9882 org-log-note-how how
9883 org-log-note-extra extra)
9884 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
9886 (defun org-skip-over-state-notes ()
9887 "Skip past the list of State notes in an entry."
9888 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9889 (while (looking-at "[ \t]*- State")
9890 (condition-case nil
9891 (org-next-item)
9892 (error (org-end-of-item)))))
9894 (defun org-add-log-note (&optional purpose)
9895 "Pop up a window for taking a note, and add this note later at point."
9896 (remove-hook 'post-command-hook 'org-add-log-note)
9897 (setq org-log-note-window-configuration (current-window-configuration))
9898 (delete-other-windows)
9899 (move-marker org-log-note-return-to (point))
9900 (switch-to-buffer (marker-buffer org-log-note-marker))
9901 (goto-char org-log-note-marker)
9902 (org-switch-to-buffer-other-window "*Org Note*")
9903 (erase-buffer)
9904 (if (memq org-log-note-how '(time state))
9905 (let (current-prefix-arg) (org-store-log-note))
9906 (let ((org-inhibit-startup t)) (org-mode))
9907 (insert (format "# Insert note for %s.
9908 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9909 (cond
9910 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9911 ((eq org-log-note-purpose 'done) "closed todo item")
9912 ((eq org-log-note-purpose 'state)
9913 (format "state change from \"%s\" to \"%s\""
9914 (or org-log-note-previous-state "")
9915 (or org-log-note-state "")))
9916 ((eq org-log-note-purpose 'note)
9917 "this entry")
9918 (t (error "This should not happen")))))
9919 (if org-log-note-extra (insert org-log-note-extra))
9920 (org-set-local 'org-finish-function 'org-store-log-note)))
9922 (defvar org-note-abort nil) ; dynamically scoped
9923 (defun org-store-log-note ()
9924 "Finish taking a log note, and insert it to where it belongs."
9925 (let ((txt (buffer-string))
9926 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9927 lines ind)
9928 (kill-buffer (current-buffer))
9929 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9930 (setq txt (replace-match "" t t txt)))
9931 (if (string-match "\\s-+\\'" txt)
9932 (setq txt (replace-match "" t t txt)))
9933 (setq lines (org-split-string txt "\n"))
9934 (when (and note (string-match "\\S-" note))
9935 (setq note
9936 (org-replace-escapes
9937 note
9938 (list (cons "%u" (user-login-name))
9939 (cons "%U" user-full-name)
9940 (cons "%t" (format-time-string
9941 (org-time-stamp-format 'long 'inactive)
9942 (current-time)))
9943 (cons "%s" (if org-log-note-state
9944 (concat "\"" org-log-note-state "\"")
9945 ""))
9946 (cons "%S" (if org-log-note-previous-state
9947 (concat "\"" org-log-note-previous-state "\"")
9948 "\"\"")))))
9949 (if lines (setq note (concat note " \\\\")))
9950 (push note lines))
9951 (when (or current-prefix-arg org-note-abort)
9952 (when org-log-into-drawer
9953 (org-remove-empty-drawer-at
9954 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
9955 org-log-note-marker))
9956 (setq lines nil))
9957 (when lines
9958 (save-excursion
9959 (set-buffer (marker-buffer org-log-note-marker))
9960 (save-excursion
9961 (goto-char org-log-note-marker)
9962 (move-marker org-log-note-marker nil)
9963 (end-of-line 1)
9964 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9965 (insert "- " (pop lines))
9966 (org-indent-line-function)
9967 (beginning-of-line 1)
9968 (looking-at "[ \t]*")
9969 (setq ind (concat (match-string 0) " "))
9970 (end-of-line 1)
9971 (while lines (insert "\n" ind (pop lines)))
9972 (message "Note stored")
9973 (org-back-to-heading t)
9974 (org-cycle-hide-drawers 'children)))))
9975 (set-window-configuration org-log-note-window-configuration)
9976 (with-current-buffer (marker-buffer org-log-note-return-to)
9977 (goto-char org-log-note-return-to))
9978 (move-marker org-log-note-return-to nil)
9979 (and org-log-post-message (message "%s" org-log-post-message)))
9981 (defun org-remove-empty-drawer-at (drawer pos)
9982 "Remove an emptyr DARWER drawer at position POS.
9983 POS may also be a marker."
9984 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
9985 (save-excursion
9986 (save-restriction
9987 (widen)
9988 (goto-char pos)
9989 (if (org-in-regexp
9990 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
9991 (replace-match ""))))))
9993 (defun org-sparse-tree (&optional arg)
9994 "Create a sparse tree, prompt for the details.
9995 This command can create sparse trees. You first need to select the type
9996 of match used to create the tree:
9998 t Show entries with a specific TODO keyword.
9999 m Show entries selected by a tags/property match.
10000 p Enter a property name and its value (both with completion on existing
10001 names/values) and show entries with that property.
10002 r Show entries matching a regular expression.
10003 d Show deadlines due within `org-deadline-warning-days'.
10004 b Show deadlines and scheduled items before a date.
10005 a Show deadlines and scheduled items after a date."
10006 (interactive "P")
10007 (let (ans kwd value)
10008 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
10009 (setq ans (read-char-exclusive))
10010 (cond
10011 ((equal ans ?d)
10012 (call-interactively 'org-check-deadlines))
10013 ((equal ans ?b)
10014 (call-interactively 'org-check-before-date))
10015 ((equal ans ?a)
10016 (call-interactively 'org-check-after-date))
10017 ((equal ans ?t)
10018 (org-show-todo-tree '(4)))
10019 ((member ans '(?T ?m))
10020 (call-interactively 'org-match-sparse-tree))
10021 ((member ans '(?p ?P))
10022 (setq kwd (org-ido-completing-read "Property: "
10023 (mapcar 'list (org-buffer-property-keys))))
10024 (setq value (org-ido-completing-read "Value: "
10025 (mapcar 'list (org-property-values kwd))))
10026 (unless (string-match "\\`{.*}\\'" value)
10027 (setq value (concat "\"" value "\"")))
10028 (org-match-sparse-tree arg (concat kwd "=" value)))
10029 ((member ans '(?r ?R ?/))
10030 (call-interactively 'org-occur))
10031 (t (error "No such sparse tree command \"%c\"" ans)))))
10033 (defvar org-occur-highlights nil
10034 "List of overlays used for occur matches.")
10035 (make-variable-buffer-local 'org-occur-highlights)
10036 (defvar org-occur-parameters nil
10037 "Parameters of the active org-occur calls.
10038 This is a list, each call to org-occur pushes as cons cell,
10039 containing the regular expression and the callback, onto the list.
10040 The list can contain several entries if `org-occur' has been called
10041 several time with the KEEP-PREVIOUS argument. Otherwise, this list
10042 will only contain one set of parameters. When the highlights are
10043 removed (for example with `C-c C-c', or with the next edit (depending
10044 on `org-remove-highlights-with-change'), this variable is emptied
10045 as well.")
10046 (make-variable-buffer-local 'org-occur-parameters)
10048 (defun org-occur (regexp &optional keep-previous callback)
10049 "Make a compact tree which shows all matches of REGEXP.
10050 The tree will show the lines where the regexp matches, and all higher
10051 headlines above the match. It will also show the heading after the match,
10052 to make sure editing the matching entry is easy.
10053 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
10054 call to `org-occur' will be kept, to allow stacking of calls to this
10055 command.
10056 If CALLBACK is non-nil, it is a function which is called to confirm
10057 that the match should indeed be shown."
10058 (interactive "sRegexp: \nP")
10059 (unless keep-previous
10060 (org-remove-occur-highlights nil nil t))
10061 (push (cons regexp callback) org-occur-parameters)
10062 (let ((cnt 0))
10063 (save-excursion
10064 (goto-char (point-min))
10065 (if (or (not keep-previous) ; do not want to keep
10066 (not org-occur-highlights)) ; no previous matches
10067 ;; hide everything
10068 (org-overview))
10069 (while (re-search-forward regexp nil t)
10070 (when (or (not callback)
10071 (save-match-data (funcall callback)))
10072 (setq cnt (1+ cnt))
10073 (when org-highlight-sparse-tree-matches
10074 (org-highlight-new-match (match-beginning 0) (match-end 0)))
10075 (org-show-context 'occur-tree))))
10076 (when org-remove-highlights-with-change
10077 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10078 nil 'local))
10079 (unless org-sparse-tree-open-archived-trees
10080 (org-hide-archived-subtrees (point-min) (point-max)))
10081 (run-hooks 'org-occur-hook)
10082 (if (interactive-p)
10083 (message "%d match(es) for regexp %s" cnt regexp))
10084 cnt))
10086 (defun org-show-context (&optional key)
10087 "Make sure point and context and visible.
10088 How much context is shown depends upon the variables
10089 `org-show-hierarchy-above', `org-show-following-heading'. and
10090 `org-show-siblings'."
10091 (let ((heading-p (org-on-heading-p t))
10092 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
10093 (following-p (org-get-alist-option org-show-following-heading key))
10094 (entry-p (org-get-alist-option org-show-entry-below key))
10095 (siblings-p (org-get-alist-option org-show-siblings key)))
10096 (catch 'exit
10097 ;; Show heading or entry text
10098 (if (and heading-p (not entry-p))
10099 (org-flag-heading nil) ; only show the heading
10100 (and (or entry-p (org-invisible-p) (org-invisible-p2))
10101 (org-show-hidden-entry))) ; show entire entry
10102 (when following-p
10103 ;; Show next sibling, or heading below text
10104 (save-excursion
10105 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10106 (org-flag-heading nil))))
10107 (when siblings-p (org-show-siblings))
10108 (when hierarchy-p
10109 ;; show all higher headings, possibly with siblings
10110 (save-excursion
10111 (while (and (condition-case nil
10112 (progn (org-up-heading-all 1) t)
10113 (error nil))
10114 (not (bobp)))
10115 (org-flag-heading nil)
10116 (when siblings-p (org-show-siblings))))))))
10118 (defun org-reveal (&optional siblings)
10119 "Show current entry, hierarchy above it, and the following headline.
10120 This can be used to show a consistent set of context around locations
10121 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10122 not t for the search context.
10124 With optional argument SIBLINGS, on each level of the hierarchy all
10125 siblings are shown. This repairs the tree structure to what it would
10126 look like when opened with hierarchical calls to `org-cycle'."
10127 (interactive "P")
10128 (let ((org-show-hierarchy-above t)
10129 (org-show-following-heading t)
10130 (org-show-siblings (if siblings t org-show-siblings)))
10131 (org-show-context nil)))
10133 (defun org-highlight-new-match (beg end)
10134 "Highlight from BEG to END and mark the highlight is an occur headline."
10135 (let ((ov (org-make-overlay beg end)))
10136 (org-overlay-put ov 'face 'secondary-selection)
10137 (push ov org-occur-highlights)))
10139 (defun org-remove-occur-highlights (&optional beg end noremove)
10140 "Remove the occur highlights from the buffer.
10141 BEG and END are ignored. If NOREMOVE is nil, remove this function
10142 from the `before-change-functions' in the current buffer."
10143 (interactive)
10144 (unless org-inhibit-highlight-removal
10145 (mapc 'org-delete-overlay org-occur-highlights)
10146 (setq org-occur-highlights nil)
10147 (setq org-occur-parameters nil)
10148 (unless noremove
10149 (remove-hook 'before-change-functions
10150 'org-remove-occur-highlights 'local))))
10152 ;;;; Priorities
10154 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
10155 "Regular expression matching the priority indicator.")
10157 (defvar org-remove-priority-next-time nil)
10159 (defun org-priority-up ()
10160 "Increase the priority of the current item."
10161 (interactive)
10162 (org-priority 'up))
10164 (defun org-priority-down ()
10165 "Decrease the priority of the current item."
10166 (interactive)
10167 (org-priority 'down))
10169 (defun org-priority (&optional action)
10170 "Change the priority of an item by ARG.
10171 ACTION can be `set', `up', `down', or a character."
10172 (interactive)
10173 (unless org-enable-priority-commands
10174 (error "Priority commands are disabled"))
10175 (setq action (or action 'set))
10176 (let (current new news have remove)
10177 (save-excursion
10178 (org-back-to-heading t)
10179 (if (looking-at org-priority-regexp)
10180 (setq current (string-to-char (match-string 2))
10181 have t)
10182 (setq current org-default-priority))
10183 (cond
10184 ((or (eq action 'set)
10185 (if (featurep 'xemacs) (characterp action) (integerp action)))
10186 (if (not (eq action 'set))
10187 (setq new action)
10188 (message "Priority %c-%c, SPC to remove: "
10189 org-highest-priority org-lowest-priority)
10190 (setq new (read-char-exclusive)))
10191 (if (and (= (upcase org-highest-priority) org-highest-priority)
10192 (= (upcase org-lowest-priority) org-lowest-priority))
10193 (setq new (upcase new)))
10194 (cond ((equal new ?\ ) (setq remove t))
10195 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
10196 (error "Priority must be between `%c' and `%c'"
10197 org-highest-priority org-lowest-priority))))
10198 ((eq action 'up)
10199 (if (and (not have) (eq last-command this-command))
10200 (setq new org-lowest-priority)
10201 (setq new (if (and org-priority-start-cycle-with-default (not have))
10202 org-default-priority (1- current)))))
10203 ((eq action 'down)
10204 (if (and (not have) (eq last-command this-command))
10205 (setq new org-highest-priority)
10206 (setq new (if (and org-priority-start-cycle-with-default (not have))
10207 org-default-priority (1+ current)))))
10208 (t (error "Invalid action")))
10209 (if (or (< (upcase new) org-highest-priority)
10210 (> (upcase new) org-lowest-priority))
10211 (setq remove t))
10212 (setq news (format "%c" new))
10213 (if have
10214 (if remove
10215 (replace-match "" t t nil 1)
10216 (replace-match news t t nil 2))
10217 (if remove
10218 (error "No priority cookie found in line")
10219 (let ((case-fold-search nil))
10220 (looking-at org-todo-line-regexp))
10221 (if (match-end 2)
10222 (progn
10223 (goto-char (match-end 2))
10224 (insert " [#" news "]"))
10225 (goto-char (match-beginning 3))
10226 (insert "[#" news "] ")))))
10227 (org-preserve-lc (org-set-tags nil 'align))
10228 (if remove
10229 (message "Priority removed")
10230 (message "Priority of current item set to %s" news))))
10233 (defun org-get-priority (s)
10234 "Find priority cookie and return priority."
10235 (save-match-data
10236 (if (not (string-match org-priority-regexp s))
10237 (* 1000 (- org-lowest-priority org-default-priority))
10238 (* 1000 (- org-lowest-priority
10239 (string-to-char (match-string 2 s)))))))
10241 ;;;; Tags
10243 (defvar org-agenda-archives-mode)
10244 (defvar org-map-continue-from nil
10245 "Position from where mapping should continue.
10246 Can be set byt the action argument to `org-scan-tag's and `org-map-entries'.")
10248 (defvar org-scanner-tags nil
10249 "The current tag list while the tags scanner is running.")
10250 (defvar org-trust-scanner-tags nil
10251 "Should `org-get-tags-at' use the tags fro the scanner.
10252 This is for internal dynamical scoping only.
10253 When this is non-nil, the function `org-get-tags-at' will return the value
10254 of `org-scanner-tags' instead of building the list by itself. This
10255 can lead to large speed-ups when the tags scanner is used in a file with
10256 many entries, and when the list of tags is retrieved, for example to
10257 obtain a list of properties. Building the tags list for each entry in such
10258 a file becomes an N^2 operation - but with this variable set, it scales
10259 as N.")
10261 (defun org-scan-tags (action matcher &optional todo-only)
10262 "Scan headline tags with inheritance and produce output ACTION.
10264 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
10265 or `agenda' to produce an entry list for an agenda view. It can also be
10266 a Lisp form or a function that should be called at each matched headline, in
10267 this case the return value is a list of all return values from these calls.
10269 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
10270 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
10271 only lines with a TODO keyword are included in the output."
10272 (require 'org-agenda)
10273 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
10274 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
10275 (org-re
10276 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
10277 (props (list 'face 'default
10278 'done-face 'org-agenda-done
10279 'undone-face 'default
10280 'mouse-face 'highlight
10281 'org-not-done-regexp org-not-done-regexp
10282 'org-todo-regexp org-todo-regexp
10283 'keymap org-agenda-keymap
10284 'help-echo
10285 (format "mouse-2 or RET jump to org file %s"
10286 (abbreviate-file-name
10287 (or (buffer-file-name (buffer-base-buffer))
10288 (buffer-name (buffer-base-buffer)))))))
10289 (case-fold-search nil)
10290 (org-map-continue-from nil)
10291 lspos tags tags-list
10292 (tags-alist (list (cons 0 org-file-tags)))
10293 (llast 0) rtn rtn1 level category i txt
10294 todo marker entry priority)
10295 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
10296 (setq action (list 'lambda nil action)))
10297 (save-excursion
10298 (goto-char (point-min))
10299 (when (eq action 'sparse-tree)
10300 (org-overview)
10301 (org-remove-occur-highlights))
10302 (while (re-search-forward re nil t)
10303 (catch :skip
10304 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
10305 tags (if (match-end 4) (org-match-string-no-properties 4)))
10306 (goto-char (setq lspos (match-beginning 0)))
10307 (setq level (org-reduced-level (funcall outline-level))
10308 category (org-get-category))
10309 (setq i llast llast level)
10310 ;; remove tag lists from same and sublevels
10311 (while (>= i level)
10312 (when (setq entry (assoc i tags-alist))
10313 (setq tags-alist (delete entry tags-alist)))
10314 (setq i (1- i)))
10315 ;; add the next tags
10316 (when tags
10317 (setq tags (org-split-string tags ":")
10318 tags-alist
10319 (cons (cons level tags) tags-alist)))
10320 ;; compile tags for current headline
10321 (setq tags-list
10322 (if org-use-tag-inheritance
10323 (apply 'append (mapcar 'cdr (reverse tags-alist)))
10324 tags)
10325 org-scanner-tags tags-list)
10326 (when org-use-tag-inheritance
10327 (setcdr (car tags-alist)
10328 (mapcar (lambda (x)
10329 (setq x (copy-sequence x))
10330 (org-add-prop-inherited x))
10331 (cdar tags-alist))))
10332 (when (and tags org-use-tag-inheritance
10333 (or (not (eq t org-use-tag-inheritance))
10334 org-tags-exclude-from-inheritance))
10335 ;; selective inheritance, remove uninherited ones
10336 (setcdr (car tags-alist)
10337 (org-remove-uniherited-tags (cdar tags-alist))))
10338 (when (and (or (not todo-only)
10339 (and (member todo org-not-done-keywords)
10340 (or (not org-agenda-tags-todo-honor-ignore-options)
10341 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
10342 (let ((case-fold-search t)) (eval matcher))
10344 (not (member org-archive-tag tags-list))
10345 ;; we have an archive tag, should we use this anyway?
10346 (or (not org-agenda-skip-archived-trees)
10347 (and (eq action 'agenda) org-agenda-archives-mode))))
10348 (unless (eq action 'sparse-tree) (org-agenda-skip))
10350 ;; select this headline
10352 (cond
10353 ((eq action 'sparse-tree)
10354 (and org-highlight-sparse-tree-matches
10355 (org-get-heading) (match-end 0)
10356 (org-highlight-new-match
10357 (match-beginning 0) (match-beginning 1)))
10358 (org-show-context 'tags-tree))
10359 ((eq action 'agenda)
10360 (setq txt (org-format-agenda-item
10362 (concat
10363 (if (eq org-tags-match-list-sublevels 'indented)
10364 (make-string (1- level) ?.) "")
10365 (org-get-heading))
10366 category
10367 tags-list
10369 priority (org-get-priority txt))
10370 (goto-char lspos)
10371 (setq marker (org-agenda-new-marker))
10372 (org-add-props txt props
10373 'org-marker marker 'org-hd-marker marker 'org-category category
10374 'todo-state todo
10375 'priority priority 'type "tagsmatch")
10376 (push txt rtn))
10377 ((functionp action)
10378 (setq org-map-continue-from nil)
10379 (save-excursion
10380 (setq rtn1 (funcall action))
10381 (push rtn1 rtn)))
10382 (t (error "Invalid action")))
10384 ;; if we are to skip sublevels, jump to end of subtree
10385 (unless org-tags-match-list-sublevels
10386 (org-end-of-subtree t)
10387 (backward-char 1))))
10388 ;; Get the correct position from where to continue
10389 (if org-map-continue-from
10390 (goto-char org-map-continue-from)
10391 (and (= (point) lspos) (end-of-line 1)))))
10392 (when (and (eq action 'sparse-tree)
10393 (not org-sparse-tree-open-archived-trees))
10394 (org-hide-archived-subtrees (point-min) (point-max)))
10395 (nreverse rtn)))
10397 (defun org-remove-uniherited-tags (tags)
10398 "Remove all tags that are not inherited from the list TAGS."
10399 (cond
10400 ((eq org-use-tag-inheritance t)
10401 (if org-tags-exclude-from-inheritance
10402 (org-delete-all org-tags-exclude-from-inheritance tags)
10403 tags))
10404 ((not org-use-tag-inheritance) nil)
10405 ((stringp org-use-tag-inheritance)
10406 (delq nil (mapcar
10407 (lambda (x)
10408 (if (and (string-match org-use-tag-inheritance x)
10409 (not (member x org-tags-exclude-from-inheritance)))
10410 x nil))
10411 tags)))
10412 ((listp org-use-tag-inheritance)
10413 (delq nil (mapcar
10414 (lambda (x)
10415 (if (member x org-use-tag-inheritance) x nil))
10416 tags)))))
10418 (defvar todo-only) ;; dynamically scoped
10420 (defun org-match-sparse-tree (&optional todo-only match)
10421 "Create a sparse tree according to tags string MATCH.
10422 MATCH can contain positive and negative selection of tags, like
10423 \"+WORK+URGENT-WITHBOSS\".
10424 If optional argument TODO-ONLY is non-nil, only select lines that are
10425 also TODO lines."
10426 (interactive "P")
10427 (org-prepare-agenda-buffers (list (current-buffer)))
10428 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
10430 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
10432 (defvar org-cached-props nil)
10433 (defun org-cached-entry-get (pom property)
10434 (if (or (eq t org-use-property-inheritance)
10435 (and (stringp org-use-property-inheritance)
10436 (string-match org-use-property-inheritance property))
10437 (and (listp org-use-property-inheritance)
10438 (member property org-use-property-inheritance)))
10439 ;; Caching is not possible, check it directly
10440 (org-entry-get pom property 'inherit)
10441 ;; Get all properties, so that we can do complicated checks easily
10442 (cdr (assoc property (or org-cached-props
10443 (setq org-cached-props
10444 (org-entry-properties pom)))))))
10446 (defun org-global-tags-completion-table (&optional files)
10447 "Return the list of all tags in all agenda buffer/files."
10448 (save-excursion
10449 (org-uniquify
10450 (delq nil
10451 (apply 'append
10452 (mapcar
10453 (lambda (file)
10454 (set-buffer (find-file-noselect file))
10455 (append (org-get-buffer-tags)
10456 (mapcar (lambda (x) (if (stringp (car-safe x))
10457 (list (car-safe x)) nil))
10458 org-tag-alist)))
10459 (if (and files (car files))
10460 files
10461 (org-agenda-files))))))))
10463 (defun org-make-tags-matcher (match)
10464 "Create the TAGS//TODO matcher form for the selection string MATCH."
10465 ;; todo-only is scoped dynamically into this function, and the function
10466 ;; may change it if the matcher asks for it.
10467 (unless match
10468 ;; Get a new match request, with completion
10469 (let ((org-last-tags-completion-table
10470 (org-global-tags-completion-table)))
10471 (setq match (org-completing-read-no-ido
10472 "Match: " 'org-tags-completion-function nil nil nil
10473 'org-tags-history))))
10475 ;; Parse the string and create a lisp form
10476 (let ((match0 match)
10477 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
10478 minus tag mm
10479 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
10480 orterms term orlist re-p str-p level-p level-op time-p
10481 prop-p pn pv po cat-p gv rest)
10482 (if (string-match "/+" match)
10483 ;; match contains also a todo-matching request
10484 (progn
10485 (setq tagsmatch (substring match 0 (match-beginning 0))
10486 todomatch (substring match (match-end 0)))
10487 (if (string-match "^!" todomatch)
10488 (setq todo-only t todomatch (substring todomatch 1)))
10489 (if (string-match "^\\s-*$" todomatch)
10490 (setq todomatch nil)))
10491 ;; only matching tags
10492 (setq tagsmatch match todomatch nil))
10494 ;; Make the tags matcher
10495 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10496 (setq tagsmatcher t)
10497 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10498 (while (setq term (pop orterms))
10499 (while (and (equal (substring term -1) "\\") orterms)
10500 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10501 (while (string-match re term)
10502 (setq rest (substring term (match-end 0))
10503 minus (and (match-end 1)
10504 (equal (match-string 1 term) "-"))
10505 tag (match-string 2 term)
10506 re-p (equal (string-to-char tag) ?{)
10507 level-p (match-end 4)
10508 prop-p (match-end 5)
10509 mm (cond
10510 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10511 (level-p
10512 (setq level-op (org-op-to-function (match-string 3 term)))
10513 `(,level-op level ,(string-to-number
10514 (match-string 4 term))))
10515 (prop-p
10516 (setq pn (match-string 5 term)
10517 po (match-string 6 term)
10518 pv (match-string 7 term)
10519 cat-p (equal pn "CATEGORY")
10520 re-p (equal (string-to-char pv) ?{)
10521 str-p (equal (string-to-char pv) ?\")
10522 time-p (save-match-data
10523 (string-match "^\"[[<].*[]>]\"$" pv))
10524 pv (if (or re-p str-p) (substring pv 1 -1) pv))
10525 (if time-p (setq pv (org-matcher-time pv)))
10526 (setq po (org-op-to-function po (if time-p 'time str-p)))
10527 (cond
10528 ((equal pn "CATEGORY")
10529 (setq gv '(get-text-property (point) 'org-category)))
10530 ((equal pn "TODO")
10531 (setq gv 'todo))
10533 (setq gv `(org-cached-entry-get nil ,pn))))
10534 (if re-p
10535 (if (eq po 'org<>)
10536 `(not (string-match ,pv (or ,gv "")))
10537 `(string-match ,pv (or ,gv "")))
10538 (if str-p
10539 `(,po (or ,gv "") ,pv)
10540 `(,po (string-to-number (or ,gv ""))
10541 ,(string-to-number pv) ))))
10542 (t `(member ,tag tags-list)))
10543 mm (if minus (list 'not mm) mm)
10544 term rest)
10545 (push mm tagsmatcher))
10546 (push (if (> (length tagsmatcher) 1)
10547 (cons 'and tagsmatcher)
10548 (car tagsmatcher))
10549 orlist)
10550 (setq tagsmatcher nil))
10551 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
10552 (setq tagsmatcher
10553 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
10554 ;; Make the todo matcher
10555 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10556 (setq todomatcher t)
10557 (setq orterms (org-split-string todomatch "|") orlist nil)
10558 (while (setq term (pop orterms))
10559 (while (string-match re term)
10560 (setq minus (and (match-end 1)
10561 (equal (match-string 1 term) "-"))
10562 kwd (match-string 2 term)
10563 re-p (equal (string-to-char kwd) ?{)
10564 term (substring term (match-end 0))
10565 mm (if re-p
10566 `(string-match ,(substring kwd 1 -1) todo)
10567 (list 'equal 'todo kwd))
10568 mm (if minus (list 'not mm) mm))
10569 (push mm todomatcher))
10570 (push (if (> (length todomatcher) 1)
10571 (cons 'and todomatcher)
10572 (car todomatcher))
10573 orlist)
10574 (setq todomatcher nil))
10575 (setq todomatcher (if (> (length orlist) 1)
10576 (cons 'or orlist) (car orlist))))
10578 ;; Return the string and lisp forms of the matcher
10579 (setq matcher (if todomatcher
10580 (list 'and tagsmatcher todomatcher)
10581 tagsmatcher))
10582 (cons match0 matcher)))
10584 (defun org-op-to-function (op &optional stringp)
10585 "Turn an operator into the appropriate function."
10586 (setq op
10587 (cond
10588 ((equal op "<" ) '(< string< org-time<))
10589 ((equal op ">" ) '(> org-string> org-time>))
10590 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
10591 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
10592 ((member op '("=" "==")) '(= string= org-time=))
10593 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
10594 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
10596 (defun org<> (a b) (not (= a b)))
10597 (defun org-string<= (a b) (or (string= a b) (string< a b)))
10598 (defun org-string>= (a b) (not (string< a b)))
10599 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
10600 (defun org-string<> (a b) (not (string= a b)))
10601 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
10602 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
10603 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
10604 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
10605 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
10606 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
10607 (defun org-2ft (s)
10608 "Convert S to a floating point time.
10609 If S is already a number, just return it. If it is a string, parse
10610 it as a time string and apply `float-time' to it. If S is nil, just return 0."
10611 (cond
10612 ((numberp s) s)
10613 ((stringp s)
10614 (condition-case nil
10615 (float-time (apply 'encode-time (org-parse-time-string s)))
10616 (error 0.)))
10617 (t 0.)))
10619 (defun org-time-today ()
10620 "Time in seconds today at 0:00.
10621 Returns the float number of seconds since the beginning of the
10622 epoch to the beginning of today (00:00)."
10623 (float-time (apply 'encode-time
10624 (append '(0 0 0) (nthcdr 3 (decode-time))))))
10626 (defun org-matcher-time (s)
10627 "Interpret a time comparison value."
10628 (save-match-data
10629 (cond
10630 ((string= s "<now>") (float-time))
10631 ((string= s "<today>") (org-time-today))
10632 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
10633 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
10634 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
10635 (+ (org-time-today)
10636 (* (string-to-number (match-string 1 s))
10637 (cdr (assoc (match-string 2 s)
10638 '(("d" . 86400.0) ("w" . 604800.0)
10639 ("m" . 2678400.0) ("y" . 31557600.0)))))))
10640 (t (org-2ft s)))))
10642 (defun org-match-any-p (re list)
10643 "Does re match any element of list?"
10644 (setq list (mapcar (lambda (x) (string-match re x)) list))
10645 (delq nil list))
10647 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
10648 (defvar org-tags-overlay (org-make-overlay 1 1))
10649 (org-detach-overlay org-tags-overlay)
10651 (defun org-get-local-tags-at (&optional pos)
10652 "Get a list of tags defined in the current headline."
10653 (org-get-tags-at pos 'local))
10655 (defun org-get-local-tags ()
10656 "Get a list of tags defined in the current headline."
10657 (org-get-tags-at nil 'local))
10659 (defun org-get-tags-at (&optional pos local)
10660 "Get a list of all headline tags applicable at POS.
10661 POS defaults to point. If tags are inherited, the list contains
10662 the targets in the same sequence as the headlines appear, i.e.
10663 the tags of the current headline come last.
10664 When LOCAL is non-nil, only return tags from the current headline,
10665 ignore inherited ones."
10666 (interactive)
10667 (if (and org-trust-scanner-tags
10668 (or (not pos) (equal pos (point)))
10669 (not local))
10670 org-scanner-tags
10671 (let (tags ltags lastpos parent)
10672 (save-excursion
10673 (save-restriction
10674 (widen)
10675 (goto-char (or pos (point)))
10676 (save-match-data
10677 (catch 'done
10678 (condition-case nil
10679 (progn
10680 (org-back-to-heading t)
10681 (while (not (equal lastpos (point)))
10682 (setq lastpos (point))
10683 (when (looking-at
10684 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
10685 (setq ltags (org-split-string
10686 (org-match-string-no-properties 1) ":"))
10687 (when parent
10688 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
10689 (setq tags (append
10690 (if parent
10691 (org-remove-uniherited-tags ltags)
10692 ltags)
10693 tags)))
10694 (or org-use-tag-inheritance (throw 'done t))
10695 (if local (throw 'done t))
10696 (or (org-up-heading-safe) (error nil))
10697 (setq parent t)))
10698 (error nil)))))
10699 (append (org-remove-uniherited-tags org-file-tags) tags)))))
10701 (defun org-add-prop-inherited (s)
10702 (add-text-properties 0 (length s) '(inherited t) s)
10705 (defun org-toggle-tag (tag &optional onoff)
10706 "Toggle the tag TAG for the current line.
10707 If ONOFF is `on' or `off', don't toggle but set to this state."
10708 (let (res current)
10709 (save-excursion
10710 (org-back-to-heading t)
10711 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
10712 (point-at-eol) t)
10713 (progn
10714 (setq current (match-string 1))
10715 (replace-match ""))
10716 (setq current ""))
10717 (setq current (nreverse (org-split-string current ":")))
10718 (cond
10719 ((eq onoff 'on)
10720 (setq res t)
10721 (or (member tag current) (push tag current)))
10722 ((eq onoff 'off)
10723 (or (not (member tag current)) (setq current (delete tag current))))
10724 (t (if (member tag current)
10725 (setq current (delete tag current))
10726 (setq res t)
10727 (push tag current))))
10728 (end-of-line 1)
10729 (if current
10730 (progn
10731 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
10732 (org-set-tags nil t))
10733 (delete-horizontal-space))
10734 (run-hooks 'org-after-tags-change-hook))
10735 res))
10737 (defun org-align-tags-here (to-col)
10738 ;; Assumes that this is a headline
10739 (let ((pos (point)) (col (current-column)) ncol tags-l p)
10740 (beginning-of-line 1)
10741 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10742 (< pos (match-beginning 2)))
10743 (progn
10744 (setq tags-l (- (match-end 2) (match-beginning 2)))
10745 (goto-char (match-beginning 1))
10746 (insert " ")
10747 (delete-region (point) (1+ (match-beginning 2)))
10748 (setq ncol (max (1+ (current-column))
10749 (1+ col)
10750 (if (> to-col 0)
10751 to-col
10752 (- (abs to-col) tags-l))))
10753 (setq p (point))
10754 (insert (make-string (- ncol (current-column)) ?\ ))
10755 (setq ncol (current-column))
10756 (when indent-tabs-mode (tabify p (point-at-eol)))
10757 (org-move-to-column (min ncol col) t))
10758 (goto-char pos))))
10760 (defun org-set-tags-command (&optional arg just-align)
10761 "Call the set-tags command for the current entry."
10762 (interactive "P")
10763 (if (org-on-heading-p)
10764 (org-set-tags arg just-align)
10765 (save-excursion
10766 (org-back-to-heading t)
10767 (org-set-tags arg just-align))))
10769 (defun org-set-tags (&optional arg just-align)
10770 "Set the tags for the current headline.
10771 With prefix ARG, realign all tags in headings in the current buffer."
10772 (interactive "P")
10773 (let* ((re (concat "^" outline-regexp))
10774 (current (org-get-tags-string))
10775 (col (current-column))
10776 (org-setting-tags t)
10777 table current-tags inherited-tags ; computed below when needed
10778 tags p0 c0 c1 rpl)
10779 (if arg
10780 (save-excursion
10781 (goto-char (point-min))
10782 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
10783 (while (re-search-forward re nil t)
10784 (org-set-tags nil t)
10785 (end-of-line 1)))
10786 (message "All tags realigned to column %d" org-tags-column))
10787 (if just-align
10788 (setq tags current)
10789 ;; Get a new set of tags from the user
10790 (save-excursion
10791 (setq table (append org-tag-persistent-alist
10792 (or org-tag-alist (org-get-buffer-tags)))
10793 org-last-tags-completion-table table
10794 current-tags (org-split-string current ":")
10795 inherited-tags (nreverse
10796 (nthcdr (length current-tags)
10797 (nreverse (org-get-tags-at))))
10798 tags
10799 (if (or (eq t org-use-fast-tag-selection)
10800 (and org-use-fast-tag-selection
10801 (delq nil (mapcar 'cdr table))))
10802 (org-fast-tag-selection
10803 current-tags inherited-tags table
10804 (if org-fast-tag-selection-include-todo org-todo-key-alist))
10805 (let ((org-add-colon-after-tag-completion t))
10806 (org-trim
10807 (org-without-partial-completion
10808 (org-ido-completing-read "Tags: " 'org-tags-completion-function
10809 nil nil current 'org-tags-history)))))))
10810 (while (string-match "[-+&]+" tags)
10811 ;; No boolean logic, just a list
10812 (setq tags (replace-match ":" t t tags))))
10814 (if (string-match "\\`[\t ]*\\'" tags)
10815 (setq tags "")
10816 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
10817 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
10819 ;; Insert new tags at the correct column
10820 (beginning-of-line 1)
10821 (cond
10822 ((and (equal current "") (equal tags "")))
10823 ((re-search-forward
10824 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10825 (point-at-eol) t)
10826 (if (equal tags "")
10827 (setq rpl "")
10828 (goto-char (match-beginning 0))
10829 (setq c0 (current-column) p0 (point)
10830 c1 (max (1+ c0) (if (> org-tags-column 0)
10831 org-tags-column
10832 (- (- org-tags-column) (length tags))))
10833 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10834 (replace-match rpl t t)
10835 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
10836 tags)
10837 (t (error "Tags alignment failed")))
10838 (org-move-to-column col)
10839 (unless just-align
10840 (run-hooks 'org-after-tags-change-hook)))))
10842 (defun org-change-tag-in-region (beg end tag off)
10843 "Add or remove TAG for each entry in the region.
10844 This works in the agenda, and also in an org-mode buffer."
10845 (interactive
10846 (list (region-beginning) (region-end)
10847 (let ((org-last-tags-completion-table
10848 (if (org-mode-p)
10849 (org-get-buffer-tags)
10850 (org-global-tags-completion-table))))
10851 (org-ido-completing-read
10852 "Tag: " 'org-tags-completion-function nil nil nil
10853 'org-tags-history))
10854 (progn
10855 (message "[s]et or [r]emove? ")
10856 (equal (read-char-exclusive) ?r))))
10857 (if (fboundp 'deactivate-mark) (deactivate-mark))
10858 (let ((agendap (equal major-mode 'org-agenda-mode))
10859 l1 l2 m buf pos newhead (cnt 0))
10860 (goto-char end)
10861 (setq l2 (1- (org-current-line)))
10862 (goto-char beg)
10863 (setq l1 (org-current-line))
10864 (loop for l from l1 to l2 do
10865 (goto-line l)
10866 (setq m (get-text-property (point) 'org-hd-marker))
10867 (when (or (and (org-mode-p) (org-on-heading-p))
10868 (and agendap m))
10869 (setq buf (if agendap (marker-buffer m) (current-buffer))
10870 pos (if agendap m (point)))
10871 (with-current-buffer buf
10872 (save-excursion
10873 (save-restriction
10874 (goto-char pos)
10875 (setq cnt (1+ cnt))
10876 (org-toggle-tag tag (if off 'off 'on))
10877 (setq newhead (org-get-heading)))))
10878 (and agendap (org-agenda-change-all-lines newhead m))))
10879 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
10881 (defun org-tags-completion-function (string predicate &optional flag)
10882 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10883 (confirm (lambda (x) (stringp (car x)))))
10884 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10885 (setq s1 (match-string 1 string)
10886 s2 (match-string 2 string))
10887 (setq s1 "" s2 string))
10888 (cond
10889 ((eq flag nil)
10890 ;; try completion
10891 (setq rtn (try-completion s2 ctable confirm))
10892 (if (stringp rtn)
10893 (setq rtn
10894 (concat s1 s2 (substring rtn (length s2))
10895 (if (and org-add-colon-after-tag-completion
10896 (assoc rtn ctable))
10897 ":" ""))))
10898 rtn)
10899 ((eq flag t)
10900 ;; all-completions
10901 (all-completions s2 ctable confirm)
10903 ((eq flag 'lambda)
10904 ;; exact match?
10905 (assoc s2 ctable)))
10908 (defun org-fast-tag-insert (kwd tags face &optional end)
10909 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
10910 (insert (format "%-12s" (concat kwd ":"))
10911 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
10912 (or end "")))
10914 (defun org-fast-tag-show-exit (flag)
10915 (save-excursion
10916 (goto-line 3)
10917 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
10918 (replace-match ""))
10919 (when flag
10920 (end-of-line 1)
10921 (org-move-to-column (- (window-width) 19) t)
10922 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
10924 (defun org-set-current-tags-overlay (current prefix)
10925 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
10926 (if (featurep 'xemacs)
10927 (org-overlay-display org-tags-overlay (concat prefix s)
10928 'secondary-selection)
10929 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
10930 (org-overlay-display org-tags-overlay (concat prefix s)))))
10932 (defun org-fast-tag-selection (current inherited table &optional todo-table)
10933 "Fast tag selection with single keys.
10934 CURRENT is the current list of tags in the headline, INHERITED is the
10935 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
10936 possibly with grouping information. TODO-TABLE is a similar table with
10937 TODO keywords, should these have keys assigned to them.
10938 If the keys are nil, a-z are automatically assigned.
10939 Returns the new tags string, or nil to not change the current settings."
10940 (let* ((fulltable (append table todo-table))
10941 (maxlen (apply 'max (mapcar
10942 (lambda (x)
10943 (if (stringp (car x)) (string-width (car x)) 0))
10944 fulltable)))
10945 (buf (current-buffer))
10946 (expert (eq org-fast-tag-selection-single-key 'expert))
10947 (buffer-tags nil)
10948 (fwidth (+ maxlen 3 1 3))
10949 (ncol (/ (- (window-width) 4) fwidth))
10950 (i-face 'org-done)
10951 (c-face 'org-todo)
10952 tg cnt e c char c1 c2 ntable tbl rtn
10953 ov-start ov-end ov-prefix
10954 (exit-after-next org-fast-tag-selection-single-key)
10955 (done-keywords org-done-keywords)
10956 groups ingroup)
10957 (save-excursion
10958 (beginning-of-line 1)
10959 (if (looking-at
10960 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10961 (setq ov-start (match-beginning 1)
10962 ov-end (match-end 1)
10963 ov-prefix "")
10964 (setq ov-start (1- (point-at-eol))
10965 ov-end (1+ ov-start))
10966 (skip-chars-forward "^\n\r")
10967 (setq ov-prefix
10968 (concat
10969 (buffer-substring (1- (point)) (point))
10970 (if (> (current-column) org-tags-column)
10972 (make-string (- org-tags-column (current-column)) ?\ ))))))
10973 (org-move-overlay org-tags-overlay ov-start ov-end)
10974 (save-window-excursion
10975 (if expert
10976 (set-buffer (get-buffer-create " *Org tags*"))
10977 (delete-other-windows)
10978 (split-window-vertically)
10979 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
10980 (erase-buffer)
10981 (org-set-local 'org-done-keywords done-keywords)
10982 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10983 (org-fast-tag-insert "Current" current c-face "\n\n")
10984 (org-fast-tag-show-exit exit-after-next)
10985 (org-set-current-tags-overlay current ov-prefix)
10986 (setq tbl fulltable char ?a cnt 0)
10987 (while (setq e (pop tbl))
10988 (cond
10989 ((equal e '(:startgroup))
10990 (push '() groups) (setq ingroup t)
10991 (when (not (= cnt 0))
10992 (setq cnt 0)
10993 (insert "\n"))
10994 (insert "{ "))
10995 ((equal e '(:endgroup))
10996 (setq ingroup nil cnt 0)
10997 (insert "}\n"))
10998 ((equal e '(:newline))
10999 (when (not (= cnt 0))
11000 (setq cnt 0)
11001 (insert "\n")
11002 (setq e (car tbl))
11003 (while (equal (car tbl) '(:newline))
11004 (insert "\n")
11005 (setq tbl (cdr tbl)))))
11007 (setq tg (car e) c2 nil)
11008 (if (cdr e)
11009 (setq c (cdr e))
11010 ;; automatically assign a character.
11011 (setq c1 (string-to-char
11012 (downcase (substring
11013 tg (if (= (string-to-char tg) ?@) 1 0)))))
11014 (if (or (rassoc c1 ntable) (rassoc c1 table))
11015 (while (or (rassoc char ntable) (rassoc char table))
11016 (setq char (1+ char)))
11017 (setq c2 c1))
11018 (setq c (or c2 char)))
11019 (if ingroup (push tg (car groups)))
11020 (setq tg (org-add-props tg nil 'face
11021 (cond
11022 ((not (assoc tg table))
11023 (org-get-todo-face tg))
11024 ((member tg current) c-face)
11025 ((member tg inherited) i-face)
11026 (t nil))))
11027 (if (and (= cnt 0) (not ingroup)) (insert " "))
11028 (insert "[" c "] " tg (make-string
11029 (- fwidth 4 (length tg)) ?\ ))
11030 (push (cons tg c) ntable)
11031 (when (= (setq cnt (1+ cnt)) ncol)
11032 (insert "\n")
11033 (if ingroup (insert " "))
11034 (setq cnt 0)))))
11035 (setq ntable (nreverse ntable))
11036 (insert "\n")
11037 (goto-char (point-min))
11038 (if (not expert) (org-fit-window-to-buffer))
11039 (setq rtn
11040 (catch 'exit
11041 (while t
11042 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
11043 (if groups " [!] no groups" " [!]groups")
11044 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
11045 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11046 (cond
11047 ((= c ?\r) (throw 'exit t))
11048 ((= c ?!)
11049 (setq groups (not groups))
11050 (goto-char (point-min))
11051 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
11052 ((= c ?\C-c)
11053 (if (not expert)
11054 (org-fast-tag-show-exit
11055 (setq exit-after-next (not exit-after-next)))
11056 (setq expert nil)
11057 (delete-other-windows)
11058 (split-window-vertically)
11059 (org-switch-to-buffer-other-window " *Org tags*")
11060 (org-fit-window-to-buffer)))
11061 ((or (= c ?\C-g)
11062 (and (= c ?q) (not (rassoc c ntable))))
11063 (org-detach-overlay org-tags-overlay)
11064 (setq quit-flag t))
11065 ((= c ?\ )
11066 (setq current nil)
11067 (if exit-after-next (setq exit-after-next 'now)))
11068 ((= c ?\t)
11069 (condition-case nil
11070 (setq tg (org-ido-completing-read
11071 "Tag: "
11072 (or buffer-tags
11073 (with-current-buffer buf
11074 (org-get-buffer-tags)))))
11075 (quit (setq tg "")))
11076 (when (string-match "\\S-" tg)
11077 (add-to-list 'buffer-tags (list tg))
11078 (if (member tg current)
11079 (setq current (delete tg current))
11080 (push tg current)))
11081 (if exit-after-next (setq exit-after-next 'now)))
11082 ((setq e (rassoc c todo-table) tg (car e))
11083 (with-current-buffer buf
11084 (save-excursion (org-todo tg)))
11085 (if exit-after-next (setq exit-after-next 'now)))
11086 ((setq e (rassoc c ntable) tg (car e))
11087 (if (member tg current)
11088 (setq current (delete tg current))
11089 (loop for g in groups do
11090 (if (member tg g)
11091 (mapc (lambda (x)
11092 (setq current (delete x current)))
11093 g)))
11094 (push tg current))
11095 (if exit-after-next (setq exit-after-next 'now))))
11097 ;; Create a sorted list
11098 (setq current
11099 (sort current
11100 (lambda (a b)
11101 (assoc b (cdr (memq (assoc a ntable) ntable))))))
11102 (if (eq exit-after-next 'now) (throw 'exit t))
11103 (goto-char (point-min))
11104 (beginning-of-line 2)
11105 (delete-region (point) (point-at-eol))
11106 (org-fast-tag-insert "Current" current c-face)
11107 (org-set-current-tags-overlay current ov-prefix)
11108 (while (re-search-forward
11109 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
11110 (setq tg (match-string 1))
11111 (add-text-properties
11112 (match-beginning 1) (match-end 1)
11113 (list 'face
11114 (cond
11115 ((member tg current) c-face)
11116 ((member tg inherited) i-face)
11117 (t (get-text-property (match-beginning 1) 'face))))))
11118 (goto-char (point-min)))))
11119 (org-detach-overlay org-tags-overlay)
11120 (if rtn
11121 (mapconcat 'identity current ":")
11122 nil))))
11124 (defun org-get-tags-string ()
11125 "Get the TAGS string in the current headline."
11126 (unless (org-on-heading-p t)
11127 (error "Not on a heading"))
11128 (save-excursion
11129 (beginning-of-line 1)
11130 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11131 (org-match-string-no-properties 1)
11132 "")))
11134 (defun org-get-tags ()
11135 "Get the list of tags specified in the current headline."
11136 (org-split-string (org-get-tags-string) ":"))
11138 (defun org-get-buffer-tags ()
11139 "Get a table of all tags used in the buffer, for completion."
11140 (let (tags)
11141 (save-excursion
11142 (goto-char (point-min))
11143 (while (re-search-forward
11144 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
11145 (when (equal (char-after (point-at-bol 0)) ?*)
11146 (mapc (lambda (x) (add-to-list 'tags x))
11147 (org-split-string (org-match-string-no-properties 1) ":")))))
11148 (mapcar 'list tags)))
11150 ;;;; The mapping API
11152 ;;;###autoload
11153 (defun org-map-entries (func &optional match scope &rest skip)
11154 "Call FUNC at each headline selected by MATCH in SCOPE.
11156 FUNC is a function or a lisp form. The function will be called without
11157 arguments, with the cursor positioned at the beginning of the headline.
11158 The return values of all calls to the function will be collected and
11159 returned as a list.
11161 The call to FUNC will be wrapped into a save-excursion form, so FUNC
11162 does not need to preserve point. After evaluaton, the cursor will be
11163 moved to the end of the line (presumably of the headline of the
11164 processed entry) and search continues from there. Under some
11165 circumstances, this may not produce the wanted results. For example,
11166 if you have removed (e.g. archived) the current (sub)tree it could
11167 mean that the next entry will be skipped entirely. In such cases, you
11168 can specify the position from where search should continue by making
11169 FUNC set the variable `org-map-continue-from' to the desired buffer
11170 position.
11172 MATCH is a tags/property/todo match as it is used in the agenda tags view.
11173 Only headlines that are matched by this query will be considered during
11174 the iteration. When MATCH is nil or t, all headlines will be
11175 visited by the iteration.
11177 SCOPE determines the scope of this command. It can be any of:
11179 nil The current buffer, respecting the restriction if any
11180 tree The subtree started with the entry at point
11181 file The current buffer, without restriction
11182 file-with-archives
11183 The current buffer, and any archives associated with it
11184 agenda All agenda files
11185 agenda-with-archives
11186 All agenda files with any archive files associated with them
11187 \(file1 file2 ...)
11188 If this is a list, all files in the list will be scanned
11190 The remaining args are treated as settings for the skipping facilities of
11191 the scanner. The following items can be given here:
11193 archive skip trees with the archive tag.
11194 comment skip trees with the COMMENT keyword
11195 function or Emacs Lisp form:
11196 will be used as value for `org-agenda-skip-function', so whenever
11197 the the function returns t, FUNC will not be called for that
11198 entry and search will continue from the point where the
11199 function leaves it.
11201 If your function needs to retrieve the tags including inherited tags
11202 at the *current* entry, you can use the value of the variable
11203 `org-scanner-tags' which will be much faster than getting the value
11204 with `org-get-tags-at'. If your function gets properties with
11205 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
11206 to t around the call to `org-entry-properties' to get the same speedup.
11207 Note that if your function moves around to retrieve tags and properties at
11208 a *different* entry, you cannot use these techniques."
11209 (let* ((org-agenda-archives-mode nil) ; just to make sure
11210 (org-agenda-skip-archived-trees (memq 'archive skip))
11211 (org-agenda-skip-comment-trees (memq 'comment skip))
11212 (org-agenda-skip-function
11213 (car (org-delete-all '(comment archive) skip)))
11214 (org-tags-match-list-sublevels t)
11215 matcher file res
11216 org-todo-keywords-for-agenda
11217 org-done-keywords-for-agenda
11218 org-todo-keyword-alist-for-agenda
11219 org-tag-alist-for-agenda)
11221 (cond
11222 ((eq match t) (setq matcher t))
11223 ((eq match nil) (setq matcher t))
11224 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
11226 (save-excursion
11227 (save-restriction
11228 (when (eq scope 'tree)
11229 (org-back-to-heading t)
11230 (org-narrow-to-subtree)
11231 (setq scope nil))
11233 (if (not scope)
11234 (progn
11235 (org-prepare-agenda-buffers
11236 (list (buffer-file-name (current-buffer))))
11237 (setq res (org-scan-tags func matcher)))
11238 ;; Get the right scope
11239 (cond
11240 ((and scope (listp scope) (symbolp (car scope)))
11241 (setq scope (eval scope)))
11242 ((eq scope 'agenda)
11243 (setq scope (org-agenda-files t)))
11244 ((eq scope 'agenda-with-archives)
11245 (setq scope (org-agenda-files t))
11246 (setq scope (org-add-archive-files scope)))
11247 ((eq scope 'file)
11248 (setq scope (list (buffer-file-name))))
11249 ((eq scope 'file-with-archives)
11250 (setq scope (org-add-archive-files (list (buffer-file-name))))))
11251 (org-prepare-agenda-buffers scope)
11252 (while (setq file (pop scope))
11253 (with-current-buffer (org-find-base-buffer-visiting file)
11254 (save-excursion
11255 (save-restriction
11256 (widen)
11257 (goto-char (point-min))
11258 (setq res (append res (org-scan-tags func matcher))))))))))
11259 res))
11261 ;;;; Properties
11263 ;;; Setting and retrieving properties
11265 (defconst org-special-properties
11266 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
11267 "TIMESTAMP" "TIMESTAMP_IA")
11268 "The special properties valid in Org-mode.
11270 These are properties that are not defined in the property drawer,
11271 but in some other way.")
11273 (defconst org-default-properties
11274 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
11275 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
11276 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
11277 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
11278 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
11279 "CLOCK_MODELINE_TOTAL")
11280 "Some properties that are used by Org-mode for various purposes.
11281 Being in this list makes sure that they are offered for completion.")
11283 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
11284 "Regular expression matching the first line of a property drawer.")
11286 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
11287 "Regular expression matching the first line of a property drawer.")
11289 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
11290 "Regular expression matching the first line of a property drawer.")
11292 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
11293 "Regular expression matching the first line of a property drawer.")
11295 (defconst org-property-drawer-re
11296 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
11297 org-property-end-re "\\)\n?")
11298 "Matches an entire property drawer.")
11300 (defconst org-clock-drawer-re
11301 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
11302 org-property-end-re "\\)\n?")
11303 "Matches an entire clock drawer.")
11305 (defun org-property-action ()
11306 "Do an action on properties."
11307 (interactive)
11308 (let (c)
11309 (org-at-property-p)
11310 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
11311 (setq c (read-char-exclusive))
11312 (cond
11313 ((equal c ?s)
11314 (call-interactively 'org-set-property))
11315 ((equal c ?d)
11316 (call-interactively 'org-delete-property))
11317 ((equal c ?D)
11318 (call-interactively 'org-delete-property-globally))
11319 ((equal c ?c)
11320 (call-interactively 'org-compute-property-at-point))
11321 (t (error "No such property action %c" c)))))
11323 (defun org-at-property-p ()
11324 "Is the cursor in a property line?"
11325 ;; FIXME: Does not check if we are actually in the drawer.
11326 ;; FIXME: also returns true on any drawers.....
11327 ;; This is used by C-c C-c for property action.
11328 (save-excursion
11329 (beginning-of-line 1)
11330 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
11332 (defun org-get-property-block (&optional beg end force)
11333 "Return the (beg . end) range of the body of the property drawer.
11334 BEG and END can be beginning and end of subtree, if not given
11335 they will be found.
11336 If the drawer does not exist and FORCE is non-nil, create the drawer."
11337 (catch 'exit
11338 (save-excursion
11339 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
11340 (end (or end (progn (outline-next-heading) (point)))))
11341 (goto-char beg)
11342 (if (re-search-forward org-property-start-re end t)
11343 (setq beg (1+ (match-end 0)))
11344 (if force
11345 (save-excursion
11346 (org-insert-property-drawer)
11347 (setq end (progn (outline-next-heading) (point))))
11348 (throw 'exit nil))
11349 (goto-char beg)
11350 (if (re-search-forward org-property-start-re end t)
11351 (setq beg (1+ (match-end 0)))))
11352 (if (re-search-forward org-property-end-re end t)
11353 (setq end (match-beginning 0))
11354 (or force (throw 'exit nil))
11355 (goto-char beg)
11356 (setq end beg)
11357 (org-indent-line-function)
11358 (insert ":END:\n"))
11359 (cons beg end)))))
11361 (defun org-entry-properties (&optional pom which)
11362 "Get all properties of the entry at point-or-marker POM.
11363 This includes the TODO keyword, the tags, time strings for deadline,
11364 scheduled, and clocking, and any additional properties defined in the
11365 entry. The return value is an alist, keys may occur multiple times
11366 if the property key was used several times.
11367 POM may also be nil, in which case the current entry is used.
11368 If WHICH is nil or `all', get all properties. If WHICH is
11369 `special' or `standard', only get that subclass."
11370 (setq which (or which 'all))
11371 (org-with-point-at pom
11372 (let ((clockstr (substring org-clock-string 0 -1))
11373 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
11374 beg end range props sum-props key value string clocksum)
11375 (save-excursion
11376 (when (condition-case nil
11377 (and (org-mode-p) (org-back-to-heading t))
11378 (error nil))
11379 (setq beg (point))
11380 (setq sum-props (get-text-property (point) 'org-summaries))
11381 (setq clocksum (get-text-property (point) :org-clock-minutes))
11382 (outline-next-heading)
11383 (setq end (point))
11384 (when (memq which '(all special))
11385 ;; Get the special properties, like TODO and tags
11386 (goto-char beg)
11387 (when (and (looking-at org-todo-line-regexp) (match-end 2))
11388 (push (cons "TODO" (org-match-string-no-properties 2)) props))
11389 (when (looking-at org-priority-regexp)
11390 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
11391 (when (and (setq value (org-get-tags-string))
11392 (string-match "\\S-" value))
11393 (push (cons "TAGS" value) props))
11394 (when (setq value (org-get-tags-at))
11395 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
11396 props))
11397 (while (re-search-forward org-maybe-keyword-time-regexp end t)
11398 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
11399 string (if (equal key clockstr)
11400 (org-no-properties
11401 (org-trim
11402 (buffer-substring
11403 (match-beginning 3) (goto-char (point-at-eol)))))
11404 (substring (org-match-string-no-properties 3) 1 -1)))
11405 (unless key
11406 (if (= (char-after (match-beginning 3)) ?\[)
11407 (setq key "TIMESTAMP_IA")
11408 (setq key "TIMESTAMP")))
11409 (when (or (equal key clockstr) (not (assoc key props)))
11410 (push (cons key string) props)))
11414 (when (memq which '(all standard))
11415 ;; Get the standard properties, like :PROP: ...
11416 (setq range (org-get-property-block beg end))
11417 (when range
11418 (goto-char (car range))
11419 (while (re-search-forward
11420 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
11421 (cdr range) t)
11422 (setq key (org-match-string-no-properties 1)
11423 value (org-trim (or (org-match-string-no-properties 2) "")))
11424 (unless (member key excluded)
11425 (push (cons key (or value "")) props)))))
11426 (if clocksum
11427 (push (cons "CLOCKSUM"
11428 (org-columns-number-to-string (/ (float clocksum) 60.)
11429 'add_times))
11430 props))
11431 (unless (assoc "CATEGORY" props)
11432 (setq value (or (org-get-category)
11433 (progn (org-refresh-category-properties)
11434 (org-get-category))))
11435 (push (cons "CATEGORY" value) props))
11436 (append sum-props (nreverse props)))))))
11438 (defun org-entry-get (pom property &optional inherit)
11439 "Get value of PROPERTY for entry at point-or-marker POM.
11440 If INHERIT is non-nil and the entry does not have the property,
11441 then also check higher levels of the hierarchy.
11442 If INHERIT is the symbol `selective', use inheritance only if the setting
11443 in `org-use-property-inheritance' selects PROPERTY for inheritance.
11444 If the property is present but empty, the return value is the empty string.
11445 If the property is not present at all, nil is returned."
11446 (org-with-point-at pom
11447 (if (and inherit (if (eq inherit 'selective)
11448 (org-property-inherit-p property)
11450 (org-entry-get-with-inheritance property)
11451 (if (member property org-special-properties)
11452 ;; We need a special property. Use brute force, get all properties.
11453 (cdr (assoc property (org-entry-properties nil 'special)))
11454 (let ((range (org-get-property-block)))
11455 (if (and range
11456 (goto-char (car range))
11457 (re-search-forward
11458 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
11459 (cdr range) t))
11460 ;; Found the property, return it.
11461 (if (match-end 1)
11462 (org-match-string-no-properties 1)
11463 "")))))))
11465 (defun org-property-or-variable-value (var &optional inherit)
11466 "Check if there is a property fixing the value of VAR.
11467 If yes, return this value. If not, return the current value of the variable."
11468 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
11469 (if (and prop (stringp prop) (string-match "\\S-" prop))
11470 (read prop)
11471 (symbol-value var))))
11473 (defun org-entry-delete (pom property)
11474 "Delete the property PROPERTY from entry at point-or-marker POM."
11475 (org-with-point-at pom
11476 (if (member property org-special-properties)
11477 nil ; cannot delete these properties.
11478 (let ((range (org-get-property-block)))
11479 (if (and range
11480 (goto-char (car range))
11481 (re-search-forward
11482 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
11483 (cdr range) t))
11484 (progn
11485 (delete-region (match-beginning 0) (1+ (point-at-eol)))
11487 nil)))))
11489 ;; Multi-values properties are properties that contain multiple values
11490 ;; These values are assumed to be single words, separated by whitespace.
11491 (defun org-entry-add-to-multivalued-property (pom property value)
11492 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
11493 (let* ((old (org-entry-get pom property))
11494 (values (and old (org-split-string old "[ \t]"))))
11495 (setq value (org-entry-protect-space value))
11496 (unless (member value values)
11497 (setq values (cons value values))
11498 (org-entry-put pom property
11499 (mapconcat 'identity values " ")))))
11501 (defun org-entry-remove-from-multivalued-property (pom property value)
11502 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
11503 (let* ((old (org-entry-get pom property))
11504 (values (and old (org-split-string old "[ \t]"))))
11505 (setq value (org-entry-protect-space value))
11506 (when (member value values)
11507 (setq values (delete value values))
11508 (org-entry-put pom property
11509 (mapconcat 'identity values " ")))))
11511 (defun org-entry-member-in-multivalued-property (pom property value)
11512 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
11513 (let* ((old (org-entry-get pom property))
11514 (values (and old (org-split-string old "[ \t]"))))
11515 (setq value (org-entry-protect-space value))
11516 (member value values)))
11518 (defun org-entry-get-multivalued-property (pom property)
11519 "Return a list of values in a multivalued property."
11520 (let* ((value (org-entry-get pom property))
11521 (values (and value (org-split-string value "[ \t]"))))
11522 (mapcar 'org-entry-restore-space values)))
11524 (defun org-entry-put-multivalued-property (pom property &rest values)
11525 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
11526 VALUES should be a list of strings. Spaces will be protected."
11527 (org-entry-put pom property
11528 (mapconcat 'org-entry-protect-space values " "))
11529 (let* ((value (org-entry-get pom property))
11530 (values (and value (org-split-string value "[ \t]"))))
11531 (mapcar 'org-entry-restore-space values)))
11533 (defun org-entry-protect-space (s)
11534 "Protect spaces and newline in string S."
11535 (while (string-match " " s)
11536 (setq s (replace-match "%20" t t s)))
11537 (while (string-match "\n" s)
11538 (setq s (replace-match "%0A" t t s)))
11541 (defun org-entry-restore-space (s)
11542 "Restore spaces and newline in string S."
11543 (while (string-match "%20" s)
11544 (setq s (replace-match " " t t s)))
11545 (while (string-match "%0A" s)
11546 (setq s (replace-match "\n" t t s)))
11549 (defvar org-entry-property-inherited-from (make-marker)
11550 "Marker pointing to the entry from where a property was inherited.
11551 Each call to `org-entry-get-with-inheritance' will set this marker to the
11552 location of the entry where the inheritance search matched. If there was
11553 no match, the marker will point nowhere.
11554 Note that also `org-entry-get' calls this function, if the INHERIT flag
11555 is set.")
11557 (defun org-entry-get-with-inheritance (property)
11558 "Get entry property, and search higher levels if not present."
11559 (move-marker org-entry-property-inherited-from nil)
11560 (let (tmp)
11561 (save-excursion
11562 (save-restriction
11563 (widen)
11564 (catch 'ex
11565 (while t
11566 (when (setq tmp (org-entry-get nil property))
11567 (org-back-to-heading t)
11568 (move-marker org-entry-property-inherited-from (point))
11569 (throw 'ex tmp))
11570 (or (org-up-heading-safe) (throw 'ex nil)))))
11571 (or tmp
11572 (cdr (assoc property org-file-properties))
11573 (cdr (assoc property org-global-properties))
11574 (cdr (assoc property org-global-properties-fixed))))))
11576 (defun org-entry-put (pom property value)
11577 "Set PROPERTY to VALUE for entry at point-or-marker POM."
11578 (org-with-point-at pom
11579 (org-back-to-heading t)
11580 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
11581 range)
11582 (cond
11583 ((equal property "TODO")
11584 (when (and (stringp value) (string-match "\\S-" value)
11585 (not (member value org-todo-keywords-1)))
11586 (error "\"%s\" is not a valid TODO state" value))
11587 (if (or (not value)
11588 (not (string-match "\\S-" value)))
11589 (setq value 'none))
11590 (org-todo value)
11591 (org-set-tags nil 'align))
11592 ((equal property "PRIORITY")
11593 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
11594 (string-to-char value) ?\ ))
11595 (org-set-tags nil 'align))
11596 ((equal property "SCHEDULED")
11597 (if (re-search-forward org-scheduled-time-regexp end t)
11598 (cond
11599 ((eq value 'earlier) (org-timestamp-change -1 'day))
11600 ((eq value 'later) (org-timestamp-change 1 'day))
11601 (t (call-interactively 'org-schedule)))
11602 (call-interactively 'org-schedule)))
11603 ((equal property "DEADLINE")
11604 (if (re-search-forward org-deadline-time-regexp end t)
11605 (cond
11606 ((eq value 'earlier) (org-timestamp-change -1 'day))
11607 ((eq value 'later) (org-timestamp-change 1 'day))
11608 (t (call-interactively 'org-deadline)))
11609 (call-interactively 'org-deadline)))
11610 ((member property org-special-properties)
11611 (error "The %s property can not yet be set with `org-entry-put'"
11612 property))
11613 (t ; a non-special property
11614 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
11615 (setq range (org-get-property-block beg end 'force))
11616 (goto-char (car range))
11617 (if (re-search-forward
11618 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
11619 (progn
11620 (delete-region (match-beginning 1) (match-end 1))
11621 (goto-char (match-beginning 1)))
11622 (goto-char (cdr range))
11623 (insert "\n")
11624 (backward-char 1)
11625 (org-indent-line-function)
11626 (insert ":" property ":"))
11627 (and value (insert " " value))
11628 (org-indent-line-function)))))))
11630 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
11631 "Get all property keys in the current buffer.
11632 With INCLUDE-SPECIALS, also list the special properties that reflect things
11633 like tags and TODO state.
11634 With INCLUDE-DEFAULTS, also include properties that has special meaning
11635 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
11636 With INCLUDE-COLUMNS, also include property names given in COLUMN
11637 formats in the current buffer."
11638 (let (rtn range cfmt s p)
11639 (save-excursion
11640 (save-restriction
11641 (widen)
11642 (goto-char (point-min))
11643 (while (re-search-forward org-property-start-re nil t)
11644 (setq range (org-get-property-block))
11645 (goto-char (car range))
11646 (while (re-search-forward
11647 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
11648 (cdr range) t)
11649 (add-to-list 'rtn (org-match-string-no-properties 1)))
11650 (outline-next-heading))))
11652 (when include-specials
11653 (setq rtn (append org-special-properties rtn)))
11655 (when include-defaults
11656 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
11657 (add-to-list 'rtn org-effort-property))
11659 (when include-columns
11660 (save-excursion
11661 (save-restriction
11662 (widen)
11663 (goto-char (point-min))
11664 (while (re-search-forward
11665 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
11666 nil t)
11667 (setq cfmt (match-string 2) s 0)
11668 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
11669 cfmt s)
11670 (setq s (match-end 0)
11671 p (match-string 1 cfmt))
11672 (unless (or (equal p "ITEM")
11673 (member p org-special-properties))
11674 (add-to-list 'rtn (match-string 1 cfmt))))))))
11676 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
11678 (defun org-property-values (key)
11679 "Return a list of all values of property KEY."
11680 (save-excursion
11681 (save-restriction
11682 (widen)
11683 (goto-char (point-min))
11684 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
11685 values)
11686 (while (re-search-forward re nil t)
11687 (add-to-list 'values (org-trim (match-string 1))))
11688 (delete "" values)))))
11690 (defun org-insert-property-drawer ()
11691 "Insert a property drawer into the current entry."
11692 (interactive)
11693 (org-back-to-heading t)
11694 (looking-at outline-regexp)
11695 (let ((indent (if org-adapt-indentation
11696 (- (match-end 0)(match-beginning 0))
11698 (beg (point))
11699 (re (concat "^[ \t]*" org-keyword-time-regexp))
11700 end hiddenp)
11701 (outline-next-heading)
11702 (setq end (point))
11703 (goto-char beg)
11704 (while (re-search-forward re end t))
11705 (setq hiddenp (org-invisible-p))
11706 (end-of-line 1)
11707 (and (equal (char-after) ?\n) (forward-char 1))
11708 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
11709 (if (member (match-string 1) '("CLOCK:" ":END:"))
11710 ;; just skip this line
11711 (beginning-of-line 2)
11712 ;; Drawer start, find the end
11713 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
11714 (beginning-of-line 1)))
11715 (org-skip-over-state-notes)
11716 (skip-chars-backward " \t\n\r")
11717 (if (eq (char-before) ?*) (forward-char 1))
11718 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
11719 (beginning-of-line 0)
11720 (org-indent-to-column indent)
11721 (beginning-of-line 2)
11722 (org-indent-to-column indent)
11723 (beginning-of-line 0)
11724 (if hiddenp
11725 (save-excursion
11726 (org-back-to-heading t)
11727 (hide-entry))
11728 (org-flag-drawer t))))
11730 (defun org-set-property (property value)
11731 "In the current entry, set PROPERTY to VALUE.
11732 When called interactively, this will prompt for a property name, offering
11733 completion on existing and default properties. And then it will prompt
11734 for a value, offering completion either on allowed values (via an inherited
11735 xxx_ALL property) or on existing values in other instances of this property
11736 in the current file."
11737 (interactive
11738 (let* ((completion-ignore-case t)
11739 (keys (org-buffer-property-keys nil t t))
11740 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
11741 (prop (if (member prop0 keys)
11742 prop0
11743 (or (cdr (assoc (downcase prop0)
11744 (mapcar (lambda (x) (cons (downcase x) x))
11745 keys)))
11746 prop0)))
11747 (cur (org-entry-get nil prop))
11748 (allowed (org-property-get-allowed-values nil prop 'table))
11749 (existing (mapcar 'list (org-property-values prop)))
11750 (val (if allowed
11751 (org-completing-read "Value: " allowed nil 'req-match)
11752 (let (org-completion-use-ido)
11753 (org-completing-read
11754 (concat "Value" (if (and cur (string-match "\\S-" cur))
11755 (concat "[" cur "]") "")
11756 ": ")
11757 existing nil nil "" nil cur)))))
11758 (list prop (if (equal val "") cur val))))
11759 (unless (equal (org-entry-get nil property) value)
11760 (org-entry-put nil property value)))
11762 (defun org-delete-property (property)
11763 "In the current entry, delete PROPERTY."
11764 (interactive
11765 (let* ((completion-ignore-case t)
11766 (prop (org-ido-completing-read
11767 "Property: " (org-entry-properties nil 'standard))))
11768 (list prop)))
11769 (message "Property %s %s" property
11770 (if (org-entry-delete nil property)
11771 "deleted"
11772 "was not present in the entry")))
11774 (defun org-delete-property-globally (property)
11775 "Remove PROPERTY globally, from all entries."
11776 (interactive
11777 (let* ((completion-ignore-case t)
11778 (prop (org-ido-completing-read
11779 "Globally remove property: "
11780 (mapcar 'list (org-buffer-property-keys)))))
11781 (list prop)))
11782 (save-excursion
11783 (save-restriction
11784 (widen)
11785 (goto-char (point-min))
11786 (let ((cnt 0))
11787 (while (re-search-forward
11788 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
11789 nil t)
11790 (setq cnt (1+ cnt))
11791 (replace-match ""))
11792 (message "Property \"%s\" removed from %d entries" property cnt)))))
11794 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
11796 (defun org-compute-property-at-point ()
11797 "Compute the property at point.
11798 This looks for an enclosing column format, extracts the operator and
11799 then applies it to the property in the column format's scope."
11800 (interactive)
11801 (unless (org-at-property-p)
11802 (error "Not at a property"))
11803 (let ((prop (org-match-string-no-properties 2)))
11804 (org-columns-get-format-and-top-level)
11805 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
11806 (error "No operator defined for property %s" prop))
11807 (org-columns-compute prop)))
11809 (defun org-property-get-allowed-values (pom property &optional table)
11810 "Get allowed values for the property PROPERTY.
11811 When TABLE is non-nil, return an alist that can directly be used for
11812 completion."
11813 (let (vals)
11814 (cond
11815 ((equal property "TODO")
11816 (setq vals (org-with-point-at pom
11817 (append org-todo-keywords-1 '("")))))
11818 ((equal property "PRIORITY")
11819 (let ((n org-lowest-priority))
11820 (while (>= n org-highest-priority)
11821 (push (char-to-string n) vals)
11822 (setq n (1- n)))))
11823 ((member property org-special-properties))
11825 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
11827 (when (and vals (string-match "\\S-" vals))
11828 (setq vals (car (read-from-string (concat "(" vals ")"))))
11829 (setq vals (mapcar (lambda (x)
11830 (cond ((stringp x) x)
11831 ((numberp x) (number-to-string x))
11832 ((symbolp x) (symbol-name x))
11833 (t "???")))
11834 vals)))))
11835 (if table (mapcar 'list vals) vals)))
11837 (defun org-property-previous-allowed-value (&optional previous)
11838 "Switch to the next allowed value for this property."
11839 (interactive)
11840 (org-property-next-allowed-value t))
11842 (defun org-property-next-allowed-value (&optional previous)
11843 "Switch to the next allowed value for this property."
11844 (interactive)
11845 (unless (org-at-property-p)
11846 (error "Not at a property"))
11847 (let* ((key (match-string 2))
11848 (value (match-string 3))
11849 (allowed (or (org-property-get-allowed-values (point) key)
11850 (and (member value '("[ ]" "[-]" "[X]"))
11851 '("[ ]" "[X]"))))
11852 nval)
11853 (unless allowed
11854 (error "Allowed values for this property have not been defined"))
11855 (if previous (setq allowed (reverse allowed)))
11856 (if (member value allowed)
11857 (setq nval (car (cdr (member value allowed)))))
11858 (setq nval (or nval (car allowed)))
11859 (if (equal nval value)
11860 (error "Only one allowed value for this property"))
11861 (org-at-property-p)
11862 (replace-match (concat " :" key ": " nval) t t)
11863 (org-indent-line-function)
11864 (beginning-of-line 1)
11865 (skip-chars-forward " \t")))
11867 (defun org-find-entry-with-id (ident)
11868 "Locate the entry that contains the ID property with exact value IDENT.
11869 IDENT can be a string, a symbol or a number, this function will search for
11870 the string representation of it.
11871 Return the position where this entry starts, or nil if there is no such entry."
11872 (interactive "sID: ")
11873 (let ((id (cond
11874 ((stringp ident) ident)
11875 ((symbol-name ident) (symbol-name ident))
11876 ((numberp ident) (number-to-string ident))
11877 (t (error "IDENT %s must be a string, symbol or number" ident))))
11878 (case-fold-search nil))
11879 (save-excursion
11880 (save-restriction
11881 (widen)
11882 (goto-char (point-min))
11883 (when (re-search-forward
11884 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
11885 nil t)
11886 (org-back-to-heading)
11887 (point))))))
11889 ;;;; Timestamps
11891 (defvar org-last-changed-timestamp nil)
11892 (defvar org-last-inserted-timestamp nil
11893 "The last time stamp inserted with `org-insert-time-stamp'.")
11894 (defvar org-time-was-given) ; dynamically scoped parameter
11895 (defvar org-end-time-was-given) ; dynamically scoped parameter
11896 (defvar org-ts-what) ; dynamically scoped parameter
11898 (defun org-time-stamp (arg &optional inactive)
11899 "Prompt for a date/time and insert a time stamp.
11900 If the user specifies a time like HH:MM, or if this command is called
11901 with a prefix argument, the time stamp will contain date and time.
11902 Otherwise, only the date will be included. All parts of a date not
11903 specified by the user will be filled in from the current date/time.
11904 So if you press just return without typing anything, the time stamp
11905 will represent the current date/time. If there is already a timestamp
11906 at the cursor, it will be modified."
11907 (interactive "P")
11908 (let* ((ts nil)
11909 (default-time
11910 ;; Default time is either today, or, when entering a range,
11911 ;; the range start.
11912 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
11913 (save-excursion
11914 (re-search-backward
11915 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
11916 (- (point) 20) t)))
11917 (apply 'encode-time (org-parse-time-string (match-string 1)))
11918 (current-time)))
11919 (default-input (and ts (org-get-compact-tod ts)))
11920 org-time-was-given org-end-time-was-given time)
11921 (cond
11922 ((and (org-at-timestamp-p t)
11923 (memq last-command '(org-time-stamp org-time-stamp-inactive))
11924 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
11925 (insert "--")
11926 (setq time (let ((this-command this-command))
11927 (org-read-date arg 'totime nil nil
11928 default-time default-input)))
11929 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
11930 ((org-at-timestamp-p t)
11931 (setq time (let ((this-command this-command))
11932 (org-read-date arg 'totime nil nil default-time default-input)))
11933 (when (org-at-timestamp-p t) ; just to get the match data
11934 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
11935 (replace-match "")
11936 (setq org-last-changed-timestamp
11937 (org-insert-time-stamp
11938 time (or org-time-was-given arg)
11939 inactive nil nil (list org-end-time-was-given))))
11940 (message "Timestamp updated"))
11942 (setq time (let ((this-command this-command))
11943 (org-read-date arg 'totime nil nil default-time default-input)))
11944 (org-insert-time-stamp time (or org-time-was-given arg) inactive
11945 nil nil (list org-end-time-was-given))))))
11947 ;; FIXME: can we use this for something else, like computing time differences?
11948 (defun org-get-compact-tod (s)
11949 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
11950 (let* ((t1 (match-string 1 s))
11951 (h1 (string-to-number (match-string 2 s)))
11952 (m1 (string-to-number (match-string 3 s)))
11953 (t2 (and (match-end 4) (match-string 5 s)))
11954 (h2 (and t2 (string-to-number (match-string 6 s))))
11955 (m2 (and t2 (string-to-number (match-string 7 s))))
11956 dh dm)
11957 (if (not t2)
11959 (setq dh (- h2 h1) dm (- m2 m1))
11960 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
11961 (concat t1 "+" (number-to-string dh)
11962 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
11964 (defun org-time-stamp-inactive (&optional arg)
11965 "Insert an inactive time stamp.
11966 An inactive time stamp is enclosed in square brackets instead of angle
11967 brackets. It is inactive in the sense that it does not trigger agenda entries,
11968 does not link to the calendar and cannot be changed with the S-cursor keys.
11969 So these are more for recording a certain time/date."
11970 (interactive "P")
11971 (org-time-stamp arg 'inactive))
11973 (defvar org-date-ovl (org-make-overlay 1 1))
11974 (org-overlay-put org-date-ovl 'face 'org-warning)
11975 (org-detach-overlay org-date-ovl)
11977 (defvar org-ans1) ; dynamically scoped parameter
11978 (defvar org-ans2) ; dynamically scoped parameter
11980 (defvar org-plain-time-of-day-regexp) ; defined below
11982 (defvar org-overriding-default-time nil) ; dynamically scoped
11983 (defvar org-read-date-overlay nil)
11984 (defvar org-dcst nil) ; dynamically scoped
11985 (defvar org-read-date-history nil)
11987 (defun org-read-date (&optional with-time to-time from-string prompt
11988 default-time default-input)
11989 "Read a date, possibly a time, and make things smooth for the user.
11990 The prompt will suggest to enter an ISO date, but you can also enter anything
11991 which will at least partially be understood by `parse-time-string'.
11992 Unrecognized parts of the date will default to the current day, month, year,
11993 hour and minute. If this command is called to replace a timestamp at point,
11994 of to enter the second timestamp of a range, the default time is taken from the
11995 existing stamp. For example,
11996 3-2-5 --> 2003-02-05
11997 feb 15 --> currentyear-02-15
11998 sep 12 9 --> 2009-09-12
11999 12:45 --> today 12:45
12000 22 sept 0:34 --> currentyear-09-22 0:34
12001 12 --> currentyear-currentmonth-12
12002 Fri --> nearest Friday (today or later)
12003 etc.
12005 Furthermore you can specify a relative date by giving, as the *first* thing
12006 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
12007 change in days weeks, months, years.
12008 With a single plus or minus, the date is relative to today. With a double
12009 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
12010 +4d --> four days from today
12011 +4 --> same as above
12012 +2w --> two weeks from today
12013 ++5 --> five days from default date
12015 The function understands only English month and weekday abbreviations,
12016 but this can be configured with the variables `parse-time-months' and
12017 `parse-time-weekdays'.
12019 While prompting, a calendar is popped up - you can also select the
12020 date with the mouse (button 1). The calendar shows a period of three
12021 months. To scroll it to other months, use the keys `>' and `<'.
12022 If you don't like the calendar, turn it off with
12023 \(setq org-read-date-popup-calendar nil)
12025 With optional argument TO-TIME, the date will immediately be converted
12026 to an internal time.
12027 With an optional argument WITH-TIME, the prompt will suggest to also
12028 insert a time. Note that when WITH-TIME is not set, you can still
12029 enter a time, and this function will inform the calling routine about
12030 this change. The calling routine may then choose to change the format
12031 used to insert the time stamp into the buffer to include the time.
12032 With optional argument FROM-STRING, read from this string instead from
12033 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
12034 the time/date that is used for everything that is not specified by the
12035 user."
12036 (require 'parse-time)
12037 (let* ((org-time-stamp-rounding-minutes
12038 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
12039 (org-dcst org-display-custom-times)
12040 (ct (org-current-time))
12041 (def (or org-overriding-default-time default-time ct))
12042 (defdecode (decode-time def))
12043 (dummy (progn
12044 (when (< (nth 2 defdecode) org-extend-today-until)
12045 (setcar (nthcdr 2 defdecode) -1)
12046 (setcar (nthcdr 1 defdecode) 59)
12047 (setq def (apply 'encode-time defdecode)
12048 defdecode (decode-time def)))))
12049 (calendar-move-hook nil)
12050 (calendar-view-diary-initially-flag nil)
12051 (view-diary-entries-initially nil)
12052 (calendar-view-holidays-initially-flag nil)
12053 (view-calendar-holidays-initially nil)
12054 (timestr (format-time-string
12055 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
12056 (prompt (concat (if prompt (concat prompt " ") "")
12057 (format "Date+time [%s]: " timestr)))
12058 ans (org-ans0 "") org-ans1 org-ans2 final)
12060 (cond
12061 (from-string (setq ans from-string))
12062 (org-read-date-popup-calendar
12063 (save-excursion
12064 (save-window-excursion
12065 (calendar)
12066 (calendar-forward-day (- (time-to-days def)
12067 (calendar-absolute-from-gregorian
12068 (calendar-current-date))))
12069 (org-eval-in-calendar nil t)
12070 (let* ((old-map (current-local-map))
12071 (map (copy-keymap calendar-mode-map))
12072 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12073 (org-defkey map (kbd "RET") 'org-calendar-select)
12074 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
12075 'org-calendar-select-mouse)
12076 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
12077 'org-calendar-select-mouse)
12078 (org-defkey minibuffer-local-map [(meta shift left)]
12079 (lambda () (interactive)
12080 (org-eval-in-calendar '(calendar-backward-month 1))))
12081 (org-defkey minibuffer-local-map [(meta shift right)]
12082 (lambda () (interactive)
12083 (org-eval-in-calendar '(calendar-forward-month 1))))
12084 (org-defkey minibuffer-local-map [(meta shift up)]
12085 (lambda () (interactive)
12086 (org-eval-in-calendar '(calendar-backward-year 1))))
12087 (org-defkey minibuffer-local-map [(meta shift down)]
12088 (lambda () (interactive)
12089 (org-eval-in-calendar '(calendar-forward-year 1))))
12090 (org-defkey minibuffer-local-map [?\e (shift left)]
12091 (lambda () (interactive)
12092 (org-eval-in-calendar '(calendar-backward-month 1))))
12093 (org-defkey minibuffer-local-map [?\e (shift right)]
12094 (lambda () (interactive)
12095 (org-eval-in-calendar '(calendar-forward-month 1))))
12096 (org-defkey minibuffer-local-map [?\e (shift up)]
12097 (lambda () (interactive)
12098 (org-eval-in-calendar '(calendar-backward-year 1))))
12099 (org-defkey minibuffer-local-map [?\e (shift down)]
12100 (lambda () (interactive)
12101 (org-eval-in-calendar '(calendar-forward-year 1))))
12102 (org-defkey minibuffer-local-map [(shift up)]
12103 (lambda () (interactive)
12104 (org-eval-in-calendar '(calendar-backward-week 1))))
12105 (org-defkey minibuffer-local-map [(shift down)]
12106 (lambda () (interactive)
12107 (org-eval-in-calendar '(calendar-forward-week 1))))
12108 (org-defkey minibuffer-local-map [(shift left)]
12109 (lambda () (interactive)
12110 (org-eval-in-calendar '(calendar-backward-day 1))))
12111 (org-defkey minibuffer-local-map [(shift right)]
12112 (lambda () (interactive)
12113 (org-eval-in-calendar '(calendar-forward-day 1))))
12114 (org-defkey minibuffer-local-map ">"
12115 (lambda () (interactive)
12116 (org-eval-in-calendar '(scroll-calendar-left 1))))
12117 (org-defkey minibuffer-local-map "<"
12118 (lambda () (interactive)
12119 (org-eval-in-calendar '(scroll-calendar-right 1))))
12120 (run-hooks 'org-read-date-minibuffer-setup-hook)
12121 (unwind-protect
12122 (progn
12123 (use-local-map map)
12124 (add-hook 'post-command-hook 'org-read-date-display)
12125 (setq org-ans0 (read-string prompt default-input
12126 'org-read-date-history nil))
12127 ;; org-ans0: from prompt
12128 ;; org-ans1: from mouse click
12129 ;; org-ans2: from calendar motion
12130 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
12131 (remove-hook 'post-command-hook 'org-read-date-display)
12132 (use-local-map old-map)
12133 (when org-read-date-overlay
12134 (org-delete-overlay org-read-date-overlay)
12135 (setq org-read-date-overlay nil)))))))
12137 (t ; Naked prompt only
12138 (unwind-protect
12139 (setq ans (read-string prompt default-input
12140 'org-read-date-history timestr))
12141 (when org-read-date-overlay
12142 (org-delete-overlay org-read-date-overlay)
12143 (setq org-read-date-overlay nil)))))
12145 (setq final (org-read-date-analyze ans def defdecode))
12147 (if to-time
12148 (apply 'encode-time final)
12149 (if (and (boundp 'org-time-was-given) org-time-was-given)
12150 (format "%04d-%02d-%02d %02d:%02d"
12151 (nth 5 final) (nth 4 final) (nth 3 final)
12152 (nth 2 final) (nth 1 final))
12153 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
12154 (defvar def)
12155 (defvar defdecode)
12156 (defvar with-time)
12157 (defun org-read-date-display ()
12158 "Display the current date prompt interpretation in the minibuffer."
12159 (when org-read-date-display-live
12160 (when org-read-date-overlay
12161 (org-delete-overlay org-read-date-overlay))
12162 (let ((p (point)))
12163 (end-of-line 1)
12164 (while (not (equal (buffer-substring
12165 (max (point-min) (- (point) 4)) (point))
12166 " "))
12167 (insert " "))
12168 (goto-char p))
12169 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
12170 " " (or org-ans1 org-ans2)))
12171 (org-end-time-was-given nil)
12172 (f (org-read-date-analyze ans def defdecode))
12173 (fmts (if org-dcst
12174 org-time-stamp-custom-formats
12175 org-time-stamp-formats))
12176 (fmt (if (or with-time
12177 (and (boundp 'org-time-was-given) org-time-was-given))
12178 (cdr fmts)
12179 (car fmts)))
12180 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
12181 (when (and org-end-time-was-given
12182 (string-match org-plain-time-of-day-regexp txt))
12183 (setq txt (concat (substring txt 0 (match-end 0)) "-"
12184 org-end-time-was-given
12185 (substring txt (match-end 0)))))
12186 (setq org-read-date-overlay
12187 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
12188 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
12190 (defun org-read-date-analyze (ans def defdecode)
12191 "Analyse the combined answer of the date prompt."
12192 ;; FIXME: cleanup and comment
12193 (let (delta deltan deltaw deltadef year month day
12194 hour minute second wday pm h2 m2 tl wday1
12195 iso-year iso-weekday iso-week iso-year iso-date)
12197 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
12198 (setq ans "+0"))
12200 (when (setq delta (org-read-date-get-relative ans (current-time) def))
12201 (setq ans (replace-match "" t t ans)
12202 deltan (car delta)
12203 deltaw (nth 1 delta)
12204 deltadef (nth 2 delta)))
12206 ;; Check if there is an iso week date in there
12207 ;; If yes, sore the info and postpone interpreting it until the rest
12208 ;; of the parsing is done
12209 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
12210 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
12211 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
12212 iso-week (string-to-number (match-string 2 ans)))
12213 (setq ans (replace-match "" t t ans)))
12215 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
12216 (when (string-match
12217 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
12218 (setq year (if (match-end 2)
12219 (string-to-number (match-string 2 ans))
12220 (string-to-number (format-time-string "%Y")))
12221 month (string-to-number (match-string 3 ans))
12222 day (string-to-number (match-string 4 ans)))
12223 (if (< year 100) (setq year (+ 2000 year)))
12224 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
12225 t nil ans)))
12226 ;; Help matching am/pm times, because `parse-time-string' does not do that.
12227 ;; If there is a time with am/pm, and *no* time without it, we convert
12228 ;; so that matching will be successful.
12229 (loop for i from 1 to 2 do ; twice, for end time as well
12230 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
12231 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
12232 (setq hour (string-to-number (match-string 1 ans))
12233 minute (if (match-end 3)
12234 (string-to-number (match-string 3 ans))
12236 pm (equal ?p
12237 (string-to-char (downcase (match-string 4 ans)))))
12238 (if (and (= hour 12) (not pm))
12239 (setq hour 0)
12240 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
12241 (setq ans (replace-match (format "%02d:%02d" hour minute)
12242 t t ans))))
12244 ;; Check if a time range is given as a duration
12245 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
12246 (setq hour (string-to-number (match-string 1 ans))
12247 h2 (+ hour (string-to-number (match-string 3 ans)))
12248 minute (string-to-number (match-string 2 ans))
12249 m2 (+ minute (if (match-end 5) (string-to-number
12250 (match-string 5 ans))0)))
12251 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
12252 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
12253 t t ans)))
12255 ;; Check if there is a time range
12256 (when (boundp 'org-end-time-was-given)
12257 (setq org-time-was-given nil)
12258 (when (and (string-match org-plain-time-of-day-regexp ans)
12259 (match-end 8))
12260 (setq org-end-time-was-given (match-string 8 ans))
12261 (setq ans (concat (substring ans 0 (match-beginning 7))
12262 (substring ans (match-end 7))))))
12264 (setq tl (parse-time-string ans)
12265 day (or (nth 3 tl) (nth 3 defdecode))
12266 month (or (nth 4 tl)
12267 (if (and org-read-date-prefer-future
12268 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
12269 (1+ (nth 4 defdecode))
12270 (nth 4 defdecode)))
12271 year (or (nth 5 tl)
12272 (if (and org-read-date-prefer-future
12273 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
12274 (1+ (nth 5 defdecode))
12275 (nth 5 defdecode)))
12276 hour (or (nth 2 tl) (nth 2 defdecode))
12277 minute (or (nth 1 tl) (nth 1 defdecode))
12278 second (or (nth 0 tl) 0)
12279 wday (nth 6 tl))
12281 ;; Special date definitions below
12282 (cond
12283 (iso-week
12284 ;; There was an iso week
12285 (setq year (or iso-year year)
12286 day (or iso-weekday wday 1)
12287 wday nil ; to make sure that the trigger below does not match
12288 iso-date (calendar-gregorian-from-absolute
12289 (calendar-absolute-from-iso
12290 (list iso-week day year))))
12291 ; FIXME: Should we also push ISO weeks into the future?
12292 ; (when (and org-read-date-prefer-future
12293 ; (not iso-year)
12294 ; (< (calendar-absolute-from-gregorian iso-date)
12295 ; (time-to-days (current-time))))
12296 ; (setq year (1+ year)
12297 ; iso-date (calendar-gregorian-from-absolute
12298 ; (calendar-absolute-from-iso
12299 ; (list iso-week day year)))))
12300 (setq month (car iso-date)
12301 year (nth 2 iso-date)
12302 day (nth 1 iso-date)))
12303 (deltan
12304 (unless deltadef
12305 (let ((now (decode-time (current-time))))
12306 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
12307 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
12308 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
12309 ((equal deltaw "m") (setq month (+ month deltan)))
12310 ((equal deltaw "y") (setq year (+ year deltan)))))
12311 ((and wday (not (nth 3 tl)))
12312 ;; Weekday was given, but no day, so pick that day in the week
12313 ;; on or after the derived date.
12314 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
12315 (unless (equal wday wday1)
12316 (setq day (+ day (% (- wday wday1 -7) 7))))))
12317 (if (and (boundp 'org-time-was-given)
12318 (nth 2 tl))
12319 (setq org-time-was-given t))
12320 (if (< year 100) (setq year (+ 2000 year)))
12321 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
12322 (list second minute hour day month year)))
12324 (defvar parse-time-weekdays)
12326 (defun org-read-date-get-relative (s today default)
12327 "Check string S for special relative date string.
12328 TODAY and DEFAULT are internal times, for today and for a default.
12329 Return shift list (N what def-flag)
12330 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
12331 N is the number of WHATs to shift.
12332 DEF-FLAG is t when a double ++ or -- indicates shift relative to
12333 the DEFAULT date rather than TODAY."
12334 (when (and
12335 (string-match
12336 (concat
12337 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
12338 "\\([0-9]+\\)?"
12339 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
12340 "\\([ \t]\\|$\\)") s)
12341 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
12342 (let* ((dir (if (> (match-end 1) (match-beginning 1))
12343 (string-to-char (substring (match-string 1 s) -1))
12344 ?+))
12345 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
12346 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
12347 (what (if (match-end 3) (match-string 3 s) "d"))
12348 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
12349 (date (if rel default today))
12350 (wday (nth 6 (decode-time date)))
12351 delta)
12352 (if wday1
12353 (progn
12354 (setq delta (mod (+ 7 (- wday1 wday)) 7))
12355 (if (= dir ?-) (setq delta (- delta 7)))
12356 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
12357 (list delta "d" rel))
12358 (list (* n (if (= dir ?-) -1 1)) what rel)))))
12360 (defun org-eval-in-calendar (form &optional keepdate)
12361 "Eval FORM in the calendar window and return to current window.
12362 Also, store the cursor date in variable org-ans2."
12363 (let ((sw (selected-window)))
12364 (select-window (get-buffer-window "*Calendar*"))
12365 (eval form)
12366 (when (and (not keepdate) (calendar-cursor-to-date))
12367 (let* ((date (calendar-cursor-to-date))
12368 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12369 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
12370 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
12371 (select-window sw)))
12373 (defun org-calendar-select ()
12374 "Return to `org-read-date' with the date currently selected.
12375 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12376 (interactive)
12377 (when (calendar-cursor-to-date)
12378 (let* ((date (calendar-cursor-to-date))
12379 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12380 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12381 (if (active-minibuffer-window) (exit-minibuffer))))
12383 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
12384 "Insert a date stamp for the date given by the internal TIME.
12385 WITH-HM means, use the stamp format that includes the time of the day.
12386 INACTIVE means use square brackets instead of angular ones, so that the
12387 stamp will not contribute to the agenda.
12388 PRE and POST are optional strings to be inserted before and after the
12389 stamp.
12390 The command returns the inserted time stamp."
12391 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
12392 stamp)
12393 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
12394 (insert-before-markers (or pre ""))
12395 (insert-before-markers (setq stamp (format-time-string fmt time)))
12396 (when (listp extra)
12397 (setq extra (car extra))
12398 (if (and (stringp extra)
12399 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
12400 (setq extra (format "-%02d:%02d"
12401 (string-to-number (match-string 1 extra))
12402 (string-to-number (match-string 2 extra))))
12403 (setq extra nil)))
12404 (when extra
12405 (backward-char 1)
12406 (insert-before-markers extra)
12407 (forward-char 1))
12408 (insert-before-markers (or post ""))
12409 (setq org-last-inserted-timestamp stamp)))
12411 (defun org-toggle-time-stamp-overlays ()
12412 "Toggle the use of custom time stamp formats."
12413 (interactive)
12414 (setq org-display-custom-times (not org-display-custom-times))
12415 (unless org-display-custom-times
12416 (let ((p (point-min)) (bmp (buffer-modified-p)))
12417 (while (setq p (next-single-property-change p 'display))
12418 (if (and (get-text-property p 'display)
12419 (eq (get-text-property p 'face) 'org-date))
12420 (remove-text-properties
12421 p (setq p (next-single-property-change p 'display))
12422 '(display t))))
12423 (set-buffer-modified-p bmp)))
12424 (if (featurep 'xemacs)
12425 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12426 (org-restart-font-lock)
12427 (setq org-table-may-need-update t)
12428 (if org-display-custom-times
12429 (message "Time stamps are overlayed with custom format")
12430 (message "Time stamp overlays removed")))
12432 (defun org-display-custom-time (beg end)
12433 "Overlay modified time stamp format over timestamp between BEG and END."
12434 (let* ((ts (buffer-substring beg end))
12435 t1 w1 with-hm tf time str w2 (off 0))
12436 (save-match-data
12437 (setq t1 (org-parse-time-string ts t))
12438 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
12439 (setq off (- (match-end 0) (match-beginning 0)))))
12440 (setq end (- end off))
12441 (setq w1 (- end beg)
12442 with-hm (and (nth 1 t1) (nth 2 t1))
12443 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
12444 time (org-fix-decoded-time t1)
12445 str (org-add-props
12446 (format-time-string
12447 (substring tf 1 -1) (apply 'encode-time time))
12448 nil 'mouse-face 'highlight)
12449 w2 (length str))
12450 (if (not (= w2 w1))
12451 (add-text-properties (1+ beg) (+ 2 beg)
12452 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12453 (if (featurep 'xemacs)
12454 (progn
12455 (put-text-property beg end 'invisible t)
12456 (put-text-property beg end 'end-glyph (make-glyph str)))
12457 (put-text-property beg end 'display str))))
12459 (defun org-translate-time (string)
12460 "Translate all timestamps in STRING to custom format.
12461 But do this only if the variable `org-display-custom-times' is set."
12462 (when org-display-custom-times
12463 (save-match-data
12464 (let* ((start 0)
12465 (re org-ts-regexp-both)
12466 t1 with-hm inactive tf time str beg end)
12467 (while (setq start (string-match re string start))
12468 (setq beg (match-beginning 0)
12469 end (match-end 0)
12470 t1 (save-match-data
12471 (org-parse-time-string (substring string beg end) t))
12472 with-hm (and (nth 1 t1) (nth 2 t1))
12473 inactive (equal (substring string beg (1+ beg)) "[")
12474 tf (funcall (if with-hm 'cdr 'car)
12475 org-time-stamp-custom-formats)
12476 time (org-fix-decoded-time t1)
12477 str (format-time-string
12478 (concat
12479 (if inactive "[" "<") (substring tf 1 -1)
12480 (if inactive "]" ">"))
12481 (apply 'encode-time time))
12482 string (replace-match str t t string)
12483 start (+ start (length str)))))))
12484 string)
12486 (defun org-fix-decoded-time (time)
12487 "Set 0 instead of nil for the first 6 elements of time.
12488 Don't touch the rest."
12489 (let ((n 0))
12490 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12492 (defun org-days-to-time (timestamp-string)
12493 "Difference between TIMESTAMP-STRING and now in days."
12494 (- (time-to-days (org-time-string-to-time timestamp-string))
12495 (time-to-days (current-time))))
12497 (defun org-deadline-close (timestamp-string &optional ndays)
12498 "Is the time in TIMESTAMP-STRING close to the current date?"
12499 (setq ndays (or ndays (org-get-wdays timestamp-string)))
12500 (and (< (org-days-to-time timestamp-string) ndays)
12501 (not (org-entry-is-done-p))))
12503 (defun org-get-wdays (ts)
12504 "Get the deadline lead time appropriate for timestring TS."
12505 (cond
12506 ((<= org-deadline-warning-days 0)
12507 ;; 0 or negative, enforce this value no matter what
12508 (- org-deadline-warning-days))
12509 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
12510 ;; lead time is specified.
12511 (floor (* (string-to-number (match-string 1 ts))
12512 (cdr (assoc (match-string 2 ts)
12513 '(("d" . 1) ("w" . 7)
12514 ("m" . 30.4) ("y" . 365.25)))))))
12515 ;; go for the default.
12516 (t org-deadline-warning-days)))
12518 (defun org-calendar-select-mouse (ev)
12519 "Return to `org-read-date' with the date currently selected.
12520 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12521 (interactive "e")
12522 (mouse-set-point ev)
12523 (when (calendar-cursor-to-date)
12524 (let* ((date (calendar-cursor-to-date))
12525 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12526 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12527 (if (active-minibuffer-window) (exit-minibuffer))))
12529 (defun org-check-deadlines (ndays)
12530 "Check if there are any deadlines due or past due.
12531 A deadline is considered due if it happens within `org-deadline-warning-days'
12532 days from today's date. If the deadline appears in an entry marked DONE,
12533 it is not shown. The prefix arg NDAYS can be used to test that many
12534 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12535 (interactive "P")
12536 (let* ((org-warn-days
12537 (cond
12538 ((equal ndays '(4)) 100000)
12539 (ndays (prefix-numeric-value ndays))
12540 (t (abs org-deadline-warning-days))))
12541 (case-fold-search nil)
12542 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12543 (callback
12544 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12546 (message "%d deadlines past-due or due within %d days"
12547 (org-occur regexp nil callback)
12548 org-warn-days)))
12550 (defun org-check-before-date (date)
12551 "Check if there are deadlines or scheduled entries before DATE."
12552 (interactive (list (org-read-date)))
12553 (let ((case-fold-search nil)
12554 (regexp (concat "\\<\\(" org-deadline-string
12555 "\\|" org-scheduled-string
12556 "\\) *<\\([^>]+\\)>"))
12557 (callback
12558 (lambda () (time-less-p
12559 (org-time-string-to-time (match-string 2))
12560 (org-time-string-to-time date)))))
12561 (message "%d entries before %s"
12562 (org-occur regexp nil callback) date)))
12564 (defun org-check-after-date (date)
12565 "Check if there are deadlines or scheduled entries after DATE."
12566 (interactive (list (org-read-date)))
12567 (let ((case-fold-search nil)
12568 (regexp (concat "\\<\\(" org-deadline-string
12569 "\\|" org-scheduled-string
12570 "\\) *<\\([^>]+\\)>"))
12571 (callback
12572 (lambda () (not
12573 (time-less-p
12574 (org-time-string-to-time (match-string 2))
12575 (org-time-string-to-time date))))))
12576 (message "%d entries after %s"
12577 (org-occur regexp nil callback) date)))
12579 (defun org-evaluate-time-range (&optional to-buffer)
12580 "Evaluate a time range by computing the difference between start and end.
12581 Normally the result is just printed in the echo area, but with prefix arg
12582 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12583 If the time range is actually in a table, the result is inserted into the
12584 next column.
12585 For time difference computation, a year is assumed to be exactly 365
12586 days in order to avoid rounding problems."
12587 (interactive "P")
12589 (org-clock-update-time-maybe)
12590 (save-excursion
12591 (unless (org-at-date-range-p t)
12592 (goto-char (point-at-bol))
12593 (re-search-forward org-tr-regexp-both (point-at-eol) t))
12594 (if (not (org-at-date-range-p t))
12595 (error "Not at a time-stamp range, and none found in current line")))
12596 (let* ((ts1 (match-string 1))
12597 (ts2 (match-string 2))
12598 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12599 (match-end (match-end 0))
12600 (time1 (org-time-string-to-time ts1))
12601 (time2 (org-time-string-to-time ts2))
12602 (t1 (time-to-seconds time1))
12603 (t2 (time-to-seconds time2))
12604 (diff (abs (- t2 t1)))
12605 (negative (< (- t2 t1) 0))
12606 ;; (ys (floor (* 365 24 60 60)))
12607 (ds (* 24 60 60))
12608 (hs (* 60 60))
12609 (fy "%dy %dd %02d:%02d")
12610 (fy1 "%dy %dd")
12611 (fd "%dd %02d:%02d")
12612 (fd1 "%dd")
12613 (fh "%02d:%02d")
12614 y d h m align)
12615 (if havetime
12616 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12618 d (floor (/ diff ds)) diff (mod diff ds)
12619 h (floor (/ diff hs)) diff (mod diff hs)
12620 m (floor (/ diff 60)))
12621 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12623 d (floor (+ (/ diff ds) 0.5))
12624 h 0 m 0))
12625 (if (not to-buffer)
12626 (message "%s" (org-make-tdiff-string y d h m))
12627 (if (org-at-table-p)
12628 (progn
12629 (goto-char match-end)
12630 (setq align t)
12631 (and (looking-at " *|") (goto-char (match-end 0))))
12632 (goto-char match-end))
12633 (if (looking-at
12634 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12635 (replace-match ""))
12636 (if negative (insert " -"))
12637 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12638 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12639 (insert " " (format fh h m))))
12640 (if align (org-table-align))
12641 (message "Time difference inserted")))))
12643 (defun org-make-tdiff-string (y d h m)
12644 (let ((fmt "")
12645 (l nil))
12646 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12647 l (push y l)))
12648 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12649 l (push d l)))
12650 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12651 l (push h l)))
12652 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12653 l (push m l)))
12654 (apply 'format fmt (nreverse l))))
12656 (defun org-time-string-to-time (s)
12657 (apply 'encode-time (org-parse-time-string s)))
12658 (defun org-time-string-to-seconds (s)
12659 (time-to-seconds (org-time-string-to-time s)))
12661 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
12662 "Convert a time stamp to an absolute day number.
12663 If there is a specifyer for a cyclic time stamp, get the closest date to
12664 DAYNR.
12665 PREFER and SHOW-ALL are passed through to `org-closest-date'.
12666 the variable date is bound by the calendar when this is called."
12667 (cond
12668 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
12669 (if (org-diary-sexp-entry (match-string 1 s) "" date)
12670 daynr
12671 (+ daynr 1000)))
12672 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
12673 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
12674 (time-to-days (current-time))) (match-string 0 s)
12675 prefer show-all))
12676 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
12678 (defun org-days-to-iso-week (days)
12679 "Return the iso week number."
12680 (require 'cal-iso)
12681 (car (calendar-iso-from-absolute days)))
12683 (defun org-small-year-to-year (year)
12684 "Convert 2-digit years into 4-digit years.
12685 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
12686 The year 2000 cannot be abbreviated. Any year larger than 99
12687 is returned unchanged."
12688 (if (< year 38)
12689 (setq year (+ 2000 year))
12690 (if (< year 100)
12691 (setq year (+ 1900 year))))
12692 year)
12694 (defun org-time-from-absolute (d)
12695 "Return the time corresponding to date D.
12696 D may be an absolute day number, or a calendar-type list (month day year)."
12697 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
12698 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
12700 (defun org-calendar-holiday ()
12701 "List of holidays, for Diary display in Org-mode."
12702 (require 'holidays)
12703 (let ((hl (funcall
12704 (if (fboundp 'calendar-check-holidays)
12705 'calendar-check-holidays 'check-calendar-holidays) date)))
12706 (if hl (mapconcat 'identity hl "; "))))
12708 (defun org-diary-sexp-entry (sexp entry date)
12709 "Process a SEXP diary ENTRY for DATE."
12710 (require 'diary-lib)
12711 (let ((result (if calendar-debug-sexp
12712 (let ((stack-trace-on-error t))
12713 (eval (car (read-from-string sexp))))
12714 (condition-case nil
12715 (eval (car (read-from-string sexp)))
12716 (error
12717 (beep)
12718 (message "Bad sexp at line %d in %s: %s"
12719 (org-current-line)
12720 (buffer-file-name) sexp)
12721 (sleep-for 2))))))
12722 (cond ((stringp result) result)
12723 ((and (consp result)
12724 (stringp (cdr result))) (cdr result))
12725 (result entry)
12726 (t nil))))
12728 (defun org-diary-to-ical-string (frombuf)
12729 "Get iCalendar entries from diary entries in buffer FROMBUF.
12730 This uses the icalendar.el library."
12731 (let* ((tmpdir (if (featurep 'xemacs)
12732 (temp-directory)
12733 temporary-file-directory))
12734 (tmpfile (make-temp-name
12735 (expand-file-name "orgics" tmpdir)))
12736 buf rtn b e)
12737 (save-excursion
12738 (set-buffer frombuf)
12739 (icalendar-export-region (point-min) (point-max) tmpfile)
12740 (setq buf (find-buffer-visiting tmpfile))
12741 (set-buffer buf)
12742 (goto-char (point-min))
12743 (if (re-search-forward "^BEGIN:VEVENT" nil t)
12744 (setq b (match-beginning 0)))
12745 (goto-char (point-max))
12746 (if (re-search-backward "^END:VEVENT" nil t)
12747 (setq e (match-end 0)))
12748 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
12749 (kill-buffer buf)
12750 (delete-file tmpfile)
12751 rtn))
12753 (defun org-closest-date (start current change prefer show-all)
12754 "Find the date closest to CURRENT that is consistent with START and CHANGE.
12755 When PREFER is `past' return a date that is either CURRENT or past.
12756 When PREFER is `future', return a date that is either CURRENT or future.
12757 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
12758 ;; Make the proper lists from the dates
12759 (catch 'exit
12760 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
12761 dn dw sday cday n1 n2 n0
12762 d m y y1 y2 date1 date2 nmonths nm ny m2)
12764 (setq start (org-date-to-gregorian start)
12765 current (org-date-to-gregorian
12766 (if show-all
12767 current
12768 (time-to-days (current-time))))
12769 sday (calendar-absolute-from-gregorian start)
12770 cday (calendar-absolute-from-gregorian current))
12772 (if (<= cday sday) (throw 'exit sday))
12774 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
12775 (setq dn (string-to-number (match-string 1 change))
12776 dw (cdr (assoc (match-string 2 change) a1)))
12777 (error "Invalid change specifyer: %s" change))
12778 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
12779 (cond
12780 ((eq dw 'day)
12781 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
12782 n2 (+ n1 dn)))
12783 ((eq dw 'year)
12784 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
12785 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
12786 (setq date1 (list m d y1)
12787 n1 (calendar-absolute-from-gregorian date1)
12788 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
12789 n2 (calendar-absolute-from-gregorian date2)))
12790 ((eq dw 'month)
12791 ;; approx number of month between the two dates
12792 (setq nmonths (floor (/ (- cday sday) 30.436875)))
12793 ;; How often does dn fit in there?
12794 (setq d (nth 1 start) m (car start) y (nth 2 start)
12795 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
12796 m (+ m nm)
12797 ny (floor (/ m 12))
12798 y (+ y ny)
12799 m (- m (* ny 12)))
12800 (while (> m 12) (setq m (- m 12) y (1+ y)))
12801 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
12802 (setq m2 (+ m dn) y2 y)
12803 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12804 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
12805 (while (<= n2 cday)
12806 (setq n1 n2 m m2 y y2)
12807 (setq m2 (+ m dn) y2 y)
12808 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12809 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
12810 ;; Make sure n1 is the earlier date
12811 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
12812 (if show-all
12813 (cond
12814 ((eq prefer 'past) n1)
12815 ((eq prefer 'future) (if (= cday n1) n1 n2))
12816 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
12817 (cond
12818 ((eq prefer 'past) n1)
12819 ((eq prefer 'future) (if (= cday n1) n1 n2))
12820 (t (if (= cday n1) n1 n2)))))))
12822 (defun org-date-to-gregorian (date)
12823 "Turn any specification of DATE into a gregorian date for the calendar."
12824 (cond ((integerp date) (calendar-gregorian-from-absolute date))
12825 ((and (listp date) (= (length date) 3)) date)
12826 ((stringp date)
12827 (setq date (org-parse-time-string date))
12828 (list (nth 4 date) (nth 3 date) (nth 5 date)))
12829 ((listp date)
12830 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
12832 (defun org-parse-time-string (s &optional nodefault)
12833 "Parse the standard Org-mode time string.
12834 This should be a lot faster than the normal `parse-time-string'.
12835 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12836 hour and minute fields will be nil if not given."
12837 (if (string-match org-ts-regexp0 s)
12838 (list 0
12839 (if (or (match-beginning 8) (not nodefault))
12840 (string-to-number (or (match-string 8 s) "0")))
12841 (if (or (match-beginning 7) (not nodefault))
12842 (string-to-number (or (match-string 7 s) "0")))
12843 (string-to-number (match-string 4 s))
12844 (string-to-number (match-string 3 s))
12845 (string-to-number (match-string 2 s))
12846 nil nil nil)
12847 (make-list 9 0)))
12849 (defun org-timestamp-up (&optional arg)
12850 "Increase the date item at the cursor by one.
12851 If the cursor is on the year, change the year. If it is on the month or
12852 the day, change that.
12853 With prefix ARG, change by that many units."
12854 (interactive "p")
12855 (org-timestamp-change (prefix-numeric-value arg)))
12857 (defun org-timestamp-down (&optional arg)
12858 "Decrease the date item at the cursor by one.
12859 If the cursor is on the year, change the year. If it is on the month or
12860 the day, change that.
12861 With prefix ARG, change by that many units."
12862 (interactive "p")
12863 (org-timestamp-change (- (prefix-numeric-value arg))))
12865 (defun org-timestamp-up-day (&optional arg)
12866 "Increase the date in the time stamp by one day.
12867 With prefix ARG, change that many days."
12868 (interactive "p")
12869 (if (and (not (org-at-timestamp-p t))
12870 (org-on-heading-p))
12871 (org-todo 'up)
12872 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12874 (defun org-timestamp-down-day (&optional arg)
12875 "Decrease the date in the time stamp by one day.
12876 With prefix ARG, change that many days."
12877 (interactive "p")
12878 (if (and (not (org-at-timestamp-p t))
12879 (org-on-heading-p))
12880 (org-todo 'down)
12881 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12883 (defun org-at-timestamp-p (&optional inactive-ok)
12884 "Determine if the cursor is in or at a timestamp."
12885 (interactive)
12886 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12887 (pos (point))
12888 (ans (or (looking-at tsr)
12889 (save-excursion
12890 (skip-chars-backward "^[<\n\r\t")
12891 (if (> (point) (point-min)) (backward-char 1))
12892 (and (looking-at tsr)
12893 (> (- (match-end 0) pos) -1))))))
12894 (and ans
12895 (boundp 'org-ts-what)
12896 (setq org-ts-what
12897 (cond
12898 ((= pos (match-beginning 0)) 'bracket)
12899 ((= pos (1- (match-end 0))) 'bracket)
12900 ((org-pos-in-match-range pos 2) 'year)
12901 ((org-pos-in-match-range pos 3) 'month)
12902 ((org-pos-in-match-range pos 7) 'hour)
12903 ((org-pos-in-match-range pos 8) 'minute)
12904 ((or (org-pos-in-match-range pos 4)
12905 (org-pos-in-match-range pos 5)) 'day)
12906 ((and (> pos (or (match-end 8) (match-end 5)))
12907 (< pos (match-end 0)))
12908 (- pos (or (match-end 8) (match-end 5))))
12909 (t 'day))))
12910 ans))
12912 (defun org-toggle-timestamp-type ()
12913 "Toggle the type (<active> or [inactive]) of a time stamp."
12914 (interactive)
12915 (when (org-at-timestamp-p t)
12916 (let ((beg (match-beginning 0)) (end (match-end 0))
12917 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
12918 (save-excursion
12919 (goto-char beg)
12920 (while (re-search-forward "[][<>]" end t)
12921 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
12922 t t)))
12923 (message "Timestamp is now %sactive"
12924 (if (equal (char-after beg) ?<) "" "in")))))
12926 (defun org-timestamp-change (n &optional what)
12927 "Change the date in the time stamp at point.
12928 The date will be changed by N times WHAT. WHAT can be `day', `month',
12929 `year', `minute', `second'. If WHAT is not given, the cursor position
12930 in the timestamp determines what will be changed."
12931 (let ((pos (point))
12932 with-hm inactive
12933 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
12934 org-ts-what
12935 extra rem
12936 ts time time0)
12937 (if (not (org-at-timestamp-p t))
12938 (error "Not at a timestamp"))
12939 (if (and (not what) (eq org-ts-what 'bracket))
12940 (org-toggle-timestamp-type)
12941 (if (and (not what) (not (eq org-ts-what 'day))
12942 org-display-custom-times
12943 (get-text-property (point) 'display)
12944 (not (get-text-property (1- (point)) 'display)))
12945 (setq org-ts-what 'day))
12946 (setq org-ts-what (or what org-ts-what)
12947 inactive (= (char-after (match-beginning 0)) ?\[)
12948 ts (match-string 0))
12949 (replace-match "")
12950 (if (string-match
12951 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
12953 (setq extra (match-string 1 ts)))
12954 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
12955 (setq with-hm t))
12956 (setq time0 (org-parse-time-string ts))
12957 (when (and (eq org-ts-what 'minute)
12958 (eq current-prefix-arg nil))
12959 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
12960 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
12961 (setcar (cdr time0) (+ (nth 1 time0)
12962 (if (> n 0) (- rem) (- dm rem))))))
12963 (setq time
12964 (encode-time (or (car time0) 0)
12965 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
12966 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
12967 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
12968 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
12969 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
12970 (nthcdr 6 time0)))
12971 (when (and (member org-ts-what '(hour minute))
12972 extra
12973 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
12974 (setq extra (org-modify-ts-extra
12975 extra
12976 (if (eq org-ts-what 'hour) 2 5)
12977 n dm)))
12978 (when (integerp org-ts-what)
12979 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
12980 (if (eq what 'calendar)
12981 (let ((cal-date (org-get-date-from-calendar)))
12982 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12983 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12984 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12985 (setcar time0 (or (car time0) 0))
12986 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12987 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
12988 (setq time (apply 'encode-time time0))))
12989 (setq org-last-changed-timestamp
12990 (org-insert-time-stamp time with-hm inactive nil nil extra))
12991 (org-clock-update-time-maybe)
12992 (goto-char pos)
12993 ;; Try to recenter the calendar window, if any
12994 (if (and org-calendar-follow-timestamp-change
12995 (get-buffer-window "*Calendar*" t)
12996 (memq org-ts-what '(day month year)))
12997 (org-recenter-calendar (time-to-days time))))))
12999 (defun org-modify-ts-extra (s pos n dm)
13000 "Change the different parts of the lead-time and repeat fields in timestamp."
13001 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
13002 ng h m new rem)
13003 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
13004 (cond
13005 ((or (org-pos-in-match-range pos 2)
13006 (org-pos-in-match-range pos 3))
13007 (setq m (string-to-number (match-string 3 s))
13008 h (string-to-number (match-string 2 s)))
13009 (if (org-pos-in-match-range pos 2)
13010 (setq h (+ h n))
13011 (setq n (* dm (org-no-warnings (signum n))))
13012 (when (not (= 0 (setq rem (% m dm))))
13013 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
13014 (setq m (+ m n)))
13015 (if (< m 0) (setq m (+ m 60) h (1- h)))
13016 (if (> m 59) (setq m (- m 60) h (1+ h)))
13017 (setq h (min 24 (max 0 h)))
13018 (setq ng 1 new (format "-%02d:%02d" h m)))
13019 ((org-pos-in-match-range pos 6)
13020 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
13021 ((org-pos-in-match-range pos 5)
13022 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
13024 ((org-pos-in-match-range pos 9)
13025 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
13026 ((org-pos-in-match-range pos 8)
13027 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
13029 (when ng
13030 (setq s (concat
13031 (substring s 0 (match-beginning ng))
13033 (substring s (match-end ng))))))
13036 (defun org-recenter-calendar (date)
13037 "If the calendar is visible, recenter it to DATE."
13038 (let* ((win (selected-window))
13039 (cwin (get-buffer-window "*Calendar*" t))
13040 (calendar-move-hook nil))
13041 (when cwin
13042 (select-window cwin)
13043 (calendar-goto-date (if (listp date) date
13044 (calendar-gregorian-from-absolute date)))
13045 (select-window win))))
13047 (defun org-goto-calendar (&optional arg)
13048 "Go to the Emacs calendar at the current date.
13049 If there is a time stamp in the current line, go to that date.
13050 A prefix ARG can be used to force the current date."
13051 (interactive "P")
13052 (let ((tsr org-ts-regexp) diff
13053 (calendar-move-hook nil)
13054 (calendar-view-holidays-initially-flag nil)
13055 (view-calendar-holidays-initially nil)
13056 (calendar-view-diary-initially-flag nil)
13057 (view-diary-entries-initially nil))
13058 (if (or (org-at-timestamp-p)
13059 (save-excursion
13060 (beginning-of-line 1)
13061 (looking-at (concat ".*" tsr))))
13062 (let ((d1 (time-to-days (current-time)))
13063 (d2 (time-to-days
13064 (org-time-string-to-time (match-string 1)))))
13065 (setq diff (- d2 d1))))
13066 (calendar)
13067 (calendar-goto-today)
13068 (if (and diff (not arg)) (calendar-forward-day diff))))
13070 (defun org-get-date-from-calendar ()
13071 "Return a list (month day year) of date at point in calendar."
13072 (with-current-buffer "*Calendar*"
13073 (save-match-data
13074 (calendar-cursor-to-date))))
13076 (defun org-date-from-calendar ()
13077 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
13078 If there is already a time stamp at the cursor position, update it."
13079 (interactive)
13080 (if (org-at-timestamp-p t)
13081 (org-timestamp-change 0 'calendar)
13082 (let ((cal-date (org-get-date-from-calendar)))
13083 (org-insert-time-stamp
13084 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
13086 (defun org-minutes-to-hh:mm-string (m)
13087 "Compute H:MM from a number of minutes."
13088 (let ((h (/ m 60)))
13089 (setq m (- m (* 60 h)))
13090 (format org-time-clocksum-format h m)))
13092 (defun org-hh:mm-string-to-minutes (s)
13093 "Convert a string H:MM to a number of minutes."
13094 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
13095 (+ (* (string-to-number (match-string 1 s)) 60)
13096 (string-to-number (match-string 2 s)))
13099 ;;;; Files
13101 (defun org-save-all-org-buffers ()
13102 "Save all Org-mode buffers without user confirmation."
13103 (interactive)
13104 (message "Saving all Org-mode buffers...")
13105 (save-some-buffers t 'org-mode-p)
13106 (when (featurep 'org-id) (org-id-locations-save))
13107 (message "Saving all Org-mode buffers... done"))
13109 (defun org-revert-all-org-buffers ()
13110 "Revert all Org-mode buffers.
13111 Prompt for confirmation when there are unsaved changes.
13112 Be sure you know what you are doing before letting this function
13113 overwrite your changes.
13115 This function is useful in a setup where one tracks org files
13116 with a version control system, to revert on one machine after pulling
13117 changes from another. I believe the procedure must be like this:
13119 1. M-x org-save-all-org-buffers
13120 2. Pull changes from the other machine, resolve conflicts
13121 3. M-x org-revert-all-org-buffers"
13122 (interactive)
13123 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
13124 (error "Abort"))
13125 (save-excursion
13126 (save-window-excursion
13127 (mapc
13128 (lambda (b)
13129 (when (and (with-current-buffer b (org-mode-p))
13130 (with-current-buffer b buffer-file-name))
13131 (switch-to-buffer b)
13132 (revert-buffer t 'no-confirm)))
13133 (buffer-list))
13134 (when (and (featurep 'org-id) org-id-track-globally)
13135 (org-id-locations-load)))))
13137 ;;;; Agenda files
13139 ;;;###autoload
13140 (defun org-iswitchb (&optional arg)
13141 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
13142 With a prefix argument, restrict available to files.
13143 With two prefix arguments, restrict available buffers to agenda files.
13145 Due to some yet unresolved reason, the global function
13146 `iswitchb-mode' needs to be active for this function to work."
13147 (interactive "P")
13148 (require 'iswitchb)
13149 (let ((enabled iswitchb-mode) blist)
13150 (or enabled (iswitchb-mode 1))
13151 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13152 ((equal arg '(16)) (org-buffer-list 'agenda))
13153 (t (org-buffer-list))))
13154 (unwind-protect
13155 (let ((iswitchb-make-buflist-hook
13156 (lambda ()
13157 (setq iswitchb-temp-buflist
13158 (mapcar 'buffer-name blist)))))
13159 (switch-to-buffer
13160 (iswitchb-read-buffer
13161 "Switch-to: " nil t))
13162 (or enabled (iswitchb-mode -1))))))
13164 ;;;###autoload
13165 (defun org-ido-switchb (&optional arg)
13166 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
13167 With a prefix argument, restrict available to files.
13168 With two prefix arguments, restrict available buffers to agenda files."
13169 (interactive "P")
13170 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13171 ((equal arg '(16)) (org-buffer-list 'agenda))
13172 (t (org-buffer-list)))))
13173 (switch-to-buffer
13174 (org-ido-completing-read "Org buffer: "
13175 (mapcar 'list (mapcar 'buffer-name blist))
13176 nil t))))
13178 (defun org-buffer-list (&optional predicate exclude-tmp)
13179 "Return a list of Org buffers.
13180 PREDICATE can be `export', `files' or `agenda'.
13182 export restrict the list to Export buffers.
13183 files restrict the list to buffers visiting Org files.
13184 agenda restrict the list to buffers visiting agenda files.
13186 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
13187 (let* ((bfn nil)
13188 (agenda-files (and (eq predicate 'agenda)
13189 (mapcar 'file-truename (org-agenda-files t))))
13190 (filter
13191 (cond
13192 ((eq predicate 'files)
13193 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
13194 ((eq predicate 'export)
13195 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
13196 ((eq predicate 'agenda)
13197 (lambda (b)
13198 (with-current-buffer b
13199 (and (eq major-mode 'org-mode)
13200 (setq bfn (buffer-file-name b))
13201 (member (file-truename bfn) agenda-files)))))
13202 (t (lambda (b) (with-current-buffer b
13203 (or (eq major-mode 'org-mode)
13204 (string-match "\*Org .*Export"
13205 (buffer-name b)))))))))
13206 (delq nil
13207 (mapcar
13208 (lambda(b)
13209 (if (and (funcall filter b)
13210 (or (not exclude-tmp)
13211 (not (string-match "tmp" (buffer-name b)))))
13213 nil))
13214 (buffer-list)))))
13216 (defun org-agenda-files (&optional unrestricted archives)
13217 "Get the list of agenda files.
13218 Optional UNRESTRICTED means return the full list even if a restriction
13219 is currently in place.
13220 When ARCHIVES is t, include all archive files hat are really being
13221 used by the agenda files. If ARCHIVE is `ifmode', do this only if
13222 `org-agenda-archives-mode' is t."
13223 (let ((files
13224 (cond
13225 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
13226 ((stringp org-agenda-files) (org-read-agenda-file-list))
13227 ((listp org-agenda-files) org-agenda-files)
13228 (t (error "Invalid value of `org-agenda-files'")))))
13229 (setq files (apply 'append
13230 (mapcar (lambda (f)
13231 (if (file-directory-p f)
13232 (directory-files
13233 f t org-agenda-file-regexp)
13234 (list f)))
13235 files)))
13236 (when org-agenda-skip-unavailable-files
13237 (setq files (delq nil
13238 (mapcar (function
13239 (lambda (file)
13240 (and (file-readable-p file) file)))
13241 files))))
13242 (when (or (eq archives t)
13243 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
13244 (setq files (org-add-archive-files files)))
13245 files))
13247 (defun org-edit-agenda-file-list ()
13248 "Edit the list of agenda files.
13249 Depending on setup, this either uses customize to edit the variable
13250 `org-agenda-files', or it visits the file that is holding the list. In the
13251 latter case, the buffer is set up in a way that saving it automatically kills
13252 the buffer and restores the previous window configuration."
13253 (interactive)
13254 (if (stringp org-agenda-files)
13255 (let ((cw (current-window-configuration)))
13256 (find-file org-agenda-files)
13257 (org-set-local 'org-window-configuration cw)
13258 (org-add-hook 'after-save-hook
13259 (lambda ()
13260 (set-window-configuration
13261 (prog1 org-window-configuration
13262 (kill-buffer (current-buffer))))
13263 (org-install-agenda-files-menu)
13264 (message "New agenda file list installed"))
13265 nil 'local)
13266 (message "%s" (substitute-command-keys
13267 "Edit list and finish with \\[save-buffer]")))
13268 (customize-variable 'org-agenda-files)))
13270 (defun org-store-new-agenda-file-list (list)
13271 "Set new value for the agenda file list and save it correctly."
13272 (if (stringp org-agenda-files)
13273 (let ((f org-agenda-files) b)
13274 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
13275 (with-temp-file f
13276 (insert (mapconcat 'identity list "\n") "\n")))
13277 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
13278 (setq org-agenda-files list)
13279 (customize-save-variable 'org-agenda-files org-agenda-files))))
13281 (defun org-read-agenda-file-list ()
13282 "Read the list of agenda files from a file."
13283 (when (file-directory-p org-agenda-files)
13284 (error "`org-agenda-files' cannot be a single directory"))
13285 (when (stringp org-agenda-files)
13286 (with-temp-buffer
13287 (insert-file-contents org-agenda-files)
13288 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
13291 ;;;###autoload
13292 (defun org-cycle-agenda-files ()
13293 "Cycle through the files in `org-agenda-files'.
13294 If the current buffer visits an agenda file, find the next one in the list.
13295 If the current buffer does not, find the first agenda file."
13296 (interactive)
13297 (let* ((fs (org-agenda-files t))
13298 (files (append fs (list (car fs))))
13299 (tcf (if buffer-file-name (file-truename buffer-file-name)))
13300 file)
13301 (unless files (error "No agenda files"))
13302 (catch 'exit
13303 (while (setq file (pop files))
13304 (if (equal (file-truename file) tcf)
13305 (when (car files)
13306 (find-file (car files))
13307 (throw 'exit t))))
13308 (find-file (car fs)))
13309 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
13311 (defun org-agenda-file-to-front (&optional to-end)
13312 "Move/add the current file to the top of the agenda file list.
13313 If the file is not present in the list, it is added to the front. If it is
13314 present, it is moved there. With optional argument TO-END, add/move to the
13315 end of the list."
13316 (interactive "P")
13317 (let ((org-agenda-skip-unavailable-files nil)
13318 (file-alist (mapcar (lambda (x)
13319 (cons (file-truename x) x))
13320 (org-agenda-files t)))
13321 (ctf (file-truename buffer-file-name))
13322 x had)
13323 (setq x (assoc ctf file-alist) had x)
13325 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
13326 (if to-end
13327 (setq file-alist (append (delq x file-alist) (list x)))
13328 (setq file-alist (cons x (delq x file-alist))))
13329 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
13330 (org-install-agenda-files-menu)
13331 (message "File %s to %s of agenda file list"
13332 (if had "moved" "added") (if to-end "end" "front"))))
13334 (defun org-remove-file (&optional file)
13335 "Remove current file from the list of files in variable `org-agenda-files'.
13336 These are the files which are being checked for agenda entries.
13337 Optional argument FILE means, use this file instead of the current."
13338 (interactive)
13339 (let* ((org-agenda-skip-unavailable-files nil)
13340 (file (or file buffer-file-name))
13341 (true-file (file-truename file))
13342 (afile (abbreviate-file-name file))
13343 (files (delq nil (mapcar
13344 (lambda (x)
13345 (if (equal true-file
13346 (file-truename x))
13347 nil x))
13348 (org-agenda-files t)))))
13349 (if (not (= (length files) (length (org-agenda-files t))))
13350 (progn
13351 (org-store-new-agenda-file-list files)
13352 (org-install-agenda-files-menu)
13353 (message "Removed file: %s" afile))
13354 (message "File was not in list: %s (not removed)" afile))))
13356 (defun org-file-menu-entry (file)
13357 (vector file (list 'find-file file) t))
13359 (defun org-check-agenda-file (file)
13360 "Make sure FILE exists. If not, ask user what to do."
13361 (when (not (file-exists-p file))
13362 (message "non-existent file %s. [R]emove from list or [A]bort?"
13363 (abbreviate-file-name file))
13364 (let ((r (downcase (read-char-exclusive))))
13365 (cond
13366 ((equal r ?r)
13367 (org-remove-file file)
13368 (throw 'nextfile t))
13369 (t (error "Abort"))))))
13371 (defun org-get-agenda-file-buffer (file)
13372 "Get a buffer visiting FILE. If the buffer needs to be created, add
13373 it to the list of buffers which might be released later."
13374 (let ((buf (org-find-base-buffer-visiting file)))
13375 (if buf
13376 buf ; just return it
13377 ;; Make a new buffer and remember it
13378 (setq buf (find-file-noselect file))
13379 (if buf (push buf org-agenda-new-buffers))
13380 buf)))
13382 (defun org-release-buffers (blist)
13383 "Release all buffers in list, asking the user for confirmation when needed.
13384 When a buffer is unmodified, it is just killed. When modified, it is saved
13385 \(if the user agrees) and then killed."
13386 (let (buf file)
13387 (while (setq buf (pop blist))
13388 (setq file (buffer-file-name buf))
13389 (when (and (buffer-modified-p buf)
13390 file
13391 (y-or-n-p (format "Save file %s? " file)))
13392 (with-current-buffer buf (save-buffer)))
13393 (kill-buffer buf))))
13395 (defun org-prepare-agenda-buffers (files)
13396 "Create buffers for all agenda files, protect archived trees and comments."
13397 (interactive)
13398 (let ((pa '(:org-archived t))
13399 (pc '(:org-comment t))
13400 (pall '(:org-archived t :org-comment t))
13401 (inhibit-read-only t)
13402 (rea (concat ":" org-archive-tag ":"))
13403 bmp file re)
13404 (save-excursion
13405 (save-restriction
13406 (while (setq file (pop files))
13407 (catch 'nextfile
13408 (if (bufferp file)
13409 (set-buffer file)
13410 (org-check-agenda-file file)
13411 (set-buffer (org-get-agenda-file-buffer file)))
13412 (widen)
13413 (setq bmp (buffer-modified-p))
13414 (org-refresh-category-properties)
13415 (setq org-todo-keywords-for-agenda
13416 (append org-todo-keywords-for-agenda org-todo-keywords-1))
13417 (setq org-done-keywords-for-agenda
13418 (append org-done-keywords-for-agenda org-done-keywords))
13419 (setq org-todo-keyword-alist-for-agenda
13420 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
13421 (setq org-tag-alist-for-agenda
13422 (append org-tag-alist-for-agenda org-tag-alist))
13424 (save-excursion
13425 (remove-text-properties (point-min) (point-max) pall)
13426 (when org-agenda-skip-archived-trees
13427 (goto-char (point-min))
13428 (while (re-search-forward rea nil t)
13429 (if (org-on-heading-p t)
13430 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
13431 (goto-char (point-min))
13432 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
13433 (while (re-search-forward re nil t)
13434 (add-text-properties
13435 (match-beginning 0) (org-end-of-subtree t) pc)))
13436 (set-buffer-modified-p bmp)))))
13437 (setq org-todo-keyword-alist-for-agenda
13438 (org-uniquify org-todo-keyword-alist-for-agenda)
13439 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
13441 ;;;; Embedded LaTeX
13443 (defvar org-cdlatex-mode-map (make-sparse-keymap)
13444 "Keymap for the minor `org-cdlatex-mode'.")
13446 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
13447 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
13448 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
13449 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
13450 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
13452 (defvar org-cdlatex-texmathp-advice-is-done nil
13453 "Flag remembering if we have applied the advice to texmathp already.")
13455 (define-minor-mode org-cdlatex-mode
13456 "Toggle the minor `org-cdlatex-mode'.
13457 This mode supports entering LaTeX environment and math in LaTeX fragments
13458 in Org-mode.
13459 \\{org-cdlatex-mode-map}"
13460 nil " OCDL" nil
13461 (when org-cdlatex-mode (require 'cdlatex))
13462 (unless org-cdlatex-texmathp-advice-is-done
13463 (setq org-cdlatex-texmathp-advice-is-done t)
13464 (defadvice texmathp (around org-math-always-on activate)
13465 "Always return t in org-mode buffers.
13466 This is because we want to insert math symbols without dollars even outside
13467 the LaTeX math segments. If Orgmode thinks that point is actually inside
13468 an embedded LaTeX fragment, let texmathp do its job.
13469 \\[org-cdlatex-mode-map]"
13470 (interactive)
13471 (let (p)
13472 (cond
13473 ((not (org-mode-p)) ad-do-it)
13474 ((eq this-command 'cdlatex-math-symbol)
13475 (setq ad-return-value t
13476 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
13478 (let ((p (org-inside-LaTeX-fragment-p)))
13479 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
13480 (setq ad-return-value t
13481 texmathp-why '("Org-mode embedded math" . 0))
13482 (if p ad-do-it)))))))))
13484 (defun turn-on-org-cdlatex ()
13485 "Unconditionally turn on `org-cdlatex-mode'."
13486 (org-cdlatex-mode 1))
13488 (defun org-inside-LaTeX-fragment-p ()
13489 "Test if point is inside a LaTeX fragment.
13490 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
13491 sequence appearing also before point.
13492 Even though the matchers for math are configurable, this function assumes
13493 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
13494 delimiters are skipped when they have been removed by customization.
13495 The return value is nil, or a cons cell with the delimiter and
13496 and the position of this delimiter.
13498 This function does a reasonably good job, but can locally be fooled by
13499 for example currency specifications. For example it will assume being in
13500 inline math after \"$22.34\". The LaTeX fragment formatter will only format
13501 fragments that are properly closed, but during editing, we have to live
13502 with the uncertainty caused by missing closing delimiters. This function
13503 looks only before point, not after."
13504 (catch 'exit
13505 (let ((pos (point))
13506 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
13507 (lim (progn
13508 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
13509 (point)))
13510 dd-on str (start 0) m re)
13511 (goto-char pos)
13512 (when dodollar
13513 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
13514 re (nth 1 (assoc "$" org-latex-regexps)))
13515 (while (string-match re str start)
13516 (cond
13517 ((= (match-end 0) (length str))
13518 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
13519 ((= (match-end 0) (- (length str) 5))
13520 (throw 'exit nil))
13521 (t (setq start (match-end 0))))))
13522 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
13523 (goto-char pos)
13524 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
13525 (and (match-beginning 2) (throw 'exit nil))
13526 ;; count $$
13527 (while (re-search-backward "\\$\\$" lim t)
13528 (setq dd-on (not dd-on)))
13529 (goto-char pos)
13530 (if dd-on (cons "$$" m))))))
13533 (defun org-try-cdlatex-tab ()
13534 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
13535 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
13536 - inside a LaTeX fragment, or
13537 - after the first word in a line, where an abbreviation expansion could
13538 insert a LaTeX environment."
13539 (when org-cdlatex-mode
13540 (cond
13541 ((save-excursion
13542 (skip-chars-backward "a-zA-Z0-9*")
13543 (skip-chars-backward " \t")
13544 (bolp))
13545 (cdlatex-tab) t)
13546 ((org-inside-LaTeX-fragment-p)
13547 (cdlatex-tab) t)
13548 (t nil))))
13550 (defun org-cdlatex-underscore-caret (&optional arg)
13551 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
13552 Revert to the normal definition outside of these fragments."
13553 (interactive "P")
13554 (if (org-inside-LaTeX-fragment-p)
13555 (call-interactively 'cdlatex-sub-superscript)
13556 (let (org-cdlatex-mode)
13557 (call-interactively (key-binding (vector last-input-event))))))
13559 (defun org-cdlatex-math-modify (&optional arg)
13560 "Execute `cdlatex-math-modify' in LaTeX fragments.
13561 Revert to the normal definition outside of these fragments."
13562 (interactive "P")
13563 (if (org-inside-LaTeX-fragment-p)
13564 (call-interactively 'cdlatex-math-modify)
13565 (let (org-cdlatex-mode)
13566 (call-interactively (key-binding (vector last-input-event))))))
13568 (defvar org-latex-fragment-image-overlays nil
13569 "List of overlays carrying the images of latex fragments.")
13570 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
13572 (defun org-remove-latex-fragment-image-overlays ()
13573 "Remove all overlays with LaTeX fragment images in current buffer."
13574 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
13575 (setq org-latex-fragment-image-overlays nil))
13577 (defun org-preview-latex-fragment (&optional subtree)
13578 "Preview the LaTeX fragment at point, or all locally or globally.
13579 If the cursor is in a LaTeX fragment, create the image and overlay
13580 it over the source code. If there is no fragment at point, display
13581 all fragments in the current text, from one headline to the next. With
13582 prefix SUBTREE, display all fragments in the current subtree. With a
13583 double prefix `C-u C-u', or when the cursor is before the first headline,
13584 display all fragments in the buffer.
13585 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
13586 (interactive "P")
13587 (org-remove-latex-fragment-image-overlays)
13588 (save-excursion
13589 (save-restriction
13590 (let (beg end at msg)
13591 (cond
13592 ((or (equal subtree '(16))
13593 (not (save-excursion
13594 (re-search-backward (concat "^" outline-regexp) nil t))))
13595 (setq beg (point-min) end (point-max)
13596 msg "Creating images for buffer...%s"))
13597 ((equal subtree '(4))
13598 (org-back-to-heading)
13599 (setq beg (point) end (org-end-of-subtree t)
13600 msg "Creating images for subtree...%s"))
13602 (if (setq at (org-inside-LaTeX-fragment-p))
13603 (goto-char (max (point-min) (- (cdr at) 2)))
13604 (org-back-to-heading))
13605 (setq beg (point) end (progn (outline-next-heading) (point))
13606 msg (if at "Creating image...%s"
13607 "Creating images for entry...%s"))))
13608 (message msg "")
13609 (narrow-to-region beg end)
13610 (goto-char beg)
13611 (org-format-latex
13612 (concat "ltxpng/" (file-name-sans-extension
13613 (file-name-nondirectory
13614 buffer-file-name)))
13615 default-directory 'overlays msg at 'forbuffer)
13616 (message msg "done. Use `C-c C-c' to remove images.")))))
13618 (defvar org-latex-regexps
13619 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
13620 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
13621 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
13622 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13623 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13624 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
13625 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
13626 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
13627 "Regular expressions for matching embedded LaTeX.")
13629 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
13630 "Replace LaTeX fragments with links to an image, and produce images."
13631 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
13632 (let* ((prefixnodir (file-name-nondirectory prefix))
13633 (absprefix (expand-file-name prefix dir))
13634 (todir (file-name-directory absprefix))
13635 (opt org-format-latex-options)
13636 (matchers (plist-get opt :matchers))
13637 (re-list org-latex-regexps)
13638 (cnt 0) txt link beg end re e checkdir
13639 executables-checked
13640 m n block linkfile movefile ov)
13641 ;; Check if there are old images files with this prefix, and remove them
13642 (when (file-directory-p todir)
13643 (mapc 'delete-file
13644 (directory-files
13645 todir 'full
13646 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
13647 ;; Check the different regular expressions
13648 (while (setq e (pop re-list))
13649 (setq m (car e) re (nth 1 e) n (nth 2 e)
13650 block (if (nth 3 e) "\n\n" ""))
13651 (when (member m matchers)
13652 (goto-char (point-min))
13653 (while (re-search-forward re nil t)
13654 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
13655 (not (get-text-property (match-beginning n)
13656 'org-protected)))
13657 (setq txt (match-string n)
13658 beg (match-beginning n) end (match-end n)
13659 cnt (1+ cnt)
13660 linkfile (format "%s_%04d.png" prefix cnt)
13661 movefile (format "%s_%04d.png" absprefix cnt)
13662 link (concat block "[[file:" linkfile "]]" block))
13663 (if msg (message msg cnt))
13664 (goto-char beg)
13665 (unless checkdir ; make sure the directory exists
13666 (setq checkdir t)
13667 (or (file-directory-p todir) (make-directory todir)))
13669 (unless executables-checked
13670 (org-check-external-command
13671 "latex" "needed to convert LaTeX fragments to images")
13672 (org-check-external-command
13673 "dvipng" "needed to convert LaTeX fragments to images")
13674 (setq executables-checked t))
13676 (org-create-formula-image
13677 txt movefile opt forbuffer)
13678 (if overlays
13679 (progn
13680 (setq ov (org-make-overlay beg end))
13681 (if (featurep 'xemacs)
13682 (progn
13683 (org-overlay-put ov 'invisible t)
13684 (org-overlay-put
13685 ov 'end-glyph
13686 (make-glyph (vector 'png :file movefile))))
13687 (org-overlay-put
13688 ov 'display
13689 (list 'image :type 'png :file movefile :ascent 'center)))
13690 (push ov org-latex-fragment-image-overlays)
13691 (goto-char end))
13692 (delete-region beg end)
13693 (insert link))))))))
13695 ;; This function borrows from Ganesh Swami's latex2png.el
13696 (defun org-create-formula-image (string tofile options buffer)
13697 (let* ((tmpdir (if (featurep 'xemacs)
13698 (temp-directory)
13699 temporary-file-directory))
13700 (texfilebase (make-temp-name
13701 (expand-file-name "orgtex" tmpdir)))
13702 (texfile (concat texfilebase ".tex"))
13703 (dvifile (concat texfilebase ".dvi"))
13704 (pngfile (concat texfilebase ".png"))
13705 (fnh (if (featurep 'xemacs)
13706 (font-height (get-face-font 'default))
13707 (face-attribute 'default :height nil)))
13708 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
13709 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
13710 (fg (or (plist-get options (if buffer :foreground :html-foreground))
13711 "Black"))
13712 (bg (or (plist-get options (if buffer :background :html-background))
13713 "Transparent")))
13714 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
13715 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
13716 (with-temp-file texfile
13717 (insert org-format-latex-header
13718 "\n\\begin{document}\n" string "\n\\end{document}\n"))
13719 (let ((dir default-directory))
13720 (condition-case nil
13721 (progn
13722 (cd tmpdir)
13723 (call-process "latex" nil nil nil texfile))
13724 (error nil))
13725 (cd dir))
13726 (if (not (file-exists-p dvifile))
13727 (progn (message "Failed to create dvi file from %s" texfile) nil)
13728 (condition-case nil
13729 (call-process "dvipng" nil nil nil
13730 "-E" "-fg" fg "-bg" bg
13731 "-D" dpi
13732 ;;"-x" scale "-y" scale
13733 "-T" "tight"
13734 "-o" pngfile
13735 dvifile)
13736 (error nil))
13737 (if (not (file-exists-p pngfile))
13738 (progn (message "Failed to create png file from %s" texfile) nil)
13739 ;; Use the requested file name and clean up
13740 (copy-file pngfile tofile 'replace)
13741 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
13742 (delete-file (concat texfilebase e)))
13743 pngfile))))
13745 (defun org-dvipng-color (attr)
13746 "Return an rgb color specification for dvipng."
13747 (apply 'format "rgb %s %s %s"
13748 (mapcar 'org-normalize-color
13749 (color-values (face-attribute 'default attr nil)))))
13751 (defun org-normalize-color (value)
13752 "Return string to be used as color value for an RGB component."
13753 (format "%g" (/ value 65535.0)))
13755 ;;;; Key bindings
13757 ;; Make `C-c C-x' a prefix key
13758 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
13760 ;; TAB key with modifiers
13761 (org-defkey org-mode-map "\C-i" 'org-cycle)
13762 (org-defkey org-mode-map [(tab)] 'org-cycle)
13763 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
13764 (org-defkey org-mode-map [(meta tab)] 'org-complete)
13765 (org-defkey org-mode-map "\M-\t" 'org-complete)
13766 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
13767 ;; The following line is necessary under Suse GNU/Linux
13768 (unless (featurep 'xemacs)
13769 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
13770 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
13771 (define-key org-mode-map [backtab] 'org-shifttab)
13773 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
13774 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
13775 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
13777 ;; Cursor keys with modifiers
13778 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
13779 (org-defkey org-mode-map [(meta right)] 'org-metaright)
13780 (org-defkey org-mode-map [(meta up)] 'org-metaup)
13781 (org-defkey org-mode-map [(meta down)] 'org-metadown)
13783 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
13784 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
13785 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
13786 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
13788 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
13789 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
13790 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
13791 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
13793 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
13794 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
13796 ;;; Extra keys for tty access.
13797 ;; We only set them when really needed because otherwise the
13798 ;; menus don't show the simple keys
13800 (when (or org-use-extra-keys
13801 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
13802 (not window-system))
13803 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
13804 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
13805 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
13806 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
13807 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
13808 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
13809 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
13810 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
13811 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
13812 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
13813 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
13814 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
13815 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
13816 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
13817 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
13818 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
13819 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
13820 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
13821 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
13822 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
13823 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
13824 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
13825 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
13826 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
13827 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
13828 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
13829 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
13830 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
13832 ;; All the other keys
13834 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
13835 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
13836 (if (boundp 'narrow-map)
13837 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
13838 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
13839 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
13840 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
13841 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
13842 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
13843 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
13844 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
13845 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
13846 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
13847 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
13848 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
13849 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
13850 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
13851 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
13852 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
13853 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
13854 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
13855 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
13856 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
13857 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
13858 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
13859 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
13860 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
13861 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
13862 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
13863 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
13864 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
13865 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
13866 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
13867 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
13868 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
13869 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
13870 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
13871 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
13872 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
13873 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
13874 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
13875 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
13876 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
13877 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
13878 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13879 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
13880 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
13881 (org-defkey org-mode-map "\C-c^" 'org-sort)
13882 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
13883 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
13884 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
13885 (org-defkey org-mode-map "\C-m" 'org-return)
13886 (org-defkey org-mode-map "\C-j" 'org-return-indent)
13887 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
13888 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
13889 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
13890 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
13891 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
13892 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
13893 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
13894 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
13895 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
13896 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
13897 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
13898 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
13899 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
13900 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
13901 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
13902 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
13904 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
13905 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
13906 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
13907 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
13909 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
13910 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
13911 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
13912 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
13913 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
13914 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
13915 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
13916 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
13917 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
13918 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
13919 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
13920 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
13921 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
13923 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
13924 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
13925 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
13926 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
13928 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
13930 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
13932 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
13933 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
13935 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
13938 (when (featurep 'xemacs)
13939 (org-defkey org-mode-map 'button3 'popup-mode-menu))
13942 (defvar org-self-insert-command-undo-counter 0)
13944 (defvar org-table-auto-blank-field) ; defined in org-table.el
13945 (defun org-self-insert-command (N)
13946 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13947 If the cursor is in a table looking at whitespace, the whitespace is
13948 overwritten, and the table is not marked as requiring realignment."
13949 (interactive "p")
13950 (if (and
13951 (org-table-p)
13952 (progn
13953 ;; check if we blank the field, and if that triggers align
13954 (and (featurep 'org-table) org-table-auto-blank-field
13955 (member last-command
13956 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
13957 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
13958 ;; got extra space, this field does not determine column width
13959 (let (org-table-may-need-update) (org-table-blank-field))
13960 ;; no extra space, this field may determine column width
13961 (org-table-blank-field)))
13963 (eq N 1)
13964 (looking-at "[^|\n]* |"))
13965 (let (org-table-may-need-update)
13966 (goto-char (1- (match-end 0)))
13967 (delete-backward-char 1)
13968 (goto-char (match-beginning 0))
13969 (self-insert-command N))
13970 (setq org-table-may-need-update t)
13971 (self-insert-command N)
13972 (org-fix-tags-on-the-fly)
13973 (if org-self-insert-cluster-for-undo
13974 (if (not (eq last-command 'org-self-insert-command))
13975 (setq org-self-insert-command-undo-counter 1)
13976 (if (>= org-self-insert-command-undo-counter 20)
13977 (setq org-self-insert-command-undo-counter 1)
13978 (and (> org-self-insert-command-undo-counter 0)
13979 buffer-undo-list
13980 (not (cadr buffer-undo-list)) ; remove nil entry
13981 (setcdr buffer-undo-list (cddr buffer-undo-list)))
13982 (setq org-self-insert-command-undo-counter
13983 (1+ org-self-insert-command-undo-counter)))))))
13985 (defun org-fix-tags-on-the-fly ()
13986 (when (and (equal (char-after (point-at-bol)) ?*)
13987 (org-on-heading-p))
13988 (org-align-tags-here org-tags-column)))
13990 (defun org-delete-backward-char (N)
13991 "Like `delete-backward-char', insert whitespace at field end in tables.
13992 When deleting backwards, in tables this function will insert whitespace in
13993 front of the next \"|\" separator, to keep the table aligned. The table will
13994 still be marked for re-alignment if the field did fill the entire column,
13995 because, in this case the deletion might narrow the column."
13996 (interactive "p")
13997 (if (and (org-table-p)
13998 (eq N 1)
13999 (string-match "|" (buffer-substring (point-at-bol) (point)))
14000 (looking-at ".*?|"))
14001 (let ((pos (point))
14002 (noalign (looking-at "[^|\n\r]* |"))
14003 (c org-table-may-need-update))
14004 (backward-delete-char N)
14005 (skip-chars-forward "^|")
14006 (insert " ")
14007 (goto-char (1- pos))
14008 ;; noalign: if there were two spaces at the end, this field
14009 ;; does not determine the width of the column.
14010 (if noalign (setq org-table-may-need-update c)))
14011 (backward-delete-char N)
14012 (org-fix-tags-on-the-fly)))
14014 (defun org-delete-char (N)
14015 "Like `delete-char', but insert whitespace at field end in tables.
14016 When deleting characters, in tables this function will insert whitespace in
14017 front of the next \"|\" separator, to keep the table aligned. The table will
14018 still be marked for re-alignment if the field did fill the entire column,
14019 because, in this case the deletion might narrow the column."
14020 (interactive "p")
14021 (if (and (org-table-p)
14022 (not (bolp))
14023 (not (= (char-after) ?|))
14024 (eq N 1))
14025 (if (looking-at ".*?|")
14026 (let ((pos (point))
14027 (noalign (looking-at "[^|\n\r]* |"))
14028 (c org-table-may-need-update))
14029 (replace-match (concat
14030 (substring (match-string 0) 1 -1)
14031 " |"))
14032 (goto-char pos)
14033 ;; noalign: if there were two spaces at the end, this field
14034 ;; does not determine the width of the column.
14035 (if noalign (setq org-table-may-need-update c)))
14036 (delete-char N))
14037 (delete-char N)
14038 (org-fix-tags-on-the-fly)))
14040 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
14041 (put 'org-self-insert-command 'delete-selection t)
14042 (put 'orgtbl-self-insert-command 'delete-selection t)
14043 (put 'org-delete-char 'delete-selection 'supersede)
14044 (put 'org-delete-backward-char 'delete-selection 'supersede)
14045 (put 'org-yank 'delete-selection 'yank)
14047 ;; Make `flyspell-mode' delay after some commands
14048 (put 'org-self-insert-command 'flyspell-delayed t)
14049 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
14050 (put 'org-delete-char 'flyspell-delayed t)
14051 (put 'org-delete-backward-char 'flyspell-delayed t)
14053 ;; Make pabbrev-mode expand after org-mode commands
14054 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
14055 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
14057 ;; How to do this: Measure non-white length of current string
14058 ;; If equal to column width, we should realign.
14060 (defun org-remap (map &rest commands)
14061 "In MAP, remap the functions given in COMMANDS.
14062 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
14063 (let (new old)
14064 (while commands
14065 (setq old (pop commands) new (pop commands))
14066 (if (fboundp 'command-remapping)
14067 (org-defkey map (vector 'remap old) new)
14068 (substitute-key-definition old new map global-map)))))
14070 (when (eq org-enable-table-editor 'optimized)
14071 ;; If the user wants maximum table support, we need to hijack
14072 ;; some standard editing functions
14073 (org-remap org-mode-map
14074 'self-insert-command 'org-self-insert-command
14075 'delete-char 'org-delete-char
14076 'delete-backward-char 'org-delete-backward-char)
14077 (org-defkey org-mode-map "|" 'org-force-self-insert))
14079 (defvar org-ctrl-c-ctrl-c-hook nil
14080 "Hook for functions attaching themselves to `C-c C-c'.
14081 This can be used to add additional functionality to the C-c C-c key which
14082 executes context-dependent commands.
14083 Each function will be called with no arguments. The function must check
14084 if the context is appropriate for it to act. If yes, it should do its
14085 thing and then return a non-nil value. If the context is wrong,
14086 just do nothing and return nil.")
14088 (defvar org-tab-first-hook nil
14089 "Hook for functions to attach themselves to TAB.
14090 See `org-ctrl-c-ctrl-c-hook' for more information.
14091 This hook runs as the first action when TAB is pressed, even before
14092 `org-cycle' messes around with the `outline-regexp' to cater for
14093 inline tasks and plain list item folding.
14094 If any function in this hook returns t, not other actions like table
14095 field motion visibility cycling will be done.")
14097 (defvar org-tab-after-check-for-table-hook nil
14098 "Hook for functions to attach themselves to TAB.
14099 See `org-ctrl-c-ctrl-c-hook' for more information.
14100 This hook runs after it has been established that the cursor is not in a
14101 table, but before checking if the cursor is in a headline or if global cycling
14102 should be done.
14103 If any function in this hook returns t, not other actions like visibility
14104 cycling will be done.")
14106 (defvar org-tab-after-check-for-cycling-hook nil
14107 "Hook for functions to attach themselves to TAB.
14108 See `org-ctrl-c-ctrl-c-hook' for more information.
14109 This hook runs after it has been established that not table field motion and
14110 not visibility should be done because of current context. This is probably
14111 the place where a package like yasnippets can hook in.")
14113 (defvar org-metaleft-hook nil
14114 "Hook for functions attaching themselves to `M-left'.
14115 See `org-ctrl-c-ctrl-c-hook' for more information.")
14116 (defvar org-metaright-hook nil
14117 "Hook for functions attaching themselves to `M-right'.
14118 See `org-ctrl-c-ctrl-c-hook' for more information.")
14119 (defvar org-metaup-hook nil
14120 "Hook for functions attaching themselves to `M-up'.
14121 See `org-ctrl-c-ctrl-c-hook' for more information.")
14122 (defvar org-metadown-hook nil
14123 "Hook for functions attaching themselves to `M-down'.
14124 See `org-ctrl-c-ctrl-c-hook' for more information.")
14125 (defvar org-shiftmetaleft-hook nil
14126 "Hook for functions attaching themselves to `M-S-left'.
14127 See `org-ctrl-c-ctrl-c-hook' for more information.")
14128 (defvar org-shiftmetaright-hook nil
14129 "Hook for functions attaching themselves to `M-S-right'.
14130 See `org-ctrl-c-ctrl-c-hook' for more information.")
14131 (defvar org-shiftmetaup-hook nil
14132 "Hook for functions attaching themselves to `M-S-up'.
14133 See `org-ctrl-c-ctrl-c-hook' for more information.")
14134 (defvar org-shiftmetadown-hook nil
14135 "Hook for functions attaching themselves to `M-S-down'.
14136 See `org-ctrl-c-ctrl-c-hook' for more information.")
14137 (defvar org-metareturn-hook nil
14138 "Hook for functions attaching themselves to `M-RET'.
14139 See `org-ctrl-c-ctrl-c-hook' for more information.")
14141 (defun org-modifier-cursor-error ()
14142 "Throw an error, a modified cursor command was applied in wrong context."
14143 (error "This command is active in special context like tables, headlines or items"))
14145 (defun org-shiftselect-error ()
14146 "Throw an error because Shift-Cursor command was applied in wrong context."
14147 (if (and (boundp 'shift-select-mode) shift-select-mode)
14148 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
14149 (error "This command works only in special context like headlines or timestamps.")))
14151 (defun org-call-for-shift-select (cmd)
14152 (let ((this-command-keys-shift-translated t))
14153 (call-interactively cmd)))
14155 (defun org-shifttab (&optional arg)
14156 "Global visibility cycling or move to previous table field.
14157 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
14158 on context.
14159 See the individual commands for more information."
14160 (interactive "P")
14161 (cond
14162 ((org-at-table-p) (call-interactively 'org-table-previous-field))
14163 ((integerp arg)
14164 (message "Content view to level: %d" arg)
14165 (org-content (prefix-numeric-value arg))
14166 (setq org-cycle-global-status 'overview))
14167 (t (call-interactively 'org-global-cycle))))
14169 (defun org-shiftmetaleft ()
14170 "Promote subtree or delete table column.
14171 Calls `org-promote-subtree', `org-outdent-item',
14172 or `org-table-delete-column', depending on context.
14173 See the individual commands for more information."
14174 (interactive)
14175 (cond
14176 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
14177 ((org-at-table-p) (call-interactively 'org-table-delete-column))
14178 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
14179 ((org-at-item-p) (call-interactively 'org-outdent-item))
14180 (t (org-modifier-cursor-error))))
14182 (defun org-shiftmetaright ()
14183 "Demote subtree or insert table column.
14184 Calls `org-demote-subtree', `org-indent-item',
14185 or `org-table-insert-column', depending on context.
14186 See the individual commands for more information."
14187 (interactive)
14188 (cond
14189 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
14190 ((org-at-table-p) (call-interactively 'org-table-insert-column))
14191 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
14192 ((org-at-item-p) (call-interactively 'org-indent-item))
14193 (t (org-modifier-cursor-error))))
14195 (defun org-shiftmetaup (&optional arg)
14196 "Move subtree up or kill table row.
14197 Calls `org-move-subtree-up' or `org-table-kill-row' or
14198 `org-move-item-up' depending on context. See the individual commands
14199 for more information."
14200 (interactive "P")
14201 (cond
14202 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
14203 ((org-at-table-p) (call-interactively 'org-table-kill-row))
14204 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14205 ((org-at-item-p) (call-interactively 'org-move-item-up))
14206 (t (org-modifier-cursor-error))))
14208 (defun org-shiftmetadown (&optional arg)
14209 "Move subtree down or insert table row.
14210 Calls `org-move-subtree-down' or `org-table-insert-row' or
14211 `org-move-item-down', depending on context. See the individual
14212 commands for more information."
14213 (interactive "P")
14214 (cond
14215 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
14216 ((org-at-table-p) (call-interactively 'org-table-insert-row))
14217 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14218 ((org-at-item-p) (call-interactively 'org-move-item-down))
14219 (t (org-modifier-cursor-error))))
14221 (defun org-metaleft (&optional arg)
14222 "Promote heading or move table column to left.
14223 Calls `org-do-promote' or `org-table-move-column', depending on context.
14224 With no specific context, calls the Emacs default `backward-word'.
14225 See the individual commands for more information."
14226 (interactive "P")
14227 (cond
14228 ((run-hook-with-args-until-success 'org-metaleft-hook))
14229 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
14230 ((or (org-on-heading-p)
14231 (and (org-region-active-p)
14232 (save-excursion
14233 (goto-char (region-beginning))
14234 (org-on-heading-p))))
14235 (call-interactively 'org-do-promote))
14236 ((or (org-at-item-p)
14237 (and (org-region-active-p)
14238 (save-excursion
14239 (goto-char (region-beginning))
14240 (org-at-item-p))))
14241 (call-interactively 'org-outdent-item))
14242 (t (call-interactively 'backward-word))))
14244 (defun org-metaright (&optional arg)
14245 "Demote subtree or move table column to right.
14246 Calls `org-do-demote' or `org-table-move-column', depending on context.
14247 With no specific context, calls the Emacs default `forward-word'.
14248 See the individual commands for more information."
14249 (interactive "P")
14250 (cond
14251 ((run-hook-with-args-until-success 'org-metaright-hook))
14252 ((org-at-table-p) (call-interactively 'org-table-move-column))
14253 ((or (org-on-heading-p)
14254 (and (org-region-active-p)
14255 (save-excursion
14256 (goto-char (region-beginning))
14257 (org-on-heading-p))))
14258 (call-interactively 'org-do-demote))
14259 ((or (org-at-item-p)
14260 (and (org-region-active-p)
14261 (save-excursion
14262 (goto-char (region-beginning))
14263 (org-at-item-p))))
14264 (call-interactively 'org-indent-item))
14265 (t (call-interactively 'forward-word))))
14267 (defun org-metaup (&optional arg)
14268 "Move subtree up or move table row up.
14269 Calls `org-move-subtree-up' or `org-table-move-row' or
14270 `org-move-item-up', depending on context. See the individual commands
14271 for more information."
14272 (interactive "P")
14273 (cond
14274 ((run-hook-with-args-until-success 'org-metaup-hook))
14275 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
14276 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14277 ((org-at-item-p) (call-interactively 'org-move-item-up))
14278 (t (transpose-lines 1) (beginning-of-line -1))))
14280 (defun org-metadown (&optional arg)
14281 "Move subtree down or move table row down.
14282 Calls `org-move-subtree-down' or `org-table-move-row' or
14283 `org-move-item-down', depending on context. See the individual
14284 commands for more information."
14285 (interactive "P")
14286 (cond
14287 ((run-hook-with-args-until-success 'org-metadown-hook))
14288 ((org-at-table-p) (call-interactively 'org-table-move-row))
14289 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14290 ((org-at-item-p) (call-interactively 'org-move-item-down))
14291 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
14293 (defun org-shiftup (&optional arg)
14294 "Increase item in timestamp or increase priority of current headline.
14295 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
14296 depending on context. See the individual commands for more information."
14297 (interactive "P")
14298 (cond
14299 ((and org-support-shift-select (org-region-active-p))
14300 (org-call-for-shift-select 'previous-line))
14301 ((org-at-timestamp-p t)
14302 (call-interactively (if org-edit-timestamp-down-means-later
14303 'org-timestamp-down 'org-timestamp-up)))
14304 ((and (not (eq org-support-shift-select 'always))
14305 org-enable-priority-commands
14306 (org-on-heading-p))
14307 (call-interactively 'org-priority-up))
14308 ((and (not org-support-shift-select) (org-at-item-p))
14309 (call-interactively 'org-previous-item))
14310 ((org-clocktable-try-shift 'up arg))
14311 (org-support-shift-select
14312 (org-call-for-shift-select 'previous-line))
14313 (t (org-shiftselect-error))))
14315 (defun org-shiftdown (&optional arg)
14316 "Decrease item in timestamp or decrease priority of current headline.
14317 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
14318 depending on context. See the individual commands for more information."
14319 (interactive "P")
14320 (cond
14321 ((and org-support-shift-select (org-region-active-p))
14322 (org-call-for-shift-select 'next-line))
14323 ((org-at-timestamp-p t)
14324 (call-interactively (if org-edit-timestamp-down-means-later
14325 'org-timestamp-up 'org-timestamp-down)))
14326 ((and (not (eq org-support-shift-select 'always))
14327 org-enable-priority-commands
14328 (org-on-heading-p))
14329 (call-interactively 'org-priority-down))
14330 ((and (not org-support-shift-select) (org-at-item-p))
14331 (call-interactively 'org-next-item))
14332 ((org-clocktable-try-shift 'down arg))
14333 (org-support-shift-select
14334 (org-call-for-shift-select 'next-line))
14335 (t (org-shiftselect-error))))
14337 (defun org-shiftright (&optional arg)
14338 "Cycle the thing at point or in the current line, depending on context.
14339 Depending on context, this does one of the following:
14341 - switch a timestamp at point one day into the future
14342 - on a headline, switch to the next TODO keyword.
14343 - on an item, switch entire list to the next bullet type
14344 - on a property line, switch to the next allowed value
14345 - on a clocktable definition line, move time block into the future"
14346 (interactive "P")
14347 (cond
14348 ((and org-support-shift-select (org-region-active-p))
14349 (org-call-for-shift-select 'forward-char))
14350 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
14351 ((and (not (eq org-support-shift-select 'always))
14352 (org-on-heading-p))
14353 (let ((org-inhibit-logging
14354 (not org-treat-S-cursor-todo-selection-as-state-change)))
14355 (org-call-with-arg 'org-todo 'right)))
14356 ((or (and org-support-shift-select
14357 (not (eq org-support-shift-select 'always))
14358 (org-at-item-bullet-p))
14359 (and (not org-support-shift-select) (org-at-item-p)))
14360 (org-call-with-arg 'org-cycle-list-bullet nil))
14361 ((and (not (eq org-support-shift-select 'always))
14362 (org-at-property-p))
14363 (call-interactively 'org-property-next-allowed-value))
14364 ((org-clocktable-try-shift 'right arg))
14365 (org-support-shift-select
14366 (org-call-for-shift-select 'forward-char))
14367 (t (org-shiftselect-error))))
14369 (defun org-shiftleft (&optional arg)
14370 "Cycle the thing at point or in the current line, depending on context.
14371 Depending on context, this does one of the following:
14373 - switch a timestamp at point one day into the past
14374 - on a headline, switch to the previous TODO keyword.
14375 - on an item, switch entire list to the previous bullet type
14376 - on a property line, switch to the previous allowed value
14377 - on a clocktable definition line, move time block into the past"
14378 (interactive "P")
14379 (cond
14380 ((and org-support-shift-select (org-region-active-p))
14381 (org-call-for-shift-select 'backward-char))
14382 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
14383 ((and (not (eq org-support-shift-select 'always))
14384 (org-on-heading-p))
14385 (let ((org-inhibit-logging
14386 (not org-treat-S-cursor-todo-selection-as-state-change)))
14387 (org-call-with-arg 'org-todo 'left)))
14388 ((or (and org-support-shift-select
14389 (not (eq org-support-shift-select 'always))
14390 (org-at-item-bullet-p))
14391 (and (not org-support-shift-select) (org-at-item-p)))
14392 (org-call-with-arg 'org-cycle-list-bullet 'previous))
14393 ((and (not (eq org-support-shift-select 'always))
14394 (org-at-property-p))
14395 (call-interactively 'org-property-previous-allowed-value))
14396 ((org-clocktable-try-shift 'left arg))
14397 (org-support-shift-select
14398 (org-call-for-shift-select 'backward-char))
14399 (t (org-shiftselect-error))))
14401 (defun org-shiftcontrolright ()
14402 "Switch to next TODO set."
14403 (interactive)
14404 (cond
14405 ((and org-support-shift-select (org-region-active-p))
14406 (org-call-for-shift-select 'forward-word))
14407 ((and (not (eq org-support-shift-select 'always))
14408 (org-on-heading-p))
14409 (org-call-with-arg 'org-todo 'nextset))
14410 (org-support-shift-select
14411 (org-call-for-shift-select 'forward-word))
14412 (t (org-shiftselect-error))))
14414 (defun org-shiftcontrolleft ()
14415 "Switch to previous TODO set."
14416 (interactive)
14417 (cond
14418 ((and org-support-shift-select (org-region-active-p))
14419 (org-call-for-shift-select 'backward-word))
14420 ((and (not (eq org-support-shift-select 'always))
14421 (org-on-heading-p))
14422 (org-call-with-arg 'org-todo 'previousset))
14423 (org-support-shift-select
14424 (org-call-for-shift-select 'backward-word))
14425 (t (org-shiftselect-error))))
14427 (defun org-ctrl-c-ret ()
14428 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
14429 (interactive)
14430 (cond
14431 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
14432 (t (call-interactively 'org-insert-heading))))
14434 (defun org-copy-special ()
14435 "Copy region in table or copy current subtree.
14436 Calls `org-table-copy' or `org-copy-subtree', depending on context.
14437 See the individual commands for more information."
14438 (interactive)
14439 (call-interactively
14440 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
14442 (defun org-cut-special ()
14443 "Cut region in table or cut current subtree.
14444 Calls `org-table-copy' or `org-cut-subtree', depending on context.
14445 See the individual commands for more information."
14446 (interactive)
14447 (call-interactively
14448 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
14450 (defun org-paste-special (arg)
14451 "Paste rectangular region into table, or past subtree relative to level.
14452 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
14453 See the individual commands for more information."
14454 (interactive "P")
14455 (if (org-at-table-p)
14456 (org-table-paste-rectangle)
14457 (org-paste-subtree arg)))
14459 (defun org-edit-special ()
14460 "Call a special editor for the stuff at point.
14461 When at a table, call the formula editor with `org-table-edit-formulas'.
14462 When at the first line of an src example, call `org-edit-src-code'.
14463 When in an #+include line, visit the include file. Otherwise call
14464 `ffap' to visit the file at point."
14465 (interactive)
14466 (cond
14467 ((org-at-table-p)
14468 (call-interactively 'org-table-edit-formulas))
14469 ((save-excursion
14470 (beginning-of-line 1)
14471 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
14472 (find-file (org-trim (match-string 1))))
14473 ((org-edit-src-code))
14474 ((org-edit-fixed-width-region))
14475 (t (call-interactively 'ffap))))
14478 (defun org-ctrl-c-ctrl-c (&optional arg)
14479 "Set tags in headline, or update according to changed information at point.
14481 This command does many different things, depending on context:
14483 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
14484 this is what we do.
14486 - If the cursor is in a headline, prompt for tags and insert them
14487 into the current line, aligned to `org-tags-column'. When called
14488 with prefix arg, realign all tags in the current buffer.
14490 - If the cursor is in one of the special #+KEYWORD lines, this
14491 triggers scanning the buffer for these lines and updating the
14492 information.
14494 - If the cursor is inside a table, realign the table. This command
14495 works even if the automatic table editor has been turned off.
14497 - If the cursor is on a #+TBLFM line, re-apply the formulas to
14498 the entire table.
14500 - If the cursor is at a footnote reference or definition, jump to
14501 the corresponding definition or references, respectively.
14503 - If the cursor is a the beginning of a dynamic block, update it.
14505 - If the cursor is inside a table created by the table.el package,
14506 activate that table.
14508 - If the current buffer is a remember buffer, close note and file
14509 it. A prefix argument of 1 files to the default location
14510 without further interaction. A prefix argument of 2 files to
14511 the currently clocking task.
14513 - If the cursor is on a <<<target>>>, update radio targets and corresponding
14514 links in this buffer.
14516 - If the cursor is on a numbered item in a plain list, renumber the
14517 ordered list.
14519 - If the cursor is on a checkbox, toggle it."
14520 (interactive "P")
14521 (let ((org-enable-table-editor t))
14522 (cond
14523 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
14524 org-occur-highlights
14525 org-latex-fragment-image-overlays)
14526 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
14527 (org-remove-occur-highlights)
14528 (org-remove-latex-fragment-image-overlays)
14529 (message "Temporary highlights/overlays removed from current buffer"))
14530 ((and (local-variable-p 'org-finish-function (current-buffer))
14531 (fboundp org-finish-function))
14532 (funcall org-finish-function))
14533 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
14534 ((org-at-property-p)
14535 (call-interactively 'org-property-action))
14536 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
14537 ((org-on-heading-p) (call-interactively 'org-set-tags))
14538 ((org-at-table.el-p)
14539 (require 'table)
14540 (beginning-of-line 1)
14541 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
14542 (call-interactively 'table-recognize-table))
14543 ((org-at-table-p)
14544 (org-table-maybe-eval-formula)
14545 (if arg
14546 (call-interactively 'org-table-recalculate)
14547 (org-table-maybe-recalculate-line))
14548 (call-interactively 'org-table-align))
14549 ((or (org-footnote-at-reference-p)
14550 (org-footnote-at-definition-p))
14551 (call-interactively 'org-footnote-action))
14552 ((org-at-item-checkbox-p)
14553 (call-interactively 'org-toggle-checkbox))
14554 ((org-at-item-p)
14555 (if arg
14556 (call-interactively 'org-toggle-checkbox)
14557 (call-interactively 'org-maybe-renumber-ordered-list)))
14558 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
14559 ;; Dynamic block
14560 (beginning-of-line 1)
14561 (save-excursion (org-update-dblock)))
14562 ((save-excursion
14563 (beginning-of-line 1)
14564 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
14565 (cond
14566 ((equal (match-string 1) "TBLFM")
14567 ;; Recalculate the table before this line
14568 (save-excursion
14569 (beginning-of-line 1)
14570 (skip-chars-backward " \r\n\t")
14571 (if (org-at-table-p)
14572 (org-call-with-arg 'org-table-recalculate t))))
14574 ; (org-set-regexps-and-options)
14575 ; (org-restart-font-lock)
14576 (let ((org-inhibit-startup t)) (org-mode-restart))
14577 (message "Local setup has been refreshed"))))
14578 ((org-clock-update-time-maybe))
14579 (t (error "C-c C-c can do nothing useful at this location.")))))
14581 (defun org-mode-restart ()
14582 "Restart Org-mode, to scan again for special lines.
14583 Also updates the keyword regular expressions."
14584 (interactive)
14585 (org-mode)
14586 (message "Org-mode restarted"))
14588 (defun org-kill-note-or-show-branches ()
14589 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
14590 (interactive)
14591 (if (not org-finish-function)
14592 (call-interactively 'show-branches)
14593 (let ((org-note-abort t))
14594 (funcall org-finish-function))))
14596 (defun org-return (&optional indent)
14597 "Goto next table row or insert a newline.
14598 Calls `org-table-next-row' or `newline', depending on context.
14599 See the individual commands for more information."
14600 (interactive)
14601 (cond
14602 ((bobp) (if indent (newline-and-indent) (newline)))
14603 ((org-at-table-p)
14604 (org-table-justify-field-maybe)
14605 (call-interactively 'org-table-next-row))
14606 ((and org-return-follows-link
14607 (eq (get-text-property (point) 'face) 'org-link))
14608 (call-interactively 'org-open-at-point))
14609 ((and (org-at-heading-p)
14610 (looking-at
14611 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
14612 (org-show-entry)
14613 (end-of-line 1)
14614 (newline))
14615 (t (if indent (newline-and-indent) (newline)))))
14617 (defun org-return-indent ()
14618 "Goto next table row or insert a newline and indent.
14619 Calls `org-table-next-row' or `newline-and-indent', depending on
14620 context. See the individual commands for more information."
14621 (interactive)
14622 (org-return t))
14624 (defun org-ctrl-c-star ()
14625 "Compute table, or change heading status of lines.
14626 Calls `org-table-recalculate' or `org-toggle-heading',
14627 depending on context."
14628 (interactive)
14629 (cond
14630 ((org-at-table-p)
14631 (call-interactively 'org-table-recalculate))
14633 ;; Convert all lines in region to list items
14634 (call-interactively 'org-toggle-heading))))
14636 (defun org-ctrl-c-minus ()
14637 "Insert separator line in table or modify bullet status of line.
14638 Also turns a plain line or a region of lines into list items.
14639 Calls `org-table-insert-hline', `org-toggle-item', or
14640 `org-cycle-list-bullet', depending on context."
14641 (interactive)
14642 (cond
14643 ((org-at-table-p)
14644 (call-interactively 'org-table-insert-hline))
14645 ((org-region-active-p)
14646 (call-interactively 'org-toggle-item))
14647 ((org-in-item-p)
14648 (call-interactively 'org-cycle-list-bullet))
14650 (call-interactively 'org-toggle-item))))
14652 (defun org-toggle-item ()
14653 "Convert headings or normal lines to items, items to normal lines.
14654 If there is no active region, only the current line is considered.
14656 If the first line in the region is a headline, convert all headlines to items.
14658 If the first line in the region is an item, convert all items to normal lines.
14660 If the first line is normal text, add an item bullet to each line."
14661 (interactive)
14662 (let (l2 l beg end)
14663 (if (org-region-active-p)
14664 (setq beg (region-beginning) end (region-end))
14665 (setq beg (point-at-bol)
14666 end (min (1+ (point-at-eol)) (point-max))))
14667 (save-excursion
14668 (goto-char end)
14669 (setq l2 (org-current-line))
14670 (goto-char beg)
14671 (beginning-of-line 1)
14672 (setq l (1- (org-current-line)))
14673 (if (org-at-item-p)
14674 ;; We already have items, de-itemize
14675 (while (< (setq l (1+ l)) l2)
14676 (when (org-at-item-p)
14677 (goto-char (match-beginning 2))
14678 (delete-region (match-beginning 2) (match-end 2))
14679 (and (looking-at "[ \t]+") (replace-match "")))
14680 (beginning-of-line 2))
14681 (if (org-on-heading-p)
14682 ;; Headings, convert to items
14683 (while (< (setq l (1+ l)) l2)
14684 (if (looking-at org-outline-regexp)
14685 (replace-match "- " t t))
14686 (beginning-of-line 2))
14687 ;; normal lines, turn them into items
14688 (while (< (setq l (1+ l)) l2)
14689 (unless (org-at-item-p)
14690 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14691 (replace-match "\\1- \\2")))
14692 (beginning-of-line 2)))))))
14694 (defun org-toggle-heading (&optional nstars)
14695 "Convert headings to normal text, or items or text to headings.
14696 If there is no active region, only the current line is considered.
14698 If the first line is a heading, remove the stars from all headlines
14699 in the region.
14701 If the first line is a plain list item, turn all plain list items into
14702 headings.
14704 If the first line is a normal line, turn each and every line in the region
14705 into a heading.
14707 When converting a line into a heading, the number of stars is chosen
14708 such that the lines become children of the current entry. However, when
14709 a prefix argument is given, its value determines the number of stars to add."
14710 (interactive "P")
14711 (let (l2 l itemp beg end)
14712 (if (org-region-active-p)
14713 (setq beg (region-beginning) end (region-end))
14714 (setq beg (point-at-bol)
14715 end (min (1+ (point-at-eol)) (point-max))))
14716 (save-excursion
14717 (goto-char end)
14718 (setq l2 (org-current-line))
14719 (goto-char beg)
14720 (beginning-of-line 1)
14721 (setq l (1- (org-current-line)))
14722 (if (org-on-heading-p)
14723 ;; We already have headlines, de-star them
14724 (while (< (setq l (1+ l)) l2)
14725 (when (org-on-heading-p t)
14726 (and (looking-at outline-regexp) (replace-match "")))
14727 (beginning-of-line 2))
14728 (setq itemp (org-at-item-p))
14729 (let* ((stars
14730 (if nstars
14731 (make-string (prefix-numeric-value current-prefix-arg)
14733 (save-excursion
14734 (re-search-backward org-complex-heading-regexp nil t)
14735 (or (match-string 1) ""))))
14736 (add-stars (cond (nstars "")
14737 ((equal stars "") "*")
14738 (org-odd-levels-only "**")
14739 (t "*")))
14740 (rpl (concat stars add-stars " ")))
14741 (while (< (setq l (1+ l)) l2)
14742 (if itemp
14743 (and (org-at-item-p) (replace-match rpl t t))
14744 (unless (org-on-heading-p)
14745 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14746 (replace-match (concat rpl (match-string 2))))))
14747 (beginning-of-line 2)))))))
14749 (defun org-meta-return (&optional arg)
14750 "Insert a new heading or wrap a region in a table.
14751 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
14752 See the individual commands for more information."
14753 (interactive "P")
14754 (cond
14755 ((run-hook-with-args-until-success 'org-metareturn-hook))
14756 ((org-at-table-p)
14757 (call-interactively 'org-table-wrap-region))
14758 (t (call-interactively 'org-insert-heading))))
14760 ;;; Menu entries
14762 ;; Define the Org-mode menus
14763 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
14764 '("Tbl"
14765 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
14766 ["Next Field" org-cycle (org-at-table-p)]
14767 ["Previous Field" org-shifttab (org-at-table-p)]
14768 ["Next Row" org-return (org-at-table-p)]
14769 "--"
14770 ["Blank Field" org-table-blank-field (org-at-table-p)]
14771 ["Edit Field" org-table-edit-field (org-at-table-p)]
14772 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
14773 "--"
14774 ("Column"
14775 ["Move Column Left" org-metaleft (org-at-table-p)]
14776 ["Move Column Right" org-metaright (org-at-table-p)]
14777 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
14778 ["Insert Column" org-shiftmetaright (org-at-table-p)])
14779 ("Row"
14780 ["Move Row Up" org-metaup (org-at-table-p)]
14781 ["Move Row Down" org-metadown (org-at-table-p)]
14782 ["Delete Row" org-shiftmetaup (org-at-table-p)]
14783 ["Insert Row" org-shiftmetadown (org-at-table-p)]
14784 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
14785 "--"
14786 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
14787 ("Rectangle"
14788 ["Copy Rectangle" org-copy-special (org-at-table-p)]
14789 ["Cut Rectangle" org-cut-special (org-at-table-p)]
14790 ["Paste Rectangle" org-paste-special (org-at-table-p)]
14791 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
14792 "--"
14793 ("Calculate"
14794 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
14795 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
14796 ["Edit Formulas" org-edit-special (org-at-table-p)]
14797 "--"
14798 ["Recalculate line" org-table-recalculate (org-at-table-p)]
14799 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
14800 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
14801 "--"
14802 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
14803 "--"
14804 ["Sum Column/Rectangle" org-table-sum
14805 (or (org-at-table-p) (org-region-active-p))]
14806 ["Which Column?" org-table-current-column (org-at-table-p)])
14807 ["Debug Formulas"
14808 org-table-toggle-formula-debugger
14809 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
14810 ["Show Col/Row Numbers"
14811 org-table-toggle-coordinate-overlays
14812 :style toggle
14813 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
14814 "--"
14815 ["Create" org-table-create (and (not (org-at-table-p))
14816 org-enable-table-editor)]
14817 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
14818 ["Import from File" org-table-import (not (org-at-table-p))]
14819 ["Export to File" org-table-export (org-at-table-p)]
14820 "--"
14821 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
14823 (easy-menu-define org-org-menu org-mode-map "Org menu"
14824 '("Org"
14825 ("Show/Hide"
14826 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
14827 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
14828 ["Sparse Tree..." org-sparse-tree t]
14829 ["Reveal Context" org-reveal t]
14830 ["Show All" show-all t]
14831 "--"
14832 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
14833 "--"
14834 ["New Heading" org-insert-heading t]
14835 ("Navigate Headings"
14836 ["Up" outline-up-heading t]
14837 ["Next" outline-next-visible-heading t]
14838 ["Previous" outline-previous-visible-heading t]
14839 ["Next Same Level" outline-forward-same-level t]
14840 ["Previous Same Level" outline-backward-same-level t]
14841 "--"
14842 ["Jump" org-goto t])
14843 ("Edit Structure"
14844 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
14845 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
14846 "--"
14847 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
14848 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
14849 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
14850 "--"
14851 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
14852 "--"
14853 ["Promote Heading" org-metaleft (not (org-at-table-p))]
14854 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
14855 ["Demote Heading" org-metaright (not (org-at-table-p))]
14856 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
14857 "--"
14858 ["Sort Region/Children" org-sort (not (org-at-table-p))]
14859 "--"
14860 ["Convert to odd levels" org-convert-to-odd-levels t]
14861 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
14862 ("Editing"
14863 ["Emphasis..." org-emphasize t]
14864 ["Edit Source Example" org-edit-special t]
14865 "--"
14866 ["Footnote new/jump" org-footnote-action t]
14867 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
14868 ("Archive"
14869 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
14870 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
14871 ; :active t :keys "C-u C-c C-x C-a"]
14872 ["Sparse trees open ARCHIVE trees"
14873 (setq org-sparse-tree-open-archived-trees
14874 (not org-sparse-tree-open-archived-trees))
14875 :style toggle :selected org-sparse-tree-open-archived-trees]
14876 ["Cycling opens ARCHIVE trees"
14877 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
14878 :style toggle :selected org-cycle-open-archived-trees]
14879 "--"
14880 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
14881 ["Move Subtree to Archive" org-advertized-archive-subtree t]
14882 ; ["Check and Move Children" (org-archive-subtree '(4))
14883 ; :active t :keys "C-u C-c C-x C-s"]
14885 "--"
14886 ("Hyperlinks"
14887 ["Store Link (Global)" org-store-link t]
14888 ["Insert Link" org-insert-link t]
14889 ["Follow Link" org-open-at-point t]
14890 "--"
14891 ["Next link" org-next-link t]
14892 ["Previous link" org-previous-link t]
14893 "--"
14894 ["Descriptive Links"
14895 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
14896 :style radio
14897 :selected (member '(org-link) buffer-invisibility-spec)]
14898 ["Literal Links"
14899 (progn
14900 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
14901 :style radio
14902 :selected (not (member '(org-link) buffer-invisibility-spec))])
14903 "--"
14904 ("TODO Lists"
14905 ["TODO/DONE/-" org-todo t]
14906 ("Select keyword"
14907 ["Next keyword" org-shiftright (org-on-heading-p)]
14908 ["Previous keyword" org-shiftleft (org-on-heading-p)]
14909 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
14910 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
14911 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
14912 ["Show TODO Tree" org-show-todo-tree t]
14913 ["Global TODO list" org-todo-list t]
14914 "--"
14915 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
14916 :selected org-enforce-todo-dependencies :style toggle :active t]
14917 "Settings for tree at point"
14918 ["Do Children sequentially" org-toggle-ordered-property :style radio
14919 :selected (ignore-errors (org-entry-get nil "ORDERED"))
14920 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14921 ["Do Children parallel" org-toggle-ordered-property :style radio
14922 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
14923 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14924 "--"
14925 ["Set Priority" org-priority t]
14926 ["Priority Up" org-shiftup t]
14927 ["Priority Down" org-shiftdown t]
14928 "--"
14929 ["Get news from all feeds" org-feed-update-all t]
14930 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
14931 ["Customize feeds" (customize-variable 'org-feed-alist) t])
14932 ("TAGS and Properties"
14933 ["Set Tags" org-set-tags-command t]
14934 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
14935 "--"
14936 ["Set property" org-set-property t]
14937 ["Column view of properties" org-columns t]
14938 ["Insert Column View DBlock" org-insert-columns-dblock t])
14939 ("Dates and Scheduling"
14940 ["Timestamp" org-time-stamp t]
14941 ["Timestamp (inactive)" org-time-stamp-inactive t]
14942 ("Change Date"
14943 ["1 Day Later" org-shiftright t]
14944 ["1 Day Earlier" org-shiftleft t]
14945 ["1 ... Later" org-shiftup t]
14946 ["1 ... Earlier" org-shiftdown t])
14947 ["Compute Time Range" org-evaluate-time-range t]
14948 ["Schedule Item" org-schedule t]
14949 ["Deadline" org-deadline t]
14950 "--"
14951 ["Custom time format" org-toggle-time-stamp-overlays
14952 :style radio :selected org-display-custom-times]
14953 "--"
14954 ["Goto Calendar" org-goto-calendar t]
14955 ["Date from Calendar" org-date-from-calendar t]
14956 "--"
14957 ["Start/Restart Timer" org-timer-start t]
14958 ["Pause/Continue Timer" org-timer-pause-or-continue t]
14959 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
14960 ["Insert Timer String" org-timer t]
14961 ["Insert Timer Item" org-timer-item t])
14962 ("Logging work"
14963 ["Clock in" org-clock-in t]
14964 ["Clock out" org-clock-out t]
14965 ["Clock cancel" org-clock-cancel t]
14966 ["Goto running clock" org-clock-goto t]
14967 ["Display times" org-clock-display t]
14968 ["Create clock table" org-clock-report t]
14969 "--"
14970 ["Record DONE time"
14971 (progn (setq org-log-done (not org-log-done))
14972 (message "Switching to %s will %s record a timestamp"
14973 (car org-done-keywords)
14974 (if org-log-done "automatically" "not")))
14975 :style toggle :selected org-log-done])
14976 "--"
14977 ["Agenda Command..." org-agenda t]
14978 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
14979 ("File List for Agenda")
14980 ("Special views current file"
14981 ["TODO Tree" org-show-todo-tree t]
14982 ["Check Deadlines" org-check-deadlines t]
14983 ["Timeline" org-timeline t]
14984 ["Tags/Property tree" org-match-sparse-tree t])
14985 "--"
14986 ["Export/Publish..." org-export t]
14987 ("LaTeX"
14988 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
14989 :selected org-cdlatex-mode]
14990 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
14991 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
14992 ["Modify math symbol" org-cdlatex-math-modify
14993 (org-inside-LaTeX-fragment-p)]
14994 ["Insert citation" org-reftex-citation t]
14995 "--"
14996 ["Export LaTeX fragments as images"
14997 (if (featurep 'org-exp)
14998 (setq org-export-with-LaTeX-fragments
14999 (not org-export-with-LaTeX-fragments))
15000 (require 'org-exp))
15001 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
15002 org-export-with-LaTeX-fragments)])
15003 "--"
15004 ("Documentation"
15005 ["Show Version" org-version t]
15006 ["Info Documentation" org-info t])
15007 ("Customize"
15008 ["Browse Org Group" org-customize t]
15009 "--"
15010 ["Expand This Menu" org-create-customize-menu
15011 (fboundp 'customize-menu-create)])
15012 "--"
15013 ("Refresh/Reload"
15014 ["Refresh setup current buffer" org-mode-restart t]
15015 ["Reload Org (after update)" org-reload t]
15016 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
15019 (defun org-info (&optional node)
15020 "Read documentation for Org-mode in the info system.
15021 With optional NODE, go directly to that node."
15022 (interactive)
15023 (info (format "(org)%s" (or node ""))))
15025 (defun org-install-agenda-files-menu ()
15026 (let ((bl (buffer-list)))
15027 (save-excursion
15028 (while bl
15029 (set-buffer (pop bl))
15030 (if (org-mode-p) (setq bl nil)))
15031 (when (org-mode-p)
15032 (easy-menu-change
15033 '("Org") "File List for Agenda"
15034 (append
15035 (list
15036 ["Edit File List" (org-edit-agenda-file-list) t]
15037 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
15038 ["Remove Current File from List" org-remove-file t]
15039 ["Cycle through agenda files" org-cycle-agenda-files t]
15040 ["Occur in all agenda files" org-occur-in-agenda-files t]
15041 "--")
15042 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
15044 ;;;; Documentation
15046 ;;;###autoload
15047 (defun org-require-autoloaded-modules ()
15048 (interactive)
15049 (mapc 'require
15050 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
15051 org-docbook org-exp org-html org-icalendar
15052 org-id org-latex
15053 org-publish org-remember org-table
15054 org-timer org-xoxo)))
15056 ;;;###autoload
15057 (defun org-reload (&optional uncompiled)
15058 "Reload all org lisp files.
15059 With prefix arg UNCOMPILED, load the uncompiled versions."
15060 (interactive "P")
15061 (require 'find-func)
15062 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
15063 (dir-org (file-name-directory (org-find-library-name "org")))
15064 (dir-org-contrib (ignore-errors
15065 (file-name-directory
15066 (org-find-library-name "org-contribdir"))))
15067 (files
15068 (append (directory-files dir-org t file-re)
15069 (and dir-org-contrib
15070 (directory-files dir-org-contrib t file-re))))
15071 (remove-re (concat (if (featurep 'xemacs)
15072 "org-colview" "org-colview-xemacs")
15073 "\\'")))
15074 (setq files (mapcar 'file-name-sans-extension files))
15075 (setq files (mapcar
15076 (lambda (x) (if (string-match remove-re x) nil x))
15077 files))
15078 (setq files (delq nil files))
15079 (mapc
15080 (lambda (f)
15081 (when (featurep (intern (file-name-nondirectory f)))
15082 (if (and (not uncompiled)
15083 (file-exists-p (concat f ".elc")))
15084 (load (concat f ".elc") nil nil t)
15085 (load (concat f ".el") nil nil t))))
15086 files))
15087 (org-version))
15089 ;;;###autoload
15090 (defun org-customize ()
15091 "Call the customize function with org as argument."
15092 (interactive)
15093 (org-load-modules-maybe)
15094 (org-require-autoloaded-modules)
15095 (customize-browse 'org))
15097 (defun org-create-customize-menu ()
15098 "Create a full customization menu for Org-mode, insert it into the menu."
15099 (interactive)
15100 (org-load-modules-maybe)
15101 (org-require-autoloaded-modules)
15102 (if (fboundp 'customize-menu-create)
15103 (progn
15104 (easy-menu-change
15105 '("Org") "Customize"
15106 `(["Browse Org group" org-customize t]
15107 "--"
15108 ,(customize-menu-create 'org)
15109 ["Set" Custom-set t]
15110 ["Save" Custom-save t]
15111 ["Reset to Current" Custom-reset-current t]
15112 ["Reset to Saved" Custom-reset-saved t]
15113 ["Reset to Standard Settings" Custom-reset-standard t]))
15114 (message "\"Org\"-menu now contains full customization menu"))
15115 (error "Cannot expand menu (outdated version of cus-edit.el)")))
15117 ;;;; Miscellaneous stuff
15119 ;;; Generally useful functions
15121 (defun org-find-text-property-in-string (prop s)
15122 "Return the first non-nil value of property PROP in string S."
15123 (or (get-text-property 0 prop s)
15124 (get-text-property (or (next-single-property-change 0 prop s) 0)
15125 prop s)))
15127 (defun org-display-warning (message) ;; Copied from Emacs-Muse
15128 "Display the given MESSAGE as a warning."
15129 (if (fboundp 'display-warning)
15130 (display-warning 'org message
15131 (if (featurep 'xemacs)
15132 'warning
15133 :warning))
15134 (let ((buf (get-buffer-create "*Org warnings*")))
15135 (with-current-buffer buf
15136 (goto-char (point-max))
15137 (insert "Warning (Org): " message)
15138 (unless (bolp)
15139 (newline)))
15140 (display-buffer buf)
15141 (sit-for 0))))
15143 (defun org-goto-marker-or-bmk (marker &optional bookmark)
15144 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
15145 (if (and marker (marker-buffer marker)
15146 (buffer-live-p (marker-buffer marker)))
15147 (progn
15148 (switch-to-buffer (marker-buffer marker))
15149 (if (or (> marker (point-max)) (< marker (point-min)))
15150 (widen))
15151 (goto-char marker)
15152 (org-show-context 'org-goto))
15153 (if bookmark
15154 (bookmark-jump bookmark)
15155 (error "Cannot find location"))))
15157 (defun org-quote-csv-field (s)
15158 "Quote field for inclusion in CSV material."
15159 (if (string-match "[\",]" s)
15160 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
15163 (defun org-plist-delete (plist property)
15164 "Delete PROPERTY from PLIST.
15165 This is in contrast to merely setting it to 0."
15166 (let (p)
15167 (while plist
15168 (if (not (eq property (car plist)))
15169 (setq p (plist-put p (car plist) (nth 1 plist))))
15170 (setq plist (cddr plist)))
15173 (defun org-force-self-insert (N)
15174 "Needed to enforce self-insert under remapping."
15175 (interactive "p")
15176 (self-insert-command N))
15178 (defun org-string-width (s)
15179 "Compute width of string, ignoring invisible characters.
15180 This ignores character with invisibility property `org-link', and also
15181 characters with property `org-cwidth', because these will become invisible
15182 upon the next fontification round."
15183 (let (b l)
15184 (when (or (eq t buffer-invisibility-spec)
15185 (assq 'org-link buffer-invisibility-spec))
15186 (while (setq b (text-property-any 0 (length s)
15187 'invisible 'org-link s))
15188 (setq s (concat (substring s 0 b)
15189 (substring s (or (next-single-property-change
15190 b 'invisible s) (length s)))))))
15191 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
15192 (setq s (concat (substring s 0 b)
15193 (substring s (or (next-single-property-change
15194 b 'org-cwidth s) (length s))))))
15195 (setq l (string-width s) b -1)
15196 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
15197 (setq l (- l (get-text-property b 'org-dwidth-n s))))
15200 (defun org-get-indentation (&optional line)
15201 "Get the indentation of the current line, interpreting tabs.
15202 When LINE is given, assume it represents a line and compute its indentation."
15203 (if line
15204 (if (string-match "^ *" (org-remove-tabs line))
15205 (match-end 0))
15206 (save-excursion
15207 (beginning-of-line 1)
15208 (skip-chars-forward " \t")
15209 (current-column))))
15211 (defun org-remove-tabs (s &optional width)
15212 "Replace tabulators in S with spaces.
15213 Assumes that s is a single line, starting in column 0."
15214 (setq width (or width tab-width))
15215 (while (string-match "\t" s)
15216 (setq s (replace-match
15217 (make-string
15218 (- (* width (/ (+ (match-beginning 0) width) width))
15219 (match-beginning 0)) ?\ )
15220 t t s)))
15223 (defun org-fix-indentation (line ind)
15224 "Fix indentation in LINE.
15225 IND is a cons cell with target and minimum indentation.
15226 If the current indentation in LINE is smaller than the minimum,
15227 leave it alone. If it is larger than ind, set it to the target."
15228 (let* ((l (org-remove-tabs line))
15229 (i (org-get-indentation l))
15230 (i1 (car ind)) (i2 (cdr ind)))
15231 (if (>= i i2) (setq l (substring line i2)))
15232 (if (> i1 0)
15233 (concat (make-string i1 ?\ ) l)
15234 l)))
15236 (defun org-remove-indentation (code &optional n)
15237 "Remove the maximum common indentation from the lines in CODE.
15238 N may optionally be the number of spaces to remove."
15239 (with-temp-buffer
15240 (insert code)
15241 (org-do-remove-indentation n)
15242 (buffer-string)))
15244 (defun org-do-remove-indentation (&optional n)
15245 "Remove the maximum common indentation from the buffer."
15246 (untabify (point-min) (point-max))
15247 (let ((min 10000) re)
15248 (if n
15249 (setq min n)
15250 (goto-char (point-min))
15251 (while (re-search-forward "^ *[^ \n]" nil t)
15252 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
15253 (unless (or (= min 0) (= min 10000))
15254 (setq re (format "^ \\{%d\\}" min))
15255 (goto-char (point-min))
15256 (while (re-search-forward re nil t)
15257 (replace-match "")
15258 (end-of-line 1))
15259 min)))
15261 (defun org-base-buffer (buffer)
15262 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
15263 (if (not buffer)
15264 buffer
15265 (or (buffer-base-buffer buffer)
15266 buffer)))
15268 (defun org-trim (s)
15269 "Remove whitespace at beginning and end of string."
15270 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
15271 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
15274 (defun org-wrap (string &optional width lines)
15275 "Wrap string to either a number of lines, or a width in characters.
15276 If WIDTH is non-nil, the string is wrapped to that width, however many lines
15277 that costs. If there is a word longer than WIDTH, the text is actually
15278 wrapped to the length of that word.
15279 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
15280 many lines, whatever width that takes.
15281 The return value is a list of lines, without newlines at the end."
15282 (let* ((words (org-split-string string "[ \t\n]+"))
15283 (maxword (apply 'max (mapcar 'org-string-width words)))
15284 w ll)
15285 (cond (width
15286 (org-do-wrap words (max maxword width)))
15287 (lines
15288 (setq w maxword)
15289 (setq ll (org-do-wrap words maxword))
15290 (if (<= (length ll) lines)
15292 (setq ll words)
15293 (while (> (length ll) lines)
15294 (setq w (1+ w))
15295 (setq ll (org-do-wrap words w)))
15296 ll))
15297 (t (error "Cannot wrap this")))))
15299 (defun org-do-wrap (words width)
15300 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
15301 (let (lines line)
15302 (while words
15303 (setq line (pop words))
15304 (while (and words (< (+ (length line) (length (car words))) width))
15305 (setq line (concat line " " (pop words))))
15306 (setq lines (push line lines)))
15307 (nreverse lines)))
15309 (defun org-split-string (string &optional separators)
15310 "Splits STRING into substrings at SEPARATORS.
15311 No empty strings are returned if there are matches at the beginning
15312 and end of string."
15313 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
15314 (start 0)
15315 notfirst
15316 (list nil))
15317 (while (and (string-match rexp string
15318 (if (and notfirst
15319 (= start (match-beginning 0))
15320 (< start (length string)))
15321 (1+ start) start))
15322 (< (match-beginning 0) (length string)))
15323 (setq notfirst t)
15324 (or (eq (match-beginning 0) 0)
15325 (and (eq (match-beginning 0) (match-end 0))
15326 (eq (match-beginning 0) start))
15327 (setq list
15328 (cons (substring string start (match-beginning 0))
15329 list)))
15330 (setq start (match-end 0)))
15331 (or (eq start (length string))
15332 (setq list
15333 (cons (substring string start)
15334 list)))
15335 (nreverse list)))
15337 (defun org-uuidgen-p (s)
15338 "Is S an ID created by UUIDGEN?"
15339 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
15341 (defun org-context ()
15342 "Return a list of contexts of the current cursor position.
15343 If several contexts apply, all are returned.
15344 Each context entry is a list with a symbol naming the context, and
15345 two positions indicating start and end of the context. Possible
15346 contexts are:
15348 :headline anywhere in a headline
15349 :headline-stars on the leading stars in a headline
15350 :todo-keyword on a TODO keyword (including DONE) in a headline
15351 :tags on the TAGS in a headline
15352 :priority on the priority cookie in a headline
15353 :item on the first line of a plain list item
15354 :item-bullet on the bullet/number of a plain list item
15355 :checkbox on the checkbox in a plain list item
15356 :table in an org-mode table
15357 :table-special on a special filed in a table
15358 :table-table in a table.el table
15359 :link on a hyperlink
15360 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
15361 :target on a <<target>>
15362 :radio-target on a <<<radio-target>>>
15363 :latex-fragment on a LaTeX fragment
15364 :latex-preview on a LaTeX fragment with overlayed preview image
15366 This function expects the position to be visible because it uses font-lock
15367 faces as a help to recognize the following contexts: :table-special, :link,
15368 and :keyword."
15369 (let* ((f (get-text-property (point) 'face))
15370 (faces (if (listp f) f (list f)))
15371 (p (point)) clist o)
15372 ;; First the large context
15373 (cond
15374 ((org-on-heading-p t)
15375 (push (list :headline (point-at-bol) (point-at-eol)) clist)
15376 (when (progn
15377 (beginning-of-line 1)
15378 (looking-at org-todo-line-tags-regexp))
15379 (push (org-point-in-group p 1 :headline-stars) clist)
15380 (push (org-point-in-group p 2 :todo-keyword) clist)
15381 (push (org-point-in-group p 4 :tags) clist))
15382 (goto-char p)
15383 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
15384 (if (looking-at "\\[#[A-Z0-9]\\]")
15385 (push (org-point-in-group p 0 :priority) clist)))
15387 ((org-at-item-p)
15388 (push (org-point-in-group p 2 :item-bullet) clist)
15389 (push (list :item (point-at-bol)
15390 (save-excursion (org-end-of-item) (point)))
15391 clist)
15392 (and (org-at-item-checkbox-p)
15393 (push (org-point-in-group p 0 :checkbox) clist)))
15395 ((org-at-table-p)
15396 (push (list :table (org-table-begin) (org-table-end)) clist)
15397 (if (memq 'org-formula faces)
15398 (push (list :table-special
15399 (previous-single-property-change p 'face)
15400 (next-single-property-change p 'face)) clist)))
15401 ((org-at-table-p 'any)
15402 (push (list :table-table) clist)))
15403 (goto-char p)
15405 ;; Now the small context
15406 (cond
15407 ((org-at-timestamp-p)
15408 (push (org-point-in-group p 0 :timestamp) clist))
15409 ((memq 'org-link faces)
15410 (push (list :link
15411 (previous-single-property-change p 'face)
15412 (next-single-property-change p 'face)) clist))
15413 ((memq 'org-special-keyword faces)
15414 (push (list :keyword
15415 (previous-single-property-change p 'face)
15416 (next-single-property-change p 'face)) clist))
15417 ((org-on-target-p)
15418 (push (org-point-in-group p 0 :target) clist)
15419 (goto-char (1- (match-beginning 0)))
15420 (if (looking-at org-radio-target-regexp)
15421 (push (org-point-in-group p 0 :radio-target) clist))
15422 (goto-char p))
15423 ((setq o (car (delq nil
15424 (mapcar
15425 (lambda (x)
15426 (if (memq x org-latex-fragment-image-overlays) x))
15427 (org-overlays-at (point))))))
15428 (push (list :latex-fragment
15429 (org-overlay-start o) (org-overlay-end o)) clist)
15430 (push (list :latex-preview
15431 (org-overlay-start o) (org-overlay-end o)) clist))
15432 ((org-inside-LaTeX-fragment-p)
15433 ;; FIXME: positions wrong.
15434 (push (list :latex-fragment (point) (point)) clist)))
15436 (setq clist (nreverse (delq nil clist)))
15437 clist))
15439 ;; FIXME: Compare with at-regexp-p Do we need both?
15440 (defun org-in-regexp (re &optional nlines visually)
15441 "Check if point is inside a match of regexp.
15442 Normally only the current line is checked, but you can include NLINES extra
15443 lines both before and after point into the search.
15444 If VISUALLY is set, require that the cursor is not after the match but
15445 really on, so that the block visually is on the match."
15446 (catch 'exit
15447 (let ((pos (point))
15448 (eol (point-at-eol (+ 1 (or nlines 0))))
15449 (inc (if visually 1 0)))
15450 (save-excursion
15451 (beginning-of-line (- 1 (or nlines 0)))
15452 (while (re-search-forward re eol t)
15453 (if (and (<= (match-beginning 0) pos)
15454 (>= (+ inc (match-end 0)) pos))
15455 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
15457 (defun org-at-regexp-p (regexp)
15458 "Is point inside a match of REGEXP in the current line?"
15459 (catch 'exit
15460 (save-excursion
15461 (let ((pos (point)) (end (point-at-eol)))
15462 (beginning-of-line 1)
15463 (while (re-search-forward regexp end t)
15464 (if (and (<= (match-beginning 0) pos)
15465 (>= (match-end 0) pos))
15466 (throw 'exit t)))
15467 nil))))
15469 (defun org-occur-in-agenda-files (regexp &optional nlines)
15470 "Call `multi-occur' with buffers for all agenda files."
15471 (interactive "sOrg-files matching: \np")
15472 (let* ((files (org-agenda-files))
15473 (tnames (mapcar 'file-truename files))
15474 (extra org-agenda-text-search-extra-files)
15476 (when (eq (car extra) 'agenda-archives)
15477 (setq extra (cdr extra))
15478 (setq files (org-add-archive-files files)))
15479 (while (setq f (pop extra))
15480 (unless (member (file-truename f) tnames)
15481 (add-to-list 'files f 'append)
15482 (add-to-list 'tnames (file-truename f) 'append)))
15483 (multi-occur
15484 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
15485 regexp)))
15487 (if (boundp 'occur-mode-find-occurrence-hook)
15488 ;; Emacs 23
15489 (add-hook 'occur-mode-find-occurrence-hook
15490 (lambda ()
15491 (when (org-mode-p)
15492 (org-reveal))))
15493 ;; Emacs 22
15494 (defadvice occur-mode-goto-occurrence
15495 (after org-occur-reveal activate)
15496 (and (org-mode-p) (org-reveal)))
15497 (defadvice occur-mode-goto-occurrence-other-window
15498 (after org-occur-reveal activate)
15499 (and (org-mode-p) (org-reveal)))
15500 (defadvice occur-mode-display-occurrence
15501 (after org-occur-reveal activate)
15502 (when (org-mode-p)
15503 (let ((pos (occur-mode-find-occurrence)))
15504 (with-current-buffer (marker-buffer pos)
15505 (save-excursion
15506 (goto-char pos)
15507 (org-reveal)))))))
15509 (defun org-uniquify (list)
15510 "Remove duplicate elements from LIST."
15511 (let (res)
15512 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
15513 res))
15515 (defun org-delete-all (elts list)
15516 "Remove all elements in ELTS from LIST."
15517 (while elts
15518 (setq list (delete (pop elts) list)))
15519 list)
15521 (defun org-back-over-empty-lines ()
15522 "Move backwards over whitespace, to the beginning of the first empty line.
15523 Returns the number of empty lines passed."
15524 (let ((pos (point)))
15525 (skip-chars-backward " \t\n\r")
15526 (beginning-of-line 2)
15527 (goto-char (min (point) pos))
15528 (count-lines (point) pos)))
15530 (defun org-skip-whitespace ()
15531 (skip-chars-forward " \t\n\r"))
15533 (defun org-point-in-group (point group &optional context)
15534 "Check if POINT is in match-group GROUP.
15535 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
15536 match. If the match group does ot exist or point is not inside it,
15537 return nil."
15538 (and (match-beginning group)
15539 (>= point (match-beginning group))
15540 (<= point (match-end group))
15541 (if context
15542 (list context (match-beginning group) (match-end group))
15543 t)))
15545 (defun org-switch-to-buffer-other-window (&rest args)
15546 "Switch to buffer in a second window on the current frame.
15547 In particular, do not allow pop-up frames."
15548 (let (pop-up-frames special-display-buffer-names special-display-regexps
15549 special-display-function)
15550 (apply 'switch-to-buffer-other-window args)))
15552 (defun org-combine-plists (&rest plists)
15553 "Create a single property list from all plists in PLISTS.
15554 The process starts by copying the first list, and then setting properties
15555 from the other lists. Settings in the last list are the most significant
15556 ones and overrule settings in the other lists."
15557 (let ((rtn (copy-sequence (pop plists)))
15558 p v ls)
15559 (while plists
15560 (setq ls (pop plists))
15561 (while ls
15562 (setq p (pop ls) v (pop ls))
15563 (setq rtn (plist-put rtn p v))))
15564 rtn))
15566 (defun org-move-line-down (arg)
15567 "Move the current line down. With prefix argument, move it past ARG lines."
15568 (interactive "p")
15569 (let ((col (current-column))
15570 beg end pos)
15571 (beginning-of-line 1) (setq beg (point))
15572 (beginning-of-line 2) (setq end (point))
15573 (beginning-of-line (+ 1 arg))
15574 (setq pos (move-marker (make-marker) (point)))
15575 (insert (delete-and-extract-region beg end))
15576 (goto-char pos)
15577 (org-move-to-column col)))
15579 (defun org-move-line-up (arg)
15580 "Move the current line up. With prefix argument, move it past ARG lines."
15581 (interactive "p")
15582 (let ((col (current-column))
15583 beg end pos)
15584 (beginning-of-line 1) (setq beg (point))
15585 (beginning-of-line 2) (setq end (point))
15586 (beginning-of-line (- arg))
15587 (setq pos (move-marker (make-marker) (point)))
15588 (insert (delete-and-extract-region beg end))
15589 (goto-char pos)
15590 (org-move-to-column col)))
15592 (defun org-replace-escapes (string table)
15593 "Replace %-escapes in STRING with values in TABLE.
15594 TABLE is an association list with keys like \"%a\" and string values.
15595 The sequences in STRING may contain normal field width and padding information,
15596 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
15597 so values can contain further %-escapes if they are define later in TABLE."
15598 (let ((case-fold-search nil)
15599 e re rpl)
15600 (while (setq e (pop table))
15601 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
15602 (while (string-match re string)
15603 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
15604 (cdr e)))
15605 (setq string (replace-match rpl t t string))))
15606 string))
15609 (defun org-sublist (list start end)
15610 "Return a section of LIST, from START to END.
15611 Counting starts at 1."
15612 (let (rtn (c start))
15613 (setq list (nthcdr (1- start) list))
15614 (while (and list (<= c end))
15615 (push (pop list) rtn)
15616 (setq c (1+ c)))
15617 (nreverse rtn)))
15619 (defun org-find-base-buffer-visiting (file)
15620 "Like `find-buffer-visiting' but always return the base buffer and
15621 not an indirect buffer."
15622 (let ((buf (or (get-file-buffer file)
15623 (find-buffer-visiting file))))
15624 (if buf
15625 (or (buffer-base-buffer buf) buf)
15626 nil)))
15628 (defun org-image-file-name-regexp (&optional extensions)
15629 "Return regexp matching the file names of images.
15630 If EXTENSIONS is given, only match these."
15631 (if (and (not extensions) (fboundp 'image-file-name-regexp))
15632 (image-file-name-regexp)
15633 (let ((image-file-name-extensions
15634 (or extensions
15635 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
15636 "xbm" "xpm" "pbm" "pgm" "ppm"))))
15637 (concat "\\."
15638 (regexp-opt (nconc (mapcar 'upcase
15639 image-file-name-extensions)
15640 image-file-name-extensions)
15642 "\\'"))))
15644 (defun org-file-image-p (file &optional extensions)
15645 "Return non-nil if FILE is an image."
15646 (save-match-data
15647 (string-match (org-image-file-name-regexp extensions) file)))
15649 (defun org-get-cursor-date ()
15650 "Return the date at cursor in as a time.
15651 This works in the calendar and in the agenda, anywhere else it just
15652 returns the current time."
15653 (let (date day defd)
15654 (cond
15655 ((eq major-mode 'calendar-mode)
15656 (setq date (calendar-cursor-to-date)
15657 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15658 ((eq major-mode 'org-agenda-mode)
15659 (setq day (get-text-property (point) 'day))
15660 (if day
15661 (setq date (calendar-gregorian-from-absolute day)
15662 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
15663 (nth 2 date))))))
15664 (or defd (current-time))))
15666 (defvar org-agenda-action-marker (make-marker)
15667 "Marker pointing to the entry for the next agenda action.")
15669 (defun org-mark-entry-for-agenda-action ()
15670 "Mark the current entry as target of an agenda action.
15671 Agenda actions are actions executed from the agenda with the key `k',
15672 which make use of the date at the cursor."
15673 (interactive)
15674 (move-marker org-agenda-action-marker
15675 (save-excursion (org-back-to-heading t) (point))
15676 (current-buffer))
15677 (message
15678 "Entry marked for action; press `k' at desired date in agenda or calendar"))
15680 ;;; Paragraph filling stuff.
15681 ;; We want this to be just right, so use the full arsenal.
15683 (defun org-indent-line-function ()
15684 "Indent line like previous, but further if previous was headline or item."
15685 (interactive)
15686 (let* ((pos (point))
15687 (itemp (org-at-item-p))
15688 (org-drawer-regexp (or org-drawer-regexp "\000"))
15689 column bpos bcol tpos tcol bullet btype bullet-type)
15690 ;; Find the previous relevant line
15691 (beginning-of-line 1)
15692 (cond
15693 ((looking-at "#") (setq column 0))
15694 ((looking-at "\\*+ ") (setq column 0))
15695 ((and (looking-at "[ \t]*:END:")
15696 (save-excursion (re-search-backward org-drawer-regexp nil t)))
15697 (save-excursion
15698 (goto-char (1- (match-beginning 1)))
15699 (setq column (current-column))))
15701 (beginning-of-line 0)
15702 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
15703 (not (looking-at "[ \t]*:END:"))
15704 (not (looking-at org-drawer-regexp)))
15705 (beginning-of-line 0))
15706 (cond
15707 ((looking-at "\\*+[ \t]+")
15708 (if (not org-adapt-indentation)
15709 (setq column 0)
15710 (goto-char (match-end 0))
15711 (setq column (current-column))))
15712 ((looking-at org-drawer-regexp)
15713 (goto-char (1- (match-beginning 1)))
15714 (setq column (current-column)))
15715 ((looking-at "\\([ \t]*\\):END:")
15716 (goto-char (match-end 1))
15717 (setq column (current-column)))
15718 ((org-in-item-p)
15719 (org-beginning-of-item)
15720 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
15721 (setq bpos (match-beginning 1) tpos (match-end 0)
15722 bcol (progn (goto-char bpos) (current-column))
15723 tcol (progn (goto-char tpos) (current-column))
15724 bullet (match-string 1)
15725 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
15726 (if (> tcol (+ bcol org-description-max-indent))
15727 (setq tcol (+ bcol 5)))
15728 (if (not itemp)
15729 (setq column tcol)
15730 (goto-char pos)
15731 (beginning-of-line 1)
15732 (if (looking-at "\\S-")
15733 (progn
15734 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
15735 (setq bullet (match-string 1)
15736 btype (if (string-match "[0-9]" bullet) "n" bullet))
15737 (setq column (if (equal btype bullet-type) bcol tcol)))
15738 (setq column (org-get-indentation)))))
15739 (t (setq column (org-get-indentation))))))
15740 (goto-char pos)
15741 (if (<= (current-column) (current-indentation))
15742 (org-indent-line-to column)
15743 (save-excursion (org-indent-line-to column)))
15744 (setq column (current-column))
15745 (beginning-of-line 1)
15746 (if (looking-at
15747 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
15748 (replace-match (concat "\\1" (format org-property-format
15749 (match-string 2) (match-string 3)))
15750 t nil))
15751 (org-move-to-column column)))
15753 (defun org-set-autofill-regexps ()
15754 (interactive)
15755 ;; In the paragraph separator we include headlines, because filling
15756 ;; text in a line directly attached to a headline would otherwise
15757 ;; fill the headline as well.
15758 (org-set-local 'comment-start-skip "^#+[ \t]*")
15759 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
15760 ;; The paragraph starter includes hand-formatted lists.
15761 (org-set-local 'paragraph-start
15762 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
15763 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
15764 ;; But only if the user has not turned off tables or fixed-width regions
15765 (org-set-local
15766 'auto-fill-inhibit-regexp
15767 (concat "\\*+ \\|#\\+"
15768 "\\|[ \t]*" org-keyword-time-regexp
15769 (if (or org-enable-table-editor org-enable-fixed-width-editor)
15770 (concat
15771 "\\|[ \t]*["
15772 (if org-enable-table-editor "|" "")
15773 (if org-enable-fixed-width-editor ":" "")
15774 "]"))))
15775 ;; We use our own fill-paragraph function, to make sure that tables
15776 ;; and fixed-width regions are not wrapped. That function will pass
15777 ;; through to `fill-paragraph' when appropriate.
15778 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
15779 ; Adaptive filling: To get full control, first make sure that
15780 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
15781 (org-set-local 'adaptive-fill-regexp "\000")
15782 (org-set-local 'adaptive-fill-function
15783 'org-adaptive-fill-function)
15784 (org-set-local
15785 'align-mode-rules-list
15786 '((org-in-buffer-settings
15787 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
15788 (modes . '(org-mode))))))
15790 (defun org-fill-paragraph (&optional justify)
15791 "Re-align a table, pass through to fill-paragraph if no table."
15792 (let ((table-p (org-at-table-p))
15793 (table.el-p (org-at-table.el-p)))
15794 (cond ((and (equal (char-after (point-at-bol)) ?*)
15795 (save-excursion (goto-char (point-at-bol))
15796 (looking-at outline-regexp)))
15797 t) ; skip headlines
15798 (table.el-p t) ; skip table.el tables
15799 (table-p (org-table-align) t) ; align org-mode tables
15800 (t nil)))) ; call paragraph-fill
15802 ;; For reference, this is the default value of adaptive-fill-regexp
15803 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
15805 (defun org-adaptive-fill-function ()
15806 "Return a fill prefix for org-mode files.
15807 In particular, this makes sure hanging paragraphs for hand-formatted lists
15808 work correctly."
15809 (cond ((looking-at "#[ \t]+")
15810 (match-string 0))
15811 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
15812 (save-excursion
15813 (if (> (match-end 1) (+ (match-beginning 1)
15814 org-description-max-indent))
15815 (goto-char (+ (match-beginning 1) 5))
15816 (goto-char (match-end 0)))
15817 (make-string (current-column) ?\ )))
15818 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
15819 (save-excursion
15820 (goto-char (match-end 0))
15821 (make-string (current-column) ?\ )))
15822 (t nil)))
15824 ;;; Other stuff.
15826 (defun org-toggle-fixed-width-section (arg)
15827 "Toggle the fixed-width export.
15828 If there is no active region, the QUOTE keyword at the current headline is
15829 inserted or removed. When present, it causes the text between this headline
15830 and the next to be exported as fixed-width text, and unmodified.
15831 If there is an active region, this command adds or removes a colon as the
15832 first character of this line. If the first character of a line is a colon,
15833 this line is also exported in fixed-width font."
15834 (interactive "P")
15835 (let* ((cc 0)
15836 (regionp (org-region-active-p))
15837 (beg (if regionp (region-beginning) (point)))
15838 (end (if regionp (region-end)))
15839 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
15840 (case-fold-search nil)
15841 (re "[ \t]*\\(: \\)")
15842 off)
15843 (if regionp
15844 (save-excursion
15845 (goto-char beg)
15846 (setq cc (current-column))
15847 (beginning-of-line 1)
15848 (setq off (looking-at re))
15849 (while (> nlines 0)
15850 (setq nlines (1- nlines))
15851 (beginning-of-line 1)
15852 (cond
15853 (arg
15854 (org-move-to-column cc t)
15855 (insert ": \n")
15856 (forward-line -1))
15857 ((and off (looking-at re))
15858 (replace-match "" t t nil 1))
15859 ((not off) (org-move-to-column cc t) (insert ": ")))
15860 (forward-line 1)))
15861 (save-excursion
15862 (org-back-to-heading)
15863 (if (looking-at (concat outline-regexp
15864 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
15865 (replace-match "" t t nil 1)
15866 (if (looking-at outline-regexp)
15867 (progn
15868 (goto-char (match-end 0))
15869 (insert org-quote-string " "))))))))
15871 (defun org-reftex-citation ()
15872 "Use reftex-citation to insert a citation into the buffer.
15873 This looks for a line like
15875 #+BIBLIOGRAPHY: foo plain option:-d
15877 and derives from it that foo.bib is the bbliography file relevant
15878 for this document. It then installs the necessary environment for RefTeX
15879 to work in this buffer and calls `reftex-citation' to insert a citation
15880 into the buffer.
15882 Export of such citations to both LaTeX and HTML is handled by the contributed
15883 package org-exp-bibtex by Taru Karttunen."
15884 (interactive)
15885 (let ((reftex-docstruct-symbol 'rds)
15886 (reftex-cite-format "\\cite{%l}")
15887 rds bib)
15888 (save-excursion
15889 (save-restriction
15890 (widen)
15891 (let ((case-fold-search t)
15892 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
15893 (if (not (save-excursion
15894 (or (re-search-forward re nil t)
15895 (re-search-backward re nil t))))
15896 (error "No bibliography defined in file")
15897 (setq bib (concat (match-string 1) ".bib")
15898 rds (list (list 'bib bib)))))))
15899 (call-interactively 'reftex-citation)))
15901 ;;;; Functions extending outline functionality
15903 (defun org-beginning-of-line (&optional arg)
15904 "Go to the beginning of the current line. If that is invisible, continue
15905 to a visible line beginning. This makes the function of C-a more intuitive.
15906 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15907 first attempt, and only move to after the tags when the cursor is already
15908 beyond the end of the headline."
15909 (interactive "P")
15910 (let ((pos (point))
15911 (special (if (consp org-special-ctrl-a/e)
15912 (car org-special-ctrl-a/e)
15913 org-special-ctrl-a/e))
15914 refpos)
15915 (beginning-of-line 1)
15916 (if (and arg (fboundp 'move-beginning-of-line))
15917 (call-interactively 'move-beginning-of-line)
15918 (if (bobp)
15920 (backward-char 1)
15921 (if (org-invisible-p)
15922 (while (and (not (bobp)) (org-invisible-p))
15923 (backward-char 1)
15924 (beginning-of-line 1))
15925 (forward-char 1))))
15926 (when special
15927 (cond
15928 ((and (looking-at org-complex-heading-regexp)
15929 (= (char-after (match-end 1)) ?\ ))
15930 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
15931 (point-at-eol)))
15932 (goto-char
15933 (if (eq special t)
15934 (cond ((> pos refpos) refpos)
15935 ((= pos (point)) refpos)
15936 (t (point)))
15937 (cond ((> pos (point)) (point))
15938 ((not (eq last-command this-command)) (point))
15939 (t refpos)))))
15940 ((org-at-item-p)
15941 (goto-char
15942 (if (eq special t)
15943 (cond ((> pos (match-end 4)) (match-end 4))
15944 ((= pos (point)) (match-end 4))
15945 (t (point)))
15946 (cond ((> pos (point)) (point))
15947 ((not (eq last-command this-command)) (point))
15948 (t (match-end 4))))))))
15949 (org-no-warnings
15950 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15952 (defun org-end-of-line (&optional arg)
15953 "Go to the end of the line.
15954 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15955 first attempt, and only move to after the tags when the cursor is already
15956 beyond the end of the headline."
15957 (interactive "P")
15958 (let ((special (if (consp org-special-ctrl-a/e)
15959 (cdr org-special-ctrl-a/e)
15960 org-special-ctrl-a/e)))
15961 (if (or (not special)
15962 (not (org-on-heading-p))
15963 arg)
15964 (call-interactively (if (fboundp 'move-end-of-line)
15965 'move-end-of-line
15966 'end-of-line))
15967 (let ((pos (point)))
15968 (beginning-of-line 1)
15969 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15970 (if (eq special t)
15971 (if (or (< pos (match-beginning 1))
15972 (= pos (match-end 0)))
15973 (goto-char (match-beginning 1))
15974 (goto-char (match-end 0)))
15975 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
15976 (goto-char (match-end 0))
15977 (goto-char (match-beginning 1))))
15978 (call-interactively (if (fboundp 'move-end-of-line)
15979 'move-end-of-line
15980 'end-of-line)))))
15981 (org-no-warnings
15982 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15984 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
15985 (define-key org-mode-map "\C-e" 'org-end-of-line)
15987 (defun org-backward-sentence (&optional arg)
15988 "Go to beginning of sentence, or beginning of table field.
15989 This will call `backward-sentence' or `org-table-beginning-of-field',
15990 depending on context."
15991 (interactive "P")
15992 (cond
15993 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
15994 (t (call-interactively 'backward-sentence))))
15996 (defun org-forward-sentence (&optional arg)
15997 "Go to end of sentence, or end of table field.
15998 This will call `forward-sentence' or `org-table-end-of-field',
15999 depending on context."
16000 (interactive "P")
16001 (cond
16002 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
16003 (t (call-interactively 'forward-sentence))))
16005 (define-key org-mode-map "\M-a" 'org-backward-sentence)
16006 (define-key org-mode-map "\M-e" 'org-forward-sentence)
16008 (defun org-kill-line (&optional arg)
16009 "Kill line, to tags or end of line."
16010 (interactive "P")
16011 (cond
16012 ((or (not org-special-ctrl-k)
16013 (bolp)
16014 (not (org-on-heading-p)))
16015 (call-interactively 'kill-line))
16016 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
16017 (kill-region (point) (match-beginning 1))
16018 (org-set-tags nil t))
16019 (t (kill-region (point) (point-at-eol)))))
16021 (define-key org-mode-map "\C-k" 'org-kill-line)
16023 (defun org-yank (&optional arg)
16024 "Yank. If the kill is a subtree, treat it specially.
16025 This command will look at the current kill and check if is a single
16026 subtree, or a series of subtrees[1]. If it passes the test, and if the
16027 cursor is at the beginning of a line or after the stars of a currently
16028 empty headline, then the yank is handled specially. How exactly depends
16029 on the value of the following variables, both set by default.
16031 org-yank-folded-subtrees
16032 When set, the subtree(s) will be folded after insertion, but only
16033 if doing so would now swallow text after the yanked text.
16035 org-yank-adjusted-subtrees
16036 When set, the subtree will be promoted or demoted in order to
16037 fit into the local outline tree structure, which means that the level
16038 will be adjusted so that it becomes the smaller one of the two
16039 *visible* surrounding headings.
16041 Any prefix to this command will cause `yank' to be called directly with
16042 no special treatment. In particular, a simple `C-u' prefix will just
16043 plainly yank the text as it is.
16045 \[1] The test checks if the first non-white line is a heading
16046 and if there are no other headings with fewer stars."
16047 (interactive "P")
16048 (org-yank-generic 'yank arg))
16050 (defun org-yank-generic (command arg)
16051 "Perform some yank-like command.
16053 This function implements the behavior described in the `org-yank'
16054 documentation. However, it has been generalized to work for any
16055 interactive command with similar behavior."
16057 ;; pretend to be command COMMAND
16058 (setq this-command command)
16060 (if arg
16061 (call-interactively command)
16063 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
16064 (and (org-kill-is-subtree-p)
16065 (or (bolp)
16066 (and (looking-at "[ \t]*$")
16067 (string-match
16068 "\\`\\*+\\'"
16069 (buffer-substring (point-at-bol) (point)))))))
16070 swallowp)
16071 (cond
16072 ((and subtreep org-yank-folded-subtrees)
16073 (let ((beg (point))
16074 end)
16075 (if (and subtreep org-yank-adjusted-subtrees)
16076 (org-paste-subtree nil nil 'for-yank)
16077 (call-interactively command))
16079 (setq end (point))
16080 (goto-char beg)
16081 (when (and (bolp) subtreep
16082 (not (setq swallowp
16083 (org-yank-folding-would-swallow-text beg end))))
16084 (or (looking-at outline-regexp)
16085 (re-search-forward (concat "^" outline-regexp) end t))
16086 (while (and (< (point) end) (looking-at outline-regexp))
16087 (hide-subtree)
16088 (org-cycle-show-empty-lines 'folded)
16089 (condition-case nil
16090 (outline-forward-same-level 1)
16091 (error (goto-char end)))))
16092 (when swallowp
16093 (message
16094 "Inserted text not folded because that would swallow text"))
16096 (goto-char end)
16097 (skip-chars-forward " \t\n\r")
16098 (beginning-of-line 1)
16099 (push-mark beg 'nomsg)))
16100 ((and subtreep org-yank-adjusted-subtrees)
16101 (let ((beg (point-at-bol)))
16102 (org-paste-subtree nil nil 'for-yank)
16103 (push-mark beg 'nomsg)))
16105 (call-interactively command))))))
16107 (defun org-yank-folding-would-swallow-text (beg end)
16108 "Would hide-subtree at BEG swallow any text after END?"
16109 (let (level)
16110 (save-excursion
16111 (goto-char beg)
16112 (when (or (looking-at outline-regexp)
16113 (re-search-forward (concat "^" outline-regexp) end t))
16114 (setq level (org-outline-level)))
16115 (goto-char end)
16116 (skip-chars-forward " \t\r\n\v\f")
16117 (if (or (eobp)
16118 (and (bolp) (looking-at org-outline-regexp)
16119 (<= (org-outline-level) level)))
16120 nil ; Nothing would be swallowed
16121 t)))) ; something would swallow
16123 (define-key org-mode-map "\C-y" 'org-yank)
16125 (defun org-invisible-p ()
16126 "Check if point is at a character currently not visible."
16127 ;; Early versions of noutline don't have `outline-invisible-p'.
16128 (if (fboundp 'outline-invisible-p)
16129 (outline-invisible-p)
16130 (get-char-property (point) 'invisible)))
16132 (defun org-invisible-p2 ()
16133 "Check if point is at a character currently not visible."
16134 (save-excursion
16135 (if (and (eolp) (not (bobp))) (backward-char 1))
16136 ;; Early versions of noutline don't have `outline-invisible-p'.
16137 (if (fboundp 'outline-invisible-p)
16138 (outline-invisible-p)
16139 (get-char-property (point) 'invisible))))
16141 (defun org-back-to-heading (&optional invisible-ok)
16142 "Call `outline-back-to-heading', but provide a better error message."
16143 (condition-case nil
16144 (outline-back-to-heading invisible-ok)
16145 (error (error "Before first headline at position %d in buffer %s"
16146 (point) (current-buffer)))))
16148 (defun org-before-first-heading-p ()
16149 "Before first heading?"
16150 (save-excursion
16151 (null (re-search-backward "^\\*+ " nil t))))
16153 (defalias 'org-on-heading-p 'outline-on-heading-p)
16154 (defalias 'org-at-heading-p 'outline-on-heading-p)
16155 (defun org-at-heading-or-item-p ()
16156 (or (org-on-heading-p) (org-at-item-p)))
16158 (defun org-on-target-p ()
16159 (or (org-in-regexp org-radio-target-regexp)
16160 (org-in-regexp org-target-regexp)))
16162 (defun org-up-heading-all (arg)
16163 "Move to the heading line of which the present line is a subheading.
16164 This function considers both visible and invisible heading lines.
16165 With argument, move up ARG levels."
16166 (if (fboundp 'outline-up-heading-all)
16167 (outline-up-heading-all arg) ; emacs 21 version of outline.el
16168 (outline-up-heading arg t))) ; emacs 22 version of outline.el
16170 (defun org-up-heading-safe ()
16171 "Move to the heading line of which the present line is a subheading.
16172 This version will not throw an error. It will return the level of the
16173 headline found, or nil if no higher level is found.
16175 Also, this function will be a lot faster than `outline-up-heading',
16176 because it relies on stars being the outline starters. This can really
16177 make a significant difference in outlines with very many siblings."
16178 (let (start-level re)
16179 (org-back-to-heading t)
16180 (setq start-level (funcall outline-level))
16181 (if (equal start-level 1)
16183 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
16184 (if (re-search-backward re nil t)
16185 (funcall outline-level)))))
16187 (defun org-first-sibling-p ()
16188 "Is this heading the first child of its parents?"
16189 (interactive)
16190 (let ((re (concat "^" outline-regexp))
16191 level l)
16192 (unless (org-at-heading-p t)
16193 (error "Not at a heading"))
16194 (setq level (funcall outline-level))
16195 (save-excursion
16196 (if (not (re-search-backward re nil t))
16198 (setq l (funcall outline-level))
16199 (< l level)))))
16201 (defun org-goto-sibling (&optional previous)
16202 "Goto the next sibling, even if it is invisible.
16203 When PREVIOUS is set, go to the previous sibling instead. Returns t
16204 when a sibling was found. When none is found, return nil and don't
16205 move point."
16206 (let ((fun (if previous 're-search-backward 're-search-forward))
16207 (pos (point))
16208 (re (concat "^" outline-regexp))
16209 level l)
16210 (when (condition-case nil (org-back-to-heading t) (error nil))
16211 (setq level (funcall outline-level))
16212 (catch 'exit
16213 (or previous (forward-char 1))
16214 (while (funcall fun re nil t)
16215 (setq l (funcall outline-level))
16216 (when (< l level) (goto-char pos) (throw 'exit nil))
16217 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
16218 (goto-char pos)
16219 nil))))
16221 (defun org-show-siblings ()
16222 "Show all siblings of the current headline."
16223 (save-excursion
16224 (while (org-goto-sibling) (org-flag-heading nil)))
16225 (save-excursion
16226 (while (org-goto-sibling 'previous)
16227 (org-flag-heading nil))))
16229 (defun org-show-hidden-entry ()
16230 "Show an entry where even the heading is hidden."
16231 (save-excursion
16232 (org-show-entry)))
16234 (defun org-flag-heading (flag &optional entry)
16235 "Flag the current heading. FLAG non-nil means make invisible.
16236 When ENTRY is non-nil, show the entire entry."
16237 (save-excursion
16238 (org-back-to-heading t)
16239 ;; Check if we should show the entire entry
16240 (if entry
16241 (progn
16242 (org-show-entry)
16243 (save-excursion
16244 (and (outline-next-heading)
16245 (org-flag-heading nil))))
16246 (outline-flag-region (max (point-min) (1- (point)))
16247 (save-excursion (outline-end-of-heading) (point))
16248 flag))))
16250 (defun org-forward-same-level (arg)
16251 "Move forward to the ARG'th subheading at same level as this one.
16252 Stop at the first and last subheadings of a superior heading.
16253 This is like outline-forward-same-level, but invisible headings are ok."
16254 (interactive "p")
16255 (org-back-to-heading t)
16256 (while (> arg 0)
16257 (let ((point-to-move-to (save-excursion
16258 (org-get-next-sibling))))
16259 (if point-to-move-to
16260 (progn
16261 (goto-char point-to-move-to)
16262 (setq arg (1- arg)))
16263 (progn
16264 (setq arg 0)
16265 (error "No following same-level heading"))))))
16267 (defun org-get-next-sibling ()
16268 "Move to next heading of the same level, and return point.
16269 If there is no such heading, return nil.
16270 This is like outline-next-sibling, but invisible headings are ok."
16271 (let ((level (funcall outline-level)))
16272 (outline-next-heading)
16273 (while (and (not (eobp)) (> (funcall outline-level) level))
16274 (outline-next-heading))
16275 (if (or (eobp) (< (funcall outline-level) level))
16277 (point))))
16279 (defun org-end-of-subtree (&optional invisible-OK to-heading)
16280 ;; This contains an exact copy of the original function, but it uses
16281 ;; `org-back-to-heading', to make it work also in invisible
16282 ;; trees. And is uses an invisible-OK argument.
16283 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
16284 ;; Furthermore, when used inside Org, finding the end of a large subtree
16285 ;; with many children and grandchildren etc, this can be much faster
16286 ;; than the outline version.
16287 (org-back-to-heading invisible-OK)
16288 (let ((first t)
16289 (level (funcall outline-level)))
16290 (if (and (org-mode-p) (< level 1000))
16291 ;; A true heading (not a plain list item), in Org-mode
16292 ;; This means we can easily find the end by looking
16293 ;; only for the right number of stars. Using a regexp to do
16294 ;; this is so much faster than using a Lisp loop.
16295 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
16296 (forward-char 1)
16297 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
16298 ;; something else, do it the slow way
16299 (while (and (not (eobp))
16300 (or first (> (funcall outline-level) level)))
16301 (setq first nil)
16302 (outline-next-heading)))
16303 (unless to-heading
16304 (if (memq (preceding-char) '(?\n ?\^M))
16305 (progn
16306 ;; Go to end of line before heading
16307 (forward-char -1)
16308 (if (memq (preceding-char) '(?\n ?\^M))
16309 ;; leave blank line before heading
16310 (forward-char -1))))))
16311 (point))
16313 (defun org-show-subtree ()
16314 "Show everything after this heading at deeper levels."
16315 (outline-flag-region
16316 (point)
16317 (save-excursion
16318 (outline-end-of-subtree) (outline-next-heading) (point))
16319 nil))
16321 (defun org-show-entry ()
16322 "Show the body directly following this heading.
16323 Show the heading too, if it is currently invisible."
16324 (interactive)
16325 (save-excursion
16326 (condition-case nil
16327 (progn
16328 (org-back-to-heading t)
16329 (outline-flag-region
16330 (max (point-min) (1- (point)))
16331 (save-excursion
16332 (if (re-search-forward
16333 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
16334 (match-beginning 1)
16335 (point-max)))
16336 nil))
16337 (error nil))))
16339 (defun org-make-options-regexp (kwds &optional extra)
16340 "Make a regular expression for keyword lines."
16341 (concat
16343 "#?[ \t]*\\+\\("
16344 (mapconcat 'regexp-quote kwds "\\|")
16345 (if extra (concat "\\|" extra))
16346 "\\):[ \t]*"
16347 "\\(.+\\)"))
16349 ;; Make isearch reveal the necessary context
16350 (defun org-isearch-end ()
16351 "Reveal context after isearch exits."
16352 (when isearch-success ; only if search was successful
16353 (if (featurep 'xemacs)
16354 ;; Under XEmacs, the hook is run in the correct place,
16355 ;; we directly show the context.
16356 (org-show-context 'isearch)
16357 ;; In Emacs the hook runs *before* restoring the overlays.
16358 ;; So we have to use a one-time post-command-hook to do this.
16359 ;; (Emacs 22 has a special variable, see function `org-mode')
16360 (unless (and (boundp 'isearch-mode-end-hook-quit)
16361 isearch-mode-end-hook-quit)
16362 ;; Only when the isearch was not quitted.
16363 (org-add-hook 'post-command-hook 'org-isearch-post-command
16364 'append 'local)))))
16366 (defun org-isearch-post-command ()
16367 "Remove self from hook, and show context."
16368 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
16369 (org-show-context 'isearch))
16372 ;;;; Integration with and fixes for other packages
16374 ;;; Imenu support
16376 (defvar org-imenu-markers nil
16377 "All markers currently used by Imenu.")
16378 (make-variable-buffer-local 'org-imenu-markers)
16380 (defun org-imenu-new-marker (&optional pos)
16381 "Return a new marker for use by Imenu, and remember the marker."
16382 (let ((m (make-marker)))
16383 (move-marker m (or pos (point)))
16384 (push m org-imenu-markers)
16387 (defun org-imenu-get-tree ()
16388 "Produce the index for Imenu."
16389 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
16390 (setq org-imenu-markers nil)
16391 (let* ((n org-imenu-depth)
16392 (re (concat "^" outline-regexp))
16393 (subs (make-vector (1+ n) nil))
16394 (last-level 0)
16395 m level head)
16396 (save-excursion
16397 (save-restriction
16398 (widen)
16399 (goto-char (point-max))
16400 (while (re-search-backward re nil t)
16401 (setq level (org-reduced-level (funcall outline-level)))
16402 (when (<= level n)
16403 (looking-at org-complex-heading-regexp)
16404 (setq head (org-link-display-format
16405 (org-match-string-no-properties 4))
16406 m (org-imenu-new-marker))
16407 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
16408 (if (>= level last-level)
16409 (push (cons head m) (aref subs level))
16410 (push (cons head (aref subs (1+ level))) (aref subs level))
16411 (loop for i from (1+ level) to n do (aset subs i nil)))
16412 (setq last-level level)))))
16413 (aref subs 1)))
16415 (eval-after-load "imenu"
16416 '(progn
16417 (add-hook 'imenu-after-jump-hook
16418 (lambda ()
16419 (if (eq major-mode 'org-mode)
16420 (org-show-context 'org-goto))))))
16422 (defun org-link-display-format (link)
16423 "Replace a link with either the description, or the link target
16424 if no description is present"
16425 (save-match-data
16426 (if (string-match org-bracket-link-analytic-regexp link)
16427 (replace-match (or (match-string 5 link)
16428 (concat (match-string 1 link)
16429 (match-string 3 link)))
16430 nil nil link)
16431 link)))
16433 ;; Speedbar support
16435 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
16436 "Overlay marking the agenda restriction line in speedbar.")
16437 (org-overlay-put org-speedbar-restriction-lock-overlay
16438 'face 'org-agenda-restriction-lock)
16439 (org-overlay-put org-speedbar-restriction-lock-overlay
16440 'help-echo "Agendas are currently limited to this item.")
16441 (org-detach-overlay org-speedbar-restriction-lock-overlay)
16443 (defun org-speedbar-set-agenda-restriction ()
16444 "Restrict future agenda commands to the location at point in speedbar.
16445 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
16446 (interactive)
16447 (require 'org-agenda)
16448 (let (p m tp np dir txt)
16449 (cond
16450 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16451 'org-imenu t))
16452 (setq m (get-text-property p 'org-imenu-marker))
16453 (save-excursion
16454 (save-restriction
16455 (set-buffer (marker-buffer m))
16456 (goto-char m)
16457 (org-agenda-set-restriction-lock 'subtree))))
16458 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16459 'speedbar-function 'speedbar-find-file))
16460 (setq tp (previous-single-property-change
16461 (1+ p) 'speedbar-function)
16462 np (next-single-property-change
16463 tp 'speedbar-function)
16464 dir (speedbar-line-directory)
16465 txt (buffer-substring-no-properties (or tp (point-min))
16466 (or np (point-max))))
16467 (save-excursion
16468 (save-restriction
16469 (set-buffer (find-file-noselect
16470 (let ((default-directory dir))
16471 (expand-file-name txt))))
16472 (unless (org-mode-p)
16473 (error "Cannot restrict to non-Org-mode file"))
16474 (org-agenda-set-restriction-lock 'file))))
16475 (t (error "Don't know how to restrict Org-mode's agenda")))
16476 (org-move-overlay org-speedbar-restriction-lock-overlay
16477 (point-at-bol) (point-at-eol))
16478 (setq current-prefix-arg nil)
16479 (org-agenda-maybe-redo)))
16481 (eval-after-load "speedbar"
16482 '(progn
16483 (speedbar-add-supported-extension ".org")
16484 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
16485 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
16486 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
16487 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16488 (add-hook 'speedbar-visiting-tag-hook
16489 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
16492 ;;; Fixes and Hacks for problems with other packages
16494 ;; Make flyspell not check words in links, to not mess up our keymap
16495 (defun org-mode-flyspell-verify ()
16496 "Don't let flyspell put overlays at active buttons."
16497 (not (get-text-property (point) 'keymap)))
16499 (defun org-remove-flyspell-overlays-in (beg end)
16500 "Remove flyspell overlays in region."
16501 (and (org-bound-and-true-p flyspell-mode)
16502 (fboundp 'flyspell-delete-region-overlays)
16503 (flyspell-delete-region-overlays beg end)))
16505 ;; Make `bookmark-jump' show the jump location if it was hidden.
16506 (eval-after-load "bookmark"
16507 '(if (boundp 'bookmark-after-jump-hook)
16508 ;; We can use the hook
16509 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
16510 ;; Hook not available, use advice
16511 (defadvice bookmark-jump (after org-make-visible activate)
16512 "Make the position visible."
16513 (org-bookmark-jump-unhide))))
16515 ;; Make sure saveplace show the location if it was hidden
16516 (eval-after-load "saveplace"
16517 '(defadvice save-place-find-file-hook (after org-make-visible activate)
16518 "Make the position visible."
16519 (org-bookmark-jump-unhide)))
16521 (defun org-bookmark-jump-unhide ()
16522 "Unhide the current position, to show the bookmark location."
16523 (and (org-mode-p)
16524 (or (org-invisible-p)
16525 (save-excursion (goto-char (max (point-min) (1- (point))))
16526 (org-invisible-p)))
16527 (org-show-context 'bookmark-jump)))
16529 ;; Make session.el ignore our circular variable
16530 (eval-after-load "session"
16531 '(add-to-list 'session-globals-exclude 'org-mark-ring))
16533 ;;;; Experimental code
16535 (defun org-closed-in-range ()
16536 "Sparse tree of items closed in a certain time range.
16537 Still experimental, may disappear in the future."
16538 (interactive)
16539 ;; Get the time interval from the user.
16540 (let* ((time1 (time-to-seconds
16541 (org-read-date nil 'to-time nil "Starting date: ")))
16542 (time2 (time-to-seconds
16543 (org-read-date nil 'to-time nil "End date:")))
16544 ;; callback function
16545 (callback (lambda ()
16546 (let ((time
16547 (time-to-seconds
16548 (apply 'encode-time
16549 (org-parse-time-string
16550 (match-string 1))))))
16551 ;; check if time in interval
16552 (and (>= time time1) (<= time time2))))))
16553 ;; make tree, check each match with the callback
16554 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
16556 ;;;; Finish up
16558 (provide 'org)
16560 (run-hooks 'org-load-hook)
16562 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
16564 ;;; org.el ends here