Allow normal lists completion also when using ido.el
[org-mode/org-tableheadings.git] / lisp / org.el
blob3b3a6ba6a6b6ab49f5916072202438e02090e873
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.28trans
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.28trans"
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 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
212 (defcustom org-support-shift-select nil
213 "Non-nil means, make shift-cursor commands select text when possible.
215 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
216 selecting a region, or enlarge thusly regions started in this way.
217 In Org-mode, in special contexts, these same keys are used for other
218 purposes, important enough to compete with shift selection. Org tries
219 to balance these needs by supporting `shift-select-mode' outside these
220 special contexts, under control of this variable.
222 The default of this variable is nil, to avoid confusing behavior. Shifted
223 cursor keys will then execute Org commands in the following contexts:
224 - on a headline, changing TODO state (left/right) and priority (up/down)
225 - on a time stamp, changing the time
226 - in a plain list item, changing the bullet type
227 - in a property definition line, switching between allowed values
228 - in the BEGIN line of a clock table (changing the time block).
229 Outside these contexts, the commands will throw an error.
231 When this variable is t and the cursor is not in a special context,
232 Org-mode will support shift-selection for making and enlarging regions.
233 To make this more effective, the bullet cycling will no longer happen
234 anywhere in an item line, but only if the cursor is exactly on the bullet.
236 If you set this variable to the symbol `always', then the keys
237 will not be special in headlines, property lines, and item lines, to make
238 shift selection work there as well. If this is what you want, you can
239 use the following alternative commands: `C-c C-t' and `C-c ,' to
240 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
241 TODO sets, `C-c -' to cycle item bullet types, and properties can be
242 edited by hand or in column view.
244 However, when the cursor is on a timestamp, shift-cursor commands
245 will still edit the time stamp - this is just too good to give up.
247 XEmacs user should have this variable set to nil, because shift-select-mode
248 is Emacs 23 only."
249 :group 'org
250 :type '(choice
251 (const :tag "Never" nil)
252 (const :tag "When outside special context" t)
253 (const :tag "Everywhere except timestamps" always)))
255 (defgroup org-startup nil
256 "Options concerning startup of Org-mode."
257 :tag "Org Startup"
258 :group 'org)
260 (defcustom org-startup-folded t
261 "Non-nil means, entering Org-mode will switch to OVERVIEW.
262 This can also be configured on a per-file basis by adding one of
263 the following lines anywhere in the buffer:
265 #+STARTUP: fold
266 #+STARTUP: nofold
267 #+STARTUP: content"
268 :group 'org-startup
269 :type '(choice
270 (const :tag "nofold: show all" nil)
271 (const :tag "fold: overview" t)
272 (const :tag "content: all headlines" content)))
274 (defcustom org-startup-truncated t
275 "Non-nil means, entering Org-mode will set `truncate-lines'.
276 This is useful since some lines containing links can be very long and
277 uninteresting. Also tables look terrible when wrapped."
278 :group 'org-startup
279 :type 'boolean)
281 (defcustom org-startup-indented nil
282 "Non-nil means, turn on `org-indent-mode' on startup.
283 This can also be configured on a per-file basis by adding one of
284 the following lines anywhere in the buffer:
286 #+STARTUP: indent
287 #+STARTUP: noindent"
288 :group 'org-structure
289 :type '(choice
290 (const :tag "Not" nil)
291 (const :tag "Globally (slow on startup in large files)" t)))
293 (defcustom org-startup-align-all-tables nil
294 "Non-nil means, align all tables when visiting a file.
295 This is useful when the column width in tables is forced with <N> cookies
296 in table fields. Such tables will look correct only after the first re-align.
297 This can also be configured on a per-file basis by adding one of
298 the following lines anywhere in the buffer:
299 #+STARTUP: align
300 #+STARTUP: noalign"
301 :group 'org-startup
302 :type 'boolean)
304 (defcustom org-insert-mode-line-in-empty-file nil
305 "Non-nil means insert the first line setting Org-mode in empty files.
306 When the function `org-mode' is called interactively in an empty file, this
307 normally means that the file name does not automatically trigger Org-mode.
308 To ensure that the file will always be in Org-mode in the future, a
309 line enforcing Org-mode will be inserted into the buffer, if this option
310 has been set."
311 :group 'org-startup
312 :type 'boolean)
314 (defcustom org-replace-disputed-keys nil
315 "Non-nil means use alternative key bindings for some keys.
316 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
317 These keys are also used by other packages like shift-selection-mode'
318 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
319 If you want to use Org-mode together with one of these other modes,
320 or more generally if you would like to move some Org-mode commands to
321 other keys, set this variable and configure the keys with the variable
322 `org-disputed-keys'.
324 This option is only relevant at load-time of Org-mode, and must be set
325 *before* org.el is loaded. Changing it requires a restart of Emacs to
326 become effective."
327 :group 'org-startup
328 :type 'boolean)
330 (defcustom org-use-extra-keys nil
331 "Non-nil means use extra key sequence definitions for certain
332 commands. This happens automatically if you run XEmacs or if
333 window-system is nil. This variable lets you do the same
334 manually. You must set it before loading org.
336 Example: on Carbon Emacs 22 running graphically, with an external
337 keyboard on a Powerbook, the default way of setting M-left might
338 not work for either Alt or ESC. Setting this variable will make
339 it work for ESC."
340 :group 'org-startup
341 :type 'boolean)
343 (if (fboundp 'defvaralias)
344 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
346 (defcustom org-disputed-keys
347 '(([(shift up)] . [(meta p)])
348 ([(shift down)] . [(meta n)])
349 ([(shift left)] . [(meta -)])
350 ([(shift right)] . [(meta +)])
351 ([(control shift right)] . [(meta shift +)])
352 ([(control shift left)] . [(meta shift -)]))
353 "Keys for which Org-mode and other modes compete.
354 This is an alist, cars are the default keys, second element specifies
355 the alternative to use when `org-replace-disputed-keys' is t.
357 Keys can be specified in any syntax supported by `define-key'.
358 The value of this option takes effect only at Org-mode's startup,
359 therefore you'll have to restart Emacs to apply it after changing."
360 :group 'org-startup
361 :type 'alist)
363 (defun org-key (key)
364 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
365 Or return the original if not disputed."
366 (if org-replace-disputed-keys
367 (let* ((nkey (key-description key))
368 (x (org-find-if (lambda (x)
369 (equal (key-description (car x)) nkey))
370 org-disputed-keys)))
371 (if x (cdr x) key))
372 key))
374 (defun org-find-if (predicate seq)
375 (catch 'exit
376 (while seq
377 (if (funcall predicate (car seq))
378 (throw 'exit (car seq))
379 (pop seq)))))
381 (defun org-defkey (keymap key def)
382 "Define a key, possibly translated, as returned by `org-key'."
383 (define-key keymap (org-key key) def))
385 (defcustom org-ellipsis nil
386 "The ellipsis to use in the Org-mode outline.
387 When nil, just use the standard three dots. When a string, use that instead,
388 When a face, use the standard 3 dots, but with the specified face.
389 The change affects only Org-mode (which will then use its own display table).
390 Changing this requires executing `M-x org-mode' in a buffer to become
391 effective."
392 :group 'org-startup
393 :type '(choice (const :tag "Default" nil)
394 (face :tag "Face" :value org-warning)
395 (string :tag "String" :value "...#")))
397 (defvar org-display-table nil
398 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
400 (defgroup org-keywords nil
401 "Keywords in Org-mode."
402 :tag "Org Keywords"
403 :group 'org)
405 (defcustom org-deadline-string "DEADLINE:"
406 "String to mark deadline entries.
407 A deadline is this string, followed by a time stamp. Should be a word,
408 terminated by a colon. You can insert a schedule keyword and
409 a timestamp with \\[org-deadline].
410 Changes become only effective after restarting Emacs."
411 :group 'org-keywords
412 :type 'string)
414 (defcustom org-scheduled-string "SCHEDULED:"
415 "String to mark scheduled TODO entries.
416 A schedule is this string, followed by a time stamp. Should be a word,
417 terminated by a colon. You can insert a schedule keyword and
418 a timestamp with \\[org-schedule].
419 Changes become only effective after restarting Emacs."
420 :group 'org-keywords
421 :type 'string)
423 (defcustom org-closed-string "CLOSED:"
424 "String used as the prefix for timestamps logging closing a TODO entry."
425 :group 'org-keywords
426 :type 'string)
428 (defcustom org-clock-string "CLOCK:"
429 "String used as prefix for timestamps clocking work hours on an item."
430 :group 'org-keywords
431 :type 'string)
433 (defcustom org-comment-string "COMMENT"
434 "Entries starting with this keyword will never be exported.
435 An entry can be toggled between COMMENT and normal with
436 \\[org-toggle-comment].
437 Changes become only effective after restarting Emacs."
438 :group 'org-keywords
439 :type 'string)
441 (defcustom org-quote-string "QUOTE"
442 "Entries starting with this keyword will be exported in fixed-width font.
443 Quoting applies only to the text in the entry following the headline, and does
444 not extend beyond the next headline, even if that is lower level.
445 An entry can be toggled between QUOTE and normal with
446 \\[org-toggle-fixed-width-section]."
447 :group 'org-keywords
448 :type 'string)
450 (defconst org-repeat-re
451 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
452 "Regular expression for specifying repeated events.
453 After a match, group 1 contains the repeat expression.")
455 (defgroup org-structure nil
456 "Options concerning the general structure of Org-mode files."
457 :tag "Org Structure"
458 :group 'org)
460 (defgroup org-reveal-location nil
461 "Options about how to make context of a location visible."
462 :tag "Org Reveal Location"
463 :group 'org-structure)
465 (defconst org-context-choice
466 '(choice
467 (const :tag "Always" t)
468 (const :tag "Never" nil)
469 (repeat :greedy t :tag "Individual contexts"
470 (cons
471 (choice :tag "Context"
472 (const agenda)
473 (const org-goto)
474 (const occur-tree)
475 (const tags-tree)
476 (const link-search)
477 (const mark-goto)
478 (const bookmark-jump)
479 (const isearch)
480 (const default))
481 (boolean))))
482 "Contexts for the reveal options.")
484 (defcustom org-show-hierarchy-above '((default . t))
485 "Non-nil means, show full hierarchy when revealing a location.
486 Org-mode often shows locations in an org-mode file which might have
487 been invisible before. When this is set, the hierarchy of headings
488 above the exposed location is shown.
489 Turning this off for example for sparse trees makes them very compact.
490 Instead of t, this can also be an alist specifying this option for different
491 contexts. Valid contexts are
492 agenda when exposing an entry from the agenda
493 org-goto when using the command `org-goto' on key C-c C-j
494 occur-tree when using the command `org-occur' on key C-c /
495 tags-tree when constructing a sparse tree based on tags matches
496 link-search when exposing search matches associated with a link
497 mark-goto when exposing the jump goal of a mark
498 bookmark-jump when exposing a bookmark location
499 isearch when exiting from an incremental search
500 default default for all contexts not set explicitly"
501 :group 'org-reveal-location
502 :type org-context-choice)
504 (defcustom org-show-following-heading '((default . nil))
505 "Non-nil means, show following heading when revealing a location.
506 Org-mode often shows locations in an org-mode file which might have
507 been invisible before. When this is set, the heading following the
508 match is shown.
509 Turning this off for example for sparse trees makes them very compact,
510 but makes it harder to edit the location of the match. In such a case,
511 use the command \\[org-reveal] to show more context.
512 Instead of t, this can also be an alist specifying this option for different
513 contexts. See `org-show-hierarchy-above' for valid contexts."
514 :group 'org-reveal-location
515 :type org-context-choice)
517 (defcustom org-show-siblings '((default . nil) (isearch t))
518 "Non-nil means, show all sibling heading when revealing a location.
519 Org-mode often shows locations in an org-mode file which might have
520 been invisible before. When this is set, the sibling of the current entry
521 heading are all made visible. If `org-show-hierarchy-above' is t,
522 the same happens on each level of the hierarchy above the current entry.
524 By default this is on for the isearch context, off for all other contexts.
525 Turning this off for example for sparse trees makes them very compact,
526 but makes it harder to edit the location of the match. In such a case,
527 use the command \\[org-reveal] to show more context.
528 Instead of t, this can also be an alist specifying this option for different
529 contexts. See `org-show-hierarchy-above' for valid contexts."
530 :group 'org-reveal-location
531 :type org-context-choice)
533 (defcustom org-show-entry-below '((default . nil))
534 "Non-nil means, show the entry below a headline when revealing a location.
535 Org-mode often shows locations in an org-mode file which might have
536 been invisible before. When this is set, the text below the headline that is
537 exposed is also shown.
539 By default this is off for all contexts.
540 Instead of t, this can also be an alist specifying this option for different
541 contexts. See `org-show-hierarchy-above' for valid contexts."
542 :group 'org-reveal-location
543 :type org-context-choice)
545 (defcustom org-indirect-buffer-display 'other-window
546 "How should indirect tree buffers be displayed?
547 This applies to indirect buffers created with the commands
548 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
549 Valid values are:
550 current-window Display in the current window
551 other-window Just display in another window.
552 dedicated-frame Create one new frame, and re-use it each time.
553 new-frame Make a new frame each time. Note that in this case
554 previously-made indirect buffers are kept, and you need to
555 kill these buffers yourself."
556 :group 'org-structure
557 :group 'org-agenda-windows
558 :type '(choice
559 (const :tag "In current window" current-window)
560 (const :tag "In current frame, other window" other-window)
561 (const :tag "Each time a new frame" new-frame)
562 (const :tag "One dedicated frame" dedicated-frame)))
564 (defgroup org-cycle nil
565 "Options concerning visibility cycling in Org-mode."
566 :tag "Org Cycle"
567 :group 'org-structure)
569 (defcustom org-cycle-skip-children-state-if-no-children t
570 "Non-nil means, skip CHILDREN state in entries that don't have any."
571 :group 'org-cycle
572 :type 'boolean)
574 (defcustom org-cycle-max-level nil
575 "Maximum level which should still be subject to visibility cycling.
576 Levels higher than this will, for cycling, be treated as text, not a headline.
577 When `org-odd-levels-only' is set, a value of N in this variable actually
578 means 2N-1 stars as the limiting headline.
579 When nil, cycle all levels.
580 Note that the limiting level of cycling is also influenced by
581 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
582 `org-inlinetask-min-level' is, cycling will be limited to levels one less
583 than its value."
584 :group 'org-cycle
585 :type '(choice
586 (const :tag "No limit" nil)
587 (integer :tag "Maximum level")))
589 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
590 "Names of drawers. Drawers are not opened by cycling on the headline above.
591 Drawers only open with a TAB on the drawer line itself. A drawer looks like
592 this:
593 :DRAWERNAME:
594 .....
595 :END:
596 The drawer \"PROPERTIES\" is special for capturing properties through
597 the property API.
599 Drawers can be defined on the per-file basis with a line like:
601 #+DRAWERS: HIDDEN STATE PROPERTIES"
602 :group 'org-structure
603 :group 'org-cycle
604 :type '(repeat (string :tag "Drawer Name")))
606 (defcustom org-hide-block-startup nil
607 "Non-nil means, , entering Org-mode will fold all blocks.
608 This can also be set in on a per-file basis with
610 #+STARTUP: hideblocks
611 #+STARTUP: showblocks"
612 :group 'org-startup
613 :group 'org-cycle
614 :type 'boolean)
616 (defcustom org-cycle-global-at-bob nil
617 "Cycle globally if cursor is at beginning of buffer and not at a headline.
618 This makes it possible to do global cycling without having to use S-TAB or
619 C-u TAB. For this special case to work, the first line of the buffer
620 must not be a headline - it may be empty or some other text. When used in
621 this way, `org-cycle-hook' is disables temporarily, to make sure the
622 cursor stays at the beginning of the buffer.
623 When this option is nil, don't do anything special at the beginning
624 of the buffer."
625 :group 'org-cycle
626 :type 'boolean)
628 (defcustom org-cycle-emulate-tab t
629 "Where should `org-cycle' emulate TAB.
630 nil Never
631 white Only in completely white lines
632 whitestart Only at the beginning of lines, before the first non-white char
633 t Everywhere except in headlines
634 exc-hl-bol Everywhere except at the start of a headline
635 If TAB is used in a place where it does not emulate TAB, the current subtree
636 visibility is cycled."
637 :group 'org-cycle
638 :type '(choice (const :tag "Never" nil)
639 (const :tag "Only in completely white lines" white)
640 (const :tag "Before first char in a line" whitestart)
641 (const :tag "Everywhere except in headlines" t)
642 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
645 (defcustom org-cycle-separator-lines 2
646 "Number of empty lines needed to keep an empty line between collapsed trees.
647 If you leave an empty line between the end of a subtree and the following
648 headline, this empty line is hidden when the subtree is folded.
649 Org-mode will leave (exactly) one empty line visible if the number of
650 empty lines is equal or larger to the number given in this variable.
651 So the default 2 means, at least 2 empty lines after the end of a subtree
652 are needed to produce free space between a collapsed subtree and the
653 following headline.
655 Special case: when 0, never leave empty lines in collapsed view."
656 :group 'org-cycle
657 :type 'integer)
658 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
660 (defcustom org-pre-cycle-hook nil
661 "Hook that is run before visibility cycling is happening.
662 The function(s) in this hook must accept a single argument which indicates
663 the new state that will be set right after running this hook. The
664 argument is a symbol. Before a global state change, it can have the values
665 `overview', `content', or `all'. Before a local state change, it can have
666 the values `folded', `children', or `subtree'."
667 :group 'org-cycle
668 :type 'hook)
670 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
671 org-cycle-hide-drawers
672 org-cycle-show-empty-lines
673 org-optimize-window-after-visibility-change)
674 "Hook that is run after `org-cycle' has changed the buffer visibility.
675 The function(s) in this hook must accept a single argument which indicates
676 the new state that was set by the most recent `org-cycle' command. The
677 argument is a symbol. After a global state change, it can have the values
678 `overview', `content', or `all'. After a local state change, it can have
679 the values `folded', `children', or `subtree'."
680 :group 'org-cycle
681 :type 'hook)
683 (defgroup org-edit-structure nil
684 "Options concerning structure editing in Org-mode."
685 :tag "Org Edit Structure"
686 :group 'org-structure)
688 (defcustom org-odd-levels-only nil
689 "Non-nil means, skip even levels and only use odd levels for the outline.
690 This has the effect that two stars are being added/taken away in
691 promotion/demotion commands. It also influences how levels are
692 handled by the exporters.
693 Changing it requires restart of `font-lock-mode' to become effective
694 for fontification also in regions already fontified.
695 You may also set this on a per-file basis by adding one of the following
696 lines to the buffer:
698 #+STARTUP: odd
699 #+STARTUP: oddeven"
700 :group 'org-edit-structure
701 :group 'org-font-lock
702 :type 'boolean)
704 (defcustom org-adapt-indentation t
705 "Non-nil means, adapt indentation to outline node level.
707 When this variable is set, Org assumes that you write outlines by
708 indenting text in each node to align with the headline (after the stars).
709 The following issues are influenced by this variable:
711 - When this is set and the *entire* text in an entry is indented, the
712 indentation is increased by one space in a demotion command, and
713 decreased by one in a promotion command. If any line in the entry
714 body starts with text at column 0, indentation is not changed at all.
716 - Property drawers and planning information is inserted indented when
717 this variable s set. When nil, they will not be indented.
719 - TAB indents a line relative to context. The lines below a headline
720 will be indented when this variable is set.
722 Note that this is all about true indentation, by adding and removing
723 space characters. See also `org-indent.el' which does level-dependent
724 indentation in a virtual way, i.e. at display time in Emacs."
725 :group 'org-edit-structure
726 :type 'boolean)
728 (defcustom org-special-ctrl-a/e nil
729 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
731 When t, `C-a' will bring back the cursor to the beginning of the
732 headline text, i.e. after the stars and after a possible TODO keyword.
733 In an item, this will be the position after the bullet.
734 When the cursor is already at that position, another `C-a' will bring
735 it to the beginning of the line.
737 `C-e' will jump to the end of the headline, ignoring the presence of tags
738 in the headline. A second `C-e' will then jump to the true end of the
739 line, after any tags.
741 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
742 going to the true line boundary first. Only a directly following, identical
743 keypress will bring the cursor to the special positions.
745 This may also be a cons cell where the behavior for `C-a' and `C-e' is
746 set separately."
747 :group 'org-edit-structure
748 :type '(choice
749 (const :tag "off" nil)
750 (const :tag "after stars/bullet and before tags first" t)
751 (const :tag "true line boundary first" reversed)
752 (cons :tag "Set C-a and C-e separately"
753 (choice :tag "Special C-a"
754 (const :tag "off" nil)
755 (const :tag "after stars/bullet first" t)
756 (const :tag "before stars/bullet first" reversed))
757 (choice :tag "Special C-e"
758 (const :tag "off" nil)
759 (const :tag "before tags first" t)
760 (const :tag "after tags first" reversed)))))
761 (if (fboundp 'defvaralias)
762 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
764 (defcustom org-special-ctrl-k nil
765 "Non-nil means `C-k' will behave specially in headlines.
766 When nil, `C-k' will call the default `kill-line' command.
767 When t, the following will happen while the cursor is in the headline:
769 - When the cursor is at the beginning of a headline, kill the entire
770 line and possible the folded subtree below the line.
771 - When in the middle of the headline text, kill the headline up to the tags.
772 - When after the headline text, kill the tags."
773 :group 'org-edit-structure
774 :type 'boolean)
776 (defcustom org-yank-folded-subtrees t
777 "Non-nil means, when yanking subtrees, fold them.
778 If the kill is a single subtree, or a sequence of subtrees, i.e. if
779 it starts with a heading and all other headings in it are either children
780 or siblings, then fold all the subtrees. However, do this only if no
781 text after the yank would be swallowed into a folded tree by this action."
782 :group 'org-edit-structure
783 :type 'boolean)
785 (defcustom org-yank-adjusted-subtrees nil
786 "Non-nil means, when yanking subtrees, adjust the level.
787 With this setting, `org-paste-subtree' is used to insert the subtree, see
788 this function for details."
789 :group 'org-edit-structure
790 :type 'boolean)
792 (defcustom org-M-RET-may-split-line '((default . t))
793 "Non-nil means, M-RET will split the line at the cursor position.
794 When nil, it will go to the end of the line before making a
795 new line.
796 You may also set this option in a different way for different
797 contexts. Valid contexts are:
799 headline when creating a new headline
800 item when creating a new item
801 table in a table field
802 default the value to be used for all contexts not explicitly
803 customized"
804 :group 'org-structure
805 :group 'org-table
806 :type '(choice
807 (const :tag "Always" t)
808 (const :tag "Never" nil)
809 (repeat :greedy t :tag "Individual contexts"
810 (cons
811 (choice :tag "Context"
812 (const headline)
813 (const item)
814 (const table)
815 (const default))
816 (boolean)))))
819 (defcustom org-insert-heading-respect-content nil
820 "Non-nil means, insert new headings after the current subtree.
821 When nil, the new heading is created directly after the current line.
822 The commands \\[org-insert-heading-respect-content] and
823 \\[org-insert-todo-heading-respect-content] turn this variable on
824 for the duration of the command."
825 :group 'org-structure
826 :type 'boolean)
828 (defcustom org-blank-before-new-entry '((heading . auto)
829 (plain-list-item . auto))
830 "Should `org-insert-heading' leave a blank line before new heading/item?
831 The value is an alist, with `heading' and `plain-list-item' as car,
832 and a boolean flag as cdr. For plain lists, if the variable
833 `org-empty-line-terminates-plain-lists' is set, the setting here
834 is ignored and no empty line is inserted, to keep the list in tact."
835 :group 'org-edit-structure
836 :type '(list
837 (cons (const heading)
838 (choice (const :tag "Never" nil)
839 (const :tag "Always" t)
840 (const :tag "Auto" auto)))
841 (cons (const plain-list-item)
842 (choice (const :tag "Never" nil)
843 (const :tag "Always" t)
844 (const :tag "Auto" auto)))))
846 (defcustom org-insert-heading-hook nil
847 "Hook being run after inserting a new heading."
848 :group 'org-edit-structure
849 :type 'hook)
851 (defcustom org-enable-fixed-width-editor t
852 "Non-nil means, lines starting with \":\" are treated as fixed-width.
853 This currently only means, they are never auto-wrapped.
854 When nil, such lines will be treated like ordinary lines.
855 See also the QUOTE keyword."
856 :group 'org-edit-structure
857 :type 'boolean)
860 (defcustom org-goto-auto-isearch t
861 "Non-nil means, typing characters in org-goto starts incremental search."
862 :group 'org-edit-structure
863 :type 'boolean)
865 (defgroup org-sparse-trees nil
866 "Options concerning sparse trees in Org-mode."
867 :tag "Org Sparse Trees"
868 :group 'org-structure)
870 (defcustom org-highlight-sparse-tree-matches t
871 "Non-nil means, highlight all matches that define a sparse tree.
872 The highlights will automatically disappear the next time the buffer is
873 changed by an edit command."
874 :group 'org-sparse-trees
875 :type 'boolean)
877 (defcustom org-remove-highlights-with-change t
878 "Non-nil means, any change to the buffer will remove temporary highlights.
879 Such highlights are created by `org-occur' and `org-clock-display'.
880 When nil, `C-c C-c needs to be used to get rid of the highlights.
881 The highlights created by `org-preview-latex-fragment' always need
882 `C-c C-c' to be removed."
883 :group 'org-sparse-trees
884 :group 'org-time
885 :type 'boolean)
888 (defcustom org-occur-hook '(org-first-headline-recenter)
889 "Hook that is run after `org-occur' has constructed a sparse tree.
890 This can be used to recenter the window to show as much of the structure
891 as possible."
892 :group 'org-sparse-trees
893 :type 'hook)
895 (defgroup org-imenu-and-speedbar nil
896 "Options concerning imenu and speedbar in Org-mode."
897 :tag "Org Imenu and Speedbar"
898 :group 'org-structure)
900 (defcustom org-imenu-depth 2
901 "The maximum level for Imenu access to Org-mode headlines.
902 This also applied for speedbar access."
903 :group 'org-imenu-and-speedbar
904 :type 'integer)
906 (defgroup org-table nil
907 "Options concerning tables in Org-mode."
908 :tag "Org Table"
909 :group 'org)
911 (defcustom org-enable-table-editor 'optimized
912 "Non-nil means, lines starting with \"|\" are handled by the table editor.
913 When nil, such lines will be treated like ordinary lines.
915 When equal to the symbol `optimized', the table editor will be optimized to
916 do the following:
917 - Automatic overwrite mode in front of whitespace in table fields.
918 This makes the structure of the table stay in tact as long as the edited
919 field does not exceed the column width.
920 - Minimize the number of realigns. Normally, the table is aligned each time
921 TAB or RET are pressed to move to another field. With optimization this
922 happens only if changes to a field might have changed the column width.
923 Optimization requires replacing the functions `self-insert-command',
924 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
925 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
926 very good at guessing when a re-align will be necessary, but you can always
927 force one with \\[org-ctrl-c-ctrl-c].
929 If you would like to use the optimized version in Org-mode, but the
930 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
932 This variable can be used to turn on and off the table editor during a session,
933 but in order to toggle optimization, a restart is required.
935 See also the variable `org-table-auto-blank-field'."
936 :group 'org-table
937 :type '(choice
938 (const :tag "off" nil)
939 (const :tag "on" t)
940 (const :tag "on, optimized" optimized)))
942 (defcustom org-self-insert-cluster-for-undo t
943 "Non-nil means cluster self-insert commands for undo when possible.
944 If this is set, then, like in the Emacs command loop, 20 consequtive
945 characters will be undone together.
946 This is configurable, because there is some impact on typing performance."
947 :group 'org-table
948 :type 'boolean)
950 (defcustom org-table-tab-recognizes-table.el t
951 "Non-nil means, TAB will automatically notice a table.el table.
952 When it sees such a table, it moves point into it and - if necessary -
953 calls `table-recognize-table'."
954 :group 'org-table-editing
955 :type 'boolean)
957 (defgroup org-link nil
958 "Options concerning links in Org-mode."
959 :tag "Org Link"
960 :group 'org)
962 (defvar org-link-abbrev-alist-local nil
963 "Buffer-local version of `org-link-abbrev-alist', which see.
964 The value of this is taken from the #+LINK lines.")
965 (make-variable-buffer-local 'org-link-abbrev-alist-local)
967 (defcustom org-link-abbrev-alist nil
968 "Alist of link abbreviations.
969 The car of each element is a string, to be replaced at the start of a link.
970 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
971 links in Org-mode buffers can have an optional tag after a double colon, e.g.
973 [[linkkey:tag][description]]
975 The 'linkkey' must be a word word, starting with a letter, followed
976 by letters, numbers, '-' or '_'.
978 If REPLACE is a string, the tag will simply be appended to create the link.
979 If the string contains \"%s\", the tag will be inserted there. Alternatively,
980 the placeholder \"%h\" will cause a url-encoded version of the tag to
981 be inserted at that point (see the function `url-hexify-string').
983 REPLACE may also be a function that will be called with the tag as the
984 only argument to create the link, which should be returned as a string.
986 See the manual for examples."
987 :group 'org-link
988 :type '(repeat
989 (cons
990 (string :tag "Protocol")
991 (choice
992 (string :tag "Format")
993 (function)))))
995 (defcustom org-descriptive-links t
996 "Non-nil means, hide link part and only show description of bracket links.
997 Bracket links are like [[link][description]]. This variable sets the initial
998 state in new org-mode buffers. The setting can then be toggled on a
999 per-buffer basis from the Org->Hyperlinks menu."
1000 :group 'org-link
1001 :type 'boolean)
1003 (defcustom org-link-file-path-type 'adaptive
1004 "How the path name in file links should be stored.
1005 Valid values are:
1007 relative Relative to the current directory, i.e. the directory of the file
1008 into which the link is being inserted.
1009 absolute Absolute path, if possible with ~ for home directory.
1010 noabbrev Absolute path, no abbreviation of home directory.
1011 adaptive Use relative path for files in the current directory and sub-
1012 directories of it. For other files, use an absolute path."
1013 :group 'org-link
1014 :type '(choice
1015 (const relative)
1016 (const absolute)
1017 (const noabbrev)
1018 (const adaptive)))
1020 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1021 "Types of links that should be activated in Org-mode files.
1022 This is a list of symbols, each leading to the activation of a certain link
1023 type. In principle, it does not hurt to turn on most link types - there may
1024 be a small gain when turning off unused link types. The types are:
1026 bracket The recommended [[link][description]] or [[link]] links with hiding.
1027 angular Links in angular brackets that may contain whitespace like
1028 <bbdb:Carsten Dominik>.
1029 plain Plain links in normal text, no whitespace, like http://google.com.
1030 radio Text that is matched by a radio target, see manual for details.
1031 tag Tag settings in a headline (link to tag search).
1032 date Time stamps (link to calendar).
1033 footnote Footnote labels.
1035 Changing this variable requires a restart of Emacs to become effective."
1036 :group 'org-link
1037 :type '(set :greedy t
1038 (const :tag "Double bracket links (new style)" bracket)
1039 (const :tag "Angular bracket links (old style)" angular)
1040 (const :tag "Plain text links" plain)
1041 (const :tag "Radio target matches" radio)
1042 (const :tag "Tags" tag)
1043 (const :tag "Timestamps" date)
1044 (const :tag "Footnotes" footnote)))
1046 (defcustom org-make-link-description-function nil
1047 "Function to use to generate link descriptions from links. If
1048 nil the link location will be used. This function must take two
1049 parameters; the first is the link and the second the description
1050 org-insert-link has generated, and should return the description
1051 to use."
1052 :group 'org-link
1053 :type 'function)
1055 (defgroup org-link-store nil
1056 "Options concerning storing links in Org-mode."
1057 :tag "Org Store Link"
1058 :group 'org-link)
1060 (defcustom org-email-link-description-format "Email %c: %.30s"
1061 "Format of the description part of a link to an email or usenet message.
1062 The following %-escapes will be replaced by corresponding information:
1064 %F full \"From\" field
1065 %f name, taken from \"From\" field, address if no name
1066 %T full \"To\" field
1067 %t first name in \"To\" field, address if no name
1068 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1069 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1070 %s subject
1071 %m message-id.
1073 You may use normal field width specification between the % and the letter.
1074 This is for example useful to limit the length of the subject.
1076 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1077 :group 'org-link-store
1078 :type 'string)
1080 (defcustom org-from-is-user-regexp
1081 (let (r1 r2)
1082 (when (and user-mail-address (not (string= user-mail-address "")))
1083 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1084 (when (and user-full-name (not (string= user-full-name "")))
1085 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1086 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1087 "Regexp matched against the \"From:\" header of an email or usenet message.
1088 It should match if the message is from the user him/herself."
1089 :group 'org-link-store
1090 :type 'regexp)
1092 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1093 "Non-nil means, storing a link to an Org file will use entry IDs.
1095 Note that before this variable is even considered, org-id must be loaded,
1096 so please customize `org-modules' and turn it on.
1098 The variable can have the following values:
1100 t Create an ID if needed to make a link to the current entry.
1102 create-if-interactive
1103 If `org-store-link' is called directly (interactively, as a user
1104 command), do create an ID to support the link. But when doing the
1105 job for remember, only use the ID if it already exists. The
1106 purpose of this setting is to avoid proliferation of unwanted
1107 IDs, just because you happen to be in an Org file when you
1108 call `org-remember' that automatically and preemptively
1109 creates a link. If you do want to get an ID link in a remember
1110 template to an entry not having an ID, create it first by
1111 explicitly creating a link to it, using `C-c C-l' first.
1113 create-if-interactive-and-no-custom-id
1114 Like create-if-interactive, but do not create an ID if there is
1115 a CUSTOM_ID property defined in the entry. This is the default.
1117 use-existing
1118 Use existing ID, do not create one.
1120 nil Never use an ID to make a link, instead link using a text search for
1121 the headline text."
1122 :group 'org-link-store
1123 :type '(choice
1124 (const :tag "Create ID to make link" t)
1125 (const :tag "Create if storing link interactively"
1126 create-if-interactive)
1127 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1128 create-if-interactive-and-no-custom-id)
1129 (const :tag "Only use existing" use-existing)
1130 (const :tag "Do not use ID to create link" nil)))
1132 (defcustom org-context-in-file-links t
1133 "Non-nil means, file links from `org-store-link' contain context.
1134 A search string will be added to the file name with :: as separator and
1135 used to find the context when the link is activated by the command
1136 `org-open-at-point'.
1137 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1138 negates this setting for the duration of the command."
1139 :group 'org-link-store
1140 :type 'boolean)
1142 (defcustom org-keep-stored-link-after-insertion nil
1143 "Non-nil means, keep link in list for entire session.
1145 The command `org-store-link' adds a link pointing to the current
1146 location to an internal list. These links accumulate during a session.
1147 The command `org-insert-link' can be used to insert links into any
1148 Org-mode file (offering completion for all stored links). When this
1149 option is nil, every link which has been inserted once using \\[org-insert-link]
1150 will be removed from the list, to make completing the unused links
1151 more efficient."
1152 :group 'org-link-store
1153 :type 'boolean)
1155 (defgroup org-link-follow nil
1156 "Options concerning following links in Org-mode."
1157 :tag "Org Follow Link"
1158 :group 'org-link)
1160 (defcustom org-link-translation-function nil
1161 "Function to translate links with different syntax to Org syntax.
1162 This can be used to translate links created for example by the Planner
1163 or emacs-wiki packages to Org syntax.
1164 The function must accept two parameters, a TYPE containing the link
1165 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1166 which is everything after the link protocol. It should return a cons
1167 with possibly modified values of type and path.
1168 Org contains a function for this, so if you set this variable to
1169 `org-translate-link-from-planner', you should be able follow many
1170 links created by planner."
1171 :group 'org-link-follow
1172 :type 'function)
1174 (defcustom org-follow-link-hook nil
1175 "Hook that is run after a link has been followed."
1176 :group 'org-link-follow
1177 :type 'hook)
1179 (defcustom org-tab-follows-link nil
1180 "Non-nil means, on links TAB will follow the link.
1181 Needs to be set before org.el is loaded.
1182 This really should not be used, it does not make sense, and the
1183 implementation is bad."
1184 :group 'org-link-follow
1185 :type 'boolean)
1187 (defcustom org-return-follows-link nil
1188 "Non-nil means, on links RET will follow the link.
1189 Needs to be set before org.el is loaded."
1190 :group 'org-link-follow
1191 :type 'boolean)
1193 (defcustom org-mouse-1-follows-link
1194 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1195 "Non-nil means, mouse-1 on a link will follow the link.
1196 A longer mouse click will still set point. Does not work on XEmacs.
1197 Needs to be set before org.el is loaded."
1198 :group 'org-link-follow
1199 :type 'boolean)
1201 (defcustom org-mark-ring-length 4
1202 "Number of different positions to be recorded in the ring
1203 Changing this requires a restart of Emacs to work correctly."
1204 :group 'org-link-follow
1205 :type 'integer)
1207 (defcustom org-link-frame-setup
1208 '((vm . vm-visit-folder-other-frame)
1209 (gnus . gnus-other-frame)
1210 (file . find-file-other-window))
1211 "Setup the frame configuration for following links.
1212 When following a link with Emacs, it may often be useful to display
1213 this link in another window or frame. This variable can be used to
1214 set this up for the different types of links.
1215 For VM, use any of
1216 `vm-visit-folder'
1217 `vm-visit-folder-other-frame'
1218 For Gnus, use any of
1219 `gnus'
1220 `gnus-other-frame'
1221 `org-gnus-no-new-news'
1222 For FILE, use any of
1223 `find-file'
1224 `find-file-other-window'
1225 `find-file-other-frame'
1226 For the calendar, use the variable `calendar-setup'.
1227 For BBDB, it is currently only possible to display the matches in
1228 another window."
1229 :group 'org-link-follow
1230 :type '(list
1231 (cons (const vm)
1232 (choice
1233 (const vm-visit-folder)
1234 (const vm-visit-folder-other-window)
1235 (const vm-visit-folder-other-frame)))
1236 (cons (const gnus)
1237 (choice
1238 (const gnus)
1239 (const gnus-other-frame)
1240 (const org-gnus-no-new-news)))
1241 (cons (const file)
1242 (choice
1243 (const find-file)
1244 (const find-file-other-window)
1245 (const find-file-other-frame)))))
1247 (defcustom org-display-internal-link-with-indirect-buffer nil
1248 "Non-nil means, use indirect buffer to display infile links.
1249 Activating internal links (from one location in a file to another location
1250 in the same file) normally just jumps to the location. When the link is
1251 activated with a C-u prefix (or with mouse-3), the link is displayed in
1252 another window. When this option is set, the other window actually displays
1253 an indirect buffer clone of the current buffer, to avoid any visibility
1254 changes to the current buffer."
1255 :group 'org-link-follow
1256 :type 'boolean)
1258 (defcustom org-open-non-existing-files nil
1259 "Non-nil means, `org-open-file' will open non-existing files.
1260 When nil, an error will be generated.
1261 This variable applies only to external applications because they
1262 might choke on non-existing files. If the link is to a file that
1263 will be openend in Emacs, the variable is ignored."
1264 :group 'org-link-follow
1265 :type 'boolean)
1267 (defcustom org-open-directory-means-index-dot-org nil
1268 "Non-nil means, a link to a directory really means to index.org.
1269 When nil, following a directory link will run dired or open a finder/explorer
1270 window on that directory."
1271 :group 'org-link-follow
1272 :type 'boolean)
1274 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1275 "Function and arguments to call for following mailto links.
1276 This is a list with the first element being a lisp function, and the
1277 remaining elements being arguments to the function. In string arguments,
1278 %a will be replaced by the address, and %s will be replaced by the subject
1279 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1280 :group 'org-link-follow
1281 :type '(choice
1282 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1283 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1284 (const :tag "message-mail" (message-mail "%a" "%s"))
1285 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1287 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1288 "Non-nil means, ask for confirmation before executing shell links.
1289 Shell links can be dangerous: just think about a link
1291 [[shell:rm -rf ~/*][Google Search]]
1293 This link would show up in your Org-mode document as \"Google Search\",
1294 but really it would remove your entire home directory.
1295 Therefore we advise against setting this variable to nil.
1296 Just change it to `y-or-n-p' if you want to confirm with a
1297 single keystroke rather than having to type \"yes\"."
1298 :group 'org-link-follow
1299 :type '(choice
1300 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1301 (const :tag "with y-or-n (faster)" y-or-n-p)
1302 (const :tag "no confirmation (dangerous)" nil)))
1304 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1305 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1306 Elisp links can be dangerous: just think about a link
1308 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1310 This link would show up in your Org-mode document as \"Google Search\",
1311 but really it would remove your entire home directory.
1312 Therefore we advise against setting this variable to nil.
1313 Just change it to `y-or-n-p' if you want to confirm with a
1314 single keystroke rather than having to type \"yes\"."
1315 :group 'org-link-follow
1316 :type '(choice
1317 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1318 (const :tag "with y-or-n (faster)" y-or-n-p)
1319 (const :tag "no confirmation (dangerous)" nil)))
1321 (defconst org-file-apps-defaults-gnu
1322 '((remote . emacs)
1323 (system . mailcap)
1324 (t . mailcap))
1325 "Default file applications on a UNIX or GNU/Linux system.
1326 See `org-file-apps'.")
1328 (defconst org-file-apps-defaults-macosx
1329 '((remote . emacs)
1330 (t . "open %s")
1331 (system . "open %s")
1332 ("ps.gz" . "gv %s")
1333 ("eps.gz" . "gv %s")
1334 ("dvi" . "xdvi %s")
1335 ("fig" . "xfig %s"))
1336 "Default file applications on a MacOS X system.
1337 The system \"open\" is known as a default, but we use X11 applications
1338 for some files for which the OS does not have a good default.
1339 See `org-file-apps'.")
1341 (defconst org-file-apps-defaults-windowsnt
1342 (list
1343 '(remote . emacs)
1344 (cons t
1345 (list (if (featurep 'xemacs)
1346 'mswindows-shell-execute
1347 'w32-shell-execute)
1348 "open" 'file))
1349 (cons 'system
1350 (list (if (featurep 'xemacs)
1351 'mswindows-shell-execute
1352 'w32-shell-execute)
1353 "open" 'file)))
1354 "Default file applications on a Windows NT system.
1355 The system \"open\" is used for most files.
1356 See `org-file-apps'.")
1358 (defcustom org-file-apps
1360 (auto-mode . emacs)
1361 ("\\.x?html?\\'" . default)
1362 ("\\.pdf\\'" . default)
1364 "External applications for opening `file:path' items in a document.
1365 Org-mode uses system defaults for different file types, but
1366 you can use this variable to set the application for a given file
1367 extension. The entries in this list are cons cells where the car identifies
1368 files and the cdr the corresponding command. Possible values for the
1369 file identifier are
1370 \"regex\" Regular expression matched against the file name. For backward
1371 compatibility, this can also be a string with only alphanumeric
1372 characters, which is then interpreted as an extension.
1373 `directory' Matches a directory
1374 `remote' Matches a remote file, accessible through tramp or efs.
1375 Remote files most likely should be visited through Emacs
1376 because external applications cannot handle such paths.
1377 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1378 so all files Emacs knows how to handle. Using this with
1379 command `emacs' will open most files in Emacs. Beware that this
1380 will also open html files inside Emacs, unless you add
1381 (\"html\" . default) to the list as well.
1382 t Default for files not matched by any of the other options.
1383 `system' The system command to open files, like `open' on Windows
1384 and Mac OS X, and mailcap under GNU/Linux. This is the command
1385 that will be selected if you call `C-c C-o' with a double
1386 `C-u C-u' prefix.
1388 Possible values for the command are:
1389 `emacs' The file will be visited by the current Emacs process.
1390 `default' Use the default application for this file type, which is the
1391 association for t in the list, most likely in the system-specific
1392 part.
1393 This can be used to overrule an unwanted setting in the
1394 system-specific variable.
1395 `system' Use the system command for opening files, like \"open\".
1396 This command is specified by the entry whose car is `system'.
1397 Most likely, the system-specific version of this variable
1398 does define this command, but you can overrule/replace it
1399 here.
1400 string A command to be executed by a shell; %s will be replaced
1401 by the path to the file.
1402 sexp A Lisp form which will be evaluated. The file path will
1403 be available in the Lisp variable `file'.
1404 For more examples, see the system specific constants
1405 `org-file-apps-defaults-macosx'
1406 `org-file-apps-defaults-windowsnt'
1407 `org-file-apps-defaults-gnu'."
1408 :group 'org-link-follow
1409 :type '(repeat
1410 (cons (choice :value ""
1411 (string :tag "Extension")
1412 (const :tag "System command to open files" system)
1413 (const :tag "Default for unrecognized files" t)
1414 (const :tag "Remote file" remote)
1415 (const :tag "Links to a directory" directory)
1416 (const :tag "Any files that have Emacs modes"
1417 auto-mode))
1418 (choice :value ""
1419 (const :tag "Visit with Emacs" emacs)
1420 (const :tag "Use default" default)
1421 (const :tag "Use the system command" system)
1422 (string :tag "Command")
1423 (sexp :tag "Lisp form")))))
1425 (defgroup org-refile nil
1426 "Options concerning refiling entries in Org-mode."
1427 :tag "Org Refile"
1428 :group 'org)
1430 (defcustom org-directory "~/org"
1431 "Directory with org files.
1432 This is just a default location to look for Org files. There is no need
1433 at all to put your files into this directory. It is only used in the
1434 following situations:
1436 1. When a remember template specifies a target file that is not an
1437 absolute path. The path will then be interpreted relative to
1438 `org-directory'
1439 2. When a remember note is filed away in an interactive way (when exiting the
1440 note buffer with `C-1 C-c C-c'. The the user is prompted for an org file,
1441 with `org-directory' as the default path."
1442 :group 'org-refile
1443 :group 'org-remember
1444 :type 'directory)
1446 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1447 "Default target for storing notes.
1448 Used by the hooks for remember.el. This can be a string, or nil to mean
1449 the value of `remember-data-file'.
1450 You can set this on a per-template basis with the variable
1451 `org-remember-templates'."
1452 :group 'org-refile
1453 :group 'org-remember
1454 :type '(choice
1455 (const :tag "Default from remember-data-file" nil)
1456 file))
1458 (defcustom org-goto-interface 'outline
1459 "The default interface to be used for `org-goto'.
1460 Allowed values are:
1461 outline The interface shows an outline of the relevant file
1462 and the correct heading is found by moving through
1463 the outline or by searching with incremental search.
1464 outline-path-completion Headlines in the current buffer are offered via
1465 completion. This is the interface also used by
1466 the refile command."
1467 :group 'org-refile
1468 :type '(choice
1469 (const :tag "Outline" outline)
1470 (const :tag "Outline-path-completion" outline-path-completion)))
1472 (defcustom org-goto-max-level 5
1473 "Maximum level to be considered when running org-goto with refile interface."
1474 :group 'org-refile
1475 :type 'integer)
1477 (defcustom org-reverse-note-order nil
1478 "Non-nil means, store new notes at the beginning of a file or entry.
1479 When nil, new notes will be filed to the end of a file or entry.
1480 This can also be a list with cons cells of regular expressions that
1481 are matched against file names, and values."
1482 :group 'org-remember
1483 :group 'org-refile
1484 :type '(choice
1485 (const :tag "Reverse always" t)
1486 (const :tag "Reverse never" nil)
1487 (repeat :tag "By file name regexp"
1488 (cons regexp boolean))))
1490 (defcustom org-refile-targets nil
1491 "Targets for refiling entries with \\[org-refile].
1492 This is list of cons cells. Each cell contains:
1493 - a specification of the files to be considered, either a list of files,
1494 or a symbol whose function or variable value will be used to retrieve
1495 a file name or a list of file names. If you use `org-agenda-files' for
1496 that, all agenda files will be scanned for targets. Nil means, consider
1497 headings in the current buffer.
1498 - A specification of how to find candidate refile targets. This may be
1499 any of:
1500 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1501 This tag has to be present in all target headlines, inheritance will
1502 not be considered.
1503 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1504 todo keyword.
1505 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1506 headlines that are refiling targets.
1507 - a cons cell (:level . N). Any headline of level N is considered a target.
1508 Note that, when `org-odd-levels-only' is set, level corresponds to
1509 order in hierarchy, not to the number of stars.
1510 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1511 Note that, when `org-odd-levels-only' is set, level corresponds to
1512 order in hierarchy, not to the number of stars.
1514 You can set the variable `org-refile-target-verify-function' to a function
1515 to verify each headline found by the simple critery above.
1517 When this variable is nil, all top-level headlines in the current buffer
1518 are used, equivalent to the value `((nil . (:level . 1))'."
1519 :group 'org-refile
1520 :type '(repeat
1521 (cons
1522 (choice :value org-agenda-files
1523 (const :tag "All agenda files" org-agenda-files)
1524 (const :tag "Current buffer" nil)
1525 (function) (variable) (file))
1526 (choice :tag "Identify target headline by"
1527 (cons :tag "Specific tag" (const :value :tag) (string))
1528 (cons :tag "TODO keyword" (const :value :todo) (string))
1529 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1530 (cons :tag "Level number" (const :value :level) (integer))
1531 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1533 (defcustom org-refile-target-verify-function nil
1534 "Function to verify if the headline at point should be a refile target.
1535 The function will be called without arguments, with point at the
1536 beginning of the headline. It should return t and leave point
1537 where it is if the headline is a valid target for refiling.
1539 If the target should not be selected, the function must return nil.
1540 In addition to this, it may move point to a place from where the search
1541 should be continued. For example, the function may decide that the entire
1542 subtree of the current entry should be excluded and move point to the end
1543 of the subtree."
1544 :group 'org-refile
1545 :type 'function)
1547 (defcustom org-refile-use-outline-path nil
1548 "Non-nil means, provide refile targets as paths.
1549 So a level 3 headline will be available as level1/level2/level3.
1551 When the value is `file', also include the file name (without directory)
1552 into the path. In this case, you can also stop the completion after
1553 the file name, to get entries inserted as top level in the file.
1555 When `full-file-path', include the full file path."
1556 :group 'org-refile
1557 :type '(choice
1558 (const :tag "Not" nil)
1559 (const :tag "Yes" t)
1560 (const :tag "Start with file name" file)
1561 (const :tag "Start with full file path" full-file-path)))
1563 (defcustom org-outline-path-complete-in-steps t
1564 "Non-nil means, complete the outline path in hierarchical steps.
1565 When Org-mode uses the refile interface to select an outline path
1566 \(see variable `org-refile-use-outline-path'), the completion of
1567 the path can be done is a single go, or if can be done in steps down
1568 the headline hierarchy. Going in steps is probably the best if you
1569 do not use a special completion package like `ido' or `icicles'.
1570 However, when using these packages, going in one step can be very
1571 fast, while still showing the whole path to the entry."
1572 :group 'org-refile
1573 :type 'boolean)
1575 (defcustom org-refile-allow-creating-parent-nodes nil
1576 "Non-nil means, allow to create new nodes as refile targets.
1577 New nodes are then created by adding \"/new node name\" to the completion
1578 of an existing node. When the value of this variable is `confirm',
1579 new node creation must be confirmed by the user (recommended)
1580 When nil, the completion must match an existing entry.
1582 Note that, if the new heading is not seen by the criteria
1583 listed in `org-refile-targets', multiple instances of the same
1584 heading would be created by trying again to file under the new
1585 heading."
1586 :group 'org-refile
1587 :type '(choice
1588 (const :tag "Never" nil)
1589 (const :tag "Always" t)
1590 (const :tag "Prompt for confirmation" confirm)))
1592 (defgroup org-todo nil
1593 "Options concerning TODO items in Org-mode."
1594 :tag "Org TODO"
1595 :group 'org)
1597 (defgroup org-progress nil
1598 "Options concerning Progress logging in Org-mode."
1599 :tag "Org Progress"
1600 :group 'org-time)
1602 (defvar org-todo-interpretation-widgets
1604 (:tag "Sequence (cycling hits every state)" sequence)
1605 (:tag "Type (cycling directly to DONE)" type))
1606 "The available interpretation symbols for customizing
1607 `org-todo-keywords'.
1608 Interested libraries should add to this list.")
1610 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1611 "List of TODO entry keyword sequences and their interpretation.
1612 \\<org-mode-map>This is a list of sequences.
1614 Each sequence starts with a symbol, either `sequence' or `type',
1615 indicating if the keywords should be interpreted as a sequence of
1616 action steps, or as different types of TODO items. The first
1617 keywords are states requiring action - these states will select a headline
1618 for inclusion into the global TODO list Org-mode produces. If one of
1619 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1620 signify that no further action is necessary. If \"|\" is not found,
1621 the last keyword is treated as the only DONE state of the sequence.
1623 The command \\[org-todo] cycles an entry through these states, and one
1624 additional state where no keyword is present. For details about this
1625 cycling, see the manual.
1627 TODO keywords and interpretation can also be set on a per-file basis with
1628 the special #+SEQ_TODO and #+TYP_TODO lines.
1630 Each keyword can optionally specify a character for fast state selection
1631 \(in combination with the variable `org-use-fast-todo-selection')
1632 and specifiers for state change logging, using the same syntax
1633 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1634 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1635 indicates to record a time stamp each time this state is selected.
1637 Each keyword may also specify if a timestamp or a note should be
1638 recorded when entering or leaving the state, by adding additional
1639 characters in the parenthesis after the keyword. This looks like this:
1640 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1641 record only the time of the state change. With X and Y being either
1642 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1643 Y when leaving the state if and only if the *target* state does not
1644 define X. You may omit any of the fast-selection key or X or /Y,
1645 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1647 For backward compatibility, this variable may also be just a list
1648 of keywords - in this case the interpretation (sequence or type) will be
1649 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1650 :group 'org-todo
1651 :group 'org-keywords
1652 :type '(choice
1653 (repeat :tag "Old syntax, just keywords"
1654 (string :tag "Keyword"))
1655 (repeat :tag "New syntax"
1656 (cons
1657 (choice
1658 :tag "Interpretation"
1659 ;;Quick and dirty way to see
1660 ;;`org-todo-interpretations'. This takes the
1661 ;;place of item arguments
1662 :convert-widget
1663 (lambda (widget)
1664 (widget-put widget
1665 :args (mapcar
1666 #'(lambda (x)
1667 (widget-convert
1668 (cons 'const x)))
1669 org-todo-interpretation-widgets))
1670 widget))
1671 (repeat
1672 (string :tag "Keyword"))))))
1674 (defvar org-todo-keywords-1 nil
1675 "All TODO and DONE keywords active in a buffer.")
1676 (make-variable-buffer-local 'org-todo-keywords-1)
1677 (defvar org-todo-keywords-for-agenda nil)
1678 (defvar org-done-keywords-for-agenda nil)
1679 (defvar org-todo-keyword-alist-for-agenda nil)
1680 (defvar org-tag-alist-for-agenda nil)
1681 (defvar org-agenda-contributing-files nil)
1682 (defvar org-not-done-keywords nil)
1683 (make-variable-buffer-local 'org-not-done-keywords)
1684 (defvar org-done-keywords nil)
1685 (make-variable-buffer-local 'org-done-keywords)
1686 (defvar org-todo-heads nil)
1687 (make-variable-buffer-local 'org-todo-heads)
1688 (defvar org-todo-sets nil)
1689 (make-variable-buffer-local 'org-todo-sets)
1690 (defvar org-todo-log-states nil)
1691 (make-variable-buffer-local 'org-todo-log-states)
1692 (defvar org-todo-kwd-alist nil)
1693 (make-variable-buffer-local 'org-todo-kwd-alist)
1694 (defvar org-todo-key-alist nil)
1695 (make-variable-buffer-local 'org-todo-key-alist)
1696 (defvar org-todo-key-trigger nil)
1697 (make-variable-buffer-local 'org-todo-key-trigger)
1699 (defcustom org-todo-interpretation 'sequence
1700 "Controls how TODO keywords are interpreted.
1701 This variable is in principle obsolete and is only used for
1702 backward compatibility, if the interpretation of todo keywords is
1703 not given already in `org-todo-keywords'. See that variable for
1704 more information."
1705 :group 'org-todo
1706 :group 'org-keywords
1707 :type '(choice (const sequence)
1708 (const type)))
1710 (defcustom org-use-fast-todo-selection t
1711 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1712 This variable describes if and under what circumstances the cycling
1713 mechanism for TODO keywords will be replaced by a single-key, direct
1714 selection scheme.
1716 When nil, fast selection is never used.
1718 When the symbol `prefix', it will be used when `org-todo' is called with
1719 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1720 in an agenda buffer.
1722 When t, fast selection is used by default. In this case, the prefix
1723 argument forces cycling instead.
1725 In all cases, the special interface is only used if access keys have actually
1726 been assigned by the user, i.e. if keywords in the configuration are followed
1727 by a letter in parenthesis, like TODO(t)."
1728 :group 'org-todo
1729 :type '(choice
1730 (const :tag "Never" nil)
1731 (const :tag "By default" t)
1732 (const :tag "Only with C-u C-c C-t" prefix)))
1734 (defcustom org-provide-todo-statistics t
1735 "Non-nil means, update todo statistics after insert and toggle.
1736 ALL-HEADLINES means update todo statistics by including headlines
1737 with no TODO keyword as well, counting them as not done.
1738 A list of TODO keywords means the same, but skip keywords that are
1739 not in this list.
1741 When this is set, todo statistics is updated in the parent of the
1742 current entry each time a todo state is changed."
1743 :group 'org-todo
1744 :type '(choice
1745 (const :tag "Yes, only for TODO entries" t)
1746 (const :tag "Yes, including all entries" 'all-headlines)
1747 (repeat :tag "Yes, for TODOs in this list"
1748 (string :tag "TODO keyword"))
1749 (other :tag "No TODO statistics" nil)))
1751 (defcustom org-hierarchical-todo-statistics t
1752 "Non-nil means, TODO statistics covers just direct children.
1753 When nil, all entries in the subtree are considered.
1754 This has only an effect if `org-provide-todo-statistics' is set."
1755 :group 'org-todo
1756 :type 'boolean)
1758 (defcustom org-after-todo-state-change-hook nil
1759 "Hook which is run after the state of a TODO item was changed.
1760 The new state (a string with a TODO keyword, or nil) is available in the
1761 Lisp variable `state'."
1762 :group 'org-todo
1763 :type 'hook)
1765 (defvar org-blocker-hook nil
1766 "Hook for functions that are allowed to block a state change.
1768 Each function gets as its single argument a property list, see
1769 `org-trigger-hook' for more information about this list.
1771 If any of the functions in this hook returns nil, the state change
1772 is blocked.")
1774 (defvar org-trigger-hook nil
1775 "Hook for functions that are triggered by a state change.
1777 Each function gets as its single argument a property list with at least
1778 the following elements:
1780 (:type type-of-change :position pos-at-entry-start
1781 :from old-state :to new-state)
1783 Depending on the type, more properties may be present.
1785 This mechanism is currently implemented for:
1787 TODO state changes
1788 ------------------
1789 :type todo-state-change
1790 :from previous state (keyword as a string), or nil, or a symbol
1791 'todo' or 'done', to indicate the general type of state.
1792 :to new state, like in :from")
1794 (defcustom org-enforce-todo-dependencies nil
1795 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1796 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1797 be blocked if any prior sibling is not yet done.
1798 Finally, if the parent is blocked because of ordered siblings of its own,
1799 the child will also be blocked.
1800 This variable needs to be set before org.el is loaded, and you need to
1801 restart Emacs after a change to make the change effective. The only way
1802 to change is while Emacs is running is through the customize interface."
1803 :set (lambda (var val)
1804 (set var val)
1805 (if val
1806 (add-hook 'org-blocker-hook
1807 'org-block-todo-from-children-or-siblings-or-parent)
1808 (remove-hook 'org-blocker-hook
1809 'org-block-todo-from-children-or-siblings-or-parent)))
1810 :group 'org-todo
1811 :type 'boolean)
1813 (defcustom org-enforce-todo-checkbox-dependencies nil
1814 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1815 When this is nil, checkboxes have no influence on switching TODO states.
1816 When non-nil, you first need to check off all check boxes before the TODO
1817 entry can be switched to DONE.
1818 This variable needs to be set before org.el is loaded, and you need to
1819 restart Emacs after a change to make the change effective. The only way
1820 to change is while Emacs is running is through the customize interface."
1821 :set (lambda (var val)
1822 (set var val)
1823 (if val
1824 (add-hook 'org-blocker-hook
1825 'org-block-todo-from-checkboxes)
1826 (remove-hook 'org-blocker-hook
1827 'org-block-todo-from-checkboxes)))
1828 :group 'org-todo
1829 :type 'boolean)
1831 (defcustom org-treat-insert-todo-heading-as-state-change nil
1832 "Non-nil means, inserting a TODO heading is treated as state change.
1833 So when the command \\[org-insert-todo-heading] is used, state change
1834 logging will apply if appropriate. When nil, the new TODO item will
1835 be inserted directly, and no logging will take place."
1836 :group 'org-todo
1837 :type 'boolean)
1839 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1840 "Non-nil means, switching TODO states with S-cursor counts as state change.
1841 This is the default behavior. However, setting this to nil allows a
1842 convenient way to select a TODO state and bypass any logging associated
1843 with that."
1844 :group 'org-todo
1845 :type 'boolean)
1847 (defcustom org-todo-state-tags-triggers nil
1848 "Tag changes that should be triggered by TODO state changes.
1849 This is a list. Each entry is
1851 (state-change (tag . flag) .......)
1853 State-change can be a string with a state, and empty string to indicate the
1854 state that has no TODO keyword, or it can be one of the symbols `todo'
1855 or `done', meaning any not-done or done state, respectively."
1856 :group 'org-todo
1857 :group 'org-tags
1858 :type '(repeat
1859 (cons (choice :tag "When changing to"
1860 (const :tag "Not-done state" todo)
1861 (const :tag "Done state" done)
1862 (string :tag "State"))
1863 (repeat
1864 (cons :tag "Tag action"
1865 (string :tag "Tag")
1866 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1868 (defcustom org-log-done nil
1869 "Information to record when a task moves to the DONE state.
1871 Possible values are:
1873 nil Don't add anything, just change the keyword
1874 time Add a time stamp to the task
1875 note Prompt a closing note and add it with template `org-log-note-headings'
1877 This option can also be set with on a per-file-basis with
1879 #+STARTUP: nologdone
1880 #+STARTUP: logdone
1881 #+STARTUP: lognotedone
1883 You can have local logging settings for a subtree by setting the LOGGING
1884 property to one or more of these keywords."
1885 :group 'org-todo
1886 :group 'org-progress
1887 :type '(choice
1888 (const :tag "No logging" nil)
1889 (const :tag "Record CLOSED timestamp" time)
1890 (const :tag "Record CLOSED timestamp with closing note." note)))
1892 ;; Normalize old uses of org-log-done.
1893 (cond
1894 ((eq org-log-done t) (setq org-log-done 'time))
1895 ((and (listp org-log-done) (memq 'done org-log-done))
1896 (setq org-log-done 'note)))
1898 (defcustom org-log-note-clock-out nil
1899 "Non-nil means, record a note when clocking out of an item.
1900 This can also be configured on a per-file basis by adding one of
1901 the following lines anywhere in the buffer:
1903 #+STARTUP: lognoteclock-out
1904 #+STARTUP: nolognoteclock-out"
1905 :group 'org-todo
1906 :group 'org-progress
1907 :type 'boolean)
1909 (defcustom org-log-done-with-time t
1910 "Non-nil means, the CLOSED time stamp will contain date and time.
1911 When nil, only the date will be recorded."
1912 :group 'org-progress
1913 :type 'boolean)
1915 (defcustom org-log-note-headings
1916 '((done . "CLOSING NOTE %t")
1917 (state . "State %-12s from %-12S %t")
1918 (note . "Note taken on %t")
1919 (clock-out . ""))
1920 "Headings for notes added to entries.
1921 The value is an alist, with the car being a symbol indicating the note
1922 context, and the cdr is the heading to be used. The heading may also be the
1923 empty string.
1924 %t in the heading will be replaced by a time stamp.
1925 %s will be replaced by the new TODO state, in double quotes.
1926 %S will be replaced by the old TODO state, in double quotes.
1927 %u will be replaced by the user name.
1928 %U will be replaced by the full user name."
1929 :group 'org-todo
1930 :group 'org-progress
1931 :type '(list :greedy t
1932 (cons (const :tag "Heading when closing an item" done) string)
1933 (cons (const :tag
1934 "Heading when changing todo state (todo sequence only)"
1935 state) string)
1936 (cons (const :tag "Heading when just taking a note" note) string)
1937 (cons (const :tag "Heading when clocking out" clock-out) string)))
1939 (unless (assq 'note org-log-note-headings)
1940 (push '(note . "%t") org-log-note-headings))
1942 (defcustom org-log-into-drawer nil
1943 "Non-nil means, insert state change notes and time stamps into a drawer.
1944 When nil, state changes notes will be inserted after the headline and
1945 any scheduling and clock lines, but not inside a drawer.
1947 The value of this variable should be the name of the drawer to use.
1948 LOGBOOK is proposed at the default drawer for this purpose, you can
1949 also set this to a string to define the drawer of your choice.
1951 A value of t is also allowed, representing \"LOGBOOK\".
1953 If this variable is set, `org-log-state-notes-insert-after-drawers'
1954 will be ignored.
1956 You can set the property LOG_INTO_DRAWER to overrule this setting for
1957 a subtree."
1958 :group 'org-todo
1959 :group 'org-progress
1960 :type '(choice
1961 (const :tag "Not into a drawer" nil)
1962 (const :tag "LOGBOOK" t)
1963 (string :tag "Other")))
1965 (if (fboundp 'defvaralias)
1966 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
1968 (defun org-log-into-drawer ()
1969 "Return the value of `org-log-into-drawer', but let properties overrule.
1970 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
1971 used instead of the default value."
1972 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
1973 (cond
1974 ((or (not p) (equal p "nil")) org-log-into-drawer)
1975 ((equal p "t") "LOGBOOK")
1976 (t p))))
1978 (defcustom org-log-state-notes-insert-after-drawers nil
1979 "Non-nil means, insert state change notes after any drawers in entry.
1980 Only the drawers that *immediately* follow the headline and the
1981 deadline/scheduled line are skipped.
1982 When nil, insert notes right after the heading and perhaps the line
1983 with deadline/scheduling if present.
1985 This variable will have no effect if `org-log-into-drawer' is
1986 set."
1987 :group 'org-todo
1988 :group 'org-progress
1989 :type 'boolean)
1991 (defcustom org-log-states-order-reversed t
1992 "Non-nil means, the latest state change note will be directly after heading.
1993 When nil, the notes will be orderer according to time."
1994 :group 'org-todo
1995 :group 'org-progress
1996 :type 'boolean)
1998 (defcustom org-log-repeat 'time
1999 "Non-nil means, record moving through the DONE state when triggering repeat.
2000 An auto-repeating tasks is immediately switched back to TODO when marked
2001 done. If you are not logging state changes (by adding \"@\" or \"!\" to
2002 the TODO keyword definition, or recording a closing note by setting
2003 `org-log-done', there will be no record of the task moving through DONE.
2004 This variable forces taking a note anyway. Possible values are:
2006 nil Don't force a record
2007 time Record a time stamp
2008 note Record a note
2010 This option can also be set with on a per-file-basis with
2012 #+STARTUP: logrepeat
2013 #+STARTUP: lognoterepeat
2014 #+STARTUP: nologrepeat
2016 You can have local logging settings for a subtree by setting the LOGGING
2017 property to one or more of these keywords."
2018 :group 'org-todo
2019 :group 'org-progress
2020 :type '(choice
2021 (const :tag "Don't force a record" nil)
2022 (const :tag "Force recording the DONE state" time)
2023 (const :tag "Force recording a note with the DONE state" note)))
2026 (defgroup org-priorities nil
2027 "Priorities in Org-mode."
2028 :tag "Org Priorities"
2029 :group 'org-todo)
2031 (defcustom org-enable-priority-commands t
2032 "Non-nil means, priority commands are active.
2033 When nil, these commands will be disabled, so that you never accidentally
2034 set a priority."
2035 :group 'org-priorities
2036 :type 'boolean)
2038 (defcustom org-highest-priority ?A
2039 "The highest priority of TODO items. A character like ?A, ?B etc.
2040 Must have a smaller ASCII number than `org-lowest-priority'."
2041 :group 'org-priorities
2042 :type 'character)
2044 (defcustom org-lowest-priority ?C
2045 "The lowest priority of TODO items. A character like ?A, ?B etc.
2046 Must have a larger ASCII number than `org-highest-priority'."
2047 :group 'org-priorities
2048 :type 'character)
2050 (defcustom org-default-priority ?B
2051 "The default priority of TODO items.
2052 This is the priority an item get if no explicit priority is given."
2053 :group 'org-priorities
2054 :type 'character)
2056 (defcustom org-priority-start-cycle-with-default t
2057 "Non-nil means, start with default priority when starting to cycle.
2058 When this is nil, the first step in the cycle will be (depending on the
2059 command used) one higher or lower that the default priority."
2060 :group 'org-priorities
2061 :type 'boolean)
2063 (defgroup org-time nil
2064 "Options concerning time stamps and deadlines in Org-mode."
2065 :tag "Org Time"
2066 :group 'org)
2068 (defcustom org-insert-labeled-timestamps-at-point nil
2069 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
2070 When nil, these labeled time stamps are forces into the second line of an
2071 entry, just after the headline. When scheduling from the global TODO list,
2072 the time stamp will always be forced into the second line."
2073 :group 'org-time
2074 :type 'boolean)
2076 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2077 "Formats for `format-time-string' which are used for time stamps.
2078 It is not recommended to change this constant.")
2080 (defcustom org-time-stamp-rounding-minutes '(0 5)
2081 "Number of minutes to round time stamps to.
2082 These are two values, the first applies when first creating a time stamp.
2083 The second applies when changing it with the commands `S-up' and `S-down'.
2084 When changing the time stamp, this means that it will change in steps
2085 of N minutes, as given by the second value.
2087 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2088 numbers should be factors of 60, so for example 5, 10, 15.
2090 When this is larger than 1, you can still force an exact time-stamp by using
2091 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2092 and by using a prefix arg to `S-up/down' to specify the exact number
2093 of minutes to shift."
2094 :group 'org-time
2095 :get '(lambda (var) ; Make sure all entries have 5 elements
2096 (if (integerp (default-value var))
2097 (list (default-value var) 5)
2098 (default-value var)))
2099 :type '(list
2100 (integer :tag "when inserting times")
2101 (integer :tag "when modifying times")))
2103 ;; Normalize old customizations of this variable.
2104 (when (integerp org-time-stamp-rounding-minutes)
2105 (setq org-time-stamp-rounding-minutes
2106 (list org-time-stamp-rounding-minutes
2107 org-time-stamp-rounding-minutes)))
2109 (defcustom org-display-custom-times nil
2110 "Non-nil means, overlay custom formats over all time stamps.
2111 The formats are defined through the variable `org-time-stamp-custom-formats'.
2112 To turn this on on a per-file basis, insert anywhere in the file:
2113 #+STARTUP: customtime"
2114 :group 'org-time
2115 :set 'set-default
2116 :type 'sexp)
2117 (make-variable-buffer-local 'org-display-custom-times)
2119 (defcustom org-time-stamp-custom-formats
2120 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2121 "Custom formats for time stamps. See `format-time-string' for the syntax.
2122 These are overlayed over the default ISO format if the variable
2123 `org-display-custom-times' is set. Time like %H:%M should be at the
2124 end of the second format. The custom formats are also honored by export
2125 commands, if custom time display is turned on at the time of export."
2126 :group 'org-time
2127 :type 'sexp)
2129 (defun org-time-stamp-format (&optional long inactive)
2130 "Get the right format for a time string."
2131 (let ((f (if long (cdr org-time-stamp-formats)
2132 (car org-time-stamp-formats))))
2133 (if inactive
2134 (concat "[" (substring f 1 -1) "]")
2135 f)))
2137 (defcustom org-time-clocksum-format "%d:%02d"
2138 "The format string used when creating CLOCKSUM lines, or when
2139 org-mode generates a time duration."
2140 :group 'org-time
2141 :type 'string)
2143 (defcustom org-deadline-warning-days 14
2144 "No. of days before expiration during which a deadline becomes active.
2145 This variable governs the display in sparse trees and in the agenda.
2146 When 0 or negative, it means use this number (the absolute value of it)
2147 even if a deadline has a different individual lead time specified.
2149 Custom commands can set this variable in the options section."
2150 :group 'org-time
2151 :group 'org-agenda-daily/weekly
2152 :type 'integer)
2154 (defcustom org-read-date-prefer-future t
2155 "Non-nil means, assume future for incomplete date input from user.
2156 This affects the following situations:
2157 1. The user gives a day, but no month.
2158 For example, if today is the 15th, and you enter \"3\", Org-mode will
2159 read this as the third of *next* month. However, if you enter \"17\",
2160 it will be considered as *this* month.
2161 2. The user gives a month but not a year.
2162 For example, if it is april and you enter \"feb 2\", this will be read
2163 as feb 2, *next* year. \"May 5\", however, will be this year.
2165 Currently this does not work for ISO week specifications.
2167 When this option is nil, the current month and year will always be used
2168 as defaults."
2169 :group 'org-time
2170 :type 'boolean)
2172 (defcustom org-read-date-display-live t
2173 "Non-nil means, display current interpretation of date prompt live.
2174 This display will be in an overlay, in the minibuffer."
2175 :group 'org-time
2176 :type 'boolean)
2178 (defcustom org-read-date-popup-calendar t
2179 "Non-nil means, pop up a calendar when prompting for a date.
2180 In the calendar, the date can be selected with mouse-1. However, the
2181 minibuffer will also be active, and you can simply enter the date as well.
2182 When nil, only the minibuffer will be available."
2183 :group 'org-time
2184 :type 'boolean)
2185 (if (fboundp 'defvaralias)
2186 (defvaralias 'org-popup-calendar-for-date-prompt
2187 'org-read-date-popup-calendar))
2189 (defcustom org-read-date-minibuffer-setup-hook nil
2190 "Hook to be used to set up keys for the date/time interface.
2191 Add key definitions to `minibuffer-local-map', which will be a temporary
2192 copy."
2193 :group 'org-time
2194 :type 'hook)
2196 (defcustom org-extend-today-until 0
2197 "The hour when your day really ends. Must be an integer.
2198 This has influence for the following applications:
2199 - When switching the agenda to \"today\". It it is still earlier than
2200 the time given here, the day recognized as TODAY is actually yesterday.
2201 - When a date is read from the user and it is still before the time given
2202 here, the current date and time will be assumed to be yesterday, 23:59.
2203 Also, timestamps inserted in remember templates follow this rule.
2205 IMPORTANT: This is a feature whose implementation is and likely will
2206 remain incomplete. Really, it is only here because past midnight seems to
2207 be the favorite working time of John Wiegley :-)"
2208 :group 'org-time
2209 :type 'integer)
2211 (defcustom org-edit-timestamp-down-means-later nil
2212 "Non-nil means, S-down will increase the time in a time stamp.
2213 When nil, S-up will increase."
2214 :group 'org-time
2215 :type 'boolean)
2217 (defcustom org-calendar-follow-timestamp-change t
2218 "Non-nil means, make the calendar window follow timestamp changes.
2219 When a timestamp is modified and the calendar window is visible, it will be
2220 moved to the new date."
2221 :group 'org-time
2222 :type 'boolean)
2224 (defgroup org-tags nil
2225 "Options concerning tags in Org-mode."
2226 :tag "Org Tags"
2227 :group 'org)
2229 (defcustom org-tag-alist nil
2230 "List of tags allowed in Org-mode files.
2231 When this list is nil, Org-mode will base TAG input on what is already in the
2232 buffer.
2233 The value of this variable is an alist, the car of each entry must be a
2234 keyword as a string, the cdr may be a character that is used to select
2235 that tag through the fast-tag-selection interface.
2236 See the manual for details."
2237 :group 'org-tags
2238 :type '(repeat
2239 (choice
2240 (cons (string :tag "Tag name")
2241 (character :tag "Access char"))
2242 (const :tag "Start radio group" (:startgroup))
2243 (const :tag "End radio group" (:endgroup))
2244 (const :tag "New line" (:newline)))))
2246 (defcustom org-tag-persistent-alist nil
2247 "List of tags that will always appear in all Org-mode files.
2248 This is in addition to any in buffer settings or customizations
2249 of `org-tag-alist'.
2250 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2251 The value of this variable is an alist, the car of each entry must be a
2252 keyword as a string, the cdr may be a character that is used to select
2253 that tag through the fast-tag-selection interface.
2254 See the manual for details.
2255 To disable these tags on a per-file basis, insert anywhere in the file:
2256 #+STARTUP: noptag"
2257 :group 'org-tags
2258 :type '(repeat
2259 (choice
2260 (cons (string :tag "Tag name")
2261 (character :tag "Access char"))
2262 (const :tag "Start radio group" (:startgroup))
2263 (const :tag "End radio group" (:endgroup))
2264 (const :tag "New line" (:newline)))))
2266 (defvar org-file-tags nil
2267 "List of tags that can be inherited by all entries in the file.
2268 The tags will be inherited if the variable `org-use-tag-inheritance'
2269 says they should be.
2270 This variable is populated from #+TAG lines.")
2272 (defcustom org-use-fast-tag-selection 'auto
2273 "Non-nil means, use fast tag selection scheme.
2274 This is a special interface to select and deselect tags with single keys.
2275 When nil, fast selection is never used.
2276 When the symbol `auto', fast selection is used if and only if selection
2277 characters for tags have been configured, either through the variable
2278 `org-tag-alist' or through a #+TAGS line in the buffer.
2279 When t, fast selection is always used and selection keys are assigned
2280 automatically if necessary."
2281 :group 'org-tags
2282 :type '(choice
2283 (const :tag "Always" t)
2284 (const :tag "Never" nil)
2285 (const :tag "When selection characters are configured" 'auto)))
2287 (defcustom org-fast-tag-selection-single-key nil
2288 "Non-nil means, fast tag selection exits after first change.
2289 When nil, you have to press RET to exit it.
2290 During fast tag selection, you can toggle this flag with `C-c'.
2291 This variable can also have the value `expert'. In this case, the window
2292 displaying the tags menu is not even shown, until you press C-c again."
2293 :group 'org-tags
2294 :type '(choice
2295 (const :tag "No" nil)
2296 (const :tag "Yes" t)
2297 (const :tag "Expert" expert)))
2299 (defvar org-fast-tag-selection-include-todo nil
2300 "Non-nil means, fast tags selection interface will also offer TODO states.
2301 This is an undocumented feature, you should not rely on it.")
2303 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2304 "The column to which tags should be indented in a headline.
2305 If this number is positive, it specifies the column. If it is negative,
2306 it means that the tags should be flushright to that column. For example,
2307 -80 works well for a normal 80 character screen."
2308 :group 'org-tags
2309 :type 'integer)
2311 (defcustom org-auto-align-tags t
2312 "Non-nil means, realign tags after pro/demotion of TODO state change.
2313 These operations change the length of a headline and therefore shift
2314 the tags around. With this options turned on, after each such operation
2315 the tags are again aligned to `org-tags-column'."
2316 :group 'org-tags
2317 :type 'boolean)
2319 (defcustom org-use-tag-inheritance t
2320 "Non-nil means, tags in levels apply also for sublevels.
2321 When nil, only the tags directly given in a specific line apply there.
2322 This may also be a list of tags that should be inherited, or a regexp that
2323 matches tags that should be inherited. Additional control is possible
2324 with the variable `org-tags-exclude-from-inheritance' which gives an
2325 explicit list of tags to be excluded from inheritance., even if the value of
2326 `org-use-tag-inheritance' would select it for inheritance.
2328 If this option is t, a match early-on in a tree can lead to a large
2329 number of matches in the subtree when constructing the agenda or creating
2330 a sparse tree. If you only want to see the first match in a tree during
2331 a search, check out the variable `org-tags-match-list-sublevels'."
2332 :group 'org-tags
2333 :type '(choice
2334 (const :tag "Not" nil)
2335 (const :tag "Always" t)
2336 (repeat :tag "Specific tags" (string :tag "Tag"))
2337 (regexp :tag "Tags matched by regexp")))
2339 (defcustom org-tags-exclude-from-inheritance nil
2340 "List of tags that should never be inherited.
2341 This is a way to exclude a few tags from inheritance. For way to do
2342 the opposite, to actively allow inheritance for selected tags,
2343 see the variable `org-use-tag-inheritance'."
2344 :group 'org-tags
2345 :type '(repeat (string :tag "Tag")))
2347 (defun org-tag-inherit-p (tag)
2348 "Check if TAG is one that should be inherited."
2349 (cond
2350 ((member tag org-tags-exclude-from-inheritance) nil)
2351 ((eq org-use-tag-inheritance t) t)
2352 ((not org-use-tag-inheritance) nil)
2353 ((stringp org-use-tag-inheritance)
2354 (string-match org-use-tag-inheritance tag))
2355 ((listp org-use-tag-inheritance)
2356 (member tag org-use-tag-inheritance))
2357 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2359 (defcustom org-tags-match-list-sublevels t
2360 "Non-nil means list also sublevels of headlines matching a search.
2361 This variable applies to tags/property searches, and also to stuck
2362 projects because this search is based on a tags match as well.
2364 When set to the symbol `indented', sublevels are indented with
2365 leading dots.
2367 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2368 the sublevels of a headline matching a tag search often also match
2369 the same search. Listing all of them can create very long lists.
2370 Setting this variable to nil causes subtrees of a match to be skipped.
2372 This variable is semi-obsolete and probably should always be true. It
2373 is better to limit inheritance to certain tags using the variables
2374 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2375 :group 'org-tags
2376 :type '(choice
2377 (const :tag "No, don't list them" nil)
2378 (const :tag "Yes, do list them" t)
2379 (const :tag "List them, indented with leading dots" indented)))
2381 (defcustom org-tags-sort-function nil
2382 "When set, tags are sorted using this function as a comparator"
2383 :group 'org-tags
2384 :type '(choice
2385 (const :tag "No sorting" nil)
2386 (const :tag "Alphabetical" string<)
2387 (const :tag "Reverse alphabetical" string>)
2388 (function :tag "Custom function" nil)))
2390 (defvar org-tags-history nil
2391 "History of minibuffer reads for tags.")
2392 (defvar org-last-tags-completion-table nil
2393 "The last used completion table for tags.")
2394 (defvar org-after-tags-change-hook nil
2395 "Hook that is run after the tags in a line have changed.")
2397 (defgroup org-properties nil
2398 "Options concerning properties in Org-mode."
2399 :tag "Org Properties"
2400 :group 'org)
2402 (defcustom org-property-format "%-10s %s"
2403 "How property key/value pairs should be formatted by `indent-line'.
2404 When `indent-line' hits a property definition, it will format the line
2405 according to this format, mainly to make sure that the values are
2406 lined-up with respect to each other."
2407 :group 'org-properties
2408 :type 'string)
2410 (defcustom org-use-property-inheritance nil
2411 "Non-nil means, properties apply also for sublevels.
2413 This setting is chiefly used during property searches. Turning it on can
2414 cause significant overhead when doing a search, which is why it is not
2415 on by default.
2417 When nil, only the properties directly given in the current entry count.
2418 When t, every property is inherited. The value may also be a list of
2419 properties that should have inheritance, or a regular expression matching
2420 properties that should be inherited.
2422 However, note that some special properties use inheritance under special
2423 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2424 and the properties ending in \"_ALL\" when they are used as descriptor
2425 for valid values of a property.
2427 Note for programmers:
2428 When querying an entry with `org-entry-get', you can control if inheritance
2429 should be used. By default, `org-entry-get' looks only at the local
2430 properties. You can request inheritance by setting the inherit argument
2431 to t (to force inheritance) or to `selective' (to respect the setting
2432 in this variable)."
2433 :group 'org-properties
2434 :type '(choice
2435 (const :tag "Not" nil)
2436 (const :tag "Always" t)
2437 (repeat :tag "Specific properties" (string :tag "Property"))
2438 (regexp :tag "Properties matched by regexp")))
2440 (defun org-property-inherit-p (property)
2441 "Check if PROPERTY is one that should be inherited."
2442 (cond
2443 ((eq org-use-property-inheritance t) t)
2444 ((not org-use-property-inheritance) nil)
2445 ((stringp org-use-property-inheritance)
2446 (string-match org-use-property-inheritance property))
2447 ((listp org-use-property-inheritance)
2448 (member property org-use-property-inheritance))
2449 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2451 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2452 "The default column format, if no other format has been defined.
2453 This variable can be set on the per-file basis by inserting a line
2455 #+COLUMNS: %25ITEM ....."
2456 :group 'org-properties
2457 :type 'string)
2459 (defcustom org-columns-ellipses ".."
2460 "The ellipses to be used when a field in column view is truncated.
2461 When this is the empty string, as many characters as possible are shown,
2462 but then there will be no visual indication that the field has been truncated.
2463 When this is a string of length N, the last N characters of a truncated
2464 field are replaced by this string. If the column is narrower than the
2465 ellipses string, only part of the ellipses string will be shown."
2466 :group 'org-properties
2467 :type 'string)
2469 (defcustom org-columns-modify-value-for-display-function nil
2470 "Function that modifies values for display in column view.
2471 For example, it can be used to cut out a certain part from a time stamp.
2472 The function must take 2 arguments:
2474 column-title The title of the column (*not* the property name)
2475 value The value that should be modified.
2477 The function should return the value that should be displayed,
2478 or nil if the normal value should be used."
2479 :group 'org-properties
2480 :type 'function)
2482 (defcustom org-effort-property "Effort"
2483 "The property that is being used to keep track of effort estimates.
2484 Effort estimates given in this property need to have the format H:MM."
2485 :group 'org-properties
2486 :group 'org-progress
2487 :type '(string :tag "Property"))
2489 (defconst org-global-properties-fixed
2490 '(("VISIBILITY_ALL" . "folded children content all")
2491 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2492 "List of property/value pairs that can be inherited by any entry.
2494 These are fixed values, for the preset properties. The user variable
2495 that can be used to add to this list is `org-global-properties'.
2497 The entries in this list are cons cells where the car is a property
2498 name and cdr is a string with the value. If the value represents
2499 multiple items like an \"_ALL\" property, separate the items by
2500 spaces.")
2502 (defcustom org-global-properties nil
2503 "List of property/value pairs that can be inherited by any entry.
2505 This list will be combined with the constant `org-global-properties-fixed'.
2507 The entries in this list are cons cells where the car is a property
2508 name and cdr is a string with the value.
2510 You can set buffer-local values for the same purpose in the variable
2511 `org-file-properties' this by adding lines like
2513 #+PROPERTY: NAME VALUE"
2514 :group 'org-properties
2515 :type '(repeat
2516 (cons (string :tag "Property")
2517 (string :tag "Value"))))
2519 (defvar org-file-properties nil
2520 "List of property/value pairs that can be inherited by any entry.
2521 Valid for the current buffer.
2522 This variable is populated from #+PROPERTY lines.")
2523 (make-variable-buffer-local 'org-file-properties)
2525 (defgroup org-agenda nil
2526 "Options concerning agenda views in Org-mode."
2527 :tag "Org Agenda"
2528 :group 'org)
2530 (defvar org-category nil
2531 "Variable used by org files to set a category for agenda display.
2532 Such files should use a file variable to set it, for example
2534 # -*- mode: org; org-category: \"ELisp\"
2536 or contain a special line
2538 #+CATEGORY: ELisp
2540 If the file does not specify a category, then file's base name
2541 is used instead.")
2542 (make-variable-buffer-local 'org-category)
2543 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2545 (defcustom org-agenda-files nil
2546 "The files to be used for agenda display.
2547 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2548 \\[org-remove-file]. You can also use customize to edit the list.
2550 If an entry is a directory, all files in that directory that are matched by
2551 `org-agenda-file-regexp' will be part of the file list.
2553 If the value of the variable is not a list but a single file name, then
2554 the list of agenda files is actually stored and maintained in that file, one
2555 agenda file per line."
2556 :group 'org-agenda
2557 :type '(choice
2558 (repeat :tag "List of files and directories" file)
2559 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2561 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2562 "Regular expression to match files for `org-agenda-files'.
2563 If any element in the list in that variable contains a directory instead
2564 of a normal file, all files in that directory that are matched by this
2565 regular expression will be included."
2566 :group 'org-agenda
2567 :type 'regexp)
2569 (defcustom org-agenda-text-search-extra-files nil
2570 "List of extra files to be searched by text search commands.
2571 These files will be search in addition to the agenda files by the
2572 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2573 Note that these files will only be searched for text search commands,
2574 not for the other agenda views like todo lists, tag searches or the weekly
2575 agenda. This variable is intended to list notes and possibly archive files
2576 that should also be searched by these two commands.
2577 In fact, if the first element in the list is the symbol `agenda-archives',
2578 than all archive files of all agenda files will be added to the search
2579 scope."
2580 :group 'org-agenda
2581 :type '(set :greedy t
2582 (const :tag "Agenda Archives" agenda-archives)
2583 (repeat :inline t (file))))
2585 (if (fboundp 'defvaralias)
2586 (defvaralias 'org-agenda-multi-occur-extra-files
2587 'org-agenda-text-search-extra-files))
2589 (defcustom org-agenda-skip-unavailable-files nil
2590 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2591 A nil value means to remove them, after a query, from the list."
2592 :group 'org-agenda
2593 :type 'boolean)
2595 (defcustom org-calendar-to-agenda-key [?c]
2596 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2597 The command `org-calendar-goto-agenda' will be bound to this key. The
2598 default is the character `c' because then `c' can be used to switch back and
2599 forth between agenda and calendar."
2600 :group 'org-agenda
2601 :type 'sexp)
2603 (defcustom org-calendar-agenda-action-key [?k]
2604 "The key to be installed in `calendar-mode-map' for agenda-action.
2605 The command `org-agenda-action' will be bound to this key. The
2606 default is the character `k' because we use the same key in the agenda."
2607 :group 'org-agenda
2608 :type 'sexp)
2610 (eval-after-load "calendar"
2611 '(progn
2612 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2613 'org-calendar-goto-agenda)
2614 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2615 'org-agenda-action)))
2617 (defgroup org-latex nil
2618 "Options for embedding LaTeX code into Org-mode."
2619 :tag "Org LaTeX"
2620 :group 'org)
2622 (defcustom org-format-latex-options
2623 '(:foreground default :background default :scale 1.0
2624 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2625 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2626 "Options for creating images from LaTeX fragments.
2627 This is a property list with the following properties:
2628 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2629 `default' means use the foreground of the default face.
2630 :background the background color, or \"Transparent\".
2631 `default' means use the background of the default face.
2632 :scale a scaling factor for the size of the images.
2633 :html-foreground, :html-background, :html-scale
2634 the same numbers for HTML export.
2635 :matchers a list indicating which matchers should be used to
2636 find LaTeX fragments. Valid members of this list are:
2637 \"begin\" find environments
2638 \"$1\" find single characters surrounded by $.$
2639 \"$\" find math expressions surrounded by $...$
2640 \"$$\" find math expressions surrounded by $$....$$
2641 \"\\(\" find math expressions surrounded by \\(...\\)
2642 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2643 :group 'org-latex
2644 :type 'plist)
2646 (defcustom org-format-latex-header "\\documentclass{article}
2647 \\usepackage{fullpage} % do not remove
2648 \\usepackage{amssymb}
2649 \\usepackage[usenames]{color}
2650 \\usepackage{amsmath}
2651 \\usepackage{latexsym}
2652 \\usepackage[mathscr]{eucal}
2653 \\pagestyle{empty} % do not remove"
2654 "The document header used for processing LaTeX fragments."
2655 :group 'org-latex
2656 :type 'string)
2659 (defgroup org-font-lock nil
2660 "Font-lock settings for highlighting in Org-mode."
2661 :tag "Org Font Lock"
2662 :group 'org)
2664 (defcustom org-level-color-stars-only nil
2665 "Non-nil means fontify only the stars in each headline.
2666 When nil, the entire headline is fontified.
2667 Changing it requires restart of `font-lock-mode' to become effective
2668 also in regions already fontified."
2669 :group 'org-font-lock
2670 :type 'boolean)
2672 (defcustom org-hide-leading-stars nil
2673 "Non-nil means, hide the first N-1 stars in a headline.
2674 This works by using the face `org-hide' for these stars. This
2675 face is white for a light background, and black for a dark
2676 background. You may have to customize the face `org-hide' to
2677 make this work.
2678 Changing it requires restart of `font-lock-mode' to become effective
2679 also in regions already fontified.
2680 You may also set this on a per-file basis by adding one of the following
2681 lines to the buffer:
2683 #+STARTUP: hidestars
2684 #+STARTUP: showstars"
2685 :group 'org-font-lock
2686 :type 'boolean)
2688 (defcustom org-fontify-done-headline nil
2689 "Non-nil means, change the face of a headline if it is marked DONE.
2690 Normally, only the TODO/DONE keyword indicates the state of a headline.
2691 When this is non-nil, the headline after the keyword is set to the
2692 `org-headline-done' as an additional indication."
2693 :group 'org-font-lock
2694 :type 'boolean)
2696 (defcustom org-fontify-emphasized-text t
2697 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2698 Changing this variable requires a restart of Emacs to take effect."
2699 :group 'org-font-lock
2700 :type 'boolean)
2702 (defcustom org-fontify-whole-heading-line nil
2703 "Non-nil means fontify the whole line for headings.
2704 This is useful when setting a background color for the
2705 org-leve-* faces."
2706 :group 'org-font-lock
2707 :type 'boolean)
2709 (defcustom org-highlight-latex-fragments-and-specials nil
2710 "Non-nil means, fontify what is treated specially by the exporters."
2711 :group 'org-font-lock
2712 :type 'boolean)
2714 (defcustom org-hide-emphasis-markers nil
2715 "Non-nil mean font-lock should hide the emphasis marker characters."
2716 :group 'org-font-lock
2717 :type 'boolean)
2719 (defvar org-emph-re nil
2720 "Regular expression for matching emphasis.")
2721 (defvar org-verbatim-re nil
2722 "Regular expression for matching verbatim text.")
2723 (defvar org-emphasis-regexp-components) ; defined just below
2724 (defvar org-emphasis-alist) ; defined just below
2725 (defun org-set-emph-re (var val)
2726 "Set variable and compute the emphasis regular expression."
2727 (set var val)
2728 (when (and (boundp 'org-emphasis-alist)
2729 (boundp 'org-emphasis-regexp-components)
2730 org-emphasis-alist org-emphasis-regexp-components)
2731 (let* ((e org-emphasis-regexp-components)
2732 (pre (car e))
2733 (post (nth 1 e))
2734 (border (nth 2 e))
2735 (body (nth 3 e))
2736 (nl (nth 4 e))
2737 (body1 (concat body "*?"))
2738 (markers (mapconcat 'car org-emphasis-alist ""))
2739 (vmarkers (mapconcat
2740 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2741 org-emphasis-alist "")))
2742 ;; make sure special characters appear at the right position in the class
2743 (if (string-match "\\^" markers)
2744 (setq markers (concat (replace-match "" t t markers) "^")))
2745 (if (string-match "-" markers)
2746 (setq markers (concat (replace-match "" t t markers) "-")))
2747 (if (string-match "\\^" vmarkers)
2748 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2749 (if (string-match "-" vmarkers)
2750 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2751 (if (> nl 0)
2752 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2753 (int-to-string nl) "\\}")))
2754 ;; Make the regexp
2755 (setq org-emph-re
2756 (concat "\\([" pre "]\\|^\\)"
2757 "\\("
2758 "\\([" markers "]\\)"
2759 "\\("
2760 "[^" border "]\\|"
2761 "[^" border "]"
2762 body1
2763 "[^" border "]"
2764 "\\)"
2765 "\\3\\)"
2766 "\\([" post "]\\|$\\)"))
2767 (setq org-verbatim-re
2768 (concat "\\([" pre "]\\|^\\)"
2769 "\\("
2770 "\\([" vmarkers "]\\)"
2771 "\\("
2772 "[^" border "]\\|"
2773 "[^" border "]"
2774 body1
2775 "[^" border "]"
2776 "\\)"
2777 "\\3\\)"
2778 "\\([" post "]\\|$\\)")))))
2780 (defcustom org-emphasis-regexp-components
2781 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
2782 "Components used to build the regular expression for emphasis.
2783 This is a list with 6 entries. Terminology: In an emphasis string
2784 like \" *strong word* \", we call the initial space PREMATCH, the final
2785 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2786 and \"trong wor\" is the body. The different components in this variable
2787 specify what is allowed/forbidden in each part:
2789 pre Chars allowed as prematch. Beginning of line will be allowed too.
2790 post Chars allowed as postmatch. End of line will be allowed too.
2791 border The chars *forbidden* as border characters.
2792 body-regexp A regexp like \".\" to match a body character. Don't use
2793 non-shy groups here, and don't allow newline here.
2794 newline The maximum number of newlines allowed in an emphasis exp.
2796 Use customize to modify this, or restart Emacs after changing it."
2797 :group 'org-font-lock
2798 :set 'org-set-emph-re
2799 :type '(list
2800 (sexp :tag "Allowed chars in pre ")
2801 (sexp :tag "Allowed chars in post ")
2802 (sexp :tag "Forbidden chars in border ")
2803 (sexp :tag "Regexp for body ")
2804 (integer :tag "number of newlines allowed")
2805 (option (boolean :tag "Please ignore this button"))))
2807 (defcustom org-emphasis-alist
2808 `(("*" bold "<b>" "</b>")
2809 ("/" italic "<i>" "</i>")
2810 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2811 ("=" org-code "<code>" "</code>" verbatim)
2812 ("~" org-verbatim "<code>" "</code>" verbatim)
2813 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2814 "<del>" "</del>")
2816 "Special syntax for emphasized text.
2817 Text starting and ending with a special character will be emphasized, for
2818 example *bold*, _underlined_ and /italic/. This variable sets the marker
2819 characters, the face to be used by font-lock for highlighting in Org-mode
2820 Emacs buffers, and the HTML tags to be used for this.
2821 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
2822 Use customize to modify this, or restart Emacs after changing it."
2823 :group 'org-font-lock
2824 :set 'org-set-emph-re
2825 :type '(repeat
2826 (list
2827 (string :tag "Marker character")
2828 (choice
2829 (face :tag "Font-lock-face")
2830 (plist :tag "Face property list"))
2831 (string :tag "HTML start tag")
2832 (string :tag "HTML end tag")
2833 (option (const verbatim)))))
2835 (defvar org-protecting-blocks
2836 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
2837 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
2838 This is needed for font-lock setup.")
2840 ;;; Miscellaneous options
2842 (defgroup org-completion nil
2843 "Completion in Org-mode."
2844 :tag "Org Completion"
2845 :group 'org)
2847 (defcustom org-completion-use-ido nil
2848 "Non-nil means, use ido completion wherever possible.
2849 Note that `ido-mode' must be active for this variable to be relevant.
2850 If you decide to turn this variable on, you might well want to turn off
2851 `org-outline-path-complete-in-steps'."
2852 :group 'org-completion
2853 :type 'boolean)
2855 (defcustom org-completion-fallback-command 'hippie-expand
2856 "The expansion command called by \\[org-complete] in normal context.
2857 Normal means, no org-mode-specific context."
2858 :group 'org-completion
2859 :type 'function)
2861 ;;; Functions and variables from ther packages
2862 ;; Declared here to avoid compiler warnings
2864 ;; XEmacs only
2865 (defvar outline-mode-menu-heading)
2866 (defvar outline-mode-menu-show)
2867 (defvar outline-mode-menu-hide)
2868 (defvar zmacs-regions) ; XEmacs regions
2870 ;; Emacs only
2871 (defvar mark-active)
2873 ;; Various packages
2874 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2875 (declare-function calendar-forward-day "cal-move" (arg))
2876 (declare-function calendar-goto-date "cal-move" (date))
2877 (declare-function calendar-goto-today "cal-move" ())
2878 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2879 (defvar calc-embedded-close-formula)
2880 (defvar calc-embedded-open-formula)
2881 (declare-function cdlatex-tab "ext:cdlatex" ())
2882 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2883 (defvar font-lock-unfontify-region-function)
2884 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2885 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2886 (defvar iswitchb-temp-buflist)
2887 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2888 (defvar org-agenda-tags-todo-honor-ignore-options)
2889 (declare-function org-agenda-skip "org-agenda" ())
2890 (declare-function org-format-agenda-item "org-agenda"
2891 (extra txt &optional category tags dotime noprefix remove-re))
2892 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2893 (declare-function org-agenda-change-all-lines "org-agenda"
2894 (newhead hdmarker &optional fixface just-this))
2895 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2896 (declare-function org-agenda-maybe-redo "org-agenda" ())
2897 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2898 (beg end))
2899 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2900 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2901 "org-agenda" (&optional end))
2902 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
2903 (declare-function org-indent-mode "org-indent" (arg))
2904 (declare-function parse-time-string "parse-time" (string))
2905 (declare-function remember "remember" (&optional initial))
2906 (declare-function remember-buffer-desc "remember" ())
2907 (declare-function remember-finalize "remember" ())
2908 (defvar remember-save-after-remembering)
2909 (defvar remember-data-file)
2910 (defvar remember-register)
2911 (defvar remember-buffer)
2912 (defvar remember-handler-functions)
2913 (defvar remember-annotation-functions)
2914 (defvar texmathp-why)
2915 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2916 (declare-function table--at-cell-p "table" (position &optional object at-column))
2918 (defvar w3m-current-url)
2919 (defvar w3m-current-title)
2921 (defvar org-latex-regexps)
2923 ;;; Autoload and prepare some org modules
2925 ;; Some table stuff that needs to be defined here, because it is used
2926 ;; by the functions setting up org-mode or checking for table context.
2928 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2929 "Detects an org-type or table-type table.")
2930 (defconst org-table-line-regexp "^[ \t]*|"
2931 "Detects an org-type table line.")
2932 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2933 "Detects an org-type table line.")
2934 (defconst org-table-hline-regexp "^[ \t]*|-"
2935 "Detects an org-type table hline.")
2936 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2937 "Detects a table-type table hline.")
2938 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2939 "Searching from within a table (any type) this finds the first line
2940 outside the table.")
2942 ;; Autoload the functions in org-table.el that are needed by functions here.
2944 (eval-and-compile
2945 (org-autoload "org-table"
2946 '(org-table-align org-table-begin org-table-blank-field
2947 org-table-convert org-table-convert-region org-table-copy-down
2948 org-table-copy-region org-table-create
2949 org-table-create-or-convert-from-region
2950 org-table-create-with-table.el org-table-current-dline
2951 org-table-cut-region org-table-delete-column org-table-edit-field
2952 org-table-edit-formulas org-table-end org-table-eval-formula
2953 org-table-export org-table-field-info
2954 org-table-get-stored-formulas org-table-goto-column
2955 org-table-hline-and-move org-table-import org-table-insert-column
2956 org-table-insert-hline org-table-insert-row org-table-iterate
2957 org-table-justify-field-maybe org-table-kill-row
2958 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2959 org-table-move-column org-table-move-column-left
2960 org-table-move-column-right org-table-move-row
2961 org-table-move-row-down org-table-move-row-up
2962 org-table-next-field org-table-next-row org-table-paste-rectangle
2963 org-table-previous-field org-table-recalculate
2964 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2965 org-table-toggle-coordinate-overlays
2966 org-table-toggle-formula-debugger org-table-wrap-region
2967 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2969 (defun org-at-table-p (&optional table-type)
2970 "Return t if the cursor is inside an org-type table.
2971 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2972 (if org-enable-table-editor
2973 (save-excursion
2974 (beginning-of-line 1)
2975 (looking-at (if table-type org-table-any-line-regexp
2976 org-table-line-regexp)))
2977 nil))
2978 (defsubst org-table-p () (org-at-table-p))
2980 (defun org-at-table.el-p ()
2981 "Return t if and only if we are at a table.el table."
2982 (and (org-at-table-p 'any)
2983 (save-excursion
2984 (goto-char (org-table-begin 'any))
2985 (looking-at org-table1-hline-regexp))))
2986 (defun org-table-recognize-table.el ()
2987 "If there is a table.el table nearby, recognize it and move into it."
2988 (if org-table-tab-recognizes-table.el
2989 (if (org-at-table.el-p)
2990 (progn
2991 (beginning-of-line 1)
2992 (if (looking-at org-table-dataline-regexp)
2994 (if (looking-at org-table1-hline-regexp)
2995 (progn
2996 (beginning-of-line 2)
2997 (if (looking-at org-table-any-border-regexp)
2998 (beginning-of-line -1)))))
2999 (if (re-search-forward "|" (org-table-end t) t)
3000 (progn
3001 (require 'table)
3002 (if (table--at-cell-p (point))
3004 (message "recognizing table.el table...")
3005 (table-recognize-table)
3006 (message "recognizing table.el table...done")))
3007 (error "This should not happen..."))
3009 nil)
3010 nil))
3012 (defun org-at-table-hline-p ()
3013 "Return t if the cursor is inside a hline in a table."
3014 (if org-enable-table-editor
3015 (save-excursion
3016 (beginning-of-line 1)
3017 (looking-at org-table-hline-regexp))
3018 nil))
3020 (defvar org-table-clean-did-remove-column nil)
3022 (defun org-table-map-tables (function)
3023 "Apply FUNCTION to the start of all tables in the buffer."
3024 (save-excursion
3025 (save-restriction
3026 (widen)
3027 (goto-char (point-min))
3028 (while (re-search-forward org-table-any-line-regexp nil t)
3029 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
3030 (beginning-of-line 1)
3031 (if (looking-at org-table-line-regexp)
3032 (save-excursion (funcall function)))
3033 (re-search-forward org-table-any-border-regexp nil 1))))
3034 (message "Mapping tables: done"))
3036 ;; Declare and autoload functions from org-exp.el & Co
3038 (declare-function org-default-export-plist "org-exp")
3039 (declare-function org-infile-export-plist "org-exp")
3040 (declare-function org-get-current-options "org-exp")
3041 (eval-and-compile
3042 (org-autoload "org-exp"
3043 '(org-export org-export-visible
3044 org-insert-export-options-template
3045 org-table-clean-before-export))
3046 (org-autoload "org-ascii"
3047 '(org-export-as-ascii org-export-ascii-preprocess
3048 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3049 org-export-region-as-ascii))
3050 (org-autoload "org-html"
3051 '(org-export-as-html-and-open
3052 org-export-as-html-batch org-export-as-html-to-buffer
3053 org-replace-region-by-html org-export-region-as-html
3054 org-export-as-html))
3055 (org-autoload "org-icalendar"
3056 '(org-export-icalendar-this-file
3057 org-export-icalendar-all-agenda-files
3058 org-export-icalendar-combine-agenda-files))
3059 (org-autoload "org-xoxo" '(org-export-as-xoxo)))
3061 ;; Declare and autoload functions from org-agenda.el
3063 (eval-and-compile
3064 (org-autoload "org-agenda"
3065 '(org-agenda org-agenda-list org-search-view
3066 org-todo-list org-tags-view org-agenda-list-stuck-projects
3067 org-diary org-agenda-to-appt
3068 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3070 ;; Autoload org-remember
3072 (eval-and-compile
3073 (org-autoload "org-remember"
3074 '(org-remember-insinuate org-remember-annotation
3075 org-remember-apply-template org-remember org-remember-handler)))
3077 ;; Autoload org-clock.el
3080 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3081 (beg end))
3082 (declare-function org-clock-update-mode-line "org-clock" ())
3083 (defvar org-clock-start-time)
3084 (defvar org-clock-marker (make-marker)
3085 "Marker recording the last clock-in.")
3086 (defun org-clock-is-active ()
3087 "Return non-nil if clock is currently running.
3088 The return value is actually the clock marker."
3089 (marker-buffer org-clock-marker))
3091 (eval-and-compile
3092 (org-autoload
3093 "org-clock"
3094 '(org-clock-in org-clock-out org-clock-cancel
3095 org-clock-goto org-clock-sum org-clock-display
3096 org-clock-remove-overlays org-clock-report
3097 org-clocktable-shift org-dblock-write:clocktable
3098 org-get-clocktable)))
3100 (defun org-clock-update-time-maybe ()
3101 "If this is a CLOCK line, update it and return t.
3102 Otherwise, return nil."
3103 (interactive)
3104 (save-excursion
3105 (beginning-of-line 1)
3106 (skip-chars-forward " \t")
3107 (when (looking-at org-clock-string)
3108 (let ((re (concat "[ \t]*" org-clock-string
3109 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3110 "\\([ \t]*=>.*\\)?\\)?"))
3111 ts te h m s neg)
3112 (cond
3113 ((not (looking-at re))
3114 nil)
3115 ((not (match-end 2))
3116 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3117 (> org-clock-marker (point))
3118 (<= org-clock-marker (point-at-eol)))
3119 ;; The clock is running here
3120 (setq org-clock-start-time
3121 (apply 'encode-time
3122 (org-parse-time-string (match-string 1))))
3123 (org-clock-update-mode-line)))
3125 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3126 (end-of-line 1)
3127 (setq ts (match-string 1)
3128 te (match-string 3))
3129 (setq s (- (time-to-seconds
3130 (apply 'encode-time (org-parse-time-string te)))
3131 (time-to-seconds
3132 (apply 'encode-time (org-parse-time-string ts))))
3133 neg (< s 0)
3134 s (abs s)
3135 h (floor (/ s 3600))
3136 s (- s (* 3600 h))
3137 m (floor (/ s 60))
3138 s (- s (* 60 s)))
3139 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3140 t))))))
3142 (defun org-check-running-clock ()
3143 "Check if the current buffer contains the running clock.
3144 If yes, offer to stop it and to save the buffer with the changes."
3145 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3146 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3147 (buffer-name))))
3148 (org-clock-out)
3149 (when (y-or-n-p "Save changed buffer?")
3150 (save-buffer))))
3152 (defun org-clocktable-try-shift (dir n)
3153 "Check if this line starts a clock table, if yes, shift the time block."
3154 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3155 (org-clocktable-shift dir n)))
3157 ;; Autoload org-timer.el
3159 (eval-and-compile
3160 (org-autoload
3161 "org-timer"
3162 '(org-timer-start org-timer org-timer-item
3163 org-timer-change-times-in-region
3164 org-timer-set-timer
3165 org-timer-reset-timers
3166 org-timer-show-remaining-time)))
3168 ;; Autoload org-feed.el
3170 (eval-and-compile
3171 (org-autoload
3172 "org-feed"
3173 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3176 ;; Autoload org-indent.el
3178 (eval-and-compile
3179 (org-autoload
3180 "org-indent"
3181 '(org-indent-mode)))
3183 ;; Autoload archiving code
3184 ;; The stuff that is needed for cycling and tags has to be defined here.
3186 (defgroup org-archive nil
3187 "Options concerning archiving in Org-mode."
3188 :tag "Org Archive"
3189 :group 'org-structure)
3191 (defcustom org-archive-location "%s_archive::"
3192 "The location where subtrees should be archived.
3194 The value of this variable is a string, consisting of two parts,
3195 separated by a double-colon. The first part is a filename and
3196 the second part is a headline.
3198 When the filename is omitted, archiving happens in the same file.
3199 %s in the filename will be replaced by the current file
3200 name (without the directory part). Archiving to a different file
3201 is useful to keep archived entries from contributing to the
3202 Org-mode Agenda.
3204 The archived entries will be filed as subtrees of the specified
3205 headline. When the headline is omitted, the subtrees are simply
3206 filed away at the end of the file, as top-level entries. Also in
3207 the heading you can use %s to represent the file name, this can be
3208 useful when using the same archive for a number of different files.
3210 Here are a few examples:
3211 \"%s_archive::\"
3212 If the current file is Projects.org, archive in file
3213 Projects.org_archive, as top-level trees. This is the default.
3215 \"::* Archived Tasks\"
3216 Archive in the current file, under the top-level headline
3217 \"* Archived Tasks\".
3219 \"~/org/archive.org::\"
3220 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3222 \"~/org/archive.org::From %s\"
3223 Archive in file ~/org/archive.org (absolute path), und headlines
3224 \"From FILENAME\" where file name is the current file name.
3226 \"basement::** Finished Tasks\"
3227 Archive in file ./basement (relative path), as level 3 trees
3228 below the level 2 heading \"** Finished Tasks\".
3230 You may set this option on a per-file basis by adding to the buffer a
3231 line like
3233 #+ARCHIVE: basement::** Finished Tasks
3235 You may also define it locally for a subtree by setting an ARCHIVE property
3236 in the entry. If such a property is found in an entry, or anywhere up
3237 the hierarchy, it will be used."
3238 :group 'org-archive
3239 :type 'string)
3241 (defcustom org-archive-tag "ARCHIVE"
3242 "The tag that marks a subtree as archived.
3243 An archived subtree does not open during visibility cycling, and does
3244 not contribute to the agenda listings.
3245 After changing this, font-lock must be restarted in the relevant buffers to
3246 get the proper fontification."
3247 :group 'org-archive
3248 :group 'org-keywords
3249 :type 'string)
3251 (defcustom org-agenda-skip-archived-trees t
3252 "Non-nil means, the agenda will skip any items located in archived trees.
3253 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3254 variable is no longer recommended, you should leave it at the value t.
3255 Instead, use the key `v' to cycle the archives-mode in the agenda."
3256 :group 'org-archive
3257 :group 'org-agenda-skip
3258 :type 'boolean)
3260 (defcustom org-columns-skip-arrchived-trees t
3261 "Non-nil means, irgnore archived trees when creating column view."
3262 :group 'org-archive
3263 :group 'org-properties
3264 :type 'boolean)
3266 (defcustom org-cycle-open-archived-trees nil
3267 "Non-nil means, `org-cycle' will open archived trees.
3268 An archived tree is a tree marked with the tag ARCHIVE.
3269 When nil, archived trees will stay folded. You can still open them with
3270 normal outline commands like `show-all', but not with the cycling commands."
3271 :group 'org-archive
3272 :group 'org-cycle
3273 :type 'boolean)
3275 (defcustom org-sparse-tree-open-archived-trees nil
3276 "Non-nil means sparse tree construction shows matches in archived trees.
3277 When nil, matches in these trees are highlighted, but the trees are kept in
3278 collapsed state."
3279 :group 'org-archive
3280 :group 'org-sparse-trees
3281 :type 'boolean)
3283 (defun org-cycle-hide-archived-subtrees (state)
3284 "Re-hide all archived subtrees after a visibility state change."
3285 (when (and (not org-cycle-open-archived-trees)
3286 (not (memq state '(overview folded))))
3287 (save-excursion
3288 (let* ((globalp (memq state '(contents all)))
3289 (beg (if globalp (point-min) (point)))
3290 (end (if globalp (point-max) (org-end-of-subtree t))))
3291 (org-hide-archived-subtrees beg end)
3292 (goto-char beg)
3293 (if (looking-at (concat ".*:" org-archive-tag ":"))
3294 (message "%s" (substitute-command-keys
3295 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3297 (defun org-force-cycle-archived ()
3298 "Cycle subtree even if it is archived."
3299 (interactive)
3300 (setq this-command 'org-cycle)
3301 (let ((org-cycle-open-archived-trees t))
3302 (call-interactively 'org-cycle)))
3304 (defun org-hide-archived-subtrees (beg end)
3305 "Re-hide all archived subtrees after a visibility state change."
3306 (save-excursion
3307 (let* ((re (concat ":" org-archive-tag ":")))
3308 (goto-char beg)
3309 (while (re-search-forward re end t)
3310 (and (org-on-heading-p) (hide-subtree))
3311 (org-end-of-subtree t)))))
3313 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3315 (eval-and-compile
3316 (org-autoload "org-archive"
3317 '(org-add-archive-files org-archive-subtree
3318 org-archive-to-archive-sibling org-toggle-archive-tag)))
3320 ;; Autoload Column View Code
3322 (declare-function org-columns-number-to-string "org-colview")
3323 (declare-function org-columns-get-format-and-top-level "org-colview")
3324 (declare-function org-columns-compute "org-colview")
3326 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3327 '(org-columns-number-to-string org-columns-get-format-and-top-level
3328 org-columns-compute org-agenda-columns org-columns-remove-overlays
3329 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3331 ;; Autoload ID code
3333 (declare-function org-id-store-link "org-id")
3334 (declare-function org-id-locations-load "org-id")
3335 (declare-function org-id-locations-save "org-id")
3336 (defvar org-id-track-globally)
3337 (org-autoload "org-id"
3338 '(org-id-get-create org-id-new org-id-copy org-id-get
3339 org-id-get-with-outline-path-completion
3340 org-id-get-with-outline-drilling
3341 org-id-goto org-id-find org-id-store-link))
3343 ;; Autoload Plotting Code
3345 (org-autoload "org-plot"
3346 '(org-plot/gnuplot))
3348 ;;; Variables for pre-computed regular expressions, all buffer local
3350 (defvar org-drawer-regexp nil
3351 "Matches first line of a hidden block.")
3352 (make-variable-buffer-local 'org-drawer-regexp)
3353 (defvar org-todo-regexp nil
3354 "Matches any of the TODO state keywords.")
3355 (make-variable-buffer-local 'org-todo-regexp)
3356 (defvar org-not-done-regexp nil
3357 "Matches any of the TODO state keywords except the last one.")
3358 (make-variable-buffer-local 'org-not-done-regexp)
3359 (defvar org-not-done-heading-regexp nil
3360 "Matches a TODO headline that is not done.")
3361 (make-variable-buffer-local 'org-not-done-regexp)
3362 (defvar org-todo-line-regexp nil
3363 "Matches a headline and puts TODO state into group 2 if present.")
3364 (make-variable-buffer-local 'org-todo-line-regexp)
3365 (defvar org-complex-heading-regexp nil
3366 "Matches a headline and puts everything into groups:
3367 group 1: the stars
3368 group 2: The todo keyword, maybe
3369 group 3: Priority cookie
3370 group 4: True headline
3371 group 5: Tags")
3372 (make-variable-buffer-local 'org-complex-heading-regexp)
3373 (defvar org-todo-line-tags-regexp nil
3374 "Matches a headline and puts TODO state into group 2 if present.
3375 Also put tags into group 4 if tags are present.")
3376 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3377 (defvar org-nl-done-regexp nil
3378 "Matches newline followed by a headline with the DONE keyword.")
3379 (make-variable-buffer-local 'org-nl-done-regexp)
3380 (defvar org-looking-at-done-regexp nil
3381 "Matches the DONE keyword a point.")
3382 (make-variable-buffer-local 'org-looking-at-done-regexp)
3383 (defvar org-ds-keyword-length 12
3384 "Maximum length of the Deadline and SCHEDULED keywords.")
3385 (make-variable-buffer-local 'org-ds-keyword-length)
3386 (defvar org-deadline-regexp nil
3387 "Matches the DEADLINE keyword.")
3388 (make-variable-buffer-local 'org-deadline-regexp)
3389 (defvar org-deadline-time-regexp nil
3390 "Matches the DEADLINE keyword together with a time stamp.")
3391 (make-variable-buffer-local 'org-deadline-time-regexp)
3392 (defvar org-deadline-line-regexp nil
3393 "Matches the DEADLINE keyword and the rest of the line.")
3394 (make-variable-buffer-local 'org-deadline-line-regexp)
3395 (defvar org-scheduled-regexp nil
3396 "Matches the SCHEDULED keyword.")
3397 (make-variable-buffer-local 'org-scheduled-regexp)
3398 (defvar org-scheduled-time-regexp nil
3399 "Matches the SCHEDULED keyword together with a time stamp.")
3400 (make-variable-buffer-local 'org-scheduled-time-regexp)
3401 (defvar org-closed-time-regexp nil
3402 "Matches the CLOSED keyword together with a time stamp.")
3403 (make-variable-buffer-local 'org-closed-time-regexp)
3405 (defvar org-keyword-time-regexp nil
3406 "Matches any of the 4 keywords, together with the time stamp.")
3407 (make-variable-buffer-local 'org-keyword-time-regexp)
3408 (defvar org-keyword-time-not-clock-regexp nil
3409 "Matches any of the 3 keywords, together with the time stamp.")
3410 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3411 (defvar org-maybe-keyword-time-regexp nil
3412 "Matches a timestamp, possibly preceeded by a keyword.")
3413 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3414 (defvar org-planning-or-clock-line-re nil
3415 "Matches a line with planning or clock info.")
3416 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3418 (defconst org-plain-time-of-day-regexp
3419 (concat
3420 "\\(\\<[012]?[0-9]"
3421 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3422 "\\(--?"
3423 "\\(\\<[012]?[0-9]"
3424 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3425 "\\)?")
3426 "Regular expression to match a plain time or time range.
3427 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3428 groups carry important information:
3429 0 the full match
3430 1 the first time, range or not
3431 8 the second time, if it is a range.")
3433 (defconst org-plain-time-extension-regexp
3434 (concat
3435 "\\(\\<[012]?[0-9]"
3436 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3437 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3438 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3439 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3440 groups carry important information:
3441 0 the full match
3442 7 hours of duration
3443 9 minutes of duration")
3445 (defconst org-stamp-time-of-day-regexp
3446 (concat
3447 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3448 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3449 "\\(--?"
3450 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3451 "Regular expression to match a timestamp time or time range.
3452 After a match, the following groups carry important information:
3453 0 the full match
3454 1 date plus weekday, for backreferencing to make sure both times on same day
3455 2 the first time, range or not
3456 4 the second time, if it is a range.")
3458 (defconst org-startup-options
3459 '(("fold" org-startup-folded t)
3460 ("overview" org-startup-folded t)
3461 ("nofold" org-startup-folded nil)
3462 ("showall" org-startup-folded nil)
3463 ("content" org-startup-folded content)
3464 ("indent" org-startup-indented t)
3465 ("noindent" org-startup-indented nil)
3466 ("hidestars" org-hide-leading-stars t)
3467 ("showstars" org-hide-leading-stars nil)
3468 ("odd" org-odd-levels-only t)
3469 ("oddeven" org-odd-levels-only nil)
3470 ("align" org-startup-align-all-tables t)
3471 ("noalign" org-startup-align-all-tables nil)
3472 ("customtime" org-display-custom-times t)
3473 ("logdone" org-log-done time)
3474 ("lognotedone" org-log-done note)
3475 ("nologdone" org-log-done nil)
3476 ("lognoteclock-out" org-log-note-clock-out t)
3477 ("nolognoteclock-out" org-log-note-clock-out nil)
3478 ("logrepeat" org-log-repeat state)
3479 ("lognoterepeat" org-log-repeat note)
3480 ("nologrepeat" org-log-repeat nil)
3481 ("fninline" org-footnote-define-inline t)
3482 ("nofninline" org-footnote-define-inline nil)
3483 ("fnlocal" org-footnote-section nil)
3484 ("fnauto" org-footnote-auto-label t)
3485 ("fnprompt" org-footnote-auto-label nil)
3486 ("fnconfirm" org-footnote-auto-label confirm)
3487 ("fnplain" org-footnote-auto-label plain)
3488 ("fnadjust" org-footnote-auto-adjust t)
3489 ("nofnadjust" org-footnote-auto-adjust nil)
3490 ("constcgs" constants-unit-system cgs)
3491 ("constSI" constants-unit-system SI)
3492 ("noptag" org-tag-persistent-alist nil)
3493 ("hideblocks" org-hide-block-startup t)
3494 ("nohideblocks" org-hide-block-startup nil))
3495 "Variable associated with STARTUP options for org-mode.
3496 Each element is a list of three items: The startup options as written
3497 in the #+STARTUP line, the corresponding variable, and the value to
3498 set this variable to if the option is found. An optional forth element PUSH
3499 means to push this value onto the list in the variable.")
3501 (defun org-set-regexps-and-options ()
3502 "Precompute regular expressions for current buffer."
3503 (when (org-mode-p)
3504 (org-set-local 'org-todo-kwd-alist nil)
3505 (org-set-local 'org-todo-key-alist nil)
3506 (org-set-local 'org-todo-key-trigger nil)
3507 (org-set-local 'org-todo-keywords-1 nil)
3508 (org-set-local 'org-done-keywords nil)
3509 (org-set-local 'org-todo-heads nil)
3510 (org-set-local 'org-todo-sets nil)
3511 (org-set-local 'org-todo-log-states nil)
3512 (org-set-local 'org-file-properties nil)
3513 (org-set-local 'org-file-tags nil)
3514 (let ((re (org-make-options-regexp
3515 '("CATEGORY" "TODO" "COLUMNS"
3516 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3517 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3518 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3519 (splitre "[ \t]+")
3520 kwds kws0 kwsa key log value cat arch tags const links hw dws
3521 tail sep kws1 prio props ftags drawers
3522 ext-setup-or-nil setup-contents (start 0))
3523 (save-excursion
3524 (save-restriction
3525 (widen)
3526 (goto-char (point-min))
3527 (while (or (and ext-setup-or-nil
3528 (string-match re ext-setup-or-nil start)
3529 (setq start (match-end 0)))
3530 (and (setq ext-setup-or-nil nil start 0)
3531 (re-search-forward re nil t)))
3532 (setq key (upcase (match-string 1 ext-setup-or-nil))
3533 value (org-match-string-no-properties 2 ext-setup-or-nil))
3534 (cond
3535 ((equal key "CATEGORY")
3536 (if (string-match "[ \t]+$" value)
3537 (setq value (replace-match "" t t value)))
3538 (setq cat value))
3539 ((member key '("SEQ_TODO" "TODO"))
3540 (push (cons 'sequence (org-split-string value splitre)) kwds))
3541 ((equal key "TYP_TODO")
3542 (push (cons 'type (org-split-string value splitre)) kwds))
3543 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3544 ;; general TODO-like setup
3545 (push (cons (intern (downcase (match-string 1 key)))
3546 (org-split-string value splitre)) kwds))
3547 ((equal key "TAGS")
3548 (setq tags (append tags (if tags '("\\n") nil)
3549 (org-split-string value splitre))))
3550 ((equal key "COLUMNS")
3551 (org-set-local 'org-columns-default-format value))
3552 ((equal key "LINK")
3553 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3554 (push (cons (match-string 1 value)
3555 (org-trim (match-string 2 value)))
3556 links)))
3557 ((equal key "PRIORITIES")
3558 (setq prio (org-split-string value " +")))
3559 ((equal key "PROPERTY")
3560 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3561 (push (cons (match-string 1 value) (match-string 2 value))
3562 props)))
3563 ((equal key "FILETAGS")
3564 (when (string-match "\\S-" value)
3565 (setq ftags
3566 (append
3567 ftags
3568 (apply 'append
3569 (mapcar (lambda (x) (org-split-string x ":"))
3570 (org-split-string value)))))))
3571 ((equal key "DRAWERS")
3572 (setq drawers (org-split-string value splitre)))
3573 ((equal key "CONSTANTS")
3574 (setq const (append const (org-split-string value splitre))))
3575 ((equal key "STARTUP")
3576 (let ((opts (org-split-string value splitre))
3577 l var val)
3578 (while (setq l (pop opts))
3579 (when (setq l (assoc l org-startup-options))
3580 (setq var (nth 1 l) val (nth 2 l))
3581 (if (not (nth 3 l))
3582 (set (make-local-variable var) val)
3583 (if (not (listp (symbol-value var)))
3584 (set (make-local-variable var) nil))
3585 (set (make-local-variable var) (symbol-value var))
3586 (add-to-list var val))))))
3587 ((equal key "ARCHIVE")
3588 (string-match " *$" value)
3589 (setq arch (replace-match "" t t value))
3590 (remove-text-properties 0 (length arch)
3591 '(face t fontified t) arch))
3592 ((equal key "SETUPFILE")
3593 (setq setup-contents (org-file-contents
3594 (expand-file-name
3595 (org-remove-double-quotes value))
3596 'noerror))
3597 (if (not ext-setup-or-nil)
3598 (setq ext-setup-or-nil setup-contents start 0)
3599 (setq ext-setup-or-nil
3600 (concat (substring ext-setup-or-nil 0 start)
3601 "\n" setup-contents "\n"
3602 (substring ext-setup-or-nil start)))))
3603 ))))
3604 (when cat
3605 (org-set-local 'org-category (intern cat))
3606 (push (cons "CATEGORY" cat) props))
3607 (when prio
3608 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3609 (setq prio (mapcar 'string-to-char prio))
3610 (org-set-local 'org-highest-priority (nth 0 prio))
3611 (org-set-local 'org-lowest-priority (nth 1 prio))
3612 (org-set-local 'org-default-priority (nth 2 prio)))
3613 (and props (org-set-local 'org-file-properties (nreverse props)))
3614 (and ftags (org-set-local 'org-file-tags
3615 (mapcar 'org-add-prop-inherited ftags)))
3616 (and drawers (org-set-local 'org-drawers drawers))
3617 (and arch (org-set-local 'org-archive-location arch))
3618 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3619 ;; Process the TODO keywords
3620 (unless kwds
3621 ;; Use the global values as if they had been given locally.
3622 (setq kwds (default-value 'org-todo-keywords))
3623 (if (stringp (car kwds))
3624 (setq kwds (list (cons org-todo-interpretation
3625 (default-value 'org-todo-keywords)))))
3626 (setq kwds (reverse kwds)))
3627 (setq kwds (nreverse kwds))
3628 (let (inter kws kw)
3629 (while (setq kws (pop kwds))
3630 (let ((kws (or
3631 (run-hook-with-args-until-success
3632 'org-todo-setup-filter-hook kws)
3633 kws)))
3634 (setq inter (pop kws) sep (member "|" kws)
3635 kws0 (delete "|" (copy-sequence kws))
3636 kwsa nil
3637 kws1 (mapcar
3638 (lambda (x)
3639 ;; 1 2
3640 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3641 (progn
3642 (setq kw (match-string 1 x)
3643 key (and (match-end 2) (match-string 2 x))
3644 log (org-extract-log-state-settings x))
3645 (push (cons kw (and key (string-to-char key))) kwsa)
3646 (and log (push log org-todo-log-states))
3648 (error "Invalid TODO keyword %s" x)))
3649 kws0)
3650 kwsa (if kwsa (append '((:startgroup))
3651 (nreverse kwsa)
3652 '((:endgroup))))
3653 hw (car kws1)
3654 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3655 tail (list inter hw (car dws) (org-last dws))))
3656 (add-to-list 'org-todo-heads hw 'append)
3657 (push kws1 org-todo-sets)
3658 (setq org-done-keywords (append org-done-keywords dws nil))
3659 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3660 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3661 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3662 (setq org-todo-sets (nreverse org-todo-sets)
3663 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3664 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3665 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3666 ;; Process the constants
3667 (when const
3668 (let (e cst)
3669 (while (setq e (pop const))
3670 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3671 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3672 (setq org-table-formula-constants-local cst)))
3674 ;; Process the tags.
3675 (when tags
3676 (let (e tgs)
3677 (while (setq e (pop tags))
3678 (cond
3679 ((equal e "{") (push '(:startgroup) tgs))
3680 ((equal e "}") (push '(:endgroup) tgs))
3681 ((equal e "\\n") (push '(:newline) tgs))
3682 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3683 (push (cons (match-string 1 e)
3684 (string-to-char (match-string 2 e)))
3685 tgs))
3686 (t (push (list e) tgs))))
3687 (org-set-local 'org-tag-alist nil)
3688 (while (setq e (pop tgs))
3689 (or (and (stringp (car e))
3690 (assoc (car e) org-tag-alist))
3691 (push e org-tag-alist)))))
3693 ;; Compute the regular expressions and other local variables
3694 (if (not org-done-keywords)
3695 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3696 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3697 (length org-scheduled-string)
3698 (length org-clock-string)
3699 (length org-closed-string)))
3700 org-drawer-regexp
3701 (concat "^[ \t]*:\\("
3702 (mapconcat 'regexp-quote org-drawers "\\|")
3703 "\\):[ \t]*$")
3704 org-not-done-keywords
3705 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3706 org-todo-regexp
3707 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3708 "\\|") "\\)\\>")
3709 org-not-done-regexp
3710 (concat "\\<\\("
3711 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3712 "\\)\\>")
3713 org-not-done-heading-regexp
3714 (concat "^\\(\\*+\\)[ \t]+\\("
3715 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3716 "\\)\\>")
3717 org-todo-line-regexp
3718 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3719 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3720 "\\)\\>\\)?[ \t]*\\(.*\\)")
3721 org-complex-heading-regexp
3722 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3723 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3724 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3725 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3726 org-nl-done-regexp
3727 (concat "\n\\*+[ \t]+"
3728 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3729 "\\)" "\\>")
3730 org-todo-line-tags-regexp
3731 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3732 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3733 (org-re
3734 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3735 org-looking-at-done-regexp
3736 (concat "^" "\\(?:"
3737 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3738 "\\>")
3739 org-deadline-regexp (concat "\\<" org-deadline-string)
3740 org-deadline-time-regexp
3741 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3742 org-deadline-line-regexp
3743 (concat "\\<\\(" org-deadline-string "\\).*")
3744 org-scheduled-regexp
3745 (concat "\\<" org-scheduled-string)
3746 org-scheduled-time-regexp
3747 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3748 org-closed-time-regexp
3749 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3750 org-keyword-time-regexp
3751 (concat "\\<\\(" org-scheduled-string
3752 "\\|" org-deadline-string
3753 "\\|" org-closed-string
3754 "\\|" org-clock-string "\\)"
3755 " *[[<]\\([^]>]+\\)[]>]")
3756 org-keyword-time-not-clock-regexp
3757 (concat "\\<\\(" org-scheduled-string
3758 "\\|" org-deadline-string
3759 "\\|" org-closed-string
3760 "\\)"
3761 " *[[<]\\([^]>]+\\)[]>]")
3762 org-maybe-keyword-time-regexp
3763 (concat "\\(\\<\\(" org-scheduled-string
3764 "\\|" org-deadline-string
3765 "\\|" org-closed-string
3766 "\\|" org-clock-string "\\)\\)?"
3767 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3768 org-planning-or-clock-line-re
3769 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3770 "\\|" org-deadline-string
3771 "\\|" org-closed-string "\\|" org-clock-string
3772 "\\)\\>\\)")
3774 (org-compute-latex-and-specials-regexp)
3775 (org-set-font-lock-defaults))))
3777 (defun org-file-contents (file &optional noerror)
3778 "Return the contents of FILE, as a string."
3779 (if (or (not file)
3780 (not (file-readable-p file)))
3781 (if noerror
3782 (progn
3783 (message "Cannot read file %s" file)
3784 (ding) (sit-for 2)
3786 (error "Cannot read file %s" file))
3787 (with-temp-buffer
3788 (insert-file-contents file)
3789 (buffer-string))))
3791 (defun org-extract-log-state-settings (x)
3792 "Extract the log state setting from a TODO keyword string.
3793 This will extract info from a string like \"WAIT(w@/!)\"."
3794 (let (kw key log1 log2)
3795 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3796 (setq kw (match-string 1 x)
3797 key (and (match-end 2) (match-string 2 x))
3798 log1 (and (match-end 3) (match-string 3 x))
3799 log2 (and (match-end 4) (match-string 4 x)))
3800 (and (or log1 log2)
3801 (list kw
3802 (and log1 (if (equal log1 "!") 'time 'note))
3803 (and log2 (if (equal log2 "!") 'time 'note)))))))
3805 (defun org-remove-keyword-keys (list)
3806 "Remove a pair of parenthesis at the end of each string in LIST."
3807 (mapcar (lambda (x)
3808 (if (string-match "(.*)$" x)
3809 (substring x 0 (match-beginning 0))
3811 list))
3813 ;; FIXME: this could be done much better, using second characters etc.
3814 (defun org-assign-fast-keys (alist)
3815 "Assign fast keys to a keyword-key alist.
3816 Respect keys that are already there."
3817 (let (new e k c c1 c2 (char ?a))
3818 (while (setq e (pop alist))
3819 (cond
3820 ((equal e '(:startgroup)) (push e new))
3821 ((equal e '(:endgroup)) (push e new))
3822 ((equal e '(:newline)) (push e new))
3824 (setq k (car e) c2 nil)
3825 (if (cdr e)
3826 (setq c (cdr e))
3827 ;; automatically assign a character.
3828 (setq c1 (string-to-char
3829 (downcase (substring
3830 k (if (= (string-to-char k) ?@) 1 0)))))
3831 (if (or (rassoc c1 new) (rassoc c1 alist))
3832 (while (or (rassoc char new) (rassoc char alist))
3833 (setq char (1+ char)))
3834 (setq c2 c1))
3835 (setq c (or c2 char)))
3836 (push (cons k c) new))))
3837 (nreverse new)))
3839 ;;; Some variables used in various places
3841 (defvar org-window-configuration nil
3842 "Used in various places to store a window configuration.")
3843 (defvar org-finish-function nil
3844 "Function to be called when `C-c C-c' is used.
3845 This is for getting out of special buffers like remember.")
3848 ;; FIXME: Occasionally check by commenting these, to make sure
3849 ;; no other functions uses these, forgetting to let-bind them.
3850 (defvar entry)
3851 (defvar last-state)
3852 (defvar date)
3854 ;; Defined somewhere in this file, but used before definition.
3855 (defvar org-html-entities)
3856 (defvar org-struct-menu)
3857 (defvar org-org-menu)
3858 (defvar org-tbl-menu)
3859 (defvar org-agenda-keymap)
3861 ;;;; Define the Org-mode
3863 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3864 (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."))
3867 ;; We use a before-change function to check if a table might need
3868 ;; an update.
3869 (defvar org-table-may-need-update t
3870 "Indicates that a table might need an update.
3871 This variable is set by `org-before-change-function'.
3872 `org-table-align' sets it back to nil.")
3873 (defun org-before-change-function (beg end)
3874 "Every change indicates that a table might need an update."
3875 (setq org-table-may-need-update t))
3876 (defvar org-mode-map)
3877 (defvar org-mode-hook nil
3878 "Mode hook for Org-mode, run after the mode was turned on.")
3879 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3880 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3881 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
3882 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
3883 (defvar org-table-buffer-is-an nil)
3884 (defconst org-outline-regexp "\\*+ ")
3886 ;;;###autoload
3887 (define-derived-mode org-mode outline-mode "Org"
3888 "Outline-based notes management and organizer, alias
3889 \"Carsten's outline-mode for keeping track of everything.\"
3891 Org-mode develops organizational tasks around a NOTES file which
3892 contains information about projects as plain text. Org-mode is
3893 implemented on top of outline-mode, which is ideal to keep the content
3894 of large files well structured. It supports ToDo items, deadlines and
3895 time stamps, which magically appear in the diary listing of the Emacs
3896 calendar. Tables are easily created with a built-in table editor.
3897 Plain text URL-like links connect to websites, emails (VM), Usenet
3898 messages (Gnus), BBDB entries, and any files related to the project.
3899 For printing and sharing of notes, an Org-mode file (or a part of it)
3900 can be exported as a structured ASCII or HTML file.
3902 The following commands are available:
3904 \\{org-mode-map}"
3906 ;; Get rid of Outline menus, they are not needed
3907 ;; Need to do this here because define-derived-mode sets up
3908 ;; the keymap so late. Still, it is a waste to call this each time
3909 ;; we switch another buffer into org-mode.
3910 (if (featurep 'xemacs)
3911 (when (boundp 'outline-mode-menu-heading)
3912 ;; Assume this is Greg's port, it used easymenu
3913 (easy-menu-remove outline-mode-menu-heading)
3914 (easy-menu-remove outline-mode-menu-show)
3915 (easy-menu-remove outline-mode-menu-hide))
3916 (define-key org-mode-map [menu-bar headings] 'undefined)
3917 (define-key org-mode-map [menu-bar hide] 'undefined)
3918 (define-key org-mode-map [menu-bar show] 'undefined))
3920 (org-load-modules-maybe)
3921 (easy-menu-add org-org-menu)
3922 (easy-menu-add org-tbl-menu)
3923 (org-install-agenda-files-menu)
3924 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3925 (org-add-to-invisibility-spec '(org-cwidth))
3926 (org-add-to-invisibility-spec '(org-hide-block . t))
3927 (when (featurep 'xemacs)
3928 (org-set-local 'line-move-ignore-invisible t))
3929 (org-set-local 'outline-regexp org-outline-regexp)
3930 (org-set-local 'outline-level 'org-outline-level)
3931 (when (and org-ellipsis
3932 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3933 (fboundp 'make-glyph-code))
3934 (unless org-display-table
3935 (setq org-display-table (make-display-table)))
3936 (set-display-table-slot
3937 org-display-table 4
3938 (vconcat (mapcar
3939 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3940 org-ellipsis)))
3941 (if (stringp org-ellipsis) org-ellipsis "..."))))
3942 (setq buffer-display-table org-display-table))
3943 (org-set-regexps-and-options)
3944 (when (and org-tag-faces (not org-tags-special-faces-re))
3945 ;; tag faces set outside customize.... force initialization.
3946 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3947 ;; Calc embedded
3948 (org-set-local 'calc-embedded-open-mode "# ")
3949 (modify-syntax-entry ?# "<")
3950 (modify-syntax-entry ?@ "w")
3951 (if org-startup-truncated (setq truncate-lines t))
3952 (org-set-local 'font-lock-unfontify-region-function
3953 'org-unfontify-region)
3954 ;; Activate before-change-function
3955 (org-set-local 'org-table-may-need-update t)
3956 (org-add-hook 'before-change-functions 'org-before-change-function nil
3957 'local)
3958 ;; Check for running clock before killing a buffer
3959 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3960 ;; Paragraphs and auto-filling
3961 (org-set-autofill-regexps)
3962 (setq indent-line-function 'org-indent-line-function)
3963 (org-update-radio-target-regexp)
3964 ;; Make sure dependence stuff works reliably, even for users who set it
3965 ;; too late :-(
3966 (if org-enforce-todo-dependencies
3967 (add-hook 'org-blocker-hook
3968 'org-block-todo-from-children-or-siblings-or-parent)
3969 (remove-hook 'org-blocker-hook
3970 'org-block-todo-from-children-or-siblings-or-parent))
3971 (if org-enforce-todo-checkbox-dependencies
3972 (add-hook 'org-blocker-hook
3973 'org-block-todo-from-checkboxes)
3974 (remove-hook 'org-blocker-hook
3975 'org-block-todo-from-checkboxes))
3977 ;; Comment characters
3978 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3979 (org-set-local 'comment-padding " ")
3981 ;; Align options lines
3982 (org-set-local
3983 'align-mode-rules-list
3984 '((org-in-buffer-settings
3985 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3986 (modes . '(org-mode)))))
3988 ;; Imenu
3989 (org-set-local 'imenu-create-index-function
3990 'org-imenu-get-tree)
3992 ;; Make isearch reveal context
3993 (if (or (featurep 'xemacs)
3994 (not (boundp 'outline-isearch-open-invisible-function)))
3995 ;; Emacs 21 and XEmacs make use of the hook
3996 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3997 ;; Emacs 22 deals with this through a special variable
3998 (org-set-local 'outline-isearch-open-invisible-function
3999 (lambda (&rest ignore) (org-show-context 'isearch))))
4001 ;; If empty file that did not turn on org-mode automatically, make it to.
4002 (if (and org-insert-mode-line-in-empty-file
4003 (interactive-p)
4004 (= (point-min) (point-max)))
4005 (insert "# -*- mode: org -*-\n\n"))
4007 (unless org-inhibit-startup
4008 (when org-startup-align-all-tables
4009 (let ((bmp (buffer-modified-p)))
4010 (org-table-map-tables 'org-table-align)
4011 (set-buffer-modified-p bmp)))
4012 (when org-startup-indented
4013 (require 'org-indent)
4014 (org-indent-mode 1))
4015 (org-set-startup-visibility)))
4017 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4019 (defun org-current-time ()
4020 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4021 (if (> (car org-time-stamp-rounding-minutes) 1)
4022 (let ((r (car org-time-stamp-rounding-minutes))
4023 (time (decode-time)))
4024 (apply 'encode-time
4025 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4026 (nthcdr 2 time))))
4027 (current-time)))
4029 ;;;; Font-Lock stuff, including the activators
4031 (defvar org-mouse-map (make-sparse-keymap))
4032 (org-defkey org-mouse-map
4033 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4034 (org-defkey org-mouse-map
4035 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4036 (when org-mouse-1-follows-link
4037 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4038 (when org-tab-follows-link
4039 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4040 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4042 (require 'font-lock)
4044 (defconst org-non-link-chars "]\t\n\r<>")
4045 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4046 "shell" "elisp"))
4047 (defvar org-link-types-re nil
4048 "Matches a link that has a url-like prefix like \"http:\"")
4049 (defvar org-link-re-with-space nil
4050 "Matches a link with spaces, optional angular brackets around it.")
4051 (defvar org-link-re-with-space2 nil
4052 "Matches a link with spaces, optional angular brackets around it.")
4053 (defvar org-link-re-with-space3 nil
4054 "Matches a link with spaces, only for internal part in bracket links.")
4055 (defvar org-angle-link-re nil
4056 "Matches link with angular brackets, spaces are allowed.")
4057 (defvar org-plain-link-re nil
4058 "Matches plain link, without spaces.")
4059 (defvar org-bracket-link-regexp nil
4060 "Matches a link in double brackets.")
4061 (defvar org-bracket-link-analytic-regexp nil
4062 "Regular expression used to analyze links.
4063 Here is what the match groups contain after a match:
4064 1: http:
4065 2: http
4066 3: path
4067 4: [desc]
4068 5: desc")
4069 (defvar org-bracket-link-analytic-regexp++ nil
4070 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4071 (defvar org-any-link-re nil
4072 "Regular expression matching any link.")
4074 (defun org-make-link-regexps ()
4075 "Update the link regular expressions.
4076 This should be called after the variable `org-link-types' has changed."
4077 (setq org-link-types-re
4078 (concat
4079 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
4080 org-link-re-with-space
4081 (concat
4082 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4083 "\\([^" org-non-link-chars " ]"
4084 "[^" org-non-link-chars "]*"
4085 "[^" org-non-link-chars " ]\\)>?")
4086 org-link-re-with-space2
4087 (concat
4088 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4089 "\\([^" org-non-link-chars " ]"
4090 "[^\t\n\r]*"
4091 "[^" org-non-link-chars " ]\\)>?")
4092 org-link-re-with-space3
4093 (concat
4094 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4095 "\\([^" org-non-link-chars " ]"
4096 "[^\t\n\r]*\\)")
4097 org-angle-link-re
4098 (concat
4099 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4100 "\\([^" org-non-link-chars " ]"
4101 "[^" org-non-link-chars "]*"
4102 "\\)>")
4103 org-plain-link-re
4104 (concat
4105 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4106 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4107 org-bracket-link-regexp
4108 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4109 org-bracket-link-analytic-regexp
4110 (concat
4111 "\\[\\["
4112 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4113 "\\([^]]+\\)"
4114 "\\]"
4115 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4116 "\\]")
4117 org-bracket-link-analytic-regexp++
4118 (concat
4119 "\\[\\["
4120 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4121 "\\([^]]+\\)"
4122 "\\]"
4123 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4124 "\\]")
4125 org-any-link-re
4126 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4127 org-angle-link-re "\\)\\|\\("
4128 org-plain-link-re "\\)")))
4130 (org-make-link-regexps)
4132 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4133 "Regular expression for fast time stamp matching.")
4134 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4135 "Regular expression for fast time stamp matching.")
4136 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4137 "Regular expression matching time strings for analysis.
4138 This one does not require the space after the date, so it can be used
4139 on a string that terminates immediately after the date.")
4140 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4141 "Regular expression matching time strings for analysis.")
4142 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4143 "Regular expression matching time stamps, with groups.")
4144 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4145 "Regular expression matching time stamps (also [..]), with groups.")
4146 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4147 "Regular expression matching a time stamp range.")
4148 (defconst org-tr-regexp-both
4149 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4150 "Regular expression matching a time stamp range.")
4151 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4152 org-ts-regexp "\\)?")
4153 "Regular expression matching a time stamp or time stamp range.")
4154 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4155 org-ts-regexp-both "\\)?")
4156 "Regular expression matching a time stamp or time stamp range.
4157 The time stamps may be either active or inactive.")
4159 (defvar org-emph-face nil)
4161 (defun org-do-emphasis-faces (limit)
4162 "Run through the buffer and add overlays to links."
4163 (let (rtn a)
4164 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4165 (if (not (= (char-after (match-beginning 3))
4166 (char-after (match-beginning 4))))
4167 (progn
4168 (setq rtn t)
4169 (setq a (assoc (match-string 3) org-emphasis-alist))
4170 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4171 'face
4172 (nth 1 a))
4173 (and (nth 4 a)
4174 (org-remove-flyspell-overlays-in
4175 (match-beginning 0) (match-end 0)))
4176 (add-text-properties (match-beginning 2) (match-end 2)
4177 '(font-lock-multiline t))
4178 (when org-hide-emphasis-markers
4179 (add-text-properties (match-end 4) (match-beginning 5)
4180 '(invisible org-link))
4181 (add-text-properties (match-beginning 3) (match-end 3)
4182 '(invisible org-link)))))
4183 (backward-char 1))
4184 rtn))
4186 (defun org-emphasize (&optional char)
4187 "Insert or change an emphasis, i.e. a font like bold or italic.
4188 If there is an active region, change that region to a new emphasis.
4189 If there is no region, just insert the marker characters and position
4190 the cursor between them.
4191 CHAR should be either the marker character, or the first character of the
4192 HTML tag associated with that emphasis. If CHAR is a space, the means
4193 to remove the emphasis of the selected region.
4194 If char is not given (for example in an interactive call) it
4195 will be prompted for."
4196 (interactive)
4197 (let ((eal org-emphasis-alist) e det
4198 (erc org-emphasis-regexp-components)
4199 (prompt "")
4200 (string "") beg end move tag c s)
4201 (if (org-region-active-p)
4202 (setq beg (region-beginning) end (region-end)
4203 string (buffer-substring beg end))
4204 (setq move t))
4206 (while (setq e (pop eal))
4207 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4208 c (aref tag 0))
4209 (push (cons c (string-to-char (car e))) det)
4210 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4211 (substring tag 1)))))
4212 (setq det (nreverse det))
4213 (unless char
4214 (message "%s" (concat "Emphasis marker or tag:" prompt))
4215 (setq char (read-char-exclusive)))
4216 (setq char (or (cdr (assoc char det)) char))
4217 (if (equal char ?\ )
4218 (setq s "" move nil)
4219 (unless (assoc (char-to-string char) org-emphasis-alist)
4220 (error "No such emphasis marker: \"%c\"" char))
4221 (setq s (char-to-string char)))
4222 (while (and (> (length string) 1)
4223 (equal (substring string 0 1) (substring string -1))
4224 (assoc (substring string 0 1) org-emphasis-alist))
4225 (setq string (substring string 1 -1)))
4226 (setq string (concat s string s))
4227 (if beg (delete-region beg end))
4228 (unless (or (bolp)
4229 (string-match (concat "[" (nth 0 erc) "\n]")
4230 (char-to-string (char-before (point)))))
4231 (insert " "))
4232 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4233 (char-to-string (char-after (point))))
4234 (insert " ") (backward-char 1))
4235 (insert string)
4236 (and move (backward-char 1))))
4238 (defconst org-nonsticky-props
4239 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4241 (defsubst org-rear-nonsticky-at (pos)
4242 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4244 (defun org-activate-plain-links (limit)
4245 "Run through the buffer and add overlays to links."
4246 (catch 'exit
4247 (let (f)
4248 (if (re-search-forward org-plain-link-re limit t)
4249 (progn
4250 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4251 (setq f (get-text-property (match-beginning 0) 'face))
4252 (if (or (eq f 'org-tag)
4253 (and (listp f) (memq 'org-tag f)))
4255 (add-text-properties (match-beginning 0) (match-end 0)
4256 (list 'mouse-face 'highlight
4257 'keymap org-mouse-map))
4258 (org-rear-nonsticky-at (match-end 0)))
4259 t)))))
4261 (defun org-activate-code (limit)
4262 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4263 (progn
4264 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4265 (remove-text-properties (match-beginning 0) (match-end 0)
4266 '(display t invisible t intangible t))
4267 t)))
4269 (defun org-fontify-meta-lines-and-blocks (limit)
4270 "Fontify #+ lines and blocks, in the correct ways."
4271 (let ((case-fold-search t))
4272 (if (re-search-forward
4273 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4274 limit t)
4275 (let ((beg (match-beginning 0))
4276 (beg1 (line-beginning-position 2))
4277 (dc1 (downcase (match-string 2)))
4278 (dc3 (downcase (match-string 3)))
4279 end end1 quoting)
4280 (cond
4281 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4282 ;; a single line of backend-specific content
4283 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4284 (remove-text-properties (match-beginning 0) (match-end 0)
4285 '(display t invisible t intangible t))
4286 (add-text-properties (match-beginning 1) (match-end 3)
4287 '(font-lock-fontified t face org-meta-line))
4288 (add-text-properties (match-beginning 6) (match-end 6)
4289 '(font-lock-fontified t face org-block))
4291 ((and (match-end 4) (equal dc3 "begin"))
4292 ;; Truely a block
4293 (setq quoting (member (downcase (match-string 5))
4294 org-protecting-blocks))
4295 (when (re-search-forward
4296 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4297 nil t) ;; on purpose, we look further than LIMIT
4298 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4299 (when quoting
4300 (remove-text-properties beg end
4301 '(display t invisible t intangible t)))
4302 (add-text-properties
4303 beg end
4304 '(font-lock-fontified t font-lock-multiline t))
4305 (add-text-properties beg beg1 '(face org-meta-line))
4306 (add-text-properties end1 end '(face org-meta-line))
4307 (when quoting
4308 (add-text-properties beg1 end1 '(face org-block)))
4310 ((not (member (char-after beg) '(?\ ?\t)))
4311 ;; just any other in-buffer setting, but not indented
4312 (add-text-properties
4313 beg (match-end 0)
4314 '(font-lock-fontified t face org-meta-line))
4316 ((or (member dc1 '("caption:" "label:" "orgtbl:" "tblfm:" "tblname:"))
4317 (and (match-end 4) (equal dc3 "attr")))
4318 (add-text-properties
4319 beg (match-end 0)
4320 '(font-lock-fontified t face org-meta-line))
4322 (t nil))))))
4324 (defun org-activate-angle-links (limit)
4325 "Run through the buffer and add overlays to links."
4326 (if (re-search-forward org-angle-link-re limit t)
4327 (progn
4328 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4329 (add-text-properties (match-beginning 0) (match-end 0)
4330 (list 'mouse-face 'highlight
4331 'keymap org-mouse-map))
4332 (org-rear-nonsticky-at (match-end 0))
4333 t)))
4335 (defun org-activate-footnote-links (limit)
4336 "Run through the buffer and add overlays to links."
4337 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4338 limit t)
4339 (progn
4340 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4341 (add-text-properties (match-beginning 2) (match-end 2)
4342 (list 'mouse-face 'highlight
4343 'keymap org-mouse-map
4344 'help-echo
4345 (if (= (point-at-bol) (match-beginning 2))
4346 "Footnote definition"
4347 "Footnote reference")
4349 (org-rear-nonsticky-at (match-end 2))
4350 t)))
4352 (defun org-activate-bracket-links (limit)
4353 "Run through the buffer and add overlays to bracketed links."
4354 (if (re-search-forward org-bracket-link-regexp limit t)
4355 (let* ((help (concat "LINK: "
4356 (org-match-string-no-properties 1)))
4357 ;; FIXME: above we should remove the escapes.
4358 ;; but that requires another match, protecting match data,
4359 ;; a lot of overhead for font-lock.
4360 (ip (org-maybe-intangible
4361 (list 'invisible 'org-link
4362 'keymap org-mouse-map 'mouse-face 'highlight
4363 'font-lock-multiline t 'help-echo help)))
4364 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4365 'font-lock-multiline t 'help-echo help)))
4366 ;; We need to remove the invisible property here. Table narrowing
4367 ;; may have made some of this invisible.
4368 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4369 (remove-text-properties (match-beginning 0) (match-end 0)
4370 '(invisible nil))
4371 (if (match-end 3)
4372 (progn
4373 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4374 (org-rear-nonsticky-at (match-beginning 3))
4375 (add-text-properties (match-beginning 3) (match-end 3) vp)
4376 (org-rear-nonsticky-at (match-end 3))
4377 (add-text-properties (match-end 3) (match-end 0) ip)
4378 (org-rear-nonsticky-at (match-end 0)))
4379 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4380 (org-rear-nonsticky-at (match-beginning 1))
4381 (add-text-properties (match-beginning 1) (match-end 1) vp)
4382 (org-rear-nonsticky-at (match-end 1))
4383 (add-text-properties (match-end 1) (match-end 0) ip)
4384 (org-rear-nonsticky-at (match-end 0)))
4385 t)))
4387 (defun org-activate-dates (limit)
4388 "Run through the buffer and add overlays to dates."
4389 (if (re-search-forward org-tsr-regexp-both limit t)
4390 (progn
4391 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4392 (add-text-properties (match-beginning 0) (match-end 0)
4393 (list 'mouse-face 'highlight
4394 'keymap org-mouse-map))
4395 (org-rear-nonsticky-at (match-end 0))
4396 (when org-display-custom-times
4397 (if (match-end 3)
4398 (org-display-custom-time (match-beginning 3) (match-end 3)))
4399 (org-display-custom-time (match-beginning 1) (match-end 1)))
4400 t)))
4402 (defvar org-target-link-regexp nil
4403 "Regular expression matching radio targets in plain text.")
4404 (make-variable-buffer-local 'org-target-link-regexp)
4405 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4406 "Regular expression matching a link target.")
4407 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4408 "Regular expression matching a radio target.")
4409 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4410 "Regular expression matching any target.")
4412 (defun org-activate-target-links (limit)
4413 "Run through the buffer and add overlays to target matches."
4414 (when org-target-link-regexp
4415 (let ((case-fold-search t))
4416 (if (re-search-forward org-target-link-regexp limit t)
4417 (progn
4418 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4419 (add-text-properties (match-beginning 0) (match-end 0)
4420 (list 'mouse-face 'highlight
4421 'keymap org-mouse-map
4422 'help-echo "Radio target link"
4423 'org-linked-text t))
4424 (org-rear-nonsticky-at (match-end 0))
4425 t)))))
4427 (defun org-update-radio-target-regexp ()
4428 "Find all radio targets in this file and update the regular expression."
4429 (interactive)
4430 (when (memq 'radio org-activate-links)
4431 (setq org-target-link-regexp
4432 (org-make-target-link-regexp (org-all-targets 'radio)))
4433 (org-restart-font-lock)))
4435 (defun org-hide-wide-columns (limit)
4436 (let (s e)
4437 (setq s (text-property-any (point) (or limit (point-max))
4438 'org-cwidth t))
4439 (when s
4440 (setq e (next-single-property-change s 'org-cwidth))
4441 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4442 (goto-char e)
4443 t)))
4445 (defvar org-latex-and-specials-regexp nil
4446 "Regular expression for highlighting export special stuff.")
4447 (defvar org-match-substring-regexp)
4448 (defvar org-match-substring-with-braces-regexp)
4449 (defvar org-export-html-special-string-regexps)
4451 (defun org-compute-latex-and-specials-regexp ()
4452 "Compute regular expression for stuff treated specially by exporters."
4453 (if (not org-highlight-latex-fragments-and-specials)
4454 (org-set-local 'org-latex-and-specials-regexp nil)
4455 (require 'org-exp)
4456 (let*
4457 ((matchers (plist-get org-format-latex-options :matchers))
4458 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4459 org-latex-regexps)))
4460 (options (org-combine-plists (org-default-export-plist)
4461 (org-infile-export-plist)))
4462 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4463 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4464 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4465 (org-export-html-expand (plist-get options :expand-quoted-html))
4466 (org-export-with-special-strings (plist-get options :special-strings))
4467 (re-sub
4468 (cond
4469 ((equal org-export-with-sub-superscripts '{})
4470 (list org-match-substring-with-braces-regexp))
4471 (org-export-with-sub-superscripts
4472 (list org-match-substring-regexp))
4473 (t nil)))
4474 (re-latex
4475 (if org-export-with-LaTeX-fragments
4476 (mapcar (lambda (x) (nth 1 x)) latexs)))
4477 (re-macros
4478 (if org-export-with-TeX-macros
4479 (list (concat "\\\\"
4480 (regexp-opt
4481 (append (mapcar 'car org-html-entities)
4482 (if (boundp 'org-latex-entities)
4483 (mapcar (lambda (x)
4484 (or (car-safe x) x))
4485 org-latex-entities)
4486 nil))
4487 'words))) ; FIXME
4489 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4490 (re-special (if org-export-with-special-strings
4491 (mapcar (lambda (x) (car x))
4492 org-export-html-special-string-regexps)))
4493 (re-rest
4494 (delq nil
4495 (list
4496 (if org-export-html-expand "@<[^>\n]+>")
4497 ))))
4498 (org-set-local
4499 'org-latex-and-specials-regexp
4500 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4501 re-rest) "\\|")))))
4503 (defun org-do-latex-and-special-faces (limit)
4504 "Run through the buffer and add overlays to links."
4505 (when org-latex-and-specials-regexp
4506 (let (rtn d)
4507 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4508 limit t))
4509 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4510 'face))
4511 '(org-code org-verbatim underline)))
4512 (progn
4513 (setq rtn t
4514 d (cond ((member (char-after (1+ (match-beginning 0)))
4515 '(?_ ?^)) 1)
4516 (t 0)))
4517 (font-lock-prepend-text-property
4518 (+ d (match-beginning 0)) (match-end 0)
4519 'face 'org-latex-and-export-specials)
4520 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4521 '(font-lock-multiline t)))))
4522 rtn)))
4524 (defun org-restart-font-lock ()
4525 "Restart font-lock-mode, to force refontification."
4526 (when (and (boundp 'font-lock-mode) font-lock-mode)
4527 (font-lock-mode -1)
4528 (font-lock-mode 1)))
4530 (defun org-all-targets (&optional radio)
4531 "Return a list of all targets in this file.
4532 With optional argument RADIO, only find radio targets."
4533 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4534 rtn)
4535 (save-excursion
4536 (goto-char (point-min))
4537 (while (re-search-forward re nil t)
4538 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4539 rtn)))
4541 (defun org-make-target-link-regexp (targets)
4542 "Make regular expression matching all strings in TARGETS.
4543 The regular expression finds the targets also if there is a line break
4544 between words."
4545 (and targets
4546 (concat
4547 "\\<\\("
4548 (mapconcat
4549 (lambda (x)
4550 (while (string-match " +" x)
4551 (setq x (replace-match "\\s-+" t t x)))
4553 targets
4554 "\\|")
4555 "\\)\\>")))
4557 (defun org-activate-tags (limit)
4558 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4559 (progn
4560 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4561 (add-text-properties (match-beginning 1) (match-end 1)
4562 (list 'mouse-face 'highlight
4563 'keymap org-mouse-map))
4564 (org-rear-nonsticky-at (match-end 1))
4565 t)))
4567 (defun org-outline-level ()
4568 (save-excursion
4569 (looking-at outline-regexp)
4570 (if (match-beginning 1)
4571 (+ (org-get-string-indentation (match-string 1)) 1000)
4572 (1- (- (match-end 0) (match-beginning 0))))))
4574 (defvar org-font-lock-keywords nil)
4576 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4577 "Regular expression matching a property line.")
4579 (defvar org-font-lock-hook nil
4580 "Functions to be called for special font lock stuff.")
4582 (defun org-font-lock-hook (limit)
4583 (run-hook-with-args 'org-font-lock-hook limit))
4585 (defun org-set-font-lock-defaults ()
4586 (let* ((em org-fontify-emphasized-text)
4587 (lk org-activate-links)
4588 (org-font-lock-extra-keywords
4589 (list
4590 ;; Call the hook
4591 '(org-font-lock-hook)
4592 ;; Headlines
4593 `(,(if org-fontify-whole-heading-line
4594 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
4595 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
4596 (1 (org-get-level-face 1))
4597 (2 (org-get-level-face 2))
4598 (3 (org-get-level-face 3)))
4599 ;; Table lines
4600 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4601 (1 'org-table t))
4602 ;; Table internals
4603 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4604 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4605 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4606 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
4607 ;; Drawers
4608 (list org-drawer-regexp '(0 'org-special-keyword t))
4609 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4610 ;; Properties
4611 (list org-property-re
4612 '(1 'org-special-keyword t)
4613 '(3 'org-property-value t))
4614 ;; Links
4615 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4616 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4617 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4618 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4619 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4620 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4621 (if (memq 'footnote lk) '(org-activate-footnote-links
4622 (2 'org-footnote t)))
4623 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4624 '(org-hide-wide-columns (0 nil append))
4625 ;; TODO lines
4626 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4627 '(1 (org-get-todo-face 1) t))
4628 ;; DONE
4629 (if org-fontify-done-headline
4630 (list (concat "^[*]+ +\\<\\("
4631 (mapconcat 'regexp-quote org-done-keywords "\\|")
4632 "\\)\\(.*\\)")
4633 '(2 'org-headline-done t))
4634 nil)
4635 ;; Priorities
4636 '(org-font-lock-add-priority-faces)
4637 ;; Tags
4638 '(org-font-lock-add-tag-faces)
4639 ;; Special keywords
4640 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4641 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4642 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4643 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4644 ;; Emphasis
4645 (if em
4646 (if (featurep 'xemacs)
4647 '(org-do-emphasis-faces (0 nil append))
4648 '(org-do-emphasis-faces)))
4649 ;; Checkboxes
4650 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4651 2 'org-checkbox prepend)
4652 (if org-provide-checkbox-statistics
4653 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4654 (0 (org-get-checkbox-statistics-face) t)))
4655 ;; Description list items
4656 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4657 2 'bold prepend)
4658 ;; ARCHIVEd headings
4659 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4660 '(1 'org-archived prepend))
4661 ;; Specials
4662 '(org-do-latex-and-special-faces)
4663 ;; Code
4664 '(org-activate-code (1 'org-code t))
4665 ;; COMMENT
4666 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4667 "\\|" org-quote-string "\\)\\>")
4668 '(1 'org-special-keyword t))
4669 '("^#.*" (0 'font-lock-comment-face t))
4670 ;; Blocks and meta lines
4671 '(org-fontify-meta-lines-and-blocks)
4673 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4674 ;; Now set the full font-lock-keywords
4675 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4676 (org-set-local 'font-lock-defaults
4677 '(org-font-lock-keywords t nil nil backward-paragraph))
4678 (kill-local-variable 'font-lock-keywords) nil))
4680 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
4681 "Fontify string S like in Org-mode"
4682 (with-temp-buffer
4683 (insert s)
4684 (let ((org-odd-levels-only odd-levels))
4685 (org-mode)
4686 (font-lock-fontify-buffer)
4687 (buffer-string))))
4689 (defvar org-m nil)
4690 (defvar org-l nil)
4691 (defvar org-f nil)
4692 (defun org-get-level-face (n)
4693 "Get the right face for match N in font-lock matching of headlines."
4694 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4695 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4696 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4697 (cond
4698 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4699 ((eq n 2) org-f)
4700 (t (if org-level-color-stars-only nil org-f))))
4702 (defun org-get-todo-face (kwd)
4703 "Get the right face for a TODO keyword KWD.
4704 If KWD is a number, get the corresponding match group."
4705 (if (numberp kwd) (setq kwd (match-string kwd)))
4706 (or (cdr (assoc kwd org-todo-keyword-faces))
4707 (and (member kwd org-done-keywords) 'org-done)
4708 'org-todo))
4710 (defun org-font-lock-add-tag-faces (limit)
4711 "Add the special tag faces."
4712 (when (and org-tag-faces org-tags-special-faces-re)
4713 (while (re-search-forward org-tags-special-faces-re limit t)
4714 (add-text-properties (match-beginning 1) (match-end 1)
4715 (list 'face (org-get-tag-face 1)
4716 'font-lock-fontified t))
4717 (backward-char 1))))
4719 (defun org-font-lock-add-priority-faces (limit)
4720 "Add the special priority faces."
4721 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4722 (add-text-properties
4723 (match-beginning 0) (match-end 0)
4724 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4725 org-priority-faces))
4726 'org-special-keyword)
4727 'font-lock-fontified t))))
4729 (defun org-get-tag-face (kwd)
4730 "Get the right face for a TODO keyword KWD.
4731 If KWD is a number, get the corresponding match group."
4732 (if (numberp kwd) (setq kwd (match-string kwd)))
4733 (or (cdr (assoc kwd org-tag-faces))
4734 'org-tag))
4736 (defun org-unfontify-region (beg end &optional maybe_loudly)
4737 "Remove fontification and activation overlays from links."
4738 (font-lock-default-unfontify-region beg end)
4739 (let* ((buffer-undo-list t)
4740 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4741 (inhibit-modification-hooks t)
4742 deactivate-mark buffer-file-name buffer-file-truename)
4743 (remove-text-properties beg end
4744 '(mouse-face t keymap t org-linked-text t
4745 invisible t intangible t
4746 line-prefix t wrap-prefix t
4747 org-no-flyspell t))))
4749 ;;;; Visibility cycling, including org-goto and indirect buffer
4751 ;;; Cycling
4753 (defvar org-cycle-global-status nil)
4754 (make-variable-buffer-local 'org-cycle-global-status)
4755 (defvar org-cycle-subtree-status nil)
4756 (make-variable-buffer-local 'org-cycle-subtree-status)
4758 ;;;###autoload
4760 (defvar org-inlinetask-min-level)
4762 (defun org-cycle (&optional arg)
4763 "TAB-action and visibility cycling for Org-mode.
4765 This is the command invoked in Org-moe by the TAB key. It's main purpose
4766 is outine visibility cycling, but it also invokes other actions
4767 in special contexts.
4769 - When this function is called with a prefix argument, rotate the entire
4770 buffer through 3 states (global cycling)
4771 1. OVERVIEW: Show only top-level headlines.
4772 2. CONTENTS: Show all headlines of all levels, but no body text.
4773 3. SHOW ALL: Show everything.
4774 When called with two `C-u C-u' prefixes, switch to the startup visibility,
4775 determined by the variable `org-startup-folded', and by any VISIBILITY
4776 properties in the buffer.
4777 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
4778 including any drawers.
4780 - When inside a table, re-align the table and move to the next field.
4782 - When point is at the beginning of a headline, rotate the subtree started
4783 by this line through 3 different states (local cycling)
4784 1. FOLDED: Only the main headline is shown.
4785 2. CHILDREN: The main headline and the direct children are shown.
4786 From this state, you can move to one of the children
4787 and zoom in further.
4788 3. SUBTREE: Show the entire subtree, including body text.
4789 If there is no subtree, switch directly from CHILDREN to FOLDED.
4791 - When there is a numeric prefix, go up to a heading with level ARG, do
4792 a `show-subtree' and return to the previous cursor position. If ARG
4793 is negative, go up that many levels.
4795 - When point is not at the beginning of a headline, execute the global
4796 binding for TAB, which is re-indenting the line. See the option
4797 `org-cycle-emulate-tab' for details.
4799 - Special case: if point is at the beginning of the buffer and there is
4800 no headline in line 1, this function will act as if called with prefix arg.
4801 But only if also the variable `org-cycle-global-at-bob' is t."
4802 (interactive "P")
4803 (org-load-modules-maybe)
4804 (unless (run-hook-with-args-until-success 'org-tab-first-hook)
4805 (let* ((limit-level
4806 (or org-cycle-max-level
4807 (and (boundp 'org-inlinetask-min-level)
4808 org-inlinetask-min-level
4809 (1- org-inlinetask-min-level))))
4810 (nstars (and limit-level
4811 (if org-odd-levels-only
4812 (and limit-level (1- (* limit-level 2)))
4813 limit-level)))
4814 (outline-regexp
4815 (cond
4816 ((not (org-mode-p)) outline-regexp)
4817 ((or (eq org-cycle-include-plain-lists 'integrate)
4818 (and org-cycle-include-plain-lists (org-at-item-p)))
4819 (concat "\\(?:\\*"
4820 (if nstars (format "\\{1,%d\\}" nstars) "+")
4821 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
4822 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
4823 (bob-special (and org-cycle-global-at-bob (bobp)
4824 (not (looking-at outline-regexp))))
4825 (org-cycle-hook
4826 (if bob-special
4827 (delq 'org-optimize-window-after-visibility-change
4828 (copy-sequence org-cycle-hook))
4829 org-cycle-hook))
4830 (pos (point)))
4832 (if (or bob-special (equal arg '(4)))
4833 ;; special case: use global cycling
4834 (setq arg t))
4836 (cond
4838 ((equal arg '(16))
4839 (org-set-startup-visibility)
4840 (message "Startup visibility, plus VISIBILITY properties"))
4842 ((equal arg '(64))
4843 (show-all)
4844 (message "Entire buffer visible, including drawers"))
4846 ((org-at-table-p 'any)
4847 ;; Enter the table or move to the next field in the table
4848 (or (org-table-recognize-table.el)
4849 (progn
4850 (if arg (org-table-edit-field t)
4851 (org-table-justify-field-maybe)
4852 (call-interactively 'org-table-next-field)))))
4854 ((run-hook-with-args-until-success
4855 'org-tab-after-check-for-table-hook))
4857 ((eq arg t) ;; Global cycling
4858 (org-cycle-internal-global))
4860 ((and org-drawers org-drawer-regexp
4861 (save-excursion
4862 (beginning-of-line 1)
4863 (looking-at org-drawer-regexp)))
4864 ;; Toggle block visibility
4865 (org-flag-drawer
4866 (not (get-char-property (match-end 0) 'invisible))))
4868 ((integerp arg)
4869 ;; Show-subtree, ARG levels up from here.
4870 (save-excursion
4871 (org-back-to-heading)
4872 (outline-up-heading (if (< arg 0) (- arg)
4873 (- (funcall outline-level) arg)))
4874 (org-show-subtree)))
4876 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4877 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4879 (org-cycle-internal-local))
4881 ;; TAB emulation and template completion
4882 (buffer-read-only (org-back-to-heading))
4884 ((run-hook-with-args-until-success
4885 'org-tab-after-check-for-cycling-hook))
4887 ((org-try-structure-completion))
4889 ((org-try-cdlatex-tab))
4891 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4892 (or (not (bolp))
4893 (not (looking-at outline-regexp))))
4894 (call-interactively (global-key-binding "\t")))
4896 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4897 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4898 (or (and (eq org-cycle-emulate-tab 'white)
4899 (= (match-end 0) (point-at-eol)))
4900 (and (eq org-cycle-emulate-tab 'whitestart)
4901 (>= (match-end 0) pos))))
4903 (eq org-cycle-emulate-tab t))
4904 (call-interactively (global-key-binding "\t")))
4906 (t (save-excursion
4907 (org-back-to-heading)
4908 (org-cycle)))))))
4910 (defun org-cycle-internal-global ()
4911 "Do the global cycling action."
4912 (cond
4913 ((and (eq last-command this-command)
4914 (eq org-cycle-global-status 'overview))
4915 ;; We just created the overview - now do table of contents
4916 ;; This can be slow in very large buffers, so indicate action
4917 (run-hook-with-args 'org-pre-cycle-hook 'contents)
4918 (message "CONTENTS...")
4919 (org-content)
4920 (message "CONTENTS...done")
4921 (setq org-cycle-global-status 'contents)
4922 (run-hook-with-args 'org-cycle-hook 'contents))
4924 ((and (eq last-command this-command)
4925 (eq org-cycle-global-status 'contents))
4926 ;; We just showed the table of contents - now show everything
4927 (run-hook-with-args 'org-pre-cycle-hook 'all)
4928 (show-all)
4929 (message "SHOW ALL")
4930 (setq org-cycle-global-status 'all)
4931 (run-hook-with-args 'org-cycle-hook 'all))
4934 ;; Default action: go to overview
4935 (run-hook-with-args 'org-pre-cycle-hook 'overview)
4936 (org-overview)
4937 (message "OVERVIEW")
4938 (setq org-cycle-global-status 'overview)
4939 (run-hook-with-args 'org-cycle-hook 'overview))))
4941 (defun org-cycle-internal-local ()
4942 "Do the local cycling action."
4943 (org-back-to-heading)
4944 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
4945 ;; First, some boundaries
4946 (save-excursion
4947 (org-back-to-heading)
4948 (setq level (funcall outline-level))
4949 (save-excursion
4950 (beginning-of-line 2)
4951 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
4952 ; XEmacs does not have `next-single-char-property-change'
4953 ; I'm not sure about Emacs 21.
4954 (while (and (not (eobp)) ;; this is like `next-line'
4955 (get-char-property (1- (point)) 'invisible))
4956 (beginning-of-line 2))
4957 (while (and (not (eobp)) ;; this is like `next-line'
4958 (get-char-property (1- (point)) 'invisible))
4959 (goto-char (next-single-char-property-change (point) 'invisible))
4960 ;;;??? (or (bolp) (beginning-of-line 2))))
4961 (and (eolp) (beginning-of-line 2))))
4962 (setq eol (point)))
4963 (outline-end-of-heading) (setq eoh (point))
4964 (save-excursion
4965 (outline-next-heading)
4966 (setq has-children (and (org-at-heading-p t)
4967 (> (funcall outline-level) level))))
4968 (org-end-of-subtree t)
4969 (unless (eobp)
4970 (skip-chars-forward " \t\n")
4971 (beginning-of-line 1) ; in case this is an item
4973 (setq eos (1- (point))))
4974 ;; Find out what to do next and set `this-command'
4975 (cond
4976 ((= eos eoh)
4977 ;; Nothing is hidden behind this heading
4978 (run-hook-with-args 'org-pre-cycle-hook 'empty)
4979 (message "EMPTY ENTRY")
4980 (setq org-cycle-subtree-status nil)
4981 (save-excursion
4982 (goto-char eos)
4983 (outline-next-heading)
4984 (if (org-invisible-p) (org-flag-heading nil))))
4985 ((and (or (>= eol eos)
4986 (not (string-match "\\S-" (buffer-substring eol eos))))
4987 (or has-children
4988 (not (setq children-skipped
4989 org-cycle-skip-children-state-if-no-children))))
4990 ;; Entire subtree is hidden in one line: children view
4991 (run-hook-with-args 'org-pre-cycle-hook 'children)
4992 (org-show-entry)
4993 (show-children)
4994 (message "CHILDREN")
4995 (save-excursion
4996 (goto-char eos)
4997 (outline-next-heading)
4998 (if (org-invisible-p) (org-flag-heading nil)))
4999 (setq org-cycle-subtree-status 'children)
5000 (run-hook-with-args 'org-cycle-hook 'children))
5001 ((or children-skipped
5002 (and (eq last-command this-command)
5003 (eq org-cycle-subtree-status 'children)))
5004 ;; We just showed the children, or no children are there,
5005 ;; now show everything.
5006 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5007 (org-show-subtree)
5008 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5009 (setq org-cycle-subtree-status 'subtree)
5010 (run-hook-with-args 'org-cycle-hook 'subtree))
5012 ;; Default action: hide the subtree.
5013 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5014 (hide-subtree)
5015 (message "FOLDED")
5016 (setq org-cycle-subtree-status 'folded)
5017 (run-hook-with-args 'org-cycle-hook 'folded)))))
5019 ;;;###autoload
5020 (defun org-global-cycle (&optional arg)
5021 "Cycle the global visibility. For details see `org-cycle'.
5022 With C-u prefix arg, switch to startup visibility.
5023 With a numeric prefix, show all headlines up to that level."
5024 (interactive "P")
5025 (let ((org-cycle-include-plain-lists
5026 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5027 (cond
5028 ((integerp arg)
5029 (show-all)
5030 (hide-sublevels arg)
5031 (setq org-cycle-global-status 'contents))
5032 ((equal arg '(4))
5033 (org-set-startup-visibility)
5034 (message "Startup visibility, plus VISIBILITY properties."))
5036 (org-cycle '(4))))))
5038 (defun org-set-startup-visibility ()
5039 "Set the visibility required by startup options and properties."
5040 (cond
5041 ((eq org-startup-folded t)
5042 (org-cycle '(4)))
5043 ((eq org-startup-folded 'content)
5044 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5045 (org-cycle '(4)) (org-cycle '(4)))))
5046 (if org-hide-block-startup (org-hide-block-all))
5047 (org-set-visibility-according-to-property 'no-cleanup)
5048 (org-cycle-hide-archived-subtrees 'all)
5049 (org-cycle-hide-drawers 'all)
5050 (org-cycle-show-empty-lines 'all))
5052 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5053 "Switch subtree visibilities according to :VISIBILITY: property."
5054 (interactive)
5055 (let (org-show-entry-below state)
5056 (save-excursion
5057 (goto-char (point-min))
5058 (while (re-search-forward
5059 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5060 nil t)
5061 (setq state (match-string 1))
5062 (save-excursion
5063 (org-back-to-heading t)
5064 (hide-subtree)
5065 (org-reveal)
5066 (cond
5067 ((equal state '("fold" "folded"))
5068 (hide-subtree))
5069 ((equal state "children")
5070 (org-show-hidden-entry)
5071 (show-children))
5072 ((equal state "content")
5073 (save-excursion
5074 (save-restriction
5075 (org-narrow-to-subtree)
5076 (org-content))))
5077 ((member state '("all" "showall"))
5078 (show-subtree)))))
5079 (unless no-cleanup
5080 (org-cycle-hide-archived-subtrees 'all)
5081 (org-cycle-hide-drawers 'all)
5082 (org-cycle-show-empty-lines 'all)))))
5084 (defun org-overview ()
5085 "Switch to overview mode, showing only top-level headlines.
5086 Really, this shows all headlines with level equal or greater than the level
5087 of the first headline in the buffer. This is important, because if the
5088 first headline is not level one, then (hide-sublevels 1) gives confusing
5089 results."
5090 (interactive)
5091 (let ((level (save-excursion
5092 (goto-char (point-min))
5093 (if (re-search-forward (concat "^" outline-regexp) nil t)
5094 (progn
5095 (goto-char (match-beginning 0))
5096 (funcall outline-level))))))
5097 (and level (hide-sublevels level))))
5099 (defun org-content (&optional arg)
5100 "Show all headlines in the buffer, like a table of contents.
5101 With numerical argument N, show content up to level N."
5102 (interactive "P")
5103 (save-excursion
5104 ;; Visit all headings and show their offspring
5105 (and (integerp arg) (org-overview))
5106 (goto-char (point-max))
5107 (catch 'exit
5108 (while (and (progn (condition-case nil
5109 (outline-previous-visible-heading 1)
5110 (error (goto-char (point-min))))
5112 (looking-at outline-regexp))
5113 (if (integerp arg)
5114 (show-children (1- arg))
5115 (show-branches))
5116 (if (bobp) (throw 'exit nil))))))
5119 (defun org-optimize-window-after-visibility-change (state)
5120 "Adjust the window after a change in outline visibility.
5121 This function is the default value of the hook `org-cycle-hook'."
5122 (when (get-buffer-window (current-buffer))
5123 (cond
5124 ((eq state 'content) nil)
5125 ((eq state 'all) nil)
5126 ((eq state 'folded) nil)
5127 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5128 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5130 ;; FIXME: no longer in use
5131 (defun org-compact-display-after-subtree-move ()
5132 "Show a compacter version of the tree of the entry's parent."
5133 (save-excursion
5134 (if (org-up-heading-safe)
5135 (progn
5136 (hide-subtree)
5137 (show-entry)
5138 (show-children)
5139 (org-cycle-show-empty-lines 'children)
5140 (org-cycle-hide-drawers 'children))
5141 (org-overview))))
5143 (defun org-remove-empty-overlays-at (pos)
5144 "Remove outline overlays that do not contain non-white stuff."
5145 (mapc
5146 (lambda (o)
5147 (and (eq 'outline (org-overlay-get o 'invisible))
5148 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5149 (org-overlay-end o))))
5150 (org-delete-overlay o)))
5151 (org-overlays-at pos)))
5153 (defun org-clean-visibility-after-subtree-move ()
5154 "Fix visibility issues after moving a subtree."
5155 ;; First, find a reasonable region to look at:
5156 ;; Start two siblings above, end three below
5157 (let* ((beg (save-excursion
5158 (and (outline-get-last-sibling)
5159 (outline-get-last-sibling))
5160 (point)))
5161 (end (save-excursion
5162 (and (outline-get-next-sibling)
5163 (outline-get-next-sibling)
5164 (outline-get-next-sibling))
5165 (if (org-at-heading-p)
5166 (point-at-eol)
5167 (point))))
5168 (level (looking-at "\\*+"))
5169 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5170 (save-excursion
5171 (save-restriction
5172 (narrow-to-region beg end)
5173 (when re
5174 ;; Properly fold already folded siblings
5175 (goto-char (point-min))
5176 (while (re-search-forward re nil t)
5177 (if (save-excursion (goto-char (point-at-eol)) (org-invisible-p))
5178 (hide-entry))))
5179 (org-cycle-show-empty-lines 'overview)
5180 (org-cycle-hide-drawers 'overview)))))
5182 (defun org-cycle-show-empty-lines (state)
5183 "Show empty lines above all visible headlines.
5184 The region to be covered depends on STATE when called through
5185 `org-cycle-hook'. Lisp program can use t for STATE to get the
5186 entire buffer covered. Note that an empty line is only shown if there
5187 are at least `org-cycle-separator-lines' empty lines before the headline."
5188 (when (> org-cycle-separator-lines 0)
5189 (save-excursion
5190 (let* ((n org-cycle-separator-lines)
5191 (re (cond
5192 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5193 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5194 (t (let ((ns (number-to-string (- n 2))))
5195 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5196 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5197 beg end)
5198 (cond
5199 ((memq state '(overview contents t))
5200 (setq beg (point-min) end (point-max)))
5201 ((memq state '(children folded))
5202 (setq beg (point) end (progn (org-end-of-subtree t t)
5203 (beginning-of-line 2)
5204 (point)))))
5205 (when beg
5206 (goto-char beg)
5207 (while (re-search-forward re end t)
5208 (if (not (get-char-property (match-end 1) 'invisible))
5209 (outline-flag-region
5210 (match-beginning 1) (match-end 1) nil)))))))
5211 ;; Never hide empty lines at the end of the file.
5212 (save-excursion
5213 (goto-char (point-max))
5214 (outline-previous-heading)
5215 (outline-end-of-heading)
5216 (if (and (looking-at "[ \t\n]+")
5217 (= (match-end 0) (point-max)))
5218 (outline-flag-region (point) (match-end 0) nil))))
5220 (defun org-show-empty-lines-in-parent ()
5221 "Move to the parent and re-show empty lines before visible headlines."
5222 (save-excursion
5223 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5224 (org-cycle-show-empty-lines context))))
5226 (defun org-cycle-hide-drawers (state)
5227 "Re-hide all drawers after a visibility state change."
5228 (when (and (org-mode-p)
5229 (not (memq state '(overview folded contents))))
5230 (save-excursion
5231 (let* ((globalp (memq state '(contents all)))
5232 (beg (if globalp (point-min) (point)))
5233 (end (if globalp (point-max)
5234 (if (eq state 'children)
5235 (save-excursion (outline-next-heading) (point))
5236 (org-end-of-subtree t)))))
5237 (goto-char beg)
5238 (while (re-search-forward org-drawer-regexp end t)
5239 (org-flag-drawer t))))))
5241 (defun org-flag-drawer (flag)
5242 (save-excursion
5243 (beginning-of-line 1)
5244 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5245 (let ((b (match-end 0))
5246 (outline-regexp org-outline-regexp))
5247 (if (re-search-forward
5248 "^[ \t]*:END:"
5249 (save-excursion (outline-next-heading) (point)) t)
5250 (outline-flag-region b (point-at-eol) flag)
5251 (error ":END: line missing"))))))
5253 (defun org-subtree-end-visible-p ()
5254 "Is the end of the current subtree visible?"
5255 (pos-visible-in-window-p
5256 (save-excursion (org-end-of-subtree t) (point))))
5258 (defun org-first-headline-recenter (&optional N)
5259 "Move cursor to the first headline and recenter the headline.
5260 Optional argument N means, put the headline into the Nth line of the window."
5261 (goto-char (point-min))
5262 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5263 (beginning-of-line)
5264 (recenter (prefix-numeric-value N))))
5266 ;;; Folding of blocks
5268 (defconst org-block-regexp
5270 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5271 "Regular expression for hiding blocks.")
5273 (defvar org-hide-block-overlays nil
5274 "Overays hiding blocks.")
5275 (make-variable-buffer-local 'org-hide-block-overlays)
5277 (defun org-block-map (function &optional start end)
5278 "Call func at the head of all source blocks in the current
5279 buffer. Optional arguments START and END can be used to limit
5280 the range."
5281 (let ((start (or start (point-min)))
5282 (end (or end (point-max))))
5283 (save-excursion
5284 (goto-char start)
5285 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5286 (save-excursion
5287 (save-match-data
5288 (goto-char (match-beginning 0))
5289 (funcall function)))))))
5291 (defun org-hide-block-toggle-all ()
5292 "Toggle the visibility of all blocks in the current buffer."
5293 (org-block-map #'org-hide-block-toggle))
5295 (defun org-hide-block-all ()
5296 "Fold all blocks in the current buffer."
5297 (interactive)
5298 (org-show-block-all)
5299 (org-block-map #'org-hide-block-toggle-maybe))
5301 (defun org-show-block-all ()
5302 "Unfold all blocks in the current buffer."
5303 (mapc 'org-delete-overlay org-hide-block-overlays)
5304 (setq org-hide-block-overlays nil))
5306 (defun org-hide-block-toggle-maybe ()
5307 "Toggle visibility of block at point."
5308 (interactive)
5309 (let ((case-fold-search t))
5310 (if (save-excursion
5311 (beginning-of-line 1)
5312 (looking-at org-block-regexp))
5313 (progn (org-hide-block-toggle)
5314 t) ;; to signal that we took action
5315 nil))) ;; to signal that we did not
5317 (defun org-hide-block-toggle (&optional force)
5318 "Toggle the visibility of the current block."
5319 (interactive)
5320 (save-excursion
5321 (beginning-of-line)
5322 (if (re-search-forward org-block-regexp nil t)
5323 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5324 (end (match-end 0))
5325 ov) ;; end of entire body
5326 (if (memq t (mapcar (lambda (overlay)
5327 (eq (org-overlay-get overlay 'invisible)
5328 'org-hide-block))
5329 (org-overlays-at start)))
5330 (if (or (not force) (eq force 'off))
5331 (mapc (lambda (ov)
5332 (when (member ov org-hide-block-overlays)
5333 (setq org-hide-block-overlays
5334 (delq ov org-hide-block-overlays)))
5335 (when (eq (org-overlay-get ov 'invisible)
5336 'org-hide-block)
5337 (org-delete-overlay ov)))
5338 (org-overlays-at start)))
5339 (setq ov (org-make-overlay start end))
5340 (org-overlay-put ov 'invisible 'org-hide-block)
5341 (push ov org-hide-block-overlays)))
5342 (error "Not looking at a source block"))))
5344 ;; org-tab-after-check-for-cycling-hook
5345 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5346 ;; Remove overlays when changing major mode
5347 (add-hook 'org-mode-hook
5348 (lambda () (org-add-hook 'change-major-mode-hook
5349 'org-show-block-all 'append 'local)))
5351 ;;; Org-goto
5353 (defvar org-goto-window-configuration nil)
5354 (defvar org-goto-marker nil)
5355 (defvar org-goto-map
5356 (let ((map (make-sparse-keymap)))
5357 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5358 (while (setq cmd (pop cmds))
5359 (substitute-key-definition cmd cmd map global-map)))
5360 (suppress-keymap map)
5361 (org-defkey map "\C-m" 'org-goto-ret)
5362 (org-defkey map [(return)] 'org-goto-ret)
5363 (org-defkey map [(left)] 'org-goto-left)
5364 (org-defkey map [(right)] 'org-goto-right)
5365 (org-defkey map [(control ?g)] 'org-goto-quit)
5366 (org-defkey map "\C-i" 'org-cycle)
5367 (org-defkey map [(tab)] 'org-cycle)
5368 (org-defkey map [(down)] 'outline-next-visible-heading)
5369 (org-defkey map [(up)] 'outline-previous-visible-heading)
5370 (if org-goto-auto-isearch
5371 (if (fboundp 'define-key-after)
5372 (define-key-after map [t] 'org-goto-local-auto-isearch)
5373 nil)
5374 (org-defkey map "q" 'org-goto-quit)
5375 (org-defkey map "n" 'outline-next-visible-heading)
5376 (org-defkey map "p" 'outline-previous-visible-heading)
5377 (org-defkey map "f" 'outline-forward-same-level)
5378 (org-defkey map "b" 'outline-backward-same-level)
5379 (org-defkey map "u" 'outline-up-heading))
5380 (org-defkey map "/" 'org-occur)
5381 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5382 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5383 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5384 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5385 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5386 map))
5388 (defconst org-goto-help
5389 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5390 RET=jump to location [Q]uit and return to previous location
5391 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5393 (defvar org-goto-start-pos) ; dynamically scoped parameter
5395 ;; FIXME: Docstring doe not mention both interfaces
5396 (defun org-goto (&optional alternative-interface)
5397 "Look up a different location in the current file, keeping current visibility.
5399 When you want look-up or go to a different location in a document, the
5400 fastest way is often to fold the entire buffer and then dive into the tree.
5401 This method has the disadvantage, that the previous location will be folded,
5402 which may not be what you want.
5404 This command works around this by showing a copy of the current buffer
5405 in an indirect buffer, in overview mode. You can dive into the tree in
5406 that copy, use org-occur and incremental search to find a location.
5407 When pressing RET or `Q', the command returns to the original buffer in
5408 which the visibility is still unchanged. After RET is will also jump to
5409 the location selected in the indirect buffer and expose the
5410 the headline hierarchy above."
5411 (interactive "P")
5412 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5413 (org-refile-use-outline-path t)
5414 (org-refile-target-verify-function nil)
5415 (interface
5416 (if (not alternative-interface)
5417 org-goto-interface
5418 (if (eq org-goto-interface 'outline)
5419 'outline-path-completion
5420 'outline)))
5421 (org-goto-start-pos (point))
5422 (selected-point
5423 (if (eq interface 'outline)
5424 (car (org-get-location (current-buffer) org-goto-help))
5425 (nth 3 (org-refile-get-location "Goto: ")))))
5426 (if selected-point
5427 (progn
5428 (org-mark-ring-push org-goto-start-pos)
5429 (goto-char selected-point)
5430 (if (or (org-invisible-p) (org-invisible-p2))
5431 (org-show-context 'org-goto)))
5432 (message "Quit"))))
5434 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5435 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5436 (defvar org-goto-local-auto-isearch-map) ; defined below
5438 (defun org-get-location (buf help)
5439 "Let the user select a location in the Org-mode buffer BUF.
5440 This function uses a recursive edit. It returns the selected position
5441 or nil."
5442 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5443 (isearch-hide-immediately nil)
5444 (isearch-search-fun-function
5445 (lambda () 'org-goto-local-search-headings))
5446 (org-goto-selected-point org-goto-exit-command))
5447 (save-excursion
5448 (save-window-excursion
5449 (delete-other-windows)
5450 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5451 (switch-to-buffer
5452 (condition-case nil
5453 (make-indirect-buffer (current-buffer) "*org-goto*")
5454 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5455 (with-output-to-temp-buffer "*Help*"
5456 (princ help))
5457 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5458 (setq buffer-read-only nil)
5459 (let ((org-startup-truncated t)
5460 (org-startup-folded nil)
5461 (org-startup-align-all-tables nil))
5462 (org-mode)
5463 (org-overview))
5464 (setq buffer-read-only t)
5465 (if (and (boundp 'org-goto-start-pos)
5466 (integer-or-marker-p org-goto-start-pos))
5467 (let ((org-show-hierarchy-above t)
5468 (org-show-siblings t)
5469 (org-show-following-heading t))
5470 (goto-char org-goto-start-pos)
5471 (and (org-invisible-p) (org-show-context)))
5472 (goto-char (point-min)))
5473 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5474 (message "Select location and press RET")
5475 (use-local-map org-goto-map)
5476 (recursive-edit)
5478 (kill-buffer "*org-goto*")
5479 (cons org-goto-selected-point org-goto-exit-command)))
5481 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5482 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5483 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5484 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5486 (defun org-goto-local-search-headings (string bound noerror)
5487 "Search and make sure that any matches are in headlines."
5488 (catch 'return
5489 (while (if isearch-forward
5490 (search-forward string bound noerror)
5491 (search-backward string bound noerror))
5492 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5493 (and (member :headline context)
5494 (not (member :tags context))))
5495 (throw 'return (point))))))
5497 (defun org-goto-local-auto-isearch ()
5498 "Start isearch."
5499 (interactive)
5500 (goto-char (point-min))
5501 (let ((keys (this-command-keys)))
5502 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5503 (isearch-mode t)
5504 (isearch-process-search-char (string-to-char keys)))))
5506 (defun org-goto-ret (&optional arg)
5507 "Finish `org-goto' by going to the new location."
5508 (interactive "P")
5509 (setq org-goto-selected-point (point)
5510 org-goto-exit-command 'return)
5511 (throw 'exit nil))
5513 (defun org-goto-left ()
5514 "Finish `org-goto' by going to the new location."
5515 (interactive)
5516 (if (org-on-heading-p)
5517 (progn
5518 (beginning-of-line 1)
5519 (setq org-goto-selected-point (point)
5520 org-goto-exit-command 'left)
5521 (throw 'exit nil))
5522 (error "Not on a heading")))
5524 (defun org-goto-right ()
5525 "Finish `org-goto' by going to the new location."
5526 (interactive)
5527 (if (org-on-heading-p)
5528 (progn
5529 (setq org-goto-selected-point (point)
5530 org-goto-exit-command 'right)
5531 (throw 'exit nil))
5532 (error "Not on a heading")))
5534 (defun org-goto-quit ()
5535 "Finish `org-goto' without cursor motion."
5536 (interactive)
5537 (setq org-goto-selected-point nil)
5538 (setq org-goto-exit-command 'quit)
5539 (throw 'exit nil))
5541 ;;; Indirect buffer display of subtrees
5543 (defvar org-indirect-dedicated-frame nil
5544 "This is the frame being used for indirect tree display.")
5545 (defvar org-last-indirect-buffer nil)
5547 (defun org-tree-to-indirect-buffer (&optional arg)
5548 "Create indirect buffer and narrow it to current subtree.
5549 With numerical prefix ARG, go up to this level and then take that tree.
5550 If ARG is negative, go up that many levels.
5551 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5552 indirect buffer previously made with this command, to avoid proliferation of
5553 indirect buffers. However, when you call the command with a `C-u' prefix, or
5554 when `org-indirect-buffer-display' is `new-frame', the last buffer
5555 is kept so that you can work with several indirect buffers at the same time.
5556 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5557 requests that a new frame be made for the new buffer, so that the dedicated
5558 frame is not changed."
5559 (interactive "P")
5560 (let ((cbuf (current-buffer))
5561 (cwin (selected-window))
5562 (pos (point))
5563 beg end level heading ibuf)
5564 (save-excursion
5565 (org-back-to-heading t)
5566 (when (numberp arg)
5567 (setq level (org-outline-level))
5568 (if (< arg 0) (setq arg (+ level arg)))
5569 (while (> (setq level (org-outline-level)) arg)
5570 (outline-up-heading 1 t)))
5571 (setq beg (point)
5572 heading (org-get-heading))
5573 (org-end-of-subtree t) (setq end (point)))
5574 (if (and (buffer-live-p org-last-indirect-buffer)
5575 (not (eq org-indirect-buffer-display 'new-frame))
5576 (not arg))
5577 (kill-buffer org-last-indirect-buffer))
5578 (setq ibuf (org-get-indirect-buffer cbuf)
5579 org-last-indirect-buffer ibuf)
5580 (cond
5581 ((or (eq org-indirect-buffer-display 'new-frame)
5582 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5583 (select-frame (make-frame))
5584 (delete-other-windows)
5585 (switch-to-buffer ibuf)
5586 (org-set-frame-title heading))
5587 ((eq org-indirect-buffer-display 'dedicated-frame)
5588 (raise-frame
5589 (select-frame (or (and org-indirect-dedicated-frame
5590 (frame-live-p org-indirect-dedicated-frame)
5591 org-indirect-dedicated-frame)
5592 (setq org-indirect-dedicated-frame (make-frame)))))
5593 (delete-other-windows)
5594 (switch-to-buffer ibuf)
5595 (org-set-frame-title (concat "Indirect: " heading)))
5596 ((eq org-indirect-buffer-display 'current-window)
5597 (switch-to-buffer ibuf))
5598 ((eq org-indirect-buffer-display 'other-window)
5599 (pop-to-buffer ibuf))
5600 (t (error "Invalid value.")))
5601 (if (featurep 'xemacs)
5602 (save-excursion (org-mode) (turn-on-font-lock)))
5603 (narrow-to-region beg end)
5604 (show-all)
5605 (goto-char pos)
5606 (and (window-live-p cwin) (select-window cwin))))
5608 (defun org-get-indirect-buffer (&optional buffer)
5609 (setq buffer (or buffer (current-buffer)))
5610 (let ((n 1) (base (buffer-name buffer)) bname)
5611 (while (buffer-live-p
5612 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5613 (setq n (1+ n)))
5614 (condition-case nil
5615 (make-indirect-buffer buffer bname 'clone)
5616 (error (make-indirect-buffer buffer bname)))))
5618 (defun org-set-frame-title (title)
5619 "Set the title of the current frame to the string TITLE."
5620 ;; FIXME: how to name a single frame in XEmacs???
5621 (unless (featurep 'xemacs)
5622 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5624 ;;;; Structure editing
5626 ;;; Inserting headlines
5628 (defun org-previous-line-empty-p ()
5629 (save-excursion
5630 (and (not (bobp))
5631 (or (beginning-of-line 0) t)
5632 (save-match-data
5633 (looking-at "[ \t]*$")))))
5635 (defun org-insert-heading (&optional force-heading)
5636 "Insert a new heading or item with same depth at point.
5637 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5638 If point is at the beginning of a headline, insert a sibling before the
5639 current headline. If point is not at the beginning, do not split the line,
5640 but create the new headline after the current line."
5641 (interactive "P")
5642 (if (= (buffer-size) 0)
5643 (insert "\n* ")
5644 (when (or force-heading (not (org-insert-item)))
5645 (let* ((empty-line-p nil)
5646 (head (save-excursion
5647 (condition-case nil
5648 (progn
5649 (org-back-to-heading)
5650 (setq empty-line-p (org-previous-line-empty-p))
5651 (match-string 0))
5652 (error "*"))))
5653 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5654 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5655 pos hide-previous previous-pos)
5656 (cond
5657 ((and (org-on-heading-p) (bolp)
5658 (or (bobp)
5659 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5660 ;; insert before the current line
5661 (open-line (if blank 2 1)))
5662 ((and (bolp)
5663 (or (bobp)
5664 (save-excursion
5665 (backward-char 1) (not (org-invisible-p)))))
5666 ;; insert right here
5667 nil)
5669 ;; somewhere in the line
5670 (save-excursion
5671 (setq previous-pos (point-at-bol))
5672 (end-of-line)
5673 (setq hide-previous (org-invisible-p)))
5674 (and org-insert-heading-respect-content (org-show-subtree))
5675 (let ((split
5676 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5677 (save-excursion
5678 (let ((p (point)))
5679 (goto-char (point-at-bol))
5680 (and (looking-at org-complex-heading-regexp)
5681 (> p (match-beginning 4)))))))
5682 tags pos)
5683 (cond
5684 (org-insert-heading-respect-content
5685 (org-end-of-subtree nil t)
5686 (or (bolp) (newline))
5687 (or (org-previous-line-empty-p)
5688 (and blank (newline)))
5689 (open-line 1))
5690 ((org-on-heading-p)
5691 (when hide-previous
5692 (show-children)
5693 (org-show-entry))
5694 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5695 (setq tags (and (match-end 2) (match-string 2)))
5696 (and (match-end 1)
5697 (delete-region (match-beginning 1) (match-end 1)))
5698 (setq pos (point-at-bol))
5699 (or split (end-of-line 1))
5700 (delete-horizontal-space)
5701 (newline (if blank 2 1))
5702 (when tags
5703 (save-excursion
5704 (goto-char pos)
5705 (end-of-line 1)
5706 (insert " " tags)
5707 (org-set-tags nil 'align))))
5709 (or split (end-of-line 1))
5710 (newline (if blank 2 1)))))))
5711 (insert head) (just-one-space)
5712 (setq pos (point))
5713 (end-of-line 1)
5714 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5715 (when (and org-insert-heading-respect-content hide-previous)
5716 (save-excursion
5717 (goto-char previous-pos)
5718 (hide-subtree)))
5719 (run-hooks 'org-insert-heading-hook)))))
5721 (defun org-get-heading (&optional no-tags)
5722 "Return the heading of the current entry, without the stars."
5723 (save-excursion
5724 (org-back-to-heading t)
5725 (if (looking-at
5726 (if no-tags
5727 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5728 "\\*+[ \t]+\\([^\r\n]*\\)"))
5729 (match-string 1) "")))
5731 (defun org-heading-components ()
5732 "Return the components of the current heading.
5733 This is a list with the following elements:
5734 - the level as an integer
5735 - the reduced level, different if `org-odd-levels-only' is set.
5736 - the TODO keyword, or nil
5737 - the priority character, like ?A, or nil if no priority is given
5738 - the headline text itself, or the tags string if no headline text
5739 - the tags string, or nil."
5740 (save-excursion
5741 (org-back-to-heading t)
5742 (if (looking-at org-complex-heading-regexp)
5743 (list (length (match-string 1))
5744 (org-reduced-level (length (match-string 1)))
5745 (org-match-string-no-properties 2)
5746 (and (match-end 3) (aref (match-string 3) 2))
5747 (org-match-string-no-properties 4)
5748 (org-match-string-no-properties 5)))))
5750 (defun org-get-entry ()
5751 "Get the entry text, after heading, entire subtree."
5752 (save-excursion
5753 (org-back-to-heading t)
5754 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
5756 (defun org-insert-heading-after-current ()
5757 "Insert a new heading with same level as current, after current subtree."
5758 (interactive)
5759 (org-back-to-heading)
5760 (org-insert-heading)
5761 (org-move-subtree-down)
5762 (end-of-line 1))
5764 (defun org-insert-heading-respect-content ()
5765 (interactive)
5766 (let ((org-insert-heading-respect-content t))
5767 (org-insert-heading t)))
5769 (defun org-insert-todo-heading-respect-content (&optional force-state)
5770 (interactive "P")
5771 (let ((org-insert-heading-respect-content t))
5772 (org-insert-todo-heading force-state t)))
5774 (defun org-insert-todo-heading (arg &optional force-heading)
5775 "Insert a new heading with the same level and TODO state as current heading.
5776 If the heading has no TODO state, or if the state is DONE, use the first
5777 state (TODO by default). Also with prefix arg, force first state."
5778 (interactive "P")
5779 (when (or force-heading (not (org-insert-item 'checkbox)))
5780 (org-insert-heading force-heading)
5781 (save-excursion
5782 (org-back-to-heading)
5783 (outline-previous-heading)
5784 (looking-at org-todo-line-regexp))
5785 (let*
5786 ((new-mark-x
5787 (if (or arg
5788 (not (match-beginning 2))
5789 (member (match-string 2) org-done-keywords))
5790 (car org-todo-keywords-1)
5791 (match-string 2)))
5792 (new-mark
5794 (run-hook-with-args-until-success
5795 'org-todo-get-default-hook new-mark-x nil)
5796 new-mark-x)))
5797 (beginning-of-line 1)
5798 (and (looking-at "\\*+ ") (goto-char (match-end 0))
5799 (if org-treat-insert-todo-heading-as-state-change
5800 (org-todo new-mark)
5801 (insert new-mark " "))))
5802 (when org-provide-todo-statistics
5803 (org-update-parent-todo-statistics))))
5805 (defun org-insert-subheading (arg)
5806 "Insert a new subheading and demote it.
5807 Works for outline headings and for plain lists alike."
5808 (interactive "P")
5809 (org-insert-heading arg)
5810 (cond
5811 ((org-on-heading-p) (org-do-demote))
5812 ((org-at-item-p) (org-indent-item 1))))
5814 (defun org-insert-todo-subheading (arg)
5815 "Insert a new subheading with TODO keyword or checkbox and demote it.
5816 Works for outline headings and for plain lists alike."
5817 (interactive "P")
5818 (org-insert-todo-heading arg)
5819 (cond
5820 ((org-on-heading-p) (org-do-demote))
5821 ((org-at-item-p) (org-indent-item 1))))
5823 ;;; Promotion and Demotion
5825 (defvar org-after-demote-entry-hook nil
5826 "Hook run after an entry has been demoted.
5827 The cursor will be at the beginning of the entry.
5828 When a subtree is being demoted, the hook will be called for each node.")
5830 (defvar org-after-promote-entry-hook nil
5831 "Hook run after an entry has been promoted.
5832 The cursor will be at the beginning of the entry.
5833 When a subtree is being promoted, the hook will be called for each node.")
5835 (defun org-promote-subtree ()
5836 "Promote the entire subtree.
5837 See also `org-promote'."
5838 (interactive)
5839 (save-excursion
5840 (org-map-tree 'org-promote))
5841 (org-fix-position-after-promote))
5843 (defun org-demote-subtree ()
5844 "Demote the entire subtree. See `org-demote'.
5845 See also `org-promote'."
5846 (interactive)
5847 (save-excursion
5848 (org-map-tree 'org-demote))
5849 (org-fix-position-after-promote))
5852 (defun org-do-promote ()
5853 "Promote the current heading higher up the tree.
5854 If the region is active in `transient-mark-mode', promote all headings
5855 in the region."
5856 (interactive)
5857 (save-excursion
5858 (if (org-region-active-p)
5859 (org-map-region 'org-promote (region-beginning) (region-end))
5860 (org-promote)))
5861 (org-fix-position-after-promote))
5863 (defun org-do-demote ()
5864 "Demote the current heading lower down the tree.
5865 If the region is active in `transient-mark-mode', demote all headings
5866 in the region."
5867 (interactive)
5868 (save-excursion
5869 (if (org-region-active-p)
5870 (org-map-region 'org-demote (region-beginning) (region-end))
5871 (org-demote)))
5872 (org-fix-position-after-promote))
5874 (defun org-fix-position-after-promote ()
5875 "Make sure that after pro/demotion cursor position is right."
5876 (let ((pos (point)))
5877 (when (save-excursion
5878 (beginning-of-line 1)
5879 (looking-at org-todo-line-regexp)
5880 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5881 (cond ((eobp) (insert " "))
5882 ((eolp) (insert " "))
5883 ((equal (char-after) ?\ ) (forward-char 1))))))
5885 (defun org-reduced-level (l)
5886 "Compute the effective level of a heading.
5887 This takes into account the setting of `org-odd-levels-only'."
5888 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5890 (defun org-get-valid-level (level &optional change)
5891 "Rectify a level change under the influence of `org-odd-levels-only'
5892 LEVEL is a current level, CHANGE is by how much the level should be
5893 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5894 even level numbers will become the next higher odd number."
5895 (if org-odd-levels-only
5896 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5897 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5898 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5899 (max 1 (+ level (or change 0)))))
5901 (if (boundp 'define-obsolete-function-alias)
5902 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5903 (define-obsolete-function-alias 'org-get-legal-level
5904 'org-get-valid-level)
5905 (define-obsolete-function-alias 'org-get-legal-level
5906 'org-get-valid-level "23.1")))
5908 (defun org-promote ()
5909 "Promote the current heading higher up the tree.
5910 If the region is active in `transient-mark-mode', promote all headings
5911 in the region."
5912 (org-back-to-heading t)
5913 (let* ((level (save-match-data (funcall outline-level)))
5914 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5915 (diff (abs (- level (length up-head) -1))))
5916 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5917 (replace-match up-head nil t)
5918 ;; Fixup tag positioning
5919 (and org-auto-align-tags (org-set-tags nil t))
5920 (if org-adapt-indentation (org-fixup-indentation (- diff)))
5921 (run-hooks 'org-after-promote-entry-hook)))
5923 (defun org-demote ()
5924 "Demote the current heading lower down the tree.
5925 If the region is active in `transient-mark-mode', demote all headings
5926 in the region."
5927 (org-back-to-heading t)
5928 (let* ((level (save-match-data (funcall outline-level)))
5929 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5930 (diff (abs (- level (length down-head) -1))))
5931 (replace-match down-head nil t)
5932 ;; Fixup tag positioning
5933 (and org-auto-align-tags (org-set-tags nil t))
5934 (if org-adapt-indentation (org-fixup-indentation diff))
5935 (run-hooks 'org-after-demote-entry-hook)))
5937 (defun org-map-tree (fun)
5938 "Call FUN for every heading underneath the current one."
5939 (org-back-to-heading)
5940 (let ((level (funcall outline-level)))
5941 (save-excursion
5942 (funcall fun)
5943 (while (and (progn
5944 (outline-next-heading)
5945 (> (funcall outline-level) level))
5946 (not (eobp)))
5947 (funcall fun)))))
5949 (defun org-map-region (fun beg end)
5950 "Call FUN for every heading between BEG and END."
5951 (let ((org-ignore-region t))
5952 (save-excursion
5953 (setq end (copy-marker end))
5954 (goto-char beg)
5955 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5956 (< (point) end))
5957 (funcall fun))
5958 (while (and (progn
5959 (outline-next-heading)
5960 (< (point) end))
5961 (not (eobp)))
5962 (funcall fun)))))
5964 (defun org-fixup-indentation (diff)
5965 "Change the indentation in the current entry by DIFF
5966 However, if any line in the current entry has no indentation, or if it
5967 would end up with no indentation after the change, nothing at all is done."
5968 (save-excursion
5969 (let ((end (save-excursion (outline-next-heading)
5970 (point-marker)))
5971 (prohibit (if (> diff 0)
5972 "^\\S-"
5973 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5974 col)
5975 (unless (save-excursion (end-of-line 1)
5976 (re-search-forward prohibit end t))
5977 (while (and (< (point) end)
5978 (re-search-forward "^[ \t]+" end t))
5979 (goto-char (match-end 0))
5980 (setq col (current-column))
5981 (if (< diff 0) (replace-match ""))
5982 (org-indent-to-column (+ diff col))))
5983 (move-marker end nil))))
5985 (defun org-convert-to-odd-levels ()
5986 "Convert an org-mode file with all levels allowed to one with odd levels.
5987 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5988 level 5 etc."
5989 (interactive)
5990 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5991 (let ((org-odd-levels-only nil) n)
5992 (save-excursion
5993 (goto-char (point-min))
5994 (while (re-search-forward "^\\*\\*+ " nil t)
5995 (setq n (- (length (match-string 0)) 2))
5996 (while (>= (setq n (1- n)) 0)
5997 (org-demote))
5998 (end-of-line 1))))))
6001 (defun org-convert-to-oddeven-levels ()
6002 "Convert an org-mode file with only odd levels to one with odd and even levels.
6003 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6004 section with an even level, conversion would destroy the structure of the file. An error
6005 is signaled in this case."
6006 (interactive)
6007 (goto-char (point-min))
6008 ;; First check if there are no even levels
6009 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6010 (org-show-context t)
6011 (error "Not all levels are odd in this file. Conversion not possible."))
6012 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6013 (let ((org-odd-levels-only nil) n)
6014 (save-excursion
6015 (goto-char (point-min))
6016 (while (re-search-forward "^\\*\\*+ " nil t)
6017 (setq n (/ (1- (length (match-string 0))) 2))
6018 (while (>= (setq n (1- n)) 0)
6019 (org-promote))
6020 (end-of-line 1))))))
6022 (defun org-tr-level (n)
6023 "Make N odd if required."
6024 (if org-odd-levels-only (1+ (/ n 2)) n))
6026 ;;; Vertical tree motion, cutting and pasting of subtrees
6028 (defun org-move-subtree-up (&optional arg)
6029 "Move the current subtree up past ARG headlines of the same level."
6030 (interactive "p")
6031 (org-move-subtree-down (- (prefix-numeric-value arg))))
6033 (defun org-move-subtree-down (&optional arg)
6034 "Move the current subtree down past ARG headlines of the same level."
6035 (interactive "p")
6036 (setq arg (prefix-numeric-value arg))
6037 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6038 'outline-get-last-sibling))
6039 (ins-point (make-marker))
6040 (cnt (abs arg))
6041 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6042 ;; Select the tree
6043 (org-back-to-heading)
6044 (setq beg0 (point))
6045 (save-excursion
6046 (setq ne-beg (org-back-over-empty-lines))
6047 (setq beg (point)))
6048 (save-match-data
6049 (save-excursion (outline-end-of-heading)
6050 (setq folded (org-invisible-p)))
6051 (outline-end-of-subtree))
6052 (outline-next-heading)
6053 (setq ne-end (org-back-over-empty-lines))
6054 (setq end (point))
6055 (goto-char beg0)
6056 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6057 ;; include less whitespace
6058 (save-excursion
6059 (goto-char beg)
6060 (forward-line (- ne-beg ne-end))
6061 (setq beg (point))))
6062 ;; Find insertion point, with error handling
6063 (while (> cnt 0)
6064 (or (and (funcall movfunc) (looking-at outline-regexp))
6065 (progn (goto-char beg0)
6066 (error "Cannot move past superior level or buffer limit")))
6067 (setq cnt (1- cnt)))
6068 (if (> arg 0)
6069 ;; Moving forward - still need to move over subtree
6070 (progn (org-end-of-subtree t t)
6071 (save-excursion
6072 (org-back-over-empty-lines)
6073 (or (bolp) (newline)))))
6074 (setq ne-ins (org-back-over-empty-lines))
6075 (move-marker ins-point (point))
6076 (setq txt (buffer-substring beg end))
6077 (org-save-markers-in-region beg end)
6078 (delete-region beg end)
6079 (org-remove-empty-overlays-at beg)
6080 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6081 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6082 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6083 (let ((bbb (point)))
6084 (insert-before-markers txt)
6085 (org-reinstall-markers-in-region bbb)
6086 (move-marker ins-point bbb))
6087 (or (bolp) (insert "\n"))
6088 (setq ins-end (point))
6089 (goto-char ins-point)
6090 (org-skip-whitespace)
6091 (when (and (< arg 0)
6092 (org-first-sibling-p)
6093 (> ne-ins ne-beg))
6094 ;; Move whitespace back to beginning
6095 (save-excursion
6096 (goto-char ins-end)
6097 (let ((kill-whole-line t))
6098 (kill-line (- ne-ins ne-beg)) (point)))
6099 (insert (make-string (- ne-ins ne-beg) ?\n)))
6100 (move-marker ins-point nil)
6101 (if folded
6102 (hide-entry)
6103 (org-show-entry)
6104 (show-children)
6105 (org-cycle-hide-drawers 'children))
6106 (org-clean-visibility-after-subtree-move)))
6108 (defvar org-subtree-clip ""
6109 "Clipboard for cut and paste of subtrees.
6110 This is actually only a copy of the kill, because we use the normal kill
6111 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6113 (defvar org-subtree-clip-folded nil
6114 "Was the last copied subtree folded?
6115 This is used to fold the tree back after pasting.")
6117 (defun org-cut-subtree (&optional n)
6118 "Cut the current subtree into the clipboard.
6119 With prefix arg N, cut this many sequential subtrees.
6120 This is a short-hand for marking the subtree and then cutting it."
6121 (interactive "p")
6122 (org-copy-subtree n 'cut))
6124 (defun org-copy-subtree (&optional n cut force-store-markers)
6125 "Cut the current subtree into the clipboard.
6126 With prefix arg N, cut this many sequential subtrees.
6127 This is a short-hand for marking the subtree and then copying it.
6128 If CUT is non-nil, actually cut the subtree.
6129 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6130 of some markers in the region, even if CUT is non-nil. This is
6131 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6132 (interactive "p")
6133 (let (beg end folded (beg0 (point)))
6134 (if (interactive-p)
6135 (org-back-to-heading nil) ; take what looks like a subtree
6136 (org-back-to-heading t)) ; take what is really there
6137 (org-back-over-empty-lines)
6138 (setq beg (point))
6139 (skip-chars-forward " \t\r\n")
6140 (save-match-data
6141 (save-excursion (outline-end-of-heading)
6142 (setq folded (org-invisible-p)))
6143 (condition-case nil
6144 (outline-forward-same-level (1- n))
6145 (error nil))
6146 (org-end-of-subtree t t))
6147 (org-back-over-empty-lines)
6148 (setq end (point))
6149 (goto-char beg0)
6150 (when (> end beg)
6151 (setq org-subtree-clip-folded folded)
6152 (when (or cut force-store-markers)
6153 (org-save-markers-in-region beg end))
6154 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6155 (setq org-subtree-clip (current-kill 0))
6156 (message "%s: Subtree(s) with %d characters"
6157 (if cut "Cut" "Copied")
6158 (length org-subtree-clip)))))
6160 (defun org-paste-subtree (&optional level tree for-yank)
6161 "Paste the clipboard as a subtree, with modification of headline level.
6162 The entire subtree is promoted or demoted in order to match a new headline
6163 level.
6165 If the cursor is at the beginning of a headline, the same level as
6166 that headline is used to paste the tree
6168 If not, the new level is derived from the *visible* headings
6169 before and after the insertion point, and taken to be the inferior headline
6170 level of the two. So if the previous visible heading is level 3 and the
6171 next is level 4 (or vice versa), level 4 will be used for insertion.
6172 This makes sure that the subtree remains an independent subtree and does
6173 not swallow low level entries.
6175 You can also force a different level, either by using a numeric prefix
6176 argument, or by inserting the heading marker by hand. For example, if the
6177 cursor is after \"*****\", then the tree will be shifted to level 5.
6179 If optional TREE is given, use this text instead of the kill ring.
6181 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6182 move back over whitespace before inserting, and move point to the end of
6183 the inserted text when done."
6184 (interactive "P")
6185 (unless (org-kill-is-subtree-p tree)
6186 (error "%s"
6187 (substitute-command-keys
6188 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6189 (let* ((visp (not (org-invisible-p)))
6190 (txt (or tree (and kill-ring (current-kill 0))))
6191 (^re (concat "^\\(" outline-regexp "\\)"))
6192 (re (concat "\\(" outline-regexp "\\)"))
6193 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6195 (old-level (if (string-match ^re txt)
6196 (- (match-end 0) (match-beginning 0) 1)
6197 -1))
6198 (force-level (cond (level (prefix-numeric-value level))
6199 ((and (looking-at "[ \t]*$")
6200 (string-match
6201 ^re_ (buffer-substring
6202 (point-at-bol) (point))))
6203 (- (match-end 1) (match-beginning 1)))
6204 ((and (bolp)
6205 (looking-at org-outline-regexp))
6206 (- (match-end 0) (point) 1))
6207 (t nil)))
6208 (previous-level (save-excursion
6209 (condition-case nil
6210 (progn
6211 (outline-previous-visible-heading 1)
6212 (if (looking-at re)
6213 (- (match-end 0) (match-beginning 0) 1)
6215 (error 1))))
6216 (next-level (save-excursion
6217 (condition-case nil
6218 (progn
6219 (or (looking-at outline-regexp)
6220 (outline-next-visible-heading 1))
6221 (if (looking-at re)
6222 (- (match-end 0) (match-beginning 0) 1)
6224 (error 1))))
6225 (new-level (or force-level (max previous-level next-level)))
6226 (shift (if (or (= old-level -1)
6227 (= new-level -1)
6228 (= old-level new-level))
6230 (- new-level old-level)))
6231 (delta (if (> shift 0) -1 1))
6232 (func (if (> shift 0) 'org-demote 'org-promote))
6233 (org-odd-levels-only nil)
6234 beg end newend)
6235 ;; Remove the forced level indicator
6236 (if force-level
6237 (delete-region (point-at-bol) (point)))
6238 ;; Paste
6239 (beginning-of-line 1)
6240 (unless for-yank (org-back-over-empty-lines))
6241 (setq beg (point))
6242 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6243 (insert-before-markers txt)
6244 (unless (string-match "\n\\'" txt) (insert "\n"))
6245 (setq newend (point))
6246 (org-reinstall-markers-in-region beg)
6247 (setq end (point))
6248 (goto-char beg)
6249 (skip-chars-forward " \t\n\r")
6250 (setq beg (point))
6251 (if (and (org-invisible-p) visp)
6252 (save-excursion (outline-show-heading)))
6253 ;; Shift if necessary
6254 (unless (= shift 0)
6255 (save-restriction
6256 (narrow-to-region beg end)
6257 (while (not (= shift 0))
6258 (org-map-region func (point-min) (point-max))
6259 (setq shift (+ delta shift)))
6260 (goto-char (point-min))
6261 (setq newend (point-max))))
6262 (when (or (interactive-p) for-yank)
6263 (message "Clipboard pasted as level %d subtree" new-level))
6264 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6265 kill-ring
6266 (eq org-subtree-clip (current-kill 0))
6267 org-subtree-clip-folded)
6268 ;; The tree was folded before it was killed/copied
6269 (hide-subtree))
6270 (and for-yank (goto-char newend))))
6272 (defun org-kill-is-subtree-p (&optional txt)
6273 "Check if the current kill is an outline subtree, or a set of trees.
6274 Returns nil if kill does not start with a headline, or if the first
6275 headline level is not the largest headline level in the tree.
6276 So this will actually accept several entries of equal levels as well,
6277 which is OK for `org-paste-subtree'.
6278 If optional TXT is given, check this string instead of the current kill."
6279 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6280 (start-level (and kill
6281 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6282 org-outline-regexp "\\)")
6283 kill)
6284 (- (match-end 2) (match-beginning 2) 1)))
6285 (re (concat "^" org-outline-regexp))
6286 (start (1+ (or (match-beginning 2) -1))))
6287 (if (not start-level)
6288 (progn
6289 nil) ;; does not even start with a heading
6290 (catch 'exit
6291 (while (setq start (string-match re kill (1+ start)))
6292 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6293 (throw 'exit nil)))
6294 t))))
6296 (defvar org-markers-to-move nil
6297 "Markers that should be moved with a cut-and-paste operation.
6298 Those markers are stored together with their positions relative to
6299 the start of the region.")
6301 (defun org-save-markers-in-region (beg end)
6302 "Check markers in region.
6303 If these markers are between BEG and END, record their position relative
6304 to BEG, so that after moving the block of text, we can put the markers back
6305 into place.
6306 This function gets called just before an entry or tree gets cut from the
6307 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6308 called immediately, to move the markers with the entries."
6309 (setq org-markers-to-move nil)
6310 (when (featurep 'org-clock)
6311 (org-clock-save-markers-for-cut-and-paste beg end))
6312 (when (featurep 'org-agenda)
6313 (org-agenda-save-markers-for-cut-and-paste beg end)))
6315 (defun org-check-and-save-marker (marker beg end)
6316 "Check if MARKER is between BEG and END.
6317 If yes, remember the marker and the distance to BEG."
6318 (when (and (marker-buffer marker)
6319 (equal (marker-buffer marker) (current-buffer)))
6320 (if (and (>= marker beg) (< marker end))
6321 (push (cons marker (- marker beg)) org-markers-to-move))))
6323 (defun org-reinstall-markers-in-region (beg)
6324 "Move all remembered markers to their position relative to BEG."
6325 (mapc (lambda (x)
6326 (move-marker (car x) (+ beg (cdr x))))
6327 org-markers-to-move)
6328 (setq org-markers-to-move nil))
6330 (defun org-narrow-to-subtree ()
6331 "Narrow buffer to the current subtree."
6332 (interactive)
6333 (save-excursion
6334 (save-match-data
6335 (narrow-to-region
6336 (progn (org-back-to-heading t) (point))
6337 (progn (org-end-of-subtree t) (point))))))
6339 (defun org-clone-subtree-with-time-shift (n &optional shift)
6340 "Clone the task (subtree) at point N times.
6341 The clones will be inserted as siblings.
6343 In interactive use, the user will be prompted for the number of clones
6344 to be produced, and for a time SHIFT, which may be a repeater as used
6345 in time stamps, for example `+3d'.
6347 When a valid repeater is given and the entry contains any time stamps,
6348 the clones will become a sequence in time, with time stamps in the
6349 subtree shifted for each clone produced. If SHIFT is nil or the
6350 empty string, time stamps will be left alone.
6352 If the original subtree did contain time stamps with a repeater,
6353 the following will happen:
6354 - the repeater will be removed in each clone
6355 - an additional clone will be produced, with the current, unshifted
6356 date(s) in the entry.
6357 - the original entry will be placed *after* all the clones, with
6358 repeater intact.
6359 - the start days in the repeater in the original entry will be shifted
6360 to past the last clone.
6361 I this way you can spell out a number of instances of a repeating task,
6362 and still retain the repeater to cover future instances of the task."
6363 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6364 (let (beg end template task
6365 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6366 (if (not (and (integerp n) (> n 0)))
6367 (error "Invalid number of replications %s" n))
6368 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6369 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6370 shift)))
6371 (error "Invalid shift specification %s" shift))
6372 (when doshift
6373 (setq shift-n (string-to-number (match-string 1 shift))
6374 shift-what (cdr (assoc (match-string 2 shift)
6375 '(("d" . day) ("w" . week)
6376 ("m" . month) ("y" . year))))))
6377 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6378 (setq nmin 1 nmax n)
6379 (org-back-to-heading t)
6380 (setq beg (point))
6381 (org-end-of-subtree t t)
6382 (setq end (point))
6383 (setq template (buffer-substring beg end))
6384 (when (and doshift
6385 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6386 (delete-region beg end)
6387 (setq end beg)
6388 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6389 (goto-char end)
6390 (loop for n from nmin to nmax do
6391 (if (not doshift)
6392 (setq task template)
6393 (with-temp-buffer
6394 (insert template)
6395 (org-mode)
6396 (goto-char (point-min))
6397 (while (re-search-forward org-ts-regexp-both nil t)
6398 (org-timestamp-change (* n shift-n) shift-what))
6399 (unless (= n n-no-remove)
6400 (goto-char (point-min))
6401 (while (re-search-forward org-ts-regexp nil t)
6402 (save-excursion
6403 (goto-char (match-beginning 0))
6404 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6405 (delete-region (match-beginning 1) (match-end 1))))))
6406 (setq task (buffer-string))))
6407 (insert task))
6408 (goto-char beg)))
6410 ;;; Outline Sorting
6412 (defun org-sort (with-case)
6413 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6414 Optional argument WITH-CASE means sort case-sensitively.
6415 With a double prefix argument, also remove duplicate entries."
6416 (interactive "P")
6417 (if (org-at-table-p)
6418 (org-call-with-arg 'org-table-sort-lines with-case)
6419 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6421 (defun org-sort-remove-invisible (s)
6422 (remove-text-properties 0 (length s) org-rm-props s)
6423 (while (string-match org-bracket-link-regexp s)
6424 (setq s (replace-match (if (match-end 2)
6425 (match-string 3 s)
6426 (match-string 1 s)) t t s)))
6429 (defvar org-priority-regexp) ; defined later in the file
6431 (defvar org-after-sorting-entries-or-items-hook nil
6432 "Hook that is run after a bunch of entries or items have been sorted.
6433 When children are sorted, the cursor is in the parent line when this
6434 hook gets called. When a region or a plain list is sorted, the cursor
6435 will be in the first entry of the sorted region/list.")
6437 (defun org-sort-entries-or-items
6438 (&optional with-case sorting-type getkey-func compare-func property)
6439 "Sort entries on a certain level of an outline tree, or plain list items.
6440 If there is an active region, the entries in the region are sorted.
6441 Else, if the cursor is before the first entry, sort the top-level items.
6442 Else, the children of the entry at point are sorted.
6443 If the cursor is at the first item in a plain list, the list items will be
6444 sorted.
6446 Sorting can be alphabetically, numerically, by date/time as given by
6447 a time stamp, by a property or by priority.
6449 The command prompts for the sorting type unless it has been given to the
6450 function through the SORTING-TYPE argument, which needs to a character,
6451 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6452 precise meaning of each character:
6454 n Numerically, by converting the beginning of the entry/item to a number.
6455 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6456 t By date/time, either the first active time stamp in the entry, or, if
6457 none exist, by the first inactive one.
6458 In items, only the first line will be chekced.
6459 s By the scheduled date/time.
6460 d By deadline date/time.
6461 c By creation time, which is assumed to be the first inactive time stamp
6462 at the beginning of a line.
6463 p By priority according to the cookie.
6464 r By the value of a property.
6466 Capital letters will reverse the sort order.
6468 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6469 called with point at the beginning of the record. It must return either
6470 a string or a number that should serve as the sorting key for that record.
6472 Comparing entries ignores case by default. However, with an optional argument
6473 WITH-CASE, the sorting considers case as well."
6474 (interactive "P")
6475 (let ((case-func (if with-case 'identity 'downcase))
6476 start beg end stars re re2
6477 txt what tmp plain-list-p)
6478 ;; Find beginning and end of region to sort
6479 (cond
6480 ((org-region-active-p)
6481 ;; we will sort the region
6482 (setq end (region-end)
6483 what "region")
6484 (goto-char (region-beginning))
6485 (if (not (org-on-heading-p)) (outline-next-heading))
6486 (setq start (point)))
6487 ((org-at-item-p)
6488 ;; we will sort this plain list
6489 (org-beginning-of-item-list) (setq start (point))
6490 (org-end-of-item-list) (setq end (point))
6491 (goto-char start)
6492 (setq plain-list-p t
6493 what "plain list"))
6494 ((or (org-on-heading-p)
6495 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6496 ;; we will sort the children of the current headline
6497 (org-back-to-heading)
6498 (setq start (point)
6499 end (progn (org-end-of-subtree t t)
6500 (org-back-over-empty-lines)
6501 (point))
6502 what "children")
6503 (goto-char start)
6504 (show-subtree)
6505 (outline-next-heading))
6507 ;; we will sort the top-level entries in this file
6508 (goto-char (point-min))
6509 (or (org-on-heading-p) (outline-next-heading))
6510 (setq start (point) end (point-max) what "top-level")
6511 (goto-char start)
6512 (show-all)))
6514 (setq beg (point))
6515 (if (>= beg end) (error "Nothing to sort"))
6517 (unless plain-list-p
6518 (looking-at "\\(\\*+\\)")
6519 (setq stars (match-string 1)
6520 re (concat "^" (regexp-quote stars) " +")
6521 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6522 txt (buffer-substring beg end))
6523 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6524 (if (and (not (equal stars "*")) (string-match re2 txt))
6525 (error "Region to sort contains a level above the first entry")))
6527 (unless sorting-type
6528 (message
6529 (if plain-list-p
6530 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6531 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
6532 [t]ime [s]cheduled [d]eadline [c]reated
6533 A/N/T/S/D/C/P/O/F means reversed:")
6534 what)
6535 (setq sorting-type (read-char-exclusive))
6537 (and (= (downcase sorting-type) ?f)
6538 (setq getkey-func
6539 (org-ido-completing-read "Sort using function: "
6540 obarray 'fboundp t nil nil))
6541 (setq getkey-func (intern getkey-func)))
6543 (and (= (downcase sorting-type) ?r)
6544 (setq property
6545 (org-ido-completing-read "Property: "
6546 (mapcar 'list (org-buffer-property-keys t))
6547 nil t))))
6549 (message "Sorting entries...")
6551 (save-restriction
6552 (narrow-to-region start end)
6554 (let ((dcst (downcase sorting-type))
6555 (case-fold-search nil)
6556 (now (current-time)))
6557 (sort-subr
6558 (/= dcst sorting-type)
6559 ;; This function moves to the beginning character of the "record" to
6560 ;; be sorted.
6561 (if plain-list-p
6562 (lambda nil
6563 (if (org-at-item-p) t (goto-char (point-max))))
6564 (lambda nil
6565 (if (re-search-forward re nil t)
6566 (goto-char (match-beginning 0))
6567 (goto-char (point-max)))))
6568 ;; This function moves to the last character of the "record" being
6569 ;; sorted.
6570 (if plain-list-p
6571 'org-end-of-item
6572 (lambda nil
6573 (save-match-data
6574 (condition-case nil
6575 (outline-forward-same-level 1)
6576 (error
6577 (goto-char (point-max)))))))
6579 ;; This function returns the value that gets sorted against.
6580 (if plain-list-p
6581 (lambda nil
6582 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6583 (cond
6584 ((= dcst ?n)
6585 (string-to-number (buffer-substring (match-end 0)
6586 (point-at-eol))))
6587 ((= dcst ?a)
6588 (buffer-substring (match-end 0) (point-at-eol)))
6589 ((= dcst ?t)
6590 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
6591 (re-search-forward org-ts-regexp-both
6592 (point-at-eol) t))
6593 (org-time-string-to-seconds (match-string 0))
6594 (time-to-seconds now)))
6595 ((= dcst ?f)
6596 (if getkey-func
6597 (progn
6598 (setq tmp (funcall getkey-func))
6599 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6600 tmp)
6601 (error "Invalid key function `%s'" getkey-func)))
6602 (t (error "Invalid sorting type `%c'" sorting-type)))))
6603 (lambda nil
6604 (cond
6605 ((= dcst ?n)
6606 (if (looking-at org-complex-heading-regexp)
6607 (string-to-number (match-string 4))
6608 nil))
6609 ((= dcst ?a)
6610 (if (looking-at org-complex-heading-regexp)
6611 (funcall case-func (match-string 4))
6612 nil))
6613 ((= dcst ?t)
6614 (let ((end (save-excursion (outline-next-heading) (point))))
6615 (if (or (re-search-forward org-ts-regexp end t)
6616 (re-search-forward org-ts-regexp-both end t))
6617 (org-time-string-to-seconds (match-string 0))
6618 (time-to-seconds now))))
6619 ((= dcst ?c)
6620 (let ((end (save-excursion (outline-next-heading) (point))))
6621 (if (re-search-forward
6622 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
6623 end t)
6624 (org-time-string-to-seconds (match-string 0))
6625 (time-to-seconds now))))
6626 ((= dcst ?s)
6627 (let ((end (save-excursion (outline-next-heading) (point))))
6628 (if (re-search-forward org-scheduled-time-regexp end t)
6629 (org-time-string-to-seconds (match-string 1))
6630 (time-to-seconds now))))
6631 ((= dcst ?d)
6632 (let ((end (save-excursion (outline-next-heading) (point))))
6633 (if (re-search-forward org-deadline-time-regexp end t)
6634 (org-time-string-to-seconds (match-string 1))
6635 (time-to-seconds now))))
6636 ((= dcst ?p)
6637 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6638 (string-to-char (match-string 2))
6639 org-default-priority))
6640 ((= dcst ?r)
6641 (or (org-entry-get nil property) ""))
6642 ((= dcst ?o)
6643 (if (looking-at org-complex-heading-regexp)
6644 (- 9999 (length (member (match-string 2)
6645 org-todo-keywords-1)))))
6646 ((= dcst ?f)
6647 (if getkey-func
6648 (progn
6649 (setq tmp (funcall getkey-func))
6650 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6651 tmp)
6652 (error "Invalid key function `%s'" getkey-func)))
6653 (t (error "Invalid sorting type `%c'" sorting-type)))))
6655 (cond
6656 ((= dcst ?a) 'string<)
6657 ((= dcst ?f) compare-func)
6658 ((member dcst '(?p ?t ?s ?d ?c)) '<)
6659 (t nil)))))
6660 (run-hooks 'org-after-sorting-entries-or-items-hook)
6661 (message "Sorting entries...done")))
6663 (defun org-do-sort (table what &optional with-case sorting-type)
6664 "Sort TABLE of WHAT according to SORTING-TYPE.
6665 The user will be prompted for the SORTING-TYPE if the call to this
6666 function does not specify it. WHAT is only for the prompt, to indicate
6667 what is being sorted. The sorting key will be extracted from
6668 the car of the elements of the table.
6669 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6670 (unless sorting-type
6671 (message
6672 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6673 what)
6674 (setq sorting-type (read-char-exclusive)))
6675 (let ((dcst (downcase sorting-type))
6676 extractfun comparefun)
6677 ;; Define the appropriate functions
6678 (cond
6679 ((= dcst ?n)
6680 (setq extractfun 'string-to-number
6681 comparefun (if (= dcst sorting-type) '< '>)))
6682 ((= dcst ?a)
6683 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6684 (lambda(x) (downcase (org-sort-remove-invisible x))))
6685 comparefun (if (= dcst sorting-type)
6686 'string<
6687 (lambda (a b) (and (not (string< a b))
6688 (not (string= a b)))))))
6689 ((= dcst ?t)
6690 (setq extractfun
6691 (lambda (x)
6692 (if (or (string-match org-ts-regexp x)
6693 (string-match org-ts-regexp-both x))
6694 (time-to-seconds
6695 (org-time-string-to-time (match-string 0 x)))
6697 comparefun (if (= dcst sorting-type) '< '>)))
6698 (t (error "Invalid sorting type `%c'" sorting-type)))
6700 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6701 table)
6702 (lambda (a b) (funcall comparefun (car a) (car b))))))
6705 ;;; The orgstruct minor mode
6707 ;; Define a minor mode which can be used in other modes in order to
6708 ;; integrate the org-mode structure editing commands.
6710 ;; This is really a hack, because the org-mode structure commands use
6711 ;; keys which normally belong to the major mode. Here is how it
6712 ;; works: The minor mode defines all the keys necessary to operate the
6713 ;; structure commands, but wraps the commands into a function which
6714 ;; tests if the cursor is currently at a headline or a plain list
6715 ;; item. If that is the case, the structure command is used,
6716 ;; temporarily setting many Org-mode variables like regular
6717 ;; expressions for filling etc. However, when any of those keys is
6718 ;; used at a different location, function uses `key-binding' to look
6719 ;; up if the key has an associated command in another currently active
6720 ;; keymap (minor modes, major mode, global), and executes that
6721 ;; command. There might be problems if any of the keys is otherwise
6722 ;; used as a prefix key.
6724 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6725 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6726 ;; addresses this by checking explicitly for both bindings.
6728 (defvar orgstruct-mode-map (make-sparse-keymap)
6729 "Keymap for the minor `orgstruct-mode'.")
6731 (defvar org-local-vars nil
6732 "List of local variables, for use by `orgstruct-mode'")
6734 ;;;###autoload
6735 (define-minor-mode orgstruct-mode
6736 "Toggle the minor more `orgstruct-mode'.
6737 This mode is for using Org-mode structure commands in other modes.
6738 The following key behave as if Org-mode was active, if the cursor
6739 is on a headline, or on a plain list item (both in the definition
6740 of Org-mode).
6742 M-up Move entry/item up
6743 M-down Move entry/item down
6744 M-left Promote
6745 M-right Demote
6746 M-S-up Move entry/item up
6747 M-S-down Move entry/item down
6748 M-S-left Promote subtree
6749 M-S-right Demote subtree
6750 M-q Fill paragraph and items like in Org-mode
6751 C-c ^ Sort entries
6752 C-c - Cycle list bullet
6753 TAB Cycle item visibility
6754 M-RET Insert new heading/item
6755 S-M-RET Insert new TODO heading / Checkbox item
6756 C-c C-c Set tags / toggle checkbox"
6757 nil " OrgStruct" nil
6758 (org-load-modules-maybe)
6759 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6761 ;;;###autoload
6762 (defun turn-on-orgstruct ()
6763 "Unconditionally turn on `orgstruct-mode'."
6764 (orgstruct-mode 1))
6766 (defun orgstruct++-mode (&optional arg)
6767 "Toggle `orgstruct-mode', the enhanced version of it.
6768 In addition to setting orgstruct-mode, this also exports all indentation
6769 and autofilling variables from org-mode into the buffer. It will also
6770 recognize item context in multiline items.
6771 Note that turning off orgstruct-mode will *not* remove the
6772 indentation/paragraph settings. This can only be done by refreshing the
6773 major mode, for example with \\[normal-mode]."
6774 (interactive "P")
6775 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6776 (if (< arg 1)
6777 (orgstruct-mode -1)
6778 (orgstruct-mode 1)
6779 (let (var val)
6780 (mapc
6781 (lambda (x)
6782 (when (string-match
6783 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6784 (symbol-name (car x)))
6785 (setq var (car x) val (nth 1 x))
6786 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6787 org-local-vars)
6788 (org-set-local 'orgstruct-is-++ t))))
6790 (defvar orgstruct-is-++ nil
6791 "Is orgstruct-mode in ++ version in the current-buffer?")
6792 (make-variable-buffer-local 'orgstruct-is-++)
6794 ;;;###autoload
6795 (defun turn-on-orgstruct++ ()
6796 "Unconditionally turn on `orgstruct++-mode'."
6797 (orgstruct++-mode 1))
6799 (defun orgstruct-error ()
6800 "Error when there is no default binding for a structure key."
6801 (interactive)
6802 (error "This key has no function outside structure elements"))
6804 (defun orgstruct-setup ()
6805 "Setup orgstruct keymaps."
6806 (let ((nfunc 0)
6807 (bindings
6808 (list
6809 '([(meta up)] org-metaup)
6810 '([(meta down)] org-metadown)
6811 '([(meta left)] org-metaleft)
6812 '([(meta right)] org-metaright)
6813 '([(meta shift up)] org-shiftmetaup)
6814 '([(meta shift down)] org-shiftmetadown)
6815 '([(meta shift left)] org-shiftmetaleft)
6816 '([(meta shift right)] org-shiftmetaright)
6817 '([?\e (up)] org-metaup)
6818 '([?\e (down)] org-metadown)
6819 '([?\e (left)] org-metaleft)
6820 '([?\e (right)] org-metaright)
6821 '([?\e (shift up)] org-shiftmetaup)
6822 '([?\e (shift down)] org-shiftmetadown)
6823 '([?\e (shift left)] org-shiftmetaleft)
6824 '([?\e (shift right)] org-shiftmetaright)
6825 '([(shift up)] org-shiftup)
6826 '([(shift down)] org-shiftdown)
6827 '([(shift left)] org-shiftleft)
6828 '([(shift right)] org-shiftright)
6829 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6830 '("\M-q" fill-paragraph)
6831 '("\C-c^" org-sort)
6832 '("\C-c-" org-cycle-list-bullet)))
6833 elt key fun cmd)
6834 (while (setq elt (pop bindings))
6835 (setq nfunc (1+ nfunc))
6836 (setq key (org-key (car elt))
6837 fun (nth 1 elt)
6838 cmd (orgstruct-make-binding fun nfunc key))
6839 (org-defkey orgstruct-mode-map key cmd))
6841 ;; Special treatment needed for TAB and RET
6842 (org-defkey orgstruct-mode-map [(tab)]
6843 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6844 (org-defkey orgstruct-mode-map "\C-i"
6845 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6847 (org-defkey orgstruct-mode-map "\M-\C-m"
6848 (orgstruct-make-binding 'org-insert-heading 105
6849 "\M-\C-m" [(meta return)]))
6850 (org-defkey orgstruct-mode-map [(meta return)]
6851 (orgstruct-make-binding 'org-insert-heading 106
6852 [(meta return)] "\M-\C-m"))
6854 (org-defkey orgstruct-mode-map [(shift meta return)]
6855 (orgstruct-make-binding 'org-insert-todo-heading 107
6856 [(meta return)] "\M-\C-m"))
6858 (org-defkey orgstruct-mode-map "\e\C-m"
6859 (orgstruct-make-binding 'org-insert-heading 108
6860 "\e\C-m" [?\e (return)]))
6861 (org-defkey orgstruct-mode-map [?\e (return)]
6862 (orgstruct-make-binding 'org-insert-heading 109
6863 [?\e (return)] "\e\C-m"))
6864 (org-defkey orgstruct-mode-map [?\e (shift return)]
6865 (orgstruct-make-binding 'org-insert-todo-heading 110
6866 [?\e (return)] "\e\C-m"))
6868 (unless org-local-vars
6869 (setq org-local-vars (org-get-local-variables)))
6873 (defun orgstruct-make-binding (fun n &rest keys)
6874 "Create a function for binding in the structure minor mode.
6875 FUN is the command to call inside a table. N is used to create a unique
6876 command name. KEYS are keys that should be checked in for a command
6877 to execute outside of tables."
6878 (eval
6879 (list 'defun
6880 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6881 '(arg)
6882 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6883 "Outside of structure, run the binding of `"
6884 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6885 "'.")
6886 '(interactive "p")
6887 (list 'if
6888 `(org-context-p 'headline 'item
6889 (and orgstruct-is-++
6890 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
6891 'item-body))
6892 (list 'org-run-like-in-org-mode (list 'quote fun))
6893 (list 'let '(orgstruct-mode)
6894 (list 'call-interactively
6895 (append '(or)
6896 (mapcar (lambda (k)
6897 (list 'key-binding k))
6898 keys)
6899 '('orgstruct-error))))))))
6901 (defun org-context-p (&rest contexts)
6902 "Check if local context is any of CONTEXTS.
6903 Possible values in the list of contexts are `table', `headline', and `item'."
6904 (let ((pos (point)))
6905 (goto-char (point-at-bol))
6906 (prog1 (or (and (memq 'table contexts)
6907 (looking-at "[ \t]*|"))
6908 (and (memq 'headline contexts)
6909 ;;????????? (looking-at "\\*+"))
6910 (looking-at outline-regexp))
6911 (and (memq 'item contexts)
6912 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
6913 (and (memq 'item-body contexts)
6914 (org-in-item-p)))
6915 (goto-char pos))))
6917 (defun org-get-local-variables ()
6918 "Return a list of all local variables in an org-mode buffer."
6919 (let (varlist)
6920 (with-current-buffer (get-buffer-create "*Org tmp*")
6921 (erase-buffer)
6922 (org-mode)
6923 (setq varlist (buffer-local-variables)))
6924 (kill-buffer "*Org tmp*")
6925 (delq nil
6926 (mapcar
6927 (lambda (x)
6928 (setq x
6929 (if (symbolp x)
6930 (list x)
6931 (list (car x) (list 'quote (cdr x)))))
6932 (if (string-match
6933 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6934 (symbol-name (car x)))
6935 x nil))
6936 varlist))))
6938 ;;;###autoload
6939 (defun org-run-like-in-org-mode (cmd)
6940 "Run a command, pretending that the current buffer is in Org-mode.
6941 This will temporarily bind local variables that are typically bound in
6942 Org-mode to the values they have in Org-mode, and then interactively
6943 call CMD."
6944 (org-load-modules-maybe)
6945 (unless org-local-vars
6946 (setq org-local-vars (org-get-local-variables)))
6947 (eval (list 'let org-local-vars
6948 (list 'call-interactively (list 'quote cmd)))))
6950 ;;;; Archiving
6952 (defun org-get-category (&optional pos)
6953 "Get the category applying to position POS."
6954 (get-text-property (or pos (point)) 'org-category))
6956 (defun org-refresh-category-properties ()
6957 "Refresh category text properties in the buffer."
6958 (let ((def-cat (cond
6959 ((null org-category)
6960 (if buffer-file-name
6961 (file-name-sans-extension
6962 (file-name-nondirectory buffer-file-name))
6963 "???"))
6964 ((symbolp org-category) (symbol-name org-category))
6965 (t org-category)))
6966 beg end cat pos optionp)
6967 (org-unmodified
6968 (save-excursion
6969 (save-restriction
6970 (widen)
6971 (goto-char (point-min))
6972 (put-text-property (point) (point-max) 'org-category def-cat)
6973 (while (re-search-forward
6974 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6975 (setq pos (match-end 0)
6976 optionp (equal (char-after (match-beginning 0)) ?#)
6977 cat (org-trim (match-string 2)))
6978 (if optionp
6979 (setq beg (point-at-bol) end (point-max))
6980 (org-back-to-heading t)
6981 (setq beg (point) end (org-end-of-subtree t t)))
6982 (put-text-property beg end 'org-category cat)
6983 (goto-char pos)))))))
6986 ;;;; Link Stuff
6988 ;;; Link abbreviations
6990 (defun org-link-expand-abbrev (link)
6991 "Apply replacements as defined in `org-link-abbrev-alist."
6992 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6993 (let* ((key (match-string 1 link))
6994 (as (or (assoc key org-link-abbrev-alist-local)
6995 (assoc key org-link-abbrev-alist)))
6996 (tag (and (match-end 2) (match-string 3 link)))
6997 rpl)
6998 (if (not as)
6999 link
7000 (setq rpl (cdr as))
7001 (cond
7002 ((symbolp rpl) (funcall rpl tag))
7003 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7004 ((string-match "%h" rpl)
7005 (replace-match (url-hexify-string (or tag "")) t t rpl))
7006 (t (concat rpl tag)))))
7007 link))
7009 ;;; Storing and inserting links
7011 (defvar org-insert-link-history nil
7012 "Minibuffer history for links inserted with `org-insert-link'.")
7014 (defvar org-stored-links nil
7015 "Contains the links stored with `org-store-link'.")
7017 (defvar org-store-link-plist nil
7018 "Plist with info about the most recently link created with `org-store-link'.")
7020 (defvar org-link-protocols nil
7021 "Link protocols added to Org-mode using `org-add-link-type'.")
7023 (defvar org-store-link-functions nil
7024 "List of functions that are called to create and store a link.
7025 Each function will be called in turn until one returns a non-nil
7026 value. Each function should check if it is responsible for creating
7027 this link (for example by looking at the major mode).
7028 If not, it must exit and return nil.
7029 If yes, it should return a non-nil value after a calling
7030 `org-store-link-props' with a list of properties and values.
7031 Special properties are:
7033 :type The link prefix. like \"http\". This must be given.
7034 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7035 This is obligatory as well.
7036 :description Optional default description for the second pair
7037 of brackets in an Org-mode link. The user can still change
7038 this when inserting this link into an Org-mode buffer.
7040 In addition to these, any additional properties can be specified
7041 and then used in remember templates.")
7043 (defun org-add-link-type (type &optional follow export)
7044 "Add TYPE to the list of `org-link-types'.
7045 Re-compute all regular expressions depending on `org-link-types'
7047 FOLLOW and EXPORT are two functions.
7049 FOLLOW should take the link path as the single argument and do whatever
7050 is necessary to follow the link, for example find a file or display
7051 a mail message.
7053 EXPORT should format the link path for export to one of the export formats.
7054 It should be a function accepting three arguments:
7056 path the path of the link, the text after the prefix (like \"http:\")
7057 desc the description of the link, if any, nil if there was no description
7058 format the export format, a symbol like `html' or `latex'.
7060 The function may use the FORMAT information to return different values
7061 depending on the format. The return value will be put literally into
7062 the exported file.
7063 Org-mode has a built-in default for exporting links. If you are happy with
7064 this default, there is no need to define an export function for the link
7065 type. For a simple example of an export function, see `org-bbdb.el'."
7066 (add-to-list 'org-link-types type t)
7067 (org-make-link-regexps)
7068 (if (assoc type org-link-protocols)
7069 (setcdr (assoc type org-link-protocols) (list follow export))
7070 (push (list type follow export) org-link-protocols)))
7072 ;;;###autoload
7073 (defun org-store-link (arg)
7074 "\\<org-mode-map>Store an org-link to the current location.
7075 This link is added to `org-stored-links' and can later be inserted
7076 into an org-buffer with \\[org-insert-link].
7078 For some link types, a prefix arg is interpreted:
7079 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7080 For file links, arg negates `org-context-in-file-links'."
7081 (interactive "P")
7082 (org-load-modules-maybe)
7083 (setq org-store-link-plist nil) ; reset
7084 (let ((outline-regexp (org-get-limited-outline-regexp))
7085 link cpltxt desc description search txt custom-id)
7086 (cond
7088 ((run-hook-with-args-until-success 'org-store-link-functions)
7089 (setq link (plist-get org-store-link-plist :link)
7090 desc (or (plist-get org-store-link-plist :description) link)))
7092 ((equal (buffer-name) "*Org Edit Src Example*")
7093 (let (label gc)
7094 (while (or (not label)
7095 (save-excursion
7096 (save-restriction
7097 (widen)
7098 (goto-char (point-min))
7099 (re-search-forward
7100 (regexp-quote (format org-coderef-label-format label))
7101 nil t))))
7102 (when label (message "Label exists already") (sit-for 2))
7103 (setq label (read-string "Code line label: " label)))
7104 (end-of-line 1)
7105 (setq link (format org-coderef-label-format label))
7106 (setq gc (- 79 (length link)))
7107 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7108 (insert link)
7109 (setq link (concat "(" label ")") desc nil)))
7111 ((eq major-mode 'calendar-mode)
7112 (let ((cd (calendar-cursor-to-date)))
7113 (setq link
7114 (format-time-string
7115 (car org-time-stamp-formats)
7116 (apply 'encode-time
7117 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7118 nil nil nil))))
7119 (org-store-link-props :type "calendar" :date cd)))
7121 ((eq major-mode 'w3-mode)
7122 (setq cpltxt (if (and (buffer-name)
7123 (not (string-match "Untitled" (buffer-name))))
7124 (buffer-name)
7125 (url-view-url t))
7126 link (org-make-link (url-view-url t)))
7127 (org-store-link-props :type "w3" :url (url-view-url t)))
7129 ((eq major-mode 'w3m-mode)
7130 (setq cpltxt (or w3m-current-title w3m-current-url)
7131 link (org-make-link w3m-current-url))
7132 (org-store-link-props :type "w3m" :url (url-view-url t)))
7134 ((setq search (run-hook-with-args-until-success
7135 'org-create-file-search-functions))
7136 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7137 "::" search))
7138 (setq cpltxt (or description link)))
7140 ((eq major-mode 'image-mode)
7141 (setq cpltxt (concat "file:"
7142 (abbreviate-file-name buffer-file-name))
7143 link (org-make-link cpltxt))
7144 (org-store-link-props :type "image" :file buffer-file-name))
7146 ((eq major-mode 'dired-mode)
7147 ;; link to the file in the current line
7148 (setq cpltxt (concat "file:"
7149 (abbreviate-file-name
7150 (expand-file-name
7151 (dired-get-filename nil t))))
7152 link (org-make-link cpltxt)))
7154 ((and buffer-file-name (org-mode-p))
7155 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7156 (cond
7157 ((org-in-regexp "<<\\(.*?\\)>>")
7158 (setq cpltxt
7159 (concat "file:"
7160 (abbreviate-file-name buffer-file-name)
7161 "::" (match-string 1))
7162 link (org-make-link cpltxt)))
7163 ((and (featurep 'org-id)
7164 (or (eq org-link-to-org-use-id t)
7165 (and (eq org-link-to-org-use-id 'create-if-interactive)
7166 (interactive-p))
7167 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7168 (interactive-p)
7169 (not custom-id))
7170 (and org-link-to-org-use-id
7171 (condition-case nil
7172 (org-entry-get nil "ID")
7173 (error nil)))))
7174 ;; We can make a link using the ID.
7175 (setq link (condition-case nil
7176 (prog1 (org-id-store-link)
7177 (setq desc (plist-get org-store-link-plist
7178 :description)))
7179 (error
7180 ;; probably before first headline, link to file only
7181 (concat "file:"
7182 (abbreviate-file-name buffer-file-name))))))
7184 ;; Just link to current headline
7185 (setq cpltxt (concat "file:"
7186 (abbreviate-file-name buffer-file-name)))
7187 ;; Add a context search string
7188 (when (org-xor org-context-in-file-links arg)
7189 (setq txt (cond
7190 ((org-on-heading-p) nil)
7191 ((org-region-active-p)
7192 (buffer-substring (region-beginning) (region-end)))
7193 (t nil)))
7194 (when (or (null txt) (string-match "\\S-" txt))
7195 (setq cpltxt
7196 (concat cpltxt "::"
7197 (condition-case nil
7198 (org-make-org-heading-search-string txt)
7199 (error "")))
7200 desc (or (nth 4 (org-heading-components)) "NONE"))))
7201 (if (string-match "::\\'" cpltxt)
7202 (setq cpltxt (substring cpltxt 0 -2)))
7203 (setq link (org-make-link cpltxt)))))
7205 ((buffer-file-name (buffer-base-buffer))
7206 ;; Just link to this file here.
7207 (setq cpltxt (concat "file:"
7208 (abbreviate-file-name
7209 (buffer-file-name (buffer-base-buffer)))))
7210 ;; Add a context string
7211 (when (org-xor org-context-in-file-links arg)
7212 (setq txt (if (org-region-active-p)
7213 (buffer-substring (region-beginning) (region-end))
7214 (buffer-substring (point-at-bol) (point-at-eol))))
7215 ;; Only use search option if there is some text.
7216 (when (string-match "\\S-" txt)
7217 (setq cpltxt
7218 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7219 desc "NONE")))
7220 (setq link (org-make-link cpltxt)))
7222 ((interactive-p)
7223 (error "Cannot link to a buffer which is not visiting a file"))
7225 (t (setq link nil)))
7227 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7228 (setq link (or link cpltxt)
7229 desc (or desc cpltxt))
7230 (if (equal desc "NONE") (setq desc nil))
7232 (if (and (or (interactive-p) executing-kbd-macro) link)
7233 (progn
7234 (setq org-stored-links
7235 (cons (list link desc) org-stored-links))
7236 (message "Stored: %s" (or desc link))
7237 (when custom-id
7238 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7239 "::#" custom-id))
7240 (setq org-stored-links
7241 (cons (list link desc) org-stored-links))))
7242 (and link (org-make-link-string link desc)))))
7244 (defun org-store-link-props (&rest plist)
7245 "Store link properties, extract names and addresses."
7246 (let (x adr)
7247 (when (setq x (plist-get plist :from))
7248 (setq adr (mail-extract-address-components x))
7249 (setq plist (plist-put plist :fromname (car adr)))
7250 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7251 (when (setq x (plist-get plist :to))
7252 (setq adr (mail-extract-address-components x))
7253 (setq plist (plist-put plist :toname (car adr)))
7254 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7255 (let ((from (plist-get plist :from))
7256 (to (plist-get plist :to)))
7257 (when (and from to org-from-is-user-regexp)
7258 (setq plist
7259 (plist-put plist :fromto
7260 (if (string-match org-from-is-user-regexp from)
7261 (concat "to %t")
7262 (concat "from %f"))))))
7263 (setq org-store-link-plist plist))
7265 (defun org-add-link-props (&rest plist)
7266 "Add these properties to the link property list."
7267 (let (key value)
7268 (while plist
7269 (setq key (pop plist) value (pop plist))
7270 (setq org-store-link-plist
7271 (plist-put org-store-link-plist key value)))))
7273 (defun org-email-link-description (&optional fmt)
7274 "Return the description part of an email link.
7275 This takes information from `org-store-link-plist' and formats it
7276 according to FMT (default from `org-email-link-description-format')."
7277 (setq fmt (or fmt org-email-link-description-format))
7278 (let* ((p org-store-link-plist)
7279 (to (plist-get p :toaddress))
7280 (from (plist-get p :fromaddress))
7281 (table
7282 (list
7283 (cons "%c" (plist-get p :fromto))
7284 (cons "%F" (plist-get p :from))
7285 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7286 (cons "%T" (plist-get p :to))
7287 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7288 (cons "%s" (plist-get p :subject))
7289 (cons "%m" (plist-get p :message-id)))))
7290 (when (string-match "%c" fmt)
7291 ;; Check if the user wrote this message
7292 (if (and org-from-is-user-regexp from to
7293 (save-match-data (string-match org-from-is-user-regexp from)))
7294 (setq fmt (replace-match "to %t" t t fmt))
7295 (setq fmt (replace-match "from %f" t t fmt))))
7296 (org-replace-escapes fmt table)))
7298 (defun org-make-org-heading-search-string (&optional string heading)
7299 "Make search string for STRING or current headline."
7300 (interactive)
7301 (let ((s (or string (org-get-heading))))
7302 (unless (and string (not heading))
7303 ;; We are using a headline, clean up garbage in there.
7304 (if (string-match org-todo-regexp s)
7305 (setq s (replace-match "" t t s)))
7306 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7307 (setq s (replace-match "" t t s)))
7308 (setq s (org-trim s))
7309 (if (string-match (concat "^\\(" org-quote-string "\\|"
7310 org-comment-string "\\)") s)
7311 (setq s (replace-match "" t t s)))
7312 (while (string-match org-ts-regexp s)
7313 (setq s (replace-match "" t t s))))
7314 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7315 (setq s (replace-match " " t t s)))
7316 (or string (setq s (concat "*" s))) ; Add * for headlines
7317 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7319 (defun org-make-link (&rest strings)
7320 "Concatenate STRINGS."
7321 (apply 'concat strings))
7323 (defun org-make-link-string (link &optional description)
7324 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7325 (unless (string-match "\\S-" link)
7326 (error "Empty link"))
7327 (when (stringp description)
7328 ;; Remove brackets from the description, they are fatal.
7329 (while (string-match "\\[" description)
7330 (setq description (replace-match "{" t t description)))
7331 (while (string-match "\\]" description)
7332 (setq description (replace-match "}" t t description))))
7333 (when (equal (org-link-escape link) description)
7334 ;; No description needed, it is identical
7335 (setq description nil))
7336 (when (and (not description)
7337 (not (equal link (org-link-escape link))))
7338 (setq description (org-extract-attributes link)))
7339 (concat "[[" (org-link-escape link) "]"
7340 (if description (concat "[" description "]") "")
7341 "]"))
7343 (defconst org-link-escape-chars
7344 '((?\ . "%20")
7345 (?\[ . "%5B")
7346 (?\] . "%5D")
7347 (?\340 . "%E0") ; `a
7348 (?\342 . "%E2") ; ^a
7349 (?\347 . "%E7") ; ,c
7350 (?\350 . "%E8") ; `e
7351 (?\351 . "%E9") ; 'e
7352 (?\352 . "%EA") ; ^e
7353 (?\356 . "%EE") ; ^i
7354 (?\364 . "%F4") ; ^o
7355 (?\371 . "%F9") ; `u
7356 (?\373 . "%FB") ; ^u
7357 (?\; . "%3B")
7358 (?? . "%3F")
7359 (?= . "%3D")
7360 (?+ . "%2B")
7362 "Association list of escapes for some characters problematic in links.
7363 This is the list that is used for internal purposes.")
7365 (defvar org-url-encoding-use-url-hexify nil)
7367 (defconst org-link-escape-chars-browser
7368 '((?\ . "%20")) ; 32 for the SPC char
7369 "Association list of escapes for some characters problematic in links.
7370 This is the list that is used before handing over to the browser.")
7372 (defun org-link-escape (text &optional table)
7373 "Escape characters in TEXT that are problematic for links."
7374 (if org-url-encoding-use-url-hexify
7375 (url-hexify-string text)
7376 (setq table (or table org-link-escape-chars))
7377 (when text
7378 (let ((re (mapconcat (lambda (x) (regexp-quote
7379 (char-to-string (car x))))
7380 table "\\|")))
7381 (while (string-match re text)
7382 (setq text
7383 (replace-match
7384 (cdr (assoc (string-to-char (match-string 0 text))
7385 table))
7386 t t text)))
7387 text))))
7389 (defun org-link-unescape (text &optional table)
7390 "Reverse the action of `org-link-escape'."
7391 (if org-url-encoding-use-url-hexify
7392 (url-unhex-string text)
7393 (setq table (or table org-link-escape-chars))
7394 (when text
7395 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7396 table "\\|")))
7397 (while (string-match re text)
7398 (setq text
7399 (replace-match
7400 (char-to-string (car (rassoc (match-string 0 text) table)))
7401 t t text)))
7402 text))))
7404 (defun org-xor (a b)
7405 "Exclusive or."
7406 (if a (not b) b))
7408 (defun org-fixup-message-id-for-http (s)
7409 "Replace special characters in a message id, so it can be used in an http query."
7410 (while (string-match "<" s)
7411 (setq s (replace-match "%3C" t t s)))
7412 (while (string-match ">" s)
7413 (setq s (replace-match "%3E" t t s)))
7414 (while (string-match "@" s)
7415 (setq s (replace-match "%40" t t s)))
7418 ;;;###autoload
7419 (defun org-insert-link-global ()
7420 "Insert a link like Org-mode does.
7421 This command can be called in any mode to insert a link in Org-mode syntax."
7422 (interactive)
7423 (org-load-modules-maybe)
7424 (org-run-like-in-org-mode 'org-insert-link))
7426 (defun org-insert-link (&optional complete-file link-location)
7427 "Insert a link. At the prompt, enter the link.
7429 Completion can be used to insert any of the link protocol prefixes like
7430 http or ftp in use.
7432 The history can be used to select a link previously stored with
7433 `org-store-link'. When the empty string is entered (i.e. if you just
7434 press RET at the prompt), the link defaults to the most recently
7435 stored link. As SPC triggers completion in the minibuffer, you need to
7436 use M-SPC or C-q SPC to force the insertion of a space character.
7438 You will also be prompted for a description, and if one is given, it will
7439 be displayed in the buffer instead of the link.
7441 If there is already a link at point, this command will allow you to edit link
7442 and description parts.
7444 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7445 be selected using completion. The path to the file will be relative to the
7446 current directory if the file is in the current directory or a subdirectory.
7447 Otherwise, the link will be the absolute path as completed in the minibuffer
7448 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7449 option `org-link-file-path-type'.
7451 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7452 the current directory or below.
7454 With three \\[universal-argument] prefixes, negate the meaning of
7455 `org-keep-stored-link-after-insertion'.
7457 If `org-make-link-description-function' is non-nil, this function will be
7458 called with the link target, and the result will be the default
7459 link description.
7461 If the LINK-LOCATION parameter is non-nil, this value will be
7462 used as the link location instead of reading one interactively."
7463 (interactive "P")
7464 (let* ((wcf (current-window-configuration))
7465 (region (if (org-region-active-p)
7466 (buffer-substring (region-beginning) (region-end))))
7467 (remove (and region (list (region-beginning) (region-end))))
7468 (desc region)
7469 tmphist ; byte-compile incorrectly complains about this
7470 (link link-location)
7471 entry file all-prefixes)
7472 (cond
7473 (link-location) ; specified by arg, just use it.
7474 ((org-in-regexp org-bracket-link-regexp 1)
7475 ;; We do have a link at point, and we are going to edit it.
7476 (setq remove (list (match-beginning 0) (match-end 0)))
7477 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7478 (setq link (read-string "Link: "
7479 (org-link-unescape
7480 (org-match-string-no-properties 1)))))
7481 ((or (org-in-regexp org-angle-link-re)
7482 (org-in-regexp org-plain-link-re))
7483 ;; Convert to bracket link
7484 (setq remove (list (match-beginning 0) (match-end 0))
7485 link (read-string "Link: "
7486 (org-remove-angle-brackets (match-string 0)))))
7487 ((member complete-file '((4) (16)))
7488 ;; Completing read for file names.
7489 (setq link (org-file-complete-link complete-file)))
7491 ;; Read link, with completion for stored links.
7492 (with-output-to-temp-buffer "*Org Links*"
7493 (princ "Insert a link.
7494 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
7495 (when org-stored-links
7496 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7497 (princ (mapconcat
7498 (lambda (x)
7499 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7500 (reverse org-stored-links) "\n"))))
7501 (let ((cw (selected-window)))
7502 (select-window (get-buffer-window "*Org Links*"))
7503 (setq truncate-lines t)
7504 (unless (pos-visible-in-window-p (point-max))
7505 (org-fit-window-to-buffer))
7506 (and (window-live-p cw) (select-window cw)))
7507 ;; Fake a link history, containing the stored links.
7508 (setq tmphist (append (mapcar 'car org-stored-links)
7509 org-insert-link-history))
7510 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
7511 (mapcar 'car org-link-abbrev-alist)
7512 org-link-types))
7513 (unwind-protect
7514 (progn
7515 (setq link
7516 (let ((org-completion-use-ido nil))
7517 (org-completing-read
7518 "Link: "
7519 (append
7520 (mapcar (lambda (x) (list (concat x ":")))
7521 all-prefixes)
7522 (mapcar 'car org-stored-links))
7523 nil nil nil
7524 'tmphist
7525 (car (car org-stored-links)))))
7526 (if (or (member link all-prefixes)
7527 (and (equal ":" (substring link -1))
7528 (member (substring link 0 -1) all-prefixes)
7529 (setq link (substring link 0 -1))))
7530 (setq link (org-link-try-special-completion link))))
7531 (set-window-configuration wcf)
7532 (kill-buffer "*Org Links*"))
7533 (setq entry (assoc link org-stored-links))
7534 (or entry (push link org-insert-link-history))
7535 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7536 (not org-keep-stored-link-after-insertion))
7537 (setq org-stored-links (delq (assoc link org-stored-links)
7538 org-stored-links)))
7539 (setq desc (or desc (nth 1 entry)))))
7541 (if (string-match org-plain-link-re link)
7542 ;; URL-like link, normalize the use of angular brackets.
7543 (setq link (org-make-link (org-remove-angle-brackets link))))
7545 ;; Check if we are linking to the current file with a search option
7546 ;; If yes, simplify the link by using only the search option.
7547 (when (and buffer-file-name
7548 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7549 (let* ((path (match-string 1 link))
7550 (case-fold-search nil)
7551 (search (match-string 2 link)))
7552 (save-match-data
7553 (if (equal (file-truename buffer-file-name) (file-truename path))
7554 ;; We are linking to this same file, with a search option
7555 (setq link search)))))
7557 ;; Check if we can/should use a relative path. If yes, simplify the link
7558 (when (string-match "^file:\\(.*\\)" link)
7559 (let* ((path (match-string 1 link))
7560 (origpath path)
7561 (case-fold-search nil))
7562 (cond
7563 ((or (eq org-link-file-path-type 'absolute)
7564 (equal complete-file '(16)))
7565 (setq path (abbreviate-file-name (expand-file-name path))))
7566 ((eq org-link-file-path-type 'noabbrev)
7567 (setq path (expand-file-name path)))
7568 ((eq org-link-file-path-type 'relative)
7569 (setq path (file-relative-name path)))
7571 (save-match-data
7572 (if (string-match (concat "^" (regexp-quote
7573 (file-name-as-directory
7574 (expand-file-name "."))))
7575 (expand-file-name path))
7576 ;; We are linking a file with relative path name.
7577 (setq path (substring (expand-file-name path)
7578 (match-end 0)))
7579 (setq path (abbreviate-file-name (expand-file-name path)))))))
7580 (setq link (concat "file:" path))
7581 (if (equal desc origpath)
7582 (setq desc path))))
7584 (if org-make-link-description-function
7585 (setq desc (funcall org-make-link-description-function link desc)))
7587 (setq desc (read-string "Description: " desc))
7588 (unless (string-match "\\S-" desc) (setq desc nil))
7589 (if remove (apply 'delete-region remove))
7590 (insert (org-make-link-string link desc))))
7592 (defun org-link-try-special-completion (type)
7593 "If there is completion support for link type TYPE, offer it."
7594 (let ((fun (intern (concat "org-" type "-complete-link"))))
7595 (if (functionp fun)
7596 (funcall fun)
7597 (read-string "Link (no completion support): " (concat type ":")))))
7599 (defun org-file-complete-link (&optional arg)
7600 "Create a file link using completion."
7601 (let (file link)
7602 (setq file (read-file-name "File: "))
7603 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7604 (pwd1 (file-name-as-directory (abbreviate-file-name
7605 (expand-file-name ".")))))
7606 (cond
7607 ((equal arg '(16))
7608 (setq link (org-make-link
7609 "file:"
7610 (abbreviate-file-name (expand-file-name file)))))
7611 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7612 (setq link (org-make-link "file:" (match-string 1 file))))
7613 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7614 (expand-file-name file))
7615 (setq link (org-make-link
7616 "file:" (match-string 1 (expand-file-name file)))))
7617 (t (setq link (org-make-link "file:" file)))))
7618 link))
7620 (defun org-completing-read (&rest args)
7621 "Completing-read with SPACE being a normal character."
7622 (let ((minibuffer-local-completion-map
7623 (copy-keymap minibuffer-local-completion-map)))
7624 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7625 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7626 (apply 'org-ido-completing-read args)))
7628 (defun org-completing-read-no-ido (&rest args)
7629 (let (org-completion-use-ido)
7630 (apply 'org-completing-read args)))
7632 (defun org-ido-completing-read (&rest args)
7633 "Completing-read using `ido-mode' speedups if available"
7634 (if (and org-completion-use-ido
7635 (fboundp 'ido-completing-read)
7636 (boundp 'ido-mode) ido-mode
7637 (listp (second args)))
7638 (let ((ido-enter-matching-directory nil))
7639 (apply 'ido-completing-read (concat (car args))
7640 (if (consp (car (nth 1 args)))
7641 (mapcar (lambda (x) (car x)) (nth 1 args))
7642 (nth 1 args))
7643 (cddr args)))
7644 (apply 'completing-read args)))
7646 (defun org-extract-attributes (s)
7647 "Extract the attributes cookie from a string and set as text property."
7648 (let (a attr (start 0) key value)
7649 (save-match-data
7650 (when (string-match "{{\\([^}]+\\)}}$" s)
7651 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7652 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7653 (setq key (match-string 1 a) value (match-string 2 a)
7654 start (match-end 0)
7655 attr (plist-put attr (intern key) value))))
7656 (org-add-props s nil 'org-attr attr))
7659 (defun org-extract-attributes-from-string (tag)
7660 (let (key value attr)
7661 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
7662 (setq key (match-string 1 tag) value (match-string 2 tag)
7663 tag (replace-match "" t t tag)
7664 attr (plist-put attr (intern key) value)))
7665 (cons tag attr)))
7667 (defun org-attributes-to-string (plist)
7668 "Format a property list into an HTML attribute list."
7669 (let ((s "") key value)
7670 (while plist
7671 (setq key (pop plist) value (pop plist))
7672 (and value
7673 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7676 ;;; Opening/following a link
7678 (defvar org-link-search-failed nil)
7680 (defun org-next-link ()
7681 "Move forward to the next link.
7682 If the link is in hidden text, expose it."
7683 (interactive)
7684 (when (and org-link-search-failed (eq this-command last-command))
7685 (goto-char (point-min))
7686 (message "Link search wrapped back to beginning of buffer"))
7687 (setq org-link-search-failed nil)
7688 (let* ((pos (point))
7689 (ct (org-context))
7690 (a (assoc :link ct)))
7691 (if a (goto-char (nth 2 a)))
7692 (if (re-search-forward org-any-link-re nil t)
7693 (progn
7694 (goto-char (match-beginning 0))
7695 (if (org-invisible-p) (org-show-context)))
7696 (goto-char pos)
7697 (setq org-link-search-failed t)
7698 (error "No further link found"))))
7700 (defun org-previous-link ()
7701 "Move backward to the previous link.
7702 If the link is in hidden text, expose it."
7703 (interactive)
7704 (when (and org-link-search-failed (eq this-command last-command))
7705 (goto-char (point-max))
7706 (message "Link search wrapped back to end of buffer"))
7707 (setq org-link-search-failed nil)
7708 (let* ((pos (point))
7709 (ct (org-context))
7710 (a (assoc :link ct)))
7711 (if a (goto-char (nth 1 a)))
7712 (if (re-search-backward org-any-link-re nil t)
7713 (progn
7714 (goto-char (match-beginning 0))
7715 (if (org-invisible-p) (org-show-context)))
7716 (goto-char pos)
7717 (setq org-link-search-failed t)
7718 (error "No further link found"))))
7720 (defun org-translate-link (s)
7721 "Translate a link string if a translation function has been defined."
7722 (if (and org-link-translation-function
7723 (fboundp org-link-translation-function)
7724 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7725 (progn
7726 (setq s (funcall org-link-translation-function
7727 (match-string 1) (match-string 2)))
7728 (concat (car s) ":" (cdr s)))
7731 (defun org-translate-link-from-planner (type path)
7732 "Translate a link from Emacs Planner syntax so that Org can follow it.
7733 This is still an experimental function, your mileage may vary."
7734 (cond
7735 ((member type '("http" "https" "news" "ftp"))
7736 ;; standard Internet links are the same.
7737 nil)
7738 ((and (equal type "irc") (string-match "^//" path))
7739 ;; Planner has two / at the beginning of an irc link, we have 1.
7740 ;; We should have zero, actually....
7741 (setq path (substring path 1)))
7742 ((and (equal type "lisp") (string-match "^/" path))
7743 ;; Planner has a slash, we do not.
7744 (setq type "elisp" path (substring path 1)))
7745 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7746 ;; A typical message link. Planner has the id after the fina slash,
7747 ;; we separate it with a hash mark
7748 (setq path (concat (match-string 1 path) "#"
7749 (org-remove-angle-brackets (match-string 2 path)))))
7751 (cons type path))
7753 (defun org-find-file-at-mouse (ev)
7754 "Open file link or URL at mouse."
7755 (interactive "e")
7756 (mouse-set-point ev)
7757 (org-open-at-point 'in-emacs))
7759 (defun org-open-at-mouse (ev)
7760 "Open file link or URL at mouse."
7761 (interactive "e")
7762 (mouse-set-point ev)
7763 (if (eq major-mode 'org-agenda-mode)
7764 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7765 (org-open-at-point))
7767 (defvar org-window-config-before-follow-link nil
7768 "The window configuration before following a link.
7769 This is saved in case the need arises to restore it.")
7771 (defvar org-open-link-marker (make-marker)
7772 "Marker pointing to the location where `org-open-at-point; was called.")
7774 ;;;###autoload
7775 (defun org-open-at-point-global ()
7776 "Follow a link like Org-mode does.
7777 This command can be called in any mode to follow a link that has
7778 Org-mode syntax."
7779 (interactive)
7780 (org-run-like-in-org-mode 'org-open-at-point))
7782 ;;;###autoload
7783 (defun org-open-link-from-string (s &optional arg)
7784 "Open a link in the string S, as if it was in Org-mode."
7785 (interactive "sLink: \nP")
7786 (let ((reference-buffer (current-buffer)))
7787 (with-temp-buffer
7788 (let ((org-inhibit-startup t))
7789 (org-mode)
7790 (insert s)
7791 (goto-char (point-min))
7792 (org-open-at-point arg reference-buffer)))))
7794 (defun org-open-at-point (&optional in-emacs reference-buffer)
7795 "Open link at or after point.
7796 If there is no link at point, this function will search forward up to
7797 the end of the current line.
7798 Normally, files will be opened by an appropriate application. If the
7799 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7800 With a double prefix argument, try to open outside of Emacs, in the
7801 application the system uses for this file type."
7802 (interactive "P")
7803 (org-load-modules-maybe)
7804 (move-marker org-open-link-marker (point))
7805 (setq org-window-config-before-follow-link (current-window-configuration))
7806 (org-remove-occur-highlights nil nil t)
7807 (cond
7808 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7809 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7810 (org-footnote-action))
7812 (let (type path link line search (pos (point)))
7813 (catch 'match
7814 (save-excursion
7815 (skip-chars-forward "^]\n\r")
7816 (when (org-in-regexp org-bracket-link-regexp)
7817 (setq link (org-extract-attributes
7818 (org-link-unescape (org-match-string-no-properties 1))))
7819 (while (string-match " *\n *" link)
7820 (setq link (replace-match " " t t link)))
7821 (setq link (org-link-expand-abbrev link))
7822 (cond
7823 ((or (file-name-absolute-p link)
7824 (string-match "^\\.\\.?/" link))
7825 (setq type "file" path link))
7826 ((string-match org-link-re-with-space3 link)
7827 (setq type (match-string 1 link) path (match-string 2 link)))
7828 (t (setq type "thisfile" path link)))
7829 (throw 'match t)))
7831 (when (get-text-property (point) 'org-linked-text)
7832 (setq type "thisfile"
7833 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7834 (1+ (point)) (point))
7835 path (buffer-substring
7836 (previous-single-property-change pos 'org-linked-text)
7837 (next-single-property-change pos 'org-linked-text)))
7838 (throw 'match t))
7840 (save-excursion
7841 (when (or (org-in-regexp org-angle-link-re)
7842 (org-in-regexp org-plain-link-re))
7843 (setq type (match-string 1) path (match-string 2))
7844 (throw 'match t)))
7845 (save-excursion
7846 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7847 (setq type "tags"
7848 path (match-string 1))
7849 (while (string-match ":" path)
7850 (setq path (replace-match "+" t t path)))
7851 (throw 'match t)))
7852 (when (org-in-regexp "<\\([^><\n]+\\)>")
7853 (setq type "tree-match"
7854 path (match-string 1))
7855 (throw 'match t)))
7856 (unless path
7857 (error "No link found"))
7859 ;; switch back to reference buffer
7860 ;; needed when if called in a temporary buffer through
7861 ;; org-open-link-from-string
7862 (and reference-buffer (switch-to-buffer reference-buffer))
7864 ;; Remove any trailing spaces in path
7865 (if (string-match " +\\'" path)
7866 (setq path (replace-match "" t t path)))
7867 (if (and org-link-translation-function
7868 (fboundp org-link-translation-function))
7869 ;; Check if we need to translate the link
7870 (let ((tmp (funcall org-link-translation-function type path)))
7871 (setq type (car tmp) path (cdr tmp))))
7873 (cond
7875 ((assoc type org-link-protocols)
7876 (funcall (nth 1 (assoc type org-link-protocols)) path))
7878 ((equal type "mailto")
7879 (let ((cmd (car org-link-mailto-program))
7880 (args (cdr org-link-mailto-program)) args1
7881 (address path) (subject "") a)
7882 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7883 (setq address (match-string 1 path)
7884 subject (org-link-escape (match-string 2 path))))
7885 (while args
7886 (cond
7887 ((not (stringp (car args))) (push (pop args) args1))
7888 (t (setq a (pop args))
7889 (if (string-match "%a" a)
7890 (setq a (replace-match address t t a)))
7891 (if (string-match "%s" a)
7892 (setq a (replace-match subject t t a)))
7893 (push a args1))))
7894 (apply cmd (nreverse args1))))
7896 ((member type '("http" "https" "ftp" "news"))
7897 (browse-url (concat type ":" (org-link-escape
7898 path org-link-escape-chars-browser))))
7900 ((member type '("message"))
7901 (browse-url (concat type ":" path)))
7903 ((string= type "tags")
7904 (org-tags-view in-emacs path))
7905 ((string= type "thisfile")
7906 (if in-emacs
7907 (switch-to-buffer-other-window
7908 (org-get-buffer-for-internal-link (current-buffer)))
7909 (org-mark-ring-push))
7910 (let ((cmd `(org-link-search
7911 ,path
7912 ,(cond ((equal in-emacs '(4)) 'occur)
7913 ((equal in-emacs '(16)) 'org-occur)
7914 (t nil))
7915 ,pos)))
7916 (condition-case nil (eval cmd)
7917 (error (progn (widen) (eval cmd))))))
7919 ((string= type "tree-match")
7920 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7922 ((string= type "file")
7923 (if (string-match "::\\([0-9]+\\)\\'" path)
7924 (setq line (string-to-number (match-string 1 path))
7925 path (substring path 0 (match-beginning 0)))
7926 (if (string-match "::\\(.+\\)\\'" path)
7927 (setq search (match-string 1 path)
7928 path (substring path 0 (match-beginning 0)))))
7929 (if (string-match "[*?{]" (file-name-nondirectory path))
7930 (dired path)
7931 (org-open-file path in-emacs line search)))
7933 ((string= type "news")
7934 (require 'org-gnus)
7935 (org-gnus-follow-link path))
7937 ((string= type "shell")
7938 (let ((cmd path))
7939 (if (or (not org-confirm-shell-link-function)
7940 (funcall org-confirm-shell-link-function
7941 (format "Execute \"%s\" in shell? "
7942 (org-add-props cmd nil
7943 'face 'org-warning))))
7944 (progn
7945 (message "Executing %s" cmd)
7946 (shell-command cmd))
7947 (error "Abort"))))
7949 ((string= type "elisp")
7950 (let ((cmd path))
7951 (if (or (not org-confirm-elisp-link-function)
7952 (funcall org-confirm-elisp-link-function
7953 (format "Execute \"%s\" as elisp? "
7954 (org-add-props cmd nil
7955 'face 'org-warning))))
7956 (message "%s => %s" cmd
7957 (if (equal (string-to-char cmd) ?\()
7958 (eval (read cmd))
7959 (call-interactively (read cmd))))
7960 (error "Abort"))))
7963 (browse-url-at-point))))))
7964 (move-marker org-open-link-marker nil)
7965 (run-hook-with-args 'org-follow-link-hook))
7967 ;;;; Time estimates
7969 (defun org-get-effort (&optional pom)
7970 "Get the effort estimate for the current entry."
7971 (org-entry-get pom org-effort-property))
7973 ;;; File search
7975 (defvar org-create-file-search-functions nil
7976 "List of functions to construct the right search string for a file link.
7977 These functions are called in turn with point at the location to
7978 which the link should point.
7980 A function in the hook should first test if it would like to
7981 handle this file type, for example by checking the major-mode or
7982 the file extension. If it decides not to handle this file, it
7983 should just return nil to give other functions a chance. If it
7984 does handle the file, it must return the search string to be used
7985 when following the link. The search string will be part of the
7986 file link, given after a double colon, and `org-open-at-point'
7987 will automatically search for it. If special measures must be
7988 taken to make the search successful, another function should be
7989 added to the companion hook `org-execute-file-search-functions',
7990 which see.
7992 A function in this hook may also use `setq' to set the variable
7993 `description' to provide a suggestion for the descriptive text to
7994 be used for this link when it gets inserted into an Org-mode
7995 buffer with \\[org-insert-link].")
7997 (defvar org-execute-file-search-functions nil
7998 "List of functions to execute a file search triggered by a link.
8000 Functions added to this hook must accept a single argument, the
8001 search string that was part of the file link, the part after the
8002 double colon. The function must first check if it would like to
8003 handle this search, for example by checking the major-mode or the
8004 file extension. If it decides not to handle this search, it
8005 should just return nil to give other functions a chance. If it
8006 does handle the search, it must return a non-nil value to keep
8007 other functions from trying.
8009 Each function can access the current prefix argument through the
8010 variable `current-prefix-argument'. Note that a single prefix is
8011 used to force opening a link in Emacs, so it may be good to only
8012 use a numeric or double prefix to guide the search function.
8014 In case this is needed, a function in this hook can also restore
8015 the window configuration before `org-open-at-point' was called using:
8017 (set-window-configuration org-window-config-before-follow-link)")
8019 (defun org-link-search (s &optional type avoid-pos)
8020 "Search for a link search option.
8021 If S is surrounded by forward slashes, it is interpreted as a
8022 regular expression. In org-mode files, this will create an `org-occur'
8023 sparse tree. In ordinary files, `occur' will be used to list matches.
8024 If the current buffer is in `dired-mode', grep will be used to search
8025 in all files. If AVOID-POS is given, ignore matches near that position."
8026 (let ((case-fold-search t)
8027 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8028 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8029 (append '(("") (" ") ("\t") ("\n"))
8030 org-emphasis-alist)
8031 "\\|") "\\)"))
8032 (pos (point))
8033 (pre nil) (post nil)
8034 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8035 (cond
8036 ;; First check if there are any special
8037 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8038 ;; Now try the builtin stuff
8039 ((and (equal (string-to-char s0) ?#)
8040 (> (length s0) 1)
8041 (save-excursion
8042 (goto-char (point-min))
8043 (and
8044 (re-search-forward
8045 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8046 (setq type 'dedicated
8047 pos (match-beginning 0))))
8048 ;; There is an exact target for this
8049 (goto-char pos)
8050 (org-back-to-heading t)))
8051 ((save-excursion
8052 (goto-char (point-min))
8053 (and
8054 (re-search-forward
8055 (concat "<<" (regexp-quote s0) ">>") nil t)
8056 (setq type 'dedicated
8057 pos (match-beginning 0))))
8058 ;; There is an exact target for this
8059 (goto-char pos))
8060 ((and (string-match "^(\\(.*\\))$" s0)
8061 (save-excursion
8062 (goto-char (point-min))
8063 (and
8064 (re-search-forward
8065 (concat "[^[]" (regexp-quote
8066 (format org-coderef-label-format
8067 (match-string 1 s0))))
8068 nil t)
8069 (setq type 'dedicated
8070 pos (1+ (match-beginning 0))))))
8071 ;; There is a coderef target for this
8072 (goto-char pos))
8073 ((string-match "^/\\(.*\\)/$" s)
8074 ;; A regular expression
8075 (cond
8076 ((org-mode-p)
8077 (org-occur (match-string 1 s)))
8078 ;;((eq major-mode 'dired-mode)
8079 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8080 (t (org-do-occur (match-string 1 s)))))
8082 ;; A normal search strings
8083 (when (equal (string-to-char s) ?*)
8084 ;; Anchor on headlines, post may include tags.
8085 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8086 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8087 s (substring s 1)))
8088 (remove-text-properties
8089 0 (length s)
8090 '(face nil mouse-face nil keymap nil fontified nil) s)
8091 ;; Make a series of regular expressions to find a match
8092 (setq words (org-split-string s "[ \n\r\t]+")
8094 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8095 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8096 "\\)" markers)
8097 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8098 re2a (concat "[ \t\r\n]" re2a_)
8099 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8100 re4 (concat "[^a-zA-Z_]" re4_)
8102 re1 (concat pre re2 post)
8103 re3 (concat pre (if pre re4_ re4) post)
8104 re5 (concat pre ".*" re4)
8105 re2 (concat pre re2)
8106 re2a (concat pre (if pre re2a_ re2a))
8107 re4 (concat pre (if pre re4_ re4))
8108 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8109 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8110 re5 "\\)"
8112 (cond
8113 ((eq type 'org-occur) (org-occur reall))
8114 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8115 (t (goto-char (point-min))
8116 (setq type 'fuzzy)
8117 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8118 (org-search-not-self 1 re1 nil t)
8119 (org-search-not-self 1 re2 nil t)
8120 (org-search-not-self 1 re2a nil t)
8121 (org-search-not-self 1 re3 nil t)
8122 (org-search-not-self 1 re4 nil t)
8123 (org-search-not-self 1 re5 nil t)
8125 (goto-char (match-beginning 1))
8126 (goto-char pos)
8127 (error "No match")))))
8129 ;; Normal string-search
8130 (goto-char (point-min))
8131 (if (search-forward s nil t)
8132 (goto-char (match-beginning 0))
8133 (error "No match"))))
8134 (and (org-mode-p) (org-show-context 'link-search))
8135 type))
8137 (defun org-search-not-self (group &rest args)
8138 "Execute `re-search-forward', but only accept matches that do not
8139 enclose the position of `org-open-link-marker'."
8140 (let ((m org-open-link-marker))
8141 (catch 'exit
8142 (while (apply 're-search-forward args)
8143 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8144 (goto-char (match-end group))
8145 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8146 (> (match-beginning 0) (marker-position m))
8147 (< (match-end 0) (marker-position m)))
8148 (save-match-data
8149 (or (not (org-in-regexp
8150 org-bracket-link-analytic-regexp 1))
8151 (not (match-end 4)) ; no description
8152 (and (<= (match-beginning 4) (point))
8153 (>= (match-end 4) (point))))))
8154 (throw 'exit (point))))))))
8156 (defun org-get-buffer-for-internal-link (buffer)
8157 "Return a buffer to be used for displaying the link target of internal links."
8158 (cond
8159 ((not org-display-internal-link-with-indirect-buffer)
8160 buffer)
8161 ((string-match "(Clone)$" (buffer-name buffer))
8162 (message "Buffer is already a clone, not making another one")
8163 ;; we also do not modify visibility in this case
8164 buffer)
8165 (t ; make a new indirect buffer for displaying the link
8166 (let* ((bn (buffer-name buffer))
8167 (ibn (concat bn "(Clone)"))
8168 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8169 (with-current-buffer ib (org-overview))
8170 ib))))
8172 (defun org-do-occur (regexp &optional cleanup)
8173 "Call the Emacs command `occur'.
8174 If CLEANUP is non-nil, remove the printout of the regular expression
8175 in the *Occur* buffer. This is useful if the regex is long and not useful
8176 to read."
8177 (occur regexp)
8178 (when cleanup
8179 (let ((cwin (selected-window)) win beg end)
8180 (when (setq win (get-buffer-window "*Occur*"))
8181 (select-window win))
8182 (goto-char (point-min))
8183 (when (re-search-forward "match[a-z]+" nil t)
8184 (setq beg (match-end 0))
8185 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8186 (setq end (1- (match-beginning 0)))))
8187 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8188 (goto-char (point-min))
8189 (select-window cwin))))
8191 ;;; The mark ring for links jumps
8193 (defvar org-mark-ring nil
8194 "Mark ring for positions before jumps in Org-mode.")
8195 (defvar org-mark-ring-last-goto nil
8196 "Last position in the mark ring used to go back.")
8197 ;; Fill and close the ring
8198 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8199 (loop for i from 1 to org-mark-ring-length do
8200 (push (make-marker) org-mark-ring))
8201 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8202 org-mark-ring)
8204 (defun org-mark-ring-push (&optional pos buffer)
8205 "Put the current position or POS into the mark ring and rotate it."
8206 (interactive)
8207 (setq pos (or pos (point)))
8208 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8209 (move-marker (car org-mark-ring)
8210 (or pos (point))
8211 (or buffer (current-buffer)))
8212 (message "%s"
8213 (substitute-command-keys
8214 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8216 (defun org-mark-ring-goto (&optional n)
8217 "Jump to the previous position in the mark ring.
8218 With prefix arg N, jump back that many stored positions. When
8219 called several times in succession, walk through the entire ring.
8220 Org-mode commands jumping to a different position in the current file,
8221 or to another Org-mode file, automatically push the old position
8222 onto the ring."
8223 (interactive "p")
8224 (let (p m)
8225 (if (eq last-command this-command)
8226 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8227 (setq p org-mark-ring))
8228 (setq org-mark-ring-last-goto p)
8229 (setq m (car p))
8230 (switch-to-buffer (marker-buffer m))
8231 (goto-char m)
8232 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8234 (defun org-remove-angle-brackets (s)
8235 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8236 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8238 (defun org-add-angle-brackets (s)
8239 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8240 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8242 (defun org-remove-double-quotes (s)
8243 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8244 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8247 ;;; Following specific links
8249 (defun org-follow-timestamp-link ()
8250 (cond
8251 ((org-at-date-range-p t)
8252 (let ((org-agenda-start-on-weekday)
8253 (t1 (match-string 1))
8254 (t2 (match-string 2)))
8255 (setq t1 (time-to-days (org-time-string-to-time t1))
8256 t2 (time-to-days (org-time-string-to-time t2)))
8257 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8258 ((org-at-timestamp-p t)
8259 (org-agenda-list nil (time-to-days (org-time-string-to-time
8260 (substring (match-string 1) 0 10)))
8262 (t (error "This should not happen"))))
8265 ;;; Following file links
8266 (defvar org-wait nil)
8267 (defun org-open-file (path &optional in-emacs line search)
8268 "Open the file at PATH.
8269 First, this expands any special file name abbreviations. Then the
8270 configuration variable `org-file-apps' is checked if it contains an
8271 entry for this file type, and if yes, the corresponding command is launched.
8273 If no application is found, Emacs simply visits the file.
8275 With optional prefix argument IN-EMACS, Emacs will visit the file.
8276 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8277 and o use an external application to visit the file.
8279 Optional LINE specifies a line to go to, optional SEARCH a string to
8280 search for. If LINE or SEARCH is given, the file will always be
8281 opened in Emacs.
8282 If the file does not exist, an error is thrown."
8283 (setq in-emacs (or in-emacs line search))
8284 (let* ((file (if (equal path "")
8285 buffer-file-name
8286 (substitute-in-file-name (expand-file-name path))))
8287 (apps (append org-file-apps (org-default-apps)))
8288 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8289 (dirp (if remp nil (file-directory-p file)))
8290 (file (if (and dirp org-open-directory-means-index-dot-org)
8291 (concat (file-name-as-directory file) "index.org")
8292 file))
8293 (a-m-a-p (assq 'auto-mode apps))
8294 (dfile (downcase file))
8295 (old-buffer (current-buffer))
8296 (old-pos (point))
8297 (old-mode major-mode)
8298 ext cmd)
8299 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8300 (setq ext (match-string 1 dfile))
8301 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8302 (setq ext (match-string 1 dfile))))
8303 (cond
8304 ((equal in-emacs '(16))
8305 (setq cmd (cdr (assoc 'system apps))))
8306 (in-emacs (setq cmd 'emacs))
8308 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8309 (and dirp (cdr (assoc 'directory apps)))
8310 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8311 'string-match)
8312 (cdr (assoc ext apps))
8313 (cdr (assoc t apps))))))
8314 (when (eq cmd 'system)
8315 (setq cmd (cdr (assoc 'system apps))))
8316 (when (eq cmd 'default)
8317 (setq cmd (cdr (assoc t apps))))
8318 (when (eq cmd 'mailcap)
8319 (require 'mailcap)
8320 (mailcap-parse-mailcaps)
8321 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8322 (command (mailcap-mime-info mime-type)))
8323 (if (stringp command)
8324 (setq cmd command)
8325 (setq cmd 'emacs))))
8326 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8327 (not (file-exists-p file))
8328 (not org-open-non-existing-files))
8329 (error "No such file: %s" file))
8330 (cond
8331 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8332 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8333 (while (string-match "['\"]%s['\"]" cmd)
8334 (setq cmd (replace-match "%s" t t cmd)))
8335 (while (string-match "%s" cmd)
8336 (setq cmd (replace-match
8337 (save-match-data
8338 (shell-quote-argument
8339 (convert-standard-filename file)))
8340 t t cmd)))
8341 (save-window-excursion
8342 (start-process-shell-command cmd nil cmd)
8343 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8345 ((or (stringp cmd)
8346 (eq cmd 'emacs))
8347 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8348 (widen)
8349 (if line (goto-line line)
8350 (if search (org-link-search search))))
8351 ((consp cmd)
8352 (let ((file (convert-standard-filename file)))
8353 (eval cmd)))
8354 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8355 (and (org-mode-p) (eq old-mode 'org-mode)
8356 (or (not (equal old-buffer (current-buffer)))
8357 (not (equal old-pos (point))))
8358 (org-mark-ring-push old-pos old-buffer))))
8360 (defun org-default-apps ()
8361 "Return the default applications for this operating system."
8362 (cond
8363 ((eq system-type 'darwin)
8364 org-file-apps-defaults-macosx)
8365 ((eq system-type 'windows-nt)
8366 org-file-apps-defaults-windowsnt)
8367 (t org-file-apps-defaults-gnu)))
8369 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8370 "Convert extensions to regular expressions in the cars of LIST.
8371 Also, weed out any non-string entries, because the return value is used
8372 only for regexp matching.
8373 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8374 point to the symbol `emacs', indicating that the file should
8375 be opened in Emacs."
8376 (append
8377 (delq nil
8378 (mapcar (lambda (x)
8379 (if (not (stringp (car x)))
8381 (if (string-match "\\W" (car x))
8383 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8384 list))
8385 (if add-auto-mode
8386 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8388 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8389 (defun org-file-remote-p (file)
8390 "Test whether FILE specifies a location on a remote system.
8391 Return non-nil if the location is indeed remote.
8393 For example, the filename \"/user@host:/foo\" specifies a location
8394 on the system \"/user@host:\"."
8395 (cond ((fboundp 'file-remote-p)
8396 (file-remote-p file))
8397 ((fboundp 'tramp-handle-file-remote-p)
8398 (tramp-handle-file-remote-p file))
8399 ((and (boundp 'ange-ftp-name-format)
8400 (string-match (car ange-ftp-name-format) file))
8402 (t nil)))
8405 ;;;; Refiling
8407 (defun org-get-org-file ()
8408 "Read a filename, with default directory `org-directory'."
8409 (let ((default (or org-default-notes-file remember-data-file)))
8410 (read-file-name (format "File name [%s]: " default)
8411 (file-name-as-directory org-directory)
8412 default)))
8414 (defun org-notes-order-reversed-p ()
8415 "Check if the current file should receive notes in reversed order."
8416 (cond
8417 ((not org-reverse-note-order) nil)
8418 ((eq t org-reverse-note-order) t)
8419 ((not (listp org-reverse-note-order)) nil)
8420 (t (catch 'exit
8421 (let ((all org-reverse-note-order)
8422 entry)
8423 (while (setq entry (pop all))
8424 (if (string-match (car entry) buffer-file-name)
8425 (throw 'exit (cdr entry))))
8426 nil)))))
8428 (defvar org-refile-target-table nil
8429 "The list of refile targets, created by `org-refile'.")
8431 (defvar org-agenda-new-buffers nil
8432 "Buffers created to visit agenda files.")
8434 (defun org-get-refile-targets (&optional default-buffer)
8435 "Produce a table with refile targets."
8436 (let ((case-fold-search nil)
8437 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
8438 (entries (or org-refile-targets '((nil . (:level . 1)))))
8439 targets txt re files f desc descre fast-path-p level pos0)
8440 (message "Getting targets...")
8441 (with-current-buffer (or default-buffer (current-buffer))
8442 (while (setq entry (pop entries))
8443 (setq files (car entry) desc (cdr entry))
8444 (setq fast-path-p nil)
8445 (cond
8446 ((null files) (setq files (list (current-buffer))))
8447 ((eq files 'org-agenda-files)
8448 (setq files (org-agenda-files 'unrestricted)))
8449 ((and (symbolp files) (fboundp files))
8450 (setq files (funcall files)))
8451 ((and (symbolp files) (boundp files))
8452 (setq files (symbol-value files))))
8453 (if (stringp files) (setq files (list files)))
8454 (cond
8455 ((eq (car desc) :tag)
8456 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8457 ((eq (car desc) :todo)
8458 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8459 ((eq (car desc) :regexp)
8460 (setq descre (cdr desc)))
8461 ((eq (car desc) :level)
8462 (setq descre (concat "^\\*\\{" (number-to-string
8463 (if org-odd-levels-only
8464 (1- (* 2 (cdr desc)))
8465 (cdr desc)))
8466 "\\}[ \t]")))
8467 ((eq (car desc) :maxlevel)
8468 (setq fast-path-p t)
8469 (setq descre (concat "^\\*\\{1," (number-to-string
8470 (if org-odd-levels-only
8471 (1- (* 2 (cdr desc)))
8472 (cdr desc)))
8473 "\\}[ \t]")))
8474 (t (error "Bad refiling target description %s" desc)))
8475 (while (setq f (pop files))
8476 (save-excursion
8477 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
8478 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8479 (setq f (expand-file-name f))
8480 (if (eq org-refile-use-outline-path 'file)
8481 (push (list (file-name-nondirectory f) f nil nil) targets))
8482 (save-excursion
8483 (save-restriction
8484 (widen)
8485 (goto-char (point-min))
8486 (while (re-search-forward descre nil t)
8487 (goto-char (setq pos0 (point-at-bol)))
8488 (catch 'next
8489 (when org-refile-target-verify-function
8490 (save-match-data
8491 (or (funcall org-refile-target-verify-function)
8492 (throw 'next t))))
8493 (when (looking-at org-complex-heading-regexp)
8494 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8495 txt (org-link-display-format (match-string 4))
8496 re (concat "^" (regexp-quote
8497 (buffer-substring (match-beginning 1)
8498 (match-end 4)))))
8499 (if (match-end 5) (setq re (concat re "[ \t]+"
8500 (regexp-quote
8501 (match-string 5)))))
8502 (setq re (concat re "[ \t]*$"))
8503 (when org-refile-use-outline-path
8504 (setq txt (mapconcat 'org-protect-slash
8505 (append
8506 (if (eq org-refile-use-outline-path 'file)
8507 (list (file-name-nondirectory
8508 (buffer-file-name (buffer-base-buffer))))
8509 (if (eq org-refile-use-outline-path 'full-file-path)
8510 (list (buffer-file-name (buffer-base-buffer)))))
8511 (org-get-outline-path fast-path-p level txt)
8512 (list txt))
8513 "/")))
8514 (push (list txt f re (point)) targets)))
8515 (when (= (point) pos0)
8516 ;; verification function has not moved point
8517 (goto-char (point-at-eol))))))))))
8518 (message "Getting targets...done")
8519 (nreverse targets)))
8521 (defun org-protect-slash (s)
8522 (while (string-match "/" s)
8523 (setq s (replace-match "\\" t t s)))
8526 (defvar org-olpa (make-vector 20 nil))
8528 (defun org-get-outline-path (&optional fastp level heading)
8529 "Return the outline path to the current entry, as a list."
8530 (if fastp
8531 (progn
8532 (if (> level 19)
8533 (error "Outline path failure, more than 19 levels."))
8534 (loop for i from level upto 19 do
8535 (aset org-olpa i nil))
8536 (prog1
8537 (delq nil (append org-olpa nil))
8538 (aset org-olpa level heading)))
8539 (let (rtn)
8540 (save-excursion
8541 (while (org-up-heading-safe)
8542 (when (looking-at org-complex-heading-regexp)
8543 (push (org-match-string-no-properties 4) rtn)))
8544 rtn))))
8546 (defvar org-refile-history nil
8547 "History for refiling operations.")
8549 (defvar org-after-refile-insert-hook nil
8550 "Hook run after `org-refile' has inserted its stuff at the new location.
8551 Note that this is still *before* the stuff will be removed from
8552 the *old* location.")
8554 (defun org-refile (&optional goto default-buffer rfloc)
8555 "Move the entry at point to another heading.
8556 The list of target headings is compiled using the information in
8557 `org-refile-targets', which see. This list is created before each use
8558 and will therefore always be up-to-date.
8560 At the target location, the entry is filed as a subitem of the target heading.
8561 Depending on `org-reverse-note-order', the new subitem will either be the
8562 first or the last subitem.
8564 If there is an active region, all entries in that region will be moved.
8565 However, the region must fulfil the requirement that the first heading
8566 is the first one sets the top-level of the moved text - at most siblings
8567 below it are allowed.
8569 With prefix arg GOTO, the command will only visit the target location,
8570 not actually move anything.
8571 With a double prefix `C-u C-u', go to the location where the last refiling
8572 operation has put the subtree.
8574 RFLOC can be a refile location obtained in a different way.
8576 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
8577 (interactive "P")
8578 (let* ((cbuf (current-buffer))
8579 (regionp (org-region-active-p))
8580 (region-start (and regionp (region-beginning)))
8581 (region-end (and regionp (region-end)))
8582 (region-length (and regionp (- region-end region-start)))
8583 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8584 pos it nbuf file re level reversed)
8585 (when regionp (goto-char region-start)
8586 (unless (org-kill-is-subtree-p
8587 (buffer-substring region-start region-end))
8588 (error "The region is not a (sequence of) subtree(s)")))
8589 (if (equal goto '(16))
8590 (org-refile-goto-last-stored)
8591 (when (setq it (or rfloc
8592 (save-excursion
8593 (org-refile-get-location
8594 (if goto "Goto: " "Refile to: ") default-buffer
8595 org-refile-allow-creating-parent-nodes))))
8596 (setq file (nth 1 it)
8597 re (nth 2 it)
8598 pos (nth 3 it))
8599 (if (and (not goto)
8601 (equal (buffer-file-name) file)
8602 (if regionp
8603 (and (>= pos region-start)
8604 (<= pos region-end))
8605 (and (>= pos (point))
8606 (< pos (save-excursion
8607 (org-end-of-subtree t t))))))
8608 (error "Cannot refile to position inside the tree or region"))
8610 (setq nbuf (or (find-buffer-visiting file)
8611 (find-file-noselect file)))
8612 (if goto
8613 (progn
8614 (switch-to-buffer nbuf)
8615 (goto-char pos)
8616 (org-show-context 'org-goto))
8617 (if regionp
8618 (progn
8619 (org-kill-new (buffer-substring region-start region-end))
8620 (org-save-markers-in-region region-start region-end))
8621 (org-copy-subtree 1 nil t))
8622 (save-excursion
8623 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8624 (find-file-noselect file))))
8625 (setq reversed (org-notes-order-reversed-p))
8626 (save-excursion
8627 (save-restriction
8628 (widen)
8629 (if pos
8630 (progn
8631 (goto-char pos)
8632 (looking-at outline-regexp)
8633 (setq level (org-get-valid-level (funcall outline-level) 1))
8634 (goto-char
8635 (if reversed
8636 (or (outline-next-heading) (point-max))
8637 (or (save-excursion (outline-get-next-sibling))
8638 (org-end-of-subtree t t)
8639 (point-max)))))
8640 (setq level 1)
8641 (if (not reversed)
8642 (goto-char (point-max))
8643 (goto-char (point-min))
8644 (or (outline-next-heading) (goto-char (point-max)))))
8645 (if (not (bolp)) (newline))
8646 (bookmark-set "org-refile-last-stored")
8647 (org-paste-subtree level)
8648 (if (fboundp 'deactivate-mark) (deactivate-mark))
8649 (run-hooks 'org-after-refile-insert-hook))))
8650 (if regionp
8651 (delete-region (point) (+ (point) region-length))
8652 (org-cut-subtree))
8653 (when (featurep 'org-inlinetask)
8654 (org-inlinetask-remove-END-maybe))
8655 (setq org-markers-to-move nil)
8656 (message "Refiled to \"%s\"" (car it))))))
8657 (org-reveal))
8659 (defun org-refile-goto-last-stored ()
8660 "Go to the location where the last refile was stored."
8661 (interactive)
8662 (bookmark-jump "org-refile-last-stored")
8663 (message "This is the location of the last refile"))
8665 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
8666 "Prompt the user for a refile location, using PROMPT."
8667 (let ((org-refile-targets org-refile-targets)
8668 (org-refile-use-outline-path org-refile-use-outline-path))
8669 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8670 (unless org-refile-target-table
8671 (error "No refile targets"))
8672 (let* ((cbuf (current-buffer))
8673 (partial-completion-mode nil)
8674 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8675 (cfunc (if (and org-refile-use-outline-path
8676 org-outline-path-complete-in-steps)
8677 'org-olpath-completing-read
8678 'org-ido-completing-read))
8679 (extra (if org-refile-use-outline-path "/" ""))
8680 (filename (and cfn (expand-file-name cfn)))
8681 (tbl (mapcar
8682 (lambda (x)
8683 (if (and (not (member org-refile-use-outline-path
8684 '(file full-file-path)))
8685 (not (equal filename (nth 1 x))))
8686 (cons (concat (car x) extra " ("
8687 (file-name-nondirectory (nth 1 x)) ")")
8688 (cdr x))
8689 (cons (concat (car x) extra) (cdr x))))
8690 org-refile-target-table))
8691 (completion-ignore-case t)
8692 pa answ parent-target child parent)
8693 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
8694 nil 'org-refile-history))
8695 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
8696 (if pa
8697 (progn
8698 (setcar org-refile-history (car pa))
8700 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
8701 (setq parent (match-string 1 answ)
8702 child (match-string 2 answ))
8703 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
8704 (when (and parent-target
8705 (or (eq new-nodes t)
8706 (and (eq new-nodes 'confirm)
8707 (y-or-n-p (format "Create new node \"%s\"? " child)))))
8708 (org-refile-new-child parent-target child))))))
8710 (defun org-refile-new-child (parent-target child)
8711 "Use refile target PARENT-TARGET to add new CHILD below it."
8712 (unless parent-target
8713 (error "Cannot find parent for new node"))
8714 (let ((file (nth 1 parent-target))
8715 (pos (nth 3 parent-target))
8716 level)
8717 (with-current-buffer (or (find-buffer-visiting file)
8718 (find-file-noselect file))
8719 (save-excursion
8720 (save-restriction
8721 (widen)
8722 (if pos
8723 (goto-char pos)
8724 (goto-char (point-max))
8725 (if (not (bolp)) (newline)))
8726 (when (looking-at outline-regexp)
8727 (setq level (funcall outline-level))
8728 (org-end-of-subtree t t))
8729 (org-back-over-empty-lines)
8730 (insert "\n" (make-string
8731 (if pos (org-get-valid-level level 1) 1) ?*)
8732 " " child "\n")
8733 (beginning-of-line 0)
8734 (list (concat (car parent-target) "/" child) file "" (point)))))))
8736 (defun org-olpath-completing-read (prompt collection &rest args)
8737 "Read an outline path like a file name."
8738 (let ((thetable collection)
8739 (org-completion-use-ido nil)) ; does not work with ido.
8740 (apply
8741 'org-ido-completing-read prompt
8742 (lambda (string predicate &optional flag)
8743 (let (rtn r f (l (length string)))
8744 (cond
8745 ((eq flag nil)
8746 ;; try completion
8747 (try-completion string thetable))
8748 ((eq flag t)
8749 ;; all-completions
8750 (setq rtn (all-completions string thetable predicate))
8751 (mapcar
8752 (lambda (x)
8753 (setq r (substring x l))
8754 (if (string-match " ([^)]*)$" x)
8755 (setq f (match-string 0 x))
8756 (setq f ""))
8757 (if (string-match "/" r)
8758 (concat string (substring r 0 (match-end 0)) f)
8760 rtn))
8761 ((eq flag 'lambda)
8762 ;; exact match?
8763 (assoc string thetable)))
8765 args)))
8767 ;;;; Dynamic blocks
8769 (defun org-find-dblock (name)
8770 "Find the first dynamic block with name NAME in the buffer.
8771 If not found, stay at current position and return nil."
8772 (let (pos)
8773 (save-excursion
8774 (goto-char (point-min))
8775 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8776 nil t)
8777 (match-beginning 0))))
8778 (if pos (goto-char pos))
8779 pos))
8781 (defconst org-dblock-start-re
8782 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8783 "Matches the startline of a dynamic block, with parameters.")
8785 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8786 "Matches the end of a dynamic block.")
8788 (defun org-create-dblock (plist)
8789 "Create a dynamic block section, with parameters taken from PLIST.
8790 PLIST must contain a :name entry which is used as name of the block."
8791 (unless (bolp) (newline))
8792 (let ((name (plist-get plist :name)))
8793 (insert "#+BEGIN: " name)
8794 (while plist
8795 (if (eq (car plist) :name)
8796 (setq plist (cddr plist))
8797 (insert " " (prin1-to-string (pop plist)))))
8798 (insert "\n\n#+END:\n")
8799 (beginning-of-line -2)))
8801 (defun org-prepare-dblock ()
8802 "Prepare dynamic block for refresh.
8803 This empties the block, puts the cursor at the insert position and returns
8804 the property list including an extra property :name with the block name."
8805 (unless (looking-at org-dblock-start-re)
8806 (error "Not at a dynamic block"))
8807 (let* ((begdel (1+ (match-end 0)))
8808 (name (org-no-properties (match-string 1)))
8809 (params (append (list :name name)
8810 (read (concat "(" (match-string 3) ")")))))
8811 (unless (re-search-forward org-dblock-end-re nil t)
8812 (error "Dynamic block not terminated"))
8813 (setq params
8814 (append params
8815 (list :content (buffer-substring
8816 begdel (match-beginning 0)))))
8817 (delete-region begdel (match-beginning 0))
8818 (goto-char begdel)
8819 (open-line 1)
8820 params))
8822 (defun org-map-dblocks (&optional command)
8823 "Apply COMMAND to all dynamic blocks in the current buffer.
8824 If COMMAND is not given, use `org-update-dblock'."
8825 (let ((cmd (or command 'org-update-dblock))
8826 pos)
8827 (save-excursion
8828 (goto-char (point-min))
8829 (while (re-search-forward org-dblock-start-re nil t)
8830 (goto-char (setq pos (match-beginning 0)))
8831 (condition-case nil
8832 (funcall cmd)
8833 (error (message "Error during update of dynamic block")))
8834 (goto-char pos)
8835 (unless (re-search-forward org-dblock-end-re nil t)
8836 (error "Dynamic block not terminated"))))))
8838 (defun org-dblock-update (&optional arg)
8839 "User command for updating dynamic blocks.
8840 Update the dynamic block at point. With prefix ARG, update all dynamic
8841 blocks in the buffer."
8842 (interactive "P")
8843 (if arg
8844 (org-update-all-dblocks)
8845 (or (looking-at org-dblock-start-re)
8846 (org-beginning-of-dblock))
8847 (org-update-dblock)))
8849 (defun org-update-dblock ()
8850 "Update the dynamic block at point
8851 This means to empty the block, parse for parameters and then call
8852 the correct writing function."
8853 (save-window-excursion
8854 (let* ((pos (point))
8855 (line (org-current-line))
8856 (params (org-prepare-dblock))
8857 (name (plist-get params :name))
8858 (cmd (intern (concat "org-dblock-write:" name))))
8859 (message "Updating dynamic block `%s' at line %d..." name line)
8860 (funcall cmd params)
8861 (message "Updating dynamic block `%s' at line %d...done" name line)
8862 (goto-char pos))))
8864 (defun org-beginning-of-dblock ()
8865 "Find the beginning of the dynamic block at point.
8866 Error if there is no such block at point."
8867 (let ((pos (point))
8868 beg)
8869 (end-of-line 1)
8870 (if (and (re-search-backward org-dblock-start-re nil t)
8871 (setq beg (match-beginning 0))
8872 (re-search-forward org-dblock-end-re nil t)
8873 (> (match-end 0) pos))
8874 (goto-char beg)
8875 (goto-char pos)
8876 (error "Not in a dynamic block"))))
8878 (defun org-update-all-dblocks ()
8879 "Update all dynamic blocks in the buffer.
8880 This function can be used in a hook."
8881 (when (org-mode-p)
8882 (org-map-dblocks 'org-update-dblock)))
8885 ;;;; Completion
8887 (defconst org-additional-option-like-keywords
8888 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
8889 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
8890 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:" "ATTR_LaTeX"
8891 "BEGIN:" "END:"
8892 "ORGTBL" "TBLFM:" "TBLNAME:"
8893 "BEGIN_EXAMPLE" "END_EXAMPLE"
8894 "BEGIN_QUOTE" "END_QUOTE"
8895 "BEGIN_VERSE" "END_VERSE"
8896 "BEGIN_CENTER" "END_CENTER"
8897 "BEGIN_SRC" "END_SRC"
8898 "CATEGORY" "COLUMNS"
8899 "CAPTION" "LABEL"
8900 "BIND"))
8902 (defcustom org-structure-template-alist
8904 ("s" "#+begin_src ?\n\n#+end_src"
8905 "<src lang=\"?\">\n\n</src>")
8906 ("e" "#+begin_example\n?\n#+end_example"
8907 "<example>\n?\n</example>")
8908 ("q" "#+begin_quote\n?\n#+end_quote"
8909 "<quote>\n?\n</quote>")
8910 ("v" "#+begin_verse\n?\n#+end_verse"
8911 "<verse>\n?\n/verse>")
8912 ("c" "#+begin_center\n?\n#+end_center"
8913 "<center>\n?\n/center>")
8914 ("l" "#+begin_latex\n?\n#+end_latex"
8915 "<literal style=\"latex\">\n?\n</literal>")
8916 ("L" "#+latex: "
8917 "<literal style=\"latex\">?</literal>")
8918 ("h" "#+begin_html\n?\n#+end_html"
8919 "<literal style=\"html\">\n?\n</literal>")
8920 ("H" "#+html: "
8921 "<literal style=\"html\">?</literal>")
8922 ("a" "#+begin_ascii\n?\n#+end_ascii")
8923 ("A" "#+ascii: ")
8924 ("i" "#+include %file ?"
8925 "<include file=%file markup=\"?\">")
8927 "Structure completion elements.
8928 This is a list of abbreviation keys and values. The value gets inserted
8929 it you type @samp{.} followed by the key and then the completion key,
8930 usually `M-TAB'. %file will be replaced by a file name after prompting
8931 for the file using completion.
8932 There are two templates for each key, the first uses the original Org syntax,
8933 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8934 the default when the /org-mtags.el/ module has been loaded. See also the
8935 variable `org-mtags-prefer-muse-templates'.
8936 This is an experimental feature, it is undecided if it is going to stay in."
8937 :group 'org-completion
8938 :type '(repeat
8939 (string :tag "Key")
8940 (string :tag "Template")
8941 (string :tag "Muse Template")))
8943 (defun org-try-structure-completion ()
8944 "Try to complete a structure template before point.
8945 This looks for strings like \"<e\" on an otherwise empty line and
8946 expands them."
8947 (let ((l (buffer-substring (point-at-bol) (point)))
8949 (when (and (looking-at "[ \t]*$")
8950 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8951 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8952 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8953 (match-beginning 1)) a)
8954 t)))
8956 (defun org-complete-expand-structure-template (start cell)
8957 "Expand a structure template."
8958 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8959 (rpl (nth (if musep 2 1) cell))
8960 (ind ""))
8961 (delete-region start (point))
8962 (when (string-match "\\`#\\+" rpl)
8963 (cond
8964 ((bolp))
8965 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8966 (setq ind (buffer-substring (point-at-bol) (point))))
8967 (t (newline))))
8968 (setq start (point))
8969 (if (string-match "%file" rpl)
8970 (setq rpl (replace-match
8971 (concat
8972 "\""
8973 (save-match-data
8974 (abbreviate-file-name (read-file-name "Include file: ")))
8975 "\"")
8976 t t rpl)))
8977 (setq rpl (mapconcat 'identity (split-string rpl "\n")
8978 (concat "\n" ind)))
8979 (insert rpl)
8980 (if (re-search-backward "\\?" start t) (delete-char 1))))
8983 (defun org-complete (&optional arg)
8984 "Perform completion on word at point.
8985 At the beginning of a headline, this completes TODO keywords as given in
8986 `org-todo-keywords'.
8987 If the current word is preceded by a backslash, completes the TeX symbols
8988 that are supported for HTML support.
8989 If the current word is preceded by \"#+\", completes special words for
8990 setting file options.
8991 In the line after \"#+STARTUP:, complete valid keywords.\"
8992 At all other locations, this simply calls the value of
8993 `org-completion-fallback-command'."
8994 (interactive "P")
8995 (org-without-partial-completion
8996 (catch 'exit
8997 (let* ((a nil)
8998 (end (point))
8999 (beg1 (save-excursion
9000 (skip-chars-backward (org-re "[:alnum:]_@"))
9001 (point)))
9002 (beg (save-excursion
9003 (skip-chars-backward "a-zA-Z0-9_:$")
9004 (point)))
9005 (confirm (lambda (x) (stringp (car x))))
9006 (searchhead (equal (char-before beg) ?*))
9007 (struct
9008 (when (and (member (char-before beg1) '(?. ?<))
9009 (setq a (assoc (buffer-substring beg1 (point))
9010 org-structure-template-alist)))
9011 (org-complete-expand-structure-template (1- beg1) a)
9012 (throw 'exit t)))
9013 (tag (and (equal (char-before beg1) ?:)
9014 (equal (char-after (point-at-bol)) ?*)))
9015 (prop (and (equal (char-before beg1) ?:)
9016 (not (equal (char-after (point-at-bol)) ?*))))
9017 (texp (equal (char-before beg) ?\\))
9018 (link (equal (char-before beg) ?\[))
9019 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9020 beg)
9021 "#+"))
9022 (startup (string-match "^#\\+STARTUP:.*"
9023 (buffer-substring (point-at-bol) (point))))
9024 (completion-ignore-case opt)
9025 (type nil)
9026 (tbl nil)
9027 (table (cond
9028 (opt
9029 (setq type :opt)
9030 (require 'org-exp)
9031 (append
9032 (mapcar
9033 (lambda (x)
9034 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9035 (cons (match-string 2 x) (match-string 1 x)))
9036 (org-split-string (org-get-current-options) "\n"))
9037 (mapcar 'list org-additional-option-like-keywords)))
9038 (startup
9039 (setq type :startup)
9040 org-startup-options)
9041 (link (append org-link-abbrev-alist-local
9042 org-link-abbrev-alist))
9043 (texp
9044 (setq type :tex)
9045 org-html-entities)
9046 ((string-match "\\`\\*+[ \t]+\\'"
9047 (buffer-substring (point-at-bol) beg))
9048 (setq type :todo)
9049 (mapcar 'list org-todo-keywords-1))
9050 (searchhead
9051 (setq type :searchhead)
9052 (save-excursion
9053 (goto-char (point-min))
9054 (while (re-search-forward org-todo-line-regexp nil t)
9055 (push (list
9056 (org-make-org-heading-search-string
9057 (match-string 3) t))
9058 tbl)))
9059 tbl)
9060 (tag (setq type :tag beg beg1)
9061 (or org-tag-alist (org-get-buffer-tags)))
9062 (prop (setq type :prop beg beg1)
9063 (mapcar 'list (org-buffer-property-keys nil t t)))
9064 (t (progn
9065 (call-interactively org-completion-fallback-command)
9066 (throw 'exit nil)))))
9067 (pattern (buffer-substring-no-properties beg end))
9068 (completion (try-completion pattern table confirm)))
9069 (cond ((eq completion t)
9070 (if (not (assoc (upcase pattern) table))
9071 (message "Already complete")
9072 (if (and (equal type :opt)
9073 (not (member (car (assoc (upcase pattern) table))
9074 org-additional-option-like-keywords)))
9075 (insert (substring (cdr (assoc (upcase pattern) table))
9076 (length pattern)))
9077 (if (memq type '(:tag :prop)) (insert ":")))))
9078 ((null completion)
9079 (message "Can't find completion for \"%s\"" pattern)
9080 (ding))
9081 ((not (string= pattern completion))
9082 (delete-region beg end)
9083 (if (string-match " +$" completion)
9084 (setq completion (replace-match "" t t completion)))
9085 (insert completion)
9086 (if (get-buffer-window "*Completions*")
9087 (delete-window (get-buffer-window "*Completions*")))
9088 (if (assoc completion table)
9089 (if (eq type :todo) (insert " ")
9090 (if (memq type '(:tag :prop)) (insert ":"))))
9091 (if (and (equal type :opt) (assoc completion table))
9092 (message "%s" (substitute-command-keys
9093 "Press \\[org-complete] again to insert example settings"))))
9095 (message "Making completion list...")
9096 (let ((list (sort (all-completions pattern table confirm)
9097 'string<)))
9098 (with-output-to-temp-buffer "*Completions*"
9099 (condition-case nil
9100 ;; Protection needed for XEmacs and emacs 21
9101 (display-completion-list list pattern)
9102 (error (display-completion-list list)))))
9103 (message "Making completion list...%s" "done")))))))
9105 ;;;; TODO, DEADLINE, Comments
9107 (defun org-toggle-comment ()
9108 "Change the COMMENT state of an entry."
9109 (interactive)
9110 (save-excursion
9111 (org-back-to-heading)
9112 (let (case-fold-search)
9113 (if (looking-at (concat outline-regexp
9114 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9115 (replace-match "" t t nil 1)
9116 (if (looking-at outline-regexp)
9117 (progn
9118 (goto-char (match-end 0))
9119 (insert org-comment-string " ")))))))
9121 (defvar org-last-todo-state-is-todo nil
9122 "This is non-nil when the last TODO state change led to a TODO state.
9123 If the last change removed the TODO tag or switched to DONE, then
9124 this is nil.")
9126 (defvar org-setting-tags nil) ; dynamically skipped
9128 (defun org-parse-local-options (string var)
9129 "Parse STRING for startup setting relevant for variable VAR."
9130 (let ((rtn (symbol-value var))
9131 e opts)
9132 (save-match-data
9133 (if (or (not string) (not (string-match "\\S-" string)))
9135 (setq opts (delq nil (mapcar (lambda (x)
9136 (setq e (assoc x org-startup-options))
9137 (if (eq (nth 1 e) var) e nil))
9138 (org-split-string string "[ \t]+"))))
9139 (if (not opts)
9141 (setq rtn nil)
9142 (while (setq e (pop opts))
9143 (if (not (nth 3 e))
9144 (setq rtn (nth 2 e))
9145 (if (not (listp rtn)) (setq rtn nil))
9146 (push (nth 2 e) rtn)))
9147 rtn)))))
9149 (defvar org-todo-setup-filter-hook nil
9150 "Hook for functions that pre-filter todo specs.
9152 Each function takes a todo spec and returns either `nil' or the spec
9153 transformed into canonical form." )
9155 (defvar org-todo-get-default-hook nil
9156 "Hook for functions that get a default item for todo.
9158 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9159 `nil' or a string to be used for the todo mark." )
9161 (defvar org-agenda-headline-snapshot-before-repeat)
9163 (defun org-todo (&optional arg)
9164 "Change the TODO state of an item.
9165 The state of an item is given by a keyword at the start of the heading,
9166 like
9167 *** TODO Write paper
9168 *** DONE Call mom
9170 The different keywords are specified in the variable `org-todo-keywords'.
9171 By default the available states are \"TODO\" and \"DONE\".
9172 So for this example: when the item starts with TODO, it is changed to DONE.
9173 When it starts with DONE, the DONE is removed. And when neither TODO nor
9174 DONE are present, add TODO at the beginning of the heading.
9176 With C-u prefix arg, use completion to determine the new state.
9177 With numeric prefix arg, switch to that state.
9178 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9179 With a tripple C-u prefix, circumvent any state blocking.
9181 For calling through lisp, arg is also interpreted in the following way:
9182 'none -> empty state
9183 \"\"(empty string) -> switch to empty state
9184 'done -> switch to DONE
9185 'nextset -> switch to the next set of keywords
9186 'previousset -> switch to the previous set of keywords
9187 \"WAITING\" -> switch to the specified keyword, but only if it
9188 really is a member of `org-todo-keywords'."
9189 (interactive "P")
9190 (if (equal arg '(16)) (setq arg 'nextset))
9191 (let ((org-blocker-hook org-blocker-hook)
9192 (case-fold-search nil))
9193 (when (equal arg '(64))
9194 (setq arg nil org-blocker-hook nil))
9195 (when (and org-blocker-hook
9196 (or org-inhibit-blocking
9197 (org-entry-get nil "NOBLOCKING")))
9198 (setq org-blocker-hook nil))
9199 (save-excursion
9200 (catch 'exit
9201 (org-back-to-heading)
9202 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9203 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9204 (looking-at " *"))
9205 (let* ((match-data (match-data))
9206 (startpos (point-at-bol))
9207 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9208 (org-log-done org-log-done)
9209 (org-log-repeat org-log-repeat)
9210 (org-todo-log-states org-todo-log-states)
9211 (this (match-string 1))
9212 (hl-pos (match-beginning 0))
9213 (head (org-get-todo-sequence-head this))
9214 (ass (assoc head org-todo-kwd-alist))
9215 (interpret (nth 1 ass))
9216 (done-word (nth 3 ass))
9217 (final-done-word (nth 4 ass))
9218 (last-state (or this ""))
9219 (completion-ignore-case t)
9220 (member (member this org-todo-keywords-1))
9221 (tail (cdr member))
9222 (state (cond
9223 ((and org-todo-key-trigger
9224 (or (and (equal arg '(4))
9225 (eq org-use-fast-todo-selection 'prefix))
9226 (and (not arg) org-use-fast-todo-selection
9227 (not (eq org-use-fast-todo-selection
9228 'prefix)))))
9229 ;; Use fast selection
9230 (org-fast-todo-selection))
9231 ((and (equal arg '(4))
9232 (or (not org-use-fast-todo-selection)
9233 (not org-todo-key-trigger)))
9234 ;; Read a state with completion
9235 (org-ido-completing-read
9236 "State: " (mapcar (lambda(x) (list x))
9237 org-todo-keywords-1)
9238 nil t))
9239 ((eq arg 'right)
9240 (if this
9241 (if tail (car tail) nil)
9242 (car org-todo-keywords-1)))
9243 ((eq arg 'left)
9244 (if (equal member org-todo-keywords-1)
9246 (if this
9247 (nth (- (length org-todo-keywords-1)
9248 (length tail) 2)
9249 org-todo-keywords-1)
9250 (org-last org-todo-keywords-1))))
9251 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9252 (setq arg nil))) ; hack to fall back to cycling
9253 (arg
9254 ;; user or caller requests a specific state
9255 (cond
9256 ((equal arg "") nil)
9257 ((eq arg 'none) nil)
9258 ((eq arg 'done) (or done-word (car org-done-keywords)))
9259 ((eq arg 'nextset)
9260 (or (car (cdr (member head org-todo-heads)))
9261 (car org-todo-heads)))
9262 ((eq arg 'previousset)
9263 (let ((org-todo-heads (reverse org-todo-heads)))
9264 (or (car (cdr (member head org-todo-heads)))
9265 (car org-todo-heads))))
9266 ((car (member arg org-todo-keywords-1)))
9267 ((nth (1- (prefix-numeric-value arg))
9268 org-todo-keywords-1))))
9269 ((null member) (or head (car org-todo-keywords-1)))
9270 ((equal this final-done-word) nil) ;; -> make empty
9271 ((null tail) nil) ;; -> first entry
9272 ((memq interpret '(type priority))
9273 (if (eq this-command last-command)
9274 (car tail)
9275 (if (> (length tail) 0)
9276 (or done-word (car org-done-keywords))
9277 nil)))
9279 (car tail))))
9280 (state (or
9281 (run-hook-with-args-until-success
9282 'org-todo-get-default-hook state last-state)
9283 state))
9284 (next (if state (concat " " state " ") " "))
9285 (change-plist (list :type 'todo-state-change :from this :to state
9286 :position startpos))
9287 dolog now-done-p)
9288 (when org-blocker-hook
9289 (setq org-last-todo-state-is-todo
9290 (not (member this org-done-keywords)))
9291 (unless (save-excursion
9292 (save-match-data
9293 (run-hook-with-args-until-failure
9294 'org-blocker-hook change-plist)))
9295 (if (interactive-p)
9296 (error "TODO state change from %s to %s blocked" this state)
9297 ;; fail silently
9298 (message "TODO state change from %s to %s blocked" this state)
9299 (throw 'exit nil))))
9300 (store-match-data match-data)
9301 (replace-match next t t)
9302 (unless (pos-visible-in-window-p hl-pos)
9303 (message "TODO state changed to %s" (org-trim next)))
9304 (unless head
9305 (setq head (org-get-todo-sequence-head state)
9306 ass (assoc head org-todo-kwd-alist)
9307 interpret (nth 1 ass)
9308 done-word (nth 3 ass)
9309 final-done-word (nth 4 ass)))
9310 (when (memq arg '(nextset previousset))
9311 (message "Keyword-Set %d/%d: %s"
9312 (- (length org-todo-sets) -1
9313 (length (memq (assoc state org-todo-sets) org-todo-sets)))
9314 (length org-todo-sets)
9315 (mapconcat 'identity (assoc state org-todo-sets) " ")))
9316 (setq org-last-todo-state-is-todo
9317 (not (member state org-done-keywords)))
9318 (setq now-done-p (and (member state org-done-keywords)
9319 (not (member this org-done-keywords))))
9320 (and logging (org-local-logging logging))
9321 (when (and (or org-todo-log-states org-log-done)
9322 (not (eq org-inhibit-logging t))
9323 (not (memq arg '(nextset previousset))))
9324 ;; we need to look at recording a time and note
9325 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
9326 (nth 2 (assoc this org-todo-log-states))))
9327 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
9328 (setq dolog 'time))
9329 (when (and state
9330 (member state org-not-done-keywords)
9331 (not (member this org-not-done-keywords)))
9332 ;; This is now a todo state and was not one before
9333 ;; If there was a CLOSED time stamp, get rid of it.
9334 (org-add-planning-info nil nil 'closed))
9335 (when (and now-done-p org-log-done)
9336 ;; It is now done, and it was not done before
9337 (org-add-planning-info 'closed (org-current-time))
9338 (if (and (not dolog) (eq 'note org-log-done))
9339 (org-add-log-setup 'done state this 'findpos 'note)))
9340 (when (and state dolog)
9341 ;; This is a non-nil state, and we need to log it
9342 (org-add-log-setup 'state state this 'findpos dolog)))
9343 ;; Fixup tag positioning
9344 (org-todo-trigger-tag-changes state)
9345 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
9346 (when org-provide-todo-statistics
9347 (org-update-parent-todo-statistics))
9348 (run-hooks 'org-after-todo-state-change-hook)
9349 (if (and arg (not (member state org-done-keywords)))
9350 (setq head (org-get-todo-sequence-head state)))
9351 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9352 ;; Do we need to trigger a repeat?
9353 (when now-done-p
9354 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
9355 ;; This is for the agenda, take a snapshot of the headline.
9356 (save-match-data
9357 (setq org-agenda-headline-snapshot-before-repeat
9358 (org-get-heading))))
9359 (org-auto-repeat-maybe state))
9360 ;; Fixup cursor location if close to the keyword
9361 (if (and (outline-on-heading-p)
9362 (not (bolp))
9363 (save-excursion (beginning-of-line 1)
9364 (looking-at org-todo-line-regexp))
9365 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9366 (progn
9367 (goto-char (or (match-end 2) (match-end 1)))
9368 (and (looking-at " ") (just-one-space))))
9369 (when org-trigger-hook
9370 (save-excursion
9371 (run-hook-with-args 'org-trigger-hook change-plist))))))))
9373 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
9374 "Block turning an entry into a TODO, using the hierarchy.
9375 This checks whether the current task should be blocked from state
9376 changes. Such blocking occurs when:
9378 1. The task has children which are not all in a completed state.
9380 2. A task has a parent with the property :ORDERED:, and there
9381 are siblings prior to the current task with incomplete
9382 status.
9384 3. The parent of the task is blocked because it has siblings that should
9385 be done first, or is child of a block grandparent TODO entry."
9387 (catch 'dont-block
9388 ;; If this is not a todo state change, or if this entry is already DONE,
9389 ;; do not block
9390 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9391 (member (plist-get change-plist :from)
9392 (cons 'done org-done-keywords))
9393 (member (plist-get change-plist :to)
9394 (cons 'todo org-not-done-keywords)))
9395 (throw 'dont-block t))
9396 ;; If this task has children, and any are undone, it's blocked
9397 (save-excursion
9398 (org-back-to-heading t)
9399 (let ((this-level (funcall outline-level)))
9400 (outline-next-heading)
9401 (let ((child-level (funcall outline-level)))
9402 (while (and (not (eobp))
9403 (> child-level this-level))
9404 ;; this todo has children, check whether they are all
9405 ;; completed
9406 (if (and (not (org-entry-is-done-p))
9407 (org-entry-is-todo-p))
9408 (throw 'dont-block nil))
9409 (outline-next-heading)
9410 (setq child-level (funcall outline-level))))))
9411 ;; Otherwise, if the task's parent has the :ORDERED: property, and
9412 ;; any previous siblings are undone, it's blocked
9413 (save-excursion
9414 (org-back-to-heading t)
9415 (let* ((pos (point))
9416 (parent-pos (and (org-up-heading-safe) (point))))
9417 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9418 (when (and (org-entry-get (point) "ORDERED")
9419 (forward-line 1)
9420 (re-search-forward org-not-done-heading-regexp pos t))
9421 (throw 'dont-block nil)) ; block, there is an older sibling not done.
9422 ;; Search further up the hierarchy, to see if an anchestor is blocked
9423 (while t
9424 (goto-char parent-pos)
9425 (if (not (looking-at org-not-done-heading-regexp))
9426 (throw 'dont-block t)) ; do not block, parent is not a TODO
9427 (setq pos (point))
9428 (setq parent-pos (and (org-up-heading-safe) (point)))
9429 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9430 (when (and (org-entry-get (point) "ORDERED")
9431 (forward-line 1)
9432 (re-search-forward org-not-done-heading-regexp pos t))
9433 (throw 'dont-block nil))))))) ; block, older sibling not done.
9435 (defcustom org-track-ordered-property-with-tag nil
9436 "Should the ORDERED property also be shown as a tag?
9437 The ORDERED property decides if an entry should require subtasks to be
9438 completed in sequence. Since a property is not very visible, setting
9439 this option means that toggling the ORDERED property with the command
9440 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
9441 not relevant for the behavior, but it makes things more visible.
9443 Note that toggling the tag with tags commands will not change the property
9444 and therefore not influence behavior!
9446 This can be t, meaning the tag ORDERED should be used, It can also be a
9447 string to select a different tag for this task."
9448 :group 'org-todo
9449 :type '(choice
9450 (const :tag "No tracking" nil)
9451 (const :tag "Track with ORDERED tag" t)
9452 (string :tag "Use other tag")))
9454 (defun org-toggle-ordered-property ()
9455 "Toggle the ORDERED property of the current entry.
9456 For better visibility, you can track the value of this property with a tag.
9457 See variable `org-track-ordered-property-with-tag'."
9458 (interactive)
9459 (let* ((t1 org-track-ordered-property-with-tag)
9460 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
9461 (save-excursion
9462 (org-back-to-heading)
9463 (if (org-entry-get nil "ORDERED")
9464 (progn
9465 (org-delete-property "ORDERED")
9466 (and tag (org-toggle-tag tag 'off))
9467 (message "Subtasks can be completed in arbitrary order"))
9468 (org-entry-put nil "ORDERED" "t")
9469 (and tag (org-toggle-tag tag 'on))
9470 (message "Subtasks must be completed in sequence")))))
9472 (defvar org-blocked-by-checkboxes) ; dynamically scoped
9473 (defun org-block-todo-from-checkboxes (change-plist)
9474 "Block turning an entry into a TODO, using checkboxes.
9475 This checks whether the current task should be blocked from state
9476 changes because there are uncheckd boxes in this entry."
9477 (catch 'dont-block
9478 ;; If this is not a todo state change, or if this entry is already DONE,
9479 ;; do not block
9480 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9481 (member (plist-get change-plist :from)
9482 (cons 'done org-done-keywords))
9483 (member (plist-get change-plist :to)
9484 (cons 'todo org-not-done-keywords)))
9485 (throw 'dont-block t))
9486 ;; If this task has checkboxes that are not checked, it's blocked
9487 (save-excursion
9488 (org-back-to-heading t)
9489 (let ((beg (point)) end)
9490 (outline-next-heading)
9491 (setq end (point))
9492 (goto-char beg)
9493 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
9494 end t)
9495 (progn
9496 (if (boundp 'org-blocked-by-checkboxes)
9497 (setq org-blocked-by-checkboxes t))
9498 (throw 'dont-block nil)))))
9499 t)) ; do not block
9501 (defvar org-entry-property-inherited-from) ;; defined below
9502 (defun org-update-parent-todo-statistics ()
9503 "Update any statistics cookie in the parent of the current headline.
9504 When `org-hierarchical-todo-statistics' is nil, statistics will cover
9505 the entire subtree and this will travel up the hierarchy and update
9506 statistics everywhere."
9507 (interactive)
9508 (let* ((lim 0) prop
9509 (recursive (or (not org-hierarchical-todo-statistics)
9510 (string-match
9511 "\\<recursive\\>"
9512 (or (setq prop (org-entry-get
9513 nil "COOKIE_DATA" 'inherit)) ""))))
9514 (lim (or (and prop (marker-position
9515 org-entry-property-inherited-from))
9516 lim))
9517 (first t)
9518 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
9519 level ltoggle l1
9520 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
9521 (catch 'exit
9522 (save-excursion
9523 (beginning-of-line 1)
9524 (if (org-at-heading-p)
9525 (setq ltoggle (funcall outline-level))
9526 (error "This should not happen"))
9527 (while (and (setq level (org-up-heading-safe))
9528 (or recursive first)
9529 (>= (point) lim))
9530 (setq first nil)
9531 (unless (and level
9532 (not (string-match
9533 "\\<checkbox\\>"
9534 (downcase
9535 (or (org-entry-get
9536 nil "COOKIE_DATA")
9537 "")))))
9538 (throw 'exit nil))
9539 (while (re-search-forward box-re (point-at-eol) t)
9540 (setq cnt-all 0 cnt-done 0 cookie-present t)
9541 (setq is-percent (match-end 2))
9542 (save-match-data
9543 (unless (outline-next-heading) (throw 'exit nil))
9544 (while (and (looking-at org-complex-heading-regexp)
9545 (> (setq l1 (length (match-string 1))) level))
9546 (setq kwd (and (or recursive (= l1 ltoggle))
9547 (match-string 2)))
9548 (if (or (eq org-provide-todo-statistics 'all-headlines)
9549 (and (listp org-provide-todo-statistics)
9550 (or (member kwd org-provide-todo-statistics)
9551 (member kwd org-done-keywords))))
9552 (setq cnt-all (1+ cnt-all))
9553 (if (eq org-provide-todo-statistics t)
9554 (and kwd (setq cnt-all (1+ cnt-all)))))
9555 (and (member kwd org-done-keywords)
9556 (setq cnt-done (1+ cnt-done)))
9557 (outline-next-heading)))
9558 (replace-match
9559 (if is-percent
9560 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
9561 (format "[%d/%d]" cnt-done cnt-all)))))
9562 (when cookie-present
9563 (run-hook-with-args 'org-after-todo-statistics-hook
9564 cnt-done (- cnt-all cnt-done)))))
9565 (run-hooks 'org-todo-statistics-hook)))
9567 (defvar org-after-todo-statistics-hook nil
9568 "Hook that is called after a TODO statistics cookie has been updated.
9569 Each function is called with two arguments: the number of not-done entries
9570 and the number of done entries.
9572 For example, the following function, when added to this hook, will switch
9573 an entry to DONE when all children are done, and back to TODO when new
9574 entries are set to a TODO status. Note that this hook is only called
9575 when there is a statistics cookie in the headline!
9577 (defun org-summary-todo (n-done n-not-done)
9578 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
9579 (let (org-log-done org-log-states) ; turn off logging
9580 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
9583 (defvar org-todo-statistics-hook nil
9584 "Hook that is run whenever Org thinks TODO statistics should be updated.
9585 This hook runs even if there is no statisics cookie present, in which case
9586 `org-after-todo-statistics-hook' would not run.")
9588 (defun org-todo-trigger-tag-changes (state)
9589 "Apply the changes defined in `org-todo-state-tags-triggers'."
9590 (let ((l org-todo-state-tags-triggers)
9591 changes)
9592 (when (or (not state) (equal state ""))
9593 (setq changes (append changes (cdr (assoc "" l)))))
9594 (when (and (stringp state) (> (length state) 0))
9595 (setq changes (append changes (cdr (assoc state l)))))
9596 (when (member state org-not-done-keywords)
9597 (setq changes (append changes (cdr (assoc 'todo l)))))
9598 (when (member state org-done-keywords)
9599 (setq changes (append changes (cdr (assoc 'done l)))))
9600 (dolist (c changes)
9601 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
9603 (defun org-local-logging (value)
9604 "Get logging settings from a property VALUE."
9605 (let* (words w a)
9606 ;; directly set the variables, they are already local.
9607 (setq org-log-done nil
9608 org-log-repeat nil
9609 org-todo-log-states nil)
9610 (setq words (org-split-string value))
9611 (while (setq w (pop words))
9612 (cond
9613 ((setq a (assoc w org-startup-options))
9614 (and (member (nth 1 a) '(org-log-done org-log-repeat))
9615 (set (nth 1 a) (nth 2 a))))
9616 ((setq a (org-extract-log-state-settings w))
9617 (and (member (car a) org-todo-keywords-1)
9618 (push a org-todo-log-states)))))))
9620 (defun org-get-todo-sequence-head (kwd)
9621 "Return the head of the TODO sequence to which KWD belongs.
9622 If KWD is not set, check if there is a text property remembering the
9623 right sequence."
9624 (let (p)
9625 (cond
9626 ((not kwd)
9627 (or (get-text-property (point-at-bol) 'org-todo-head)
9628 (progn
9629 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
9630 nil (point-at-eol)))
9631 (get-text-property p 'org-todo-head))))
9632 ((not (member kwd org-todo-keywords-1))
9633 (car org-todo-keywords-1))
9634 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
9636 (defun org-fast-todo-selection ()
9637 "Fast TODO keyword selection with single keys.
9638 Returns the new TODO keyword, or nil if no state change should occur."
9639 (let* ((fulltable org-todo-key-alist)
9640 (done-keywords org-done-keywords) ;; needed for the faces.
9641 (maxlen (apply 'max (mapcar
9642 (lambda (x)
9643 (if (stringp (car x)) (string-width (car x)) 0))
9644 fulltable)))
9645 (expert nil)
9646 (fwidth (+ maxlen 3 1 3))
9647 (ncol (/ (- (window-width) 4) fwidth))
9648 tg cnt e c tbl
9649 groups ingroup)
9650 (save-excursion
9651 (save-window-excursion
9652 (if expert
9653 (set-buffer (get-buffer-create " *Org todo*"))
9654 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
9655 (erase-buffer)
9656 (org-set-local 'org-done-keywords done-keywords)
9657 (setq tbl fulltable cnt 0)
9658 (while (setq e (pop tbl))
9659 (cond
9660 ((equal e '(:startgroup))
9661 (push '() groups) (setq ingroup t)
9662 (when (not (= cnt 0))
9663 (setq cnt 0)
9664 (insert "\n"))
9665 (insert "{ "))
9666 ((equal e '(:endgroup))
9667 (setq ingroup nil cnt 0)
9668 (insert "}\n"))
9669 ((equal e '(:newline))
9670 (when (not (= cnt 0))
9671 (setq cnt 0)
9672 (insert "\n")
9673 (setq e (car tbl))
9674 (while (equal (car tbl) '(:newline))
9675 (insert "\n")
9676 (setq tbl (cdr tbl)))))
9678 (setq tg (car e) c (cdr e))
9679 (if ingroup (push tg (car groups)))
9680 (setq tg (org-add-props tg nil 'face
9681 (org-get-todo-face tg)))
9682 (if (and (= cnt 0) (not ingroup)) (insert " "))
9683 (insert "[" c "] " tg (make-string
9684 (- fwidth 4 (length tg)) ?\ ))
9685 (when (= (setq cnt (1+ cnt)) ncol)
9686 (insert "\n")
9687 (if ingroup (insert " "))
9688 (setq cnt 0)))))
9689 (insert "\n")
9690 (goto-char (point-min))
9691 (if (not expert) (org-fit-window-to-buffer))
9692 (message "[a-z..]:Set [SPC]:clear")
9693 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9694 (cond
9695 ((or (= c ?\C-g)
9696 (and (= c ?q) (not (rassoc c fulltable))))
9697 (setq quit-flag t))
9698 ((= c ?\ ) nil)
9699 ((setq e (rassoc c fulltable) tg (car e))
9701 (t (setq quit-flag t)))))))
9703 (defun org-entry-is-todo-p ()
9704 (member (org-get-todo-state) org-not-done-keywords))
9706 (defun org-entry-is-done-p ()
9707 (member (org-get-todo-state) org-done-keywords))
9709 (defun org-get-todo-state ()
9710 (save-excursion
9711 (org-back-to-heading t)
9712 (and (looking-at org-todo-line-regexp)
9713 (match-end 2)
9714 (match-string 2))))
9716 (defun org-at-date-range-p (&optional inactive-ok)
9717 "Is the cursor inside a date range?"
9718 (interactive)
9719 (save-excursion
9720 (catch 'exit
9721 (let ((pos (point)))
9722 (skip-chars-backward "^[<\r\n")
9723 (skip-chars-backward "<[")
9724 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9725 (>= (match-end 0) pos)
9726 (throw 'exit t))
9727 (skip-chars-backward "^<[\r\n")
9728 (skip-chars-backward "<[")
9729 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9730 (>= (match-end 0) pos)
9731 (throw 'exit t)))
9732 nil)))
9734 (defun org-get-repeat ()
9735 "Check if there is a deadline/schedule with repeater in this entry."
9736 (save-match-data
9737 (save-excursion
9738 (org-back-to-heading t)
9739 (if (re-search-forward
9740 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9741 (match-string 1)))))
9743 (defvar org-last-changed-timestamp)
9744 (defvar org-last-inserted-timestamp)
9745 (defvar org-log-post-message)
9746 (defvar org-log-note-purpose)
9747 (defvar org-log-note-how)
9748 (defvar org-log-note-extra)
9749 (defun org-auto-repeat-maybe (done-word)
9750 "Check if the current headline contains a repeated deadline/schedule.
9751 If yes, set TODO state back to what it was and change the base date
9752 of repeating deadline/scheduled time stamps to new date.
9753 This function is run automatically after each state change to a DONE state."
9754 ;; last-state is dynamically scoped into this function
9755 (let* ((repeat (org-get-repeat))
9756 (aa (assoc last-state org-todo-kwd-alist))
9757 (interpret (nth 1 aa))
9758 (head (nth 2 aa))
9759 (whata '(("d" . day) ("m" . month) ("y" . year)))
9760 (msg "Entry repeats: ")
9761 (org-log-done nil)
9762 (org-todo-log-states nil)
9763 (nshiftmax 10) (nshift 0)
9764 re type n what ts time)
9765 (when repeat
9766 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9767 (org-todo (if (eq interpret 'type) last-state head))
9768 (org-entry-put nil "LAST_REPEAT" (format-time-string
9769 (org-time-stamp-format t t)))
9770 (when org-log-repeat
9771 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9772 (memq 'org-add-log-note post-command-hook))
9773 ;; OK, we are already setup for some record
9774 (if (eq org-log-repeat 'note)
9775 ;; make sure we take a note, not only a time stamp
9776 (setq org-log-note-how 'note))
9777 ;; Set up for taking a record
9778 (org-add-log-setup 'state (or done-word (car org-done-keywords))
9779 last-state
9780 'findpos org-log-repeat)))
9781 (org-back-to-heading t)
9782 (org-add-planning-info nil nil 'closed)
9783 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9784 org-deadline-time-regexp "\\)\\|\\("
9785 org-ts-regexp "\\)"))
9786 (while (re-search-forward
9787 re (save-excursion (outline-next-heading) (point)) t)
9788 (setq type (if (match-end 1) org-scheduled-string
9789 (if (match-end 3) org-deadline-string "Plain:"))
9790 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
9791 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
9792 (setq n (string-to-number (match-string 2 ts))
9793 what (match-string 3 ts))
9794 (if (equal what "w") (setq n (* n 7) what "d"))
9795 ;; Preparation, see if we need to modify the start date for the change
9796 (when (match-end 1)
9797 (setq time (save-match-data (org-time-string-to-time ts)))
9798 (cond
9799 ((equal (match-string 1 ts) ".")
9800 ;; Shift starting date to today
9801 (org-timestamp-change
9802 (- (time-to-days (current-time)) (time-to-days time))
9803 'day))
9804 ((equal (match-string 1 ts) "+")
9805 (while (or (= nshift 0)
9806 (<= (time-to-days time) (time-to-days (current-time))))
9807 (when (= (incf nshift) nshiftmax)
9808 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
9809 (error "Abort")))
9810 (org-timestamp-change n (cdr (assoc what whata)))
9811 (org-at-timestamp-p t)
9812 (setq ts (match-string 1))
9813 (setq time (save-match-data (org-time-string-to-time ts))))
9814 (org-timestamp-change (- n) (cdr (assoc what whata)))
9815 ;; rematch, so that we have everything in place for the real shift
9816 (org-at-timestamp-p t)
9817 (setq ts (match-string 1))
9818 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
9819 (org-timestamp-change n (cdr (assoc what whata)))
9820 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
9821 (setq org-log-post-message msg)
9822 (message "%s" msg))))
9824 (defun org-show-todo-tree (arg)
9825 "Make a compact tree which shows all headlines marked with TODO.
9826 The tree will show the lines where the regexp matches, and all higher
9827 headlines above the match.
9828 With a \\[universal-argument] prefix, prompt for a regexp to match.
9829 With a numeric prefix N, construct a sparse tree for the Nth element
9830 of `org-todo-keywords-1'."
9831 (interactive "P")
9832 (let ((case-fold-search nil)
9833 (kwd-re
9834 (cond ((null arg) org-not-done-regexp)
9835 ((equal arg '(4))
9836 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
9837 (mapcar 'list org-todo-keywords-1))))
9838 (concat "\\("
9839 (mapconcat 'identity (org-split-string kwd "|") "\\|")
9840 "\\)\\>")))
9841 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
9842 (regexp-quote (nth (1- (prefix-numeric-value arg))
9843 org-todo-keywords-1)))
9844 (t (error "Invalid prefix argument: %s" arg)))))
9845 (message "%d TODO entries found"
9846 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
9848 (defun org-deadline (&optional remove time)
9849 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
9850 With argument REMOVE, remove any deadline from the item.
9851 When TIME is set, it should be an internal time specification, and the
9852 scheduling will use the corresponding date."
9853 (interactive "P")
9854 (if remove
9855 (progn
9856 (org-remove-timestamp-with-keyword org-deadline-string)
9857 (message "Item no longer has a deadline."))
9858 (if (org-get-repeat)
9859 (error "Cannot change deadline on task with repeater, please do that by hand")
9860 (org-add-planning-info 'deadline time 'closed)
9861 (message "Deadline on %s" org-last-inserted-timestamp))))
9863 (defun org-schedule (&optional remove time)
9864 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
9865 With argument REMOVE, remove any scheduling date from the item.
9866 When TIME is set, it should be an internal time specification, and the
9867 scheduling will use the corresponding date."
9868 (interactive "P")
9869 (if remove
9870 (progn
9871 (org-remove-timestamp-with-keyword org-scheduled-string)
9872 (message "Item is no longer scheduled."))
9873 (if (org-get-repeat)
9874 (error "Cannot reschedule task with repeater, please do that by hand")
9875 (org-add-planning-info 'scheduled time 'closed)
9876 (message "Scheduled to %s" org-last-inserted-timestamp))))
9878 (defun org-get-scheduled-time (pom &optional inherit)
9879 "Get the scheduled time as a time tuple, of a format suitable
9880 for calling org-schedule with, or if there is no scheduling,
9881 returns nil."
9882 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
9883 (when time
9884 (apply 'encode-time (org-parse-time-string time)))))
9886 (defun org-get-deadline-time (pom &optional inherit)
9887 "Get the deadine as a time tuple, of a format suitable for
9888 calling org-deadlin with, or if there is no scheduling, returns
9889 nil."
9890 (let ((time (org-entry-get pom "DEADLINE" inherit)))
9891 (when time
9892 (apply 'encode-time (org-parse-time-string time)))))
9894 (defun org-remove-timestamp-with-keyword (keyword)
9895 "Remove all time stamps with KEYWORD in the current entry."
9896 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
9897 beg)
9898 (save-excursion
9899 (org-back-to-heading t)
9900 (setq beg (point))
9901 (org-end-of-subtree t t)
9902 (while (re-search-backward re beg t)
9903 (replace-match "")
9904 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9905 (equal (char-before) ?\ ))
9906 (backward-delete-char 1)
9907 (if (string-match "^[ \t]*$" (buffer-substring
9908 (point-at-bol) (point-at-eol)))
9909 (delete-region (point-at-bol)
9910 (min (point-max) (1+ (point-at-eol))))))))))
9912 (defun org-add-planning-info (what &optional time &rest remove)
9913 "Insert new timestamp with keyword in the line directly after the headline.
9914 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9915 If non is given, the user is prompted for a date.
9916 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9917 be removed."
9918 (interactive)
9919 (let (org-time-was-given org-end-time-was-given ts
9920 end default-time default-input)
9922 (catch 'exit
9923 (when (and (not time) (memq what '(scheduled deadline)))
9924 ;; Try to get a default date/time from existing timestamp
9925 (save-excursion
9926 (org-back-to-heading t)
9927 (setq end (save-excursion (outline-next-heading) (point)))
9928 (when (re-search-forward (if (eq what 'scheduled)
9929 org-scheduled-time-regexp
9930 org-deadline-time-regexp)
9931 end t)
9932 (setq ts (match-string 1)
9933 default-time
9934 (apply 'encode-time (org-parse-time-string ts))
9935 default-input (and ts (org-get-compact-tod ts))))))
9936 (when what
9937 ;; If necessary, get the time from the user
9938 (setq time (or time (org-read-date nil 'to-time nil nil
9939 default-time default-input))))
9941 (when (and org-insert-labeled-timestamps-at-point
9942 (member what '(scheduled deadline)))
9943 (insert
9944 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9945 (org-insert-time-stamp time org-time-was-given
9946 nil nil nil (list org-end-time-was-given))
9947 (setq what nil))
9948 (save-excursion
9949 (save-restriction
9950 (let (col list elt ts buffer-invisibility-spec)
9951 (org-back-to-heading t)
9952 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9953 (goto-char (match-end 1))
9954 (setq col (current-column))
9955 (goto-char (match-end 0))
9956 (if (eobp) (insert "\n") (forward-char 1))
9957 (when (and (not what)
9958 (not (looking-at
9959 (concat "[ \t]*"
9960 org-keyword-time-not-clock-regexp))))
9961 ;; Nothing to add, nothing to remove...... :-)
9962 (throw 'exit nil))
9963 (if (and (not (looking-at outline-regexp))
9964 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9965 "[^\r\n]*"))
9966 (not (equal (match-string 1) org-clock-string)))
9967 (narrow-to-region (match-beginning 0) (match-end 0))
9968 (insert-before-markers "\n")
9969 (backward-char 1)
9970 (narrow-to-region (point) (point))
9971 (and org-adapt-indentation (org-indent-to-column col)))
9972 ;; Check if we have to remove something.
9973 (setq list (cons what remove))
9974 (while list
9975 (setq elt (pop list))
9976 (goto-char (point-min))
9977 (when (or (and (eq elt 'scheduled)
9978 (re-search-forward org-scheduled-time-regexp nil t))
9979 (and (eq elt 'deadline)
9980 (re-search-forward org-deadline-time-regexp nil t))
9981 (and (eq elt 'closed)
9982 (re-search-forward org-closed-time-regexp nil t)))
9983 (replace-match "")
9984 (if (looking-at "--+<[^>]+>") (replace-match ""))
9985 (if (looking-at " +") (replace-match ""))))
9986 (goto-char (point-max))
9987 (when what
9988 (insert
9989 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9990 (cond ((eq what 'scheduled) org-scheduled-string)
9991 ((eq what 'deadline) org-deadline-string)
9992 ((eq what 'closed) org-closed-string))
9993 " ")
9994 (setq ts (org-insert-time-stamp
9995 time
9996 (or org-time-was-given
9997 (and (eq what 'closed) org-log-done-with-time))
9998 (eq what 'closed)
9999 nil nil (list org-end-time-was-given)))
10000 (end-of-line 1))
10001 (goto-char (point-min))
10002 (widen)
10003 (if (and (looking-at "[ \t]+\n")
10004 (equal (char-before) ?\n))
10005 (delete-region (1- (point)) (point-at-eol)))
10006 ts))))))
10008 (defvar org-log-note-marker (make-marker))
10009 (defvar org-log-note-purpose nil)
10010 (defvar org-log-note-state nil)
10011 (defvar org-log-note-previous-state nil)
10012 (defvar org-log-note-how nil)
10013 (defvar org-log-note-extra nil)
10014 (defvar org-log-note-window-configuration nil)
10015 (defvar org-log-note-return-to (make-marker))
10016 (defvar org-log-post-message nil
10017 "Message to be displayed after a log note has been stored.
10018 The auto-repeater uses this.")
10020 (defun org-add-note ()
10021 "Add a note to the current entry.
10022 This is done in the same way as adding a state change note."
10023 (interactive)
10024 (org-add-log-setup 'note nil nil 'findpos nil))
10026 (defvar org-property-end-re)
10027 (defun org-add-log-setup (&optional purpose state prev-state
10028 findpos how &optional extra)
10029 "Set up the post command hook to take a note.
10030 If this is about to TODO state change, the new state is expected in STATE.
10031 When FINDPOS is non-nil, find the correct position for the note in
10032 the current entry. If not, assume that it can be inserted at point.
10033 HOW is an indicator what kind of note should be created.
10034 EXTRA is additional text that will be inserted into the notes buffer."
10035 (let* ((org-log-into-drawer (org-log-into-drawer))
10036 (drawer (cond ((stringp org-log-into-drawer)
10037 org-log-into-drawer)
10038 (org-log-into-drawer "LOGBOOK")
10039 (t nil))))
10040 (save-restriction
10041 (save-excursion
10042 (when findpos
10043 (org-back-to-heading t)
10044 (narrow-to-region (point) (save-excursion
10045 (outline-next-heading) (point)))
10046 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
10047 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
10048 "[^\r\n]*\\)?"))
10049 (goto-char (match-end 0))
10050 (cond
10051 (drawer
10052 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
10053 nil t)
10054 (progn
10055 (goto-char (match-end 0))
10056 (or org-log-states-order-reversed
10057 (and (re-search-forward org-property-end-re nil t)
10058 (goto-char (1- (match-beginning 0))))))
10059 (insert "\n:" drawer ":\n:END:")
10060 (beginning-of-line 0)
10061 (org-indent-line-function)
10062 (beginning-of-line 2)
10063 (org-indent-line-function)
10064 (end-of-line 0)))
10065 ((and org-log-state-notes-insert-after-drawers
10066 (save-excursion
10067 (forward-line) (looking-at org-drawer-regexp)))
10068 (forward-line)
10069 (while (looking-at org-drawer-regexp)
10070 (goto-char (match-end 0))
10071 (re-search-forward org-property-end-re (point-max) t)
10072 (forward-line))
10073 (forward-line -1)))
10074 (unless org-log-states-order-reversed
10075 (and (= (char-after) ?\n) (forward-char 1))
10076 (org-skip-over-state-notes)
10077 (skip-chars-backward " \t\n\r")))
10078 (move-marker org-log-note-marker (point))
10079 (setq org-log-note-purpose purpose
10080 org-log-note-state state
10081 org-log-note-previous-state prev-state
10082 org-log-note-how how
10083 org-log-note-extra extra)
10084 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
10086 (defun org-skip-over-state-notes ()
10087 "Skip past the list of State notes in an entry."
10088 (if (looking-at "\n[ \t]*- State") (forward-char 1))
10089 (while (looking-at "[ \t]*- State")
10090 (condition-case nil
10091 (org-next-item)
10092 (error (org-end-of-item)))))
10094 (defun org-add-log-note (&optional purpose)
10095 "Pop up a window for taking a note, and add this note later at point."
10096 (remove-hook 'post-command-hook 'org-add-log-note)
10097 (setq org-log-note-window-configuration (current-window-configuration))
10098 (delete-other-windows)
10099 (move-marker org-log-note-return-to (point))
10100 (switch-to-buffer (marker-buffer org-log-note-marker))
10101 (goto-char org-log-note-marker)
10102 (org-switch-to-buffer-other-window "*Org Note*")
10103 (erase-buffer)
10104 (if (memq org-log-note-how '(time state))
10105 (let (current-prefix-arg) (org-store-log-note))
10106 (let ((org-inhibit-startup t)) (org-mode))
10107 (insert (format "# Insert note for %s.
10108 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10109 (cond
10110 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10111 ((eq org-log-note-purpose 'done) "closed todo item")
10112 ((eq org-log-note-purpose 'state)
10113 (format "state change from \"%s\" to \"%s\""
10114 (or org-log-note-previous-state "")
10115 (or org-log-note-state "")))
10116 ((eq org-log-note-purpose 'note)
10117 "this entry")
10118 (t (error "This should not happen")))))
10119 (if org-log-note-extra (insert org-log-note-extra))
10120 (org-set-local 'org-finish-function 'org-store-log-note)))
10122 (defvar org-note-abort nil) ; dynamically scoped
10123 (defun org-store-log-note ()
10124 "Finish taking a log note, and insert it to where it belongs."
10125 (let ((txt (buffer-string))
10126 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10127 lines ind)
10128 (kill-buffer (current-buffer))
10129 (while (string-match "\\`#.*\n[ \t\n]*" txt)
10130 (setq txt (replace-match "" t t txt)))
10131 (if (string-match "\\s-+\\'" txt)
10132 (setq txt (replace-match "" t t txt)))
10133 (setq lines (org-split-string txt "\n"))
10134 (when (and note (string-match "\\S-" note))
10135 (setq note
10136 (org-replace-escapes
10137 note
10138 (list (cons "%u" (user-login-name))
10139 (cons "%U" user-full-name)
10140 (cons "%t" (format-time-string
10141 (org-time-stamp-format 'long 'inactive)
10142 (current-time)))
10143 (cons "%s" (if org-log-note-state
10144 (concat "\"" org-log-note-state "\"")
10145 ""))
10146 (cons "%S" (if org-log-note-previous-state
10147 (concat "\"" org-log-note-previous-state "\"")
10148 "\"\"")))))
10149 (if lines (setq note (concat note " \\\\")))
10150 (push note lines))
10151 (when (or current-prefix-arg org-note-abort)
10152 (when org-log-into-drawer
10153 (org-remove-empty-drawer-at
10154 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
10155 org-log-note-marker))
10156 (setq lines nil))
10157 (when lines
10158 (save-excursion
10159 (set-buffer (marker-buffer org-log-note-marker))
10160 (save-excursion
10161 (goto-char org-log-note-marker)
10162 (move-marker org-log-note-marker nil)
10163 (end-of-line 1)
10164 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
10165 (insert "- " (pop lines))
10166 (org-indent-line-function)
10167 (beginning-of-line 1)
10168 (looking-at "[ \t]*")
10169 (setq ind (concat (match-string 0) " "))
10170 (end-of-line 1)
10171 (while lines (insert "\n" ind (pop lines)))
10172 (message "Note stored")
10173 (org-back-to-heading t)
10174 (org-cycle-hide-drawers 'children)))))
10175 (set-window-configuration org-log-note-window-configuration)
10176 (with-current-buffer (marker-buffer org-log-note-return-to)
10177 (goto-char org-log-note-return-to))
10178 (move-marker org-log-note-return-to nil)
10179 (and org-log-post-message (message "%s" org-log-post-message)))
10181 (defun org-remove-empty-drawer-at (drawer pos)
10182 "Remove an emptyr DARWER drawer at position POS.
10183 POS may also be a marker."
10184 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
10185 (save-excursion
10186 (save-restriction
10187 (widen)
10188 (goto-char pos)
10189 (if (org-in-regexp
10190 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
10191 (replace-match ""))))))
10193 (defun org-sparse-tree (&optional arg)
10194 "Create a sparse tree, prompt for the details.
10195 This command can create sparse trees. You first need to select the type
10196 of match used to create the tree:
10198 t Show entries with a specific TODO keyword.
10199 m Show entries selected by a tags/property match.
10200 p Enter a property name and its value (both with completion on existing
10201 names/values) and show entries with that property.
10202 r Show entries matching a regular expression.
10203 d Show deadlines due within `org-deadline-warning-days'.
10204 b Show deadlines and scheduled items before a date.
10205 a Show deadlines and scheduled items after a date."
10206 (interactive "P")
10207 (let (ans kwd value)
10208 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
10209 (setq ans (read-char-exclusive))
10210 (cond
10211 ((equal ans ?d)
10212 (call-interactively 'org-check-deadlines))
10213 ((equal ans ?b)
10214 (call-interactively 'org-check-before-date))
10215 ((equal ans ?a)
10216 (call-interactively 'org-check-after-date))
10217 ((equal ans ?t)
10218 (org-show-todo-tree '(4)))
10219 ((member ans '(?T ?m))
10220 (call-interactively 'org-match-sparse-tree))
10221 ((member ans '(?p ?P))
10222 (setq kwd (org-ido-completing-read "Property: "
10223 (mapcar 'list (org-buffer-property-keys))))
10224 (setq value (org-ido-completing-read "Value: "
10225 (mapcar 'list (org-property-values kwd))))
10226 (unless (string-match "\\`{.*}\\'" value)
10227 (setq value (concat "\"" value "\"")))
10228 (org-match-sparse-tree arg (concat kwd "=" value)))
10229 ((member ans '(?r ?R ?/))
10230 (call-interactively 'org-occur))
10231 (t (error "No such sparse tree command \"%c\"" ans)))))
10233 (defvar org-occur-highlights nil
10234 "List of overlays used for occur matches.")
10235 (make-variable-buffer-local 'org-occur-highlights)
10236 (defvar org-occur-parameters nil
10237 "Parameters of the active org-occur calls.
10238 This is a list, each call to org-occur pushes as cons cell,
10239 containing the regular expression and the callback, onto the list.
10240 The list can contain several entries if `org-occur' has been called
10241 several time with the KEEP-PREVIOUS argument. Otherwise, this list
10242 will only contain one set of parameters. When the highlights are
10243 removed (for example with `C-c C-c', or with the next edit (depending
10244 on `org-remove-highlights-with-change'), this variable is emptied
10245 as well.")
10246 (make-variable-buffer-local 'org-occur-parameters)
10248 (defun org-occur (regexp &optional keep-previous callback)
10249 "Make a compact tree which shows all matches of REGEXP.
10250 The tree will show the lines where the regexp matches, and all higher
10251 headlines above the match. It will also show the heading after the match,
10252 to make sure editing the matching entry is easy.
10253 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
10254 call to `org-occur' will be kept, to allow stacking of calls to this
10255 command.
10256 If CALLBACK is non-nil, it is a function which is called to confirm
10257 that the match should indeed be shown."
10258 (interactive "sRegexp: \nP")
10259 (when (equal regexp "")
10260 (error "Regexp cannot be empty"))
10261 (unless keep-previous
10262 (org-remove-occur-highlights nil nil t))
10263 (push (cons regexp callback) org-occur-parameters)
10264 (let ((cnt 0))
10265 (save-excursion
10266 (goto-char (point-min))
10267 (if (or (not keep-previous) ; do not want to keep
10268 (not org-occur-highlights)) ; no previous matches
10269 ;; hide everything
10270 (org-overview))
10271 (while (re-search-forward regexp nil t)
10272 (when (or (not callback)
10273 (save-match-data (funcall callback)))
10274 (setq cnt (1+ cnt))
10275 (when org-highlight-sparse-tree-matches
10276 (org-highlight-new-match (match-beginning 0) (match-end 0)))
10277 (org-show-context 'occur-tree))))
10278 (when org-remove-highlights-with-change
10279 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10280 nil 'local))
10281 (unless org-sparse-tree-open-archived-trees
10282 (org-hide-archived-subtrees (point-min) (point-max)))
10283 (run-hooks 'org-occur-hook)
10284 (if (interactive-p)
10285 (message "%d match(es) for regexp %s" cnt regexp))
10286 cnt))
10288 (defun org-show-context (&optional key)
10289 "Make sure point and context and visible.
10290 How much context is shown depends upon the variables
10291 `org-show-hierarchy-above', `org-show-following-heading'. and
10292 `org-show-siblings'."
10293 (let ((heading-p (org-on-heading-p t))
10294 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
10295 (following-p (org-get-alist-option org-show-following-heading key))
10296 (entry-p (org-get-alist-option org-show-entry-below key))
10297 (siblings-p (org-get-alist-option org-show-siblings key)))
10298 (catch 'exit
10299 ;; Show heading or entry text
10300 (if (and heading-p (not entry-p))
10301 (org-flag-heading nil) ; only show the heading
10302 (and (or entry-p (org-invisible-p) (org-invisible-p2))
10303 (org-show-hidden-entry))) ; show entire entry
10304 (when following-p
10305 ;; Show next sibling, or heading below text
10306 (save-excursion
10307 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10308 (org-flag-heading nil))))
10309 (when siblings-p (org-show-siblings))
10310 (when hierarchy-p
10311 ;; show all higher headings, possibly with siblings
10312 (save-excursion
10313 (while (and (condition-case nil
10314 (progn (org-up-heading-all 1) t)
10315 (error nil))
10316 (not (bobp)))
10317 (org-flag-heading nil)
10318 (when siblings-p (org-show-siblings))))))))
10320 (defun org-reveal (&optional siblings)
10321 "Show current entry, hierarchy above it, and the following headline.
10322 This can be used to show a consistent set of context around locations
10323 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10324 not t for the search context.
10326 With optional argument SIBLINGS, on each level of the hierarchy all
10327 siblings are shown. This repairs the tree structure to what it would
10328 look like when opened with hierarchical calls to `org-cycle'."
10329 (interactive "P")
10330 (let ((org-show-hierarchy-above t)
10331 (org-show-following-heading t)
10332 (org-show-siblings (if siblings t org-show-siblings)))
10333 (org-show-context nil)))
10335 (defun org-highlight-new-match (beg end)
10336 "Highlight from BEG to END and mark the highlight is an occur headline."
10337 (let ((ov (org-make-overlay beg end)))
10338 (org-overlay-put ov 'face 'secondary-selection)
10339 (push ov org-occur-highlights)))
10341 (defun org-remove-occur-highlights (&optional beg end noremove)
10342 "Remove the occur highlights from the buffer.
10343 BEG and END are ignored. If NOREMOVE is nil, remove this function
10344 from the `before-change-functions' in the current buffer."
10345 (interactive)
10346 (unless org-inhibit-highlight-removal
10347 (mapc 'org-delete-overlay org-occur-highlights)
10348 (setq org-occur-highlights nil)
10349 (setq org-occur-parameters nil)
10350 (unless noremove
10351 (remove-hook 'before-change-functions
10352 'org-remove-occur-highlights 'local))))
10354 ;;;; Priorities
10356 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
10357 "Regular expression matching the priority indicator.")
10359 (defvar org-remove-priority-next-time nil)
10361 (defun org-priority-up ()
10362 "Increase the priority of the current item."
10363 (interactive)
10364 (org-priority 'up))
10366 (defun org-priority-down ()
10367 "Decrease the priority of the current item."
10368 (interactive)
10369 (org-priority 'down))
10371 (defun org-priority (&optional action)
10372 "Change the priority of an item by ARG.
10373 ACTION can be `set', `up', `down', or a character."
10374 (interactive)
10375 (unless org-enable-priority-commands
10376 (error "Priority commands are disabled"))
10377 (setq action (or action 'set))
10378 (let (current new news have remove)
10379 (save-excursion
10380 (org-back-to-heading t)
10381 (if (looking-at org-priority-regexp)
10382 (setq current (string-to-char (match-string 2))
10383 have t)
10384 (setq current org-default-priority))
10385 (cond
10386 ((or (eq action 'set)
10387 (if (featurep 'xemacs) (characterp action) (integerp action)))
10388 (if (not (eq action 'set))
10389 (setq new action)
10390 (message "Priority %c-%c, SPC to remove: "
10391 org-highest-priority org-lowest-priority)
10392 (setq new (read-char-exclusive)))
10393 (if (and (= (upcase org-highest-priority) org-highest-priority)
10394 (= (upcase org-lowest-priority) org-lowest-priority))
10395 (setq new (upcase new)))
10396 (cond ((equal new ?\ ) (setq remove t))
10397 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
10398 (error "Priority must be between `%c' and `%c'"
10399 org-highest-priority org-lowest-priority))))
10400 ((eq action 'up)
10401 (if (and (not have) (eq last-command this-command))
10402 (setq new org-lowest-priority)
10403 (setq new (if (and org-priority-start-cycle-with-default (not have))
10404 org-default-priority (1- current)))))
10405 ((eq action 'down)
10406 (if (and (not have) (eq last-command this-command))
10407 (setq new org-highest-priority)
10408 (setq new (if (and org-priority-start-cycle-with-default (not have))
10409 org-default-priority (1+ current)))))
10410 (t (error "Invalid action")))
10411 (if (or (< (upcase new) org-highest-priority)
10412 (> (upcase new) org-lowest-priority))
10413 (setq remove t))
10414 (setq news (format "%c" new))
10415 (if have
10416 (if remove
10417 (replace-match "" t t nil 1)
10418 (replace-match news t t nil 2))
10419 (if remove
10420 (error "No priority cookie found in line")
10421 (let ((case-fold-search nil))
10422 (looking-at org-todo-line-regexp))
10423 (if (match-end 2)
10424 (progn
10425 (goto-char (match-end 2))
10426 (insert " [#" news "]"))
10427 (goto-char (match-beginning 3))
10428 (insert "[#" news "] "))))
10429 (org-preserve-lc (org-set-tags nil 'align)))
10430 (if remove
10431 (message "Priority removed")
10432 (message "Priority of current item set to %s" news))))
10434 (defun org-get-priority (s)
10435 "Find priority cookie and return priority."
10436 (save-match-data
10437 (if (not (string-match org-priority-regexp s))
10438 (* 1000 (- org-lowest-priority org-default-priority))
10439 (* 1000 (- org-lowest-priority
10440 (string-to-char (match-string 2 s)))))))
10442 ;;;; Tags
10444 (defvar org-agenda-archives-mode)
10445 (defvar org-map-continue-from nil
10446 "Position from where mapping should continue.
10447 Can be set byt the action argument to `org-scan-tag's and `org-map-entries'.")
10449 (defvar org-scanner-tags nil
10450 "The current tag list while the tags scanner is running.")
10451 (defvar org-trust-scanner-tags nil
10452 "Should `org-get-tags-at' use the tags fro the scanner.
10453 This is for internal dynamical scoping only.
10454 When this is non-nil, the function `org-get-tags-at' will return the value
10455 of `org-scanner-tags' instead of building the list by itself. This
10456 can lead to large speed-ups when the tags scanner is used in a file with
10457 many entries, and when the list of tags is retrieved, for example to
10458 obtain a list of properties. Building the tags list for each entry in such
10459 a file becomes an N^2 operation - but with this variable set, it scales
10460 as N.")
10462 (defun org-scan-tags (action matcher &optional todo-only)
10463 "Scan headline tags with inheritance and produce output ACTION.
10465 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
10466 or `agenda' to produce an entry list for an agenda view. It can also be
10467 a Lisp form or a function that should be called at each matched headline, in
10468 this case the return value is a list of all return values from these calls.
10470 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
10471 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
10472 only lines with a TODO keyword are included in the output."
10473 (require 'org-agenda)
10474 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
10475 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
10476 (org-re
10477 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
10478 (props (list 'face 'default
10479 'done-face 'org-agenda-done
10480 'undone-face 'default
10481 'mouse-face 'highlight
10482 'org-not-done-regexp org-not-done-regexp
10483 'org-todo-regexp org-todo-regexp
10484 'keymap org-agenda-keymap
10485 'help-echo
10486 (format "mouse-2 or RET jump to org file %s"
10487 (abbreviate-file-name
10488 (or (buffer-file-name (buffer-base-buffer))
10489 (buffer-name (buffer-base-buffer)))))))
10490 (case-fold-search nil)
10491 (org-map-continue-from nil)
10492 lspos tags tags-list
10493 (tags-alist (list (cons 0 org-file-tags)))
10494 (llast 0) rtn rtn1 level category i txt
10495 todo marker entry priority)
10496 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
10497 (setq action (list 'lambda nil action)))
10498 (save-excursion
10499 (goto-char (point-min))
10500 (when (eq action 'sparse-tree)
10501 (org-overview)
10502 (org-remove-occur-highlights))
10503 (while (re-search-forward re nil t)
10504 (catch :skip
10505 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
10506 tags (if (match-end 4) (org-match-string-no-properties 4)))
10507 (goto-char (setq lspos (match-beginning 0)))
10508 (setq level (org-reduced-level (funcall outline-level))
10509 category (org-get-category))
10510 (setq i llast llast level)
10511 ;; remove tag lists from same and sublevels
10512 (while (>= i level)
10513 (when (setq entry (assoc i tags-alist))
10514 (setq tags-alist (delete entry tags-alist)))
10515 (setq i (1- i)))
10516 ;; add the next tags
10517 (when tags
10518 (setq tags (org-split-string tags ":")
10519 tags-alist
10520 (cons (cons level tags) tags-alist)))
10521 ;; compile tags for current headline
10522 (setq tags-list
10523 (if org-use-tag-inheritance
10524 (apply 'append (mapcar 'cdr (reverse tags-alist)))
10525 tags)
10526 org-scanner-tags tags-list)
10527 (when org-use-tag-inheritance
10528 (setcdr (car tags-alist)
10529 (mapcar (lambda (x)
10530 (setq x (copy-sequence x))
10531 (org-add-prop-inherited x))
10532 (cdar tags-alist))))
10533 (when (and tags org-use-tag-inheritance
10534 (or (not (eq t org-use-tag-inheritance))
10535 org-tags-exclude-from-inheritance))
10536 ;; selective inheritance, remove uninherited ones
10537 (setcdr (car tags-alist)
10538 (org-remove-uniherited-tags (cdar tags-alist))))
10539 (when (and (or (not todo-only)
10540 (and (member todo org-not-done-keywords)
10541 (or (not org-agenda-tags-todo-honor-ignore-options)
10542 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
10543 (let ((case-fold-search t)) (eval matcher))
10545 (not (member org-archive-tag tags-list))
10546 ;; we have an archive tag, should we use this anyway?
10547 (or (not org-agenda-skip-archived-trees)
10548 (and (eq action 'agenda) org-agenda-archives-mode))))
10549 (unless (eq action 'sparse-tree) (org-agenda-skip))
10551 ;; select this headline
10553 (cond
10554 ((eq action 'sparse-tree)
10555 (and org-highlight-sparse-tree-matches
10556 (org-get-heading) (match-end 0)
10557 (org-highlight-new-match
10558 (match-beginning 0) (match-beginning 1)))
10559 (org-show-context 'tags-tree))
10560 ((eq action 'agenda)
10561 (setq txt (org-format-agenda-item
10563 (concat
10564 (if (eq org-tags-match-list-sublevels 'indented)
10565 (make-string (1- level) ?.) "")
10566 (org-get-heading))
10567 category
10568 tags-list
10570 priority (org-get-priority txt))
10571 (goto-char lspos)
10572 (setq marker (org-agenda-new-marker))
10573 (org-add-props txt props
10574 'org-marker marker 'org-hd-marker marker 'org-category category
10575 'todo-state todo
10576 'priority priority 'type "tagsmatch")
10577 (push txt rtn))
10578 ((functionp action)
10579 (setq org-map-continue-from nil)
10580 (save-excursion
10581 (setq rtn1 (funcall action))
10582 (push rtn1 rtn)))
10583 (t (error "Invalid action")))
10585 ;; if we are to skip sublevels, jump to end of subtree
10586 (unless org-tags-match-list-sublevels
10587 (org-end-of-subtree t)
10588 (backward-char 1))))
10589 ;; Get the correct position from where to continue
10590 (if org-map-continue-from
10591 (goto-char org-map-continue-from)
10592 (and (= (point) lspos) (end-of-line 1)))))
10593 (when (and (eq action 'sparse-tree)
10594 (not org-sparse-tree-open-archived-trees))
10595 (org-hide-archived-subtrees (point-min) (point-max)))
10596 (nreverse rtn)))
10598 (defun org-remove-uniherited-tags (tags)
10599 "Remove all tags that are not inherited from the list TAGS."
10600 (cond
10601 ((eq org-use-tag-inheritance t)
10602 (if org-tags-exclude-from-inheritance
10603 (org-delete-all org-tags-exclude-from-inheritance tags)
10604 tags))
10605 ((not org-use-tag-inheritance) nil)
10606 ((stringp org-use-tag-inheritance)
10607 (delq nil (mapcar
10608 (lambda (x)
10609 (if (and (string-match org-use-tag-inheritance x)
10610 (not (member x org-tags-exclude-from-inheritance)))
10611 x nil))
10612 tags)))
10613 ((listp org-use-tag-inheritance)
10614 (delq nil (mapcar
10615 (lambda (x)
10616 (if (member x org-use-tag-inheritance) x nil))
10617 tags)))))
10619 (defvar todo-only) ;; dynamically scoped
10621 (defun org-match-sparse-tree (&optional todo-only match)
10622 "Create a sparse tree according to tags string MATCH.
10623 MATCH can contain positive and negative selection of tags, like
10624 \"+WORK+URGENT-WITHBOSS\".
10625 If optional argument TODO-ONLY is non-nil, only select lines that are
10626 also TODO lines."
10627 (interactive "P")
10628 (org-prepare-agenda-buffers (list (current-buffer)))
10629 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
10631 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
10633 (defvar org-cached-props nil)
10634 (defun org-cached-entry-get (pom property)
10635 (if (or (eq t org-use-property-inheritance)
10636 (and (stringp org-use-property-inheritance)
10637 (string-match org-use-property-inheritance property))
10638 (and (listp org-use-property-inheritance)
10639 (member property org-use-property-inheritance)))
10640 ;; Caching is not possible, check it directly
10641 (org-entry-get pom property 'inherit)
10642 ;; Get all properties, so that we can do complicated checks easily
10643 (cdr (assoc property (or org-cached-props
10644 (setq org-cached-props
10645 (org-entry-properties pom)))))))
10647 (defun org-global-tags-completion-table (&optional files)
10648 "Return the list of all tags in all agenda buffer/files."
10649 (save-excursion
10650 (org-uniquify
10651 (delq nil
10652 (apply 'append
10653 (mapcar
10654 (lambda (file)
10655 (set-buffer (find-file-noselect file))
10656 (append (org-get-buffer-tags)
10657 (mapcar (lambda (x) (if (stringp (car-safe x))
10658 (list (car-safe x)) nil))
10659 org-tag-alist)))
10660 (if (and files (car files))
10661 files
10662 (org-agenda-files))))))))
10664 (defun org-make-tags-matcher (match)
10665 "Create the TAGS//TODO matcher form for the selection string MATCH."
10666 ;; todo-only is scoped dynamically into this function, and the function
10667 ;; may change it if the matcher asks for it.
10668 (unless match
10669 ;; Get a new match request, with completion
10670 (let ((org-last-tags-completion-table
10671 (org-global-tags-completion-table)))
10672 (setq match (org-completing-read-no-ido
10673 "Match: " 'org-tags-completion-function nil nil nil
10674 'org-tags-history))))
10676 ;; Parse the string and create a lisp form
10677 (let ((match0 match)
10678 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
10679 minus tag mm
10680 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
10681 orterms term orlist re-p str-p level-p level-op time-p
10682 prop-p pn pv po cat-p gv rest)
10683 (if (string-match "/+" match)
10684 ;; match contains also a todo-matching request
10685 (progn
10686 (setq tagsmatch (substring match 0 (match-beginning 0))
10687 todomatch (substring match (match-end 0)))
10688 (if (string-match "^!" todomatch)
10689 (setq todo-only t todomatch (substring todomatch 1)))
10690 (if (string-match "^\\s-*$" todomatch)
10691 (setq todomatch nil)))
10692 ;; only matching tags
10693 (setq tagsmatch match todomatch nil))
10695 ;; Make the tags matcher
10696 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10697 (setq tagsmatcher t)
10698 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10699 (while (setq term (pop orterms))
10700 (while (and (equal (substring term -1) "\\") orterms)
10701 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10702 (while (string-match re term)
10703 (setq rest (substring term (match-end 0))
10704 minus (and (match-end 1)
10705 (equal (match-string 1 term) "-"))
10706 tag (match-string 2 term)
10707 re-p (equal (string-to-char tag) ?{)
10708 level-p (match-end 4)
10709 prop-p (match-end 5)
10710 mm (cond
10711 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10712 (level-p
10713 (setq level-op (org-op-to-function (match-string 3 term)))
10714 `(,level-op level ,(string-to-number
10715 (match-string 4 term))))
10716 (prop-p
10717 (setq pn (match-string 5 term)
10718 po (match-string 6 term)
10719 pv (match-string 7 term)
10720 cat-p (equal pn "CATEGORY")
10721 re-p (equal (string-to-char pv) ?{)
10722 str-p (equal (string-to-char pv) ?\")
10723 time-p (save-match-data
10724 (string-match "^\"[[<].*[]>]\"$" pv))
10725 pv (if (or re-p str-p) (substring pv 1 -1) pv))
10726 (if time-p (setq pv (org-matcher-time pv)))
10727 (setq po (org-op-to-function po (if time-p 'time str-p)))
10728 (cond
10729 ((equal pn "CATEGORY")
10730 (setq gv '(get-text-property (point) 'org-category)))
10731 ((equal pn "TODO")
10732 (setq gv 'todo))
10734 (setq gv `(org-cached-entry-get nil ,pn))))
10735 (if re-p
10736 (if (eq po 'org<>)
10737 `(not (string-match ,pv (or ,gv "")))
10738 `(string-match ,pv (or ,gv "")))
10739 (if str-p
10740 `(,po (or ,gv "") ,pv)
10741 `(,po (string-to-number (or ,gv ""))
10742 ,(string-to-number pv) ))))
10743 (t `(member ,tag tags-list)))
10744 mm (if minus (list 'not mm) mm)
10745 term rest)
10746 (push mm tagsmatcher))
10747 (push (if (> (length tagsmatcher) 1)
10748 (cons 'and tagsmatcher)
10749 (car tagsmatcher))
10750 orlist)
10751 (setq tagsmatcher nil))
10752 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
10753 (setq tagsmatcher
10754 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
10755 ;; Make the todo matcher
10756 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10757 (setq todomatcher t)
10758 (setq orterms (org-split-string todomatch "|") orlist nil)
10759 (while (setq term (pop orterms))
10760 (while (string-match re term)
10761 (setq minus (and (match-end 1)
10762 (equal (match-string 1 term) "-"))
10763 kwd (match-string 2 term)
10764 re-p (equal (string-to-char kwd) ?{)
10765 term (substring term (match-end 0))
10766 mm (if re-p
10767 `(string-match ,(substring kwd 1 -1) todo)
10768 (list 'equal 'todo kwd))
10769 mm (if minus (list 'not mm) mm))
10770 (push mm todomatcher))
10771 (push (if (> (length todomatcher) 1)
10772 (cons 'and todomatcher)
10773 (car todomatcher))
10774 orlist)
10775 (setq todomatcher nil))
10776 (setq todomatcher (if (> (length orlist) 1)
10777 (cons 'or orlist) (car orlist))))
10779 ;; Return the string and lisp forms of the matcher
10780 (setq matcher (if todomatcher
10781 (list 'and tagsmatcher todomatcher)
10782 tagsmatcher))
10783 (cons match0 matcher)))
10785 (defun org-op-to-function (op &optional stringp)
10786 "Turn an operator into the appropriate function."
10787 (setq op
10788 (cond
10789 ((equal op "<" ) '(< string< org-time<))
10790 ((equal op ">" ) '(> org-string> org-time>))
10791 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
10792 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
10793 ((member op '("=" "==")) '(= string= org-time=))
10794 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
10795 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
10797 (defun org<> (a b) (not (= a b)))
10798 (defun org-string<= (a b) (or (string= a b) (string< a b)))
10799 (defun org-string>= (a b) (not (string< a b)))
10800 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
10801 (defun org-string<> (a b) (not (string= a b)))
10802 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
10803 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
10804 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
10805 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
10806 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
10807 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
10808 (defun org-2ft (s)
10809 "Convert S to a floating point time.
10810 If S is already a number, just return it. If it is a string, parse
10811 it as a time string and apply `float-time' to it. If S is nil, just return 0."
10812 (cond
10813 ((numberp s) s)
10814 ((stringp s)
10815 (condition-case nil
10816 (float-time (apply 'encode-time (org-parse-time-string s)))
10817 (error 0.)))
10818 (t 0.)))
10820 (defun org-time-today ()
10821 "Time in seconds today at 0:00.
10822 Returns the float number of seconds since the beginning of the
10823 epoch to the beginning of today (00:00)."
10824 (float-time (apply 'encode-time
10825 (append '(0 0 0) (nthcdr 3 (decode-time))))))
10827 (defun org-matcher-time (s)
10828 "Interpret a time comparison value."
10829 (save-match-data
10830 (cond
10831 ((string= s "<now>") (float-time))
10832 ((string= s "<today>") (org-time-today))
10833 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
10834 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
10835 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
10836 (+ (org-time-today)
10837 (* (string-to-number (match-string 1 s))
10838 (cdr (assoc (match-string 2 s)
10839 '(("d" . 86400.0) ("w" . 604800.0)
10840 ("m" . 2678400.0) ("y" . 31557600.0)))))))
10841 (t (org-2ft s)))))
10843 (defun org-match-any-p (re list)
10844 "Does re match any element of list?"
10845 (setq list (mapcar (lambda (x) (string-match re x)) list))
10846 (delq nil list))
10848 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
10849 (defvar org-tags-overlay (org-make-overlay 1 1))
10850 (org-detach-overlay org-tags-overlay)
10852 (defun org-get-local-tags-at (&optional pos)
10853 "Get a list of tags defined in the current headline."
10854 (org-get-tags-at pos 'local))
10856 (defun org-get-local-tags ()
10857 "Get a list of tags defined in the current headline."
10858 (org-get-tags-at nil 'local))
10860 (defun org-get-tags-at (&optional pos local)
10861 "Get a list of all headline tags applicable at POS.
10862 POS defaults to point. If tags are inherited, the list contains
10863 the targets in the same sequence as the headlines appear, i.e.
10864 the tags of the current headline come last.
10865 When LOCAL is non-nil, only return tags from the current headline,
10866 ignore inherited ones."
10867 (interactive)
10868 (if (and org-trust-scanner-tags
10869 (or (not pos) (equal pos (point)))
10870 (not local))
10871 org-scanner-tags
10872 (let (tags ltags lastpos parent)
10873 (save-excursion
10874 (save-restriction
10875 (widen)
10876 (goto-char (or pos (point)))
10877 (save-match-data
10878 (catch 'done
10879 (condition-case nil
10880 (progn
10881 (org-back-to-heading t)
10882 (while (not (equal lastpos (point)))
10883 (setq lastpos (point))
10884 (when (looking-at
10885 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
10886 (setq ltags (org-split-string
10887 (org-match-string-no-properties 1) ":"))
10888 (when parent
10889 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
10890 (setq tags (append
10891 (if parent
10892 (org-remove-uniherited-tags ltags)
10893 ltags)
10894 tags)))
10895 (or org-use-tag-inheritance (throw 'done t))
10896 (if local (throw 'done t))
10897 (or (org-up-heading-safe) (error nil))
10898 (setq parent t)))
10899 (error nil)))))
10900 (append (org-remove-uniherited-tags org-file-tags) tags)))))
10902 (defun org-add-prop-inherited (s)
10903 (add-text-properties 0 (length s) '(inherited t) s)
10906 (defun org-toggle-tag (tag &optional onoff)
10907 "Toggle the tag TAG for the current line.
10908 If ONOFF is `on' or `off', don't toggle but set to this state."
10909 (let (res current)
10910 (save-excursion
10911 (org-back-to-heading t)
10912 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
10913 (point-at-eol) t)
10914 (progn
10915 (setq current (match-string 1))
10916 (replace-match ""))
10917 (setq current ""))
10918 (setq current (nreverse (org-split-string current ":")))
10919 (cond
10920 ((eq onoff 'on)
10921 (setq res t)
10922 (or (member tag current) (push tag current)))
10923 ((eq onoff 'off)
10924 (or (not (member tag current)) (setq current (delete tag current))))
10925 (t (if (member tag current)
10926 (setq current (delete tag current))
10927 (setq res t)
10928 (push tag current))))
10929 (end-of-line 1)
10930 (if current
10931 (progn
10932 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
10933 (org-set-tags nil t))
10934 (delete-horizontal-space))
10935 (run-hooks 'org-after-tags-change-hook))
10936 res))
10938 (defun org-align-tags-here (to-col)
10939 ;; Assumes that this is a headline
10940 (let ((pos (point)) (col (current-column)) ncol tags-l p)
10941 (beginning-of-line 1)
10942 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10943 (< pos (match-beginning 2)))
10944 (progn
10945 (setq tags-l (- (match-end 2) (match-beginning 2)))
10946 (goto-char (match-beginning 1))
10947 (insert " ")
10948 (delete-region (point) (1+ (match-beginning 2)))
10949 (setq ncol (max (1+ (current-column))
10950 (1+ col)
10951 (if (> to-col 0)
10952 to-col
10953 (- (abs to-col) tags-l))))
10954 (setq p (point))
10955 (insert (make-string (- ncol (current-column)) ?\ ))
10956 (setq ncol (current-column))
10957 (when indent-tabs-mode (tabify p (point-at-eol)))
10958 (org-move-to-column (min ncol col) t))
10959 (goto-char pos))))
10961 (defun org-set-tags-command (&optional arg just-align)
10962 "Call the set-tags command for the current entry."
10963 (interactive "P")
10964 (if (org-on-heading-p)
10965 (org-set-tags arg just-align)
10966 (save-excursion
10967 (org-back-to-heading t)
10968 (org-set-tags arg just-align))))
10970 (defun org-set-tags (&optional arg just-align)
10971 "Set the tags for the current headline.
10972 With prefix ARG, realign all tags in headings in the current buffer."
10973 (interactive "P")
10974 (let* ((re (concat "^" outline-regexp))
10975 (current (org-get-tags-string))
10976 (col (current-column))
10977 (org-setting-tags t)
10978 table current-tags inherited-tags ; computed below when needed
10979 tags p0 c0 c1 rpl)
10980 (if arg
10981 (save-excursion
10982 (goto-char (point-min))
10983 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
10984 (while (re-search-forward re nil t)
10985 (org-set-tags nil t)
10986 (end-of-line 1)))
10987 (message "All tags realigned to column %d" org-tags-column))
10988 (if just-align
10989 (setq tags current)
10990 ;; Get a new set of tags from the user
10991 (save-excursion
10992 (setq table (append org-tag-persistent-alist
10993 (or org-tag-alist (org-get-buffer-tags)))
10994 org-last-tags-completion-table table
10995 current-tags (org-split-string current ":")
10996 inherited-tags (nreverse
10997 (nthcdr (length current-tags)
10998 (nreverse (org-get-tags-at))))
10999 tags
11000 (if (or (eq t org-use-fast-tag-selection)
11001 (and org-use-fast-tag-selection
11002 (delq nil (mapcar 'cdr table))))
11003 (org-fast-tag-selection
11004 current-tags inherited-tags table
11005 (if org-fast-tag-selection-include-todo org-todo-key-alist))
11006 (let ((org-add-colon-after-tag-completion t))
11007 (org-trim
11008 (org-without-partial-completion
11009 (org-ido-completing-read "Tags: " 'org-tags-completion-function
11010 nil nil current 'org-tags-history)))))))
11011 (while (string-match "[-+&]+" tags)
11012 ;; No boolean logic, just a list
11013 (setq tags (replace-match ":" t t tags))))
11015 (if org-tags-sort-function
11016 (setq tags (mapconcat 'identity
11017 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
11018 org-tags-sort-function) ":")))
11020 (if (string-match "\\`[\t ]*\\'" tags)
11021 (setq tags "")
11022 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
11023 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
11025 ;; Insert new tags at the correct column
11026 (beginning-of-line 1)
11027 (cond
11028 ((and (equal current "") (equal tags "")))
11029 ((re-search-forward
11030 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
11031 (point-at-eol) t)
11032 (if (equal tags "")
11033 (setq rpl "")
11034 (goto-char (match-beginning 0))
11035 (setq c0 (current-column) p0 (point)
11036 c1 (max (1+ c0) (if (> org-tags-column 0)
11037 org-tags-column
11038 (- (- org-tags-column) (length tags))))
11039 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
11040 (replace-match rpl t t)
11041 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
11042 tags)
11043 (t (error "Tags alignment failed")))
11044 (org-move-to-column col)
11045 (unless just-align
11046 (run-hooks 'org-after-tags-change-hook)))))
11048 (defun org-change-tag-in-region (beg end tag off)
11049 "Add or remove TAG for each entry in the region.
11050 This works in the agenda, and also in an org-mode buffer."
11051 (interactive
11052 (list (region-beginning) (region-end)
11053 (let ((org-last-tags-completion-table
11054 (if (org-mode-p)
11055 (org-get-buffer-tags)
11056 (org-global-tags-completion-table))))
11057 (org-ido-completing-read
11058 "Tag: " 'org-tags-completion-function nil nil nil
11059 'org-tags-history))
11060 (progn
11061 (message "[s]et or [r]emove? ")
11062 (equal (read-char-exclusive) ?r))))
11063 (if (fboundp 'deactivate-mark) (deactivate-mark))
11064 (let ((agendap (equal major-mode 'org-agenda-mode))
11065 l1 l2 m buf pos newhead (cnt 0))
11066 (goto-char end)
11067 (setq l2 (1- (org-current-line)))
11068 (goto-char beg)
11069 (setq l1 (org-current-line))
11070 (loop for l from l1 to l2 do
11071 (goto-line l)
11072 (setq m (get-text-property (point) 'org-hd-marker))
11073 (when (or (and (org-mode-p) (org-on-heading-p))
11074 (and agendap m))
11075 (setq buf (if agendap (marker-buffer m) (current-buffer))
11076 pos (if agendap m (point)))
11077 (with-current-buffer buf
11078 (save-excursion
11079 (save-restriction
11080 (goto-char pos)
11081 (setq cnt (1+ cnt))
11082 (org-toggle-tag tag (if off 'off 'on))
11083 (setq newhead (org-get-heading)))))
11084 (and agendap (org-agenda-change-all-lines newhead m))))
11085 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
11087 (defun org-tags-completion-function (string predicate &optional flag)
11088 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
11089 (confirm (lambda (x) (stringp (car x)))))
11090 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
11091 (setq s1 (match-string 1 string)
11092 s2 (match-string 2 string))
11093 (setq s1 "" s2 string))
11094 (cond
11095 ((eq flag nil)
11096 ;; try completion
11097 (setq rtn (try-completion s2 ctable confirm))
11098 (if (stringp rtn)
11099 (setq rtn
11100 (concat s1 s2 (substring rtn (length s2))
11101 (if (and org-add-colon-after-tag-completion
11102 (assoc rtn ctable))
11103 ":" ""))))
11104 rtn)
11105 ((eq flag t)
11106 ;; all-completions
11107 (all-completions s2 ctable confirm)
11109 ((eq flag 'lambda)
11110 ;; exact match?
11111 (assoc s2 ctable)))
11114 (defun org-fast-tag-insert (kwd tags face &optional end)
11115 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
11116 (insert (format "%-12s" (concat kwd ":"))
11117 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
11118 (or end "")))
11120 (defun org-fast-tag-show-exit (flag)
11121 (save-excursion
11122 (goto-line 3)
11123 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
11124 (replace-match ""))
11125 (when flag
11126 (end-of-line 1)
11127 (org-move-to-column (- (window-width) 19) t)
11128 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
11130 (defun org-set-current-tags-overlay (current prefix)
11131 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
11132 (if (featurep 'xemacs)
11133 (org-overlay-display org-tags-overlay (concat prefix s)
11134 'secondary-selection)
11135 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
11136 (org-overlay-display org-tags-overlay (concat prefix s)))))
11138 (defun org-fast-tag-selection (current inherited table &optional todo-table)
11139 "Fast tag selection with single keys.
11140 CURRENT is the current list of tags in the headline, INHERITED is the
11141 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
11142 possibly with grouping information. TODO-TABLE is a similar table with
11143 TODO keywords, should these have keys assigned to them.
11144 If the keys are nil, a-z are automatically assigned.
11145 Returns the new tags string, or nil to not change the current settings."
11146 (let* ((fulltable (append table todo-table))
11147 (maxlen (apply 'max (mapcar
11148 (lambda (x)
11149 (if (stringp (car x)) (string-width (car x)) 0))
11150 fulltable)))
11151 (buf (current-buffer))
11152 (expert (eq org-fast-tag-selection-single-key 'expert))
11153 (buffer-tags nil)
11154 (fwidth (+ maxlen 3 1 3))
11155 (ncol (/ (- (window-width) 4) fwidth))
11156 (i-face 'org-done)
11157 (c-face 'org-todo)
11158 tg cnt e c char c1 c2 ntable tbl rtn
11159 ov-start ov-end ov-prefix
11160 (exit-after-next org-fast-tag-selection-single-key)
11161 (done-keywords org-done-keywords)
11162 groups ingroup)
11163 (save-excursion
11164 (beginning-of-line 1)
11165 (if (looking-at
11166 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11167 (setq ov-start (match-beginning 1)
11168 ov-end (match-end 1)
11169 ov-prefix "")
11170 (setq ov-start (1- (point-at-eol))
11171 ov-end (1+ ov-start))
11172 (skip-chars-forward "^\n\r")
11173 (setq ov-prefix
11174 (concat
11175 (buffer-substring (1- (point)) (point))
11176 (if (> (current-column) org-tags-column)
11178 (make-string (- org-tags-column (current-column)) ?\ ))))))
11179 (org-move-overlay org-tags-overlay ov-start ov-end)
11180 (save-window-excursion
11181 (if expert
11182 (set-buffer (get-buffer-create " *Org tags*"))
11183 (delete-other-windows)
11184 (split-window-vertically)
11185 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
11186 (erase-buffer)
11187 (org-set-local 'org-done-keywords done-keywords)
11188 (org-fast-tag-insert "Inherited" inherited i-face "\n")
11189 (org-fast-tag-insert "Current" current c-face "\n\n")
11190 (org-fast-tag-show-exit exit-after-next)
11191 (org-set-current-tags-overlay current ov-prefix)
11192 (setq tbl fulltable char ?a cnt 0)
11193 (while (setq e (pop tbl))
11194 (cond
11195 ((equal e '(:startgroup))
11196 (push '() groups) (setq ingroup t)
11197 (when (not (= cnt 0))
11198 (setq cnt 0)
11199 (insert "\n"))
11200 (insert "{ "))
11201 ((equal e '(:endgroup))
11202 (setq ingroup nil cnt 0)
11203 (insert "}\n"))
11204 ((equal e '(:newline))
11205 (when (not (= cnt 0))
11206 (setq cnt 0)
11207 (insert "\n")
11208 (setq e (car tbl))
11209 (while (equal (car tbl) '(:newline))
11210 (insert "\n")
11211 (setq tbl (cdr tbl)))))
11213 (setq tg (car e) c2 nil)
11214 (if (cdr e)
11215 (setq c (cdr e))
11216 ;; automatically assign a character.
11217 (setq c1 (string-to-char
11218 (downcase (substring
11219 tg (if (= (string-to-char tg) ?@) 1 0)))))
11220 (if (or (rassoc c1 ntable) (rassoc c1 table))
11221 (while (or (rassoc char ntable) (rassoc char table))
11222 (setq char (1+ char)))
11223 (setq c2 c1))
11224 (setq c (or c2 char)))
11225 (if ingroup (push tg (car groups)))
11226 (setq tg (org-add-props tg nil 'face
11227 (cond
11228 ((not (assoc tg table))
11229 (org-get-todo-face tg))
11230 ((member tg current) c-face)
11231 ((member tg inherited) i-face)
11232 (t nil))))
11233 (if (and (= cnt 0) (not ingroup)) (insert " "))
11234 (insert "[" c "] " tg (make-string
11235 (- fwidth 4 (length tg)) ?\ ))
11236 (push (cons tg c) ntable)
11237 (when (= (setq cnt (1+ cnt)) ncol)
11238 (insert "\n")
11239 (if ingroup (insert " "))
11240 (setq cnt 0)))))
11241 (setq ntable (nreverse ntable))
11242 (insert "\n")
11243 (goto-char (point-min))
11244 (if (not expert) (org-fit-window-to-buffer))
11245 (setq rtn
11246 (catch 'exit
11247 (while t
11248 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
11249 (if groups " [!] no groups" " [!]groups")
11250 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
11251 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11252 (cond
11253 ((= c ?\r) (throw 'exit t))
11254 ((= c ?!)
11255 (setq groups (not groups))
11256 (goto-char (point-min))
11257 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
11258 ((= c ?\C-c)
11259 (if (not expert)
11260 (org-fast-tag-show-exit
11261 (setq exit-after-next (not exit-after-next)))
11262 (setq expert nil)
11263 (delete-other-windows)
11264 (split-window-vertically)
11265 (org-switch-to-buffer-other-window " *Org tags*")
11266 (org-fit-window-to-buffer)))
11267 ((or (= c ?\C-g)
11268 (and (= c ?q) (not (rassoc c ntable))))
11269 (org-detach-overlay org-tags-overlay)
11270 (setq quit-flag t))
11271 ((= c ?\ )
11272 (setq current nil)
11273 (if exit-after-next (setq exit-after-next 'now)))
11274 ((= c ?\t)
11275 (condition-case nil
11276 (setq tg (org-ido-completing-read
11277 "Tag: "
11278 (or buffer-tags
11279 (with-current-buffer buf
11280 (org-get-buffer-tags)))))
11281 (quit (setq tg "")))
11282 (when (string-match "\\S-" tg)
11283 (add-to-list 'buffer-tags (list tg))
11284 (if (member tg current)
11285 (setq current (delete tg current))
11286 (push tg current)))
11287 (if exit-after-next (setq exit-after-next 'now)))
11288 ((setq e (rassoc c todo-table) tg (car e))
11289 (with-current-buffer buf
11290 (save-excursion (org-todo tg)))
11291 (if exit-after-next (setq exit-after-next 'now)))
11292 ((setq e (rassoc c ntable) tg (car e))
11293 (if (member tg current)
11294 (setq current (delete tg current))
11295 (loop for g in groups do
11296 (if (member tg g)
11297 (mapc (lambda (x)
11298 (setq current (delete x current)))
11299 g)))
11300 (push tg current))
11301 (if exit-after-next (setq exit-after-next 'now))))
11303 ;; Create a sorted list
11304 (setq current
11305 (sort current
11306 (lambda (a b)
11307 (assoc b (cdr (memq (assoc a ntable) ntable))))))
11308 (if (eq exit-after-next 'now) (throw 'exit t))
11309 (goto-char (point-min))
11310 (beginning-of-line 2)
11311 (delete-region (point) (point-at-eol))
11312 (org-fast-tag-insert "Current" current c-face)
11313 (org-set-current-tags-overlay current ov-prefix)
11314 (while (re-search-forward
11315 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
11316 (setq tg (match-string 1))
11317 (add-text-properties
11318 (match-beginning 1) (match-end 1)
11319 (list 'face
11320 (cond
11321 ((member tg current) c-face)
11322 ((member tg inherited) i-face)
11323 (t (get-text-property (match-beginning 1) 'face))))))
11324 (goto-char (point-min)))))
11325 (org-detach-overlay org-tags-overlay)
11326 (if rtn
11327 (mapconcat 'identity current ":")
11328 nil))))
11330 (defun org-get-tags-string ()
11331 "Get the TAGS string in the current headline."
11332 (unless (org-on-heading-p t)
11333 (error "Not on a heading"))
11334 (save-excursion
11335 (beginning-of-line 1)
11336 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11337 (org-match-string-no-properties 1)
11338 "")))
11340 (defun org-get-tags ()
11341 "Get the list of tags specified in the current headline."
11342 (org-split-string (org-get-tags-string) ":"))
11344 (defun org-get-buffer-tags ()
11345 "Get a table of all tags used in the buffer, for completion."
11346 (let (tags)
11347 (save-excursion
11348 (goto-char (point-min))
11349 (while (re-search-forward
11350 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
11351 (when (equal (char-after (point-at-bol 0)) ?*)
11352 (mapc (lambda (x) (add-to-list 'tags x))
11353 (org-split-string (org-match-string-no-properties 1) ":")))))
11354 (mapcar 'list tags)))
11356 ;;;; The mapping API
11358 ;;;###autoload
11359 (defun org-map-entries (func &optional match scope &rest skip)
11360 "Call FUNC at each headline selected by MATCH in SCOPE.
11362 FUNC is a function or a lisp form. The function will be called without
11363 arguments, with the cursor positioned at the beginning of the headline.
11364 The return values of all calls to the function will be collected and
11365 returned as a list.
11367 The call to FUNC will be wrapped into a save-excursion form, so FUNC
11368 does not need to preserve point. After evaluation, the cursor will be
11369 moved to the end of the line (presumably of the headline of the
11370 processed entry) and search continues from there. Under some
11371 circumstances, this may not produce the wanted results. For example,
11372 if you have removed (e.g. archived) the current (sub)tree it could
11373 mean that the next entry will be skipped entirely. In such cases, you
11374 can specify the position from where search should continue by making
11375 FUNC set the variable `org-map-continue-from' to the desired buffer
11376 position.
11378 MATCH is a tags/property/todo match as it is used in the agenda tags view.
11379 Only headlines that are matched by this query will be considered during
11380 the iteration. When MATCH is nil or t, all headlines will be
11381 visited by the iteration.
11383 SCOPE determines the scope of this command. It can be any of:
11385 nil The current buffer, respecting the restriction if any
11386 tree The subtree started with the entry at point
11387 file The current buffer, without restriction
11388 file-with-archives
11389 The current buffer, and any archives associated with it
11390 agenda All agenda files
11391 agenda-with-archives
11392 All agenda files with any archive files associated with them
11393 \(file1 file2 ...)
11394 If this is a list, all files in the list will be scanned
11396 The remaining args are treated as settings for the skipping facilities of
11397 the scanner. The following items can be given here:
11399 archive skip trees with the archive tag.
11400 comment skip trees with the COMMENT keyword
11401 function or Emacs Lisp form:
11402 will be used as value for `org-agenda-skip-function', so whenever
11403 the the function returns t, FUNC will not be called for that
11404 entry and search will continue from the point where the
11405 function leaves it.
11407 If your function needs to retrieve the tags including inherited tags
11408 at the *current* entry, you can use the value of the variable
11409 `org-scanner-tags' which will be much faster than getting the value
11410 with `org-get-tags-at'. If your function gets properties with
11411 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
11412 to t around the call to `org-entry-properties' to get the same speedup.
11413 Note that if your function moves around to retrieve tags and properties at
11414 a *different* entry, you cannot use these techniques."
11415 (let* ((org-agenda-archives-mode nil) ; just to make sure
11416 (org-agenda-skip-archived-trees (memq 'archive skip))
11417 (org-agenda-skip-comment-trees (memq 'comment skip))
11418 (org-agenda-skip-function
11419 (car (org-delete-all '(comment archive) skip)))
11420 (org-tags-match-list-sublevels t)
11421 matcher file res
11422 org-todo-keywords-for-agenda
11423 org-done-keywords-for-agenda
11424 org-todo-keyword-alist-for-agenda
11425 org-tag-alist-for-agenda)
11427 (cond
11428 ((eq match t) (setq matcher t))
11429 ((eq match nil) (setq matcher t))
11430 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
11432 (save-excursion
11433 (save-restriction
11434 (when (eq scope 'tree)
11435 (org-back-to-heading t)
11436 (org-narrow-to-subtree)
11437 (setq scope nil))
11439 (if (not scope)
11440 (progn
11441 (org-prepare-agenda-buffers
11442 (list (buffer-file-name (current-buffer))))
11443 (setq res (org-scan-tags func matcher)))
11444 ;; Get the right scope
11445 (cond
11446 ((and scope (listp scope) (symbolp (car scope)))
11447 (setq scope (eval scope)))
11448 ((eq scope 'agenda)
11449 (setq scope (org-agenda-files t)))
11450 ((eq scope 'agenda-with-archives)
11451 (setq scope (org-agenda-files t))
11452 (setq scope (org-add-archive-files scope)))
11453 ((eq scope 'file)
11454 (setq scope (list (buffer-file-name))))
11455 ((eq scope 'file-with-archives)
11456 (setq scope (org-add-archive-files (list (buffer-file-name))))))
11457 (org-prepare-agenda-buffers scope)
11458 (while (setq file (pop scope))
11459 (with-current-buffer (org-find-base-buffer-visiting file)
11460 (save-excursion
11461 (save-restriction
11462 (widen)
11463 (goto-char (point-min))
11464 (setq res (append res (org-scan-tags func matcher))))))))))
11465 res))
11467 ;;;; Properties
11469 ;;; Setting and retrieving properties
11471 (defconst org-special-properties
11472 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
11473 "TIMESTAMP" "TIMESTAMP_IA")
11474 "The special properties valid in Org-mode.
11476 These are properties that are not defined in the property drawer,
11477 but in some other way.")
11479 (defconst org-default-properties
11480 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
11481 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
11482 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
11483 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
11484 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
11485 "CLOCK_MODELINE_TOTAL")
11486 "Some properties that are used by Org-mode for various purposes.
11487 Being in this list makes sure that they are offered for completion.")
11489 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
11490 "Regular expression matching the first line of a property drawer.")
11492 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
11493 "Regular expression matching the first line of a property drawer.")
11495 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
11496 "Regular expression matching the first line of a property drawer.")
11498 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
11499 "Regular expression matching the first line of a property drawer.")
11501 (defconst org-property-drawer-re
11502 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
11503 org-property-end-re "\\)\n?")
11504 "Matches an entire property drawer.")
11506 (defconst org-clock-drawer-re
11507 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
11508 org-property-end-re "\\)\n?")
11509 "Matches an entire clock drawer.")
11511 (defun org-property-action ()
11512 "Do an action on properties."
11513 (interactive)
11514 (let (c)
11515 (org-at-property-p)
11516 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
11517 (setq c (read-char-exclusive))
11518 (cond
11519 ((equal c ?s)
11520 (call-interactively 'org-set-property))
11521 ((equal c ?d)
11522 (call-interactively 'org-delete-property))
11523 ((equal c ?D)
11524 (call-interactively 'org-delete-property-globally))
11525 ((equal c ?c)
11526 (call-interactively 'org-compute-property-at-point))
11527 (t (error "No such property action %c" c)))))
11529 (defun org-at-property-p ()
11530 "Is the cursor in a property line?"
11531 ;; FIXME: Does not check if we are actually in the drawer.
11532 ;; FIXME: also returns true on any drawers.....
11533 ;; This is used by C-c C-c for property action.
11534 (save-excursion
11535 (beginning-of-line 1)
11536 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
11538 (defun org-get-property-block (&optional beg end force)
11539 "Return the (beg . end) range of the body of the property drawer.
11540 BEG and END can be beginning and end of subtree, if not given
11541 they will be found.
11542 If the drawer does not exist and FORCE is non-nil, create the drawer."
11543 (catch 'exit
11544 (save-excursion
11545 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
11546 (end (or end (progn (outline-next-heading) (point)))))
11547 (goto-char beg)
11548 (if (re-search-forward org-property-start-re end t)
11549 (setq beg (1+ (match-end 0)))
11550 (if force
11551 (save-excursion
11552 (org-insert-property-drawer)
11553 (setq end (progn (outline-next-heading) (point))))
11554 (throw 'exit nil))
11555 (goto-char beg)
11556 (if (re-search-forward org-property-start-re end t)
11557 (setq beg (1+ (match-end 0)))))
11558 (if (re-search-forward org-property-end-re end t)
11559 (setq end (match-beginning 0))
11560 (or force (throw 'exit nil))
11561 (goto-char beg)
11562 (setq end beg)
11563 (org-indent-line-function)
11564 (insert ":END:\n"))
11565 (cons beg end)))))
11567 (defun org-entry-properties (&optional pom which)
11568 "Get all properties of the entry at point-or-marker POM.
11569 This includes the TODO keyword, the tags, time strings for deadline,
11570 scheduled, and clocking, and any additional properties defined in the
11571 entry. The return value is an alist, keys may occur multiple times
11572 if the property key was used several times.
11573 POM may also be nil, in which case the current entry is used.
11574 If WHICH is nil or `all', get all properties. If WHICH is
11575 `special' or `standard', only get that subclass."
11576 (setq which (or which 'all))
11577 (org-with-point-at pom
11578 (let ((clockstr (substring org-clock-string 0 -1))
11579 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
11580 beg end range props sum-props key value string clocksum)
11581 (save-excursion
11582 (when (condition-case nil
11583 (and (org-mode-p) (org-back-to-heading t))
11584 (error nil))
11585 (setq beg (point))
11586 (setq sum-props (get-text-property (point) 'org-summaries))
11587 (setq clocksum (get-text-property (point) :org-clock-minutes))
11588 (outline-next-heading)
11589 (setq end (point))
11590 (when (memq which '(all special))
11591 ;; Get the special properties, like TODO and tags
11592 (goto-char beg)
11593 (when (and (looking-at org-todo-line-regexp) (match-end 2))
11594 (push (cons "TODO" (org-match-string-no-properties 2)) props))
11595 (when (looking-at org-priority-regexp)
11596 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
11597 (when (and (setq value (org-get-tags-string))
11598 (string-match "\\S-" value))
11599 (push (cons "TAGS" value) props))
11600 (when (setq value (org-get-tags-at))
11601 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
11602 props))
11603 (while (re-search-forward org-maybe-keyword-time-regexp end t)
11604 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
11605 string (if (equal key clockstr)
11606 (org-no-properties
11607 (org-trim
11608 (buffer-substring
11609 (match-beginning 3) (goto-char (point-at-eol)))))
11610 (substring (org-match-string-no-properties 3) 1 -1)))
11611 (unless key
11612 (if (= (char-after (match-beginning 3)) ?\[)
11613 (setq key "TIMESTAMP_IA")
11614 (setq key "TIMESTAMP")))
11615 (when (or (equal key clockstr) (not (assoc key props)))
11616 (push (cons key string) props)))
11620 (when (memq which '(all standard))
11621 ;; Get the standard properties, like :PROP: ...
11622 (setq range (org-get-property-block beg end))
11623 (when range
11624 (goto-char (car range))
11625 (while (re-search-forward
11626 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
11627 (cdr range) t)
11628 (setq key (org-match-string-no-properties 1)
11629 value (org-trim (or (org-match-string-no-properties 2) "")))
11630 (unless (member key excluded)
11631 (push (cons key (or value "")) props)))))
11632 (if clocksum
11633 (push (cons "CLOCKSUM"
11634 (org-columns-number-to-string (/ (float clocksum) 60.)
11635 'add_times))
11636 props))
11637 (unless (assoc "CATEGORY" props)
11638 (setq value (or (org-get-category)
11639 (progn (org-refresh-category-properties)
11640 (org-get-category))))
11641 (push (cons "CATEGORY" value) props))
11642 (append sum-props (nreverse props)))))))
11644 (defun org-entry-get (pom property &optional inherit)
11645 "Get value of PROPERTY for entry at point-or-marker POM.
11646 If INHERIT is non-nil and the entry does not have the property,
11647 then also check higher levels of the hierarchy.
11648 If INHERIT is the symbol `selective', use inheritance only if the setting
11649 in `org-use-property-inheritance' selects PROPERTY for inheritance.
11650 If the property is present but empty, the return value is the empty string.
11651 If the property is not present at all, nil is returned."
11652 (org-with-point-at pom
11653 (if (and inherit (if (eq inherit 'selective)
11654 (org-property-inherit-p property)
11656 (org-entry-get-with-inheritance property)
11657 (if (member property org-special-properties)
11658 ;; We need a special property. Use brute force, get all properties.
11659 (cdr (assoc property (org-entry-properties nil 'special)))
11660 (let ((range (org-get-property-block)))
11661 (if (and range
11662 (goto-char (car range))
11663 (re-search-forward
11664 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
11665 (cdr range) t))
11666 ;; Found the property, return it.
11667 (if (match-end 1)
11668 (org-match-string-no-properties 1)
11669 "")))))))
11671 (defun org-property-or-variable-value (var &optional inherit)
11672 "Check if there is a property fixing the value of VAR.
11673 If yes, return this value. If not, return the current value of the variable."
11674 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
11675 (if (and prop (stringp prop) (string-match "\\S-" prop))
11676 (read prop)
11677 (symbol-value var))))
11679 (defun org-entry-delete (pom property)
11680 "Delete the property PROPERTY from entry at point-or-marker POM."
11681 (org-with-point-at pom
11682 (if (member property org-special-properties)
11683 nil ; cannot delete these properties.
11684 (let ((range (org-get-property-block)))
11685 (if (and range
11686 (goto-char (car range))
11687 (re-search-forward
11688 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
11689 (cdr range) t))
11690 (progn
11691 (delete-region (match-beginning 0) (1+ (point-at-eol)))
11693 nil)))))
11695 ;; Multi-values properties are properties that contain multiple values
11696 ;; These values are assumed to be single words, separated by whitespace.
11697 (defun org-entry-add-to-multivalued-property (pom property value)
11698 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
11699 (let* ((old (org-entry-get pom property))
11700 (values (and old (org-split-string old "[ \t]"))))
11701 (setq value (org-entry-protect-space value))
11702 (unless (member value values)
11703 (setq values (cons value values))
11704 (org-entry-put pom property
11705 (mapconcat 'identity values " ")))))
11707 (defun org-entry-remove-from-multivalued-property (pom property value)
11708 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
11709 (let* ((old (org-entry-get pom property))
11710 (values (and old (org-split-string old "[ \t]"))))
11711 (setq value (org-entry-protect-space value))
11712 (when (member value values)
11713 (setq values (delete value values))
11714 (org-entry-put pom property
11715 (mapconcat 'identity values " ")))))
11717 (defun org-entry-member-in-multivalued-property (pom property value)
11718 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
11719 (let* ((old (org-entry-get pom property))
11720 (values (and old (org-split-string old "[ \t]"))))
11721 (setq value (org-entry-protect-space value))
11722 (member value values)))
11724 (defun org-entry-get-multivalued-property (pom property)
11725 "Return a list of values in a multivalued property."
11726 (let* ((value (org-entry-get pom property))
11727 (values (and value (org-split-string value "[ \t]"))))
11728 (mapcar 'org-entry-restore-space values)))
11730 (defun org-entry-put-multivalued-property (pom property &rest values)
11731 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
11732 VALUES should be a list of strings. Spaces will be protected."
11733 (org-entry-put pom property
11734 (mapconcat 'org-entry-protect-space values " "))
11735 (let* ((value (org-entry-get pom property))
11736 (values (and value (org-split-string value "[ \t]"))))
11737 (mapcar 'org-entry-restore-space values)))
11739 (defun org-entry-protect-space (s)
11740 "Protect spaces and newline in string S."
11741 (while (string-match " " s)
11742 (setq s (replace-match "%20" t t s)))
11743 (while (string-match "\n" s)
11744 (setq s (replace-match "%0A" t t s)))
11747 (defun org-entry-restore-space (s)
11748 "Restore spaces and newline in string S."
11749 (while (string-match "%20" s)
11750 (setq s (replace-match " " t t s)))
11751 (while (string-match "%0A" s)
11752 (setq s (replace-match "\n" t t s)))
11755 (defvar org-entry-property-inherited-from (make-marker)
11756 "Marker pointing to the entry from where a property was inherited.
11757 Each call to `org-entry-get-with-inheritance' will set this marker to the
11758 location of the entry where the inheritance search matched. If there was
11759 no match, the marker will point nowhere.
11760 Note that also `org-entry-get' calls this function, if the INHERIT flag
11761 is set.")
11763 (defun org-entry-get-with-inheritance (property)
11764 "Get entry property, and search higher levels if not present."
11765 (move-marker org-entry-property-inherited-from nil)
11766 (let (tmp)
11767 (save-excursion
11768 (save-restriction
11769 (widen)
11770 (catch 'ex
11771 (while t
11772 (when (setq tmp (org-entry-get nil property))
11773 (org-back-to-heading t)
11774 (move-marker org-entry-property-inherited-from (point))
11775 (throw 'ex tmp))
11776 (or (org-up-heading-safe) (throw 'ex nil)))))
11777 (or tmp
11778 (cdr (assoc property org-file-properties))
11779 (cdr (assoc property org-global-properties))
11780 (cdr (assoc property org-global-properties-fixed))))))
11782 (defun org-entry-put (pom property value)
11783 "Set PROPERTY to VALUE for entry at point-or-marker POM."
11784 (org-with-point-at pom
11785 (org-back-to-heading t)
11786 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
11787 range)
11788 (cond
11789 ((equal property "TODO")
11790 (when (and (stringp value) (string-match "\\S-" value)
11791 (not (member value org-todo-keywords-1)))
11792 (error "\"%s\" is not a valid TODO state" value))
11793 (if (or (not value)
11794 (not (string-match "\\S-" value)))
11795 (setq value 'none))
11796 (org-todo value)
11797 (org-set-tags nil 'align))
11798 ((equal property "PRIORITY")
11799 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
11800 (string-to-char value) ?\ ))
11801 (org-set-tags nil 'align))
11802 ((equal property "SCHEDULED")
11803 (if (re-search-forward org-scheduled-time-regexp end t)
11804 (cond
11805 ((eq value 'earlier) (org-timestamp-change -1 'day))
11806 ((eq value 'later) (org-timestamp-change 1 'day))
11807 (t (call-interactively 'org-schedule)))
11808 (call-interactively 'org-schedule)))
11809 ((equal property "DEADLINE")
11810 (if (re-search-forward org-deadline-time-regexp end t)
11811 (cond
11812 ((eq value 'earlier) (org-timestamp-change -1 'day))
11813 ((eq value 'later) (org-timestamp-change 1 'day))
11814 (t (call-interactively 'org-deadline)))
11815 (call-interactively 'org-deadline)))
11816 ((member property org-special-properties)
11817 (error "The %s property can not yet be set with `org-entry-put'"
11818 property))
11819 (t ; a non-special property
11820 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
11821 (setq range (org-get-property-block beg end 'force))
11822 (goto-char (car range))
11823 (if (re-search-forward
11824 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
11825 (progn
11826 (delete-region (match-beginning 1) (match-end 1))
11827 (goto-char (match-beginning 1)))
11828 (goto-char (cdr range))
11829 (insert "\n")
11830 (backward-char 1)
11831 (org-indent-line-function)
11832 (insert ":" property ":"))
11833 (and value (insert " " value))
11834 (org-indent-line-function)))))))
11836 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
11837 "Get all property keys in the current buffer.
11838 With INCLUDE-SPECIALS, also list the special properties that reflect things
11839 like tags and TODO state.
11840 With INCLUDE-DEFAULTS, also include properties that has special meaning
11841 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
11842 With INCLUDE-COLUMNS, also include property names given in COLUMN
11843 formats in the current buffer."
11844 (let (rtn range cfmt s p)
11845 (save-excursion
11846 (save-restriction
11847 (widen)
11848 (goto-char (point-min))
11849 (while (re-search-forward org-property-start-re nil t)
11850 (setq range (org-get-property-block))
11851 (goto-char (car range))
11852 (while (re-search-forward
11853 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
11854 (cdr range) t)
11855 (add-to-list 'rtn (org-match-string-no-properties 1)))
11856 (outline-next-heading))))
11858 (when include-specials
11859 (setq rtn (append org-special-properties rtn)))
11861 (when include-defaults
11862 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
11863 (add-to-list 'rtn org-effort-property))
11865 (when include-columns
11866 (save-excursion
11867 (save-restriction
11868 (widen)
11869 (goto-char (point-min))
11870 (while (re-search-forward
11871 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
11872 nil t)
11873 (setq cfmt (match-string 2) s 0)
11874 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
11875 cfmt s)
11876 (setq s (match-end 0)
11877 p (match-string 1 cfmt))
11878 (unless (or (equal p "ITEM")
11879 (member p org-special-properties))
11880 (add-to-list 'rtn (match-string 1 cfmt))))))))
11882 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
11884 (defun org-property-values (key)
11885 "Return a list of all values of property KEY."
11886 (save-excursion
11887 (save-restriction
11888 (widen)
11889 (goto-char (point-min))
11890 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
11891 values)
11892 (while (re-search-forward re nil t)
11893 (add-to-list 'values (org-trim (match-string 1))))
11894 (delete "" values)))))
11896 (defun org-insert-property-drawer ()
11897 "Insert a property drawer into the current entry."
11898 (interactive)
11899 (org-back-to-heading t)
11900 (looking-at outline-regexp)
11901 (let ((indent (if org-adapt-indentation
11902 (- (match-end 0)(match-beginning 0))
11904 (beg (point))
11905 (re (concat "^[ \t]*" org-keyword-time-regexp))
11906 end hiddenp)
11907 (outline-next-heading)
11908 (setq end (point))
11909 (goto-char beg)
11910 (while (re-search-forward re end t))
11911 (setq hiddenp (org-invisible-p))
11912 (end-of-line 1)
11913 (and (equal (char-after) ?\n) (forward-char 1))
11914 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
11915 (if (member (match-string 1) '("CLOCK:" ":END:"))
11916 ;; just skip this line
11917 (beginning-of-line 2)
11918 ;; Drawer start, find the end
11919 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
11920 (beginning-of-line 1)))
11921 (org-skip-over-state-notes)
11922 (skip-chars-backward " \t\n\r")
11923 (if (eq (char-before) ?*) (forward-char 1))
11924 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
11925 (beginning-of-line 0)
11926 (org-indent-to-column indent)
11927 (beginning-of-line 2)
11928 (org-indent-to-column indent)
11929 (beginning-of-line 0)
11930 (if hiddenp
11931 (save-excursion
11932 (org-back-to-heading t)
11933 (hide-entry))
11934 (org-flag-drawer t))))
11936 (defun org-set-property (property value)
11937 "In the current entry, set PROPERTY to VALUE.
11938 When called interactively, this will prompt for a property name, offering
11939 completion on existing and default properties. And then it will prompt
11940 for a value, offering completion either on allowed values (via an inherited
11941 xxx_ALL property) or on existing values in other instances of this property
11942 in the current file."
11943 (interactive
11944 (let* ((completion-ignore-case t)
11945 (keys (org-buffer-property-keys nil t t))
11946 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
11947 (prop (if (member prop0 keys)
11948 prop0
11949 (or (cdr (assoc (downcase prop0)
11950 (mapcar (lambda (x) (cons (downcase x) x))
11951 keys)))
11952 prop0)))
11953 (cur (org-entry-get nil prop))
11954 (allowed (org-property-get-allowed-values nil prop 'table))
11955 (existing (mapcar 'list (org-property-values prop)))
11956 (val (if allowed
11957 (org-completing-read "Value: " allowed nil 'req-match)
11958 (let (org-completion-use-ido)
11959 (org-completing-read
11960 (concat "Value" (if (and cur (string-match "\\S-" cur))
11961 (concat "[" cur "]") "")
11962 ": ")
11963 existing nil nil "" nil cur)))))
11964 (list prop (if (equal val "") cur val))))
11965 (unless (equal (org-entry-get nil property) value)
11966 (org-entry-put nil property value)))
11968 (defun org-delete-property (property)
11969 "In the current entry, delete PROPERTY."
11970 (interactive
11971 (let* ((completion-ignore-case t)
11972 (prop (org-ido-completing-read
11973 "Property: " (org-entry-properties nil 'standard))))
11974 (list prop)))
11975 (message "Property %s %s" property
11976 (if (org-entry-delete nil property)
11977 "deleted"
11978 "was not present in the entry")))
11980 (defun org-delete-property-globally (property)
11981 "Remove PROPERTY globally, from all entries."
11982 (interactive
11983 (let* ((completion-ignore-case t)
11984 (prop (org-ido-completing-read
11985 "Globally remove property: "
11986 (mapcar 'list (org-buffer-property-keys)))))
11987 (list prop)))
11988 (save-excursion
11989 (save-restriction
11990 (widen)
11991 (goto-char (point-min))
11992 (let ((cnt 0))
11993 (while (re-search-forward
11994 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
11995 nil t)
11996 (setq cnt (1+ cnt))
11997 (replace-match ""))
11998 (message "Property \"%s\" removed from %d entries" property cnt)))))
12000 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
12002 (defun org-compute-property-at-point ()
12003 "Compute the property at point.
12004 This looks for an enclosing column format, extracts the operator and
12005 then applies it to the property in the column format's scope."
12006 (interactive)
12007 (unless (org-at-property-p)
12008 (error "Not at a property"))
12009 (let ((prop (org-match-string-no-properties 2)))
12010 (org-columns-get-format-and-top-level)
12011 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
12012 (error "No operator defined for property %s" prop))
12013 (org-columns-compute prop)))
12015 (defun org-property-get-allowed-values (pom property &optional table)
12016 "Get allowed values for the property PROPERTY.
12017 When TABLE is non-nil, return an alist that can directly be used for
12018 completion."
12019 (let (vals)
12020 (cond
12021 ((equal property "TODO")
12022 (setq vals (org-with-point-at pom
12023 (append org-todo-keywords-1 '("")))))
12024 ((equal property "PRIORITY")
12025 (let ((n org-lowest-priority))
12026 (while (>= n org-highest-priority)
12027 (push (char-to-string n) vals)
12028 (setq n (1- n)))))
12029 ((member property org-special-properties))
12031 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
12033 (when (and vals (string-match "\\S-" vals))
12034 (setq vals (car (read-from-string (concat "(" vals ")"))))
12035 (setq vals (mapcar (lambda (x)
12036 (cond ((stringp x) x)
12037 ((numberp x) (number-to-string x))
12038 ((symbolp x) (symbol-name x))
12039 (t "???")))
12040 vals)))))
12041 (if table (mapcar 'list vals) vals)))
12043 (defun org-property-previous-allowed-value (&optional previous)
12044 "Switch to the next allowed value for this property."
12045 (interactive)
12046 (org-property-next-allowed-value t))
12048 (defun org-property-next-allowed-value (&optional previous)
12049 "Switch to the next allowed value for this property."
12050 (interactive)
12051 (unless (org-at-property-p)
12052 (error "Not at a property"))
12053 (let* ((key (match-string 2))
12054 (value (match-string 3))
12055 (allowed (or (org-property-get-allowed-values (point) key)
12056 (and (member value '("[ ]" "[-]" "[X]"))
12057 '("[ ]" "[X]"))))
12058 nval)
12059 (unless allowed
12060 (error "Allowed values for this property have not been defined"))
12061 (if previous (setq allowed (reverse allowed)))
12062 (if (member value allowed)
12063 (setq nval (car (cdr (member value allowed)))))
12064 (setq nval (or nval (car allowed)))
12065 (if (equal nval value)
12066 (error "Only one allowed value for this property"))
12067 (org-at-property-p)
12068 (replace-match (concat " :" key ": " nval) t t)
12069 (org-indent-line-function)
12070 (beginning-of-line 1)
12071 (skip-chars-forward " \t")))
12073 (defun org-find-entry-with-id (ident)
12074 "Locate the entry that contains the ID property with exact value IDENT.
12075 IDENT can be a string, a symbol or a number, this function will search for
12076 the string representation of it.
12077 Return the position where this entry starts, or nil if there is no such entry."
12078 (interactive "sID: ")
12079 (let ((id (cond
12080 ((stringp ident) ident)
12081 ((symbol-name ident) (symbol-name ident))
12082 ((numberp ident) (number-to-string ident))
12083 (t (error "IDENT %s must be a string, symbol or number" ident))))
12084 (case-fold-search nil))
12085 (save-excursion
12086 (save-restriction
12087 (widen)
12088 (goto-char (point-min))
12089 (when (re-search-forward
12090 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
12091 nil t)
12092 (org-back-to-heading t)
12093 (point))))))
12095 ;;;; Timestamps
12097 (defvar org-last-changed-timestamp nil)
12098 (defvar org-last-inserted-timestamp nil
12099 "The last time stamp inserted with `org-insert-time-stamp'.")
12100 (defvar org-time-was-given) ; dynamically scoped parameter
12101 (defvar org-end-time-was-given) ; dynamically scoped parameter
12102 (defvar org-ts-what) ; dynamically scoped parameter
12104 (defun org-time-stamp (arg &optional inactive)
12105 "Prompt for a date/time and insert a time stamp.
12106 If the user specifies a time like HH:MM, or if this command is called
12107 with a prefix argument, the time stamp will contain date and time.
12108 Otherwise, only the date will be included. All parts of a date not
12109 specified by the user will be filled in from the current date/time.
12110 So if you press just return without typing anything, the time stamp
12111 will represent the current date/time. If there is already a timestamp
12112 at the cursor, it will be modified."
12113 (interactive "P")
12114 (let* ((ts nil)
12115 (default-time
12116 ;; Default time is either today, or, when entering a range,
12117 ;; the range start.
12118 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
12119 (save-excursion
12120 (re-search-backward
12121 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
12122 (- (point) 20) t)))
12123 (apply 'encode-time (org-parse-time-string (match-string 1)))
12124 (current-time)))
12125 (default-input (and ts (org-get-compact-tod ts)))
12126 org-time-was-given org-end-time-was-given time)
12127 (cond
12128 ((and (org-at-timestamp-p t)
12129 (memq last-command '(org-time-stamp org-time-stamp-inactive))
12130 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
12131 (insert "--")
12132 (setq time (let ((this-command this-command))
12133 (org-read-date arg 'totime nil nil
12134 default-time default-input)))
12135 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
12136 ((org-at-timestamp-p t)
12137 (setq time (let ((this-command this-command))
12138 (org-read-date arg 'totime nil nil default-time default-input)))
12139 (when (org-at-timestamp-p t) ; just to get the match data
12140 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
12141 (replace-match "")
12142 (setq org-last-changed-timestamp
12143 (org-insert-time-stamp
12144 time (or org-time-was-given arg)
12145 inactive nil nil (list org-end-time-was-given))))
12146 (message "Timestamp updated"))
12148 (setq time (let ((this-command this-command))
12149 (org-read-date arg 'totime nil nil default-time default-input)))
12150 (org-insert-time-stamp time (or org-time-was-given arg) inactive
12151 nil nil (list org-end-time-was-given))))))
12153 ;; FIXME: can we use this for something else, like computing time differences?
12154 (defun org-get-compact-tod (s)
12155 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
12156 (let* ((t1 (match-string 1 s))
12157 (h1 (string-to-number (match-string 2 s)))
12158 (m1 (string-to-number (match-string 3 s)))
12159 (t2 (and (match-end 4) (match-string 5 s)))
12160 (h2 (and t2 (string-to-number (match-string 6 s))))
12161 (m2 (and t2 (string-to-number (match-string 7 s))))
12162 dh dm)
12163 (if (not t2)
12165 (setq dh (- h2 h1) dm (- m2 m1))
12166 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
12167 (concat t1 "+" (number-to-string dh)
12168 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
12170 (defun org-time-stamp-inactive (&optional arg)
12171 "Insert an inactive time stamp.
12172 An inactive time stamp is enclosed in square brackets instead of angle
12173 brackets. It is inactive in the sense that it does not trigger agenda entries,
12174 does not link to the calendar and cannot be changed with the S-cursor keys.
12175 So these are more for recording a certain time/date."
12176 (interactive "P")
12177 (org-time-stamp arg 'inactive))
12179 (defvar org-date-ovl (org-make-overlay 1 1))
12180 (org-overlay-put org-date-ovl 'face 'org-warning)
12181 (org-detach-overlay org-date-ovl)
12183 (defvar org-ans1) ; dynamically scoped parameter
12184 (defvar org-ans2) ; dynamically scoped parameter
12186 (defvar org-plain-time-of-day-regexp) ; defined below
12188 (defvar org-overriding-default-time nil) ; dynamically scoped
12189 (defvar org-read-date-overlay nil)
12190 (defvar org-dcst nil) ; dynamically scoped
12191 (defvar org-read-date-history nil)
12192 (defvar org-read-date-final-answer nil)
12194 (defun org-read-date (&optional with-time to-time from-string prompt
12195 default-time default-input)
12196 "Read a date, possibly a time, and make things smooth for the user.
12197 The prompt will suggest to enter an ISO date, but you can also enter anything
12198 which will at least partially be understood by `parse-time-string'.
12199 Unrecognized parts of the date will default to the current day, month, year,
12200 hour and minute. If this command is called to replace a timestamp at point,
12201 of to enter the second timestamp of a range, the default time is taken from the
12202 existing stamp. For example,
12203 3-2-5 --> 2003-02-05
12204 feb 15 --> currentyear-02-15
12205 sep 12 9 --> 2009-09-12
12206 12:45 --> today 12:45
12207 22 sept 0:34 --> currentyear-09-22 0:34
12208 12 --> currentyear-currentmonth-12
12209 Fri --> nearest Friday (today or later)
12210 etc.
12212 Furthermore you can specify a relative date by giving, as the *first* thing
12213 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
12214 change in days weeks, months, years.
12215 With a single plus or minus, the date is relative to today. With a double
12216 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
12217 +4d --> four days from today
12218 +4 --> same as above
12219 +2w --> two weeks from today
12220 ++5 --> five days from default date
12222 The function understands only English month and weekday abbreviations,
12223 but this can be configured with the variables `parse-time-months' and
12224 `parse-time-weekdays'.
12226 While prompting, a calendar is popped up - you can also select the
12227 date with the mouse (button 1). The calendar shows a period of three
12228 months. To scroll it to other months, use the keys `>' and `<'.
12229 If you don't like the calendar, turn it off with
12230 \(setq org-read-date-popup-calendar nil)
12232 With optional argument TO-TIME, the date will immediately be converted
12233 to an internal time.
12234 With an optional argument WITH-TIME, the prompt will suggest to also
12235 insert a time. Note that when WITH-TIME is not set, you can still
12236 enter a time, and this function will inform the calling routine about
12237 this change. The calling routine may then choose to change the format
12238 used to insert the time stamp into the buffer to include the time.
12239 With optional argument FROM-STRING, read from this string instead from
12240 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
12241 the time/date that is used for everything that is not specified by the
12242 user."
12243 (require 'parse-time)
12244 (let* ((org-time-stamp-rounding-minutes
12245 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
12246 (org-dcst org-display-custom-times)
12247 (ct (org-current-time))
12248 (def (or org-overriding-default-time default-time ct))
12249 (defdecode (decode-time def))
12250 (dummy (progn
12251 (when (< (nth 2 defdecode) org-extend-today-until)
12252 (setcar (nthcdr 2 defdecode) -1)
12253 (setcar (nthcdr 1 defdecode) 59)
12254 (setq def (apply 'encode-time defdecode)
12255 defdecode (decode-time def)))))
12256 (calendar-frame-setup nil)
12257 (calendar-move-hook nil)
12258 (calendar-view-diary-initially-flag nil)
12259 (view-diary-entries-initially nil)
12260 (calendar-view-holidays-initially-flag nil)
12261 (view-calendar-holidays-initially nil)
12262 (timestr (format-time-string
12263 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
12264 (prompt (concat (if prompt (concat prompt " ") "")
12265 (format "Date+time [%s]: " timestr)))
12266 ans (org-ans0 "") org-ans1 org-ans2 final)
12268 (cond
12269 (from-string (setq ans from-string))
12270 (org-read-date-popup-calendar
12271 (save-excursion
12272 (save-window-excursion
12273 (calendar)
12274 (calendar-forward-day (- (time-to-days def)
12275 (calendar-absolute-from-gregorian
12276 (calendar-current-date))))
12277 (org-eval-in-calendar nil t)
12278 (let* ((old-map (current-local-map))
12279 (map (copy-keymap calendar-mode-map))
12280 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12281 (org-defkey map (kbd "RET") 'org-calendar-select)
12282 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
12283 'org-calendar-select-mouse)
12284 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
12285 'org-calendar-select-mouse)
12286 (org-defkey minibuffer-local-map [(meta shift left)]
12287 (lambda () (interactive)
12288 (org-eval-in-calendar '(calendar-backward-month 1))))
12289 (org-defkey minibuffer-local-map [(meta shift right)]
12290 (lambda () (interactive)
12291 (org-eval-in-calendar '(calendar-forward-month 1))))
12292 (org-defkey minibuffer-local-map [(meta shift up)]
12293 (lambda () (interactive)
12294 (org-eval-in-calendar '(calendar-backward-year 1))))
12295 (org-defkey minibuffer-local-map [(meta shift down)]
12296 (lambda () (interactive)
12297 (org-eval-in-calendar '(calendar-forward-year 1))))
12298 (org-defkey minibuffer-local-map [?\e (shift left)]
12299 (lambda () (interactive)
12300 (org-eval-in-calendar '(calendar-backward-month 1))))
12301 (org-defkey minibuffer-local-map [?\e (shift right)]
12302 (lambda () (interactive)
12303 (org-eval-in-calendar '(calendar-forward-month 1))))
12304 (org-defkey minibuffer-local-map [?\e (shift up)]
12305 (lambda () (interactive)
12306 (org-eval-in-calendar '(calendar-backward-year 1))))
12307 (org-defkey minibuffer-local-map [?\e (shift down)]
12308 (lambda () (interactive)
12309 (org-eval-in-calendar '(calendar-forward-year 1))))
12310 (org-defkey minibuffer-local-map [(shift up)]
12311 (lambda () (interactive)
12312 (org-eval-in-calendar '(calendar-backward-week 1))))
12313 (org-defkey minibuffer-local-map [(shift down)]
12314 (lambda () (interactive)
12315 (org-eval-in-calendar '(calendar-forward-week 1))))
12316 (org-defkey minibuffer-local-map [(shift left)]
12317 (lambda () (interactive)
12318 (org-eval-in-calendar '(calendar-backward-day 1))))
12319 (org-defkey minibuffer-local-map [(shift right)]
12320 (lambda () (interactive)
12321 (org-eval-in-calendar '(calendar-forward-day 1))))
12322 (org-defkey minibuffer-local-map ">"
12323 (lambda () (interactive)
12324 (org-eval-in-calendar '(scroll-calendar-left 1))))
12325 (org-defkey minibuffer-local-map "<"
12326 (lambda () (interactive)
12327 (org-eval-in-calendar '(scroll-calendar-right 1))))
12328 (run-hooks 'org-read-date-minibuffer-setup-hook)
12329 (unwind-protect
12330 (progn
12331 (use-local-map map)
12332 (add-hook 'post-command-hook 'org-read-date-display)
12333 (setq org-ans0 (read-string prompt default-input
12334 'org-read-date-history nil))
12335 ;; org-ans0: from prompt
12336 ;; org-ans1: from mouse click
12337 ;; org-ans2: from calendar motion
12338 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
12339 (remove-hook 'post-command-hook 'org-read-date-display)
12340 (use-local-map old-map)
12341 (when org-read-date-overlay
12342 (org-delete-overlay org-read-date-overlay)
12343 (setq org-read-date-overlay nil)))))))
12345 (t ; Naked prompt only
12346 (unwind-protect
12347 (setq ans (read-string prompt default-input
12348 'org-read-date-history timestr))
12349 (when org-read-date-overlay
12350 (org-delete-overlay org-read-date-overlay)
12351 (setq org-read-date-overlay nil)))))
12353 (setq final (org-read-date-analyze ans def defdecode))
12354 (setq org-read-date-final-answer ans)
12356 (if to-time
12357 (apply 'encode-time final)
12358 (if (and (boundp 'org-time-was-given) org-time-was-given)
12359 (format "%04d-%02d-%02d %02d:%02d"
12360 (nth 5 final) (nth 4 final) (nth 3 final)
12361 (nth 2 final) (nth 1 final))
12362 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
12364 (defvar def)
12365 (defvar defdecode)
12366 (defvar with-time)
12367 (defun org-read-date-display ()
12368 "Display the current date prompt interpretation in the minibuffer."
12369 (when org-read-date-display-live
12370 (when org-read-date-overlay
12371 (org-delete-overlay org-read-date-overlay))
12372 (let ((p (point)))
12373 (end-of-line 1)
12374 (while (not (equal (buffer-substring
12375 (max (point-min) (- (point) 4)) (point))
12376 " "))
12377 (insert " "))
12378 (goto-char p))
12379 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
12380 " " (or org-ans1 org-ans2)))
12381 (org-end-time-was-given nil)
12382 (f (org-read-date-analyze ans def defdecode))
12383 (fmts (if org-dcst
12384 org-time-stamp-custom-formats
12385 org-time-stamp-formats))
12386 (fmt (if (or with-time
12387 (and (boundp 'org-time-was-given) org-time-was-given))
12388 (cdr fmts)
12389 (car fmts)))
12390 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
12391 (when (and org-end-time-was-given
12392 (string-match org-plain-time-of-day-regexp txt))
12393 (setq txt (concat (substring txt 0 (match-end 0)) "-"
12394 org-end-time-was-given
12395 (substring txt (match-end 0)))))
12396 (setq org-read-date-overlay
12397 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
12398 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
12400 (defun org-read-date-analyze (ans def defdecode)
12401 "Analyse the combined answer of the date prompt."
12402 ;; FIXME: cleanup and comment
12403 (let (delta deltan deltaw deltadef year month day
12404 hour minute second wday pm h2 m2 tl wday1
12405 iso-year iso-weekday iso-week iso-year iso-date)
12407 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
12408 (setq ans "+0"))
12410 (when (setq delta (org-read-date-get-relative ans (current-time) def))
12411 (setq ans (replace-match "" t t ans)
12412 deltan (car delta)
12413 deltaw (nth 1 delta)
12414 deltadef (nth 2 delta)))
12416 ;; Check if there is an iso week date in there
12417 ;; If yes, sore the info and postpone interpreting it until the rest
12418 ;; of the parsing is done
12419 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
12420 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
12421 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
12422 iso-week (string-to-number (match-string 2 ans)))
12423 (setq ans (replace-match "" t t ans)))
12425 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
12426 (when (string-match
12427 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
12428 (setq year (if (match-end 2)
12429 (string-to-number (match-string 2 ans))
12430 (string-to-number (format-time-string "%Y")))
12431 month (string-to-number (match-string 3 ans))
12432 day (string-to-number (match-string 4 ans)))
12433 (if (< year 100) (setq year (+ 2000 year)))
12434 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
12435 t nil ans)))
12436 ;; Help matching am/pm times, because `parse-time-string' does not do that.
12437 ;; If there is a time with am/pm, and *no* time without it, we convert
12438 ;; so that matching will be successful.
12439 (loop for i from 1 to 2 do ; twice, for end time as well
12440 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
12441 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
12442 (setq hour (string-to-number (match-string 1 ans))
12443 minute (if (match-end 3)
12444 (string-to-number (match-string 3 ans))
12446 pm (equal ?p
12447 (string-to-char (downcase (match-string 4 ans)))))
12448 (if (and (= hour 12) (not pm))
12449 (setq hour 0)
12450 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
12451 (setq ans (replace-match (format "%02d:%02d" hour minute)
12452 t t ans))))
12454 ;; Check if a time range is given as a duration
12455 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
12456 (setq hour (string-to-number (match-string 1 ans))
12457 h2 (+ hour (string-to-number (match-string 3 ans)))
12458 minute (string-to-number (match-string 2 ans))
12459 m2 (+ minute (if (match-end 5) (string-to-number
12460 (match-string 5 ans))0)))
12461 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
12462 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
12463 t t ans)))
12465 ;; Check if there is a time range
12466 (when (boundp 'org-end-time-was-given)
12467 (setq org-time-was-given nil)
12468 (when (and (string-match org-plain-time-of-day-regexp ans)
12469 (match-end 8))
12470 (setq org-end-time-was-given (match-string 8 ans))
12471 (setq ans (concat (substring ans 0 (match-beginning 7))
12472 (substring ans (match-end 7))))))
12474 (setq tl (parse-time-string ans)
12475 day (or (nth 3 tl) (nth 3 defdecode))
12476 month (or (nth 4 tl)
12477 (if (and org-read-date-prefer-future
12478 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
12479 (1+ (nth 4 defdecode))
12480 (nth 4 defdecode)))
12481 year (or (nth 5 tl)
12482 (if (and org-read-date-prefer-future
12483 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
12484 (1+ (nth 5 defdecode))
12485 (nth 5 defdecode)))
12486 hour (or (nth 2 tl) (nth 2 defdecode))
12487 minute (or (nth 1 tl) (nth 1 defdecode))
12488 second (or (nth 0 tl) 0)
12489 wday (nth 6 tl))
12491 ;; Special date definitions below
12492 (cond
12493 (iso-week
12494 ;; There was an iso week
12495 (setq year (or iso-year year)
12496 day (or iso-weekday wday 1)
12497 wday nil ; to make sure that the trigger below does not match
12498 iso-date (calendar-gregorian-from-absolute
12499 (calendar-absolute-from-iso
12500 (list iso-week day year))))
12501 ; FIXME: Should we also push ISO weeks into the future?
12502 ; (when (and org-read-date-prefer-future
12503 ; (not iso-year)
12504 ; (< (calendar-absolute-from-gregorian iso-date)
12505 ; (time-to-days (current-time))))
12506 ; (setq year (1+ year)
12507 ; iso-date (calendar-gregorian-from-absolute
12508 ; (calendar-absolute-from-iso
12509 ; (list iso-week day year)))))
12510 (setq month (car iso-date)
12511 year (nth 2 iso-date)
12512 day (nth 1 iso-date)))
12513 (deltan
12514 (unless deltadef
12515 (let ((now (decode-time (current-time))))
12516 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
12517 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
12518 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
12519 ((equal deltaw "m") (setq month (+ month deltan)))
12520 ((equal deltaw "y") (setq year (+ year deltan)))))
12521 ((and wday (not (nth 3 tl)))
12522 ;; Weekday was given, but no day, so pick that day in the week
12523 ;; on or after the derived date.
12524 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
12525 (unless (equal wday wday1)
12526 (setq day (+ day (% (- wday wday1 -7) 7))))))
12527 (if (and (boundp 'org-time-was-given)
12528 (nth 2 tl))
12529 (setq org-time-was-given t))
12530 (if (< year 100) (setq year (+ 2000 year)))
12531 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
12532 (list second minute hour day month year)))
12534 (defvar parse-time-weekdays)
12536 (defun org-read-date-get-relative (s today default)
12537 "Check string S for special relative date string.
12538 TODAY and DEFAULT are internal times, for today and for a default.
12539 Return shift list (N what def-flag)
12540 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
12541 N is the number of WHATs to shift.
12542 DEF-FLAG is t when a double ++ or -- indicates shift relative to
12543 the DEFAULT date rather than TODAY."
12544 (when (and
12545 (string-match
12546 (concat
12547 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
12548 "\\([0-9]+\\)?"
12549 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
12550 "\\([ \t]\\|$\\)") s)
12551 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
12552 (let* ((dir (if (> (match-end 1) (match-beginning 1))
12553 (string-to-char (substring (match-string 1 s) -1))
12554 ?+))
12555 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
12556 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
12557 (what (if (match-end 3) (match-string 3 s) "d"))
12558 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
12559 (date (if rel default today))
12560 (wday (nth 6 (decode-time date)))
12561 delta)
12562 (if wday1
12563 (progn
12564 (setq delta (mod (+ 7 (- wday1 wday)) 7))
12565 (if (= dir ?-) (setq delta (- delta 7)))
12566 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
12567 (list delta "d" rel))
12568 (list (* n (if (= dir ?-) -1 1)) what rel)))))
12570 (defun org-eval-in-calendar (form &optional keepdate)
12571 "Eval FORM in the calendar window and return to current window.
12572 Also, store the cursor date in variable org-ans2."
12573 (let ((sf (selected-frame))
12574 (sw (selected-window)))
12575 (select-window (get-buffer-window "*Calendar*" t))
12576 (eval form)
12577 (when (and (not keepdate) (calendar-cursor-to-date))
12578 (let* ((date (calendar-cursor-to-date))
12579 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12580 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
12581 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
12582 (select-window sw)
12583 (select-frame-set-input-focus sf)))
12585 (defun org-calendar-select ()
12586 "Return to `org-read-date' with the date currently selected.
12587 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12588 (interactive)
12589 (when (calendar-cursor-to-date)
12590 (let* ((date (calendar-cursor-to-date))
12591 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12592 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12593 (if (active-minibuffer-window) (exit-minibuffer))))
12595 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
12596 "Insert a date stamp for the date given by the internal TIME.
12597 WITH-HM means, use the stamp format that includes the time of the day.
12598 INACTIVE means use square brackets instead of angular ones, so that the
12599 stamp will not contribute to the agenda.
12600 PRE and POST are optional strings to be inserted before and after the
12601 stamp.
12602 The command returns the inserted time stamp."
12603 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
12604 stamp)
12605 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
12606 (insert-before-markers (or pre ""))
12607 (insert-before-markers (setq stamp (format-time-string fmt time)))
12608 (when (listp extra)
12609 (setq extra (car extra))
12610 (if (and (stringp extra)
12611 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
12612 (setq extra (format "-%02d:%02d"
12613 (string-to-number (match-string 1 extra))
12614 (string-to-number (match-string 2 extra))))
12615 (setq extra nil)))
12616 (when extra
12617 (backward-char 1)
12618 (insert-before-markers extra)
12619 (forward-char 1))
12620 (insert-before-markers (or post ""))
12621 (setq org-last-inserted-timestamp stamp)))
12623 (defun org-toggle-time-stamp-overlays ()
12624 "Toggle the use of custom time stamp formats."
12625 (interactive)
12626 (setq org-display-custom-times (not org-display-custom-times))
12627 (unless org-display-custom-times
12628 (let ((p (point-min)) (bmp (buffer-modified-p)))
12629 (while (setq p (next-single-property-change p 'display))
12630 (if (and (get-text-property p 'display)
12631 (eq (get-text-property p 'face) 'org-date))
12632 (remove-text-properties
12633 p (setq p (next-single-property-change p 'display))
12634 '(display t))))
12635 (set-buffer-modified-p bmp)))
12636 (if (featurep 'xemacs)
12637 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12638 (org-restart-font-lock)
12639 (setq org-table-may-need-update t)
12640 (if org-display-custom-times
12641 (message "Time stamps are overlayed with custom format")
12642 (message "Time stamp overlays removed")))
12644 (defun org-display-custom-time (beg end)
12645 "Overlay modified time stamp format over timestamp between BEG and END."
12646 (let* ((ts (buffer-substring beg end))
12647 t1 w1 with-hm tf time str w2 (off 0))
12648 (save-match-data
12649 (setq t1 (org-parse-time-string ts t))
12650 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
12651 (setq off (- (match-end 0) (match-beginning 0)))))
12652 (setq end (- end off))
12653 (setq w1 (- end beg)
12654 with-hm (and (nth 1 t1) (nth 2 t1))
12655 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
12656 time (org-fix-decoded-time t1)
12657 str (org-add-props
12658 (format-time-string
12659 (substring tf 1 -1) (apply 'encode-time time))
12660 nil 'mouse-face 'highlight)
12661 w2 (length str))
12662 (if (not (= w2 w1))
12663 (add-text-properties (1+ beg) (+ 2 beg)
12664 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12665 (if (featurep 'xemacs)
12666 (progn
12667 (put-text-property beg end 'invisible t)
12668 (put-text-property beg end 'end-glyph (make-glyph str)))
12669 (put-text-property beg end 'display str))))
12671 (defun org-translate-time (string)
12672 "Translate all timestamps in STRING to custom format.
12673 But do this only if the variable `org-display-custom-times' is set."
12674 (when org-display-custom-times
12675 (save-match-data
12676 (let* ((start 0)
12677 (re org-ts-regexp-both)
12678 t1 with-hm inactive tf time str beg end)
12679 (while (setq start (string-match re string start))
12680 (setq beg (match-beginning 0)
12681 end (match-end 0)
12682 t1 (save-match-data
12683 (org-parse-time-string (substring string beg end) t))
12684 with-hm (and (nth 1 t1) (nth 2 t1))
12685 inactive (equal (substring string beg (1+ beg)) "[")
12686 tf (funcall (if with-hm 'cdr 'car)
12687 org-time-stamp-custom-formats)
12688 time (org-fix-decoded-time t1)
12689 str (format-time-string
12690 (concat
12691 (if inactive "[" "<") (substring tf 1 -1)
12692 (if inactive "]" ">"))
12693 (apply 'encode-time time))
12694 string (replace-match str t t string)
12695 start (+ start (length str)))))))
12696 string)
12698 (defun org-fix-decoded-time (time)
12699 "Set 0 instead of nil for the first 6 elements of time.
12700 Don't touch the rest."
12701 (let ((n 0))
12702 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12704 (defun org-days-to-time (timestamp-string)
12705 "Difference between TIMESTAMP-STRING and now in days."
12706 (- (time-to-days (org-time-string-to-time timestamp-string))
12707 (time-to-days (current-time))))
12709 (defun org-deadline-close (timestamp-string &optional ndays)
12710 "Is the time in TIMESTAMP-STRING close to the current date?"
12711 (setq ndays (or ndays (org-get-wdays timestamp-string)))
12712 (and (< (org-days-to-time timestamp-string) ndays)
12713 (not (org-entry-is-done-p))))
12715 (defun org-get-wdays (ts)
12716 "Get the deadline lead time appropriate for timestring TS."
12717 (cond
12718 ((<= org-deadline-warning-days 0)
12719 ;; 0 or negative, enforce this value no matter what
12720 (- org-deadline-warning-days))
12721 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
12722 ;; lead time is specified.
12723 (floor (* (string-to-number (match-string 1 ts))
12724 (cdr (assoc (match-string 2 ts)
12725 '(("d" . 1) ("w" . 7)
12726 ("m" . 30.4) ("y" . 365.25)))))))
12727 ;; go for the default.
12728 (t org-deadline-warning-days)))
12730 (defun org-calendar-select-mouse (ev)
12731 "Return to `org-read-date' with the date currently selected.
12732 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12733 (interactive "e")
12734 (mouse-set-point ev)
12735 (when (calendar-cursor-to-date)
12736 (let* ((date (calendar-cursor-to-date))
12737 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12738 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12739 (if (active-minibuffer-window) (exit-minibuffer))))
12741 (defun org-check-deadlines (ndays)
12742 "Check if there are any deadlines due or past due.
12743 A deadline is considered due if it happens within `org-deadline-warning-days'
12744 days from today's date. If the deadline appears in an entry marked DONE,
12745 it is not shown. The prefix arg NDAYS can be used to test that many
12746 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12747 (interactive "P")
12748 (let* ((org-warn-days
12749 (cond
12750 ((equal ndays '(4)) 100000)
12751 (ndays (prefix-numeric-value ndays))
12752 (t (abs org-deadline-warning-days))))
12753 (case-fold-search nil)
12754 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12755 (callback
12756 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12758 (message "%d deadlines past-due or due within %d days"
12759 (org-occur regexp nil callback)
12760 org-warn-days)))
12762 (defun org-check-before-date (date)
12763 "Check if there are deadlines or scheduled entries before DATE."
12764 (interactive (list (org-read-date)))
12765 (let ((case-fold-search nil)
12766 (regexp (concat "\\<\\(" org-deadline-string
12767 "\\|" org-scheduled-string
12768 "\\) *<\\([^>]+\\)>"))
12769 (callback
12770 (lambda () (time-less-p
12771 (org-time-string-to-time (match-string 2))
12772 (org-time-string-to-time date)))))
12773 (message "%d entries before %s"
12774 (org-occur regexp nil callback) date)))
12776 (defun org-check-after-date (date)
12777 "Check if there are deadlines or scheduled entries after DATE."
12778 (interactive (list (org-read-date)))
12779 (let ((case-fold-search nil)
12780 (regexp (concat "\\<\\(" org-deadline-string
12781 "\\|" org-scheduled-string
12782 "\\) *<\\([^>]+\\)>"))
12783 (callback
12784 (lambda () (not
12785 (time-less-p
12786 (org-time-string-to-time (match-string 2))
12787 (org-time-string-to-time date))))))
12788 (message "%d entries after %s"
12789 (org-occur regexp nil callback) date)))
12791 (defun org-evaluate-time-range (&optional to-buffer)
12792 "Evaluate a time range by computing the difference between start and end.
12793 Normally the result is just printed in the echo area, but with prefix arg
12794 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12795 If the time range is actually in a table, the result is inserted into the
12796 next column.
12797 For time difference computation, a year is assumed to be exactly 365
12798 days in order to avoid rounding problems."
12799 (interactive "P")
12801 (org-clock-update-time-maybe)
12802 (save-excursion
12803 (unless (org-at-date-range-p t)
12804 (goto-char (point-at-bol))
12805 (re-search-forward org-tr-regexp-both (point-at-eol) t))
12806 (if (not (org-at-date-range-p t))
12807 (error "Not at a time-stamp range, and none found in current line")))
12808 (let* ((ts1 (match-string 1))
12809 (ts2 (match-string 2))
12810 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12811 (match-end (match-end 0))
12812 (time1 (org-time-string-to-time ts1))
12813 (time2 (org-time-string-to-time ts2))
12814 (t1 (time-to-seconds time1))
12815 (t2 (time-to-seconds time2))
12816 (diff (abs (- t2 t1)))
12817 (negative (< (- t2 t1) 0))
12818 ;; (ys (floor (* 365 24 60 60)))
12819 (ds (* 24 60 60))
12820 (hs (* 60 60))
12821 (fy "%dy %dd %02d:%02d")
12822 (fy1 "%dy %dd")
12823 (fd "%dd %02d:%02d")
12824 (fd1 "%dd")
12825 (fh "%02d:%02d")
12826 y d h m align)
12827 (if havetime
12828 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12830 d (floor (/ diff ds)) diff (mod diff ds)
12831 h (floor (/ diff hs)) diff (mod diff hs)
12832 m (floor (/ diff 60)))
12833 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12835 d (floor (+ (/ diff ds) 0.5))
12836 h 0 m 0))
12837 (if (not to-buffer)
12838 (message "%s" (org-make-tdiff-string y d h m))
12839 (if (org-at-table-p)
12840 (progn
12841 (goto-char match-end)
12842 (setq align t)
12843 (and (looking-at " *|") (goto-char (match-end 0))))
12844 (goto-char match-end))
12845 (if (looking-at
12846 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12847 (replace-match ""))
12848 (if negative (insert " -"))
12849 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12850 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12851 (insert " " (format fh h m))))
12852 (if align (org-table-align))
12853 (message "Time difference inserted")))))
12855 (defun org-make-tdiff-string (y d h m)
12856 (let ((fmt "")
12857 (l nil))
12858 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12859 l (push y l)))
12860 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12861 l (push d l)))
12862 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12863 l (push h l)))
12864 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12865 l (push m l)))
12866 (apply 'format fmt (nreverse l))))
12868 (defun org-time-string-to-time (s)
12869 (apply 'encode-time (org-parse-time-string s)))
12870 (defun org-time-string-to-seconds (s)
12871 (time-to-seconds (org-time-string-to-time s)))
12873 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
12874 "Convert a time stamp to an absolute day number.
12875 If there is a specifyer for a cyclic time stamp, get the closest date to
12876 DAYNR.
12877 PREFER and SHOW-ALL are passed through to `org-closest-date'.
12878 the variable date is bound by the calendar when this is called."
12879 (cond
12880 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
12881 (if (org-diary-sexp-entry (match-string 1 s) "" date)
12882 daynr
12883 (+ daynr 1000)))
12884 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
12885 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
12886 (time-to-days (current-time))) (match-string 0 s)
12887 prefer show-all))
12888 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
12890 (defun org-days-to-iso-week (days)
12891 "Return the iso week number."
12892 (require 'cal-iso)
12893 (car (calendar-iso-from-absolute days)))
12895 (defun org-small-year-to-year (year)
12896 "Convert 2-digit years into 4-digit years.
12897 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
12898 The year 2000 cannot be abbreviated. Any year larger than 99
12899 is returned unchanged."
12900 (if (< year 38)
12901 (setq year (+ 2000 year))
12902 (if (< year 100)
12903 (setq year (+ 1900 year))))
12904 year)
12906 (defun org-time-from-absolute (d)
12907 "Return the time corresponding to date D.
12908 D may be an absolute day number, or a calendar-type list (month day year)."
12909 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
12910 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
12912 (defun org-calendar-holiday ()
12913 "List of holidays, for Diary display in Org-mode."
12914 (require 'holidays)
12915 (let ((hl (funcall
12916 (if (fboundp 'calendar-check-holidays)
12917 'calendar-check-holidays 'check-calendar-holidays) date)))
12918 (if hl (mapconcat 'identity hl "; "))))
12920 (defun org-diary-sexp-entry (sexp entry date)
12921 "Process a SEXP diary ENTRY for DATE."
12922 (require 'diary-lib)
12923 (let ((result (if calendar-debug-sexp
12924 (let ((stack-trace-on-error t))
12925 (eval (car (read-from-string sexp))))
12926 (condition-case nil
12927 (eval (car (read-from-string sexp)))
12928 (error
12929 (beep)
12930 (message "Bad sexp at line %d in %s: %s"
12931 (org-current-line)
12932 (buffer-file-name) sexp)
12933 (sleep-for 2))))))
12934 (cond ((stringp result) result)
12935 ((and (consp result)
12936 (stringp (cdr result))) (cdr result))
12937 (result entry)
12938 (t nil))))
12940 (defun org-diary-to-ical-string (frombuf)
12941 "Get iCalendar entries from diary entries in buffer FROMBUF.
12942 This uses the icalendar.el library."
12943 (let* ((tmpdir (if (featurep 'xemacs)
12944 (temp-directory)
12945 temporary-file-directory))
12946 (tmpfile (make-temp-name
12947 (expand-file-name "orgics" tmpdir)))
12948 buf rtn b e)
12949 (save-excursion
12950 (set-buffer frombuf)
12951 (icalendar-export-region (point-min) (point-max) tmpfile)
12952 (setq buf (find-buffer-visiting tmpfile))
12953 (set-buffer buf)
12954 (goto-char (point-min))
12955 (if (re-search-forward "^BEGIN:VEVENT" nil t)
12956 (setq b (match-beginning 0)))
12957 (goto-char (point-max))
12958 (if (re-search-backward "^END:VEVENT" nil t)
12959 (setq e (match-end 0)))
12960 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
12961 (kill-buffer buf)
12962 (delete-file tmpfile)
12963 rtn))
12965 (defun org-closest-date (start current change prefer show-all)
12966 "Find the date closest to CURRENT that is consistent with START and CHANGE.
12967 When PREFER is `past' return a date that is either CURRENT or past.
12968 When PREFER is `future', return a date that is either CURRENT or future.
12969 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
12970 ;; Make the proper lists from the dates
12971 (catch 'exit
12972 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
12973 dn dw sday cday n1 n2 n0
12974 d m y y1 y2 date1 date2 nmonths nm ny m2)
12976 (setq start (org-date-to-gregorian start)
12977 current (org-date-to-gregorian
12978 (if show-all
12979 current
12980 (time-to-days (current-time))))
12981 sday (calendar-absolute-from-gregorian start)
12982 cday (calendar-absolute-from-gregorian current))
12984 (if (<= cday sday) (throw 'exit sday))
12986 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
12987 (setq dn (string-to-number (match-string 1 change))
12988 dw (cdr (assoc (match-string 2 change) a1)))
12989 (error "Invalid change specifyer: %s" change))
12990 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
12991 (cond
12992 ((eq dw 'day)
12993 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
12994 n2 (+ n1 dn)))
12995 ((eq dw 'year)
12996 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
12997 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
12998 (setq date1 (list m d y1)
12999 n1 (calendar-absolute-from-gregorian date1)
13000 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
13001 n2 (calendar-absolute-from-gregorian date2)))
13002 ((eq dw 'month)
13003 ;; approx number of month between the two dates
13004 (setq nmonths (floor (/ (- cday sday) 30.436875)))
13005 ;; How often does dn fit in there?
13006 (setq d (nth 1 start) m (car start) y (nth 2 start)
13007 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
13008 m (+ m nm)
13009 ny (floor (/ m 12))
13010 y (+ y ny)
13011 m (- m (* ny 12)))
13012 (while (> m 12) (setq m (- m 12) y (1+ y)))
13013 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
13014 (setq m2 (+ m dn) y2 y)
13015 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13016 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
13017 (while (<= n2 cday)
13018 (setq n1 n2 m m2 y y2)
13019 (setq m2 (+ m dn) y2 y)
13020 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13021 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
13022 ;; Make sure n1 is the earlier date
13023 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
13024 (if show-all
13025 (cond
13026 ((eq prefer 'past) n1)
13027 ((eq prefer 'future) (if (= cday n1) n1 n2))
13028 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
13029 (cond
13030 ((eq prefer 'past) n1)
13031 ((eq prefer 'future) (if (= cday n1) n1 n2))
13032 (t (if (= cday n1) n1 n2)))))))
13034 (defun org-date-to-gregorian (date)
13035 "Turn any specification of DATE into a gregorian date for the calendar."
13036 (cond ((integerp date) (calendar-gregorian-from-absolute date))
13037 ((and (listp date) (= (length date) 3)) date)
13038 ((stringp date)
13039 (setq date (org-parse-time-string date))
13040 (list (nth 4 date) (nth 3 date) (nth 5 date)))
13041 ((listp date)
13042 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
13044 (defun org-parse-time-string (s &optional nodefault)
13045 "Parse the standard Org-mode time string.
13046 This should be a lot faster than the normal `parse-time-string'.
13047 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
13048 hour and minute fields will be nil if not given."
13049 (if (string-match org-ts-regexp0 s)
13050 (list 0
13051 (if (or (match-beginning 8) (not nodefault))
13052 (string-to-number (or (match-string 8 s) "0")))
13053 (if (or (match-beginning 7) (not nodefault))
13054 (string-to-number (or (match-string 7 s) "0")))
13055 (string-to-number (match-string 4 s))
13056 (string-to-number (match-string 3 s))
13057 (string-to-number (match-string 2 s))
13058 nil nil nil)
13059 (make-list 9 0)))
13061 (defun org-timestamp-up (&optional arg)
13062 "Increase the date item at the cursor by one.
13063 If the cursor is on the year, change the year. If it is on the month or
13064 the day, change that.
13065 With prefix ARG, change by that many units."
13066 (interactive "p")
13067 (org-timestamp-change (prefix-numeric-value arg)))
13069 (defun org-timestamp-down (&optional arg)
13070 "Decrease the date item at the cursor by one.
13071 If the cursor is on the year, change the year. If it is on the month or
13072 the day, change that.
13073 With prefix ARG, change by that many units."
13074 (interactive "p")
13075 (org-timestamp-change (- (prefix-numeric-value arg))))
13077 (defun org-timestamp-up-day (&optional arg)
13078 "Increase the date in the time stamp by one day.
13079 With prefix ARG, change that many days."
13080 (interactive "p")
13081 (if (and (not (org-at-timestamp-p t))
13082 (org-on-heading-p))
13083 (org-todo 'up)
13084 (org-timestamp-change (prefix-numeric-value arg) 'day)))
13086 (defun org-timestamp-down-day (&optional arg)
13087 "Decrease the date in the time stamp by one day.
13088 With prefix ARG, change that many days."
13089 (interactive "p")
13090 (if (and (not (org-at-timestamp-p t))
13091 (org-on-heading-p))
13092 (org-todo 'down)
13093 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
13095 (defun org-at-timestamp-p (&optional inactive-ok)
13096 "Determine if the cursor is in or at a timestamp."
13097 (interactive)
13098 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
13099 (pos (point))
13100 (ans (or (looking-at tsr)
13101 (save-excursion
13102 (skip-chars-backward "^[<\n\r\t")
13103 (if (> (point) (point-min)) (backward-char 1))
13104 (and (looking-at tsr)
13105 (> (- (match-end 0) pos) -1))))))
13106 (and ans
13107 (boundp 'org-ts-what)
13108 (setq org-ts-what
13109 (cond
13110 ((= pos (match-beginning 0)) 'bracket)
13111 ((= pos (1- (match-end 0))) 'bracket)
13112 ((org-pos-in-match-range pos 2) 'year)
13113 ((org-pos-in-match-range pos 3) 'month)
13114 ((org-pos-in-match-range pos 7) 'hour)
13115 ((org-pos-in-match-range pos 8) 'minute)
13116 ((or (org-pos-in-match-range pos 4)
13117 (org-pos-in-match-range pos 5)) 'day)
13118 ((and (> pos (or (match-end 8) (match-end 5)))
13119 (< pos (match-end 0)))
13120 (- pos (or (match-end 8) (match-end 5))))
13121 (t 'day))))
13122 ans))
13124 (defun org-toggle-timestamp-type ()
13125 "Toggle the type (<active> or [inactive]) of a time stamp."
13126 (interactive)
13127 (when (org-at-timestamp-p t)
13128 (let ((beg (match-beginning 0)) (end (match-end 0))
13129 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
13130 (save-excursion
13131 (goto-char beg)
13132 (while (re-search-forward "[][<>]" end t)
13133 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
13134 t t)))
13135 (message "Timestamp is now %sactive"
13136 (if (equal (char-after beg) ?<) "" "in")))))
13138 (defun org-timestamp-change (n &optional what)
13139 "Change the date in the time stamp at point.
13140 The date will be changed by N times WHAT. WHAT can be `day', `month',
13141 `year', `minute', `second'. If WHAT is not given, the cursor position
13142 in the timestamp determines what will be changed."
13143 (let ((pos (point))
13144 with-hm inactive
13145 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
13146 org-ts-what
13147 extra rem
13148 ts time time0)
13149 (if (not (org-at-timestamp-p t))
13150 (error "Not at a timestamp"))
13151 (if (and (not what) (eq org-ts-what 'bracket))
13152 (org-toggle-timestamp-type)
13153 (if (and (not what) (not (eq org-ts-what 'day))
13154 org-display-custom-times
13155 (get-text-property (point) 'display)
13156 (not (get-text-property (1- (point)) 'display)))
13157 (setq org-ts-what 'day))
13158 (setq org-ts-what (or what org-ts-what)
13159 inactive (= (char-after (match-beginning 0)) ?\[)
13160 ts (match-string 0))
13161 (replace-match "")
13162 (if (string-match
13163 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
13165 (setq extra (match-string 1 ts)))
13166 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
13167 (setq with-hm t))
13168 (setq time0 (org-parse-time-string ts))
13169 (when (and (eq org-ts-what 'minute)
13170 (eq current-prefix-arg nil))
13171 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
13172 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
13173 (setcar (cdr time0) (+ (nth 1 time0)
13174 (if (> n 0) (- rem) (- dm rem))))))
13175 (setq time
13176 (encode-time (or (car time0) 0)
13177 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
13178 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
13179 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
13180 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
13181 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
13182 (nthcdr 6 time0)))
13183 (when (and (member org-ts-what '(hour minute))
13184 extra
13185 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
13186 (setq extra (org-modify-ts-extra
13187 extra
13188 (if (eq org-ts-what 'hour) 2 5)
13189 n dm)))
13190 (when (integerp org-ts-what)
13191 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
13192 (if (eq what 'calendar)
13193 (let ((cal-date (org-get-date-from-calendar)))
13194 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
13195 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
13196 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
13197 (setcar time0 (or (car time0) 0))
13198 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
13199 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
13200 (setq time (apply 'encode-time time0))))
13201 (setq org-last-changed-timestamp
13202 (org-insert-time-stamp time with-hm inactive nil nil extra))
13203 (org-clock-update-time-maybe)
13204 (goto-char pos)
13205 ;; Try to recenter the calendar window, if any
13206 (if (and org-calendar-follow-timestamp-change
13207 (get-buffer-window "*Calendar*" t)
13208 (memq org-ts-what '(day month year)))
13209 (org-recenter-calendar (time-to-days time))))))
13211 (defun org-modify-ts-extra (s pos n dm)
13212 "Change the different parts of the lead-time and repeat fields in timestamp."
13213 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
13214 ng h m new rem)
13215 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
13216 (cond
13217 ((or (org-pos-in-match-range pos 2)
13218 (org-pos-in-match-range pos 3))
13219 (setq m (string-to-number (match-string 3 s))
13220 h (string-to-number (match-string 2 s)))
13221 (if (org-pos-in-match-range pos 2)
13222 (setq h (+ h n))
13223 (setq n (* dm (org-no-warnings (signum n))))
13224 (when (not (= 0 (setq rem (% m dm))))
13225 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
13226 (setq m (+ m n)))
13227 (if (< m 0) (setq m (+ m 60) h (1- h)))
13228 (if (> m 59) (setq m (- m 60) h (1+ h)))
13229 (setq h (min 24 (max 0 h)))
13230 (setq ng 1 new (format "-%02d:%02d" h m)))
13231 ((org-pos-in-match-range pos 6)
13232 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
13233 ((org-pos-in-match-range pos 5)
13234 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
13236 ((org-pos-in-match-range pos 9)
13237 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
13238 ((org-pos-in-match-range pos 8)
13239 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
13241 (when ng
13242 (setq s (concat
13243 (substring s 0 (match-beginning ng))
13245 (substring s (match-end ng))))))
13248 (defun org-recenter-calendar (date)
13249 "If the calendar is visible, recenter it to DATE."
13250 (let* ((win (selected-window))
13251 (cwin (get-buffer-window "*Calendar*" t))
13252 (calendar-move-hook nil))
13253 (when cwin
13254 (select-window cwin)
13255 (calendar-goto-date (if (listp date) date
13256 (calendar-gregorian-from-absolute date)))
13257 (select-window win))))
13259 (defun org-goto-calendar (&optional arg)
13260 "Go to the Emacs calendar at the current date.
13261 If there is a time stamp in the current line, go to that date.
13262 A prefix ARG can be used to force the current date."
13263 (interactive "P")
13264 (let ((tsr org-ts-regexp) diff
13265 (calendar-move-hook nil)
13266 (calendar-view-holidays-initially-flag nil)
13267 (view-calendar-holidays-initially nil)
13268 (calendar-view-diary-initially-flag nil)
13269 (view-diary-entries-initially nil))
13270 (if (or (org-at-timestamp-p)
13271 (save-excursion
13272 (beginning-of-line 1)
13273 (looking-at (concat ".*" tsr))))
13274 (let ((d1 (time-to-days (current-time)))
13275 (d2 (time-to-days
13276 (org-time-string-to-time (match-string 1)))))
13277 (setq diff (- d2 d1))))
13278 (calendar)
13279 (calendar-goto-today)
13280 (if (and diff (not arg)) (calendar-forward-day diff))))
13282 (defun org-get-date-from-calendar ()
13283 "Return a list (month day year) of date at point in calendar."
13284 (with-current-buffer "*Calendar*"
13285 (save-match-data
13286 (calendar-cursor-to-date))))
13288 (defun org-date-from-calendar ()
13289 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
13290 If there is already a time stamp at the cursor position, update it."
13291 (interactive)
13292 (if (org-at-timestamp-p t)
13293 (org-timestamp-change 0 'calendar)
13294 (let ((cal-date (org-get-date-from-calendar)))
13295 (org-insert-time-stamp
13296 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
13298 (defun org-minutes-to-hh:mm-string (m)
13299 "Compute H:MM from a number of minutes."
13300 (let ((h (/ m 60)))
13301 (setq m (- m (* 60 h)))
13302 (format org-time-clocksum-format h m)))
13304 (defun org-hh:mm-string-to-minutes (s)
13305 "Convert a string H:MM to a number of minutes.
13306 If the string is just a number, interprete it as minutes.
13307 In fact, the first hh:mm or number in the string will be taken,
13308 there can be extra stuff in the string.
13309 If no number is found, the return value is 0."
13310 (cond
13311 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
13312 (+ (* (string-to-number (match-string 1 s)) 60)
13313 (string-to-number (match-string 2 s))))
13314 ((string-match "\\([0-9]+\\)" s)
13315 (string-to-number (match-string 1 s)))
13316 (t 0)))
13318 ;;;; Files
13320 (defun org-save-all-org-buffers ()
13321 "Save all Org-mode buffers without user confirmation."
13322 (interactive)
13323 (message "Saving all Org-mode buffers...")
13324 (save-some-buffers t 'org-mode-p)
13325 (when (featurep 'org-id) (org-id-locations-save))
13326 (message "Saving all Org-mode buffers... done"))
13328 (defun org-revert-all-org-buffers ()
13329 "Revert all Org-mode buffers.
13330 Prompt for confirmation when there are unsaved changes.
13331 Be sure you know what you are doing before letting this function
13332 overwrite your changes.
13334 This function is useful in a setup where one tracks org files
13335 with a version control system, to revert on one machine after pulling
13336 changes from another. I believe the procedure must be like this:
13338 1. M-x org-save-all-org-buffers
13339 2. Pull changes from the other machine, resolve conflicts
13340 3. M-x org-revert-all-org-buffers"
13341 (interactive)
13342 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
13343 (error "Abort"))
13344 (save-excursion
13345 (save-window-excursion
13346 (mapc
13347 (lambda (b)
13348 (when (and (with-current-buffer b (org-mode-p))
13349 (with-current-buffer b buffer-file-name))
13350 (switch-to-buffer b)
13351 (revert-buffer t 'no-confirm)))
13352 (buffer-list))
13353 (when (and (featurep 'org-id) org-id-track-globally)
13354 (org-id-locations-load)))))
13356 ;;;; Agenda files
13358 ;;;###autoload
13359 (defun org-iswitchb (&optional arg)
13360 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
13361 With a prefix argument, restrict available to files.
13362 With two prefix arguments, restrict available buffers to agenda files.
13364 Due to some yet unresolved reason, the global function
13365 `iswitchb-mode' needs to be active for this function to work."
13366 (interactive "P")
13367 (require 'iswitchb)
13368 (let ((enabled iswitchb-mode) blist)
13369 (or enabled (iswitchb-mode 1))
13370 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13371 ((equal arg '(16)) (org-buffer-list 'agenda))
13372 (t (org-buffer-list))))
13373 (unwind-protect
13374 (let ((iswitchb-make-buflist-hook
13375 (lambda ()
13376 (setq iswitchb-temp-buflist
13377 (mapcar 'buffer-name blist)))))
13378 (switch-to-buffer
13379 (iswitchb-read-buffer
13380 "Switch-to: " nil t))
13381 (or enabled (iswitchb-mode -1))))))
13383 ;;;###autoload
13384 (defun org-ido-switchb (&optional arg)
13385 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
13386 With a prefix argument, restrict available to files.
13387 With two prefix arguments, restrict available buffers to agenda files."
13388 (interactive "P")
13389 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13390 ((equal arg '(16)) (org-buffer-list 'agenda))
13391 (t (org-buffer-list)))))
13392 (switch-to-buffer
13393 (org-ido-completing-read "Org buffer: "
13394 (mapcar 'list (mapcar 'buffer-name blist))
13395 nil t))))
13397 (defun org-buffer-list (&optional predicate exclude-tmp)
13398 "Return a list of Org buffers.
13399 PREDICATE can be `export', `files' or `agenda'.
13401 export restrict the list to Export buffers.
13402 files restrict the list to buffers visiting Org files.
13403 agenda restrict the list to buffers visiting agenda files.
13405 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
13406 (let* ((bfn nil)
13407 (agenda-files (and (eq predicate 'agenda)
13408 (mapcar 'file-truename (org-agenda-files t))))
13409 (filter
13410 (cond
13411 ((eq predicate 'files)
13412 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
13413 ((eq predicate 'export)
13414 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
13415 ((eq predicate 'agenda)
13416 (lambda (b)
13417 (with-current-buffer b
13418 (and (eq major-mode 'org-mode)
13419 (setq bfn (buffer-file-name b))
13420 (member (file-truename bfn) agenda-files)))))
13421 (t (lambda (b) (with-current-buffer b
13422 (or (eq major-mode 'org-mode)
13423 (string-match "\*Org .*Export"
13424 (buffer-name b)))))))))
13425 (delq nil
13426 (mapcar
13427 (lambda(b)
13428 (if (and (funcall filter b)
13429 (or (not exclude-tmp)
13430 (not (string-match "tmp" (buffer-name b)))))
13432 nil))
13433 (buffer-list)))))
13435 (defun org-agenda-files (&optional unrestricted archives)
13436 "Get the list of agenda files.
13437 Optional UNRESTRICTED means return the full list even if a restriction
13438 is currently in place.
13439 When ARCHIVES is t, include all archive files hat are really being
13440 used by the agenda files. If ARCHIVE is `ifmode', do this only if
13441 `org-agenda-archives-mode' is t."
13442 (let ((files
13443 (cond
13444 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
13445 ((stringp org-agenda-files) (org-read-agenda-file-list))
13446 ((listp org-agenda-files) org-agenda-files)
13447 (t (error "Invalid value of `org-agenda-files'")))))
13448 (setq files (apply 'append
13449 (mapcar (lambda (f)
13450 (if (file-directory-p f)
13451 (directory-files
13452 f t org-agenda-file-regexp)
13453 (list f)))
13454 files)))
13455 (when org-agenda-skip-unavailable-files
13456 (setq files (delq nil
13457 (mapcar (function
13458 (lambda (file)
13459 (and (file-readable-p file) file)))
13460 files))))
13461 (when (or (eq archives t)
13462 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
13463 (setq files (org-add-archive-files files)))
13464 files))
13466 (defun org-edit-agenda-file-list ()
13467 "Edit the list of agenda files.
13468 Depending on setup, this either uses customize to edit the variable
13469 `org-agenda-files', or it visits the file that is holding the list. In the
13470 latter case, the buffer is set up in a way that saving it automatically kills
13471 the buffer and restores the previous window configuration."
13472 (interactive)
13473 (if (stringp org-agenda-files)
13474 (let ((cw (current-window-configuration)))
13475 (find-file org-agenda-files)
13476 (org-set-local 'org-window-configuration cw)
13477 (org-add-hook 'after-save-hook
13478 (lambda ()
13479 (set-window-configuration
13480 (prog1 org-window-configuration
13481 (kill-buffer (current-buffer))))
13482 (org-install-agenda-files-menu)
13483 (message "New agenda file list installed"))
13484 nil 'local)
13485 (message "%s" (substitute-command-keys
13486 "Edit list and finish with \\[save-buffer]")))
13487 (customize-variable 'org-agenda-files)))
13489 (defun org-store-new-agenda-file-list (list)
13490 "Set new value for the agenda file list and save it correctly."
13491 (if (stringp org-agenda-files)
13492 (let ((f org-agenda-files) b)
13493 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
13494 (with-temp-file f
13495 (insert (mapconcat 'identity list "\n") "\n")))
13496 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
13497 (setq org-agenda-files list)
13498 (customize-save-variable 'org-agenda-files org-agenda-files))))
13500 (defun org-read-agenda-file-list ()
13501 "Read the list of agenda files from a file."
13502 (when (file-directory-p org-agenda-files)
13503 (error "`org-agenda-files' cannot be a single directory"))
13504 (when (stringp org-agenda-files)
13505 (with-temp-buffer
13506 (insert-file-contents org-agenda-files)
13507 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
13510 ;;;###autoload
13511 (defun org-cycle-agenda-files ()
13512 "Cycle through the files in `org-agenda-files'.
13513 If the current buffer visits an agenda file, find the next one in the list.
13514 If the current buffer does not, find the first agenda file."
13515 (interactive)
13516 (let* ((fs (org-agenda-files t))
13517 (files (append fs (list (car fs))))
13518 (tcf (if buffer-file-name (file-truename buffer-file-name)))
13519 file)
13520 (unless files (error "No agenda files"))
13521 (catch 'exit
13522 (while (setq file (pop files))
13523 (if (equal (file-truename file) tcf)
13524 (when (car files)
13525 (find-file (car files))
13526 (throw 'exit t))))
13527 (find-file (car fs)))
13528 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
13530 (defun org-agenda-file-to-front (&optional to-end)
13531 "Move/add the current file to the top of the agenda file list.
13532 If the file is not present in the list, it is added to the front. If it is
13533 present, it is moved there. With optional argument TO-END, add/move to the
13534 end of the list."
13535 (interactive "P")
13536 (let ((org-agenda-skip-unavailable-files nil)
13537 (file-alist (mapcar (lambda (x)
13538 (cons (file-truename x) x))
13539 (org-agenda-files t)))
13540 (ctf (file-truename buffer-file-name))
13541 x had)
13542 (setq x (assoc ctf file-alist) had x)
13544 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
13545 (if to-end
13546 (setq file-alist (append (delq x file-alist) (list x)))
13547 (setq file-alist (cons x (delq x file-alist))))
13548 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
13549 (org-install-agenda-files-menu)
13550 (message "File %s to %s of agenda file list"
13551 (if had "moved" "added") (if to-end "end" "front"))))
13553 (defun org-remove-file (&optional file)
13554 "Remove current file from the list of files in variable `org-agenda-files'.
13555 These are the files which are being checked for agenda entries.
13556 Optional argument FILE means, use this file instead of the current."
13557 (interactive)
13558 (let* ((org-agenda-skip-unavailable-files nil)
13559 (file (or file buffer-file-name))
13560 (true-file (file-truename file))
13561 (afile (abbreviate-file-name file))
13562 (files (delq nil (mapcar
13563 (lambda (x)
13564 (if (equal true-file
13565 (file-truename x))
13566 nil x))
13567 (org-agenda-files t)))))
13568 (if (not (= (length files) (length (org-agenda-files t))))
13569 (progn
13570 (org-store-new-agenda-file-list files)
13571 (org-install-agenda-files-menu)
13572 (message "Removed file: %s" afile))
13573 (message "File was not in list: %s (not removed)" afile))))
13575 (defun org-file-menu-entry (file)
13576 (vector file (list 'find-file file) t))
13578 (defun org-check-agenda-file (file)
13579 "Make sure FILE exists. If not, ask user what to do."
13580 (when (not (file-exists-p file))
13581 (message "non-existent file %s. [R]emove from list or [A]bort?"
13582 (abbreviate-file-name file))
13583 (let ((r (downcase (read-char-exclusive))))
13584 (cond
13585 ((equal r ?r)
13586 (org-remove-file file)
13587 (throw 'nextfile t))
13588 (t (error "Abort"))))))
13590 (defun org-get-agenda-file-buffer (file)
13591 "Get a buffer visiting FILE. If the buffer needs to be created, add
13592 it to the list of buffers which might be released later."
13593 (let ((buf (org-find-base-buffer-visiting file)))
13594 (if buf
13595 buf ; just return it
13596 ;; Make a new buffer and remember it
13597 (setq buf (find-file-noselect file))
13598 (if buf (push buf org-agenda-new-buffers))
13599 buf)))
13601 (defun org-release-buffers (blist)
13602 "Release all buffers in list, asking the user for confirmation when needed.
13603 When a buffer is unmodified, it is just killed. When modified, it is saved
13604 \(if the user agrees) and then killed."
13605 (let (buf file)
13606 (while (setq buf (pop blist))
13607 (setq file (buffer-file-name buf))
13608 (when (and (buffer-modified-p buf)
13609 file
13610 (y-or-n-p (format "Save file %s? " file)))
13611 (with-current-buffer buf (save-buffer)))
13612 (kill-buffer buf))))
13614 (defun org-prepare-agenda-buffers (files)
13615 "Create buffers for all agenda files, protect archived trees and comments."
13616 (interactive)
13617 (let ((pa '(:org-archived t))
13618 (pc '(:org-comment t))
13619 (pall '(:org-archived t :org-comment t))
13620 (inhibit-read-only t)
13621 (rea (concat ":" org-archive-tag ":"))
13622 bmp file re)
13623 (save-excursion
13624 (save-restriction
13625 (while (setq file (pop files))
13626 (catch 'nextfile
13627 (if (bufferp file)
13628 (set-buffer file)
13629 (org-check-agenda-file file)
13630 (set-buffer (org-get-agenda-file-buffer file)))
13631 (widen)
13632 (setq bmp (buffer-modified-p))
13633 (org-refresh-category-properties)
13634 (setq org-todo-keywords-for-agenda
13635 (append org-todo-keywords-for-agenda org-todo-keywords-1))
13636 (setq org-done-keywords-for-agenda
13637 (append org-done-keywords-for-agenda org-done-keywords))
13638 (setq org-todo-keyword-alist-for-agenda
13639 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
13640 (setq org-tag-alist-for-agenda
13641 (append org-tag-alist-for-agenda org-tag-alist))
13643 (save-excursion
13644 (remove-text-properties (point-min) (point-max) pall)
13645 (when org-agenda-skip-archived-trees
13646 (goto-char (point-min))
13647 (while (re-search-forward rea nil t)
13648 (if (org-on-heading-p t)
13649 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
13650 (goto-char (point-min))
13651 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
13652 (while (re-search-forward re nil t)
13653 (add-text-properties
13654 (match-beginning 0) (org-end-of-subtree t) pc)))
13655 (set-buffer-modified-p bmp)))))
13656 (setq org-todo-keyword-alist-for-agenda
13657 (org-uniquify org-todo-keyword-alist-for-agenda)
13658 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
13660 ;;;; Embedded LaTeX
13662 (defvar org-cdlatex-mode-map (make-sparse-keymap)
13663 "Keymap for the minor `org-cdlatex-mode'.")
13665 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
13666 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
13667 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
13668 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
13669 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
13671 (defvar org-cdlatex-texmathp-advice-is-done nil
13672 "Flag remembering if we have applied the advice to texmathp already.")
13674 (define-minor-mode org-cdlatex-mode
13675 "Toggle the minor `org-cdlatex-mode'.
13676 This mode supports entering LaTeX environment and math in LaTeX fragments
13677 in Org-mode.
13678 \\{org-cdlatex-mode-map}"
13679 nil " OCDL" nil
13680 (when org-cdlatex-mode (require 'cdlatex))
13681 (unless org-cdlatex-texmathp-advice-is-done
13682 (setq org-cdlatex-texmathp-advice-is-done t)
13683 (defadvice texmathp (around org-math-always-on activate)
13684 "Always return t in org-mode buffers.
13685 This is because we want to insert math symbols without dollars even outside
13686 the LaTeX math segments. If Orgmode thinks that point is actually inside
13687 an embedded LaTeX fragment, let texmathp do its job.
13688 \\[org-cdlatex-mode-map]"
13689 (interactive)
13690 (let (p)
13691 (cond
13692 ((not (org-mode-p)) ad-do-it)
13693 ((eq this-command 'cdlatex-math-symbol)
13694 (setq ad-return-value t
13695 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
13697 (let ((p (org-inside-LaTeX-fragment-p)))
13698 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
13699 (setq ad-return-value t
13700 texmathp-why '("Org-mode embedded math" . 0))
13701 (if p ad-do-it)))))))))
13703 (defun turn-on-org-cdlatex ()
13704 "Unconditionally turn on `org-cdlatex-mode'."
13705 (org-cdlatex-mode 1))
13707 (defun org-inside-LaTeX-fragment-p ()
13708 "Test if point is inside a LaTeX fragment.
13709 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
13710 sequence appearing also before point.
13711 Even though the matchers for math are configurable, this function assumes
13712 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
13713 delimiters are skipped when they have been removed by customization.
13714 The return value is nil, or a cons cell with the delimiter and
13715 and the position of this delimiter.
13717 This function does a reasonably good job, but can locally be fooled by
13718 for example currency specifications. For example it will assume being in
13719 inline math after \"$22.34\". The LaTeX fragment formatter will only format
13720 fragments that are properly closed, but during editing, we have to live
13721 with the uncertainty caused by missing closing delimiters. This function
13722 looks only before point, not after."
13723 (catch 'exit
13724 (let ((pos (point))
13725 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
13726 (lim (progn
13727 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
13728 (point)))
13729 dd-on str (start 0) m re)
13730 (goto-char pos)
13731 (when dodollar
13732 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
13733 re (nth 1 (assoc "$" org-latex-regexps)))
13734 (while (string-match re str start)
13735 (cond
13736 ((= (match-end 0) (length str))
13737 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
13738 ((= (match-end 0) (- (length str) 5))
13739 (throw 'exit nil))
13740 (t (setq start (match-end 0))))))
13741 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
13742 (goto-char pos)
13743 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
13744 (and (match-beginning 2) (throw 'exit nil))
13745 ;; count $$
13746 (while (re-search-backward "\\$\\$" lim t)
13747 (setq dd-on (not dd-on)))
13748 (goto-char pos)
13749 (if dd-on (cons "$$" m))))))
13752 (defun org-try-cdlatex-tab ()
13753 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
13754 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
13755 - inside a LaTeX fragment, or
13756 - after the first word in a line, where an abbreviation expansion could
13757 insert a LaTeX environment."
13758 (when org-cdlatex-mode
13759 (cond
13760 ((save-excursion
13761 (skip-chars-backward "a-zA-Z0-9*")
13762 (skip-chars-backward " \t")
13763 (bolp))
13764 (cdlatex-tab) t)
13765 ((org-inside-LaTeX-fragment-p)
13766 (cdlatex-tab) t)
13767 (t nil))))
13769 (defun org-cdlatex-underscore-caret (&optional arg)
13770 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
13771 Revert to the normal definition outside of these fragments."
13772 (interactive "P")
13773 (if (org-inside-LaTeX-fragment-p)
13774 (call-interactively 'cdlatex-sub-superscript)
13775 (let (org-cdlatex-mode)
13776 (call-interactively (key-binding (vector last-input-event))))))
13778 (defun org-cdlatex-math-modify (&optional arg)
13779 "Execute `cdlatex-math-modify' in LaTeX fragments.
13780 Revert to the normal definition outside of these fragments."
13781 (interactive "P")
13782 (if (org-inside-LaTeX-fragment-p)
13783 (call-interactively 'cdlatex-math-modify)
13784 (let (org-cdlatex-mode)
13785 (call-interactively (key-binding (vector last-input-event))))))
13787 (defvar org-latex-fragment-image-overlays nil
13788 "List of overlays carrying the images of latex fragments.")
13789 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
13791 (defun org-remove-latex-fragment-image-overlays ()
13792 "Remove all overlays with LaTeX fragment images in current buffer."
13793 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
13794 (setq org-latex-fragment-image-overlays nil))
13796 (defun org-preview-latex-fragment (&optional subtree)
13797 "Preview the LaTeX fragment at point, or all locally or globally.
13798 If the cursor is in a LaTeX fragment, create the image and overlay
13799 it over the source code. If there is no fragment at point, display
13800 all fragments in the current text, from one headline to the next. With
13801 prefix SUBTREE, display all fragments in the current subtree. With a
13802 double prefix `C-u C-u', or when the cursor is before the first headline,
13803 display all fragments in the buffer.
13804 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
13805 (interactive "P")
13806 (org-remove-latex-fragment-image-overlays)
13807 (save-excursion
13808 (save-restriction
13809 (let (beg end at msg)
13810 (cond
13811 ((or (equal subtree '(16))
13812 (not (save-excursion
13813 (re-search-backward (concat "^" outline-regexp) nil t))))
13814 (setq beg (point-min) end (point-max)
13815 msg "Creating images for buffer...%s"))
13816 ((equal subtree '(4))
13817 (org-back-to-heading)
13818 (setq beg (point) end (org-end-of-subtree t)
13819 msg "Creating images for subtree...%s"))
13821 (if (setq at (org-inside-LaTeX-fragment-p))
13822 (goto-char (max (point-min) (- (cdr at) 2)))
13823 (org-back-to-heading))
13824 (setq beg (point) end (progn (outline-next-heading) (point))
13825 msg (if at "Creating image...%s"
13826 "Creating images for entry...%s"))))
13827 (message msg "")
13828 (narrow-to-region beg end)
13829 (goto-char beg)
13830 (org-format-latex
13831 (concat "ltxpng/" (file-name-sans-extension
13832 (file-name-nondirectory
13833 buffer-file-name)))
13834 default-directory 'overlays msg at 'forbuffer)
13835 (message msg "done. Use `C-c C-c' to remove images.")))))
13837 (defvar org-latex-regexps
13838 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
13839 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
13840 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
13841 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13842 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13843 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
13844 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
13845 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
13846 "Regular expressions for matching embedded LaTeX.")
13848 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
13849 "Replace LaTeX fragments with links to an image, and produce images."
13850 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
13851 (let* ((prefixnodir (file-name-nondirectory prefix))
13852 (absprefix (expand-file-name prefix dir))
13853 (todir (file-name-directory absprefix))
13854 (opt org-format-latex-options)
13855 (matchers (plist-get opt :matchers))
13856 (re-list org-latex-regexps)
13857 (cnt 0) txt link beg end re e checkdir
13858 executables-checked
13859 m n block linkfile movefile ov)
13860 ;; Check if there are old images files with this prefix, and remove them
13861 (when (file-directory-p todir)
13862 (mapc 'delete-file
13863 (directory-files
13864 todir 'full
13865 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
13866 ;; Check the different regular expressions
13867 (while (setq e (pop re-list))
13868 (setq m (car e) re (nth 1 e) n (nth 2 e)
13869 block (if (nth 3 e) "\n\n" ""))
13870 (when (member m matchers)
13871 (goto-char (point-min))
13872 (while (re-search-forward re nil t)
13873 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
13874 (not (get-text-property (match-beginning n)
13875 'org-protected)))
13876 (setq txt (match-string n)
13877 beg (match-beginning n) end (match-end n)
13878 cnt (1+ cnt)
13879 linkfile (format "%s_%04d.png" prefix cnt)
13880 movefile (format "%s_%04d.png" absprefix cnt)
13881 link (concat block "[[file:" linkfile "]]" block))
13882 (if msg (message msg cnt))
13883 (goto-char beg)
13884 (unless checkdir ; make sure the directory exists
13885 (setq checkdir t)
13886 (or (file-directory-p todir) (make-directory todir)))
13888 (unless executables-checked
13889 (org-check-external-command
13890 "latex" "needed to convert LaTeX fragments to images")
13891 (org-check-external-command
13892 "dvipng" "needed to convert LaTeX fragments to images")
13893 (setq executables-checked t))
13895 (org-create-formula-image
13896 txt movefile opt forbuffer)
13897 (if overlays
13898 (progn
13899 (setq ov (org-make-overlay beg end))
13900 (if (featurep 'xemacs)
13901 (progn
13902 (org-overlay-put ov 'invisible t)
13903 (org-overlay-put
13904 ov 'end-glyph
13905 (make-glyph (vector 'png :file movefile))))
13906 (org-overlay-put
13907 ov 'display
13908 (list 'image :type 'png :file movefile :ascent 'center)))
13909 (push ov org-latex-fragment-image-overlays)
13910 (goto-char end))
13911 (delete-region beg end)
13912 (insert link))))))))
13914 ;; This function borrows from Ganesh Swami's latex2png.el
13915 (defun org-create-formula-image (string tofile options buffer)
13916 (let* ((tmpdir (if (featurep 'xemacs)
13917 (temp-directory)
13918 temporary-file-directory))
13919 (texfilebase (make-temp-name
13920 (expand-file-name "orgtex" tmpdir)))
13921 (texfile (concat texfilebase ".tex"))
13922 (dvifile (concat texfilebase ".dvi"))
13923 (pngfile (concat texfilebase ".png"))
13924 (fnh (if (featurep 'xemacs)
13925 (font-height (get-face-font 'default))
13926 (face-attribute 'default :height nil)))
13927 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
13928 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
13929 (fg (or (plist-get options (if buffer :foreground :html-foreground))
13930 "Black"))
13931 (bg (or (plist-get options (if buffer :background :html-background))
13932 "Transparent")))
13933 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
13934 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
13935 (with-temp-file texfile
13936 (insert org-format-latex-header
13937 "\n\\begin{document}\n" string "\n\\end{document}\n"))
13938 (let ((dir default-directory))
13939 (condition-case nil
13940 (progn
13941 (cd tmpdir)
13942 (call-process "latex" nil nil nil texfile))
13943 (error nil))
13944 (cd dir))
13945 (if (not (file-exists-p dvifile))
13946 (progn (message "Failed to create dvi file from %s" texfile) nil)
13947 (condition-case nil
13948 (call-process "dvipng" nil nil nil
13949 "-E" "-fg" fg "-bg" bg
13950 "-D" dpi
13951 ;;"-x" scale "-y" scale
13952 "-T" "tight"
13953 "-o" pngfile
13954 dvifile)
13955 (error nil))
13956 (if (not (file-exists-p pngfile))
13957 (progn (message "Failed to create png file from %s" texfile) nil)
13958 ;; Use the requested file name and clean up
13959 (copy-file pngfile tofile 'replace)
13960 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
13961 (delete-file (concat texfilebase e)))
13962 pngfile))))
13964 (defun org-dvipng-color (attr)
13965 "Return an rgb color specification for dvipng."
13966 (apply 'format "rgb %s %s %s"
13967 (mapcar 'org-normalize-color
13968 (color-values (face-attribute 'default attr nil)))))
13970 (defun org-normalize-color (value)
13971 "Return string to be used as color value for an RGB component."
13972 (format "%g" (/ value 65535.0)))
13974 ;;;; Key bindings
13976 ;; Make `C-c C-x' a prefix key
13977 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
13979 ;; TAB key with modifiers
13980 (org-defkey org-mode-map "\C-i" 'org-cycle)
13981 (org-defkey org-mode-map [(tab)] 'org-cycle)
13982 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
13983 (org-defkey org-mode-map [(meta tab)] 'org-complete)
13984 (org-defkey org-mode-map "\M-\t" 'org-complete)
13985 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
13986 ;; The following line is necessary under Suse GNU/Linux
13987 (unless (featurep 'xemacs)
13988 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
13989 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
13990 (define-key org-mode-map [backtab] 'org-shifttab)
13992 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
13993 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
13994 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
13996 ;; Cursor keys with modifiers
13997 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
13998 (org-defkey org-mode-map [(meta right)] 'org-metaright)
13999 (org-defkey org-mode-map [(meta up)] 'org-metaup)
14000 (org-defkey org-mode-map [(meta down)] 'org-metadown)
14002 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
14003 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
14004 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
14005 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
14007 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
14008 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
14009 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
14010 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
14012 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
14013 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
14015 ;;; Extra keys for tty access.
14016 ;; We only set them when really needed because otherwise the
14017 ;; menus don't show the simple keys
14019 (when (or org-use-extra-keys
14020 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
14021 (not window-system))
14022 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
14023 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
14024 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
14025 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
14026 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
14027 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
14028 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
14029 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
14030 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
14031 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
14032 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
14033 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
14034 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
14035 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
14036 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
14037 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
14038 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
14039 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
14040 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
14041 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
14042 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
14043 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
14044 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
14045 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
14046 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
14047 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
14048 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
14049 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
14051 ;; All the other keys
14053 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
14054 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
14055 (if (boundp 'narrow-map)
14056 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
14057 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
14058 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
14059 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
14060 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
14061 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
14062 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
14063 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
14064 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
14065 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
14066 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
14067 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
14068 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
14069 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
14070 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
14071 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
14072 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
14073 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
14074 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
14075 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
14076 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
14077 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
14078 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
14079 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
14080 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
14081 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
14082 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
14083 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
14084 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
14085 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
14086 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
14087 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
14088 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
14089 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
14090 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
14091 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
14092 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
14093 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
14094 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
14095 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
14096 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
14097 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
14098 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
14099 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14100 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
14101 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
14102 (org-defkey org-mode-map "\C-c^" 'org-sort)
14103 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
14104 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
14105 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
14106 (org-defkey org-mode-map "\C-m" 'org-return)
14107 (org-defkey org-mode-map "\C-j" 'org-return-indent)
14108 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
14109 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
14110 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
14111 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
14112 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
14113 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
14114 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
14115 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
14116 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
14117 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
14118 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
14119 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
14120 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
14121 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
14122 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
14123 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
14124 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
14125 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
14127 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
14128 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
14129 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
14130 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
14132 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
14133 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
14134 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
14135 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
14136 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
14137 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
14138 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
14139 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
14140 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
14141 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
14142 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
14143 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
14144 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
14145 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
14147 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
14148 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
14149 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
14150 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
14152 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
14154 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
14156 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
14157 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
14159 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
14162 (when (featurep 'xemacs)
14163 (org-defkey org-mode-map 'button3 'popup-mode-menu))
14166 (defvar org-self-insert-command-undo-counter 0)
14168 (defvar org-table-auto-blank-field) ; defined in org-table.el
14169 (defun org-self-insert-command (N)
14170 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
14171 If the cursor is in a table looking at whitespace, the whitespace is
14172 overwritten, and the table is not marked as requiring realignment."
14173 (interactive "p")
14174 (if (and
14175 (org-table-p)
14176 (progn
14177 ;; check if we blank the field, and if that triggers align
14178 (and (featurep 'org-table) org-table-auto-blank-field
14179 (member last-command
14180 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
14181 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
14182 ;; got extra space, this field does not determine column width
14183 (let (org-table-may-need-update) (org-table-blank-field))
14184 ;; no extra space, this field may determine column width
14185 (org-table-blank-field)))
14187 (eq N 1)
14188 (looking-at "[^|\n]* |"))
14189 (let (org-table-may-need-update)
14190 (goto-char (1- (match-end 0)))
14191 (delete-backward-char 1)
14192 (goto-char (match-beginning 0))
14193 (self-insert-command N))
14194 (setq org-table-may-need-update t)
14195 (self-insert-command N)
14196 (org-fix-tags-on-the-fly)
14197 (if org-self-insert-cluster-for-undo
14198 (if (not (eq last-command 'org-self-insert-command))
14199 (setq org-self-insert-command-undo-counter 1)
14200 (if (>= org-self-insert-command-undo-counter 20)
14201 (setq org-self-insert-command-undo-counter 1)
14202 (and (> org-self-insert-command-undo-counter 0)
14203 buffer-undo-list
14204 (not (cadr buffer-undo-list)) ; remove nil entry
14205 (setcdr buffer-undo-list (cddr buffer-undo-list)))
14206 (setq org-self-insert-command-undo-counter
14207 (1+ org-self-insert-command-undo-counter)))))))
14209 (defun org-fix-tags-on-the-fly ()
14210 (when (and (equal (char-after (point-at-bol)) ?*)
14211 (org-on-heading-p))
14212 (org-align-tags-here org-tags-column)))
14214 (defun org-delete-backward-char (N)
14215 "Like `delete-backward-char', insert whitespace at field end in tables.
14216 When deleting backwards, in tables this function will insert whitespace in
14217 front of the next \"|\" separator, to keep the table aligned. The table will
14218 still be marked for re-alignment if the field did fill the entire column,
14219 because, in this case the deletion might narrow the column."
14220 (interactive "p")
14221 (if (and (org-table-p)
14222 (eq N 1)
14223 (string-match "|" (buffer-substring (point-at-bol) (point)))
14224 (looking-at ".*?|"))
14225 (let ((pos (point))
14226 (noalign (looking-at "[^|\n\r]* |"))
14227 (c org-table-may-need-update))
14228 (backward-delete-char N)
14229 (skip-chars-forward "^|")
14230 (insert " ")
14231 (goto-char (1- pos))
14232 ;; noalign: if there were two spaces at the end, this field
14233 ;; does not determine the width of the column.
14234 (if noalign (setq org-table-may-need-update c)))
14235 (backward-delete-char N)
14236 (org-fix-tags-on-the-fly)))
14238 (defun org-delete-char (N)
14239 "Like `delete-char', but insert whitespace at field end in tables.
14240 When deleting characters, in tables this function will insert whitespace in
14241 front of the next \"|\" separator, to keep the table aligned. The table will
14242 still be marked for re-alignment if the field did fill the entire column,
14243 because, in this case the deletion might narrow the column."
14244 (interactive "p")
14245 (if (and (org-table-p)
14246 (not (bolp))
14247 (not (= (char-after) ?|))
14248 (eq N 1))
14249 (if (looking-at ".*?|")
14250 (let ((pos (point))
14251 (noalign (looking-at "[^|\n\r]* |"))
14252 (c org-table-may-need-update))
14253 (replace-match (concat
14254 (substring (match-string 0) 1 -1)
14255 " |"))
14256 (goto-char pos)
14257 ;; noalign: if there were two spaces at the end, this field
14258 ;; does not determine the width of the column.
14259 (if noalign (setq org-table-may-need-update c)))
14260 (delete-char N))
14261 (delete-char N)
14262 (org-fix-tags-on-the-fly)))
14264 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
14265 (put 'org-self-insert-command 'delete-selection t)
14266 (put 'orgtbl-self-insert-command 'delete-selection t)
14267 (put 'org-delete-char 'delete-selection 'supersede)
14268 (put 'org-delete-backward-char 'delete-selection 'supersede)
14269 (put 'org-yank 'delete-selection 'yank)
14271 ;; Make `flyspell-mode' delay after some commands
14272 (put 'org-self-insert-command 'flyspell-delayed t)
14273 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
14274 (put 'org-delete-char 'flyspell-delayed t)
14275 (put 'org-delete-backward-char 'flyspell-delayed t)
14277 ;; Make pabbrev-mode expand after org-mode commands
14278 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
14279 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
14281 ;; How to do this: Measure non-white length of current string
14282 ;; If equal to column width, we should realign.
14284 (defun org-remap (map &rest commands)
14285 "In MAP, remap the functions given in COMMANDS.
14286 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
14287 (let (new old)
14288 (while commands
14289 (setq old (pop commands) new (pop commands))
14290 (if (fboundp 'command-remapping)
14291 (org-defkey map (vector 'remap old) new)
14292 (substitute-key-definition old new map global-map)))))
14294 (when (eq org-enable-table-editor 'optimized)
14295 ;; If the user wants maximum table support, we need to hijack
14296 ;; some standard editing functions
14297 (org-remap org-mode-map
14298 'self-insert-command 'org-self-insert-command
14299 'delete-char 'org-delete-char
14300 'delete-backward-char 'org-delete-backward-char)
14301 (org-defkey org-mode-map "|" 'org-force-self-insert))
14303 (defvar org-ctrl-c-ctrl-c-hook nil
14304 "Hook for functions attaching themselves to `C-c C-c'.
14305 This can be used to add additional functionality to the C-c C-c key which
14306 executes context-dependent commands.
14307 Each function will be called with no arguments. The function must check
14308 if the context is appropriate for it to act. If yes, it should do its
14309 thing and then return a non-nil value. If the context is wrong,
14310 just do nothing and return nil.")
14312 (defvar org-tab-first-hook nil
14313 "Hook for functions to attach themselves to TAB.
14314 See `org-ctrl-c-ctrl-c-hook' for more information.
14315 This hook runs as the first action when TAB is pressed, even before
14316 `org-cycle' messes around with the `outline-regexp' to cater for
14317 inline tasks and plain list item folding.
14318 If any function in this hook returns t, not other actions like table
14319 field motion visibility cycling will be done.")
14321 (defvar org-tab-after-check-for-table-hook nil
14322 "Hook for functions to attach themselves to TAB.
14323 See `org-ctrl-c-ctrl-c-hook' for more information.
14324 This hook runs after it has been established that the cursor is not in a
14325 table, but before checking if the cursor is in a headline or if global cycling
14326 should be done.
14327 If any function in this hook returns t, not other actions like visibility
14328 cycling will be done.")
14330 (defvar org-tab-after-check-for-cycling-hook nil
14331 "Hook for functions to attach themselves to TAB.
14332 See `org-ctrl-c-ctrl-c-hook' for more information.
14333 This hook runs after it has been established that not table field motion and
14334 not visibility should be done because of current context. This is probably
14335 the place where a package like yasnippets can hook in.")
14337 (defvar org-metaleft-hook nil
14338 "Hook for functions attaching themselves to `M-left'.
14339 See `org-ctrl-c-ctrl-c-hook' for more information.")
14340 (defvar org-metaright-hook nil
14341 "Hook for functions attaching themselves to `M-right'.
14342 See `org-ctrl-c-ctrl-c-hook' for more information.")
14343 (defvar org-metaup-hook nil
14344 "Hook for functions attaching themselves to `M-up'.
14345 See `org-ctrl-c-ctrl-c-hook' for more information.")
14346 (defvar org-metadown-hook nil
14347 "Hook for functions attaching themselves to `M-down'.
14348 See `org-ctrl-c-ctrl-c-hook' for more information.")
14349 (defvar org-shiftmetaleft-hook nil
14350 "Hook for functions attaching themselves to `M-S-left'.
14351 See `org-ctrl-c-ctrl-c-hook' for more information.")
14352 (defvar org-shiftmetaright-hook nil
14353 "Hook for functions attaching themselves to `M-S-right'.
14354 See `org-ctrl-c-ctrl-c-hook' for more information.")
14355 (defvar org-shiftmetaup-hook nil
14356 "Hook for functions attaching themselves to `M-S-up'.
14357 See `org-ctrl-c-ctrl-c-hook' for more information.")
14358 (defvar org-shiftmetadown-hook nil
14359 "Hook for functions attaching themselves to `M-S-down'.
14360 See `org-ctrl-c-ctrl-c-hook' for more information.")
14361 (defvar org-metareturn-hook nil
14362 "Hook for functions attaching themselves to `M-RET'.
14363 See `org-ctrl-c-ctrl-c-hook' for more information.")
14365 (defun org-modifier-cursor-error ()
14366 "Throw an error, a modified cursor command was applied in wrong context."
14367 (error "This command is active in special context like tables, headlines or items"))
14369 (defun org-shiftselect-error ()
14370 "Throw an error because Shift-Cursor command was applied in wrong context."
14371 (if (and (boundp 'shift-select-mode) shift-select-mode)
14372 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
14373 (error "This command works only in special context like headlines or timestamps.")))
14375 (defun org-call-for-shift-select (cmd)
14376 (let ((this-command-keys-shift-translated t))
14377 (call-interactively cmd)))
14379 (defun org-shifttab (&optional arg)
14380 "Global visibility cycling or move to previous table field.
14381 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
14382 on context.
14383 See the individual commands for more information."
14384 (interactive "P")
14385 (cond
14386 ((org-at-table-p) (call-interactively 'org-table-previous-field))
14387 ((integerp arg)
14388 (message "Content view to level: %d" arg)
14389 (org-content (prefix-numeric-value arg))
14390 (setq org-cycle-global-status 'overview))
14391 (t (call-interactively 'org-global-cycle))))
14393 (defun org-shiftmetaleft ()
14394 "Promote subtree or delete table column.
14395 Calls `org-promote-subtree', `org-outdent-item',
14396 or `org-table-delete-column', depending on context.
14397 See the individual commands for more information."
14398 (interactive)
14399 (cond
14400 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
14401 ((org-at-table-p) (call-interactively 'org-table-delete-column))
14402 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
14403 ((org-at-item-p) (call-interactively 'org-outdent-item))
14404 (t (org-modifier-cursor-error))))
14406 (defun org-shiftmetaright ()
14407 "Demote subtree or insert table column.
14408 Calls `org-demote-subtree', `org-indent-item',
14409 or `org-table-insert-column', depending on context.
14410 See the individual commands for more information."
14411 (interactive)
14412 (cond
14413 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
14414 ((org-at-table-p) (call-interactively 'org-table-insert-column))
14415 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
14416 ((org-at-item-p) (call-interactively 'org-indent-item))
14417 (t (org-modifier-cursor-error))))
14419 (defun org-shiftmetaup (&optional arg)
14420 "Move subtree up or kill table row.
14421 Calls `org-move-subtree-up' or `org-table-kill-row' or
14422 `org-move-item-up' depending on context. See the individual commands
14423 for more information."
14424 (interactive "P")
14425 (cond
14426 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
14427 ((org-at-table-p) (call-interactively 'org-table-kill-row))
14428 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14429 ((org-at-item-p) (call-interactively 'org-move-item-up))
14430 (t (org-modifier-cursor-error))))
14432 (defun org-shiftmetadown (&optional arg)
14433 "Move subtree down or insert table row.
14434 Calls `org-move-subtree-down' or `org-table-insert-row' or
14435 `org-move-item-down', depending on context. See the individual
14436 commands for more information."
14437 (interactive "P")
14438 (cond
14439 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
14440 ((org-at-table-p) (call-interactively 'org-table-insert-row))
14441 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14442 ((org-at-item-p) (call-interactively 'org-move-item-down))
14443 (t (org-modifier-cursor-error))))
14445 (defun org-metaleft (&optional arg)
14446 "Promote heading or move table column to left.
14447 Calls `org-do-promote' or `org-table-move-column', depending on context.
14448 With no specific context, calls the Emacs default `backward-word'.
14449 See the individual commands for more information."
14450 (interactive "P")
14451 (cond
14452 ((run-hook-with-args-until-success 'org-metaleft-hook))
14453 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
14454 ((or (org-on-heading-p)
14455 (and (org-region-active-p)
14456 (save-excursion
14457 (goto-char (region-beginning))
14458 (org-on-heading-p))))
14459 (call-interactively 'org-do-promote))
14460 ((or (org-at-item-p)
14461 (and (org-region-active-p)
14462 (save-excursion
14463 (goto-char (region-beginning))
14464 (org-at-item-p))))
14465 (call-interactively 'org-outdent-item))
14466 (t (call-interactively 'backward-word))))
14468 (defun org-metaright (&optional arg)
14469 "Demote subtree or move table column to right.
14470 Calls `org-do-demote' or `org-table-move-column', depending on context.
14471 With no specific context, calls the Emacs default `forward-word'.
14472 See the individual commands for more information."
14473 (interactive "P")
14474 (cond
14475 ((run-hook-with-args-until-success 'org-metaright-hook))
14476 ((org-at-table-p) (call-interactively 'org-table-move-column))
14477 ((or (org-on-heading-p)
14478 (and (org-region-active-p)
14479 (save-excursion
14480 (goto-char (region-beginning))
14481 (org-on-heading-p))))
14482 (call-interactively 'org-do-demote))
14483 ((or (org-at-item-p)
14484 (and (org-region-active-p)
14485 (save-excursion
14486 (goto-char (region-beginning))
14487 (org-at-item-p))))
14488 (call-interactively 'org-indent-item))
14489 (t (call-interactively 'forward-word))))
14491 (defun org-metaup (&optional arg)
14492 "Move subtree up or move table row up.
14493 Calls `org-move-subtree-up' or `org-table-move-row' or
14494 `org-move-item-up', depending on context. See the individual commands
14495 for more information."
14496 (interactive "P")
14497 (cond
14498 ((run-hook-with-args-until-success 'org-metaup-hook))
14499 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
14500 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14501 ((org-at-item-p) (call-interactively 'org-move-item-up))
14502 (t (transpose-lines 1) (beginning-of-line -1))))
14504 (defun org-metadown (&optional arg)
14505 "Move subtree down or move table row down.
14506 Calls `org-move-subtree-down' or `org-table-move-row' or
14507 `org-move-item-down', depending on context. See the individual
14508 commands for more information."
14509 (interactive "P")
14510 (cond
14511 ((run-hook-with-args-until-success 'org-metadown-hook))
14512 ((org-at-table-p) (call-interactively 'org-table-move-row))
14513 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14514 ((org-at-item-p) (call-interactively 'org-move-item-down))
14515 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
14517 (defun org-shiftup (&optional arg)
14518 "Increase item in timestamp or increase priority of current headline.
14519 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
14520 depending on context. See the individual commands for more information."
14521 (interactive "P")
14522 (cond
14523 ((and org-support-shift-select (org-region-active-p))
14524 (org-call-for-shift-select 'previous-line))
14525 ((org-at-timestamp-p t)
14526 (call-interactively (if org-edit-timestamp-down-means-later
14527 'org-timestamp-down 'org-timestamp-up)))
14528 ((and (not (eq org-support-shift-select 'always))
14529 org-enable-priority-commands
14530 (org-on-heading-p))
14531 (call-interactively 'org-priority-up))
14532 ((and (not org-support-shift-select) (org-at-item-p))
14533 (call-interactively 'org-previous-item))
14534 ((org-clocktable-try-shift 'up arg))
14535 (org-support-shift-select
14536 (org-call-for-shift-select 'previous-line))
14537 (t (org-shiftselect-error))))
14539 (defun org-shiftdown (&optional arg)
14540 "Decrease item in timestamp or decrease priority of current headline.
14541 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
14542 depending on context. See the individual commands for more information."
14543 (interactive "P")
14544 (cond
14545 ((and org-support-shift-select (org-region-active-p))
14546 (org-call-for-shift-select 'next-line))
14547 ((org-at-timestamp-p t)
14548 (call-interactively (if org-edit-timestamp-down-means-later
14549 'org-timestamp-up 'org-timestamp-down)))
14550 ((and (not (eq org-support-shift-select 'always))
14551 org-enable-priority-commands
14552 (org-on-heading-p))
14553 (call-interactively 'org-priority-down))
14554 ((and (not org-support-shift-select) (org-at-item-p))
14555 (call-interactively 'org-next-item))
14556 ((org-clocktable-try-shift 'down arg))
14557 (org-support-shift-select
14558 (org-call-for-shift-select 'next-line))
14559 (t (org-shiftselect-error))))
14561 (defun org-shiftright (&optional arg)
14562 "Cycle the thing at point or in the current line, depending on context.
14563 Depending on context, this does one of the following:
14565 - switch a timestamp at point one day into the future
14566 - on a headline, switch to the next TODO keyword.
14567 - on an item, switch entire list to the next bullet type
14568 - on a property line, switch to the next allowed value
14569 - on a clocktable definition line, move time block into the future"
14570 (interactive "P")
14571 (cond
14572 ((and org-support-shift-select (org-region-active-p))
14573 (org-call-for-shift-select 'forward-char))
14574 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
14575 ((and (not (eq org-support-shift-select 'always))
14576 (org-on-heading-p))
14577 (let ((org-inhibit-logging
14578 (not org-treat-S-cursor-todo-selection-as-state-change))
14579 (org-inhibit-blocking
14580 (not org-treat-S-cursor-todo-selection-as-state-change)))
14581 (org-call-with-arg 'org-todo 'right)))
14582 ((or (and org-support-shift-select
14583 (not (eq org-support-shift-select 'always))
14584 (org-at-item-bullet-p))
14585 (and (not org-support-shift-select) (org-at-item-p)))
14586 (org-call-with-arg 'org-cycle-list-bullet nil))
14587 ((and (not (eq org-support-shift-select 'always))
14588 (org-at-property-p))
14589 (call-interactively 'org-property-next-allowed-value))
14590 ((org-clocktable-try-shift 'right arg))
14591 (org-support-shift-select
14592 (org-call-for-shift-select 'forward-char))
14593 (t (org-shiftselect-error))))
14595 (defun org-shiftleft (&optional arg)
14596 "Cycle the thing at point or in the current line, depending on context.
14597 Depending on context, this does one of the following:
14599 - switch a timestamp at point one day into the past
14600 - on a headline, switch to the previous TODO keyword.
14601 - on an item, switch entire list to the previous bullet type
14602 - on a property line, switch to the previous allowed value
14603 - on a clocktable definition line, move time block into the past"
14604 (interactive "P")
14605 (cond
14606 ((and org-support-shift-select (org-region-active-p))
14607 (org-call-for-shift-select 'backward-char))
14608 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
14609 ((and (not (eq org-support-shift-select 'always))
14610 (org-on-heading-p))
14611 (let ((org-inhibit-logging
14612 (not org-treat-S-cursor-todo-selection-as-state-change))
14613 (org-inhibit-blocking
14614 (not org-treat-S-cursor-todo-selection-as-state-change)))
14615 (org-call-with-arg 'org-todo 'left)))
14616 ((or (and org-support-shift-select
14617 (not (eq org-support-shift-select 'always))
14618 (org-at-item-bullet-p))
14619 (and (not org-support-shift-select) (org-at-item-p)))
14620 (org-call-with-arg 'org-cycle-list-bullet 'previous))
14621 ((and (not (eq org-support-shift-select 'always))
14622 (org-at-property-p))
14623 (call-interactively 'org-property-previous-allowed-value))
14624 ((org-clocktable-try-shift 'left arg))
14625 (org-support-shift-select
14626 (org-call-for-shift-select 'backward-char))
14627 (t (org-shiftselect-error))))
14629 (defun org-shiftcontrolright ()
14630 "Switch to next TODO set."
14631 (interactive)
14632 (cond
14633 ((and org-support-shift-select (org-region-active-p))
14634 (org-call-for-shift-select 'forward-word))
14635 ((and (not (eq org-support-shift-select 'always))
14636 (org-on-heading-p))
14637 (org-call-with-arg 'org-todo 'nextset))
14638 (org-support-shift-select
14639 (org-call-for-shift-select 'forward-word))
14640 (t (org-shiftselect-error))))
14642 (defun org-shiftcontrolleft ()
14643 "Switch to previous TODO set."
14644 (interactive)
14645 (cond
14646 ((and org-support-shift-select (org-region-active-p))
14647 (org-call-for-shift-select 'backward-word))
14648 ((and (not (eq org-support-shift-select 'always))
14649 (org-on-heading-p))
14650 (org-call-with-arg 'org-todo 'previousset))
14651 (org-support-shift-select
14652 (org-call-for-shift-select 'backward-word))
14653 (t (org-shiftselect-error))))
14655 (defun org-ctrl-c-ret ()
14656 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
14657 (interactive)
14658 (cond
14659 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
14660 (t (call-interactively 'org-insert-heading))))
14662 (defun org-copy-special ()
14663 "Copy region in table or copy current subtree.
14664 Calls `org-table-copy' or `org-copy-subtree', depending on context.
14665 See the individual commands for more information."
14666 (interactive)
14667 (call-interactively
14668 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
14670 (defun org-cut-special ()
14671 "Cut region in table or cut current subtree.
14672 Calls `org-table-copy' or `org-cut-subtree', depending on context.
14673 See the individual commands for more information."
14674 (interactive)
14675 (call-interactively
14676 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
14678 (defun org-paste-special (arg)
14679 "Paste rectangular region into table, or past subtree relative to level.
14680 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
14681 See the individual commands for more information."
14682 (interactive "P")
14683 (if (org-at-table-p)
14684 (org-table-paste-rectangle)
14685 (org-paste-subtree arg)))
14687 (defun org-edit-special ()
14688 "Call a special editor for the stuff at point.
14689 When at a table, call the formula editor with `org-table-edit-formulas'.
14690 When at the first line of an src example, call `org-edit-src-code'.
14691 When in an #+include line, visit the include file. Otherwise call
14692 `ffap' to visit the file at point."
14693 (interactive)
14694 (cond
14695 ((org-at-table-p)
14696 (call-interactively 'org-table-edit-formulas))
14697 ((save-excursion
14698 (beginning-of-line 1)
14699 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
14700 (find-file (org-trim (match-string 1))))
14701 ((org-edit-src-code))
14702 ((org-edit-fixed-width-region))
14703 (t (call-interactively 'ffap))))
14706 (defun org-ctrl-c-ctrl-c (&optional arg)
14707 "Set tags in headline, or update according to changed information at point.
14709 This command does many different things, depending on context:
14711 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
14712 this is what we do.
14714 - If the cursor is in a headline, prompt for tags and insert them
14715 into the current line, aligned to `org-tags-column'. When called
14716 with prefix arg, realign all tags in the current buffer.
14718 - If the cursor is in one of the special #+KEYWORD lines, this
14719 triggers scanning the buffer for these lines and updating the
14720 information.
14722 - If the cursor is inside a table, realign the table. This command
14723 works even if the automatic table editor has been turned off.
14725 - If the cursor is on a #+TBLFM line, re-apply the formulas to
14726 the entire table.
14728 - If the cursor is at a footnote reference or definition, jump to
14729 the corresponding definition or references, respectively.
14731 - If the cursor is a the beginning of a dynamic block, update it.
14733 - If the cursor is inside a table created by the table.el package,
14734 activate that table.
14736 - If the current buffer is a remember buffer, close note and file
14737 it. A prefix argument of 1 files to the default location
14738 without further interaction. A prefix argument of 2 files to
14739 the currently clocking task.
14741 - If the cursor is on a <<<target>>>, update radio targets and corresponding
14742 links in this buffer.
14744 - If the cursor is on a numbered item in a plain list, renumber the
14745 ordered list.
14747 - If the cursor is on a checkbox, toggle it."
14748 (interactive "P")
14749 (let ((org-enable-table-editor t))
14750 (cond
14751 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
14752 org-occur-highlights
14753 org-latex-fragment-image-overlays)
14754 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
14755 (org-remove-occur-highlights)
14756 (org-remove-latex-fragment-image-overlays)
14757 (message "Temporary highlights/overlays removed from current buffer"))
14758 ((and (local-variable-p 'org-finish-function (current-buffer))
14759 (fboundp org-finish-function))
14760 (funcall org-finish-function))
14761 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
14762 ((org-at-property-p)
14763 (call-interactively 'org-property-action))
14764 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
14765 ((org-on-heading-p) (call-interactively 'org-set-tags))
14766 ((org-at-table.el-p)
14767 (require 'table)
14768 (beginning-of-line 1)
14769 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
14770 (call-interactively 'table-recognize-table))
14771 ((org-at-table-p)
14772 (org-table-maybe-eval-formula)
14773 (if arg
14774 (call-interactively 'org-table-recalculate)
14775 (org-table-maybe-recalculate-line))
14776 (call-interactively 'org-table-align))
14777 ((or (org-footnote-at-reference-p)
14778 (org-footnote-at-definition-p))
14779 (call-interactively 'org-footnote-action))
14780 ((org-at-item-checkbox-p)
14781 (call-interactively 'org-toggle-checkbox))
14782 ((org-at-item-p)
14783 (if arg
14784 (call-interactively 'org-toggle-checkbox)
14785 (call-interactively 'org-maybe-renumber-ordered-list)))
14786 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
14787 ;; Dynamic block
14788 (beginning-of-line 1)
14789 (save-excursion (org-update-dblock)))
14790 ((save-excursion
14791 (beginning-of-line 1)
14792 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
14793 (cond
14794 ((equal (match-string 1) "TBLFM")
14795 ;; Recalculate the table before this line
14796 (save-excursion
14797 (beginning-of-line 1)
14798 (skip-chars-backward " \r\n\t")
14799 (if (org-at-table-p)
14800 (org-call-with-arg 'org-table-recalculate t))))
14802 ; (org-set-regexps-and-options)
14803 ; (org-restart-font-lock)
14804 (let ((org-inhibit-startup t)) (org-mode-restart))
14805 (message "Local setup has been refreshed"))))
14806 ((org-clock-update-time-maybe))
14807 (t (error "C-c C-c can do nothing useful at this location.")))))
14809 (defun org-mode-restart ()
14810 "Restart Org-mode, to scan again for special lines.
14811 Also updates the keyword regular expressions."
14812 (interactive)
14813 (org-mode)
14814 (message "Org-mode restarted"))
14816 (defun org-kill-note-or-show-branches ()
14817 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
14818 (interactive)
14819 (if (not org-finish-function)
14820 (call-interactively 'show-branches)
14821 (let ((org-note-abort t))
14822 (funcall org-finish-function))))
14824 (defun org-return (&optional indent)
14825 "Goto next table row or insert a newline.
14826 Calls `org-table-next-row' or `newline', depending on context.
14827 See the individual commands for more information."
14828 (interactive)
14829 (cond
14830 ((bobp) (if indent (newline-and-indent) (newline)))
14831 ((org-at-table-p)
14832 (org-table-justify-field-maybe)
14833 (call-interactively 'org-table-next-row))
14834 ((and org-return-follows-link
14835 (eq (get-text-property (point) 'face) 'org-link))
14836 (call-interactively 'org-open-at-point))
14837 ((and (org-at-heading-p)
14838 (looking-at
14839 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
14840 (org-show-entry)
14841 (end-of-line 1)
14842 (newline))
14843 (t (if indent (newline-and-indent) (newline)))))
14845 (defun org-return-indent ()
14846 "Goto next table row or insert a newline and indent.
14847 Calls `org-table-next-row' or `newline-and-indent', depending on
14848 context. See the individual commands for more information."
14849 (interactive)
14850 (org-return t))
14852 (defun org-ctrl-c-star ()
14853 "Compute table, or change heading status of lines.
14854 Calls `org-table-recalculate' or `org-toggle-heading',
14855 depending on context."
14856 (interactive)
14857 (cond
14858 ((org-at-table-p)
14859 (call-interactively 'org-table-recalculate))
14861 ;; Convert all lines in region to list items
14862 (call-interactively 'org-toggle-heading))))
14864 (defun org-ctrl-c-minus ()
14865 "Insert separator line in table or modify bullet status of line.
14866 Also turns a plain line or a region of lines into list items.
14867 Calls `org-table-insert-hline', `org-toggle-item', or
14868 `org-cycle-list-bullet', depending on context."
14869 (interactive)
14870 (cond
14871 ((org-at-table-p)
14872 (call-interactively 'org-table-insert-hline))
14873 ((org-region-active-p)
14874 (call-interactively 'org-toggle-item))
14875 ((org-in-item-p)
14876 (call-interactively 'org-cycle-list-bullet))
14878 (call-interactively 'org-toggle-item))))
14880 (defun org-toggle-item ()
14881 "Convert headings or normal lines to items, items to normal lines.
14882 If there is no active region, only the current line is considered.
14884 If the first line in the region is a headline, convert all headlines to items.
14886 If the first line in the region is an item, convert all items to normal lines.
14888 If the first line is normal text, add an item bullet to each line."
14889 (interactive)
14890 (let (l2 l beg end)
14891 (if (org-region-active-p)
14892 (setq beg (region-beginning) end (region-end))
14893 (setq beg (point-at-bol)
14894 end (min (1+ (point-at-eol)) (point-max))))
14895 (save-excursion
14896 (goto-char end)
14897 (setq l2 (org-current-line))
14898 (goto-char beg)
14899 (beginning-of-line 1)
14900 (setq l (1- (org-current-line)))
14901 (if (org-at-item-p)
14902 ;; We already have items, de-itemize
14903 (while (< (setq l (1+ l)) l2)
14904 (when (org-at-item-p)
14905 (goto-char (match-beginning 2))
14906 (delete-region (match-beginning 2) (match-end 2))
14907 (and (looking-at "[ \t]+") (replace-match "")))
14908 (beginning-of-line 2))
14909 (if (org-on-heading-p)
14910 ;; Headings, convert to items
14911 (while (< (setq l (1+ l)) l2)
14912 (if (looking-at org-outline-regexp)
14913 (replace-match "- " t t))
14914 (beginning-of-line 2))
14915 ;; normal lines, turn them into items
14916 (while (< (setq l (1+ l)) l2)
14917 (unless (org-at-item-p)
14918 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14919 (replace-match "\\1- \\2")))
14920 (beginning-of-line 2)))))))
14922 (defun org-toggle-heading (&optional nstars)
14923 "Convert headings to normal text, or items or text to headings.
14924 If there is no active region, only the current line is considered.
14926 If the first line is a heading, remove the stars from all headlines
14927 in the region.
14929 If the first line is a plain list item, turn all plain list items
14930 into headings.
14932 If the first line is a normal line, turn each and every line in the
14933 region into a heading.
14935 When converting a line into a heading, the number of stars is chosen
14936 such that the lines become children of the current entry. However,
14937 when a prefix argument is given, its value determines the number of
14938 stars to add."
14939 (interactive "P")
14940 (let (l2 l itemp beg end)
14941 (if (org-region-active-p)
14942 (setq beg (region-beginning) end (region-end))
14943 (setq beg (point-at-bol)
14944 end (min (1+ (point-at-eol)) (point-max))))
14945 (save-excursion
14946 (goto-char end)
14947 (setq l2 (org-current-line))
14948 (goto-char beg)
14949 (beginning-of-line 1)
14950 (setq l (1- (org-current-line)))
14951 (if (org-on-heading-p)
14952 ;; We already have headlines, de-star them
14953 (while (< (setq l (1+ l)) l2)
14954 (when (org-on-heading-p t)
14955 (and (looking-at outline-regexp) (replace-match "")))
14956 (beginning-of-line 2))
14957 (setq itemp (org-at-item-p))
14958 (let* ((stars
14959 (if nstars
14960 (make-string (prefix-numeric-value current-prefix-arg)
14962 (save-excursion
14963 (if (re-search-backward org-complex-heading-regexp nil t)
14964 (match-string 1) ""))))
14965 (add-stars (cond (nstars "")
14966 ((equal stars "") "*")
14967 (org-odd-levels-only "**")
14968 (t "*")))
14969 (rpl (concat stars add-stars " ")))
14970 (while (< (setq l (1+ l)) l2)
14971 (if itemp
14972 (and (org-at-item-p) (replace-match rpl t t))
14973 (unless (org-on-heading-p)
14974 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14975 (replace-match (concat rpl (match-string 2))))))
14976 (beginning-of-line 2)))))))
14978 (defun org-meta-return (&optional arg)
14979 "Insert a new heading or wrap a region in a table.
14980 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
14981 See the individual commands for more information."
14982 (interactive "P")
14983 (cond
14984 ((run-hook-with-args-until-success 'org-metareturn-hook))
14985 ((org-at-table-p)
14986 (call-interactively 'org-table-wrap-region))
14987 (t (call-interactively 'org-insert-heading))))
14989 ;;; Menu entries
14991 ;; Define the Org-mode menus
14992 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
14993 '("Tbl"
14994 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
14995 ["Next Field" org-cycle (org-at-table-p)]
14996 ["Previous Field" org-shifttab (org-at-table-p)]
14997 ["Next Row" org-return (org-at-table-p)]
14998 "--"
14999 ["Blank Field" org-table-blank-field (org-at-table-p)]
15000 ["Edit Field" org-table-edit-field (org-at-table-p)]
15001 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
15002 "--"
15003 ("Column"
15004 ["Move Column Left" org-metaleft (org-at-table-p)]
15005 ["Move Column Right" org-metaright (org-at-table-p)]
15006 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
15007 ["Insert Column" org-shiftmetaright (org-at-table-p)])
15008 ("Row"
15009 ["Move Row Up" org-metaup (org-at-table-p)]
15010 ["Move Row Down" org-metadown (org-at-table-p)]
15011 ["Delete Row" org-shiftmetaup (org-at-table-p)]
15012 ["Insert Row" org-shiftmetadown (org-at-table-p)]
15013 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
15014 "--"
15015 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
15016 ("Rectangle"
15017 ["Copy Rectangle" org-copy-special (org-at-table-p)]
15018 ["Cut Rectangle" org-cut-special (org-at-table-p)]
15019 ["Paste Rectangle" org-paste-special (org-at-table-p)]
15020 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
15021 "--"
15022 ("Calculate"
15023 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
15024 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
15025 ["Edit Formulas" org-edit-special (org-at-table-p)]
15026 "--"
15027 ["Recalculate line" org-table-recalculate (org-at-table-p)]
15028 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
15029 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
15030 "--"
15031 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
15032 "--"
15033 ["Sum Column/Rectangle" org-table-sum
15034 (or (org-at-table-p) (org-region-active-p))]
15035 ["Which Column?" org-table-current-column (org-at-table-p)])
15036 ["Debug Formulas"
15037 org-table-toggle-formula-debugger
15038 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
15039 ["Show Col/Row Numbers"
15040 org-table-toggle-coordinate-overlays
15041 :style toggle
15042 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
15043 "--"
15044 ["Create" org-table-create (and (not (org-at-table-p))
15045 org-enable-table-editor)]
15046 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
15047 ["Import from File" org-table-import (not (org-at-table-p))]
15048 ["Export to File" org-table-export (org-at-table-p)]
15049 "--"
15050 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
15052 (easy-menu-define org-org-menu org-mode-map "Org menu"
15053 '("Org"
15054 ("Show/Hide"
15055 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
15056 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
15057 ["Sparse Tree..." org-sparse-tree t]
15058 ["Reveal Context" org-reveal t]
15059 ["Show All" show-all t]
15060 "--"
15061 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
15062 "--"
15063 ["New Heading" org-insert-heading t]
15064 ("Navigate Headings"
15065 ["Up" outline-up-heading t]
15066 ["Next" outline-next-visible-heading t]
15067 ["Previous" outline-previous-visible-heading t]
15068 ["Next Same Level" outline-forward-same-level t]
15069 ["Previous Same Level" outline-backward-same-level t]
15070 "--"
15071 ["Jump" org-goto t])
15072 ("Edit Structure"
15073 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
15074 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
15075 "--"
15076 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
15077 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
15078 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
15079 "--"
15080 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
15081 "--"
15082 ["Promote Heading" org-metaleft (not (org-at-table-p))]
15083 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
15084 ["Demote Heading" org-metaright (not (org-at-table-p))]
15085 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
15086 "--"
15087 ["Sort Region/Children" org-sort (not (org-at-table-p))]
15088 "--"
15089 ["Convert to odd levels" org-convert-to-odd-levels t]
15090 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
15091 ("Editing"
15092 ["Emphasis..." org-emphasize t]
15093 ["Edit Source Example" org-edit-special t]
15094 "--"
15095 ["Footnote new/jump" org-footnote-action t]
15096 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
15097 ("Archive"
15098 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
15099 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
15100 ; :active t :keys "C-u C-c C-x C-a"]
15101 ["Sparse trees open ARCHIVE trees"
15102 (setq org-sparse-tree-open-archived-trees
15103 (not org-sparse-tree-open-archived-trees))
15104 :style toggle :selected org-sparse-tree-open-archived-trees]
15105 ["Cycling opens ARCHIVE trees"
15106 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
15107 :style toggle :selected org-cycle-open-archived-trees]
15108 "--"
15109 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
15110 ["Move Subtree to Archive" org-advertized-archive-subtree t]
15111 ; ["Check and Move Children" (org-archive-subtree '(4))
15112 ; :active t :keys "C-u C-c C-x C-s"]
15114 "--"
15115 ("Hyperlinks"
15116 ["Store Link (Global)" org-store-link t]
15117 ["Find existing link to here" org-occur-link-in-agenda-files t]
15118 ["Insert Link" org-insert-link t]
15119 ["Follow Link" org-open-at-point t]
15120 "--"
15121 ["Next link" org-next-link t]
15122 ["Previous link" org-previous-link t]
15123 "--"
15124 ["Descriptive Links"
15125 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
15126 :style radio
15127 :selected (member '(org-link) buffer-invisibility-spec)]
15128 ["Literal Links"
15129 (progn
15130 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
15131 :style radio
15132 :selected (not (member '(org-link) buffer-invisibility-spec))])
15133 "--"
15134 ("TODO Lists"
15135 ["TODO/DONE/-" org-todo t]
15136 ("Select keyword"
15137 ["Next keyword" org-shiftright (org-on-heading-p)]
15138 ["Previous keyword" org-shiftleft (org-on-heading-p)]
15139 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
15140 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
15141 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
15142 ["Show TODO Tree" org-show-todo-tree t]
15143 ["Global TODO list" org-todo-list t]
15144 "--"
15145 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
15146 :selected org-enforce-todo-dependencies :style toggle :active t]
15147 "Settings for tree at point"
15148 ["Do Children sequentially" org-toggle-ordered-property :style radio
15149 :selected (ignore-errors (org-entry-get nil "ORDERED"))
15150 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15151 ["Do Children parallel" org-toggle-ordered-property :style radio
15152 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
15153 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15154 "--"
15155 ["Set Priority" org-priority t]
15156 ["Priority Up" org-shiftup t]
15157 ["Priority Down" org-shiftdown t]
15158 "--"
15159 ["Get news from all feeds" org-feed-update-all t]
15160 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
15161 ["Customize feeds" (customize-variable 'org-feed-alist) t])
15162 ("TAGS and Properties"
15163 ["Set Tags" org-set-tags-command t]
15164 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
15165 "--"
15166 ["Set property" org-set-property t]
15167 ["Column view of properties" org-columns t]
15168 ["Insert Column View DBlock" org-insert-columns-dblock t])
15169 ("Dates and Scheduling"
15170 ["Timestamp" org-time-stamp t]
15171 ["Timestamp (inactive)" org-time-stamp-inactive t]
15172 ("Change Date"
15173 ["1 Day Later" org-shiftright t]
15174 ["1 Day Earlier" org-shiftleft t]
15175 ["1 ... Later" org-shiftup t]
15176 ["1 ... Earlier" org-shiftdown t])
15177 ["Compute Time Range" org-evaluate-time-range t]
15178 ["Schedule Item" org-schedule t]
15179 ["Deadline" org-deadline t]
15180 "--"
15181 ["Custom time format" org-toggle-time-stamp-overlays
15182 :style radio :selected org-display-custom-times]
15183 "--"
15184 ["Goto Calendar" org-goto-calendar t]
15185 ["Date from Calendar" org-date-from-calendar t]
15186 "--"
15187 ["Start/Restart Timer" org-timer-start t]
15188 ["Pause/Continue Timer" org-timer-pause-or-continue t]
15189 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
15190 ["Insert Timer String" org-timer t]
15191 ["Insert Timer Item" org-timer-item t])
15192 ("Logging work"
15193 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
15194 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
15195 ["Clock out" org-clock-out t]
15196 ["Clock cancel" org-clock-cancel t]
15197 "--"
15198 ["Mark as default task" org-clock-mark-default-task t]
15199 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
15200 ["Goto running clock" org-clock-goto t]
15201 "--"
15202 ["Display times" org-clock-display t]
15203 ["Create clock table" org-clock-report t]
15204 "--"
15205 ["Record DONE time"
15206 (progn (setq org-log-done (not org-log-done))
15207 (message "Switching to %s will %s record a timestamp"
15208 (car org-done-keywords)
15209 (if org-log-done "automatically" "not")))
15210 :style toggle :selected org-log-done])
15211 "--"
15212 ["Agenda Command..." org-agenda t]
15213 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
15214 ("File List for Agenda")
15215 ("Special views current file"
15216 ["TODO Tree" org-show-todo-tree t]
15217 ["Check Deadlines" org-check-deadlines t]
15218 ["Timeline" org-timeline t]
15219 ["Tags/Property tree" org-match-sparse-tree t])
15220 "--"
15221 ["Export/Publish..." org-export t]
15222 ("LaTeX"
15223 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
15224 :selected org-cdlatex-mode]
15225 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
15226 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
15227 ["Modify math symbol" org-cdlatex-math-modify
15228 (org-inside-LaTeX-fragment-p)]
15229 ["Insert citation" org-reftex-citation t]
15230 "--"
15231 ["Export LaTeX fragments as images"
15232 (if (featurep 'org-exp)
15233 (setq org-export-with-LaTeX-fragments
15234 (not org-export-with-LaTeX-fragments))
15235 (require 'org-exp))
15236 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
15237 org-export-with-LaTeX-fragments)])
15238 "--"
15239 ("Documentation"
15240 ["Show Version" org-version t]
15241 ["Info Documentation" org-info t])
15242 ("Customize"
15243 ["Browse Org Group" org-customize t]
15244 "--"
15245 ["Expand This Menu" org-create-customize-menu
15246 (fboundp 'customize-menu-create)])
15247 "--"
15248 ("Refresh/Reload"
15249 ["Refresh setup current buffer" org-mode-restart t]
15250 ["Reload Org (after update)" org-reload t]
15251 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
15254 (defun org-info (&optional node)
15255 "Read documentation for Org-mode in the info system.
15256 With optional NODE, go directly to that node."
15257 (interactive)
15258 (info (format "(org)%s" (or node ""))))
15260 (defun org-install-agenda-files-menu ()
15261 (let ((bl (buffer-list)))
15262 (save-excursion
15263 (while bl
15264 (set-buffer (pop bl))
15265 (if (org-mode-p) (setq bl nil)))
15266 (when (org-mode-p)
15267 (easy-menu-change
15268 '("Org") "File List for Agenda"
15269 (append
15270 (list
15271 ["Edit File List" (org-edit-agenda-file-list) t]
15272 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
15273 ["Remove Current File from List" org-remove-file t]
15274 ["Cycle through agenda files" org-cycle-agenda-files t]
15275 ["Occur in all agenda files" org-occur-in-agenda-files t]
15276 "--")
15277 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
15279 ;;;; Documentation
15281 ;;;###autoload
15282 (defun org-require-autoloaded-modules ()
15283 (interactive)
15284 (mapc 'require
15285 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
15286 org-docbook org-exp org-html org-icalendar
15287 org-id org-latex
15288 org-publish org-remember org-table
15289 org-timer org-xoxo)))
15291 ;;;###autoload
15292 (defun org-reload (&optional uncompiled)
15293 "Reload all org lisp files.
15294 With prefix arg UNCOMPILED, load the uncompiled versions."
15295 (interactive "P")
15296 (require 'find-func)
15297 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
15298 (dir-org (file-name-directory (org-find-library-name "org")))
15299 (dir-org-contrib (ignore-errors
15300 (file-name-directory
15301 (org-find-library-name "org-contribdir"))))
15302 (files
15303 (append (directory-files dir-org t file-re)
15304 (and dir-org-contrib
15305 (directory-files dir-org-contrib t file-re))))
15306 (remove-re (concat (if (featurep 'xemacs)
15307 "org-colview" "org-colview-xemacs")
15308 "\\'")))
15309 (setq files (mapcar 'file-name-sans-extension files))
15310 (setq files (mapcar
15311 (lambda (x) (if (string-match remove-re x) nil x))
15312 files))
15313 (setq files (delq nil files))
15314 (mapc
15315 (lambda (f)
15316 (when (featurep (intern (file-name-nondirectory f)))
15317 (if (and (not uncompiled)
15318 (file-exists-p (concat f ".elc")))
15319 (load (concat f ".elc") nil nil t)
15320 (load (concat f ".el") nil nil t))))
15321 files))
15322 (org-version))
15324 ;;;###autoload
15325 (defun org-customize ()
15326 "Call the customize function with org as argument."
15327 (interactive)
15328 (org-load-modules-maybe)
15329 (org-require-autoloaded-modules)
15330 (customize-browse 'org))
15332 (defun org-create-customize-menu ()
15333 "Create a full customization menu for Org-mode, insert it into the menu."
15334 (interactive)
15335 (org-load-modules-maybe)
15336 (org-require-autoloaded-modules)
15337 (if (fboundp 'customize-menu-create)
15338 (progn
15339 (easy-menu-change
15340 '("Org") "Customize"
15341 `(["Browse Org group" org-customize t]
15342 "--"
15343 ,(customize-menu-create 'org)
15344 ["Set" Custom-set t]
15345 ["Save" Custom-save t]
15346 ["Reset to Current" Custom-reset-current t]
15347 ["Reset to Saved" Custom-reset-saved t]
15348 ["Reset to Standard Settings" Custom-reset-standard t]))
15349 (message "\"Org\"-menu now contains full customization menu"))
15350 (error "Cannot expand menu (outdated version of cus-edit.el)")))
15352 ;;;; Miscellaneous stuff
15354 ;;; Generally useful functions
15356 (defun org-find-text-property-in-string (prop s)
15357 "Return the first non-nil value of property PROP in string S."
15358 (or (get-text-property 0 prop s)
15359 (get-text-property (or (next-single-property-change 0 prop s) 0)
15360 prop s)))
15362 (defun org-display-warning (message) ;; Copied from Emacs-Muse
15363 "Display the given MESSAGE as a warning."
15364 (if (fboundp 'display-warning)
15365 (display-warning 'org message
15366 (if (featurep 'xemacs)
15367 'warning
15368 :warning))
15369 (let ((buf (get-buffer-create "*Org warnings*")))
15370 (with-current-buffer buf
15371 (goto-char (point-max))
15372 (insert "Warning (Org): " message)
15373 (unless (bolp)
15374 (newline)))
15375 (display-buffer buf)
15376 (sit-for 0))))
15378 (defun org-goto-marker-or-bmk (marker &optional bookmark)
15379 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
15380 (if (and marker (marker-buffer marker)
15381 (buffer-live-p (marker-buffer marker)))
15382 (progn
15383 (switch-to-buffer (marker-buffer marker))
15384 (if (or (> marker (point-max)) (< marker (point-min)))
15385 (widen))
15386 (goto-char marker)
15387 (org-show-context 'org-goto))
15388 (if bookmark
15389 (bookmark-jump bookmark)
15390 (error "Cannot find location"))))
15392 (defun org-quote-csv-field (s)
15393 "Quote field for inclusion in CSV material."
15394 (if (string-match "[\",]" s)
15395 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
15398 (defun org-plist-delete (plist property)
15399 "Delete PROPERTY from PLIST.
15400 This is in contrast to merely setting it to 0."
15401 (let (p)
15402 (while plist
15403 (if (not (eq property (car plist)))
15404 (setq p (plist-put p (car plist) (nth 1 plist))))
15405 (setq plist (cddr plist)))
15408 (defun org-force-self-insert (N)
15409 "Needed to enforce self-insert under remapping."
15410 (interactive "p")
15411 (self-insert-command N))
15413 (defun org-string-width (s)
15414 "Compute width of string, ignoring invisible characters.
15415 This ignores character with invisibility property `org-link', and also
15416 characters with property `org-cwidth', because these will become invisible
15417 upon the next fontification round."
15418 (let (b l)
15419 (when (or (eq t buffer-invisibility-spec)
15420 (assq 'org-link buffer-invisibility-spec))
15421 (while (setq b (text-property-any 0 (length s)
15422 'invisible 'org-link s))
15423 (setq s (concat (substring s 0 b)
15424 (substring s (or (next-single-property-change
15425 b 'invisible s) (length s)))))))
15426 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
15427 (setq s (concat (substring s 0 b)
15428 (substring s (or (next-single-property-change
15429 b 'org-cwidth s) (length s))))))
15430 (setq l (string-width s) b -1)
15431 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
15432 (setq l (- l (get-text-property b 'org-dwidth-n s))))
15435 (defun org-get-indentation (&optional line)
15436 "Get the indentation of the current line, interpreting tabs.
15437 When LINE is given, assume it represents a line and compute its indentation."
15438 (if line
15439 (if (string-match "^ *" (org-remove-tabs line))
15440 (match-end 0))
15441 (save-excursion
15442 (beginning-of-line 1)
15443 (skip-chars-forward " \t")
15444 (current-column))))
15446 (defun org-remove-tabs (s &optional width)
15447 "Replace tabulators in S with spaces.
15448 Assumes that s is a single line, starting in column 0."
15449 (setq width (or width tab-width))
15450 (while (string-match "\t" s)
15451 (setq s (replace-match
15452 (make-string
15453 (- (* width (/ (+ (match-beginning 0) width) width))
15454 (match-beginning 0)) ?\ )
15455 t t s)))
15458 (defun org-fix-indentation (line ind)
15459 "Fix indentation in LINE.
15460 IND is a cons cell with target and minimum indentation.
15461 If the current indentation in LINE is smaller than the minimum,
15462 leave it alone. If it is larger than ind, set it to the target."
15463 (let* ((l (org-remove-tabs line))
15464 (i (org-get-indentation l))
15465 (i1 (car ind)) (i2 (cdr ind)))
15466 (if (>= i i2) (setq l (substring line i2)))
15467 (if (> i1 0)
15468 (concat (make-string i1 ?\ ) l)
15469 l)))
15471 (defun org-remove-indentation (code &optional n)
15472 "Remove the maximum common indentation from the lines in CODE.
15473 N may optionally be the number of spaces to remove."
15474 (with-temp-buffer
15475 (insert code)
15476 (org-do-remove-indentation n)
15477 (buffer-string)))
15479 (defun org-do-remove-indentation (&optional n)
15480 "Remove the maximum common indentation from the buffer."
15481 (untabify (point-min) (point-max))
15482 (let ((min 10000) re)
15483 (if n
15484 (setq min n)
15485 (goto-char (point-min))
15486 (while (re-search-forward "^ *[^ \n]" nil t)
15487 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
15488 (unless (or (= min 0) (= min 10000))
15489 (setq re (format "^ \\{%d\\}" min))
15490 (goto-char (point-min))
15491 (while (re-search-forward re nil t)
15492 (replace-match "")
15493 (end-of-line 1))
15494 min)))
15496 (defun org-base-buffer (buffer)
15497 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
15498 (if (not buffer)
15499 buffer
15500 (or (buffer-base-buffer buffer)
15501 buffer)))
15503 (defun org-trim (s)
15504 "Remove whitespace at beginning and end of string."
15505 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
15506 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
15509 (defun org-wrap (string &optional width lines)
15510 "Wrap string to either a number of lines, or a width in characters.
15511 If WIDTH is non-nil, the string is wrapped to that width, however many lines
15512 that costs. If there is a word longer than WIDTH, the text is actually
15513 wrapped to the length of that word.
15514 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
15515 many lines, whatever width that takes.
15516 The return value is a list of lines, without newlines at the end."
15517 (let* ((words (org-split-string string "[ \t\n]+"))
15518 (maxword (apply 'max (mapcar 'org-string-width words)))
15519 w ll)
15520 (cond (width
15521 (org-do-wrap words (max maxword width)))
15522 (lines
15523 (setq w maxword)
15524 (setq ll (org-do-wrap words maxword))
15525 (if (<= (length ll) lines)
15527 (setq ll words)
15528 (while (> (length ll) lines)
15529 (setq w (1+ w))
15530 (setq ll (org-do-wrap words w)))
15531 ll))
15532 (t (error "Cannot wrap this")))))
15534 (defun org-do-wrap (words width)
15535 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
15536 (let (lines line)
15537 (while words
15538 (setq line (pop words))
15539 (while (and words (< (+ (length line) (length (car words))) width))
15540 (setq line (concat line " " (pop words))))
15541 (setq lines (push line lines)))
15542 (nreverse lines)))
15544 (defun org-split-string (string &optional separators)
15545 "Splits STRING into substrings at SEPARATORS.
15546 No empty strings are returned if there are matches at the beginning
15547 and end of string."
15548 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
15549 (start 0)
15550 notfirst
15551 (list nil))
15552 (while (and (string-match rexp string
15553 (if (and notfirst
15554 (= start (match-beginning 0))
15555 (< start (length string)))
15556 (1+ start) start))
15557 (< (match-beginning 0) (length string)))
15558 (setq notfirst t)
15559 (or (eq (match-beginning 0) 0)
15560 (and (eq (match-beginning 0) (match-end 0))
15561 (eq (match-beginning 0) start))
15562 (setq list
15563 (cons (substring string start (match-beginning 0))
15564 list)))
15565 (setq start (match-end 0)))
15566 (or (eq start (length string))
15567 (setq list
15568 (cons (substring string start)
15569 list)))
15570 (nreverse list)))
15572 (defun org-quote-vert (s)
15573 "Replace \"|\" with \"\\vert\"."
15574 (while (string-match "|" s)
15575 (setq s (replace-match "\\vert" t t s)))
15578 (defun org-uuidgen-p (s)
15579 "Is S an ID created by UUIDGEN?"
15580 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
15582 (defun org-context ()
15583 "Return a list of contexts of the current cursor position.
15584 If several contexts apply, all are returned.
15585 Each context entry is a list with a symbol naming the context, and
15586 two positions indicating start and end of the context. Possible
15587 contexts are:
15589 :headline anywhere in a headline
15590 :headline-stars on the leading stars in a headline
15591 :todo-keyword on a TODO keyword (including DONE) in a headline
15592 :tags on the TAGS in a headline
15593 :priority on the priority cookie in a headline
15594 :item on the first line of a plain list item
15595 :item-bullet on the bullet/number of a plain list item
15596 :checkbox on the checkbox in a plain list item
15597 :table in an org-mode table
15598 :table-special on a special filed in a table
15599 :table-table in a table.el table
15600 :link on a hyperlink
15601 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
15602 :target on a <<target>>
15603 :radio-target on a <<<radio-target>>>
15604 :latex-fragment on a LaTeX fragment
15605 :latex-preview on a LaTeX fragment with overlayed preview image
15607 This function expects the position to be visible because it uses font-lock
15608 faces as a help to recognize the following contexts: :table-special, :link,
15609 and :keyword."
15610 (let* ((f (get-text-property (point) 'face))
15611 (faces (if (listp f) f (list f)))
15612 (p (point)) clist o)
15613 ;; First the large context
15614 (cond
15615 ((org-on-heading-p t)
15616 (push (list :headline (point-at-bol) (point-at-eol)) clist)
15617 (when (progn
15618 (beginning-of-line 1)
15619 (looking-at org-todo-line-tags-regexp))
15620 (push (org-point-in-group p 1 :headline-stars) clist)
15621 (push (org-point-in-group p 2 :todo-keyword) clist)
15622 (push (org-point-in-group p 4 :tags) clist))
15623 (goto-char p)
15624 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
15625 (if (looking-at "\\[#[A-Z0-9]\\]")
15626 (push (org-point-in-group p 0 :priority) clist)))
15628 ((org-at-item-p)
15629 (push (org-point-in-group p 2 :item-bullet) clist)
15630 (push (list :item (point-at-bol)
15631 (save-excursion (org-end-of-item) (point)))
15632 clist)
15633 (and (org-at-item-checkbox-p)
15634 (push (org-point-in-group p 0 :checkbox) clist)))
15636 ((org-at-table-p)
15637 (push (list :table (org-table-begin) (org-table-end)) clist)
15638 (if (memq 'org-formula faces)
15639 (push (list :table-special
15640 (previous-single-property-change p 'face)
15641 (next-single-property-change p 'face)) clist)))
15642 ((org-at-table-p 'any)
15643 (push (list :table-table) clist)))
15644 (goto-char p)
15646 ;; Now the small context
15647 (cond
15648 ((org-at-timestamp-p)
15649 (push (org-point-in-group p 0 :timestamp) clist))
15650 ((memq 'org-link faces)
15651 (push (list :link
15652 (previous-single-property-change p 'face)
15653 (next-single-property-change p 'face)) clist))
15654 ((memq 'org-special-keyword faces)
15655 (push (list :keyword
15656 (previous-single-property-change p 'face)
15657 (next-single-property-change p 'face)) clist))
15658 ((org-on-target-p)
15659 (push (org-point-in-group p 0 :target) clist)
15660 (goto-char (1- (match-beginning 0)))
15661 (if (looking-at org-radio-target-regexp)
15662 (push (org-point-in-group p 0 :radio-target) clist))
15663 (goto-char p))
15664 ((setq o (car (delq nil
15665 (mapcar
15666 (lambda (x)
15667 (if (memq x org-latex-fragment-image-overlays) x))
15668 (org-overlays-at (point))))))
15669 (push (list :latex-fragment
15670 (org-overlay-start o) (org-overlay-end o)) clist)
15671 (push (list :latex-preview
15672 (org-overlay-start o) (org-overlay-end o)) clist))
15673 ((org-inside-LaTeX-fragment-p)
15674 ;; FIXME: positions wrong.
15675 (push (list :latex-fragment (point) (point)) clist)))
15677 (setq clist (nreverse (delq nil clist)))
15678 clist))
15680 ;; FIXME: Compare with at-regexp-p Do we need both?
15681 (defun org-in-regexp (re &optional nlines visually)
15682 "Check if point is inside a match of regexp.
15683 Normally only the current line is checked, but you can include NLINES extra
15684 lines both before and after point into the search.
15685 If VISUALLY is set, require that the cursor is not after the match but
15686 really on, so that the block visually is on the match."
15687 (catch 'exit
15688 (let ((pos (point))
15689 (eol (point-at-eol (+ 1 (or nlines 0))))
15690 (inc (if visually 1 0)))
15691 (save-excursion
15692 (beginning-of-line (- 1 (or nlines 0)))
15693 (while (re-search-forward re eol t)
15694 (if (and (<= (match-beginning 0) pos)
15695 (>= (+ inc (match-end 0)) pos))
15696 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
15698 (defun org-at-regexp-p (regexp)
15699 "Is point inside a match of REGEXP in the current line?"
15700 (catch 'exit
15701 (save-excursion
15702 (let ((pos (point)) (end (point-at-eol)))
15703 (beginning-of-line 1)
15704 (while (re-search-forward regexp end t)
15705 (if (and (<= (match-beginning 0) pos)
15706 (>= (match-end 0) pos))
15707 (throw 'exit t)))
15708 nil))))
15710 (defun org-occur-in-agenda-files (regexp &optional nlines)
15711 "Call `multi-occur' with buffers for all agenda files."
15712 (interactive "sOrg-files matching: \np")
15713 (let* ((files (org-agenda-files))
15714 (tnames (mapcar 'file-truename files))
15715 (extra org-agenda-text-search-extra-files)
15717 (when (eq (car extra) 'agenda-archives)
15718 (setq extra (cdr extra))
15719 (setq files (org-add-archive-files files)))
15720 (while (setq f (pop extra))
15721 (unless (member (file-truename f) tnames)
15722 (add-to-list 'files f 'append)
15723 (add-to-list 'tnames (file-truename f) 'append)))
15724 (multi-occur
15725 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
15726 regexp)))
15728 (if (boundp 'occur-mode-find-occurrence-hook)
15729 ;; Emacs 23
15730 (add-hook 'occur-mode-find-occurrence-hook
15731 (lambda ()
15732 (when (org-mode-p)
15733 (org-reveal))))
15734 ;; Emacs 22
15735 (defadvice occur-mode-goto-occurrence
15736 (after org-occur-reveal activate)
15737 (and (org-mode-p) (org-reveal)))
15738 (defadvice occur-mode-goto-occurrence-other-window
15739 (after org-occur-reveal activate)
15740 (and (org-mode-p) (org-reveal)))
15741 (defadvice occur-mode-display-occurrence
15742 (after org-occur-reveal activate)
15743 (when (org-mode-p)
15744 (let ((pos (occur-mode-find-occurrence)))
15745 (with-current-buffer (marker-buffer pos)
15746 (save-excursion
15747 (goto-char pos)
15748 (org-reveal)))))))
15750 (defun org-occur-link-in-agenda-files ()
15751 "Create a link and search for it in the agendas.
15752 The link is not stored in `org-stored-links', it is just created
15753 for the search purpose."
15754 (interactive)
15755 (let ((link (condition-case nil
15756 (org-store-link nil)
15757 (error "Unable to create a link to here"))))
15758 (org-occur-in-agenda-files (regexp-quote link))))
15760 (defun org-uniquify (list)
15761 "Remove duplicate elements from LIST."
15762 (let (res)
15763 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
15764 res))
15766 (defun org-delete-all (elts list)
15767 "Remove all elements in ELTS from LIST."
15768 (while elts
15769 (setq list (delete (pop elts) list)))
15770 list)
15772 (defun org-back-over-empty-lines ()
15773 "Move backwards over whitespace, to the beginning of the first empty line.
15774 Returns the number of empty lines passed."
15775 (let ((pos (point)))
15776 (skip-chars-backward " \t\n\r")
15777 (beginning-of-line 2)
15778 (goto-char (min (point) pos))
15779 (count-lines (point) pos)))
15781 (defun org-skip-whitespace ()
15782 (skip-chars-forward " \t\n\r"))
15784 (defun org-point-in-group (point group &optional context)
15785 "Check if POINT is in match-group GROUP.
15786 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
15787 match. If the match group does ot exist or point is not inside it,
15788 return nil."
15789 (and (match-beginning group)
15790 (>= point (match-beginning group))
15791 (<= point (match-end group))
15792 (if context
15793 (list context (match-beginning group) (match-end group))
15794 t)))
15796 (defun org-switch-to-buffer-other-window (&rest args)
15797 "Switch to buffer in a second window on the current frame.
15798 In particular, do not allow pop-up frames."
15799 (let (pop-up-frames special-display-buffer-names special-display-regexps
15800 special-display-function)
15801 (apply 'switch-to-buffer-other-window args)))
15803 (defun org-combine-plists (&rest plists)
15804 "Create a single property list from all plists in PLISTS.
15805 The process starts by copying the first list, and then setting properties
15806 from the other lists. Settings in the last list are the most significant
15807 ones and overrule settings in the other lists."
15808 (let ((rtn (copy-sequence (pop plists)))
15809 p v ls)
15810 (while plists
15811 (setq ls (pop plists))
15812 (while ls
15813 (setq p (pop ls) v (pop ls))
15814 (setq rtn (plist-put rtn p v))))
15815 rtn))
15817 (defun org-move-line-down (arg)
15818 "Move the current line down. With prefix argument, move it past ARG lines."
15819 (interactive "p")
15820 (let ((col (current-column))
15821 beg end pos)
15822 (beginning-of-line 1) (setq beg (point))
15823 (beginning-of-line 2) (setq end (point))
15824 (beginning-of-line (+ 1 arg))
15825 (setq pos (move-marker (make-marker) (point)))
15826 (insert (delete-and-extract-region beg end))
15827 (goto-char pos)
15828 (org-move-to-column col)))
15830 (defun org-move-line-up (arg)
15831 "Move the current line up. With prefix argument, move it past ARG lines."
15832 (interactive "p")
15833 (let ((col (current-column))
15834 beg end pos)
15835 (beginning-of-line 1) (setq beg (point))
15836 (beginning-of-line 2) (setq end (point))
15837 (beginning-of-line (- arg))
15838 (setq pos (move-marker (make-marker) (point)))
15839 (insert (delete-and-extract-region beg end))
15840 (goto-char pos)
15841 (org-move-to-column col)))
15843 (defun org-replace-escapes (string table)
15844 "Replace %-escapes in STRING with values in TABLE.
15845 TABLE is an association list with keys like \"%a\" and string values.
15846 The sequences in STRING may contain normal field width and padding information,
15847 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
15848 so values can contain further %-escapes if they are define later in TABLE."
15849 (let ((case-fold-search nil)
15850 e re rpl)
15851 (while (setq e (pop table))
15852 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
15853 (while (string-match re string)
15854 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
15855 (cdr e)))
15856 (setq string (replace-match rpl t t string))))
15857 string))
15860 (defun org-sublist (list start end)
15861 "Return a section of LIST, from START to END.
15862 Counting starts at 1."
15863 (let (rtn (c start))
15864 (setq list (nthcdr (1- start) list))
15865 (while (and list (<= c end))
15866 (push (pop list) rtn)
15867 (setq c (1+ c)))
15868 (nreverse rtn)))
15870 (defun org-find-base-buffer-visiting (file)
15871 "Like `find-buffer-visiting' but always return the base buffer and
15872 not an indirect buffer."
15873 (let ((buf (or (get-file-buffer file)
15874 (find-buffer-visiting file))))
15875 (if buf
15876 (or (buffer-base-buffer buf) buf)
15877 nil)))
15879 (defun org-image-file-name-regexp (&optional extensions)
15880 "Return regexp matching the file names of images.
15881 If EXTENSIONS is given, only match these."
15882 (if (and (not extensions) (fboundp 'image-file-name-regexp))
15883 (image-file-name-regexp)
15884 (let ((image-file-name-extensions
15885 (or extensions
15886 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
15887 "xbm" "xpm" "pbm" "pgm" "ppm"))))
15888 (concat "\\."
15889 (regexp-opt (nconc (mapcar 'upcase
15890 image-file-name-extensions)
15891 image-file-name-extensions)
15893 "\\'"))))
15895 (defun org-file-image-p (file &optional extensions)
15896 "Return non-nil if FILE is an image."
15897 (save-match-data
15898 (string-match (org-image-file-name-regexp extensions) file)))
15900 (defun org-get-cursor-date ()
15901 "Return the date at cursor in as a time.
15902 This works in the calendar and in the agenda, anywhere else it just
15903 returns the current time."
15904 (let (date day defd)
15905 (cond
15906 ((eq major-mode 'calendar-mode)
15907 (setq date (calendar-cursor-to-date)
15908 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15909 ((eq major-mode 'org-agenda-mode)
15910 (setq day (get-text-property (point) 'day))
15911 (if day
15912 (setq date (calendar-gregorian-from-absolute day)
15913 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
15914 (nth 2 date))))))
15915 (or defd (current-time))))
15917 (defvar org-agenda-action-marker (make-marker)
15918 "Marker pointing to the entry for the next agenda action.")
15920 (defun org-mark-entry-for-agenda-action ()
15921 "Mark the current entry as target of an agenda action.
15922 Agenda actions are actions executed from the agenda with the key `k',
15923 which make use of the date at the cursor."
15924 (interactive)
15925 (move-marker org-agenda-action-marker
15926 (save-excursion (org-back-to-heading t) (point))
15927 (current-buffer))
15928 (message
15929 "Entry marked for action; press `k' at desired date in agenda or calendar"))
15931 ;;; Paragraph filling stuff.
15932 ;; We want this to be just right, so use the full arsenal.
15934 (defun org-indent-line-function ()
15935 "Indent line like previous, but further if previous was headline or item."
15936 (interactive)
15937 (let* ((pos (point))
15938 (itemp (org-at-item-p))
15939 (case-fold-search t)
15940 (org-drawer-regexp (or org-drawer-regexp "\000"))
15941 column bpos bcol tpos tcol bullet btype bullet-type)
15942 ;; Find the previous relevant line
15943 (beginning-of-line 1)
15944 (cond
15945 ((looking-at "#") (setq column 0))
15946 ((looking-at "\\*+ ") (setq column 0))
15947 ((and (looking-at "[ \t]*:END:")
15948 (save-excursion (re-search-backward org-drawer-regexp nil t)))
15949 (save-excursion
15950 (goto-char (1- (match-beginning 1)))
15951 (setq column (current-column))))
15952 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
15953 (save-excursion
15954 (re-search-backward
15955 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
15956 (setq column (org-get-indentation (match-string 0))))
15958 (beginning-of-line 0)
15959 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
15960 (not (looking-at "[ \t]*:END:"))
15961 (not (looking-at org-drawer-regexp)))
15962 (beginning-of-line 0))
15963 (cond
15964 ((looking-at "\\*+[ \t]+")
15965 (if (not org-adapt-indentation)
15966 (setq column 0)
15967 (goto-char (match-end 0))
15968 (setq column (current-column))))
15969 ((looking-at org-drawer-regexp)
15970 (goto-char (1- (match-beginning 1)))
15971 (setq column (current-column)))
15972 ((looking-at "\\([ \t]*\\):END:")
15973 (goto-char (match-end 1))
15974 (setq column (current-column)))
15975 ((org-in-item-p)
15976 (org-beginning-of-item)
15977 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
15978 (setq bpos (match-beginning 1) tpos (match-end 0)
15979 bcol (progn (goto-char bpos) (current-column))
15980 tcol (progn (goto-char tpos) (current-column))
15981 bullet (match-string 1)
15982 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
15983 (if (> tcol (+ bcol org-description-max-indent))
15984 (setq tcol (+ bcol 5)))
15985 (if (not itemp)
15986 (setq column tcol)
15987 (goto-char pos)
15988 (beginning-of-line 1)
15989 (if (looking-at "\\S-")
15990 (progn
15991 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
15992 (setq bullet (match-string 1)
15993 btype (if (string-match "[0-9]" bullet) "n" bullet))
15994 (setq column (if (equal btype bullet-type) bcol tcol)))
15995 (setq column (org-get-indentation)))))
15996 (t (setq column (org-get-indentation))))))
15997 (goto-char pos)
15998 (if (<= (current-column) (current-indentation))
15999 (org-indent-line-to column)
16000 (save-excursion (org-indent-line-to column)))
16001 (setq column (current-column))
16002 (beginning-of-line 1)
16003 (if (looking-at
16004 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
16005 (replace-match (concat "\\1" (format org-property-format
16006 (match-string 2) (match-string 3)))
16007 t nil))
16008 (org-move-to-column column)))
16010 (defun org-set-autofill-regexps ()
16011 (interactive)
16012 ;; In the paragraph separator we include headlines, because filling
16013 ;; text in a line directly attached to a headline would otherwise
16014 ;; fill the headline as well.
16015 (org-set-local 'comment-start-skip "^#+[ \t]*")
16016 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
16017 ;; The paragraph starter includes hand-formatted lists.
16018 (org-set-local
16019 'paragraph-start
16020 (concat
16021 "\f" "\\|"
16022 "[ ]*$" "\\|"
16023 "\\*+ " "\\|"
16024 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
16025 "[ \t]*[:|]" "\\|"
16026 "\\$\\$" "\\|"
16027 "\\\\\\(begin\\|end\\|[][]\\)"))
16028 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
16029 ;; But only if the user has not turned off tables or fixed-width regions
16030 (org-set-local
16031 'auto-fill-inhibit-regexp
16032 (concat "\\*+ \\|#\\+"
16033 "\\|[ \t]*" org-keyword-time-regexp
16034 (if (or org-enable-table-editor org-enable-fixed-width-editor)
16035 (concat
16036 "\\|[ \t]*["
16037 (if org-enable-table-editor "|" "")
16038 (if org-enable-fixed-width-editor ":" "")
16039 "]"))))
16040 ;; We use our own fill-paragraph function, to make sure that tables
16041 ;; and fixed-width regions are not wrapped. That function will pass
16042 ;; through to `fill-paragraph' when appropriate.
16043 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
16044 ; Adaptive filling: To get full control, first make sure that
16045 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
16046 (org-set-local 'adaptive-fill-regexp "\000")
16047 (org-set-local 'adaptive-fill-function
16048 'org-adaptive-fill-function)
16049 (org-set-local
16050 'align-mode-rules-list
16051 '((org-in-buffer-settings
16052 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
16053 (modes . '(org-mode))))))
16055 (defun org-fill-paragraph (&optional justify)
16056 "Re-align a table, pass through to fill-paragraph if no table."
16057 (let ((table-p (org-at-table-p))
16058 (table.el-p (org-at-table.el-p)))
16059 (cond ((and (equal (char-after (point-at-bol)) ?*)
16060 (save-excursion (goto-char (point-at-bol))
16061 (looking-at outline-regexp)))
16062 t) ; skip headlines
16063 (table.el-p t) ; skip table.el tables
16064 (table-p (org-table-align) t) ; align org-mode tables
16065 (t nil)))) ; call paragraph-fill
16067 ;; For reference, this is the default value of adaptive-fill-regexp
16068 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
16070 (defun org-adaptive-fill-function ()
16071 "Return a fill prefix for org-mode files.
16072 In particular, this makes sure hanging paragraphs for hand-formatted lists
16073 work correctly."
16074 (cond ((looking-at "#[ \t]+")
16075 (match-string 0))
16076 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
16077 (save-excursion
16078 (if (> (match-end 1) (+ (match-beginning 1)
16079 org-description-max-indent))
16080 (goto-char (+ (match-beginning 1) 5))
16081 (goto-char (match-end 0)))
16082 (make-string (current-column) ?\ )))
16083 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
16084 (save-excursion
16085 (goto-char (match-end 0))
16086 (make-string (current-column) ?\ )))
16087 (t nil)))
16089 ;;; Other stuff.
16091 (defun org-toggle-fixed-width-section (arg)
16092 "Toggle the fixed-width export.
16093 If there is no active region, the QUOTE keyword at the current headline is
16094 inserted or removed. When present, it causes the text between this headline
16095 and the next to be exported as fixed-width text, and unmodified.
16096 If there is an active region, this command adds or removes a colon as the
16097 first character of this line. If the first character of a line is a colon,
16098 this line is also exported in fixed-width font."
16099 (interactive "P")
16100 (let* ((cc 0)
16101 (regionp (org-region-active-p))
16102 (beg (if regionp (region-beginning) (point)))
16103 (end (if regionp (region-end)))
16104 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
16105 (case-fold-search nil)
16106 (re "[ \t]*\\(: \\)")
16107 off)
16108 (if regionp
16109 (save-excursion
16110 (goto-char beg)
16111 (setq cc (current-column))
16112 (beginning-of-line 1)
16113 (setq off (looking-at re))
16114 (while (> nlines 0)
16115 (setq nlines (1- nlines))
16116 (beginning-of-line 1)
16117 (cond
16118 (arg
16119 (org-move-to-column cc t)
16120 (insert ": \n")
16121 (forward-line -1))
16122 ((and off (looking-at re))
16123 (replace-match "" t t nil 1))
16124 ((not off) (org-move-to-column cc t) (insert ": ")))
16125 (forward-line 1)))
16126 (save-excursion
16127 (org-back-to-heading)
16128 (if (looking-at (concat outline-regexp
16129 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
16130 (replace-match "" t t nil 1)
16131 (if (looking-at outline-regexp)
16132 (progn
16133 (goto-char (match-end 0))
16134 (insert org-quote-string " "))))))))
16136 (defun org-reftex-citation ()
16137 "Use reftex-citation to insert a citation into the buffer.
16138 This looks for a line like
16140 #+BIBLIOGRAPHY: foo plain option:-d
16142 and derives from it that foo.bib is the bbliography file relevant
16143 for this document. It then installs the necessary environment for RefTeX
16144 to work in this buffer and calls `reftex-citation' to insert a citation
16145 into the buffer.
16147 Export of such citations to both LaTeX and HTML is handled by the contributed
16148 package org-exp-bibtex by Taru Karttunen."
16149 (interactive)
16150 (let ((reftex-docstruct-symbol 'rds)
16151 (reftex-cite-format "\\cite{%l}")
16152 rds bib)
16153 (save-excursion
16154 (save-restriction
16155 (widen)
16156 (let ((case-fold-search t)
16157 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
16158 (if (not (save-excursion
16159 (or (re-search-forward re nil t)
16160 (re-search-backward re nil t))))
16161 (error "No bibliography defined in file")
16162 (setq bib (concat (match-string 1) ".bib")
16163 rds (list (list 'bib bib)))))))
16164 (call-interactively 'reftex-citation)))
16166 ;;;; Functions extending outline functionality
16168 (defun org-beginning-of-line (&optional arg)
16169 "Go to the beginning of the current line. If that is invisible, continue
16170 to a visible line beginning. This makes the function of C-a more intuitive.
16171 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16172 first attempt, and only move to after the tags when the cursor is already
16173 beyond the end of the headline."
16174 (interactive "P")
16175 (let ((pos (point))
16176 (special (if (consp org-special-ctrl-a/e)
16177 (car org-special-ctrl-a/e)
16178 org-special-ctrl-a/e))
16179 refpos)
16180 (if (org-bound-and-true-p line-move-visual)
16181 (beginning-of-visual-line 1)
16182 (beginning-of-line 1))
16183 (if (and arg (fboundp 'move-beginning-of-line))
16184 (call-interactively 'move-beginning-of-line)
16185 (if (bobp)
16187 (backward-char 1)
16188 (if (org-invisible-p)
16189 (while (and (not (bobp)) (org-invisible-p))
16190 (backward-char 1)
16191 (beginning-of-line 1))
16192 (forward-char 1))))
16193 (when special
16194 (cond
16195 ((and (looking-at org-complex-heading-regexp)
16196 (= (char-after (match-end 1)) ?\ ))
16197 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
16198 (point-at-eol)))
16199 (goto-char
16200 (if (eq special t)
16201 (cond ((> pos refpos) refpos)
16202 ((= pos (point)) refpos)
16203 (t (point)))
16204 (cond ((> pos (point)) (point))
16205 ((not (eq last-command this-command)) (point))
16206 (t refpos)))))
16207 ((org-at-item-p)
16208 (goto-char
16209 (if (eq special t)
16210 (cond ((> pos (match-end 4)) (match-end 4))
16211 ((= pos (point)) (match-end 4))
16212 (t (point)))
16213 (cond ((> pos (point)) (point))
16214 ((not (eq last-command this-command)) (point))
16215 (t (match-end 4))))))))
16216 (org-no-warnings
16217 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16219 (defun org-end-of-line (&optional arg)
16220 "Go to the end of the line.
16221 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16222 first attempt, and only move to after the tags when the cursor is already
16223 beyond the end of the headline."
16224 (interactive "P")
16225 (let ((special (if (consp org-special-ctrl-a/e)
16226 (cdr org-special-ctrl-a/e)
16227 org-special-ctrl-a/e)))
16228 (if (or (not special)
16229 (not (org-on-heading-p))
16230 arg)
16231 (call-interactively
16232 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
16233 ((fboundp 'move-end-of-line) 'move-end-of-line)
16234 (t 'end-of-line)))
16235 (let ((pos (point)))
16236 (beginning-of-line 1)
16237 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
16238 (if (eq special t)
16239 (if (or (< pos (match-beginning 1))
16240 (= pos (match-end 0)))
16241 (goto-char (match-beginning 1))
16242 (goto-char (match-end 0)))
16243 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
16244 (goto-char (match-end 0))
16245 (goto-char (match-beginning 1))))
16246 (call-interactively (if (fboundp 'move-end-of-line)
16247 'move-end-of-line
16248 'end-of-line)))))
16249 (org-no-warnings
16250 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16252 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
16253 (define-key org-mode-map "\C-e" 'org-end-of-line)
16255 (defun org-backward-sentence (&optional arg)
16256 "Go to beginning of sentence, or beginning of table field.
16257 This will call `backward-sentence' or `org-table-beginning-of-field',
16258 depending on context."
16259 (interactive "P")
16260 (cond
16261 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
16262 (t (call-interactively 'backward-sentence))))
16264 (defun org-forward-sentence (&optional arg)
16265 "Go to end of sentence, or end of table field.
16266 This will call `forward-sentence' or `org-table-end-of-field',
16267 depending on context."
16268 (interactive "P")
16269 (cond
16270 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
16271 (t (call-interactively 'forward-sentence))))
16273 (define-key org-mode-map "\M-a" 'org-backward-sentence)
16274 (define-key org-mode-map "\M-e" 'org-forward-sentence)
16276 (defun org-kill-line (&optional arg)
16277 "Kill line, to tags or end of line."
16278 (interactive "P")
16279 (cond
16280 ((or (not org-special-ctrl-k)
16281 (bolp)
16282 (not (org-on-heading-p)))
16283 (call-interactively 'kill-line))
16284 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
16285 (kill-region (point) (match-beginning 1))
16286 (org-set-tags nil t))
16287 (t (kill-region (point) (point-at-eol)))))
16289 (define-key org-mode-map "\C-k" 'org-kill-line)
16291 (defun org-yank (&optional arg)
16292 "Yank. If the kill is a subtree, treat it specially.
16293 This command will look at the current kill and check if is a single
16294 subtree, or a series of subtrees[1]. If it passes the test, and if the
16295 cursor is at the beginning of a line or after the stars of a currently
16296 empty headline, then the yank is handled specially. How exactly depends
16297 on the value of the following variables, both set by default.
16299 org-yank-folded-subtrees
16300 When set, the subtree(s) will be folded after insertion, but only
16301 if doing so would now swallow text after the yanked text.
16303 org-yank-adjusted-subtrees
16304 When set, the subtree will be promoted or demoted in order to
16305 fit into the local outline tree structure, which means that the level
16306 will be adjusted so that it becomes the smaller one of the two
16307 *visible* surrounding headings.
16309 Any prefix to this command will cause `yank' to be called directly with
16310 no special treatment. In particular, a simple `C-u' prefix will just
16311 plainly yank the text as it is.
16313 \[1] The test checks if the first non-white line is a heading
16314 and if there are no other headings with fewer stars."
16315 (interactive "P")
16316 (org-yank-generic 'yank arg))
16318 (defun org-yank-generic (command arg)
16319 "Perform some yank-like command.
16321 This function implements the behavior described in the `org-yank'
16322 documentation. However, it has been generalized to work for any
16323 interactive command with similar behavior."
16325 ;; pretend to be command COMMAND
16326 (setq this-command command)
16328 (if arg
16329 (call-interactively command)
16331 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
16332 (and (org-kill-is-subtree-p)
16333 (or (bolp)
16334 (and (looking-at "[ \t]*$")
16335 (string-match
16336 "\\`\\*+\\'"
16337 (buffer-substring (point-at-bol) (point)))))))
16338 swallowp)
16339 (cond
16340 ((and subtreep org-yank-folded-subtrees)
16341 (let ((beg (point))
16342 end)
16343 (if (and subtreep org-yank-adjusted-subtrees)
16344 (org-paste-subtree nil nil 'for-yank)
16345 (call-interactively command))
16347 (setq end (point))
16348 (goto-char beg)
16349 (when (and (bolp) subtreep
16350 (not (setq swallowp
16351 (org-yank-folding-would-swallow-text beg end))))
16352 (or (looking-at outline-regexp)
16353 (re-search-forward (concat "^" outline-regexp) end t))
16354 (while (and (< (point) end) (looking-at outline-regexp))
16355 (hide-subtree)
16356 (org-cycle-show-empty-lines 'folded)
16357 (condition-case nil
16358 (outline-forward-same-level 1)
16359 (error (goto-char end)))))
16360 (when swallowp
16361 (message
16362 "Inserted text not folded because that would swallow text"))
16364 (goto-char end)
16365 (skip-chars-forward " \t\n\r")
16366 (beginning-of-line 1)
16367 (push-mark beg 'nomsg)))
16368 ((and subtreep org-yank-adjusted-subtrees)
16369 (let ((beg (point-at-bol)))
16370 (org-paste-subtree nil nil 'for-yank)
16371 (push-mark beg 'nomsg)))
16373 (call-interactively command))))))
16375 (defun org-yank-folding-would-swallow-text (beg end)
16376 "Would hide-subtree at BEG swallow any text after END?"
16377 (let (level)
16378 (save-excursion
16379 (goto-char beg)
16380 (when (or (looking-at outline-regexp)
16381 (re-search-forward (concat "^" outline-regexp) end t))
16382 (setq level (org-outline-level)))
16383 (goto-char end)
16384 (skip-chars-forward " \t\r\n\v\f")
16385 (if (or (eobp)
16386 (and (bolp) (looking-at org-outline-regexp)
16387 (<= (org-outline-level) level)))
16388 nil ; Nothing would be swallowed
16389 t)))) ; something would swallow
16391 (define-key org-mode-map "\C-y" 'org-yank)
16393 (defun org-invisible-p ()
16394 "Check if point is at a character currently not visible."
16395 ;; Early versions of noutline don't have `outline-invisible-p'.
16396 (if (fboundp 'outline-invisible-p)
16397 (outline-invisible-p)
16398 (get-char-property (point) 'invisible)))
16400 (defun org-invisible-p2 ()
16401 "Check if point is at a character currently not visible."
16402 (save-excursion
16403 (if (and (eolp) (not (bobp))) (backward-char 1))
16404 ;; Early versions of noutline don't have `outline-invisible-p'.
16405 (if (fboundp 'outline-invisible-p)
16406 (outline-invisible-p)
16407 (get-char-property (point) 'invisible))))
16409 (defun org-back-to-heading (&optional invisible-ok)
16410 "Call `outline-back-to-heading', but provide a better error message."
16411 (condition-case nil
16412 (outline-back-to-heading invisible-ok)
16413 (error (error "Before first headline at position %d in buffer %s"
16414 (point) (current-buffer)))))
16416 (defun org-before-first-heading-p ()
16417 "Before first heading?"
16418 (save-excursion
16419 (null (re-search-backward "^\\*+ " nil t))))
16421 (defalias 'org-on-heading-p 'outline-on-heading-p)
16422 (defalias 'org-at-heading-p 'outline-on-heading-p)
16423 (defun org-at-heading-or-item-p ()
16424 (or (org-on-heading-p) (org-at-item-p)))
16426 (defun org-on-target-p ()
16427 (or (org-in-regexp org-radio-target-regexp)
16428 (org-in-regexp org-target-regexp)))
16430 (defun org-up-heading-all (arg)
16431 "Move to the heading line of which the present line is a subheading.
16432 This function considers both visible and invisible heading lines.
16433 With argument, move up ARG levels."
16434 (if (fboundp 'outline-up-heading-all)
16435 (outline-up-heading-all arg) ; emacs 21 version of outline.el
16436 (outline-up-heading arg t))) ; emacs 22 version of outline.el
16438 (defun org-up-heading-safe ()
16439 "Move to the heading line of which the present line is a subheading.
16440 This version will not throw an error. It will return the level of the
16441 headline found, or nil if no higher level is found.
16443 Also, this function will be a lot faster than `outline-up-heading',
16444 because it relies on stars being the outline starters. This can really
16445 make a significant difference in outlines with very many siblings."
16446 (let (start-level re)
16447 (org-back-to-heading t)
16448 (setq start-level (funcall outline-level))
16449 (if (equal start-level 1)
16451 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
16452 (if (re-search-backward re nil t)
16453 (funcall outline-level)))))
16455 (defun org-first-sibling-p ()
16456 "Is this heading the first child of its parents?"
16457 (interactive)
16458 (let ((re (concat "^" outline-regexp))
16459 level l)
16460 (unless (org-at-heading-p t)
16461 (error "Not at a heading"))
16462 (setq level (funcall outline-level))
16463 (save-excursion
16464 (if (not (re-search-backward re nil t))
16466 (setq l (funcall outline-level))
16467 (< l level)))))
16469 (defun org-goto-sibling (&optional previous)
16470 "Goto the next sibling, even if it is invisible.
16471 When PREVIOUS is set, go to the previous sibling instead. Returns t
16472 when a sibling was found. When none is found, return nil and don't
16473 move point."
16474 (let ((fun (if previous 're-search-backward 're-search-forward))
16475 (pos (point))
16476 (re (concat "^" outline-regexp))
16477 level l)
16478 (when (condition-case nil (org-back-to-heading t) (error nil))
16479 (setq level (funcall outline-level))
16480 (catch 'exit
16481 (or previous (forward-char 1))
16482 (while (funcall fun re nil t)
16483 (setq l (funcall outline-level))
16484 (when (< l level) (goto-char pos) (throw 'exit nil))
16485 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
16486 (goto-char pos)
16487 nil))))
16489 (defun org-show-siblings ()
16490 "Show all siblings of the current headline."
16491 (save-excursion
16492 (while (org-goto-sibling) (org-flag-heading nil)))
16493 (save-excursion
16494 (while (org-goto-sibling 'previous)
16495 (org-flag-heading nil))))
16497 (defun org-show-hidden-entry ()
16498 "Show an entry where even the heading is hidden."
16499 (save-excursion
16500 (org-show-entry)))
16502 (defun org-flag-heading (flag &optional entry)
16503 "Flag the current heading. FLAG non-nil means make invisible.
16504 When ENTRY is non-nil, show the entire entry."
16505 (save-excursion
16506 (org-back-to-heading t)
16507 ;; Check if we should show the entire entry
16508 (if entry
16509 (progn
16510 (org-show-entry)
16511 (save-excursion
16512 (and (outline-next-heading)
16513 (org-flag-heading nil))))
16514 (outline-flag-region (max (point-min) (1- (point)))
16515 (save-excursion (outline-end-of-heading) (point))
16516 flag))))
16518 (defun org-get-next-sibling ()
16519 "Move to next heading of the same level, and return point.
16520 If there is no such heading, return nil.
16521 This is like outline-next-sibling, but invisible headings are ok."
16522 (let ((level (funcall outline-level)))
16523 (outline-next-heading)
16524 (while (and (not (eobp)) (> (funcall outline-level) level))
16525 (outline-next-heading))
16526 (if (or (eobp) (< (funcall outline-level) level))
16528 (point))))
16530 (defun org-end-of-subtree (&optional invisible-OK to-heading)
16531 ;; This contains an exact copy of the original function, but it uses
16532 ;; `org-back-to-heading', to make it work also in invisible
16533 ;; trees. And is uses an invisible-OK argument.
16534 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
16535 ;; Furthermore, when used inside Org, finding the end of a large subtree
16536 ;; with many children and grandchildren etc, this can be much faster
16537 ;; than the outline version.
16538 (org-back-to-heading invisible-OK)
16539 (let ((first t)
16540 (level (funcall outline-level)))
16541 (if (and (org-mode-p) (< level 1000))
16542 ;; A true heading (not a plain list item), in Org-mode
16543 ;; This means we can easily find the end by looking
16544 ;; only for the right number of stars. Using a regexp to do
16545 ;; this is so much faster than using a Lisp loop.
16546 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
16547 (forward-char 1)
16548 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
16549 ;; something else, do it the slow way
16550 (while (and (not (eobp))
16551 (or first (> (funcall outline-level) level)))
16552 (setq first nil)
16553 (outline-next-heading)))
16554 (unless to-heading
16555 (if (memq (preceding-char) '(?\n ?\^M))
16556 (progn
16557 ;; Go to end of line before heading
16558 (forward-char -1)
16559 (if (memq (preceding-char) '(?\n ?\^M))
16560 ;; leave blank line before heading
16561 (forward-char -1))))))
16562 (point))
16564 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
16565 "Use Org version in org-mode, for dramatic speed-up."
16566 (if (eq major-mode 'org-mode)
16567 (progn
16568 (org-end-of-subtree nil t)
16569 (backward-char 1))
16570 ad-do-it))
16572 (defun org-forward-same-level (arg &optional invisible-ok)
16573 "Move forward to the arg'th subheading at same level as this one.
16574 Stop at the first and last subheadings of a superior heading."
16575 (interactive "p")
16576 (org-back-to-heading)
16577 (org-on-heading-p)
16578 (let* ((level (- (match-end 0) (match-beginning 0) 1))
16579 (re (format "^\\*\\{1,%d\\} " level))
16581 (forward-char 1)
16582 (while (> arg 0)
16583 (while (and (re-search-forward re nil 'move)
16584 (setq l (- (match-end 0) (match-beginning 0) 1))
16585 (= l level)
16586 (not invisible-ok)
16587 (org-invisible-p))
16588 (if (< l level) (setq arg 1)))
16589 (setq arg (1- arg)))
16590 (beginning-of-line 1)))
16592 (defun org-backward-same-level (arg &optional invisible-ok)
16593 "Move backward to the arg'th subheading at same level as this one.
16594 Stop at the first and last subheadings of a superior heading."
16595 (interactive "p")
16596 (org-back-to-heading)
16597 (org-on-heading-p)
16598 (let* ((level (- (match-end 0) (match-beginning 0) 1))
16599 (re (format "^\\*\\{1,%d\\} " level))
16601 (while (> arg 0)
16602 (while (and (re-search-backward re nil 'move)
16603 (setq l (- (match-end 0) (match-beginning 0) 1))
16604 (= l level)
16605 (not invisible-ok)
16606 (org-invisible-p))
16607 (if (< l level) (setq arg 1)))
16608 (setq arg (1- arg)))))
16610 (defun org-show-subtree ()
16611 "Show everything after this heading at deeper levels."
16612 (outline-flag-region
16613 (point)
16614 (save-excursion
16615 (outline-end-of-subtree) (outline-next-heading) (point))
16616 nil))
16618 (defun org-show-entry ()
16619 "Show the body directly following this heading.
16620 Show the heading too, if it is currently invisible."
16621 (interactive)
16622 (save-excursion
16623 (condition-case nil
16624 (progn
16625 (org-back-to-heading t)
16626 (outline-flag-region
16627 (max (point-min) (1- (point)))
16628 (save-excursion
16629 (if (re-search-forward
16630 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
16631 (match-beginning 1)
16632 (point-max)))
16633 nil)
16634 (org-cycle-hide-drawers 'children))
16635 (error nil))))
16637 (defun org-make-options-regexp (kwds &optional extra)
16638 "Make a regular expression for keyword lines."
16639 (concat
16641 "#?[ \t]*\\+\\("
16642 (mapconcat 'regexp-quote kwds "\\|")
16643 (if extra (concat "\\|" extra))
16644 "\\):[ \t]*"
16645 "\\(.*\\)"))
16647 ;; Make isearch reveal the necessary context
16648 (defun org-isearch-end ()
16649 "Reveal context after isearch exits."
16650 (when isearch-success ; only if search was successful
16651 (if (featurep 'xemacs)
16652 ;; Under XEmacs, the hook is run in the correct place,
16653 ;; we directly show the context.
16654 (org-show-context 'isearch)
16655 ;; In Emacs the hook runs *before* restoring the overlays.
16656 ;; So we have to use a one-time post-command-hook to do this.
16657 ;; (Emacs 22 has a special variable, see function `org-mode')
16658 (unless (and (boundp 'isearch-mode-end-hook-quit)
16659 isearch-mode-end-hook-quit)
16660 ;; Only when the isearch was not quitted.
16661 (org-add-hook 'post-command-hook 'org-isearch-post-command
16662 'append 'local)))))
16664 (defun org-isearch-post-command ()
16665 "Remove self from hook, and show context."
16666 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
16667 (org-show-context 'isearch))
16670 ;;;; Integration with and fixes for other packages
16672 ;;; Imenu support
16674 (defvar org-imenu-markers nil
16675 "All markers currently used by Imenu.")
16676 (make-variable-buffer-local 'org-imenu-markers)
16678 (defun org-imenu-new-marker (&optional pos)
16679 "Return a new marker for use by Imenu, and remember the marker."
16680 (let ((m (make-marker)))
16681 (move-marker m (or pos (point)))
16682 (push m org-imenu-markers)
16685 (defun org-imenu-get-tree ()
16686 "Produce the index for Imenu."
16687 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
16688 (setq org-imenu-markers nil)
16689 (let* ((n org-imenu-depth)
16690 (re (concat "^" outline-regexp))
16691 (subs (make-vector (1+ n) nil))
16692 (last-level 0)
16693 m level head)
16694 (save-excursion
16695 (save-restriction
16696 (widen)
16697 (goto-char (point-max))
16698 (while (re-search-backward re nil t)
16699 (setq level (org-reduced-level (funcall outline-level)))
16700 (when (<= level n)
16701 (looking-at org-complex-heading-regexp)
16702 (setq head (org-link-display-format
16703 (org-match-string-no-properties 4))
16704 m (org-imenu-new-marker))
16705 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
16706 (if (>= level last-level)
16707 (push (cons head m) (aref subs level))
16708 (push (cons head (aref subs (1+ level))) (aref subs level))
16709 (loop for i from (1+ level) to n do (aset subs i nil)))
16710 (setq last-level level)))))
16711 (aref subs 1)))
16713 (eval-after-load "imenu"
16714 '(progn
16715 (add-hook 'imenu-after-jump-hook
16716 (lambda ()
16717 (if (eq major-mode 'org-mode)
16718 (org-show-context 'org-goto))))))
16720 (defun org-link-display-format (link)
16721 "Replace a link with either the description, or the link target
16722 if no description is present"
16723 (save-match-data
16724 (if (string-match org-bracket-link-analytic-regexp link)
16725 (replace-match (or (match-string 5 link)
16726 (concat (match-string 1 link)
16727 (match-string 3 link)))
16728 nil nil link)
16729 link)))
16731 ;; Speedbar support
16733 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
16734 "Overlay marking the agenda restriction line in speedbar.")
16735 (org-overlay-put org-speedbar-restriction-lock-overlay
16736 'face 'org-agenda-restriction-lock)
16737 (org-overlay-put org-speedbar-restriction-lock-overlay
16738 'help-echo "Agendas are currently limited to this item.")
16739 (org-detach-overlay org-speedbar-restriction-lock-overlay)
16741 (defun org-speedbar-set-agenda-restriction ()
16742 "Restrict future agenda commands to the location at point in speedbar.
16743 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
16744 (interactive)
16745 (require 'org-agenda)
16746 (let (p m tp np dir txt)
16747 (cond
16748 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16749 'org-imenu t))
16750 (setq m (get-text-property p 'org-imenu-marker))
16751 (save-excursion
16752 (save-restriction
16753 (set-buffer (marker-buffer m))
16754 (goto-char m)
16755 (org-agenda-set-restriction-lock 'subtree))))
16756 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16757 'speedbar-function 'speedbar-find-file))
16758 (setq tp (previous-single-property-change
16759 (1+ p) 'speedbar-function)
16760 np (next-single-property-change
16761 tp 'speedbar-function)
16762 dir (speedbar-line-directory)
16763 txt (buffer-substring-no-properties (or tp (point-min))
16764 (or np (point-max))))
16765 (save-excursion
16766 (save-restriction
16767 (set-buffer (find-file-noselect
16768 (let ((default-directory dir))
16769 (expand-file-name txt))))
16770 (unless (org-mode-p)
16771 (error "Cannot restrict to non-Org-mode file"))
16772 (org-agenda-set-restriction-lock 'file))))
16773 (t (error "Don't know how to restrict Org-mode's agenda")))
16774 (org-move-overlay org-speedbar-restriction-lock-overlay
16775 (point-at-bol) (point-at-eol))
16776 (setq current-prefix-arg nil)
16777 (org-agenda-maybe-redo)))
16779 (eval-after-load "speedbar"
16780 '(progn
16781 (speedbar-add-supported-extension ".org")
16782 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
16783 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
16784 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
16785 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16786 (add-hook 'speedbar-visiting-tag-hook
16787 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
16790 ;;; Fixes and Hacks for problems with other packages
16792 ;; Make flyspell not check words in links, to not mess up our keymap
16793 (defun org-mode-flyspell-verify ()
16794 "Don't let flyspell put overlays at active buttons."
16795 (and (not (get-text-property (point) 'keymap))
16796 (not (get-text-property (point) 'org-no-flyspell))))
16798 (defun org-remove-flyspell-overlays-in (beg end)
16799 "Remove flyspell overlays in region."
16800 (and (org-bound-and-true-p flyspell-mode)
16801 (fboundp 'flyspell-delete-region-overlays)
16802 (flyspell-delete-region-overlays beg end))
16803 (add-text-properties beg end '(org-no-flyspell t)))
16805 ;; Make `bookmark-jump' show the jump location if it was hidden.
16806 (eval-after-load "bookmark"
16807 '(if (boundp 'bookmark-after-jump-hook)
16808 ;; We can use the hook
16809 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
16810 ;; Hook not available, use advice
16811 (defadvice bookmark-jump (after org-make-visible activate)
16812 "Make the position visible."
16813 (org-bookmark-jump-unhide))))
16815 ;; Make sure saveplace show the location if it was hidden
16816 (eval-after-load "saveplace"
16817 '(defadvice save-place-find-file-hook (after org-make-visible activate)
16818 "Make the position visible."
16819 (org-bookmark-jump-unhide)))
16821 (defun org-bookmark-jump-unhide ()
16822 "Unhide the current position, to show the bookmark location."
16823 (and (org-mode-p)
16824 (or (org-invisible-p)
16825 (save-excursion (goto-char (max (point-min) (1- (point))))
16826 (org-invisible-p)))
16827 (org-show-context 'bookmark-jump)))
16829 ;; Make session.el ignore our circular variable
16830 (eval-after-load "session"
16831 '(add-to-list 'session-globals-exclude 'org-mark-ring))
16833 ;;;; Experimental code
16835 (defun org-closed-in-range ()
16836 "Sparse tree of items closed in a certain time range.
16837 Still experimental, may disappear in the future."
16838 (interactive)
16839 ;; Get the time interval from the user.
16840 (let* ((time1 (time-to-seconds
16841 (org-read-date nil 'to-time nil "Starting date: ")))
16842 (time2 (time-to-seconds
16843 (org-read-date nil 'to-time nil "End date:")))
16844 ;; callback function
16845 (callback (lambda ()
16846 (let ((time
16847 (time-to-seconds
16848 (apply 'encode-time
16849 (org-parse-time-string
16850 (match-string 1))))))
16851 ;; check if time in interval
16852 (and (>= time time1) (<= time time2))))))
16853 ;; make tree, check each match with the callback
16854 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
16856 ;;;; Finish up
16858 (provide 'org)
16860 (run-hooks 'org-load-hook)
16862 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
16864 ;;; org.el ends here