Bugfix: Keep todo keyword list valid
[org-mode.git] / lisp / org.el
blobceacb18fd4fbd6121915f2445dc27333248b2b59
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.29trans
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.29trans"
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 checklist: Extra functions for checklists in repeated tasks" org-checklist)
188 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
189 (const :tag "C collector: Collect properties into tables" org-collector)
190 (const :tag "C depend: TODO dependencies for Org-mode (PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
191 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
192 (const :tag "C eval: Include command output as text" org-eval)
193 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
194 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
195 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
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 (const :tag "C track: Keep up with Org development" org-track)
211 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
213 (defcustom org-support-shift-select nil
214 "Non-nil means, make shift-cursor commands select text when possible.
216 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
217 selecting a region, or enlarge thusly regions started in this way.
218 In Org-mode, in special contexts, these same keys are used for other
219 purposes, important enough to compete with shift selection. Org tries
220 to balance these needs by supporting `shift-select-mode' outside these
221 special contexts, under control of this variable.
223 The default of this variable is nil, to avoid confusing behavior. Shifted
224 cursor keys will then execute Org commands in the following contexts:
225 - on a headline, changing TODO state (left/right) and priority (up/down)
226 - on a time stamp, changing the time
227 - in a plain list item, changing the bullet type
228 - in a property definition line, switching between allowed values
229 - in the BEGIN line of a clock table (changing the time block).
230 Outside these contexts, the commands will throw an error.
232 When this variable is t and the cursor is not in a special context,
233 Org-mode will support shift-selection for making and enlarging regions.
234 To make this more effective, the bullet cycling will no longer happen
235 anywhere in an item line, but only if the cursor is exactly on the bullet.
237 If you set this variable to the symbol `always', then the keys
238 will not be special in headlines, property lines, and item lines, to make
239 shift selection work there as well. If this is what you want, you can
240 use the following alternative commands: `C-c C-t' and `C-c ,' to
241 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
242 TODO sets, `C-c -' to cycle item bullet types, and properties can be
243 edited by hand or in column view.
245 However, when the cursor is on a timestamp, shift-cursor commands
246 will still edit the time stamp - this is just too good to give up.
248 XEmacs user should have this variable set to nil, because shift-select-mode
249 is Emacs 23 only."
250 :group 'org
251 :type '(choice
252 (const :tag "Never" nil)
253 (const :tag "When outside special context" t)
254 (const :tag "Everywhere except timestamps" always)))
256 (defgroup org-startup nil
257 "Options concerning startup of Org-mode."
258 :tag "Org Startup"
259 :group 'org)
261 (defcustom org-startup-folded t
262 "Non-nil means, entering Org-mode will switch to OVERVIEW.
263 This can also be configured on a per-file basis by adding one of
264 the following lines anywhere in the buffer:
266 #+STARTUP: fold
267 #+STARTUP: nofold
268 #+STARTUP: content"
269 :group 'org-startup
270 :type '(choice
271 (const :tag "nofold: show all" nil)
272 (const :tag "fold: overview" t)
273 (const :tag "content: all headlines" content)))
275 (defcustom org-startup-truncated t
276 "Non-nil means, entering Org-mode will set `truncate-lines'.
277 This is useful since some lines containing links can be very long and
278 uninteresting. Also tables look terrible when wrapped."
279 :group 'org-startup
280 :type 'boolean)
282 (defcustom org-startup-indented nil
283 "Non-nil means, turn on `org-indent-mode' on startup.
284 This can also be configured on a per-file basis by adding one of
285 the following lines anywhere in the buffer:
287 #+STARTUP: indent
288 #+STARTUP: noindent"
289 :group 'org-structure
290 :type '(choice
291 (const :tag "Not" nil)
292 (const :tag "Globally (slow on startup in large files)" t)))
294 (defcustom org-startup-align-all-tables nil
295 "Non-nil means, align all tables when visiting a file.
296 This is useful when the column width in tables is forced with <N> cookies
297 in table fields. Such tables will look correct only after the first re-align.
298 This can also be configured on a per-file basis by adding one of
299 the following lines anywhere in the buffer:
300 #+STARTUP: align
301 #+STARTUP: noalign"
302 :group 'org-startup
303 :type 'boolean)
305 (defcustom org-insert-mode-line-in-empty-file nil
306 "Non-nil means insert the first line setting Org-mode in empty files.
307 When the function `org-mode' is called interactively in an empty file, this
308 normally means that the file name does not automatically trigger Org-mode.
309 To ensure that the file will always be in Org-mode in the future, a
310 line enforcing Org-mode will be inserted into the buffer, if this option
311 has been set."
312 :group 'org-startup
313 :type 'boolean)
315 (defcustom org-replace-disputed-keys nil
316 "Non-nil means use alternative key bindings for some keys.
317 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
318 These keys are also used by other packages like shift-selection-mode'
319 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
320 If you want to use Org-mode together with one of these other modes,
321 or more generally if you would like to move some Org-mode commands to
322 other keys, set this variable and configure the keys with the variable
323 `org-disputed-keys'.
325 This option is only relevant at load-time of Org-mode, and must be set
326 *before* org.el is loaded. Changing it requires a restart of Emacs to
327 become effective."
328 :group 'org-startup
329 :type 'boolean)
331 (defcustom org-use-extra-keys nil
332 "Non-nil means use extra key sequence definitions for certain
333 commands. This happens automatically if you run XEmacs or if
334 window-system is nil. This variable lets you do the same
335 manually. You must set it before loading org.
337 Example: on Carbon Emacs 22 running graphically, with an external
338 keyboard on a Powerbook, the default way of setting M-left might
339 not work for either Alt or ESC. Setting this variable will make
340 it work for ESC."
341 :group 'org-startup
342 :type 'boolean)
344 (if (fboundp 'defvaralias)
345 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
347 (defcustom org-disputed-keys
348 '(([(shift up)] . [(meta p)])
349 ([(shift down)] . [(meta n)])
350 ([(shift left)] . [(meta -)])
351 ([(shift right)] . [(meta +)])
352 ([(control shift right)] . [(meta shift +)])
353 ([(control shift left)] . [(meta shift -)]))
354 "Keys for which Org-mode and other modes compete.
355 This is an alist, cars are the default keys, second element specifies
356 the alternative to use when `org-replace-disputed-keys' is t.
358 Keys can be specified in any syntax supported by `define-key'.
359 The value of this option takes effect only at Org-mode's startup,
360 therefore you'll have to restart Emacs to apply it after changing."
361 :group 'org-startup
362 :type 'alist)
364 (defun org-key (key)
365 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
366 Or return the original if not disputed."
367 (if org-replace-disputed-keys
368 (let* ((nkey (key-description key))
369 (x (org-find-if (lambda (x)
370 (equal (key-description (car x)) nkey))
371 org-disputed-keys)))
372 (if x (cdr x) key))
373 key))
375 (defun org-find-if (predicate seq)
376 (catch 'exit
377 (while seq
378 (if (funcall predicate (car seq))
379 (throw 'exit (car seq))
380 (pop seq)))))
382 (defun org-defkey (keymap key def)
383 "Define a key, possibly translated, as returned by `org-key'."
384 (define-key keymap (org-key key) def))
386 (defcustom org-ellipsis nil
387 "The ellipsis to use in the Org-mode outline.
388 When nil, just use the standard three dots. When a string, use that instead,
389 When a face, use the standard 3 dots, but with the specified face.
390 The change affects only Org-mode (which will then use its own display table).
391 Changing this requires executing `M-x org-mode' in a buffer to become
392 effective."
393 :group 'org-startup
394 :type '(choice (const :tag "Default" nil)
395 (face :tag "Face" :value org-warning)
396 (string :tag "String" :value "...#")))
398 (defvar org-display-table nil
399 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
401 (defgroup org-keywords nil
402 "Keywords in Org-mode."
403 :tag "Org Keywords"
404 :group 'org)
406 (defcustom org-deadline-string "DEADLINE:"
407 "String to mark deadline entries.
408 A deadline is this string, followed by a time stamp. Should be a word,
409 terminated by a colon. You can insert a schedule keyword and
410 a timestamp with \\[org-deadline].
411 Changes become only effective after restarting Emacs."
412 :group 'org-keywords
413 :type 'string)
415 (defcustom org-scheduled-string "SCHEDULED:"
416 "String to mark scheduled TODO entries.
417 A schedule is this string, followed by a time stamp. Should be a word,
418 terminated by a colon. You can insert a schedule keyword and
419 a timestamp with \\[org-schedule].
420 Changes become only effective after restarting Emacs."
421 :group 'org-keywords
422 :type 'string)
424 (defcustom org-closed-string "CLOSED:"
425 "String used as the prefix for timestamps logging closing a TODO entry."
426 :group 'org-keywords
427 :type 'string)
429 (defcustom org-clock-string "CLOCK:"
430 "String used as prefix for timestamps clocking work hours on an item."
431 :group 'org-keywords
432 :type 'string)
434 (defcustom org-comment-string "COMMENT"
435 "Entries starting with this keyword will never be exported.
436 An entry can be toggled between COMMENT and normal with
437 \\[org-toggle-comment].
438 Changes become only effective after restarting Emacs."
439 :group 'org-keywords
440 :type 'string)
442 (defcustom org-quote-string "QUOTE"
443 "Entries starting with this keyword will be exported in fixed-width font.
444 Quoting applies only to the text in the entry following the headline, and does
445 not extend beyond the next headline, even if that is lower level.
446 An entry can be toggled between QUOTE and normal with
447 \\[org-toggle-fixed-width-section]."
448 :group 'org-keywords
449 :type 'string)
451 (defconst org-repeat-re
452 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
453 "Regular expression for specifying repeated events.
454 After a match, group 1 contains the repeat expression.")
456 (defgroup org-structure nil
457 "Options concerning the general structure of Org-mode files."
458 :tag "Org Structure"
459 :group 'org)
461 (defgroup org-reveal-location nil
462 "Options about how to make context of a location visible."
463 :tag "Org Reveal Location"
464 :group 'org-structure)
466 (defconst org-context-choice
467 '(choice
468 (const :tag "Always" t)
469 (const :tag "Never" nil)
470 (repeat :greedy t :tag "Individual contexts"
471 (cons
472 (choice :tag "Context"
473 (const agenda)
474 (const org-goto)
475 (const occur-tree)
476 (const tags-tree)
477 (const link-search)
478 (const mark-goto)
479 (const bookmark-jump)
480 (const isearch)
481 (const default))
482 (boolean))))
483 "Contexts for the reveal options.")
485 (defcustom org-show-hierarchy-above '((default . t))
486 "Non-nil means, show full hierarchy when revealing a location.
487 Org-mode often shows locations in an org-mode file which might have
488 been invisible before. When this is set, the hierarchy of headings
489 above the exposed location is shown.
490 Turning this off for example for sparse trees makes them very compact.
491 Instead of t, this can also be an alist specifying this option for different
492 contexts. Valid contexts are
493 agenda when exposing an entry from the agenda
494 org-goto when using the command `org-goto' on key C-c C-j
495 occur-tree when using the command `org-occur' on key C-c /
496 tags-tree when constructing a sparse tree based on tags matches
497 link-search when exposing search matches associated with a link
498 mark-goto when exposing the jump goal of a mark
499 bookmark-jump when exposing a bookmark location
500 isearch when exiting from an incremental search
501 default default for all contexts not set explicitly"
502 :group 'org-reveal-location
503 :type org-context-choice)
505 (defcustom org-show-following-heading '((default . nil))
506 "Non-nil means, show following 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 heading following the
509 match is shown.
510 Turning this off for example for sparse trees makes them very compact,
511 but makes it harder to edit the location of the match. In such a case,
512 use the command \\[org-reveal] to show more context.
513 Instead of t, this can also be an alist specifying this option for different
514 contexts. See `org-show-hierarchy-above' for valid contexts."
515 :group 'org-reveal-location
516 :type org-context-choice)
518 (defcustom org-show-siblings '((default . nil) (isearch t))
519 "Non-nil means, show all sibling heading when revealing a location.
520 Org-mode often shows locations in an org-mode file which might have
521 been invisible before. When this is set, the sibling of the current entry
522 heading are all made visible. If `org-show-hierarchy-above' is t,
523 the same happens on each level of the hierarchy above the current entry.
525 By default this is on for the isearch context, off for all other contexts.
526 Turning this off for example for sparse trees makes them very compact,
527 but makes it harder to edit the location of the match. In such a case,
528 use the command \\[org-reveal] to show more context.
529 Instead of t, this can also be an alist specifying this option for different
530 contexts. See `org-show-hierarchy-above' for valid contexts."
531 :group 'org-reveal-location
532 :type org-context-choice)
534 (defcustom org-show-entry-below '((default . nil))
535 "Non-nil means, show the entry below a headline when revealing a location.
536 Org-mode often shows locations in an org-mode file which might have
537 been invisible before. When this is set, the text below the headline that is
538 exposed is also shown.
540 By default this is off for all contexts.
541 Instead of t, this can also be an alist specifying this option for different
542 contexts. See `org-show-hierarchy-above' for valid contexts."
543 :group 'org-reveal-location
544 :type org-context-choice)
546 (defcustom org-indirect-buffer-display 'other-window
547 "How should indirect tree buffers be displayed?
548 This applies to indirect buffers created with the commands
549 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
550 Valid values are:
551 current-window Display in the current window
552 other-window Just display in another window.
553 dedicated-frame Create one new frame, and re-use it each time.
554 new-frame Make a new frame each time. Note that in this case
555 previously-made indirect buffers are kept, and you need to
556 kill these buffers yourself."
557 :group 'org-structure
558 :group 'org-agenda-windows
559 :type '(choice
560 (const :tag "In current window" current-window)
561 (const :tag "In current frame, other window" other-window)
562 (const :tag "Each time a new frame" new-frame)
563 (const :tag "One dedicated frame" dedicated-frame)))
565 (defgroup org-cycle nil
566 "Options concerning visibility cycling in Org-mode."
567 :tag "Org Cycle"
568 :group 'org-structure)
570 (defcustom org-cycle-skip-children-state-if-no-children t
571 "Non-nil means, skip CHILDREN state in entries that don't have any."
572 :group 'org-cycle
573 :type 'boolean)
575 (defcustom org-cycle-max-level nil
576 "Maximum level which should still be subject to visibility cycling.
577 Levels higher than this will, for cycling, be treated as text, not a headline.
578 When `org-odd-levels-only' is set, a value of N in this variable actually
579 means 2N-1 stars as the limiting headline.
580 When nil, cycle all levels.
581 Note that the limiting level of cycling is also influenced by
582 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
583 `org-inlinetask-min-level' is, cycling will be limited to levels one less
584 than its value."
585 :group 'org-cycle
586 :type '(choice
587 (const :tag "No limit" nil)
588 (integer :tag "Maximum level")))
590 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
591 "Names of drawers. Drawers are not opened by cycling on the headline above.
592 Drawers only open with a TAB on the drawer line itself. A drawer looks like
593 this:
594 :DRAWERNAME:
595 .....
596 :END:
597 The drawer \"PROPERTIES\" is special for capturing properties through
598 the property API.
600 Drawers can be defined on the per-file basis with a line like:
602 #+DRAWERS: HIDDEN STATE PROPERTIES"
603 :group 'org-structure
604 :group 'org-cycle
605 :type '(repeat (string :tag "Drawer Name")))
607 (defcustom org-hide-block-startup nil
608 "Non-nil means, , entering Org-mode will fold all blocks.
609 This can also be set in on a per-file basis with
611 #+STARTUP: hideblocks
612 #+STARTUP: showblocks"
613 :group 'org-startup
614 :group 'org-cycle
615 :type 'boolean)
617 (defcustom org-cycle-global-at-bob nil
618 "Cycle globally if cursor is at beginning of buffer and not at a headline.
619 This makes it possible to do global cycling without having to use S-TAB or
620 C-u TAB. For this special case to work, the first line of the buffer
621 must not be a headline - it may be empty or some other text. When used in
622 this way, `org-cycle-hook' is disables temporarily, to make sure the
623 cursor stays at the beginning of the buffer.
624 When this option is nil, don't do anything special at the beginning
625 of the buffer."
626 :group 'org-cycle
627 :type 'boolean)
629 (defcustom org-cycle-emulate-tab t
630 "Where should `org-cycle' emulate TAB.
631 nil Never
632 white Only in completely white lines
633 whitestart Only at the beginning of lines, before the first non-white char
634 t Everywhere except in headlines
635 exc-hl-bol Everywhere except at the start of a headline
636 If TAB is used in a place where it does not emulate TAB, the current subtree
637 visibility is cycled."
638 :group 'org-cycle
639 :type '(choice (const :tag "Never" nil)
640 (const :tag "Only in completely white lines" white)
641 (const :tag "Before first char in a line" whitestart)
642 (const :tag "Everywhere except in headlines" t)
643 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
646 (defcustom org-cycle-separator-lines 2
647 "Number of empty lines needed to keep an empty line between collapsed trees.
648 If you leave an empty line between the end of a subtree and the following
649 headline, this empty line is hidden when the subtree is folded.
650 Org-mode will leave (exactly) one empty line visible if the number of
651 empty lines is equal or larger to the number given in this variable.
652 So the default 2 means, at least 2 empty lines after the end of a subtree
653 are needed to produce free space between a collapsed subtree and the
654 following headline.
656 Special case: when 0, never leave empty lines in collapsed view."
657 :group 'org-cycle
658 :type 'integer)
659 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
661 (defcustom org-pre-cycle-hook nil
662 "Hook that is run before visibility cycling is happening.
663 The function(s) in this hook must accept a single argument which indicates
664 the new state that will be set right after running this hook. The
665 argument is a symbol. Before a global state change, it can have the values
666 `overview', `content', or `all'. Before a local state change, it can have
667 the values `folded', `children', or `subtree'."
668 :group 'org-cycle
669 :type 'hook)
671 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
672 org-cycle-hide-drawers
673 org-cycle-show-empty-lines
674 org-optimize-window-after-visibility-change)
675 "Hook that is run after `org-cycle' has changed the buffer visibility.
676 The function(s) in this hook must accept a single argument which indicates
677 the new state that was set by the most recent `org-cycle' command. The
678 argument is a symbol. After a global state change, it can have the values
679 `overview', `content', or `all'. After a local state change, it can have
680 the values `folded', `children', or `subtree'."
681 :group 'org-cycle
682 :type 'hook)
684 (defgroup org-edit-structure nil
685 "Options concerning structure editing in Org-mode."
686 :tag "Org Edit Structure"
687 :group 'org-structure)
689 (defcustom org-odd-levels-only nil
690 "Non-nil means, skip even levels and only use odd levels for the outline.
691 This has the effect that two stars are being added/taken away in
692 promotion/demotion commands. It also influences how levels are
693 handled by the exporters.
694 Changing it requires restart of `font-lock-mode' to become effective
695 for fontification also in regions already fontified.
696 You may also set this on a per-file basis by adding one of the following
697 lines to the buffer:
699 #+STARTUP: odd
700 #+STARTUP: oddeven"
701 :group 'org-edit-structure
702 :group 'org-font-lock
703 :type 'boolean)
705 (defcustom org-adapt-indentation t
706 "Non-nil means, adapt indentation to outline node level.
708 When this variable is set, Org assumes that you write outlines by
709 indenting text in each node to align with the headline (after the stars).
710 The following issues are influenced by this variable:
712 - When this is set and the *entire* text in an entry is indented, the
713 indentation is increased by one space in a demotion command, and
714 decreased by one in a promotion command. If any line in the entry
715 body starts with text at column 0, indentation is not changed at all.
717 - Property drawers and planning information is inserted indented when
718 this variable s set. When nil, they will not be indented.
720 - TAB indents a line relative to context. The lines below a headline
721 will be indented when this variable is set.
723 Note that this is all about true indentation, by adding and removing
724 space characters. See also `org-indent.el' which does level-dependent
725 indentation in a virtual way, i.e. at display time in Emacs."
726 :group 'org-edit-structure
727 :type 'boolean)
729 (defcustom org-special-ctrl-a/e nil
730 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
732 When t, `C-a' will bring back the cursor to the beginning of the
733 headline text, i.e. after the stars and after a possible TODO keyword.
734 In an item, this will be the position after the bullet.
735 When the cursor is already at that position, another `C-a' will bring
736 it to the beginning of the line.
738 `C-e' will jump to the end of the headline, ignoring the presence of tags
739 in the headline. A second `C-e' will then jump to the true end of the
740 line, after any tags.
742 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
743 going to the true line boundary first. Only a directly following, identical
744 keypress will bring the cursor to the special positions.
746 This may also be a cons cell where the behavior for `C-a' and `C-e' is
747 set separately."
748 :group 'org-edit-structure
749 :type '(choice
750 (const :tag "off" nil)
751 (const :tag "after stars/bullet and before tags first" t)
752 (const :tag "true line boundary first" reversed)
753 (cons :tag "Set C-a and C-e separately"
754 (choice :tag "Special C-a"
755 (const :tag "off" nil)
756 (const :tag "after stars/bullet first" t)
757 (const :tag "before stars/bullet first" reversed))
758 (choice :tag "Special C-e"
759 (const :tag "off" nil)
760 (const :tag "before tags first" t)
761 (const :tag "after tags first" reversed)))))
762 (if (fboundp 'defvaralias)
763 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
765 (defcustom org-special-ctrl-k nil
766 "Non-nil means `C-k' will behave specially in headlines.
767 When nil, `C-k' will call the default `kill-line' command.
768 When t, the following will happen while the cursor is in the headline:
770 - When the cursor is at the beginning of a headline, kill the entire
771 line and possible the folded subtree below the line.
772 - When in the middle of the headline text, kill the headline up to the tags.
773 - When after the headline text, kill the tags."
774 :group 'org-edit-structure
775 :type 'boolean)
777 (defcustom org-yank-folded-subtrees t
778 "Non-nil means, when yanking subtrees, fold them.
779 If the kill is a single subtree, or a sequence of subtrees, i.e. if
780 it starts with a heading and all other headings in it are either children
781 or siblings, then fold all the subtrees. However, do this only if no
782 text after the yank would be swallowed into a folded tree by this action."
783 :group 'org-edit-structure
784 :type 'boolean)
786 (defcustom org-yank-adjusted-subtrees nil
787 "Non-nil means, when yanking subtrees, adjust the level.
788 With this setting, `org-paste-subtree' is used to insert the subtree, see
789 this function for details."
790 :group 'org-edit-structure
791 :type 'boolean)
793 (defcustom org-M-RET-may-split-line '((default . t))
794 "Non-nil means, M-RET will split the line at the cursor position.
795 When nil, it will go to the end of the line before making a
796 new line.
797 You may also set this option in a different way for different
798 contexts. Valid contexts are:
800 headline when creating a new headline
801 item when creating a new item
802 table in a table field
803 default the value to be used for all contexts not explicitly
804 customized"
805 :group 'org-structure
806 :group 'org-table
807 :type '(choice
808 (const :tag "Always" t)
809 (const :tag "Never" nil)
810 (repeat :greedy t :tag "Individual contexts"
811 (cons
812 (choice :tag "Context"
813 (const headline)
814 (const item)
815 (const table)
816 (const default))
817 (boolean)))))
820 (defcustom org-insert-heading-respect-content nil
821 "Non-nil means, insert new headings after the current subtree.
822 When nil, the new heading is created directly after the current line.
823 The commands \\[org-insert-heading-respect-content] and
824 \\[org-insert-todo-heading-respect-content] turn this variable on
825 for the duration of the command."
826 :group 'org-structure
827 :type 'boolean)
829 (defcustom org-blank-before-new-entry '((heading . auto)
830 (plain-list-item . auto))
831 "Should `org-insert-heading' leave a blank line before new heading/item?
832 The value is an alist, with `heading' and `plain-list-item' as car,
833 and a boolean flag as cdr. For plain lists, if the variable
834 `org-empty-line-terminates-plain-lists' is set, the setting here
835 is ignored and no empty line is inserted, to keep the list in tact."
836 :group 'org-edit-structure
837 :type '(list
838 (cons (const heading)
839 (choice (const :tag "Never" nil)
840 (const :tag "Always" t)
841 (const :tag "Auto" auto)))
842 (cons (const plain-list-item)
843 (choice (const :tag "Never" nil)
844 (const :tag "Always" t)
845 (const :tag "Auto" auto)))))
847 (defcustom org-insert-heading-hook nil
848 "Hook being run after inserting a new heading."
849 :group 'org-edit-structure
850 :type 'hook)
852 (defcustom org-enable-fixed-width-editor t
853 "Non-nil means, lines starting with \":\" are treated as fixed-width.
854 This currently only means, they are never auto-wrapped.
855 When nil, such lines will be treated like ordinary lines.
856 See also the QUOTE keyword."
857 :group 'org-edit-structure
858 :type 'boolean)
861 (defcustom org-goto-auto-isearch t
862 "Non-nil means, typing characters in org-goto starts incremental search."
863 :group 'org-edit-structure
864 :type 'boolean)
866 (defgroup org-sparse-trees nil
867 "Options concerning sparse trees in Org-mode."
868 :tag "Org Sparse Trees"
869 :group 'org-structure)
871 (defcustom org-highlight-sparse-tree-matches t
872 "Non-nil means, highlight all matches that define a sparse tree.
873 The highlights will automatically disappear the next time the buffer is
874 changed by an edit command."
875 :group 'org-sparse-trees
876 :type 'boolean)
878 (defcustom org-remove-highlights-with-change t
879 "Non-nil means, any change to the buffer will remove temporary highlights.
880 Such highlights are created by `org-occur' and `org-clock-display'.
881 When nil, `C-c C-c needs to be used to get rid of the highlights.
882 The highlights created by `org-preview-latex-fragment' always need
883 `C-c C-c' to be removed."
884 :group 'org-sparse-trees
885 :group 'org-time
886 :type 'boolean)
889 (defcustom org-occur-hook '(org-first-headline-recenter)
890 "Hook that is run after `org-occur' has constructed a sparse tree.
891 This can be used to recenter the window to show as much of the structure
892 as possible."
893 :group 'org-sparse-trees
894 :type 'hook)
896 (defgroup org-imenu-and-speedbar nil
897 "Options concerning imenu and speedbar in Org-mode."
898 :tag "Org Imenu and Speedbar"
899 :group 'org-structure)
901 (defcustom org-imenu-depth 2
902 "The maximum level for Imenu access to Org-mode headlines.
903 This also applied for speedbar access."
904 :group 'org-imenu-and-speedbar
905 :type 'integer)
907 (defgroup org-table nil
908 "Options concerning tables in Org-mode."
909 :tag "Org Table"
910 :group 'org)
912 (defcustom org-enable-table-editor 'optimized
913 "Non-nil means, lines starting with \"|\" are handled by the table editor.
914 When nil, such lines will be treated like ordinary lines.
916 When equal to the symbol `optimized', the table editor will be optimized to
917 do the following:
918 - Automatic overwrite mode in front of whitespace in table fields.
919 This makes the structure of the table stay in tact as long as the edited
920 field does not exceed the column width.
921 - Minimize the number of realigns. Normally, the table is aligned each time
922 TAB or RET are pressed to move to another field. With optimization this
923 happens only if changes to a field might have changed the column width.
924 Optimization requires replacing the functions `self-insert-command',
925 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
926 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
927 very good at guessing when a re-align will be necessary, but you can always
928 force one with \\[org-ctrl-c-ctrl-c].
930 If you would like to use the optimized version in Org-mode, but the
931 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
933 This variable can be used to turn on and off the table editor during a session,
934 but in order to toggle optimization, a restart is required.
936 See also the variable `org-table-auto-blank-field'."
937 :group 'org-table
938 :type '(choice
939 (const :tag "off" nil)
940 (const :tag "on" t)
941 (const :tag "on, optimized" optimized)))
943 (defcustom org-self-insert-cluster-for-undo t
944 "Non-nil means cluster self-insert commands for undo when possible.
945 If this is set, then, like in the Emacs command loop, 20 consequtive
946 characters will be undone together.
947 This is configurable, because there is some impact on typing performance."
948 :group 'org-table
949 :type 'boolean)
951 (defcustom org-table-tab-recognizes-table.el t
952 "Non-nil means, TAB will automatically notice a table.el table.
953 When it sees such a table, it moves point into it and - if necessary -
954 calls `table-recognize-table'."
955 :group 'org-table-editing
956 :type 'boolean)
958 (defgroup org-link nil
959 "Options concerning links in Org-mode."
960 :tag "Org Link"
961 :group 'org)
963 (defvar org-link-abbrev-alist-local nil
964 "Buffer-local version of `org-link-abbrev-alist', which see.
965 The value of this is taken from the #+LINK lines.")
966 (make-variable-buffer-local 'org-link-abbrev-alist-local)
968 (defcustom org-link-abbrev-alist nil
969 "Alist of link abbreviations.
970 The car of each element is a string, to be replaced at the start of a link.
971 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
972 links in Org-mode buffers can have an optional tag after a double colon, e.g.
974 [[linkkey:tag][description]]
976 The 'linkkey' must be a word word, starting with a letter, followed
977 by letters, numbers, '-' or '_'.
979 If REPLACE is a string, the tag will simply be appended to create the link.
980 If the string contains \"%s\", the tag will be inserted there. Alternatively,
981 the placeholder \"%h\" will cause a url-encoded version of the tag to
982 be inserted at that point (see the function `url-hexify-string').
984 REPLACE may also be a function that will be called with the tag as the
985 only argument to create the link, which should be returned as a string.
987 See the manual for examples."
988 :group 'org-link
989 :type '(repeat
990 (cons
991 (string :tag "Protocol")
992 (choice
993 (string :tag "Format")
994 (function)))))
996 (defcustom org-descriptive-links t
997 "Non-nil means, hide link part and only show description of bracket links.
998 Bracket links are like [[link][description]]. This variable sets the initial
999 state in new org-mode buffers. The setting can then be toggled on a
1000 per-buffer basis from the Org->Hyperlinks menu."
1001 :group 'org-link
1002 :type 'boolean)
1004 (defcustom org-link-file-path-type 'adaptive
1005 "How the path name in file links should be stored.
1006 Valid values are:
1008 relative Relative to the current directory, i.e. the directory of the file
1009 into which the link is being inserted.
1010 absolute Absolute path, if possible with ~ for home directory.
1011 noabbrev Absolute path, no abbreviation of home directory.
1012 adaptive Use relative path for files in the current directory and sub-
1013 directories of it. For other files, use an absolute path."
1014 :group 'org-link
1015 :type '(choice
1016 (const relative)
1017 (const absolute)
1018 (const noabbrev)
1019 (const adaptive)))
1021 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1022 "Types of links that should be activated in Org-mode files.
1023 This is a list of symbols, each leading to the activation of a certain link
1024 type. In principle, it does not hurt to turn on most link types - there may
1025 be a small gain when turning off unused link types. The types are:
1027 bracket The recommended [[link][description]] or [[link]] links with hiding.
1028 angular Links in angular brackets that may contain whitespace like
1029 <bbdb:Carsten Dominik>.
1030 plain Plain links in normal text, no whitespace, like http://google.com.
1031 radio Text that is matched by a radio target, see manual for details.
1032 tag Tag settings in a headline (link to tag search).
1033 date Time stamps (link to calendar).
1034 footnote Footnote labels.
1036 Changing this variable requires a restart of Emacs to become effective."
1037 :group 'org-link
1038 :type '(set :greedy t
1039 (const :tag "Double bracket links (new style)" bracket)
1040 (const :tag "Angular bracket links (old style)" angular)
1041 (const :tag "Plain text links" plain)
1042 (const :tag "Radio target matches" radio)
1043 (const :tag "Tags" tag)
1044 (const :tag "Timestamps" date)
1045 (const :tag "Footnotes" footnote)))
1047 (defcustom org-make-link-description-function nil
1048 "Function to use to generate link descriptions from links. If
1049 nil the link location will be used. This function must take two
1050 parameters; the first is the link and the second the description
1051 org-insert-link has generated, and should return the description
1052 to use."
1053 :group 'org-link
1054 :type 'function)
1056 (defgroup org-link-store nil
1057 "Options concerning storing links in Org-mode."
1058 :tag "Org Store Link"
1059 :group 'org-link)
1061 (defcustom org-email-link-description-format "Email %c: %.30s"
1062 "Format of the description part of a link to an email or usenet message.
1063 The following %-escapes will be replaced by corresponding information:
1065 %F full \"From\" field
1066 %f name, taken from \"From\" field, address if no name
1067 %T full \"To\" field
1068 %t first name in \"To\" field, address if no name
1069 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1070 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1071 %s subject
1072 %m message-id.
1074 You may use normal field width specification between the % and the letter.
1075 This is for example useful to limit the length of the subject.
1077 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1078 :group 'org-link-store
1079 :type 'string)
1081 (defcustom org-from-is-user-regexp
1082 (let (r1 r2)
1083 (when (and user-mail-address (not (string= user-mail-address "")))
1084 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1085 (when (and user-full-name (not (string= user-full-name "")))
1086 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1087 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1088 "Regexp matched against the \"From:\" header of an email or usenet message.
1089 It should match if the message is from the user him/herself."
1090 :group 'org-link-store
1091 :type 'regexp)
1093 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1094 "Non-nil means, storing a link to an Org file will use entry IDs.
1096 Note that before this variable is even considered, org-id must be loaded,
1097 so please customize `org-modules' and turn it on.
1099 The variable can have the following values:
1101 t Create an ID if needed to make a link to the current entry.
1103 create-if-interactive
1104 If `org-store-link' is called directly (interactively, as a user
1105 command), do create an ID to support the link. But when doing the
1106 job for remember, only use the ID if it already exists. The
1107 purpose of this setting is to avoid proliferation of unwanted
1108 IDs, just because you happen to be in an Org file when you
1109 call `org-remember' that automatically and preemptively
1110 creates a link. If you do want to get an ID link in a remember
1111 template to an entry not having an ID, create it first by
1112 explicitly creating a link to it, using `C-c C-l' first.
1114 create-if-interactive-and-no-custom-id
1115 Like create-if-interactive, but do not create an ID if there is
1116 a CUSTOM_ID property defined in the entry. This is the default.
1118 use-existing
1119 Use existing ID, do not create one.
1121 nil Never use an ID to make a link, instead link using a text search for
1122 the headline text."
1123 :group 'org-link-store
1124 :type '(choice
1125 (const :tag "Create ID to make link" t)
1126 (const :tag "Create if storing link interactively"
1127 create-if-interactive)
1128 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1129 create-if-interactive-and-no-custom-id)
1130 (const :tag "Only use existing" use-existing)
1131 (const :tag "Do not use ID to create link" nil)))
1133 (defcustom org-context-in-file-links t
1134 "Non-nil means, file links from `org-store-link' contain context.
1135 A search string will be added to the file name with :: as separator and
1136 used to find the context when the link is activated by the command
1137 `org-open-at-point'.
1138 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1139 negates this setting for the duration of the command."
1140 :group 'org-link-store
1141 :type 'boolean)
1143 (defcustom org-keep-stored-link-after-insertion nil
1144 "Non-nil means, keep link in list for entire session.
1146 The command `org-store-link' adds a link pointing to the current
1147 location to an internal list. These links accumulate during a session.
1148 The command `org-insert-link' can be used to insert links into any
1149 Org-mode file (offering completion for all stored links). When this
1150 option is nil, every link which has been inserted once using \\[org-insert-link]
1151 will be removed from the list, to make completing the unused links
1152 more efficient."
1153 :group 'org-link-store
1154 :type 'boolean)
1156 (defgroup org-link-follow nil
1157 "Options concerning following links in Org-mode."
1158 :tag "Org Follow Link"
1159 :group 'org-link)
1161 (defcustom org-link-translation-function nil
1162 "Function to translate links with different syntax to Org syntax.
1163 This can be used to translate links created for example by the Planner
1164 or emacs-wiki packages to Org syntax.
1165 The function must accept two parameters, a TYPE containing the link
1166 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1167 which is everything after the link protocol. It should return a cons
1168 with possibly modified values of type and path.
1169 Org contains a function for this, so if you set this variable to
1170 `org-translate-link-from-planner', you should be able follow many
1171 links created by planner."
1172 :group 'org-link-follow
1173 :type 'function)
1175 (defcustom org-follow-link-hook nil
1176 "Hook that is run after a link has been followed."
1177 :group 'org-link-follow
1178 :type 'hook)
1180 (defcustom org-tab-follows-link nil
1181 "Non-nil means, on links TAB will follow the link.
1182 Needs to be set before org.el is loaded.
1183 This really should not be used, it does not make sense, and the
1184 implementation is bad."
1185 :group 'org-link-follow
1186 :type 'boolean)
1188 (defcustom org-return-follows-link nil
1189 "Non-nil means, on links RET will follow the link.
1190 Needs to be set before org.el is loaded."
1191 :group 'org-link-follow
1192 :type 'boolean)
1194 (defcustom org-mouse-1-follows-link
1195 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1196 "Non-nil means, mouse-1 on a link will follow the link.
1197 A longer mouse click will still set point. Does not work on XEmacs.
1198 Needs to be set before org.el is loaded."
1199 :group 'org-link-follow
1200 :type 'boolean)
1202 (defcustom org-mark-ring-length 4
1203 "Number of different positions to be recorded in the ring
1204 Changing this requires a restart of Emacs to work correctly."
1205 :group 'org-link-follow
1206 :type 'integer)
1208 (defcustom org-link-frame-setup
1209 '((vm . vm-visit-folder-other-frame)
1210 (gnus . gnus-other-frame)
1211 (file . find-file-other-window))
1212 "Setup the frame configuration for following links.
1213 When following a link with Emacs, it may often be useful to display
1214 this link in another window or frame. This variable can be used to
1215 set this up for the different types of links.
1216 For VM, use any of
1217 `vm-visit-folder'
1218 `vm-visit-folder-other-frame'
1219 For Gnus, use any of
1220 `gnus'
1221 `gnus-other-frame'
1222 `org-gnus-no-new-news'
1223 For FILE, use any of
1224 `find-file'
1225 `find-file-other-window'
1226 `find-file-other-frame'
1227 For the calendar, use the variable `calendar-setup'.
1228 For BBDB, it is currently only possible to display the matches in
1229 another window."
1230 :group 'org-link-follow
1231 :type '(list
1232 (cons (const vm)
1233 (choice
1234 (const vm-visit-folder)
1235 (const vm-visit-folder-other-window)
1236 (const vm-visit-folder-other-frame)))
1237 (cons (const gnus)
1238 (choice
1239 (const gnus)
1240 (const gnus-other-frame)
1241 (const org-gnus-no-new-news)))
1242 (cons (const file)
1243 (choice
1244 (const find-file)
1245 (const find-file-other-window)
1246 (const find-file-other-frame)))))
1248 (defcustom org-display-internal-link-with-indirect-buffer nil
1249 "Non-nil means, use indirect buffer to display infile links.
1250 Activating internal links (from one location in a file to another location
1251 in the same file) normally just jumps to the location. When the link is
1252 activated with a C-u prefix (or with mouse-3), the link is displayed in
1253 another window. When this option is set, the other window actually displays
1254 an indirect buffer clone of the current buffer, to avoid any visibility
1255 changes to the current buffer."
1256 :group 'org-link-follow
1257 :type 'boolean)
1259 (defcustom org-open-non-existing-files nil
1260 "Non-nil means, `org-open-file' will open non-existing files.
1261 When nil, an error will be generated.
1262 This variable applies only to external applications because they
1263 might choke on non-existing files. If the link is to a file that
1264 will be openend in Emacs, the variable is ignored."
1265 :group 'org-link-follow
1266 :type 'boolean)
1268 (defcustom org-open-directory-means-index-dot-org nil
1269 "Non-nil means, a link to a directory really means to index.org.
1270 When nil, following a directory link will run dired or open a finder/explorer
1271 window on that directory."
1272 :group 'org-link-follow
1273 :type 'boolean)
1275 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1276 "Function and arguments to call for following mailto links.
1277 This is a list with the first element being a lisp function, and the
1278 remaining elements being arguments to the function. In string arguments,
1279 %a will be replaced by the address, and %s will be replaced by the subject
1280 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1281 :group 'org-link-follow
1282 :type '(choice
1283 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1284 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1285 (const :tag "message-mail" (message-mail "%a" "%s"))
1286 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1288 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1289 "Non-nil means, ask for confirmation before executing shell links.
1290 Shell links can be dangerous: just think about a link
1292 [[shell:rm -rf ~/*][Google Search]]
1294 This link would show up in your Org-mode document as \"Google Search\",
1295 but really it would remove your entire home directory.
1296 Therefore we advise against setting this variable to nil.
1297 Just change it to `y-or-n-p' if you want to confirm with a
1298 single keystroke rather than having to type \"yes\"."
1299 :group 'org-link-follow
1300 :type '(choice
1301 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1302 (const :tag "with y-or-n (faster)" y-or-n-p)
1303 (const :tag "no confirmation (dangerous)" nil)))
1305 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1306 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1307 Elisp links can be dangerous: just think about a link
1309 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1311 This link would show up in your Org-mode document as \"Google Search\",
1312 but really it would remove your entire home directory.
1313 Therefore we advise against setting this variable to nil.
1314 Just change it to `y-or-n-p' if you want to confirm with a
1315 single keystroke rather than having to type \"yes\"."
1316 :group 'org-link-follow
1317 :type '(choice
1318 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1319 (const :tag "with y-or-n (faster)" y-or-n-p)
1320 (const :tag "no confirmation (dangerous)" nil)))
1322 (defconst org-file-apps-defaults-gnu
1323 '((remote . emacs)
1324 (system . mailcap)
1325 (t . mailcap))
1326 "Default file applications on a UNIX or GNU/Linux system.
1327 See `org-file-apps'.")
1329 (defconst org-file-apps-defaults-macosx
1330 '((remote . emacs)
1331 (t . "open %s")
1332 (system . "open %s")
1333 ("ps.gz" . "gv %s")
1334 ("eps.gz" . "gv %s")
1335 ("dvi" . "xdvi %s")
1336 ("fig" . "xfig %s"))
1337 "Default file applications on a MacOS X system.
1338 The system \"open\" is known as a default, but we use X11 applications
1339 for some files for which the OS does not have a good default.
1340 See `org-file-apps'.")
1342 (defconst org-file-apps-defaults-windowsnt
1343 (list
1344 '(remote . emacs)
1345 (cons t
1346 (list (if (featurep 'xemacs)
1347 'mswindows-shell-execute
1348 'w32-shell-execute)
1349 "open" 'file))
1350 (cons 'system
1351 (list (if (featurep 'xemacs)
1352 'mswindows-shell-execute
1353 'w32-shell-execute)
1354 "open" 'file)))
1355 "Default file applications on a Windows NT system.
1356 The system \"open\" is used for most files.
1357 See `org-file-apps'.")
1359 (defcustom org-file-apps
1361 (auto-mode . emacs)
1362 ("\\.x?html?\\'" . default)
1363 ("\\.pdf\\'" . default)
1365 "External applications for opening `file:path' items in a document.
1366 Org-mode uses system defaults for different file types, but
1367 you can use this variable to set the application for a given file
1368 extension. The entries in this list are cons cells where the car identifies
1369 files and the cdr the corresponding command. Possible values for the
1370 file identifier are
1371 \"regex\" Regular expression matched against the file name. For backward
1372 compatibility, this can also be a string with only alphanumeric
1373 characters, which is then interpreted as an extension.
1374 `directory' Matches a directory
1375 `remote' Matches a remote file, accessible through tramp or efs.
1376 Remote files most likely should be visited through Emacs
1377 because external applications cannot handle such paths.
1378 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1379 so all files Emacs knows how to handle. Using this with
1380 command `emacs' will open most files in Emacs. Beware that this
1381 will also open html files inside Emacs, unless you add
1382 (\"html\" . default) to the list as well.
1383 t Default for files not matched by any of the other options.
1384 `system' The system command to open files, like `open' on Windows
1385 and Mac OS X, and mailcap under GNU/Linux. This is the command
1386 that will be selected if you call `C-c C-o' with a double
1387 `C-u C-u' prefix.
1389 Possible values for the command are:
1390 `emacs' The file will be visited by the current Emacs process.
1391 `default' Use the default application for this file type, which is the
1392 association for t in the list, most likely in the system-specific
1393 part.
1394 This can be used to overrule an unwanted setting in the
1395 system-specific variable.
1396 `system' Use the system command for opening files, like \"open\".
1397 This command is specified by the entry whose car is `system'.
1398 Most likely, the system-specific version of this variable
1399 does define this command, but you can overrule/replace it
1400 here.
1401 string A command to be executed by a shell; %s will be replaced
1402 by the path to the file.
1403 sexp A Lisp form which will be evaluated. The file path will
1404 be available in the Lisp variable `file'.
1405 For more examples, see the system specific constants
1406 `org-file-apps-defaults-macosx'
1407 `org-file-apps-defaults-windowsnt'
1408 `org-file-apps-defaults-gnu'."
1409 :group 'org-link-follow
1410 :type '(repeat
1411 (cons (choice :value ""
1412 (string :tag "Extension")
1413 (const :tag "System command to open files" system)
1414 (const :tag "Default for unrecognized files" t)
1415 (const :tag "Remote file" remote)
1416 (const :tag "Links to a directory" directory)
1417 (const :tag "Any files that have Emacs modes"
1418 auto-mode))
1419 (choice :value ""
1420 (const :tag "Visit with Emacs" emacs)
1421 (const :tag "Use default" default)
1422 (const :tag "Use the system command" system)
1423 (string :tag "Command")
1424 (sexp :tag "Lisp form")))))
1426 (defgroup org-refile nil
1427 "Options concerning refiling entries in Org-mode."
1428 :tag "Org Refile"
1429 :group 'org)
1431 (defcustom org-directory "~/org"
1432 "Directory with org files.
1433 This is just a default location to look for Org files. There is no need
1434 at all to put your files into this directory. It is only used in the
1435 following situations:
1437 1. When a remember template specifies a target file that is not an
1438 absolute path. The path will then be interpreted relative to
1439 `org-directory'
1440 2. When a remember note is filed away in an interactive way (when exiting the
1441 note buffer with `C-1 C-c C-c'. The the user is prompted for an org file,
1442 with `org-directory' as the default path."
1443 :group 'org-refile
1444 :group 'org-remember
1445 :type 'directory)
1447 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1448 "Default target for storing notes.
1449 Used by the hooks for remember.el. This can be a string, or nil to mean
1450 the value of `remember-data-file'.
1451 You can set this on a per-template basis with the variable
1452 `org-remember-templates'."
1453 :group 'org-refile
1454 :group 'org-remember
1455 :type '(choice
1456 (const :tag "Default from remember-data-file" nil)
1457 file))
1459 (defcustom org-goto-interface 'outline
1460 "The default interface to be used for `org-goto'.
1461 Allowed values are:
1462 outline The interface shows an outline of the relevant file
1463 and the correct heading is found by moving through
1464 the outline or by searching with incremental search.
1465 outline-path-completion Headlines in the current buffer are offered via
1466 completion. This is the interface also used by
1467 the refile command."
1468 :group 'org-refile
1469 :type '(choice
1470 (const :tag "Outline" outline)
1471 (const :tag "Outline-path-completion" outline-path-completion)))
1473 (defcustom org-goto-max-level 5
1474 "Maximum level to be considered when running org-goto with refile interface."
1475 :group 'org-refile
1476 :type 'integer)
1478 (defcustom org-reverse-note-order nil
1479 "Non-nil means, store new notes at the beginning of a file or entry.
1480 When nil, new notes will be filed to the end of a file or entry.
1481 This can also be a list with cons cells of regular expressions that
1482 are matched against file names, and values."
1483 :group 'org-remember
1484 :group 'org-refile
1485 :type '(choice
1486 (const :tag "Reverse always" t)
1487 (const :tag "Reverse never" nil)
1488 (repeat :tag "By file name regexp"
1489 (cons regexp boolean))))
1491 (defcustom org-refile-targets nil
1492 "Targets for refiling entries with \\[org-refile].
1493 This is list of cons cells. Each cell contains:
1494 - a specification of the files to be considered, either a list of files,
1495 or a symbol whose function or variable value will be used to retrieve
1496 a file name or a list of file names. If you use `org-agenda-files' for
1497 that, all agenda files will be scanned for targets. Nil means, consider
1498 headings in the current buffer.
1499 - A specification of how to find candidate refile targets. This may be
1500 any of:
1501 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1502 This tag has to be present in all target headlines, inheritance will
1503 not be considered.
1504 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1505 todo keyword.
1506 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1507 headlines that are refiling targets.
1508 - a cons cell (:level . N). Any headline of level N is considered a target.
1509 Note that, when `org-odd-levels-only' is set, level corresponds to
1510 order in hierarchy, not to the number of stars.
1511 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1512 Note that, when `org-odd-levels-only' is set, level corresponds to
1513 order in hierarchy, not to the number of stars.
1515 You can set the variable `org-refile-target-verify-function' to a function
1516 to verify each headline found by the simple critery above.
1518 When this variable is nil, all top-level headlines in the current buffer
1519 are used, equivalent to the value `((nil . (:level . 1))'."
1520 :group 'org-refile
1521 :type '(repeat
1522 (cons
1523 (choice :value org-agenda-files
1524 (const :tag "All agenda files" org-agenda-files)
1525 (const :tag "Current buffer" nil)
1526 (function) (variable) (file))
1527 (choice :tag "Identify target headline by"
1528 (cons :tag "Specific tag" (const :value :tag) (string))
1529 (cons :tag "TODO keyword" (const :value :todo) (string))
1530 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1531 (cons :tag "Level number" (const :value :level) (integer))
1532 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1534 (defcustom org-refile-target-verify-function nil
1535 "Function to verify if the headline at point should be a refile target.
1536 The function will be called without arguments, with point at the
1537 beginning of the headline. It should return t and leave point
1538 where it is if the headline is a valid target for refiling.
1540 If the target should not be selected, the function must return nil.
1541 In addition to this, it may move point to a place from where the search
1542 should be continued. For example, the function may decide that the entire
1543 subtree of the current entry should be excluded and move point to the end
1544 of the subtree."
1545 :group 'org-refile
1546 :type 'function)
1548 (defcustom org-refile-use-outline-path nil
1549 "Non-nil means, provide refile targets as paths.
1550 So a level 3 headline will be available as level1/level2/level3.
1552 When the value is `file', also include the file name (without directory)
1553 into the path. In this case, you can also stop the completion after
1554 the file name, to get entries inserted as top level in the file.
1556 When `full-file-path', include the full file path."
1557 :group 'org-refile
1558 :type '(choice
1559 (const :tag "Not" nil)
1560 (const :tag "Yes" t)
1561 (const :tag "Start with file name" file)
1562 (const :tag "Start with full file path" full-file-path)))
1564 (defcustom org-outline-path-complete-in-steps t
1565 "Non-nil means, complete the outline path in hierarchical steps.
1566 When Org-mode uses the refile interface to select an outline path
1567 \(see variable `org-refile-use-outline-path'), the completion of
1568 the path can be done is a single go, or if can be done in steps down
1569 the headline hierarchy. Going in steps is probably the best if you
1570 do not use a special completion package like `ido' or `icicles'.
1571 However, when using these packages, going in one step can be very
1572 fast, while still showing the whole path to the entry."
1573 :group 'org-refile
1574 :type 'boolean)
1576 (defcustom org-refile-allow-creating-parent-nodes nil
1577 "Non-nil means, allow to create new nodes as refile targets.
1578 New nodes are then created by adding \"/new node name\" to the completion
1579 of an existing node. When the value of this variable is `confirm',
1580 new node creation must be confirmed by the user (recommended)
1581 When nil, the completion must match an existing entry.
1583 Note that, if the new heading is not seen by the criteria
1584 listed in `org-refile-targets', multiple instances of the same
1585 heading would be created by trying again to file under the new
1586 heading."
1587 :group 'org-refile
1588 :type '(choice
1589 (const :tag "Never" nil)
1590 (const :tag "Always" t)
1591 (const :tag "Prompt for confirmation" confirm)))
1593 (defgroup org-todo nil
1594 "Options concerning TODO items in Org-mode."
1595 :tag "Org TODO"
1596 :group 'org)
1598 (defgroup org-progress nil
1599 "Options concerning Progress logging in Org-mode."
1600 :tag "Org Progress"
1601 :group 'org-time)
1603 (defvar org-todo-interpretation-widgets
1605 (:tag "Sequence (cycling hits every state)" sequence)
1606 (:tag "Type (cycling directly to DONE)" type))
1607 "The available interpretation symbols for customizing
1608 `org-todo-keywords'.
1609 Interested libraries should add to this list.")
1611 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1612 "List of TODO entry keyword sequences and their interpretation.
1613 \\<org-mode-map>This is a list of sequences.
1615 Each sequence starts with a symbol, either `sequence' or `type',
1616 indicating if the keywords should be interpreted as a sequence of
1617 action steps, or as different types of TODO items. The first
1618 keywords are states requiring action - these states will select a headline
1619 for inclusion into the global TODO list Org-mode produces. If one of
1620 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1621 signify that no further action is necessary. If \"|\" is not found,
1622 the last keyword is treated as the only DONE state of the sequence.
1624 The command \\[org-todo] cycles an entry through these states, and one
1625 additional state where no keyword is present. For details about this
1626 cycling, see the manual.
1628 TODO keywords and interpretation can also be set on a per-file basis with
1629 the special #+SEQ_TODO and #+TYP_TODO lines.
1631 Each keyword can optionally specify a character for fast state selection
1632 \(in combination with the variable `org-use-fast-todo-selection')
1633 and specifiers for state change logging, using the same syntax
1634 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1635 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1636 indicates to record a time stamp each time this state is selected.
1638 Each keyword may also specify if a timestamp or a note should be
1639 recorded when entering or leaving the state, by adding additional
1640 characters in the parenthesis after the keyword. This looks like this:
1641 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1642 record only the time of the state change. With X and Y being either
1643 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1644 Y when leaving the state if and only if the *target* state does not
1645 define X. You may omit any of the fast-selection key or X or /Y,
1646 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1648 For backward compatibility, this variable may also be just a list
1649 of keywords - in this case the interpretation (sequence or type) will be
1650 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1651 :group 'org-todo
1652 :group 'org-keywords
1653 :type '(choice
1654 (repeat :tag "Old syntax, just keywords"
1655 (string :tag "Keyword"))
1656 (repeat :tag "New syntax"
1657 (cons
1658 (choice
1659 :tag "Interpretation"
1660 ;;Quick and dirty way to see
1661 ;;`org-todo-interpretations'. This takes the
1662 ;;place of item arguments
1663 :convert-widget
1664 (lambda (widget)
1665 (widget-put widget
1666 :args (mapcar
1667 #'(lambda (x)
1668 (widget-convert
1669 (cons 'const x)))
1670 org-todo-interpretation-widgets))
1671 widget))
1672 (repeat
1673 (string :tag "Keyword"))))))
1675 (defvar org-todo-keywords-1 nil
1676 "All TODO and DONE keywords active in a buffer.")
1677 (make-variable-buffer-local 'org-todo-keywords-1)
1678 (defvar org-todo-keywords-for-agenda nil)
1679 (defvar org-done-keywords-for-agenda nil)
1680 (defvar org-todo-keyword-alist-for-agenda nil)
1681 (defvar org-tag-alist-for-agenda nil)
1682 (defvar org-agenda-contributing-files nil)
1683 (defvar org-not-done-keywords nil)
1684 (make-variable-buffer-local 'org-not-done-keywords)
1685 (defvar org-done-keywords nil)
1686 (make-variable-buffer-local 'org-done-keywords)
1687 (defvar org-todo-heads nil)
1688 (make-variable-buffer-local 'org-todo-heads)
1689 (defvar org-todo-sets nil)
1690 (make-variable-buffer-local 'org-todo-sets)
1691 (defvar org-todo-log-states nil)
1692 (make-variable-buffer-local 'org-todo-log-states)
1693 (defvar org-todo-kwd-alist nil)
1694 (make-variable-buffer-local 'org-todo-kwd-alist)
1695 (defvar org-todo-key-alist nil)
1696 (make-variable-buffer-local 'org-todo-key-alist)
1697 (defvar org-todo-key-trigger nil)
1698 (make-variable-buffer-local 'org-todo-key-trigger)
1700 (defcustom org-todo-interpretation 'sequence
1701 "Controls how TODO keywords are interpreted.
1702 This variable is in principle obsolete and is only used for
1703 backward compatibility, if the interpretation of todo keywords is
1704 not given already in `org-todo-keywords'. See that variable for
1705 more information."
1706 :group 'org-todo
1707 :group 'org-keywords
1708 :type '(choice (const sequence)
1709 (const type)))
1711 (defcustom org-use-fast-todo-selection t
1712 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1713 This variable describes if and under what circumstances the cycling
1714 mechanism for TODO keywords will be replaced by a single-key, direct
1715 selection scheme.
1717 When nil, fast selection is never used.
1719 When the symbol `prefix', it will be used when `org-todo' is called with
1720 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1721 in an agenda buffer.
1723 When t, fast selection is used by default. In this case, the prefix
1724 argument forces cycling instead.
1726 In all cases, the special interface is only used if access keys have actually
1727 been assigned by the user, i.e. if keywords in the configuration are followed
1728 by a letter in parenthesis, like TODO(t)."
1729 :group 'org-todo
1730 :type '(choice
1731 (const :tag "Never" nil)
1732 (const :tag "By default" t)
1733 (const :tag "Only with C-u C-c C-t" prefix)))
1735 (defcustom org-provide-todo-statistics t
1736 "Non-nil means, update todo statistics after insert and toggle.
1737 ALL-HEADLINES means update todo statistics by including headlines
1738 with no TODO keyword as well, counting them as not done.
1739 A list of TODO keywords means the same, but skip keywords that are
1740 not in this list.
1742 When this is set, todo statistics is updated in the parent of the
1743 current entry each time a todo state is changed."
1744 :group 'org-todo
1745 :type '(choice
1746 (const :tag "Yes, only for TODO entries" t)
1747 (const :tag "Yes, including all entries" 'all-headlines)
1748 (repeat :tag "Yes, for TODOs in this list"
1749 (string :tag "TODO keyword"))
1750 (other :tag "No TODO statistics" nil)))
1752 (defcustom org-hierarchical-todo-statistics t
1753 "Non-nil means, TODO statistics covers just direct children.
1754 When nil, all entries in the subtree are considered.
1755 This has only an effect if `org-provide-todo-statistics' is set."
1756 :group 'org-todo
1757 :type 'boolean)
1759 (defcustom org-after-todo-state-change-hook nil
1760 "Hook which is run after the state of a TODO item was changed.
1761 The new state (a string with a TODO keyword, or nil) is available in the
1762 Lisp variable `state'."
1763 :group 'org-todo
1764 :type 'hook)
1766 (defvar org-blocker-hook nil
1767 "Hook for functions that are allowed to block a state change.
1769 Each function gets as its single argument a property list, see
1770 `org-trigger-hook' for more information about this list.
1772 If any of the functions in this hook returns nil, the state change
1773 is blocked.")
1775 (defvar org-trigger-hook nil
1776 "Hook for functions that are triggered by a state change.
1778 Each function gets as its single argument a property list with at least
1779 the following elements:
1781 (:type type-of-change :position pos-at-entry-start
1782 :from old-state :to new-state)
1784 Depending on the type, more properties may be present.
1786 This mechanism is currently implemented for:
1788 TODO state changes
1789 ------------------
1790 :type todo-state-change
1791 :from previous state (keyword as a string), or nil, or a symbol
1792 'todo' or 'done', to indicate the general type of state.
1793 :to new state, like in :from")
1795 (defcustom org-enforce-todo-dependencies nil
1796 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1797 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1798 be blocked if any prior sibling is not yet done.
1799 Finally, if the parent is blocked because of ordered siblings of its own,
1800 the child will also be blocked.
1801 This variable needs to be set before org.el is loaded, and you need to
1802 restart Emacs after a change to make the change effective. The only way
1803 to change is while Emacs is running is through the customize interface."
1804 :set (lambda (var val)
1805 (set var val)
1806 (if val
1807 (add-hook 'org-blocker-hook
1808 'org-block-todo-from-children-or-siblings-or-parent)
1809 (remove-hook 'org-blocker-hook
1810 'org-block-todo-from-children-or-siblings-or-parent)))
1811 :group 'org-todo
1812 :type 'boolean)
1814 (defcustom org-enforce-todo-checkbox-dependencies nil
1815 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1816 When this is nil, checkboxes have no influence on switching TODO states.
1817 When non-nil, you first need to check off all check boxes before the TODO
1818 entry can be switched to DONE.
1819 This variable needs to be set before org.el is loaded, and you need to
1820 restart Emacs after a change to make the change effective. The only way
1821 to change is while Emacs is running is through the customize interface."
1822 :set (lambda (var val)
1823 (set var val)
1824 (if val
1825 (add-hook 'org-blocker-hook
1826 'org-block-todo-from-checkboxes)
1827 (remove-hook 'org-blocker-hook
1828 'org-block-todo-from-checkboxes)))
1829 :group 'org-todo
1830 :type 'boolean)
1832 (defcustom org-treat-insert-todo-heading-as-state-change nil
1833 "Non-nil means, inserting a TODO heading is treated as state change.
1834 So when the command \\[org-insert-todo-heading] is used, state change
1835 logging will apply if appropriate. When nil, the new TODO item will
1836 be inserted directly, and no logging will take place."
1837 :group 'org-todo
1838 :type 'boolean)
1840 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1841 "Non-nil means, switching TODO states with S-cursor counts as state change.
1842 This is the default behavior. However, setting this to nil allows a
1843 convenient way to select a TODO state and bypass any logging associated
1844 with that."
1845 :group 'org-todo
1846 :type 'boolean)
1848 (defcustom org-todo-state-tags-triggers nil
1849 "Tag changes that should be triggered by TODO state changes.
1850 This is a list. Each entry is
1852 (state-change (tag . flag) .......)
1854 State-change can be a string with a state, and empty string to indicate the
1855 state that has no TODO keyword, or it can be one of the symbols `todo'
1856 or `done', meaning any not-done or done state, respectively."
1857 :group 'org-todo
1858 :group 'org-tags
1859 :type '(repeat
1860 (cons (choice :tag "When changing to"
1861 (const :tag "Not-done state" todo)
1862 (const :tag "Done state" done)
1863 (string :tag "State"))
1864 (repeat
1865 (cons :tag "Tag action"
1866 (string :tag "Tag")
1867 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1869 (defcustom org-log-done nil
1870 "Information to record when a task moves to the DONE state.
1872 Possible values are:
1874 nil Don't add anything, just change the keyword
1875 time Add a time stamp to the task
1876 note Prompt a closing note and add it with template `org-log-note-headings'
1878 This option can also be set with on a per-file-basis with
1880 #+STARTUP: nologdone
1881 #+STARTUP: logdone
1882 #+STARTUP: lognotedone
1884 You can have local logging settings for a subtree by setting the LOGGING
1885 property to one or more of these keywords."
1886 :group 'org-todo
1887 :group 'org-progress
1888 :type '(choice
1889 (const :tag "No logging" nil)
1890 (const :tag "Record CLOSED timestamp" time)
1891 (const :tag "Record CLOSED timestamp with closing note." note)))
1893 ;; Normalize old uses of org-log-done.
1894 (cond
1895 ((eq org-log-done t) (setq org-log-done 'time))
1896 ((and (listp org-log-done) (memq 'done org-log-done))
1897 (setq org-log-done 'note)))
1899 (defcustom org-log-note-clock-out nil
1900 "Non-nil means, record a note when clocking out of an item.
1901 This can also be configured on a per-file basis by adding one of
1902 the following lines anywhere in the buffer:
1904 #+STARTUP: lognoteclock-out
1905 #+STARTUP: nolognoteclock-out"
1906 :group 'org-todo
1907 :group 'org-progress
1908 :type 'boolean)
1910 (defcustom org-log-done-with-time t
1911 "Non-nil means, the CLOSED time stamp will contain date and time.
1912 When nil, only the date will be recorded."
1913 :group 'org-progress
1914 :type 'boolean)
1916 (defcustom org-log-note-headings
1917 '((done . "CLOSING NOTE %t")
1918 (state . "State %-12s from %-12S %t")
1919 (note . "Note taken on %t")
1920 (clock-out . ""))
1921 "Headings for notes added to entries.
1922 The value is an alist, with the car being a symbol indicating the note
1923 context, and the cdr is the heading to be used. The heading may also be the
1924 empty string.
1925 %t in the heading will be replaced by a time stamp.
1926 %s will be replaced by the new TODO state, in double quotes.
1927 %S will be replaced by the old TODO state, in double quotes.
1928 %u will be replaced by the user name.
1929 %U will be replaced by the full user name."
1930 :group 'org-todo
1931 :group 'org-progress
1932 :type '(list :greedy t
1933 (cons (const :tag "Heading when closing an item" done) string)
1934 (cons (const :tag
1935 "Heading when changing todo state (todo sequence only)"
1936 state) string)
1937 (cons (const :tag "Heading when just taking a note" note) string)
1938 (cons (const :tag "Heading when clocking out" clock-out) string)))
1940 (unless (assq 'note org-log-note-headings)
1941 (push '(note . "%t") org-log-note-headings))
1943 (defcustom org-log-into-drawer nil
1944 "Non-nil means, insert state change notes and time stamps into a drawer.
1945 When nil, state changes notes will be inserted after the headline and
1946 any scheduling and clock lines, but not inside a drawer.
1948 The value of this variable should be the name of the drawer to use.
1949 LOGBOOK is proposed at the default drawer for this purpose, you can
1950 also set this to a string to define the drawer of your choice.
1952 A value of t is also allowed, representing \"LOGBOOK\".
1954 If this variable is set, `org-log-state-notes-insert-after-drawers'
1955 will be ignored.
1957 You can set the property LOG_INTO_DRAWER to overrule this setting for
1958 a subtree."
1959 :group 'org-todo
1960 :group 'org-progress
1961 :type '(choice
1962 (const :tag "Not into a drawer" nil)
1963 (const :tag "LOGBOOK" t)
1964 (string :tag "Other")))
1966 (if (fboundp 'defvaralias)
1967 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
1969 (defun org-log-into-drawer ()
1970 "Return the value of `org-log-into-drawer', but let properties overrule.
1971 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
1972 used instead of the default value."
1973 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
1974 (cond
1975 ((or (not p) (equal p "nil")) org-log-into-drawer)
1976 ((equal p "t") "LOGBOOK")
1977 (t p))))
1979 (defcustom org-log-state-notes-insert-after-drawers nil
1980 "Non-nil means, insert state change notes after any drawers in entry.
1981 Only the drawers that *immediately* follow the headline and the
1982 deadline/scheduled line are skipped.
1983 When nil, insert notes right after the heading and perhaps the line
1984 with deadline/scheduling if present.
1986 This variable will have no effect if `org-log-into-drawer' is
1987 set."
1988 :group 'org-todo
1989 :group 'org-progress
1990 :type 'boolean)
1992 (defcustom org-log-states-order-reversed t
1993 "Non-nil means, the latest state change note will be directly after heading.
1994 When nil, the notes will be orderer according to time."
1995 :group 'org-todo
1996 :group 'org-progress
1997 :type 'boolean)
1999 (defcustom org-log-repeat 'time
2000 "Non-nil means, record moving through the DONE state when triggering repeat.
2001 An auto-repeating tasks is immediately switched back to TODO when marked
2002 done. If you are not logging state changes (by adding \"@\" or \"!\" to
2003 the TODO keyword definition, or recording a closing note by setting
2004 `org-log-done', there will be no record of the task moving through DONE.
2005 This variable forces taking a note anyway. Possible values are:
2007 nil Don't force a record
2008 time Record a time stamp
2009 note Record a note
2011 This option can also be set with on a per-file-basis with
2013 #+STARTUP: logrepeat
2014 #+STARTUP: lognoterepeat
2015 #+STARTUP: nologrepeat
2017 You can have local logging settings for a subtree by setting the LOGGING
2018 property to one or more of these keywords."
2019 :group 'org-todo
2020 :group 'org-progress
2021 :type '(choice
2022 (const :tag "Don't force a record" nil)
2023 (const :tag "Force recording the DONE state" time)
2024 (const :tag "Force recording a note with the DONE state" note)))
2027 (defgroup org-priorities nil
2028 "Priorities in Org-mode."
2029 :tag "Org Priorities"
2030 :group 'org-todo)
2032 (defcustom org-enable-priority-commands t
2033 "Non-nil means, priority commands are active.
2034 When nil, these commands will be disabled, so that you never accidentally
2035 set a priority."
2036 :group 'org-priorities
2037 :type 'boolean)
2039 (defcustom org-highest-priority ?A
2040 "The highest priority of TODO items. A character like ?A, ?B etc.
2041 Must have a smaller ASCII number than `org-lowest-priority'."
2042 :group 'org-priorities
2043 :type 'character)
2045 (defcustom org-lowest-priority ?C
2046 "The lowest priority of TODO items. A character like ?A, ?B etc.
2047 Must have a larger ASCII number than `org-highest-priority'."
2048 :group 'org-priorities
2049 :type 'character)
2051 (defcustom org-default-priority ?B
2052 "The default priority of TODO items.
2053 This is the priority an item get if no explicit priority is given."
2054 :group 'org-priorities
2055 :type 'character)
2057 (defcustom org-priority-start-cycle-with-default t
2058 "Non-nil means, start with default priority when starting to cycle.
2059 When this is nil, the first step in the cycle will be (depending on the
2060 command used) one higher or lower that the default priority."
2061 :group 'org-priorities
2062 :type 'boolean)
2064 (defgroup org-time nil
2065 "Options concerning time stamps and deadlines in Org-mode."
2066 :tag "Org Time"
2067 :group 'org)
2069 (defcustom org-insert-labeled-timestamps-at-point nil
2070 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
2071 When nil, these labeled time stamps are forces into the second line of an
2072 entry, just after the headline. When scheduling from the global TODO list,
2073 the time stamp will always be forced into the second line."
2074 :group 'org-time
2075 :type 'boolean)
2077 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2078 "Formats for `format-time-string' which are used for time stamps.
2079 It is not recommended to change this constant.")
2081 (defcustom org-time-stamp-rounding-minutes '(0 5)
2082 "Number of minutes to round time stamps to.
2083 These are two values, the first applies when first creating a time stamp.
2084 The second applies when changing it with the commands `S-up' and `S-down'.
2085 When changing the time stamp, this means that it will change in steps
2086 of N minutes, as given by the second value.
2088 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2089 numbers should be factors of 60, so for example 5, 10, 15.
2091 When this is larger than 1, you can still force an exact time-stamp by using
2092 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2093 and by using a prefix arg to `S-up/down' to specify the exact number
2094 of minutes to shift."
2095 :group 'org-time
2096 :get '(lambda (var) ; Make sure all entries have 5 elements
2097 (if (integerp (default-value var))
2098 (list (default-value var) 5)
2099 (default-value var)))
2100 :type '(list
2101 (integer :tag "when inserting times")
2102 (integer :tag "when modifying times")))
2104 ;; Normalize old customizations of this variable.
2105 (when (integerp org-time-stamp-rounding-minutes)
2106 (setq org-time-stamp-rounding-minutes
2107 (list org-time-stamp-rounding-minutes
2108 org-time-stamp-rounding-minutes)))
2110 (defcustom org-display-custom-times nil
2111 "Non-nil means, overlay custom formats over all time stamps.
2112 The formats are defined through the variable `org-time-stamp-custom-formats'.
2113 To turn this on on a per-file basis, insert anywhere in the file:
2114 #+STARTUP: customtime"
2115 :group 'org-time
2116 :set 'set-default
2117 :type 'sexp)
2118 (make-variable-buffer-local 'org-display-custom-times)
2120 (defcustom org-time-stamp-custom-formats
2121 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2122 "Custom formats for time stamps. See `format-time-string' for the syntax.
2123 These are overlayed over the default ISO format if the variable
2124 `org-display-custom-times' is set. Time like %H:%M should be at the
2125 end of the second format. The custom formats are also honored by export
2126 commands, if custom time display is turned on at the time of export."
2127 :group 'org-time
2128 :type 'sexp)
2130 (defun org-time-stamp-format (&optional long inactive)
2131 "Get the right format for a time string."
2132 (let ((f (if long (cdr org-time-stamp-formats)
2133 (car org-time-stamp-formats))))
2134 (if inactive
2135 (concat "[" (substring f 1 -1) "]")
2136 f)))
2138 (defcustom org-time-clocksum-format "%d:%02d"
2139 "The format string used when creating CLOCKSUM lines, or when
2140 org-mode generates a time duration."
2141 :group 'org-time
2142 :type 'string)
2144 (defcustom org-deadline-warning-days 14
2145 "No. of days before expiration during which a deadline becomes active.
2146 This variable governs the display in sparse trees and in the agenda.
2147 When 0 or negative, it means use this number (the absolute value of it)
2148 even if a deadline has a different individual lead time specified.
2150 Custom commands can set this variable in the options section."
2151 :group 'org-time
2152 :group 'org-agenda-daily/weekly
2153 :type 'integer)
2155 (defcustom org-read-date-prefer-future t
2156 "Non-nil means, assume future for incomplete date input from user.
2157 This affects the following situations:
2158 1. The user gives a day, but no month.
2159 For example, if today is the 15th, and you enter \"3\", Org-mode will
2160 read this as the third of *next* month. However, if you enter \"17\",
2161 it will be considered as *this* month.
2162 2. The user gives a month but not a year.
2163 For example, if it is april and you enter \"feb 2\", this will be read
2164 as feb 2, *next* year. \"May 5\", however, will be this year.
2166 Currently this does not work for ISO week specifications.
2168 When this option is nil, the current month and year will always be used
2169 as defaults."
2170 :group 'org-time
2171 :type 'boolean)
2173 (defcustom org-read-date-display-live t
2174 "Non-nil means, display current interpretation of date prompt live.
2175 This display will be in an overlay, in the minibuffer."
2176 :group 'org-time
2177 :type 'boolean)
2179 (defcustom org-read-date-popup-calendar t
2180 "Non-nil means, pop up a calendar when prompting for a date.
2181 In the calendar, the date can be selected with mouse-1. However, the
2182 minibuffer will also be active, and you can simply enter the date as well.
2183 When nil, only the minibuffer will be available."
2184 :group 'org-time
2185 :type 'boolean)
2186 (if (fboundp 'defvaralias)
2187 (defvaralias 'org-popup-calendar-for-date-prompt
2188 'org-read-date-popup-calendar))
2190 (defcustom org-read-date-minibuffer-setup-hook nil
2191 "Hook to be used to set up keys for the date/time interface.
2192 Add key definitions to `minibuffer-local-map', which will be a temporary
2193 copy."
2194 :group 'org-time
2195 :type 'hook)
2197 (defcustom org-extend-today-until 0
2198 "The hour when your day really ends. Must be an integer.
2199 This has influence for the following applications:
2200 - When switching the agenda to \"today\". It it is still earlier than
2201 the time given here, the day recognized as TODAY is actually yesterday.
2202 - When a date is read from the user and it is still before the time given
2203 here, the current date and time will be assumed to be yesterday, 23:59.
2204 Also, timestamps inserted in remember templates follow this rule.
2206 IMPORTANT: This is a feature whose implementation is and likely will
2207 remain incomplete. Really, it is only here because past midnight seems to
2208 be the favorite working time of John Wiegley :-)"
2209 :group 'org-time
2210 :type 'integer)
2212 (defcustom org-edit-timestamp-down-means-later nil
2213 "Non-nil means, S-down will increase the time in a time stamp.
2214 When nil, S-up will increase."
2215 :group 'org-time
2216 :type 'boolean)
2218 (defcustom org-calendar-follow-timestamp-change t
2219 "Non-nil means, make the calendar window follow timestamp changes.
2220 When a timestamp is modified and the calendar window is visible, it will be
2221 moved to the new date."
2222 :group 'org-time
2223 :type 'boolean)
2225 (defgroup org-tags nil
2226 "Options concerning tags in Org-mode."
2227 :tag "Org Tags"
2228 :group 'org)
2230 (defcustom org-tag-alist nil
2231 "List of tags allowed in Org-mode files.
2232 When this list is nil, Org-mode will base TAG input on what is already in the
2233 buffer.
2234 The value of this variable is an alist, the car of each entry must be a
2235 keyword as a string, the cdr may be a character that is used to select
2236 that tag through the fast-tag-selection interface.
2237 See the manual for details."
2238 :group 'org-tags
2239 :type '(repeat
2240 (choice
2241 (cons (string :tag "Tag name")
2242 (character :tag "Access char"))
2243 (const :tag "Start radio group" (:startgroup))
2244 (const :tag "End radio group" (:endgroup))
2245 (const :tag "New line" (:newline)))))
2247 (defcustom org-tag-persistent-alist nil
2248 "List of tags that will always appear in all Org-mode files.
2249 This is in addition to any in buffer settings or customizations
2250 of `org-tag-alist'.
2251 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2252 The value of this variable is an alist, the car of each entry must be a
2253 keyword as a string, the cdr may be a character that is used to select
2254 that tag through the fast-tag-selection interface.
2255 See the manual for details.
2256 To disable these tags on a per-file basis, insert anywhere in the file:
2257 #+STARTUP: noptag"
2258 :group 'org-tags
2259 :type '(repeat
2260 (choice
2261 (cons (string :tag "Tag name")
2262 (character :tag "Access char"))
2263 (const :tag "Start radio group" (:startgroup))
2264 (const :tag "End radio group" (:endgroup))
2265 (const :tag "New line" (:newline)))))
2267 (defvar org-file-tags nil
2268 "List of tags that can be inherited by all entries in the file.
2269 The tags will be inherited if the variable `org-use-tag-inheritance'
2270 says they should be.
2271 This variable is populated from #+TAG lines.")
2273 (defcustom org-use-fast-tag-selection 'auto
2274 "Non-nil means, use fast tag selection scheme.
2275 This is a special interface to select and deselect tags with single keys.
2276 When nil, fast selection is never used.
2277 When the symbol `auto', fast selection is used if and only if selection
2278 characters for tags have been configured, either through the variable
2279 `org-tag-alist' or through a #+TAGS line in the buffer.
2280 When t, fast selection is always used and selection keys are assigned
2281 automatically if necessary."
2282 :group 'org-tags
2283 :type '(choice
2284 (const :tag "Always" t)
2285 (const :tag "Never" nil)
2286 (const :tag "When selection characters are configured" 'auto)))
2288 (defcustom org-fast-tag-selection-single-key nil
2289 "Non-nil means, fast tag selection exits after first change.
2290 When nil, you have to press RET to exit it.
2291 During fast tag selection, you can toggle this flag with `C-c'.
2292 This variable can also have the value `expert'. In this case, the window
2293 displaying the tags menu is not even shown, until you press C-c again."
2294 :group 'org-tags
2295 :type '(choice
2296 (const :tag "No" nil)
2297 (const :tag "Yes" t)
2298 (const :tag "Expert" expert)))
2300 (defvar org-fast-tag-selection-include-todo nil
2301 "Non-nil means, fast tags selection interface will also offer TODO states.
2302 This is an undocumented feature, you should not rely on it.")
2304 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2305 "The column to which tags should be indented in a headline.
2306 If this number is positive, it specifies the column. If it is negative,
2307 it means that the tags should be flushright to that column. For example,
2308 -80 works well for a normal 80 character screen."
2309 :group 'org-tags
2310 :type 'integer)
2312 (defcustom org-auto-align-tags t
2313 "Non-nil means, realign tags after pro/demotion of TODO state change.
2314 These operations change the length of a headline and therefore shift
2315 the tags around. With this options turned on, after each such operation
2316 the tags are again aligned to `org-tags-column'."
2317 :group 'org-tags
2318 :type 'boolean)
2320 (defcustom org-use-tag-inheritance t
2321 "Non-nil means, tags in levels apply also for sublevels.
2322 When nil, only the tags directly given in a specific line apply there.
2323 This may also be a list of tags that should be inherited, or a regexp that
2324 matches tags that should be inherited. Additional control is possible
2325 with the variable `org-tags-exclude-from-inheritance' which gives an
2326 explicit list of tags to be excluded from inheritance., even if the value of
2327 `org-use-tag-inheritance' would select it for inheritance.
2329 If this option is t, a match early-on in a tree can lead to a large
2330 number of matches in the subtree when constructing the agenda or creating
2331 a sparse tree. If you only want to see the first match in a tree during
2332 a search, check out the variable `org-tags-match-list-sublevels'."
2333 :group 'org-tags
2334 :type '(choice
2335 (const :tag "Not" nil)
2336 (const :tag "Always" t)
2337 (repeat :tag "Specific tags" (string :tag "Tag"))
2338 (regexp :tag "Tags matched by regexp")))
2340 (defcustom org-tags-exclude-from-inheritance nil
2341 "List of tags that should never be inherited.
2342 This is a way to exclude a few tags from inheritance. For way to do
2343 the opposite, to actively allow inheritance for selected tags,
2344 see the variable `org-use-tag-inheritance'."
2345 :group 'org-tags
2346 :type '(repeat (string :tag "Tag")))
2348 (defun org-tag-inherit-p (tag)
2349 "Check if TAG is one that should be inherited."
2350 (cond
2351 ((member tag org-tags-exclude-from-inheritance) nil)
2352 ((eq org-use-tag-inheritance t) t)
2353 ((not org-use-tag-inheritance) nil)
2354 ((stringp org-use-tag-inheritance)
2355 (string-match org-use-tag-inheritance tag))
2356 ((listp org-use-tag-inheritance)
2357 (member tag org-use-tag-inheritance))
2358 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2360 (defcustom org-tags-match-list-sublevels t
2361 "Non-nil means list also sublevels of headlines matching a search.
2362 This variable applies to tags/property searches, and also to stuck
2363 projects because this search is based on a tags match as well.
2365 When set to the symbol `indented', sublevels are indented with
2366 leading dots.
2368 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2369 the sublevels of a headline matching a tag search often also match
2370 the same search. Listing all of them can create very long lists.
2371 Setting this variable to nil causes subtrees of a match to be skipped.
2373 This variable is semi-obsolete and probably should always be true. It
2374 is better to limit inheritance to certain tags using the variables
2375 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2376 :group 'org-tags
2377 :type '(choice
2378 (const :tag "No, don't list them" nil)
2379 (const :tag "Yes, do list them" t)
2380 (const :tag "List them, indented with leading dots" indented)))
2382 (defcustom org-tags-sort-function nil
2383 "When set, tags are sorted using this function as a comparator"
2384 :group 'org-tags
2385 :type '(choice
2386 (const :tag "No sorting" nil)
2387 (const :tag "Alphabetical" string<)
2388 (const :tag "Reverse alphabetical" string>)
2389 (function :tag "Custom function" nil)))
2391 (defvar org-tags-history nil
2392 "History of minibuffer reads for tags.")
2393 (defvar org-last-tags-completion-table nil
2394 "The last used completion table for tags.")
2395 (defvar org-after-tags-change-hook nil
2396 "Hook that is run after the tags in a line have changed.")
2398 (defgroup org-properties nil
2399 "Options concerning properties in Org-mode."
2400 :tag "Org Properties"
2401 :group 'org)
2403 (defcustom org-property-format "%-10s %s"
2404 "How property key/value pairs should be formatted by `indent-line'.
2405 When `indent-line' hits a property definition, it will format the line
2406 according to this format, mainly to make sure that the values are
2407 lined-up with respect to each other."
2408 :group 'org-properties
2409 :type 'string)
2411 (defcustom org-use-property-inheritance nil
2412 "Non-nil means, properties apply also for sublevels.
2414 This setting is chiefly used during property searches. Turning it on can
2415 cause significant overhead when doing a search, which is why it is not
2416 on by default.
2418 When nil, only the properties directly given in the current entry count.
2419 When t, every property is inherited. The value may also be a list of
2420 properties that should have inheritance, or a regular expression matching
2421 properties that should be inherited.
2423 However, note that some special properties use inheritance under special
2424 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2425 and the properties ending in \"_ALL\" when they are used as descriptor
2426 for valid values of a property.
2428 Note for programmers:
2429 When querying an entry with `org-entry-get', you can control if inheritance
2430 should be used. By default, `org-entry-get' looks only at the local
2431 properties. You can request inheritance by setting the inherit argument
2432 to t (to force inheritance) or to `selective' (to respect the setting
2433 in this variable)."
2434 :group 'org-properties
2435 :type '(choice
2436 (const :tag "Not" nil)
2437 (const :tag "Always" t)
2438 (repeat :tag "Specific properties" (string :tag "Property"))
2439 (regexp :tag "Properties matched by regexp")))
2441 (defun org-property-inherit-p (property)
2442 "Check if PROPERTY is one that should be inherited."
2443 (cond
2444 ((eq org-use-property-inheritance t) t)
2445 ((not org-use-property-inheritance) nil)
2446 ((stringp org-use-property-inheritance)
2447 (string-match org-use-property-inheritance property))
2448 ((listp org-use-property-inheritance)
2449 (member property org-use-property-inheritance))
2450 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2452 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2453 "The default column format, if no other format has been defined.
2454 This variable can be set on the per-file basis by inserting a line
2456 #+COLUMNS: %25ITEM ....."
2457 :group 'org-properties
2458 :type 'string)
2460 (defcustom org-columns-ellipses ".."
2461 "The ellipses to be used when a field in column view is truncated.
2462 When this is the empty string, as many characters as possible are shown,
2463 but then there will be no visual indication that the field has been truncated.
2464 When this is a string of length N, the last N characters of a truncated
2465 field are replaced by this string. If the column is narrower than the
2466 ellipses string, only part of the ellipses string will be shown."
2467 :group 'org-properties
2468 :type 'string)
2470 (defcustom org-columns-modify-value-for-display-function nil
2471 "Function that modifies values for display in column view.
2472 For example, it can be used to cut out a certain part from a time stamp.
2473 The function must take 2 arguments:
2475 column-title The title of the column (*not* the property name)
2476 value The value that should be modified.
2478 The function should return the value that should be displayed,
2479 or nil if the normal value should be used."
2480 :group 'org-properties
2481 :type 'function)
2483 (defcustom org-effort-property "Effort"
2484 "The property that is being used to keep track of effort estimates.
2485 Effort estimates given in this property need to have the format H:MM."
2486 :group 'org-properties
2487 :group 'org-progress
2488 :type '(string :tag "Property"))
2490 (defconst org-global-properties-fixed
2491 '(("VISIBILITY_ALL" . "folded children content all")
2492 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2493 "List of property/value pairs that can be inherited by any entry.
2495 These are fixed values, for the preset properties. The user variable
2496 that can be used to add to this list is `org-global-properties'.
2498 The entries in this list are cons cells where the car is a property
2499 name and cdr is a string with the value. If the value represents
2500 multiple items like an \"_ALL\" property, separate the items by
2501 spaces.")
2503 (defcustom org-global-properties nil
2504 "List of property/value pairs that can be inherited by any entry.
2506 This list will be combined with the constant `org-global-properties-fixed'.
2508 The entries in this list are cons cells where the car is a property
2509 name and cdr is a string with the value.
2511 You can set buffer-local values for the same purpose in the variable
2512 `org-file-properties' this by adding lines like
2514 #+PROPERTY: NAME VALUE"
2515 :group 'org-properties
2516 :type '(repeat
2517 (cons (string :tag "Property")
2518 (string :tag "Value"))))
2520 (defvar org-file-properties nil
2521 "List of property/value pairs that can be inherited by any entry.
2522 Valid for the current buffer.
2523 This variable is populated from #+PROPERTY lines.")
2524 (make-variable-buffer-local 'org-file-properties)
2526 (defgroup org-agenda nil
2527 "Options concerning agenda views in Org-mode."
2528 :tag "Org Agenda"
2529 :group 'org)
2531 (defvar org-category nil
2532 "Variable used by org files to set a category for agenda display.
2533 Such files should use a file variable to set it, for example
2535 # -*- mode: org; org-category: \"ELisp\"
2537 or contain a special line
2539 #+CATEGORY: ELisp
2541 If the file does not specify a category, then file's base name
2542 is used instead.")
2543 (make-variable-buffer-local 'org-category)
2544 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2546 (defcustom org-agenda-files nil
2547 "The files to be used for agenda display.
2548 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2549 \\[org-remove-file]. You can also use customize to edit the list.
2551 If an entry is a directory, all files in that directory that are matched by
2552 `org-agenda-file-regexp' will be part of the file list.
2554 If the value of the variable is not a list but a single file name, then
2555 the list of agenda files is actually stored and maintained in that file, one
2556 agenda file per line."
2557 :group 'org-agenda
2558 :type '(choice
2559 (repeat :tag "List of files and directories" file)
2560 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2562 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2563 "Regular expression to match files for `org-agenda-files'.
2564 If any element in the list in that variable contains a directory instead
2565 of a normal file, all files in that directory that are matched by this
2566 regular expression will be included."
2567 :group 'org-agenda
2568 :type 'regexp)
2570 (defcustom org-agenda-text-search-extra-files nil
2571 "List of extra files to be searched by text search commands.
2572 These files will be search in addition to the agenda files by the
2573 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2574 Note that these files will only be searched for text search commands,
2575 not for the other agenda views like todo lists, tag searches or the weekly
2576 agenda. This variable is intended to list notes and possibly archive files
2577 that should also be searched by these two commands.
2578 In fact, if the first element in the list is the symbol `agenda-archives',
2579 than all archive files of all agenda files will be added to the search
2580 scope."
2581 :group 'org-agenda
2582 :type '(set :greedy t
2583 (const :tag "Agenda Archives" agenda-archives)
2584 (repeat :inline t (file))))
2586 (if (fboundp 'defvaralias)
2587 (defvaralias 'org-agenda-multi-occur-extra-files
2588 'org-agenda-text-search-extra-files))
2590 (defcustom org-agenda-skip-unavailable-files nil
2591 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2592 A nil value means to remove them, after a query, from the list."
2593 :group 'org-agenda
2594 :type 'boolean)
2596 (defcustom org-calendar-to-agenda-key [?c]
2597 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2598 The command `org-calendar-goto-agenda' will be bound to this key. The
2599 default is the character `c' because then `c' can be used to switch back and
2600 forth between agenda and calendar."
2601 :group 'org-agenda
2602 :type 'sexp)
2604 (defcustom org-calendar-agenda-action-key [?k]
2605 "The key to be installed in `calendar-mode-map' for agenda-action.
2606 The command `org-agenda-action' will be bound to this key. The
2607 default is the character `k' because we use the same key in the agenda."
2608 :group 'org-agenda
2609 :type 'sexp)
2611 (eval-after-load "calendar"
2612 '(progn
2613 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2614 'org-calendar-goto-agenda)
2615 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2616 'org-agenda-action)))
2618 (defgroup org-latex nil
2619 "Options for embedding LaTeX code into Org-mode."
2620 :tag "Org LaTeX"
2621 :group 'org)
2623 (defcustom org-format-latex-options
2624 '(:foreground default :background default :scale 1.0
2625 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2626 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2627 "Options for creating images from LaTeX fragments.
2628 This is a property list with the following properties:
2629 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2630 `default' means use the foreground of the default face.
2631 :background the background color, or \"Transparent\".
2632 `default' means use the background of the default face.
2633 :scale a scaling factor for the size of the images.
2634 :html-foreground, :html-background, :html-scale
2635 the same numbers for HTML export.
2636 :matchers a list indicating which matchers should be used to
2637 find LaTeX fragments. Valid members of this list are:
2638 \"begin\" find environments
2639 \"$1\" find single characters surrounded by $.$
2640 \"$\" find math expressions surrounded by $...$
2641 \"$$\" find math expressions surrounded by $$....$$
2642 \"\\(\" find math expressions surrounded by \\(...\\)
2643 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2644 :group 'org-latex
2645 :type 'plist)
2647 (defcustom org-format-latex-header "\\documentclass{article}
2648 \\usepackage{fullpage} % do not remove
2649 \\usepackage{amssymb}
2650 \\usepackage[usenames]{color}
2651 \\usepackage{amsmath}
2652 \\usepackage{latexsym}
2653 \\usepackage[mathscr]{eucal}
2654 \\pagestyle{empty} % do not remove"
2655 "The document header used for processing LaTeX fragments."
2656 :group 'org-latex
2657 :type 'string)
2660 (defgroup org-font-lock nil
2661 "Font-lock settings for highlighting in Org-mode."
2662 :tag "Org Font Lock"
2663 :group 'org)
2665 (defcustom org-level-color-stars-only nil
2666 "Non-nil means fontify only the stars in each headline.
2667 When nil, the entire headline is fontified.
2668 Changing it requires restart of `font-lock-mode' to become effective
2669 also in regions already fontified."
2670 :group 'org-font-lock
2671 :type 'boolean)
2673 (defcustom org-hide-leading-stars nil
2674 "Non-nil means, hide the first N-1 stars in a headline.
2675 This works by using the face `org-hide' for these stars. This
2676 face is white for a light background, and black for a dark
2677 background. You may have to customize the face `org-hide' to
2678 make this work.
2679 Changing it requires restart of `font-lock-mode' to become effective
2680 also in regions already fontified.
2681 You may also set this on a per-file basis by adding one of the following
2682 lines to the buffer:
2684 #+STARTUP: hidestars
2685 #+STARTUP: showstars"
2686 :group 'org-font-lock
2687 :type 'boolean)
2689 (defcustom org-fontify-done-headline nil
2690 "Non-nil means, change the face of a headline if it is marked DONE.
2691 Normally, only the TODO/DONE keyword indicates the state of a headline.
2692 When this is non-nil, the headline after the keyword is set to the
2693 `org-headline-done' as an additional indication."
2694 :group 'org-font-lock
2695 :type 'boolean)
2697 (defcustom org-fontify-emphasized-text t
2698 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2699 Changing this variable requires a restart of Emacs to take effect."
2700 :group 'org-font-lock
2701 :type 'boolean)
2703 (defcustom org-fontify-whole-heading-line nil
2704 "Non-nil means fontify the whole line for headings.
2705 This is useful when setting a background color for the
2706 org-leve-* faces."
2707 :group 'org-font-lock
2708 :type 'boolean)
2710 (defcustom org-highlight-latex-fragments-and-specials nil
2711 "Non-nil means, fontify what is treated specially by the exporters."
2712 :group 'org-font-lock
2713 :type 'boolean)
2715 (defcustom org-hide-emphasis-markers nil
2716 "Non-nil mean font-lock should hide the emphasis marker characters."
2717 :group 'org-font-lock
2718 :type 'boolean)
2720 (defvar org-emph-re nil
2721 "Regular expression for matching emphasis.")
2722 (defvar org-verbatim-re nil
2723 "Regular expression for matching verbatim text.")
2724 (defvar org-emphasis-regexp-components) ; defined just below
2725 (defvar org-emphasis-alist) ; defined just below
2726 (defun org-set-emph-re (var val)
2727 "Set variable and compute the emphasis regular expression."
2728 (set var val)
2729 (when (and (boundp 'org-emphasis-alist)
2730 (boundp 'org-emphasis-regexp-components)
2731 org-emphasis-alist org-emphasis-regexp-components)
2732 (let* ((e org-emphasis-regexp-components)
2733 (pre (car e))
2734 (post (nth 1 e))
2735 (border (nth 2 e))
2736 (body (nth 3 e))
2737 (nl (nth 4 e))
2738 (body1 (concat body "*?"))
2739 (markers (mapconcat 'car org-emphasis-alist ""))
2740 (vmarkers (mapconcat
2741 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2742 org-emphasis-alist "")))
2743 ;; make sure special characters appear at the right position in the class
2744 (if (string-match "\\^" markers)
2745 (setq markers (concat (replace-match "" t t markers) "^")))
2746 (if (string-match "-" markers)
2747 (setq markers (concat (replace-match "" t t markers) "-")))
2748 (if (string-match "\\^" vmarkers)
2749 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2750 (if (string-match "-" vmarkers)
2751 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2752 (if (> nl 0)
2753 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2754 (int-to-string nl) "\\}")))
2755 ;; Make the regexp
2756 (setq org-emph-re
2757 (concat "\\([" pre "]\\|^\\)"
2758 "\\("
2759 "\\([" markers "]\\)"
2760 "\\("
2761 "[^" border "]\\|"
2762 "[^" border "]"
2763 body1
2764 "[^" border "]"
2765 "\\)"
2766 "\\3\\)"
2767 "\\([" post "]\\|$\\)"))
2768 (setq org-verbatim-re
2769 (concat "\\([" pre "]\\|^\\)"
2770 "\\("
2771 "\\([" vmarkers "]\\)"
2772 "\\("
2773 "[^" border "]\\|"
2774 "[^" border "]"
2775 body1
2776 "[^" border "]"
2777 "\\)"
2778 "\\3\\)"
2779 "\\([" post "]\\|$\\)")))))
2781 (defcustom org-emphasis-regexp-components
2782 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
2783 "Components used to build the regular expression for emphasis.
2784 This is a list with 6 entries. Terminology: In an emphasis string
2785 like \" *strong word* \", we call the initial space PREMATCH, the final
2786 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2787 and \"trong wor\" is the body. The different components in this variable
2788 specify what is allowed/forbidden in each part:
2790 pre Chars allowed as prematch. Beginning of line will be allowed too.
2791 post Chars allowed as postmatch. End of line will be allowed too.
2792 border The chars *forbidden* as border characters.
2793 body-regexp A regexp like \".\" to match a body character. Don't use
2794 non-shy groups here, and don't allow newline here.
2795 newline The maximum number of newlines allowed in an emphasis exp.
2797 Use customize to modify this, or restart Emacs after changing it."
2798 :group 'org-font-lock
2799 :set 'org-set-emph-re
2800 :type '(list
2801 (sexp :tag "Allowed chars in pre ")
2802 (sexp :tag "Allowed chars in post ")
2803 (sexp :tag "Forbidden chars in border ")
2804 (sexp :tag "Regexp for body ")
2805 (integer :tag "number of newlines allowed")
2806 (option (boolean :tag "Please ignore this button"))))
2808 (defcustom org-emphasis-alist
2809 `(("*" bold "<b>" "</b>")
2810 ("/" italic "<i>" "</i>")
2811 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2812 ("=" org-code "<code>" "</code>" verbatim)
2813 ("~" org-verbatim "<code>" "</code>" verbatim)
2814 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2815 "<del>" "</del>")
2817 "Special syntax for emphasized text.
2818 Text starting and ending with a special character will be emphasized, for
2819 example *bold*, _underlined_ and /italic/. This variable sets the marker
2820 characters, the face to be used by font-lock for highlighting in Org-mode
2821 Emacs buffers, and the HTML tags to be used for this.
2822 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
2823 Use customize to modify this, or restart Emacs after changing it."
2824 :group 'org-font-lock
2825 :set 'org-set-emph-re
2826 :type '(repeat
2827 (list
2828 (string :tag "Marker character")
2829 (choice
2830 (face :tag "Font-lock-face")
2831 (plist :tag "Face property list"))
2832 (string :tag "HTML start tag")
2833 (string :tag "HTML end tag")
2834 (option (const verbatim)))))
2836 (defvar org-protecting-blocks
2837 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
2838 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
2839 This is needed for font-lock setup.")
2841 ;;; Miscellaneous options
2843 (defgroup org-completion nil
2844 "Completion in Org-mode."
2845 :tag "Org Completion"
2846 :group 'org)
2848 (defcustom org-completion-use-ido nil
2849 "Non-nil means, use ido completion wherever possible.
2850 Note that `ido-mode' must be active for this variable to be relevant.
2851 If you decide to turn this variable on, you might well want to turn off
2852 `org-outline-path-complete-in-steps'."
2853 :group 'org-completion
2854 :type 'boolean)
2856 (defcustom org-completion-fallback-command 'hippie-expand
2857 "The expansion command called by \\[org-complete] in normal context.
2858 Normal means, no org-mode-specific context."
2859 :group 'org-completion
2860 :type 'function)
2862 ;;; Functions and variables from ther packages
2863 ;; Declared here to avoid compiler warnings
2865 ;; XEmacs only
2866 (defvar outline-mode-menu-heading)
2867 (defvar outline-mode-menu-show)
2868 (defvar outline-mode-menu-hide)
2869 (defvar zmacs-regions) ; XEmacs regions
2871 ;; Emacs only
2872 (defvar mark-active)
2874 ;; Various packages
2875 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2876 (declare-function calendar-forward-day "cal-move" (arg))
2877 (declare-function calendar-goto-date "cal-move" (date))
2878 (declare-function calendar-goto-today "cal-move" ())
2879 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2880 (defvar calc-embedded-close-formula)
2881 (defvar calc-embedded-open-formula)
2882 (declare-function cdlatex-tab "ext:cdlatex" ())
2883 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2884 (defvar font-lock-unfontify-region-function)
2885 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2886 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2887 (defvar iswitchb-temp-buflist)
2888 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2889 (defvar org-agenda-tags-todo-honor-ignore-options)
2890 (declare-function org-agenda-skip "org-agenda" ())
2891 (declare-function org-format-agenda-item "org-agenda"
2892 (extra txt &optional category tags dotime noprefix remove-re))
2893 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2894 (declare-function org-agenda-change-all-lines "org-agenda"
2895 (newhead hdmarker &optional fixface just-this))
2896 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2897 (declare-function org-agenda-maybe-redo "org-agenda" ())
2898 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2899 (beg end))
2900 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2901 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2902 "org-agenda" (&optional end))
2903 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
2904 (declare-function org-indent-mode "org-indent" (arg))
2905 (declare-function parse-time-string "parse-time" (string))
2906 (declare-function remember "remember" (&optional initial))
2907 (declare-function remember-buffer-desc "remember" ())
2908 (declare-function remember-finalize "remember" ())
2909 (defvar remember-save-after-remembering)
2910 (defvar remember-data-file)
2911 (defvar remember-register)
2912 (defvar remember-buffer)
2913 (defvar remember-handler-functions)
2914 (defvar remember-annotation-functions)
2915 (defvar texmathp-why)
2916 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2917 (declare-function table--at-cell-p "table" (position &optional object at-column))
2919 (defvar w3m-current-url)
2920 (defvar w3m-current-title)
2922 (defvar org-latex-regexps)
2924 ;;; Autoload and prepare some org modules
2926 ;; Some table stuff that needs to be defined here, because it is used
2927 ;; by the functions setting up org-mode or checking for table context.
2929 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2930 "Detects an org-type or table-type table.")
2931 (defconst org-table-line-regexp "^[ \t]*|"
2932 "Detects an org-type table line.")
2933 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2934 "Detects an org-type table line.")
2935 (defconst org-table-hline-regexp "^[ \t]*|-"
2936 "Detects an org-type table hline.")
2937 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2938 "Detects a table-type table hline.")
2939 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2940 "Searching from within a table (any type) this finds the first line
2941 outside the table.")
2943 ;; Autoload the functions in org-table.el that are needed by functions here.
2945 (eval-and-compile
2946 (org-autoload "org-table"
2947 '(org-table-align org-table-begin org-table-blank-field
2948 org-table-convert org-table-convert-region org-table-copy-down
2949 org-table-copy-region org-table-create
2950 org-table-create-or-convert-from-region
2951 org-table-create-with-table.el org-table-current-dline
2952 org-table-cut-region org-table-delete-column org-table-edit-field
2953 org-table-edit-formulas org-table-end org-table-eval-formula
2954 org-table-export org-table-field-info
2955 org-table-get-stored-formulas org-table-goto-column
2956 org-table-hline-and-move org-table-import org-table-insert-column
2957 org-table-insert-hline org-table-insert-row org-table-iterate
2958 org-table-justify-field-maybe org-table-kill-row
2959 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2960 org-table-move-column org-table-move-column-left
2961 org-table-move-column-right org-table-move-row
2962 org-table-move-row-down org-table-move-row-up
2963 org-table-next-field org-table-next-row org-table-paste-rectangle
2964 org-table-previous-field org-table-recalculate
2965 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2966 org-table-toggle-coordinate-overlays
2967 org-table-toggle-formula-debugger org-table-wrap-region
2968 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2970 (defun org-at-table-p (&optional table-type)
2971 "Return t if the cursor is inside an org-type table.
2972 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2973 (if org-enable-table-editor
2974 (save-excursion
2975 (beginning-of-line 1)
2976 (looking-at (if table-type org-table-any-line-regexp
2977 org-table-line-regexp)))
2978 nil))
2979 (defsubst org-table-p () (org-at-table-p))
2981 (defun org-at-table.el-p ()
2982 "Return t if and only if we are at a table.el table."
2983 (and (org-at-table-p 'any)
2984 (save-excursion
2985 (goto-char (org-table-begin 'any))
2986 (looking-at org-table1-hline-regexp))))
2987 (defun org-table-recognize-table.el ()
2988 "If there is a table.el table nearby, recognize it and move into it."
2989 (if org-table-tab-recognizes-table.el
2990 (if (org-at-table.el-p)
2991 (progn
2992 (beginning-of-line 1)
2993 (if (looking-at org-table-dataline-regexp)
2995 (if (looking-at org-table1-hline-regexp)
2996 (progn
2997 (beginning-of-line 2)
2998 (if (looking-at org-table-any-border-regexp)
2999 (beginning-of-line -1)))))
3000 (if (re-search-forward "|" (org-table-end t) t)
3001 (progn
3002 (require 'table)
3003 (if (table--at-cell-p (point))
3005 (message "recognizing table.el table...")
3006 (table-recognize-table)
3007 (message "recognizing table.el table...done")))
3008 (error "This should not happen..."))
3010 nil)
3011 nil))
3013 (defun org-at-table-hline-p ()
3014 "Return t if the cursor is inside a hline in a table."
3015 (if org-enable-table-editor
3016 (save-excursion
3017 (beginning-of-line 1)
3018 (looking-at org-table-hline-regexp))
3019 nil))
3021 (defvar org-table-clean-did-remove-column nil)
3023 (defun org-table-map-tables (function)
3024 "Apply FUNCTION to the start of all tables in the buffer."
3025 (save-excursion
3026 (save-restriction
3027 (widen)
3028 (goto-char (point-min))
3029 (while (re-search-forward org-table-any-line-regexp nil t)
3030 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
3031 (beginning-of-line 1)
3032 (when (looking-at org-table-line-regexp)
3033 (save-excursion (funcall function))
3034 (or (looking-at org-table-line-regexp)
3035 (forward-char 1)))
3036 (re-search-forward org-table-any-border-regexp nil 1))))
3037 (message "Mapping tables: done"))
3039 ;; Declare and autoload functions from org-exp.el & Co
3041 (declare-function org-default-export-plist "org-exp")
3042 (declare-function org-infile-export-plist "org-exp")
3043 (declare-function org-get-current-options "org-exp")
3044 (eval-and-compile
3045 (org-autoload "org-exp"
3046 '(org-export org-export-visible
3047 org-insert-export-options-template
3048 org-table-clean-before-export))
3049 (org-autoload "org-ascii"
3050 '(org-export-as-ascii org-export-ascii-preprocess
3051 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3052 org-export-region-as-ascii))
3053 (org-autoload "org-html"
3054 '(org-export-as-html-and-open
3055 org-export-as-html-batch org-export-as-html-to-buffer
3056 org-replace-region-by-html org-export-region-as-html
3057 org-export-as-html))
3058 (org-autoload "org-icalendar"
3059 '(org-export-icalendar-this-file
3060 org-export-icalendar-all-agenda-files
3061 org-export-icalendar-combine-agenda-files))
3062 (org-autoload "org-xoxo" '(org-export-as-xoxo)))
3064 ;; Declare and autoload functions from org-agenda.el
3066 (eval-and-compile
3067 (org-autoload "org-agenda"
3068 '(org-agenda org-agenda-list org-search-view
3069 org-todo-list org-tags-view org-agenda-list-stuck-projects
3070 org-diary org-agenda-to-appt
3071 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3073 ;; Autoload org-remember
3075 (eval-and-compile
3076 (org-autoload "org-remember"
3077 '(org-remember-insinuate org-remember-annotation
3078 org-remember-apply-template org-remember org-remember-handler)))
3080 ;; Autoload org-clock.el
3083 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3084 (beg end))
3085 (declare-function org-clock-update-mode-line "org-clock" ())
3086 (defvar org-clock-start-time)
3087 (defvar org-clock-marker (make-marker)
3088 "Marker recording the last clock-in.")
3089 (defvar org-clock-hd-marker (make-marker)
3090 "Marker recording the last clock-in, but the headline position.")
3091 (defun org-clock-is-active ()
3092 "Return non-nil if clock is currently running.
3093 The return value is actually the clock marker."
3094 (marker-buffer org-clock-marker))
3096 (eval-and-compile
3097 (org-autoload
3098 "org-clock"
3099 '(org-clock-in org-clock-out org-clock-cancel
3100 org-clock-goto org-clock-sum org-clock-display
3101 org-clock-remove-overlays org-clock-report
3102 org-clocktable-shift org-dblock-write:clocktable
3103 org-get-clocktable)))
3105 (defun org-clock-update-time-maybe ()
3106 "If this is a CLOCK line, update it and return t.
3107 Otherwise, return nil."
3108 (interactive)
3109 (save-excursion
3110 (beginning-of-line 1)
3111 (skip-chars-forward " \t")
3112 (when (looking-at org-clock-string)
3113 (let ((re (concat "[ \t]*" org-clock-string
3114 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3115 "\\([ \t]*=>.*\\)?\\)?"))
3116 ts te h m s neg)
3117 (cond
3118 ((not (looking-at re))
3119 nil)
3120 ((not (match-end 2))
3121 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3122 (> org-clock-marker (point))
3123 (<= org-clock-marker (point-at-eol)))
3124 ;; The clock is running here
3125 (setq org-clock-start-time
3126 (apply 'encode-time
3127 (org-parse-time-string (match-string 1))))
3128 (org-clock-update-mode-line)))
3130 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3131 (end-of-line 1)
3132 (setq ts (match-string 1)
3133 te (match-string 3))
3134 (setq s (- (time-to-seconds
3135 (apply 'encode-time (org-parse-time-string te)))
3136 (time-to-seconds
3137 (apply 'encode-time (org-parse-time-string ts))))
3138 neg (< s 0)
3139 s (abs s)
3140 h (floor (/ s 3600))
3141 s (- s (* 3600 h))
3142 m (floor (/ s 60))
3143 s (- s (* 60 s)))
3144 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3145 t))))))
3147 (defun org-check-running-clock ()
3148 "Check if the current buffer contains the running clock.
3149 If yes, offer to stop it and to save the buffer with the changes."
3150 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3151 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3152 (buffer-name))))
3153 (org-clock-out)
3154 (when (y-or-n-p "Save changed buffer?")
3155 (save-buffer))))
3157 (defun org-clocktable-try-shift (dir n)
3158 "Check if this line starts a clock table, if yes, shift the time block."
3159 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3160 (org-clocktable-shift dir n)))
3162 ;; Autoload org-timer.el
3164 (eval-and-compile
3165 (org-autoload
3166 "org-timer"
3167 '(org-timer-start org-timer org-timer-item
3168 org-timer-change-times-in-region
3169 org-timer-set-timer
3170 org-timer-reset-timers
3171 org-timer-show-remaining-time)))
3173 ;; Autoload org-feed.el
3175 (eval-and-compile
3176 (org-autoload
3177 "org-feed"
3178 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3181 ;; Autoload org-indent.el
3183 (eval-and-compile
3184 (org-autoload
3185 "org-indent"
3186 '(org-indent-mode)))
3188 ;; Autoload archiving code
3189 ;; The stuff that is needed for cycling and tags has to be defined here.
3191 (defgroup org-archive nil
3192 "Options concerning archiving in Org-mode."
3193 :tag "Org Archive"
3194 :group 'org-structure)
3196 (defcustom org-archive-location "%s_archive::"
3197 "The location where subtrees should be archived.
3199 The value of this variable is a string, consisting of two parts,
3200 separated by a double-colon. The first part is a filename and
3201 the second part is a headline.
3203 When the filename is omitted, archiving happens in the same file.
3204 %s in the filename will be replaced by the current file
3205 name (without the directory part). Archiving to a different file
3206 is useful to keep archived entries from contributing to the
3207 Org-mode Agenda.
3209 The archived entries will be filed as subtrees of the specified
3210 headline. When the headline is omitted, the subtrees are simply
3211 filed away at the end of the file, as top-level entries. Also in
3212 the heading you can use %s to represent the file name, this can be
3213 useful when using the same archive for a number of different files.
3215 Here are a few examples:
3216 \"%s_archive::\"
3217 If the current file is Projects.org, archive in file
3218 Projects.org_archive, as top-level trees. This is the default.
3220 \"::* Archived Tasks\"
3221 Archive in the current file, under the top-level headline
3222 \"* Archived Tasks\".
3224 \"~/org/archive.org::\"
3225 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3227 \"~/org/archive.org::From %s\"
3228 Archive in file ~/org/archive.org (absolute path), und headlines
3229 \"From FILENAME\" where file name is the current file name.
3231 \"basement::** Finished Tasks\"
3232 Archive in file ./basement (relative path), as level 3 trees
3233 below the level 2 heading \"** Finished Tasks\".
3235 You may set this option on a per-file basis by adding to the buffer a
3236 line like
3238 #+ARCHIVE: basement::** Finished Tasks
3240 You may also define it locally for a subtree by setting an ARCHIVE property
3241 in the entry. If such a property is found in an entry, or anywhere up
3242 the hierarchy, it will be used."
3243 :group 'org-archive
3244 :type 'string)
3246 (defcustom org-archive-tag "ARCHIVE"
3247 "The tag that marks a subtree as archived.
3248 An archived subtree does not open during visibility cycling, and does
3249 not contribute to the agenda listings.
3250 After changing this, font-lock must be restarted in the relevant buffers to
3251 get the proper fontification."
3252 :group 'org-archive
3253 :group 'org-keywords
3254 :type 'string)
3256 (defcustom org-agenda-skip-archived-trees t
3257 "Non-nil means, the agenda will skip any items located in archived trees.
3258 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3259 variable is no longer recommended, you should leave it at the value t.
3260 Instead, use the key `v' to cycle the archives-mode in the agenda."
3261 :group 'org-archive
3262 :group 'org-agenda-skip
3263 :type 'boolean)
3265 (defcustom org-columns-skip-arrchived-trees t
3266 "Non-nil means, irgnore archived trees when creating column view."
3267 :group 'org-archive
3268 :group 'org-properties
3269 :type 'boolean)
3271 (defcustom org-cycle-open-archived-trees nil
3272 "Non-nil means, `org-cycle' will open archived trees.
3273 An archived tree is a tree marked with the tag ARCHIVE.
3274 When nil, archived trees will stay folded. You can still open them with
3275 normal outline commands like `show-all', but not with the cycling commands."
3276 :group 'org-archive
3277 :group 'org-cycle
3278 :type 'boolean)
3280 (defcustom org-sparse-tree-open-archived-trees nil
3281 "Non-nil means sparse tree construction shows matches in archived trees.
3282 When nil, matches in these trees are highlighted, but the trees are kept in
3283 collapsed state."
3284 :group 'org-archive
3285 :group 'org-sparse-trees
3286 :type 'boolean)
3288 (defun org-cycle-hide-archived-subtrees (state)
3289 "Re-hide all archived subtrees after a visibility state change."
3290 (when (and (not org-cycle-open-archived-trees)
3291 (not (memq state '(overview folded))))
3292 (save-excursion
3293 (let* ((globalp (memq state '(contents all)))
3294 (beg (if globalp (point-min) (point)))
3295 (end (if globalp (point-max) (org-end-of-subtree t))))
3296 (org-hide-archived-subtrees beg end)
3297 (goto-char beg)
3298 (if (looking-at (concat ".*:" org-archive-tag ":"))
3299 (message "%s" (substitute-command-keys
3300 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3302 (defun org-force-cycle-archived ()
3303 "Cycle subtree even if it is archived."
3304 (interactive)
3305 (setq this-command 'org-cycle)
3306 (let ((org-cycle-open-archived-trees t))
3307 (call-interactively 'org-cycle)))
3309 (defun org-hide-archived-subtrees (beg end)
3310 "Re-hide all archived subtrees after a visibility state change."
3311 (save-excursion
3312 (let* ((re (concat ":" org-archive-tag ":")))
3313 (goto-char beg)
3314 (while (re-search-forward re end t)
3315 (and (org-on-heading-p) (hide-subtree))
3316 (org-end-of-subtree t)))))
3318 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3320 (eval-and-compile
3321 (org-autoload "org-archive"
3322 '(org-add-archive-files org-archive-subtree
3323 org-archive-to-archive-sibling org-toggle-archive-tag)))
3325 ;; Autoload Column View Code
3327 (declare-function org-columns-number-to-string "org-colview")
3328 (declare-function org-columns-get-format-and-top-level "org-colview")
3329 (declare-function org-columns-compute "org-colview")
3331 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3332 '(org-columns-number-to-string org-columns-get-format-and-top-level
3333 org-columns-compute org-agenda-columns org-columns-remove-overlays
3334 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3336 ;; Autoload ID code
3338 (declare-function org-id-store-link "org-id")
3339 (declare-function org-id-locations-load "org-id")
3340 (declare-function org-id-locations-save "org-id")
3341 (defvar org-id-track-globally)
3342 (org-autoload "org-id"
3343 '(org-id-get-create org-id-new org-id-copy org-id-get
3344 org-id-get-with-outline-path-completion
3345 org-id-get-with-outline-drilling
3346 org-id-goto org-id-find org-id-store-link))
3348 ;; Autoload Plotting Code
3350 (org-autoload "org-plot"
3351 '(org-plot/gnuplot))
3353 ;;; Variables for pre-computed regular expressions, all buffer local
3355 (defvar org-drawer-regexp nil
3356 "Matches first line of a hidden block.")
3357 (make-variable-buffer-local 'org-drawer-regexp)
3358 (defvar org-todo-regexp nil
3359 "Matches any of the TODO state keywords.")
3360 (make-variable-buffer-local 'org-todo-regexp)
3361 (defvar org-not-done-regexp nil
3362 "Matches any of the TODO state keywords except the last one.")
3363 (make-variable-buffer-local 'org-not-done-regexp)
3364 (defvar org-not-done-heading-regexp nil
3365 "Matches a TODO headline that is not done.")
3366 (make-variable-buffer-local 'org-not-done-regexp)
3367 (defvar org-todo-line-regexp nil
3368 "Matches a headline and puts TODO state into group 2 if present.")
3369 (make-variable-buffer-local 'org-todo-line-regexp)
3370 (defvar org-complex-heading-regexp nil
3371 "Matches a headline and puts everything into groups:
3372 group 1: the stars
3373 group 2: The todo keyword, maybe
3374 group 3: Priority cookie
3375 group 4: True headline
3376 group 5: Tags")
3377 (make-variable-buffer-local 'org-complex-heading-regexp)
3378 (defvar org-todo-line-tags-regexp nil
3379 "Matches a headline and puts TODO state into group 2 if present.
3380 Also put tags into group 4 if tags are present.")
3381 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3382 (defvar org-nl-done-regexp nil
3383 "Matches newline followed by a headline with the DONE keyword.")
3384 (make-variable-buffer-local 'org-nl-done-regexp)
3385 (defvar org-looking-at-done-regexp nil
3386 "Matches the DONE keyword a point.")
3387 (make-variable-buffer-local 'org-looking-at-done-regexp)
3388 (defvar org-ds-keyword-length 12
3389 "Maximum length of the Deadline and SCHEDULED keywords.")
3390 (make-variable-buffer-local 'org-ds-keyword-length)
3391 (defvar org-deadline-regexp nil
3392 "Matches the DEADLINE keyword.")
3393 (make-variable-buffer-local 'org-deadline-regexp)
3394 (defvar org-deadline-time-regexp nil
3395 "Matches the DEADLINE keyword together with a time stamp.")
3396 (make-variable-buffer-local 'org-deadline-time-regexp)
3397 (defvar org-deadline-line-regexp nil
3398 "Matches the DEADLINE keyword and the rest of the line.")
3399 (make-variable-buffer-local 'org-deadline-line-regexp)
3400 (defvar org-scheduled-regexp nil
3401 "Matches the SCHEDULED keyword.")
3402 (make-variable-buffer-local 'org-scheduled-regexp)
3403 (defvar org-scheduled-time-regexp nil
3404 "Matches the SCHEDULED keyword together with a time stamp.")
3405 (make-variable-buffer-local 'org-scheduled-time-regexp)
3406 (defvar org-closed-time-regexp nil
3407 "Matches the CLOSED keyword together with a time stamp.")
3408 (make-variable-buffer-local 'org-closed-time-regexp)
3410 (defvar org-keyword-time-regexp nil
3411 "Matches any of the 4 keywords, together with the time stamp.")
3412 (make-variable-buffer-local 'org-keyword-time-regexp)
3413 (defvar org-keyword-time-not-clock-regexp nil
3414 "Matches any of the 3 keywords, together with the time stamp.")
3415 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3416 (defvar org-maybe-keyword-time-regexp nil
3417 "Matches a timestamp, possibly preceeded by a keyword.")
3418 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3419 (defvar org-planning-or-clock-line-re nil
3420 "Matches a line with planning or clock info.")
3421 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3423 (defconst org-plain-time-of-day-regexp
3424 (concat
3425 "\\(\\<[012]?[0-9]"
3426 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3427 "\\(--?"
3428 "\\(\\<[012]?[0-9]"
3429 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3430 "\\)?")
3431 "Regular expression to match a plain time or time range.
3432 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3433 groups carry important information:
3434 0 the full match
3435 1 the first time, range or not
3436 8 the second time, if it is a range.")
3438 (defconst org-plain-time-extension-regexp
3439 (concat
3440 "\\(\\<[012]?[0-9]"
3441 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3442 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3443 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3444 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3445 groups carry important information:
3446 0 the full match
3447 7 hours of duration
3448 9 minutes of duration")
3450 (defconst org-stamp-time-of-day-regexp
3451 (concat
3452 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3453 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3454 "\\(--?"
3455 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3456 "Regular expression to match a timestamp time or time range.
3457 After a match, the following groups carry important information:
3458 0 the full match
3459 1 date plus weekday, for backreferencing to make sure both times on same day
3460 2 the first time, range or not
3461 4 the second time, if it is a range.")
3463 (defconst org-startup-options
3464 '(("fold" org-startup-folded t)
3465 ("overview" org-startup-folded t)
3466 ("nofold" org-startup-folded nil)
3467 ("showall" org-startup-folded nil)
3468 ("content" org-startup-folded content)
3469 ("indent" org-startup-indented t)
3470 ("noindent" org-startup-indented nil)
3471 ("hidestars" org-hide-leading-stars t)
3472 ("showstars" org-hide-leading-stars nil)
3473 ("odd" org-odd-levels-only t)
3474 ("oddeven" org-odd-levels-only nil)
3475 ("align" org-startup-align-all-tables t)
3476 ("noalign" org-startup-align-all-tables nil)
3477 ("customtime" org-display-custom-times t)
3478 ("logdone" org-log-done time)
3479 ("lognotedone" org-log-done note)
3480 ("nologdone" org-log-done nil)
3481 ("lognoteclock-out" org-log-note-clock-out t)
3482 ("nolognoteclock-out" org-log-note-clock-out nil)
3483 ("logrepeat" org-log-repeat state)
3484 ("lognoterepeat" org-log-repeat note)
3485 ("nologrepeat" org-log-repeat nil)
3486 ("fninline" org-footnote-define-inline t)
3487 ("nofninline" org-footnote-define-inline nil)
3488 ("fnlocal" org-footnote-section nil)
3489 ("fnauto" org-footnote-auto-label t)
3490 ("fnprompt" org-footnote-auto-label nil)
3491 ("fnconfirm" org-footnote-auto-label confirm)
3492 ("fnplain" org-footnote-auto-label plain)
3493 ("fnadjust" org-footnote-auto-adjust t)
3494 ("nofnadjust" org-footnote-auto-adjust nil)
3495 ("constcgs" constants-unit-system cgs)
3496 ("constSI" constants-unit-system SI)
3497 ("noptag" org-tag-persistent-alist nil)
3498 ("hideblocks" org-hide-block-startup t)
3499 ("nohideblocks" org-hide-block-startup nil))
3500 "Variable associated with STARTUP options for org-mode.
3501 Each element is a list of three items: The startup options as written
3502 in the #+STARTUP line, the corresponding variable, and the value to
3503 set this variable to if the option is found. An optional forth element PUSH
3504 means to push this value onto the list in the variable.")
3506 (defun org-set-regexps-and-options ()
3507 "Precompute regular expressions for current buffer."
3508 (when (org-mode-p)
3509 (org-set-local 'org-todo-kwd-alist nil)
3510 (org-set-local 'org-todo-key-alist nil)
3511 (org-set-local 'org-todo-key-trigger nil)
3512 (org-set-local 'org-todo-keywords-1 nil)
3513 (org-set-local 'org-done-keywords nil)
3514 (org-set-local 'org-todo-heads nil)
3515 (org-set-local 'org-todo-sets nil)
3516 (org-set-local 'org-todo-log-states nil)
3517 (org-set-local 'org-file-properties nil)
3518 (org-set-local 'org-file-tags nil)
3519 (let ((re (org-make-options-regexp
3520 '("CATEGORY" "TODO" "COLUMNS"
3521 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3522 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3523 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3524 (splitre "[ \t]+")
3525 kwds kws0 kwsa key log value cat arch tags const links hw dws
3526 tail sep kws1 prio props ftags drawers
3527 ext-setup-or-nil setup-contents (start 0))
3528 (save-excursion
3529 (save-restriction
3530 (widen)
3531 (goto-char (point-min))
3532 (while (or (and ext-setup-or-nil
3533 (string-match re ext-setup-or-nil start)
3534 (setq start (match-end 0)))
3535 (and (setq ext-setup-or-nil nil start 0)
3536 (re-search-forward re nil t)))
3537 (setq key (upcase (match-string 1 ext-setup-or-nil))
3538 value (org-match-string-no-properties 2 ext-setup-or-nil))
3539 (cond
3540 ((equal key "CATEGORY")
3541 (if (string-match "[ \t]+$" value)
3542 (setq value (replace-match "" t t value)))
3543 (setq cat value))
3544 ((member key '("SEQ_TODO" "TODO"))
3545 (push (cons 'sequence (org-split-string value splitre)) kwds))
3546 ((equal key "TYP_TODO")
3547 (push (cons 'type (org-split-string value splitre)) kwds))
3548 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3549 ;; general TODO-like setup
3550 (push (cons (intern (downcase (match-string 1 key)))
3551 (org-split-string value splitre)) kwds))
3552 ((equal key "TAGS")
3553 (setq tags (append tags (if tags '("\\n") nil)
3554 (org-split-string value splitre))))
3555 ((equal key "COLUMNS")
3556 (org-set-local 'org-columns-default-format value))
3557 ((equal key "LINK")
3558 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3559 (push (cons (match-string 1 value)
3560 (org-trim (match-string 2 value)))
3561 links)))
3562 ((equal key "PRIORITIES")
3563 (setq prio (org-split-string value " +")))
3564 ((equal key "PROPERTY")
3565 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3566 (push (cons (match-string 1 value) (match-string 2 value))
3567 props)))
3568 ((equal key "FILETAGS")
3569 (when (string-match "\\S-" value)
3570 (setq ftags
3571 (append
3572 ftags
3573 (apply 'append
3574 (mapcar (lambda (x) (org-split-string x ":"))
3575 (org-split-string value)))))))
3576 ((equal key "DRAWERS")
3577 (setq drawers (org-split-string value splitre)))
3578 ((equal key "CONSTANTS")
3579 (setq const (append const (org-split-string value splitre))))
3580 ((equal key "STARTUP")
3581 (let ((opts (org-split-string value splitre))
3582 l var val)
3583 (while (setq l (pop opts))
3584 (when (setq l (assoc l org-startup-options))
3585 (setq var (nth 1 l) val (nth 2 l))
3586 (if (not (nth 3 l))
3587 (set (make-local-variable var) val)
3588 (if (not (listp (symbol-value var)))
3589 (set (make-local-variable var) nil))
3590 (set (make-local-variable var) (symbol-value var))
3591 (add-to-list var val))))))
3592 ((equal key "ARCHIVE")
3593 (string-match " *$" value)
3594 (setq arch (replace-match "" t t value))
3595 (remove-text-properties 0 (length arch)
3596 '(face t fontified t) arch))
3597 ((equal key "SETUPFILE")
3598 (setq setup-contents (org-file-contents
3599 (expand-file-name
3600 (org-remove-double-quotes value))
3601 'noerror))
3602 (if (not ext-setup-or-nil)
3603 (setq ext-setup-or-nil setup-contents start 0)
3604 (setq ext-setup-or-nil
3605 (concat (substring ext-setup-or-nil 0 start)
3606 "\n" setup-contents "\n"
3607 (substring ext-setup-or-nil start)))))
3608 ))))
3609 (when cat
3610 (org-set-local 'org-category (intern cat))
3611 (push (cons "CATEGORY" cat) props))
3612 (when prio
3613 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3614 (setq prio (mapcar 'string-to-char prio))
3615 (org-set-local 'org-highest-priority (nth 0 prio))
3616 (org-set-local 'org-lowest-priority (nth 1 prio))
3617 (org-set-local 'org-default-priority (nth 2 prio)))
3618 (and props (org-set-local 'org-file-properties (nreverse props)))
3619 (and ftags (org-set-local 'org-file-tags
3620 (mapcar 'org-add-prop-inherited ftags)))
3621 (and drawers (org-set-local 'org-drawers drawers))
3622 (and arch (org-set-local 'org-archive-location arch))
3623 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3624 ;; Process the TODO keywords
3625 (unless kwds
3626 ;; Use the global values as if they had been given locally.
3627 (setq kwds (default-value 'org-todo-keywords))
3628 (if (stringp (car kwds))
3629 (setq kwds (list (cons org-todo-interpretation
3630 (default-value 'org-todo-keywords)))))
3631 (setq kwds (reverse kwds)))
3632 (setq kwds (nreverse kwds))
3633 (let (inter kws kw)
3634 (while (setq kws (pop kwds))
3635 (let ((kws (or
3636 (run-hook-with-args-until-success
3637 'org-todo-setup-filter-hook kws)
3638 kws)))
3639 (setq inter (pop kws) sep (member "|" kws)
3640 kws0 (delete "|" (copy-sequence kws))
3641 kwsa nil
3642 kws1 (mapcar
3643 (lambda (x)
3644 ;; 1 2
3645 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3646 (progn
3647 (setq kw (match-string 1 x)
3648 key (and (match-end 2) (match-string 2 x))
3649 log (org-extract-log-state-settings x))
3650 (push (cons kw (and key (string-to-char key))) kwsa)
3651 (and log (push log org-todo-log-states))
3653 (error "Invalid TODO keyword %s" x)))
3654 kws0)
3655 kwsa (if kwsa (append '((:startgroup))
3656 (nreverse kwsa)
3657 '((:endgroup))))
3658 hw (car kws1)
3659 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3660 tail (list inter hw (car dws) (org-last dws))))
3661 (add-to-list 'org-todo-heads hw 'append)
3662 (push kws1 org-todo-sets)
3663 (setq org-done-keywords (append org-done-keywords dws nil))
3664 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3665 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3666 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3667 (setq org-todo-sets (nreverse org-todo-sets)
3668 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3669 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3670 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3671 ;; Process the constants
3672 (when const
3673 (let (e cst)
3674 (while (setq e (pop const))
3675 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3676 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3677 (setq org-table-formula-constants-local cst)))
3679 ;; Process the tags.
3680 (when tags
3681 (let (e tgs)
3682 (while (setq e (pop tags))
3683 (cond
3684 ((equal e "{") (push '(:startgroup) tgs))
3685 ((equal e "}") (push '(:endgroup) tgs))
3686 ((equal e "\\n") (push '(:newline) tgs))
3687 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3688 (push (cons (match-string 1 e)
3689 (string-to-char (match-string 2 e)))
3690 tgs))
3691 (t (push (list e) tgs))))
3692 (org-set-local 'org-tag-alist nil)
3693 (while (setq e (pop tgs))
3694 (or (and (stringp (car e))
3695 (assoc (car e) org-tag-alist))
3696 (push e org-tag-alist)))))
3698 ;; Compute the regular expressions and other local variables
3699 (if (not org-done-keywords)
3700 (setq org-done-keywords (and org-todo-keywords-1
3701 (list (org-last org-todo-keywords-1)))))
3702 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3703 (length org-scheduled-string)
3704 (length org-clock-string)
3705 (length org-closed-string)))
3706 org-drawer-regexp
3707 (concat "^[ \t]*:\\("
3708 (mapconcat 'regexp-quote org-drawers "\\|")
3709 "\\):[ \t]*$")
3710 org-not-done-keywords
3711 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3712 org-todo-regexp
3713 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3714 "\\|") "\\)\\>")
3715 org-not-done-regexp
3716 (concat "\\<\\("
3717 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3718 "\\)\\>")
3719 org-not-done-heading-regexp
3720 (concat "^\\(\\*+\\)[ \t]+\\("
3721 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3722 "\\)\\>")
3723 org-todo-line-regexp
3724 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3725 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3726 "\\)\\>\\)?[ \t]*\\(.*\\)")
3727 org-complex-heading-regexp
3728 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3729 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3730 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3731 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3732 org-nl-done-regexp
3733 (concat "\n\\*+[ \t]+"
3734 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3735 "\\)" "\\>")
3736 org-todo-line-tags-regexp
3737 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3738 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3739 (org-re
3740 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3741 org-looking-at-done-regexp
3742 (concat "^" "\\(?:"
3743 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3744 "\\>")
3745 org-deadline-regexp (concat "\\<" org-deadline-string)
3746 org-deadline-time-regexp
3747 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3748 org-deadline-line-regexp
3749 (concat "\\<\\(" org-deadline-string "\\).*")
3750 org-scheduled-regexp
3751 (concat "\\<" org-scheduled-string)
3752 org-scheduled-time-regexp
3753 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3754 org-closed-time-regexp
3755 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3756 org-keyword-time-regexp
3757 (concat "\\<\\(" org-scheduled-string
3758 "\\|" org-deadline-string
3759 "\\|" org-closed-string
3760 "\\|" org-clock-string "\\)"
3761 " *[[<]\\([^]>]+\\)[]>]")
3762 org-keyword-time-not-clock-regexp
3763 (concat "\\<\\(" org-scheduled-string
3764 "\\|" org-deadline-string
3765 "\\|" org-closed-string
3766 "\\)"
3767 " *[[<]\\([^]>]+\\)[]>]")
3768 org-maybe-keyword-time-regexp
3769 (concat "\\(\\<\\(" org-scheduled-string
3770 "\\|" org-deadline-string
3771 "\\|" org-closed-string
3772 "\\|" org-clock-string "\\)\\)?"
3773 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3774 org-planning-or-clock-line-re
3775 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3776 "\\|" org-deadline-string
3777 "\\|" org-closed-string "\\|" org-clock-string
3778 "\\)\\>\\)")
3780 (org-compute-latex-and-specials-regexp)
3781 (org-set-font-lock-defaults))))
3783 (defun org-file-contents (file &optional noerror)
3784 "Return the contents of FILE, as a string."
3785 (if (or (not file)
3786 (not (file-readable-p file)))
3787 (if noerror
3788 (progn
3789 (message "Cannot read file %s" file)
3790 (ding) (sit-for 2)
3792 (error "Cannot read file %s" file))
3793 (with-temp-buffer
3794 (insert-file-contents file)
3795 (buffer-string))))
3797 (defun org-extract-log-state-settings (x)
3798 "Extract the log state setting from a TODO keyword string.
3799 This will extract info from a string like \"WAIT(w@/!)\"."
3800 (let (kw key log1 log2)
3801 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3802 (setq kw (match-string 1 x)
3803 key (and (match-end 2) (match-string 2 x))
3804 log1 (and (match-end 3) (match-string 3 x))
3805 log2 (and (match-end 4) (match-string 4 x)))
3806 (and (or log1 log2)
3807 (list kw
3808 (and log1 (if (equal log1 "!") 'time 'note))
3809 (and log2 (if (equal log2 "!") 'time 'note)))))))
3811 (defun org-remove-keyword-keys (list)
3812 "Remove a pair of parenthesis at the end of each string in LIST."
3813 (mapcar (lambda (x)
3814 (if (string-match "(.*)$" x)
3815 (substring x 0 (match-beginning 0))
3817 list))
3819 ;; FIXME: this could be done much better, using second characters etc.
3820 (defun org-assign-fast-keys (alist)
3821 "Assign fast keys to a keyword-key alist.
3822 Respect keys that are already there."
3823 (let (new e k c c1 c2 (char ?a))
3824 (while (setq e (pop alist))
3825 (cond
3826 ((equal e '(:startgroup)) (push e new))
3827 ((equal e '(:endgroup)) (push e new))
3828 ((equal e '(:newline)) (push e new))
3830 (setq k (car e) c2 nil)
3831 (if (cdr e)
3832 (setq c (cdr e))
3833 ;; automatically assign a character.
3834 (setq c1 (string-to-char
3835 (downcase (substring
3836 k (if (= (string-to-char k) ?@) 1 0)))))
3837 (if (or (rassoc c1 new) (rassoc c1 alist))
3838 (while (or (rassoc char new) (rassoc char alist))
3839 (setq char (1+ char)))
3840 (setq c2 c1))
3841 (setq c (or c2 char)))
3842 (push (cons k c) new))))
3843 (nreverse new)))
3845 ;;; Some variables used in various places
3847 (defvar org-window-configuration nil
3848 "Used in various places to store a window configuration.")
3849 (defvar org-finish-function nil
3850 "Function to be called when `C-c C-c' is used.
3851 This is for getting out of special buffers like remember.")
3854 ;; FIXME: Occasionally check by commenting these, to make sure
3855 ;; no other functions uses these, forgetting to let-bind them.
3856 (defvar entry)
3857 (defvar last-state)
3858 (defvar date)
3860 ;; Defined somewhere in this file, but used before definition.
3861 (defvar org-html-entities)
3862 (defvar org-struct-menu)
3863 (defvar org-org-menu)
3864 (defvar org-tbl-menu)
3865 (defvar org-agenda-keymap)
3867 ;;;; Define the Org-mode
3869 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3870 (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."))
3873 ;; We use a before-change function to check if a table might need
3874 ;; an update.
3875 (defvar org-table-may-need-update t
3876 "Indicates that a table might need an update.
3877 This variable is set by `org-before-change-function'.
3878 `org-table-align' sets it back to nil.")
3879 (defun org-before-change-function (beg end)
3880 "Every change indicates that a table might need an update."
3881 (setq org-table-may-need-update t))
3882 (defvar org-mode-map)
3883 (defvar org-mode-hook nil
3884 "Mode hook for Org-mode, run after the mode was turned on.")
3885 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3886 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3887 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
3888 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
3889 (defvar org-table-buffer-is-an nil)
3890 (defconst org-outline-regexp "\\*+ ")
3892 ;;;###autoload
3893 (define-derived-mode org-mode outline-mode "Org"
3894 "Outline-based notes management and organizer, alias
3895 \"Carsten's outline-mode for keeping track of everything.\"
3897 Org-mode develops organizational tasks around a NOTES file which
3898 contains information about projects as plain text. Org-mode is
3899 implemented on top of outline-mode, which is ideal to keep the content
3900 of large files well structured. It supports ToDo items, deadlines and
3901 time stamps, which magically appear in the diary listing of the Emacs
3902 calendar. Tables are easily created with a built-in table editor.
3903 Plain text URL-like links connect to websites, emails (VM), Usenet
3904 messages (Gnus), BBDB entries, and any files related to the project.
3905 For printing and sharing of notes, an Org-mode file (or a part of it)
3906 can be exported as a structured ASCII or HTML file.
3908 The following commands are available:
3910 \\{org-mode-map}"
3912 ;; Get rid of Outline menus, they are not needed
3913 ;; Need to do this here because define-derived-mode sets up
3914 ;; the keymap so late. Still, it is a waste to call this each time
3915 ;; we switch another buffer into org-mode.
3916 (if (featurep 'xemacs)
3917 (when (boundp 'outline-mode-menu-heading)
3918 ;; Assume this is Greg's port, it used easymenu
3919 (easy-menu-remove outline-mode-menu-heading)
3920 (easy-menu-remove outline-mode-menu-show)
3921 (easy-menu-remove outline-mode-menu-hide))
3922 (define-key org-mode-map [menu-bar headings] 'undefined)
3923 (define-key org-mode-map [menu-bar hide] 'undefined)
3924 (define-key org-mode-map [menu-bar show] 'undefined))
3926 (org-load-modules-maybe)
3927 (easy-menu-add org-org-menu)
3928 (easy-menu-add org-tbl-menu)
3929 (org-install-agenda-files-menu)
3930 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3931 (org-add-to-invisibility-spec '(org-cwidth))
3932 (org-add-to-invisibility-spec '(org-hide-block . t))
3933 (when (featurep 'xemacs)
3934 (org-set-local 'line-move-ignore-invisible t))
3935 (org-set-local 'outline-regexp org-outline-regexp)
3936 (org-set-local 'outline-level 'org-outline-level)
3937 (when (and org-ellipsis
3938 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3939 (fboundp 'make-glyph-code))
3940 (unless org-display-table
3941 (setq org-display-table (make-display-table)))
3942 (set-display-table-slot
3943 org-display-table 4
3944 (vconcat (mapcar
3945 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3946 org-ellipsis)))
3947 (if (stringp org-ellipsis) org-ellipsis "..."))))
3948 (setq buffer-display-table org-display-table))
3949 (org-set-regexps-and-options)
3950 (when (and org-tag-faces (not org-tags-special-faces-re))
3951 ;; tag faces set outside customize.... force initialization.
3952 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3953 ;; Calc embedded
3954 (org-set-local 'calc-embedded-open-mode "# ")
3955 (modify-syntax-entry ?# "<")
3956 (modify-syntax-entry ?@ "w")
3957 (if org-startup-truncated (setq truncate-lines t))
3958 (org-set-local 'font-lock-unfontify-region-function
3959 'org-unfontify-region)
3960 ;; Activate before-change-function
3961 (org-set-local 'org-table-may-need-update t)
3962 (org-add-hook 'before-change-functions 'org-before-change-function nil
3963 'local)
3964 ;; Check for running clock before killing a buffer
3965 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3966 ;; Paragraphs and auto-filling
3967 (org-set-autofill-regexps)
3968 (setq indent-line-function 'org-indent-line-function)
3969 (org-update-radio-target-regexp)
3970 ;; Make sure dependence stuff works reliably, even for users who set it
3971 ;; too late :-(
3972 (if org-enforce-todo-dependencies
3973 (add-hook 'org-blocker-hook
3974 'org-block-todo-from-children-or-siblings-or-parent)
3975 (remove-hook 'org-blocker-hook
3976 'org-block-todo-from-children-or-siblings-or-parent))
3977 (if org-enforce-todo-checkbox-dependencies
3978 (add-hook 'org-blocker-hook
3979 'org-block-todo-from-checkboxes)
3980 (remove-hook 'org-blocker-hook
3981 'org-block-todo-from-checkboxes))
3983 ;; Comment characters
3984 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3985 (org-set-local 'comment-padding " ")
3987 ;; Align options lines
3988 (org-set-local
3989 'align-mode-rules-list
3990 '((org-in-buffer-settings
3991 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3992 (modes . '(org-mode)))))
3994 ;; Imenu
3995 (org-set-local 'imenu-create-index-function
3996 'org-imenu-get-tree)
3998 ;; Make isearch reveal context
3999 (if (or (featurep 'xemacs)
4000 (not (boundp 'outline-isearch-open-invisible-function)))
4001 ;; Emacs 21 and XEmacs make use of the hook
4002 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4003 ;; Emacs 22 deals with this through a special variable
4004 (org-set-local 'outline-isearch-open-invisible-function
4005 (lambda (&rest ignore) (org-show-context 'isearch))))
4007 ;; If empty file that did not turn on org-mode automatically, make it to.
4008 (if (and org-insert-mode-line-in-empty-file
4009 (interactive-p)
4010 (= (point-min) (point-max)))
4011 (insert "# -*- mode: org -*-\n\n"))
4013 (unless org-inhibit-startup
4014 (when org-startup-align-all-tables
4015 (let ((bmp (buffer-modified-p)))
4016 (org-table-map-tables 'org-table-align)
4017 (set-buffer-modified-p bmp)))
4018 (when org-startup-indented
4019 (require 'org-indent)
4020 (org-indent-mode 1))
4021 (org-set-startup-visibility)))
4023 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4025 (defun org-current-time ()
4026 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4027 (if (> (car org-time-stamp-rounding-minutes) 1)
4028 (let ((r (car org-time-stamp-rounding-minutes))
4029 (time (decode-time)))
4030 (apply 'encode-time
4031 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4032 (nthcdr 2 time))))
4033 (current-time)))
4035 ;;;; Font-Lock stuff, including the activators
4037 (defvar org-mouse-map (make-sparse-keymap))
4038 (org-defkey org-mouse-map
4039 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4040 (org-defkey org-mouse-map
4041 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4042 (when org-mouse-1-follows-link
4043 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4044 (when org-tab-follows-link
4045 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4046 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4048 (require 'font-lock)
4050 (defconst org-non-link-chars "]\t\n\r<>")
4051 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4052 "shell" "elisp"))
4053 (defvar org-link-types-re nil
4054 "Matches a link that has a url-like prefix like \"http:\"")
4055 (defvar org-link-re-with-space nil
4056 "Matches a link with spaces, optional angular brackets around it.")
4057 (defvar org-link-re-with-space2 nil
4058 "Matches a link with spaces, optional angular brackets around it.")
4059 (defvar org-link-re-with-space3 nil
4060 "Matches a link with spaces, only for internal part in bracket links.")
4061 (defvar org-angle-link-re nil
4062 "Matches link with angular brackets, spaces are allowed.")
4063 (defvar org-plain-link-re nil
4064 "Matches plain link, without spaces.")
4065 (defvar org-bracket-link-regexp nil
4066 "Matches a link in double brackets.")
4067 (defvar org-bracket-link-analytic-regexp nil
4068 "Regular expression used to analyze links.
4069 Here is what the match groups contain after a match:
4070 1: http:
4071 2: http
4072 3: path
4073 4: [desc]
4074 5: desc")
4075 (defvar org-bracket-link-analytic-regexp++ nil
4076 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4077 (defvar org-any-link-re nil
4078 "Regular expression matching any link.")
4080 (defun org-make-link-regexps ()
4081 "Update the link regular expressions.
4082 This should be called after the variable `org-link-types' has changed."
4083 (setq org-link-types-re
4084 (concat
4085 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
4086 org-link-re-with-space
4087 (concat
4088 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4089 "\\([^" org-non-link-chars " ]"
4090 "[^" org-non-link-chars "]*"
4091 "[^" org-non-link-chars " ]\\)>?")
4092 org-link-re-with-space2
4093 (concat
4094 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4095 "\\([^" org-non-link-chars " ]"
4096 "[^\t\n\r]*"
4097 "[^" org-non-link-chars " ]\\)>?")
4098 org-link-re-with-space3
4099 (concat
4100 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4101 "\\([^" org-non-link-chars " ]"
4102 "[^\t\n\r]*\\)")
4103 org-angle-link-re
4104 (concat
4105 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4106 "\\([^" org-non-link-chars " ]"
4107 "[^" org-non-link-chars "]*"
4108 "\\)>")
4109 org-plain-link-re
4110 (concat
4111 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4112 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4113 org-bracket-link-regexp
4114 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4115 org-bracket-link-analytic-regexp
4116 (concat
4117 "\\[\\["
4118 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4119 "\\([^]]+\\)"
4120 "\\]"
4121 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4122 "\\]")
4123 org-bracket-link-analytic-regexp++
4124 (concat
4125 "\\[\\["
4126 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4127 "\\([^]]+\\)"
4128 "\\]"
4129 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4130 "\\]")
4131 org-any-link-re
4132 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4133 org-angle-link-re "\\)\\|\\("
4134 org-plain-link-re "\\)")))
4136 (org-make-link-regexps)
4138 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4139 "Regular expression for fast time stamp matching.")
4140 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4141 "Regular expression for fast time stamp matching.")
4142 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4143 "Regular expression matching time strings for analysis.
4144 This one does not require the space after the date, so it can be used
4145 on a string that terminates immediately after the date.")
4146 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4147 "Regular expression matching time strings for analysis.")
4148 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4149 "Regular expression matching time stamps, with groups.")
4150 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4151 "Regular expression matching time stamps (also [..]), with groups.")
4152 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4153 "Regular expression matching a time stamp range.")
4154 (defconst org-tr-regexp-both
4155 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4156 "Regular expression matching a time stamp range.")
4157 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4158 org-ts-regexp "\\)?")
4159 "Regular expression matching a time stamp or time stamp range.")
4160 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4161 org-ts-regexp-both "\\)?")
4162 "Regular expression matching a time stamp or time stamp range.
4163 The time stamps may be either active or inactive.")
4165 (defvar org-emph-face nil)
4167 (defun org-do-emphasis-faces (limit)
4168 "Run through the buffer and add overlays to links."
4169 (let (rtn a)
4170 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4171 (if (not (= (char-after (match-beginning 3))
4172 (char-after (match-beginning 4))))
4173 (progn
4174 (setq rtn t)
4175 (setq a (assoc (match-string 3) org-emphasis-alist))
4176 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4177 'face
4178 (nth 1 a))
4179 (and (nth 4 a)
4180 (org-remove-flyspell-overlays-in
4181 (match-beginning 0) (match-end 0)))
4182 (add-text-properties (match-beginning 2) (match-end 2)
4183 '(font-lock-multiline t))
4184 (when org-hide-emphasis-markers
4185 (add-text-properties (match-end 4) (match-beginning 5)
4186 '(invisible org-link))
4187 (add-text-properties (match-beginning 3) (match-end 3)
4188 '(invisible org-link)))))
4189 (backward-char 1))
4190 rtn))
4192 (defun org-emphasize (&optional char)
4193 "Insert or change an emphasis, i.e. a font like bold or italic.
4194 If there is an active region, change that region to a new emphasis.
4195 If there is no region, just insert the marker characters and position
4196 the cursor between them.
4197 CHAR should be either the marker character, or the first character of the
4198 HTML tag associated with that emphasis. If CHAR is a space, the means
4199 to remove the emphasis of the selected region.
4200 If char is not given (for example in an interactive call) it
4201 will be prompted for."
4202 (interactive)
4203 (let ((eal org-emphasis-alist) e det
4204 (erc org-emphasis-regexp-components)
4205 (prompt "")
4206 (string "") beg end move tag c s)
4207 (if (org-region-active-p)
4208 (setq beg (region-beginning) end (region-end)
4209 string (buffer-substring beg end))
4210 (setq move t))
4212 (while (setq e (pop eal))
4213 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4214 c (aref tag 0))
4215 (push (cons c (string-to-char (car e))) det)
4216 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4217 (substring tag 1)))))
4218 (setq det (nreverse det))
4219 (unless char
4220 (message "%s" (concat "Emphasis marker or tag:" prompt))
4221 (setq char (read-char-exclusive)))
4222 (setq char (or (cdr (assoc char det)) char))
4223 (if (equal char ?\ )
4224 (setq s "" move nil)
4225 (unless (assoc (char-to-string char) org-emphasis-alist)
4226 (error "No such emphasis marker: \"%c\"" char))
4227 (setq s (char-to-string char)))
4228 (while (and (> (length string) 1)
4229 (equal (substring string 0 1) (substring string -1))
4230 (assoc (substring string 0 1) org-emphasis-alist))
4231 (setq string (substring string 1 -1)))
4232 (setq string (concat s string s))
4233 (if beg (delete-region beg end))
4234 (unless (or (bolp)
4235 (string-match (concat "[" (nth 0 erc) "\n]")
4236 (char-to-string (char-before (point)))))
4237 (insert " "))
4238 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4239 (char-to-string (char-after (point))))
4240 (insert " ") (backward-char 1))
4241 (insert string)
4242 (and move (backward-char 1))))
4244 (defconst org-nonsticky-props
4245 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4247 (defsubst org-rear-nonsticky-at (pos)
4248 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4250 (defun org-activate-plain-links (limit)
4251 "Run through the buffer and add overlays to links."
4252 (catch 'exit
4253 (let (f)
4254 (if (re-search-forward org-plain-link-re limit t)
4255 (progn
4256 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4257 (setq f (get-text-property (match-beginning 0) 'face))
4258 (if (or (eq f 'org-tag)
4259 (and (listp f) (memq 'org-tag f)))
4261 (add-text-properties (match-beginning 0) (match-end 0)
4262 (list 'mouse-face 'highlight
4263 'keymap org-mouse-map))
4264 (org-rear-nonsticky-at (match-end 0)))
4265 t)))))
4267 (defun org-activate-code (limit)
4268 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4269 (progn
4270 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4271 (remove-text-properties (match-beginning 0) (match-end 0)
4272 '(display t invisible t intangible t))
4273 t)))
4275 (defun org-fontify-meta-lines-and-blocks (limit)
4276 "Fontify #+ lines and blocks, in the correct ways."
4277 (let ((case-fold-search t))
4278 (if (re-search-forward
4279 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4280 limit t)
4281 (let ((beg (match-beginning 0))
4282 (beg1 (line-beginning-position 2))
4283 (dc1 (downcase (match-string 2)))
4284 (dc3 (downcase (match-string 3)))
4285 end end1 quoting)
4286 (cond
4287 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4288 ;; a single line of backend-specific content
4289 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4290 (remove-text-properties (match-beginning 0) (match-end 0)
4291 '(display t invisible t intangible t))
4292 (add-text-properties (match-beginning 1) (match-end 3)
4293 '(font-lock-fontified t face org-meta-line))
4294 (add-text-properties (match-beginning 6) (match-end 6)
4295 '(font-lock-fontified t face org-block))
4297 ((and (match-end 4) (equal dc3 "begin"))
4298 ;; Truely a block
4299 (setq quoting (member (downcase (match-string 5))
4300 org-protecting-blocks))
4301 (when (re-search-forward
4302 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4303 nil t) ;; on purpose, we look further than LIMIT
4304 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4305 (when quoting
4306 (remove-text-properties beg end
4307 '(display t invisible t intangible t)))
4308 (add-text-properties
4309 beg end
4310 '(font-lock-fontified t font-lock-multiline t))
4311 (add-text-properties beg beg1 '(face org-meta-line))
4312 (add-text-properties end1 end '(face org-meta-line))
4313 (when quoting
4314 (add-text-properties beg1 end1 '(face org-block)))
4316 ((not (member (char-after beg) '(?\ ?\t)))
4317 ;; just any other in-buffer setting, but not indented
4318 (add-text-properties
4319 beg (match-end 0)
4320 '(font-lock-fontified t face org-meta-line))
4322 ((or (member dc1 '("caption:" "label:" "orgtbl:" "tblfm:" "tblname:"))
4323 (and (match-end 4) (equal dc3 "attr")))
4324 (add-text-properties
4325 beg (match-end 0)
4326 '(font-lock-fontified t face org-meta-line))
4328 (t nil))))))
4330 (defun org-activate-angle-links (limit)
4331 "Run through the buffer and add overlays to links."
4332 (if (re-search-forward org-angle-link-re limit t)
4333 (progn
4334 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4335 (add-text-properties (match-beginning 0) (match-end 0)
4336 (list 'mouse-face 'highlight
4337 'keymap org-mouse-map))
4338 (org-rear-nonsticky-at (match-end 0))
4339 t)))
4341 (defun org-activate-footnote-links (limit)
4342 "Run through the buffer and add overlays to links."
4343 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4344 limit t)
4345 (progn
4346 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4347 (add-text-properties (match-beginning 2) (match-end 2)
4348 (list 'mouse-face 'highlight
4349 'keymap org-mouse-map
4350 'help-echo
4351 (if (= (point-at-bol) (match-beginning 2))
4352 "Footnote definition"
4353 "Footnote reference")
4355 (org-rear-nonsticky-at (match-end 2))
4356 t)))
4358 (defun org-activate-bracket-links (limit)
4359 "Run through the buffer and add overlays to bracketed links."
4360 (if (re-search-forward org-bracket-link-regexp limit t)
4361 (let* ((help (concat "LINK: "
4362 (org-match-string-no-properties 1)))
4363 ;; FIXME: above we should remove the escapes.
4364 ;; but that requires another match, protecting match data,
4365 ;; a lot of overhead for font-lock.
4366 (ip (org-maybe-intangible
4367 (list 'invisible 'org-link
4368 'keymap org-mouse-map 'mouse-face 'highlight
4369 'font-lock-multiline t 'help-echo help)))
4370 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4371 'font-lock-multiline t 'help-echo help)))
4372 ;; We need to remove the invisible property here. Table narrowing
4373 ;; may have made some of this invisible.
4374 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4375 (remove-text-properties (match-beginning 0) (match-end 0)
4376 '(invisible nil))
4377 (if (match-end 3)
4378 (progn
4379 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4380 (org-rear-nonsticky-at (match-beginning 3))
4381 (add-text-properties (match-beginning 3) (match-end 3) vp)
4382 (org-rear-nonsticky-at (match-end 3))
4383 (add-text-properties (match-end 3) (match-end 0) ip)
4384 (org-rear-nonsticky-at (match-end 0)))
4385 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4386 (org-rear-nonsticky-at (match-beginning 1))
4387 (add-text-properties (match-beginning 1) (match-end 1) vp)
4388 (org-rear-nonsticky-at (match-end 1))
4389 (add-text-properties (match-end 1) (match-end 0) ip)
4390 (org-rear-nonsticky-at (match-end 0)))
4391 t)))
4393 (defun org-activate-dates (limit)
4394 "Run through the buffer and add overlays to dates."
4395 (if (re-search-forward org-tsr-regexp-both limit t)
4396 (progn
4397 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4398 (add-text-properties (match-beginning 0) (match-end 0)
4399 (list 'mouse-face 'highlight
4400 'keymap org-mouse-map))
4401 (org-rear-nonsticky-at (match-end 0))
4402 (when org-display-custom-times
4403 (if (match-end 3)
4404 (org-display-custom-time (match-beginning 3) (match-end 3)))
4405 (org-display-custom-time (match-beginning 1) (match-end 1)))
4406 t)))
4408 (defvar org-target-link-regexp nil
4409 "Regular expression matching radio targets in plain text.")
4410 (make-variable-buffer-local 'org-target-link-regexp)
4411 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4412 "Regular expression matching a link target.")
4413 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4414 "Regular expression matching a radio target.")
4415 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4416 "Regular expression matching any target.")
4418 (defun org-activate-target-links (limit)
4419 "Run through the buffer and add overlays to target matches."
4420 (when org-target-link-regexp
4421 (let ((case-fold-search t))
4422 (if (re-search-forward org-target-link-regexp limit t)
4423 (progn
4424 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4425 (add-text-properties (match-beginning 0) (match-end 0)
4426 (list 'mouse-face 'highlight
4427 'keymap org-mouse-map
4428 'help-echo "Radio target link"
4429 'org-linked-text t))
4430 (org-rear-nonsticky-at (match-end 0))
4431 t)))))
4433 (defun org-update-radio-target-regexp ()
4434 "Find all radio targets in this file and update the regular expression."
4435 (interactive)
4436 (when (memq 'radio org-activate-links)
4437 (setq org-target-link-regexp
4438 (org-make-target-link-regexp (org-all-targets 'radio)))
4439 (org-restart-font-lock)))
4441 (defun org-hide-wide-columns (limit)
4442 (let (s e)
4443 (setq s (text-property-any (point) (or limit (point-max))
4444 'org-cwidth t))
4445 (when s
4446 (setq e (next-single-property-change s 'org-cwidth))
4447 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4448 (goto-char e)
4449 t)))
4451 (defvar org-latex-and-specials-regexp nil
4452 "Regular expression for highlighting export special stuff.")
4453 (defvar org-match-substring-regexp)
4454 (defvar org-match-substring-with-braces-regexp)
4456 ;; This should be with the exporter code, but we also use if for font-locking
4457 (defconst org-export-html-special-string-regexps
4458 '(("\\\\-" . "&shy;")
4459 ("---\\([^-]\\)" . "&mdash;\\1")
4460 ("--\\([^-]\\)" . "&ndash;\\1")
4461 ("\\.\\.\\." . "&hellip;"))
4462 "Regular expressions for special string conversion.")
4465 (defun org-compute-latex-and-specials-regexp ()
4466 "Compute regular expression for stuff treated specially by exporters."
4467 (if (not org-highlight-latex-fragments-and-specials)
4468 (org-set-local 'org-latex-and-specials-regexp nil)
4469 (require 'org-exp)
4470 (let*
4471 ((matchers (plist-get org-format-latex-options :matchers))
4472 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4473 org-latex-regexps)))
4474 (options (org-combine-plists (org-default-export-plist)
4475 (org-infile-export-plist)))
4476 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4477 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4478 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4479 (org-export-html-expand (plist-get options :expand-quoted-html))
4480 (org-export-with-special-strings (plist-get options :special-strings))
4481 (re-sub
4482 (cond
4483 ((equal org-export-with-sub-superscripts '{})
4484 (list org-match-substring-with-braces-regexp))
4485 (org-export-with-sub-superscripts
4486 (list org-match-substring-regexp))
4487 (t nil)))
4488 (re-latex
4489 (if org-export-with-LaTeX-fragments
4490 (mapcar (lambda (x) (nth 1 x)) latexs)))
4491 (re-macros
4492 (if org-export-with-TeX-macros
4493 (list (concat "\\\\"
4494 (regexp-opt
4495 (append (mapcar 'car org-html-entities)
4496 (if (boundp 'org-latex-entities)
4497 (mapcar (lambda (x)
4498 (or (car-safe x) x))
4499 org-latex-entities)
4500 nil))
4501 'words))) ; FIXME
4503 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4504 (re-special (if org-export-with-special-strings
4505 (mapcar (lambda (x) (car x))
4506 org-export-html-special-string-regexps)))
4507 (re-rest
4508 (delq nil
4509 (list
4510 (if org-export-html-expand "@<[^>\n]+>")
4511 ))))
4512 (org-set-local
4513 'org-latex-and-specials-regexp
4514 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4515 re-rest) "\\|")))))
4517 (defun org-do-latex-and-special-faces (limit)
4518 "Run through the buffer and add overlays to links."
4519 (when org-latex-and-specials-regexp
4520 (let (rtn d)
4521 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4522 limit t))
4523 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4524 'face))
4525 '(org-code org-verbatim underline)))
4526 (progn
4527 (setq rtn t
4528 d (cond ((member (char-after (1+ (match-beginning 0)))
4529 '(?_ ?^)) 1)
4530 (t 0)))
4531 (font-lock-prepend-text-property
4532 (+ d (match-beginning 0)) (match-end 0)
4533 'face 'org-latex-and-export-specials)
4534 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4535 '(font-lock-multiline t)))))
4536 rtn)))
4538 (defun org-restart-font-lock ()
4539 "Restart font-lock-mode, to force refontification."
4540 (when (and (boundp 'font-lock-mode) font-lock-mode)
4541 (font-lock-mode -1)
4542 (font-lock-mode 1)))
4544 (defun org-all-targets (&optional radio)
4545 "Return a list of all targets in this file.
4546 With optional argument RADIO, only find radio targets."
4547 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4548 rtn)
4549 (save-excursion
4550 (goto-char (point-min))
4551 (while (re-search-forward re nil t)
4552 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4553 rtn)))
4555 (defun org-make-target-link-regexp (targets)
4556 "Make regular expression matching all strings in TARGETS.
4557 The regular expression finds the targets also if there is a line break
4558 between words."
4559 (and targets
4560 (concat
4561 "\\<\\("
4562 (mapconcat
4563 (lambda (x)
4564 (while (string-match " +" x)
4565 (setq x (replace-match "\\s-+" t t x)))
4567 targets
4568 "\\|")
4569 "\\)\\>")))
4571 (defun org-activate-tags (limit)
4572 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4573 (progn
4574 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4575 (add-text-properties (match-beginning 1) (match-end 1)
4576 (list 'mouse-face 'highlight
4577 'keymap org-mouse-map))
4578 (org-rear-nonsticky-at (match-end 1))
4579 t)))
4581 (defun org-outline-level ()
4582 (save-excursion
4583 (looking-at outline-regexp)
4584 (if (match-beginning 1)
4585 (+ (org-get-string-indentation (match-string 1)) 1000)
4586 (1- (- (match-end 0) (match-beginning 0))))))
4588 (defvar org-font-lock-keywords nil)
4590 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4591 "Regular expression matching a property line.")
4593 (defvar org-font-lock-hook nil
4594 "Functions to be called for special font lock stuff.")
4596 (defun org-font-lock-hook (limit)
4597 (run-hook-with-args 'org-font-lock-hook limit))
4599 (defun org-set-font-lock-defaults ()
4600 (let* ((em org-fontify-emphasized-text)
4601 (lk org-activate-links)
4602 (org-font-lock-extra-keywords
4603 (list
4604 ;; Call the hook
4605 '(org-font-lock-hook)
4606 ;; Headlines
4607 `(,(if org-fontify-whole-heading-line
4608 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
4609 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
4610 (1 (org-get-level-face 1))
4611 (2 (org-get-level-face 2))
4612 (3 (org-get-level-face 3)))
4613 ;; Table lines
4614 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4615 (1 'org-table t))
4616 ;; Table internals
4617 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4618 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4619 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4620 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
4621 ;; Drawers
4622 (list org-drawer-regexp '(0 'org-special-keyword t))
4623 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4624 ;; Properties
4625 (list org-property-re
4626 '(1 'org-special-keyword t)
4627 '(3 'org-property-value t))
4628 ;; Links
4629 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4630 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4631 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4632 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4633 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4634 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4635 (if (memq 'footnote lk) '(org-activate-footnote-links
4636 (2 'org-footnote t)))
4637 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4638 '(org-hide-wide-columns (0 nil append))
4639 ;; TODO lines
4640 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4641 '(1 (org-get-todo-face 1) t))
4642 ;; DONE
4643 (if org-fontify-done-headline
4644 (list (concat "^[*]+ +\\<\\("
4645 (mapconcat 'regexp-quote org-done-keywords "\\|")
4646 "\\)\\(.*\\)")
4647 '(2 'org-headline-done t))
4648 nil)
4649 ;; Priorities
4650 '(org-font-lock-add-priority-faces)
4651 ;; Tags
4652 '(org-font-lock-add-tag-faces)
4653 ;; Special keywords
4654 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4655 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4656 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4657 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4658 ;; Emphasis
4659 (if em
4660 (if (featurep 'xemacs)
4661 '(org-do-emphasis-faces (0 nil append))
4662 '(org-do-emphasis-faces)))
4663 ;; Checkboxes
4664 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4665 2 'org-checkbox prepend)
4666 (if org-provide-checkbox-statistics
4667 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4668 (0 (org-get-checkbox-statistics-face) t)))
4669 ;; Description list items
4670 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4671 2 'bold prepend)
4672 ;; ARCHIVEd headings
4673 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4674 '(1 'org-archived prepend))
4675 ;; Specials
4676 '(org-do-latex-and-special-faces)
4677 ;; Code
4678 '(org-activate-code (1 'org-code t))
4679 ;; COMMENT
4680 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4681 "\\|" org-quote-string "\\)\\>")
4682 '(1 'org-special-keyword t))
4683 '("^#.*" (0 'font-lock-comment-face t))
4684 ;; Blocks and meta lines
4685 '(org-fontify-meta-lines-and-blocks)
4687 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4688 ;; Now set the full font-lock-keywords
4689 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4690 (org-set-local 'font-lock-defaults
4691 '(org-font-lock-keywords t nil nil backward-paragraph))
4692 (kill-local-variable 'font-lock-keywords) nil))
4694 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
4695 "Fontify string S like in Org-mode"
4696 (with-temp-buffer
4697 (insert s)
4698 (let ((org-odd-levels-only odd-levels))
4699 (org-mode)
4700 (font-lock-fontify-buffer)
4701 (buffer-string))))
4703 (defvar org-m nil)
4704 (defvar org-l nil)
4705 (defvar org-f nil)
4706 (defun org-get-level-face (n)
4707 "Get the right face for match N in font-lock matching of headlines."
4708 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4709 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4710 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4711 (cond
4712 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4713 ((eq n 2) org-f)
4714 (t (if org-level-color-stars-only nil org-f))))
4716 (defun org-get-todo-face (kwd)
4717 "Get the right face for a TODO keyword KWD.
4718 If KWD is a number, get the corresponding match group."
4719 (if (numberp kwd) (setq kwd (match-string kwd)))
4720 (or (cdr (assoc kwd org-todo-keyword-faces))
4721 (and (member kwd org-done-keywords) 'org-done)
4722 'org-todo))
4724 (defun org-font-lock-add-tag-faces (limit)
4725 "Add the special tag faces."
4726 (when (and org-tag-faces org-tags-special-faces-re)
4727 (while (re-search-forward org-tags-special-faces-re limit t)
4728 (add-text-properties (match-beginning 1) (match-end 1)
4729 (list 'face (org-get-tag-face 1)
4730 'font-lock-fontified t))
4731 (backward-char 1))))
4733 (defun org-font-lock-add-priority-faces (limit)
4734 "Add the special priority faces."
4735 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4736 (add-text-properties
4737 (match-beginning 0) (match-end 0)
4738 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4739 org-priority-faces))
4740 'org-special-keyword)
4741 'font-lock-fontified t))))
4743 (defun org-get-tag-face (kwd)
4744 "Get the right face for a TODO keyword KWD.
4745 If KWD is a number, get the corresponding match group."
4746 (if (numberp kwd) (setq kwd (match-string kwd)))
4747 (or (cdr (assoc kwd org-tag-faces))
4748 'org-tag))
4750 (defun org-unfontify-region (beg end &optional maybe_loudly)
4751 "Remove fontification and activation overlays from links."
4752 (font-lock-default-unfontify-region beg end)
4753 (let* ((buffer-undo-list t)
4754 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4755 (inhibit-modification-hooks t)
4756 deactivate-mark buffer-file-name buffer-file-truename)
4757 (remove-text-properties beg end
4758 '(mouse-face t keymap t org-linked-text t
4759 invisible t intangible t
4760 line-prefix t wrap-prefix t
4761 org-no-flyspell t))))
4763 ;;;; Visibility cycling, including org-goto and indirect buffer
4765 ;;; Cycling
4767 (defvar org-cycle-global-status nil)
4768 (make-variable-buffer-local 'org-cycle-global-status)
4769 (defvar org-cycle-subtree-status nil)
4770 (make-variable-buffer-local 'org-cycle-subtree-status)
4772 ;;;###autoload
4774 (defvar org-inlinetask-min-level)
4776 (defun org-cycle (&optional arg)
4777 "TAB-action and visibility cycling for Org-mode.
4779 This is the command invoked in Org-moe by the TAB key. It's main purpose
4780 is outine visibility cycling, but it also invokes other actions
4781 in special contexts.
4783 - When this function is called with a prefix argument, rotate the entire
4784 buffer through 3 states (global cycling)
4785 1. OVERVIEW: Show only top-level headlines.
4786 2. CONTENTS: Show all headlines of all levels, but no body text.
4787 3. SHOW ALL: Show everything.
4788 When called with two `C-u C-u' prefixes, switch to the startup visibility,
4789 determined by the variable `org-startup-folded', and by any VISIBILITY
4790 properties in the buffer.
4791 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
4792 including any drawers.
4794 - When inside a table, re-align the table and move to the next field.
4796 - When point is at the beginning of a headline, rotate the subtree started
4797 by this line through 3 different states (local cycling)
4798 1. FOLDED: Only the main headline is shown.
4799 2. CHILDREN: The main headline and the direct children are shown.
4800 From this state, you can move to one of the children
4801 and zoom in further.
4802 3. SUBTREE: Show the entire subtree, including body text.
4803 If there is no subtree, switch directly from CHILDREN to FOLDED.
4805 - When there is a numeric prefix, go up to a heading with level ARG, do
4806 a `show-subtree' and return to the previous cursor position. If ARG
4807 is negative, go up that many levels.
4809 - When point is not at the beginning of a headline, execute the global
4810 binding for TAB, which is re-indenting the line. See the option
4811 `org-cycle-emulate-tab' for details.
4813 - Special case: if point is at the beginning of the buffer and there is
4814 no headline in line 1, this function will act as if called with prefix arg.
4815 But only if also the variable `org-cycle-global-at-bob' is t."
4816 (interactive "P")
4817 (org-load-modules-maybe)
4818 (unless (run-hook-with-args-until-success 'org-tab-first-hook)
4819 (let* ((limit-level
4820 (or org-cycle-max-level
4821 (and (boundp 'org-inlinetask-min-level)
4822 org-inlinetask-min-level
4823 (1- org-inlinetask-min-level))))
4824 (nstars (and limit-level
4825 (if org-odd-levels-only
4826 (and limit-level (1- (* limit-level 2)))
4827 limit-level)))
4828 (outline-regexp
4829 (cond
4830 ((not (org-mode-p)) outline-regexp)
4831 ((or (eq org-cycle-include-plain-lists 'integrate)
4832 (and org-cycle-include-plain-lists (org-at-item-p)))
4833 (concat "\\(?:\\*"
4834 (if nstars (format "\\{1,%d\\}" nstars) "+")
4835 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
4836 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
4837 (bob-special (and org-cycle-global-at-bob (bobp)
4838 (not (looking-at outline-regexp))))
4839 (org-cycle-hook
4840 (if bob-special
4841 (delq 'org-optimize-window-after-visibility-change
4842 (copy-sequence org-cycle-hook))
4843 org-cycle-hook))
4844 (pos (point)))
4846 (if (or bob-special (equal arg '(4)))
4847 ;; special case: use global cycling
4848 (setq arg t))
4850 (cond
4852 ((equal arg '(16))
4853 (org-set-startup-visibility)
4854 (message "Startup visibility, plus VISIBILITY properties"))
4856 ((equal arg '(64))
4857 (show-all)
4858 (message "Entire buffer visible, including drawers"))
4860 ((org-at-table-p 'any)
4861 ;; Enter the table or move to the next field in the table
4862 (or (org-table-recognize-table.el)
4863 (progn
4864 (if arg (org-table-edit-field t)
4865 (org-table-justify-field-maybe)
4866 (call-interactively 'org-table-next-field)))))
4868 ((run-hook-with-args-until-success
4869 'org-tab-after-check-for-table-hook))
4871 ((eq arg t) ;; Global cycling
4872 (org-cycle-internal-global))
4874 ((and org-drawers org-drawer-regexp
4875 (save-excursion
4876 (beginning-of-line 1)
4877 (looking-at org-drawer-regexp)))
4878 ;; Toggle block visibility
4879 (org-flag-drawer
4880 (not (get-char-property (match-end 0) 'invisible))))
4882 ((integerp arg)
4883 ;; Show-subtree, ARG levels up from here.
4884 (save-excursion
4885 (org-back-to-heading)
4886 (outline-up-heading (if (< arg 0) (- arg)
4887 (- (funcall outline-level) arg)))
4888 (org-show-subtree)))
4890 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4891 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4893 (org-cycle-internal-local))
4895 ;; TAB emulation and template completion
4896 (buffer-read-only (org-back-to-heading))
4898 ((run-hook-with-args-until-success
4899 'org-tab-after-check-for-cycling-hook))
4901 ((org-try-structure-completion))
4903 ((org-try-cdlatex-tab))
4905 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4906 (or (not (bolp))
4907 (not (looking-at outline-regexp))))
4908 (call-interactively (global-key-binding "\t")))
4910 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4911 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4912 (or (and (eq org-cycle-emulate-tab 'white)
4913 (= (match-end 0) (point-at-eol)))
4914 (and (eq org-cycle-emulate-tab 'whitestart)
4915 (>= (match-end 0) pos))))
4917 (eq org-cycle-emulate-tab t))
4918 (call-interactively (global-key-binding "\t")))
4920 (t (save-excursion
4921 (org-back-to-heading)
4922 (org-cycle)))))))
4924 (defun org-cycle-internal-global ()
4925 "Do the global cycling action."
4926 (cond
4927 ((and (eq last-command this-command)
4928 (eq org-cycle-global-status 'overview))
4929 ;; We just created the overview - now do table of contents
4930 ;; This can be slow in very large buffers, so indicate action
4931 (run-hook-with-args 'org-pre-cycle-hook 'contents)
4932 (message "CONTENTS...")
4933 (org-content)
4934 (message "CONTENTS...done")
4935 (setq org-cycle-global-status 'contents)
4936 (run-hook-with-args 'org-cycle-hook 'contents))
4938 ((and (eq last-command this-command)
4939 (eq org-cycle-global-status 'contents))
4940 ;; We just showed the table of contents - now show everything
4941 (run-hook-with-args 'org-pre-cycle-hook 'all)
4942 (show-all)
4943 (message "SHOW ALL")
4944 (setq org-cycle-global-status 'all)
4945 (run-hook-with-args 'org-cycle-hook 'all))
4948 ;; Default action: go to overview
4949 (run-hook-with-args 'org-pre-cycle-hook 'overview)
4950 (org-overview)
4951 (message "OVERVIEW")
4952 (setq org-cycle-global-status 'overview)
4953 (run-hook-with-args 'org-cycle-hook 'overview))))
4955 (defun org-cycle-internal-local ()
4956 "Do the local cycling action."
4957 (org-back-to-heading)
4958 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
4959 ;; First, some boundaries
4960 (save-excursion
4961 (org-back-to-heading)
4962 (setq level (funcall outline-level))
4963 (save-excursion
4964 (beginning-of-line 2)
4965 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
4966 ; XEmacs does not have `next-single-char-property-change'
4967 ; I'm not sure about Emacs 21.
4968 (while (and (not (eobp)) ;; this is like `next-line'
4969 (get-char-property (1- (point)) 'invisible))
4970 (beginning-of-line 2))
4971 (while (and (not (eobp)) ;; this is like `next-line'
4972 (get-char-property (1- (point)) 'invisible))
4973 (goto-char (next-single-char-property-change (point) 'invisible))
4974 ;;;??? (or (bolp) (beginning-of-line 2))))
4975 (and (eolp) (beginning-of-line 2))))
4976 (setq eol (point)))
4977 (outline-end-of-heading) (setq eoh (point))
4978 (save-excursion
4979 (outline-next-heading)
4980 (setq has-children (and (org-at-heading-p t)
4981 (> (funcall outline-level) level))))
4982 (org-end-of-subtree t)
4983 (unless (eobp)
4984 (skip-chars-forward " \t\n")
4985 (beginning-of-line 1) ; in case this is an item
4987 (setq eos (1- (point))))
4988 ;; Find out what to do next and set `this-command'
4989 (cond
4990 ((= eos eoh)
4991 ;; Nothing is hidden behind this heading
4992 (run-hook-with-args 'org-pre-cycle-hook 'empty)
4993 (message "EMPTY ENTRY")
4994 (setq org-cycle-subtree-status nil)
4995 (save-excursion
4996 (goto-char eos)
4997 (outline-next-heading)
4998 (if (org-invisible-p) (org-flag-heading nil))))
4999 ((and (or (>= eol eos)
5000 (not (string-match "\\S-" (buffer-substring eol eos))))
5001 (or has-children
5002 (not (setq children-skipped
5003 org-cycle-skip-children-state-if-no-children))))
5004 ;; Entire subtree is hidden in one line: children view
5005 (run-hook-with-args 'org-pre-cycle-hook 'children)
5006 (org-show-entry)
5007 (show-children)
5008 (message "CHILDREN")
5009 (save-excursion
5010 (goto-char eos)
5011 (outline-next-heading)
5012 (if (org-invisible-p) (org-flag-heading nil)))
5013 (setq org-cycle-subtree-status 'children)
5014 (run-hook-with-args 'org-cycle-hook 'children))
5015 ((or children-skipped
5016 (and (eq last-command this-command)
5017 (eq org-cycle-subtree-status 'children)))
5018 ;; We just showed the children, or no children are there,
5019 ;; now show everything.
5020 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5021 (org-show-subtree)
5022 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5023 (setq org-cycle-subtree-status 'subtree)
5024 (run-hook-with-args 'org-cycle-hook 'subtree))
5026 ;; Default action: hide the subtree.
5027 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5028 (hide-subtree)
5029 (message "FOLDED")
5030 (setq org-cycle-subtree-status 'folded)
5031 (run-hook-with-args 'org-cycle-hook 'folded)))))
5033 ;;;###autoload
5034 (defun org-global-cycle (&optional arg)
5035 "Cycle the global visibility. For details see `org-cycle'.
5036 With C-u prefix arg, switch to startup visibility.
5037 With a numeric prefix, show all headlines up to that level."
5038 (interactive "P")
5039 (let ((org-cycle-include-plain-lists
5040 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5041 (cond
5042 ((integerp arg)
5043 (show-all)
5044 (hide-sublevels arg)
5045 (setq org-cycle-global-status 'contents))
5046 ((equal arg '(4))
5047 (org-set-startup-visibility)
5048 (message "Startup visibility, plus VISIBILITY properties."))
5050 (org-cycle '(4))))))
5052 (defun org-set-startup-visibility ()
5053 "Set the visibility required by startup options and properties."
5054 (cond
5055 ((eq org-startup-folded t)
5056 (org-cycle '(4)))
5057 ((eq org-startup-folded 'content)
5058 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5059 (org-cycle '(4)) (org-cycle '(4)))))
5060 (if org-hide-block-startup (org-hide-block-all))
5061 (org-set-visibility-according-to-property 'no-cleanup)
5062 (org-cycle-hide-archived-subtrees 'all)
5063 (org-cycle-hide-drawers 'all)
5064 (org-cycle-show-empty-lines 'all))
5066 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5067 "Switch subtree visibilities according to :VISIBILITY: property."
5068 (interactive)
5069 (let (org-show-entry-below state)
5070 (save-excursion
5071 (goto-char (point-min))
5072 (while (re-search-forward
5073 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5074 nil t)
5075 (setq state (match-string 1))
5076 (save-excursion
5077 (org-back-to-heading t)
5078 (hide-subtree)
5079 (org-reveal)
5080 (cond
5081 ((equal state '("fold" "folded"))
5082 (hide-subtree))
5083 ((equal state "children")
5084 (org-show-hidden-entry)
5085 (show-children))
5086 ((equal state "content")
5087 (save-excursion
5088 (save-restriction
5089 (org-narrow-to-subtree)
5090 (org-content))))
5091 ((member state '("all" "showall"))
5092 (show-subtree)))))
5093 (unless no-cleanup
5094 (org-cycle-hide-archived-subtrees 'all)
5095 (org-cycle-hide-drawers 'all)
5096 (org-cycle-show-empty-lines 'all)))))
5098 (defun org-overview ()
5099 "Switch to overview mode, showing only top-level headlines.
5100 Really, this shows all headlines with level equal or greater than the level
5101 of the first headline in the buffer. This is important, because if the
5102 first headline is not level one, then (hide-sublevels 1) gives confusing
5103 results."
5104 (interactive)
5105 (let ((level (save-excursion
5106 (goto-char (point-min))
5107 (if (re-search-forward (concat "^" outline-regexp) nil t)
5108 (progn
5109 (goto-char (match-beginning 0))
5110 (funcall outline-level))))))
5111 (and level (hide-sublevels level))))
5113 (defun org-content (&optional arg)
5114 "Show all headlines in the buffer, like a table of contents.
5115 With numerical argument N, show content up to level N."
5116 (interactive "P")
5117 (save-excursion
5118 ;; Visit all headings and show their offspring
5119 (and (integerp arg) (org-overview))
5120 (goto-char (point-max))
5121 (catch 'exit
5122 (while (and (progn (condition-case nil
5123 (outline-previous-visible-heading 1)
5124 (error (goto-char (point-min))))
5126 (looking-at outline-regexp))
5127 (if (integerp arg)
5128 (show-children (1- arg))
5129 (show-branches))
5130 (if (bobp) (throw 'exit nil))))))
5133 (defun org-optimize-window-after-visibility-change (state)
5134 "Adjust the window after a change in outline visibility.
5135 This function is the default value of the hook `org-cycle-hook'."
5136 (when (get-buffer-window (current-buffer))
5137 (cond
5138 ((eq state 'content) nil)
5139 ((eq state 'all) nil)
5140 ((eq state 'folded) nil)
5141 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5142 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5144 ;; FIXME: no longer in use
5145 (defun org-compact-display-after-subtree-move ()
5146 "Show a compacter version of the tree of the entry's parent."
5147 (save-excursion
5148 (if (org-up-heading-safe)
5149 (progn
5150 (hide-subtree)
5151 (show-entry)
5152 (show-children)
5153 (org-cycle-show-empty-lines 'children)
5154 (org-cycle-hide-drawers 'children))
5155 (org-overview))))
5157 (defun org-remove-empty-overlays-at (pos)
5158 "Remove outline overlays that do not contain non-white stuff."
5159 (mapc
5160 (lambda (o)
5161 (and (eq 'outline (org-overlay-get o 'invisible))
5162 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5163 (org-overlay-end o))))
5164 (org-delete-overlay o)))
5165 (org-overlays-at pos)))
5167 (defun org-clean-visibility-after-subtree-move ()
5168 "Fix visibility issues after moving a subtree."
5169 ;; First, find a reasonable region to look at:
5170 ;; Start two siblings above, end three below
5171 (let* ((beg (save-excursion
5172 (and (outline-get-last-sibling)
5173 (outline-get-last-sibling))
5174 (point)))
5175 (end (save-excursion
5176 (and (outline-get-next-sibling)
5177 (outline-get-next-sibling)
5178 (outline-get-next-sibling))
5179 (if (org-at-heading-p)
5180 (point-at-eol)
5181 (point))))
5182 (level (looking-at "\\*+"))
5183 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5184 (save-excursion
5185 (save-restriction
5186 (narrow-to-region beg end)
5187 (when re
5188 ;; Properly fold already folded siblings
5189 (goto-char (point-min))
5190 (while (re-search-forward re nil t)
5191 (if (save-excursion (goto-char (point-at-eol)) (org-invisible-p))
5192 (hide-entry))))
5193 (org-cycle-show-empty-lines 'overview)
5194 (org-cycle-hide-drawers 'overview)))))
5196 (defun org-cycle-show-empty-lines (state)
5197 "Show empty lines above all visible headlines.
5198 The region to be covered depends on STATE when called through
5199 `org-cycle-hook'. Lisp program can use t for STATE to get the
5200 entire buffer covered. Note that an empty line is only shown if there
5201 are at least `org-cycle-separator-lines' empty lines before the headline."
5202 (when (> org-cycle-separator-lines 0)
5203 (save-excursion
5204 (let* ((n org-cycle-separator-lines)
5205 (re (cond
5206 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5207 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5208 (t (let ((ns (number-to-string (- n 2))))
5209 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5210 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5211 beg end)
5212 (cond
5213 ((memq state '(overview contents t))
5214 (setq beg (point-min) end (point-max)))
5215 ((memq state '(children folded))
5216 (setq beg (point) end (progn (org-end-of-subtree t t)
5217 (beginning-of-line 2)
5218 (point)))))
5219 (when beg
5220 (goto-char beg)
5221 (while (re-search-forward re end t)
5222 (if (not (get-char-property (match-end 1) 'invisible))
5223 (outline-flag-region
5224 (match-beginning 1) (match-end 1) nil)))))))
5225 ;; Never hide empty lines at the end of the file.
5226 (save-excursion
5227 (goto-char (point-max))
5228 (outline-previous-heading)
5229 (outline-end-of-heading)
5230 (if (and (looking-at "[ \t\n]+")
5231 (= (match-end 0) (point-max)))
5232 (outline-flag-region (point) (match-end 0) nil))))
5234 (defun org-show-empty-lines-in-parent ()
5235 "Move to the parent and re-show empty lines before visible headlines."
5236 (save-excursion
5237 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5238 (org-cycle-show-empty-lines context))))
5240 (defun org-cycle-hide-drawers (state)
5241 "Re-hide all drawers after a visibility state change."
5242 (when (and (org-mode-p)
5243 (not (memq state '(overview folded contents))))
5244 (save-excursion
5245 (let* ((globalp (memq state '(contents all)))
5246 (beg (if globalp (point-min) (point)))
5247 (end (if globalp (point-max)
5248 (if (eq state 'children)
5249 (save-excursion (outline-next-heading) (point))
5250 (org-end-of-subtree t)))))
5251 (goto-char beg)
5252 (while (re-search-forward org-drawer-regexp end t)
5253 (org-flag-drawer t))))))
5255 (defun org-flag-drawer (flag)
5256 (save-excursion
5257 (beginning-of-line 1)
5258 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5259 (let ((b (match-end 0))
5260 (outline-regexp org-outline-regexp))
5261 (if (re-search-forward
5262 "^[ \t]*:END:"
5263 (save-excursion (outline-next-heading) (point)) t)
5264 (outline-flag-region b (point-at-eol) flag)
5265 (error ":END: line missing"))))))
5267 (defun org-subtree-end-visible-p ()
5268 "Is the end of the current subtree visible?"
5269 (pos-visible-in-window-p
5270 (save-excursion (org-end-of-subtree t) (point))))
5272 (defun org-first-headline-recenter (&optional N)
5273 "Move cursor to the first headline and recenter the headline.
5274 Optional argument N means, put the headline into the Nth line of the window."
5275 (goto-char (point-min))
5276 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5277 (beginning-of-line)
5278 (recenter (prefix-numeric-value N))))
5280 ;;; Folding of blocks
5282 (defconst org-block-regexp
5284 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5285 "Regular expression for hiding blocks.")
5287 (defvar org-hide-block-overlays nil
5288 "Overays hiding blocks.")
5289 (make-variable-buffer-local 'org-hide-block-overlays)
5291 (defun org-block-map (function &optional start end)
5292 "Call func at the head of all source blocks in the current
5293 buffer. Optional arguments START and END can be used to limit
5294 the range."
5295 (let ((start (or start (point-min)))
5296 (end (or end (point-max))))
5297 (save-excursion
5298 (goto-char start)
5299 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5300 (save-excursion
5301 (save-match-data
5302 (goto-char (match-beginning 0))
5303 (funcall function)))))))
5305 (defun org-hide-block-toggle-all ()
5306 "Toggle the visibility of all blocks in the current buffer."
5307 (org-block-map #'org-hide-block-toggle))
5309 (defun org-hide-block-all ()
5310 "Fold all blocks in the current buffer."
5311 (interactive)
5312 (org-show-block-all)
5313 (org-block-map #'org-hide-block-toggle-maybe))
5315 (defun org-show-block-all ()
5316 "Unfold all blocks in the current buffer."
5317 (mapc 'org-delete-overlay org-hide-block-overlays)
5318 (setq org-hide-block-overlays nil))
5320 (defun org-hide-block-toggle-maybe ()
5321 "Toggle visibility of block at point."
5322 (interactive)
5323 (let ((case-fold-search t))
5324 (if (save-excursion
5325 (beginning-of-line 1)
5326 (looking-at org-block-regexp))
5327 (progn (org-hide-block-toggle)
5328 t) ;; to signal that we took action
5329 nil))) ;; to signal that we did not
5331 (defun org-hide-block-toggle (&optional force)
5332 "Toggle the visibility of the current block."
5333 (interactive)
5334 (save-excursion
5335 (beginning-of-line)
5336 (if (re-search-forward org-block-regexp nil t)
5337 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5338 (end (match-end 0))
5339 ov) ;; end of entire body
5340 (if (memq t (mapcar (lambda (overlay)
5341 (eq (org-overlay-get overlay 'invisible)
5342 'org-hide-block))
5343 (org-overlays-at start)))
5344 (if (or (not force) (eq force 'off))
5345 (mapc (lambda (ov)
5346 (when (member ov org-hide-block-overlays)
5347 (setq org-hide-block-overlays
5348 (delq ov org-hide-block-overlays)))
5349 (when (eq (org-overlay-get ov 'invisible)
5350 'org-hide-block)
5351 (org-delete-overlay ov)))
5352 (org-overlays-at start)))
5353 (setq ov (org-make-overlay start end))
5354 (org-overlay-put ov 'invisible 'org-hide-block)
5355 (push ov org-hide-block-overlays)))
5356 (error "Not looking at a source block"))))
5358 ;; org-tab-after-check-for-cycling-hook
5359 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5360 ;; Remove overlays when changing major mode
5361 (add-hook 'org-mode-hook
5362 (lambda () (org-add-hook 'change-major-mode-hook
5363 'org-show-block-all 'append 'local)))
5365 ;;; Org-goto
5367 (defvar org-goto-window-configuration nil)
5368 (defvar org-goto-marker nil)
5369 (defvar org-goto-map
5370 (let ((map (make-sparse-keymap)))
5371 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5372 (while (setq cmd (pop cmds))
5373 (substitute-key-definition cmd cmd map global-map)))
5374 (suppress-keymap map)
5375 (org-defkey map "\C-m" 'org-goto-ret)
5376 (org-defkey map [(return)] 'org-goto-ret)
5377 (org-defkey map [(left)] 'org-goto-left)
5378 (org-defkey map [(right)] 'org-goto-right)
5379 (org-defkey map [(control ?g)] 'org-goto-quit)
5380 (org-defkey map "\C-i" 'org-cycle)
5381 (org-defkey map [(tab)] 'org-cycle)
5382 (org-defkey map [(down)] 'outline-next-visible-heading)
5383 (org-defkey map [(up)] 'outline-previous-visible-heading)
5384 (if org-goto-auto-isearch
5385 (if (fboundp 'define-key-after)
5386 (define-key-after map [t] 'org-goto-local-auto-isearch)
5387 nil)
5388 (org-defkey map "q" 'org-goto-quit)
5389 (org-defkey map "n" 'outline-next-visible-heading)
5390 (org-defkey map "p" 'outline-previous-visible-heading)
5391 (org-defkey map "f" 'outline-forward-same-level)
5392 (org-defkey map "b" 'outline-backward-same-level)
5393 (org-defkey map "u" 'outline-up-heading))
5394 (org-defkey map "/" 'org-occur)
5395 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5396 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5397 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5398 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5399 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5400 map))
5402 (defconst org-goto-help
5403 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5404 RET=jump to location [Q]uit and return to previous location
5405 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5407 (defvar org-goto-start-pos) ; dynamically scoped parameter
5409 ;; FIXME: Docstring doe not mention both interfaces
5410 (defun org-goto (&optional alternative-interface)
5411 "Look up a different location in the current file, keeping current visibility.
5413 When you want look-up or go to a different location in a document, the
5414 fastest way is often to fold the entire buffer and then dive into the tree.
5415 This method has the disadvantage, that the previous location will be folded,
5416 which may not be what you want.
5418 This command works around this by showing a copy of the current buffer
5419 in an indirect buffer, in overview mode. You can dive into the tree in
5420 that copy, use org-occur and incremental search to find a location.
5421 When pressing RET or `Q', the command returns to the original buffer in
5422 which the visibility is still unchanged. After RET is will also jump to
5423 the location selected in the indirect buffer and expose the
5424 the headline hierarchy above."
5425 (interactive "P")
5426 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5427 (org-refile-use-outline-path t)
5428 (org-refile-target-verify-function nil)
5429 (interface
5430 (if (not alternative-interface)
5431 org-goto-interface
5432 (if (eq org-goto-interface 'outline)
5433 'outline-path-completion
5434 'outline)))
5435 (org-goto-start-pos (point))
5436 (selected-point
5437 (if (eq interface 'outline)
5438 (car (org-get-location (current-buffer) org-goto-help))
5439 (nth 3 (org-refile-get-location "Goto: ")))))
5440 (if selected-point
5441 (progn
5442 (org-mark-ring-push org-goto-start-pos)
5443 (goto-char selected-point)
5444 (if (or (org-invisible-p) (org-invisible-p2))
5445 (org-show-context 'org-goto)))
5446 (message "Quit"))))
5448 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5449 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5450 (defvar org-goto-local-auto-isearch-map) ; defined below
5452 (defun org-get-location (buf help)
5453 "Let the user select a location in the Org-mode buffer BUF.
5454 This function uses a recursive edit. It returns the selected position
5455 or nil."
5456 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5457 (isearch-hide-immediately nil)
5458 (isearch-search-fun-function
5459 (lambda () 'org-goto-local-search-headings))
5460 (org-goto-selected-point org-goto-exit-command))
5461 (save-excursion
5462 (save-window-excursion
5463 (delete-other-windows)
5464 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5465 (switch-to-buffer
5466 (condition-case nil
5467 (make-indirect-buffer (current-buffer) "*org-goto*")
5468 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5469 (with-output-to-temp-buffer "*Help*"
5470 (princ help))
5471 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5472 (setq buffer-read-only nil)
5473 (let ((org-startup-truncated t)
5474 (org-startup-folded nil)
5475 (org-startup-align-all-tables nil))
5476 (org-mode)
5477 (org-overview))
5478 (setq buffer-read-only t)
5479 (if (and (boundp 'org-goto-start-pos)
5480 (integer-or-marker-p org-goto-start-pos))
5481 (let ((org-show-hierarchy-above t)
5482 (org-show-siblings t)
5483 (org-show-following-heading t))
5484 (goto-char org-goto-start-pos)
5485 (and (org-invisible-p) (org-show-context)))
5486 (goto-char (point-min)))
5487 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5488 (message "Select location and press RET")
5489 (use-local-map org-goto-map)
5490 (recursive-edit)
5492 (kill-buffer "*org-goto*")
5493 (cons org-goto-selected-point org-goto-exit-command)))
5495 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5496 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5497 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5498 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5500 (defun org-goto-local-search-headings (string bound noerror)
5501 "Search and make sure that any matches are in headlines."
5502 (catch 'return
5503 (while (if isearch-forward
5504 (search-forward string bound noerror)
5505 (search-backward string bound noerror))
5506 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5507 (and (member :headline context)
5508 (not (member :tags context))))
5509 (throw 'return (point))))))
5511 (defun org-goto-local-auto-isearch ()
5512 "Start isearch."
5513 (interactive)
5514 (goto-char (point-min))
5515 (let ((keys (this-command-keys)))
5516 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5517 (isearch-mode t)
5518 (isearch-process-search-char (string-to-char keys)))))
5520 (defun org-goto-ret (&optional arg)
5521 "Finish `org-goto' by going to the new location."
5522 (interactive "P")
5523 (setq org-goto-selected-point (point)
5524 org-goto-exit-command 'return)
5525 (throw 'exit nil))
5527 (defun org-goto-left ()
5528 "Finish `org-goto' by going to the new location."
5529 (interactive)
5530 (if (org-on-heading-p)
5531 (progn
5532 (beginning-of-line 1)
5533 (setq org-goto-selected-point (point)
5534 org-goto-exit-command 'left)
5535 (throw 'exit nil))
5536 (error "Not on a heading")))
5538 (defun org-goto-right ()
5539 "Finish `org-goto' by going to the new location."
5540 (interactive)
5541 (if (org-on-heading-p)
5542 (progn
5543 (setq org-goto-selected-point (point)
5544 org-goto-exit-command 'right)
5545 (throw 'exit nil))
5546 (error "Not on a heading")))
5548 (defun org-goto-quit ()
5549 "Finish `org-goto' without cursor motion."
5550 (interactive)
5551 (setq org-goto-selected-point nil)
5552 (setq org-goto-exit-command 'quit)
5553 (throw 'exit nil))
5555 ;;; Indirect buffer display of subtrees
5557 (defvar org-indirect-dedicated-frame nil
5558 "This is the frame being used for indirect tree display.")
5559 (defvar org-last-indirect-buffer nil)
5561 (defun org-tree-to-indirect-buffer (&optional arg)
5562 "Create indirect buffer and narrow it to current subtree.
5563 With numerical prefix ARG, go up to this level and then take that tree.
5564 If ARG is negative, go up that many levels.
5565 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5566 indirect buffer previously made with this command, to avoid proliferation of
5567 indirect buffers. However, when you call the command with a `C-u' prefix, or
5568 when `org-indirect-buffer-display' is `new-frame', the last buffer
5569 is kept so that you can work with several indirect buffers at the same time.
5570 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5571 requests that a new frame be made for the new buffer, so that the dedicated
5572 frame is not changed."
5573 (interactive "P")
5574 (let ((cbuf (current-buffer))
5575 (cwin (selected-window))
5576 (pos (point))
5577 beg end level heading ibuf)
5578 (save-excursion
5579 (org-back-to-heading t)
5580 (when (numberp arg)
5581 (setq level (org-outline-level))
5582 (if (< arg 0) (setq arg (+ level arg)))
5583 (while (> (setq level (org-outline-level)) arg)
5584 (outline-up-heading 1 t)))
5585 (setq beg (point)
5586 heading (org-get-heading))
5587 (org-end-of-subtree t) (setq end (point)))
5588 (if (and (buffer-live-p org-last-indirect-buffer)
5589 (not (eq org-indirect-buffer-display 'new-frame))
5590 (not arg))
5591 (kill-buffer org-last-indirect-buffer))
5592 (setq ibuf (org-get-indirect-buffer cbuf)
5593 org-last-indirect-buffer ibuf)
5594 (cond
5595 ((or (eq org-indirect-buffer-display 'new-frame)
5596 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5597 (select-frame (make-frame))
5598 (delete-other-windows)
5599 (switch-to-buffer ibuf)
5600 (org-set-frame-title heading))
5601 ((eq org-indirect-buffer-display 'dedicated-frame)
5602 (raise-frame
5603 (select-frame (or (and org-indirect-dedicated-frame
5604 (frame-live-p org-indirect-dedicated-frame)
5605 org-indirect-dedicated-frame)
5606 (setq org-indirect-dedicated-frame (make-frame)))))
5607 (delete-other-windows)
5608 (switch-to-buffer ibuf)
5609 (org-set-frame-title (concat "Indirect: " heading)))
5610 ((eq org-indirect-buffer-display 'current-window)
5611 (switch-to-buffer ibuf))
5612 ((eq org-indirect-buffer-display 'other-window)
5613 (pop-to-buffer ibuf))
5614 (t (error "Invalid value.")))
5615 (if (featurep 'xemacs)
5616 (save-excursion (org-mode) (turn-on-font-lock)))
5617 (narrow-to-region beg end)
5618 (show-all)
5619 (goto-char pos)
5620 (and (window-live-p cwin) (select-window cwin))))
5622 (defun org-get-indirect-buffer (&optional buffer)
5623 (setq buffer (or buffer (current-buffer)))
5624 (let ((n 1) (base (buffer-name buffer)) bname)
5625 (while (buffer-live-p
5626 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5627 (setq n (1+ n)))
5628 (condition-case nil
5629 (make-indirect-buffer buffer bname 'clone)
5630 (error (make-indirect-buffer buffer bname)))))
5632 (defun org-set-frame-title (title)
5633 "Set the title of the current frame to the string TITLE."
5634 ;; FIXME: how to name a single frame in XEmacs???
5635 (unless (featurep 'xemacs)
5636 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5638 ;;;; Structure editing
5640 ;;; Inserting headlines
5642 (defun org-previous-line-empty-p ()
5643 (save-excursion
5644 (and (not (bobp))
5645 (or (beginning-of-line 0) t)
5646 (save-match-data
5647 (looking-at "[ \t]*$")))))
5649 (defun org-insert-heading (&optional force-heading)
5650 "Insert a new heading or item with same depth at point.
5651 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5652 If point is at the beginning of a headline, insert a sibling before the
5653 current headline. If point is not at the beginning, do not split the line,
5654 but create the new headline after the current line."
5655 (interactive "P")
5656 (if (= (buffer-size) 0)
5657 (insert "\n* ")
5658 (when (or force-heading (not (org-insert-item)))
5659 (let* ((empty-line-p nil)
5660 (head (save-excursion
5661 (condition-case nil
5662 (progn
5663 (org-back-to-heading)
5664 (setq empty-line-p (org-previous-line-empty-p))
5665 (match-string 0))
5666 (error "*"))))
5667 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5668 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5669 pos hide-previous previous-pos)
5670 (cond
5671 ((and (org-on-heading-p) (bolp)
5672 (or (bobp)
5673 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5674 ;; insert before the current line
5675 (open-line (if blank 2 1)))
5676 ((and (bolp)
5677 (not org-insert-heading-respect-content)
5678 (or (bobp)
5679 (save-excursion
5680 (backward-char 1) (not (org-invisible-p)))))
5681 ;; insert right here
5682 nil)
5684 ;; somewhere in the line
5685 (save-excursion
5686 (setq previous-pos (point-at-bol))
5687 (end-of-line)
5688 (setq hide-previous (org-invisible-p)))
5689 (and org-insert-heading-respect-content (org-show-subtree))
5690 (let ((split
5691 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5692 (save-excursion
5693 (let ((p (point)))
5694 (goto-char (point-at-bol))
5695 (and (looking-at org-complex-heading-regexp)
5696 (> p (match-beginning 4)))))))
5697 tags pos)
5698 (cond
5699 (org-insert-heading-respect-content
5700 (org-end-of-subtree nil t)
5701 (or (bolp) (newline))
5702 (or (org-previous-line-empty-p)
5703 (and blank (newline)))
5704 (open-line 1))
5705 ((org-on-heading-p)
5706 (when hide-previous
5707 (show-children)
5708 (org-show-entry))
5709 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5710 (setq tags (and (match-end 2) (match-string 2)))
5711 (and (match-end 1)
5712 (delete-region (match-beginning 1) (match-end 1)))
5713 (setq pos (point-at-bol))
5714 (or split (end-of-line 1))
5715 (delete-horizontal-space)
5716 (newline (if blank 2 1))
5717 (when tags
5718 (save-excursion
5719 (goto-char pos)
5720 (end-of-line 1)
5721 (insert " " tags)
5722 (org-set-tags nil 'align))))
5724 (or split (end-of-line 1))
5725 (newline (if blank 2 1)))))))
5726 (insert head) (just-one-space)
5727 (setq pos (point))
5728 (end-of-line 1)
5729 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5730 (when (and org-insert-heading-respect-content hide-previous)
5731 (save-excursion
5732 (goto-char previous-pos)
5733 (hide-subtree)))
5734 (run-hooks 'org-insert-heading-hook)))))
5736 (defun org-get-heading (&optional no-tags)
5737 "Return the heading of the current entry, without the stars."
5738 (save-excursion
5739 (org-back-to-heading t)
5740 (if (looking-at
5741 (if no-tags
5742 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5743 "\\*+[ \t]+\\([^\r\n]*\\)"))
5744 (match-string 1) "")))
5746 (defun org-heading-components ()
5747 "Return the components of the current heading.
5748 This is a list with the following elements:
5749 - the level as an integer
5750 - the reduced level, different if `org-odd-levels-only' is set.
5751 - the TODO keyword, or nil
5752 - the priority character, like ?A, or nil if no priority is given
5753 - the headline text itself, or the tags string if no headline text
5754 - the tags string, or nil."
5755 (save-excursion
5756 (org-back-to-heading t)
5757 (if (looking-at org-complex-heading-regexp)
5758 (list (length (match-string 1))
5759 (org-reduced-level (length (match-string 1)))
5760 (org-match-string-no-properties 2)
5761 (and (match-end 3) (aref (match-string 3) 2))
5762 (org-match-string-no-properties 4)
5763 (org-match-string-no-properties 5)))))
5765 (defun org-get-entry ()
5766 "Get the entry text, after heading, entire subtree."
5767 (save-excursion
5768 (org-back-to-heading t)
5769 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
5771 (defun org-insert-heading-after-current ()
5772 "Insert a new heading with same level as current, after current subtree."
5773 (interactive)
5774 (org-back-to-heading)
5775 (org-insert-heading)
5776 (org-move-subtree-down)
5777 (end-of-line 1))
5779 (defun org-insert-heading-respect-content ()
5780 (interactive)
5781 (let ((org-insert-heading-respect-content t))
5782 (org-insert-heading t)))
5784 (defun org-insert-todo-heading-respect-content (&optional force-state)
5785 (interactive "P")
5786 (let ((org-insert-heading-respect-content t))
5787 (org-insert-todo-heading force-state t)))
5789 (defun org-insert-todo-heading (arg &optional force-heading)
5790 "Insert a new heading with the same level and TODO state as current heading.
5791 If the heading has no TODO state, or if the state is DONE, use the first
5792 state (TODO by default). Also with prefix arg, force first state."
5793 (interactive "P")
5794 (when (or force-heading (not (org-insert-item 'checkbox)))
5795 (org-insert-heading force-heading)
5796 (save-excursion
5797 (org-back-to-heading)
5798 (outline-previous-heading)
5799 (looking-at org-todo-line-regexp))
5800 (let*
5801 ((new-mark-x
5802 (if (or arg
5803 (not (match-beginning 2))
5804 (member (match-string 2) org-done-keywords))
5805 (car org-todo-keywords-1)
5806 (match-string 2)))
5807 (new-mark
5809 (run-hook-with-args-until-success
5810 'org-todo-get-default-hook new-mark-x nil)
5811 new-mark-x)))
5812 (beginning-of-line 1)
5813 (and (looking-at "\\*+ ") (goto-char (match-end 0))
5814 (if org-treat-insert-todo-heading-as-state-change
5815 (org-todo new-mark)
5816 (insert new-mark " "))))
5817 (when org-provide-todo-statistics
5818 (org-update-parent-todo-statistics))))
5820 (defun org-insert-subheading (arg)
5821 "Insert a new subheading and demote it.
5822 Works for outline headings and for plain lists alike."
5823 (interactive "P")
5824 (org-insert-heading arg)
5825 (cond
5826 ((org-on-heading-p) (org-do-demote))
5827 ((org-at-item-p) (org-indent-item 1))))
5829 (defun org-insert-todo-subheading (arg)
5830 "Insert a new subheading with TODO keyword or checkbox and demote it.
5831 Works for outline headings and for plain lists alike."
5832 (interactive "P")
5833 (org-insert-todo-heading arg)
5834 (cond
5835 ((org-on-heading-p) (org-do-demote))
5836 ((org-at-item-p) (org-indent-item 1))))
5838 ;;; Promotion and Demotion
5840 (defvar org-after-demote-entry-hook nil
5841 "Hook run after an entry has been demoted.
5842 The cursor will be at the beginning of the entry.
5843 When a subtree is being demoted, the hook will be called for each node.")
5845 (defvar org-after-promote-entry-hook nil
5846 "Hook run after an entry has been promoted.
5847 The cursor will be at the beginning of the entry.
5848 When a subtree is being promoted, the hook will be called for each node.")
5850 (defun org-promote-subtree ()
5851 "Promote the entire subtree.
5852 See also `org-promote'."
5853 (interactive)
5854 (save-excursion
5855 (org-map-tree 'org-promote))
5856 (org-fix-position-after-promote))
5858 (defun org-demote-subtree ()
5859 "Demote the entire subtree. See `org-demote'.
5860 See also `org-promote'."
5861 (interactive)
5862 (save-excursion
5863 (org-map-tree 'org-demote))
5864 (org-fix-position-after-promote))
5867 (defun org-do-promote ()
5868 "Promote the current heading higher up the tree.
5869 If the region is active in `transient-mark-mode', promote all headings
5870 in the region."
5871 (interactive)
5872 (save-excursion
5873 (if (org-region-active-p)
5874 (org-map-region 'org-promote (region-beginning) (region-end))
5875 (org-promote)))
5876 (org-fix-position-after-promote))
5878 (defun org-do-demote ()
5879 "Demote the current heading lower down the tree.
5880 If the region is active in `transient-mark-mode', demote all headings
5881 in the region."
5882 (interactive)
5883 (save-excursion
5884 (if (org-region-active-p)
5885 (org-map-region 'org-demote (region-beginning) (region-end))
5886 (org-demote)))
5887 (org-fix-position-after-promote))
5889 (defun org-fix-position-after-promote ()
5890 "Make sure that after pro/demotion cursor position is right."
5891 (let ((pos (point)))
5892 (when (save-excursion
5893 (beginning-of-line 1)
5894 (looking-at org-todo-line-regexp)
5895 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5896 (cond ((eobp) (insert " "))
5897 ((eolp) (insert " "))
5898 ((equal (char-after) ?\ ) (forward-char 1))))))
5900 (defun org-reduced-level (l)
5901 "Compute the effective level of a heading.
5902 This takes into account the setting of `org-odd-levels-only'."
5903 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5905 (defun org-get-valid-level (level &optional change)
5906 "Rectify a level change under the influence of `org-odd-levels-only'
5907 LEVEL is a current level, CHANGE is by how much the level should be
5908 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5909 even level numbers will become the next higher odd number."
5910 (if org-odd-levels-only
5911 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5912 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5913 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5914 (max 1 (+ level (or change 0)))))
5916 (if (boundp 'define-obsolete-function-alias)
5917 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5918 (define-obsolete-function-alias 'org-get-legal-level
5919 'org-get-valid-level)
5920 (define-obsolete-function-alias 'org-get-legal-level
5921 'org-get-valid-level "23.1")))
5923 (defun org-promote ()
5924 "Promote the current heading higher up the tree.
5925 If the region is active in `transient-mark-mode', promote all headings
5926 in the region."
5927 (org-back-to-heading t)
5928 (let* ((level (save-match-data (funcall outline-level)))
5929 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5930 (diff (abs (- level (length up-head) -1))))
5931 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5932 (replace-match up-head nil t)
5933 ;; Fixup tag positioning
5934 (and org-auto-align-tags (org-set-tags nil t))
5935 (if org-adapt-indentation (org-fixup-indentation (- diff)))
5936 (run-hooks 'org-after-promote-entry-hook)))
5938 (defun org-demote ()
5939 "Demote the current heading lower down the tree.
5940 If the region is active in `transient-mark-mode', demote all headings
5941 in the region."
5942 (org-back-to-heading t)
5943 (let* ((level (save-match-data (funcall outline-level)))
5944 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5945 (diff (abs (- level (length down-head) -1))))
5946 (replace-match down-head nil t)
5947 ;; Fixup tag positioning
5948 (and org-auto-align-tags (org-set-tags nil t))
5949 (if org-adapt-indentation (org-fixup-indentation diff))
5950 (run-hooks 'org-after-demote-entry-hook)))
5952 (defun org-map-tree (fun)
5953 "Call FUN for every heading underneath the current one."
5954 (org-back-to-heading)
5955 (let ((level (funcall outline-level)))
5956 (save-excursion
5957 (funcall fun)
5958 (while (and (progn
5959 (outline-next-heading)
5960 (> (funcall outline-level) level))
5961 (not (eobp)))
5962 (funcall fun)))))
5964 (defun org-map-region (fun beg end)
5965 "Call FUN for every heading between BEG and END."
5966 (let ((org-ignore-region t))
5967 (save-excursion
5968 (setq end (copy-marker end))
5969 (goto-char beg)
5970 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5971 (< (point) end))
5972 (funcall fun))
5973 (while (and (progn
5974 (outline-next-heading)
5975 (< (point) end))
5976 (not (eobp)))
5977 (funcall fun)))))
5979 (defun org-fixup-indentation (diff)
5980 "Change the indentation in the current entry by DIFF
5981 However, if any line in the current entry has no indentation, or if it
5982 would end up with no indentation after the change, nothing at all is done."
5983 (save-excursion
5984 (let ((end (save-excursion (outline-next-heading)
5985 (point-marker)))
5986 (prohibit (if (> diff 0)
5987 "^\\S-"
5988 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5989 col)
5990 (unless (save-excursion (end-of-line 1)
5991 (re-search-forward prohibit end t))
5992 (while (and (< (point) end)
5993 (re-search-forward "^[ \t]+" end t))
5994 (goto-char (match-end 0))
5995 (setq col (current-column))
5996 (if (< diff 0) (replace-match ""))
5997 (org-indent-to-column (+ diff col))))
5998 (move-marker end nil))))
6000 (defun org-convert-to-odd-levels ()
6001 "Convert an org-mode file with all levels allowed to one with odd levels.
6002 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6003 level 5 etc."
6004 (interactive)
6005 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6006 (let ((org-odd-levels-only nil) n)
6007 (save-excursion
6008 (goto-char (point-min))
6009 (while (re-search-forward "^\\*\\*+ " nil t)
6010 (setq n (- (length (match-string 0)) 2))
6011 (while (>= (setq n (1- n)) 0)
6012 (org-demote))
6013 (end-of-line 1))))))
6016 (defun org-convert-to-oddeven-levels ()
6017 "Convert an org-mode file with only odd levels to one with odd and even levels.
6018 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6019 section with an even level, conversion would destroy the structure of the file. An error
6020 is signaled in this case."
6021 (interactive)
6022 (goto-char (point-min))
6023 ;; First check if there are no even levels
6024 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6025 (org-show-context t)
6026 (error "Not all levels are odd in this file. Conversion not possible."))
6027 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6028 (let ((org-odd-levels-only nil) n)
6029 (save-excursion
6030 (goto-char (point-min))
6031 (while (re-search-forward "^\\*\\*+ " nil t)
6032 (setq n (/ (1- (length (match-string 0))) 2))
6033 (while (>= (setq n (1- n)) 0)
6034 (org-promote))
6035 (end-of-line 1))))))
6037 (defun org-tr-level (n)
6038 "Make N odd if required."
6039 (if org-odd-levels-only (1+ (/ n 2)) n))
6041 ;;; Vertical tree motion, cutting and pasting of subtrees
6043 (defun org-move-subtree-up (&optional arg)
6044 "Move the current subtree up past ARG headlines of the same level."
6045 (interactive "p")
6046 (org-move-subtree-down (- (prefix-numeric-value arg))))
6048 (defun org-move-subtree-down (&optional arg)
6049 "Move the current subtree down past ARG headlines of the same level."
6050 (interactive "p")
6051 (setq arg (prefix-numeric-value arg))
6052 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6053 'outline-get-last-sibling))
6054 (ins-point (make-marker))
6055 (cnt (abs arg))
6056 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6057 ;; Select the tree
6058 (org-back-to-heading)
6059 (setq beg0 (point))
6060 (save-excursion
6061 (setq ne-beg (org-back-over-empty-lines))
6062 (setq beg (point)))
6063 (save-match-data
6064 (save-excursion (outline-end-of-heading)
6065 (setq folded (org-invisible-p)))
6066 (outline-end-of-subtree))
6067 (outline-next-heading)
6068 (setq ne-end (org-back-over-empty-lines))
6069 (setq end (point))
6070 (goto-char beg0)
6071 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6072 ;; include less whitespace
6073 (save-excursion
6074 (goto-char beg)
6075 (forward-line (- ne-beg ne-end))
6076 (setq beg (point))))
6077 ;; Find insertion point, with error handling
6078 (while (> cnt 0)
6079 (or (and (funcall movfunc) (looking-at outline-regexp))
6080 (progn (goto-char beg0)
6081 (error "Cannot move past superior level or buffer limit")))
6082 (setq cnt (1- cnt)))
6083 (if (> arg 0)
6084 ;; Moving forward - still need to move over subtree
6085 (progn (org-end-of-subtree t t)
6086 (save-excursion
6087 (org-back-over-empty-lines)
6088 (or (bolp) (newline)))))
6089 (setq ne-ins (org-back-over-empty-lines))
6090 (move-marker ins-point (point))
6091 (setq txt (buffer-substring beg end))
6092 (org-save-markers-in-region beg end)
6093 (delete-region beg end)
6094 (org-remove-empty-overlays-at beg)
6095 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6096 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6097 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6098 (let ((bbb (point)))
6099 (insert-before-markers txt)
6100 (org-reinstall-markers-in-region bbb)
6101 (move-marker ins-point bbb))
6102 (or (bolp) (insert "\n"))
6103 (setq ins-end (point))
6104 (goto-char ins-point)
6105 (org-skip-whitespace)
6106 (when (and (< arg 0)
6107 (org-first-sibling-p)
6108 (> ne-ins ne-beg))
6109 ;; Move whitespace back to beginning
6110 (save-excursion
6111 (goto-char ins-end)
6112 (let ((kill-whole-line t))
6113 (kill-line (- ne-ins ne-beg)) (point)))
6114 (insert (make-string (- ne-ins ne-beg) ?\n)))
6115 (move-marker ins-point nil)
6116 (if folded
6117 (hide-subtree)
6118 (org-show-entry)
6119 (show-children)
6120 (org-cycle-hide-drawers 'children))
6121 (org-clean-visibility-after-subtree-move)))
6123 (defvar org-subtree-clip ""
6124 "Clipboard for cut and paste of subtrees.
6125 This is actually only a copy of the kill, because we use the normal kill
6126 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6128 (defvar org-subtree-clip-folded nil
6129 "Was the last copied subtree folded?
6130 This is used to fold the tree back after pasting.")
6132 (defun org-cut-subtree (&optional n)
6133 "Cut the current subtree into the clipboard.
6134 With prefix arg N, cut this many sequential subtrees.
6135 This is a short-hand for marking the subtree and then cutting it."
6136 (interactive "p")
6137 (org-copy-subtree n 'cut))
6139 (defun org-copy-subtree (&optional n cut force-store-markers)
6140 "Cut the current subtree into the clipboard.
6141 With prefix arg N, cut this many sequential subtrees.
6142 This is a short-hand for marking the subtree and then copying it.
6143 If CUT is non-nil, actually cut the subtree.
6144 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6145 of some markers in the region, even if CUT is non-nil. This is
6146 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6147 (interactive "p")
6148 (let (beg end folded (beg0 (point)))
6149 (if (interactive-p)
6150 (org-back-to-heading nil) ; take what looks like a subtree
6151 (org-back-to-heading t)) ; take what is really there
6152 (org-back-over-empty-lines)
6153 (setq beg (point))
6154 (skip-chars-forward " \t\r\n")
6155 (save-match-data
6156 (save-excursion (outline-end-of-heading)
6157 (setq folded (org-invisible-p)))
6158 (condition-case nil
6159 (org-forward-same-level (1- n) t)
6160 (error nil))
6161 (org-end-of-subtree t t))
6162 (org-back-over-empty-lines)
6163 (setq end (point))
6164 (goto-char beg0)
6165 (when (> end beg)
6166 (setq org-subtree-clip-folded folded)
6167 (when (or cut force-store-markers)
6168 (org-save-markers-in-region beg end))
6169 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6170 (setq org-subtree-clip (current-kill 0))
6171 (message "%s: Subtree(s) with %d characters"
6172 (if cut "Cut" "Copied")
6173 (length org-subtree-clip)))))
6175 (defun org-paste-subtree (&optional level tree for-yank)
6176 "Paste the clipboard as a subtree, with modification of headline level.
6177 The entire subtree is promoted or demoted in order to match a new headline
6178 level.
6180 If the cursor is at the beginning of a headline, the same level as
6181 that headline is used to paste the tree
6183 If not, the new level is derived from the *visible* headings
6184 before and after the insertion point, and taken to be the inferior headline
6185 level of the two. So if the previous visible heading is level 3 and the
6186 next is level 4 (or vice versa), level 4 will be used for insertion.
6187 This makes sure that the subtree remains an independent subtree and does
6188 not swallow low level entries.
6190 You can also force a different level, either by using a numeric prefix
6191 argument, or by inserting the heading marker by hand. For example, if the
6192 cursor is after \"*****\", then the tree will be shifted to level 5.
6194 If optional TREE is given, use this text instead of the kill ring.
6196 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6197 move back over whitespace before inserting, and move point to the end of
6198 the inserted text when done."
6199 (interactive "P")
6200 (setq tree (or tree (and kill-ring (current-kill 0))))
6201 (unless (org-kill-is-subtree-p tree)
6202 (error "%s"
6203 (substitute-command-keys
6204 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6205 (let* ((visp (not (org-invisible-p)))
6206 (txt tree)
6207 (^re (concat "^\\(" outline-regexp "\\)"))
6208 (re (concat "\\(" outline-regexp "\\)"))
6209 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6211 (old-level (if (string-match ^re txt)
6212 (- (match-end 0) (match-beginning 0) 1)
6213 -1))
6214 (force-level (cond (level (prefix-numeric-value level))
6215 ((and (looking-at "[ \t]*$")
6216 (string-match
6217 ^re_ (buffer-substring
6218 (point-at-bol) (point))))
6219 (- (match-end 1) (match-beginning 1)))
6220 ((and (bolp)
6221 (looking-at org-outline-regexp))
6222 (- (match-end 0) (point) 1))
6223 (t nil)))
6224 (previous-level (save-excursion
6225 (condition-case nil
6226 (progn
6227 (outline-previous-visible-heading 1)
6228 (if (looking-at re)
6229 (- (match-end 0) (match-beginning 0) 1)
6231 (error 1))))
6232 (next-level (save-excursion
6233 (condition-case nil
6234 (progn
6235 (or (looking-at outline-regexp)
6236 (outline-next-visible-heading 1))
6237 (if (looking-at re)
6238 (- (match-end 0) (match-beginning 0) 1)
6240 (error 1))))
6241 (new-level (or force-level (max previous-level next-level)))
6242 (shift (if (or (= old-level -1)
6243 (= new-level -1)
6244 (= old-level new-level))
6246 (- new-level old-level)))
6247 (delta (if (> shift 0) -1 1))
6248 (func (if (> shift 0) 'org-demote 'org-promote))
6249 (org-odd-levels-only nil)
6250 beg end newend)
6251 ;; Remove the forced level indicator
6252 (if force-level
6253 (delete-region (point-at-bol) (point)))
6254 ;; Paste
6255 (beginning-of-line 1)
6256 (unless for-yank (org-back-over-empty-lines))
6257 (setq beg (point))
6258 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6259 (insert-before-markers txt)
6260 (unless (string-match "\n\\'" txt) (insert "\n"))
6261 (setq newend (point))
6262 (org-reinstall-markers-in-region beg)
6263 (setq end (point))
6264 (goto-char beg)
6265 (skip-chars-forward " \t\n\r")
6266 (setq beg (point))
6267 (if (and (org-invisible-p) visp)
6268 (save-excursion (outline-show-heading)))
6269 ;; Shift if necessary
6270 (unless (= shift 0)
6271 (save-restriction
6272 (narrow-to-region beg end)
6273 (while (not (= shift 0))
6274 (org-map-region func (point-min) (point-max))
6275 (setq shift (+ delta shift)))
6276 (goto-char (point-min))
6277 (setq newend (point-max))))
6278 (when (or (interactive-p) for-yank)
6279 (message "Clipboard pasted as level %d subtree" new-level))
6280 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6281 kill-ring
6282 (eq org-subtree-clip (current-kill 0))
6283 org-subtree-clip-folded)
6284 ;; The tree was folded before it was killed/copied
6285 (hide-subtree))
6286 (and for-yank (goto-char newend))))
6288 (defun org-kill-is-subtree-p (&optional txt)
6289 "Check if the current kill is an outline subtree, or a set of trees.
6290 Returns nil if kill does not start with a headline, or if the first
6291 headline level is not the largest headline level in the tree.
6292 So this will actually accept several entries of equal levels as well,
6293 which is OK for `org-paste-subtree'.
6294 If optional TXT is given, check this string instead of the current kill."
6295 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6296 (start-level (and kill
6297 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6298 org-outline-regexp "\\)")
6299 kill)
6300 (- (match-end 2) (match-beginning 2) 1)))
6301 (re (concat "^" org-outline-regexp))
6302 (start (1+ (or (match-beginning 2) -1))))
6303 (if (not start-level)
6304 (progn
6305 nil) ;; does not even start with a heading
6306 (catch 'exit
6307 (while (setq start (string-match re kill (1+ start)))
6308 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6309 (throw 'exit nil)))
6310 t))))
6312 (defvar org-markers-to-move nil
6313 "Markers that should be moved with a cut-and-paste operation.
6314 Those markers are stored together with their positions relative to
6315 the start of the region.")
6317 (defun org-save-markers-in-region (beg end)
6318 "Check markers in region.
6319 If these markers are between BEG and END, record their position relative
6320 to BEG, so that after moving the block of text, we can put the markers back
6321 into place.
6322 This function gets called just before an entry or tree gets cut from the
6323 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6324 called immediately, to move the markers with the entries."
6325 (setq org-markers-to-move nil)
6326 (when (featurep 'org-clock)
6327 (org-clock-save-markers-for-cut-and-paste beg end))
6328 (when (featurep 'org-agenda)
6329 (org-agenda-save-markers-for-cut-and-paste beg end)))
6331 (defun org-check-and-save-marker (marker beg end)
6332 "Check if MARKER is between BEG and END.
6333 If yes, remember the marker and the distance to BEG."
6334 (when (and (marker-buffer marker)
6335 (equal (marker-buffer marker) (current-buffer)))
6336 (if (and (>= marker beg) (< marker end))
6337 (push (cons marker (- marker beg)) org-markers-to-move))))
6339 (defun org-reinstall-markers-in-region (beg)
6340 "Move all remembered markers to their position relative to BEG."
6341 (mapc (lambda (x)
6342 (move-marker (car x) (+ beg (cdr x))))
6343 org-markers-to-move)
6344 (setq org-markers-to-move nil))
6346 (defun org-narrow-to-subtree ()
6347 "Narrow buffer to the current subtree."
6348 (interactive)
6349 (save-excursion
6350 (save-match-data
6351 (narrow-to-region
6352 (progn (org-back-to-heading t) (point))
6353 (progn (org-end-of-subtree t) (point))))))
6355 (defun org-clone-subtree-with-time-shift (n &optional shift)
6356 "Clone the task (subtree) at point N times.
6357 The clones will be inserted as siblings.
6359 In interactive use, the user will be prompted for the number of clones
6360 to be produced, and for a time SHIFT, which may be a repeater as used
6361 in time stamps, for example `+3d'.
6363 When a valid repeater is given and the entry contains any time stamps,
6364 the clones will become a sequence in time, with time stamps in the
6365 subtree shifted for each clone produced. If SHIFT is nil or the
6366 empty string, time stamps will be left alone.
6368 If the original subtree did contain time stamps with a repeater,
6369 the following will happen:
6370 - the repeater will be removed in each clone
6371 - an additional clone will be produced, with the current, unshifted
6372 date(s) in the entry.
6373 - the original entry will be placed *after* all the clones, with
6374 repeater intact.
6375 - the start days in the repeater in the original entry will be shifted
6376 to past the last clone.
6377 I this way you can spell out a number of instances of a repeating task,
6378 and still retain the repeater to cover future instances of the task."
6379 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6380 (let (beg end template task
6381 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6382 (if (not (and (integerp n) (> n 0)))
6383 (error "Invalid number of replications %s" n))
6384 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6385 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6386 shift)))
6387 (error "Invalid shift specification %s" shift))
6388 (when doshift
6389 (setq shift-n (string-to-number (match-string 1 shift))
6390 shift-what (cdr (assoc (match-string 2 shift)
6391 '(("d" . day) ("w" . week)
6392 ("m" . month) ("y" . year))))))
6393 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6394 (setq nmin 1 nmax n)
6395 (org-back-to-heading t)
6396 (setq beg (point))
6397 (org-end-of-subtree t t)
6398 (setq end (point))
6399 (setq template (buffer-substring beg end))
6400 (when (and doshift
6401 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6402 (delete-region beg end)
6403 (setq end beg)
6404 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6405 (goto-char end)
6406 (loop for n from nmin to nmax do
6407 (if (not doshift)
6408 (setq task template)
6409 (with-temp-buffer
6410 (insert template)
6411 (org-mode)
6412 (goto-char (point-min))
6413 (while (re-search-forward org-ts-regexp-both nil t)
6414 (org-timestamp-change (* n shift-n) shift-what))
6415 (unless (= n n-no-remove)
6416 (goto-char (point-min))
6417 (while (re-search-forward org-ts-regexp nil t)
6418 (save-excursion
6419 (goto-char (match-beginning 0))
6420 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6421 (delete-region (match-beginning 1) (match-end 1))))))
6422 (setq task (buffer-string))))
6423 (insert task))
6424 (goto-char beg)))
6426 ;;; Outline Sorting
6428 (defun org-sort (with-case)
6429 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6430 Optional argument WITH-CASE means sort case-sensitively.
6431 With a double prefix argument, also remove duplicate entries."
6432 (interactive "P")
6433 (if (org-at-table-p)
6434 (org-call-with-arg 'org-table-sort-lines with-case)
6435 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6437 (defun org-sort-remove-invisible (s)
6438 (remove-text-properties 0 (length s) org-rm-props s)
6439 (while (string-match org-bracket-link-regexp s)
6440 (setq s (replace-match (if (match-end 2)
6441 (match-string 3 s)
6442 (match-string 1 s)) t t s)))
6445 (defvar org-priority-regexp) ; defined later in the file
6447 (defvar org-after-sorting-entries-or-items-hook nil
6448 "Hook that is run after a bunch of entries or items have been sorted.
6449 When children are sorted, the cursor is in the parent line when this
6450 hook gets called. When a region or a plain list is sorted, the cursor
6451 will be in the first entry of the sorted region/list.")
6453 (defun org-sort-entries-or-items
6454 (&optional with-case sorting-type getkey-func compare-func property)
6455 "Sort entries on a certain level of an outline tree, or plain list items.
6456 If there is an active region, the entries in the region are sorted.
6457 Else, if the cursor is before the first entry, sort the top-level items.
6458 Else, the children of the entry at point are sorted.
6459 If the cursor is at the first item in a plain list, the list items will be
6460 sorted.
6462 Sorting can be alphabetically, numerically, by date/time as given by
6463 a time stamp, by a property or by priority.
6465 The command prompts for the sorting type unless it has been given to the
6466 function through the SORTING-TYPE argument, which needs to a character,
6467 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6468 precise meaning of each character:
6470 n Numerically, by converting the beginning of the entry/item to a number.
6471 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6472 t By date/time, either the first active time stamp in the entry, or, if
6473 none exist, by the first inactive one.
6474 In items, only the first line will be chekced.
6475 s By the scheduled date/time.
6476 d By deadline date/time.
6477 c By creation time, which is assumed to be the first inactive time stamp
6478 at the beginning of a line.
6479 p By priority according to the cookie.
6480 r By the value of a property.
6482 Capital letters will reverse the sort order.
6484 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6485 called with point at the beginning of the record. It must return either
6486 a string or a number that should serve as the sorting key for that record.
6488 Comparing entries ignores case by default. However, with an optional argument
6489 WITH-CASE, the sorting considers case as well."
6490 (interactive "P")
6491 (let ((case-func (if with-case 'identity 'downcase))
6492 start beg end stars re re2
6493 txt what tmp plain-list-p)
6494 ;; Find beginning and end of region to sort
6495 (cond
6496 ((org-region-active-p)
6497 ;; we will sort the region
6498 (setq end (region-end)
6499 what "region")
6500 (goto-char (region-beginning))
6501 (if (not (org-on-heading-p)) (outline-next-heading))
6502 (setq start (point)))
6503 ((org-at-item-p)
6504 ;; we will sort this plain list
6505 (org-beginning-of-item-list) (setq start (point))
6506 (org-end-of-item-list) (setq end (point))
6507 (goto-char start)
6508 (setq plain-list-p t
6509 what "plain list"))
6510 ((or (org-on-heading-p)
6511 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6512 ;; we will sort the children of the current headline
6513 (org-back-to-heading)
6514 (setq start (point)
6515 end (progn (org-end-of-subtree t t)
6516 (org-back-over-empty-lines)
6517 (point))
6518 what "children")
6519 (goto-char start)
6520 (show-subtree)
6521 (outline-next-heading))
6523 ;; we will sort the top-level entries in this file
6524 (goto-char (point-min))
6525 (or (org-on-heading-p) (outline-next-heading))
6526 (setq start (point) end (point-max) what "top-level")
6527 (goto-char start)
6528 (show-all)))
6530 (setq beg (point))
6531 (if (>= beg end) (error "Nothing to sort"))
6533 (unless plain-list-p
6534 (looking-at "\\(\\*+\\)")
6535 (setq stars (match-string 1)
6536 re (concat "^" (regexp-quote stars) " +")
6537 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6538 txt (buffer-substring beg end))
6539 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6540 (if (and (not (equal stars "*")) (string-match re2 txt))
6541 (error "Region to sort contains a level above the first entry")))
6543 (unless sorting-type
6544 (message
6545 (if plain-list-p
6546 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6547 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
6548 [t]ime [s]cheduled [d]eadline [c]reated
6549 A/N/T/S/D/C/P/O/F means reversed:")
6550 what)
6551 (setq sorting-type (read-char-exclusive))
6553 (and (= (downcase sorting-type) ?f)
6554 (setq getkey-func
6555 (org-ido-completing-read "Sort using function: "
6556 obarray 'fboundp t nil nil))
6557 (setq getkey-func (intern getkey-func)))
6559 (and (= (downcase sorting-type) ?r)
6560 (setq property
6561 (org-ido-completing-read "Property: "
6562 (mapcar 'list (org-buffer-property-keys t))
6563 nil t))))
6565 (message "Sorting entries...")
6567 (save-restriction
6568 (narrow-to-region start end)
6570 (let ((dcst (downcase sorting-type))
6571 (case-fold-search nil)
6572 (now (current-time)))
6573 (sort-subr
6574 (/= dcst sorting-type)
6575 ;; This function moves to the beginning character of the "record" to
6576 ;; be sorted.
6577 (if plain-list-p
6578 (lambda nil
6579 (if (org-at-item-p) t (goto-char (point-max))))
6580 (lambda nil
6581 (if (re-search-forward re nil t)
6582 (goto-char (match-beginning 0))
6583 (goto-char (point-max)))))
6584 ;; This function moves to the last character of the "record" being
6585 ;; sorted.
6586 (if plain-list-p
6587 'org-end-of-item
6588 (lambda nil
6589 (save-match-data
6590 (condition-case nil
6591 (outline-forward-same-level 1)
6592 (error
6593 (goto-char (point-max)))))))
6595 ;; This function returns the value that gets sorted against.
6596 (if plain-list-p
6597 (lambda nil
6598 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6599 (cond
6600 ((= dcst ?n)
6601 (string-to-number (buffer-substring (match-end 0)
6602 (point-at-eol))))
6603 ((= dcst ?a)
6604 (buffer-substring (match-end 0) (point-at-eol)))
6605 ((= dcst ?t)
6606 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
6607 (re-search-forward org-ts-regexp-both
6608 (point-at-eol) t))
6609 (org-time-string-to-seconds (match-string 0))
6610 (time-to-seconds now)))
6611 ((= dcst ?f)
6612 (if getkey-func
6613 (progn
6614 (setq tmp (funcall getkey-func))
6615 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6616 tmp)
6617 (error "Invalid key function `%s'" getkey-func)))
6618 (t (error "Invalid sorting type `%c'" sorting-type)))))
6619 (lambda nil
6620 (cond
6621 ((= dcst ?n)
6622 (if (looking-at org-complex-heading-regexp)
6623 (string-to-number (match-string 4))
6624 nil))
6625 ((= dcst ?a)
6626 (if (looking-at org-complex-heading-regexp)
6627 (funcall case-func (match-string 4))
6628 nil))
6629 ((= dcst ?t)
6630 (let ((end (save-excursion (outline-next-heading) (point))))
6631 (if (or (re-search-forward org-ts-regexp end t)
6632 (re-search-forward org-ts-regexp-both end t))
6633 (org-time-string-to-seconds (match-string 0))
6634 (time-to-seconds now))))
6635 ((= dcst ?c)
6636 (let ((end (save-excursion (outline-next-heading) (point))))
6637 (if (re-search-forward
6638 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
6639 end t)
6640 (org-time-string-to-seconds (match-string 0))
6641 (time-to-seconds now))))
6642 ((= dcst ?s)
6643 (let ((end (save-excursion (outline-next-heading) (point))))
6644 (if (re-search-forward org-scheduled-time-regexp end t)
6645 (org-time-string-to-seconds (match-string 1))
6646 (time-to-seconds now))))
6647 ((= dcst ?d)
6648 (let ((end (save-excursion (outline-next-heading) (point))))
6649 (if (re-search-forward org-deadline-time-regexp end t)
6650 (org-time-string-to-seconds (match-string 1))
6651 (time-to-seconds now))))
6652 ((= dcst ?p)
6653 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6654 (string-to-char (match-string 2))
6655 org-default-priority))
6656 ((= dcst ?r)
6657 (or (org-entry-get nil property) ""))
6658 ((= dcst ?o)
6659 (if (looking-at org-complex-heading-regexp)
6660 (- 9999 (length (member (match-string 2)
6661 org-todo-keywords-1)))))
6662 ((= dcst ?f)
6663 (if getkey-func
6664 (progn
6665 (setq tmp (funcall getkey-func))
6666 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6667 tmp)
6668 (error "Invalid key function `%s'" getkey-func)))
6669 (t (error "Invalid sorting type `%c'" sorting-type)))))
6671 (cond
6672 ((= dcst ?a) 'string<)
6673 ((= dcst ?f) compare-func)
6674 ((member dcst '(?p ?t ?s ?d ?c)) '<)
6675 (t nil)))))
6676 (run-hooks 'org-after-sorting-entries-or-items-hook)
6677 (message "Sorting entries...done")))
6679 (defun org-do-sort (table what &optional with-case sorting-type)
6680 "Sort TABLE of WHAT according to SORTING-TYPE.
6681 The user will be prompted for the SORTING-TYPE if the call to this
6682 function does not specify it. WHAT is only for the prompt, to indicate
6683 what is being sorted. The sorting key will be extracted from
6684 the car of the elements of the table.
6685 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6686 (unless sorting-type
6687 (message
6688 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6689 what)
6690 (setq sorting-type (read-char-exclusive)))
6691 (let ((dcst (downcase sorting-type))
6692 extractfun comparefun)
6693 ;; Define the appropriate functions
6694 (cond
6695 ((= dcst ?n)
6696 (setq extractfun 'string-to-number
6697 comparefun (if (= dcst sorting-type) '< '>)))
6698 ((= dcst ?a)
6699 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6700 (lambda(x) (downcase (org-sort-remove-invisible x))))
6701 comparefun (if (= dcst sorting-type)
6702 'string<
6703 (lambda (a b) (and (not (string< a b))
6704 (not (string= a b)))))))
6705 ((= dcst ?t)
6706 (setq extractfun
6707 (lambda (x)
6708 (if (or (string-match org-ts-regexp x)
6709 (string-match org-ts-regexp-both x))
6710 (time-to-seconds
6711 (org-time-string-to-time (match-string 0 x)))
6713 comparefun (if (= dcst sorting-type) '< '>)))
6714 (t (error "Invalid sorting type `%c'" sorting-type)))
6716 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6717 table)
6718 (lambda (a b) (funcall comparefun (car a) (car b))))))
6721 ;;; The orgstruct minor mode
6723 ;; Define a minor mode which can be used in other modes in order to
6724 ;; integrate the org-mode structure editing commands.
6726 ;; This is really a hack, because the org-mode structure commands use
6727 ;; keys which normally belong to the major mode. Here is how it
6728 ;; works: The minor mode defines all the keys necessary to operate the
6729 ;; structure commands, but wraps the commands into a function which
6730 ;; tests if the cursor is currently at a headline or a plain list
6731 ;; item. If that is the case, the structure command is used,
6732 ;; temporarily setting many Org-mode variables like regular
6733 ;; expressions for filling etc. However, when any of those keys is
6734 ;; used at a different location, function uses `key-binding' to look
6735 ;; up if the key has an associated command in another currently active
6736 ;; keymap (minor modes, major mode, global), and executes that
6737 ;; command. There might be problems if any of the keys is otherwise
6738 ;; used as a prefix key.
6740 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6741 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6742 ;; addresses this by checking explicitly for both bindings.
6744 (defvar orgstruct-mode-map (make-sparse-keymap)
6745 "Keymap for the minor `orgstruct-mode'.")
6747 (defvar org-local-vars nil
6748 "List of local variables, for use by `orgstruct-mode'")
6750 ;;;###autoload
6751 (define-minor-mode orgstruct-mode
6752 "Toggle the minor more `orgstruct-mode'.
6753 This mode is for using Org-mode structure commands in other modes.
6754 The following key behave as if Org-mode was active, if the cursor
6755 is on a headline, or on a plain list item (both in the definition
6756 of Org-mode).
6758 M-up Move entry/item up
6759 M-down Move entry/item down
6760 M-left Promote
6761 M-right Demote
6762 M-S-up Move entry/item up
6763 M-S-down Move entry/item down
6764 M-S-left Promote subtree
6765 M-S-right Demote subtree
6766 M-q Fill paragraph and items like in Org-mode
6767 C-c ^ Sort entries
6768 C-c - Cycle list bullet
6769 TAB Cycle item visibility
6770 M-RET Insert new heading/item
6771 S-M-RET Insert new TODO heading / Checkbox item
6772 C-c C-c Set tags / toggle checkbox"
6773 nil " OrgStruct" nil
6774 (org-load-modules-maybe)
6775 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6777 ;;;###autoload
6778 (defun turn-on-orgstruct ()
6779 "Unconditionally turn on `orgstruct-mode'."
6780 (orgstruct-mode 1))
6782 (defun orgstruct++-mode (&optional arg)
6783 "Toggle `orgstruct-mode', the enhanced version of it.
6784 In addition to setting orgstruct-mode, this also exports all indentation
6785 and autofilling variables from org-mode into the buffer. It will also
6786 recognize item context in multiline items.
6787 Note that turning off orgstruct-mode will *not* remove the
6788 indentation/paragraph settings. This can only be done by refreshing the
6789 major mode, for example with \\[normal-mode]."
6790 (interactive "P")
6791 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6792 (if (< arg 1)
6793 (orgstruct-mode -1)
6794 (orgstruct-mode 1)
6795 (let (var val)
6796 (mapc
6797 (lambda (x)
6798 (when (string-match
6799 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6800 (symbol-name (car x)))
6801 (setq var (car x) val (nth 1 x))
6802 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6803 org-local-vars)
6804 (org-set-local 'orgstruct-is-++ t))))
6806 (defvar orgstruct-is-++ nil
6807 "Is orgstruct-mode in ++ version in the current-buffer?")
6808 (make-variable-buffer-local 'orgstruct-is-++)
6810 ;;;###autoload
6811 (defun turn-on-orgstruct++ ()
6812 "Unconditionally turn on `orgstruct++-mode'."
6813 (orgstruct++-mode 1))
6815 (defun orgstruct-error ()
6816 "Error when there is no default binding for a structure key."
6817 (interactive)
6818 (error "This key has no function outside structure elements"))
6820 (defun orgstruct-setup ()
6821 "Setup orgstruct keymaps."
6822 (let ((nfunc 0)
6823 (bindings
6824 (list
6825 '([(meta up)] org-metaup)
6826 '([(meta down)] org-metadown)
6827 '([(meta left)] org-metaleft)
6828 '([(meta right)] org-metaright)
6829 '([(meta shift up)] org-shiftmetaup)
6830 '([(meta shift down)] org-shiftmetadown)
6831 '([(meta shift left)] org-shiftmetaleft)
6832 '([(meta shift right)] org-shiftmetaright)
6833 '([?\e (up)] org-metaup)
6834 '([?\e (down)] org-metadown)
6835 '([?\e (left)] org-metaleft)
6836 '([?\e (right)] org-metaright)
6837 '([?\e (shift up)] org-shiftmetaup)
6838 '([?\e (shift down)] org-shiftmetadown)
6839 '([?\e (shift left)] org-shiftmetaleft)
6840 '([?\e (shift right)] org-shiftmetaright)
6841 '([(shift up)] org-shiftup)
6842 '([(shift down)] org-shiftdown)
6843 '([(shift left)] org-shiftleft)
6844 '([(shift right)] org-shiftright)
6845 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6846 '("\M-q" fill-paragraph)
6847 '("\C-c^" org-sort)
6848 '("\C-c-" org-cycle-list-bullet)))
6849 elt key fun cmd)
6850 (while (setq elt (pop bindings))
6851 (setq nfunc (1+ nfunc))
6852 (setq key (org-key (car elt))
6853 fun (nth 1 elt)
6854 cmd (orgstruct-make-binding fun nfunc key))
6855 (org-defkey orgstruct-mode-map key cmd))
6857 ;; Special treatment needed for TAB and RET
6858 (org-defkey orgstruct-mode-map [(tab)]
6859 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6860 (org-defkey orgstruct-mode-map "\C-i"
6861 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6863 (org-defkey orgstruct-mode-map "\M-\C-m"
6864 (orgstruct-make-binding 'org-insert-heading 105
6865 "\M-\C-m" [(meta return)]))
6866 (org-defkey orgstruct-mode-map [(meta return)]
6867 (orgstruct-make-binding 'org-insert-heading 106
6868 [(meta return)] "\M-\C-m"))
6870 (org-defkey orgstruct-mode-map [(shift meta return)]
6871 (orgstruct-make-binding 'org-insert-todo-heading 107
6872 [(meta return)] "\M-\C-m"))
6874 (org-defkey orgstruct-mode-map "\e\C-m"
6875 (orgstruct-make-binding 'org-insert-heading 108
6876 "\e\C-m" [?\e (return)]))
6877 (org-defkey orgstruct-mode-map [?\e (return)]
6878 (orgstruct-make-binding 'org-insert-heading 109
6879 [?\e (return)] "\e\C-m"))
6880 (org-defkey orgstruct-mode-map [?\e (shift return)]
6881 (orgstruct-make-binding 'org-insert-todo-heading 110
6882 [?\e (return)] "\e\C-m"))
6884 (unless org-local-vars
6885 (setq org-local-vars (org-get-local-variables)))
6889 (defun orgstruct-make-binding (fun n &rest keys)
6890 "Create a function for binding in the structure minor mode.
6891 FUN is the command to call inside a table. N is used to create a unique
6892 command name. KEYS are keys that should be checked in for a command
6893 to execute outside of tables."
6894 (eval
6895 (list 'defun
6896 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6897 '(arg)
6898 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6899 "Outside of structure, run the binding of `"
6900 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6901 "'.")
6902 '(interactive "p")
6903 (list 'if
6904 `(org-context-p 'headline 'item
6905 (and orgstruct-is-++
6906 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
6907 'item-body))
6908 (list 'org-run-like-in-org-mode (list 'quote fun))
6909 (list 'let '(orgstruct-mode)
6910 (list 'call-interactively
6911 (append '(or)
6912 (mapcar (lambda (k)
6913 (list 'key-binding k))
6914 keys)
6915 '('orgstruct-error))))))))
6917 (defun org-context-p (&rest contexts)
6918 "Check if local context is any of CONTEXTS.
6919 Possible values in the list of contexts are `table', `headline', and `item'."
6920 (let ((pos (point)))
6921 (goto-char (point-at-bol))
6922 (prog1 (or (and (memq 'table contexts)
6923 (looking-at "[ \t]*|"))
6924 (and (memq 'headline contexts)
6925 ;;????????? (looking-at "\\*+"))
6926 (looking-at outline-regexp))
6927 (and (memq 'item contexts)
6928 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
6929 (and (memq 'item-body contexts)
6930 (org-in-item-p)))
6931 (goto-char pos))))
6933 (defun org-get-local-variables ()
6934 "Return a list of all local variables in an org-mode buffer."
6935 (let (varlist)
6936 (with-current-buffer (get-buffer-create "*Org tmp*")
6937 (erase-buffer)
6938 (org-mode)
6939 (setq varlist (buffer-local-variables)))
6940 (kill-buffer "*Org tmp*")
6941 (delq nil
6942 (mapcar
6943 (lambda (x)
6944 (setq x
6945 (if (symbolp x)
6946 (list x)
6947 (list (car x) (list 'quote (cdr x)))))
6948 (if (string-match
6949 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6950 (symbol-name (car x)))
6951 x nil))
6952 varlist))))
6954 ;;;###autoload
6955 (defun org-run-like-in-org-mode (cmd)
6956 "Run a command, pretending that the current buffer is in Org-mode.
6957 This will temporarily bind local variables that are typically bound in
6958 Org-mode to the values they have in Org-mode, and then interactively
6959 call CMD."
6960 (org-load-modules-maybe)
6961 (unless org-local-vars
6962 (setq org-local-vars (org-get-local-variables)))
6963 (eval (list 'let org-local-vars
6964 (list 'call-interactively (list 'quote cmd)))))
6966 ;;;; Archiving
6968 (defun org-get-category (&optional pos)
6969 "Get the category applying to position POS."
6970 (get-text-property (or pos (point)) 'org-category))
6972 (defun org-refresh-category-properties ()
6973 "Refresh category text properties in the buffer."
6974 (let ((def-cat (cond
6975 ((null org-category)
6976 (if buffer-file-name
6977 (file-name-sans-extension
6978 (file-name-nondirectory buffer-file-name))
6979 "???"))
6980 ((symbolp org-category) (symbol-name org-category))
6981 (t org-category)))
6982 beg end cat pos optionp)
6983 (org-unmodified
6984 (save-excursion
6985 (save-restriction
6986 (widen)
6987 (goto-char (point-min))
6988 (put-text-property (point) (point-max) 'org-category def-cat)
6989 (while (re-search-forward
6990 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6991 (setq pos (match-end 0)
6992 optionp (equal (char-after (match-beginning 0)) ?#)
6993 cat (org-trim (match-string 2)))
6994 (if optionp
6995 (setq beg (point-at-bol) end (point-max))
6996 (org-back-to-heading t)
6997 (setq beg (point) end (org-end-of-subtree t t)))
6998 (put-text-property beg end 'org-category cat)
6999 (goto-char pos)))))))
7002 ;;;; Link Stuff
7004 ;;; Link abbreviations
7006 (defun org-link-expand-abbrev (link)
7007 "Apply replacements as defined in `org-link-abbrev-alist."
7008 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7009 (let* ((key (match-string 1 link))
7010 (as (or (assoc key org-link-abbrev-alist-local)
7011 (assoc key org-link-abbrev-alist)))
7012 (tag (and (match-end 2) (match-string 3 link)))
7013 rpl)
7014 (if (not as)
7015 link
7016 (setq rpl (cdr as))
7017 (cond
7018 ((symbolp rpl) (funcall rpl tag))
7019 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7020 ((string-match "%h" rpl)
7021 (replace-match (url-hexify-string (or tag "")) t t rpl))
7022 (t (concat rpl tag)))))
7023 link))
7025 ;;; Storing and inserting links
7027 (defvar org-insert-link-history nil
7028 "Minibuffer history for links inserted with `org-insert-link'.")
7030 (defvar org-stored-links nil
7031 "Contains the links stored with `org-store-link'.")
7033 (defvar org-store-link-plist nil
7034 "Plist with info about the most recently link created with `org-store-link'.")
7036 (defvar org-link-protocols nil
7037 "Link protocols added to Org-mode using `org-add-link-type'.")
7039 (defvar org-store-link-functions nil
7040 "List of functions that are called to create and store a link.
7041 Each function will be called in turn until one returns a non-nil
7042 value. Each function should check if it is responsible for creating
7043 this link (for example by looking at the major mode).
7044 If not, it must exit and return nil.
7045 If yes, it should return a non-nil value after a calling
7046 `org-store-link-props' with a list of properties and values.
7047 Special properties are:
7049 :type The link prefix. like \"http\". This must be given.
7050 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7051 This is obligatory as well.
7052 :description Optional default description for the second pair
7053 of brackets in an Org-mode link. The user can still change
7054 this when inserting this link into an Org-mode buffer.
7056 In addition to these, any additional properties can be specified
7057 and then used in remember templates.")
7059 (defun org-add-link-type (type &optional follow export)
7060 "Add TYPE to the list of `org-link-types'.
7061 Re-compute all regular expressions depending on `org-link-types'
7063 FOLLOW and EXPORT are two functions.
7065 FOLLOW should take the link path as the single argument and do whatever
7066 is necessary to follow the link, for example find a file or display
7067 a mail message.
7069 EXPORT should format the link path for export to one of the export formats.
7070 It should be a function accepting three arguments:
7072 path the path of the link, the text after the prefix (like \"http:\")
7073 desc the description of the link, if any, nil if there was no description
7074 format the export format, a symbol like `html' or `latex'.
7076 The function may use the FORMAT information to return different values
7077 depending on the format. The return value will be put literally into
7078 the exported file.
7079 Org-mode has a built-in default for exporting links. If you are happy with
7080 this default, there is no need to define an export function for the link
7081 type. For a simple example of an export function, see `org-bbdb.el'."
7082 (add-to-list 'org-link-types type t)
7083 (org-make-link-regexps)
7084 (if (assoc type org-link-protocols)
7085 (setcdr (assoc type org-link-protocols) (list follow export))
7086 (push (list type follow export) org-link-protocols)))
7088 ;;;###autoload
7089 (defun org-store-link (arg)
7090 "\\<org-mode-map>Store an org-link to the current location.
7091 This link is added to `org-stored-links' and can later be inserted
7092 into an org-buffer with \\[org-insert-link].
7094 For some link types, a prefix arg is interpreted:
7095 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7096 For file links, arg negates `org-context-in-file-links'."
7097 (interactive "P")
7098 (org-load-modules-maybe)
7099 (setq org-store-link-plist nil) ; reset
7100 (let ((outline-regexp (org-get-limited-outline-regexp))
7101 link cpltxt desc description search txt custom-id)
7102 (cond
7104 ((run-hook-with-args-until-success 'org-store-link-functions)
7105 (setq link (plist-get org-store-link-plist :link)
7106 desc (or (plist-get org-store-link-plist :description) link)))
7108 ((equal (buffer-name) "*Org Edit Src Example*")
7109 (let (label gc)
7110 (while (or (not label)
7111 (save-excursion
7112 (save-restriction
7113 (widen)
7114 (goto-char (point-min))
7115 (re-search-forward
7116 (regexp-quote (format org-coderef-label-format label))
7117 nil t))))
7118 (when label (message "Label exists already") (sit-for 2))
7119 (setq label (read-string "Code line label: " label)))
7120 (end-of-line 1)
7121 (setq link (format org-coderef-label-format label))
7122 (setq gc (- 79 (length link)))
7123 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7124 (insert link)
7125 (setq link (concat "(" label ")") desc nil)))
7127 ((eq major-mode 'calendar-mode)
7128 (let ((cd (calendar-cursor-to-date)))
7129 (setq link
7130 (format-time-string
7131 (car org-time-stamp-formats)
7132 (apply 'encode-time
7133 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7134 nil nil nil))))
7135 (org-store-link-props :type "calendar" :date cd)))
7137 ((eq major-mode 'w3-mode)
7138 (setq cpltxt (if (and (buffer-name)
7139 (not (string-match "Untitled" (buffer-name))))
7140 (buffer-name)
7141 (url-view-url t))
7142 link (org-make-link (url-view-url t)))
7143 (org-store-link-props :type "w3" :url (url-view-url t)))
7145 ((eq major-mode 'w3m-mode)
7146 (setq cpltxt (or w3m-current-title w3m-current-url)
7147 link (org-make-link w3m-current-url))
7148 (org-store-link-props :type "w3m" :url (url-view-url t)))
7150 ((setq search (run-hook-with-args-until-success
7151 'org-create-file-search-functions))
7152 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7153 "::" search))
7154 (setq cpltxt (or description link)))
7156 ((eq major-mode 'image-mode)
7157 (setq cpltxt (concat "file:"
7158 (abbreviate-file-name buffer-file-name))
7159 link (org-make-link cpltxt))
7160 (org-store-link-props :type "image" :file buffer-file-name))
7162 ((eq major-mode 'dired-mode)
7163 ;; link to the file in the current line
7164 (setq cpltxt (concat "file:"
7165 (abbreviate-file-name
7166 (expand-file-name
7167 (dired-get-filename nil t))))
7168 link (org-make-link cpltxt)))
7170 ((and buffer-file-name (org-mode-p))
7171 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7172 (cond
7173 ((org-in-regexp "<<\\(.*?\\)>>")
7174 (setq cpltxt
7175 (concat "file:"
7176 (abbreviate-file-name buffer-file-name)
7177 "::" (match-string 1))
7178 link (org-make-link cpltxt)))
7179 ((and (featurep 'org-id)
7180 (or (eq org-link-to-org-use-id t)
7181 (and (eq org-link-to-org-use-id 'create-if-interactive)
7182 (interactive-p))
7183 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7184 (interactive-p)
7185 (not custom-id))
7186 (and org-link-to-org-use-id
7187 (condition-case nil
7188 (org-entry-get nil "ID")
7189 (error nil)))))
7190 ;; We can make a link using the ID.
7191 (setq link (condition-case nil
7192 (prog1 (org-id-store-link)
7193 (setq desc (plist-get org-store-link-plist
7194 :description)))
7195 (error
7196 ;; probably before first headline, link to file only
7197 (concat "file:"
7198 (abbreviate-file-name buffer-file-name))))))
7200 ;; Just link to current headline
7201 (setq cpltxt (concat "file:"
7202 (abbreviate-file-name buffer-file-name)))
7203 ;; Add a context search string
7204 (when (org-xor org-context-in-file-links arg)
7205 (setq txt (cond
7206 ((org-on-heading-p) nil)
7207 ((org-region-active-p)
7208 (buffer-substring (region-beginning) (region-end)))
7209 (t nil)))
7210 (when (or (null txt) (string-match "\\S-" txt))
7211 (setq cpltxt
7212 (concat cpltxt "::"
7213 (condition-case nil
7214 (org-make-org-heading-search-string txt)
7215 (error "")))
7216 desc (or (nth 4 (org-heading-components)) "NONE"))))
7217 (if (string-match "::\\'" cpltxt)
7218 (setq cpltxt (substring cpltxt 0 -2)))
7219 (setq link (org-make-link cpltxt)))))
7221 ((buffer-file-name (buffer-base-buffer))
7222 ;; Just link to this file here.
7223 (setq cpltxt (concat "file:"
7224 (abbreviate-file-name
7225 (buffer-file-name (buffer-base-buffer)))))
7226 ;; Add a context string
7227 (when (org-xor org-context-in-file-links arg)
7228 (setq txt (if (org-region-active-p)
7229 (buffer-substring (region-beginning) (region-end))
7230 (buffer-substring (point-at-bol) (point-at-eol))))
7231 ;; Only use search option if there is some text.
7232 (when (string-match "\\S-" txt)
7233 (setq cpltxt
7234 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7235 desc "NONE")))
7236 (setq link (org-make-link cpltxt)))
7238 ((interactive-p)
7239 (error "Cannot link to a buffer which is not visiting a file"))
7241 (t (setq link nil)))
7243 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7244 (setq link (or link cpltxt)
7245 desc (or desc cpltxt))
7246 (if (equal desc "NONE") (setq desc nil))
7248 (if (and (or (interactive-p) executing-kbd-macro) link)
7249 (progn
7250 (setq org-stored-links
7251 (cons (list link desc) org-stored-links))
7252 (message "Stored: %s" (or desc link))
7253 (when custom-id
7254 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7255 "::#" custom-id))
7256 (setq org-stored-links
7257 (cons (list link desc) org-stored-links))))
7258 (and link (org-make-link-string link desc)))))
7260 (defun org-store-link-props (&rest plist)
7261 "Store link properties, extract names and addresses."
7262 (let (x adr)
7263 (when (setq x (plist-get plist :from))
7264 (setq adr (mail-extract-address-components x))
7265 (setq plist (plist-put plist :fromname (car adr)))
7266 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7267 (when (setq x (plist-get plist :to))
7268 (setq adr (mail-extract-address-components x))
7269 (setq plist (plist-put plist :toname (car adr)))
7270 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7271 (let ((from (plist-get plist :from))
7272 (to (plist-get plist :to)))
7273 (when (and from to org-from-is-user-regexp)
7274 (setq plist
7275 (plist-put plist :fromto
7276 (if (string-match org-from-is-user-regexp from)
7277 (concat "to %t")
7278 (concat "from %f"))))))
7279 (setq org-store-link-plist plist))
7281 (defun org-add-link-props (&rest plist)
7282 "Add these properties to the link property list."
7283 (let (key value)
7284 (while plist
7285 (setq key (pop plist) value (pop plist))
7286 (setq org-store-link-plist
7287 (plist-put org-store-link-plist key value)))))
7289 (defun org-email-link-description (&optional fmt)
7290 "Return the description part of an email link.
7291 This takes information from `org-store-link-plist' and formats it
7292 according to FMT (default from `org-email-link-description-format')."
7293 (setq fmt (or fmt org-email-link-description-format))
7294 (let* ((p org-store-link-plist)
7295 (to (plist-get p :toaddress))
7296 (from (plist-get p :fromaddress))
7297 (table
7298 (list
7299 (cons "%c" (plist-get p :fromto))
7300 (cons "%F" (plist-get p :from))
7301 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7302 (cons "%T" (plist-get p :to))
7303 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7304 (cons "%s" (plist-get p :subject))
7305 (cons "%m" (plist-get p :message-id)))))
7306 (when (string-match "%c" fmt)
7307 ;; Check if the user wrote this message
7308 (if (and org-from-is-user-regexp from to
7309 (save-match-data (string-match org-from-is-user-regexp from)))
7310 (setq fmt (replace-match "to %t" t t fmt))
7311 (setq fmt (replace-match "from %f" t t fmt))))
7312 (org-replace-escapes fmt table)))
7314 (defun org-make-org-heading-search-string (&optional string heading)
7315 "Make search string for STRING or current headline."
7316 (interactive)
7317 (let ((s (or string (org-get-heading))))
7318 (unless (and string (not heading))
7319 ;; We are using a headline, clean up garbage in there.
7320 (if (string-match org-todo-regexp s)
7321 (setq s (replace-match "" t t s)))
7322 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7323 (setq s (replace-match "" t t s)))
7324 (setq s (org-trim s))
7325 (if (string-match (concat "^\\(" org-quote-string "\\|"
7326 org-comment-string "\\)") s)
7327 (setq s (replace-match "" t t s)))
7328 (while (string-match org-ts-regexp s)
7329 (setq s (replace-match "" t t s))))
7330 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7331 (setq s (replace-match " " t t s)))
7332 (or string (setq s (concat "*" s))) ; Add * for headlines
7333 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7335 (defun org-make-link (&rest strings)
7336 "Concatenate STRINGS."
7337 (apply 'concat strings))
7339 (defun org-make-link-string (link &optional description)
7340 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7341 (unless (string-match "\\S-" link)
7342 (error "Empty link"))
7343 (when (stringp description)
7344 ;; Remove brackets from the description, they are fatal.
7345 (while (string-match "\\[" description)
7346 (setq description (replace-match "{" t t description)))
7347 (while (string-match "\\]" description)
7348 (setq description (replace-match "}" t t description))))
7349 (when (equal (org-link-escape link) description)
7350 ;; No description needed, it is identical
7351 (setq description nil))
7352 (when (and (not description)
7353 (not (equal link (org-link-escape link))))
7354 (setq description (org-extract-attributes link)))
7355 (concat "[[" (org-link-escape link) "]"
7356 (if description (concat "[" description "]") "")
7357 "]"))
7359 (defconst org-link-escape-chars
7360 '((?\ . "%20")
7361 (?\[ . "%5B")
7362 (?\] . "%5D")
7363 (?\340 . "%E0") ; `a
7364 (?\342 . "%E2") ; ^a
7365 (?\347 . "%E7") ; ,c
7366 (?\350 . "%E8") ; `e
7367 (?\351 . "%E9") ; 'e
7368 (?\352 . "%EA") ; ^e
7369 (?\356 . "%EE") ; ^i
7370 (?\364 . "%F4") ; ^o
7371 (?\371 . "%F9") ; `u
7372 (?\373 . "%FB") ; ^u
7373 (?\; . "%3B")
7374 (?? . "%3F")
7375 (?= . "%3D")
7376 (?+ . "%2B")
7378 "Association list of escapes for some characters problematic in links.
7379 This is the list that is used for internal purposes.")
7381 (defvar org-url-encoding-use-url-hexify nil)
7383 (defconst org-link-escape-chars-browser
7384 '((?\ . "%20")) ; 32 for the SPC char
7385 "Association list of escapes for some characters problematic in links.
7386 This is the list that is used before handing over to the browser.")
7388 (defun org-link-escape (text &optional table)
7389 "Escape characters in TEXT that are problematic for links."
7390 (if org-url-encoding-use-url-hexify
7391 (url-hexify-string text)
7392 (setq table (or table org-link-escape-chars))
7393 (when text
7394 (let ((re (mapconcat (lambda (x) (regexp-quote
7395 (char-to-string (car x))))
7396 table "\\|")))
7397 (while (string-match re text)
7398 (setq text
7399 (replace-match
7400 (cdr (assoc (string-to-char (match-string 0 text))
7401 table))
7402 t t text)))
7403 text))))
7405 (defun org-link-unescape (text &optional table)
7406 "Reverse the action of `org-link-escape'."
7407 (if org-url-encoding-use-url-hexify
7408 (url-unhex-string text)
7409 (setq table (or table org-link-escape-chars))
7410 (when text
7411 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7412 table "\\|")))
7413 (while (string-match re text)
7414 (setq text
7415 (replace-match
7416 (char-to-string (car (rassoc (match-string 0 text) table)))
7417 t t text)))
7418 text))))
7420 (defun org-xor (a b)
7421 "Exclusive or."
7422 (if a (not b) b))
7424 (defun org-fixup-message-id-for-http (s)
7425 "Replace special characters in a message id, so it can be used in an http query."
7426 (while (string-match "<" s)
7427 (setq s (replace-match "%3C" t t s)))
7428 (while (string-match ">" s)
7429 (setq s (replace-match "%3E" t t s)))
7430 (while (string-match "@" s)
7431 (setq s (replace-match "%40" t t s)))
7434 ;;;###autoload
7435 (defun org-insert-link-global ()
7436 "Insert a link like Org-mode does.
7437 This command can be called in any mode to insert a link in Org-mode syntax."
7438 (interactive)
7439 (org-load-modules-maybe)
7440 (org-run-like-in-org-mode 'org-insert-link))
7442 (defun org-insert-link (&optional complete-file link-location)
7443 "Insert a link. At the prompt, enter the link.
7445 Completion can be used to insert any of the link protocol prefixes like
7446 http or ftp in use.
7448 The history can be used to select a link previously stored with
7449 `org-store-link'. When the empty string is entered (i.e. if you just
7450 press RET at the prompt), the link defaults to the most recently
7451 stored link. As SPC triggers completion in the minibuffer, you need to
7452 use M-SPC or C-q SPC to force the insertion of a space character.
7454 You will also be prompted for a description, and if one is given, it will
7455 be displayed in the buffer instead of the link.
7457 If there is already a link at point, this command will allow you to edit link
7458 and description parts.
7460 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7461 be selected using completion. The path to the file will be relative to the
7462 current directory if the file is in the current directory or a subdirectory.
7463 Otherwise, the link will be the absolute path as completed in the minibuffer
7464 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7465 option `org-link-file-path-type'.
7467 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7468 the current directory or below.
7470 With three \\[universal-argument] prefixes, negate the meaning of
7471 `org-keep-stored-link-after-insertion'.
7473 If `org-make-link-description-function' is non-nil, this function will be
7474 called with the link target, and the result will be the default
7475 link description.
7477 If the LINK-LOCATION parameter is non-nil, this value will be
7478 used as the link location instead of reading one interactively."
7479 (interactive "P")
7480 (let* ((wcf (current-window-configuration))
7481 (region (if (org-region-active-p)
7482 (buffer-substring (region-beginning) (region-end))))
7483 (remove (and region (list (region-beginning) (region-end))))
7484 (desc region)
7485 tmphist ; byte-compile incorrectly complains about this
7486 (link link-location)
7487 entry file all-prefixes)
7488 (cond
7489 (link-location) ; specified by arg, just use it.
7490 ((org-in-regexp org-bracket-link-regexp 1)
7491 ;; We do have a link at point, and we are going to edit it.
7492 (setq remove (list (match-beginning 0) (match-end 0)))
7493 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7494 (setq link (read-string "Link: "
7495 (org-link-unescape
7496 (org-match-string-no-properties 1)))))
7497 ((or (org-in-regexp org-angle-link-re)
7498 (org-in-regexp org-plain-link-re))
7499 ;; Convert to bracket link
7500 (setq remove (list (match-beginning 0) (match-end 0))
7501 link (read-string "Link: "
7502 (org-remove-angle-brackets (match-string 0)))))
7503 ((member complete-file '((4) (16)))
7504 ;; Completing read for file names.
7505 (setq link (org-file-complete-link complete-file)))
7507 ;; Read link, with completion for stored links.
7508 (with-output-to-temp-buffer "*Org Links*"
7509 (princ "Insert a link.
7510 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
7511 (when org-stored-links
7512 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7513 (princ (mapconcat
7514 (lambda (x)
7515 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7516 (reverse org-stored-links) "\n"))))
7517 (let ((cw (selected-window)))
7518 (select-window (get-buffer-window "*Org Links*"))
7519 (setq truncate-lines t)
7520 (unless (pos-visible-in-window-p (point-max))
7521 (org-fit-window-to-buffer))
7522 (and (window-live-p cw) (select-window cw)))
7523 ;; Fake a link history, containing the stored links.
7524 (setq tmphist (append (mapcar 'car org-stored-links)
7525 org-insert-link-history))
7526 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
7527 (mapcar 'car org-link-abbrev-alist)
7528 org-link-types))
7529 (unwind-protect
7530 (progn
7531 (setq link
7532 (let ((org-completion-use-ido nil))
7533 (org-completing-read
7534 "Link: "
7535 (append
7536 (mapcar (lambda (x) (list (concat x ":")))
7537 all-prefixes)
7538 (mapcar 'car org-stored-links))
7539 nil nil nil
7540 'tmphist
7541 (car (car org-stored-links)))))
7542 (if (or (member link all-prefixes)
7543 (and (equal ":" (substring link -1))
7544 (member (substring link 0 -1) all-prefixes)
7545 (setq link (substring link 0 -1))))
7546 (setq link (org-link-try-special-completion link))))
7547 (set-window-configuration wcf)
7548 (kill-buffer "*Org Links*"))
7549 (setq entry (assoc link org-stored-links))
7550 (or entry (push link org-insert-link-history))
7551 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7552 (not org-keep-stored-link-after-insertion))
7553 (setq org-stored-links (delq (assoc link org-stored-links)
7554 org-stored-links)))
7555 (setq desc (or desc (nth 1 entry)))))
7557 (if (string-match org-plain-link-re link)
7558 ;; URL-like link, normalize the use of angular brackets.
7559 (setq link (org-make-link (org-remove-angle-brackets link))))
7561 ;; Check if we are linking to the current file with a search option
7562 ;; If yes, simplify the link by using only the search option.
7563 (when (and buffer-file-name
7564 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7565 (let* ((path (match-string 1 link))
7566 (case-fold-search nil)
7567 (search (match-string 2 link)))
7568 (save-match-data
7569 (if (equal (file-truename buffer-file-name) (file-truename path))
7570 ;; We are linking to this same file, with a search option
7571 (setq link search)))))
7573 ;; Check if we can/should use a relative path. If yes, simplify the link
7574 (when (string-match "^file:\\(.*\\)" link)
7575 (let* ((path (match-string 1 link))
7576 (origpath path)
7577 (case-fold-search nil))
7578 (cond
7579 ((or (eq org-link-file-path-type 'absolute)
7580 (equal complete-file '(16)))
7581 (setq path (abbreviate-file-name (expand-file-name path))))
7582 ((eq org-link-file-path-type 'noabbrev)
7583 (setq path (expand-file-name path)))
7584 ((eq org-link-file-path-type 'relative)
7585 (setq path (file-relative-name path)))
7587 (save-match-data
7588 (if (string-match (concat "^" (regexp-quote
7589 (file-name-as-directory
7590 (expand-file-name "."))))
7591 (expand-file-name path))
7592 ;; We are linking a file with relative path name.
7593 (setq path (substring (expand-file-name path)
7594 (match-end 0)))
7595 (setq path (abbreviate-file-name (expand-file-name path)))))))
7596 (setq link (concat "file:" path))
7597 (if (equal desc origpath)
7598 (setq desc path))))
7600 (if org-make-link-description-function
7601 (setq desc (funcall org-make-link-description-function link desc)))
7603 (setq desc (read-string "Description: " desc))
7604 (unless (string-match "\\S-" desc) (setq desc nil))
7605 (if remove (apply 'delete-region remove))
7606 (insert (org-make-link-string link desc))))
7608 (defun org-link-try-special-completion (type)
7609 "If there is completion support for link type TYPE, offer it."
7610 (let ((fun (intern (concat "org-" type "-complete-link"))))
7611 (if (functionp fun)
7612 (funcall fun)
7613 (read-string "Link (no completion support): " (concat type ":")))))
7615 (defun org-file-complete-link (&optional arg)
7616 "Create a file link using completion."
7617 (let (file link)
7618 (setq file (read-file-name "File: "))
7619 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7620 (pwd1 (file-name-as-directory (abbreviate-file-name
7621 (expand-file-name ".")))))
7622 (cond
7623 ((equal arg '(16))
7624 (setq link (org-make-link
7625 "file:"
7626 (abbreviate-file-name (expand-file-name file)))))
7627 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7628 (setq link (org-make-link "file:" (match-string 1 file))))
7629 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7630 (expand-file-name file))
7631 (setq link (org-make-link
7632 "file:" (match-string 1 (expand-file-name file)))))
7633 (t (setq link (org-make-link "file:" file)))))
7634 link))
7636 (defun org-completing-read (&rest args)
7637 "Completing-read with SPACE being a normal character."
7638 (let ((minibuffer-local-completion-map
7639 (copy-keymap minibuffer-local-completion-map)))
7640 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7641 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7642 (apply 'org-ido-completing-read args)))
7644 (defun org-completing-read-no-ido (&rest args)
7645 (let (org-completion-use-ido)
7646 (apply 'org-completing-read args)))
7648 (defun org-ido-completing-read (&rest args)
7649 "Completing-read using `ido-mode' speedups if available"
7650 (if (and org-completion-use-ido
7651 (fboundp 'ido-completing-read)
7652 (boundp 'ido-mode) ido-mode
7653 (listp (second args)))
7654 (let ((ido-enter-matching-directory nil))
7655 (apply 'ido-completing-read (concat (car args))
7656 (if (consp (car (nth 1 args)))
7657 (mapcar (lambda (x) (car x)) (nth 1 args))
7658 (nth 1 args))
7659 (cddr args)))
7660 (apply 'completing-read args)))
7662 (defun org-extract-attributes (s)
7663 "Extract the attributes cookie from a string and set as text property."
7664 (let (a attr (start 0) key value)
7665 (save-match-data
7666 (when (string-match "{{\\([^}]+\\)}}$" s)
7667 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7668 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7669 (setq key (match-string 1 a) value (match-string 2 a)
7670 start (match-end 0)
7671 attr (plist-put attr (intern key) value))))
7672 (org-add-props s nil 'org-attr attr))
7675 (defun org-extract-attributes-from-string (tag)
7676 (let (key value attr)
7677 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
7678 (setq key (match-string 1 tag) value (match-string 2 tag)
7679 tag (replace-match "" t t tag)
7680 attr (plist-put attr (intern key) value)))
7681 (cons tag attr)))
7683 (defun org-attributes-to-string (plist)
7684 "Format a property list into an HTML attribute list."
7685 (let ((s "") key value)
7686 (while plist
7687 (setq key (pop plist) value (pop plist))
7688 (and value
7689 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7692 ;;; Opening/following a link
7694 (defvar org-link-search-failed nil)
7696 (defun org-next-link ()
7697 "Move forward to the next link.
7698 If the link is in hidden text, expose it."
7699 (interactive)
7700 (when (and org-link-search-failed (eq this-command last-command))
7701 (goto-char (point-min))
7702 (message "Link search wrapped back to beginning of buffer"))
7703 (setq org-link-search-failed nil)
7704 (let* ((pos (point))
7705 (ct (org-context))
7706 (a (assoc :link ct)))
7707 (if a (goto-char (nth 2 a)))
7708 (if (re-search-forward org-any-link-re nil t)
7709 (progn
7710 (goto-char (match-beginning 0))
7711 (if (org-invisible-p) (org-show-context)))
7712 (goto-char pos)
7713 (setq org-link-search-failed t)
7714 (error "No further link found"))))
7716 (defun org-previous-link ()
7717 "Move backward to the previous link.
7718 If the link is in hidden text, expose it."
7719 (interactive)
7720 (when (and org-link-search-failed (eq this-command last-command))
7721 (goto-char (point-max))
7722 (message "Link search wrapped back to end of buffer"))
7723 (setq org-link-search-failed nil)
7724 (let* ((pos (point))
7725 (ct (org-context))
7726 (a (assoc :link ct)))
7727 (if a (goto-char (nth 1 a)))
7728 (if (re-search-backward org-any-link-re nil t)
7729 (progn
7730 (goto-char (match-beginning 0))
7731 (if (org-invisible-p) (org-show-context)))
7732 (goto-char pos)
7733 (setq org-link-search-failed t)
7734 (error "No further link found"))))
7736 (defun org-translate-link (s)
7737 "Translate a link string if a translation function has been defined."
7738 (if (and org-link-translation-function
7739 (fboundp org-link-translation-function)
7740 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7741 (progn
7742 (setq s (funcall org-link-translation-function
7743 (match-string 1) (match-string 2)))
7744 (concat (car s) ":" (cdr s)))
7747 (defun org-translate-link-from-planner (type path)
7748 "Translate a link from Emacs Planner syntax so that Org can follow it.
7749 This is still an experimental function, your mileage may vary."
7750 (cond
7751 ((member type '("http" "https" "news" "ftp"))
7752 ;; standard Internet links are the same.
7753 nil)
7754 ((and (equal type "irc") (string-match "^//" path))
7755 ;; Planner has two / at the beginning of an irc link, we have 1.
7756 ;; We should have zero, actually....
7757 (setq path (substring path 1)))
7758 ((and (equal type "lisp") (string-match "^/" path))
7759 ;; Planner has a slash, we do not.
7760 (setq type "elisp" path (substring path 1)))
7761 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7762 ;; A typical message link. Planner has the id after the fina slash,
7763 ;; we separate it with a hash mark
7764 (setq path (concat (match-string 1 path) "#"
7765 (org-remove-angle-brackets (match-string 2 path)))))
7767 (cons type path))
7769 (defun org-find-file-at-mouse (ev)
7770 "Open file link or URL at mouse."
7771 (interactive "e")
7772 (mouse-set-point ev)
7773 (org-open-at-point 'in-emacs))
7775 (defun org-open-at-mouse (ev)
7776 "Open file link or URL at mouse."
7777 (interactive "e")
7778 (mouse-set-point ev)
7779 (if (eq major-mode 'org-agenda-mode)
7780 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7781 (org-open-at-point))
7783 (defvar org-window-config-before-follow-link nil
7784 "The window configuration before following a link.
7785 This is saved in case the need arises to restore it.")
7787 (defvar org-open-link-marker (make-marker)
7788 "Marker pointing to the location where `org-open-at-point; was called.")
7790 ;;;###autoload
7791 (defun org-open-at-point-global ()
7792 "Follow a link like Org-mode does.
7793 This command can be called in any mode to follow a link that has
7794 Org-mode syntax."
7795 (interactive)
7796 (org-run-like-in-org-mode 'org-open-at-point))
7798 ;;;###autoload
7799 (defun org-open-link-from-string (s &optional arg)
7800 "Open a link in the string S, as if it was in Org-mode."
7801 (interactive "sLink: \nP")
7802 (let ((reference-buffer (current-buffer)))
7803 (with-temp-buffer
7804 (let ((org-inhibit-startup t))
7805 (org-mode)
7806 (insert s)
7807 (goto-char (point-min))
7808 (org-open-at-point arg reference-buffer)))))
7810 (defun org-open-at-point (&optional in-emacs reference-buffer)
7811 "Open link at or after point.
7812 If there is no link at point, this function will search forward up to
7813 the end of the current line.
7814 Normally, files will be opened by an appropriate application. If the
7815 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7816 With a double prefix argument, try to open outside of Emacs, in the
7817 application the system uses for this file type."
7818 (interactive "P")
7819 (org-load-modules-maybe)
7820 (move-marker org-open-link-marker (point))
7821 (setq org-window-config-before-follow-link (current-window-configuration))
7822 (org-remove-occur-highlights nil nil t)
7823 (cond
7824 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7825 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7826 (org-footnote-action))
7828 (let (type path link line search (pos (point)))
7829 (catch 'match
7830 (save-excursion
7831 (skip-chars-forward "^]\n\r")
7832 (when (org-in-regexp org-bracket-link-regexp)
7833 (setq link (org-extract-attributes
7834 (org-link-unescape (org-match-string-no-properties 1))))
7835 (while (string-match " *\n *" link)
7836 (setq link (replace-match " " t t link)))
7837 (setq link (org-link-expand-abbrev link))
7838 (cond
7839 ((or (file-name-absolute-p link)
7840 (string-match "^\\.\\.?/" link))
7841 (setq type "file" path link))
7842 ((string-match org-link-re-with-space3 link)
7843 (setq type (match-string 1 link) path (match-string 2 link)))
7844 (t (setq type "thisfile" path link)))
7845 (throw 'match t)))
7847 (when (get-text-property (point) 'org-linked-text)
7848 (setq type "thisfile"
7849 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7850 (1+ (point)) (point))
7851 path (buffer-substring
7852 (previous-single-property-change pos 'org-linked-text)
7853 (next-single-property-change pos 'org-linked-text)))
7854 (throw 'match t))
7856 (save-excursion
7857 (when (or (org-in-regexp org-angle-link-re)
7858 (org-in-regexp org-plain-link-re))
7859 (setq type (match-string 1) path (match-string 2))
7860 (throw 'match t)))
7861 (save-excursion
7862 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7863 (setq type "tags"
7864 path (match-string 1))
7865 (while (string-match ":" path)
7866 (setq path (replace-match "+" t t path)))
7867 (throw 'match t)))
7868 (when (org-in-regexp "<\\([^><\n]+\\)>")
7869 (setq type "tree-match"
7870 path (match-string 1))
7871 (throw 'match t)))
7872 (unless path
7873 (error "No link found"))
7875 ;; switch back to reference buffer
7876 ;; needed when if called in a temporary buffer through
7877 ;; org-open-link-from-string
7878 (and reference-buffer (switch-to-buffer reference-buffer))
7880 ;; Remove any trailing spaces in path
7881 (if (string-match " +\\'" path)
7882 (setq path (replace-match "" t t path)))
7883 (if (and org-link-translation-function
7884 (fboundp org-link-translation-function))
7885 ;; Check if we need to translate the link
7886 (let ((tmp (funcall org-link-translation-function type path)))
7887 (setq type (car tmp) path (cdr tmp))))
7889 (cond
7891 ((assoc type org-link-protocols)
7892 (funcall (nth 1 (assoc type org-link-protocols)) path))
7894 ((equal type "mailto")
7895 (let ((cmd (car org-link-mailto-program))
7896 (args (cdr org-link-mailto-program)) args1
7897 (address path) (subject "") a)
7898 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7899 (setq address (match-string 1 path)
7900 subject (org-link-escape (match-string 2 path))))
7901 (while args
7902 (cond
7903 ((not (stringp (car args))) (push (pop args) args1))
7904 (t (setq a (pop args))
7905 (if (string-match "%a" a)
7906 (setq a (replace-match address t t a)))
7907 (if (string-match "%s" a)
7908 (setq a (replace-match subject t t a)))
7909 (push a args1))))
7910 (apply cmd (nreverse args1))))
7912 ((member type '("http" "https" "ftp" "news"))
7913 (browse-url (concat type ":" (org-link-escape
7914 path org-link-escape-chars-browser))))
7916 ((member type '("message"))
7917 (browse-url (concat type ":" path)))
7919 ((string= type "tags")
7920 (org-tags-view in-emacs path))
7921 ((string= type "thisfile")
7922 (if in-emacs
7923 (switch-to-buffer-other-window
7924 (org-get-buffer-for-internal-link (current-buffer)))
7925 (org-mark-ring-push))
7926 (let ((cmd `(org-link-search
7927 ,path
7928 ,(cond ((equal in-emacs '(4)) 'occur)
7929 ((equal in-emacs '(16)) 'org-occur)
7930 (t nil))
7931 ,pos)))
7932 (condition-case nil (eval cmd)
7933 (error (progn (widen) (eval cmd))))))
7935 ((string= type "tree-match")
7936 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7938 ((string= type "file")
7939 (if (string-match "::\\([0-9]+\\)\\'" path)
7940 (setq line (string-to-number (match-string 1 path))
7941 path (substring path 0 (match-beginning 0)))
7942 (if (string-match "::\\(.+\\)\\'" path)
7943 (setq search (match-string 1 path)
7944 path (substring path 0 (match-beginning 0)))))
7945 (if (string-match "[*?{]" (file-name-nondirectory path))
7946 (dired path)
7947 (org-open-file path in-emacs line search)))
7949 ((string= type "news")
7950 (require 'org-gnus)
7951 (org-gnus-follow-link path))
7953 ((string= type "shell")
7954 (let ((cmd path))
7955 (if (or (not org-confirm-shell-link-function)
7956 (funcall org-confirm-shell-link-function
7957 (format "Execute \"%s\" in shell? "
7958 (org-add-props cmd nil
7959 'face 'org-warning))))
7960 (progn
7961 (message "Executing %s" cmd)
7962 (shell-command cmd))
7963 (error "Abort"))))
7965 ((string= type "elisp")
7966 (let ((cmd path))
7967 (if (or (not org-confirm-elisp-link-function)
7968 (funcall org-confirm-elisp-link-function
7969 (format "Execute \"%s\" as elisp? "
7970 (org-add-props cmd nil
7971 'face 'org-warning))))
7972 (message "%s => %s" cmd
7973 (if (equal (string-to-char cmd) ?\()
7974 (eval (read cmd))
7975 (call-interactively (read cmd))))
7976 (error "Abort"))))
7979 (browse-url-at-point))))))
7980 (move-marker org-open-link-marker nil)
7981 (run-hook-with-args 'org-follow-link-hook))
7983 ;;;; Time estimates
7985 (defun org-get-effort (&optional pom)
7986 "Get the effort estimate for the current entry."
7987 (org-entry-get pom org-effort-property))
7989 ;;; File search
7991 (defvar org-create-file-search-functions nil
7992 "List of functions to construct the right search string for a file link.
7993 These functions are called in turn with point at the location to
7994 which the link should point.
7996 A function in the hook should first test if it would like to
7997 handle this file type, for example by checking the major-mode or
7998 the file extension. If it decides not to handle this file, it
7999 should just return nil to give other functions a chance. If it
8000 does handle the file, it must return the search string to be used
8001 when following the link. The search string will be part of the
8002 file link, given after a double colon, and `org-open-at-point'
8003 will automatically search for it. If special measures must be
8004 taken to make the search successful, another function should be
8005 added to the companion hook `org-execute-file-search-functions',
8006 which see.
8008 A function in this hook may also use `setq' to set the variable
8009 `description' to provide a suggestion for the descriptive text to
8010 be used for this link when it gets inserted into an Org-mode
8011 buffer with \\[org-insert-link].")
8013 (defvar org-execute-file-search-functions nil
8014 "List of functions to execute a file search triggered by a link.
8016 Functions added to this hook must accept a single argument, the
8017 search string that was part of the file link, the part after the
8018 double colon. The function must first check if it would like to
8019 handle this search, for example by checking the major-mode or the
8020 file extension. If it decides not to handle this search, it
8021 should just return nil to give other functions a chance. If it
8022 does handle the search, it must return a non-nil value to keep
8023 other functions from trying.
8025 Each function can access the current prefix argument through the
8026 variable `current-prefix-argument'. Note that a single prefix is
8027 used to force opening a link in Emacs, so it may be good to only
8028 use a numeric or double prefix to guide the search function.
8030 In case this is needed, a function in this hook can also restore
8031 the window configuration before `org-open-at-point' was called using:
8033 (set-window-configuration org-window-config-before-follow-link)")
8035 (defun org-link-search (s &optional type avoid-pos)
8036 "Search for a link search option.
8037 If S is surrounded by forward slashes, it is interpreted as a
8038 regular expression. In org-mode files, this will create an `org-occur'
8039 sparse tree. In ordinary files, `occur' will be used to list matches.
8040 If the current buffer is in `dired-mode', grep will be used to search
8041 in all files. If AVOID-POS is given, ignore matches near that position."
8042 (let ((case-fold-search t)
8043 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8044 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8045 (append '(("") (" ") ("\t") ("\n"))
8046 org-emphasis-alist)
8047 "\\|") "\\)"))
8048 (pos (point))
8049 (pre nil) (post nil)
8050 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8051 (cond
8052 ;; First check if there are any special
8053 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8054 ;; Now try the builtin stuff
8055 ((and (equal (string-to-char s0) ?#)
8056 (> (length s0) 1)
8057 (save-excursion
8058 (goto-char (point-min))
8059 (and
8060 (re-search-forward
8061 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8062 (setq type 'dedicated
8063 pos (match-beginning 0))))
8064 ;; There is an exact target for this
8065 (goto-char pos)
8066 (org-back-to-heading t)))
8067 ((save-excursion
8068 (goto-char (point-min))
8069 (and
8070 (re-search-forward
8071 (concat "<<" (regexp-quote s0) ">>") nil t)
8072 (setq type 'dedicated
8073 pos (match-beginning 0))))
8074 ;; There is an exact target for this
8075 (goto-char pos))
8076 ((and (string-match "^(\\(.*\\))$" s0)
8077 (save-excursion
8078 (goto-char (point-min))
8079 (and
8080 (re-search-forward
8081 (concat "[^[]" (regexp-quote
8082 (format org-coderef-label-format
8083 (match-string 1 s0))))
8084 nil t)
8085 (setq type 'dedicated
8086 pos (1+ (match-beginning 0))))))
8087 ;; There is a coderef target for this
8088 (goto-char pos))
8089 ((string-match "^/\\(.*\\)/$" s)
8090 ;; A regular expression
8091 (cond
8092 ((org-mode-p)
8093 (org-occur (match-string 1 s)))
8094 ;;((eq major-mode 'dired-mode)
8095 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8096 (t (org-do-occur (match-string 1 s)))))
8098 ;; A normal search strings
8099 (when (equal (string-to-char s) ?*)
8100 ;; Anchor on headlines, post may include tags.
8101 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8102 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8103 s (substring s 1)))
8104 (remove-text-properties
8105 0 (length s)
8106 '(face nil mouse-face nil keymap nil fontified nil) s)
8107 ;; Make a series of regular expressions to find a match
8108 (setq words (org-split-string s "[ \n\r\t]+")
8110 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8111 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8112 "\\)" markers)
8113 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8114 re2a (concat "[ \t\r\n]" re2a_)
8115 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8116 re4 (concat "[^a-zA-Z_]" re4_)
8118 re1 (concat pre re2 post)
8119 re3 (concat pre (if pre re4_ re4) post)
8120 re5 (concat pre ".*" re4)
8121 re2 (concat pre re2)
8122 re2a (concat pre (if pre re2a_ re2a))
8123 re4 (concat pre (if pre re4_ re4))
8124 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8125 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8126 re5 "\\)"
8128 (cond
8129 ((eq type 'org-occur) (org-occur reall))
8130 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8131 (t (goto-char (point-min))
8132 (setq type 'fuzzy)
8133 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8134 (org-search-not-self 1 re1 nil t)
8135 (org-search-not-self 1 re2 nil t)
8136 (org-search-not-self 1 re2a nil t)
8137 (org-search-not-self 1 re3 nil t)
8138 (org-search-not-self 1 re4 nil t)
8139 (org-search-not-self 1 re5 nil t)
8141 (goto-char (match-beginning 1))
8142 (goto-char pos)
8143 (error "No match")))))
8145 ;; Normal string-search
8146 (goto-char (point-min))
8147 (if (search-forward s nil t)
8148 (goto-char (match-beginning 0))
8149 (error "No match"))))
8150 (and (org-mode-p) (org-show-context 'link-search))
8151 type))
8153 (defun org-search-not-self (group &rest args)
8154 "Execute `re-search-forward', but only accept matches that do not
8155 enclose the position of `org-open-link-marker'."
8156 (let ((m org-open-link-marker))
8157 (catch 'exit
8158 (while (apply 're-search-forward args)
8159 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8160 (goto-char (match-end group))
8161 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8162 (> (match-beginning 0) (marker-position m))
8163 (< (match-end 0) (marker-position m)))
8164 (save-match-data
8165 (or (not (org-in-regexp
8166 org-bracket-link-analytic-regexp 1))
8167 (not (match-end 4)) ; no description
8168 (and (<= (match-beginning 4) (point))
8169 (>= (match-end 4) (point))))))
8170 (throw 'exit (point))))))))
8172 (defun org-get-buffer-for-internal-link (buffer)
8173 "Return a buffer to be used for displaying the link target of internal links."
8174 (cond
8175 ((not org-display-internal-link-with-indirect-buffer)
8176 buffer)
8177 ((string-match "(Clone)$" (buffer-name buffer))
8178 (message "Buffer is already a clone, not making another one")
8179 ;; we also do not modify visibility in this case
8180 buffer)
8181 (t ; make a new indirect buffer for displaying the link
8182 (let* ((bn (buffer-name buffer))
8183 (ibn (concat bn "(Clone)"))
8184 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8185 (with-current-buffer ib (org-overview))
8186 ib))))
8188 (defun org-do-occur (regexp &optional cleanup)
8189 "Call the Emacs command `occur'.
8190 If CLEANUP is non-nil, remove the printout of the regular expression
8191 in the *Occur* buffer. This is useful if the regex is long and not useful
8192 to read."
8193 (occur regexp)
8194 (when cleanup
8195 (let ((cwin (selected-window)) win beg end)
8196 (when (setq win (get-buffer-window "*Occur*"))
8197 (select-window win))
8198 (goto-char (point-min))
8199 (when (re-search-forward "match[a-z]+" nil t)
8200 (setq beg (match-end 0))
8201 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8202 (setq end (1- (match-beginning 0)))))
8203 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8204 (goto-char (point-min))
8205 (select-window cwin))))
8207 ;;; The mark ring for links jumps
8209 (defvar org-mark-ring nil
8210 "Mark ring for positions before jumps in Org-mode.")
8211 (defvar org-mark-ring-last-goto nil
8212 "Last position in the mark ring used to go back.")
8213 ;; Fill and close the ring
8214 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8215 (loop for i from 1 to org-mark-ring-length do
8216 (push (make-marker) org-mark-ring))
8217 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8218 org-mark-ring)
8220 (defun org-mark-ring-push (&optional pos buffer)
8221 "Put the current position or POS into the mark ring and rotate it."
8222 (interactive)
8223 (setq pos (or pos (point)))
8224 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8225 (move-marker (car org-mark-ring)
8226 (or pos (point))
8227 (or buffer (current-buffer)))
8228 (message "%s"
8229 (substitute-command-keys
8230 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8232 (defun org-mark-ring-goto (&optional n)
8233 "Jump to the previous position in the mark ring.
8234 With prefix arg N, jump back that many stored positions. When
8235 called several times in succession, walk through the entire ring.
8236 Org-mode commands jumping to a different position in the current file,
8237 or to another Org-mode file, automatically push the old position
8238 onto the ring."
8239 (interactive "p")
8240 (let (p m)
8241 (if (eq last-command this-command)
8242 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8243 (setq p org-mark-ring))
8244 (setq org-mark-ring-last-goto p)
8245 (setq m (car p))
8246 (switch-to-buffer (marker-buffer m))
8247 (goto-char m)
8248 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8250 (defun org-remove-angle-brackets (s)
8251 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8252 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8254 (defun org-add-angle-brackets (s)
8255 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8256 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8258 (defun org-remove-double-quotes (s)
8259 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8260 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8263 ;;; Following specific links
8265 (defun org-follow-timestamp-link ()
8266 (cond
8267 ((org-at-date-range-p t)
8268 (let ((org-agenda-start-on-weekday)
8269 (t1 (match-string 1))
8270 (t2 (match-string 2)))
8271 (setq t1 (time-to-days (org-time-string-to-time t1))
8272 t2 (time-to-days (org-time-string-to-time t2)))
8273 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8274 ((org-at-timestamp-p t)
8275 (org-agenda-list nil (time-to-days (org-time-string-to-time
8276 (substring (match-string 1) 0 10)))
8278 (t (error "This should not happen"))))
8281 ;;; Following file links
8282 (defvar org-wait nil)
8283 (defun org-open-file (path &optional in-emacs line search)
8284 "Open the file at PATH.
8285 First, this expands any special file name abbreviations. Then the
8286 configuration variable `org-file-apps' is checked if it contains an
8287 entry for this file type, and if yes, the corresponding command is launched.
8289 If no application is found, Emacs simply visits the file.
8291 With optional prefix argument IN-EMACS, Emacs will visit the file.
8292 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8293 and o use an external application to visit the file.
8295 Optional LINE specifies a line to go to, optional SEARCH a string to
8296 search for. If LINE or SEARCH is given, the file will always be
8297 opened in Emacs.
8298 If the file does not exist, an error is thrown."
8299 (setq in-emacs (or in-emacs line search))
8300 (let* ((file (if (equal path "")
8301 buffer-file-name
8302 (substitute-in-file-name (expand-file-name path))))
8303 (apps (append org-file-apps (org-default-apps)))
8304 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8305 (dirp (if remp nil (file-directory-p file)))
8306 (file (if (and dirp org-open-directory-means-index-dot-org)
8307 (concat (file-name-as-directory file) "index.org")
8308 file))
8309 (a-m-a-p (assq 'auto-mode apps))
8310 (dfile (downcase file))
8311 (old-buffer (current-buffer))
8312 (old-pos (point))
8313 (old-mode major-mode)
8314 ext cmd)
8315 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8316 (setq ext (match-string 1 dfile))
8317 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8318 (setq ext (match-string 1 dfile))))
8319 (cond
8320 ((equal in-emacs '(16))
8321 (setq cmd (cdr (assoc 'system apps))))
8322 (in-emacs (setq cmd 'emacs))
8324 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8325 (and dirp (cdr (assoc 'directory apps)))
8326 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8327 'string-match)
8328 (cdr (assoc ext apps))
8329 (cdr (assoc t apps))))))
8330 (when (eq cmd 'system)
8331 (setq cmd (cdr (assoc 'system apps))))
8332 (when (eq cmd 'default)
8333 (setq cmd (cdr (assoc t apps))))
8334 (when (eq cmd 'mailcap)
8335 (require 'mailcap)
8336 (mailcap-parse-mailcaps)
8337 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8338 (command (mailcap-mime-info mime-type)))
8339 (if (stringp command)
8340 (setq cmd command)
8341 (setq cmd 'emacs))))
8342 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8343 (not (file-exists-p file))
8344 (not org-open-non-existing-files))
8345 (error "No such file: %s" file))
8346 (cond
8347 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8348 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8349 (while (string-match "['\"]%s['\"]" cmd)
8350 (setq cmd (replace-match "%s" t t cmd)))
8351 (while (string-match "%s" cmd)
8352 (setq cmd (replace-match
8353 (save-match-data
8354 (shell-quote-argument
8355 (convert-standard-filename file)))
8356 t t cmd)))
8357 (save-window-excursion
8358 (start-process-shell-command cmd nil cmd)
8359 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8361 ((or (stringp cmd)
8362 (eq cmd 'emacs))
8363 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8364 (widen)
8365 (if line (goto-line line)
8366 (if search (org-link-search search))))
8367 ((consp cmd)
8368 (let ((file (convert-standard-filename file)))
8369 (eval cmd)))
8370 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8371 (and (org-mode-p) (eq old-mode 'org-mode)
8372 (or (not (equal old-buffer (current-buffer)))
8373 (not (equal old-pos (point))))
8374 (org-mark-ring-push old-pos old-buffer))))
8376 (defun org-default-apps ()
8377 "Return the default applications for this operating system."
8378 (cond
8379 ((eq system-type 'darwin)
8380 org-file-apps-defaults-macosx)
8381 ((eq system-type 'windows-nt)
8382 org-file-apps-defaults-windowsnt)
8383 (t org-file-apps-defaults-gnu)))
8385 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8386 "Convert extensions to regular expressions in the cars of LIST.
8387 Also, weed out any non-string entries, because the return value is used
8388 only for regexp matching.
8389 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8390 point to the symbol `emacs', indicating that the file should
8391 be opened in Emacs."
8392 (append
8393 (delq nil
8394 (mapcar (lambda (x)
8395 (if (not (stringp (car x)))
8397 (if (string-match "\\W" (car x))
8399 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8400 list))
8401 (if add-auto-mode
8402 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8404 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8405 (defun org-file-remote-p (file)
8406 "Test whether FILE specifies a location on a remote system.
8407 Return non-nil if the location is indeed remote.
8409 For example, the filename \"/user@host:/foo\" specifies a location
8410 on the system \"/user@host:\"."
8411 (cond ((fboundp 'file-remote-p)
8412 (file-remote-p file))
8413 ((fboundp 'tramp-handle-file-remote-p)
8414 (tramp-handle-file-remote-p file))
8415 ((and (boundp 'ange-ftp-name-format)
8416 (string-match (car ange-ftp-name-format) file))
8418 (t nil)))
8421 ;;;; Refiling
8423 (defun org-get-org-file ()
8424 "Read a filename, with default directory `org-directory'."
8425 (let ((default (or org-default-notes-file remember-data-file)))
8426 (read-file-name (format "File name [%s]: " default)
8427 (file-name-as-directory org-directory)
8428 default)))
8430 (defun org-notes-order-reversed-p ()
8431 "Check if the current file should receive notes in reversed order."
8432 (cond
8433 ((not org-reverse-note-order) nil)
8434 ((eq t org-reverse-note-order) t)
8435 ((not (listp org-reverse-note-order)) nil)
8436 (t (catch 'exit
8437 (let ((all org-reverse-note-order)
8438 entry)
8439 (while (setq entry (pop all))
8440 (if (string-match (car entry) buffer-file-name)
8441 (throw 'exit (cdr entry))))
8442 nil)))))
8444 (defvar org-refile-target-table nil
8445 "The list of refile targets, created by `org-refile'.")
8447 (defvar org-agenda-new-buffers nil
8448 "Buffers created to visit agenda files.")
8450 (defun org-get-refile-targets (&optional default-buffer)
8451 "Produce a table with refile targets."
8452 (let ((case-fold-search nil)
8453 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
8454 (entries (or org-refile-targets '((nil . (:level . 1)))))
8455 targets txt re files f desc descre fast-path-p level pos0)
8456 (message "Getting targets...")
8457 (with-current-buffer (or default-buffer (current-buffer))
8458 (while (setq entry (pop entries))
8459 (setq files (car entry) desc (cdr entry))
8460 (setq fast-path-p nil)
8461 (cond
8462 ((null files) (setq files (list (current-buffer))))
8463 ((eq files 'org-agenda-files)
8464 (setq files (org-agenda-files 'unrestricted)))
8465 ((and (symbolp files) (fboundp files))
8466 (setq files (funcall files)))
8467 ((and (symbolp files) (boundp files))
8468 (setq files (symbol-value files))))
8469 (if (stringp files) (setq files (list files)))
8470 (cond
8471 ((eq (car desc) :tag)
8472 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8473 ((eq (car desc) :todo)
8474 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8475 ((eq (car desc) :regexp)
8476 (setq descre (cdr desc)))
8477 ((eq (car desc) :level)
8478 (setq descre (concat "^\\*\\{" (number-to-string
8479 (if org-odd-levels-only
8480 (1- (* 2 (cdr desc)))
8481 (cdr desc)))
8482 "\\}[ \t]")))
8483 ((eq (car desc) :maxlevel)
8484 (setq fast-path-p t)
8485 (setq descre (concat "^\\*\\{1," (number-to-string
8486 (if org-odd-levels-only
8487 (1- (* 2 (cdr desc)))
8488 (cdr desc)))
8489 "\\}[ \t]")))
8490 (t (error "Bad refiling target description %s" desc)))
8491 (while (setq f (pop files))
8492 (save-excursion
8493 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
8494 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8495 (setq f (expand-file-name f))
8496 (if (eq org-refile-use-outline-path 'file)
8497 (push (list (file-name-nondirectory f) f nil nil) targets))
8498 (save-excursion
8499 (save-restriction
8500 (widen)
8501 (goto-char (point-min))
8502 (while (re-search-forward descre nil t)
8503 (goto-char (setq pos0 (point-at-bol)))
8504 (catch 'next
8505 (when org-refile-target-verify-function
8506 (save-match-data
8507 (or (funcall org-refile-target-verify-function)
8508 (throw 'next t))))
8509 (when (looking-at org-complex-heading-regexp)
8510 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8511 txt (org-link-display-format (match-string 4))
8512 re (concat "^" (regexp-quote
8513 (buffer-substring (match-beginning 1)
8514 (match-end 4)))))
8515 (if (match-end 5) (setq re (concat re "[ \t]+"
8516 (regexp-quote
8517 (match-string 5)))))
8518 (setq re (concat re "[ \t]*$"))
8519 (when org-refile-use-outline-path
8520 (setq txt (mapconcat 'org-protect-slash
8521 (append
8522 (if (eq org-refile-use-outline-path 'file)
8523 (list (file-name-nondirectory
8524 (buffer-file-name (buffer-base-buffer))))
8525 (if (eq org-refile-use-outline-path 'full-file-path)
8526 (list (buffer-file-name (buffer-base-buffer)))))
8527 (org-get-outline-path fast-path-p level txt)
8528 (list txt))
8529 "/")))
8530 (push (list txt f re (point)) targets)))
8531 (when (= (point) pos0)
8532 ;; verification function has not moved point
8533 (goto-char (point-at-eol))))))))))
8534 (message "Getting targets...done")
8535 (nreverse targets)))
8537 (defun org-protect-slash (s)
8538 (while (string-match "/" s)
8539 (setq s (replace-match "\\" t t s)))
8542 (defvar org-olpa (make-vector 20 nil))
8544 (defun org-get-outline-path (&optional fastp level heading)
8545 "Return the outline path to the current entry, as a list."
8546 (if fastp
8547 (progn
8548 (if (> level 19)
8549 (error "Outline path failure, more than 19 levels."))
8550 (loop for i from level upto 19 do
8551 (aset org-olpa i nil))
8552 (prog1
8553 (delq nil (append org-olpa nil))
8554 (aset org-olpa level heading)))
8555 (let (rtn)
8556 (save-excursion
8557 (while (org-up-heading-safe)
8558 (when (looking-at org-complex-heading-regexp)
8559 (push (org-match-string-no-properties 4) rtn)))
8560 rtn))))
8562 (defvar org-refile-history nil
8563 "History for refiling operations.")
8565 (defvar org-after-refile-insert-hook nil
8566 "Hook run after `org-refile' has inserted its stuff at the new location.
8567 Note that this is still *before* the stuff will be removed from
8568 the *old* location.")
8570 (defun org-refile (&optional goto default-buffer rfloc)
8571 "Move the entry at point to another heading.
8572 The list of target headings is compiled using the information in
8573 `org-refile-targets', which see. This list is created before each use
8574 and will therefore always be up-to-date.
8576 At the target location, the entry is filed as a subitem of the target heading.
8577 Depending on `org-reverse-note-order', the new subitem will either be the
8578 first or the last subitem.
8580 If there is an active region, all entries in that region will be moved.
8581 However, the region must fulfil the requirement that the first heading
8582 is the first one sets the top-level of the moved text - at most siblings
8583 below it are allowed.
8585 With prefix arg GOTO, the command will only visit the target location,
8586 not actually move anything.
8587 With a double prefix `C-u C-u', go to the location where the last refiling
8588 operation has put the subtree.
8590 RFLOC can be a refile location obtained in a different way.
8592 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
8593 (interactive "P")
8594 (let* ((cbuf (current-buffer))
8595 (regionp (org-region-active-p))
8596 (region-start (and regionp (region-beginning)))
8597 (region-end (and regionp (region-end)))
8598 (region-length (and regionp (- region-end region-start)))
8599 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8600 pos it nbuf file re level reversed)
8601 (when regionp
8602 (goto-char region-start)
8603 (or (bolp) (goto-char (point-at-bol)))
8604 (setq region-start (point))
8605 (unless (org-kill-is-subtree-p
8606 (buffer-substring region-start region-end))
8607 (error "The region is not a (sequence of) subtree(s)")))
8608 (if (equal goto '(16))
8609 (org-refile-goto-last-stored)
8610 (when (setq it (or rfloc
8611 (save-excursion
8612 (org-refile-get-location
8613 (if goto "Goto: " "Refile to: ") default-buffer
8614 org-refile-allow-creating-parent-nodes))))
8615 (setq file (nth 1 it)
8616 re (nth 2 it)
8617 pos (nth 3 it))
8618 (if (and (not goto)
8620 (equal (buffer-file-name) file)
8621 (if regionp
8622 (and (>= pos region-start)
8623 (<= pos region-end))
8624 (and (>= pos (point))
8625 (< pos (save-excursion
8626 (org-end-of-subtree t t))))))
8627 (error "Cannot refile to position inside the tree or region"))
8629 (setq nbuf (or (find-buffer-visiting file)
8630 (find-file-noselect file)))
8631 (if goto
8632 (progn
8633 (switch-to-buffer nbuf)
8634 (goto-char pos)
8635 (org-show-context 'org-goto))
8636 (if regionp
8637 (progn
8638 (org-kill-new (buffer-substring region-start region-end))
8639 (org-save-markers-in-region region-start region-end))
8640 (org-copy-subtree 1 nil t))
8641 (save-excursion
8642 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8643 (find-file-noselect file))))
8644 (setq reversed (org-notes-order-reversed-p))
8645 (save-excursion
8646 (save-restriction
8647 (widen)
8648 (if pos
8649 (progn
8650 (goto-char pos)
8651 (looking-at outline-regexp)
8652 (setq level (org-get-valid-level (funcall outline-level) 1))
8653 (goto-char
8654 (if reversed
8655 (or (outline-next-heading) (point-max))
8656 (or (save-excursion (outline-get-next-sibling))
8657 (org-end-of-subtree t t)
8658 (point-max)))))
8659 (setq level 1)
8660 (if (not reversed)
8661 (goto-char (point-max))
8662 (goto-char (point-min))
8663 (or (outline-next-heading) (goto-char (point-max)))))
8664 (if (not (bolp)) (newline))
8665 (bookmark-set "org-refile-last-stored")
8666 (org-paste-subtree level)
8667 (if (fboundp 'deactivate-mark) (deactivate-mark))
8668 (run-hooks 'org-after-refile-insert-hook))))
8669 (if regionp
8670 (delete-region (point) (+ (point) region-length))
8671 (org-cut-subtree))
8672 (when (featurep 'org-inlinetask)
8673 (org-inlinetask-remove-END-maybe))
8674 (setq org-markers-to-move nil)
8675 (message "Refiled to \"%s\"" (car it))))))
8676 (org-reveal))
8678 (defun org-refile-goto-last-stored ()
8679 "Go to the location where the last refile was stored."
8680 (interactive)
8681 (bookmark-jump "org-refile-last-stored")
8682 (message "This is the location of the last refile"))
8684 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
8685 "Prompt the user for a refile location, using PROMPT."
8686 (let ((org-refile-targets org-refile-targets)
8687 (org-refile-use-outline-path org-refile-use-outline-path))
8688 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8689 (unless org-refile-target-table
8690 (error "No refile targets"))
8691 (let* ((cbuf (current-buffer))
8692 (partial-completion-mode nil)
8693 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8694 (cfunc (if (and org-refile-use-outline-path
8695 org-outline-path-complete-in-steps)
8696 'org-olpath-completing-read
8697 'org-ido-completing-read))
8698 (extra (if org-refile-use-outline-path "/" ""))
8699 (filename (and cfn (expand-file-name cfn)))
8700 (tbl (mapcar
8701 (lambda (x)
8702 (if (and (not (member org-refile-use-outline-path
8703 '(file full-file-path)))
8704 (not (equal filename (nth 1 x))))
8705 (cons (concat (car x) extra " ("
8706 (file-name-nondirectory (nth 1 x)) ")")
8707 (cdr x))
8708 (cons (concat (car x) extra) (cdr x))))
8709 org-refile-target-table))
8710 (completion-ignore-case t)
8711 pa answ parent-target child parent old-hist)
8712 (setq old-hist org-refile-history)
8713 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
8714 nil 'org-refile-history))
8715 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
8716 (if pa
8717 (progn
8718 (when (or (not org-refile-history)
8719 (not (eq old-hist org-refile-history))
8720 (not (equal (car pa) (car org-refile-history))))
8721 (setq org-refile-history
8722 (cons (car pa) (if (assoc (car org-refile-history) tbl)
8723 org-refile-history
8724 (cdr org-refile-history))))
8725 (if (equal (car org-refile-history) (nth 1 org-refile-history))
8726 (pop org-refile-history)))
8728 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
8729 (setq parent (match-string 1 answ)
8730 child (match-string 2 answ))
8731 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
8732 (when (and parent-target
8733 (or (eq new-nodes t)
8734 (and (eq new-nodes 'confirm)
8735 (y-or-n-p (format "Create new node \"%s\"? " child)))))
8736 (org-refile-new-child parent-target child))))))
8738 (defun org-refile-new-child (parent-target child)
8739 "Use refile target PARENT-TARGET to add new CHILD below it."
8740 (unless parent-target
8741 (error "Cannot find parent for new node"))
8742 (let ((file (nth 1 parent-target))
8743 (pos (nth 3 parent-target))
8744 level)
8745 (with-current-buffer (or (find-buffer-visiting file)
8746 (find-file-noselect file))
8747 (save-excursion
8748 (save-restriction
8749 (widen)
8750 (if pos
8751 (goto-char pos)
8752 (goto-char (point-max))
8753 (if (not (bolp)) (newline)))
8754 (when (looking-at outline-regexp)
8755 (setq level (funcall outline-level))
8756 (org-end-of-subtree t t))
8757 (org-back-over-empty-lines)
8758 (insert "\n" (make-string
8759 (if pos (org-get-valid-level level 1) 1) ?*)
8760 " " child "\n")
8761 (beginning-of-line 0)
8762 (list (concat (car parent-target) "/" child) file "" (point)))))))
8764 (defun org-olpath-completing-read (prompt collection &rest args)
8765 "Read an outline path like a file name."
8766 (let ((thetable collection)
8767 (org-completion-use-ido nil)) ; does not work with ido.
8768 (apply
8769 'org-ido-completing-read prompt
8770 (lambda (string predicate &optional flag)
8771 (let (rtn r f (l (length string)))
8772 (cond
8773 ((eq flag nil)
8774 ;; try completion
8775 (try-completion string thetable))
8776 ((eq flag t)
8777 ;; all-completions
8778 (setq rtn (all-completions string thetable predicate))
8779 (mapcar
8780 (lambda (x)
8781 (setq r (substring x l))
8782 (if (string-match " ([^)]*)$" x)
8783 (setq f (match-string 0 x))
8784 (setq f ""))
8785 (if (string-match "/" r)
8786 (concat string (substring r 0 (match-end 0)) f)
8788 rtn))
8789 ((eq flag 'lambda)
8790 ;; exact match?
8791 (assoc string thetable)))
8793 args)))
8795 ;;;; Dynamic blocks
8797 (defun org-find-dblock (name)
8798 "Find the first dynamic block with name NAME in the buffer.
8799 If not found, stay at current position and return nil."
8800 (let (pos)
8801 (save-excursion
8802 (goto-char (point-min))
8803 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8804 nil t)
8805 (match-beginning 0))))
8806 (if pos (goto-char pos))
8807 pos))
8809 (defconst org-dblock-start-re
8810 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8811 "Matches the startline of a dynamic block, with parameters.")
8813 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8814 "Matches the end of a dynamic block.")
8816 (defun org-create-dblock (plist)
8817 "Create a dynamic block section, with parameters taken from PLIST.
8818 PLIST must contain a :name entry which is used as name of the block."
8819 (unless (bolp) (newline))
8820 (let ((name (plist-get plist :name)))
8821 (insert "#+BEGIN: " name)
8822 (while plist
8823 (if (eq (car plist) :name)
8824 (setq plist (cddr plist))
8825 (insert " " (prin1-to-string (pop plist)))))
8826 (insert "\n\n#+END:\n")
8827 (beginning-of-line -2)))
8829 (defun org-prepare-dblock ()
8830 "Prepare dynamic block for refresh.
8831 This empties the block, puts the cursor at the insert position and returns
8832 the property list including an extra property :name with the block name."
8833 (unless (looking-at org-dblock-start-re)
8834 (error "Not at a dynamic block"))
8835 (let* ((begdel (1+ (match-end 0)))
8836 (name (org-no-properties (match-string 1)))
8837 (params (append (list :name name)
8838 (read (concat "(" (match-string 3) ")")))))
8839 (unless (re-search-forward org-dblock-end-re nil t)
8840 (error "Dynamic block not terminated"))
8841 (setq params
8842 (append params
8843 (list :content (buffer-substring
8844 begdel (match-beginning 0)))))
8845 (delete-region begdel (match-beginning 0))
8846 (goto-char begdel)
8847 (open-line 1)
8848 params))
8850 (defun org-map-dblocks (&optional command)
8851 "Apply COMMAND to all dynamic blocks in the current buffer.
8852 If COMMAND is not given, use `org-update-dblock'."
8853 (let ((cmd (or command 'org-update-dblock))
8854 pos)
8855 (save-excursion
8856 (goto-char (point-min))
8857 (while (re-search-forward org-dblock-start-re nil t)
8858 (goto-char (setq pos (match-beginning 0)))
8859 (condition-case nil
8860 (funcall cmd)
8861 (error (message "Error during update of dynamic block")))
8862 (goto-char pos)
8863 (unless (re-search-forward org-dblock-end-re nil t)
8864 (error "Dynamic block not terminated"))))))
8866 (defun org-dblock-update (&optional arg)
8867 "User command for updating dynamic blocks.
8868 Update the dynamic block at point. With prefix ARG, update all dynamic
8869 blocks in the buffer."
8870 (interactive "P")
8871 (if arg
8872 (org-update-all-dblocks)
8873 (or (looking-at org-dblock-start-re)
8874 (org-beginning-of-dblock))
8875 (org-update-dblock)))
8877 (defun org-update-dblock ()
8878 "Update the dynamic block at point
8879 This means to empty the block, parse for parameters and then call
8880 the correct writing function."
8881 (save-window-excursion
8882 (let* ((pos (point))
8883 (line (org-current-line))
8884 (params (org-prepare-dblock))
8885 (name (plist-get params :name))
8886 (cmd (intern (concat "org-dblock-write:" name))))
8887 (message "Updating dynamic block `%s' at line %d..." name line)
8888 (funcall cmd params)
8889 (message "Updating dynamic block `%s' at line %d...done" name line)
8890 (goto-char pos))))
8892 (defun org-beginning-of-dblock ()
8893 "Find the beginning of the dynamic block at point.
8894 Error if there is no such block at point."
8895 (let ((pos (point))
8896 beg)
8897 (end-of-line 1)
8898 (if (and (re-search-backward org-dblock-start-re nil t)
8899 (setq beg (match-beginning 0))
8900 (re-search-forward org-dblock-end-re nil t)
8901 (> (match-end 0) pos))
8902 (goto-char beg)
8903 (goto-char pos)
8904 (error "Not in a dynamic block"))))
8906 (defun org-update-all-dblocks ()
8907 "Update all dynamic blocks in the buffer.
8908 This function can be used in a hook."
8909 (when (org-mode-p)
8910 (org-map-dblocks 'org-update-dblock)))
8913 ;;;; Completion
8915 (defconst org-additional-option-like-keywords
8916 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
8917 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
8918 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:" "ATTR_LaTeX"
8919 "BEGIN:" "END:"
8920 "ORGTBL" "TBLFM:" "TBLNAME:"
8921 "BEGIN_EXAMPLE" "END_EXAMPLE"
8922 "BEGIN_QUOTE" "END_QUOTE"
8923 "BEGIN_VERSE" "END_VERSE"
8924 "BEGIN_CENTER" "END_CENTER"
8925 "BEGIN_SRC" "END_SRC"
8926 "CATEGORY" "COLUMNS"
8927 "CAPTION" "LABEL"
8928 "BIND"))
8930 (defcustom org-structure-template-alist
8932 ("s" "#+begin_src ?\n\n#+end_src"
8933 "<src lang=\"?\">\n\n</src>")
8934 ("e" "#+begin_example\n?\n#+end_example"
8935 "<example>\n?\n</example>")
8936 ("q" "#+begin_quote\n?\n#+end_quote"
8937 "<quote>\n?\n</quote>")
8938 ("v" "#+begin_verse\n?\n#+end_verse"
8939 "<verse>\n?\n/verse>")
8940 ("c" "#+begin_center\n?\n#+end_center"
8941 "<center>\n?\n/center>")
8942 ("l" "#+begin_latex\n?\n#+end_latex"
8943 "<literal style=\"latex\">\n?\n</literal>")
8944 ("L" "#+latex: "
8945 "<literal style=\"latex\">?</literal>")
8946 ("h" "#+begin_html\n?\n#+end_html"
8947 "<literal style=\"html\">\n?\n</literal>")
8948 ("H" "#+html: "
8949 "<literal style=\"html\">?</literal>")
8950 ("a" "#+begin_ascii\n?\n#+end_ascii")
8951 ("A" "#+ascii: ")
8952 ("i" "#+include %file ?"
8953 "<include file=%file markup=\"?\">")
8955 "Structure completion elements.
8956 This is a list of abbreviation keys and values. The value gets inserted
8957 it you type @samp{.} followed by the key and then the completion key,
8958 usually `M-TAB'. %file will be replaced by a file name after prompting
8959 for the file using completion.
8960 There are two templates for each key, the first uses the original Org syntax,
8961 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8962 the default when the /org-mtags.el/ module has been loaded. See also the
8963 variable `org-mtags-prefer-muse-templates'.
8964 This is an experimental feature, it is undecided if it is going to stay in."
8965 :group 'org-completion
8966 :type '(repeat
8967 (string :tag "Key")
8968 (string :tag "Template")
8969 (string :tag "Muse Template")))
8971 (defun org-try-structure-completion ()
8972 "Try to complete a structure template before point.
8973 This looks for strings like \"<e\" on an otherwise empty line and
8974 expands them."
8975 (let ((l (buffer-substring (point-at-bol) (point)))
8977 (when (and (looking-at "[ \t]*$")
8978 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8979 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8980 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8981 (match-beginning 1)) a)
8982 t)))
8984 (defun org-complete-expand-structure-template (start cell)
8985 "Expand a structure template."
8986 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8987 (rpl (nth (if musep 2 1) cell))
8988 (ind ""))
8989 (delete-region start (point))
8990 (when (string-match "\\`#\\+" rpl)
8991 (cond
8992 ((bolp))
8993 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8994 (setq ind (buffer-substring (point-at-bol) (point))))
8995 (t (newline))))
8996 (setq start (point))
8997 (if (string-match "%file" rpl)
8998 (setq rpl (replace-match
8999 (concat
9000 "\""
9001 (save-match-data
9002 (abbreviate-file-name (read-file-name "Include file: ")))
9003 "\"")
9004 t t rpl)))
9005 (setq rpl (mapconcat 'identity (split-string rpl "\n")
9006 (concat "\n" ind)))
9007 (insert rpl)
9008 (if (re-search-backward "\\?" start t) (delete-char 1))))
9011 (defun org-complete (&optional arg)
9012 "Perform completion on word at point.
9013 At the beginning of a headline, this completes TODO keywords as given in
9014 `org-todo-keywords'.
9015 If the current word is preceded by a backslash, completes the TeX symbols
9016 that are supported for HTML support.
9017 If the current word is preceded by \"#+\", completes special words for
9018 setting file options.
9019 In the line after \"#+STARTUP:, complete valid keywords.\"
9020 At all other locations, this simply calls the value of
9021 `org-completion-fallback-command'."
9022 (interactive "P")
9023 (org-without-partial-completion
9024 (catch 'exit
9025 (let* ((a nil)
9026 (end (point))
9027 (beg1 (save-excursion
9028 (skip-chars-backward (org-re "[:alnum:]_@"))
9029 (point)))
9030 (beg (save-excursion
9031 (skip-chars-backward "a-zA-Z0-9_:$")
9032 (point)))
9033 (confirm (lambda (x) (stringp (car x))))
9034 (searchhead (equal (char-before beg) ?*))
9035 (struct
9036 (when (and (member (char-before beg1) '(?. ?<))
9037 (setq a (assoc (buffer-substring beg1 (point))
9038 org-structure-template-alist)))
9039 (org-complete-expand-structure-template (1- beg1) a)
9040 (throw 'exit t)))
9041 (tag (and (equal (char-before beg1) ?:)
9042 (equal (char-after (point-at-bol)) ?*)))
9043 (prop (and (equal (char-before beg1) ?:)
9044 (not (equal (char-after (point-at-bol)) ?*))))
9045 (texp (equal (char-before beg) ?\\))
9046 (link (equal (char-before beg) ?\[))
9047 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9048 beg)
9049 "#+"))
9050 (startup (string-match "^#\\+STARTUP:.*"
9051 (buffer-substring (point-at-bol) (point))))
9052 (completion-ignore-case opt)
9053 (type nil)
9054 (tbl nil)
9055 (table (cond
9056 (opt
9057 (setq type :opt)
9058 (require 'org-exp)
9059 (append
9060 (delq nil
9061 (mapcar
9062 (lambda (x)
9063 (if (string-match
9064 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9065 (cons (match-string 2 x)
9066 (match-string 1 x))))
9067 (org-split-string (org-get-current-options) "\n")))
9068 (mapcar 'list org-additional-option-like-keywords)))
9069 (startup
9070 (setq type :startup)
9071 org-startup-options)
9072 (link (append org-link-abbrev-alist-local
9073 org-link-abbrev-alist))
9074 (texp
9075 (setq type :tex)
9076 org-html-entities)
9077 ((string-match "\\`\\*+[ \t]+\\'"
9078 (buffer-substring (point-at-bol) beg))
9079 (setq type :todo)
9080 (mapcar 'list org-todo-keywords-1))
9081 (searchhead
9082 (setq type :searchhead)
9083 (save-excursion
9084 (goto-char (point-min))
9085 (while (re-search-forward org-todo-line-regexp nil t)
9086 (push (list
9087 (org-make-org-heading-search-string
9088 (match-string 3) t))
9089 tbl)))
9090 tbl)
9091 (tag (setq type :tag beg beg1)
9092 (or org-tag-alist (org-get-buffer-tags)))
9093 (prop (setq type :prop beg beg1)
9094 (mapcar 'list (org-buffer-property-keys nil t t)))
9095 (t (progn
9096 (call-interactively org-completion-fallback-command)
9097 (throw 'exit nil)))))
9098 (pattern (buffer-substring-no-properties beg end))
9099 (completion (try-completion pattern table confirm)))
9100 (cond ((eq completion t)
9101 (if (not (assoc (upcase pattern) table))
9102 (message "Already complete")
9103 (if (and (equal type :opt)
9104 (not (member (car (assoc (upcase pattern) table))
9105 org-additional-option-like-keywords)))
9106 (insert (substring (cdr (assoc (upcase pattern) table))
9107 (length pattern)))
9108 (if (memq type '(:tag :prop)) (insert ":")))))
9109 ((null completion)
9110 (message "Can't find completion for \"%s\"" pattern)
9111 (ding))
9112 ((not (string= pattern completion))
9113 (delete-region beg end)
9114 (if (string-match " +$" completion)
9115 (setq completion (replace-match "" t t completion)))
9116 (insert completion)
9117 (if (get-buffer-window "*Completions*")
9118 (delete-window (get-buffer-window "*Completions*")))
9119 (if (assoc completion table)
9120 (if (eq type :todo) (insert " ")
9121 (if (memq type '(:tag :prop)) (insert ":"))))
9122 (if (and (equal type :opt) (assoc completion table))
9123 (message "%s" (substitute-command-keys
9124 "Press \\[org-complete] again to insert example settings"))))
9126 (message "Making completion list...")
9127 (let ((list (sort (all-completions pattern table confirm)
9128 'string<)))
9129 (with-output-to-temp-buffer "*Completions*"
9130 (condition-case nil
9131 ;; Protection needed for XEmacs and emacs 21
9132 (display-completion-list list pattern)
9133 (error (display-completion-list list)))))
9134 (message "Making completion list...%s" "done")))))))
9136 ;;;; TODO, DEADLINE, Comments
9138 (defun org-toggle-comment ()
9139 "Change the COMMENT state of an entry."
9140 (interactive)
9141 (save-excursion
9142 (org-back-to-heading)
9143 (let (case-fold-search)
9144 (if (looking-at (concat outline-regexp
9145 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9146 (replace-match "" t t nil 1)
9147 (if (looking-at outline-regexp)
9148 (progn
9149 (goto-char (match-end 0))
9150 (insert org-comment-string " ")))))))
9152 (defvar org-last-todo-state-is-todo nil
9153 "This is non-nil when the last TODO state change led to a TODO state.
9154 If the last change removed the TODO tag or switched to DONE, then
9155 this is nil.")
9157 (defvar org-setting-tags nil) ; dynamically skipped
9159 (defun org-parse-local-options (string var)
9160 "Parse STRING for startup setting relevant for variable VAR."
9161 (let ((rtn (symbol-value var))
9162 e opts)
9163 (save-match-data
9164 (if (or (not string) (not (string-match "\\S-" string)))
9166 (setq opts (delq nil (mapcar (lambda (x)
9167 (setq e (assoc x org-startup-options))
9168 (if (eq (nth 1 e) var) e nil))
9169 (org-split-string string "[ \t]+"))))
9170 (if (not opts)
9172 (setq rtn nil)
9173 (while (setq e (pop opts))
9174 (if (not (nth 3 e))
9175 (setq rtn (nth 2 e))
9176 (if (not (listp rtn)) (setq rtn nil))
9177 (push (nth 2 e) rtn)))
9178 rtn)))))
9180 (defvar org-todo-setup-filter-hook nil
9181 "Hook for functions that pre-filter todo specs.
9183 Each function takes a todo spec and returns either `nil' or the spec
9184 transformed into canonical form." )
9186 (defvar org-todo-get-default-hook nil
9187 "Hook for functions that get a default item for todo.
9189 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9190 `nil' or a string to be used for the todo mark." )
9192 (defvar org-agenda-headline-snapshot-before-repeat)
9194 (defun org-todo (&optional arg)
9195 "Change the TODO state of an item.
9196 The state of an item is given by a keyword at the start of the heading,
9197 like
9198 *** TODO Write paper
9199 *** DONE Call mom
9201 The different keywords are specified in the variable `org-todo-keywords'.
9202 By default the available states are \"TODO\" and \"DONE\".
9203 So for this example: when the item starts with TODO, it is changed to DONE.
9204 When it starts with DONE, the DONE is removed. And when neither TODO nor
9205 DONE are present, add TODO at the beginning of the heading.
9207 With C-u prefix arg, use completion to determine the new state.
9208 With numeric prefix arg, switch to that state.
9209 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9210 With a tripple C-u prefix, circumvent any state blocking.
9212 For calling through lisp, arg is also interpreted in the following way:
9213 'none -> empty state
9214 \"\"(empty string) -> switch to empty state
9215 'done -> switch to DONE
9216 'nextset -> switch to the next set of keywords
9217 'previousset -> switch to the previous set of keywords
9218 \"WAITING\" -> switch to the specified keyword, but only if it
9219 really is a member of `org-todo-keywords'."
9220 (interactive "P")
9221 (if (equal arg '(16)) (setq arg 'nextset))
9222 (let ((org-blocker-hook org-blocker-hook)
9223 (case-fold-search nil))
9224 (when (equal arg '(64))
9225 (setq arg nil org-blocker-hook nil))
9226 (when (and org-blocker-hook
9227 (or org-inhibit-blocking
9228 (org-entry-get nil "NOBLOCKING")))
9229 (setq org-blocker-hook nil))
9230 (save-excursion
9231 (catch 'exit
9232 (org-back-to-heading)
9233 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9234 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9235 (looking-at " *"))
9236 (let* ((match-data (match-data))
9237 (startpos (point-at-bol))
9238 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9239 (org-log-done org-log-done)
9240 (org-log-repeat org-log-repeat)
9241 (org-todo-log-states org-todo-log-states)
9242 (this (match-string 1))
9243 (hl-pos (match-beginning 0))
9244 (head (org-get-todo-sequence-head this))
9245 (ass (assoc head org-todo-kwd-alist))
9246 (interpret (nth 1 ass))
9247 (done-word (nth 3 ass))
9248 (final-done-word (nth 4 ass))
9249 (last-state (or this ""))
9250 (completion-ignore-case t)
9251 (member (member this org-todo-keywords-1))
9252 (tail (cdr member))
9253 (state (cond
9254 ((and org-todo-key-trigger
9255 (or (and (equal arg '(4))
9256 (eq org-use-fast-todo-selection 'prefix))
9257 (and (not arg) org-use-fast-todo-selection
9258 (not (eq org-use-fast-todo-selection
9259 'prefix)))))
9260 ;; Use fast selection
9261 (org-fast-todo-selection))
9262 ((and (equal arg '(4))
9263 (or (not org-use-fast-todo-selection)
9264 (not org-todo-key-trigger)))
9265 ;; Read a state with completion
9266 (org-ido-completing-read
9267 "State: " (mapcar (lambda(x) (list x))
9268 org-todo-keywords-1)
9269 nil t))
9270 ((eq arg 'right)
9271 (if this
9272 (if tail (car tail) nil)
9273 (car org-todo-keywords-1)))
9274 ((eq arg 'left)
9275 (if (equal member org-todo-keywords-1)
9277 (if this
9278 (nth (- (length org-todo-keywords-1)
9279 (length tail) 2)
9280 org-todo-keywords-1)
9281 (org-last org-todo-keywords-1))))
9282 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9283 (setq arg nil))) ; hack to fall back to cycling
9284 (arg
9285 ;; user or caller requests a specific state
9286 (cond
9287 ((equal arg "") nil)
9288 ((eq arg 'none) nil)
9289 ((eq arg 'done) (or done-word (car org-done-keywords)))
9290 ((eq arg 'nextset)
9291 (or (car (cdr (member head org-todo-heads)))
9292 (car org-todo-heads)))
9293 ((eq arg 'previousset)
9294 (let ((org-todo-heads (reverse org-todo-heads)))
9295 (or (car (cdr (member head org-todo-heads)))
9296 (car org-todo-heads))))
9297 ((car (member arg org-todo-keywords-1)))
9298 ((nth (1- (prefix-numeric-value arg))
9299 org-todo-keywords-1))))
9300 ((null member) (or head (car org-todo-keywords-1)))
9301 ((equal this final-done-word) nil) ;; -> make empty
9302 ((null tail) nil) ;; -> first entry
9303 ((memq interpret '(type priority))
9304 (if (eq this-command last-command)
9305 (car tail)
9306 (if (> (length tail) 0)
9307 (or done-word (car org-done-keywords))
9308 nil)))
9310 (car tail))))
9311 (state (or
9312 (run-hook-with-args-until-success
9313 'org-todo-get-default-hook state last-state)
9314 state))
9315 (next (if state (concat " " state " ") " "))
9316 (change-plist (list :type 'todo-state-change :from this :to state
9317 :position startpos))
9318 dolog now-done-p)
9319 (when org-blocker-hook
9320 (setq org-last-todo-state-is-todo
9321 (not (member this org-done-keywords)))
9322 (unless (save-excursion
9323 (save-match-data
9324 (run-hook-with-args-until-failure
9325 'org-blocker-hook change-plist)))
9326 (if (interactive-p)
9327 (error "TODO state change from %s to %s blocked" this state)
9328 ;; fail silently
9329 (message "TODO state change from %s to %s blocked" this state)
9330 (throw 'exit nil))))
9331 (store-match-data match-data)
9332 (replace-match next t t)
9333 (unless (pos-visible-in-window-p hl-pos)
9334 (message "TODO state changed to %s" (org-trim next)))
9335 (unless head
9336 (setq head (org-get-todo-sequence-head state)
9337 ass (assoc head org-todo-kwd-alist)
9338 interpret (nth 1 ass)
9339 done-word (nth 3 ass)
9340 final-done-word (nth 4 ass)))
9341 (when (memq arg '(nextset previousset))
9342 (message "Keyword-Set %d/%d: %s"
9343 (- (length org-todo-sets) -1
9344 (length (memq (assoc state org-todo-sets) org-todo-sets)))
9345 (length org-todo-sets)
9346 (mapconcat 'identity (assoc state org-todo-sets) " ")))
9347 (setq org-last-todo-state-is-todo
9348 (not (member state org-done-keywords)))
9349 (setq now-done-p (and (member state org-done-keywords)
9350 (not (member this org-done-keywords))))
9351 (and logging (org-local-logging logging))
9352 (when (and (or org-todo-log-states org-log-done)
9353 (not (eq org-inhibit-logging t))
9354 (not (memq arg '(nextset previousset))))
9355 ;; we need to look at recording a time and note
9356 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
9357 (nth 2 (assoc this org-todo-log-states))))
9358 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
9359 (setq dolog 'time))
9360 (when (and state
9361 (member state org-not-done-keywords)
9362 (not (member this org-not-done-keywords)))
9363 ;; This is now a todo state and was not one before
9364 ;; If there was a CLOSED time stamp, get rid of it.
9365 (org-add-planning-info nil nil 'closed))
9366 (when (and now-done-p org-log-done)
9367 ;; It is now done, and it was not done before
9368 (org-add-planning-info 'closed (org-current-time))
9369 (if (and (not dolog) (eq 'note org-log-done))
9370 (org-add-log-setup 'done state this 'findpos 'note)))
9371 (when (and state dolog)
9372 ;; This is a non-nil state, and we need to log it
9373 (org-add-log-setup 'state state this 'findpos dolog)))
9374 ;; Fixup tag positioning
9375 (org-todo-trigger-tag-changes state)
9376 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
9377 (when org-provide-todo-statistics
9378 (org-update-parent-todo-statistics))
9379 (run-hooks 'org-after-todo-state-change-hook)
9380 (if (and arg (not (member state org-done-keywords)))
9381 (setq head (org-get-todo-sequence-head state)))
9382 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9383 ;; Do we need to trigger a repeat?
9384 (when now-done-p
9385 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
9386 ;; This is for the agenda, take a snapshot of the headline.
9387 (save-match-data
9388 (setq org-agenda-headline-snapshot-before-repeat
9389 (org-get-heading))))
9390 (org-auto-repeat-maybe state))
9391 ;; Fixup cursor location if close to the keyword
9392 (if (and (outline-on-heading-p)
9393 (not (bolp))
9394 (save-excursion (beginning-of-line 1)
9395 (looking-at org-todo-line-regexp))
9396 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9397 (progn
9398 (goto-char (or (match-end 2) (match-end 1)))
9399 (and (looking-at " ") (just-one-space))))
9400 (when org-trigger-hook
9401 (save-excursion
9402 (run-hook-with-args 'org-trigger-hook change-plist))))))))
9404 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
9405 "Block turning an entry into a TODO, using the hierarchy.
9406 This checks whether the current task should be blocked from state
9407 changes. Such blocking occurs when:
9409 1. The task has children which are not all in a completed state.
9411 2. A task has a parent with the property :ORDERED:, and there
9412 are siblings prior to the current task with incomplete
9413 status.
9415 3. The parent of the task is blocked because it has siblings that should
9416 be done first, or is child of a block grandparent TODO entry."
9418 (catch 'dont-block
9419 ;; If this is not a todo state change, or if this entry is already DONE,
9420 ;; do not block
9421 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9422 (member (plist-get change-plist :from)
9423 (cons 'done org-done-keywords))
9424 (member (plist-get change-plist :to)
9425 (cons 'todo org-not-done-keywords)))
9426 (throw 'dont-block t))
9427 ;; If this task has children, and any are undone, it's blocked
9428 (save-excursion
9429 (org-back-to-heading t)
9430 (let ((this-level (funcall outline-level)))
9431 (outline-next-heading)
9432 (let ((child-level (funcall outline-level)))
9433 (while (and (not (eobp))
9434 (> child-level this-level))
9435 ;; this todo has children, check whether they are all
9436 ;; completed
9437 (if (and (not (org-entry-is-done-p))
9438 (org-entry-is-todo-p))
9439 (throw 'dont-block nil))
9440 (outline-next-heading)
9441 (setq child-level (funcall outline-level))))))
9442 ;; Otherwise, if the task's parent has the :ORDERED: property, and
9443 ;; any previous siblings are undone, it's blocked
9444 (save-excursion
9445 (org-back-to-heading t)
9446 (let* ((pos (point))
9447 (parent-pos (and (org-up-heading-safe) (point))))
9448 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9449 (when (and (org-entry-get (point) "ORDERED")
9450 (forward-line 1)
9451 (re-search-forward org-not-done-heading-regexp pos t))
9452 (throw 'dont-block nil)) ; block, there is an older sibling not done.
9453 ;; Search further up the hierarchy, to see if an anchestor is blocked
9454 (while t
9455 (goto-char parent-pos)
9456 (if (not (looking-at org-not-done-heading-regexp))
9457 (throw 'dont-block t)) ; do not block, parent is not a TODO
9458 (setq pos (point))
9459 (setq parent-pos (and (org-up-heading-safe) (point)))
9460 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9461 (when (and (org-entry-get (point) "ORDERED")
9462 (forward-line 1)
9463 (re-search-forward org-not-done-heading-regexp pos t))
9464 (throw 'dont-block nil))))))) ; block, older sibling not done.
9466 (defcustom org-track-ordered-property-with-tag nil
9467 "Should the ORDERED property also be shown as a tag?
9468 The ORDERED property decides if an entry should require subtasks to be
9469 completed in sequence. Since a property is not very visible, setting
9470 this option means that toggling the ORDERED property with the command
9471 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
9472 not relevant for the behavior, but it makes things more visible.
9474 Note that toggling the tag with tags commands will not change the property
9475 and therefore not influence behavior!
9477 This can be t, meaning the tag ORDERED should be used, It can also be a
9478 string to select a different tag for this task."
9479 :group 'org-todo
9480 :type '(choice
9481 (const :tag "No tracking" nil)
9482 (const :tag "Track with ORDERED tag" t)
9483 (string :tag "Use other tag")))
9485 (defun org-toggle-ordered-property ()
9486 "Toggle the ORDERED property of the current entry.
9487 For better visibility, you can track the value of this property with a tag.
9488 See variable `org-track-ordered-property-with-tag'."
9489 (interactive)
9490 (let* ((t1 org-track-ordered-property-with-tag)
9491 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
9492 (save-excursion
9493 (org-back-to-heading)
9494 (if (org-entry-get nil "ORDERED")
9495 (progn
9496 (org-delete-property "ORDERED")
9497 (and tag (org-toggle-tag tag 'off))
9498 (message "Subtasks can be completed in arbitrary order"))
9499 (org-entry-put nil "ORDERED" "t")
9500 (and tag (org-toggle-tag tag 'on))
9501 (message "Subtasks must be completed in sequence")))))
9503 (defvar org-blocked-by-checkboxes) ; dynamically scoped
9504 (defun org-block-todo-from-checkboxes (change-plist)
9505 "Block turning an entry into a TODO, using checkboxes.
9506 This checks whether the current task should be blocked from state
9507 changes because there are uncheckd boxes in this entry."
9508 (catch 'dont-block
9509 ;; If this is not a todo state change, or if this entry is already DONE,
9510 ;; do not block
9511 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9512 (member (plist-get change-plist :from)
9513 (cons 'done org-done-keywords))
9514 (member (plist-get change-plist :to)
9515 (cons 'todo org-not-done-keywords)))
9516 (throw 'dont-block t))
9517 ;; If this task has checkboxes that are not checked, it's blocked
9518 (save-excursion
9519 (org-back-to-heading t)
9520 (let ((beg (point)) end)
9521 (outline-next-heading)
9522 (setq end (point))
9523 (goto-char beg)
9524 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
9525 end t)
9526 (progn
9527 (if (boundp 'org-blocked-by-checkboxes)
9528 (setq org-blocked-by-checkboxes t))
9529 (throw 'dont-block nil)))))
9530 t)) ; do not block
9532 (defvar org-entry-property-inherited-from) ;; defined below
9533 (defun org-update-parent-todo-statistics ()
9534 "Update any statistics cookie in the parent of the current headline.
9535 When `org-hierarchical-todo-statistics' is nil, statistics will cover
9536 the entire subtree and this will travel up the hierarchy and update
9537 statistics everywhere."
9538 (interactive)
9539 (let* ((lim 0) prop
9540 (recursive (or (not org-hierarchical-todo-statistics)
9541 (string-match
9542 "\\<recursive\\>"
9543 (or (setq prop (org-entry-get
9544 nil "COOKIE_DATA" 'inherit)) ""))))
9545 (lim (or (and prop (marker-position
9546 org-entry-property-inherited-from))
9547 lim))
9548 (first t)
9549 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
9550 level ltoggle l1
9551 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
9552 (catch 'exit
9553 (save-excursion
9554 (beginning-of-line 1)
9555 (if (org-at-heading-p)
9556 (setq ltoggle (funcall outline-level))
9557 (error "This should not happen"))
9558 (while (and (setq level (org-up-heading-safe))
9559 (or recursive first)
9560 (>= (point) lim))
9561 (setq first nil)
9562 (unless (and level
9563 (not (string-match
9564 "\\<checkbox\\>"
9565 (downcase
9566 (or (org-entry-get
9567 nil "COOKIE_DATA")
9568 "")))))
9569 (throw 'exit nil))
9570 (while (re-search-forward box-re (point-at-eol) t)
9571 (setq cnt-all 0 cnt-done 0 cookie-present t)
9572 (setq is-percent (match-end 2))
9573 (save-match-data
9574 (unless (outline-next-heading) (throw 'exit nil))
9575 (while (and (looking-at org-complex-heading-regexp)
9576 (> (setq l1 (length (match-string 1))) level))
9577 (setq kwd (and (or recursive (= l1 ltoggle))
9578 (match-string 2)))
9579 (if (or (eq org-provide-todo-statistics 'all-headlines)
9580 (and (listp org-provide-todo-statistics)
9581 (or (member kwd org-provide-todo-statistics)
9582 (member kwd org-done-keywords))))
9583 (setq cnt-all (1+ cnt-all))
9584 (if (eq org-provide-todo-statistics t)
9585 (and kwd (setq cnt-all (1+ cnt-all)))))
9586 (and (member kwd org-done-keywords)
9587 (setq cnt-done (1+ cnt-done)))
9588 (outline-next-heading)))
9589 (replace-match
9590 (if is-percent
9591 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
9592 (format "[%d/%d]" cnt-done cnt-all)))))
9593 (when cookie-present
9594 (run-hook-with-args 'org-after-todo-statistics-hook
9595 cnt-done (- cnt-all cnt-done)))))
9596 (run-hooks 'org-todo-statistics-hook)))
9598 (defvar org-after-todo-statistics-hook nil
9599 "Hook that is called after a TODO statistics cookie has been updated.
9600 Each function is called with two arguments: the number of not-done entries
9601 and the number of done entries.
9603 For example, the following function, when added to this hook, will switch
9604 an entry to DONE when all children are done, and back to TODO when new
9605 entries are set to a TODO status. Note that this hook is only called
9606 when there is a statistics cookie in the headline!
9608 (defun org-summary-todo (n-done n-not-done)
9609 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
9610 (let (org-log-done org-log-states) ; turn off logging
9611 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
9614 (defvar org-todo-statistics-hook nil
9615 "Hook that is run whenever Org thinks TODO statistics should be updated.
9616 This hook runs even if there is no statisics cookie present, in which case
9617 `org-after-todo-statistics-hook' would not run.")
9619 (defun org-todo-trigger-tag-changes (state)
9620 "Apply the changes defined in `org-todo-state-tags-triggers'."
9621 (let ((l org-todo-state-tags-triggers)
9622 changes)
9623 (when (or (not state) (equal state ""))
9624 (setq changes (append changes (cdr (assoc "" l)))))
9625 (when (and (stringp state) (> (length state) 0))
9626 (setq changes (append changes (cdr (assoc state l)))))
9627 (when (member state org-not-done-keywords)
9628 (setq changes (append changes (cdr (assoc 'todo l)))))
9629 (when (member state org-done-keywords)
9630 (setq changes (append changes (cdr (assoc 'done l)))))
9631 (dolist (c changes)
9632 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
9634 (defun org-local-logging (value)
9635 "Get logging settings from a property VALUE."
9636 (let* (words w a)
9637 ;; directly set the variables, they are already local.
9638 (setq org-log-done nil
9639 org-log-repeat nil
9640 org-todo-log-states nil)
9641 (setq words (org-split-string value))
9642 (while (setq w (pop words))
9643 (cond
9644 ((setq a (assoc w org-startup-options))
9645 (and (member (nth 1 a) '(org-log-done org-log-repeat))
9646 (set (nth 1 a) (nth 2 a))))
9647 ((setq a (org-extract-log-state-settings w))
9648 (and (member (car a) org-todo-keywords-1)
9649 (push a org-todo-log-states)))))))
9651 (defun org-get-todo-sequence-head (kwd)
9652 "Return the head of the TODO sequence to which KWD belongs.
9653 If KWD is not set, check if there is a text property remembering the
9654 right sequence."
9655 (let (p)
9656 (cond
9657 ((not kwd)
9658 (or (get-text-property (point-at-bol) 'org-todo-head)
9659 (progn
9660 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
9661 nil (point-at-eol)))
9662 (get-text-property p 'org-todo-head))))
9663 ((not (member kwd org-todo-keywords-1))
9664 (car org-todo-keywords-1))
9665 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
9667 (defun org-fast-todo-selection ()
9668 "Fast TODO keyword selection with single keys.
9669 Returns the new TODO keyword, or nil if no state change should occur."
9670 (let* ((fulltable org-todo-key-alist)
9671 (done-keywords org-done-keywords) ;; needed for the faces.
9672 (maxlen (apply 'max (mapcar
9673 (lambda (x)
9674 (if (stringp (car x)) (string-width (car x)) 0))
9675 fulltable)))
9676 (expert nil)
9677 (fwidth (+ maxlen 3 1 3))
9678 (ncol (/ (- (window-width) 4) fwidth))
9679 tg cnt e c tbl
9680 groups ingroup)
9681 (save-excursion
9682 (save-window-excursion
9683 (if expert
9684 (set-buffer (get-buffer-create " *Org todo*"))
9685 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
9686 (erase-buffer)
9687 (org-set-local 'org-done-keywords done-keywords)
9688 (setq tbl fulltable cnt 0)
9689 (while (setq e (pop tbl))
9690 (cond
9691 ((equal e '(:startgroup))
9692 (push '() groups) (setq ingroup t)
9693 (when (not (= cnt 0))
9694 (setq cnt 0)
9695 (insert "\n"))
9696 (insert "{ "))
9697 ((equal e '(:endgroup))
9698 (setq ingroup nil cnt 0)
9699 (insert "}\n"))
9700 ((equal e '(:newline))
9701 (when (not (= cnt 0))
9702 (setq cnt 0)
9703 (insert "\n")
9704 (setq e (car tbl))
9705 (while (equal (car tbl) '(:newline))
9706 (insert "\n")
9707 (setq tbl (cdr tbl)))))
9709 (setq tg (car e) c (cdr e))
9710 (if ingroup (push tg (car groups)))
9711 (setq tg (org-add-props tg nil 'face
9712 (org-get-todo-face tg)))
9713 (if (and (= cnt 0) (not ingroup)) (insert " "))
9714 (insert "[" c "] " tg (make-string
9715 (- fwidth 4 (length tg)) ?\ ))
9716 (when (= (setq cnt (1+ cnt)) ncol)
9717 (insert "\n")
9718 (if ingroup (insert " "))
9719 (setq cnt 0)))))
9720 (insert "\n")
9721 (goto-char (point-min))
9722 (if (not expert) (org-fit-window-to-buffer))
9723 (message "[a-z..]:Set [SPC]:clear")
9724 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9725 (cond
9726 ((or (= c ?\C-g)
9727 (and (= c ?q) (not (rassoc c fulltable))))
9728 (setq quit-flag t))
9729 ((= c ?\ ) nil)
9730 ((setq e (rassoc c fulltable) tg (car e))
9732 (t (setq quit-flag t)))))))
9734 (defun org-entry-is-todo-p ()
9735 (member (org-get-todo-state) org-not-done-keywords))
9737 (defun org-entry-is-done-p ()
9738 (member (org-get-todo-state) org-done-keywords))
9740 (defun org-get-todo-state ()
9741 (save-excursion
9742 (org-back-to-heading t)
9743 (and (looking-at org-todo-line-regexp)
9744 (match-end 2)
9745 (match-string 2))))
9747 (defun org-at-date-range-p (&optional inactive-ok)
9748 "Is the cursor inside a date range?"
9749 (interactive)
9750 (save-excursion
9751 (catch 'exit
9752 (let ((pos (point)))
9753 (skip-chars-backward "^[<\r\n")
9754 (skip-chars-backward "<[")
9755 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9756 (>= (match-end 0) pos)
9757 (throw 'exit t))
9758 (skip-chars-backward "^<[\r\n")
9759 (skip-chars-backward "<[")
9760 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9761 (>= (match-end 0) pos)
9762 (throw 'exit t)))
9763 nil)))
9765 (defun org-get-repeat ()
9766 "Check if there is a deadline/schedule with repeater in this entry."
9767 (save-match-data
9768 (save-excursion
9769 (org-back-to-heading t)
9770 (if (re-search-forward
9771 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9772 (match-string 1)))))
9774 (defvar org-last-changed-timestamp)
9775 (defvar org-last-inserted-timestamp)
9776 (defvar org-log-post-message)
9777 (defvar org-log-note-purpose)
9778 (defvar org-log-note-how)
9779 (defvar org-log-note-extra)
9780 (defun org-auto-repeat-maybe (done-word)
9781 "Check if the current headline contains a repeated deadline/schedule.
9782 If yes, set TODO state back to what it was and change the base date
9783 of repeating deadline/scheduled time stamps to new date.
9784 This function is run automatically after each state change to a DONE state."
9785 ;; last-state is dynamically scoped into this function
9786 (let* ((repeat (org-get-repeat))
9787 (aa (assoc last-state org-todo-kwd-alist))
9788 (interpret (nth 1 aa))
9789 (head (nth 2 aa))
9790 (whata '(("d" . day) ("m" . month) ("y" . year)))
9791 (msg "Entry repeats: ")
9792 (org-log-done nil)
9793 (org-todo-log-states nil)
9794 (nshiftmax 10) (nshift 0)
9795 re type n what ts time)
9796 (when repeat
9797 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9798 (org-todo (if (eq interpret 'type) last-state head))
9799 (org-entry-put nil "LAST_REPEAT" (format-time-string
9800 (org-time-stamp-format t t)))
9801 (when org-log-repeat
9802 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9803 (memq 'org-add-log-note post-command-hook))
9804 ;; OK, we are already setup for some record
9805 (if (eq org-log-repeat 'note)
9806 ;; make sure we take a note, not only a time stamp
9807 (setq org-log-note-how 'note))
9808 ;; Set up for taking a record
9809 (org-add-log-setup 'state (or done-word (car org-done-keywords))
9810 last-state
9811 'findpos org-log-repeat)))
9812 (org-back-to-heading t)
9813 (org-add-planning-info nil nil 'closed)
9814 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9815 org-deadline-time-regexp "\\)\\|\\("
9816 org-ts-regexp "\\)"))
9817 (while (re-search-forward
9818 re (save-excursion (outline-next-heading) (point)) t)
9819 (setq type (if (match-end 1) org-scheduled-string
9820 (if (match-end 3) org-deadline-string "Plain:"))
9821 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
9822 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
9823 (setq n (string-to-number (match-string 2 ts))
9824 what (match-string 3 ts))
9825 (if (equal what "w") (setq n (* n 7) what "d"))
9826 ;; Preparation, see if we need to modify the start date for the change
9827 (when (match-end 1)
9828 (setq time (save-match-data (org-time-string-to-time ts)))
9829 (cond
9830 ((equal (match-string 1 ts) ".")
9831 ;; Shift starting date to today
9832 (org-timestamp-change
9833 (- (time-to-days (current-time)) (time-to-days time))
9834 'day))
9835 ((equal (match-string 1 ts) "+")
9836 (while (or (= nshift 0)
9837 (<= (time-to-days time) (time-to-days (current-time))))
9838 (when (= (incf nshift) nshiftmax)
9839 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
9840 (error "Abort")))
9841 (org-timestamp-change n (cdr (assoc what whata)))
9842 (org-at-timestamp-p t)
9843 (setq ts (match-string 1))
9844 (setq time (save-match-data (org-time-string-to-time ts))))
9845 (org-timestamp-change (- n) (cdr (assoc what whata)))
9846 ;; rematch, so that we have everything in place for the real shift
9847 (org-at-timestamp-p t)
9848 (setq ts (match-string 1))
9849 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
9850 (org-timestamp-change n (cdr (assoc what whata)))
9851 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
9852 (setq org-log-post-message msg)
9853 (message "%s" msg))))
9855 (defun org-show-todo-tree (arg)
9856 "Make a compact tree which shows all headlines marked with TODO.
9857 The tree will show the lines where the regexp matches, and all higher
9858 headlines above the match.
9859 With a \\[universal-argument] prefix, prompt for a regexp to match.
9860 With a numeric prefix N, construct a sparse tree for the Nth element
9861 of `org-todo-keywords-1'."
9862 (interactive "P")
9863 (let ((case-fold-search nil)
9864 (kwd-re
9865 (cond ((null arg) org-not-done-regexp)
9866 ((equal arg '(4))
9867 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
9868 (mapcar 'list org-todo-keywords-1))))
9869 (concat "\\("
9870 (mapconcat 'identity (org-split-string kwd "|") "\\|")
9871 "\\)\\>")))
9872 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
9873 (regexp-quote (nth (1- (prefix-numeric-value arg))
9874 org-todo-keywords-1)))
9875 (t (error "Invalid prefix argument: %s" arg)))))
9876 (message "%d TODO entries found"
9877 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
9879 (defun org-deadline (&optional remove time)
9880 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
9881 With argument REMOVE, remove any deadline from the item.
9882 When TIME is set, it should be an internal time specification, and the
9883 scheduling will use the corresponding date."
9884 (interactive "P")
9885 (if remove
9886 (progn
9887 (org-remove-timestamp-with-keyword org-deadline-string)
9888 (message "Item no longer has a deadline."))
9889 (if (org-get-repeat)
9890 (error "Cannot change deadline on task with repeater, please do that by hand")
9891 (org-add-planning-info 'deadline time 'closed)
9892 (message "Deadline on %s" org-last-inserted-timestamp))))
9894 (defun org-schedule (&optional remove time)
9895 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
9896 With argument REMOVE, remove any scheduling date from the item.
9897 When TIME is set, it should be an internal time specification, and the
9898 scheduling will use the corresponding date."
9899 (interactive "P")
9900 (if remove
9901 (progn
9902 (org-remove-timestamp-with-keyword org-scheduled-string)
9903 (message "Item is no longer scheduled."))
9904 (if (org-get-repeat)
9905 (error "Cannot reschedule task with repeater, please do that by hand")
9906 (org-add-planning-info 'scheduled time 'closed)
9907 (message "Scheduled to %s" org-last-inserted-timestamp))))
9909 (defun org-get-scheduled-time (pom &optional inherit)
9910 "Get the scheduled time as a time tuple, of a format suitable
9911 for calling org-schedule with, or if there is no scheduling,
9912 returns nil."
9913 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
9914 (when time
9915 (apply 'encode-time (org-parse-time-string time)))))
9917 (defun org-get-deadline-time (pom &optional inherit)
9918 "Get the deadine as a time tuple, of a format suitable for
9919 calling org-deadlin with, or if there is no scheduling, returns
9920 nil."
9921 (let ((time (org-entry-get pom "DEADLINE" inherit)))
9922 (when time
9923 (apply 'encode-time (org-parse-time-string time)))))
9925 (defun org-remove-timestamp-with-keyword (keyword)
9926 "Remove all time stamps with KEYWORD in the current entry."
9927 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
9928 beg)
9929 (save-excursion
9930 (org-back-to-heading t)
9931 (setq beg (point))
9932 (org-end-of-subtree t t)
9933 (while (re-search-backward re beg t)
9934 (replace-match "")
9935 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9936 (equal (char-before) ?\ ))
9937 (backward-delete-char 1)
9938 (if (string-match "^[ \t]*$" (buffer-substring
9939 (point-at-bol) (point-at-eol)))
9940 (delete-region (point-at-bol)
9941 (min (point-max) (1+ (point-at-eol))))))))))
9943 (defun org-add-planning-info (what &optional time &rest remove)
9944 "Insert new timestamp with keyword in the line directly after the headline.
9945 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9946 If non is given, the user is prompted for a date.
9947 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9948 be removed."
9949 (interactive)
9950 (let (org-time-was-given org-end-time-was-given ts
9951 end default-time default-input)
9953 (catch 'exit
9954 (when (and (not time) (memq what '(scheduled deadline)))
9955 ;; Try to get a default date/time from existing timestamp
9956 (save-excursion
9957 (org-back-to-heading t)
9958 (setq end (save-excursion (outline-next-heading) (point)))
9959 (when (re-search-forward (if (eq what 'scheduled)
9960 org-scheduled-time-regexp
9961 org-deadline-time-regexp)
9962 end t)
9963 (setq ts (match-string 1)
9964 default-time
9965 (apply 'encode-time (org-parse-time-string ts))
9966 default-input (and ts (org-get-compact-tod ts))))))
9967 (when what
9968 ;; If necessary, get the time from the user
9969 (setq time (or time (org-read-date nil 'to-time nil nil
9970 default-time default-input))))
9972 (when (and org-insert-labeled-timestamps-at-point
9973 (member what '(scheduled deadline)))
9974 (insert
9975 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9976 (org-insert-time-stamp time org-time-was-given
9977 nil nil nil (list org-end-time-was-given))
9978 (setq what nil))
9979 (save-excursion
9980 (save-restriction
9981 (let (col list elt ts buffer-invisibility-spec)
9982 (org-back-to-heading t)
9983 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9984 (goto-char (match-end 1))
9985 (setq col (current-column))
9986 (goto-char (match-end 0))
9987 (if (eobp) (insert "\n") (forward-char 1))
9988 (when (and (not what)
9989 (not (looking-at
9990 (concat "[ \t]*"
9991 org-keyword-time-not-clock-regexp))))
9992 ;; Nothing to add, nothing to remove...... :-)
9993 (throw 'exit nil))
9994 (if (and (not (looking-at outline-regexp))
9995 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9996 "[^\r\n]*"))
9997 (not (equal (match-string 1) org-clock-string)))
9998 (narrow-to-region (match-beginning 0) (match-end 0))
9999 (insert-before-markers "\n")
10000 (backward-char 1)
10001 (narrow-to-region (point) (point))
10002 (and org-adapt-indentation (org-indent-to-column col)))
10003 ;; Check if we have to remove something.
10004 (setq list (cons what remove))
10005 (while list
10006 (setq elt (pop list))
10007 (goto-char (point-min))
10008 (when (or (and (eq elt 'scheduled)
10009 (re-search-forward org-scheduled-time-regexp nil t))
10010 (and (eq elt 'deadline)
10011 (re-search-forward org-deadline-time-regexp nil t))
10012 (and (eq elt 'closed)
10013 (re-search-forward org-closed-time-regexp nil t)))
10014 (replace-match "")
10015 (if (looking-at "--+<[^>]+>") (replace-match ""))
10016 (if (looking-at " +") (replace-match ""))))
10017 (goto-char (point-max))
10018 (when what
10019 (insert
10020 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
10021 (cond ((eq what 'scheduled) org-scheduled-string)
10022 ((eq what 'deadline) org-deadline-string)
10023 ((eq what 'closed) org-closed-string))
10024 " ")
10025 (setq ts (org-insert-time-stamp
10026 time
10027 (or org-time-was-given
10028 (and (eq what 'closed) org-log-done-with-time))
10029 (eq what 'closed)
10030 nil nil (list org-end-time-was-given)))
10031 (end-of-line 1))
10032 (goto-char (point-min))
10033 (widen)
10034 (if (and (looking-at "[ \t]+\n")
10035 (equal (char-before) ?\n))
10036 (delete-region (1- (point)) (point-at-eol)))
10037 ts))))))
10039 (defvar org-log-note-marker (make-marker))
10040 (defvar org-log-note-purpose nil)
10041 (defvar org-log-note-state nil)
10042 (defvar org-log-note-previous-state nil)
10043 (defvar org-log-note-how nil)
10044 (defvar org-log-note-extra nil)
10045 (defvar org-log-note-window-configuration nil)
10046 (defvar org-log-note-return-to (make-marker))
10047 (defvar org-log-post-message nil
10048 "Message to be displayed after a log note has been stored.
10049 The auto-repeater uses this.")
10051 (defun org-add-note ()
10052 "Add a note to the current entry.
10053 This is done in the same way as adding a state change note."
10054 (interactive)
10055 (org-add-log-setup 'note nil nil 'findpos nil))
10057 (defvar org-property-end-re)
10058 (defun org-add-log-setup (&optional purpose state prev-state
10059 findpos how &optional extra)
10060 "Set up the post command hook to take a note.
10061 If this is about to TODO state change, the new state is expected in STATE.
10062 When FINDPOS is non-nil, find the correct position for the note in
10063 the current entry. If not, assume that it can be inserted at point.
10064 HOW is an indicator what kind of note should be created.
10065 EXTRA is additional text that will be inserted into the notes buffer."
10066 (let* ((org-log-into-drawer (org-log-into-drawer))
10067 (drawer (cond ((stringp org-log-into-drawer)
10068 org-log-into-drawer)
10069 (org-log-into-drawer "LOGBOOK")
10070 (t nil))))
10071 (save-restriction
10072 (save-excursion
10073 (when findpos
10074 (org-back-to-heading t)
10075 (narrow-to-region (point) (save-excursion
10076 (outline-next-heading) (point)))
10077 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
10078 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
10079 "[^\r\n]*\\)?"))
10080 (goto-char (match-end 0))
10081 (cond
10082 (drawer
10083 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
10084 nil t)
10085 (progn
10086 (goto-char (match-end 0))
10087 (or org-log-states-order-reversed
10088 (and (re-search-forward org-property-end-re nil t)
10089 (goto-char (1- (match-beginning 0))))))
10090 (insert "\n:" drawer ":\n:END:")
10091 (beginning-of-line 0)
10092 (org-indent-line-function)
10093 (beginning-of-line 2)
10094 (org-indent-line-function)
10095 (end-of-line 0)))
10096 ((and org-log-state-notes-insert-after-drawers
10097 (save-excursion
10098 (forward-line) (looking-at org-drawer-regexp)))
10099 (forward-line)
10100 (while (looking-at org-drawer-regexp)
10101 (goto-char (match-end 0))
10102 (re-search-forward org-property-end-re (point-max) t)
10103 (forward-line))
10104 (forward-line -1)))
10105 (unless org-log-states-order-reversed
10106 (and (= (char-after) ?\n) (forward-char 1))
10107 (org-skip-over-state-notes)
10108 (skip-chars-backward " \t\n\r")))
10109 (move-marker org-log-note-marker (point))
10110 (setq org-log-note-purpose purpose
10111 org-log-note-state state
10112 org-log-note-previous-state prev-state
10113 org-log-note-how how
10114 org-log-note-extra extra)
10115 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
10117 (defun org-skip-over-state-notes ()
10118 "Skip past the list of State notes in an entry."
10119 (if (looking-at "\n[ \t]*- State") (forward-char 1))
10120 (while (looking-at "[ \t]*- State")
10121 (condition-case nil
10122 (org-next-item)
10123 (error (org-end-of-item)))))
10125 (defun org-add-log-note (&optional purpose)
10126 "Pop up a window for taking a note, and add this note later at point."
10127 (remove-hook 'post-command-hook 'org-add-log-note)
10128 (setq org-log-note-window-configuration (current-window-configuration))
10129 (delete-other-windows)
10130 (move-marker org-log-note-return-to (point))
10131 (switch-to-buffer (marker-buffer org-log-note-marker))
10132 (goto-char org-log-note-marker)
10133 (org-switch-to-buffer-other-window "*Org Note*")
10134 (erase-buffer)
10135 (if (memq org-log-note-how '(time state))
10136 (let (current-prefix-arg) (org-store-log-note))
10137 (let ((org-inhibit-startup t)) (org-mode))
10138 (insert (format "# Insert note for %s.
10139 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10140 (cond
10141 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10142 ((eq org-log-note-purpose 'done) "closed todo item")
10143 ((eq org-log-note-purpose 'state)
10144 (format "state change from \"%s\" to \"%s\""
10145 (or org-log-note-previous-state "")
10146 (or org-log-note-state "")))
10147 ((eq org-log-note-purpose 'note)
10148 "this entry")
10149 (t (error "This should not happen")))))
10150 (if org-log-note-extra (insert org-log-note-extra))
10151 (org-set-local 'org-finish-function 'org-store-log-note)))
10153 (defvar org-note-abort nil) ; dynamically scoped
10154 (defun org-store-log-note ()
10155 "Finish taking a log note, and insert it to where it belongs."
10156 (let ((txt (buffer-string))
10157 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10158 lines ind)
10159 (kill-buffer (current-buffer))
10160 (while (string-match "\\`#.*\n[ \t\n]*" txt)
10161 (setq txt (replace-match "" t t txt)))
10162 (if (string-match "\\s-+\\'" txt)
10163 (setq txt (replace-match "" t t txt)))
10164 (setq lines (org-split-string txt "\n"))
10165 (when (and note (string-match "\\S-" note))
10166 (setq note
10167 (org-replace-escapes
10168 note
10169 (list (cons "%u" (user-login-name))
10170 (cons "%U" user-full-name)
10171 (cons "%t" (format-time-string
10172 (org-time-stamp-format 'long 'inactive)
10173 (current-time)))
10174 (cons "%s" (if org-log-note-state
10175 (concat "\"" org-log-note-state "\"")
10176 ""))
10177 (cons "%S" (if org-log-note-previous-state
10178 (concat "\"" org-log-note-previous-state "\"")
10179 "\"\"")))))
10180 (if lines (setq note (concat note " \\\\")))
10181 (push note lines))
10182 (when (or current-prefix-arg org-note-abort)
10183 (when org-log-into-drawer
10184 (org-remove-empty-drawer-at
10185 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
10186 org-log-note-marker))
10187 (setq lines nil))
10188 (when lines
10189 (save-excursion
10190 (set-buffer (marker-buffer org-log-note-marker))
10191 (save-excursion
10192 (goto-char org-log-note-marker)
10193 (move-marker org-log-note-marker nil)
10194 (end-of-line 1)
10195 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
10196 (insert "- " (pop lines))
10197 (org-indent-line-function)
10198 (beginning-of-line 1)
10199 (looking-at "[ \t]*")
10200 (setq ind (concat (match-string 0) " "))
10201 (end-of-line 1)
10202 (while lines (insert "\n" ind (pop lines)))
10203 (message "Note stored")
10204 (org-back-to-heading t)
10205 (org-cycle-hide-drawers 'children)))))
10206 (set-window-configuration org-log-note-window-configuration)
10207 (with-current-buffer (marker-buffer org-log-note-return-to)
10208 (goto-char org-log-note-return-to))
10209 (move-marker org-log-note-return-to nil)
10210 (and org-log-post-message (message "%s" org-log-post-message)))
10212 (defun org-remove-empty-drawer-at (drawer pos)
10213 "Remove an emptyr DARWER drawer at position POS.
10214 POS may also be a marker."
10215 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
10216 (save-excursion
10217 (save-restriction
10218 (widen)
10219 (goto-char pos)
10220 (if (org-in-regexp
10221 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
10222 (replace-match ""))))))
10224 (defun org-sparse-tree (&optional arg)
10225 "Create a sparse tree, prompt for the details.
10226 This command can create sparse trees. You first need to select the type
10227 of match used to create the tree:
10229 t Show entries with a specific TODO keyword.
10230 m Show entries selected by a tags/property match.
10231 p Enter a property name and its value (both with completion on existing
10232 names/values) and show entries with that property.
10233 r Show entries matching a regular expression.
10234 d Show deadlines due within `org-deadline-warning-days'.
10235 b Show deadlines and scheduled items before a date.
10236 a Show deadlines and scheduled items after a date."
10237 (interactive "P")
10238 (let (ans kwd value)
10239 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
10240 (setq ans (read-char-exclusive))
10241 (cond
10242 ((equal ans ?d)
10243 (call-interactively 'org-check-deadlines))
10244 ((equal ans ?b)
10245 (call-interactively 'org-check-before-date))
10246 ((equal ans ?a)
10247 (call-interactively 'org-check-after-date))
10248 ((equal ans ?t)
10249 (org-show-todo-tree '(4)))
10250 ((member ans '(?T ?m))
10251 (call-interactively 'org-match-sparse-tree))
10252 ((member ans '(?p ?P))
10253 (setq kwd (org-ido-completing-read "Property: "
10254 (mapcar 'list (org-buffer-property-keys))))
10255 (setq value (org-ido-completing-read "Value: "
10256 (mapcar 'list (org-property-values kwd))))
10257 (unless (string-match "\\`{.*}\\'" value)
10258 (setq value (concat "\"" value "\"")))
10259 (org-match-sparse-tree arg (concat kwd "=" value)))
10260 ((member ans '(?r ?R ?/))
10261 (call-interactively 'org-occur))
10262 (t (error "No such sparse tree command \"%c\"" ans)))))
10264 (defvar org-occur-highlights nil
10265 "List of overlays used for occur matches.")
10266 (make-variable-buffer-local 'org-occur-highlights)
10267 (defvar org-occur-parameters nil
10268 "Parameters of the active org-occur calls.
10269 This is a list, each call to org-occur pushes as cons cell,
10270 containing the regular expression and the callback, onto the list.
10271 The list can contain several entries if `org-occur' has been called
10272 several time with the KEEP-PREVIOUS argument. Otherwise, this list
10273 will only contain one set of parameters. When the highlights are
10274 removed (for example with `C-c C-c', or with the next edit (depending
10275 on `org-remove-highlights-with-change'), this variable is emptied
10276 as well.")
10277 (make-variable-buffer-local 'org-occur-parameters)
10279 (defun org-occur (regexp &optional keep-previous callback)
10280 "Make a compact tree which shows all matches of REGEXP.
10281 The tree will show the lines where the regexp matches, and all higher
10282 headlines above the match. It will also show the heading after the match,
10283 to make sure editing the matching entry is easy.
10284 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
10285 call to `org-occur' will be kept, to allow stacking of calls to this
10286 command.
10287 If CALLBACK is non-nil, it is a function which is called to confirm
10288 that the match should indeed be shown."
10289 (interactive "sRegexp: \nP")
10290 (when (equal regexp "")
10291 (error "Regexp cannot be empty"))
10292 (unless keep-previous
10293 (org-remove-occur-highlights nil nil t))
10294 (push (cons regexp callback) org-occur-parameters)
10295 (let ((cnt 0))
10296 (save-excursion
10297 (goto-char (point-min))
10298 (if (or (not keep-previous) ; do not want to keep
10299 (not org-occur-highlights)) ; no previous matches
10300 ;; hide everything
10301 (org-overview))
10302 (while (re-search-forward regexp nil t)
10303 (when (or (not callback)
10304 (save-match-data (funcall callback)))
10305 (setq cnt (1+ cnt))
10306 (when org-highlight-sparse-tree-matches
10307 (org-highlight-new-match (match-beginning 0) (match-end 0)))
10308 (org-show-context 'occur-tree))))
10309 (when org-remove-highlights-with-change
10310 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10311 nil 'local))
10312 (unless org-sparse-tree-open-archived-trees
10313 (org-hide-archived-subtrees (point-min) (point-max)))
10314 (run-hooks 'org-occur-hook)
10315 (if (interactive-p)
10316 (message "%d match(es) for regexp %s" cnt regexp))
10317 cnt))
10319 (defun org-show-context (&optional key)
10320 "Make sure point and context and visible.
10321 How much context is shown depends upon the variables
10322 `org-show-hierarchy-above', `org-show-following-heading'. and
10323 `org-show-siblings'."
10324 (let ((heading-p (org-on-heading-p t))
10325 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
10326 (following-p (org-get-alist-option org-show-following-heading key))
10327 (entry-p (org-get-alist-option org-show-entry-below key))
10328 (siblings-p (org-get-alist-option org-show-siblings key)))
10329 (catch 'exit
10330 ;; Show heading or entry text
10331 (if (and heading-p (not entry-p))
10332 (org-flag-heading nil) ; only show the heading
10333 (and (or entry-p (org-invisible-p) (org-invisible-p2))
10334 (org-show-hidden-entry))) ; show entire entry
10335 (when following-p
10336 ;; Show next sibling, or heading below text
10337 (save-excursion
10338 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10339 (org-flag-heading nil))))
10340 (when siblings-p (org-show-siblings))
10341 (when hierarchy-p
10342 ;; show all higher headings, possibly with siblings
10343 (save-excursion
10344 (while (and (condition-case nil
10345 (progn (org-up-heading-all 1) t)
10346 (error nil))
10347 (not (bobp)))
10348 (org-flag-heading nil)
10349 (when siblings-p (org-show-siblings))))))))
10351 (defun org-reveal (&optional siblings)
10352 "Show current entry, hierarchy above it, and the following headline.
10353 This can be used to show a consistent set of context around locations
10354 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10355 not t for the search context.
10357 With optional argument SIBLINGS, on each level of the hierarchy all
10358 siblings are shown. This repairs the tree structure to what it would
10359 look like when opened with hierarchical calls to `org-cycle'."
10360 (interactive "P")
10361 (let ((org-show-hierarchy-above t)
10362 (org-show-following-heading t)
10363 (org-show-siblings (if siblings t org-show-siblings)))
10364 (org-show-context nil)))
10366 (defun org-highlight-new-match (beg end)
10367 "Highlight from BEG to END and mark the highlight is an occur headline."
10368 (let ((ov (org-make-overlay beg end)))
10369 (org-overlay-put ov 'face 'secondary-selection)
10370 (push ov org-occur-highlights)))
10372 (defun org-remove-occur-highlights (&optional beg end noremove)
10373 "Remove the occur highlights from the buffer.
10374 BEG and END are ignored. If NOREMOVE is nil, remove this function
10375 from the `before-change-functions' in the current buffer."
10376 (interactive)
10377 (unless org-inhibit-highlight-removal
10378 (mapc 'org-delete-overlay org-occur-highlights)
10379 (setq org-occur-highlights nil)
10380 (setq org-occur-parameters nil)
10381 (unless noremove
10382 (remove-hook 'before-change-functions
10383 'org-remove-occur-highlights 'local))))
10385 ;;;; Priorities
10387 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
10388 "Regular expression matching the priority indicator.")
10390 (defvar org-remove-priority-next-time nil)
10392 (defun org-priority-up ()
10393 "Increase the priority of the current item."
10394 (interactive)
10395 (org-priority 'up))
10397 (defun org-priority-down ()
10398 "Decrease the priority of the current item."
10399 (interactive)
10400 (org-priority 'down))
10402 (defun org-priority (&optional action)
10403 "Change the priority of an item by ARG.
10404 ACTION can be `set', `up', `down', or a character."
10405 (interactive)
10406 (unless org-enable-priority-commands
10407 (error "Priority commands are disabled"))
10408 (setq action (or action 'set))
10409 (let (current new news have remove)
10410 (save-excursion
10411 (org-back-to-heading t)
10412 (if (looking-at org-priority-regexp)
10413 (setq current (string-to-char (match-string 2))
10414 have t)
10415 (setq current org-default-priority))
10416 (cond
10417 ((or (eq action 'set)
10418 (if (featurep 'xemacs) (characterp action) (integerp action)))
10419 (if (not (eq action 'set))
10420 (setq new action)
10421 (message "Priority %c-%c, SPC to remove: "
10422 org-highest-priority org-lowest-priority)
10423 (setq new (read-char-exclusive)))
10424 (if (and (= (upcase org-highest-priority) org-highest-priority)
10425 (= (upcase org-lowest-priority) org-lowest-priority))
10426 (setq new (upcase new)))
10427 (cond ((equal new ?\ ) (setq remove t))
10428 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
10429 (error "Priority must be between `%c' and `%c'"
10430 org-highest-priority org-lowest-priority))))
10431 ((eq action 'up)
10432 (if (and (not have) (eq last-command this-command))
10433 (setq new org-lowest-priority)
10434 (setq new (if (and org-priority-start-cycle-with-default (not have))
10435 org-default-priority (1- current)))))
10436 ((eq action 'down)
10437 (if (and (not have) (eq last-command this-command))
10438 (setq new org-highest-priority)
10439 (setq new (if (and org-priority-start-cycle-with-default (not have))
10440 org-default-priority (1+ current)))))
10441 (t (error "Invalid action")))
10442 (if (or (< (upcase new) org-highest-priority)
10443 (> (upcase new) org-lowest-priority))
10444 (setq remove t))
10445 (setq news (format "%c" new))
10446 (if have
10447 (if remove
10448 (replace-match "" t t nil 1)
10449 (replace-match news t t nil 2))
10450 (if remove
10451 (error "No priority cookie found in line")
10452 (let ((case-fold-search nil))
10453 (looking-at org-todo-line-regexp))
10454 (if (match-end 2)
10455 (progn
10456 (goto-char (match-end 2))
10457 (insert " [#" news "]"))
10458 (goto-char (match-beginning 3))
10459 (insert "[#" news "] "))))
10460 (org-preserve-lc (org-set-tags nil 'align)))
10461 (if remove
10462 (message "Priority removed")
10463 (message "Priority of current item set to %s" news))))
10465 (defun org-get-priority (s)
10466 "Find priority cookie and return priority."
10467 (save-match-data
10468 (if (not (string-match org-priority-regexp s))
10469 (* 1000 (- org-lowest-priority org-default-priority))
10470 (* 1000 (- org-lowest-priority
10471 (string-to-char (match-string 2 s)))))))
10473 ;;;; Tags
10475 (defvar org-agenda-archives-mode)
10476 (defvar org-map-continue-from nil
10477 "Position from where mapping should continue.
10478 Can be set byt the action argument to `org-scan-tag's and `org-map-entries'.")
10480 (defvar org-scanner-tags nil
10481 "The current tag list while the tags scanner is running.")
10482 (defvar org-trust-scanner-tags nil
10483 "Should `org-get-tags-at' use the tags fro the scanner.
10484 This is for internal dynamical scoping only.
10485 When this is non-nil, the function `org-get-tags-at' will return the value
10486 of `org-scanner-tags' instead of building the list by itself. This
10487 can lead to large speed-ups when the tags scanner is used in a file with
10488 many entries, and when the list of tags is retrieved, for example to
10489 obtain a list of properties. Building the tags list for each entry in such
10490 a file becomes an N^2 operation - but with this variable set, it scales
10491 as N.")
10493 (defun org-scan-tags (action matcher &optional todo-only)
10494 "Scan headline tags with inheritance and produce output ACTION.
10496 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
10497 or `agenda' to produce an entry list for an agenda view. It can also be
10498 a Lisp form or a function that should be called at each matched headline, in
10499 this case the return value is a list of all return values from these calls.
10501 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
10502 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
10503 only lines with a TODO keyword are included in the output."
10504 (require 'org-agenda)
10505 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
10506 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
10507 (org-re
10508 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
10509 (props (list 'face 'default
10510 'done-face 'org-agenda-done
10511 'undone-face 'default
10512 'mouse-face 'highlight
10513 'org-not-done-regexp org-not-done-regexp
10514 'org-todo-regexp org-todo-regexp
10515 'keymap org-agenda-keymap
10516 'help-echo
10517 (format "mouse-2 or RET jump to org file %s"
10518 (abbreviate-file-name
10519 (or (buffer-file-name (buffer-base-buffer))
10520 (buffer-name (buffer-base-buffer)))))))
10521 (case-fold-search nil)
10522 (org-map-continue-from nil)
10523 lspos tags tags-list
10524 (tags-alist (list (cons 0 org-file-tags)))
10525 (llast 0) rtn rtn1 level category i txt
10526 todo marker entry priority)
10527 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
10528 (setq action (list 'lambda nil action)))
10529 (save-excursion
10530 (goto-char (point-min))
10531 (when (eq action 'sparse-tree)
10532 (org-overview)
10533 (org-remove-occur-highlights))
10534 (while (re-search-forward re nil t)
10535 (catch :skip
10536 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
10537 tags (if (match-end 4) (org-match-string-no-properties 4)))
10538 (goto-char (setq lspos (match-beginning 0)))
10539 (setq level (org-reduced-level (funcall outline-level))
10540 category (org-get-category))
10541 (setq i llast llast level)
10542 ;; remove tag lists from same and sublevels
10543 (while (>= i level)
10544 (when (setq entry (assoc i tags-alist))
10545 (setq tags-alist (delete entry tags-alist)))
10546 (setq i (1- i)))
10547 ;; add the next tags
10548 (when tags
10549 (setq tags (org-split-string tags ":")
10550 tags-alist
10551 (cons (cons level tags) tags-alist)))
10552 ;; compile tags for current headline
10553 (setq tags-list
10554 (if org-use-tag-inheritance
10555 (apply 'append (mapcar 'cdr (reverse tags-alist)))
10556 tags)
10557 org-scanner-tags tags-list)
10558 (when org-use-tag-inheritance
10559 (setcdr (car tags-alist)
10560 (mapcar (lambda (x)
10561 (setq x (copy-sequence x))
10562 (org-add-prop-inherited x))
10563 (cdar tags-alist))))
10564 (when (and tags org-use-tag-inheritance
10565 (or (not (eq t org-use-tag-inheritance))
10566 org-tags-exclude-from-inheritance))
10567 ;; selective inheritance, remove uninherited ones
10568 (setcdr (car tags-alist)
10569 (org-remove-uniherited-tags (cdar tags-alist))))
10570 (when (and (or (not todo-only)
10571 (and (member todo org-not-done-keywords)
10572 (or (not org-agenda-tags-todo-honor-ignore-options)
10573 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
10574 (let ((case-fold-search t)) (eval matcher))
10576 (not (member org-archive-tag tags-list))
10577 ;; we have an archive tag, should we use this anyway?
10578 (or (not org-agenda-skip-archived-trees)
10579 (and (eq action 'agenda) org-agenda-archives-mode))))
10580 (unless (eq action 'sparse-tree) (org-agenda-skip))
10582 ;; select this headline
10584 (cond
10585 ((eq action 'sparse-tree)
10586 (and org-highlight-sparse-tree-matches
10587 (org-get-heading) (match-end 0)
10588 (org-highlight-new-match
10589 (match-beginning 0) (match-beginning 1)))
10590 (org-show-context 'tags-tree))
10591 ((eq action 'agenda)
10592 (setq txt (org-format-agenda-item
10594 (concat
10595 (if (eq org-tags-match-list-sublevels 'indented)
10596 (make-string (1- level) ?.) "")
10597 (org-get-heading))
10598 category
10599 tags-list
10601 priority (org-get-priority txt))
10602 (goto-char lspos)
10603 (setq marker (org-agenda-new-marker))
10604 (org-add-props txt props
10605 'org-marker marker 'org-hd-marker marker 'org-category category
10606 'todo-state todo
10607 'priority priority 'type "tagsmatch")
10608 (push txt rtn))
10609 ((functionp action)
10610 (setq org-map-continue-from nil)
10611 (save-excursion
10612 (setq rtn1 (funcall action))
10613 (push rtn1 rtn)))
10614 (t (error "Invalid action")))
10616 ;; if we are to skip sublevels, jump to end of subtree
10617 (unless org-tags-match-list-sublevels
10618 (org-end-of-subtree t)
10619 (backward-char 1))))
10620 ;; Get the correct position from where to continue
10621 (if org-map-continue-from
10622 (goto-char org-map-continue-from)
10623 (and (= (point) lspos) (end-of-line 1)))))
10624 (when (and (eq action 'sparse-tree)
10625 (not org-sparse-tree-open-archived-trees))
10626 (org-hide-archived-subtrees (point-min) (point-max)))
10627 (nreverse rtn)))
10629 (defun org-remove-uniherited-tags (tags)
10630 "Remove all tags that are not inherited from the list TAGS."
10631 (cond
10632 ((eq org-use-tag-inheritance t)
10633 (if org-tags-exclude-from-inheritance
10634 (org-delete-all org-tags-exclude-from-inheritance tags)
10635 tags))
10636 ((not org-use-tag-inheritance) nil)
10637 ((stringp org-use-tag-inheritance)
10638 (delq nil (mapcar
10639 (lambda (x)
10640 (if (and (string-match org-use-tag-inheritance x)
10641 (not (member x org-tags-exclude-from-inheritance)))
10642 x nil))
10643 tags)))
10644 ((listp org-use-tag-inheritance)
10645 (delq nil (mapcar
10646 (lambda (x)
10647 (if (member x org-use-tag-inheritance) x nil))
10648 tags)))))
10650 (defvar todo-only) ;; dynamically scoped
10652 (defun org-match-sparse-tree (&optional todo-only match)
10653 "Create a sparse tree according to tags string MATCH.
10654 MATCH can contain positive and negative selection of tags, like
10655 \"+WORK+URGENT-WITHBOSS\".
10656 If optional argument TODO-ONLY is non-nil, only select lines that are
10657 also TODO lines."
10658 (interactive "P")
10659 (org-prepare-agenda-buffers (list (current-buffer)))
10660 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
10662 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
10664 (defvar org-cached-props nil)
10665 (defun org-cached-entry-get (pom property)
10666 (if (or (eq t org-use-property-inheritance)
10667 (and (stringp org-use-property-inheritance)
10668 (string-match org-use-property-inheritance property))
10669 (and (listp org-use-property-inheritance)
10670 (member property org-use-property-inheritance)))
10671 ;; Caching is not possible, check it directly
10672 (org-entry-get pom property 'inherit)
10673 ;; Get all properties, so that we can do complicated checks easily
10674 (cdr (assoc property (or org-cached-props
10675 (setq org-cached-props
10676 (org-entry-properties pom)))))))
10678 (defun org-global-tags-completion-table (&optional files)
10679 "Return the list of all tags in all agenda buffer/files."
10680 (save-excursion
10681 (org-uniquify
10682 (delq nil
10683 (apply 'append
10684 (mapcar
10685 (lambda (file)
10686 (set-buffer (find-file-noselect file))
10687 (append (org-get-buffer-tags)
10688 (mapcar (lambda (x) (if (stringp (car-safe x))
10689 (list (car-safe x)) nil))
10690 org-tag-alist)))
10691 (if (and files (car files))
10692 files
10693 (org-agenda-files))))))))
10695 (defun org-make-tags-matcher (match)
10696 "Create the TAGS//TODO matcher form for the selection string MATCH."
10697 ;; todo-only is scoped dynamically into this function, and the function
10698 ;; may change it if the matcher asks for it.
10699 (unless match
10700 ;; Get a new match request, with completion
10701 (let ((org-last-tags-completion-table
10702 (org-global-tags-completion-table)))
10703 (setq match (org-completing-read-no-ido
10704 "Match: " 'org-tags-completion-function nil nil nil
10705 'org-tags-history))))
10707 ;; Parse the string and create a lisp form
10708 (let ((match0 match)
10709 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
10710 minus tag mm
10711 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
10712 orterms term orlist re-p str-p level-p level-op time-p
10713 prop-p pn pv po cat-p gv rest)
10714 (if (string-match "/+" match)
10715 ;; match contains also a todo-matching request
10716 (progn
10717 (setq tagsmatch (substring match 0 (match-beginning 0))
10718 todomatch (substring match (match-end 0)))
10719 (if (string-match "^!" todomatch)
10720 (setq todo-only t todomatch (substring todomatch 1)))
10721 (if (string-match "^\\s-*$" todomatch)
10722 (setq todomatch nil)))
10723 ;; only matching tags
10724 (setq tagsmatch match todomatch nil))
10726 ;; Make the tags matcher
10727 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10728 (setq tagsmatcher t)
10729 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10730 (while (setq term (pop orterms))
10731 (while (and (equal (substring term -1) "\\") orterms)
10732 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10733 (while (string-match re term)
10734 (setq rest (substring term (match-end 0))
10735 minus (and (match-end 1)
10736 (equal (match-string 1 term) "-"))
10737 tag (match-string 2 term)
10738 re-p (equal (string-to-char tag) ?{)
10739 level-p (match-end 4)
10740 prop-p (match-end 5)
10741 mm (cond
10742 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10743 (level-p
10744 (setq level-op (org-op-to-function (match-string 3 term)))
10745 `(,level-op level ,(string-to-number
10746 (match-string 4 term))))
10747 (prop-p
10748 (setq pn (match-string 5 term)
10749 po (match-string 6 term)
10750 pv (match-string 7 term)
10751 cat-p (equal pn "CATEGORY")
10752 re-p (equal (string-to-char pv) ?{)
10753 str-p (equal (string-to-char pv) ?\")
10754 time-p (save-match-data
10755 (string-match "^\"[[<].*[]>]\"$" pv))
10756 pv (if (or re-p str-p) (substring pv 1 -1) pv))
10757 (if time-p (setq pv (org-matcher-time pv)))
10758 (setq po (org-op-to-function po (if time-p 'time str-p)))
10759 (cond
10760 ((equal pn "CATEGORY")
10761 (setq gv '(get-text-property (point) 'org-category)))
10762 ((equal pn "TODO")
10763 (setq gv 'todo))
10765 (setq gv `(org-cached-entry-get nil ,pn))))
10766 (if re-p
10767 (if (eq po 'org<>)
10768 `(not (string-match ,pv (or ,gv "")))
10769 `(string-match ,pv (or ,gv "")))
10770 (if str-p
10771 `(,po (or ,gv "") ,pv)
10772 `(,po (string-to-number (or ,gv ""))
10773 ,(string-to-number pv) ))))
10774 (t `(member ,tag tags-list)))
10775 mm (if minus (list 'not mm) mm)
10776 term rest)
10777 (push mm tagsmatcher))
10778 (push (if (> (length tagsmatcher) 1)
10779 (cons 'and tagsmatcher)
10780 (car tagsmatcher))
10781 orlist)
10782 (setq tagsmatcher nil))
10783 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
10784 (setq tagsmatcher
10785 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
10786 ;; Make the todo matcher
10787 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10788 (setq todomatcher t)
10789 (setq orterms (org-split-string todomatch "|") orlist nil)
10790 (while (setq term (pop orterms))
10791 (while (string-match re term)
10792 (setq minus (and (match-end 1)
10793 (equal (match-string 1 term) "-"))
10794 kwd (match-string 2 term)
10795 re-p (equal (string-to-char kwd) ?{)
10796 term (substring term (match-end 0))
10797 mm (if re-p
10798 `(string-match ,(substring kwd 1 -1) todo)
10799 (list 'equal 'todo kwd))
10800 mm (if minus (list 'not mm) mm))
10801 (push mm todomatcher))
10802 (push (if (> (length todomatcher) 1)
10803 (cons 'and todomatcher)
10804 (car todomatcher))
10805 orlist)
10806 (setq todomatcher nil))
10807 (setq todomatcher (if (> (length orlist) 1)
10808 (cons 'or orlist) (car orlist))))
10810 ;; Return the string and lisp forms of the matcher
10811 (setq matcher (if todomatcher
10812 (list 'and tagsmatcher todomatcher)
10813 tagsmatcher))
10814 (cons match0 matcher)))
10816 (defun org-op-to-function (op &optional stringp)
10817 "Turn an operator into the appropriate function."
10818 (setq op
10819 (cond
10820 ((equal op "<" ) '(< string< org-time<))
10821 ((equal op ">" ) '(> org-string> org-time>))
10822 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
10823 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
10824 ((member op '("=" "==")) '(= string= org-time=))
10825 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
10826 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
10828 (defun org<> (a b) (not (= a b)))
10829 (defun org-string<= (a b) (or (string= a b) (string< a b)))
10830 (defun org-string>= (a b) (not (string< a b)))
10831 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
10832 (defun org-string<> (a b) (not (string= a b)))
10833 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
10834 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
10835 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
10836 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
10837 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
10838 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
10839 (defun org-2ft (s)
10840 "Convert S to a floating point time.
10841 If S is already a number, just return it. If it is a string, parse
10842 it as a time string and apply `float-time' to it. If S is nil, just return 0."
10843 (cond
10844 ((numberp s) s)
10845 ((stringp s)
10846 (condition-case nil
10847 (float-time (apply 'encode-time (org-parse-time-string s)))
10848 (error 0.)))
10849 (t 0.)))
10851 (defun org-time-today ()
10852 "Time in seconds today at 0:00.
10853 Returns the float number of seconds since the beginning of the
10854 epoch to the beginning of today (00:00)."
10855 (float-time (apply 'encode-time
10856 (append '(0 0 0) (nthcdr 3 (decode-time))))))
10858 (defun org-matcher-time (s)
10859 "Interpret a time comparison value."
10860 (save-match-data
10861 (cond
10862 ((string= s "<now>") (float-time))
10863 ((string= s "<today>") (org-time-today))
10864 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
10865 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
10866 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
10867 (+ (org-time-today)
10868 (* (string-to-number (match-string 1 s))
10869 (cdr (assoc (match-string 2 s)
10870 '(("d" . 86400.0) ("w" . 604800.0)
10871 ("m" . 2678400.0) ("y" . 31557600.0)))))))
10872 (t (org-2ft s)))))
10874 (defun org-match-any-p (re list)
10875 "Does re match any element of list?"
10876 (setq list (mapcar (lambda (x) (string-match re x)) list))
10877 (delq nil list))
10879 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
10880 (defvar org-tags-overlay (org-make-overlay 1 1))
10881 (org-detach-overlay org-tags-overlay)
10883 (defun org-get-local-tags-at (&optional pos)
10884 "Get a list of tags defined in the current headline."
10885 (org-get-tags-at pos 'local))
10887 (defun org-get-local-tags ()
10888 "Get a list of tags defined in the current headline."
10889 (org-get-tags-at nil 'local))
10891 (defun org-get-tags-at (&optional pos local)
10892 "Get a list of all headline tags applicable at POS.
10893 POS defaults to point. If tags are inherited, the list contains
10894 the targets in the same sequence as the headlines appear, i.e.
10895 the tags of the current headline come last.
10896 When LOCAL is non-nil, only return tags from the current headline,
10897 ignore inherited ones."
10898 (interactive)
10899 (if (and org-trust-scanner-tags
10900 (or (not pos) (equal pos (point)))
10901 (not local))
10902 org-scanner-tags
10903 (let (tags ltags lastpos parent)
10904 (save-excursion
10905 (save-restriction
10906 (widen)
10907 (goto-char (or pos (point)))
10908 (save-match-data
10909 (catch 'done
10910 (condition-case nil
10911 (progn
10912 (org-back-to-heading t)
10913 (while (not (equal lastpos (point)))
10914 (setq lastpos (point))
10915 (when (looking-at
10916 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
10917 (setq ltags (org-split-string
10918 (org-match-string-no-properties 1) ":"))
10919 (when parent
10920 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
10921 (setq tags (append
10922 (if parent
10923 (org-remove-uniherited-tags ltags)
10924 ltags)
10925 tags)))
10926 (or org-use-tag-inheritance (throw 'done t))
10927 (if local (throw 'done t))
10928 (or (org-up-heading-safe) (error nil))
10929 (setq parent t)))
10930 (error nil)))))
10931 (append (org-remove-uniherited-tags org-file-tags) tags)))))
10933 (defun org-add-prop-inherited (s)
10934 (add-text-properties 0 (length s) '(inherited t) s)
10937 (defun org-toggle-tag (tag &optional onoff)
10938 "Toggle the tag TAG for the current line.
10939 If ONOFF is `on' or `off', don't toggle but set to this state."
10940 (let (res current)
10941 (save-excursion
10942 (org-back-to-heading t)
10943 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
10944 (point-at-eol) t)
10945 (progn
10946 (setq current (match-string 1))
10947 (replace-match ""))
10948 (setq current ""))
10949 (setq current (nreverse (org-split-string current ":")))
10950 (cond
10951 ((eq onoff 'on)
10952 (setq res t)
10953 (or (member tag current) (push tag current)))
10954 ((eq onoff 'off)
10955 (or (not (member tag current)) (setq current (delete tag current))))
10956 (t (if (member tag current)
10957 (setq current (delete tag current))
10958 (setq res t)
10959 (push tag current))))
10960 (end-of-line 1)
10961 (if current
10962 (progn
10963 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
10964 (org-set-tags nil t))
10965 (delete-horizontal-space))
10966 (run-hooks 'org-after-tags-change-hook))
10967 res))
10969 (defun org-align-tags-here (to-col)
10970 ;; Assumes that this is a headline
10971 (let ((pos (point)) (col (current-column)) ncol tags-l p)
10972 (beginning-of-line 1)
10973 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10974 (< pos (match-beginning 2)))
10975 (progn
10976 (setq tags-l (- (match-end 2) (match-beginning 2)))
10977 (goto-char (match-beginning 1))
10978 (insert " ")
10979 (delete-region (point) (1+ (match-beginning 2)))
10980 (setq ncol (max (1+ (current-column))
10981 (1+ col)
10982 (if (> to-col 0)
10983 to-col
10984 (- (abs to-col) tags-l))))
10985 (setq p (point))
10986 (insert (make-string (- ncol (current-column)) ?\ ))
10987 (setq ncol (current-column))
10988 (when indent-tabs-mode (tabify p (point-at-eol)))
10989 (org-move-to-column (min ncol col) t))
10990 (goto-char pos))))
10992 (defun org-set-tags-command (&optional arg just-align)
10993 "Call the set-tags command for the current entry."
10994 (interactive "P")
10995 (if (org-on-heading-p)
10996 (org-set-tags arg just-align)
10997 (save-excursion
10998 (org-back-to-heading t)
10999 (org-set-tags arg just-align))))
11001 (defun org-set-tags (&optional arg just-align)
11002 "Set the tags for the current headline.
11003 With prefix ARG, realign all tags in headings in the current buffer."
11004 (interactive "P")
11005 (let* ((re (concat "^" outline-regexp))
11006 (current (org-get-tags-string))
11007 (col (current-column))
11008 (org-setting-tags t)
11009 table current-tags inherited-tags ; computed below when needed
11010 tags p0 c0 c1 rpl)
11011 (if arg
11012 (save-excursion
11013 (goto-char (point-min))
11014 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
11015 (while (re-search-forward re nil t)
11016 (org-set-tags nil t)
11017 (end-of-line 1)))
11018 (message "All tags realigned to column %d" org-tags-column))
11019 (if just-align
11020 (setq tags current)
11021 ;; Get a new set of tags from the user
11022 (save-excursion
11023 (setq table (append org-tag-persistent-alist
11024 (or org-tag-alist (org-get-buffer-tags)))
11025 org-last-tags-completion-table table
11026 current-tags (org-split-string current ":")
11027 inherited-tags (nreverse
11028 (nthcdr (length current-tags)
11029 (nreverse (org-get-tags-at))))
11030 tags
11031 (if (or (eq t org-use-fast-tag-selection)
11032 (and org-use-fast-tag-selection
11033 (delq nil (mapcar 'cdr table))))
11034 (org-fast-tag-selection
11035 current-tags inherited-tags table
11036 (if org-fast-tag-selection-include-todo org-todo-key-alist))
11037 (let ((org-add-colon-after-tag-completion t))
11038 (org-trim
11039 (org-without-partial-completion
11040 (org-ido-completing-read "Tags: " 'org-tags-completion-function
11041 nil nil current 'org-tags-history)))))))
11042 (while (string-match "[-+&]+" tags)
11043 ;; No boolean logic, just a list
11044 (setq tags (replace-match ":" t t tags))))
11046 (if org-tags-sort-function
11047 (setq tags (mapconcat 'identity
11048 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
11049 org-tags-sort-function) ":")))
11051 (if (string-match "\\`[\t ]*\\'" tags)
11052 (setq tags "")
11053 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
11054 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
11056 ;; Insert new tags at the correct column
11057 (beginning-of-line 1)
11058 (cond
11059 ((and (equal current "") (equal tags "")))
11060 ((re-search-forward
11061 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
11062 (point-at-eol) t)
11063 (if (equal tags "")
11064 (setq rpl "")
11065 (goto-char (match-beginning 0))
11066 (setq c0 (current-column) p0 (point)
11067 c1 (max (1+ c0) (if (> org-tags-column 0)
11068 org-tags-column
11069 (- (- org-tags-column) (length tags))))
11070 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
11071 (replace-match rpl t t)
11072 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
11073 tags)
11074 (t (error "Tags alignment failed")))
11075 (org-move-to-column col)
11076 (unless just-align
11077 (run-hooks 'org-after-tags-change-hook)))))
11079 (defun org-change-tag-in-region (beg end tag off)
11080 "Add or remove TAG for each entry in the region.
11081 This works in the agenda, and also in an org-mode buffer."
11082 (interactive
11083 (list (region-beginning) (region-end)
11084 (let ((org-last-tags-completion-table
11085 (if (org-mode-p)
11086 (org-get-buffer-tags)
11087 (org-global-tags-completion-table))))
11088 (org-ido-completing-read
11089 "Tag: " 'org-tags-completion-function nil nil nil
11090 'org-tags-history))
11091 (progn
11092 (message "[s]et or [r]emove? ")
11093 (equal (read-char-exclusive) ?r))))
11094 (if (fboundp 'deactivate-mark) (deactivate-mark))
11095 (let ((agendap (equal major-mode 'org-agenda-mode))
11096 l1 l2 m buf pos newhead (cnt 0))
11097 (goto-char end)
11098 (setq l2 (1- (org-current-line)))
11099 (goto-char beg)
11100 (setq l1 (org-current-line))
11101 (loop for l from l1 to l2 do
11102 (goto-line l)
11103 (setq m (get-text-property (point) 'org-hd-marker))
11104 (when (or (and (org-mode-p) (org-on-heading-p))
11105 (and agendap m))
11106 (setq buf (if agendap (marker-buffer m) (current-buffer))
11107 pos (if agendap m (point)))
11108 (with-current-buffer buf
11109 (save-excursion
11110 (save-restriction
11111 (goto-char pos)
11112 (setq cnt (1+ cnt))
11113 (org-toggle-tag tag (if off 'off 'on))
11114 (setq newhead (org-get-heading)))))
11115 (and agendap (org-agenda-change-all-lines newhead m))))
11116 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
11118 (defun org-tags-completion-function (string predicate &optional flag)
11119 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
11120 (confirm (lambda (x) (stringp (car x)))))
11121 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
11122 (setq s1 (match-string 1 string)
11123 s2 (match-string 2 string))
11124 (setq s1 "" s2 string))
11125 (cond
11126 ((eq flag nil)
11127 ;; try completion
11128 (setq rtn (try-completion s2 ctable confirm))
11129 (if (stringp rtn)
11130 (setq rtn
11131 (concat s1 s2 (substring rtn (length s2))
11132 (if (and org-add-colon-after-tag-completion
11133 (assoc rtn ctable))
11134 ":" ""))))
11135 rtn)
11136 ((eq flag t)
11137 ;; all-completions
11138 (all-completions s2 ctable confirm)
11140 ((eq flag 'lambda)
11141 ;; exact match?
11142 (assoc s2 ctable)))
11145 (defun org-fast-tag-insert (kwd tags face &optional end)
11146 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
11147 (insert (format "%-12s" (concat kwd ":"))
11148 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
11149 (or end "")))
11151 (defun org-fast-tag-show-exit (flag)
11152 (save-excursion
11153 (goto-line 3)
11154 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
11155 (replace-match ""))
11156 (when flag
11157 (end-of-line 1)
11158 (org-move-to-column (- (window-width) 19) t)
11159 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
11161 (defun org-set-current-tags-overlay (current prefix)
11162 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
11163 (if (featurep 'xemacs)
11164 (org-overlay-display org-tags-overlay (concat prefix s)
11165 'secondary-selection)
11166 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
11167 (org-overlay-display org-tags-overlay (concat prefix s)))))
11169 (defun org-fast-tag-selection (current inherited table &optional todo-table)
11170 "Fast tag selection with single keys.
11171 CURRENT is the current list of tags in the headline, INHERITED is the
11172 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
11173 possibly with grouping information. TODO-TABLE is a similar table with
11174 TODO keywords, should these have keys assigned to them.
11175 If the keys are nil, a-z are automatically assigned.
11176 Returns the new tags string, or nil to not change the current settings."
11177 (let* ((fulltable (append table todo-table))
11178 (maxlen (apply 'max (mapcar
11179 (lambda (x)
11180 (if (stringp (car x)) (string-width (car x)) 0))
11181 fulltable)))
11182 (buf (current-buffer))
11183 (expert (eq org-fast-tag-selection-single-key 'expert))
11184 (buffer-tags nil)
11185 (fwidth (+ maxlen 3 1 3))
11186 (ncol (/ (- (window-width) 4) fwidth))
11187 (i-face 'org-done)
11188 (c-face 'org-todo)
11189 tg cnt e c char c1 c2 ntable tbl rtn
11190 ov-start ov-end ov-prefix
11191 (exit-after-next org-fast-tag-selection-single-key)
11192 (done-keywords org-done-keywords)
11193 groups ingroup)
11194 (save-excursion
11195 (beginning-of-line 1)
11196 (if (looking-at
11197 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11198 (setq ov-start (match-beginning 1)
11199 ov-end (match-end 1)
11200 ov-prefix "")
11201 (setq ov-start (1- (point-at-eol))
11202 ov-end (1+ ov-start))
11203 (skip-chars-forward "^\n\r")
11204 (setq ov-prefix
11205 (concat
11206 (buffer-substring (1- (point)) (point))
11207 (if (> (current-column) org-tags-column)
11209 (make-string (- org-tags-column (current-column)) ?\ ))))))
11210 (org-move-overlay org-tags-overlay ov-start ov-end)
11211 (save-window-excursion
11212 (if expert
11213 (set-buffer (get-buffer-create " *Org tags*"))
11214 (delete-other-windows)
11215 (split-window-vertically)
11216 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
11217 (erase-buffer)
11218 (org-set-local 'org-done-keywords done-keywords)
11219 (org-fast-tag-insert "Inherited" inherited i-face "\n")
11220 (org-fast-tag-insert "Current" current c-face "\n\n")
11221 (org-fast-tag-show-exit exit-after-next)
11222 (org-set-current-tags-overlay current ov-prefix)
11223 (setq tbl fulltable char ?a cnt 0)
11224 (while (setq e (pop tbl))
11225 (cond
11226 ((equal e '(:startgroup))
11227 (push '() groups) (setq ingroup t)
11228 (when (not (= cnt 0))
11229 (setq cnt 0)
11230 (insert "\n"))
11231 (insert "{ "))
11232 ((equal e '(:endgroup))
11233 (setq ingroup nil cnt 0)
11234 (insert "}\n"))
11235 ((equal e '(:newline))
11236 (when (not (= cnt 0))
11237 (setq cnt 0)
11238 (insert "\n")
11239 (setq e (car tbl))
11240 (while (equal (car tbl) '(:newline))
11241 (insert "\n")
11242 (setq tbl (cdr tbl)))))
11244 (setq tg (car e) c2 nil)
11245 (if (cdr e)
11246 (setq c (cdr e))
11247 ;; automatically assign a character.
11248 (setq c1 (string-to-char
11249 (downcase (substring
11250 tg (if (= (string-to-char tg) ?@) 1 0)))))
11251 (if (or (rassoc c1 ntable) (rassoc c1 table))
11252 (while (or (rassoc char ntable) (rassoc char table))
11253 (setq char (1+ char)))
11254 (setq c2 c1))
11255 (setq c (or c2 char)))
11256 (if ingroup (push tg (car groups)))
11257 (setq tg (org-add-props tg nil 'face
11258 (cond
11259 ((not (assoc tg table))
11260 (org-get-todo-face tg))
11261 ((member tg current) c-face)
11262 ((member tg inherited) i-face)
11263 (t nil))))
11264 (if (and (= cnt 0) (not ingroup)) (insert " "))
11265 (insert "[" c "] " tg (make-string
11266 (- fwidth 4 (length tg)) ?\ ))
11267 (push (cons tg c) ntable)
11268 (when (= (setq cnt (1+ cnt)) ncol)
11269 (insert "\n")
11270 (if ingroup (insert " "))
11271 (setq cnt 0)))))
11272 (setq ntable (nreverse ntable))
11273 (insert "\n")
11274 (goto-char (point-min))
11275 (if (not expert) (org-fit-window-to-buffer))
11276 (setq rtn
11277 (catch 'exit
11278 (while t
11279 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
11280 (if groups " [!] no groups" " [!]groups")
11281 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
11282 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11283 (cond
11284 ((= c ?\r) (throw 'exit t))
11285 ((= c ?!)
11286 (setq groups (not groups))
11287 (goto-char (point-min))
11288 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
11289 ((= c ?\C-c)
11290 (if (not expert)
11291 (org-fast-tag-show-exit
11292 (setq exit-after-next (not exit-after-next)))
11293 (setq expert nil)
11294 (delete-other-windows)
11295 (split-window-vertically)
11296 (org-switch-to-buffer-other-window " *Org tags*")
11297 (org-fit-window-to-buffer)))
11298 ((or (= c ?\C-g)
11299 (and (= c ?q) (not (rassoc c ntable))))
11300 (org-detach-overlay org-tags-overlay)
11301 (setq quit-flag t))
11302 ((= c ?\ )
11303 (setq current nil)
11304 (if exit-after-next (setq exit-after-next 'now)))
11305 ((= c ?\t)
11306 (condition-case nil
11307 (setq tg (org-ido-completing-read
11308 "Tag: "
11309 (or buffer-tags
11310 (with-current-buffer buf
11311 (org-get-buffer-tags)))))
11312 (quit (setq tg "")))
11313 (when (string-match "\\S-" tg)
11314 (add-to-list 'buffer-tags (list tg))
11315 (if (member tg current)
11316 (setq current (delete tg current))
11317 (push tg current)))
11318 (if exit-after-next (setq exit-after-next 'now)))
11319 ((setq e (rassoc c todo-table) tg (car e))
11320 (with-current-buffer buf
11321 (save-excursion (org-todo tg)))
11322 (if exit-after-next (setq exit-after-next 'now)))
11323 ((setq e (rassoc c ntable) tg (car e))
11324 (if (member tg current)
11325 (setq current (delete tg current))
11326 (loop for g in groups do
11327 (if (member tg g)
11328 (mapc (lambda (x)
11329 (setq current (delete x current)))
11330 g)))
11331 (push tg current))
11332 (if exit-after-next (setq exit-after-next 'now))))
11334 ;; Create a sorted list
11335 (setq current
11336 (sort current
11337 (lambda (a b)
11338 (assoc b (cdr (memq (assoc a ntable) ntable))))))
11339 (if (eq exit-after-next 'now) (throw 'exit t))
11340 (goto-char (point-min))
11341 (beginning-of-line 2)
11342 (delete-region (point) (point-at-eol))
11343 (org-fast-tag-insert "Current" current c-face)
11344 (org-set-current-tags-overlay current ov-prefix)
11345 (while (re-search-forward
11346 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
11347 (setq tg (match-string 1))
11348 (add-text-properties
11349 (match-beginning 1) (match-end 1)
11350 (list 'face
11351 (cond
11352 ((member tg current) c-face)
11353 ((member tg inherited) i-face)
11354 (t (get-text-property (match-beginning 1) 'face))))))
11355 (goto-char (point-min)))))
11356 (org-detach-overlay org-tags-overlay)
11357 (if rtn
11358 (mapconcat 'identity current ":")
11359 nil))))
11361 (defun org-get-tags-string ()
11362 "Get the TAGS string in the current headline."
11363 (unless (org-on-heading-p t)
11364 (error "Not on a heading"))
11365 (save-excursion
11366 (beginning-of-line 1)
11367 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11368 (org-match-string-no-properties 1)
11369 "")))
11371 (defun org-get-tags ()
11372 "Get the list of tags specified in the current headline."
11373 (org-split-string (org-get-tags-string) ":"))
11375 (defun org-get-buffer-tags ()
11376 "Get a table of all tags used in the buffer, for completion."
11377 (let (tags)
11378 (save-excursion
11379 (goto-char (point-min))
11380 (while (re-search-forward
11381 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
11382 (when (equal (char-after (point-at-bol 0)) ?*)
11383 (mapc (lambda (x) (add-to-list 'tags x))
11384 (org-split-string (org-match-string-no-properties 1) ":")))))
11385 (mapcar 'list tags)))
11387 ;;;; The mapping API
11389 ;;;###autoload
11390 (defun org-map-entries (func &optional match scope &rest skip)
11391 "Call FUNC at each headline selected by MATCH in SCOPE.
11393 FUNC is a function or a lisp form. The function will be called without
11394 arguments, with the cursor positioned at the beginning of the headline.
11395 The return values of all calls to the function will be collected and
11396 returned as a list.
11398 The call to FUNC will be wrapped into a save-excursion form, so FUNC
11399 does not need to preserve point. After evaluation, the cursor will be
11400 moved to the end of the line (presumably of the headline of the
11401 processed entry) and search continues from there. Under some
11402 circumstances, this may not produce the wanted results. For example,
11403 if you have removed (e.g. archived) the current (sub)tree it could
11404 mean that the next entry will be skipped entirely. In such cases, you
11405 can specify the position from where search should continue by making
11406 FUNC set the variable `org-map-continue-from' to the desired buffer
11407 position.
11409 MATCH is a tags/property/todo match as it is used in the agenda tags view.
11410 Only headlines that are matched by this query will be considered during
11411 the iteration. When MATCH is nil or t, all headlines will be
11412 visited by the iteration.
11414 SCOPE determines the scope of this command. It can be any of:
11416 nil The current buffer, respecting the restriction if any
11417 tree The subtree started with the entry at point
11418 file The current buffer, without restriction
11419 file-with-archives
11420 The current buffer, and any archives associated with it
11421 agenda All agenda files
11422 agenda-with-archives
11423 All agenda files with any archive files associated with them
11424 \(file1 file2 ...)
11425 If this is a list, all files in the list will be scanned
11427 The remaining args are treated as settings for the skipping facilities of
11428 the scanner. The following items can be given here:
11430 archive skip trees with the archive tag.
11431 comment skip trees with the COMMENT keyword
11432 function or Emacs Lisp form:
11433 will be used as value for `org-agenda-skip-function', so whenever
11434 the the function returns t, FUNC will not be called for that
11435 entry and search will continue from the point where the
11436 function leaves it.
11438 If your function needs to retrieve the tags including inherited tags
11439 at the *current* entry, you can use the value of the variable
11440 `org-scanner-tags' which will be much faster than getting the value
11441 with `org-get-tags-at'. If your function gets properties with
11442 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
11443 to t around the call to `org-entry-properties' to get the same speedup.
11444 Note that if your function moves around to retrieve tags and properties at
11445 a *different* entry, you cannot use these techniques."
11446 (let* ((org-agenda-archives-mode nil) ; just to make sure
11447 (org-agenda-skip-archived-trees (memq 'archive skip))
11448 (org-agenda-skip-comment-trees (memq 'comment skip))
11449 (org-agenda-skip-function
11450 (car (org-delete-all '(comment archive) skip)))
11451 (org-tags-match-list-sublevels t)
11452 matcher file res
11453 org-todo-keywords-for-agenda
11454 org-done-keywords-for-agenda
11455 org-todo-keyword-alist-for-agenda
11456 org-tag-alist-for-agenda)
11458 (cond
11459 ((eq match t) (setq matcher t))
11460 ((eq match nil) (setq matcher t))
11461 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
11463 (save-excursion
11464 (save-restriction
11465 (when (eq scope 'tree)
11466 (org-back-to-heading t)
11467 (org-narrow-to-subtree)
11468 (setq scope nil))
11470 (if (not scope)
11471 (progn
11472 (org-prepare-agenda-buffers
11473 (list (buffer-file-name (current-buffer))))
11474 (setq res (org-scan-tags func matcher)))
11475 ;; Get the right scope
11476 (cond
11477 ((and scope (listp scope) (symbolp (car scope)))
11478 (setq scope (eval scope)))
11479 ((eq scope 'agenda)
11480 (setq scope (org-agenda-files t)))
11481 ((eq scope 'agenda-with-archives)
11482 (setq scope (org-agenda-files t))
11483 (setq scope (org-add-archive-files scope)))
11484 ((eq scope 'file)
11485 (setq scope (list (buffer-file-name))))
11486 ((eq scope 'file-with-archives)
11487 (setq scope (org-add-archive-files (list (buffer-file-name))))))
11488 (org-prepare-agenda-buffers scope)
11489 (while (setq file (pop scope))
11490 (with-current-buffer (org-find-base-buffer-visiting file)
11491 (save-excursion
11492 (save-restriction
11493 (widen)
11494 (goto-char (point-min))
11495 (setq res (append res (org-scan-tags func matcher))))))))))
11496 res))
11498 ;;;; Properties
11500 ;;; Setting and retrieving properties
11502 (defconst org-special-properties
11503 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
11504 "TIMESTAMP" "TIMESTAMP_IA")
11505 "The special properties valid in Org-mode.
11507 These are properties that are not defined in the property drawer,
11508 but in some other way.")
11510 (defconst org-default-properties
11511 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
11512 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
11513 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
11514 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
11515 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
11516 "CLOCK_MODELINE_TOTAL")
11517 "Some properties that are used by Org-mode for various purposes.
11518 Being in this list makes sure that they are offered for completion.")
11520 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
11521 "Regular expression matching the first line of a property drawer.")
11523 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
11524 "Regular expression matching the first line of a property drawer.")
11526 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
11527 "Regular expression matching the first line of a property drawer.")
11529 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
11530 "Regular expression matching the first line of a property drawer.")
11532 (defconst org-property-drawer-re
11533 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
11534 org-property-end-re "\\)\n?")
11535 "Matches an entire property drawer.")
11537 (defconst org-clock-drawer-re
11538 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
11539 org-property-end-re "\\)\n?")
11540 "Matches an entire clock drawer.")
11542 (defun org-property-action ()
11543 "Do an action on properties."
11544 (interactive)
11545 (let (c)
11546 (org-at-property-p)
11547 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
11548 (setq c (read-char-exclusive))
11549 (cond
11550 ((equal c ?s)
11551 (call-interactively 'org-set-property))
11552 ((equal c ?d)
11553 (call-interactively 'org-delete-property))
11554 ((equal c ?D)
11555 (call-interactively 'org-delete-property-globally))
11556 ((equal c ?c)
11557 (call-interactively 'org-compute-property-at-point))
11558 (t (error "No such property action %c" c)))))
11560 (defun org-at-property-p ()
11561 "Is the cursor in a property line?"
11562 ;; FIXME: Does not check if we are actually in the drawer.
11563 ;; FIXME: also returns true on any drawers.....
11564 ;; This is used by C-c C-c for property action.
11565 (save-excursion
11566 (beginning-of-line 1)
11567 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
11569 (defun org-get-property-block (&optional beg end force)
11570 "Return the (beg . end) range of the body of the property drawer.
11571 BEG and END can be beginning and end of subtree, if not given
11572 they will be found.
11573 If the drawer does not exist and FORCE is non-nil, create the drawer."
11574 (catch 'exit
11575 (save-excursion
11576 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
11577 (end (or end (progn (outline-next-heading) (point)))))
11578 (goto-char beg)
11579 (if (re-search-forward org-property-start-re end t)
11580 (setq beg (1+ (match-end 0)))
11581 (if force
11582 (save-excursion
11583 (org-insert-property-drawer)
11584 (setq end (progn (outline-next-heading) (point))))
11585 (throw 'exit nil))
11586 (goto-char beg)
11587 (if (re-search-forward org-property-start-re end t)
11588 (setq beg (1+ (match-end 0)))))
11589 (if (re-search-forward org-property-end-re end t)
11590 (setq end (match-beginning 0))
11591 (or force (throw 'exit nil))
11592 (goto-char beg)
11593 (setq end beg)
11594 (org-indent-line-function)
11595 (insert ":END:\n"))
11596 (cons beg end)))))
11598 (defun org-entry-properties (&optional pom which)
11599 "Get all properties of the entry at point-or-marker POM.
11600 This includes the TODO keyword, the tags, time strings for deadline,
11601 scheduled, and clocking, and any additional properties defined in the
11602 entry. The return value is an alist, keys may occur multiple times
11603 if the property key was used several times.
11604 POM may also be nil, in which case the current entry is used.
11605 If WHICH is nil or `all', get all properties. If WHICH is
11606 `special' or `standard', only get that subclass."
11607 (setq which (or which 'all))
11608 (org-with-point-at pom
11609 (let ((clockstr (substring org-clock-string 0 -1))
11610 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
11611 beg end range props sum-props key value string clocksum)
11612 (save-excursion
11613 (when (condition-case nil
11614 (and (org-mode-p) (org-back-to-heading t))
11615 (error nil))
11616 (setq beg (point))
11617 (setq sum-props (get-text-property (point) 'org-summaries))
11618 (setq clocksum (get-text-property (point) :org-clock-minutes))
11619 (outline-next-heading)
11620 (setq end (point))
11621 (when (memq which '(all special))
11622 ;; Get the special properties, like TODO and tags
11623 (goto-char beg)
11624 (when (and (looking-at org-todo-line-regexp) (match-end 2))
11625 (push (cons "TODO" (org-match-string-no-properties 2)) props))
11626 (when (looking-at org-priority-regexp)
11627 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
11628 (when (and (setq value (org-get-tags-string))
11629 (string-match "\\S-" value))
11630 (push (cons "TAGS" value) props))
11631 (when (setq value (org-get-tags-at))
11632 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
11633 props))
11634 (while (re-search-forward org-maybe-keyword-time-regexp end t)
11635 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
11636 string (if (equal key clockstr)
11637 (org-no-properties
11638 (org-trim
11639 (buffer-substring
11640 (match-beginning 3) (goto-char (point-at-eol)))))
11641 (substring (org-match-string-no-properties 3) 1 -1)))
11642 (unless key
11643 (if (= (char-after (match-beginning 3)) ?\[)
11644 (setq key "TIMESTAMP_IA")
11645 (setq key "TIMESTAMP")))
11646 (when (or (equal key clockstr) (not (assoc key props)))
11647 (push (cons key string) props)))
11651 (when (memq which '(all standard))
11652 ;; Get the standard properties, like :PROP: ...
11653 (setq range (org-get-property-block beg end))
11654 (when range
11655 (goto-char (car range))
11656 (while (re-search-forward
11657 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
11658 (cdr range) t)
11659 (setq key (org-match-string-no-properties 1)
11660 value (org-trim (or (org-match-string-no-properties 2) "")))
11661 (unless (member key excluded)
11662 (push (cons key (or value "")) props)))))
11663 (if clocksum
11664 (push (cons "CLOCKSUM"
11665 (org-columns-number-to-string (/ (float clocksum) 60.)
11666 'add_times))
11667 props))
11668 (unless (assoc "CATEGORY" props)
11669 (setq value (or (org-get-category)
11670 (progn (org-refresh-category-properties)
11671 (org-get-category))))
11672 (push (cons "CATEGORY" value) props))
11673 (append sum-props (nreverse props)))))))
11675 (defun org-entry-get (pom property &optional inherit)
11676 "Get value of PROPERTY for entry at point-or-marker POM.
11677 If INHERIT is non-nil and the entry does not have the property,
11678 then also check higher levels of the hierarchy.
11679 If INHERIT is the symbol `selective', use inheritance only if the setting
11680 in `org-use-property-inheritance' selects PROPERTY for inheritance.
11681 If the property is present but empty, the return value is the empty string.
11682 If the property is not present at all, nil is returned."
11683 (org-with-point-at pom
11684 (if (and inherit (if (eq inherit 'selective)
11685 (org-property-inherit-p property)
11687 (org-entry-get-with-inheritance property)
11688 (if (member property org-special-properties)
11689 ;; We need a special property. Use brute force, get all properties.
11690 (cdr (assoc property (org-entry-properties nil 'special)))
11691 (let ((range (org-get-property-block)))
11692 (if (and range
11693 (goto-char (car range))
11694 (re-search-forward
11695 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
11696 (cdr range) t))
11697 ;; Found the property, return it.
11698 (if (match-end 1)
11699 (org-match-string-no-properties 1)
11700 "")))))))
11702 (defun org-property-or-variable-value (var &optional inherit)
11703 "Check if there is a property fixing the value of VAR.
11704 If yes, return this value. If not, return the current value of the variable."
11705 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
11706 (if (and prop (stringp prop) (string-match "\\S-" prop))
11707 (read prop)
11708 (symbol-value var))))
11710 (defun org-entry-delete (pom property)
11711 "Delete the property PROPERTY from entry at point-or-marker POM."
11712 (org-with-point-at pom
11713 (if (member property org-special-properties)
11714 nil ; cannot delete these properties.
11715 (let ((range (org-get-property-block)))
11716 (if (and range
11717 (goto-char (car range))
11718 (re-search-forward
11719 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
11720 (cdr range) t))
11721 (progn
11722 (delete-region (match-beginning 0) (1+ (point-at-eol)))
11724 nil)))))
11726 ;; Multi-values properties are properties that contain multiple values
11727 ;; These values are assumed to be single words, separated by whitespace.
11728 (defun org-entry-add-to-multivalued-property (pom property value)
11729 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
11730 (let* ((old (org-entry-get pom property))
11731 (values (and old (org-split-string old "[ \t]"))))
11732 (setq value (org-entry-protect-space value))
11733 (unless (member value values)
11734 (setq values (cons value values))
11735 (org-entry-put pom property
11736 (mapconcat 'identity values " ")))))
11738 (defun org-entry-remove-from-multivalued-property (pom property value)
11739 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
11740 (let* ((old (org-entry-get pom property))
11741 (values (and old (org-split-string old "[ \t]"))))
11742 (setq value (org-entry-protect-space value))
11743 (when (member value values)
11744 (setq values (delete value values))
11745 (org-entry-put pom property
11746 (mapconcat 'identity values " ")))))
11748 (defun org-entry-member-in-multivalued-property (pom property value)
11749 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
11750 (let* ((old (org-entry-get pom property))
11751 (values (and old (org-split-string old "[ \t]"))))
11752 (setq value (org-entry-protect-space value))
11753 (member value values)))
11755 (defun org-entry-get-multivalued-property (pom property)
11756 "Return a list of values in a multivalued property."
11757 (let* ((value (org-entry-get pom property))
11758 (values (and value (org-split-string value "[ \t]"))))
11759 (mapcar 'org-entry-restore-space values)))
11761 (defun org-entry-put-multivalued-property (pom property &rest values)
11762 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
11763 VALUES should be a list of strings. Spaces will be protected."
11764 (org-entry-put pom property
11765 (mapconcat 'org-entry-protect-space values " "))
11766 (let* ((value (org-entry-get pom property))
11767 (values (and value (org-split-string value "[ \t]"))))
11768 (mapcar 'org-entry-restore-space values)))
11770 (defun org-entry-protect-space (s)
11771 "Protect spaces and newline in string S."
11772 (while (string-match " " s)
11773 (setq s (replace-match "%20" t t s)))
11774 (while (string-match "\n" s)
11775 (setq s (replace-match "%0A" t t s)))
11778 (defun org-entry-restore-space (s)
11779 "Restore spaces and newline in string S."
11780 (while (string-match "%20" s)
11781 (setq s (replace-match " " t t s)))
11782 (while (string-match "%0A" s)
11783 (setq s (replace-match "\n" t t s)))
11786 (defvar org-entry-property-inherited-from (make-marker)
11787 "Marker pointing to the entry from where a property was inherited.
11788 Each call to `org-entry-get-with-inheritance' will set this marker to the
11789 location of the entry where the inheritance search matched. If there was
11790 no match, the marker will point nowhere.
11791 Note that also `org-entry-get' calls this function, if the INHERIT flag
11792 is set.")
11794 (defun org-entry-get-with-inheritance (property)
11795 "Get entry property, and search higher levels if not present."
11796 (move-marker org-entry-property-inherited-from nil)
11797 (let (tmp)
11798 (save-excursion
11799 (save-restriction
11800 (widen)
11801 (catch 'ex
11802 (while t
11803 (when (setq tmp (org-entry-get nil property))
11804 (org-back-to-heading t)
11805 (move-marker org-entry-property-inherited-from (point))
11806 (throw 'ex tmp))
11807 (or (org-up-heading-safe) (throw 'ex nil)))))
11808 (or tmp
11809 (cdr (assoc property org-file-properties))
11810 (cdr (assoc property org-global-properties))
11811 (cdr (assoc property org-global-properties-fixed))))))
11813 (defun org-entry-put (pom property value)
11814 "Set PROPERTY to VALUE for entry at point-or-marker POM."
11815 (org-with-point-at pom
11816 (org-back-to-heading t)
11817 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
11818 range)
11819 (cond
11820 ((equal property "TODO")
11821 (when (and (stringp value) (string-match "\\S-" value)
11822 (not (member value org-todo-keywords-1)))
11823 (error "\"%s\" is not a valid TODO state" value))
11824 (if (or (not value)
11825 (not (string-match "\\S-" value)))
11826 (setq value 'none))
11827 (org-todo value)
11828 (org-set-tags nil 'align))
11829 ((equal property "PRIORITY")
11830 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
11831 (string-to-char value) ?\ ))
11832 (org-set-tags nil 'align))
11833 ((equal property "SCHEDULED")
11834 (if (re-search-forward org-scheduled-time-regexp end t)
11835 (cond
11836 ((eq value 'earlier) (org-timestamp-change -1 'day))
11837 ((eq value 'later) (org-timestamp-change 1 'day))
11838 (t (call-interactively 'org-schedule)))
11839 (call-interactively 'org-schedule)))
11840 ((equal property "DEADLINE")
11841 (if (re-search-forward org-deadline-time-regexp end t)
11842 (cond
11843 ((eq value 'earlier) (org-timestamp-change -1 'day))
11844 ((eq value 'later) (org-timestamp-change 1 'day))
11845 (t (call-interactively 'org-deadline)))
11846 (call-interactively 'org-deadline)))
11847 ((member property org-special-properties)
11848 (error "The %s property can not yet be set with `org-entry-put'"
11849 property))
11850 (t ; a non-special property
11851 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
11852 (setq range (org-get-property-block beg end 'force))
11853 (goto-char (car range))
11854 (if (re-search-forward
11855 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
11856 (progn
11857 (delete-region (match-beginning 1) (match-end 1))
11858 (goto-char (match-beginning 1)))
11859 (goto-char (cdr range))
11860 (insert "\n")
11861 (backward-char 1)
11862 (org-indent-line-function)
11863 (insert ":" property ":"))
11864 (and value (insert " " value))
11865 (org-indent-line-function)))))))
11867 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
11868 "Get all property keys in the current buffer.
11869 With INCLUDE-SPECIALS, also list the special properties that reflect things
11870 like tags and TODO state.
11871 With INCLUDE-DEFAULTS, also include properties that has special meaning
11872 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
11873 With INCLUDE-COLUMNS, also include property names given in COLUMN
11874 formats in the current buffer."
11875 (let (rtn range cfmt s p)
11876 (save-excursion
11877 (save-restriction
11878 (widen)
11879 (goto-char (point-min))
11880 (while (re-search-forward org-property-start-re nil t)
11881 (setq range (org-get-property-block))
11882 (goto-char (car range))
11883 (while (re-search-forward
11884 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
11885 (cdr range) t)
11886 (add-to-list 'rtn (org-match-string-no-properties 1)))
11887 (outline-next-heading))))
11889 (when include-specials
11890 (setq rtn (append org-special-properties rtn)))
11892 (when include-defaults
11893 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
11894 (add-to-list 'rtn org-effort-property))
11896 (when include-columns
11897 (save-excursion
11898 (save-restriction
11899 (widen)
11900 (goto-char (point-min))
11901 (while (re-search-forward
11902 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
11903 nil t)
11904 (setq cfmt (match-string 2) s 0)
11905 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
11906 cfmt s)
11907 (setq s (match-end 0)
11908 p (match-string 1 cfmt))
11909 (unless (or (equal p "ITEM")
11910 (member p org-special-properties))
11911 (add-to-list 'rtn (match-string 1 cfmt))))))))
11913 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
11915 (defun org-property-values (key)
11916 "Return a list of all values of property KEY."
11917 (save-excursion
11918 (save-restriction
11919 (widen)
11920 (goto-char (point-min))
11921 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
11922 values)
11923 (while (re-search-forward re nil t)
11924 (add-to-list 'values (org-trim (match-string 1))))
11925 (delete "" values)))))
11927 (defun org-insert-property-drawer ()
11928 "Insert a property drawer into the current entry."
11929 (interactive)
11930 (org-back-to-heading t)
11931 (looking-at outline-regexp)
11932 (let ((indent (if org-adapt-indentation
11933 (- (match-end 0)(match-beginning 0))
11935 (beg (point))
11936 (re (concat "^[ \t]*" org-keyword-time-regexp))
11937 end hiddenp)
11938 (outline-next-heading)
11939 (setq end (point))
11940 (goto-char beg)
11941 (while (re-search-forward re end t))
11942 (setq hiddenp (org-invisible-p))
11943 (end-of-line 1)
11944 (and (equal (char-after) ?\n) (forward-char 1))
11945 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
11946 (if (member (match-string 1) '("CLOCK:" ":END:"))
11947 ;; just skip this line
11948 (beginning-of-line 2)
11949 ;; Drawer start, find the end
11950 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
11951 (beginning-of-line 1)))
11952 (org-skip-over-state-notes)
11953 (skip-chars-backward " \t\n\r")
11954 (if (eq (char-before) ?*) (forward-char 1))
11955 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
11956 (beginning-of-line 0)
11957 (org-indent-to-column indent)
11958 (beginning-of-line 2)
11959 (org-indent-to-column indent)
11960 (beginning-of-line 0)
11961 (if hiddenp
11962 (save-excursion
11963 (org-back-to-heading t)
11964 (hide-entry))
11965 (org-flag-drawer t))))
11967 (defun org-set-property (property value)
11968 "In the current entry, set PROPERTY to VALUE.
11969 When called interactively, this will prompt for a property name, offering
11970 completion on existing and default properties. And then it will prompt
11971 for a value, offering completion either on allowed values (via an inherited
11972 xxx_ALL property) or on existing values in other instances of this property
11973 in the current file."
11974 (interactive
11975 (let* ((completion-ignore-case t)
11976 (keys (org-buffer-property-keys nil t t))
11977 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
11978 (prop (if (member prop0 keys)
11979 prop0
11980 (or (cdr (assoc (downcase prop0)
11981 (mapcar (lambda (x) (cons (downcase x) x))
11982 keys)))
11983 prop0)))
11984 (cur (org-entry-get nil prop))
11985 (allowed (org-property-get-allowed-values nil prop 'table))
11986 (existing (mapcar 'list (org-property-values prop)))
11987 (val (if allowed
11988 (org-completing-read "Value: " allowed nil 'req-match)
11989 (let (org-completion-use-ido)
11990 (org-completing-read
11991 (concat "Value" (if (and cur (string-match "\\S-" cur))
11992 (concat "[" cur "]") "")
11993 ": ")
11994 existing nil nil "" nil cur)))))
11995 (list prop (if (equal val "") cur val))))
11996 (unless (equal (org-entry-get nil property) value)
11997 (org-entry-put nil property value)))
11999 (defun org-delete-property (property)
12000 "In the current entry, delete PROPERTY."
12001 (interactive
12002 (let* ((completion-ignore-case t)
12003 (prop (org-ido-completing-read
12004 "Property: " (org-entry-properties nil 'standard))))
12005 (list prop)))
12006 (message "Property %s %s" property
12007 (if (org-entry-delete nil property)
12008 "deleted"
12009 "was not present in the entry")))
12011 (defun org-delete-property-globally (property)
12012 "Remove PROPERTY globally, from all entries."
12013 (interactive
12014 (let* ((completion-ignore-case t)
12015 (prop (org-ido-completing-read
12016 "Globally remove property: "
12017 (mapcar 'list (org-buffer-property-keys)))))
12018 (list prop)))
12019 (save-excursion
12020 (save-restriction
12021 (widen)
12022 (goto-char (point-min))
12023 (let ((cnt 0))
12024 (while (re-search-forward
12025 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
12026 nil t)
12027 (setq cnt (1+ cnt))
12028 (replace-match ""))
12029 (message "Property \"%s\" removed from %d entries" property cnt)))))
12031 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
12033 (defun org-compute-property-at-point ()
12034 "Compute the property at point.
12035 This looks for an enclosing column format, extracts the operator and
12036 then applies it to the property in the column format's scope."
12037 (interactive)
12038 (unless (org-at-property-p)
12039 (error "Not at a property"))
12040 (let ((prop (org-match-string-no-properties 2)))
12041 (org-columns-get-format-and-top-level)
12042 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
12043 (error "No operator defined for property %s" prop))
12044 (org-columns-compute prop)))
12046 (defun org-property-get-allowed-values (pom property &optional table)
12047 "Get allowed values for the property PROPERTY.
12048 When TABLE is non-nil, return an alist that can directly be used for
12049 completion."
12050 (let (vals)
12051 (cond
12052 ((equal property "TODO")
12053 (setq vals (org-with-point-at pom
12054 (append org-todo-keywords-1 '("")))))
12055 ((equal property "PRIORITY")
12056 (let ((n org-lowest-priority))
12057 (while (>= n org-highest-priority)
12058 (push (char-to-string n) vals)
12059 (setq n (1- n)))))
12060 ((member property org-special-properties))
12062 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
12064 (when (and vals (string-match "\\S-" vals))
12065 (setq vals (car (read-from-string (concat "(" vals ")"))))
12066 (setq vals (mapcar (lambda (x)
12067 (cond ((stringp x) x)
12068 ((numberp x) (number-to-string x))
12069 ((symbolp x) (symbol-name x))
12070 (t "???")))
12071 vals)))))
12072 (if table (mapcar 'list vals) vals)))
12074 (defun org-property-previous-allowed-value (&optional previous)
12075 "Switch to the next allowed value for this property."
12076 (interactive)
12077 (org-property-next-allowed-value t))
12079 (defun org-property-next-allowed-value (&optional previous)
12080 "Switch to the next allowed value for this property."
12081 (interactive)
12082 (unless (org-at-property-p)
12083 (error "Not at a property"))
12084 (let* ((key (match-string 2))
12085 (value (match-string 3))
12086 (allowed (or (org-property-get-allowed-values (point) key)
12087 (and (member value '("[ ]" "[-]" "[X]"))
12088 '("[ ]" "[X]"))))
12089 nval)
12090 (unless allowed
12091 (error "Allowed values for this property have not been defined"))
12092 (if previous (setq allowed (reverse allowed)))
12093 (if (member value allowed)
12094 (setq nval (car (cdr (member value allowed)))))
12095 (setq nval (or nval (car allowed)))
12096 (if (equal nval value)
12097 (error "Only one allowed value for this property"))
12098 (org-at-property-p)
12099 (replace-match (concat " :" key ": " nval) t t)
12100 (org-indent-line-function)
12101 (beginning-of-line 1)
12102 (skip-chars-forward " \t")))
12104 (defun org-find-entry-with-id (ident)
12105 "Locate the entry that contains the ID property with exact value IDENT.
12106 IDENT can be a string, a symbol or a number, this function will search for
12107 the string representation of it.
12108 Return the position where this entry starts, or nil if there is no such entry."
12109 (interactive "sID: ")
12110 (let ((id (cond
12111 ((stringp ident) ident)
12112 ((symbol-name ident) (symbol-name ident))
12113 ((numberp ident) (number-to-string ident))
12114 (t (error "IDENT %s must be a string, symbol or number" ident))))
12115 (case-fold-search nil))
12116 (save-excursion
12117 (save-restriction
12118 (widen)
12119 (goto-char (point-min))
12120 (when (re-search-forward
12121 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
12122 nil t)
12123 (org-back-to-heading t)
12124 (point))))))
12126 ;;;; Timestamps
12128 (defvar org-last-changed-timestamp nil)
12129 (defvar org-last-inserted-timestamp nil
12130 "The last time stamp inserted with `org-insert-time-stamp'.")
12131 (defvar org-time-was-given) ; dynamically scoped parameter
12132 (defvar org-end-time-was-given) ; dynamically scoped parameter
12133 (defvar org-ts-what) ; dynamically scoped parameter
12135 (defun org-time-stamp (arg &optional inactive)
12136 "Prompt for a date/time and insert a time stamp.
12137 If the user specifies a time like HH:MM, or if this command is called
12138 with a prefix argument, the time stamp will contain date and time.
12139 Otherwise, only the date will be included. All parts of a date not
12140 specified by the user will be filled in from the current date/time.
12141 So if you press just return without typing anything, the time stamp
12142 will represent the current date/time. If there is already a timestamp
12143 at the cursor, it will be modified."
12144 (interactive "P")
12145 (let* ((ts nil)
12146 (default-time
12147 ;; Default time is either today, or, when entering a range,
12148 ;; the range start.
12149 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
12150 (save-excursion
12151 (re-search-backward
12152 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
12153 (- (point) 20) t)))
12154 (apply 'encode-time (org-parse-time-string (match-string 1)))
12155 (current-time)))
12156 (default-input (and ts (org-get-compact-tod ts)))
12157 org-time-was-given org-end-time-was-given time)
12158 (cond
12159 ((and (org-at-timestamp-p t)
12160 (memq last-command '(org-time-stamp org-time-stamp-inactive))
12161 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
12162 (insert "--")
12163 (setq time (let ((this-command this-command))
12164 (org-read-date arg 'totime nil nil
12165 default-time default-input)))
12166 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
12167 ((org-at-timestamp-p t)
12168 (setq time (let ((this-command this-command))
12169 (org-read-date arg 'totime nil nil default-time default-input)))
12170 (when (org-at-timestamp-p t) ; just to get the match data
12171 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
12172 (replace-match "")
12173 (setq org-last-changed-timestamp
12174 (org-insert-time-stamp
12175 time (or org-time-was-given arg)
12176 inactive nil nil (list org-end-time-was-given))))
12177 (message "Timestamp updated"))
12179 (setq time (let ((this-command this-command))
12180 (org-read-date arg 'totime nil nil default-time default-input)))
12181 (org-insert-time-stamp time (or org-time-was-given arg) inactive
12182 nil nil (list org-end-time-was-given))))))
12184 ;; FIXME: can we use this for something else, like computing time differences?
12185 (defun org-get-compact-tod (s)
12186 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
12187 (let* ((t1 (match-string 1 s))
12188 (h1 (string-to-number (match-string 2 s)))
12189 (m1 (string-to-number (match-string 3 s)))
12190 (t2 (and (match-end 4) (match-string 5 s)))
12191 (h2 (and t2 (string-to-number (match-string 6 s))))
12192 (m2 (and t2 (string-to-number (match-string 7 s))))
12193 dh dm)
12194 (if (not t2)
12196 (setq dh (- h2 h1) dm (- m2 m1))
12197 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
12198 (concat t1 "+" (number-to-string dh)
12199 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
12201 (defun org-time-stamp-inactive (&optional arg)
12202 "Insert an inactive time stamp.
12203 An inactive time stamp is enclosed in square brackets instead of angle
12204 brackets. It is inactive in the sense that it does not trigger agenda entries,
12205 does not link to the calendar and cannot be changed with the S-cursor keys.
12206 So these are more for recording a certain time/date."
12207 (interactive "P")
12208 (org-time-stamp arg 'inactive))
12210 (defvar org-date-ovl (org-make-overlay 1 1))
12211 (org-overlay-put org-date-ovl 'face 'org-warning)
12212 (org-detach-overlay org-date-ovl)
12214 (defvar org-ans1) ; dynamically scoped parameter
12215 (defvar org-ans2) ; dynamically scoped parameter
12217 (defvar org-plain-time-of-day-regexp) ; defined below
12219 (defvar org-overriding-default-time nil) ; dynamically scoped
12220 (defvar org-read-date-overlay nil)
12221 (defvar org-dcst nil) ; dynamically scoped
12222 (defvar org-read-date-history nil)
12223 (defvar org-read-date-final-answer nil)
12225 (defun org-read-date (&optional with-time to-time from-string prompt
12226 default-time default-input)
12227 "Read a date, possibly a time, and make things smooth for the user.
12228 The prompt will suggest to enter an ISO date, but you can also enter anything
12229 which will at least partially be understood by `parse-time-string'.
12230 Unrecognized parts of the date will default to the current day, month, year,
12231 hour and minute. If this command is called to replace a timestamp at point,
12232 of to enter the second timestamp of a range, the default time is taken from the
12233 existing stamp. For example,
12234 3-2-5 --> 2003-02-05
12235 feb 15 --> currentyear-02-15
12236 sep 12 9 --> 2009-09-12
12237 12:45 --> today 12:45
12238 22 sept 0:34 --> currentyear-09-22 0:34
12239 12 --> currentyear-currentmonth-12
12240 Fri --> nearest Friday (today or later)
12241 etc.
12243 Furthermore you can specify a relative date by giving, as the *first* thing
12244 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
12245 change in days weeks, months, years.
12246 With a single plus or minus, the date is relative to today. With a double
12247 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
12248 +4d --> four days from today
12249 +4 --> same as above
12250 +2w --> two weeks from today
12251 ++5 --> five days from default date
12253 The function understands only English month and weekday abbreviations,
12254 but this can be configured with the variables `parse-time-months' and
12255 `parse-time-weekdays'.
12257 While prompting, a calendar is popped up - you can also select the
12258 date with the mouse (button 1). The calendar shows a period of three
12259 months. To scroll it to other months, use the keys `>' and `<'.
12260 If you don't like the calendar, turn it off with
12261 \(setq org-read-date-popup-calendar nil)
12263 With optional argument TO-TIME, the date will immediately be converted
12264 to an internal time.
12265 With an optional argument WITH-TIME, the prompt will suggest to also
12266 insert a time. Note that when WITH-TIME is not set, you can still
12267 enter a time, and this function will inform the calling routine about
12268 this change. The calling routine may then choose to change the format
12269 used to insert the time stamp into the buffer to include the time.
12270 With optional argument FROM-STRING, read from this string instead from
12271 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
12272 the time/date that is used for everything that is not specified by the
12273 user."
12274 (require 'parse-time)
12275 (let* ((org-time-stamp-rounding-minutes
12276 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
12277 (org-dcst org-display-custom-times)
12278 (ct (org-current-time))
12279 (def (or org-overriding-default-time default-time ct))
12280 (defdecode (decode-time def))
12281 (dummy (progn
12282 (when (< (nth 2 defdecode) org-extend-today-until)
12283 (setcar (nthcdr 2 defdecode) -1)
12284 (setcar (nthcdr 1 defdecode) 59)
12285 (setq def (apply 'encode-time defdecode)
12286 defdecode (decode-time def)))))
12287 (calendar-frame-setup nil)
12288 (calendar-move-hook nil)
12289 (calendar-view-diary-initially-flag nil)
12290 (view-diary-entries-initially nil)
12291 (calendar-view-holidays-initially-flag nil)
12292 (view-calendar-holidays-initially nil)
12293 (timestr (format-time-string
12294 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
12295 (prompt (concat (if prompt (concat prompt " ") "")
12296 (format "Date+time [%s]: " timestr)))
12297 ans (org-ans0 "") org-ans1 org-ans2 final)
12299 (cond
12300 (from-string (setq ans from-string))
12301 (org-read-date-popup-calendar
12302 (save-excursion
12303 (save-window-excursion
12304 (calendar)
12305 (calendar-forward-day (- (time-to-days def)
12306 (calendar-absolute-from-gregorian
12307 (calendar-current-date))))
12308 (org-eval-in-calendar nil t)
12309 (let* ((old-map (current-local-map))
12310 (map (copy-keymap calendar-mode-map))
12311 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12312 (org-defkey map (kbd "RET") 'org-calendar-select)
12313 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
12314 'org-calendar-select-mouse)
12315 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
12316 'org-calendar-select-mouse)
12317 (org-defkey minibuffer-local-map [(meta shift left)]
12318 (lambda () (interactive)
12319 (org-eval-in-calendar '(calendar-backward-month 1))))
12320 (org-defkey minibuffer-local-map [(meta shift right)]
12321 (lambda () (interactive)
12322 (org-eval-in-calendar '(calendar-forward-month 1))))
12323 (org-defkey minibuffer-local-map [(meta shift up)]
12324 (lambda () (interactive)
12325 (org-eval-in-calendar '(calendar-backward-year 1))))
12326 (org-defkey minibuffer-local-map [(meta shift down)]
12327 (lambda () (interactive)
12328 (org-eval-in-calendar '(calendar-forward-year 1))))
12329 (org-defkey minibuffer-local-map [?\e (shift left)]
12330 (lambda () (interactive)
12331 (org-eval-in-calendar '(calendar-backward-month 1))))
12332 (org-defkey minibuffer-local-map [?\e (shift right)]
12333 (lambda () (interactive)
12334 (org-eval-in-calendar '(calendar-forward-month 1))))
12335 (org-defkey minibuffer-local-map [?\e (shift up)]
12336 (lambda () (interactive)
12337 (org-eval-in-calendar '(calendar-backward-year 1))))
12338 (org-defkey minibuffer-local-map [?\e (shift down)]
12339 (lambda () (interactive)
12340 (org-eval-in-calendar '(calendar-forward-year 1))))
12341 (org-defkey minibuffer-local-map [(shift up)]
12342 (lambda () (interactive)
12343 (org-eval-in-calendar '(calendar-backward-week 1))))
12344 (org-defkey minibuffer-local-map [(shift down)]
12345 (lambda () (interactive)
12346 (org-eval-in-calendar '(calendar-forward-week 1))))
12347 (org-defkey minibuffer-local-map [(shift left)]
12348 (lambda () (interactive)
12349 (org-eval-in-calendar '(calendar-backward-day 1))))
12350 (org-defkey minibuffer-local-map [(shift right)]
12351 (lambda () (interactive)
12352 (org-eval-in-calendar '(calendar-forward-day 1))))
12353 (org-defkey minibuffer-local-map ">"
12354 (lambda () (interactive)
12355 (org-eval-in-calendar '(scroll-calendar-left 1))))
12356 (org-defkey minibuffer-local-map "<"
12357 (lambda () (interactive)
12358 (org-eval-in-calendar '(scroll-calendar-right 1))))
12359 (run-hooks 'org-read-date-minibuffer-setup-hook)
12360 (unwind-protect
12361 (progn
12362 (use-local-map map)
12363 (add-hook 'post-command-hook 'org-read-date-display)
12364 (setq org-ans0 (read-string prompt default-input
12365 'org-read-date-history nil))
12366 ;; org-ans0: from prompt
12367 ;; org-ans1: from mouse click
12368 ;; org-ans2: from calendar motion
12369 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
12370 (remove-hook 'post-command-hook 'org-read-date-display)
12371 (use-local-map old-map)
12372 (when org-read-date-overlay
12373 (org-delete-overlay org-read-date-overlay)
12374 (setq org-read-date-overlay nil)))))))
12376 (t ; Naked prompt only
12377 (unwind-protect
12378 (setq ans (read-string prompt default-input
12379 'org-read-date-history timestr))
12380 (when org-read-date-overlay
12381 (org-delete-overlay org-read-date-overlay)
12382 (setq org-read-date-overlay nil)))))
12384 (setq final (org-read-date-analyze ans def defdecode))
12385 (setq org-read-date-final-answer ans)
12387 (if to-time
12388 (apply 'encode-time final)
12389 (if (and (boundp 'org-time-was-given) org-time-was-given)
12390 (format "%04d-%02d-%02d %02d:%02d"
12391 (nth 5 final) (nth 4 final) (nth 3 final)
12392 (nth 2 final) (nth 1 final))
12393 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
12395 (defvar def)
12396 (defvar defdecode)
12397 (defvar with-time)
12398 (defun org-read-date-display ()
12399 "Display the current date prompt interpretation in the minibuffer."
12400 (when org-read-date-display-live
12401 (when org-read-date-overlay
12402 (org-delete-overlay org-read-date-overlay))
12403 (let ((p (point)))
12404 (end-of-line 1)
12405 (while (not (equal (buffer-substring
12406 (max (point-min) (- (point) 4)) (point))
12407 " "))
12408 (insert " "))
12409 (goto-char p))
12410 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
12411 " " (or org-ans1 org-ans2)))
12412 (org-end-time-was-given nil)
12413 (f (org-read-date-analyze ans def defdecode))
12414 (fmts (if org-dcst
12415 org-time-stamp-custom-formats
12416 org-time-stamp-formats))
12417 (fmt (if (or with-time
12418 (and (boundp 'org-time-was-given) org-time-was-given))
12419 (cdr fmts)
12420 (car fmts)))
12421 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
12422 (when (and org-end-time-was-given
12423 (string-match org-plain-time-of-day-regexp txt))
12424 (setq txt (concat (substring txt 0 (match-end 0)) "-"
12425 org-end-time-was-given
12426 (substring txt (match-end 0)))))
12427 (setq org-read-date-overlay
12428 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
12429 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
12431 (defun org-read-date-analyze (ans def defdecode)
12432 "Analyse the combined answer of the date prompt."
12433 ;; FIXME: cleanup and comment
12434 (let (delta deltan deltaw deltadef year month day
12435 hour minute second wday pm h2 m2 tl wday1
12436 iso-year iso-weekday iso-week iso-year iso-date)
12438 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
12439 (setq ans "+0"))
12441 (when (setq delta (org-read-date-get-relative ans (current-time) def))
12442 (setq ans (replace-match "" t t ans)
12443 deltan (car delta)
12444 deltaw (nth 1 delta)
12445 deltadef (nth 2 delta)))
12447 ;; Check if there is an iso week date in there
12448 ;; If yes, sore the info and postpone interpreting it until the rest
12449 ;; of the parsing is done
12450 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
12451 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
12452 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
12453 iso-week (string-to-number (match-string 2 ans)))
12454 (setq ans (replace-match "" t t ans)))
12456 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
12457 (when (string-match
12458 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
12459 (setq year (if (match-end 2)
12460 (string-to-number (match-string 2 ans))
12461 (string-to-number (format-time-string "%Y")))
12462 month (string-to-number (match-string 3 ans))
12463 day (string-to-number (match-string 4 ans)))
12464 (if (< year 100) (setq year (+ 2000 year)))
12465 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
12466 t nil ans)))
12467 ;; Help matching am/pm times, because `parse-time-string' does not do that.
12468 ;; If there is a time with am/pm, and *no* time without it, we convert
12469 ;; so that matching will be successful.
12470 (loop for i from 1 to 2 do ; twice, for end time as well
12471 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
12472 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
12473 (setq hour (string-to-number (match-string 1 ans))
12474 minute (if (match-end 3)
12475 (string-to-number (match-string 3 ans))
12477 pm (equal ?p
12478 (string-to-char (downcase (match-string 4 ans)))))
12479 (if (and (= hour 12) (not pm))
12480 (setq hour 0)
12481 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
12482 (setq ans (replace-match (format "%02d:%02d" hour minute)
12483 t t ans))))
12485 ;; Check if a time range is given as a duration
12486 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
12487 (setq hour (string-to-number (match-string 1 ans))
12488 h2 (+ hour (string-to-number (match-string 3 ans)))
12489 minute (string-to-number (match-string 2 ans))
12490 m2 (+ minute (if (match-end 5) (string-to-number
12491 (match-string 5 ans))0)))
12492 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
12493 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
12494 t t ans)))
12496 ;; Check if there is a time range
12497 (when (boundp 'org-end-time-was-given)
12498 (setq org-time-was-given nil)
12499 (when (and (string-match org-plain-time-of-day-regexp ans)
12500 (match-end 8))
12501 (setq org-end-time-was-given (match-string 8 ans))
12502 (setq ans (concat (substring ans 0 (match-beginning 7))
12503 (substring ans (match-end 7))))))
12505 (setq tl (parse-time-string ans)
12506 day (or (nth 3 tl) (nth 3 defdecode))
12507 month (or (nth 4 tl)
12508 (if (and org-read-date-prefer-future
12509 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
12510 (1+ (nth 4 defdecode))
12511 (nth 4 defdecode)))
12512 year (or (nth 5 tl)
12513 (if (and org-read-date-prefer-future
12514 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
12515 (1+ (nth 5 defdecode))
12516 (nth 5 defdecode)))
12517 hour (or (nth 2 tl) (nth 2 defdecode))
12518 minute (or (nth 1 tl) (nth 1 defdecode))
12519 second (or (nth 0 tl) 0)
12520 wday (nth 6 tl))
12522 ;; Special date definitions below
12523 (cond
12524 (iso-week
12525 ;; There was an iso week
12526 (setq year (or iso-year year)
12527 day (or iso-weekday wday 1)
12528 wday nil ; to make sure that the trigger below does not match
12529 iso-date (calendar-gregorian-from-absolute
12530 (calendar-absolute-from-iso
12531 (list iso-week day year))))
12532 ; FIXME: Should we also push ISO weeks into the future?
12533 ; (when (and org-read-date-prefer-future
12534 ; (not iso-year)
12535 ; (< (calendar-absolute-from-gregorian iso-date)
12536 ; (time-to-days (current-time))))
12537 ; (setq year (1+ year)
12538 ; iso-date (calendar-gregorian-from-absolute
12539 ; (calendar-absolute-from-iso
12540 ; (list iso-week day year)))))
12541 (setq month (car iso-date)
12542 year (nth 2 iso-date)
12543 day (nth 1 iso-date)))
12544 (deltan
12545 (unless deltadef
12546 (let ((now (decode-time (current-time))))
12547 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
12548 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
12549 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
12550 ((equal deltaw "m") (setq month (+ month deltan)))
12551 ((equal deltaw "y") (setq year (+ year deltan)))))
12552 ((and wday (not (nth 3 tl)))
12553 ;; Weekday was given, but no day, so pick that day in the week
12554 ;; on or after the derived date.
12555 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
12556 (unless (equal wday wday1)
12557 (setq day (+ day (% (- wday wday1 -7) 7))))))
12558 (if (and (boundp 'org-time-was-given)
12559 (nth 2 tl))
12560 (setq org-time-was-given t))
12561 (if (< year 100) (setq year (+ 2000 year)))
12562 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
12563 (list second minute hour day month year)))
12565 (defvar parse-time-weekdays)
12567 (defun org-read-date-get-relative (s today default)
12568 "Check string S for special relative date string.
12569 TODAY and DEFAULT are internal times, for today and for a default.
12570 Return shift list (N what def-flag)
12571 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
12572 N is the number of WHATs to shift.
12573 DEF-FLAG is t when a double ++ or -- indicates shift relative to
12574 the DEFAULT date rather than TODAY."
12575 (when (and
12576 (string-match
12577 (concat
12578 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
12579 "\\([0-9]+\\)?"
12580 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
12581 "\\([ \t]\\|$\\)") s)
12582 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
12583 (let* ((dir (if (> (match-end 1) (match-beginning 1))
12584 (string-to-char (substring (match-string 1 s) -1))
12585 ?+))
12586 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
12587 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
12588 (what (if (match-end 3) (match-string 3 s) "d"))
12589 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
12590 (date (if rel default today))
12591 (wday (nth 6 (decode-time date)))
12592 delta)
12593 (if wday1
12594 (progn
12595 (setq delta (mod (+ 7 (- wday1 wday)) 7))
12596 (if (= dir ?-) (setq delta (- delta 7)))
12597 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
12598 (list delta "d" rel))
12599 (list (* n (if (= dir ?-) -1 1)) what rel)))))
12601 (defun org-eval-in-calendar (form &optional keepdate)
12602 "Eval FORM in the calendar window and return to current window.
12603 Also, store the cursor date in variable org-ans2."
12604 (let ((sf (selected-frame))
12605 (sw (selected-window)))
12606 (select-window (get-buffer-window "*Calendar*" t))
12607 (eval form)
12608 (when (and (not keepdate) (calendar-cursor-to-date))
12609 (let* ((date (calendar-cursor-to-date))
12610 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12611 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
12612 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
12613 (select-window sw)
12614 (select-frame-set-input-focus sf)))
12616 (defun org-calendar-select ()
12617 "Return to `org-read-date' with the date currently selected.
12618 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12619 (interactive)
12620 (when (calendar-cursor-to-date)
12621 (let* ((date (calendar-cursor-to-date))
12622 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12623 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12624 (if (active-minibuffer-window) (exit-minibuffer))))
12626 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
12627 "Insert a date stamp for the date given by the internal TIME.
12628 WITH-HM means, use the stamp format that includes the time of the day.
12629 INACTIVE means use square brackets instead of angular ones, so that the
12630 stamp will not contribute to the agenda.
12631 PRE and POST are optional strings to be inserted before and after the
12632 stamp.
12633 The command returns the inserted time stamp."
12634 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
12635 stamp)
12636 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
12637 (insert-before-markers (or pre ""))
12638 (insert-before-markers (setq stamp (format-time-string fmt time)))
12639 (when (listp extra)
12640 (setq extra (car extra))
12641 (if (and (stringp extra)
12642 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
12643 (setq extra (format "-%02d:%02d"
12644 (string-to-number (match-string 1 extra))
12645 (string-to-number (match-string 2 extra))))
12646 (setq extra nil)))
12647 (when extra
12648 (backward-char 1)
12649 (insert-before-markers extra)
12650 (forward-char 1))
12651 (insert-before-markers (or post ""))
12652 (setq org-last-inserted-timestamp stamp)))
12654 (defun org-toggle-time-stamp-overlays ()
12655 "Toggle the use of custom time stamp formats."
12656 (interactive)
12657 (setq org-display-custom-times (not org-display-custom-times))
12658 (unless org-display-custom-times
12659 (let ((p (point-min)) (bmp (buffer-modified-p)))
12660 (while (setq p (next-single-property-change p 'display))
12661 (if (and (get-text-property p 'display)
12662 (eq (get-text-property p 'face) 'org-date))
12663 (remove-text-properties
12664 p (setq p (next-single-property-change p 'display))
12665 '(display t))))
12666 (set-buffer-modified-p bmp)))
12667 (if (featurep 'xemacs)
12668 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12669 (org-restart-font-lock)
12670 (setq org-table-may-need-update t)
12671 (if org-display-custom-times
12672 (message "Time stamps are overlayed with custom format")
12673 (message "Time stamp overlays removed")))
12675 (defun org-display-custom-time (beg end)
12676 "Overlay modified time stamp format over timestamp between BEG and END."
12677 (let* ((ts (buffer-substring beg end))
12678 t1 w1 with-hm tf time str w2 (off 0))
12679 (save-match-data
12680 (setq t1 (org-parse-time-string ts t))
12681 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
12682 (setq off (- (match-end 0) (match-beginning 0)))))
12683 (setq end (- end off))
12684 (setq w1 (- end beg)
12685 with-hm (and (nth 1 t1) (nth 2 t1))
12686 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
12687 time (org-fix-decoded-time t1)
12688 str (org-add-props
12689 (format-time-string
12690 (substring tf 1 -1) (apply 'encode-time time))
12691 nil 'mouse-face 'highlight)
12692 w2 (length str))
12693 (if (not (= w2 w1))
12694 (add-text-properties (1+ beg) (+ 2 beg)
12695 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12696 (if (featurep 'xemacs)
12697 (progn
12698 (put-text-property beg end 'invisible t)
12699 (put-text-property beg end 'end-glyph (make-glyph str)))
12700 (put-text-property beg end 'display str))))
12702 (defun org-translate-time (string)
12703 "Translate all timestamps in STRING to custom format.
12704 But do this only if the variable `org-display-custom-times' is set."
12705 (when org-display-custom-times
12706 (save-match-data
12707 (let* ((start 0)
12708 (re org-ts-regexp-both)
12709 t1 with-hm inactive tf time str beg end)
12710 (while (setq start (string-match re string start))
12711 (setq beg (match-beginning 0)
12712 end (match-end 0)
12713 t1 (save-match-data
12714 (org-parse-time-string (substring string beg end) t))
12715 with-hm (and (nth 1 t1) (nth 2 t1))
12716 inactive (equal (substring string beg (1+ beg)) "[")
12717 tf (funcall (if with-hm 'cdr 'car)
12718 org-time-stamp-custom-formats)
12719 time (org-fix-decoded-time t1)
12720 str (format-time-string
12721 (concat
12722 (if inactive "[" "<") (substring tf 1 -1)
12723 (if inactive "]" ">"))
12724 (apply 'encode-time time))
12725 string (replace-match str t t string)
12726 start (+ start (length str)))))))
12727 string)
12729 (defun org-fix-decoded-time (time)
12730 "Set 0 instead of nil for the first 6 elements of time.
12731 Don't touch the rest."
12732 (let ((n 0))
12733 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12735 (defun org-days-to-time (timestamp-string)
12736 "Difference between TIMESTAMP-STRING and now in days."
12737 (- (time-to-days (org-time-string-to-time timestamp-string))
12738 (time-to-days (current-time))))
12740 (defun org-deadline-close (timestamp-string &optional ndays)
12741 "Is the time in TIMESTAMP-STRING close to the current date?"
12742 (setq ndays (or ndays (org-get-wdays timestamp-string)))
12743 (and (< (org-days-to-time timestamp-string) ndays)
12744 (not (org-entry-is-done-p))))
12746 (defun org-get-wdays (ts)
12747 "Get the deadline lead time appropriate for timestring TS."
12748 (cond
12749 ((<= org-deadline-warning-days 0)
12750 ;; 0 or negative, enforce this value no matter what
12751 (- org-deadline-warning-days))
12752 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
12753 ;; lead time is specified.
12754 (floor (* (string-to-number (match-string 1 ts))
12755 (cdr (assoc (match-string 2 ts)
12756 '(("d" . 1) ("w" . 7)
12757 ("m" . 30.4) ("y" . 365.25)))))))
12758 ;; go for the default.
12759 (t org-deadline-warning-days)))
12761 (defun org-calendar-select-mouse (ev)
12762 "Return to `org-read-date' with the date currently selected.
12763 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12764 (interactive "e")
12765 (mouse-set-point ev)
12766 (when (calendar-cursor-to-date)
12767 (let* ((date (calendar-cursor-to-date))
12768 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12769 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12770 (if (active-minibuffer-window) (exit-minibuffer))))
12772 (defun org-check-deadlines (ndays)
12773 "Check if there are any deadlines due or past due.
12774 A deadline is considered due if it happens within `org-deadline-warning-days'
12775 days from today's date. If the deadline appears in an entry marked DONE,
12776 it is not shown. The prefix arg NDAYS can be used to test that many
12777 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12778 (interactive "P")
12779 (let* ((org-warn-days
12780 (cond
12781 ((equal ndays '(4)) 100000)
12782 (ndays (prefix-numeric-value ndays))
12783 (t (abs org-deadline-warning-days))))
12784 (case-fold-search nil)
12785 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12786 (callback
12787 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12789 (message "%d deadlines past-due or due within %d days"
12790 (org-occur regexp nil callback)
12791 org-warn-days)))
12793 (defun org-check-before-date (date)
12794 "Check if there are deadlines or scheduled entries before DATE."
12795 (interactive (list (org-read-date)))
12796 (let ((case-fold-search nil)
12797 (regexp (concat "\\<\\(" org-deadline-string
12798 "\\|" org-scheduled-string
12799 "\\) *<\\([^>]+\\)>"))
12800 (callback
12801 (lambda () (time-less-p
12802 (org-time-string-to-time (match-string 2))
12803 (org-time-string-to-time date)))))
12804 (message "%d entries before %s"
12805 (org-occur regexp nil callback) date)))
12807 (defun org-check-after-date (date)
12808 "Check if there are deadlines or scheduled entries after DATE."
12809 (interactive (list (org-read-date)))
12810 (let ((case-fold-search nil)
12811 (regexp (concat "\\<\\(" org-deadline-string
12812 "\\|" org-scheduled-string
12813 "\\) *<\\([^>]+\\)>"))
12814 (callback
12815 (lambda () (not
12816 (time-less-p
12817 (org-time-string-to-time (match-string 2))
12818 (org-time-string-to-time date))))))
12819 (message "%d entries after %s"
12820 (org-occur regexp nil callback) date)))
12822 (defun org-evaluate-time-range (&optional to-buffer)
12823 "Evaluate a time range by computing the difference between start and end.
12824 Normally the result is just printed in the echo area, but with prefix arg
12825 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12826 If the time range is actually in a table, the result is inserted into the
12827 next column.
12828 For time difference computation, a year is assumed to be exactly 365
12829 days in order to avoid rounding problems."
12830 (interactive "P")
12832 (org-clock-update-time-maybe)
12833 (save-excursion
12834 (unless (org-at-date-range-p t)
12835 (goto-char (point-at-bol))
12836 (re-search-forward org-tr-regexp-both (point-at-eol) t))
12837 (if (not (org-at-date-range-p t))
12838 (error "Not at a time-stamp range, and none found in current line")))
12839 (let* ((ts1 (match-string 1))
12840 (ts2 (match-string 2))
12841 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12842 (match-end (match-end 0))
12843 (time1 (org-time-string-to-time ts1))
12844 (time2 (org-time-string-to-time ts2))
12845 (t1 (time-to-seconds time1))
12846 (t2 (time-to-seconds time2))
12847 (diff (abs (- t2 t1)))
12848 (negative (< (- t2 t1) 0))
12849 ;; (ys (floor (* 365 24 60 60)))
12850 (ds (* 24 60 60))
12851 (hs (* 60 60))
12852 (fy "%dy %dd %02d:%02d")
12853 (fy1 "%dy %dd")
12854 (fd "%dd %02d:%02d")
12855 (fd1 "%dd")
12856 (fh "%02d:%02d")
12857 y d h m align)
12858 (if havetime
12859 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12861 d (floor (/ diff ds)) diff (mod diff ds)
12862 h (floor (/ diff hs)) diff (mod diff hs)
12863 m (floor (/ diff 60)))
12864 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12866 d (floor (+ (/ diff ds) 0.5))
12867 h 0 m 0))
12868 (if (not to-buffer)
12869 (message "%s" (org-make-tdiff-string y d h m))
12870 (if (org-at-table-p)
12871 (progn
12872 (goto-char match-end)
12873 (setq align t)
12874 (and (looking-at " *|") (goto-char (match-end 0))))
12875 (goto-char match-end))
12876 (if (looking-at
12877 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12878 (replace-match ""))
12879 (if negative (insert " -"))
12880 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12881 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12882 (insert " " (format fh h m))))
12883 (if align (org-table-align))
12884 (message "Time difference inserted")))))
12886 (defun org-make-tdiff-string (y d h m)
12887 (let ((fmt "")
12888 (l nil))
12889 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12890 l (push y l)))
12891 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12892 l (push d l)))
12893 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12894 l (push h l)))
12895 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12896 l (push m l)))
12897 (apply 'format fmt (nreverse l))))
12899 (defun org-time-string-to-time (s)
12900 (apply 'encode-time (org-parse-time-string s)))
12901 (defun org-time-string-to-seconds (s)
12902 (time-to-seconds (org-time-string-to-time s)))
12904 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
12905 "Convert a time stamp to an absolute day number.
12906 If there is a specifyer for a cyclic time stamp, get the closest date to
12907 DAYNR.
12908 PREFER and SHOW-ALL are passed through to `org-closest-date'.
12909 the variable date is bound by the calendar when this is called."
12910 (cond
12911 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
12912 (if (org-diary-sexp-entry (match-string 1 s) "" date)
12913 daynr
12914 (+ daynr 1000)))
12915 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
12916 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
12917 (time-to-days (current-time))) (match-string 0 s)
12918 prefer show-all))
12919 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
12921 (defun org-days-to-iso-week (days)
12922 "Return the iso week number."
12923 (require 'cal-iso)
12924 (car (calendar-iso-from-absolute days)))
12926 (defun org-small-year-to-year (year)
12927 "Convert 2-digit years into 4-digit years.
12928 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
12929 The year 2000 cannot be abbreviated. Any year larger than 99
12930 is returned unchanged."
12931 (if (< year 38)
12932 (setq year (+ 2000 year))
12933 (if (< year 100)
12934 (setq year (+ 1900 year))))
12935 year)
12937 (defun org-time-from-absolute (d)
12938 "Return the time corresponding to date D.
12939 D may be an absolute day number, or a calendar-type list (month day year)."
12940 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
12941 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
12943 (defun org-calendar-holiday ()
12944 "List of holidays, for Diary display in Org-mode."
12945 (require 'holidays)
12946 (let ((hl (funcall
12947 (if (fboundp 'calendar-check-holidays)
12948 'calendar-check-holidays 'check-calendar-holidays) date)))
12949 (if hl (mapconcat 'identity hl "; "))))
12951 (defun org-diary-sexp-entry (sexp entry date)
12952 "Process a SEXP diary ENTRY for DATE."
12953 (require 'diary-lib)
12954 (let ((result (if calendar-debug-sexp
12955 (let ((stack-trace-on-error t))
12956 (eval (car (read-from-string sexp))))
12957 (condition-case nil
12958 (eval (car (read-from-string sexp)))
12959 (error
12960 (beep)
12961 (message "Bad sexp at line %d in %s: %s"
12962 (org-current-line)
12963 (buffer-file-name) sexp)
12964 (sleep-for 2))))))
12965 (cond ((stringp result) result)
12966 ((and (consp result)
12967 (stringp (cdr result))) (cdr result))
12968 (result entry)
12969 (t nil))))
12971 (defun org-diary-to-ical-string (frombuf)
12972 "Get iCalendar entries from diary entries in buffer FROMBUF.
12973 This uses the icalendar.el library."
12974 (let* ((tmpdir (if (featurep 'xemacs)
12975 (temp-directory)
12976 temporary-file-directory))
12977 (tmpfile (make-temp-name
12978 (expand-file-name "orgics" tmpdir)))
12979 buf rtn b e)
12980 (save-excursion
12981 (set-buffer frombuf)
12982 (icalendar-export-region (point-min) (point-max) tmpfile)
12983 (setq buf (find-buffer-visiting tmpfile))
12984 (set-buffer buf)
12985 (goto-char (point-min))
12986 (if (re-search-forward "^BEGIN:VEVENT" nil t)
12987 (setq b (match-beginning 0)))
12988 (goto-char (point-max))
12989 (if (re-search-backward "^END:VEVENT" nil t)
12990 (setq e (match-end 0)))
12991 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
12992 (kill-buffer buf)
12993 (delete-file tmpfile)
12994 rtn))
12996 (defun org-closest-date (start current change prefer show-all)
12997 "Find the date closest to CURRENT that is consistent with START and CHANGE.
12998 When PREFER is `past' return a date that is either CURRENT or past.
12999 When PREFER is `future', return a date that is either CURRENT or future.
13000 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
13001 ;; Make the proper lists from the dates
13002 (catch 'exit
13003 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
13004 dn dw sday cday n1 n2 n0
13005 d m y y1 y2 date1 date2 nmonths nm ny m2)
13007 (setq start (org-date-to-gregorian start)
13008 current (org-date-to-gregorian
13009 (if show-all
13010 current
13011 (time-to-days (current-time))))
13012 sday (calendar-absolute-from-gregorian start)
13013 cday (calendar-absolute-from-gregorian current))
13015 (if (<= cday sday) (throw 'exit sday))
13017 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
13018 (setq dn (string-to-number (match-string 1 change))
13019 dw (cdr (assoc (match-string 2 change) a1)))
13020 (error "Invalid change specifyer: %s" change))
13021 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
13022 (cond
13023 ((eq dw 'day)
13024 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
13025 n2 (+ n1 dn)))
13026 ((eq dw 'year)
13027 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
13028 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
13029 (setq date1 (list m d y1)
13030 n1 (calendar-absolute-from-gregorian date1)
13031 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
13032 n2 (calendar-absolute-from-gregorian date2)))
13033 ((eq dw 'month)
13034 ;; approx number of month between the two dates
13035 (setq nmonths (floor (/ (- cday sday) 30.436875)))
13036 ;; How often does dn fit in there?
13037 (setq d (nth 1 start) m (car start) y (nth 2 start)
13038 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
13039 m (+ m nm)
13040 ny (floor (/ m 12))
13041 y (+ y ny)
13042 m (- m (* ny 12)))
13043 (while (> m 12) (setq m (- m 12) y (1+ y)))
13044 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
13045 (setq m2 (+ m dn) y2 y)
13046 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13047 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
13048 (while (<= n2 cday)
13049 (setq n1 n2 m m2 y y2)
13050 (setq m2 (+ m dn) y2 y)
13051 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13052 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
13053 ;; Make sure n1 is the earlier date
13054 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
13055 (if show-all
13056 (cond
13057 ((eq prefer 'past) n1)
13058 ((eq prefer 'future) (if (= cday n1) n1 n2))
13059 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
13060 (cond
13061 ((eq prefer 'past) n1)
13062 ((eq prefer 'future) (if (= cday n1) n1 n2))
13063 (t (if (= cday n1) n1 n2)))))))
13065 (defun org-date-to-gregorian (date)
13066 "Turn any specification of DATE into a gregorian date for the calendar."
13067 (cond ((integerp date) (calendar-gregorian-from-absolute date))
13068 ((and (listp date) (= (length date) 3)) date)
13069 ((stringp date)
13070 (setq date (org-parse-time-string date))
13071 (list (nth 4 date) (nth 3 date) (nth 5 date)))
13072 ((listp date)
13073 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
13075 (defun org-parse-time-string (s &optional nodefault)
13076 "Parse the standard Org-mode time string.
13077 This should be a lot faster than the normal `parse-time-string'.
13078 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
13079 hour and minute fields will be nil if not given."
13080 (if (string-match org-ts-regexp0 s)
13081 (list 0
13082 (if (or (match-beginning 8) (not nodefault))
13083 (string-to-number (or (match-string 8 s) "0")))
13084 (if (or (match-beginning 7) (not nodefault))
13085 (string-to-number (or (match-string 7 s) "0")))
13086 (string-to-number (match-string 4 s))
13087 (string-to-number (match-string 3 s))
13088 (string-to-number (match-string 2 s))
13089 nil nil nil)
13090 (make-list 9 0)))
13092 (defun org-timestamp-up (&optional arg)
13093 "Increase the date item at the cursor by one.
13094 If the cursor is on the year, change the year. If it is on the month or
13095 the day, change that.
13096 With prefix ARG, change by that many units."
13097 (interactive "p")
13098 (org-timestamp-change (prefix-numeric-value arg)))
13100 (defun org-timestamp-down (&optional arg)
13101 "Decrease the date item at the cursor by one.
13102 If the cursor is on the year, change the year. If it is on the month or
13103 the day, change that.
13104 With prefix ARG, change by that many units."
13105 (interactive "p")
13106 (org-timestamp-change (- (prefix-numeric-value arg))))
13108 (defun org-timestamp-up-day (&optional arg)
13109 "Increase the date in the time stamp by one day.
13110 With prefix ARG, change that many days."
13111 (interactive "p")
13112 (if (and (not (org-at-timestamp-p t))
13113 (org-on-heading-p))
13114 (org-todo 'up)
13115 (org-timestamp-change (prefix-numeric-value arg) 'day)))
13117 (defun org-timestamp-down-day (&optional arg)
13118 "Decrease the date in the time stamp by one day.
13119 With prefix ARG, change that many days."
13120 (interactive "p")
13121 (if (and (not (org-at-timestamp-p t))
13122 (org-on-heading-p))
13123 (org-todo 'down)
13124 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
13126 (defun org-at-timestamp-p (&optional inactive-ok)
13127 "Determine if the cursor is in or at a timestamp."
13128 (interactive)
13129 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
13130 (pos (point))
13131 (ans (or (looking-at tsr)
13132 (save-excursion
13133 (skip-chars-backward "^[<\n\r\t")
13134 (if (> (point) (point-min)) (backward-char 1))
13135 (and (looking-at tsr)
13136 (> (- (match-end 0) pos) -1))))))
13137 (and ans
13138 (boundp 'org-ts-what)
13139 (setq org-ts-what
13140 (cond
13141 ((= pos (match-beginning 0)) 'bracket)
13142 ((= pos (1- (match-end 0))) 'bracket)
13143 ((org-pos-in-match-range pos 2) 'year)
13144 ((org-pos-in-match-range pos 3) 'month)
13145 ((org-pos-in-match-range pos 7) 'hour)
13146 ((org-pos-in-match-range pos 8) 'minute)
13147 ((or (org-pos-in-match-range pos 4)
13148 (org-pos-in-match-range pos 5)) 'day)
13149 ((and (> pos (or (match-end 8) (match-end 5)))
13150 (< pos (match-end 0)))
13151 (- pos (or (match-end 8) (match-end 5))))
13152 (t 'day))))
13153 ans))
13155 (defun org-toggle-timestamp-type ()
13156 "Toggle the type (<active> or [inactive]) of a time stamp."
13157 (interactive)
13158 (when (org-at-timestamp-p t)
13159 (let ((beg (match-beginning 0)) (end (match-end 0))
13160 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
13161 (save-excursion
13162 (goto-char beg)
13163 (while (re-search-forward "[][<>]" end t)
13164 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
13165 t t)))
13166 (message "Timestamp is now %sactive"
13167 (if (equal (char-after beg) ?<) "" "in")))))
13169 (defun org-timestamp-change (n &optional what)
13170 "Change the date in the time stamp at point.
13171 The date will be changed by N times WHAT. WHAT can be `day', `month',
13172 `year', `minute', `second'. If WHAT is not given, the cursor position
13173 in the timestamp determines what will be changed."
13174 (let ((pos (point))
13175 with-hm inactive
13176 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
13177 org-ts-what
13178 extra rem
13179 ts time time0)
13180 (if (not (org-at-timestamp-p t))
13181 (error "Not at a timestamp"))
13182 (if (and (not what) (eq org-ts-what 'bracket))
13183 (org-toggle-timestamp-type)
13184 (if (and (not what) (not (eq org-ts-what 'day))
13185 org-display-custom-times
13186 (get-text-property (point) 'display)
13187 (not (get-text-property (1- (point)) 'display)))
13188 (setq org-ts-what 'day))
13189 (setq org-ts-what (or what org-ts-what)
13190 inactive (= (char-after (match-beginning 0)) ?\[)
13191 ts (match-string 0))
13192 (replace-match "")
13193 (if (string-match
13194 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
13196 (setq extra (match-string 1 ts)))
13197 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
13198 (setq with-hm t))
13199 (setq time0 (org-parse-time-string ts))
13200 (when (and (eq org-ts-what 'minute)
13201 (eq current-prefix-arg nil))
13202 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
13203 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
13204 (setcar (cdr time0) (+ (nth 1 time0)
13205 (if (> n 0) (- rem) (- dm rem))))))
13206 (setq time
13207 (encode-time (or (car time0) 0)
13208 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
13209 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
13210 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
13211 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
13212 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
13213 (nthcdr 6 time0)))
13214 (when (and (member org-ts-what '(hour minute))
13215 extra
13216 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
13217 (setq extra (org-modify-ts-extra
13218 extra
13219 (if (eq org-ts-what 'hour) 2 5)
13220 n dm)))
13221 (when (integerp org-ts-what)
13222 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
13223 (if (eq what 'calendar)
13224 (let ((cal-date (org-get-date-from-calendar)))
13225 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
13226 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
13227 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
13228 (setcar time0 (or (car time0) 0))
13229 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
13230 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
13231 (setq time (apply 'encode-time time0))))
13232 (setq org-last-changed-timestamp
13233 (org-insert-time-stamp time with-hm inactive nil nil extra))
13234 (org-clock-update-time-maybe)
13235 (goto-char pos)
13236 ;; Try to recenter the calendar window, if any
13237 (if (and org-calendar-follow-timestamp-change
13238 (get-buffer-window "*Calendar*" t)
13239 (memq org-ts-what '(day month year)))
13240 (org-recenter-calendar (time-to-days time))))))
13242 (defun org-modify-ts-extra (s pos n dm)
13243 "Change the different parts of the lead-time and repeat fields in timestamp."
13244 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
13245 ng h m new rem)
13246 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
13247 (cond
13248 ((or (org-pos-in-match-range pos 2)
13249 (org-pos-in-match-range pos 3))
13250 (setq m (string-to-number (match-string 3 s))
13251 h (string-to-number (match-string 2 s)))
13252 (if (org-pos-in-match-range pos 2)
13253 (setq h (+ h n))
13254 (setq n (* dm (org-no-warnings (signum n))))
13255 (when (not (= 0 (setq rem (% m dm))))
13256 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
13257 (setq m (+ m n)))
13258 (if (< m 0) (setq m (+ m 60) h (1- h)))
13259 (if (> m 59) (setq m (- m 60) h (1+ h)))
13260 (setq h (min 24 (max 0 h)))
13261 (setq ng 1 new (format "-%02d:%02d" h m)))
13262 ((org-pos-in-match-range pos 6)
13263 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
13264 ((org-pos-in-match-range pos 5)
13265 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
13267 ((org-pos-in-match-range pos 9)
13268 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
13269 ((org-pos-in-match-range pos 8)
13270 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
13272 (when ng
13273 (setq s (concat
13274 (substring s 0 (match-beginning ng))
13276 (substring s (match-end ng))))))
13279 (defun org-recenter-calendar (date)
13280 "If the calendar is visible, recenter it to DATE."
13281 (let* ((win (selected-window))
13282 (cwin (get-buffer-window "*Calendar*" t))
13283 (calendar-move-hook nil))
13284 (when cwin
13285 (select-window cwin)
13286 (calendar-goto-date (if (listp date) date
13287 (calendar-gregorian-from-absolute date)))
13288 (select-window win))))
13290 (defun org-goto-calendar (&optional arg)
13291 "Go to the Emacs calendar at the current date.
13292 If there is a time stamp in the current line, go to that date.
13293 A prefix ARG can be used to force the current date."
13294 (interactive "P")
13295 (let ((tsr org-ts-regexp) diff
13296 (calendar-move-hook nil)
13297 (calendar-view-holidays-initially-flag nil)
13298 (view-calendar-holidays-initially nil)
13299 (calendar-view-diary-initially-flag nil)
13300 (view-diary-entries-initially nil))
13301 (if (or (org-at-timestamp-p)
13302 (save-excursion
13303 (beginning-of-line 1)
13304 (looking-at (concat ".*" tsr))))
13305 (let ((d1 (time-to-days (current-time)))
13306 (d2 (time-to-days
13307 (org-time-string-to-time (match-string 1)))))
13308 (setq diff (- d2 d1))))
13309 (calendar)
13310 (calendar-goto-today)
13311 (if (and diff (not arg)) (calendar-forward-day diff))))
13313 (defun org-get-date-from-calendar ()
13314 "Return a list (month day year) of date at point in calendar."
13315 (with-current-buffer "*Calendar*"
13316 (save-match-data
13317 (calendar-cursor-to-date))))
13319 (defun org-date-from-calendar ()
13320 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
13321 If there is already a time stamp at the cursor position, update it."
13322 (interactive)
13323 (if (org-at-timestamp-p t)
13324 (org-timestamp-change 0 'calendar)
13325 (let ((cal-date (org-get-date-from-calendar)))
13326 (org-insert-time-stamp
13327 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
13329 (defun org-minutes-to-hh:mm-string (m)
13330 "Compute H:MM from a number of minutes."
13331 (let ((h (/ m 60)))
13332 (setq m (- m (* 60 h)))
13333 (format org-time-clocksum-format h m)))
13335 (defun org-hh:mm-string-to-minutes (s)
13336 "Convert a string H:MM to a number of minutes.
13337 If the string is just a number, interprete it as minutes.
13338 In fact, the first hh:mm or number in the string will be taken,
13339 there can be extra stuff in the string.
13340 If no number is found, the return value is 0."
13341 (cond
13342 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
13343 (+ (* (string-to-number (match-string 1 s)) 60)
13344 (string-to-number (match-string 2 s))))
13345 ((string-match "\\([0-9]+\\)" s)
13346 (string-to-number (match-string 1 s)))
13347 (t 0)))
13349 ;;;; Files
13351 (defun org-save-all-org-buffers ()
13352 "Save all Org-mode buffers without user confirmation."
13353 (interactive)
13354 (message "Saving all Org-mode buffers...")
13355 (save-some-buffers t 'org-mode-p)
13356 (when (featurep 'org-id) (org-id-locations-save))
13357 (message "Saving all Org-mode buffers... done"))
13359 (defun org-revert-all-org-buffers ()
13360 "Revert all Org-mode buffers.
13361 Prompt for confirmation when there are unsaved changes.
13362 Be sure you know what you are doing before letting this function
13363 overwrite your changes.
13365 This function is useful in a setup where one tracks org files
13366 with a version control system, to revert on one machine after pulling
13367 changes from another. I believe the procedure must be like this:
13369 1. M-x org-save-all-org-buffers
13370 2. Pull changes from the other machine, resolve conflicts
13371 3. M-x org-revert-all-org-buffers"
13372 (interactive)
13373 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
13374 (error "Abort"))
13375 (save-excursion
13376 (save-window-excursion
13377 (mapc
13378 (lambda (b)
13379 (when (and (with-current-buffer b (org-mode-p))
13380 (with-current-buffer b buffer-file-name))
13381 (switch-to-buffer b)
13382 (revert-buffer t 'no-confirm)))
13383 (buffer-list))
13384 (when (and (featurep 'org-id) org-id-track-globally)
13385 (org-id-locations-load)))))
13387 ;;;; Agenda files
13389 ;;;###autoload
13390 (defun org-iswitchb (&optional arg)
13391 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
13392 With a prefix argument, restrict available to files.
13393 With two prefix arguments, restrict available buffers to agenda files.
13395 Due to some yet unresolved reason, the global function
13396 `iswitchb-mode' needs to be active for this function to work."
13397 (interactive "P")
13398 (require 'iswitchb)
13399 (let ((enabled iswitchb-mode) blist)
13400 (or enabled (iswitchb-mode 1))
13401 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13402 ((equal arg '(16)) (org-buffer-list 'agenda))
13403 (t (org-buffer-list))))
13404 (unwind-protect
13405 (let ((iswitchb-make-buflist-hook
13406 (lambda ()
13407 (setq iswitchb-temp-buflist
13408 (mapcar 'buffer-name blist)))))
13409 (switch-to-buffer
13410 (iswitchb-read-buffer
13411 "Switch-to: " nil t)))
13412 (or enabled (iswitchb-mode -1)))))
13414 ;;;###autoload
13415 (defun org-ido-switchb (&optional arg)
13416 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
13417 With a prefix argument, restrict available to files.
13418 With two prefix arguments, restrict available buffers to agenda files."
13419 (interactive "P")
13420 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13421 ((equal arg '(16)) (org-buffer-list 'agenda))
13422 (t (org-buffer-list)))))
13423 (switch-to-buffer
13424 (org-ido-completing-read "Org buffer: "
13425 (mapcar 'list (mapcar 'buffer-name blist))
13426 nil t))))
13428 (defun org-buffer-list (&optional predicate exclude-tmp)
13429 "Return a list of Org buffers.
13430 PREDICATE can be `export', `files' or `agenda'.
13432 export restrict the list to Export buffers.
13433 files restrict the list to buffers visiting Org files.
13434 agenda restrict the list to buffers visiting agenda files.
13436 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
13437 (let* ((bfn nil)
13438 (agenda-files (and (eq predicate 'agenda)
13439 (mapcar 'file-truename (org-agenda-files t))))
13440 (filter
13441 (cond
13442 ((eq predicate 'files)
13443 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
13444 ((eq predicate 'export)
13445 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
13446 ((eq predicate 'agenda)
13447 (lambda (b)
13448 (with-current-buffer b
13449 (and (eq major-mode 'org-mode)
13450 (setq bfn (buffer-file-name b))
13451 (member (file-truename bfn) agenda-files)))))
13452 (t (lambda (b) (with-current-buffer b
13453 (or (eq major-mode 'org-mode)
13454 (string-match "\*Org .*Export"
13455 (buffer-name b)))))))))
13456 (delq nil
13457 (mapcar
13458 (lambda(b)
13459 (if (and (funcall filter b)
13460 (or (not exclude-tmp)
13461 (not (string-match "tmp" (buffer-name b)))))
13463 nil))
13464 (buffer-list)))))
13466 (defun org-agenda-files (&optional unrestricted archives)
13467 "Get the list of agenda files.
13468 Optional UNRESTRICTED means return the full list even if a restriction
13469 is currently in place.
13470 When ARCHIVES is t, include all archive files hat are really being
13471 used by the agenda files. If ARCHIVE is `ifmode', do this only if
13472 `org-agenda-archives-mode' is t."
13473 (let ((files
13474 (cond
13475 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
13476 ((stringp org-agenda-files) (org-read-agenda-file-list))
13477 ((listp org-agenda-files) org-agenda-files)
13478 (t (error "Invalid value of `org-agenda-files'")))))
13479 (setq files (apply 'append
13480 (mapcar (lambda (f)
13481 (if (file-directory-p f)
13482 (directory-files
13483 f t org-agenda-file-regexp)
13484 (list f)))
13485 files)))
13486 (when org-agenda-skip-unavailable-files
13487 (setq files (delq nil
13488 (mapcar (function
13489 (lambda (file)
13490 (and (file-readable-p file) file)))
13491 files))))
13492 (when (or (eq archives t)
13493 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
13494 (setq files (org-add-archive-files files)))
13495 files))
13497 (defun org-edit-agenda-file-list ()
13498 "Edit the list of agenda files.
13499 Depending on setup, this either uses customize to edit the variable
13500 `org-agenda-files', or it visits the file that is holding the list. In the
13501 latter case, the buffer is set up in a way that saving it automatically kills
13502 the buffer and restores the previous window configuration."
13503 (interactive)
13504 (if (stringp org-agenda-files)
13505 (let ((cw (current-window-configuration)))
13506 (find-file org-agenda-files)
13507 (org-set-local 'org-window-configuration cw)
13508 (org-add-hook 'after-save-hook
13509 (lambda ()
13510 (set-window-configuration
13511 (prog1 org-window-configuration
13512 (kill-buffer (current-buffer))))
13513 (org-install-agenda-files-menu)
13514 (message "New agenda file list installed"))
13515 nil 'local)
13516 (message "%s" (substitute-command-keys
13517 "Edit list and finish with \\[save-buffer]")))
13518 (customize-variable 'org-agenda-files)))
13520 (defun org-store-new-agenda-file-list (list)
13521 "Set new value for the agenda file list and save it correctly."
13522 (if (stringp org-agenda-files)
13523 (let ((f org-agenda-files) b)
13524 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
13525 (with-temp-file f
13526 (insert (mapconcat 'identity list "\n") "\n")))
13527 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
13528 (setq org-agenda-files list)
13529 (customize-save-variable 'org-agenda-files org-agenda-files))))
13531 (defun org-read-agenda-file-list ()
13532 "Read the list of agenda files from a file."
13533 (when (file-directory-p org-agenda-files)
13534 (error "`org-agenda-files' cannot be a single directory"))
13535 (when (stringp org-agenda-files)
13536 (with-temp-buffer
13537 (insert-file-contents org-agenda-files)
13538 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
13541 ;;;###autoload
13542 (defun org-cycle-agenda-files ()
13543 "Cycle through the files in `org-agenda-files'.
13544 If the current buffer visits an agenda file, find the next one in the list.
13545 If the current buffer does not, find the first agenda file."
13546 (interactive)
13547 (let* ((fs (org-agenda-files t))
13548 (files (append fs (list (car fs))))
13549 (tcf (if buffer-file-name (file-truename buffer-file-name)))
13550 file)
13551 (unless files (error "No agenda files"))
13552 (catch 'exit
13553 (while (setq file (pop files))
13554 (if (equal (file-truename file) tcf)
13555 (when (car files)
13556 (find-file (car files))
13557 (throw 'exit t))))
13558 (find-file (car fs)))
13559 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
13561 (defun org-agenda-file-to-front (&optional to-end)
13562 "Move/add the current file to the top of the agenda file list.
13563 If the file is not present in the list, it is added to the front. If it is
13564 present, it is moved there. With optional argument TO-END, add/move to the
13565 end of the list."
13566 (interactive "P")
13567 (let ((org-agenda-skip-unavailable-files nil)
13568 (file-alist (mapcar (lambda (x)
13569 (cons (file-truename x) x))
13570 (org-agenda-files t)))
13571 (ctf (file-truename buffer-file-name))
13572 x had)
13573 (setq x (assoc ctf file-alist) had x)
13575 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
13576 (if to-end
13577 (setq file-alist (append (delq x file-alist) (list x)))
13578 (setq file-alist (cons x (delq x file-alist))))
13579 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
13580 (org-install-agenda-files-menu)
13581 (message "File %s to %s of agenda file list"
13582 (if had "moved" "added") (if to-end "end" "front"))))
13584 (defun org-remove-file (&optional file)
13585 "Remove current file from the list of files in variable `org-agenda-files'.
13586 These are the files which are being checked for agenda entries.
13587 Optional argument FILE means, use this file instead of the current."
13588 (interactive)
13589 (let* ((org-agenda-skip-unavailable-files nil)
13590 (file (or file buffer-file-name))
13591 (true-file (file-truename file))
13592 (afile (abbreviate-file-name file))
13593 (files (delq nil (mapcar
13594 (lambda (x)
13595 (if (equal true-file
13596 (file-truename x))
13597 nil x))
13598 (org-agenda-files t)))))
13599 (if (not (= (length files) (length (org-agenda-files t))))
13600 (progn
13601 (org-store-new-agenda-file-list files)
13602 (org-install-agenda-files-menu)
13603 (message "Removed file: %s" afile))
13604 (message "File was not in list: %s (not removed)" afile))))
13606 (defun org-file-menu-entry (file)
13607 (vector file (list 'find-file file) t))
13609 (defun org-check-agenda-file (file)
13610 "Make sure FILE exists. If not, ask user what to do."
13611 (when (not (file-exists-p file))
13612 (message "non-existent file %s. [R]emove from list or [A]bort?"
13613 (abbreviate-file-name file))
13614 (let ((r (downcase (read-char-exclusive))))
13615 (cond
13616 ((equal r ?r)
13617 (org-remove-file file)
13618 (throw 'nextfile t))
13619 (t (error "Abort"))))))
13621 (defun org-get-agenda-file-buffer (file)
13622 "Get a buffer visiting FILE. If the buffer needs to be created, add
13623 it to the list of buffers which might be released later."
13624 (let ((buf (org-find-base-buffer-visiting file)))
13625 (if buf
13626 buf ; just return it
13627 ;; Make a new buffer and remember it
13628 (setq buf (find-file-noselect file))
13629 (if buf (push buf org-agenda-new-buffers))
13630 buf)))
13632 (defun org-release-buffers (blist)
13633 "Release all buffers in list, asking the user for confirmation when needed.
13634 When a buffer is unmodified, it is just killed. When modified, it is saved
13635 \(if the user agrees) and then killed."
13636 (let (buf file)
13637 (while (setq buf (pop blist))
13638 (setq file (buffer-file-name buf))
13639 (when (and (buffer-modified-p buf)
13640 file
13641 (y-or-n-p (format "Save file %s? " file)))
13642 (with-current-buffer buf (save-buffer)))
13643 (kill-buffer buf))))
13645 (defun org-prepare-agenda-buffers (files)
13646 "Create buffers for all agenda files, protect archived trees and comments."
13647 (interactive)
13648 (let ((pa '(:org-archived t))
13649 (pc '(:org-comment t))
13650 (pall '(:org-archived t :org-comment t))
13651 (inhibit-read-only t)
13652 (rea (concat ":" org-archive-tag ":"))
13653 bmp file re)
13654 (save-excursion
13655 (save-restriction
13656 (while (setq file (pop files))
13657 (catch 'nextfile
13658 (if (bufferp file)
13659 (set-buffer file)
13660 (org-check-agenda-file file)
13661 (set-buffer (org-get-agenda-file-buffer file)))
13662 (widen)
13663 (setq bmp (buffer-modified-p))
13664 (org-refresh-category-properties)
13665 (setq org-todo-keywords-for-agenda
13666 (append org-todo-keywords-for-agenda org-todo-keywords-1))
13667 (setq org-done-keywords-for-agenda
13668 (append org-done-keywords-for-agenda org-done-keywords))
13669 (setq org-todo-keyword-alist-for-agenda
13670 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
13671 (setq org-tag-alist-for-agenda
13672 (append org-tag-alist-for-agenda org-tag-alist))
13674 (save-excursion
13675 (remove-text-properties (point-min) (point-max) pall)
13676 (when org-agenda-skip-archived-trees
13677 (goto-char (point-min))
13678 (while (re-search-forward rea nil t)
13679 (if (org-on-heading-p t)
13680 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
13681 (goto-char (point-min))
13682 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
13683 (while (re-search-forward re nil t)
13684 (add-text-properties
13685 (match-beginning 0) (org-end-of-subtree t) pc)))
13686 (set-buffer-modified-p bmp)))))
13687 (setq org-todo-keyword-alist-for-agenda
13688 (org-uniquify org-todo-keyword-alist-for-agenda)
13689 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
13691 ;;;; Embedded LaTeX
13693 (defvar org-cdlatex-mode-map (make-sparse-keymap)
13694 "Keymap for the minor `org-cdlatex-mode'.")
13696 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
13697 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
13698 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
13699 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
13700 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
13702 (defvar org-cdlatex-texmathp-advice-is-done nil
13703 "Flag remembering if we have applied the advice to texmathp already.")
13705 (define-minor-mode org-cdlatex-mode
13706 "Toggle the minor `org-cdlatex-mode'.
13707 This mode supports entering LaTeX environment and math in LaTeX fragments
13708 in Org-mode.
13709 \\{org-cdlatex-mode-map}"
13710 nil " OCDL" nil
13711 (when org-cdlatex-mode (require 'cdlatex))
13712 (unless org-cdlatex-texmathp-advice-is-done
13713 (setq org-cdlatex-texmathp-advice-is-done t)
13714 (defadvice texmathp (around org-math-always-on activate)
13715 "Always return t in org-mode buffers.
13716 This is because we want to insert math symbols without dollars even outside
13717 the LaTeX math segments. If Orgmode thinks that point is actually inside
13718 an embedded LaTeX fragment, let texmathp do its job.
13719 \\[org-cdlatex-mode-map]"
13720 (interactive)
13721 (let (p)
13722 (cond
13723 ((not (org-mode-p)) ad-do-it)
13724 ((eq this-command 'cdlatex-math-symbol)
13725 (setq ad-return-value t
13726 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
13728 (let ((p (org-inside-LaTeX-fragment-p)))
13729 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
13730 (setq ad-return-value t
13731 texmathp-why '("Org-mode embedded math" . 0))
13732 (if p ad-do-it)))))))))
13734 (defun turn-on-org-cdlatex ()
13735 "Unconditionally turn on `org-cdlatex-mode'."
13736 (org-cdlatex-mode 1))
13738 (defun org-inside-LaTeX-fragment-p ()
13739 "Test if point is inside a LaTeX fragment.
13740 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
13741 sequence appearing also before point.
13742 Even though the matchers for math are configurable, this function assumes
13743 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
13744 delimiters are skipped when they have been removed by customization.
13745 The return value is nil, or a cons cell with the delimiter and
13746 and the position of this delimiter.
13748 This function does a reasonably good job, but can locally be fooled by
13749 for example currency specifications. For example it will assume being in
13750 inline math after \"$22.34\". The LaTeX fragment formatter will only format
13751 fragments that are properly closed, but during editing, we have to live
13752 with the uncertainty caused by missing closing delimiters. This function
13753 looks only before point, not after."
13754 (catch 'exit
13755 (let ((pos (point))
13756 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
13757 (lim (progn
13758 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
13759 (point)))
13760 dd-on str (start 0) m re)
13761 (goto-char pos)
13762 (when dodollar
13763 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
13764 re (nth 1 (assoc "$" org-latex-regexps)))
13765 (while (string-match re str start)
13766 (cond
13767 ((= (match-end 0) (length str))
13768 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
13769 ((= (match-end 0) (- (length str) 5))
13770 (throw 'exit nil))
13771 (t (setq start (match-end 0))))))
13772 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
13773 (goto-char pos)
13774 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
13775 (and (match-beginning 2) (throw 'exit nil))
13776 ;; count $$
13777 (while (re-search-backward "\\$\\$" lim t)
13778 (setq dd-on (not dd-on)))
13779 (goto-char pos)
13780 (if dd-on (cons "$$" m))))))
13783 (defun org-try-cdlatex-tab ()
13784 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
13785 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
13786 - inside a LaTeX fragment, or
13787 - after the first word in a line, where an abbreviation expansion could
13788 insert a LaTeX environment."
13789 (when org-cdlatex-mode
13790 (cond
13791 ((save-excursion
13792 (skip-chars-backward "a-zA-Z0-9*")
13793 (skip-chars-backward " \t")
13794 (bolp))
13795 (cdlatex-tab) t)
13796 ((org-inside-LaTeX-fragment-p)
13797 (cdlatex-tab) t)
13798 (t nil))))
13800 (defun org-cdlatex-underscore-caret (&optional arg)
13801 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
13802 Revert to the normal definition outside of these fragments."
13803 (interactive "P")
13804 (if (org-inside-LaTeX-fragment-p)
13805 (call-interactively 'cdlatex-sub-superscript)
13806 (let (org-cdlatex-mode)
13807 (call-interactively (key-binding (vector last-input-event))))))
13809 (defun org-cdlatex-math-modify (&optional arg)
13810 "Execute `cdlatex-math-modify' in LaTeX fragments.
13811 Revert to the normal definition outside of these fragments."
13812 (interactive "P")
13813 (if (org-inside-LaTeX-fragment-p)
13814 (call-interactively 'cdlatex-math-modify)
13815 (let (org-cdlatex-mode)
13816 (call-interactively (key-binding (vector last-input-event))))))
13818 (defvar org-latex-fragment-image-overlays nil
13819 "List of overlays carrying the images of latex fragments.")
13820 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
13822 (defun org-remove-latex-fragment-image-overlays ()
13823 "Remove all overlays with LaTeX fragment images in current buffer."
13824 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
13825 (setq org-latex-fragment-image-overlays nil))
13827 (defun org-preview-latex-fragment (&optional subtree)
13828 "Preview the LaTeX fragment at point, or all locally or globally.
13829 If the cursor is in a LaTeX fragment, create the image and overlay
13830 it over the source code. If there is no fragment at point, display
13831 all fragments in the current text, from one headline to the next. With
13832 prefix SUBTREE, display all fragments in the current subtree. With a
13833 double prefix `C-u C-u', or when the cursor is before the first headline,
13834 display all fragments in the buffer.
13835 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
13836 (interactive "P")
13837 (org-remove-latex-fragment-image-overlays)
13838 (save-excursion
13839 (save-restriction
13840 (let (beg end at msg)
13841 (cond
13842 ((or (equal subtree '(16))
13843 (not (save-excursion
13844 (re-search-backward (concat "^" outline-regexp) nil t))))
13845 (setq beg (point-min) end (point-max)
13846 msg "Creating images for buffer...%s"))
13847 ((equal subtree '(4))
13848 (org-back-to-heading)
13849 (setq beg (point) end (org-end-of-subtree t)
13850 msg "Creating images for subtree...%s"))
13852 (if (setq at (org-inside-LaTeX-fragment-p))
13853 (goto-char (max (point-min) (- (cdr at) 2)))
13854 (org-back-to-heading))
13855 (setq beg (point) end (progn (outline-next-heading) (point))
13856 msg (if at "Creating image...%s"
13857 "Creating images for entry...%s"))))
13858 (message msg "")
13859 (narrow-to-region beg end)
13860 (goto-char beg)
13861 (org-format-latex
13862 (concat "ltxpng/" (file-name-sans-extension
13863 (file-name-nondirectory
13864 buffer-file-name)))
13865 default-directory 'overlays msg at 'forbuffer)
13866 (message msg "done. Use `C-c C-c' to remove images.")))))
13868 (defvar org-latex-regexps
13869 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
13870 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
13871 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
13872 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13873 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13874 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
13875 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
13876 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
13877 "Regular expressions for matching embedded LaTeX.")
13879 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
13880 "Replace LaTeX fragments with links to an image, and produce images."
13881 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
13882 (let* ((prefixnodir (file-name-nondirectory prefix))
13883 (absprefix (expand-file-name prefix dir))
13884 (todir (file-name-directory absprefix))
13885 (opt org-format-latex-options)
13886 (matchers (plist-get opt :matchers))
13887 (re-list org-latex-regexps)
13888 (cnt 0) txt link beg end re e checkdir
13889 executables-checked
13890 m n block linkfile movefile ov)
13891 ;; Check if there are old images files with this prefix, and remove them
13892 (when (file-directory-p todir)
13893 (mapc 'delete-file
13894 (directory-files
13895 todir 'full
13896 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
13897 ;; Check the different regular expressions
13898 (while (setq e (pop re-list))
13899 (setq m (car e) re (nth 1 e) n (nth 2 e)
13900 block (if (nth 3 e) "\n\n" ""))
13901 (when (member m matchers)
13902 (goto-char (point-min))
13903 (while (re-search-forward re nil t)
13904 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
13905 (not (get-text-property (match-beginning n)
13906 'org-protected))
13907 (or (not overlays)
13908 (not (eq (get-char-property (match-beginning n)
13909 'org-overlay-type)
13910 'org-latex-overlay))))
13911 (setq txt (match-string n)
13912 beg (match-beginning n) end (match-end n)
13913 cnt (1+ cnt)
13914 linkfile (format "%s_%04d.png" prefix cnt)
13915 movefile (format "%s_%04d.png" absprefix cnt)
13916 link (concat block "[[file:" linkfile "]]" block))
13917 (if msg (message msg cnt))
13918 (goto-char beg)
13919 (unless checkdir ; make sure the directory exists
13920 (setq checkdir t)
13921 (or (file-directory-p todir) (make-directory todir)))
13923 (unless executables-checked
13924 (org-check-external-command
13925 "latex" "needed to convert LaTeX fragments to images")
13926 (org-check-external-command
13927 "dvipng" "needed to convert LaTeX fragments to images")
13928 (setq executables-checked t))
13930 (org-create-formula-image
13931 txt movefile opt forbuffer)
13932 (if overlays
13933 (progn
13934 (mapc (lambda (o)
13935 (if (eq (org-overlay-get o 'org-overlay-type)
13936 'org-latex-overlay)
13937 (org-delete-overlay o)))
13938 (org-overlays-in beg end))
13939 (setq ov (org-make-overlay beg end))
13940 (org-overlay-put ov 'org-overlay-type 'org-latex-overlay)
13941 (if (featurep 'xemacs)
13942 (progn
13943 (org-overlay-put ov 'invisible t)
13944 (org-overlay-put
13945 ov 'end-glyph
13946 (make-glyph (vector 'png :file movefile))))
13947 (org-overlay-put
13948 ov 'display
13949 (list 'image :type 'png :file movefile :ascent 'center)))
13950 (push ov org-latex-fragment-image-overlays)
13951 (goto-char end))
13952 (delete-region beg end)
13953 (insert link))))))))
13955 ;; This function borrows from Ganesh Swami's latex2png.el
13956 (defun org-create-formula-image (string tofile options buffer)
13957 (let* ((tmpdir (if (featurep 'xemacs)
13958 (temp-directory)
13959 temporary-file-directory))
13960 (texfilebase (make-temp-name
13961 (expand-file-name "orgtex" tmpdir)))
13962 (texfile (concat texfilebase ".tex"))
13963 (dvifile (concat texfilebase ".dvi"))
13964 (pngfile (concat texfilebase ".png"))
13965 (fnh (if (featurep 'xemacs)
13966 (font-height (get-face-font 'default))
13967 (face-attribute 'default :height nil)))
13968 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
13969 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
13970 (fg (or (plist-get options (if buffer :foreground :html-foreground))
13971 "Black"))
13972 (bg (or (plist-get options (if buffer :background :html-background))
13973 "Transparent")))
13974 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
13975 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
13976 (with-temp-file texfile
13977 (insert org-format-latex-header
13978 "\n\\begin{document}\n" string "\n\\end{document}\n"))
13979 (let ((dir default-directory))
13980 (condition-case nil
13981 (progn
13982 (cd tmpdir)
13983 (call-process "latex" nil nil nil texfile))
13984 (error nil))
13985 (cd dir))
13986 (if (not (file-exists-p dvifile))
13987 (progn (message "Failed to create dvi file from %s" texfile) nil)
13988 (condition-case nil
13989 (call-process "dvipng" nil nil nil
13990 "-fg" fg "-bg" bg
13991 "-D" dpi
13992 ;;"-x" scale "-y" scale
13993 "-T" "tight"
13994 "-o" pngfile
13995 dvifile)
13996 (error nil))
13997 (if (not (file-exists-p pngfile))
13998 (progn (message "Failed to create png file from %s" texfile) nil)
13999 ;; Use the requested file name and clean up
14000 (copy-file pngfile tofile 'replace)
14001 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
14002 (delete-file (concat texfilebase e)))
14003 pngfile))))
14005 (defun org-dvipng-color (attr)
14006 "Return an rgb color specification for dvipng."
14007 (apply 'format "rgb %s %s %s"
14008 (mapcar 'org-normalize-color
14009 (color-values (face-attribute 'default attr nil)))))
14011 (defun org-normalize-color (value)
14012 "Return string to be used as color value for an RGB component."
14013 (format "%g" (/ value 65535.0)))
14015 ;;;; Key bindings
14017 ;; Make `C-c C-x' a prefix key
14018 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
14020 ;; TAB key with modifiers
14021 (org-defkey org-mode-map "\C-i" 'org-cycle)
14022 (org-defkey org-mode-map [(tab)] 'org-cycle)
14023 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
14024 (org-defkey org-mode-map [(meta tab)] 'org-complete)
14025 (org-defkey org-mode-map "\M-\t" 'org-complete)
14026 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
14027 ;; The following line is necessary under Suse GNU/Linux
14028 (unless (featurep 'xemacs)
14029 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
14030 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
14031 (define-key org-mode-map [backtab] 'org-shifttab)
14033 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
14034 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
14035 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
14037 ;; Cursor keys with modifiers
14038 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
14039 (org-defkey org-mode-map [(meta right)] 'org-metaright)
14040 (org-defkey org-mode-map [(meta up)] 'org-metaup)
14041 (org-defkey org-mode-map [(meta down)] 'org-metadown)
14043 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
14044 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
14045 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
14046 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
14048 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
14049 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
14050 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
14051 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
14053 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
14054 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
14056 ;;; Extra keys for tty access.
14057 ;; We only set them when really needed because otherwise the
14058 ;; menus don't show the simple keys
14060 (when (or org-use-extra-keys
14061 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
14062 (not window-system))
14063 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
14064 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
14065 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
14066 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
14067 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
14068 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
14069 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
14070 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
14071 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
14072 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
14073 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
14074 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
14075 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
14076 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
14077 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
14078 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
14079 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
14080 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
14081 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
14082 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
14083 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
14084 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
14085 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
14086 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
14087 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
14088 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
14089 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
14090 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
14092 ;; All the other keys
14094 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
14095 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
14096 (if (boundp 'narrow-map)
14097 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
14098 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
14099 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
14100 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
14101 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
14102 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
14103 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
14104 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
14105 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
14106 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
14107 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
14108 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
14109 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
14110 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
14111 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
14112 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
14113 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
14114 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
14115 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
14116 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
14117 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
14118 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
14119 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
14120 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
14121 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
14122 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
14123 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
14124 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
14125 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
14126 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
14127 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
14128 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
14129 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
14130 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
14131 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
14132 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
14133 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
14134 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
14135 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
14136 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
14137 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
14138 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
14139 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
14140 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14141 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
14142 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
14143 (org-defkey org-mode-map "\C-c^" 'org-sort)
14144 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
14145 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
14146 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
14147 (org-defkey org-mode-map "\C-m" 'org-return)
14148 (org-defkey org-mode-map "\C-j" 'org-return-indent)
14149 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
14150 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
14151 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
14152 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
14153 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
14154 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
14155 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
14156 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
14157 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
14158 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
14159 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
14160 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
14161 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
14162 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
14163 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
14164 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
14165 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
14166 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
14168 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
14169 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
14170 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
14171 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
14173 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
14174 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
14175 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
14176 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
14177 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
14178 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
14179 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
14180 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
14181 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
14182 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
14183 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
14184 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
14185 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
14186 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
14188 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
14189 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
14190 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
14191 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
14193 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
14195 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
14197 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
14198 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
14200 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
14203 (when (featurep 'xemacs)
14204 (org-defkey org-mode-map 'button3 'popup-mode-menu))
14207 (defvar org-self-insert-command-undo-counter 0)
14209 (defvar org-table-auto-blank-field) ; defined in org-table.el
14210 (defun org-self-insert-command (N)
14211 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
14212 If the cursor is in a table looking at whitespace, the whitespace is
14213 overwritten, and the table is not marked as requiring realignment."
14214 (interactive "p")
14215 (if (and
14216 (org-table-p)
14217 (progn
14218 ;; check if we blank the field, and if that triggers align
14219 (and (featurep 'org-table) org-table-auto-blank-field
14220 (member last-command
14221 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
14222 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
14223 ;; got extra space, this field does not determine column width
14224 (let (org-table-may-need-update) (org-table-blank-field))
14225 ;; no extra space, this field may determine column width
14226 (org-table-blank-field)))
14228 (eq N 1)
14229 (looking-at "[^|\n]* |"))
14230 (let (org-table-may-need-update)
14231 (goto-char (1- (match-end 0)))
14232 (delete-backward-char 1)
14233 (goto-char (match-beginning 0))
14234 (self-insert-command N))
14235 (setq org-table-may-need-update t)
14236 (self-insert-command N)
14237 (org-fix-tags-on-the-fly)
14238 (if org-self-insert-cluster-for-undo
14239 (if (not (eq last-command 'org-self-insert-command))
14240 (setq org-self-insert-command-undo-counter 1)
14241 (if (>= org-self-insert-command-undo-counter 20)
14242 (setq org-self-insert-command-undo-counter 1)
14243 (and (> org-self-insert-command-undo-counter 0)
14244 buffer-undo-list
14245 (not (cadr buffer-undo-list)) ; remove nil entry
14246 (setcdr buffer-undo-list (cddr buffer-undo-list)))
14247 (setq org-self-insert-command-undo-counter
14248 (1+ org-self-insert-command-undo-counter)))))))
14250 (defun org-fix-tags-on-the-fly ()
14251 (when (and (equal (char-after (point-at-bol)) ?*)
14252 (org-on-heading-p))
14253 (org-align-tags-here org-tags-column)))
14255 (defun org-delete-backward-char (N)
14256 "Like `delete-backward-char', insert whitespace at field end in tables.
14257 When deleting backwards, in tables this function will insert whitespace in
14258 front of the next \"|\" separator, to keep the table aligned. The table will
14259 still be marked for re-alignment if the field did fill the entire column,
14260 because, in this case the deletion might narrow the column."
14261 (interactive "p")
14262 (if (and (org-table-p)
14263 (eq N 1)
14264 (string-match "|" (buffer-substring (point-at-bol) (point)))
14265 (looking-at ".*?|"))
14266 (let ((pos (point))
14267 (noalign (looking-at "[^|\n\r]* |"))
14268 (c org-table-may-need-update))
14269 (backward-delete-char N)
14270 (skip-chars-forward "^|")
14271 (insert " ")
14272 (goto-char (1- pos))
14273 ;; noalign: if there were two spaces at the end, this field
14274 ;; does not determine the width of the column.
14275 (if noalign (setq org-table-may-need-update c)))
14276 (backward-delete-char N)
14277 (org-fix-tags-on-the-fly)))
14279 (defun org-delete-char (N)
14280 "Like `delete-char', but insert whitespace at field end in tables.
14281 When deleting characters, in tables this function will insert whitespace in
14282 front of the next \"|\" separator, to keep the table aligned. The table will
14283 still be marked for re-alignment if the field did fill the entire column,
14284 because, in this case the deletion might narrow the column."
14285 (interactive "p")
14286 (if (and (org-table-p)
14287 (not (bolp))
14288 (not (= (char-after) ?|))
14289 (eq N 1))
14290 (if (looking-at ".*?|")
14291 (let ((pos (point))
14292 (noalign (looking-at "[^|\n\r]* |"))
14293 (c org-table-may-need-update))
14294 (replace-match (concat
14295 (substring (match-string 0) 1 -1)
14296 " |"))
14297 (goto-char pos)
14298 ;; noalign: if there were two spaces at the end, this field
14299 ;; does not determine the width of the column.
14300 (if noalign (setq org-table-may-need-update c)))
14301 (delete-char N))
14302 (delete-char N)
14303 (org-fix-tags-on-the-fly)))
14305 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
14306 (put 'org-self-insert-command 'delete-selection t)
14307 (put 'orgtbl-self-insert-command 'delete-selection t)
14308 (put 'org-delete-char 'delete-selection 'supersede)
14309 (put 'org-delete-backward-char 'delete-selection 'supersede)
14310 (put 'org-yank 'delete-selection 'yank)
14312 ;; Make `flyspell-mode' delay after some commands
14313 (put 'org-self-insert-command 'flyspell-delayed t)
14314 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
14315 (put 'org-delete-char 'flyspell-delayed t)
14316 (put 'org-delete-backward-char 'flyspell-delayed t)
14318 ;; Make pabbrev-mode expand after org-mode commands
14319 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
14320 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
14322 ;; How to do this: Measure non-white length of current string
14323 ;; If equal to column width, we should realign.
14325 (defun org-remap (map &rest commands)
14326 "In MAP, remap the functions given in COMMANDS.
14327 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
14328 (let (new old)
14329 (while commands
14330 (setq old (pop commands) new (pop commands))
14331 (if (fboundp 'command-remapping)
14332 (org-defkey map (vector 'remap old) new)
14333 (substitute-key-definition old new map global-map)))))
14335 (when (eq org-enable-table-editor 'optimized)
14336 ;; If the user wants maximum table support, we need to hijack
14337 ;; some standard editing functions
14338 (org-remap org-mode-map
14339 'self-insert-command 'org-self-insert-command
14340 'delete-char 'org-delete-char
14341 'delete-backward-char 'org-delete-backward-char)
14342 (org-defkey org-mode-map "|" 'org-force-self-insert))
14344 (defvar org-ctrl-c-ctrl-c-hook nil
14345 "Hook for functions attaching themselves to `C-c C-c'.
14346 This can be used to add additional functionality to the C-c C-c key which
14347 executes context-dependent commands.
14348 Each function will be called with no arguments. The function must check
14349 if the context is appropriate for it to act. If yes, it should do its
14350 thing and then return a non-nil value. If the context is wrong,
14351 just do nothing and return nil.")
14353 (defvar org-tab-first-hook nil
14354 "Hook for functions to attach themselves to TAB.
14355 See `org-ctrl-c-ctrl-c-hook' for more information.
14356 This hook runs as the first action when TAB is pressed, even before
14357 `org-cycle' messes around with the `outline-regexp' to cater for
14358 inline tasks and plain list item folding.
14359 If any function in this hook returns t, not other actions like table
14360 field motion visibility cycling will be done.")
14362 (defvar org-tab-after-check-for-table-hook nil
14363 "Hook for functions to attach themselves to TAB.
14364 See `org-ctrl-c-ctrl-c-hook' for more information.
14365 This hook runs after it has been established that the cursor is not in a
14366 table, but before checking if the cursor is in a headline or if global cycling
14367 should be done.
14368 If any function in this hook returns t, not other actions like visibility
14369 cycling will be done.")
14371 (defvar org-tab-after-check-for-cycling-hook nil
14372 "Hook for functions to attach themselves to TAB.
14373 See `org-ctrl-c-ctrl-c-hook' for more information.
14374 This hook runs after it has been established that not table field motion and
14375 not visibility should be done because of current context. This is probably
14376 the place where a package like yasnippets can hook in.")
14378 (defvar org-metaleft-hook nil
14379 "Hook for functions attaching themselves to `M-left'.
14380 See `org-ctrl-c-ctrl-c-hook' for more information.")
14381 (defvar org-metaright-hook nil
14382 "Hook for functions attaching themselves to `M-right'.
14383 See `org-ctrl-c-ctrl-c-hook' for more information.")
14384 (defvar org-metaup-hook nil
14385 "Hook for functions attaching themselves to `M-up'.
14386 See `org-ctrl-c-ctrl-c-hook' for more information.")
14387 (defvar org-metadown-hook nil
14388 "Hook for functions attaching themselves to `M-down'.
14389 See `org-ctrl-c-ctrl-c-hook' for more information.")
14390 (defvar org-shiftmetaleft-hook nil
14391 "Hook for functions attaching themselves to `M-S-left'.
14392 See `org-ctrl-c-ctrl-c-hook' for more information.")
14393 (defvar org-shiftmetaright-hook nil
14394 "Hook for functions attaching themselves to `M-S-right'.
14395 See `org-ctrl-c-ctrl-c-hook' for more information.")
14396 (defvar org-shiftmetaup-hook nil
14397 "Hook for functions attaching themselves to `M-S-up'.
14398 See `org-ctrl-c-ctrl-c-hook' for more information.")
14399 (defvar org-shiftmetadown-hook nil
14400 "Hook for functions attaching themselves to `M-S-down'.
14401 See `org-ctrl-c-ctrl-c-hook' for more information.")
14402 (defvar org-metareturn-hook nil
14403 "Hook for functions attaching themselves to `M-RET'.
14404 See `org-ctrl-c-ctrl-c-hook' for more information.")
14406 (defun org-modifier-cursor-error ()
14407 "Throw an error, a modified cursor command was applied in wrong context."
14408 (error "This command is active in special context like tables, headlines or items"))
14410 (defun org-shiftselect-error ()
14411 "Throw an error because Shift-Cursor command was applied in wrong context."
14412 (if (and (boundp 'shift-select-mode) shift-select-mode)
14413 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
14414 (error "This command works only in special context like headlines or timestamps.")))
14416 (defun org-call-for-shift-select (cmd)
14417 (let ((this-command-keys-shift-translated t))
14418 (call-interactively cmd)))
14420 (defun org-shifttab (&optional arg)
14421 "Global visibility cycling or move to previous table field.
14422 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
14423 on context.
14424 See the individual commands for more information."
14425 (interactive "P")
14426 (cond
14427 ((org-at-table-p) (call-interactively 'org-table-previous-field))
14428 ((integerp arg)
14429 (message "Content view to level: %d" arg)
14430 (org-content (prefix-numeric-value arg))
14431 (setq org-cycle-global-status 'overview))
14432 (t (call-interactively 'org-global-cycle))))
14434 (defun org-shiftmetaleft ()
14435 "Promote subtree or delete table column.
14436 Calls `org-promote-subtree', `org-outdent-item',
14437 or `org-table-delete-column', depending on context.
14438 See the individual commands for more information."
14439 (interactive)
14440 (cond
14441 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
14442 ((org-at-table-p) (call-interactively 'org-table-delete-column))
14443 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
14444 ((org-at-item-p) (call-interactively 'org-outdent-item))
14445 (t (org-modifier-cursor-error))))
14447 (defun org-shiftmetaright ()
14448 "Demote subtree or insert table column.
14449 Calls `org-demote-subtree', `org-indent-item',
14450 or `org-table-insert-column', depending on context.
14451 See the individual commands for more information."
14452 (interactive)
14453 (cond
14454 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
14455 ((org-at-table-p) (call-interactively 'org-table-insert-column))
14456 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
14457 ((org-at-item-p) (call-interactively 'org-indent-item))
14458 (t (org-modifier-cursor-error))))
14460 (defun org-shiftmetaup (&optional arg)
14461 "Move subtree up or kill table row.
14462 Calls `org-move-subtree-up' or `org-table-kill-row' or
14463 `org-move-item-up' depending on context. See the individual commands
14464 for more information."
14465 (interactive "P")
14466 (cond
14467 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
14468 ((org-at-table-p) (call-interactively 'org-table-kill-row))
14469 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14470 ((org-at-item-p) (call-interactively 'org-move-item-up))
14471 (t (org-modifier-cursor-error))))
14473 (defun org-shiftmetadown (&optional arg)
14474 "Move subtree down or insert table row.
14475 Calls `org-move-subtree-down' or `org-table-insert-row' or
14476 `org-move-item-down', depending on context. See the individual
14477 commands for more information."
14478 (interactive "P")
14479 (cond
14480 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
14481 ((org-at-table-p) (call-interactively 'org-table-insert-row))
14482 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14483 ((org-at-item-p) (call-interactively 'org-move-item-down))
14484 (t (org-modifier-cursor-error))))
14486 (defun org-metaleft (&optional arg)
14487 "Promote heading or move table column to left.
14488 Calls `org-do-promote' or `org-table-move-column', depending on context.
14489 With no specific context, calls the Emacs default `backward-word'.
14490 See the individual commands for more information."
14491 (interactive "P")
14492 (cond
14493 ((run-hook-with-args-until-success 'org-metaleft-hook))
14494 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
14495 ((or (org-on-heading-p)
14496 (and (org-region-active-p)
14497 (save-excursion
14498 (goto-char (region-beginning))
14499 (org-on-heading-p))))
14500 (call-interactively 'org-do-promote))
14501 ((or (org-at-item-p)
14502 (and (org-region-active-p)
14503 (save-excursion
14504 (goto-char (region-beginning))
14505 (org-at-item-p))))
14506 (call-interactively 'org-outdent-item))
14507 (t (call-interactively 'backward-word))))
14509 (defun org-metaright (&optional arg)
14510 "Demote subtree or move table column to right.
14511 Calls `org-do-demote' or `org-table-move-column', depending on context.
14512 With no specific context, calls the Emacs default `forward-word'.
14513 See the individual commands for more information."
14514 (interactive "P")
14515 (cond
14516 ((run-hook-with-args-until-success 'org-metaright-hook))
14517 ((org-at-table-p) (call-interactively 'org-table-move-column))
14518 ((or (org-on-heading-p)
14519 (and (org-region-active-p)
14520 (save-excursion
14521 (goto-char (region-beginning))
14522 (org-on-heading-p))))
14523 (call-interactively 'org-do-demote))
14524 ((or (org-at-item-p)
14525 (and (org-region-active-p)
14526 (save-excursion
14527 (goto-char (region-beginning))
14528 (org-at-item-p))))
14529 (call-interactively 'org-indent-item))
14530 (t (call-interactively 'forward-word))))
14532 (defun org-metaup (&optional arg)
14533 "Move subtree up or move table row up.
14534 Calls `org-move-subtree-up' or `org-table-move-row' or
14535 `org-move-item-up', depending on context. See the individual commands
14536 for more information."
14537 (interactive "P")
14538 (cond
14539 ((run-hook-with-args-until-success 'org-metaup-hook))
14540 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
14541 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14542 ((org-at-item-p) (call-interactively 'org-move-item-up))
14543 (t (transpose-lines 1) (beginning-of-line -1))))
14545 (defun org-metadown (&optional arg)
14546 "Move subtree down or move table row down.
14547 Calls `org-move-subtree-down' or `org-table-move-row' or
14548 `org-move-item-down', depending on context. See the individual
14549 commands for more information."
14550 (interactive "P")
14551 (cond
14552 ((run-hook-with-args-until-success 'org-metadown-hook))
14553 ((org-at-table-p) (call-interactively 'org-table-move-row))
14554 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14555 ((org-at-item-p) (call-interactively 'org-move-item-down))
14556 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
14558 (defun org-shiftup (&optional arg)
14559 "Increase item in timestamp or increase priority of current headline.
14560 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
14561 depending on context. See the individual commands for more information."
14562 (interactive "P")
14563 (cond
14564 ((and org-support-shift-select (org-region-active-p))
14565 (org-call-for-shift-select 'previous-line))
14566 ((org-at-timestamp-p t)
14567 (call-interactively (if org-edit-timestamp-down-means-later
14568 'org-timestamp-down 'org-timestamp-up)))
14569 ((and (not (eq org-support-shift-select 'always))
14570 org-enable-priority-commands
14571 (org-on-heading-p))
14572 (call-interactively 'org-priority-up))
14573 ((and (not org-support-shift-select) (org-at-item-p))
14574 (call-interactively 'org-previous-item))
14575 ((org-clocktable-try-shift 'up arg))
14576 (org-support-shift-select
14577 (org-call-for-shift-select 'previous-line))
14578 (t (org-shiftselect-error))))
14580 (defun org-shiftdown (&optional arg)
14581 "Decrease item in timestamp or decrease priority of current headline.
14582 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
14583 depending on context. See the individual commands for more information."
14584 (interactive "P")
14585 (cond
14586 ((and org-support-shift-select (org-region-active-p))
14587 (org-call-for-shift-select 'next-line))
14588 ((org-at-timestamp-p t)
14589 (call-interactively (if org-edit-timestamp-down-means-later
14590 'org-timestamp-up 'org-timestamp-down)))
14591 ((and (not (eq org-support-shift-select 'always))
14592 org-enable-priority-commands
14593 (org-on-heading-p))
14594 (call-interactively 'org-priority-down))
14595 ((and (not org-support-shift-select) (org-at-item-p))
14596 (call-interactively 'org-next-item))
14597 ((org-clocktable-try-shift 'down arg))
14598 (org-support-shift-select
14599 (org-call-for-shift-select 'next-line))
14600 (t (org-shiftselect-error))))
14602 (defun org-shiftright (&optional arg)
14603 "Cycle the thing at point or in the current line, depending on context.
14604 Depending on context, this does one of the following:
14606 - switch a timestamp at point one day into the future
14607 - on a headline, switch to the next TODO keyword.
14608 - on an item, switch entire list to the next bullet type
14609 - on a property line, switch to the next allowed value
14610 - on a clocktable definition line, move time block into the future"
14611 (interactive "P")
14612 (cond
14613 ((and org-support-shift-select (org-region-active-p))
14614 (org-call-for-shift-select 'forward-char))
14615 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
14616 ((and (not (eq org-support-shift-select 'always))
14617 (org-on-heading-p))
14618 (let ((org-inhibit-logging
14619 (not org-treat-S-cursor-todo-selection-as-state-change))
14620 (org-inhibit-blocking
14621 (not org-treat-S-cursor-todo-selection-as-state-change)))
14622 (org-call-with-arg 'org-todo 'right)))
14623 ((or (and org-support-shift-select
14624 (not (eq org-support-shift-select 'always))
14625 (org-at-item-bullet-p))
14626 (and (not org-support-shift-select) (org-at-item-p)))
14627 (org-call-with-arg 'org-cycle-list-bullet nil))
14628 ((and (not (eq org-support-shift-select 'always))
14629 (org-at-property-p))
14630 (call-interactively 'org-property-next-allowed-value))
14631 ((org-clocktable-try-shift 'right arg))
14632 (org-support-shift-select
14633 (org-call-for-shift-select 'forward-char))
14634 (t (org-shiftselect-error))))
14636 (defun org-shiftleft (&optional arg)
14637 "Cycle the thing at point or in the current line, depending on context.
14638 Depending on context, this does one of the following:
14640 - switch a timestamp at point one day into the past
14641 - on a headline, switch to the previous TODO keyword.
14642 - on an item, switch entire list to the previous bullet type
14643 - on a property line, switch to the previous allowed value
14644 - on a clocktable definition line, move time block into the past"
14645 (interactive "P")
14646 (cond
14647 ((and org-support-shift-select (org-region-active-p))
14648 (org-call-for-shift-select 'backward-char))
14649 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
14650 ((and (not (eq org-support-shift-select 'always))
14651 (org-on-heading-p))
14652 (let ((org-inhibit-logging
14653 (not org-treat-S-cursor-todo-selection-as-state-change))
14654 (org-inhibit-blocking
14655 (not org-treat-S-cursor-todo-selection-as-state-change)))
14656 (org-call-with-arg 'org-todo 'left)))
14657 ((or (and org-support-shift-select
14658 (not (eq org-support-shift-select 'always))
14659 (org-at-item-bullet-p))
14660 (and (not org-support-shift-select) (org-at-item-p)))
14661 (org-call-with-arg 'org-cycle-list-bullet 'previous))
14662 ((and (not (eq org-support-shift-select 'always))
14663 (org-at-property-p))
14664 (call-interactively 'org-property-previous-allowed-value))
14665 ((org-clocktable-try-shift 'left arg))
14666 (org-support-shift-select
14667 (org-call-for-shift-select 'backward-char))
14668 (t (org-shiftselect-error))))
14670 (defun org-shiftcontrolright ()
14671 "Switch to next TODO set."
14672 (interactive)
14673 (cond
14674 ((and org-support-shift-select (org-region-active-p))
14675 (org-call-for-shift-select 'forward-word))
14676 ((and (not (eq org-support-shift-select 'always))
14677 (org-on-heading-p))
14678 (org-call-with-arg 'org-todo 'nextset))
14679 (org-support-shift-select
14680 (org-call-for-shift-select 'forward-word))
14681 (t (org-shiftselect-error))))
14683 (defun org-shiftcontrolleft ()
14684 "Switch to previous TODO set."
14685 (interactive)
14686 (cond
14687 ((and org-support-shift-select (org-region-active-p))
14688 (org-call-for-shift-select 'backward-word))
14689 ((and (not (eq org-support-shift-select 'always))
14690 (org-on-heading-p))
14691 (org-call-with-arg 'org-todo 'previousset))
14692 (org-support-shift-select
14693 (org-call-for-shift-select 'backward-word))
14694 (t (org-shiftselect-error))))
14696 (defun org-ctrl-c-ret ()
14697 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
14698 (interactive)
14699 (cond
14700 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
14701 (t (call-interactively 'org-insert-heading))))
14703 (defun org-copy-special ()
14704 "Copy region in table or copy current subtree.
14705 Calls `org-table-copy' or `org-copy-subtree', depending on context.
14706 See the individual commands for more information."
14707 (interactive)
14708 (call-interactively
14709 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
14711 (defun org-cut-special ()
14712 "Cut region in table or cut current subtree.
14713 Calls `org-table-copy' or `org-cut-subtree', depending on context.
14714 See the individual commands for more information."
14715 (interactive)
14716 (call-interactively
14717 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
14719 (defun org-paste-special (arg)
14720 "Paste rectangular region into table, or past subtree relative to level.
14721 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
14722 See the individual commands for more information."
14723 (interactive "P")
14724 (if (org-at-table-p)
14725 (org-table-paste-rectangle)
14726 (org-paste-subtree arg)))
14728 (defun org-edit-special ()
14729 "Call a special editor for the stuff at point.
14730 When at a table, call the formula editor with `org-table-edit-formulas'.
14731 When at the first line of an src example, call `org-edit-src-code'.
14732 When in an #+include line, visit the include file. Otherwise call
14733 `ffap' to visit the file at point."
14734 (interactive)
14735 (cond
14736 ((org-at-table-p)
14737 (call-interactively 'org-table-edit-formulas))
14738 ((save-excursion
14739 (beginning-of-line 1)
14740 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
14741 (find-file (org-trim (match-string 1))))
14742 ((org-edit-src-code))
14743 ((org-edit-fixed-width-region))
14744 (t (call-interactively 'ffap))))
14747 (defun org-ctrl-c-ctrl-c (&optional arg)
14748 "Set tags in headline, or update according to changed information at point.
14750 This command does many different things, depending on context:
14752 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
14753 this is what we do.
14755 - If the cursor is in a headline, prompt for tags and insert them
14756 into the current line, aligned to `org-tags-column'. When called
14757 with prefix arg, realign all tags in the current buffer.
14759 - If the cursor is in one of the special #+KEYWORD lines, this
14760 triggers scanning the buffer for these lines and updating the
14761 information.
14763 - If the cursor is inside a table, realign the table. This command
14764 works even if the automatic table editor has been turned off.
14766 - If the cursor is on a #+TBLFM line, re-apply the formulas to
14767 the entire table.
14769 - If the cursor is at a footnote reference or definition, jump to
14770 the corresponding definition or references, respectively.
14772 - If the cursor is a the beginning of a dynamic block, update it.
14774 - If the cursor is inside a table created by the table.el package,
14775 activate that table.
14777 - If the current buffer is a remember buffer, close note and file
14778 it. A prefix argument of 1 files to the default location
14779 without further interaction. A prefix argument of 2 files to
14780 the currently clocking task.
14782 - If the cursor is on a <<<target>>>, update radio targets and corresponding
14783 links in this buffer.
14785 - If the cursor is on a numbered item in a plain list, renumber the
14786 ordered list.
14788 - If the cursor is on a checkbox, toggle it."
14789 (interactive "P")
14790 (let ((org-enable-table-editor t))
14791 (cond
14792 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
14793 org-occur-highlights
14794 org-latex-fragment-image-overlays)
14795 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
14796 (org-remove-occur-highlights)
14797 (org-remove-latex-fragment-image-overlays)
14798 (message "Temporary highlights/overlays removed from current buffer"))
14799 ((and (local-variable-p 'org-finish-function (current-buffer))
14800 (fboundp org-finish-function))
14801 (funcall org-finish-function))
14802 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
14803 ((org-at-property-p)
14804 (call-interactively 'org-property-action))
14805 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
14806 ((org-on-heading-p) (call-interactively 'org-set-tags))
14807 ((org-at-table.el-p)
14808 (require 'table)
14809 (beginning-of-line 1)
14810 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
14811 (call-interactively 'table-recognize-table))
14812 ((org-at-table-p)
14813 (org-table-maybe-eval-formula)
14814 (if arg
14815 (call-interactively 'org-table-recalculate)
14816 (org-table-maybe-recalculate-line))
14817 (call-interactively 'org-table-align))
14818 ((or (org-footnote-at-reference-p)
14819 (org-footnote-at-definition-p))
14820 (call-interactively 'org-footnote-action))
14821 ((org-at-item-checkbox-p)
14822 (call-interactively 'org-toggle-checkbox))
14823 ((org-at-item-p)
14824 (if arg
14825 (call-interactively 'org-toggle-checkbox)
14826 (call-interactively 'org-maybe-renumber-ordered-list)))
14827 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
14828 ;; Dynamic block
14829 (beginning-of-line 1)
14830 (save-excursion (org-update-dblock)))
14831 ((save-excursion
14832 (beginning-of-line 1)
14833 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
14834 (cond
14835 ((equal (match-string 1) "TBLFM")
14836 ;; Recalculate the table before this line
14837 (save-excursion
14838 (beginning-of-line 1)
14839 (skip-chars-backward " \r\n\t")
14840 (if (org-at-table-p)
14841 (org-call-with-arg 'org-table-recalculate t))))
14843 ; (org-set-regexps-and-options)
14844 ; (org-restart-font-lock)
14845 (let ((org-inhibit-startup t)) (org-mode-restart))
14846 (message "Local setup has been refreshed"))))
14847 ((org-clock-update-time-maybe))
14848 (t (error "C-c C-c can do nothing useful at this location.")))))
14850 (defun org-mode-restart ()
14851 "Restart Org-mode, to scan again for special lines.
14852 Also updates the keyword regular expressions."
14853 (interactive)
14854 (org-mode)
14855 (message "Org-mode restarted"))
14857 (defun org-kill-note-or-show-branches ()
14858 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
14859 (interactive)
14860 (if (not org-finish-function)
14861 (call-interactively 'show-branches)
14862 (let ((org-note-abort t))
14863 (funcall org-finish-function))))
14865 (defun org-return (&optional indent)
14866 "Goto next table row or insert a newline.
14867 Calls `org-table-next-row' or `newline', depending on context.
14868 See the individual commands for more information."
14869 (interactive)
14870 (cond
14871 ((bobp) (if indent (newline-and-indent) (newline)))
14872 ((org-at-table-p)
14873 (org-table-justify-field-maybe)
14874 (call-interactively 'org-table-next-row))
14875 ((and org-return-follows-link
14876 (eq (get-text-property (point) 'face) 'org-link))
14877 (call-interactively 'org-open-at-point))
14878 ((and (org-at-heading-p)
14879 (looking-at
14880 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
14881 (org-show-entry)
14882 (end-of-line 1)
14883 (newline))
14884 (t (if indent (newline-and-indent) (newline)))))
14886 (defun org-return-indent ()
14887 "Goto next table row or insert a newline and indent.
14888 Calls `org-table-next-row' or `newline-and-indent', depending on
14889 context. See the individual commands for more information."
14890 (interactive)
14891 (org-return t))
14893 (defun org-ctrl-c-star ()
14894 "Compute table, or change heading status of lines.
14895 Calls `org-table-recalculate' or `org-toggle-heading',
14896 depending on context."
14897 (interactive)
14898 (cond
14899 ((org-at-table-p)
14900 (call-interactively 'org-table-recalculate))
14902 ;; Convert all lines in region to list items
14903 (call-interactively 'org-toggle-heading))))
14905 (defun org-ctrl-c-minus ()
14906 "Insert separator line in table or modify bullet status of line.
14907 Also turns a plain line or a region of lines into list items.
14908 Calls `org-table-insert-hline', `org-toggle-item', or
14909 `org-cycle-list-bullet', depending on context."
14910 (interactive)
14911 (cond
14912 ((org-at-table-p)
14913 (call-interactively 'org-table-insert-hline))
14914 ((org-region-active-p)
14915 (call-interactively 'org-toggle-item))
14916 ((org-in-item-p)
14917 (call-interactively 'org-cycle-list-bullet))
14919 (call-interactively 'org-toggle-item))))
14921 (defun org-toggle-item ()
14922 "Convert headings or normal lines to items, items to normal lines.
14923 If there is no active region, only the current line is considered.
14925 If the first line in the region is a headline, convert all headlines to items.
14927 If the first line in the region is an item, convert all items to normal lines.
14929 If the first line is normal text, add an item bullet to each line."
14930 (interactive)
14931 (let (l2 l beg end)
14932 (if (org-region-active-p)
14933 (setq beg (region-beginning) end (region-end))
14934 (setq beg (point-at-bol)
14935 end (min (1+ (point-at-eol)) (point-max))))
14936 (save-excursion
14937 (goto-char end)
14938 (setq l2 (org-current-line))
14939 (goto-char beg)
14940 (beginning-of-line 1)
14941 (setq l (1- (org-current-line)))
14942 (if (org-at-item-p)
14943 ;; We already have items, de-itemize
14944 (while (< (setq l (1+ l)) l2)
14945 (when (org-at-item-p)
14946 (goto-char (match-beginning 2))
14947 (delete-region (match-beginning 2) (match-end 2))
14948 (and (looking-at "[ \t]+") (replace-match "")))
14949 (beginning-of-line 2))
14950 (if (org-on-heading-p)
14951 ;; Headings, convert to items
14952 (while (< (setq l (1+ l)) l2)
14953 (if (looking-at org-outline-regexp)
14954 (replace-match "- " t t))
14955 (beginning-of-line 2))
14956 ;; normal lines, turn them into items
14957 (while (< (setq l (1+ l)) l2)
14958 (unless (org-at-item-p)
14959 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14960 (replace-match "\\1- \\2")))
14961 (beginning-of-line 2)))))))
14963 (defun org-toggle-heading (&optional nstars)
14964 "Convert headings to normal text, or items or text to headings.
14965 If there is no active region, only the current line is considered.
14967 If the first line is a heading, remove the stars from all headlines
14968 in the region.
14970 If the first line is a plain list item, turn all plain list items
14971 into headings.
14973 If the first line is a normal line, turn each and every line in the
14974 region into a heading.
14976 When converting a line into a heading, the number of stars is chosen
14977 such that the lines become children of the current entry. However,
14978 when a prefix argument is given, its value determines the number of
14979 stars to add."
14980 (interactive "P")
14981 (let (l2 l itemp beg end)
14982 (if (org-region-active-p)
14983 (setq beg (region-beginning) end (region-end))
14984 (setq beg (point-at-bol)
14985 end (min (1+ (point-at-eol)) (point-max))))
14986 (save-excursion
14987 (goto-char end)
14988 (setq l2 (org-current-line))
14989 (goto-char beg)
14990 (beginning-of-line 1)
14991 (setq l (1- (org-current-line)))
14992 (if (org-on-heading-p)
14993 ;; We already have headlines, de-star them
14994 (while (< (setq l (1+ l)) l2)
14995 (when (org-on-heading-p t)
14996 (and (looking-at outline-regexp) (replace-match "")))
14997 (beginning-of-line 2))
14998 (setq itemp (org-at-item-p))
14999 (let* ((stars
15000 (if nstars
15001 (make-string (prefix-numeric-value current-prefix-arg)
15003 (save-excursion
15004 (if (re-search-backward org-complex-heading-regexp nil t)
15005 (match-string 1) ""))))
15006 (add-stars (cond (nstars "")
15007 ((equal stars "") "*")
15008 (org-odd-levels-only "**")
15009 (t "*")))
15010 (rpl (concat stars add-stars " ")))
15011 (while (< (setq l (1+ l)) l2)
15012 (if itemp
15013 (and (org-at-item-p) (replace-match rpl t t))
15014 (unless (org-on-heading-p)
15015 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15016 (replace-match (concat rpl (match-string 2))))))
15017 (beginning-of-line 2)))))))
15019 (defun org-meta-return (&optional arg)
15020 "Insert a new heading or wrap a region in a table.
15021 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
15022 See the individual commands for more information."
15023 (interactive "P")
15024 (cond
15025 ((run-hook-with-args-until-success 'org-metareturn-hook))
15026 ((org-at-table-p)
15027 (call-interactively 'org-table-wrap-region))
15028 (t (call-interactively 'org-insert-heading))))
15030 ;;; Menu entries
15032 ;; Define the Org-mode menus
15033 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
15034 '("Tbl"
15035 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
15036 ["Next Field" org-cycle (org-at-table-p)]
15037 ["Previous Field" org-shifttab (org-at-table-p)]
15038 ["Next Row" org-return (org-at-table-p)]
15039 "--"
15040 ["Blank Field" org-table-blank-field (org-at-table-p)]
15041 ["Edit Field" org-table-edit-field (org-at-table-p)]
15042 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
15043 "--"
15044 ("Column"
15045 ["Move Column Left" org-metaleft (org-at-table-p)]
15046 ["Move Column Right" org-metaright (org-at-table-p)]
15047 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
15048 ["Insert Column" org-shiftmetaright (org-at-table-p)])
15049 ("Row"
15050 ["Move Row Up" org-metaup (org-at-table-p)]
15051 ["Move Row Down" org-metadown (org-at-table-p)]
15052 ["Delete Row" org-shiftmetaup (org-at-table-p)]
15053 ["Insert Row" org-shiftmetadown (org-at-table-p)]
15054 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
15055 "--"
15056 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
15057 ("Rectangle"
15058 ["Copy Rectangle" org-copy-special (org-at-table-p)]
15059 ["Cut Rectangle" org-cut-special (org-at-table-p)]
15060 ["Paste Rectangle" org-paste-special (org-at-table-p)]
15061 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
15062 "--"
15063 ("Calculate"
15064 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
15065 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
15066 ["Edit Formulas" org-edit-special (org-at-table-p)]
15067 "--"
15068 ["Recalculate line" org-table-recalculate (org-at-table-p)]
15069 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
15070 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
15071 "--"
15072 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
15073 "--"
15074 ["Sum Column/Rectangle" org-table-sum
15075 (or (org-at-table-p) (org-region-active-p))]
15076 ["Which Column?" org-table-current-column (org-at-table-p)])
15077 ["Debug Formulas"
15078 org-table-toggle-formula-debugger
15079 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
15080 ["Show Col/Row Numbers"
15081 org-table-toggle-coordinate-overlays
15082 :style toggle
15083 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
15084 "--"
15085 ["Create" org-table-create (and (not (org-at-table-p))
15086 org-enable-table-editor)]
15087 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
15088 ["Import from File" org-table-import (not (org-at-table-p))]
15089 ["Export to File" org-table-export (org-at-table-p)]
15090 "--"
15091 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
15093 (easy-menu-define org-org-menu org-mode-map "Org menu"
15094 '("Org"
15095 ("Show/Hide"
15096 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
15097 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
15098 ["Sparse Tree..." org-sparse-tree t]
15099 ["Reveal Context" org-reveal t]
15100 ["Show All" show-all t]
15101 "--"
15102 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
15103 "--"
15104 ["New Heading" org-insert-heading t]
15105 ("Navigate Headings"
15106 ["Up" outline-up-heading t]
15107 ["Next" outline-next-visible-heading t]
15108 ["Previous" outline-previous-visible-heading t]
15109 ["Next Same Level" outline-forward-same-level t]
15110 ["Previous Same Level" outline-backward-same-level t]
15111 "--"
15112 ["Jump" org-goto t])
15113 ("Edit Structure"
15114 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
15115 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
15116 "--"
15117 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
15118 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
15119 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
15120 "--"
15121 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
15122 "--"
15123 ["Promote Heading" org-metaleft (not (org-at-table-p))]
15124 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
15125 ["Demote Heading" org-metaright (not (org-at-table-p))]
15126 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
15127 "--"
15128 ["Sort Region/Children" org-sort (not (org-at-table-p))]
15129 "--"
15130 ["Convert to odd levels" org-convert-to-odd-levels t]
15131 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
15132 ("Editing"
15133 ["Emphasis..." org-emphasize t]
15134 ["Edit Source Example" org-edit-special t]
15135 "--"
15136 ["Footnote new/jump" org-footnote-action t]
15137 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
15138 ("Archive"
15139 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
15140 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
15141 ; :active t :keys "C-u C-c C-x C-a"]
15142 ["Sparse trees open ARCHIVE trees"
15143 (setq org-sparse-tree-open-archived-trees
15144 (not org-sparse-tree-open-archived-trees))
15145 :style toggle :selected org-sparse-tree-open-archived-trees]
15146 ["Cycling opens ARCHIVE trees"
15147 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
15148 :style toggle :selected org-cycle-open-archived-trees]
15149 "--"
15150 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
15151 ["Move Subtree to Archive" org-advertized-archive-subtree t]
15152 ; ["Check and Move Children" (org-archive-subtree '(4))
15153 ; :active t :keys "C-u C-c C-x C-s"]
15155 "--"
15156 ("Hyperlinks"
15157 ["Store Link (Global)" org-store-link t]
15158 ["Find existing link to here" org-occur-link-in-agenda-files t]
15159 ["Insert Link" org-insert-link t]
15160 ["Follow Link" org-open-at-point t]
15161 "--"
15162 ["Next link" org-next-link t]
15163 ["Previous link" org-previous-link t]
15164 "--"
15165 ["Descriptive Links"
15166 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
15167 :style radio
15168 :selected (member '(org-link) buffer-invisibility-spec)]
15169 ["Literal Links"
15170 (progn
15171 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
15172 :style radio
15173 :selected (not (member '(org-link) buffer-invisibility-spec))])
15174 "--"
15175 ("TODO Lists"
15176 ["TODO/DONE/-" org-todo t]
15177 ("Select keyword"
15178 ["Next keyword" org-shiftright (org-on-heading-p)]
15179 ["Previous keyword" org-shiftleft (org-on-heading-p)]
15180 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
15181 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
15182 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
15183 ["Show TODO Tree" org-show-todo-tree t]
15184 ["Global TODO list" org-todo-list t]
15185 "--"
15186 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
15187 :selected org-enforce-todo-dependencies :style toggle :active t]
15188 "Settings for tree at point"
15189 ["Do Children sequentially" org-toggle-ordered-property :style radio
15190 :selected (ignore-errors (org-entry-get nil "ORDERED"))
15191 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15192 ["Do Children parallel" org-toggle-ordered-property :style radio
15193 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
15194 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15195 "--"
15196 ["Set Priority" org-priority t]
15197 ["Priority Up" org-shiftup t]
15198 ["Priority Down" org-shiftdown t]
15199 "--"
15200 ["Get news from all feeds" org-feed-update-all t]
15201 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
15202 ["Customize feeds" (customize-variable 'org-feed-alist) t])
15203 ("TAGS and Properties"
15204 ["Set Tags" org-set-tags-command t]
15205 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
15206 "--"
15207 ["Set property" org-set-property t]
15208 ["Column view of properties" org-columns t]
15209 ["Insert Column View DBlock" org-insert-columns-dblock t])
15210 ("Dates and Scheduling"
15211 ["Timestamp" org-time-stamp t]
15212 ["Timestamp (inactive)" org-time-stamp-inactive t]
15213 ("Change Date"
15214 ["1 Day Later" org-shiftright t]
15215 ["1 Day Earlier" org-shiftleft t]
15216 ["1 ... Later" org-shiftup t]
15217 ["1 ... Earlier" org-shiftdown t])
15218 ["Compute Time Range" org-evaluate-time-range t]
15219 ["Schedule Item" org-schedule t]
15220 ["Deadline" org-deadline t]
15221 "--"
15222 ["Custom time format" org-toggle-time-stamp-overlays
15223 :style radio :selected org-display-custom-times]
15224 "--"
15225 ["Goto Calendar" org-goto-calendar t]
15226 ["Date from Calendar" org-date-from-calendar t]
15227 "--"
15228 ["Start/Restart Timer" org-timer-start t]
15229 ["Pause/Continue Timer" org-timer-pause-or-continue t]
15230 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
15231 ["Insert Timer String" org-timer t]
15232 ["Insert Timer Item" org-timer-item t])
15233 ("Logging work"
15234 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
15235 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
15236 ["Clock out" org-clock-out t]
15237 ["Clock cancel" org-clock-cancel t]
15238 "--"
15239 ["Mark as default task" org-clock-mark-default-task t]
15240 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
15241 ["Goto running clock" org-clock-goto t]
15242 "--"
15243 ["Display times" org-clock-display t]
15244 ["Create clock table" org-clock-report t]
15245 "--"
15246 ["Record DONE time"
15247 (progn (setq org-log-done (not org-log-done))
15248 (message "Switching to %s will %s record a timestamp"
15249 (car org-done-keywords)
15250 (if org-log-done "automatically" "not")))
15251 :style toggle :selected org-log-done])
15252 "--"
15253 ["Agenda Command..." org-agenda t]
15254 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
15255 ("File List for Agenda")
15256 ("Special views current file"
15257 ["TODO Tree" org-show-todo-tree t]
15258 ["Check Deadlines" org-check-deadlines t]
15259 ["Timeline" org-timeline t]
15260 ["Tags/Property tree" org-match-sparse-tree t])
15261 "--"
15262 ["Export/Publish..." org-export t]
15263 ("LaTeX"
15264 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
15265 :selected org-cdlatex-mode]
15266 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
15267 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
15268 ["Modify math symbol" org-cdlatex-math-modify
15269 (org-inside-LaTeX-fragment-p)]
15270 ["Insert citation" org-reftex-citation t]
15271 "--"
15272 ["Export LaTeX fragments as images"
15273 (if (featurep 'org-exp)
15274 (setq org-export-with-LaTeX-fragments
15275 (not org-export-with-LaTeX-fragments))
15276 (require 'org-exp))
15277 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
15278 org-export-with-LaTeX-fragments)])
15279 "--"
15280 ("Documentation"
15281 ["Show Version" org-version t]
15282 ["Info Documentation" org-info t])
15283 ("Customize"
15284 ["Browse Org Group" org-customize t]
15285 "--"
15286 ["Expand This Menu" org-create-customize-menu
15287 (fboundp 'customize-menu-create)])
15288 "--"
15289 ("Refresh/Reload"
15290 ["Refresh setup current buffer" org-mode-restart t]
15291 ["Reload Org (after update)" org-reload t]
15292 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
15295 (defun org-info (&optional node)
15296 "Read documentation for Org-mode in the info system.
15297 With optional NODE, go directly to that node."
15298 (interactive)
15299 (info (format "(org)%s" (or node ""))))
15301 (defun org-install-agenda-files-menu ()
15302 (let ((bl (buffer-list)))
15303 (save-excursion
15304 (while bl
15305 (set-buffer (pop bl))
15306 (if (org-mode-p) (setq bl nil)))
15307 (when (org-mode-p)
15308 (easy-menu-change
15309 '("Org") "File List for Agenda"
15310 (append
15311 (list
15312 ["Edit File List" (org-edit-agenda-file-list) t]
15313 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
15314 ["Remove Current File from List" org-remove-file t]
15315 ["Cycle through agenda files" org-cycle-agenda-files t]
15316 ["Occur in all agenda files" org-occur-in-agenda-files t]
15317 "--")
15318 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
15320 ;;;; Documentation
15322 ;;;###autoload
15323 (defun org-require-autoloaded-modules ()
15324 (interactive)
15325 (mapc 'require
15326 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
15327 org-docbook org-exp org-html org-icalendar
15328 org-id org-latex
15329 org-publish org-remember org-table
15330 org-timer org-xoxo)))
15332 ;;;###autoload
15333 (defun org-reload (&optional uncompiled)
15334 "Reload all org lisp files.
15335 With prefix arg UNCOMPILED, load the uncompiled versions."
15336 (interactive "P")
15337 (require 'find-func)
15338 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
15339 (dir-org (file-name-directory (org-find-library-name "org")))
15340 (dir-org-contrib (ignore-errors
15341 (file-name-directory
15342 (org-find-library-name "org-contribdir"))))
15343 (files
15344 (append (directory-files dir-org t file-re)
15345 (and dir-org-contrib
15346 (directory-files dir-org-contrib t file-re))))
15347 (remove-re (concat (if (featurep 'xemacs)
15348 "org-colview" "org-colview-xemacs")
15349 "\\'")))
15350 (setq files (mapcar 'file-name-sans-extension files))
15351 (setq files (mapcar
15352 (lambda (x) (if (string-match remove-re x) nil x))
15353 files))
15354 (setq files (delq nil files))
15355 (mapc
15356 (lambda (f)
15357 (when (featurep (intern (file-name-nondirectory f)))
15358 (if (and (not uncompiled)
15359 (file-exists-p (concat f ".elc")))
15360 (load (concat f ".elc") nil nil t)
15361 (load (concat f ".el") nil nil t))))
15362 files))
15363 (org-version))
15365 ;;;###autoload
15366 (defun org-customize ()
15367 "Call the customize function with org as argument."
15368 (interactive)
15369 (org-load-modules-maybe)
15370 (org-require-autoloaded-modules)
15371 (customize-browse 'org))
15373 (defun org-create-customize-menu ()
15374 "Create a full customization menu for Org-mode, insert it into the menu."
15375 (interactive)
15376 (org-load-modules-maybe)
15377 (org-require-autoloaded-modules)
15378 (if (fboundp 'customize-menu-create)
15379 (progn
15380 (easy-menu-change
15381 '("Org") "Customize"
15382 `(["Browse Org group" org-customize t]
15383 "--"
15384 ,(customize-menu-create 'org)
15385 ["Set" Custom-set t]
15386 ["Save" Custom-save t]
15387 ["Reset to Current" Custom-reset-current t]
15388 ["Reset to Saved" Custom-reset-saved t]
15389 ["Reset to Standard Settings" Custom-reset-standard t]))
15390 (message "\"Org\"-menu now contains full customization menu"))
15391 (error "Cannot expand menu (outdated version of cus-edit.el)")))
15393 ;;;; Miscellaneous stuff
15395 ;;; Generally useful functions
15397 (defun org-find-text-property-in-string (prop s)
15398 "Return the first non-nil value of property PROP in string S."
15399 (or (get-text-property 0 prop s)
15400 (get-text-property (or (next-single-property-change 0 prop s) 0)
15401 prop s)))
15403 (defun org-display-warning (message) ;; Copied from Emacs-Muse
15404 "Display the given MESSAGE as a warning."
15405 (if (fboundp 'display-warning)
15406 (display-warning 'org message
15407 (if (featurep 'xemacs)
15408 'warning
15409 :warning))
15410 (let ((buf (get-buffer-create "*Org warnings*")))
15411 (with-current-buffer buf
15412 (goto-char (point-max))
15413 (insert "Warning (Org): " message)
15414 (unless (bolp)
15415 (newline)))
15416 (display-buffer buf)
15417 (sit-for 0))))
15419 (defun org-goto-marker-or-bmk (marker &optional bookmark)
15420 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
15421 (if (and marker (marker-buffer marker)
15422 (buffer-live-p (marker-buffer marker)))
15423 (progn
15424 (switch-to-buffer (marker-buffer marker))
15425 (if (or (> marker (point-max)) (< marker (point-min)))
15426 (widen))
15427 (goto-char marker)
15428 (org-show-context 'org-goto))
15429 (if bookmark
15430 (bookmark-jump bookmark)
15431 (error "Cannot find location"))))
15433 (defun org-quote-csv-field (s)
15434 "Quote field for inclusion in CSV material."
15435 (if (string-match "[\",]" s)
15436 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
15439 (defun org-plist-delete (plist property)
15440 "Delete PROPERTY from PLIST.
15441 This is in contrast to merely setting it to 0."
15442 (let (p)
15443 (while plist
15444 (if (not (eq property (car plist)))
15445 (setq p (plist-put p (car plist) (nth 1 plist))))
15446 (setq plist (cddr plist)))
15449 (defun org-force-self-insert (N)
15450 "Needed to enforce self-insert under remapping."
15451 (interactive "p")
15452 (self-insert-command N))
15454 (defun org-string-width (s)
15455 "Compute width of string, ignoring invisible characters.
15456 This ignores character with invisibility property `org-link', and also
15457 characters with property `org-cwidth', because these will become invisible
15458 upon the next fontification round."
15459 (let (b l)
15460 (when (or (eq t buffer-invisibility-spec)
15461 (assq 'org-link buffer-invisibility-spec))
15462 (while (setq b (text-property-any 0 (length s)
15463 'invisible 'org-link s))
15464 (setq s (concat (substring s 0 b)
15465 (substring s (or (next-single-property-change
15466 b 'invisible s) (length s)))))))
15467 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
15468 (setq s (concat (substring s 0 b)
15469 (substring s (or (next-single-property-change
15470 b 'org-cwidth s) (length s))))))
15471 (setq l (string-width s) b -1)
15472 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
15473 (setq l (- l (get-text-property b 'org-dwidth-n s))))
15476 (defun org-get-indentation (&optional line)
15477 "Get the indentation of the current line, interpreting tabs.
15478 When LINE is given, assume it represents a line and compute its indentation."
15479 (if line
15480 (if (string-match "^ *" (org-remove-tabs line))
15481 (match-end 0))
15482 (save-excursion
15483 (beginning-of-line 1)
15484 (skip-chars-forward " \t")
15485 (current-column))))
15487 (defun org-remove-tabs (s &optional width)
15488 "Replace tabulators in S with spaces.
15489 Assumes that s is a single line, starting in column 0."
15490 (setq width (or width tab-width))
15491 (while (string-match "\t" s)
15492 (setq s (replace-match
15493 (make-string
15494 (- (* width (/ (+ (match-beginning 0) width) width))
15495 (match-beginning 0)) ?\ )
15496 t t s)))
15499 (defun org-fix-indentation (line ind)
15500 "Fix indentation in LINE.
15501 IND is a cons cell with target and minimum indentation.
15502 If the current indentation in LINE is smaller than the minimum,
15503 leave it alone. If it is larger than ind, set it to the target."
15504 (let* ((l (org-remove-tabs line))
15505 (i (org-get-indentation l))
15506 (i1 (car ind)) (i2 (cdr ind)))
15507 (if (>= i i2) (setq l (substring line i2)))
15508 (if (> i1 0)
15509 (concat (make-string i1 ?\ ) l)
15510 l)))
15512 (defun org-remove-indentation (code &optional n)
15513 "Remove the maximum common indentation from the lines in CODE.
15514 N may optionally be the number of spaces to remove."
15515 (with-temp-buffer
15516 (insert code)
15517 (org-do-remove-indentation n)
15518 (buffer-string)))
15520 (defun org-do-remove-indentation (&optional n)
15521 "Remove the maximum common indentation from the buffer."
15522 (untabify (point-min) (point-max))
15523 (let ((min 10000) re)
15524 (if n
15525 (setq min n)
15526 (goto-char (point-min))
15527 (while (re-search-forward "^ *[^ \n]" nil t)
15528 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
15529 (unless (or (= min 0) (= min 10000))
15530 (setq re (format "^ \\{%d\\}" min))
15531 (goto-char (point-min))
15532 (while (re-search-forward re nil t)
15533 (replace-match "")
15534 (end-of-line 1))
15535 min)))
15537 (defun org-base-buffer (buffer)
15538 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
15539 (if (not buffer)
15540 buffer
15541 (or (buffer-base-buffer buffer)
15542 buffer)))
15544 (defun org-trim (s)
15545 "Remove whitespace at beginning and end of string."
15546 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
15547 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
15550 (defun org-wrap (string &optional width lines)
15551 "Wrap string to either a number of lines, or a width in characters.
15552 If WIDTH is non-nil, the string is wrapped to that width, however many lines
15553 that costs. If there is a word longer than WIDTH, the text is actually
15554 wrapped to the length of that word.
15555 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
15556 many lines, whatever width that takes.
15557 The return value is a list of lines, without newlines at the end."
15558 (let* ((words (org-split-string string "[ \t\n]+"))
15559 (maxword (apply 'max (mapcar 'org-string-width words)))
15560 w ll)
15561 (cond (width
15562 (org-do-wrap words (max maxword width)))
15563 (lines
15564 (setq w maxword)
15565 (setq ll (org-do-wrap words maxword))
15566 (if (<= (length ll) lines)
15568 (setq ll words)
15569 (while (> (length ll) lines)
15570 (setq w (1+ w))
15571 (setq ll (org-do-wrap words w)))
15572 ll))
15573 (t (error "Cannot wrap this")))))
15575 (defun org-do-wrap (words width)
15576 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
15577 (let (lines line)
15578 (while words
15579 (setq line (pop words))
15580 (while (and words (< (+ (length line) (length (car words))) width))
15581 (setq line (concat line " " (pop words))))
15582 (setq lines (push line lines)))
15583 (nreverse lines)))
15585 (defun org-split-string (string &optional separators)
15586 "Splits STRING into substrings at SEPARATORS.
15587 No empty strings are returned if there are matches at the beginning
15588 and end of string."
15589 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
15590 (start 0)
15591 notfirst
15592 (list nil))
15593 (while (and (string-match rexp string
15594 (if (and notfirst
15595 (= start (match-beginning 0))
15596 (< start (length string)))
15597 (1+ start) start))
15598 (< (match-beginning 0) (length string)))
15599 (setq notfirst t)
15600 (or (eq (match-beginning 0) 0)
15601 (and (eq (match-beginning 0) (match-end 0))
15602 (eq (match-beginning 0) start))
15603 (setq list
15604 (cons (substring string start (match-beginning 0))
15605 list)))
15606 (setq start (match-end 0)))
15607 (or (eq start (length string))
15608 (setq list
15609 (cons (substring string start)
15610 list)))
15611 (nreverse list)))
15613 (defun org-quote-vert (s)
15614 "Replace \"|\" with \"\\vert\"."
15615 (while (string-match "|" s)
15616 (setq s (replace-match "\\vert" t t s)))
15619 (defun org-uuidgen-p (s)
15620 "Is S an ID created by UUIDGEN?"
15621 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
15623 (defun org-context ()
15624 "Return a list of contexts of the current cursor position.
15625 If several contexts apply, all are returned.
15626 Each context entry is a list with a symbol naming the context, and
15627 two positions indicating start and end of the context. Possible
15628 contexts are:
15630 :headline anywhere in a headline
15631 :headline-stars on the leading stars in a headline
15632 :todo-keyword on a TODO keyword (including DONE) in a headline
15633 :tags on the TAGS in a headline
15634 :priority on the priority cookie in a headline
15635 :item on the first line of a plain list item
15636 :item-bullet on the bullet/number of a plain list item
15637 :checkbox on the checkbox in a plain list item
15638 :table in an org-mode table
15639 :table-special on a special filed in a table
15640 :table-table in a table.el table
15641 :link on a hyperlink
15642 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
15643 :target on a <<target>>
15644 :radio-target on a <<<radio-target>>>
15645 :latex-fragment on a LaTeX fragment
15646 :latex-preview on a LaTeX fragment with overlayed preview image
15648 This function expects the position to be visible because it uses font-lock
15649 faces as a help to recognize the following contexts: :table-special, :link,
15650 and :keyword."
15651 (let* ((f (get-text-property (point) 'face))
15652 (faces (if (listp f) f (list f)))
15653 (p (point)) clist o)
15654 ;; First the large context
15655 (cond
15656 ((org-on-heading-p t)
15657 (push (list :headline (point-at-bol) (point-at-eol)) clist)
15658 (when (progn
15659 (beginning-of-line 1)
15660 (looking-at org-todo-line-tags-regexp))
15661 (push (org-point-in-group p 1 :headline-stars) clist)
15662 (push (org-point-in-group p 2 :todo-keyword) clist)
15663 (push (org-point-in-group p 4 :tags) clist))
15664 (goto-char p)
15665 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
15666 (if (looking-at "\\[#[A-Z0-9]\\]")
15667 (push (org-point-in-group p 0 :priority) clist)))
15669 ((org-at-item-p)
15670 (push (org-point-in-group p 2 :item-bullet) clist)
15671 (push (list :item (point-at-bol)
15672 (save-excursion (org-end-of-item) (point)))
15673 clist)
15674 (and (org-at-item-checkbox-p)
15675 (push (org-point-in-group p 0 :checkbox) clist)))
15677 ((org-at-table-p)
15678 (push (list :table (org-table-begin) (org-table-end)) clist)
15679 (if (memq 'org-formula faces)
15680 (push (list :table-special
15681 (previous-single-property-change p 'face)
15682 (next-single-property-change p 'face)) clist)))
15683 ((org-at-table-p 'any)
15684 (push (list :table-table) clist)))
15685 (goto-char p)
15687 ;; Now the small context
15688 (cond
15689 ((org-at-timestamp-p)
15690 (push (org-point-in-group p 0 :timestamp) clist))
15691 ((memq 'org-link faces)
15692 (push (list :link
15693 (previous-single-property-change p 'face)
15694 (next-single-property-change p 'face)) clist))
15695 ((memq 'org-special-keyword faces)
15696 (push (list :keyword
15697 (previous-single-property-change p 'face)
15698 (next-single-property-change p 'face)) clist))
15699 ((org-on-target-p)
15700 (push (org-point-in-group p 0 :target) clist)
15701 (goto-char (1- (match-beginning 0)))
15702 (if (looking-at org-radio-target-regexp)
15703 (push (org-point-in-group p 0 :radio-target) clist))
15704 (goto-char p))
15705 ((setq o (car (delq nil
15706 (mapcar
15707 (lambda (x)
15708 (if (memq x org-latex-fragment-image-overlays) x))
15709 (org-overlays-at (point))))))
15710 (push (list :latex-fragment
15711 (org-overlay-start o) (org-overlay-end o)) clist)
15712 (push (list :latex-preview
15713 (org-overlay-start o) (org-overlay-end o)) clist))
15714 ((org-inside-LaTeX-fragment-p)
15715 ;; FIXME: positions wrong.
15716 (push (list :latex-fragment (point) (point)) clist)))
15718 (setq clist (nreverse (delq nil clist)))
15719 clist))
15721 ;; FIXME: Compare with at-regexp-p Do we need both?
15722 (defun org-in-regexp (re &optional nlines visually)
15723 "Check if point is inside a match of regexp.
15724 Normally only the current line is checked, but you can include NLINES extra
15725 lines both before and after point into the search.
15726 If VISUALLY is set, require that the cursor is not after the match but
15727 really on, so that the block visually is on the match."
15728 (catch 'exit
15729 (let ((pos (point))
15730 (eol (point-at-eol (+ 1 (or nlines 0))))
15731 (inc (if visually 1 0)))
15732 (save-excursion
15733 (beginning-of-line (- 1 (or nlines 0)))
15734 (while (re-search-forward re eol t)
15735 (if (and (<= (match-beginning 0) pos)
15736 (>= (+ inc (match-end 0)) pos))
15737 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
15739 (defun org-at-regexp-p (regexp)
15740 "Is point inside a match of REGEXP in the current line?"
15741 (catch 'exit
15742 (save-excursion
15743 (let ((pos (point)) (end (point-at-eol)))
15744 (beginning-of-line 1)
15745 (while (re-search-forward regexp end t)
15746 (if (and (<= (match-beginning 0) pos)
15747 (>= (match-end 0) pos))
15748 (throw 'exit t)))
15749 nil))))
15751 (defun org-occur-in-agenda-files (regexp &optional nlines)
15752 "Call `multi-occur' with buffers for all agenda files."
15753 (interactive "sOrg-files matching: \np")
15754 (let* ((files (org-agenda-files))
15755 (tnames (mapcar 'file-truename files))
15756 (extra org-agenda-text-search-extra-files)
15758 (when (eq (car extra) 'agenda-archives)
15759 (setq extra (cdr extra))
15760 (setq files (org-add-archive-files files)))
15761 (while (setq f (pop extra))
15762 (unless (member (file-truename f) tnames)
15763 (add-to-list 'files f 'append)
15764 (add-to-list 'tnames (file-truename f) 'append)))
15765 (multi-occur
15766 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
15767 regexp)))
15769 (if (boundp 'occur-mode-find-occurrence-hook)
15770 ;; Emacs 23
15771 (add-hook 'occur-mode-find-occurrence-hook
15772 (lambda ()
15773 (when (org-mode-p)
15774 (org-reveal))))
15775 ;; Emacs 22
15776 (defadvice occur-mode-goto-occurrence
15777 (after org-occur-reveal activate)
15778 (and (org-mode-p) (org-reveal)))
15779 (defadvice occur-mode-goto-occurrence-other-window
15780 (after org-occur-reveal activate)
15781 (and (org-mode-p) (org-reveal)))
15782 (defadvice occur-mode-display-occurrence
15783 (after org-occur-reveal activate)
15784 (when (org-mode-p)
15785 (let ((pos (occur-mode-find-occurrence)))
15786 (with-current-buffer (marker-buffer pos)
15787 (save-excursion
15788 (goto-char pos)
15789 (org-reveal)))))))
15791 (defun org-occur-link-in-agenda-files ()
15792 "Create a link and search for it in the agendas.
15793 The link is not stored in `org-stored-links', it is just created
15794 for the search purpose."
15795 (interactive)
15796 (let ((link (condition-case nil
15797 (org-store-link nil)
15798 (error "Unable to create a link to here"))))
15799 (org-occur-in-agenda-files (regexp-quote link))))
15801 (defun org-uniquify (list)
15802 "Remove duplicate elements from LIST."
15803 (let (res)
15804 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
15805 res))
15807 (defun org-delete-all (elts list)
15808 "Remove all elements in ELTS from LIST."
15809 (while elts
15810 (setq list (delete (pop elts) list)))
15811 list)
15813 (defun org-back-over-empty-lines ()
15814 "Move backwards over whitespace, to the beginning of the first empty line.
15815 Returns the number of empty lines passed."
15816 (let ((pos (point)))
15817 (skip-chars-backward " \t\n\r")
15818 (beginning-of-line 2)
15819 (goto-char (min (point) pos))
15820 (count-lines (point) pos)))
15822 (defun org-skip-whitespace ()
15823 (skip-chars-forward " \t\n\r"))
15825 (defun org-point-in-group (point group &optional context)
15826 "Check if POINT is in match-group GROUP.
15827 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
15828 match. If the match group does ot exist or point is not inside it,
15829 return nil."
15830 (and (match-beginning group)
15831 (>= point (match-beginning group))
15832 (<= point (match-end group))
15833 (if context
15834 (list context (match-beginning group) (match-end group))
15835 t)))
15837 (defun org-switch-to-buffer-other-window (&rest args)
15838 "Switch to buffer in a second window on the current frame.
15839 In particular, do not allow pop-up frames."
15840 (let (pop-up-frames special-display-buffer-names special-display-regexps
15841 special-display-function)
15842 (apply 'switch-to-buffer-other-window args)))
15844 (defun org-combine-plists (&rest plists)
15845 "Create a single property list from all plists in PLISTS.
15846 The process starts by copying the first list, and then setting properties
15847 from the other lists. Settings in the last list are the most significant
15848 ones and overrule settings in the other lists."
15849 (let ((rtn (copy-sequence (pop plists)))
15850 p v ls)
15851 (while plists
15852 (setq ls (pop plists))
15853 (while ls
15854 (setq p (pop ls) v (pop ls))
15855 (setq rtn (plist-put rtn p v))))
15856 rtn))
15858 (defun org-move-line-down (arg)
15859 "Move the current line down. With prefix argument, move it past ARG lines."
15860 (interactive "p")
15861 (let ((col (current-column))
15862 beg end pos)
15863 (beginning-of-line 1) (setq beg (point))
15864 (beginning-of-line 2) (setq end (point))
15865 (beginning-of-line (+ 1 arg))
15866 (setq pos (move-marker (make-marker) (point)))
15867 (insert (delete-and-extract-region beg end))
15868 (goto-char pos)
15869 (org-move-to-column col)))
15871 (defun org-move-line-up (arg)
15872 "Move the current line up. With prefix argument, move it past ARG lines."
15873 (interactive "p")
15874 (let ((col (current-column))
15875 beg end pos)
15876 (beginning-of-line 1) (setq beg (point))
15877 (beginning-of-line 2) (setq end (point))
15878 (beginning-of-line (- arg))
15879 (setq pos (move-marker (make-marker) (point)))
15880 (insert (delete-and-extract-region beg end))
15881 (goto-char pos)
15882 (org-move-to-column col)))
15884 (defun org-replace-escapes (string table)
15885 "Replace %-escapes in STRING with values in TABLE.
15886 TABLE is an association list with keys like \"%a\" and string values.
15887 The sequences in STRING may contain normal field width and padding information,
15888 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
15889 so values can contain further %-escapes if they are define later in TABLE."
15890 (let ((case-fold-search nil)
15891 e re rpl)
15892 (while (setq e (pop table))
15893 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
15894 (while (string-match re string)
15895 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
15896 (cdr e)))
15897 (setq string (replace-match rpl t t string))))
15898 string))
15901 (defun org-sublist (list start end)
15902 "Return a section of LIST, from START to END.
15903 Counting starts at 1."
15904 (let (rtn (c start))
15905 (setq list (nthcdr (1- start) list))
15906 (while (and list (<= c end))
15907 (push (pop list) rtn)
15908 (setq c (1+ c)))
15909 (nreverse rtn)))
15911 (defun org-find-base-buffer-visiting (file)
15912 "Like `find-buffer-visiting' but always return the base buffer and
15913 not an indirect buffer."
15914 (let ((buf (or (get-file-buffer file)
15915 (find-buffer-visiting file))))
15916 (if buf
15917 (or (buffer-base-buffer buf) buf)
15918 nil)))
15920 (defun org-image-file-name-regexp (&optional extensions)
15921 "Return regexp matching the file names of images.
15922 If EXTENSIONS is given, only match these."
15923 (if (and (not extensions) (fboundp 'image-file-name-regexp))
15924 (image-file-name-regexp)
15925 (let ((image-file-name-extensions
15926 (or extensions
15927 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
15928 "xbm" "xpm" "pbm" "pgm" "ppm"))))
15929 (concat "\\."
15930 (regexp-opt (nconc (mapcar 'upcase
15931 image-file-name-extensions)
15932 image-file-name-extensions)
15934 "\\'"))))
15936 (defun org-file-image-p (file &optional extensions)
15937 "Return non-nil if FILE is an image."
15938 (save-match-data
15939 (string-match (org-image-file-name-regexp extensions) file)))
15941 (defun org-get-cursor-date ()
15942 "Return the date at cursor in as a time.
15943 This works in the calendar and in the agenda, anywhere else it just
15944 returns the current time."
15945 (let (date day defd)
15946 (cond
15947 ((eq major-mode 'calendar-mode)
15948 (setq date (calendar-cursor-to-date)
15949 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15950 ((eq major-mode 'org-agenda-mode)
15951 (setq day (get-text-property (point) 'day))
15952 (if day
15953 (setq date (calendar-gregorian-from-absolute day)
15954 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
15955 (nth 2 date))))))
15956 (or defd (current-time))))
15958 (defvar org-agenda-action-marker (make-marker)
15959 "Marker pointing to the entry for the next agenda action.")
15961 (defun org-mark-entry-for-agenda-action ()
15962 "Mark the current entry as target of an agenda action.
15963 Agenda actions are actions executed from the agenda with the key `k',
15964 which make use of the date at the cursor."
15965 (interactive)
15966 (move-marker org-agenda-action-marker
15967 (save-excursion (org-back-to-heading t) (point))
15968 (current-buffer))
15969 (message
15970 "Entry marked for action; press `k' at desired date in agenda or calendar"))
15972 ;;; Paragraph filling stuff.
15973 ;; We want this to be just right, so use the full arsenal.
15975 (defun org-indent-line-function ()
15976 "Indent line like previous, but further if previous was headline or item."
15977 (interactive)
15978 (let* ((pos (point))
15979 (itemp (org-at-item-p))
15980 (case-fold-search t)
15981 (org-drawer-regexp (or org-drawer-regexp "\000"))
15982 column bpos bcol tpos tcol bullet btype bullet-type)
15983 ;; Find the previous relevant line
15984 (beginning-of-line 1)
15985 (cond
15986 ((looking-at "#") (setq column 0))
15987 ((looking-at "\\*+ ") (setq column 0))
15988 ((and (looking-at "[ \t]*:END:")
15989 (save-excursion (re-search-backward org-drawer-regexp nil t)))
15990 (save-excursion
15991 (goto-char (1- (match-beginning 1)))
15992 (setq column (current-column))))
15993 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
15994 (save-excursion
15995 (re-search-backward
15996 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
15997 (setq column (org-get-indentation (match-string 0))))
15999 (beginning-of-line 0)
16000 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
16001 (not (looking-at "[ \t]*:END:"))
16002 (not (looking-at org-drawer-regexp)))
16003 (beginning-of-line 0))
16004 (cond
16005 ((looking-at "\\*+[ \t]+")
16006 (if (not org-adapt-indentation)
16007 (setq column 0)
16008 (goto-char (match-end 0))
16009 (setq column (current-column))))
16010 ((looking-at org-drawer-regexp)
16011 (goto-char (1- (match-beginning 1)))
16012 (setq column (current-column)))
16013 ((looking-at "\\([ \t]*\\):END:")
16014 (goto-char (match-end 1))
16015 (setq column (current-column)))
16016 ((org-in-item-p)
16017 (org-beginning-of-item)
16018 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
16019 (setq bpos (match-beginning 1) tpos (match-end 0)
16020 bcol (progn (goto-char bpos) (current-column))
16021 tcol (progn (goto-char tpos) (current-column))
16022 bullet (match-string 1)
16023 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
16024 (if (> tcol (+ bcol org-description-max-indent))
16025 (setq tcol (+ bcol 5)))
16026 (if (not itemp)
16027 (setq column tcol)
16028 (goto-char pos)
16029 (beginning-of-line 1)
16030 (if (looking-at "\\S-")
16031 (progn
16032 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
16033 (setq bullet (match-string 1)
16034 btype (if (string-match "[0-9]" bullet) "n" bullet))
16035 (setq column (if (equal btype bullet-type) bcol tcol)))
16036 (setq column (org-get-indentation)))))
16037 (t (setq column (org-get-indentation))))))
16038 (goto-char pos)
16039 (if (<= (current-column) (current-indentation))
16040 (org-indent-line-to column)
16041 (save-excursion (org-indent-line-to column)))
16042 (setq column (current-column))
16043 (beginning-of-line 1)
16044 (if (looking-at
16045 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
16046 (replace-match (concat "\\1" (format org-property-format
16047 (match-string 2) (match-string 3)))
16048 t nil))
16049 (org-move-to-column column)))
16051 (defun org-set-autofill-regexps ()
16052 (interactive)
16053 ;; In the paragraph separator we include headlines, because filling
16054 ;; text in a line directly attached to a headline would otherwise
16055 ;; fill the headline as well.
16056 (org-set-local 'comment-start-skip "^#+[ \t]*")
16057 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
16058 ;; The paragraph starter includes hand-formatted lists.
16059 (org-set-local
16060 'paragraph-start
16061 (concat
16062 "\f" "\\|"
16063 "[ ]*$" "\\|"
16064 "\\*+ " "\\|"
16065 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
16066 "[ \t]*[:|]" "\\|"
16067 "\\$\\$" "\\|"
16068 "\\\\\\(begin\\|end\\|[][]\\)"))
16069 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
16070 ;; But only if the user has not turned off tables or fixed-width regions
16071 (org-set-local
16072 'auto-fill-inhibit-regexp
16073 (concat "\\*+ \\|#\\+"
16074 "\\|[ \t]*" org-keyword-time-regexp
16075 (if (or org-enable-table-editor org-enable-fixed-width-editor)
16076 (concat
16077 "\\|[ \t]*["
16078 (if org-enable-table-editor "|" "")
16079 (if org-enable-fixed-width-editor ":" "")
16080 "]"))))
16081 ;; We use our own fill-paragraph function, to make sure that tables
16082 ;; and fixed-width regions are not wrapped. That function will pass
16083 ;; through to `fill-paragraph' when appropriate.
16084 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
16085 ; Adaptive filling: To get full control, first make sure that
16086 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
16087 (org-set-local 'adaptive-fill-regexp "\000")
16088 (org-set-local 'adaptive-fill-function
16089 'org-adaptive-fill-function)
16090 (org-set-local
16091 'align-mode-rules-list
16092 '((org-in-buffer-settings
16093 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
16094 (modes . '(org-mode))))))
16096 (defun org-fill-paragraph (&optional justify)
16097 "Re-align a table, pass through to fill-paragraph if no table."
16098 (let ((table-p (org-at-table-p))
16099 (table.el-p (org-at-table.el-p)))
16100 (cond ((and (equal (char-after (point-at-bol)) ?*)
16101 (save-excursion (goto-char (point-at-bol))
16102 (looking-at outline-regexp)))
16103 t) ; skip headlines
16104 (table.el-p t) ; skip table.el tables
16105 (table-p (org-table-align) t) ; align org-mode tables
16106 (t nil)))) ; call paragraph-fill
16108 ;; For reference, this is the default value of adaptive-fill-regexp
16109 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
16111 (defun org-adaptive-fill-function ()
16112 "Return a fill prefix for org-mode files.
16113 In particular, this makes sure hanging paragraphs for hand-formatted lists
16114 work correctly."
16115 (cond ((looking-at "#[ \t]+")
16116 (match-string 0))
16117 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
16118 (save-excursion
16119 (if (> (match-end 1) (+ (match-beginning 1)
16120 org-description-max-indent))
16121 (goto-char (+ (match-beginning 1) 5))
16122 (goto-char (match-end 0)))
16123 (make-string (current-column) ?\ )))
16124 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
16125 (save-excursion
16126 (goto-char (match-end 0))
16127 (make-string (current-column) ?\ )))
16128 (t nil)))
16130 ;;; Other stuff.
16132 (defun org-toggle-fixed-width-section (arg)
16133 "Toggle the fixed-width export.
16134 If there is no active region, the QUOTE keyword at the current headline is
16135 inserted or removed. When present, it causes the text between this headline
16136 and the next to be exported as fixed-width text, and unmodified.
16137 If there is an active region, this command adds or removes a colon as the
16138 first character of this line. If the first character of a line is a colon,
16139 this line is also exported in fixed-width font."
16140 (interactive "P")
16141 (let* ((cc 0)
16142 (regionp (org-region-active-p))
16143 (beg (if regionp (region-beginning) (point)))
16144 (end (if regionp (region-end)))
16145 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
16146 (case-fold-search nil)
16147 (re "[ \t]*\\(: \\)")
16148 off)
16149 (if regionp
16150 (save-excursion
16151 (goto-char beg)
16152 (setq cc (current-column))
16153 (beginning-of-line 1)
16154 (setq off (looking-at re))
16155 (while (> nlines 0)
16156 (setq nlines (1- nlines))
16157 (beginning-of-line 1)
16158 (cond
16159 (arg
16160 (org-move-to-column cc t)
16161 (insert ": \n")
16162 (forward-line -1))
16163 ((and off (looking-at re))
16164 (replace-match "" t t nil 1))
16165 ((not off) (org-move-to-column cc t) (insert ": ")))
16166 (forward-line 1)))
16167 (save-excursion
16168 (org-back-to-heading)
16169 (if (looking-at (concat outline-regexp
16170 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
16171 (replace-match "" t t nil 1)
16172 (if (looking-at outline-regexp)
16173 (progn
16174 (goto-char (match-end 0))
16175 (insert org-quote-string " "))))))))
16177 (defun org-reftex-citation ()
16178 "Use reftex-citation to insert a citation into the buffer.
16179 This looks for a line like
16181 #+BIBLIOGRAPHY: foo plain option:-d
16183 and derives from it that foo.bib is the bbliography file relevant
16184 for this document. It then installs the necessary environment for RefTeX
16185 to work in this buffer and calls `reftex-citation' to insert a citation
16186 into the buffer.
16188 Export of such citations to both LaTeX and HTML is handled by the contributed
16189 package org-exp-bibtex by Taru Karttunen."
16190 (interactive)
16191 (let ((reftex-docstruct-symbol 'rds)
16192 (reftex-cite-format "\\cite{%l}")
16193 rds bib)
16194 (save-excursion
16195 (save-restriction
16196 (widen)
16197 (let ((case-fold-search t)
16198 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
16199 (if (not (save-excursion
16200 (or (re-search-forward re nil t)
16201 (re-search-backward re nil t))))
16202 (error "No bibliography defined in file")
16203 (setq bib (concat (match-string 1) ".bib")
16204 rds (list (list 'bib bib)))))))
16205 (call-interactively 'reftex-citation)))
16207 ;;;; Functions extending outline functionality
16209 (defun org-beginning-of-line (&optional arg)
16210 "Go to the beginning of the current line. If that is invisible, continue
16211 to a visible line beginning. This makes the function of C-a more intuitive.
16212 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16213 first attempt, and only move to after the tags when the cursor is already
16214 beyond the end of the headline."
16215 (interactive "P")
16216 (let ((pos (point))
16217 (special (if (consp org-special-ctrl-a/e)
16218 (car org-special-ctrl-a/e)
16219 org-special-ctrl-a/e))
16220 refpos)
16221 (if (org-bound-and-true-p line-move-visual)
16222 (beginning-of-visual-line 1)
16223 (beginning-of-line 1))
16224 (if (and arg (fboundp 'move-beginning-of-line))
16225 (call-interactively 'move-beginning-of-line)
16226 (if (bobp)
16228 (backward-char 1)
16229 (if (org-invisible-p)
16230 (while (and (not (bobp)) (org-invisible-p))
16231 (backward-char 1)
16232 (beginning-of-line 1))
16233 (forward-char 1))))
16234 (when special
16235 (cond
16236 ((and (looking-at org-complex-heading-regexp)
16237 (= (char-after (match-end 1)) ?\ ))
16238 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
16239 (point-at-eol)))
16240 (goto-char
16241 (if (eq special t)
16242 (cond ((> pos refpos) refpos)
16243 ((= pos (point)) refpos)
16244 (t (point)))
16245 (cond ((> pos (point)) (point))
16246 ((not (eq last-command this-command)) (point))
16247 (t refpos)))))
16248 ((org-at-item-p)
16249 (goto-char
16250 (if (eq special t)
16251 (cond ((> pos (match-end 4)) (match-end 4))
16252 ((= pos (point)) (match-end 4))
16253 (t (point)))
16254 (cond ((> pos (point)) (point))
16255 ((not (eq last-command this-command)) (point))
16256 (t (match-end 4))))))))
16257 (org-no-warnings
16258 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16260 (defun org-end-of-line (&optional arg)
16261 "Go to the end of the line.
16262 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16263 first attempt, and only move to after the tags when the cursor is already
16264 beyond the end of the headline."
16265 (interactive "P")
16266 (let ((special (if (consp org-special-ctrl-a/e)
16267 (cdr org-special-ctrl-a/e)
16268 org-special-ctrl-a/e)))
16269 (if (or (not special)
16270 (not (org-on-heading-p))
16271 arg)
16272 (call-interactively
16273 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
16274 ((fboundp 'move-end-of-line) 'move-end-of-line)
16275 (t 'end-of-line)))
16276 (let ((pos (point)))
16277 (beginning-of-line 1)
16278 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
16279 (if (eq special t)
16280 (if (or (< pos (match-beginning 1))
16281 (= pos (match-end 0)))
16282 (goto-char (match-beginning 1))
16283 (goto-char (match-end 0)))
16284 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
16285 (goto-char (match-end 0))
16286 (goto-char (match-beginning 1))))
16287 (call-interactively (if (fboundp 'move-end-of-line)
16288 'move-end-of-line
16289 'end-of-line)))))
16290 (org-no-warnings
16291 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16293 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
16294 (define-key org-mode-map "\C-e" 'org-end-of-line)
16296 (defun org-backward-sentence (&optional arg)
16297 "Go to beginning of sentence, or beginning of table field.
16298 This will call `backward-sentence' or `org-table-beginning-of-field',
16299 depending on context."
16300 (interactive "P")
16301 (cond
16302 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
16303 (t (call-interactively 'backward-sentence))))
16305 (defun org-forward-sentence (&optional arg)
16306 "Go to end of sentence, or end of table field.
16307 This will call `forward-sentence' or `org-table-end-of-field',
16308 depending on context."
16309 (interactive "P")
16310 (cond
16311 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
16312 (t (call-interactively 'forward-sentence))))
16314 (define-key org-mode-map "\M-a" 'org-backward-sentence)
16315 (define-key org-mode-map "\M-e" 'org-forward-sentence)
16317 (defun org-kill-line (&optional arg)
16318 "Kill line, to tags or end of line."
16319 (interactive "P")
16320 (cond
16321 ((or (not org-special-ctrl-k)
16322 (bolp)
16323 (not (org-on-heading-p)))
16324 (call-interactively 'kill-line))
16325 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
16326 (kill-region (point) (match-beginning 1))
16327 (org-set-tags nil t))
16328 (t (kill-region (point) (point-at-eol)))))
16330 (define-key org-mode-map "\C-k" 'org-kill-line)
16332 (defun org-yank (&optional arg)
16333 "Yank. If the kill is a subtree, treat it specially.
16334 This command will look at the current kill and check if is a single
16335 subtree, or a series of subtrees[1]. If it passes the test, and if the
16336 cursor is at the beginning of a line or after the stars of a currently
16337 empty headline, then the yank is handled specially. How exactly depends
16338 on the value of the following variables, both set by default.
16340 org-yank-folded-subtrees
16341 When set, the subtree(s) will be folded after insertion, but only
16342 if doing so would now swallow text after the yanked text.
16344 org-yank-adjusted-subtrees
16345 When set, the subtree will be promoted or demoted in order to
16346 fit into the local outline tree structure, which means that the level
16347 will be adjusted so that it becomes the smaller one of the two
16348 *visible* surrounding headings.
16350 Any prefix to this command will cause `yank' to be called directly with
16351 no special treatment. In particular, a simple `C-u' prefix will just
16352 plainly yank the text as it is.
16354 \[1] The test checks if the first non-white line is a heading
16355 and if there are no other headings with fewer stars."
16356 (interactive "P")
16357 (org-yank-generic 'yank arg))
16359 (defun org-yank-generic (command arg)
16360 "Perform some yank-like command.
16362 This function implements the behavior described in the `org-yank'
16363 documentation. However, it has been generalized to work for any
16364 interactive command with similar behavior."
16366 ;; pretend to be command COMMAND
16367 (setq this-command command)
16369 (if arg
16370 (call-interactively command)
16372 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
16373 (and (org-kill-is-subtree-p)
16374 (or (bolp)
16375 (and (looking-at "[ \t]*$")
16376 (string-match
16377 "\\`\\*+\\'"
16378 (buffer-substring (point-at-bol) (point)))))))
16379 swallowp)
16380 (cond
16381 ((and subtreep org-yank-folded-subtrees)
16382 (let ((beg (point))
16383 end)
16384 (if (and subtreep org-yank-adjusted-subtrees)
16385 (org-paste-subtree nil nil 'for-yank)
16386 (call-interactively command))
16388 (setq end (point))
16389 (goto-char beg)
16390 (when (and (bolp) subtreep
16391 (not (setq swallowp
16392 (org-yank-folding-would-swallow-text beg end))))
16393 (or (looking-at outline-regexp)
16394 (re-search-forward (concat "^" outline-regexp) end t))
16395 (while (and (< (point) end) (looking-at outline-regexp))
16396 (hide-subtree)
16397 (org-cycle-show-empty-lines 'folded)
16398 (condition-case nil
16399 (outline-forward-same-level 1)
16400 (error (goto-char end)))))
16401 (when swallowp
16402 (message
16403 "Inserted text not folded because that would swallow text"))
16405 (goto-char end)
16406 (skip-chars-forward " \t\n\r")
16407 (beginning-of-line 1)
16408 (push-mark beg 'nomsg)))
16409 ((and subtreep org-yank-adjusted-subtrees)
16410 (let ((beg (point-at-bol)))
16411 (org-paste-subtree nil nil 'for-yank)
16412 (push-mark beg 'nomsg)))
16414 (call-interactively command))))))
16416 (defun org-yank-folding-would-swallow-text (beg end)
16417 "Would hide-subtree at BEG swallow any text after END?"
16418 (let (level)
16419 (save-excursion
16420 (goto-char beg)
16421 (when (or (looking-at outline-regexp)
16422 (re-search-forward (concat "^" outline-regexp) end t))
16423 (setq level (org-outline-level)))
16424 (goto-char end)
16425 (skip-chars-forward " \t\r\n\v\f")
16426 (if (or (eobp)
16427 (and (bolp) (looking-at org-outline-regexp)
16428 (<= (org-outline-level) level)))
16429 nil ; Nothing would be swallowed
16430 t)))) ; something would swallow
16432 (define-key org-mode-map "\C-y" 'org-yank)
16434 (defun org-invisible-p ()
16435 "Check if point is at a character currently not visible."
16436 ;; Early versions of noutline don't have `outline-invisible-p'.
16437 (if (fboundp 'outline-invisible-p)
16438 (outline-invisible-p)
16439 (get-char-property (point) 'invisible)))
16441 (defun org-invisible-p2 ()
16442 "Check if point is at a character currently not visible."
16443 (save-excursion
16444 (if (and (eolp) (not (bobp))) (backward-char 1))
16445 ;; Early versions of noutline don't have `outline-invisible-p'.
16446 (if (fboundp 'outline-invisible-p)
16447 (outline-invisible-p)
16448 (get-char-property (point) 'invisible))))
16450 (defun org-back-to-heading (&optional invisible-ok)
16451 "Call `outline-back-to-heading', but provide a better error message."
16452 (condition-case nil
16453 (outline-back-to-heading invisible-ok)
16454 (error (error "Before first headline at position %d in buffer %s"
16455 (point) (current-buffer)))))
16457 (defun org-before-first-heading-p ()
16458 "Before first heading?"
16459 (save-excursion
16460 (null (re-search-backward "^\\*+ " nil t))))
16462 (defalias 'org-on-heading-p 'outline-on-heading-p)
16463 (defalias 'org-at-heading-p 'outline-on-heading-p)
16464 (defun org-at-heading-or-item-p ()
16465 (or (org-on-heading-p) (org-at-item-p)))
16467 (defun org-on-target-p ()
16468 (or (org-in-regexp org-radio-target-regexp)
16469 (org-in-regexp org-target-regexp)))
16471 (defun org-up-heading-all (arg)
16472 "Move to the heading line of which the present line is a subheading.
16473 This function considers both visible and invisible heading lines.
16474 With argument, move up ARG levels."
16475 (if (fboundp 'outline-up-heading-all)
16476 (outline-up-heading-all arg) ; emacs 21 version of outline.el
16477 (outline-up-heading arg t))) ; emacs 22 version of outline.el
16479 (defun org-up-heading-safe ()
16480 "Move to the heading line of which the present line is a subheading.
16481 This version will not throw an error. It will return the level of the
16482 headline found, or nil if no higher level is found.
16484 Also, this function will be a lot faster than `outline-up-heading',
16485 because it relies on stars being the outline starters. This can really
16486 make a significant difference in outlines with very many siblings."
16487 (let (start-level re)
16488 (org-back-to-heading t)
16489 (setq start-level (funcall outline-level))
16490 (if (equal start-level 1)
16492 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
16493 (if (re-search-backward re nil t)
16494 (funcall outline-level)))))
16496 (defun org-first-sibling-p ()
16497 "Is this heading the first child of its parents?"
16498 (interactive)
16499 (let ((re (concat "^" outline-regexp))
16500 level l)
16501 (unless (org-at-heading-p t)
16502 (error "Not at a heading"))
16503 (setq level (funcall outline-level))
16504 (save-excursion
16505 (if (not (re-search-backward re nil t))
16507 (setq l (funcall outline-level))
16508 (< l level)))))
16510 (defun org-goto-sibling (&optional previous)
16511 "Goto the next sibling, even if it is invisible.
16512 When PREVIOUS is set, go to the previous sibling instead. Returns t
16513 when a sibling was found. When none is found, return nil and don't
16514 move point."
16515 (let ((fun (if previous 're-search-backward 're-search-forward))
16516 (pos (point))
16517 (re (concat "^" outline-regexp))
16518 level l)
16519 (when (condition-case nil (org-back-to-heading t) (error nil))
16520 (setq level (funcall outline-level))
16521 (catch 'exit
16522 (or previous (forward-char 1))
16523 (while (funcall fun re nil t)
16524 (setq l (funcall outline-level))
16525 (when (< l level) (goto-char pos) (throw 'exit nil))
16526 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
16527 (goto-char pos)
16528 nil))))
16530 (defun org-show-siblings ()
16531 "Show all siblings of the current headline."
16532 (save-excursion
16533 (while (org-goto-sibling) (org-flag-heading nil)))
16534 (save-excursion
16535 (while (org-goto-sibling 'previous)
16536 (org-flag-heading nil))))
16538 (defun org-show-hidden-entry ()
16539 "Show an entry where even the heading is hidden."
16540 (save-excursion
16541 (org-show-entry)))
16543 (defun org-flag-heading (flag &optional entry)
16544 "Flag the current heading. FLAG non-nil means make invisible.
16545 When ENTRY is non-nil, show the entire entry."
16546 (save-excursion
16547 (org-back-to-heading t)
16548 ;; Check if we should show the entire entry
16549 (if entry
16550 (progn
16551 (org-show-entry)
16552 (save-excursion
16553 (and (outline-next-heading)
16554 (org-flag-heading nil))))
16555 (outline-flag-region (max (point-min) (1- (point)))
16556 (save-excursion (outline-end-of-heading) (point))
16557 flag))))
16559 (defun org-get-next-sibling ()
16560 "Move to next heading of the same level, and return point.
16561 If there is no such heading, return nil.
16562 This is like outline-next-sibling, but invisible headings are ok."
16563 (let ((level (funcall outline-level)))
16564 (outline-next-heading)
16565 (while (and (not (eobp)) (> (funcall outline-level) level))
16566 (outline-next-heading))
16567 (if (or (eobp) (< (funcall outline-level) level))
16569 (point))))
16571 (defun org-end-of-subtree (&optional invisible-OK to-heading)
16572 ;; This contains an exact copy of the original function, but it uses
16573 ;; `org-back-to-heading', to make it work also in invisible
16574 ;; trees. And is uses an invisible-OK argument.
16575 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
16576 ;; Furthermore, when used inside Org, finding the end of a large subtree
16577 ;; with many children and grandchildren etc, this can be much faster
16578 ;; than the outline version.
16579 (org-back-to-heading invisible-OK)
16580 (let ((first t)
16581 (level (funcall outline-level)))
16582 (if (and (org-mode-p) (< level 1000))
16583 ;; A true heading (not a plain list item), in Org-mode
16584 ;; This means we can easily find the end by looking
16585 ;; only for the right number of stars. Using a regexp to do
16586 ;; this is so much faster than using a Lisp loop.
16587 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
16588 (forward-char 1)
16589 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
16590 ;; something else, do it the slow way
16591 (while (and (not (eobp))
16592 (or first (> (funcall outline-level) level)))
16593 (setq first nil)
16594 (outline-next-heading)))
16595 (unless to-heading
16596 (if (memq (preceding-char) '(?\n ?\^M))
16597 (progn
16598 ;; Go to end of line before heading
16599 (forward-char -1)
16600 (if (memq (preceding-char) '(?\n ?\^M))
16601 ;; leave blank line before heading
16602 (forward-char -1))))))
16603 (point))
16605 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
16606 "Use Org version in org-mode, for dramatic speed-up."
16607 (if (eq major-mode 'org-mode)
16608 (progn
16609 (org-end-of-subtree nil t)
16610 (backward-char 1))
16611 ad-do-it))
16613 (defun org-forward-same-level (arg &optional invisible-ok)
16614 "Move forward to the arg'th subheading at same level as this one.
16615 Stop at the first and last subheadings of a superior heading."
16616 (interactive "p")
16617 (org-back-to-heading invisible-ok)
16618 (org-on-heading-p)
16619 (let* ((level (- (match-end 0) (match-beginning 0) 1))
16620 (re (format "^\\*\\{1,%d\\} " level))
16622 (forward-char 1)
16623 (while (> arg 0)
16624 (while (and (re-search-forward re nil 'move)
16625 (setq l (- (match-end 0) (match-beginning 0) 1))
16626 (= l level)
16627 (not invisible-ok)
16628 (org-invisible-p))
16629 (if (< l level) (setq arg 1)))
16630 (setq arg (1- arg)))
16631 (beginning-of-line 1)))
16633 (defun org-backward-same-level (arg &optional invisible-ok)
16634 "Move backward to the arg'th subheading at same level as this one.
16635 Stop at the first and last subheadings of a superior heading."
16636 (interactive "p")
16637 (org-back-to-heading)
16638 (org-on-heading-p)
16639 (let* ((level (- (match-end 0) (match-beginning 0) 1))
16640 (re (format "^\\*\\{1,%d\\} " level))
16642 (while (> arg 0)
16643 (while (and (re-search-backward re nil 'move)
16644 (setq l (- (match-end 0) (match-beginning 0) 1))
16645 (= l level)
16646 (not invisible-ok)
16647 (org-invisible-p))
16648 (if (< l level) (setq arg 1)))
16649 (setq arg (1- arg)))))
16651 (defun org-show-subtree ()
16652 "Show everything after this heading at deeper levels."
16653 (outline-flag-region
16654 (point)
16655 (save-excursion
16656 (outline-end-of-subtree) (outline-next-heading) (point))
16657 nil))
16659 (defun org-show-entry ()
16660 "Show the body directly following this heading.
16661 Show the heading too, if it is currently invisible."
16662 (interactive)
16663 (save-excursion
16664 (condition-case nil
16665 (progn
16666 (org-back-to-heading t)
16667 (outline-flag-region
16668 (max (point-min) (1- (point)))
16669 (save-excursion
16670 (if (re-search-forward
16671 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
16672 (match-beginning 1)
16673 (point-max)))
16674 nil)
16675 (org-cycle-hide-drawers 'children))
16676 (error nil))))
16678 (defun org-make-options-regexp (kwds &optional extra)
16679 "Make a regular expression for keyword lines."
16680 (concat
16682 "#?[ \t]*\\+\\("
16683 (mapconcat 'regexp-quote kwds "\\|")
16684 (if extra (concat "\\|" extra))
16685 "\\):[ \t]*"
16686 "\\(.*\\)"))
16688 ;; Make isearch reveal the necessary context
16689 (defun org-isearch-end ()
16690 "Reveal context after isearch exits."
16691 (when isearch-success ; only if search was successful
16692 (if (featurep 'xemacs)
16693 ;; Under XEmacs, the hook is run in the correct place,
16694 ;; we directly show the context.
16695 (org-show-context 'isearch)
16696 ;; In Emacs the hook runs *before* restoring the overlays.
16697 ;; So we have to use a one-time post-command-hook to do this.
16698 ;; (Emacs 22 has a special variable, see function `org-mode')
16699 (unless (and (boundp 'isearch-mode-end-hook-quit)
16700 isearch-mode-end-hook-quit)
16701 ;; Only when the isearch was not quitted.
16702 (org-add-hook 'post-command-hook 'org-isearch-post-command
16703 'append 'local)))))
16705 (defun org-isearch-post-command ()
16706 "Remove self from hook, and show context."
16707 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
16708 (org-show-context 'isearch))
16711 ;;;; Integration with and fixes for other packages
16713 ;;; Imenu support
16715 (defvar org-imenu-markers nil
16716 "All markers currently used by Imenu.")
16717 (make-variable-buffer-local 'org-imenu-markers)
16719 (defun org-imenu-new-marker (&optional pos)
16720 "Return a new marker for use by Imenu, and remember the marker."
16721 (let ((m (make-marker)))
16722 (move-marker m (or pos (point)))
16723 (push m org-imenu-markers)
16726 (defun org-imenu-get-tree ()
16727 "Produce the index for Imenu."
16728 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
16729 (setq org-imenu-markers nil)
16730 (let* ((n org-imenu-depth)
16731 (re (concat "^" outline-regexp))
16732 (subs (make-vector (1+ n) nil))
16733 (last-level 0)
16734 m level head)
16735 (save-excursion
16736 (save-restriction
16737 (widen)
16738 (goto-char (point-max))
16739 (while (re-search-backward re nil t)
16740 (setq level (org-reduced-level (funcall outline-level)))
16741 (when (<= level n)
16742 (looking-at org-complex-heading-regexp)
16743 (setq head (org-link-display-format
16744 (org-match-string-no-properties 4))
16745 m (org-imenu-new-marker))
16746 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
16747 (if (>= level last-level)
16748 (push (cons head m) (aref subs level))
16749 (push (cons head (aref subs (1+ level))) (aref subs level))
16750 (loop for i from (1+ level) to n do (aset subs i nil)))
16751 (setq last-level level)))))
16752 (aref subs 1)))
16754 (eval-after-load "imenu"
16755 '(progn
16756 (add-hook 'imenu-after-jump-hook
16757 (lambda ()
16758 (if (eq major-mode 'org-mode)
16759 (org-show-context 'org-goto))))))
16761 (defun org-link-display-format (link)
16762 "Replace a link with either the description, or the link target
16763 if no description is present"
16764 (save-match-data
16765 (if (string-match org-bracket-link-analytic-regexp link)
16766 (replace-match (or (match-string 5 link)
16767 (concat (match-string 1 link)
16768 (match-string 3 link)))
16769 nil nil link)
16770 link)))
16772 ;; Speedbar support
16774 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
16775 "Overlay marking the agenda restriction line in speedbar.")
16776 (org-overlay-put org-speedbar-restriction-lock-overlay
16777 'face 'org-agenda-restriction-lock)
16778 (org-overlay-put org-speedbar-restriction-lock-overlay
16779 'help-echo "Agendas are currently limited to this item.")
16780 (org-detach-overlay org-speedbar-restriction-lock-overlay)
16782 (defun org-speedbar-set-agenda-restriction ()
16783 "Restrict future agenda commands to the location at point in speedbar.
16784 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
16785 (interactive)
16786 (require 'org-agenda)
16787 (let (p m tp np dir txt)
16788 (cond
16789 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16790 'org-imenu t))
16791 (setq m (get-text-property p 'org-imenu-marker))
16792 (save-excursion
16793 (save-restriction
16794 (set-buffer (marker-buffer m))
16795 (goto-char m)
16796 (org-agenda-set-restriction-lock 'subtree))))
16797 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16798 'speedbar-function 'speedbar-find-file))
16799 (setq tp (previous-single-property-change
16800 (1+ p) 'speedbar-function)
16801 np (next-single-property-change
16802 tp 'speedbar-function)
16803 dir (speedbar-line-directory)
16804 txt (buffer-substring-no-properties (or tp (point-min))
16805 (or np (point-max))))
16806 (save-excursion
16807 (save-restriction
16808 (set-buffer (find-file-noselect
16809 (let ((default-directory dir))
16810 (expand-file-name txt))))
16811 (unless (org-mode-p)
16812 (error "Cannot restrict to non-Org-mode file"))
16813 (org-agenda-set-restriction-lock 'file))))
16814 (t (error "Don't know how to restrict Org-mode's agenda")))
16815 (org-move-overlay org-speedbar-restriction-lock-overlay
16816 (point-at-bol) (point-at-eol))
16817 (setq current-prefix-arg nil)
16818 (org-agenda-maybe-redo)))
16820 (eval-after-load "speedbar"
16821 '(progn
16822 (speedbar-add-supported-extension ".org")
16823 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
16824 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
16825 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
16826 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16827 (add-hook 'speedbar-visiting-tag-hook
16828 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
16831 ;;; Fixes and Hacks for problems with other packages
16833 ;; Make flyspell not check words in links, to not mess up our keymap
16834 (defun org-mode-flyspell-verify ()
16835 "Don't let flyspell put overlays at active buttons."
16836 (and (not (get-text-property (point) 'keymap))
16837 (not (get-text-property (point) 'org-no-flyspell))))
16839 (defun org-remove-flyspell-overlays-in (beg end)
16840 "Remove flyspell overlays in region."
16841 (and (org-bound-and-true-p flyspell-mode)
16842 (fboundp 'flyspell-delete-region-overlays)
16843 (flyspell-delete-region-overlays beg end))
16844 (add-text-properties beg end '(org-no-flyspell t)))
16846 ;; Make `bookmark-jump' show the jump location if it was hidden.
16847 (eval-after-load "bookmark"
16848 '(if (boundp 'bookmark-after-jump-hook)
16849 ;; We can use the hook
16850 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
16851 ;; Hook not available, use advice
16852 (defadvice bookmark-jump (after org-make-visible activate)
16853 "Make the position visible."
16854 (org-bookmark-jump-unhide))))
16856 ;; Make sure saveplace show the location if it was hidden
16857 (eval-after-load "saveplace"
16858 '(defadvice save-place-find-file-hook (after org-make-visible activate)
16859 "Make the position visible."
16860 (org-bookmark-jump-unhide)))
16862 (defun org-bookmark-jump-unhide ()
16863 "Unhide the current position, to show the bookmark location."
16864 (and (org-mode-p)
16865 (or (org-invisible-p)
16866 (save-excursion (goto-char (max (point-min) (1- (point))))
16867 (org-invisible-p)))
16868 (org-show-context 'bookmark-jump)))
16870 ;; Make session.el ignore our circular variable
16871 (eval-after-load "session"
16872 '(add-to-list 'session-globals-exclude 'org-mark-ring))
16874 ;;;; Experimental code
16876 (defun org-closed-in-range ()
16877 "Sparse tree of items closed in a certain time range.
16878 Still experimental, may disappear in the future."
16879 (interactive)
16880 ;; Get the time interval from the user.
16881 (let* ((time1 (time-to-seconds
16882 (org-read-date nil 'to-time nil "Starting date: ")))
16883 (time2 (time-to-seconds
16884 (org-read-date nil 'to-time nil "End date:")))
16885 ;; callback function
16886 (callback (lambda ()
16887 (let ((time
16888 (time-to-seconds
16889 (apply 'encode-time
16890 (org-parse-time-string
16891 (match-string 1))))))
16892 ;; check if time in interval
16893 (and (>= time time1) (<= time time2))))))
16894 ;; make tree, check each match with the callback
16895 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
16897 ;;;; Finish up
16899 (provide 'org)
16901 (run-hooks 'org-load-hook)
16903 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
16905 ;;; org.el ends here