Cycling: Fix bug
[org-mode/org-tableheadings.git] / lisp / org.el
blob84be9fa1ff4318876166574e11a30d85c825e7bf
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 ((and (eq last-command this-command)
5002 (or children-skipped
5003 (eq org-cycle-subtree-status 'children)))
5004 ;; We just showed the children, now show everything.
5005 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5006 (org-show-subtree)
5007 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5008 (setq org-cycle-subtree-status 'subtree)
5009 (run-hook-with-args 'org-cycle-hook 'subtree))
5011 ;; Default action: hide the subtree.
5012 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5013 (hide-subtree)
5014 (message "FOLDED")
5015 (setq org-cycle-subtree-status 'folded)
5016 (run-hook-with-args 'org-cycle-hook 'folded)))))
5018 ;;;###autoload
5019 (defun org-global-cycle (&optional arg)
5020 "Cycle the global visibility. For details see `org-cycle'.
5021 With C-u prefix arg, switch to startup visibility.
5022 With a numeric prefix, show all headlines up to that level."
5023 (interactive "P")
5024 (let ((org-cycle-include-plain-lists
5025 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5026 (cond
5027 ((integerp arg)
5028 (show-all)
5029 (hide-sublevels arg)
5030 (setq org-cycle-global-status 'contents))
5031 ((equal arg '(4))
5032 (org-set-startup-visibility)
5033 (message "Startup visibility, plus VISIBILITY properties."))
5035 (org-cycle '(4))))))
5037 (defun org-set-startup-visibility ()
5038 "Set the visibility required by startup options and properties."
5039 (cond
5040 ((eq org-startup-folded t)
5041 (org-cycle '(4)))
5042 ((eq org-startup-folded 'content)
5043 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5044 (org-cycle '(4)) (org-cycle '(4)))))
5045 (if org-hide-block-startup (org-hide-block-all))
5046 (org-set-visibility-according-to-property 'no-cleanup)
5047 (org-cycle-hide-archived-subtrees 'all)
5048 (org-cycle-hide-drawers 'all)
5049 (org-cycle-show-empty-lines 'all))
5051 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5052 "Switch subtree visibilities according to :VISIBILITY: property."
5053 (interactive)
5054 (let (org-show-entry-below state)
5055 (save-excursion
5056 (goto-char (point-min))
5057 (while (re-search-forward
5058 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5059 nil t)
5060 (setq state (match-string 1))
5061 (save-excursion
5062 (org-back-to-heading t)
5063 (hide-subtree)
5064 (org-reveal)
5065 (cond
5066 ((equal state '("fold" "folded"))
5067 (hide-subtree))
5068 ((equal state "children")
5069 (org-show-hidden-entry)
5070 (show-children))
5071 ((equal state "content")
5072 (save-excursion
5073 (save-restriction
5074 (org-narrow-to-subtree)
5075 (org-content))))
5076 ((member state '("all" "showall"))
5077 (show-subtree)))))
5078 (unless no-cleanup
5079 (org-cycle-hide-archived-subtrees 'all)
5080 (org-cycle-hide-drawers 'all)
5081 (org-cycle-show-empty-lines 'all)))))
5083 (defun org-overview ()
5084 "Switch to overview mode, showing only top-level headlines.
5085 Really, this shows all headlines with level equal or greater than the level
5086 of the first headline in the buffer. This is important, because if the
5087 first headline is not level one, then (hide-sublevels 1) gives confusing
5088 results."
5089 (interactive)
5090 (let ((level (save-excursion
5091 (goto-char (point-min))
5092 (if (re-search-forward (concat "^" outline-regexp) nil t)
5093 (progn
5094 (goto-char (match-beginning 0))
5095 (funcall outline-level))))))
5096 (and level (hide-sublevels level))))
5098 (defun org-content (&optional arg)
5099 "Show all headlines in the buffer, like a table of contents.
5100 With numerical argument N, show content up to level N."
5101 (interactive "P")
5102 (save-excursion
5103 ;; Visit all headings and show their offspring
5104 (and (integerp arg) (org-overview))
5105 (goto-char (point-max))
5106 (catch 'exit
5107 (while (and (progn (condition-case nil
5108 (outline-previous-visible-heading 1)
5109 (error (goto-char (point-min))))
5111 (looking-at outline-regexp))
5112 (if (integerp arg)
5113 (show-children (1- arg))
5114 (show-branches))
5115 (if (bobp) (throw 'exit nil))))))
5118 (defun org-optimize-window-after-visibility-change (state)
5119 "Adjust the window after a change in outline visibility.
5120 This function is the default value of the hook `org-cycle-hook'."
5121 (when (get-buffer-window (current-buffer))
5122 (cond
5123 ((eq state 'content) nil)
5124 ((eq state 'all) nil)
5125 ((eq state 'folded) nil)
5126 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5127 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5129 ;; FIXME: no longer in use
5130 (defun org-compact-display-after-subtree-move ()
5131 "Show a compacter version of the tree of the entry's parent."
5132 (save-excursion
5133 (if (org-up-heading-safe)
5134 (progn
5135 (hide-subtree)
5136 (show-entry)
5137 (show-children)
5138 (org-cycle-show-empty-lines 'children)
5139 (org-cycle-hide-drawers 'children))
5140 (org-overview))))
5142 (defun org-remove-empty-overlays-at (pos)
5143 "Remove outline overlays that do not contain non-white stuff."
5144 (mapc
5145 (lambda (o)
5146 (and (eq 'outline (org-overlay-get o 'invisible))
5147 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5148 (org-overlay-end o))))
5149 (org-delete-overlay o)))
5150 (org-overlays-at pos)))
5152 (defun org-clean-visibility-after-subtree-move ()
5153 "Fix visibility issues after moving a subtree."
5154 ;; First, find a reasonable region to look at:
5155 ;; Start two siblings above, end three below
5156 (let* ((beg (save-excursion
5157 (and (outline-get-last-sibling)
5158 (outline-get-last-sibling))
5159 (point)))
5160 (end (save-excursion
5161 (and (outline-get-next-sibling)
5162 (outline-get-next-sibling)
5163 (outline-get-next-sibling))
5164 (if (org-at-heading-p)
5165 (point-at-eol)
5166 (point))))
5167 (level (looking-at "\\*+"))
5168 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5169 (save-excursion
5170 (save-restriction
5171 (narrow-to-region beg end)
5172 (when re
5173 ;; Properly fold already folded siblings
5174 (goto-char (point-min))
5175 (while (re-search-forward re nil t)
5176 (if (save-excursion (goto-char (point-at-eol)) (org-invisible-p))
5177 (hide-entry))))
5178 (org-cycle-show-empty-lines 'overview)
5179 (org-cycle-hide-drawers 'overview)))))
5181 (defun org-cycle-show-empty-lines (state)
5182 "Show empty lines above all visible headlines.
5183 The region to be covered depends on STATE when called through
5184 `org-cycle-hook'. Lisp program can use t for STATE to get the
5185 entire buffer covered. Note that an empty line is only shown if there
5186 are at least `org-cycle-separator-lines' empty lines before the headline."
5187 (when (> org-cycle-separator-lines 0)
5188 (save-excursion
5189 (let* ((n org-cycle-separator-lines)
5190 (re (cond
5191 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5192 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5193 (t (let ((ns (number-to-string (- n 2))))
5194 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5195 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5196 beg end)
5197 (cond
5198 ((memq state '(overview contents t))
5199 (setq beg (point-min) end (point-max)))
5200 ((memq state '(children folded))
5201 (setq beg (point) end (progn (org-end-of-subtree t t)
5202 (beginning-of-line 2)
5203 (point)))))
5204 (when beg
5205 (goto-char beg)
5206 (while (re-search-forward re end t)
5207 (if (not (get-char-property (match-end 1) 'invisible))
5208 (outline-flag-region
5209 (match-beginning 1) (match-end 1) nil)))))))
5210 ;; Never hide empty lines at the end of the file.
5211 (save-excursion
5212 (goto-char (point-max))
5213 (outline-previous-heading)
5214 (outline-end-of-heading)
5215 (if (and (looking-at "[ \t\n]+")
5216 (= (match-end 0) (point-max)))
5217 (outline-flag-region (point) (match-end 0) nil))))
5219 (defun org-show-empty-lines-in-parent ()
5220 "Move to the parent and re-show empty lines before visible headlines."
5221 (save-excursion
5222 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5223 (org-cycle-show-empty-lines context))))
5225 (defun org-cycle-hide-drawers (state)
5226 "Re-hide all drawers after a visibility state change."
5227 (when (and (org-mode-p)
5228 (not (memq state '(overview folded contents))))
5229 (save-excursion
5230 (let* ((globalp (memq state '(contents all)))
5231 (beg (if globalp (point-min) (point)))
5232 (end (if globalp (point-max)
5233 (if (eq state 'children)
5234 (save-excursion (outline-next-heading) (point))
5235 (org-end-of-subtree t)))))
5236 (goto-char beg)
5237 (while (re-search-forward org-drawer-regexp end t)
5238 (org-flag-drawer t))))))
5240 (defun org-flag-drawer (flag)
5241 (save-excursion
5242 (beginning-of-line 1)
5243 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5244 (let ((b (match-end 0))
5245 (outline-regexp org-outline-regexp))
5246 (if (re-search-forward
5247 "^[ \t]*:END:"
5248 (save-excursion (outline-next-heading) (point)) t)
5249 (outline-flag-region b (point-at-eol) flag)
5250 (error ":END: line missing"))))))
5252 (defun org-subtree-end-visible-p ()
5253 "Is the end of the current subtree visible?"
5254 (pos-visible-in-window-p
5255 (save-excursion (org-end-of-subtree t) (point))))
5257 (defun org-first-headline-recenter (&optional N)
5258 "Move cursor to the first headline and recenter the headline.
5259 Optional argument N means, put the headline into the Nth line of the window."
5260 (goto-char (point-min))
5261 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5262 (beginning-of-line)
5263 (recenter (prefix-numeric-value N))))
5265 ;;; Folding of blocks
5267 (defconst org-block-regexp
5269 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5270 "Regular expression for hiding blocks.")
5272 (defvar org-hide-block-overlays nil
5273 "Overays hiding blocks.")
5274 (make-variable-buffer-local 'org-hide-block-overlays)
5276 (defun org-block-map (function &optional start end)
5277 "Call func at the head of all source blocks in the current
5278 buffer. Optional arguments START and END can be used to limit
5279 the range."
5280 (let ((start (or start (point-min)))
5281 (end (or end (point-max))))
5282 (save-excursion
5283 (goto-char start)
5284 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5285 (save-excursion
5286 (save-match-data
5287 (goto-char (match-beginning 0))
5288 (funcall function)))))))
5290 (defun org-hide-block-toggle-all ()
5291 "Toggle the visibility of all blocks in the current buffer."
5292 (org-block-map #'org-hide-block-toggle))
5294 (defun org-hide-block-all ()
5295 "Fold all blocks in the current buffer."
5296 (interactive)
5297 (org-show-block-all)
5298 (org-block-map #'org-hide-block-toggle-maybe))
5300 (defun org-show-block-all ()
5301 "Unfold all blocks in the current buffer."
5302 (mapc 'org-delete-overlay org-hide-block-overlays)
5303 (setq org-hide-block-overlays nil))
5305 (defun org-hide-block-toggle-maybe ()
5306 "Toggle visibility of block at point."
5307 (interactive)
5308 (let ((case-fold-search t))
5309 (if (save-excursion
5310 (beginning-of-line 1)
5311 (looking-at org-block-regexp))
5312 (progn (org-hide-block-toggle)
5313 t) ;; to signal that we took action
5314 nil))) ;; to signal that we did not
5316 (defun org-hide-block-toggle (&optional force)
5317 "Toggle the visibility of the current block."
5318 (interactive)
5319 (save-excursion
5320 (beginning-of-line)
5321 (if (re-search-forward org-block-regexp nil t)
5322 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5323 (end (match-end 0))
5324 ov) ;; end of entire body
5325 (if (memq t (mapcar (lambda (overlay)
5326 (eq (org-overlay-get overlay 'invisible)
5327 'org-hide-block))
5328 (org-overlays-at start)))
5329 (if (or (not force) (eq force 'off))
5330 (mapc (lambda (ov)
5331 (when (member ov org-hide-block-overlays)
5332 (setq org-hide-block-overlays
5333 (delq ov org-hide-block-overlays)))
5334 (when (eq (org-overlay-get ov 'invisible)
5335 'org-hide-block)
5336 (org-delete-overlay ov)))
5337 (org-overlays-at start)))
5338 (setq ov (org-make-overlay start end))
5339 (org-overlay-put ov 'invisible 'org-hide-block)
5340 (push ov org-hide-block-overlays)))
5341 (error "Not looking at a source block"))))
5343 ;; org-tab-after-check-for-cycling-hook
5344 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5345 ;; Remove overlays when changing major mode
5346 (add-hook 'org-mode-hook
5347 (lambda () (org-add-hook 'change-major-mode-hook
5348 'org-show-block-all 'append 'local)))
5350 ;;; Org-goto
5352 (defvar org-goto-window-configuration nil)
5353 (defvar org-goto-marker nil)
5354 (defvar org-goto-map
5355 (let ((map (make-sparse-keymap)))
5356 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5357 (while (setq cmd (pop cmds))
5358 (substitute-key-definition cmd cmd map global-map)))
5359 (suppress-keymap map)
5360 (org-defkey map "\C-m" 'org-goto-ret)
5361 (org-defkey map [(return)] 'org-goto-ret)
5362 (org-defkey map [(left)] 'org-goto-left)
5363 (org-defkey map [(right)] 'org-goto-right)
5364 (org-defkey map [(control ?g)] 'org-goto-quit)
5365 (org-defkey map "\C-i" 'org-cycle)
5366 (org-defkey map [(tab)] 'org-cycle)
5367 (org-defkey map [(down)] 'outline-next-visible-heading)
5368 (org-defkey map [(up)] 'outline-previous-visible-heading)
5369 (if org-goto-auto-isearch
5370 (if (fboundp 'define-key-after)
5371 (define-key-after map [t] 'org-goto-local-auto-isearch)
5372 nil)
5373 (org-defkey map "q" 'org-goto-quit)
5374 (org-defkey map "n" 'outline-next-visible-heading)
5375 (org-defkey map "p" 'outline-previous-visible-heading)
5376 (org-defkey map "f" 'outline-forward-same-level)
5377 (org-defkey map "b" 'outline-backward-same-level)
5378 (org-defkey map "u" 'outline-up-heading))
5379 (org-defkey map "/" 'org-occur)
5380 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5381 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5382 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5383 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5384 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5385 map))
5387 (defconst org-goto-help
5388 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5389 RET=jump to location [Q]uit and return to previous location
5390 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5392 (defvar org-goto-start-pos) ; dynamically scoped parameter
5394 ;; FIXME: Docstring doe not mention both interfaces
5395 (defun org-goto (&optional alternative-interface)
5396 "Look up a different location in the current file, keeping current visibility.
5398 When you want look-up or go to a different location in a document, the
5399 fastest way is often to fold the entire buffer and then dive into the tree.
5400 This method has the disadvantage, that the previous location will be folded,
5401 which may not be what you want.
5403 This command works around this by showing a copy of the current buffer
5404 in an indirect buffer, in overview mode. You can dive into the tree in
5405 that copy, use org-occur and incremental search to find a location.
5406 When pressing RET or `Q', the command returns to the original buffer in
5407 which the visibility is still unchanged. After RET is will also jump to
5408 the location selected in the indirect buffer and expose the
5409 the headline hierarchy above."
5410 (interactive "P")
5411 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5412 (org-refile-use-outline-path t)
5413 (org-refile-target-verify-function nil)
5414 (interface
5415 (if (not alternative-interface)
5416 org-goto-interface
5417 (if (eq org-goto-interface 'outline)
5418 'outline-path-completion
5419 'outline)))
5420 (org-goto-start-pos (point))
5421 (selected-point
5422 (if (eq interface 'outline)
5423 (car (org-get-location (current-buffer) org-goto-help))
5424 (nth 3 (org-refile-get-location "Goto: ")))))
5425 (if selected-point
5426 (progn
5427 (org-mark-ring-push org-goto-start-pos)
5428 (goto-char selected-point)
5429 (if (or (org-invisible-p) (org-invisible-p2))
5430 (org-show-context 'org-goto)))
5431 (message "Quit"))))
5433 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5434 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5435 (defvar org-goto-local-auto-isearch-map) ; defined below
5437 (defun org-get-location (buf help)
5438 "Let the user select a location in the Org-mode buffer BUF.
5439 This function uses a recursive edit. It returns the selected position
5440 or nil."
5441 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5442 (isearch-hide-immediately nil)
5443 (isearch-search-fun-function
5444 (lambda () 'org-goto-local-search-headings))
5445 (org-goto-selected-point org-goto-exit-command))
5446 (save-excursion
5447 (save-window-excursion
5448 (delete-other-windows)
5449 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5450 (switch-to-buffer
5451 (condition-case nil
5452 (make-indirect-buffer (current-buffer) "*org-goto*")
5453 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5454 (with-output-to-temp-buffer "*Help*"
5455 (princ help))
5456 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5457 (setq buffer-read-only nil)
5458 (let ((org-startup-truncated t)
5459 (org-startup-folded nil)
5460 (org-startup-align-all-tables nil))
5461 (org-mode)
5462 (org-overview))
5463 (setq buffer-read-only t)
5464 (if (and (boundp 'org-goto-start-pos)
5465 (integer-or-marker-p org-goto-start-pos))
5466 (let ((org-show-hierarchy-above t)
5467 (org-show-siblings t)
5468 (org-show-following-heading t))
5469 (goto-char org-goto-start-pos)
5470 (and (org-invisible-p) (org-show-context)))
5471 (goto-char (point-min)))
5472 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5473 (message "Select location and press RET")
5474 (use-local-map org-goto-map)
5475 (recursive-edit)
5477 (kill-buffer "*org-goto*")
5478 (cons org-goto-selected-point org-goto-exit-command)))
5480 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5481 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5482 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5483 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5485 (defun org-goto-local-search-headings (string bound noerror)
5486 "Search and make sure that any matches are in headlines."
5487 (catch 'return
5488 (while (if isearch-forward
5489 (search-forward string bound noerror)
5490 (search-backward string bound noerror))
5491 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5492 (and (member :headline context)
5493 (not (member :tags context))))
5494 (throw 'return (point))))))
5496 (defun org-goto-local-auto-isearch ()
5497 "Start isearch."
5498 (interactive)
5499 (goto-char (point-min))
5500 (let ((keys (this-command-keys)))
5501 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5502 (isearch-mode t)
5503 (isearch-process-search-char (string-to-char keys)))))
5505 (defun org-goto-ret (&optional arg)
5506 "Finish `org-goto' by going to the new location."
5507 (interactive "P")
5508 (setq org-goto-selected-point (point)
5509 org-goto-exit-command 'return)
5510 (throw 'exit nil))
5512 (defun org-goto-left ()
5513 "Finish `org-goto' by going to the new location."
5514 (interactive)
5515 (if (org-on-heading-p)
5516 (progn
5517 (beginning-of-line 1)
5518 (setq org-goto-selected-point (point)
5519 org-goto-exit-command 'left)
5520 (throw 'exit nil))
5521 (error "Not on a heading")))
5523 (defun org-goto-right ()
5524 "Finish `org-goto' by going to the new location."
5525 (interactive)
5526 (if (org-on-heading-p)
5527 (progn
5528 (setq org-goto-selected-point (point)
5529 org-goto-exit-command 'right)
5530 (throw 'exit nil))
5531 (error "Not on a heading")))
5533 (defun org-goto-quit ()
5534 "Finish `org-goto' without cursor motion."
5535 (interactive)
5536 (setq org-goto-selected-point nil)
5537 (setq org-goto-exit-command 'quit)
5538 (throw 'exit nil))
5540 ;;; Indirect buffer display of subtrees
5542 (defvar org-indirect-dedicated-frame nil
5543 "This is the frame being used for indirect tree display.")
5544 (defvar org-last-indirect-buffer nil)
5546 (defun org-tree-to-indirect-buffer (&optional arg)
5547 "Create indirect buffer and narrow it to current subtree.
5548 With numerical prefix ARG, go up to this level and then take that tree.
5549 If ARG is negative, go up that many levels.
5550 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5551 indirect buffer previously made with this command, to avoid proliferation of
5552 indirect buffers. However, when you call the command with a `C-u' prefix, or
5553 when `org-indirect-buffer-display' is `new-frame', the last buffer
5554 is kept so that you can work with several indirect buffers at the same time.
5555 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5556 requests that a new frame be made for the new buffer, so that the dedicated
5557 frame is not changed."
5558 (interactive "P")
5559 (let ((cbuf (current-buffer))
5560 (cwin (selected-window))
5561 (pos (point))
5562 beg end level heading ibuf)
5563 (save-excursion
5564 (org-back-to-heading t)
5565 (when (numberp arg)
5566 (setq level (org-outline-level))
5567 (if (< arg 0) (setq arg (+ level arg)))
5568 (while (> (setq level (org-outline-level)) arg)
5569 (outline-up-heading 1 t)))
5570 (setq beg (point)
5571 heading (org-get-heading))
5572 (org-end-of-subtree t) (setq end (point)))
5573 (if (and (buffer-live-p org-last-indirect-buffer)
5574 (not (eq org-indirect-buffer-display 'new-frame))
5575 (not arg))
5576 (kill-buffer org-last-indirect-buffer))
5577 (setq ibuf (org-get-indirect-buffer cbuf)
5578 org-last-indirect-buffer ibuf)
5579 (cond
5580 ((or (eq org-indirect-buffer-display 'new-frame)
5581 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5582 (select-frame (make-frame))
5583 (delete-other-windows)
5584 (switch-to-buffer ibuf)
5585 (org-set-frame-title heading))
5586 ((eq org-indirect-buffer-display 'dedicated-frame)
5587 (raise-frame
5588 (select-frame (or (and org-indirect-dedicated-frame
5589 (frame-live-p org-indirect-dedicated-frame)
5590 org-indirect-dedicated-frame)
5591 (setq org-indirect-dedicated-frame (make-frame)))))
5592 (delete-other-windows)
5593 (switch-to-buffer ibuf)
5594 (org-set-frame-title (concat "Indirect: " heading)))
5595 ((eq org-indirect-buffer-display 'current-window)
5596 (switch-to-buffer ibuf))
5597 ((eq org-indirect-buffer-display 'other-window)
5598 (pop-to-buffer ibuf))
5599 (t (error "Invalid value.")))
5600 (if (featurep 'xemacs)
5601 (save-excursion (org-mode) (turn-on-font-lock)))
5602 (narrow-to-region beg end)
5603 (show-all)
5604 (goto-char pos)
5605 (and (window-live-p cwin) (select-window cwin))))
5607 (defun org-get-indirect-buffer (&optional buffer)
5608 (setq buffer (or buffer (current-buffer)))
5609 (let ((n 1) (base (buffer-name buffer)) bname)
5610 (while (buffer-live-p
5611 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5612 (setq n (1+ n)))
5613 (condition-case nil
5614 (make-indirect-buffer buffer bname 'clone)
5615 (error (make-indirect-buffer buffer bname)))))
5617 (defun org-set-frame-title (title)
5618 "Set the title of the current frame to the string TITLE."
5619 ;; FIXME: how to name a single frame in XEmacs???
5620 (unless (featurep 'xemacs)
5621 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5623 ;;;; Structure editing
5625 ;;; Inserting headlines
5627 (defun org-previous-line-empty-p ()
5628 (save-excursion
5629 (and (not (bobp))
5630 (or (beginning-of-line 0) t)
5631 (save-match-data
5632 (looking-at "[ \t]*$")))))
5634 (defun org-insert-heading (&optional force-heading)
5635 "Insert a new heading or item with same depth at point.
5636 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5637 If point is at the beginning of a headline, insert a sibling before the
5638 current headline. If point is not at the beginning, do not split the line,
5639 but create the new headline after the current line."
5640 (interactive "P")
5641 (if (= (buffer-size) 0)
5642 (insert "\n* ")
5643 (when (or force-heading (not (org-insert-item)))
5644 (let* ((empty-line-p nil)
5645 (head (save-excursion
5646 (condition-case nil
5647 (progn
5648 (org-back-to-heading)
5649 (setq empty-line-p (org-previous-line-empty-p))
5650 (match-string 0))
5651 (error "*"))))
5652 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5653 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5654 pos hide-previous previous-pos)
5655 (cond
5656 ((and (org-on-heading-p) (bolp)
5657 (or (bobp)
5658 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5659 ;; insert before the current line
5660 (open-line (if blank 2 1)))
5661 ((and (bolp)
5662 (or (bobp)
5663 (save-excursion
5664 (backward-char 1) (not (org-invisible-p)))))
5665 ;; insert right here
5666 nil)
5668 ;; somewhere in the line
5669 (save-excursion
5670 (setq previous-pos (point-at-bol))
5671 (end-of-line)
5672 (setq hide-previous (org-invisible-p)))
5673 (and org-insert-heading-respect-content (org-show-subtree))
5674 (let ((split
5675 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5676 (save-excursion
5677 (let ((p (point)))
5678 (goto-char (point-at-bol))
5679 (and (looking-at org-complex-heading-regexp)
5680 (> p (match-beginning 4)))))))
5681 tags pos)
5682 (cond
5683 (org-insert-heading-respect-content
5684 (org-end-of-subtree nil t)
5685 (or (bolp) (newline))
5686 (or (org-previous-line-empty-p)
5687 (and blank (newline)))
5688 (open-line 1))
5689 ((org-on-heading-p)
5690 (when hide-previous
5691 (show-children)
5692 (org-show-entry))
5693 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5694 (setq tags (and (match-end 2) (match-string 2)))
5695 (and (match-end 1)
5696 (delete-region (match-beginning 1) (match-end 1)))
5697 (setq pos (point-at-bol))
5698 (or split (end-of-line 1))
5699 (delete-horizontal-space)
5700 (newline (if blank 2 1))
5701 (when tags
5702 (save-excursion
5703 (goto-char pos)
5704 (end-of-line 1)
5705 (insert " " tags)
5706 (org-set-tags nil 'align))))
5708 (or split (end-of-line 1))
5709 (newline (if blank 2 1)))))))
5710 (insert head) (just-one-space)
5711 (setq pos (point))
5712 (end-of-line 1)
5713 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5714 (when (and org-insert-heading-respect-content hide-previous)
5715 (save-excursion
5716 (goto-char previous-pos)
5717 (hide-subtree)))
5718 (run-hooks 'org-insert-heading-hook)))))
5720 (defun org-get-heading (&optional no-tags)
5721 "Return the heading of the current entry, without the stars."
5722 (save-excursion
5723 (org-back-to-heading t)
5724 (if (looking-at
5725 (if no-tags
5726 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5727 "\\*+[ \t]+\\([^\r\n]*\\)"))
5728 (match-string 1) "")))
5730 (defun org-heading-components ()
5731 "Return the components of the current heading.
5732 This is a list with the following elements:
5733 - the level as an integer
5734 - the reduced level, different if `org-odd-levels-only' is set.
5735 - the TODO keyword, or nil
5736 - the priority character, like ?A, or nil if no priority is given
5737 - the headline text itself, or the tags string if no headline text
5738 - the tags string, or nil."
5739 (save-excursion
5740 (org-back-to-heading t)
5741 (if (looking-at org-complex-heading-regexp)
5742 (list (length (match-string 1))
5743 (org-reduced-level (length (match-string 1)))
5744 (org-match-string-no-properties 2)
5745 (and (match-end 3) (aref (match-string 3) 2))
5746 (org-match-string-no-properties 4)
5747 (org-match-string-no-properties 5)))))
5749 (defun org-get-entry ()
5750 "Get the entry text, after heading, entire subtree."
5751 (save-excursion
5752 (org-back-to-heading t)
5753 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
5755 (defun org-insert-heading-after-current ()
5756 "Insert a new heading with same level as current, after current subtree."
5757 (interactive)
5758 (org-back-to-heading)
5759 (org-insert-heading)
5760 (org-move-subtree-down)
5761 (end-of-line 1))
5763 (defun org-insert-heading-respect-content ()
5764 (interactive)
5765 (let ((org-insert-heading-respect-content t))
5766 (org-insert-heading t)))
5768 (defun org-insert-todo-heading-respect-content (&optional force-state)
5769 (interactive "P")
5770 (let ((org-insert-heading-respect-content t))
5771 (org-insert-todo-heading force-state t)))
5773 (defun org-insert-todo-heading (arg &optional force-heading)
5774 "Insert a new heading with the same level and TODO state as current heading.
5775 If the heading has no TODO state, or if the state is DONE, use the first
5776 state (TODO by default). Also with prefix arg, force first state."
5777 (interactive "P")
5778 (when (or force-heading (not (org-insert-item 'checkbox)))
5779 (org-insert-heading force-heading)
5780 (save-excursion
5781 (org-back-to-heading)
5782 (outline-previous-heading)
5783 (looking-at org-todo-line-regexp))
5784 (let*
5785 ((new-mark-x
5786 (if (or arg
5787 (not (match-beginning 2))
5788 (member (match-string 2) org-done-keywords))
5789 (car org-todo-keywords-1)
5790 (match-string 2)))
5791 (new-mark
5793 (run-hook-with-args-until-success
5794 'org-todo-get-default-hook new-mark-x nil)
5795 new-mark-x)))
5796 (beginning-of-line 1)
5797 (and (looking-at "\\*+ ") (goto-char (match-end 0))
5798 (if org-treat-insert-todo-heading-as-state-change
5799 (org-todo new-mark)
5800 (insert new-mark " "))))
5801 (when org-provide-todo-statistics
5802 (org-update-parent-todo-statistics))))
5804 (defun org-insert-subheading (arg)
5805 "Insert a new subheading and demote it.
5806 Works for outline headings and for plain lists alike."
5807 (interactive "P")
5808 (org-insert-heading arg)
5809 (cond
5810 ((org-on-heading-p) (org-do-demote))
5811 ((org-at-item-p) (org-indent-item 1))))
5813 (defun org-insert-todo-subheading (arg)
5814 "Insert a new subheading with TODO keyword or checkbox and demote it.
5815 Works for outline headings and for plain lists alike."
5816 (interactive "P")
5817 (org-insert-todo-heading arg)
5818 (cond
5819 ((org-on-heading-p) (org-do-demote))
5820 ((org-at-item-p) (org-indent-item 1))))
5822 ;;; Promotion and Demotion
5824 (defvar org-after-demote-entry-hook nil
5825 "Hook run after an entry has been demoted.
5826 The cursor will be at the beginning of the entry.
5827 When a subtree is being demoted, the hook will be called for each node.")
5829 (defvar org-after-promote-entry-hook nil
5830 "Hook run after an entry has been promoted.
5831 The cursor will be at the beginning of the entry.
5832 When a subtree is being promoted, the hook will be called for each node.")
5834 (defun org-promote-subtree ()
5835 "Promote the entire subtree.
5836 See also `org-promote'."
5837 (interactive)
5838 (save-excursion
5839 (org-map-tree 'org-promote))
5840 (org-fix-position-after-promote))
5842 (defun org-demote-subtree ()
5843 "Demote the entire subtree. See `org-demote'.
5844 See also `org-promote'."
5845 (interactive)
5846 (save-excursion
5847 (org-map-tree 'org-demote))
5848 (org-fix-position-after-promote))
5851 (defun org-do-promote ()
5852 "Promote the current heading higher up the tree.
5853 If the region is active in `transient-mark-mode', promote all headings
5854 in the region."
5855 (interactive)
5856 (save-excursion
5857 (if (org-region-active-p)
5858 (org-map-region 'org-promote (region-beginning) (region-end))
5859 (org-promote)))
5860 (org-fix-position-after-promote))
5862 (defun org-do-demote ()
5863 "Demote the current heading lower down the tree.
5864 If the region is active in `transient-mark-mode', demote all headings
5865 in the region."
5866 (interactive)
5867 (save-excursion
5868 (if (org-region-active-p)
5869 (org-map-region 'org-demote (region-beginning) (region-end))
5870 (org-demote)))
5871 (org-fix-position-after-promote))
5873 (defun org-fix-position-after-promote ()
5874 "Make sure that after pro/demotion cursor position is right."
5875 (let ((pos (point)))
5876 (when (save-excursion
5877 (beginning-of-line 1)
5878 (looking-at org-todo-line-regexp)
5879 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5880 (cond ((eobp) (insert " "))
5881 ((eolp) (insert " "))
5882 ((equal (char-after) ?\ ) (forward-char 1))))))
5884 (defun org-reduced-level (l)
5885 "Compute the effective level of a heading.
5886 This takes into account the setting of `org-odd-levels-only'."
5887 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5889 (defun org-get-valid-level (level &optional change)
5890 "Rectify a level change under the influence of `org-odd-levels-only'
5891 LEVEL is a current level, CHANGE is by how much the level should be
5892 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5893 even level numbers will become the next higher odd number."
5894 (if org-odd-levels-only
5895 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5896 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5897 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5898 (max 1 (+ level (or change 0)))))
5900 (if (boundp 'define-obsolete-function-alias)
5901 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5902 (define-obsolete-function-alias 'org-get-legal-level
5903 'org-get-valid-level)
5904 (define-obsolete-function-alias 'org-get-legal-level
5905 'org-get-valid-level "23.1")))
5907 (defun org-promote ()
5908 "Promote the current heading higher up the tree.
5909 If the region is active in `transient-mark-mode', promote all headings
5910 in the region."
5911 (org-back-to-heading t)
5912 (let* ((level (save-match-data (funcall outline-level)))
5913 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5914 (diff (abs (- level (length up-head) -1))))
5915 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5916 (replace-match up-head nil t)
5917 ;; Fixup tag positioning
5918 (and org-auto-align-tags (org-set-tags nil t))
5919 (if org-adapt-indentation (org-fixup-indentation (- diff)))
5920 (run-hooks 'org-after-promote-entry-hook)))
5922 (defun org-demote ()
5923 "Demote the current heading lower down the tree.
5924 If the region is active in `transient-mark-mode', demote all headings
5925 in the region."
5926 (org-back-to-heading t)
5927 (let* ((level (save-match-data (funcall outline-level)))
5928 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5929 (diff (abs (- level (length down-head) -1))))
5930 (replace-match down-head nil t)
5931 ;; Fixup tag positioning
5932 (and org-auto-align-tags (org-set-tags nil t))
5933 (if org-adapt-indentation (org-fixup-indentation diff))
5934 (run-hooks 'org-after-demote-entry-hook)))
5936 (defun org-map-tree (fun)
5937 "Call FUN for every heading underneath the current one."
5938 (org-back-to-heading)
5939 (let ((level (funcall outline-level)))
5940 (save-excursion
5941 (funcall fun)
5942 (while (and (progn
5943 (outline-next-heading)
5944 (> (funcall outline-level) level))
5945 (not (eobp)))
5946 (funcall fun)))))
5948 (defun org-map-region (fun beg end)
5949 "Call FUN for every heading between BEG and END."
5950 (let ((org-ignore-region t))
5951 (save-excursion
5952 (setq end (copy-marker end))
5953 (goto-char beg)
5954 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5955 (< (point) end))
5956 (funcall fun))
5957 (while (and (progn
5958 (outline-next-heading)
5959 (< (point) end))
5960 (not (eobp)))
5961 (funcall fun)))))
5963 (defun org-fixup-indentation (diff)
5964 "Change the indentation in the current entry by DIFF
5965 However, if any line in the current entry has no indentation, or if it
5966 would end up with no indentation after the change, nothing at all is done."
5967 (save-excursion
5968 (let ((end (save-excursion (outline-next-heading)
5969 (point-marker)))
5970 (prohibit (if (> diff 0)
5971 "^\\S-"
5972 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5973 col)
5974 (unless (save-excursion (end-of-line 1)
5975 (re-search-forward prohibit end t))
5976 (while (and (< (point) end)
5977 (re-search-forward "^[ \t]+" end t))
5978 (goto-char (match-end 0))
5979 (setq col (current-column))
5980 (if (< diff 0) (replace-match ""))
5981 (org-indent-to-column (+ diff col))))
5982 (move-marker end nil))))
5984 (defun org-convert-to-odd-levels ()
5985 "Convert an org-mode file with all levels allowed to one with odd levels.
5986 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5987 level 5 etc."
5988 (interactive)
5989 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5990 (let ((org-odd-levels-only nil) n)
5991 (save-excursion
5992 (goto-char (point-min))
5993 (while (re-search-forward "^\\*\\*+ " nil t)
5994 (setq n (- (length (match-string 0)) 2))
5995 (while (>= (setq n (1- n)) 0)
5996 (org-demote))
5997 (end-of-line 1))))))
6000 (defun org-convert-to-oddeven-levels ()
6001 "Convert an org-mode file with only odd levels to one with odd and even levels.
6002 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6003 section with an even level, conversion would destroy the structure of the file. An error
6004 is signaled in this case."
6005 (interactive)
6006 (goto-char (point-min))
6007 ;; First check if there are no even levels
6008 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6009 (org-show-context t)
6010 (error "Not all levels are odd in this file. Conversion not possible."))
6011 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6012 (let ((org-odd-levels-only nil) n)
6013 (save-excursion
6014 (goto-char (point-min))
6015 (while (re-search-forward "^\\*\\*+ " nil t)
6016 (setq n (/ (1- (length (match-string 0))) 2))
6017 (while (>= (setq n (1- n)) 0)
6018 (org-promote))
6019 (end-of-line 1))))))
6021 (defun org-tr-level (n)
6022 "Make N odd if required."
6023 (if org-odd-levels-only (1+ (/ n 2)) n))
6025 ;;; Vertical tree motion, cutting and pasting of subtrees
6027 (defun org-move-subtree-up (&optional arg)
6028 "Move the current subtree up past ARG headlines of the same level."
6029 (interactive "p")
6030 (org-move-subtree-down (- (prefix-numeric-value arg))))
6032 (defun org-move-subtree-down (&optional arg)
6033 "Move the current subtree down past ARG headlines of the same level."
6034 (interactive "p")
6035 (setq arg (prefix-numeric-value arg))
6036 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6037 'outline-get-last-sibling))
6038 (ins-point (make-marker))
6039 (cnt (abs arg))
6040 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6041 ;; Select the tree
6042 (org-back-to-heading)
6043 (setq beg0 (point))
6044 (save-excursion
6045 (setq ne-beg (org-back-over-empty-lines))
6046 (setq beg (point)))
6047 (save-match-data
6048 (save-excursion (outline-end-of-heading)
6049 (setq folded (org-invisible-p)))
6050 (outline-end-of-subtree))
6051 (outline-next-heading)
6052 (setq ne-end (org-back-over-empty-lines))
6053 (setq end (point))
6054 (goto-char beg0)
6055 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6056 ;; include less whitespace
6057 (save-excursion
6058 (goto-char beg)
6059 (forward-line (- ne-beg ne-end))
6060 (setq beg (point))))
6061 ;; Find insertion point, with error handling
6062 (while (> cnt 0)
6063 (or (and (funcall movfunc) (looking-at outline-regexp))
6064 (progn (goto-char beg0)
6065 (error "Cannot move past superior level or buffer limit")))
6066 (setq cnt (1- cnt)))
6067 (if (> arg 0)
6068 ;; Moving forward - still need to move over subtree
6069 (progn (org-end-of-subtree t t)
6070 (save-excursion
6071 (org-back-over-empty-lines)
6072 (or (bolp) (newline)))))
6073 (setq ne-ins (org-back-over-empty-lines))
6074 (move-marker ins-point (point))
6075 (setq txt (buffer-substring beg end))
6076 (org-save-markers-in-region beg end)
6077 (delete-region beg end)
6078 (org-remove-empty-overlays-at beg)
6079 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6080 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6081 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6082 (let ((bbb (point)))
6083 (insert-before-markers txt)
6084 (org-reinstall-markers-in-region bbb)
6085 (move-marker ins-point bbb))
6086 (or (bolp) (insert "\n"))
6087 (setq ins-end (point))
6088 (goto-char ins-point)
6089 (org-skip-whitespace)
6090 (when (and (< arg 0)
6091 (org-first-sibling-p)
6092 (> ne-ins ne-beg))
6093 ;; Move whitespace back to beginning
6094 (save-excursion
6095 (goto-char ins-end)
6096 (let ((kill-whole-line t))
6097 (kill-line (- ne-ins ne-beg)) (point)))
6098 (insert (make-string (- ne-ins ne-beg) ?\n)))
6099 (move-marker ins-point nil)
6100 (if folded
6101 (hide-entry)
6102 (org-show-entry)
6103 (show-children)
6104 (org-cycle-hide-drawers 'children))
6105 (org-clean-visibility-after-subtree-move)))
6107 (defvar org-subtree-clip ""
6108 "Clipboard for cut and paste of subtrees.
6109 This is actually only a copy of the kill, because we use the normal kill
6110 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6112 (defvar org-subtree-clip-folded nil
6113 "Was the last copied subtree folded?
6114 This is used to fold the tree back after pasting.")
6116 (defun org-cut-subtree (&optional n)
6117 "Cut the current subtree into the clipboard.
6118 With prefix arg N, cut this many sequential subtrees.
6119 This is a short-hand for marking the subtree and then cutting it."
6120 (interactive "p")
6121 (org-copy-subtree n 'cut))
6123 (defun org-copy-subtree (&optional n cut force-store-markers)
6124 "Cut the current subtree into the clipboard.
6125 With prefix arg N, cut this many sequential subtrees.
6126 This is a short-hand for marking the subtree and then copying it.
6127 If CUT is non-nil, actually cut the subtree.
6128 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6129 of some markers in the region, even if CUT is non-nil. This is
6130 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6131 (interactive "p")
6132 (let (beg end folded (beg0 (point)))
6133 (if (interactive-p)
6134 (org-back-to-heading nil) ; take what looks like a subtree
6135 (org-back-to-heading t)) ; take what is really there
6136 (org-back-over-empty-lines)
6137 (setq beg (point))
6138 (skip-chars-forward " \t\r\n")
6139 (save-match-data
6140 (save-excursion (outline-end-of-heading)
6141 (setq folded (org-invisible-p)))
6142 (condition-case nil
6143 (outline-forward-same-level (1- n))
6144 (error nil))
6145 (org-end-of-subtree t t))
6146 (org-back-over-empty-lines)
6147 (setq end (point))
6148 (goto-char beg0)
6149 (when (> end beg)
6150 (setq org-subtree-clip-folded folded)
6151 (when (or cut force-store-markers)
6152 (org-save-markers-in-region beg end))
6153 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6154 (setq org-subtree-clip (current-kill 0))
6155 (message "%s: Subtree(s) with %d characters"
6156 (if cut "Cut" "Copied")
6157 (length org-subtree-clip)))))
6159 (defun org-paste-subtree (&optional level tree for-yank)
6160 "Paste the clipboard as a subtree, with modification of headline level.
6161 The entire subtree is promoted or demoted in order to match a new headline
6162 level.
6164 If the cursor is at the beginning of a headline, the same level as
6165 that headline is used to paste the tree
6167 If not, the new level is derived from the *visible* headings
6168 before and after the insertion point, and taken to be the inferior headline
6169 level of the two. So if the previous visible heading is level 3 and the
6170 next is level 4 (or vice versa), level 4 will be used for insertion.
6171 This makes sure that the subtree remains an independent subtree and does
6172 not swallow low level entries.
6174 You can also force a different level, either by using a numeric prefix
6175 argument, or by inserting the heading marker by hand. For example, if the
6176 cursor is after \"*****\", then the tree will be shifted to level 5.
6178 If optional TREE is given, use this text instead of the kill ring.
6180 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6181 move back over whitespace before inserting, and move point to the end of
6182 the inserted text when done."
6183 (interactive "P")
6184 (unless (org-kill-is-subtree-p tree)
6185 (error "%s"
6186 (substitute-command-keys
6187 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6188 (let* ((visp (not (org-invisible-p)))
6189 (txt (or tree (and kill-ring (current-kill 0))))
6190 (^re (concat "^\\(" outline-regexp "\\)"))
6191 (re (concat "\\(" outline-regexp "\\)"))
6192 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6194 (old-level (if (string-match ^re txt)
6195 (- (match-end 0) (match-beginning 0) 1)
6196 -1))
6197 (force-level (cond (level (prefix-numeric-value level))
6198 ((and (looking-at "[ \t]*$")
6199 (string-match
6200 ^re_ (buffer-substring
6201 (point-at-bol) (point))))
6202 (- (match-end 1) (match-beginning 1)))
6203 ((and (bolp)
6204 (looking-at org-outline-regexp))
6205 (- (match-end 0) (point) 1))
6206 (t nil)))
6207 (previous-level (save-excursion
6208 (condition-case nil
6209 (progn
6210 (outline-previous-visible-heading 1)
6211 (if (looking-at re)
6212 (- (match-end 0) (match-beginning 0) 1)
6214 (error 1))))
6215 (next-level (save-excursion
6216 (condition-case nil
6217 (progn
6218 (or (looking-at outline-regexp)
6219 (outline-next-visible-heading 1))
6220 (if (looking-at re)
6221 (- (match-end 0) (match-beginning 0) 1)
6223 (error 1))))
6224 (new-level (or force-level (max previous-level next-level)))
6225 (shift (if (or (= old-level -1)
6226 (= new-level -1)
6227 (= old-level new-level))
6229 (- new-level old-level)))
6230 (delta (if (> shift 0) -1 1))
6231 (func (if (> shift 0) 'org-demote 'org-promote))
6232 (org-odd-levels-only nil)
6233 beg end newend)
6234 ;; Remove the forced level indicator
6235 (if force-level
6236 (delete-region (point-at-bol) (point)))
6237 ;; Paste
6238 (beginning-of-line 1)
6239 (unless for-yank (org-back-over-empty-lines))
6240 (setq beg (point))
6241 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6242 (insert-before-markers txt)
6243 (unless (string-match "\n\\'" txt) (insert "\n"))
6244 (setq newend (point))
6245 (org-reinstall-markers-in-region beg)
6246 (setq end (point))
6247 (goto-char beg)
6248 (skip-chars-forward " \t\n\r")
6249 (setq beg (point))
6250 (if (and (org-invisible-p) visp)
6251 (save-excursion (outline-show-heading)))
6252 ;; Shift if necessary
6253 (unless (= shift 0)
6254 (save-restriction
6255 (narrow-to-region beg end)
6256 (while (not (= shift 0))
6257 (org-map-region func (point-min) (point-max))
6258 (setq shift (+ delta shift)))
6259 (goto-char (point-min))
6260 (setq newend (point-max))))
6261 (when (or (interactive-p) for-yank)
6262 (message "Clipboard pasted as level %d subtree" new-level))
6263 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6264 kill-ring
6265 (eq org-subtree-clip (current-kill 0))
6266 org-subtree-clip-folded)
6267 ;; The tree was folded before it was killed/copied
6268 (hide-subtree))
6269 (and for-yank (goto-char newend))))
6271 (defun org-kill-is-subtree-p (&optional txt)
6272 "Check if the current kill is an outline subtree, or a set of trees.
6273 Returns nil if kill does not start with a headline, or if the first
6274 headline level is not the largest headline level in the tree.
6275 So this will actually accept several entries of equal levels as well,
6276 which is OK for `org-paste-subtree'.
6277 If optional TXT is given, check this string instead of the current kill."
6278 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6279 (start-level (and kill
6280 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6281 org-outline-regexp "\\)")
6282 kill)
6283 (- (match-end 2) (match-beginning 2) 1)))
6284 (re (concat "^" org-outline-regexp))
6285 (start (1+ (or (match-beginning 2) -1))))
6286 (if (not start-level)
6287 (progn
6288 nil) ;; does not even start with a heading
6289 (catch 'exit
6290 (while (setq start (string-match re kill (1+ start)))
6291 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6292 (throw 'exit nil)))
6293 t))))
6295 (defvar org-markers-to-move nil
6296 "Markers that should be moved with a cut-and-paste operation.
6297 Those markers are stored together with their positions relative to
6298 the start of the region.")
6300 (defun org-save-markers-in-region (beg end)
6301 "Check markers in region.
6302 If these markers are between BEG and END, record their position relative
6303 to BEG, so that after moving the block of text, we can put the markers back
6304 into place.
6305 This function gets called just before an entry or tree gets cut from the
6306 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6307 called immediately, to move the markers with the entries."
6308 (setq org-markers-to-move nil)
6309 (when (featurep 'org-clock)
6310 (org-clock-save-markers-for-cut-and-paste beg end))
6311 (when (featurep 'org-agenda)
6312 (org-agenda-save-markers-for-cut-and-paste beg end)))
6314 (defun org-check-and-save-marker (marker beg end)
6315 "Check if MARKER is between BEG and END.
6316 If yes, remember the marker and the distance to BEG."
6317 (when (and (marker-buffer marker)
6318 (equal (marker-buffer marker) (current-buffer)))
6319 (if (and (>= marker beg) (< marker end))
6320 (push (cons marker (- marker beg)) org-markers-to-move))))
6322 (defun org-reinstall-markers-in-region (beg)
6323 "Move all remembered markers to their position relative to BEG."
6324 (mapc (lambda (x)
6325 (move-marker (car x) (+ beg (cdr x))))
6326 org-markers-to-move)
6327 (setq org-markers-to-move nil))
6329 (defun org-narrow-to-subtree ()
6330 "Narrow buffer to the current subtree."
6331 (interactive)
6332 (save-excursion
6333 (save-match-data
6334 (narrow-to-region
6335 (progn (org-back-to-heading t) (point))
6336 (progn (org-end-of-subtree t) (point))))))
6338 (defun org-clone-subtree-with-time-shift (n &optional shift)
6339 "Clone the task (subtree) at point N times.
6340 The clones will be inserted as siblings.
6342 In interactive use, the user will be prompted for the number of clones
6343 to be produced, and for a time SHIFT, which may be a repeater as used
6344 in time stamps, for example `+3d'.
6346 When a valid repeater is given and the entry contains any time stamps,
6347 the clones will become a sequence in time, with time stamps in the
6348 subtree shifted for each clone produced. If SHIFT is nil or the
6349 empty string, time stamps will be left alone.
6351 If the original subtree did contain time stamps with a repeater,
6352 the following will happen:
6353 - the repeater will be removed in each clone
6354 - an additional clone will be produced, with the current, unshifted
6355 date(s) in the entry.
6356 - the original entry will be placed *after* all the clones, with
6357 repeater intact.
6358 - the start days in the repeater in the original entry will be shifted
6359 to past the last clone.
6360 I this way you can spell out a number of instances of a repeating task,
6361 and still retain the repeater to cover future instances of the task."
6362 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6363 (let (beg end template task
6364 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6365 (if (not (and (integerp n) (> n 0)))
6366 (error "Invalid number of replications %s" n))
6367 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6368 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6369 shift)))
6370 (error "Invalid shift specification %s" shift))
6371 (when doshift
6372 (setq shift-n (string-to-number (match-string 1 shift))
6373 shift-what (cdr (assoc (match-string 2 shift)
6374 '(("d" . day) ("w" . week)
6375 ("m" . month) ("y" . year))))))
6376 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6377 (setq nmin 1 nmax n)
6378 (org-back-to-heading t)
6379 (setq beg (point))
6380 (org-end-of-subtree t t)
6381 (setq end (point))
6382 (setq template (buffer-substring beg end))
6383 (when (and doshift
6384 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6385 (delete-region beg end)
6386 (setq end beg)
6387 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6388 (goto-char end)
6389 (loop for n from nmin to nmax do
6390 (if (not doshift)
6391 (setq task template)
6392 (with-temp-buffer
6393 (insert template)
6394 (org-mode)
6395 (goto-char (point-min))
6396 (while (re-search-forward org-ts-regexp-both nil t)
6397 (org-timestamp-change (* n shift-n) shift-what))
6398 (unless (= n n-no-remove)
6399 (goto-char (point-min))
6400 (while (re-search-forward org-ts-regexp nil t)
6401 (save-excursion
6402 (goto-char (match-beginning 0))
6403 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6404 (delete-region (match-beginning 1) (match-end 1))))))
6405 (setq task (buffer-string))))
6406 (insert task))
6407 (goto-char beg)))
6409 ;;; Outline Sorting
6411 (defun org-sort (with-case)
6412 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6413 Optional argument WITH-CASE means sort case-sensitively.
6414 With a double prefix argument, also remove duplicate entries."
6415 (interactive "P")
6416 (if (org-at-table-p)
6417 (org-call-with-arg 'org-table-sort-lines with-case)
6418 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6420 (defun org-sort-remove-invisible (s)
6421 (remove-text-properties 0 (length s) org-rm-props s)
6422 (while (string-match org-bracket-link-regexp s)
6423 (setq s (replace-match (if (match-end 2)
6424 (match-string 3 s)
6425 (match-string 1 s)) t t s)))
6428 (defvar org-priority-regexp) ; defined later in the file
6430 (defvar org-after-sorting-entries-or-items-hook nil
6431 "Hook that is run after a bunch of entries or items have been sorted.
6432 When children are sorted, the cursor is in the parent line when this
6433 hook gets called. When a region or a plain list is sorted, the cursor
6434 will be in the first entry of the sorted region/list.")
6436 (defun org-sort-entries-or-items
6437 (&optional with-case sorting-type getkey-func compare-func property)
6438 "Sort entries on a certain level of an outline tree, or plain list items.
6439 If there is an active region, the entries in the region are sorted.
6440 Else, if the cursor is before the first entry, sort the top-level items.
6441 Else, the children of the entry at point are sorted.
6442 If the cursor is at the first item in a plain list, the list items will be
6443 sorted.
6445 Sorting can be alphabetically, numerically, by date/time as given by
6446 a time stamp, by a property or by priority.
6448 The command prompts for the sorting type unless it has been given to the
6449 function through the SORTING-TYPE argument, which needs to a character,
6450 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6451 precise meaning of each character:
6453 n Numerically, by converting the beginning of the entry/item to a number.
6454 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6455 t By date/time, either the first active time stamp in the entry, or, if
6456 none exist, by the first inactive one.
6457 In items, only the first line will be chekced.
6458 s By the scheduled date/time.
6459 d By deadline date/time.
6460 c By creation time, which is assumed to be the first inactive time stamp
6461 at the beginning of a line.
6462 p By priority according to the cookie.
6463 r By the value of a property.
6465 Capital letters will reverse the sort order.
6467 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6468 called with point at the beginning of the record. It must return either
6469 a string or a number that should serve as the sorting key for that record.
6471 Comparing entries ignores case by default. However, with an optional argument
6472 WITH-CASE, the sorting considers case as well."
6473 (interactive "P")
6474 (let ((case-func (if with-case 'identity 'downcase))
6475 start beg end stars re re2
6476 txt what tmp plain-list-p)
6477 ;; Find beginning and end of region to sort
6478 (cond
6479 ((org-region-active-p)
6480 ;; we will sort the region
6481 (setq end (region-end)
6482 what "region")
6483 (goto-char (region-beginning))
6484 (if (not (org-on-heading-p)) (outline-next-heading))
6485 (setq start (point)))
6486 ((org-at-item-p)
6487 ;; we will sort this plain list
6488 (org-beginning-of-item-list) (setq start (point))
6489 (org-end-of-item-list) (setq end (point))
6490 (goto-char start)
6491 (setq plain-list-p t
6492 what "plain list"))
6493 ((or (org-on-heading-p)
6494 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6495 ;; we will sort the children of the current headline
6496 (org-back-to-heading)
6497 (setq start (point)
6498 end (progn (org-end-of-subtree t t)
6499 (org-back-over-empty-lines)
6500 (point))
6501 what "children")
6502 (goto-char start)
6503 (show-subtree)
6504 (outline-next-heading))
6506 ;; we will sort the top-level entries in this file
6507 (goto-char (point-min))
6508 (or (org-on-heading-p) (outline-next-heading))
6509 (setq start (point) end (point-max) what "top-level")
6510 (goto-char start)
6511 (show-all)))
6513 (setq beg (point))
6514 (if (>= beg end) (error "Nothing to sort"))
6516 (unless plain-list-p
6517 (looking-at "\\(\\*+\\)")
6518 (setq stars (match-string 1)
6519 re (concat "^" (regexp-quote stars) " +")
6520 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6521 txt (buffer-substring beg end))
6522 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6523 (if (and (not (equal stars "*")) (string-match re2 txt))
6524 (error "Region to sort contains a level above the first entry")))
6526 (unless sorting-type
6527 (message
6528 (if plain-list-p
6529 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6530 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
6531 [t]ime [s]cheduled [d]eadline [c]reated
6532 A/N/T/S/D/C/P/O/F means reversed:")
6533 what)
6534 (setq sorting-type (read-char-exclusive))
6536 (and (= (downcase sorting-type) ?f)
6537 (setq getkey-func
6538 (org-ido-completing-read "Sort using function: "
6539 obarray 'fboundp t nil nil))
6540 (setq getkey-func (intern getkey-func)))
6542 (and (= (downcase sorting-type) ?r)
6543 (setq property
6544 (org-ido-completing-read "Property: "
6545 (mapcar 'list (org-buffer-property-keys t))
6546 nil t))))
6548 (message "Sorting entries...")
6550 (save-restriction
6551 (narrow-to-region start end)
6553 (let ((dcst (downcase sorting-type))
6554 (case-fold-search nil)
6555 (now (current-time)))
6556 (sort-subr
6557 (/= dcst sorting-type)
6558 ;; This function moves to the beginning character of the "record" to
6559 ;; be sorted.
6560 (if plain-list-p
6561 (lambda nil
6562 (if (org-at-item-p) t (goto-char (point-max))))
6563 (lambda nil
6564 (if (re-search-forward re nil t)
6565 (goto-char (match-beginning 0))
6566 (goto-char (point-max)))))
6567 ;; This function moves to the last character of the "record" being
6568 ;; sorted.
6569 (if plain-list-p
6570 'org-end-of-item
6571 (lambda nil
6572 (save-match-data
6573 (condition-case nil
6574 (outline-forward-same-level 1)
6575 (error
6576 (goto-char (point-max)))))))
6578 ;; This function returns the value that gets sorted against.
6579 (if plain-list-p
6580 (lambda nil
6581 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6582 (cond
6583 ((= dcst ?n)
6584 (string-to-number (buffer-substring (match-end 0)
6585 (point-at-eol))))
6586 ((= dcst ?a)
6587 (buffer-substring (match-end 0) (point-at-eol)))
6588 ((= dcst ?t)
6589 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
6590 (re-search-forward org-ts-regexp-both
6591 (point-at-eol) t))
6592 (org-time-string-to-seconds (match-string 0))
6593 (time-to-seconds now)))
6594 ((= dcst ?f)
6595 (if getkey-func
6596 (progn
6597 (setq tmp (funcall getkey-func))
6598 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6599 tmp)
6600 (error "Invalid key function `%s'" getkey-func)))
6601 (t (error "Invalid sorting type `%c'" sorting-type)))))
6602 (lambda nil
6603 (cond
6604 ((= dcst ?n)
6605 (if (looking-at org-complex-heading-regexp)
6606 (string-to-number (match-string 4))
6607 nil))
6608 ((= dcst ?a)
6609 (if (looking-at org-complex-heading-regexp)
6610 (funcall case-func (match-string 4))
6611 nil))
6612 ((= dcst ?t)
6613 (let ((end (save-excursion (outline-next-heading) (point))))
6614 (if (or (re-search-forward org-ts-regexp end t)
6615 (re-search-forward org-ts-regexp-both end t))
6616 (org-time-string-to-seconds (match-string 0))
6617 (time-to-seconds now))))
6618 ((= dcst ?c)
6619 (let ((end (save-excursion (outline-next-heading) (point))))
6620 (if (re-search-forward
6621 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
6622 end t)
6623 (org-time-string-to-seconds (match-string 0))
6624 (time-to-seconds now))))
6625 ((= dcst ?s)
6626 (let ((end (save-excursion (outline-next-heading) (point))))
6627 (if (re-search-forward org-scheduled-time-regexp end t)
6628 (org-time-string-to-seconds (match-string 1))
6629 (time-to-seconds now))))
6630 ((= dcst ?d)
6631 (let ((end (save-excursion (outline-next-heading) (point))))
6632 (if (re-search-forward org-deadline-time-regexp end t)
6633 (org-time-string-to-seconds (match-string 1))
6634 (time-to-seconds now))))
6635 ((= dcst ?p)
6636 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6637 (string-to-char (match-string 2))
6638 org-default-priority))
6639 ((= dcst ?r)
6640 (or (org-entry-get nil property) ""))
6641 ((= dcst ?o)
6642 (if (looking-at org-complex-heading-regexp)
6643 (- 9999 (length (member (match-string 2)
6644 org-todo-keywords-1)))))
6645 ((= dcst ?f)
6646 (if getkey-func
6647 (progn
6648 (setq tmp (funcall getkey-func))
6649 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6650 tmp)
6651 (error "Invalid key function `%s'" getkey-func)))
6652 (t (error "Invalid sorting type `%c'" sorting-type)))))
6654 (cond
6655 ((= dcst ?a) 'string<)
6656 ((= dcst ?f) compare-func)
6657 ((member dcst '(?p ?t ?s ?d ?c)) '<)
6658 (t nil)))))
6659 (run-hooks 'org-after-sorting-entries-or-items-hook)
6660 (message "Sorting entries...done")))
6662 (defun org-do-sort (table what &optional with-case sorting-type)
6663 "Sort TABLE of WHAT according to SORTING-TYPE.
6664 The user will be prompted for the SORTING-TYPE if the call to this
6665 function does not specify it. WHAT is only for the prompt, to indicate
6666 what is being sorted. The sorting key will be extracted from
6667 the car of the elements of the table.
6668 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6669 (unless sorting-type
6670 (message
6671 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6672 what)
6673 (setq sorting-type (read-char-exclusive)))
6674 (let ((dcst (downcase sorting-type))
6675 extractfun comparefun)
6676 ;; Define the appropriate functions
6677 (cond
6678 ((= dcst ?n)
6679 (setq extractfun 'string-to-number
6680 comparefun (if (= dcst sorting-type) '< '>)))
6681 ((= dcst ?a)
6682 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6683 (lambda(x) (downcase (org-sort-remove-invisible x))))
6684 comparefun (if (= dcst sorting-type)
6685 'string<
6686 (lambda (a b) (and (not (string< a b))
6687 (not (string= a b)))))))
6688 ((= dcst ?t)
6689 (setq extractfun
6690 (lambda (x)
6691 (if (or (string-match org-ts-regexp x)
6692 (string-match org-ts-regexp-both x))
6693 (time-to-seconds
6694 (org-time-string-to-time (match-string 0 x)))
6696 comparefun (if (= dcst sorting-type) '< '>)))
6697 (t (error "Invalid sorting type `%c'" sorting-type)))
6699 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6700 table)
6701 (lambda (a b) (funcall comparefun (car a) (car b))))))
6704 ;;; The orgstruct minor mode
6706 ;; Define a minor mode which can be used in other modes in order to
6707 ;; integrate the org-mode structure editing commands.
6709 ;; This is really a hack, because the org-mode structure commands use
6710 ;; keys which normally belong to the major mode. Here is how it
6711 ;; works: The minor mode defines all the keys necessary to operate the
6712 ;; structure commands, but wraps the commands into a function which
6713 ;; tests if the cursor is currently at a headline or a plain list
6714 ;; item. If that is the case, the structure command is used,
6715 ;; temporarily setting many Org-mode variables like regular
6716 ;; expressions for filling etc. However, when any of those keys is
6717 ;; used at a different location, function uses `key-binding' to look
6718 ;; up if the key has an associated command in another currently active
6719 ;; keymap (minor modes, major mode, global), and executes that
6720 ;; command. There might be problems if any of the keys is otherwise
6721 ;; used as a prefix key.
6723 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6724 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6725 ;; addresses this by checking explicitly for both bindings.
6727 (defvar orgstruct-mode-map (make-sparse-keymap)
6728 "Keymap for the minor `orgstruct-mode'.")
6730 (defvar org-local-vars nil
6731 "List of local variables, for use by `orgstruct-mode'")
6733 ;;;###autoload
6734 (define-minor-mode orgstruct-mode
6735 "Toggle the minor more `orgstruct-mode'.
6736 This mode is for using Org-mode structure commands in other modes.
6737 The following key behave as if Org-mode was active, if the cursor
6738 is on a headline, or on a plain list item (both in the definition
6739 of Org-mode).
6741 M-up Move entry/item up
6742 M-down Move entry/item down
6743 M-left Promote
6744 M-right Demote
6745 M-S-up Move entry/item up
6746 M-S-down Move entry/item down
6747 M-S-left Promote subtree
6748 M-S-right Demote subtree
6749 M-q Fill paragraph and items like in Org-mode
6750 C-c ^ Sort entries
6751 C-c - Cycle list bullet
6752 TAB Cycle item visibility
6753 M-RET Insert new heading/item
6754 S-M-RET Insert new TODO heading / Checkbox item
6755 C-c C-c Set tags / toggle checkbox"
6756 nil " OrgStruct" nil
6757 (org-load-modules-maybe)
6758 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6760 ;;;###autoload
6761 (defun turn-on-orgstruct ()
6762 "Unconditionally turn on `orgstruct-mode'."
6763 (orgstruct-mode 1))
6765 (defun orgstruct++-mode (&optional arg)
6766 "Toggle `orgstruct-mode', the enhanced version of it.
6767 In addition to setting orgstruct-mode, this also exports all indentation
6768 and autofilling variables from org-mode into the buffer. It will also
6769 recognize item context in multiline items.
6770 Note that turning off orgstruct-mode will *not* remove the
6771 indentation/paragraph settings. This can only be done by refreshing the
6772 major mode, for example with \\[normal-mode]."
6773 (interactive "P")
6774 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6775 (if (< arg 1)
6776 (orgstruct-mode -1)
6777 (orgstruct-mode 1)
6778 (let (var val)
6779 (mapc
6780 (lambda (x)
6781 (when (string-match
6782 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6783 (symbol-name (car x)))
6784 (setq var (car x) val (nth 1 x))
6785 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6786 org-local-vars)
6787 (org-set-local 'orgstruct-is-++ t))))
6789 (defvar orgstruct-is-++ nil
6790 "Is orgstruct-mode in ++ version in the current-buffer?")
6791 (make-variable-buffer-local 'orgstruct-is-++)
6793 ;;;###autoload
6794 (defun turn-on-orgstruct++ ()
6795 "Unconditionally turn on `orgstruct++-mode'."
6796 (orgstruct++-mode 1))
6798 (defun orgstruct-error ()
6799 "Error when there is no default binding for a structure key."
6800 (interactive)
6801 (error "This key has no function outside structure elements"))
6803 (defun orgstruct-setup ()
6804 "Setup orgstruct keymaps."
6805 (let ((nfunc 0)
6806 (bindings
6807 (list
6808 '([(meta up)] org-metaup)
6809 '([(meta down)] org-metadown)
6810 '([(meta left)] org-metaleft)
6811 '([(meta right)] org-metaright)
6812 '([(meta shift up)] org-shiftmetaup)
6813 '([(meta shift down)] org-shiftmetadown)
6814 '([(meta shift left)] org-shiftmetaleft)
6815 '([(meta shift right)] org-shiftmetaright)
6816 '([?\e (up)] org-metaup)
6817 '([?\e (down)] org-metadown)
6818 '([?\e (left)] org-metaleft)
6819 '([?\e (right)] org-metaright)
6820 '([?\e (shift up)] org-shiftmetaup)
6821 '([?\e (shift down)] org-shiftmetadown)
6822 '([?\e (shift left)] org-shiftmetaleft)
6823 '([?\e (shift right)] org-shiftmetaright)
6824 '([(shift up)] org-shiftup)
6825 '([(shift down)] org-shiftdown)
6826 '([(shift left)] org-shiftleft)
6827 '([(shift right)] org-shiftright)
6828 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6829 '("\M-q" fill-paragraph)
6830 '("\C-c^" org-sort)
6831 '("\C-c-" org-cycle-list-bullet)))
6832 elt key fun cmd)
6833 (while (setq elt (pop bindings))
6834 (setq nfunc (1+ nfunc))
6835 (setq key (org-key (car elt))
6836 fun (nth 1 elt)
6837 cmd (orgstruct-make-binding fun nfunc key))
6838 (org-defkey orgstruct-mode-map key cmd))
6840 ;; Special treatment needed for TAB and RET
6841 (org-defkey orgstruct-mode-map [(tab)]
6842 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6843 (org-defkey orgstruct-mode-map "\C-i"
6844 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6846 (org-defkey orgstruct-mode-map "\M-\C-m"
6847 (orgstruct-make-binding 'org-insert-heading 105
6848 "\M-\C-m" [(meta return)]))
6849 (org-defkey orgstruct-mode-map [(meta return)]
6850 (orgstruct-make-binding 'org-insert-heading 106
6851 [(meta return)] "\M-\C-m"))
6853 (org-defkey orgstruct-mode-map [(shift meta return)]
6854 (orgstruct-make-binding 'org-insert-todo-heading 107
6855 [(meta return)] "\M-\C-m"))
6857 (org-defkey orgstruct-mode-map "\e\C-m"
6858 (orgstruct-make-binding 'org-insert-heading 108
6859 "\e\C-m" [?\e (return)]))
6860 (org-defkey orgstruct-mode-map [?\e (return)]
6861 (orgstruct-make-binding 'org-insert-heading 109
6862 [?\e (return)] "\e\C-m"))
6863 (org-defkey orgstruct-mode-map [?\e (shift return)]
6864 (orgstruct-make-binding 'org-insert-todo-heading 110
6865 [?\e (return)] "\e\C-m"))
6867 (unless org-local-vars
6868 (setq org-local-vars (org-get-local-variables)))
6872 (defun orgstruct-make-binding (fun n &rest keys)
6873 "Create a function for binding in the structure minor mode.
6874 FUN is the command to call inside a table. N is used to create a unique
6875 command name. KEYS are keys that should be checked in for a command
6876 to execute outside of tables."
6877 (eval
6878 (list 'defun
6879 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6880 '(arg)
6881 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6882 "Outside of structure, run the binding of `"
6883 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6884 "'.")
6885 '(interactive "p")
6886 (list 'if
6887 `(org-context-p 'headline 'item
6888 (and orgstruct-is-++
6889 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
6890 'item-body))
6891 (list 'org-run-like-in-org-mode (list 'quote fun))
6892 (list 'let '(orgstruct-mode)
6893 (list 'call-interactively
6894 (append '(or)
6895 (mapcar (lambda (k)
6896 (list 'key-binding k))
6897 keys)
6898 '('orgstruct-error))))))))
6900 (defun org-context-p (&rest contexts)
6901 "Check if local context is any of CONTEXTS.
6902 Possible values in the list of contexts are `table', `headline', and `item'."
6903 (let ((pos (point)))
6904 (goto-char (point-at-bol))
6905 (prog1 (or (and (memq 'table contexts)
6906 (looking-at "[ \t]*|"))
6907 (and (memq 'headline contexts)
6908 ;;????????? (looking-at "\\*+"))
6909 (looking-at outline-regexp))
6910 (and (memq 'item contexts)
6911 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
6912 (and (memq 'item-body contexts)
6913 (org-in-item-p)))
6914 (goto-char pos))))
6916 (defun org-get-local-variables ()
6917 "Return a list of all local variables in an org-mode buffer."
6918 (let (varlist)
6919 (with-current-buffer (get-buffer-create "*Org tmp*")
6920 (erase-buffer)
6921 (org-mode)
6922 (setq varlist (buffer-local-variables)))
6923 (kill-buffer "*Org tmp*")
6924 (delq nil
6925 (mapcar
6926 (lambda (x)
6927 (setq x
6928 (if (symbolp x)
6929 (list x)
6930 (list (car x) (list 'quote (cdr x)))))
6931 (if (string-match
6932 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6933 (symbol-name (car x)))
6934 x nil))
6935 varlist))))
6937 ;;;###autoload
6938 (defun org-run-like-in-org-mode (cmd)
6939 "Run a command, pretending that the current buffer is in Org-mode.
6940 This will temporarily bind local variables that are typically bound in
6941 Org-mode to the values they have in Org-mode, and then interactively
6942 call CMD."
6943 (org-load-modules-maybe)
6944 (unless org-local-vars
6945 (setq org-local-vars (org-get-local-variables)))
6946 (eval (list 'let org-local-vars
6947 (list 'call-interactively (list 'quote cmd)))))
6949 ;;;; Archiving
6951 (defun org-get-category (&optional pos)
6952 "Get the category applying to position POS."
6953 (get-text-property (or pos (point)) 'org-category))
6955 (defun org-refresh-category-properties ()
6956 "Refresh category text properties in the buffer."
6957 (let ((def-cat (cond
6958 ((null org-category)
6959 (if buffer-file-name
6960 (file-name-sans-extension
6961 (file-name-nondirectory buffer-file-name))
6962 "???"))
6963 ((symbolp org-category) (symbol-name org-category))
6964 (t org-category)))
6965 beg end cat pos optionp)
6966 (org-unmodified
6967 (save-excursion
6968 (save-restriction
6969 (widen)
6970 (goto-char (point-min))
6971 (put-text-property (point) (point-max) 'org-category def-cat)
6972 (while (re-search-forward
6973 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6974 (setq pos (match-end 0)
6975 optionp (equal (char-after (match-beginning 0)) ?#)
6976 cat (org-trim (match-string 2)))
6977 (if optionp
6978 (setq beg (point-at-bol) end (point-max))
6979 (org-back-to-heading t)
6980 (setq beg (point) end (org-end-of-subtree t t)))
6981 (put-text-property beg end 'org-category cat)
6982 (goto-char pos)))))))
6985 ;;;; Link Stuff
6987 ;;; Link abbreviations
6989 (defun org-link-expand-abbrev (link)
6990 "Apply replacements as defined in `org-link-abbrev-alist."
6991 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6992 (let* ((key (match-string 1 link))
6993 (as (or (assoc key org-link-abbrev-alist-local)
6994 (assoc key org-link-abbrev-alist)))
6995 (tag (and (match-end 2) (match-string 3 link)))
6996 rpl)
6997 (if (not as)
6998 link
6999 (setq rpl (cdr as))
7000 (cond
7001 ((symbolp rpl) (funcall rpl tag))
7002 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7003 ((string-match "%h" rpl)
7004 (replace-match (url-hexify-string (or tag "")) t t rpl))
7005 (t (concat rpl tag)))))
7006 link))
7008 ;;; Storing and inserting links
7010 (defvar org-insert-link-history nil
7011 "Minibuffer history for links inserted with `org-insert-link'.")
7013 (defvar org-stored-links nil
7014 "Contains the links stored with `org-store-link'.")
7016 (defvar org-store-link-plist nil
7017 "Plist with info about the most recently link created with `org-store-link'.")
7019 (defvar org-link-protocols nil
7020 "Link protocols added to Org-mode using `org-add-link-type'.")
7022 (defvar org-store-link-functions nil
7023 "List of functions that are called to create and store a link.
7024 Each function will be called in turn until one returns a non-nil
7025 value. Each function should check if it is responsible for creating
7026 this link (for example by looking at the major mode).
7027 If not, it must exit and return nil.
7028 If yes, it should return a non-nil value after a calling
7029 `org-store-link-props' with a list of properties and values.
7030 Special properties are:
7032 :type The link prefix. like \"http\". This must be given.
7033 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7034 This is obligatory as well.
7035 :description Optional default description for the second pair
7036 of brackets in an Org-mode link. The user can still change
7037 this when inserting this link into an Org-mode buffer.
7039 In addition to these, any additional properties can be specified
7040 and then used in remember templates.")
7042 (defun org-add-link-type (type &optional follow export)
7043 "Add TYPE to the list of `org-link-types'.
7044 Re-compute all regular expressions depending on `org-link-types'
7046 FOLLOW and EXPORT are two functions.
7048 FOLLOW should take the link path as the single argument and do whatever
7049 is necessary to follow the link, for example find a file or display
7050 a mail message.
7052 EXPORT should format the link path for export to one of the export formats.
7053 It should be a function accepting three arguments:
7055 path the path of the link, the text after the prefix (like \"http:\")
7056 desc the description of the link, if any, nil if there was no description
7057 format the export format, a symbol like `html' or `latex'.
7059 The function may use the FORMAT information to return different values
7060 depending on the format. The return value will be put literally into
7061 the exported file.
7062 Org-mode has a built-in default for exporting links. If you are happy with
7063 this default, there is no need to define an export function for the link
7064 type. For a simple example of an export function, see `org-bbdb.el'."
7065 (add-to-list 'org-link-types type t)
7066 (org-make-link-regexps)
7067 (if (assoc type org-link-protocols)
7068 (setcdr (assoc type org-link-protocols) (list follow export))
7069 (push (list type follow export) org-link-protocols)))
7071 ;;;###autoload
7072 (defun org-store-link (arg)
7073 "\\<org-mode-map>Store an org-link to the current location.
7074 This link is added to `org-stored-links' and can later be inserted
7075 into an org-buffer with \\[org-insert-link].
7077 For some link types, a prefix arg is interpreted:
7078 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7079 For file links, arg negates `org-context-in-file-links'."
7080 (interactive "P")
7081 (org-load-modules-maybe)
7082 (setq org-store-link-plist nil) ; reset
7083 (let ((outline-regexp (org-get-limited-outline-regexp))
7084 link cpltxt desc description search txt custom-id)
7085 (cond
7087 ((run-hook-with-args-until-success 'org-store-link-functions)
7088 (setq link (plist-get org-store-link-plist :link)
7089 desc (or (plist-get org-store-link-plist :description) link)))
7091 ((equal (buffer-name) "*Org Edit Src Example*")
7092 (let (label gc)
7093 (while (or (not label)
7094 (save-excursion
7095 (save-restriction
7096 (widen)
7097 (goto-char (point-min))
7098 (re-search-forward
7099 (regexp-quote (format org-coderef-label-format label))
7100 nil t))))
7101 (when label (message "Label exists already") (sit-for 2))
7102 (setq label (read-string "Code line label: " label)))
7103 (end-of-line 1)
7104 (setq link (format org-coderef-label-format label))
7105 (setq gc (- 79 (length link)))
7106 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7107 (insert link)
7108 (setq link (concat "(" label ")") desc nil)))
7110 ((eq major-mode 'calendar-mode)
7111 (let ((cd (calendar-cursor-to-date)))
7112 (setq link
7113 (format-time-string
7114 (car org-time-stamp-formats)
7115 (apply 'encode-time
7116 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7117 nil nil nil))))
7118 (org-store-link-props :type "calendar" :date cd)))
7120 ((eq major-mode 'w3-mode)
7121 (setq cpltxt (if (and (buffer-name)
7122 (not (string-match "Untitled" (buffer-name))))
7123 (buffer-name)
7124 (url-view-url t))
7125 link (org-make-link (url-view-url t)))
7126 (org-store-link-props :type "w3" :url (url-view-url t)))
7128 ((eq major-mode 'w3m-mode)
7129 (setq cpltxt (or w3m-current-title w3m-current-url)
7130 link (org-make-link w3m-current-url))
7131 (org-store-link-props :type "w3m" :url (url-view-url t)))
7133 ((setq search (run-hook-with-args-until-success
7134 'org-create-file-search-functions))
7135 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7136 "::" search))
7137 (setq cpltxt (or description link)))
7139 ((eq major-mode 'image-mode)
7140 (setq cpltxt (concat "file:"
7141 (abbreviate-file-name buffer-file-name))
7142 link (org-make-link cpltxt))
7143 (org-store-link-props :type "image" :file buffer-file-name))
7145 ((eq major-mode 'dired-mode)
7146 ;; link to the file in the current line
7147 (setq cpltxt (concat "file:"
7148 (abbreviate-file-name
7149 (expand-file-name
7150 (dired-get-filename nil t))))
7151 link (org-make-link cpltxt)))
7153 ((and buffer-file-name (org-mode-p))
7154 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7155 (cond
7156 ((org-in-regexp "<<\\(.*?\\)>>")
7157 (setq cpltxt
7158 (concat "file:"
7159 (abbreviate-file-name buffer-file-name)
7160 "::" (match-string 1))
7161 link (org-make-link cpltxt)))
7162 ((and (featurep 'org-id)
7163 (or (eq org-link-to-org-use-id t)
7164 (and (eq org-link-to-org-use-id 'create-if-interactive)
7165 (interactive-p))
7166 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7167 (interactive-p)
7168 (not custom-id))
7169 (and org-link-to-org-use-id
7170 (condition-case nil
7171 (org-entry-get nil "ID")
7172 (error nil)))))
7173 ;; We can make a link using the ID.
7174 (setq link (condition-case nil
7175 (prog1 (org-id-store-link)
7176 (setq desc (plist-get org-store-link-plist
7177 :description)))
7178 (error
7179 ;; probably before first headline, link to file only
7180 (concat "file:"
7181 (abbreviate-file-name buffer-file-name))))))
7183 ;; Just link to current headline
7184 (setq cpltxt (concat "file:"
7185 (abbreviate-file-name buffer-file-name)))
7186 ;; Add a context search string
7187 (when (org-xor org-context-in-file-links arg)
7188 (setq txt (cond
7189 ((org-on-heading-p) nil)
7190 ((org-region-active-p)
7191 (buffer-substring (region-beginning) (region-end)))
7192 (t nil)))
7193 (when (or (null txt) (string-match "\\S-" txt))
7194 (setq cpltxt
7195 (concat cpltxt "::"
7196 (condition-case nil
7197 (org-make-org-heading-search-string txt)
7198 (error "")))
7199 desc (or (nth 4 (org-heading-components)) "NONE"))))
7200 (if (string-match "::\\'" cpltxt)
7201 (setq cpltxt (substring cpltxt 0 -2)))
7202 (setq link (org-make-link cpltxt)))))
7204 ((buffer-file-name (buffer-base-buffer))
7205 ;; Just link to this file here.
7206 (setq cpltxt (concat "file:"
7207 (abbreviate-file-name
7208 (buffer-file-name (buffer-base-buffer)))))
7209 ;; Add a context string
7210 (when (org-xor org-context-in-file-links arg)
7211 (setq txt (if (org-region-active-p)
7212 (buffer-substring (region-beginning) (region-end))
7213 (buffer-substring (point-at-bol) (point-at-eol))))
7214 ;; Only use search option if there is some text.
7215 (when (string-match "\\S-" txt)
7216 (setq cpltxt
7217 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7218 desc "NONE")))
7219 (setq link (org-make-link cpltxt)))
7221 ((interactive-p)
7222 (error "Cannot link to a buffer which is not visiting a file"))
7224 (t (setq link nil)))
7226 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7227 (setq link (or link cpltxt)
7228 desc (or desc cpltxt))
7229 (if (equal desc "NONE") (setq desc nil))
7231 (if (and (or (interactive-p) executing-kbd-macro) link)
7232 (progn
7233 (setq org-stored-links
7234 (cons (list link desc) org-stored-links))
7235 (message "Stored: %s" (or desc link))
7236 (when custom-id
7237 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7238 "::#" custom-id))
7239 (setq org-stored-links
7240 (cons (list link desc) org-stored-links))))
7241 (and link (org-make-link-string link desc)))))
7243 (defun org-store-link-props (&rest plist)
7244 "Store link properties, extract names and addresses."
7245 (let (x adr)
7246 (when (setq x (plist-get plist :from))
7247 (setq adr (mail-extract-address-components x))
7248 (setq plist (plist-put plist :fromname (car adr)))
7249 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7250 (when (setq x (plist-get plist :to))
7251 (setq adr (mail-extract-address-components x))
7252 (setq plist (plist-put plist :toname (car adr)))
7253 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7254 (let ((from (plist-get plist :from))
7255 (to (plist-get plist :to)))
7256 (when (and from to org-from-is-user-regexp)
7257 (setq plist
7258 (plist-put plist :fromto
7259 (if (string-match org-from-is-user-regexp from)
7260 (concat "to %t")
7261 (concat "from %f"))))))
7262 (setq org-store-link-plist plist))
7264 (defun org-add-link-props (&rest plist)
7265 "Add these properties to the link property list."
7266 (let (key value)
7267 (while plist
7268 (setq key (pop plist) value (pop plist))
7269 (setq org-store-link-plist
7270 (plist-put org-store-link-plist key value)))))
7272 (defun org-email-link-description (&optional fmt)
7273 "Return the description part of an email link.
7274 This takes information from `org-store-link-plist' and formats it
7275 according to FMT (default from `org-email-link-description-format')."
7276 (setq fmt (or fmt org-email-link-description-format))
7277 (let* ((p org-store-link-plist)
7278 (to (plist-get p :toaddress))
7279 (from (plist-get p :fromaddress))
7280 (table
7281 (list
7282 (cons "%c" (plist-get p :fromto))
7283 (cons "%F" (plist-get p :from))
7284 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7285 (cons "%T" (plist-get p :to))
7286 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7287 (cons "%s" (plist-get p :subject))
7288 (cons "%m" (plist-get p :message-id)))))
7289 (when (string-match "%c" fmt)
7290 ;; Check if the user wrote this message
7291 (if (and org-from-is-user-regexp from to
7292 (save-match-data (string-match org-from-is-user-regexp from)))
7293 (setq fmt (replace-match "to %t" t t fmt))
7294 (setq fmt (replace-match "from %f" t t fmt))))
7295 (org-replace-escapes fmt table)))
7297 (defun org-make-org-heading-search-string (&optional string heading)
7298 "Make search string for STRING or current headline."
7299 (interactive)
7300 (let ((s (or string (org-get-heading))))
7301 (unless (and string (not heading))
7302 ;; We are using a headline, clean up garbage in there.
7303 (if (string-match org-todo-regexp s)
7304 (setq s (replace-match "" t t s)))
7305 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7306 (setq s (replace-match "" t t s)))
7307 (setq s (org-trim s))
7308 (if (string-match (concat "^\\(" org-quote-string "\\|"
7309 org-comment-string "\\)") s)
7310 (setq s (replace-match "" t t s)))
7311 (while (string-match org-ts-regexp s)
7312 (setq s (replace-match "" t t s))))
7313 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7314 (setq s (replace-match " " t t s)))
7315 (or string (setq s (concat "*" s))) ; Add * for headlines
7316 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7318 (defun org-make-link (&rest strings)
7319 "Concatenate STRINGS."
7320 (apply 'concat strings))
7322 (defun org-make-link-string (link &optional description)
7323 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7324 (unless (string-match "\\S-" link)
7325 (error "Empty link"))
7326 (when (stringp description)
7327 ;; Remove brackets from the description, they are fatal.
7328 (while (string-match "\\[" description)
7329 (setq description (replace-match "{" t t description)))
7330 (while (string-match "\\]" description)
7331 (setq description (replace-match "}" t t description))))
7332 (when (equal (org-link-escape link) description)
7333 ;; No description needed, it is identical
7334 (setq description nil))
7335 (when (and (not description)
7336 (not (equal link (org-link-escape link))))
7337 (setq description (org-extract-attributes link)))
7338 (concat "[[" (org-link-escape link) "]"
7339 (if description (concat "[" description "]") "")
7340 "]"))
7342 (defconst org-link-escape-chars
7343 '((?\ . "%20")
7344 (?\[ . "%5B")
7345 (?\] . "%5D")
7346 (?\340 . "%E0") ; `a
7347 (?\342 . "%E2") ; ^a
7348 (?\347 . "%E7") ; ,c
7349 (?\350 . "%E8") ; `e
7350 (?\351 . "%E9") ; 'e
7351 (?\352 . "%EA") ; ^e
7352 (?\356 . "%EE") ; ^i
7353 (?\364 . "%F4") ; ^o
7354 (?\371 . "%F9") ; `u
7355 (?\373 . "%FB") ; ^u
7356 (?\; . "%3B")
7357 (?? . "%3F")
7358 (?= . "%3D")
7359 (?+ . "%2B")
7361 "Association list of escapes for some characters problematic in links.
7362 This is the list that is used for internal purposes.")
7364 (defvar org-url-encoding-use-url-hexify nil)
7366 (defconst org-link-escape-chars-browser
7367 '((?\ . "%20")) ; 32 for the SPC char
7368 "Association list of escapes for some characters problematic in links.
7369 This is the list that is used before handing over to the browser.")
7371 (defun org-link-escape (text &optional table)
7372 "Escape characters in TEXT that are problematic for links."
7373 (if org-url-encoding-use-url-hexify
7374 (url-hexify-string text)
7375 (setq table (or table org-link-escape-chars))
7376 (when text
7377 (let ((re (mapconcat (lambda (x) (regexp-quote
7378 (char-to-string (car x))))
7379 table "\\|")))
7380 (while (string-match re text)
7381 (setq text
7382 (replace-match
7383 (cdr (assoc (string-to-char (match-string 0 text))
7384 table))
7385 t t text)))
7386 text))))
7388 (defun org-link-unescape (text &optional table)
7389 "Reverse the action of `org-link-escape'."
7390 (if org-url-encoding-use-url-hexify
7391 (url-unhex-string text)
7392 (setq table (or table org-link-escape-chars))
7393 (when text
7394 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7395 table "\\|")))
7396 (while (string-match re text)
7397 (setq text
7398 (replace-match
7399 (char-to-string (car (rassoc (match-string 0 text) table)))
7400 t t text)))
7401 text))))
7403 (defun org-xor (a b)
7404 "Exclusive or."
7405 (if a (not b) b))
7407 (defun org-fixup-message-id-for-http (s)
7408 "Replace special characters in a message id, so it can be used in an http query."
7409 (while (string-match "<" s)
7410 (setq s (replace-match "%3C" t t s)))
7411 (while (string-match ">" s)
7412 (setq s (replace-match "%3E" t t s)))
7413 (while (string-match "@" s)
7414 (setq s (replace-match "%40" t t s)))
7417 ;;;###autoload
7418 (defun org-insert-link-global ()
7419 "Insert a link like Org-mode does.
7420 This command can be called in any mode to insert a link in Org-mode syntax."
7421 (interactive)
7422 (org-load-modules-maybe)
7423 (org-run-like-in-org-mode 'org-insert-link))
7425 (defun org-insert-link (&optional complete-file link-location)
7426 "Insert a link. At the prompt, enter the link.
7428 Completion can be used to insert any of the link protocol prefixes like
7429 http or ftp in use.
7431 The history can be used to select a link previously stored with
7432 `org-store-link'. When the empty string is entered (i.e. if you just
7433 press RET at the prompt), the link defaults to the most recently
7434 stored link. As SPC triggers completion in the minibuffer, you need to
7435 use M-SPC or C-q SPC to force the insertion of a space character.
7437 You will also be prompted for a description, and if one is given, it will
7438 be displayed in the buffer instead of the link.
7440 If there is already a link at point, this command will allow you to edit link
7441 and description parts.
7443 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7444 be selected using completion. The path to the file will be relative to the
7445 current directory if the file is in the current directory or a subdirectory.
7446 Otherwise, the link will be the absolute path as completed in the minibuffer
7447 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7448 option `org-link-file-path-type'.
7450 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7451 the current directory or below.
7453 With three \\[universal-argument] prefixes, negate the meaning of
7454 `org-keep-stored-link-after-insertion'.
7456 If `org-make-link-description-function' is non-nil, this function will be
7457 called with the link target, and the result will be the default
7458 link description.
7460 If the LINK-LOCATION parameter is non-nil, this value will be
7461 used as the link location instead of reading one interactively."
7462 (interactive "P")
7463 (let* ((wcf (current-window-configuration))
7464 (region (if (org-region-active-p)
7465 (buffer-substring (region-beginning) (region-end))))
7466 (remove (and region (list (region-beginning) (region-end))))
7467 (desc region)
7468 tmphist ; byte-compile incorrectly complains about this
7469 (link link-location)
7470 entry file all-prefixes)
7471 (cond
7472 (link-location) ; specified by arg, just use it.
7473 ((org-in-regexp org-bracket-link-regexp 1)
7474 ;; We do have a link at point, and we are going to edit it.
7475 (setq remove (list (match-beginning 0) (match-end 0)))
7476 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7477 (setq link (read-string "Link: "
7478 (org-link-unescape
7479 (org-match-string-no-properties 1)))))
7480 ((or (org-in-regexp org-angle-link-re)
7481 (org-in-regexp org-plain-link-re))
7482 ;; Convert to bracket link
7483 (setq remove (list (match-beginning 0) (match-end 0))
7484 link (read-string "Link: "
7485 (org-remove-angle-brackets (match-string 0)))))
7486 ((member complete-file '((4) (16)))
7487 ;; Completing read for file names.
7488 (setq link (org-file-complete-link complete-file)))
7490 ;; Read link, with completion for stored links.
7491 (with-output-to-temp-buffer "*Org Links*"
7492 (princ "Insert a link.
7493 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
7494 (when org-stored-links
7495 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7496 (princ (mapconcat
7497 (lambda (x)
7498 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7499 (reverse org-stored-links) "\n"))))
7500 (let ((cw (selected-window)))
7501 (select-window (get-buffer-window "*Org Links*"))
7502 (setq truncate-lines t)
7503 (unless (pos-visible-in-window-p (point-max))
7504 (org-fit-window-to-buffer))
7505 (and (window-live-p cw) (select-window cw)))
7506 ;; Fake a link history, containing the stored links.
7507 (setq tmphist (append (mapcar 'car org-stored-links)
7508 org-insert-link-history))
7509 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
7510 (mapcar 'car org-link-abbrev-alist)
7511 org-link-types))
7512 (unwind-protect
7513 (progn
7514 (setq link
7515 (let ((org-completion-use-ido nil))
7516 (org-completing-read
7517 "Link: "
7518 (append
7519 (mapcar (lambda (x) (list (concat x ":")))
7520 all-prefixes)
7521 (mapcar 'car org-stored-links))
7522 nil nil nil
7523 'tmphist
7524 (car (car org-stored-links)))))
7525 (if (or (member link all-prefixes)
7526 (and (equal ":" (substring link -1))
7527 (member (substring link 0 -1) all-prefixes)
7528 (setq link (substring link 0 -1))))
7529 (setq link (org-link-try-special-completion link))))
7530 (set-window-configuration wcf)
7531 (kill-buffer "*Org Links*"))
7532 (setq entry (assoc link org-stored-links))
7533 (or entry (push link org-insert-link-history))
7534 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7535 (not org-keep-stored-link-after-insertion))
7536 (setq org-stored-links (delq (assoc link org-stored-links)
7537 org-stored-links)))
7538 (setq desc (or desc (nth 1 entry)))))
7540 (if (string-match org-plain-link-re link)
7541 ;; URL-like link, normalize the use of angular brackets.
7542 (setq link (org-make-link (org-remove-angle-brackets link))))
7544 ;; Check if we are linking to the current file with a search option
7545 ;; If yes, simplify the link by using only the search option.
7546 (when (and buffer-file-name
7547 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7548 (let* ((path (match-string 1 link))
7549 (case-fold-search nil)
7550 (search (match-string 2 link)))
7551 (save-match-data
7552 (if (equal (file-truename buffer-file-name) (file-truename path))
7553 ;; We are linking to this same file, with a search option
7554 (setq link search)))))
7556 ;; Check if we can/should use a relative path. If yes, simplify the link
7557 (when (string-match "^file:\\(.*\\)" link)
7558 (let* ((path (match-string 1 link))
7559 (origpath path)
7560 (case-fold-search nil))
7561 (cond
7562 ((or (eq org-link-file-path-type 'absolute)
7563 (equal complete-file '(16)))
7564 (setq path (abbreviate-file-name (expand-file-name path))))
7565 ((eq org-link-file-path-type 'noabbrev)
7566 (setq path (expand-file-name path)))
7567 ((eq org-link-file-path-type 'relative)
7568 (setq path (file-relative-name path)))
7570 (save-match-data
7571 (if (string-match (concat "^" (regexp-quote
7572 (file-name-as-directory
7573 (expand-file-name "."))))
7574 (expand-file-name path))
7575 ;; We are linking a file with relative path name.
7576 (setq path (substring (expand-file-name path)
7577 (match-end 0)))
7578 (setq path (abbreviate-file-name (expand-file-name path)))))))
7579 (setq link (concat "file:" path))
7580 (if (equal desc origpath)
7581 (setq desc path))))
7583 (if org-make-link-description-function
7584 (setq desc (funcall org-make-link-description-function link desc)))
7586 (setq desc (read-string "Description: " desc))
7587 (unless (string-match "\\S-" desc) (setq desc nil))
7588 (if remove (apply 'delete-region remove))
7589 (insert (org-make-link-string link desc))))
7591 (defun org-link-try-special-completion (type)
7592 "If there is completion support for link type TYPE, offer it."
7593 (let ((fun (intern (concat "org-" type "-complete-link"))))
7594 (if (functionp fun)
7595 (funcall fun)
7596 (read-string "Link (no completion support): " (concat type ":")))))
7598 (defun org-file-complete-link (&optional arg)
7599 "Create a file link using completion."
7600 (let (file link)
7601 (setq file (read-file-name "File: "))
7602 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7603 (pwd1 (file-name-as-directory (abbreviate-file-name
7604 (expand-file-name ".")))))
7605 (cond
7606 ((equal arg '(16))
7607 (setq link (org-make-link
7608 "file:"
7609 (abbreviate-file-name (expand-file-name file)))))
7610 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7611 (setq link (org-make-link "file:" (match-string 1 file))))
7612 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7613 (expand-file-name file))
7614 (setq link (org-make-link
7615 "file:" (match-string 1 (expand-file-name file)))))
7616 (t (setq link (org-make-link "file:" file)))))
7617 link))
7619 (defun org-completing-read (&rest args)
7620 "Completing-read with SPACE being a normal character."
7621 (let ((minibuffer-local-completion-map
7622 (copy-keymap minibuffer-local-completion-map)))
7623 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7624 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7625 (apply 'org-ido-completing-read args)))
7627 (defun org-completing-read-no-ido (&rest args)
7628 (let (org-completion-use-ido)
7629 (apply 'org-completing-read args)))
7631 (defun org-ido-completing-read (&rest args)
7632 "Completing-read using `ido-mode' speedups if available"
7633 (if (and org-completion-use-ido
7634 (fboundp 'ido-completing-read)
7635 (boundp 'ido-mode) ido-mode
7636 (listp (second args)))
7637 (let ((ido-enter-matching-directory nil))
7638 (apply 'ido-completing-read (concat (car args))
7639 (mapcar (lambda (x) (car x)) (nth 1 args))
7640 (cddr args)))
7641 (apply 'completing-read args)))
7643 (defun org-extract-attributes (s)
7644 "Extract the attributes cookie from a string and set as text property."
7645 (let (a attr (start 0) key value)
7646 (save-match-data
7647 (when (string-match "{{\\([^}]+\\)}}$" s)
7648 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7649 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7650 (setq key (match-string 1 a) value (match-string 2 a)
7651 start (match-end 0)
7652 attr (plist-put attr (intern key) value))))
7653 (org-add-props s nil 'org-attr attr))
7656 (defun org-extract-attributes-from-string (tag)
7657 (let (key value attr)
7658 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
7659 (setq key (match-string 1 tag) value (match-string 2 tag)
7660 tag (replace-match "" t t tag)
7661 attr (plist-put attr (intern key) value)))
7662 (cons tag attr)))
7664 (defun org-attributes-to-string (plist)
7665 "Format a property list into an HTML attribute list."
7666 (let ((s "") key value)
7667 (while plist
7668 (setq key (pop plist) value (pop plist))
7669 (and value
7670 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7673 ;;; Opening/following a link
7675 (defvar org-link-search-failed nil)
7677 (defun org-next-link ()
7678 "Move forward to the next link.
7679 If the link is in hidden text, expose it."
7680 (interactive)
7681 (when (and org-link-search-failed (eq this-command last-command))
7682 (goto-char (point-min))
7683 (message "Link search wrapped back to beginning of buffer"))
7684 (setq org-link-search-failed nil)
7685 (let* ((pos (point))
7686 (ct (org-context))
7687 (a (assoc :link ct)))
7688 (if a (goto-char (nth 2 a)))
7689 (if (re-search-forward org-any-link-re nil t)
7690 (progn
7691 (goto-char (match-beginning 0))
7692 (if (org-invisible-p) (org-show-context)))
7693 (goto-char pos)
7694 (setq org-link-search-failed t)
7695 (error "No further link found"))))
7697 (defun org-previous-link ()
7698 "Move backward to the previous link.
7699 If the link is in hidden text, expose it."
7700 (interactive)
7701 (when (and org-link-search-failed (eq this-command last-command))
7702 (goto-char (point-max))
7703 (message "Link search wrapped back to end of buffer"))
7704 (setq org-link-search-failed nil)
7705 (let* ((pos (point))
7706 (ct (org-context))
7707 (a (assoc :link ct)))
7708 (if a (goto-char (nth 1 a)))
7709 (if (re-search-backward org-any-link-re nil t)
7710 (progn
7711 (goto-char (match-beginning 0))
7712 (if (org-invisible-p) (org-show-context)))
7713 (goto-char pos)
7714 (setq org-link-search-failed t)
7715 (error "No further link found"))))
7717 (defun org-translate-link (s)
7718 "Translate a link string if a translation function has been defined."
7719 (if (and org-link-translation-function
7720 (fboundp org-link-translation-function)
7721 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7722 (progn
7723 (setq s (funcall org-link-translation-function
7724 (match-string 1) (match-string 2)))
7725 (concat (car s) ":" (cdr s)))
7728 (defun org-translate-link-from-planner (type path)
7729 "Translate a link from Emacs Planner syntax so that Org can follow it.
7730 This is still an experimental function, your mileage may vary."
7731 (cond
7732 ((member type '("http" "https" "news" "ftp"))
7733 ;; standard Internet links are the same.
7734 nil)
7735 ((and (equal type "irc") (string-match "^//" path))
7736 ;; Planner has two / at the beginning of an irc link, we have 1.
7737 ;; We should have zero, actually....
7738 (setq path (substring path 1)))
7739 ((and (equal type "lisp") (string-match "^/" path))
7740 ;; Planner has a slash, we do not.
7741 (setq type "elisp" path (substring path 1)))
7742 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7743 ;; A typical message link. Planner has the id after the fina slash,
7744 ;; we separate it with a hash mark
7745 (setq path (concat (match-string 1 path) "#"
7746 (org-remove-angle-brackets (match-string 2 path)))))
7748 (cons type path))
7750 (defun org-find-file-at-mouse (ev)
7751 "Open file link or URL at mouse."
7752 (interactive "e")
7753 (mouse-set-point ev)
7754 (org-open-at-point 'in-emacs))
7756 (defun org-open-at-mouse (ev)
7757 "Open file link or URL at mouse."
7758 (interactive "e")
7759 (mouse-set-point ev)
7760 (if (eq major-mode 'org-agenda-mode)
7761 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7762 (org-open-at-point))
7764 (defvar org-window-config-before-follow-link nil
7765 "The window configuration before following a link.
7766 This is saved in case the need arises to restore it.")
7768 (defvar org-open-link-marker (make-marker)
7769 "Marker pointing to the location where `org-open-at-point; was called.")
7771 ;;;###autoload
7772 (defun org-open-at-point-global ()
7773 "Follow a link like Org-mode does.
7774 This command can be called in any mode to follow a link that has
7775 Org-mode syntax."
7776 (interactive)
7777 (org-run-like-in-org-mode 'org-open-at-point))
7779 ;;;###autoload
7780 (defun org-open-link-from-string (s &optional arg)
7781 "Open a link in the string S, as if it was in Org-mode."
7782 (interactive "sLink: \nP")
7783 (let ((reference-buffer (current-buffer)))
7784 (with-temp-buffer
7785 (let ((org-inhibit-startup t))
7786 (org-mode)
7787 (insert s)
7788 (goto-char (point-min))
7789 (org-open-at-point arg reference-buffer)))))
7791 (defun org-open-at-point (&optional in-emacs reference-buffer)
7792 "Open link at or after point.
7793 If there is no link at point, this function will search forward up to
7794 the end of the current line.
7795 Normally, files will be opened by an appropriate application. If the
7796 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7797 With a double prefix argument, try to open outside of Emacs, in the
7798 application the system uses for this file type."
7799 (interactive "P")
7800 (org-load-modules-maybe)
7801 (move-marker org-open-link-marker (point))
7802 (setq org-window-config-before-follow-link (current-window-configuration))
7803 (org-remove-occur-highlights nil nil t)
7804 (cond
7805 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7806 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7807 (org-footnote-action))
7809 (let (type path link line search (pos (point)))
7810 (catch 'match
7811 (save-excursion
7812 (skip-chars-forward "^]\n\r")
7813 (when (org-in-regexp org-bracket-link-regexp)
7814 (setq link (org-extract-attributes
7815 (org-link-unescape (org-match-string-no-properties 1))))
7816 (while (string-match " *\n *" link)
7817 (setq link (replace-match " " t t link)))
7818 (setq link (org-link-expand-abbrev link))
7819 (cond
7820 ((or (file-name-absolute-p link)
7821 (string-match "^\\.\\.?/" link))
7822 (setq type "file" path link))
7823 ((string-match org-link-re-with-space3 link)
7824 (setq type (match-string 1 link) path (match-string 2 link)))
7825 (t (setq type "thisfile" path link)))
7826 (throw 'match t)))
7828 (when (get-text-property (point) 'org-linked-text)
7829 (setq type "thisfile"
7830 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7831 (1+ (point)) (point))
7832 path (buffer-substring
7833 (previous-single-property-change pos 'org-linked-text)
7834 (next-single-property-change pos 'org-linked-text)))
7835 (throw 'match t))
7837 (save-excursion
7838 (when (or (org-in-regexp org-angle-link-re)
7839 (org-in-regexp org-plain-link-re))
7840 (setq type (match-string 1) path (match-string 2))
7841 (throw 'match t)))
7842 (save-excursion
7843 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7844 (setq type "tags"
7845 path (match-string 1))
7846 (while (string-match ":" path)
7847 (setq path (replace-match "+" t t path)))
7848 (throw 'match t)))
7849 (when (org-in-regexp "<\\([^><\n]+\\)>")
7850 (setq type "tree-match"
7851 path (match-string 1))
7852 (throw 'match t)))
7853 (unless path
7854 (error "No link found"))
7856 ;; switch back to reference buffer
7857 ;; needed when if called in a temporary buffer through
7858 ;; org-open-link-from-string
7859 (and reference-buffer (switch-to-buffer reference-buffer))
7861 ;; Remove any trailing spaces in path
7862 (if (string-match " +\\'" path)
7863 (setq path (replace-match "" t t path)))
7864 (if (and org-link-translation-function
7865 (fboundp org-link-translation-function))
7866 ;; Check if we need to translate the link
7867 (let ((tmp (funcall org-link-translation-function type path)))
7868 (setq type (car tmp) path (cdr tmp))))
7870 (cond
7872 ((assoc type org-link-protocols)
7873 (funcall (nth 1 (assoc type org-link-protocols)) path))
7875 ((equal type "mailto")
7876 (let ((cmd (car org-link-mailto-program))
7877 (args (cdr org-link-mailto-program)) args1
7878 (address path) (subject "") a)
7879 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7880 (setq address (match-string 1 path)
7881 subject (org-link-escape (match-string 2 path))))
7882 (while args
7883 (cond
7884 ((not (stringp (car args))) (push (pop args) args1))
7885 (t (setq a (pop args))
7886 (if (string-match "%a" a)
7887 (setq a (replace-match address t t a)))
7888 (if (string-match "%s" a)
7889 (setq a (replace-match subject t t a)))
7890 (push a args1))))
7891 (apply cmd (nreverse args1))))
7893 ((member type '("http" "https" "ftp" "news"))
7894 (browse-url (concat type ":" (org-link-escape
7895 path org-link-escape-chars-browser))))
7897 ((member type '("message"))
7898 (browse-url (concat type ":" path)))
7900 ((string= type "tags")
7901 (org-tags-view in-emacs path))
7902 ((string= type "thisfile")
7903 (if in-emacs
7904 (switch-to-buffer-other-window
7905 (org-get-buffer-for-internal-link (current-buffer)))
7906 (org-mark-ring-push))
7907 (let ((cmd `(org-link-search
7908 ,path
7909 ,(cond ((equal in-emacs '(4)) 'occur)
7910 ((equal in-emacs '(16)) 'org-occur)
7911 (t nil))
7912 ,pos)))
7913 (condition-case nil (eval cmd)
7914 (error (progn (widen) (eval cmd))))))
7916 ((string= type "tree-match")
7917 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7919 ((string= type "file")
7920 (if (string-match "::\\([0-9]+\\)\\'" path)
7921 (setq line (string-to-number (match-string 1 path))
7922 path (substring path 0 (match-beginning 0)))
7923 (if (string-match "::\\(.+\\)\\'" path)
7924 (setq search (match-string 1 path)
7925 path (substring path 0 (match-beginning 0)))))
7926 (if (string-match "[*?{]" (file-name-nondirectory path))
7927 (dired path)
7928 (org-open-file path in-emacs line search)))
7930 ((string= type "news")
7931 (require 'org-gnus)
7932 (org-gnus-follow-link path))
7934 ((string= type "shell")
7935 (let ((cmd path))
7936 (if (or (not org-confirm-shell-link-function)
7937 (funcall org-confirm-shell-link-function
7938 (format "Execute \"%s\" in shell? "
7939 (org-add-props cmd nil
7940 'face 'org-warning))))
7941 (progn
7942 (message "Executing %s" cmd)
7943 (shell-command cmd))
7944 (error "Abort"))))
7946 ((string= type "elisp")
7947 (let ((cmd path))
7948 (if (or (not org-confirm-elisp-link-function)
7949 (funcall org-confirm-elisp-link-function
7950 (format "Execute \"%s\" as elisp? "
7951 (org-add-props cmd nil
7952 'face 'org-warning))))
7953 (message "%s => %s" cmd
7954 (if (equal (string-to-char cmd) ?\()
7955 (eval (read cmd))
7956 (call-interactively (read cmd))))
7957 (error "Abort"))))
7960 (browse-url-at-point))))))
7961 (move-marker org-open-link-marker nil)
7962 (run-hook-with-args 'org-follow-link-hook))
7964 ;;;; Time estimates
7966 (defun org-get-effort (&optional pom)
7967 "Get the effort estimate for the current entry."
7968 (org-entry-get pom org-effort-property))
7970 ;;; File search
7972 (defvar org-create-file-search-functions nil
7973 "List of functions to construct the right search string for a file link.
7974 These functions are called in turn with point at the location to
7975 which the link should point.
7977 A function in the hook should first test if it would like to
7978 handle this file type, for example by checking the major-mode or
7979 the file extension. If it decides not to handle this file, it
7980 should just return nil to give other functions a chance. If it
7981 does handle the file, it must return the search string to be used
7982 when following the link. The search string will be part of the
7983 file link, given after a double colon, and `org-open-at-point'
7984 will automatically search for it. If special measures must be
7985 taken to make the search successful, another function should be
7986 added to the companion hook `org-execute-file-search-functions',
7987 which see.
7989 A function in this hook may also use `setq' to set the variable
7990 `description' to provide a suggestion for the descriptive text to
7991 be used for this link when it gets inserted into an Org-mode
7992 buffer with \\[org-insert-link].")
7994 (defvar org-execute-file-search-functions nil
7995 "List of functions to execute a file search triggered by a link.
7997 Functions added to this hook must accept a single argument, the
7998 search string that was part of the file link, the part after the
7999 double colon. The function must first check if it would like to
8000 handle this search, for example by checking the major-mode or the
8001 file extension. If it decides not to handle this search, it
8002 should just return nil to give other functions a chance. If it
8003 does handle the search, it must return a non-nil value to keep
8004 other functions from trying.
8006 Each function can access the current prefix argument through the
8007 variable `current-prefix-argument'. Note that a single prefix is
8008 used to force opening a link in Emacs, so it may be good to only
8009 use a numeric or double prefix to guide the search function.
8011 In case this is needed, a function in this hook can also restore
8012 the window configuration before `org-open-at-point' was called using:
8014 (set-window-configuration org-window-config-before-follow-link)")
8016 (defun org-link-search (s &optional type avoid-pos)
8017 "Search for a link search option.
8018 If S is surrounded by forward slashes, it is interpreted as a
8019 regular expression. In org-mode files, this will create an `org-occur'
8020 sparse tree. In ordinary files, `occur' will be used to list matches.
8021 If the current buffer is in `dired-mode', grep will be used to search
8022 in all files. If AVOID-POS is given, ignore matches near that position."
8023 (let ((case-fold-search t)
8024 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8025 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8026 (append '(("") (" ") ("\t") ("\n"))
8027 org-emphasis-alist)
8028 "\\|") "\\)"))
8029 (pos (point))
8030 (pre nil) (post nil)
8031 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8032 (cond
8033 ;; First check if there are any special
8034 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8035 ;; Now try the builtin stuff
8036 ((and (equal (string-to-char s0) ?#)
8037 (> (length s0) 1)
8038 (save-excursion
8039 (goto-char (point-min))
8040 (and
8041 (re-search-forward
8042 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8043 (setq type 'dedicated
8044 pos (match-beginning 0))))
8045 ;; There is an exact target for this
8046 (goto-char pos)
8047 (org-back-to-heading t)))
8048 ((save-excursion
8049 (goto-char (point-min))
8050 (and
8051 (re-search-forward
8052 (concat "<<" (regexp-quote s0) ">>") nil t)
8053 (setq type 'dedicated
8054 pos (match-beginning 0))))
8055 ;; There is an exact target for this
8056 (goto-char pos))
8057 ((and (string-match "^(\\(.*\\))$" s0)
8058 (save-excursion
8059 (goto-char (point-min))
8060 (and
8061 (re-search-forward
8062 (concat "[^[]" (regexp-quote
8063 (format org-coderef-label-format
8064 (match-string 1 s0))))
8065 nil t)
8066 (setq type 'dedicated
8067 pos (1+ (match-beginning 0))))))
8068 ;; There is a coderef target for this
8069 (goto-char pos))
8070 ((string-match "^/\\(.*\\)/$" s)
8071 ;; A regular expression
8072 (cond
8073 ((org-mode-p)
8074 (org-occur (match-string 1 s)))
8075 ;;((eq major-mode 'dired-mode)
8076 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8077 (t (org-do-occur (match-string 1 s)))))
8079 ;; A normal search strings
8080 (when (equal (string-to-char s) ?*)
8081 ;; Anchor on headlines, post may include tags.
8082 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8083 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8084 s (substring s 1)))
8085 (remove-text-properties
8086 0 (length s)
8087 '(face nil mouse-face nil keymap nil fontified nil) s)
8088 ;; Make a series of regular expressions to find a match
8089 (setq words (org-split-string s "[ \n\r\t]+")
8091 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8092 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8093 "\\)" markers)
8094 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8095 re2a (concat "[ \t\r\n]" re2a_)
8096 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8097 re4 (concat "[^a-zA-Z_]" re4_)
8099 re1 (concat pre re2 post)
8100 re3 (concat pre (if pre re4_ re4) post)
8101 re5 (concat pre ".*" re4)
8102 re2 (concat pre re2)
8103 re2a (concat pre (if pre re2a_ re2a))
8104 re4 (concat pre (if pre re4_ re4))
8105 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8106 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8107 re5 "\\)"
8109 (cond
8110 ((eq type 'org-occur) (org-occur reall))
8111 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8112 (t (goto-char (point-min))
8113 (setq type 'fuzzy)
8114 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8115 (org-search-not-self 1 re1 nil t)
8116 (org-search-not-self 1 re2 nil t)
8117 (org-search-not-self 1 re2a nil t)
8118 (org-search-not-self 1 re3 nil t)
8119 (org-search-not-self 1 re4 nil t)
8120 (org-search-not-self 1 re5 nil t)
8122 (goto-char (match-beginning 1))
8123 (goto-char pos)
8124 (error "No match")))))
8126 ;; Normal string-search
8127 (goto-char (point-min))
8128 (if (search-forward s nil t)
8129 (goto-char (match-beginning 0))
8130 (error "No match"))))
8131 (and (org-mode-p) (org-show-context 'link-search))
8132 type))
8134 (defun org-search-not-self (group &rest args)
8135 "Execute `re-search-forward', but only accept matches that do not
8136 enclose the position of `org-open-link-marker'."
8137 (let ((m org-open-link-marker))
8138 (catch 'exit
8139 (while (apply 're-search-forward args)
8140 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8141 (goto-char (match-end group))
8142 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8143 (> (match-beginning 0) (marker-position m))
8144 (< (match-end 0) (marker-position m)))
8145 (save-match-data
8146 (or (not (org-in-regexp
8147 org-bracket-link-analytic-regexp 1))
8148 (not (match-end 4)) ; no description
8149 (and (<= (match-beginning 4) (point))
8150 (>= (match-end 4) (point))))))
8151 (throw 'exit (point))))))))
8153 (defun org-get-buffer-for-internal-link (buffer)
8154 "Return a buffer to be used for displaying the link target of internal links."
8155 (cond
8156 ((not org-display-internal-link-with-indirect-buffer)
8157 buffer)
8158 ((string-match "(Clone)$" (buffer-name buffer))
8159 (message "Buffer is already a clone, not making another one")
8160 ;; we also do not modify visibility in this case
8161 buffer)
8162 (t ; make a new indirect buffer for displaying the link
8163 (let* ((bn (buffer-name buffer))
8164 (ibn (concat bn "(Clone)"))
8165 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8166 (with-current-buffer ib (org-overview))
8167 ib))))
8169 (defun org-do-occur (regexp &optional cleanup)
8170 "Call the Emacs command `occur'.
8171 If CLEANUP is non-nil, remove the printout of the regular expression
8172 in the *Occur* buffer. This is useful if the regex is long and not useful
8173 to read."
8174 (occur regexp)
8175 (when cleanup
8176 (let ((cwin (selected-window)) win beg end)
8177 (when (setq win (get-buffer-window "*Occur*"))
8178 (select-window win))
8179 (goto-char (point-min))
8180 (when (re-search-forward "match[a-z]+" nil t)
8181 (setq beg (match-end 0))
8182 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8183 (setq end (1- (match-beginning 0)))))
8184 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8185 (goto-char (point-min))
8186 (select-window cwin))))
8188 ;;; The mark ring for links jumps
8190 (defvar org-mark-ring nil
8191 "Mark ring for positions before jumps in Org-mode.")
8192 (defvar org-mark-ring-last-goto nil
8193 "Last position in the mark ring used to go back.")
8194 ;; Fill and close the ring
8195 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8196 (loop for i from 1 to org-mark-ring-length do
8197 (push (make-marker) org-mark-ring))
8198 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8199 org-mark-ring)
8201 (defun org-mark-ring-push (&optional pos buffer)
8202 "Put the current position or POS into the mark ring and rotate it."
8203 (interactive)
8204 (setq pos (or pos (point)))
8205 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8206 (move-marker (car org-mark-ring)
8207 (or pos (point))
8208 (or buffer (current-buffer)))
8209 (message "%s"
8210 (substitute-command-keys
8211 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8213 (defun org-mark-ring-goto (&optional n)
8214 "Jump to the previous position in the mark ring.
8215 With prefix arg N, jump back that many stored positions. When
8216 called several times in succession, walk through the entire ring.
8217 Org-mode commands jumping to a different position in the current file,
8218 or to another Org-mode file, automatically push the old position
8219 onto the ring."
8220 (interactive "p")
8221 (let (p m)
8222 (if (eq last-command this-command)
8223 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8224 (setq p org-mark-ring))
8225 (setq org-mark-ring-last-goto p)
8226 (setq m (car p))
8227 (switch-to-buffer (marker-buffer m))
8228 (goto-char m)
8229 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8231 (defun org-remove-angle-brackets (s)
8232 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8233 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8235 (defun org-add-angle-brackets (s)
8236 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8237 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8239 (defun org-remove-double-quotes (s)
8240 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8241 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8244 ;;; Following specific links
8246 (defun org-follow-timestamp-link ()
8247 (cond
8248 ((org-at-date-range-p t)
8249 (let ((org-agenda-start-on-weekday)
8250 (t1 (match-string 1))
8251 (t2 (match-string 2)))
8252 (setq t1 (time-to-days (org-time-string-to-time t1))
8253 t2 (time-to-days (org-time-string-to-time t2)))
8254 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8255 ((org-at-timestamp-p t)
8256 (org-agenda-list nil (time-to-days (org-time-string-to-time
8257 (substring (match-string 1) 0 10)))
8259 (t (error "This should not happen"))))
8262 ;;; Following file links
8263 (defvar org-wait nil)
8264 (defun org-open-file (path &optional in-emacs line search)
8265 "Open the file at PATH.
8266 First, this expands any special file name abbreviations. Then the
8267 configuration variable `org-file-apps' is checked if it contains an
8268 entry for this file type, and if yes, the corresponding command is launched.
8270 If no application is found, Emacs simply visits the file.
8272 With optional prefix argument IN-EMACS, Emacs will visit the file.
8273 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8274 and o use an external application to visit the file.
8276 Optional LINE specifies a line to go to, optional SEARCH a string to
8277 search for. If LINE or SEARCH is given, the file will always be
8278 opened in Emacs.
8279 If the file does not exist, an error is thrown."
8280 (setq in-emacs (or in-emacs line search))
8281 (let* ((file (if (equal path "")
8282 buffer-file-name
8283 (substitute-in-file-name (expand-file-name path))))
8284 (apps (append org-file-apps (org-default-apps)))
8285 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8286 (dirp (if remp nil (file-directory-p file)))
8287 (file (if (and dirp org-open-directory-means-index-dot-org)
8288 (concat (file-name-as-directory file) "index.org")
8289 file))
8290 (a-m-a-p (assq 'auto-mode apps))
8291 (dfile (downcase file))
8292 (old-buffer (current-buffer))
8293 (old-pos (point))
8294 (old-mode major-mode)
8295 ext cmd)
8296 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8297 (setq ext (match-string 1 dfile))
8298 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8299 (setq ext (match-string 1 dfile))))
8300 (cond
8301 ((equal in-emacs '(16))
8302 (setq cmd (cdr (assoc 'system apps))))
8303 (in-emacs (setq cmd 'emacs))
8305 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8306 (and dirp (cdr (assoc 'directory apps)))
8307 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8308 'string-match)
8309 (cdr (assoc ext apps))
8310 (cdr (assoc t apps))))))
8311 (when (eq cmd 'system)
8312 (setq cmd (cdr (assoc 'system apps))))
8313 (when (eq cmd 'default)
8314 (setq cmd (cdr (assoc t apps))))
8315 (when (eq cmd 'mailcap)
8316 (require 'mailcap)
8317 (mailcap-parse-mailcaps)
8318 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8319 (command (mailcap-mime-info mime-type)))
8320 (if (stringp command)
8321 (setq cmd command)
8322 (setq cmd 'emacs))))
8323 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8324 (not (file-exists-p file))
8325 (not org-open-non-existing-files))
8326 (error "No such file: %s" file))
8327 (cond
8328 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8329 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8330 (while (string-match "['\"]%s['\"]" cmd)
8331 (setq cmd (replace-match "%s" t t cmd)))
8332 (while (string-match "%s" cmd)
8333 (setq cmd (replace-match
8334 (save-match-data
8335 (shell-quote-argument
8336 (convert-standard-filename file)))
8337 t t cmd)))
8338 (save-window-excursion
8339 (start-process-shell-command cmd nil cmd)
8340 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8342 ((or (stringp cmd)
8343 (eq cmd 'emacs))
8344 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8345 (widen)
8346 (if line (goto-line line)
8347 (if search (org-link-search search))))
8348 ((consp cmd)
8349 (let ((file (convert-standard-filename file)))
8350 (eval cmd)))
8351 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8352 (and (org-mode-p) (eq old-mode 'org-mode)
8353 (or (not (equal old-buffer (current-buffer)))
8354 (not (equal old-pos (point))))
8355 (org-mark-ring-push old-pos old-buffer))))
8357 (defun org-default-apps ()
8358 "Return the default applications for this operating system."
8359 (cond
8360 ((eq system-type 'darwin)
8361 org-file-apps-defaults-macosx)
8362 ((eq system-type 'windows-nt)
8363 org-file-apps-defaults-windowsnt)
8364 (t org-file-apps-defaults-gnu)))
8366 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8367 "Convert extensions to regular expressions in the cars of LIST.
8368 Also, weed out any non-string entries, because the return value is used
8369 only for regexp matching.
8370 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8371 point to the symbol `emacs', indicating that the file should
8372 be opened in Emacs."
8373 (append
8374 (delq nil
8375 (mapcar (lambda (x)
8376 (if (not (stringp (car x)))
8378 (if (string-match "\\W" (car x))
8380 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8381 list))
8382 (if add-auto-mode
8383 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8385 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8386 (defun org-file-remote-p (file)
8387 "Test whether FILE specifies a location on a remote system.
8388 Return non-nil if the location is indeed remote.
8390 For example, the filename \"/user@host:/foo\" specifies a location
8391 on the system \"/user@host:\"."
8392 (cond ((fboundp 'file-remote-p)
8393 (file-remote-p file))
8394 ((fboundp 'tramp-handle-file-remote-p)
8395 (tramp-handle-file-remote-p file))
8396 ((and (boundp 'ange-ftp-name-format)
8397 (string-match (car ange-ftp-name-format) file))
8399 (t nil)))
8402 ;;;; Refiling
8404 (defun org-get-org-file ()
8405 "Read a filename, with default directory `org-directory'."
8406 (let ((default (or org-default-notes-file remember-data-file)))
8407 (read-file-name (format "File name [%s]: " default)
8408 (file-name-as-directory org-directory)
8409 default)))
8411 (defun org-notes-order-reversed-p ()
8412 "Check if the current file should receive notes in reversed order."
8413 (cond
8414 ((not org-reverse-note-order) nil)
8415 ((eq t org-reverse-note-order) t)
8416 ((not (listp org-reverse-note-order)) nil)
8417 (t (catch 'exit
8418 (let ((all org-reverse-note-order)
8419 entry)
8420 (while (setq entry (pop all))
8421 (if (string-match (car entry) buffer-file-name)
8422 (throw 'exit (cdr entry))))
8423 nil)))))
8425 (defvar org-refile-target-table nil
8426 "The list of refile targets, created by `org-refile'.")
8428 (defvar org-agenda-new-buffers nil
8429 "Buffers created to visit agenda files.")
8431 (defun org-get-refile-targets (&optional default-buffer)
8432 "Produce a table with refile targets."
8433 (let ((case-fold-search nil)
8434 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
8435 (entries (or org-refile-targets '((nil . (:level . 1)))))
8436 targets txt re files f desc descre fast-path-p level pos0)
8437 (message "Getting targets...")
8438 (with-current-buffer (or default-buffer (current-buffer))
8439 (while (setq entry (pop entries))
8440 (setq files (car entry) desc (cdr entry))
8441 (setq fast-path-p nil)
8442 (cond
8443 ((null files) (setq files (list (current-buffer))))
8444 ((eq files 'org-agenda-files)
8445 (setq files (org-agenda-files 'unrestricted)))
8446 ((and (symbolp files) (fboundp files))
8447 (setq files (funcall files)))
8448 ((and (symbolp files) (boundp files))
8449 (setq files (symbol-value files))))
8450 (if (stringp files) (setq files (list files)))
8451 (cond
8452 ((eq (car desc) :tag)
8453 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8454 ((eq (car desc) :todo)
8455 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8456 ((eq (car desc) :regexp)
8457 (setq descre (cdr desc)))
8458 ((eq (car desc) :level)
8459 (setq descre (concat "^\\*\\{" (number-to-string
8460 (if org-odd-levels-only
8461 (1- (* 2 (cdr desc)))
8462 (cdr desc)))
8463 "\\}[ \t]")))
8464 ((eq (car desc) :maxlevel)
8465 (setq fast-path-p t)
8466 (setq descre (concat "^\\*\\{1," (number-to-string
8467 (if org-odd-levels-only
8468 (1- (* 2 (cdr desc)))
8469 (cdr desc)))
8470 "\\}[ \t]")))
8471 (t (error "Bad refiling target description %s" desc)))
8472 (while (setq f (pop files))
8473 (save-excursion
8474 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
8475 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8476 (setq f (expand-file-name f))
8477 (if (eq org-refile-use-outline-path 'file)
8478 (push (list (file-name-nondirectory f) f nil nil) targets))
8479 (save-excursion
8480 (save-restriction
8481 (widen)
8482 (goto-char (point-min))
8483 (while (re-search-forward descre nil t)
8484 (goto-char (setq pos0 (point-at-bol)))
8485 (catch 'next
8486 (when org-refile-target-verify-function
8487 (save-match-data
8488 (or (funcall org-refile-target-verify-function)
8489 (throw 'next t))))
8490 (when (looking-at org-complex-heading-regexp)
8491 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8492 txt (org-link-display-format (match-string 4))
8493 re (concat "^" (regexp-quote
8494 (buffer-substring (match-beginning 1)
8495 (match-end 4)))))
8496 (if (match-end 5) (setq re (concat re "[ \t]+"
8497 (regexp-quote
8498 (match-string 5)))))
8499 (setq re (concat re "[ \t]*$"))
8500 (when org-refile-use-outline-path
8501 (setq txt (mapconcat 'org-protect-slash
8502 (append
8503 (if (eq org-refile-use-outline-path 'file)
8504 (list (file-name-nondirectory
8505 (buffer-file-name (buffer-base-buffer))))
8506 (if (eq org-refile-use-outline-path 'full-file-path)
8507 (list (buffer-file-name (buffer-base-buffer)))))
8508 (org-get-outline-path fast-path-p level txt)
8509 (list txt))
8510 "/")))
8511 (push (list txt f re (point)) targets)))
8512 (when (= (point) pos0)
8513 ;; verification function has not moved point
8514 (goto-char (point-at-eol))))))))))
8515 (message "Getting targets...done")
8516 (nreverse targets)))
8518 (defun org-protect-slash (s)
8519 (while (string-match "/" s)
8520 (setq s (replace-match "\\" t t s)))
8523 (defvar org-olpa (make-vector 20 nil))
8525 (defun org-get-outline-path (&optional fastp level heading)
8526 "Return the outline path to the current entry, as a list."
8527 (if fastp
8528 (progn
8529 (if (> level 19)
8530 (error "Outline path failure, more than 19 levels."))
8531 (loop for i from level upto 19 do
8532 (aset org-olpa i nil))
8533 (prog1
8534 (delq nil (append org-olpa nil))
8535 (aset org-olpa level heading)))
8536 (let (rtn)
8537 (save-excursion
8538 (while (org-up-heading-safe)
8539 (when (looking-at org-complex-heading-regexp)
8540 (push (org-match-string-no-properties 4) rtn)))
8541 rtn))))
8543 (defvar org-refile-history nil
8544 "History for refiling operations.")
8546 (defvar org-after-refile-insert-hook nil
8547 "Hook run after `org-refile' has inserted its stuff at the new location.
8548 Note that this is still *before* the stuff will be removed from
8549 the *old* location.")
8551 (defun org-refile (&optional goto default-buffer rfloc)
8552 "Move the entry at point to another heading.
8553 The list of target headings is compiled using the information in
8554 `org-refile-targets', which see. This list is created before each use
8555 and will therefore always be up-to-date.
8557 At the target location, the entry is filed as a subitem of the target heading.
8558 Depending on `org-reverse-note-order', the new subitem will either be the
8559 first or the last subitem.
8561 If there is an active region, all entries in that region will be moved.
8562 However, the region must fulfil the requirement that the first heading
8563 is the first one sets the top-level of the moved text - at most siblings
8564 below it are allowed.
8566 With prefix arg GOTO, the command will only visit the target location,
8567 not actually move anything.
8568 With a double prefix `C-u C-u', go to the location where the last refiling
8569 operation has put the subtree.
8571 RFLOC can be a refile location obtained in a different way.
8573 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
8574 (interactive "P")
8575 (let* ((cbuf (current-buffer))
8576 (regionp (org-region-active-p))
8577 (region-start (and regionp (region-beginning)))
8578 (region-end (and regionp (region-end)))
8579 (region-length (and regionp (- region-end region-start)))
8580 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8581 pos it nbuf file re level reversed)
8582 (when regionp (goto-char region-start)
8583 (unless (org-kill-is-subtree-p
8584 (buffer-substring region-start region-end))
8585 (error "The region is not a (sequence of) subtree(s)")))
8586 (if (equal goto '(16))
8587 (org-refile-goto-last-stored)
8588 (when (setq it (or rfloc
8589 (save-excursion
8590 (org-refile-get-location
8591 (if goto "Goto: " "Refile to: ") default-buffer
8592 org-refile-allow-creating-parent-nodes))))
8593 (setq file (nth 1 it)
8594 re (nth 2 it)
8595 pos (nth 3 it))
8596 (if (and (not goto)
8598 (equal (buffer-file-name) file)
8599 (if regionp
8600 (and (>= pos region-start)
8601 (<= pos region-end))
8602 (and (>= pos (point))
8603 (< pos (save-excursion
8604 (org-end-of-subtree t t))))))
8605 (error "Cannot refile to position inside the tree or region"))
8607 (setq nbuf (or (find-buffer-visiting file)
8608 (find-file-noselect file)))
8609 (if goto
8610 (progn
8611 (switch-to-buffer nbuf)
8612 (goto-char pos)
8613 (org-show-context 'org-goto))
8614 (if regionp
8615 (progn
8616 (org-kill-new (buffer-substring region-start region-end))
8617 (org-save-markers-in-region region-start region-end))
8618 (org-copy-subtree 1 nil t))
8619 (save-excursion
8620 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8621 (find-file-noselect file))))
8622 (setq reversed (org-notes-order-reversed-p))
8623 (save-excursion
8624 (save-restriction
8625 (widen)
8626 (if pos
8627 (progn
8628 (goto-char pos)
8629 (looking-at outline-regexp)
8630 (setq level (org-get-valid-level (funcall outline-level) 1))
8631 (goto-char
8632 (if reversed
8633 (or (outline-next-heading) (point-max))
8634 (or (save-excursion (outline-get-next-sibling))
8635 (org-end-of-subtree t t)
8636 (point-max)))))
8637 (setq level 1)
8638 (if (not reversed)
8639 (goto-char (point-max))
8640 (goto-char (point-min))
8641 (or (outline-next-heading) (goto-char (point-max)))))
8642 (if (not (bolp)) (newline))
8643 (bookmark-set "org-refile-last-stored")
8644 (org-paste-subtree level)
8645 (if (fboundp 'deactivate-mark) (deactivate-mark))
8646 (run-hooks 'org-after-refile-insert-hook))))
8647 (if regionp
8648 (delete-region (point) (+ (point) region-length))
8649 (org-cut-subtree))
8650 (when (featurep 'org-inlinetask)
8651 (org-inlinetask-remove-END-maybe))
8652 (setq org-markers-to-move nil)
8653 (message "Refiled to \"%s\"" (car it))))))
8654 (org-reveal))
8656 (defun org-refile-goto-last-stored ()
8657 "Go to the location where the last refile was stored."
8658 (interactive)
8659 (bookmark-jump "org-refile-last-stored")
8660 (message "This is the location of the last refile"))
8662 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
8663 "Prompt the user for a refile location, using PROMPT."
8664 (let ((org-refile-targets org-refile-targets)
8665 (org-refile-use-outline-path org-refile-use-outline-path))
8666 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8667 (unless org-refile-target-table
8668 (error "No refile targets"))
8669 (let* ((cbuf (current-buffer))
8670 (partial-completion-mode nil)
8671 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8672 (cfunc (if (and org-refile-use-outline-path
8673 org-outline-path-complete-in-steps)
8674 'org-olpath-completing-read
8675 'org-ido-completing-read))
8676 (extra (if org-refile-use-outline-path "/" ""))
8677 (filename (and cfn (expand-file-name cfn)))
8678 (tbl (mapcar
8679 (lambda (x)
8680 (if (and (not (member org-refile-use-outline-path
8681 '(file full-file-path)))
8682 (not (equal filename (nth 1 x))))
8683 (cons (concat (car x) extra " ("
8684 (file-name-nondirectory (nth 1 x)) ")")
8685 (cdr x))
8686 (cons (concat (car x) extra) (cdr x))))
8687 org-refile-target-table))
8688 (completion-ignore-case t)
8689 pa answ parent-target child parent)
8690 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
8691 nil 'org-refile-history))
8692 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
8693 (if pa
8694 (progn
8695 (setcar org-refile-history (car pa))
8697 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
8698 (setq parent (match-string 1 answ)
8699 child (match-string 2 answ))
8700 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
8701 (when (and parent-target
8702 (or (eq new-nodes t)
8703 (and (eq new-nodes 'confirm)
8704 (y-or-n-p (format "Create new node \"%s\"? " child)))))
8705 (org-refile-new-child parent-target child))))))
8707 (defun org-refile-new-child (parent-target child)
8708 "Use refile target PARENT-TARGET to add new CHILD below it."
8709 (unless parent-target
8710 (error "Cannot find parent for new node"))
8711 (let ((file (nth 1 parent-target))
8712 (pos (nth 3 parent-target))
8713 level)
8714 (with-current-buffer (or (find-buffer-visiting file)
8715 (find-file-noselect file))
8716 (save-excursion
8717 (save-restriction
8718 (widen)
8719 (if pos
8720 (goto-char pos)
8721 (goto-char (point-max))
8722 (if (not (bolp)) (newline)))
8723 (when (looking-at outline-regexp)
8724 (setq level (funcall outline-level))
8725 (org-end-of-subtree t t))
8726 (org-back-over-empty-lines)
8727 (insert "\n" (make-string
8728 (if pos (org-get-valid-level level 1) 1) ?*)
8729 " " child "\n")
8730 (beginning-of-line 0)
8731 (list (concat (car parent-target) "/" child) file "" (point)))))))
8733 (defun org-olpath-completing-read (prompt collection &rest args)
8734 "Read an outline path like a file name."
8735 (let ((thetable collection)
8736 (org-completion-use-ido nil)) ; does not work with ido.
8737 (apply
8738 'org-ido-completing-read prompt
8739 (lambda (string predicate &optional flag)
8740 (let (rtn r f (l (length string)))
8741 (cond
8742 ((eq flag nil)
8743 ;; try completion
8744 (try-completion string thetable))
8745 ((eq flag t)
8746 ;; all-completions
8747 (setq rtn (all-completions string thetable predicate))
8748 (mapcar
8749 (lambda (x)
8750 (setq r (substring x l))
8751 (if (string-match " ([^)]*)$" x)
8752 (setq f (match-string 0 x))
8753 (setq f ""))
8754 (if (string-match "/" r)
8755 (concat string (substring r 0 (match-end 0)) f)
8757 rtn))
8758 ((eq flag 'lambda)
8759 ;; exact match?
8760 (assoc string thetable)))
8762 args)))
8764 ;;;; Dynamic blocks
8766 (defun org-find-dblock (name)
8767 "Find the first dynamic block with name NAME in the buffer.
8768 If not found, stay at current position and return nil."
8769 (let (pos)
8770 (save-excursion
8771 (goto-char (point-min))
8772 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8773 nil t)
8774 (match-beginning 0))))
8775 (if pos (goto-char pos))
8776 pos))
8778 (defconst org-dblock-start-re
8779 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8780 "Matches the startline of a dynamic block, with parameters.")
8782 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8783 "Matches the end of a dynamic block.")
8785 (defun org-create-dblock (plist)
8786 "Create a dynamic block section, with parameters taken from PLIST.
8787 PLIST must contain a :name entry which is used as name of the block."
8788 (unless (bolp) (newline))
8789 (let ((name (plist-get plist :name)))
8790 (insert "#+BEGIN: " name)
8791 (while plist
8792 (if (eq (car plist) :name)
8793 (setq plist (cddr plist))
8794 (insert " " (prin1-to-string (pop plist)))))
8795 (insert "\n\n#+END:\n")
8796 (beginning-of-line -2)))
8798 (defun org-prepare-dblock ()
8799 "Prepare dynamic block for refresh.
8800 This empties the block, puts the cursor at the insert position and returns
8801 the property list including an extra property :name with the block name."
8802 (unless (looking-at org-dblock-start-re)
8803 (error "Not at a dynamic block"))
8804 (let* ((begdel (1+ (match-end 0)))
8805 (name (org-no-properties (match-string 1)))
8806 (params (append (list :name name)
8807 (read (concat "(" (match-string 3) ")")))))
8808 (unless (re-search-forward org-dblock-end-re nil t)
8809 (error "Dynamic block not terminated"))
8810 (setq params
8811 (append params
8812 (list :content (buffer-substring
8813 begdel (match-beginning 0)))))
8814 (delete-region begdel (match-beginning 0))
8815 (goto-char begdel)
8816 (open-line 1)
8817 params))
8819 (defun org-map-dblocks (&optional command)
8820 "Apply COMMAND to all dynamic blocks in the current buffer.
8821 If COMMAND is not given, use `org-update-dblock'."
8822 (let ((cmd (or command 'org-update-dblock))
8823 pos)
8824 (save-excursion
8825 (goto-char (point-min))
8826 (while (re-search-forward org-dblock-start-re nil t)
8827 (goto-char (setq pos (match-beginning 0)))
8828 (condition-case nil
8829 (funcall cmd)
8830 (error (message "Error during update of dynamic block")))
8831 (goto-char pos)
8832 (unless (re-search-forward org-dblock-end-re nil t)
8833 (error "Dynamic block not terminated"))))))
8835 (defun org-dblock-update (&optional arg)
8836 "User command for updating dynamic blocks.
8837 Update the dynamic block at point. With prefix ARG, update all dynamic
8838 blocks in the buffer."
8839 (interactive "P")
8840 (if arg
8841 (org-update-all-dblocks)
8842 (or (looking-at org-dblock-start-re)
8843 (org-beginning-of-dblock))
8844 (org-update-dblock)))
8846 (defun org-update-dblock ()
8847 "Update the dynamic block at point
8848 This means to empty the block, parse for parameters and then call
8849 the correct writing function."
8850 (save-window-excursion
8851 (let* ((pos (point))
8852 (line (org-current-line))
8853 (params (org-prepare-dblock))
8854 (name (plist-get params :name))
8855 (cmd (intern (concat "org-dblock-write:" name))))
8856 (message "Updating dynamic block `%s' at line %d..." name line)
8857 (funcall cmd params)
8858 (message "Updating dynamic block `%s' at line %d...done" name line)
8859 (goto-char pos))))
8861 (defun org-beginning-of-dblock ()
8862 "Find the beginning of the dynamic block at point.
8863 Error if there is no such block at point."
8864 (let ((pos (point))
8865 beg)
8866 (end-of-line 1)
8867 (if (and (re-search-backward org-dblock-start-re nil t)
8868 (setq beg (match-beginning 0))
8869 (re-search-forward org-dblock-end-re nil t)
8870 (> (match-end 0) pos))
8871 (goto-char beg)
8872 (goto-char pos)
8873 (error "Not in a dynamic block"))))
8875 (defun org-update-all-dblocks ()
8876 "Update all dynamic blocks in the buffer.
8877 This function can be used in a hook."
8878 (when (org-mode-p)
8879 (org-map-dblocks 'org-update-dblock)))
8882 ;;;; Completion
8884 (defconst org-additional-option-like-keywords
8885 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
8886 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
8887 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:" "ATTR_LaTeX"
8888 "BEGIN:" "END:"
8889 "ORGTBL" "TBLFM:" "TBLNAME:"
8890 "BEGIN_EXAMPLE" "END_EXAMPLE"
8891 "BEGIN_QUOTE" "END_QUOTE"
8892 "BEGIN_VERSE" "END_VERSE"
8893 "BEGIN_CENTER" "END_CENTER"
8894 "BEGIN_SRC" "END_SRC"
8895 "CATEGORY" "COLUMNS"
8896 "CAPTION" "LABEL"
8897 "BIND"))
8899 (defcustom org-structure-template-alist
8901 ("s" "#+begin_src ?\n\n#+end_src"
8902 "<src lang=\"?\">\n\n</src>")
8903 ("e" "#+begin_example\n?\n#+end_example"
8904 "<example>\n?\n</example>")
8905 ("q" "#+begin_quote\n?\n#+end_quote"
8906 "<quote>\n?\n</quote>")
8907 ("v" "#+begin_verse\n?\n#+end_verse"
8908 "<verse>\n?\n/verse>")
8909 ("c" "#+begin_center\n?\n#+end_center"
8910 "<center>\n?\n/center>")
8911 ("l" "#+begin_latex\n?\n#+end_latex"
8912 "<literal style=\"latex\">\n?\n</literal>")
8913 ("L" "#+latex: "
8914 "<literal style=\"latex\">?</literal>")
8915 ("h" "#+begin_html\n?\n#+end_html"
8916 "<literal style=\"html\">\n?\n</literal>")
8917 ("H" "#+html: "
8918 "<literal style=\"html\">?</literal>")
8919 ("a" "#+begin_ascii\n?\n#+end_ascii")
8920 ("A" "#+ascii: ")
8921 ("i" "#+include %file ?"
8922 "<include file=%file markup=\"?\">")
8924 "Structure completion elements.
8925 This is a list of abbreviation keys and values. The value gets inserted
8926 it you type @samp{.} followed by the key and then the completion key,
8927 usually `M-TAB'. %file will be replaced by a file name after prompting
8928 for the file using completion.
8929 There are two templates for each key, the first uses the original Org syntax,
8930 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8931 the default when the /org-mtags.el/ module has been loaded. See also the
8932 variable `org-mtags-prefer-muse-templates'.
8933 This is an experimental feature, it is undecided if it is going to stay in."
8934 :group 'org-completion
8935 :type '(repeat
8936 (string :tag "Key")
8937 (string :tag "Template")
8938 (string :tag "Muse Template")))
8940 (defun org-try-structure-completion ()
8941 "Try to complete a structure template before point.
8942 This looks for strings like \"<e\" on an otherwise empty line and
8943 expands them."
8944 (let ((l (buffer-substring (point-at-bol) (point)))
8946 (when (and (looking-at "[ \t]*$")
8947 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8948 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8949 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8950 (match-beginning 1)) a)
8951 t)))
8953 (defun org-complete-expand-structure-template (start cell)
8954 "Expand a structure template."
8955 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8956 (rpl (nth (if musep 2 1) cell))
8957 (ind ""))
8958 (delete-region start (point))
8959 (when (string-match "\\`#\\+" rpl)
8960 (cond
8961 ((bolp))
8962 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8963 (setq ind (buffer-substring (point-at-bol) (point))))
8964 (t (newline))))
8965 (setq start (point))
8966 (if (string-match "%file" rpl)
8967 (setq rpl (replace-match
8968 (concat
8969 "\""
8970 (save-match-data
8971 (abbreviate-file-name (read-file-name "Include file: ")))
8972 "\"")
8973 t t rpl)))
8974 (setq rpl (mapconcat 'identity (split-string rpl "\n")
8975 (concat "\n" ind)))
8976 (insert rpl)
8977 (if (re-search-backward "\\?" start t) (delete-char 1))))
8980 (defun org-complete (&optional arg)
8981 "Perform completion on word at point.
8982 At the beginning of a headline, this completes TODO keywords as given in
8983 `org-todo-keywords'.
8984 If the current word is preceded by a backslash, completes the TeX symbols
8985 that are supported for HTML support.
8986 If the current word is preceded by \"#+\", completes special words for
8987 setting file options.
8988 In the line after \"#+STARTUP:, complete valid keywords.\"
8989 At all other locations, this simply calls the value of
8990 `org-completion-fallback-command'."
8991 (interactive "P")
8992 (org-without-partial-completion
8993 (catch 'exit
8994 (let* ((a nil)
8995 (end (point))
8996 (beg1 (save-excursion
8997 (skip-chars-backward (org-re "[:alnum:]_@"))
8998 (point)))
8999 (beg (save-excursion
9000 (skip-chars-backward "a-zA-Z0-9_:$")
9001 (point)))
9002 (confirm (lambda (x) (stringp (car x))))
9003 (searchhead (equal (char-before beg) ?*))
9004 (struct
9005 (when (and (member (char-before beg1) '(?. ?<))
9006 (setq a (assoc (buffer-substring beg1 (point))
9007 org-structure-template-alist)))
9008 (org-complete-expand-structure-template (1- beg1) a)
9009 (throw 'exit t)))
9010 (tag (and (equal (char-before beg1) ?:)
9011 (equal (char-after (point-at-bol)) ?*)))
9012 (prop (and (equal (char-before beg1) ?:)
9013 (not (equal (char-after (point-at-bol)) ?*))))
9014 (texp (equal (char-before beg) ?\\))
9015 (link (equal (char-before beg) ?\[))
9016 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9017 beg)
9018 "#+"))
9019 (startup (string-match "^#\\+STARTUP:.*"
9020 (buffer-substring (point-at-bol) (point))))
9021 (completion-ignore-case opt)
9022 (type nil)
9023 (tbl nil)
9024 (table (cond
9025 (opt
9026 (setq type :opt)
9027 (require 'org-exp)
9028 (append
9029 (mapcar
9030 (lambda (x)
9031 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9032 (cons (match-string 2 x) (match-string 1 x)))
9033 (org-split-string (org-get-current-options) "\n"))
9034 (mapcar 'list org-additional-option-like-keywords)))
9035 (startup
9036 (setq type :startup)
9037 org-startup-options)
9038 (link (append org-link-abbrev-alist-local
9039 org-link-abbrev-alist))
9040 (texp
9041 (setq type :tex)
9042 org-html-entities)
9043 ((string-match "\\`\\*+[ \t]+\\'"
9044 (buffer-substring (point-at-bol) beg))
9045 (setq type :todo)
9046 (mapcar 'list org-todo-keywords-1))
9047 (searchhead
9048 (setq type :searchhead)
9049 (save-excursion
9050 (goto-char (point-min))
9051 (while (re-search-forward org-todo-line-regexp nil t)
9052 (push (list
9053 (org-make-org-heading-search-string
9054 (match-string 3) t))
9055 tbl)))
9056 tbl)
9057 (tag (setq type :tag beg beg1)
9058 (or org-tag-alist (org-get-buffer-tags)))
9059 (prop (setq type :prop beg beg1)
9060 (mapcar 'list (org-buffer-property-keys nil t t)))
9061 (t (progn
9062 (call-interactively org-completion-fallback-command)
9063 (throw 'exit nil)))))
9064 (pattern (buffer-substring-no-properties beg end))
9065 (completion (try-completion pattern table confirm)))
9066 (cond ((eq completion t)
9067 (if (not (assoc (upcase pattern) table))
9068 (message "Already complete")
9069 (if (and (equal type :opt)
9070 (not (member (car (assoc (upcase pattern) table))
9071 org-additional-option-like-keywords)))
9072 (insert (substring (cdr (assoc (upcase pattern) table))
9073 (length pattern)))
9074 (if (memq type '(:tag :prop)) (insert ":")))))
9075 ((null completion)
9076 (message "Can't find completion for \"%s\"" pattern)
9077 (ding))
9078 ((not (string= pattern completion))
9079 (delete-region beg end)
9080 (if (string-match " +$" completion)
9081 (setq completion (replace-match "" t t completion)))
9082 (insert completion)
9083 (if (get-buffer-window "*Completions*")
9084 (delete-window (get-buffer-window "*Completions*")))
9085 (if (assoc completion table)
9086 (if (eq type :todo) (insert " ")
9087 (if (memq type '(:tag :prop)) (insert ":"))))
9088 (if (and (equal type :opt) (assoc completion table))
9089 (message "%s" (substitute-command-keys
9090 "Press \\[org-complete] again to insert example settings"))))
9092 (message "Making completion list...")
9093 (let ((list (sort (all-completions pattern table confirm)
9094 'string<)))
9095 (with-output-to-temp-buffer "*Completions*"
9096 (condition-case nil
9097 ;; Protection needed for XEmacs and emacs 21
9098 (display-completion-list list pattern)
9099 (error (display-completion-list list)))))
9100 (message "Making completion list...%s" "done")))))))
9102 ;;;; TODO, DEADLINE, Comments
9104 (defun org-toggle-comment ()
9105 "Change the COMMENT state of an entry."
9106 (interactive)
9107 (save-excursion
9108 (org-back-to-heading)
9109 (let (case-fold-search)
9110 (if (looking-at (concat outline-regexp
9111 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9112 (replace-match "" t t nil 1)
9113 (if (looking-at outline-regexp)
9114 (progn
9115 (goto-char (match-end 0))
9116 (insert org-comment-string " ")))))))
9118 (defvar org-last-todo-state-is-todo nil
9119 "This is non-nil when the last TODO state change led to a TODO state.
9120 If the last change removed the TODO tag or switched to DONE, then
9121 this is nil.")
9123 (defvar org-setting-tags nil) ; dynamically skipped
9125 (defun org-parse-local-options (string var)
9126 "Parse STRING for startup setting relevant for variable VAR."
9127 (let ((rtn (symbol-value var))
9128 e opts)
9129 (save-match-data
9130 (if (or (not string) (not (string-match "\\S-" string)))
9132 (setq opts (delq nil (mapcar (lambda (x)
9133 (setq e (assoc x org-startup-options))
9134 (if (eq (nth 1 e) var) e nil))
9135 (org-split-string string "[ \t]+"))))
9136 (if (not opts)
9138 (setq rtn nil)
9139 (while (setq e (pop opts))
9140 (if (not (nth 3 e))
9141 (setq rtn (nth 2 e))
9142 (if (not (listp rtn)) (setq rtn nil))
9143 (push (nth 2 e) rtn)))
9144 rtn)))))
9146 (defvar org-todo-setup-filter-hook nil
9147 "Hook for functions that pre-filter todo specs.
9149 Each function takes a todo spec and returns either `nil' or the spec
9150 transformed into canonical form." )
9152 (defvar org-todo-get-default-hook nil
9153 "Hook for functions that get a default item for todo.
9155 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9156 `nil' or a string to be used for the todo mark." )
9158 (defvar org-agenda-headline-snapshot-before-repeat)
9160 (defun org-todo (&optional arg)
9161 "Change the TODO state of an item.
9162 The state of an item is given by a keyword at the start of the heading,
9163 like
9164 *** TODO Write paper
9165 *** DONE Call mom
9167 The different keywords are specified in the variable `org-todo-keywords'.
9168 By default the available states are \"TODO\" and \"DONE\".
9169 So for this example: when the item starts with TODO, it is changed to DONE.
9170 When it starts with DONE, the DONE is removed. And when neither TODO nor
9171 DONE are present, add TODO at the beginning of the heading.
9173 With C-u prefix arg, use completion to determine the new state.
9174 With numeric prefix arg, switch to that state.
9175 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9176 With a tripple C-u prefix, circumvent any state blocking.
9178 For calling through lisp, arg is also interpreted in the following way:
9179 'none -> empty state
9180 \"\"(empty string) -> switch to empty state
9181 'done -> switch to DONE
9182 'nextset -> switch to the next set of keywords
9183 'previousset -> switch to the previous set of keywords
9184 \"WAITING\" -> switch to the specified keyword, but only if it
9185 really is a member of `org-todo-keywords'."
9186 (interactive "P")
9187 (if (equal arg '(16)) (setq arg 'nextset))
9188 (let ((org-blocker-hook org-blocker-hook)
9189 (case-fold-search nil))
9190 (when (equal arg '(64))
9191 (setq arg nil org-blocker-hook nil))
9192 (when (and org-blocker-hook
9193 (or org-inhibit-blocking
9194 (org-entry-get nil "NOBLOCKING")))
9195 (setq org-blocker-hook nil))
9196 (save-excursion
9197 (catch 'exit
9198 (org-back-to-heading)
9199 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9200 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9201 (looking-at " *"))
9202 (let* ((match-data (match-data))
9203 (startpos (point-at-bol))
9204 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9205 (org-log-done org-log-done)
9206 (org-log-repeat org-log-repeat)
9207 (org-todo-log-states org-todo-log-states)
9208 (this (match-string 1))
9209 (hl-pos (match-beginning 0))
9210 (head (org-get-todo-sequence-head this))
9211 (ass (assoc head org-todo-kwd-alist))
9212 (interpret (nth 1 ass))
9213 (done-word (nth 3 ass))
9214 (final-done-word (nth 4 ass))
9215 (last-state (or this ""))
9216 (completion-ignore-case t)
9217 (member (member this org-todo-keywords-1))
9218 (tail (cdr member))
9219 (state (cond
9220 ((and org-todo-key-trigger
9221 (or (and (equal arg '(4))
9222 (eq org-use-fast-todo-selection 'prefix))
9223 (and (not arg) org-use-fast-todo-selection
9224 (not (eq org-use-fast-todo-selection
9225 'prefix)))))
9226 ;; Use fast selection
9227 (org-fast-todo-selection))
9228 ((and (equal arg '(4))
9229 (or (not org-use-fast-todo-selection)
9230 (not org-todo-key-trigger)))
9231 ;; Read a state with completion
9232 (org-ido-completing-read
9233 "State: " (mapcar (lambda(x) (list x))
9234 org-todo-keywords-1)
9235 nil t))
9236 ((eq arg 'right)
9237 (if this
9238 (if tail (car tail) nil)
9239 (car org-todo-keywords-1)))
9240 ((eq arg 'left)
9241 (if (equal member org-todo-keywords-1)
9243 (if this
9244 (nth (- (length org-todo-keywords-1)
9245 (length tail) 2)
9246 org-todo-keywords-1)
9247 (org-last org-todo-keywords-1))))
9248 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9249 (setq arg nil))) ; hack to fall back to cycling
9250 (arg
9251 ;; user or caller requests a specific state
9252 (cond
9253 ((equal arg "") nil)
9254 ((eq arg 'none) nil)
9255 ((eq arg 'done) (or done-word (car org-done-keywords)))
9256 ((eq arg 'nextset)
9257 (or (car (cdr (member head org-todo-heads)))
9258 (car org-todo-heads)))
9259 ((eq arg 'previousset)
9260 (let ((org-todo-heads (reverse org-todo-heads)))
9261 (or (car (cdr (member head org-todo-heads)))
9262 (car org-todo-heads))))
9263 ((car (member arg org-todo-keywords-1)))
9264 ((nth (1- (prefix-numeric-value arg))
9265 org-todo-keywords-1))))
9266 ((null member) (or head (car org-todo-keywords-1)))
9267 ((equal this final-done-word) nil) ;; -> make empty
9268 ((null tail) nil) ;; -> first entry
9269 ((memq interpret '(type priority))
9270 (if (eq this-command last-command)
9271 (car tail)
9272 (if (> (length tail) 0)
9273 (or done-word (car org-done-keywords))
9274 nil)))
9276 (car tail))))
9277 (state (or
9278 (run-hook-with-args-until-success
9279 'org-todo-get-default-hook state last-state)
9280 state))
9281 (next (if state (concat " " state " ") " "))
9282 (change-plist (list :type 'todo-state-change :from this :to state
9283 :position startpos))
9284 dolog now-done-p)
9285 (when org-blocker-hook
9286 (setq org-last-todo-state-is-todo
9287 (not (member this org-done-keywords)))
9288 (unless (save-excursion
9289 (save-match-data
9290 (run-hook-with-args-until-failure
9291 'org-blocker-hook change-plist)))
9292 (if (interactive-p)
9293 (error "TODO state change from %s to %s blocked" this state)
9294 ;; fail silently
9295 (message "TODO state change from %s to %s blocked" this state)
9296 (throw 'exit nil))))
9297 (store-match-data match-data)
9298 (replace-match next t t)
9299 (unless (pos-visible-in-window-p hl-pos)
9300 (message "TODO state changed to %s" (org-trim next)))
9301 (unless head
9302 (setq head (org-get-todo-sequence-head state)
9303 ass (assoc head org-todo-kwd-alist)
9304 interpret (nth 1 ass)
9305 done-word (nth 3 ass)
9306 final-done-word (nth 4 ass)))
9307 (when (memq arg '(nextset previousset))
9308 (message "Keyword-Set %d/%d: %s"
9309 (- (length org-todo-sets) -1
9310 (length (memq (assoc state org-todo-sets) org-todo-sets)))
9311 (length org-todo-sets)
9312 (mapconcat 'identity (assoc state org-todo-sets) " ")))
9313 (setq org-last-todo-state-is-todo
9314 (not (member state org-done-keywords)))
9315 (setq now-done-p (and (member state org-done-keywords)
9316 (not (member this org-done-keywords))))
9317 (and logging (org-local-logging logging))
9318 (when (and (or org-todo-log-states org-log-done)
9319 (not (eq org-inhibit-logging t))
9320 (not (memq arg '(nextset previousset))))
9321 ;; we need to look at recording a time and note
9322 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
9323 (nth 2 (assoc this org-todo-log-states))))
9324 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
9325 (setq dolog 'time))
9326 (when (and state
9327 (member state org-not-done-keywords)
9328 (not (member this org-not-done-keywords)))
9329 ;; This is now a todo state and was not one before
9330 ;; If there was a CLOSED time stamp, get rid of it.
9331 (org-add-planning-info nil nil 'closed))
9332 (when (and now-done-p org-log-done)
9333 ;; It is now done, and it was not done before
9334 (org-add-planning-info 'closed (org-current-time))
9335 (if (and (not dolog) (eq 'note org-log-done))
9336 (org-add-log-setup 'done state this 'findpos 'note)))
9337 (when (and state dolog)
9338 ;; This is a non-nil state, and we need to log it
9339 (org-add-log-setup 'state state this 'findpos dolog)))
9340 ;; Fixup tag positioning
9341 (org-todo-trigger-tag-changes state)
9342 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
9343 (when org-provide-todo-statistics
9344 (org-update-parent-todo-statistics))
9345 (run-hooks 'org-after-todo-state-change-hook)
9346 (if (and arg (not (member state org-done-keywords)))
9347 (setq head (org-get-todo-sequence-head state)))
9348 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9349 ;; Do we need to trigger a repeat?
9350 (when now-done-p
9351 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
9352 ;; This is for the agenda, take a snapshot of the headline.
9353 (save-match-data
9354 (setq org-agenda-headline-snapshot-before-repeat
9355 (org-get-heading))))
9356 (org-auto-repeat-maybe state))
9357 ;; Fixup cursor location if close to the keyword
9358 (if (and (outline-on-heading-p)
9359 (not (bolp))
9360 (save-excursion (beginning-of-line 1)
9361 (looking-at org-todo-line-regexp))
9362 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9363 (progn
9364 (goto-char (or (match-end 2) (match-end 1)))
9365 (and (looking-at " ") (just-one-space))))
9366 (when org-trigger-hook
9367 (save-excursion
9368 (run-hook-with-args 'org-trigger-hook change-plist))))))))
9370 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
9371 "Block turning an entry into a TODO, using the hierarchy.
9372 This checks whether the current task should be blocked from state
9373 changes. Such blocking occurs when:
9375 1. The task has children which are not all in a completed state.
9377 2. A task has a parent with the property :ORDERED:, and there
9378 are siblings prior to the current task with incomplete
9379 status.
9381 3. The parent of the task is blocked because it has siblings that should
9382 be done first, or is child of a block grandparent TODO entry."
9384 (catch 'dont-block
9385 ;; If this is not a todo state change, or if this entry is already DONE,
9386 ;; do not block
9387 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9388 (member (plist-get change-plist :from)
9389 (cons 'done org-done-keywords))
9390 (member (plist-get change-plist :to)
9391 (cons 'todo org-not-done-keywords)))
9392 (throw 'dont-block t))
9393 ;; If this task has children, and any are undone, it's blocked
9394 (save-excursion
9395 (org-back-to-heading t)
9396 (let ((this-level (funcall outline-level)))
9397 (outline-next-heading)
9398 (let ((child-level (funcall outline-level)))
9399 (while (and (not (eobp))
9400 (> child-level this-level))
9401 ;; this todo has children, check whether they are all
9402 ;; completed
9403 (if (and (not (org-entry-is-done-p))
9404 (org-entry-is-todo-p))
9405 (throw 'dont-block nil))
9406 (outline-next-heading)
9407 (setq child-level (funcall outline-level))))))
9408 ;; Otherwise, if the task's parent has the :ORDERED: property, and
9409 ;; any previous siblings are undone, it's blocked
9410 (save-excursion
9411 (org-back-to-heading t)
9412 (let* ((pos (point))
9413 (parent-pos (and (org-up-heading-safe) (point))))
9414 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9415 (when (and (org-entry-get (point) "ORDERED")
9416 (forward-line 1)
9417 (re-search-forward org-not-done-heading-regexp pos t))
9418 (throw 'dont-block nil)) ; block, there is an older sibling not done.
9419 ;; Search further up the hierarchy, to see if an anchestor is blocked
9420 (while t
9421 (goto-char parent-pos)
9422 (if (not (looking-at org-not-done-heading-regexp))
9423 (throw 'dont-block t)) ; do not block, parent is not a TODO
9424 (setq pos (point))
9425 (setq parent-pos (and (org-up-heading-safe) (point)))
9426 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9427 (when (and (org-entry-get (point) "ORDERED")
9428 (forward-line 1)
9429 (re-search-forward org-not-done-heading-regexp pos t))
9430 (throw 'dont-block nil))))))) ; block, older sibling not done.
9432 (defcustom org-track-ordered-property-with-tag nil
9433 "Should the ORDERED property also be shown as a tag?
9434 The ORDERED property decides if an entry should require subtasks to be
9435 completed in sequence. Since a property is not very visible, setting
9436 this option means that toggling the ORDERED property with the command
9437 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
9438 not relevant for the behavior, but it makes things more visible.
9440 Note that toggling the tag with tags commands will not change the property
9441 and therefore not influence behavior!
9443 This can be t, meaning the tag ORDERED should be used, It can also be a
9444 string to select a different tag for this task."
9445 :group 'org-todo
9446 :type '(choice
9447 (const :tag "No tracking" nil)
9448 (const :tag "Track with ORDERED tag" t)
9449 (string :tag "Use other tag")))
9451 (defun org-toggle-ordered-property ()
9452 "Toggle the ORDERED property of the current entry.
9453 For better visibility, you can track the value of this property with a tag.
9454 See variable `org-track-ordered-property-with-tag'."
9455 (interactive)
9456 (let* ((t1 org-track-ordered-property-with-tag)
9457 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
9458 (save-excursion
9459 (org-back-to-heading)
9460 (if (org-entry-get nil "ORDERED")
9461 (progn
9462 (org-delete-property "ORDERED")
9463 (and tag (org-toggle-tag tag 'off))
9464 (message "Subtasks can be completed in arbitrary order"))
9465 (org-entry-put nil "ORDERED" "t")
9466 (and tag (org-toggle-tag tag 'on))
9467 (message "Subtasks must be completed in sequence")))))
9469 (defvar org-blocked-by-checkboxes) ; dynamically scoped
9470 (defun org-block-todo-from-checkboxes (change-plist)
9471 "Block turning an entry into a TODO, using checkboxes.
9472 This checks whether the current task should be blocked from state
9473 changes because there are uncheckd boxes in this entry."
9474 (catch 'dont-block
9475 ;; If this is not a todo state change, or if this entry is already DONE,
9476 ;; do not block
9477 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9478 (member (plist-get change-plist :from)
9479 (cons 'done org-done-keywords))
9480 (member (plist-get change-plist :to)
9481 (cons 'todo org-not-done-keywords)))
9482 (throw 'dont-block t))
9483 ;; If this task has checkboxes that are not checked, it's blocked
9484 (save-excursion
9485 (org-back-to-heading t)
9486 (let ((beg (point)) end)
9487 (outline-next-heading)
9488 (setq end (point))
9489 (goto-char beg)
9490 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
9491 end t)
9492 (progn
9493 (if (boundp 'org-blocked-by-checkboxes)
9494 (setq org-blocked-by-checkboxes t))
9495 (throw 'dont-block nil)))))
9496 t)) ; do not block
9498 (defvar org-entry-property-inherited-from) ;; defined below
9499 (defun org-update-parent-todo-statistics ()
9500 "Update any statistics cookie in the parent of the current headline.
9501 When `org-hierarchical-todo-statistics' is nil, statistics will cover
9502 the entire subtree and this will travel up the hierarchy and update
9503 statistics everywhere."
9504 (interactive)
9505 (let* ((lim 0) prop
9506 (recursive (or (not org-hierarchical-todo-statistics)
9507 (string-match
9508 "\\<recursive\\>"
9509 (or (setq prop (org-entry-get
9510 nil "COOKIE_DATA" 'inherit)) ""))))
9511 (lim (or (and prop (marker-position
9512 org-entry-property-inherited-from))
9513 lim))
9514 (first t)
9515 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
9516 level ltoggle l1
9517 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
9518 (catch 'exit
9519 (save-excursion
9520 (beginning-of-line 1)
9521 (if (org-at-heading-p)
9522 (setq ltoggle (funcall outline-level))
9523 (error "This should not happen"))
9524 (while (and (setq level (org-up-heading-safe))
9525 (or recursive first)
9526 (>= (point) lim))
9527 (setq first nil)
9528 (unless (and level
9529 (not (string-match
9530 "\\<checkbox\\>"
9531 (downcase
9532 (or (org-entry-get
9533 nil "COOKIE_DATA")
9534 "")))))
9535 (throw 'exit nil))
9536 (while (re-search-forward box-re (point-at-eol) t)
9537 (setq cnt-all 0 cnt-done 0 cookie-present t)
9538 (setq is-percent (match-end 2))
9539 (save-match-data
9540 (unless (outline-next-heading) (throw 'exit nil))
9541 (while (and (looking-at org-complex-heading-regexp)
9542 (> (setq l1 (length (match-string 1))) level))
9543 (setq kwd (and (or recursive (= l1 ltoggle))
9544 (match-string 2)))
9545 (if (or (eq org-provide-todo-statistics 'all-headlines)
9546 (and (listp org-provide-todo-statistics)
9547 (or (member kwd org-provide-todo-statistics)
9548 (member kwd org-done-keywords))))
9549 (setq cnt-all (1+ cnt-all))
9550 (if (eq org-provide-todo-statistics t)
9551 (and kwd (setq cnt-all (1+ cnt-all)))))
9552 (and (member kwd org-done-keywords)
9553 (setq cnt-done (1+ cnt-done)))
9554 (outline-next-heading)))
9555 (replace-match
9556 (if is-percent
9557 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
9558 (format "[%d/%d]" cnt-done cnt-all)))))
9559 (when cookie-present
9560 (run-hook-with-args 'org-after-todo-statistics-hook
9561 cnt-done (- cnt-all cnt-done)))))
9562 (run-hooks 'org-todo-statistics-hook)))
9564 (defvar org-after-todo-statistics-hook nil
9565 "Hook that is called after a TODO statistics cookie has been updated.
9566 Each function is called with two arguments: the number of not-done entries
9567 and the number of done entries.
9569 For example, the following function, when added to this hook, will switch
9570 an entry to DONE when all children are done, and back to TODO when new
9571 entries are set to a TODO status. Note that this hook is only called
9572 when there is a statistics cookie in the headline!
9574 (defun org-summary-todo (n-done n-not-done)
9575 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
9576 (let (org-log-done org-log-states) ; turn off logging
9577 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
9580 (defvar org-todo-statistics-hook nil
9581 "Hook that is run whenever Org thinks TODO statistics should be updated.
9582 This hook runs even if there is no statisics cookie present, in which case
9583 `org-after-todo-statistics-hook' would not run.")
9585 (defun org-todo-trigger-tag-changes (state)
9586 "Apply the changes defined in `org-todo-state-tags-triggers'."
9587 (let ((l org-todo-state-tags-triggers)
9588 changes)
9589 (when (or (not state) (equal state ""))
9590 (setq changes (append changes (cdr (assoc "" l)))))
9591 (when (and (stringp state) (> (length state) 0))
9592 (setq changes (append changes (cdr (assoc state l)))))
9593 (when (member state org-not-done-keywords)
9594 (setq changes (append changes (cdr (assoc 'todo l)))))
9595 (when (member state org-done-keywords)
9596 (setq changes (append changes (cdr (assoc 'done l)))))
9597 (dolist (c changes)
9598 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
9600 (defun org-local-logging (value)
9601 "Get logging settings from a property VALUE."
9602 (let* (words w a)
9603 ;; directly set the variables, they are already local.
9604 (setq org-log-done nil
9605 org-log-repeat nil
9606 org-todo-log-states nil)
9607 (setq words (org-split-string value))
9608 (while (setq w (pop words))
9609 (cond
9610 ((setq a (assoc w org-startup-options))
9611 (and (member (nth 1 a) '(org-log-done org-log-repeat))
9612 (set (nth 1 a) (nth 2 a))))
9613 ((setq a (org-extract-log-state-settings w))
9614 (and (member (car a) org-todo-keywords-1)
9615 (push a org-todo-log-states)))))))
9617 (defun org-get-todo-sequence-head (kwd)
9618 "Return the head of the TODO sequence to which KWD belongs.
9619 If KWD is not set, check if there is a text property remembering the
9620 right sequence."
9621 (let (p)
9622 (cond
9623 ((not kwd)
9624 (or (get-text-property (point-at-bol) 'org-todo-head)
9625 (progn
9626 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
9627 nil (point-at-eol)))
9628 (get-text-property p 'org-todo-head))))
9629 ((not (member kwd org-todo-keywords-1))
9630 (car org-todo-keywords-1))
9631 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
9633 (defun org-fast-todo-selection ()
9634 "Fast TODO keyword selection with single keys.
9635 Returns the new TODO keyword, or nil if no state change should occur."
9636 (let* ((fulltable org-todo-key-alist)
9637 (done-keywords org-done-keywords) ;; needed for the faces.
9638 (maxlen (apply 'max (mapcar
9639 (lambda (x)
9640 (if (stringp (car x)) (string-width (car x)) 0))
9641 fulltable)))
9642 (expert nil)
9643 (fwidth (+ maxlen 3 1 3))
9644 (ncol (/ (- (window-width) 4) fwidth))
9645 tg cnt e c tbl
9646 groups ingroup)
9647 (save-excursion
9648 (save-window-excursion
9649 (if expert
9650 (set-buffer (get-buffer-create " *Org todo*"))
9651 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
9652 (erase-buffer)
9653 (org-set-local 'org-done-keywords done-keywords)
9654 (setq tbl fulltable cnt 0)
9655 (while (setq e (pop tbl))
9656 (cond
9657 ((equal e '(:startgroup))
9658 (push '() groups) (setq ingroup t)
9659 (when (not (= cnt 0))
9660 (setq cnt 0)
9661 (insert "\n"))
9662 (insert "{ "))
9663 ((equal e '(:endgroup))
9664 (setq ingroup nil cnt 0)
9665 (insert "}\n"))
9666 ((equal e '(:newline))
9667 (when (not (= cnt 0))
9668 (setq cnt 0)
9669 (insert "\n")
9670 (setq e (car tbl))
9671 (while (equal (car tbl) '(:newline))
9672 (insert "\n")
9673 (setq tbl (cdr tbl)))))
9675 (setq tg (car e) c (cdr e))
9676 (if ingroup (push tg (car groups)))
9677 (setq tg (org-add-props tg nil 'face
9678 (org-get-todo-face tg)))
9679 (if (and (= cnt 0) (not ingroup)) (insert " "))
9680 (insert "[" c "] " tg (make-string
9681 (- fwidth 4 (length tg)) ?\ ))
9682 (when (= (setq cnt (1+ cnt)) ncol)
9683 (insert "\n")
9684 (if ingroup (insert " "))
9685 (setq cnt 0)))))
9686 (insert "\n")
9687 (goto-char (point-min))
9688 (if (not expert) (org-fit-window-to-buffer))
9689 (message "[a-z..]:Set [SPC]:clear")
9690 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9691 (cond
9692 ((or (= c ?\C-g)
9693 (and (= c ?q) (not (rassoc c fulltable))))
9694 (setq quit-flag t))
9695 ((= c ?\ ) nil)
9696 ((setq e (rassoc c fulltable) tg (car e))
9698 (t (setq quit-flag t)))))))
9700 (defun org-entry-is-todo-p ()
9701 (member (org-get-todo-state) org-not-done-keywords))
9703 (defun org-entry-is-done-p ()
9704 (member (org-get-todo-state) org-done-keywords))
9706 (defun org-get-todo-state ()
9707 (save-excursion
9708 (org-back-to-heading t)
9709 (and (looking-at org-todo-line-regexp)
9710 (match-end 2)
9711 (match-string 2))))
9713 (defun org-at-date-range-p (&optional inactive-ok)
9714 "Is the cursor inside a date range?"
9715 (interactive)
9716 (save-excursion
9717 (catch 'exit
9718 (let ((pos (point)))
9719 (skip-chars-backward "^[<\r\n")
9720 (skip-chars-backward "<[")
9721 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9722 (>= (match-end 0) pos)
9723 (throw 'exit t))
9724 (skip-chars-backward "^<[\r\n")
9725 (skip-chars-backward "<[")
9726 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9727 (>= (match-end 0) pos)
9728 (throw 'exit t)))
9729 nil)))
9731 (defun org-get-repeat ()
9732 "Check if there is a deadline/schedule with repeater in this entry."
9733 (save-match-data
9734 (save-excursion
9735 (org-back-to-heading t)
9736 (if (re-search-forward
9737 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9738 (match-string 1)))))
9740 (defvar org-last-changed-timestamp)
9741 (defvar org-last-inserted-timestamp)
9742 (defvar org-log-post-message)
9743 (defvar org-log-note-purpose)
9744 (defvar org-log-note-how)
9745 (defvar org-log-note-extra)
9746 (defun org-auto-repeat-maybe (done-word)
9747 "Check if the current headline contains a repeated deadline/schedule.
9748 If yes, set TODO state back to what it was and change the base date
9749 of repeating deadline/scheduled time stamps to new date.
9750 This function is run automatically after each state change to a DONE state."
9751 ;; last-state is dynamically scoped into this function
9752 (let* ((repeat (org-get-repeat))
9753 (aa (assoc last-state org-todo-kwd-alist))
9754 (interpret (nth 1 aa))
9755 (head (nth 2 aa))
9756 (whata '(("d" . day) ("m" . month) ("y" . year)))
9757 (msg "Entry repeats: ")
9758 (org-log-done nil)
9759 (org-todo-log-states nil)
9760 (nshiftmax 10) (nshift 0)
9761 re type n what ts time)
9762 (when repeat
9763 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9764 (org-todo (if (eq interpret 'type) last-state head))
9765 (org-entry-put nil "LAST_REPEAT" (format-time-string
9766 (org-time-stamp-format t t)))
9767 (when org-log-repeat
9768 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9769 (memq 'org-add-log-note post-command-hook))
9770 ;; OK, we are already setup for some record
9771 (if (eq org-log-repeat 'note)
9772 ;; make sure we take a note, not only a time stamp
9773 (setq org-log-note-how 'note))
9774 ;; Set up for taking a record
9775 (org-add-log-setup 'state (or done-word (car org-done-keywords))
9776 last-state
9777 'findpos org-log-repeat)))
9778 (org-back-to-heading t)
9779 (org-add-planning-info nil nil 'closed)
9780 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9781 org-deadline-time-regexp "\\)\\|\\("
9782 org-ts-regexp "\\)"))
9783 (while (re-search-forward
9784 re (save-excursion (outline-next-heading) (point)) t)
9785 (setq type (if (match-end 1) org-scheduled-string
9786 (if (match-end 3) org-deadline-string "Plain:"))
9787 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
9788 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
9789 (setq n (string-to-number (match-string 2 ts))
9790 what (match-string 3 ts))
9791 (if (equal what "w") (setq n (* n 7) what "d"))
9792 ;; Preparation, see if we need to modify the start date for the change
9793 (when (match-end 1)
9794 (setq time (save-match-data (org-time-string-to-time ts)))
9795 (cond
9796 ((equal (match-string 1 ts) ".")
9797 ;; Shift starting date to today
9798 (org-timestamp-change
9799 (- (time-to-days (current-time)) (time-to-days time))
9800 'day))
9801 ((equal (match-string 1 ts) "+")
9802 (while (or (= nshift 0)
9803 (<= (time-to-days time) (time-to-days (current-time))))
9804 (when (= (incf nshift) nshiftmax)
9805 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
9806 (error "Abort")))
9807 (org-timestamp-change n (cdr (assoc what whata)))
9808 (org-at-timestamp-p t)
9809 (setq ts (match-string 1))
9810 (setq time (save-match-data (org-time-string-to-time ts))))
9811 (org-timestamp-change (- n) (cdr (assoc what whata)))
9812 ;; rematch, so that we have everything in place for the real shift
9813 (org-at-timestamp-p t)
9814 (setq ts (match-string 1))
9815 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
9816 (org-timestamp-change n (cdr (assoc what whata)))
9817 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
9818 (setq org-log-post-message msg)
9819 (message "%s" msg))))
9821 (defun org-show-todo-tree (arg)
9822 "Make a compact tree which shows all headlines marked with TODO.
9823 The tree will show the lines where the regexp matches, and all higher
9824 headlines above the match.
9825 With a \\[universal-argument] prefix, prompt for a regexp to match.
9826 With a numeric prefix N, construct a sparse tree for the Nth element
9827 of `org-todo-keywords-1'."
9828 (interactive "P")
9829 (let ((case-fold-search nil)
9830 (kwd-re
9831 (cond ((null arg) org-not-done-regexp)
9832 ((equal arg '(4))
9833 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
9834 (mapcar 'list org-todo-keywords-1))))
9835 (concat "\\("
9836 (mapconcat 'identity (org-split-string kwd "|") "\\|")
9837 "\\)\\>")))
9838 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
9839 (regexp-quote (nth (1- (prefix-numeric-value arg))
9840 org-todo-keywords-1)))
9841 (t (error "Invalid prefix argument: %s" arg)))))
9842 (message "%d TODO entries found"
9843 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
9845 (defun org-deadline (&optional remove time)
9846 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
9847 With argument REMOVE, remove any deadline from the item.
9848 When TIME is set, it should be an internal time specification, and the
9849 scheduling will use the corresponding date."
9850 (interactive "P")
9851 (if remove
9852 (progn
9853 (org-remove-timestamp-with-keyword org-deadline-string)
9854 (message "Item no longer has a deadline."))
9855 (if (org-get-repeat)
9856 (error "Cannot change deadline on task with repeater, please do that by hand")
9857 (org-add-planning-info 'deadline time 'closed)
9858 (message "Deadline on %s" org-last-inserted-timestamp))))
9860 (defun org-schedule (&optional remove time)
9861 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
9862 With argument REMOVE, remove any scheduling date from the item.
9863 When TIME is set, it should be an internal time specification, and the
9864 scheduling will use the corresponding date."
9865 (interactive "P")
9866 (if remove
9867 (progn
9868 (org-remove-timestamp-with-keyword org-scheduled-string)
9869 (message "Item is no longer scheduled."))
9870 (if (org-get-repeat)
9871 (error "Cannot reschedule task with repeater, please do that by hand")
9872 (org-add-planning-info 'scheduled time 'closed)
9873 (message "Scheduled to %s" org-last-inserted-timestamp))))
9875 (defun org-get-scheduled-time (pom &optional inherit)
9876 "Get the scheduled time as a time tuple, of a format suitable
9877 for calling org-schedule with, or if there is no scheduling,
9878 returns nil."
9879 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
9880 (when time
9881 (apply 'encode-time (org-parse-time-string time)))))
9883 (defun org-get-deadline-time (pom &optional inherit)
9884 "Get the deadine as a time tuple, of a format suitable for
9885 calling org-deadlin with, or if there is no scheduling, returns
9886 nil."
9887 (let ((time (org-entry-get pom "DEADLINE" inherit)))
9888 (when time
9889 (apply 'encode-time (org-parse-time-string time)))))
9891 (defun org-remove-timestamp-with-keyword (keyword)
9892 "Remove all time stamps with KEYWORD in the current entry."
9893 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
9894 beg)
9895 (save-excursion
9896 (org-back-to-heading t)
9897 (setq beg (point))
9898 (org-end-of-subtree t t)
9899 (while (re-search-backward re beg t)
9900 (replace-match "")
9901 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9902 (equal (char-before) ?\ ))
9903 (backward-delete-char 1)
9904 (if (string-match "^[ \t]*$" (buffer-substring
9905 (point-at-bol) (point-at-eol)))
9906 (delete-region (point-at-bol)
9907 (min (point-max) (1+ (point-at-eol))))))))))
9909 (defun org-add-planning-info (what &optional time &rest remove)
9910 "Insert new timestamp with keyword in the line directly after the headline.
9911 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9912 If non is given, the user is prompted for a date.
9913 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9914 be removed."
9915 (interactive)
9916 (let (org-time-was-given org-end-time-was-given ts
9917 end default-time default-input)
9919 (catch 'exit
9920 (when (and (not time) (memq what '(scheduled deadline)))
9921 ;; Try to get a default date/time from existing timestamp
9922 (save-excursion
9923 (org-back-to-heading t)
9924 (setq end (save-excursion (outline-next-heading) (point)))
9925 (when (re-search-forward (if (eq what 'scheduled)
9926 org-scheduled-time-regexp
9927 org-deadline-time-regexp)
9928 end t)
9929 (setq ts (match-string 1)
9930 default-time
9931 (apply 'encode-time (org-parse-time-string ts))
9932 default-input (and ts (org-get-compact-tod ts))))))
9933 (when what
9934 ;; If necessary, get the time from the user
9935 (setq time (or time (org-read-date nil 'to-time nil nil
9936 default-time default-input))))
9938 (when (and org-insert-labeled-timestamps-at-point
9939 (member what '(scheduled deadline)))
9940 (insert
9941 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9942 (org-insert-time-stamp time org-time-was-given
9943 nil nil nil (list org-end-time-was-given))
9944 (setq what nil))
9945 (save-excursion
9946 (save-restriction
9947 (let (col list elt ts buffer-invisibility-spec)
9948 (org-back-to-heading t)
9949 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9950 (goto-char (match-end 1))
9951 (setq col (current-column))
9952 (goto-char (match-end 0))
9953 (if (eobp) (insert "\n") (forward-char 1))
9954 (when (and (not what)
9955 (not (looking-at
9956 (concat "[ \t]*"
9957 org-keyword-time-not-clock-regexp))))
9958 ;; Nothing to add, nothing to remove...... :-)
9959 (throw 'exit nil))
9960 (if (and (not (looking-at outline-regexp))
9961 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9962 "[^\r\n]*"))
9963 (not (equal (match-string 1) org-clock-string)))
9964 (narrow-to-region (match-beginning 0) (match-end 0))
9965 (insert-before-markers "\n")
9966 (backward-char 1)
9967 (narrow-to-region (point) (point))
9968 (and org-adapt-indentation (org-indent-to-column col)))
9969 ;; Check if we have to remove something.
9970 (setq list (cons what remove))
9971 (while list
9972 (setq elt (pop list))
9973 (goto-char (point-min))
9974 (when (or (and (eq elt 'scheduled)
9975 (re-search-forward org-scheduled-time-regexp nil t))
9976 (and (eq elt 'deadline)
9977 (re-search-forward org-deadline-time-regexp nil t))
9978 (and (eq elt 'closed)
9979 (re-search-forward org-closed-time-regexp nil t)))
9980 (replace-match "")
9981 (if (looking-at "--+<[^>]+>") (replace-match ""))
9982 (if (looking-at " +") (replace-match ""))))
9983 (goto-char (point-max))
9984 (when what
9985 (insert
9986 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9987 (cond ((eq what 'scheduled) org-scheduled-string)
9988 ((eq what 'deadline) org-deadline-string)
9989 ((eq what 'closed) org-closed-string))
9990 " ")
9991 (setq ts (org-insert-time-stamp
9992 time
9993 (or org-time-was-given
9994 (and (eq what 'closed) org-log-done-with-time))
9995 (eq what 'closed)
9996 nil nil (list org-end-time-was-given)))
9997 (end-of-line 1))
9998 (goto-char (point-min))
9999 (widen)
10000 (if (and (looking-at "[ \t]+\n")
10001 (equal (char-before) ?\n))
10002 (delete-region (1- (point)) (point-at-eol)))
10003 ts))))))
10005 (defvar org-log-note-marker (make-marker))
10006 (defvar org-log-note-purpose nil)
10007 (defvar org-log-note-state nil)
10008 (defvar org-log-note-previous-state nil)
10009 (defvar org-log-note-how nil)
10010 (defvar org-log-note-extra nil)
10011 (defvar org-log-note-window-configuration nil)
10012 (defvar org-log-note-return-to (make-marker))
10013 (defvar org-log-post-message nil
10014 "Message to be displayed after a log note has been stored.
10015 The auto-repeater uses this.")
10017 (defun org-add-note ()
10018 "Add a note to the current entry.
10019 This is done in the same way as adding a state change note."
10020 (interactive)
10021 (org-add-log-setup 'note nil nil 'findpos nil))
10023 (defvar org-property-end-re)
10024 (defun org-add-log-setup (&optional purpose state prev-state
10025 findpos how &optional extra)
10026 "Set up the post command hook to take a note.
10027 If this is about to TODO state change, the new state is expected in STATE.
10028 When FINDPOS is non-nil, find the correct position for the note in
10029 the current entry. If not, assume that it can be inserted at point.
10030 HOW is an indicator what kind of note should be created.
10031 EXTRA is additional text that will be inserted into the notes buffer."
10032 (let* ((org-log-into-drawer (org-log-into-drawer))
10033 (drawer (cond ((stringp org-log-into-drawer)
10034 org-log-into-drawer)
10035 (org-log-into-drawer "LOGBOOK")
10036 (t nil))))
10037 (save-restriction
10038 (save-excursion
10039 (when findpos
10040 (org-back-to-heading t)
10041 (narrow-to-region (point) (save-excursion
10042 (outline-next-heading) (point)))
10043 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
10044 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
10045 "[^\r\n]*\\)?"))
10046 (goto-char (match-end 0))
10047 (cond
10048 (drawer
10049 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
10050 nil t)
10051 (progn
10052 (goto-char (match-end 0))
10053 (or org-log-states-order-reversed
10054 (and (re-search-forward org-property-end-re nil t)
10055 (goto-char (1- (match-beginning 0))))))
10056 (insert "\n:" drawer ":\n:END:")
10057 (beginning-of-line 0)
10058 (org-indent-line-function)
10059 (beginning-of-line 2)
10060 (org-indent-line-function)
10061 (end-of-line 0)))
10062 ((and org-log-state-notes-insert-after-drawers
10063 (save-excursion
10064 (forward-line) (looking-at org-drawer-regexp)))
10065 (forward-line)
10066 (while (looking-at org-drawer-regexp)
10067 (goto-char (match-end 0))
10068 (re-search-forward org-property-end-re (point-max) t)
10069 (forward-line))
10070 (forward-line -1)))
10071 (unless org-log-states-order-reversed
10072 (and (= (char-after) ?\n) (forward-char 1))
10073 (org-skip-over-state-notes)
10074 (skip-chars-backward " \t\n\r")))
10075 (move-marker org-log-note-marker (point))
10076 (setq org-log-note-purpose purpose
10077 org-log-note-state state
10078 org-log-note-previous-state prev-state
10079 org-log-note-how how
10080 org-log-note-extra extra)
10081 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
10083 (defun org-skip-over-state-notes ()
10084 "Skip past the list of State notes in an entry."
10085 (if (looking-at "\n[ \t]*- State") (forward-char 1))
10086 (while (looking-at "[ \t]*- State")
10087 (condition-case nil
10088 (org-next-item)
10089 (error (org-end-of-item)))))
10091 (defun org-add-log-note (&optional purpose)
10092 "Pop up a window for taking a note, and add this note later at point."
10093 (remove-hook 'post-command-hook 'org-add-log-note)
10094 (setq org-log-note-window-configuration (current-window-configuration))
10095 (delete-other-windows)
10096 (move-marker org-log-note-return-to (point))
10097 (switch-to-buffer (marker-buffer org-log-note-marker))
10098 (goto-char org-log-note-marker)
10099 (org-switch-to-buffer-other-window "*Org Note*")
10100 (erase-buffer)
10101 (if (memq org-log-note-how '(time state))
10102 (let (current-prefix-arg) (org-store-log-note))
10103 (let ((org-inhibit-startup t)) (org-mode))
10104 (insert (format "# Insert note for %s.
10105 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10106 (cond
10107 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10108 ((eq org-log-note-purpose 'done) "closed todo item")
10109 ((eq org-log-note-purpose 'state)
10110 (format "state change from \"%s\" to \"%s\""
10111 (or org-log-note-previous-state "")
10112 (or org-log-note-state "")))
10113 ((eq org-log-note-purpose 'note)
10114 "this entry")
10115 (t (error "This should not happen")))))
10116 (if org-log-note-extra (insert org-log-note-extra))
10117 (org-set-local 'org-finish-function 'org-store-log-note)))
10119 (defvar org-note-abort nil) ; dynamically scoped
10120 (defun org-store-log-note ()
10121 "Finish taking a log note, and insert it to where it belongs."
10122 (let ((txt (buffer-string))
10123 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10124 lines ind)
10125 (kill-buffer (current-buffer))
10126 (while (string-match "\\`#.*\n[ \t\n]*" txt)
10127 (setq txt (replace-match "" t t txt)))
10128 (if (string-match "\\s-+\\'" txt)
10129 (setq txt (replace-match "" t t txt)))
10130 (setq lines (org-split-string txt "\n"))
10131 (when (and note (string-match "\\S-" note))
10132 (setq note
10133 (org-replace-escapes
10134 note
10135 (list (cons "%u" (user-login-name))
10136 (cons "%U" user-full-name)
10137 (cons "%t" (format-time-string
10138 (org-time-stamp-format 'long 'inactive)
10139 (current-time)))
10140 (cons "%s" (if org-log-note-state
10141 (concat "\"" org-log-note-state "\"")
10142 ""))
10143 (cons "%S" (if org-log-note-previous-state
10144 (concat "\"" org-log-note-previous-state "\"")
10145 "\"\"")))))
10146 (if lines (setq note (concat note " \\\\")))
10147 (push note lines))
10148 (when (or current-prefix-arg org-note-abort)
10149 (when org-log-into-drawer
10150 (org-remove-empty-drawer-at
10151 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
10152 org-log-note-marker))
10153 (setq lines nil))
10154 (when lines
10155 (save-excursion
10156 (set-buffer (marker-buffer org-log-note-marker))
10157 (save-excursion
10158 (goto-char org-log-note-marker)
10159 (move-marker org-log-note-marker nil)
10160 (end-of-line 1)
10161 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
10162 (insert "- " (pop lines))
10163 (org-indent-line-function)
10164 (beginning-of-line 1)
10165 (looking-at "[ \t]*")
10166 (setq ind (concat (match-string 0) " "))
10167 (end-of-line 1)
10168 (while lines (insert "\n" ind (pop lines)))
10169 (message "Note stored")
10170 (org-back-to-heading t)
10171 (org-cycle-hide-drawers 'children)))))
10172 (set-window-configuration org-log-note-window-configuration)
10173 (with-current-buffer (marker-buffer org-log-note-return-to)
10174 (goto-char org-log-note-return-to))
10175 (move-marker org-log-note-return-to nil)
10176 (and org-log-post-message (message "%s" org-log-post-message)))
10178 (defun org-remove-empty-drawer-at (drawer pos)
10179 "Remove an emptyr DARWER drawer at position POS.
10180 POS may also be a marker."
10181 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
10182 (save-excursion
10183 (save-restriction
10184 (widen)
10185 (goto-char pos)
10186 (if (org-in-regexp
10187 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
10188 (replace-match ""))))))
10190 (defun org-sparse-tree (&optional arg)
10191 "Create a sparse tree, prompt for the details.
10192 This command can create sparse trees. You first need to select the type
10193 of match used to create the tree:
10195 t Show entries with a specific TODO keyword.
10196 m Show entries selected by a tags/property match.
10197 p Enter a property name and its value (both with completion on existing
10198 names/values) and show entries with that property.
10199 r Show entries matching a regular expression.
10200 d Show deadlines due within `org-deadline-warning-days'.
10201 b Show deadlines and scheduled items before a date.
10202 a Show deadlines and scheduled items after a date."
10203 (interactive "P")
10204 (let (ans kwd value)
10205 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
10206 (setq ans (read-char-exclusive))
10207 (cond
10208 ((equal ans ?d)
10209 (call-interactively 'org-check-deadlines))
10210 ((equal ans ?b)
10211 (call-interactively 'org-check-before-date))
10212 ((equal ans ?a)
10213 (call-interactively 'org-check-after-date))
10214 ((equal ans ?t)
10215 (org-show-todo-tree '(4)))
10216 ((member ans '(?T ?m))
10217 (call-interactively 'org-match-sparse-tree))
10218 ((member ans '(?p ?P))
10219 (setq kwd (org-ido-completing-read "Property: "
10220 (mapcar 'list (org-buffer-property-keys))))
10221 (setq value (org-ido-completing-read "Value: "
10222 (mapcar 'list (org-property-values kwd))))
10223 (unless (string-match "\\`{.*}\\'" value)
10224 (setq value (concat "\"" value "\"")))
10225 (org-match-sparse-tree arg (concat kwd "=" value)))
10226 ((member ans '(?r ?R ?/))
10227 (call-interactively 'org-occur))
10228 (t (error "No such sparse tree command \"%c\"" ans)))))
10230 (defvar org-occur-highlights nil
10231 "List of overlays used for occur matches.")
10232 (make-variable-buffer-local 'org-occur-highlights)
10233 (defvar org-occur-parameters nil
10234 "Parameters of the active org-occur calls.
10235 This is a list, each call to org-occur pushes as cons cell,
10236 containing the regular expression and the callback, onto the list.
10237 The list can contain several entries if `org-occur' has been called
10238 several time with the KEEP-PREVIOUS argument. Otherwise, this list
10239 will only contain one set of parameters. When the highlights are
10240 removed (for example with `C-c C-c', or with the next edit (depending
10241 on `org-remove-highlights-with-change'), this variable is emptied
10242 as well.")
10243 (make-variable-buffer-local 'org-occur-parameters)
10245 (defun org-occur (regexp &optional keep-previous callback)
10246 "Make a compact tree which shows all matches of REGEXP.
10247 The tree will show the lines where the regexp matches, and all higher
10248 headlines above the match. It will also show the heading after the match,
10249 to make sure editing the matching entry is easy.
10250 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
10251 call to `org-occur' will be kept, to allow stacking of calls to this
10252 command.
10253 If CALLBACK is non-nil, it is a function which is called to confirm
10254 that the match should indeed be shown."
10255 (interactive "sRegexp: \nP")
10256 (when (equal regexp "")
10257 (error "Regexp cannot be empty"))
10258 (unless keep-previous
10259 (org-remove-occur-highlights nil nil t))
10260 (push (cons regexp callback) org-occur-parameters)
10261 (let ((cnt 0))
10262 (save-excursion
10263 (goto-char (point-min))
10264 (if (or (not keep-previous) ; do not want to keep
10265 (not org-occur-highlights)) ; no previous matches
10266 ;; hide everything
10267 (org-overview))
10268 (while (re-search-forward regexp nil t)
10269 (when (or (not callback)
10270 (save-match-data (funcall callback)))
10271 (setq cnt (1+ cnt))
10272 (when org-highlight-sparse-tree-matches
10273 (org-highlight-new-match (match-beginning 0) (match-end 0)))
10274 (org-show-context 'occur-tree))))
10275 (when org-remove-highlights-with-change
10276 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10277 nil 'local))
10278 (unless org-sparse-tree-open-archived-trees
10279 (org-hide-archived-subtrees (point-min) (point-max)))
10280 (run-hooks 'org-occur-hook)
10281 (if (interactive-p)
10282 (message "%d match(es) for regexp %s" cnt regexp))
10283 cnt))
10285 (defun org-show-context (&optional key)
10286 "Make sure point and context and visible.
10287 How much context is shown depends upon the variables
10288 `org-show-hierarchy-above', `org-show-following-heading'. and
10289 `org-show-siblings'."
10290 (let ((heading-p (org-on-heading-p t))
10291 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
10292 (following-p (org-get-alist-option org-show-following-heading key))
10293 (entry-p (org-get-alist-option org-show-entry-below key))
10294 (siblings-p (org-get-alist-option org-show-siblings key)))
10295 (catch 'exit
10296 ;; Show heading or entry text
10297 (if (and heading-p (not entry-p))
10298 (org-flag-heading nil) ; only show the heading
10299 (and (or entry-p (org-invisible-p) (org-invisible-p2))
10300 (org-show-hidden-entry))) ; show entire entry
10301 (when following-p
10302 ;; Show next sibling, or heading below text
10303 (save-excursion
10304 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10305 (org-flag-heading nil))))
10306 (when siblings-p (org-show-siblings))
10307 (when hierarchy-p
10308 ;; show all higher headings, possibly with siblings
10309 (save-excursion
10310 (while (and (condition-case nil
10311 (progn (org-up-heading-all 1) t)
10312 (error nil))
10313 (not (bobp)))
10314 (org-flag-heading nil)
10315 (when siblings-p (org-show-siblings))))))))
10317 (defun org-reveal (&optional siblings)
10318 "Show current entry, hierarchy above it, and the following headline.
10319 This can be used to show a consistent set of context around locations
10320 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10321 not t for the search context.
10323 With optional argument SIBLINGS, on each level of the hierarchy all
10324 siblings are shown. This repairs the tree structure to what it would
10325 look like when opened with hierarchical calls to `org-cycle'."
10326 (interactive "P")
10327 (let ((org-show-hierarchy-above t)
10328 (org-show-following-heading t)
10329 (org-show-siblings (if siblings t org-show-siblings)))
10330 (org-show-context nil)))
10332 (defun org-highlight-new-match (beg end)
10333 "Highlight from BEG to END and mark the highlight is an occur headline."
10334 (let ((ov (org-make-overlay beg end)))
10335 (org-overlay-put ov 'face 'secondary-selection)
10336 (push ov org-occur-highlights)))
10338 (defun org-remove-occur-highlights (&optional beg end noremove)
10339 "Remove the occur highlights from the buffer.
10340 BEG and END are ignored. If NOREMOVE is nil, remove this function
10341 from the `before-change-functions' in the current buffer."
10342 (interactive)
10343 (unless org-inhibit-highlight-removal
10344 (mapc 'org-delete-overlay org-occur-highlights)
10345 (setq org-occur-highlights nil)
10346 (setq org-occur-parameters nil)
10347 (unless noremove
10348 (remove-hook 'before-change-functions
10349 'org-remove-occur-highlights 'local))))
10351 ;;;; Priorities
10353 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
10354 "Regular expression matching the priority indicator.")
10356 (defvar org-remove-priority-next-time nil)
10358 (defun org-priority-up ()
10359 "Increase the priority of the current item."
10360 (interactive)
10361 (org-priority 'up))
10363 (defun org-priority-down ()
10364 "Decrease the priority of the current item."
10365 (interactive)
10366 (org-priority 'down))
10368 (defun org-priority (&optional action)
10369 "Change the priority of an item by ARG.
10370 ACTION can be `set', `up', `down', or a character."
10371 (interactive)
10372 (unless org-enable-priority-commands
10373 (error "Priority commands are disabled"))
10374 (setq action (or action 'set))
10375 (let (current new news have remove)
10376 (save-excursion
10377 (org-back-to-heading t)
10378 (if (looking-at org-priority-regexp)
10379 (setq current (string-to-char (match-string 2))
10380 have t)
10381 (setq current org-default-priority))
10382 (cond
10383 ((or (eq action 'set)
10384 (if (featurep 'xemacs) (characterp action) (integerp action)))
10385 (if (not (eq action 'set))
10386 (setq new action)
10387 (message "Priority %c-%c, SPC to remove: "
10388 org-highest-priority org-lowest-priority)
10389 (setq new (read-char-exclusive)))
10390 (if (and (= (upcase org-highest-priority) org-highest-priority)
10391 (= (upcase org-lowest-priority) org-lowest-priority))
10392 (setq new (upcase new)))
10393 (cond ((equal new ?\ ) (setq remove t))
10394 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
10395 (error "Priority must be between `%c' and `%c'"
10396 org-highest-priority org-lowest-priority))))
10397 ((eq action 'up)
10398 (if (and (not have) (eq last-command this-command))
10399 (setq new org-lowest-priority)
10400 (setq new (if (and org-priority-start-cycle-with-default (not have))
10401 org-default-priority (1- current)))))
10402 ((eq action 'down)
10403 (if (and (not have) (eq last-command this-command))
10404 (setq new org-highest-priority)
10405 (setq new (if (and org-priority-start-cycle-with-default (not have))
10406 org-default-priority (1+ current)))))
10407 (t (error "Invalid action")))
10408 (if (or (< (upcase new) org-highest-priority)
10409 (> (upcase new) org-lowest-priority))
10410 (setq remove t))
10411 (setq news (format "%c" new))
10412 (if have
10413 (if remove
10414 (replace-match "" t t nil 1)
10415 (replace-match news t t nil 2))
10416 (if remove
10417 (error "No priority cookie found in line")
10418 (let ((case-fold-search nil))
10419 (looking-at org-todo-line-regexp))
10420 (if (match-end 2)
10421 (progn
10422 (goto-char (match-end 2))
10423 (insert " [#" news "]"))
10424 (goto-char (match-beginning 3))
10425 (insert "[#" news "] "))))
10426 (org-preserve-lc (org-set-tags nil 'align)))
10427 (if remove
10428 (message "Priority removed")
10429 (message "Priority of current item set to %s" news))))
10431 (defun org-get-priority (s)
10432 "Find priority cookie and return priority."
10433 (save-match-data
10434 (if (not (string-match org-priority-regexp s))
10435 (* 1000 (- org-lowest-priority org-default-priority))
10436 (* 1000 (- org-lowest-priority
10437 (string-to-char (match-string 2 s)))))))
10439 ;;;; Tags
10441 (defvar org-agenda-archives-mode)
10442 (defvar org-map-continue-from nil
10443 "Position from where mapping should continue.
10444 Can be set byt the action argument to `org-scan-tag's and `org-map-entries'.")
10446 (defvar org-scanner-tags nil
10447 "The current tag list while the tags scanner is running.")
10448 (defvar org-trust-scanner-tags nil
10449 "Should `org-get-tags-at' use the tags fro the scanner.
10450 This is for internal dynamical scoping only.
10451 When this is non-nil, the function `org-get-tags-at' will return the value
10452 of `org-scanner-tags' instead of building the list by itself. This
10453 can lead to large speed-ups when the tags scanner is used in a file with
10454 many entries, and when the list of tags is retrieved, for example to
10455 obtain a list of properties. Building the tags list for each entry in such
10456 a file becomes an N^2 operation - but with this variable set, it scales
10457 as N.")
10459 (defun org-scan-tags (action matcher &optional todo-only)
10460 "Scan headline tags with inheritance and produce output ACTION.
10462 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
10463 or `agenda' to produce an entry list for an agenda view. It can also be
10464 a Lisp form or a function that should be called at each matched headline, in
10465 this case the return value is a list of all return values from these calls.
10467 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
10468 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
10469 only lines with a TODO keyword are included in the output."
10470 (require 'org-agenda)
10471 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
10472 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
10473 (org-re
10474 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
10475 (props (list 'face 'default
10476 'done-face 'org-agenda-done
10477 'undone-face 'default
10478 'mouse-face 'highlight
10479 'org-not-done-regexp org-not-done-regexp
10480 'org-todo-regexp org-todo-regexp
10481 'keymap org-agenda-keymap
10482 'help-echo
10483 (format "mouse-2 or RET jump to org file %s"
10484 (abbreviate-file-name
10485 (or (buffer-file-name (buffer-base-buffer))
10486 (buffer-name (buffer-base-buffer)))))))
10487 (case-fold-search nil)
10488 (org-map-continue-from nil)
10489 lspos tags tags-list
10490 (tags-alist (list (cons 0 org-file-tags)))
10491 (llast 0) rtn rtn1 level category i txt
10492 todo marker entry priority)
10493 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
10494 (setq action (list 'lambda nil action)))
10495 (save-excursion
10496 (goto-char (point-min))
10497 (when (eq action 'sparse-tree)
10498 (org-overview)
10499 (org-remove-occur-highlights))
10500 (while (re-search-forward re nil t)
10501 (catch :skip
10502 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
10503 tags (if (match-end 4) (org-match-string-no-properties 4)))
10504 (goto-char (setq lspos (match-beginning 0)))
10505 (setq level (org-reduced-level (funcall outline-level))
10506 category (org-get-category))
10507 (setq i llast llast level)
10508 ;; remove tag lists from same and sublevels
10509 (while (>= i level)
10510 (when (setq entry (assoc i tags-alist))
10511 (setq tags-alist (delete entry tags-alist)))
10512 (setq i (1- i)))
10513 ;; add the next tags
10514 (when tags
10515 (setq tags (org-split-string tags ":")
10516 tags-alist
10517 (cons (cons level tags) tags-alist)))
10518 ;; compile tags for current headline
10519 (setq tags-list
10520 (if org-use-tag-inheritance
10521 (apply 'append (mapcar 'cdr (reverse tags-alist)))
10522 tags)
10523 org-scanner-tags tags-list)
10524 (when org-use-tag-inheritance
10525 (setcdr (car tags-alist)
10526 (mapcar (lambda (x)
10527 (setq x (copy-sequence x))
10528 (org-add-prop-inherited x))
10529 (cdar tags-alist))))
10530 (when (and tags org-use-tag-inheritance
10531 (or (not (eq t org-use-tag-inheritance))
10532 org-tags-exclude-from-inheritance))
10533 ;; selective inheritance, remove uninherited ones
10534 (setcdr (car tags-alist)
10535 (org-remove-uniherited-tags (cdar tags-alist))))
10536 (when (and (or (not todo-only)
10537 (and (member todo org-not-done-keywords)
10538 (or (not org-agenda-tags-todo-honor-ignore-options)
10539 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
10540 (let ((case-fold-search t)) (eval matcher))
10542 (not (member org-archive-tag tags-list))
10543 ;; we have an archive tag, should we use this anyway?
10544 (or (not org-agenda-skip-archived-trees)
10545 (and (eq action 'agenda) org-agenda-archives-mode))))
10546 (unless (eq action 'sparse-tree) (org-agenda-skip))
10548 ;; select this headline
10550 (cond
10551 ((eq action 'sparse-tree)
10552 (and org-highlight-sparse-tree-matches
10553 (org-get-heading) (match-end 0)
10554 (org-highlight-new-match
10555 (match-beginning 0) (match-beginning 1)))
10556 (org-show-context 'tags-tree))
10557 ((eq action 'agenda)
10558 (setq txt (org-format-agenda-item
10560 (concat
10561 (if (eq org-tags-match-list-sublevels 'indented)
10562 (make-string (1- level) ?.) "")
10563 (org-get-heading))
10564 category
10565 tags-list
10567 priority (org-get-priority txt))
10568 (goto-char lspos)
10569 (setq marker (org-agenda-new-marker))
10570 (org-add-props txt props
10571 'org-marker marker 'org-hd-marker marker 'org-category category
10572 'todo-state todo
10573 'priority priority 'type "tagsmatch")
10574 (push txt rtn))
10575 ((functionp action)
10576 (setq org-map-continue-from nil)
10577 (save-excursion
10578 (setq rtn1 (funcall action))
10579 (push rtn1 rtn)))
10580 (t (error "Invalid action")))
10582 ;; if we are to skip sublevels, jump to end of subtree
10583 (unless org-tags-match-list-sublevels
10584 (org-end-of-subtree t)
10585 (backward-char 1))))
10586 ;; Get the correct position from where to continue
10587 (if org-map-continue-from
10588 (goto-char org-map-continue-from)
10589 (and (= (point) lspos) (end-of-line 1)))))
10590 (when (and (eq action 'sparse-tree)
10591 (not org-sparse-tree-open-archived-trees))
10592 (org-hide-archived-subtrees (point-min) (point-max)))
10593 (nreverse rtn)))
10595 (defun org-remove-uniherited-tags (tags)
10596 "Remove all tags that are not inherited from the list TAGS."
10597 (cond
10598 ((eq org-use-tag-inheritance t)
10599 (if org-tags-exclude-from-inheritance
10600 (org-delete-all org-tags-exclude-from-inheritance tags)
10601 tags))
10602 ((not org-use-tag-inheritance) nil)
10603 ((stringp org-use-tag-inheritance)
10604 (delq nil (mapcar
10605 (lambda (x)
10606 (if (and (string-match org-use-tag-inheritance x)
10607 (not (member x org-tags-exclude-from-inheritance)))
10608 x nil))
10609 tags)))
10610 ((listp org-use-tag-inheritance)
10611 (delq nil (mapcar
10612 (lambda (x)
10613 (if (member x org-use-tag-inheritance) x nil))
10614 tags)))))
10616 (defvar todo-only) ;; dynamically scoped
10618 (defun org-match-sparse-tree (&optional todo-only match)
10619 "Create a sparse tree according to tags string MATCH.
10620 MATCH can contain positive and negative selection of tags, like
10621 \"+WORK+URGENT-WITHBOSS\".
10622 If optional argument TODO-ONLY is non-nil, only select lines that are
10623 also TODO lines."
10624 (interactive "P")
10625 (org-prepare-agenda-buffers (list (current-buffer)))
10626 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
10628 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
10630 (defvar org-cached-props nil)
10631 (defun org-cached-entry-get (pom property)
10632 (if (or (eq t org-use-property-inheritance)
10633 (and (stringp org-use-property-inheritance)
10634 (string-match org-use-property-inheritance property))
10635 (and (listp org-use-property-inheritance)
10636 (member property org-use-property-inheritance)))
10637 ;; Caching is not possible, check it directly
10638 (org-entry-get pom property 'inherit)
10639 ;; Get all properties, so that we can do complicated checks easily
10640 (cdr (assoc property (or org-cached-props
10641 (setq org-cached-props
10642 (org-entry-properties pom)))))))
10644 (defun org-global-tags-completion-table (&optional files)
10645 "Return the list of all tags in all agenda buffer/files."
10646 (save-excursion
10647 (org-uniquify
10648 (delq nil
10649 (apply 'append
10650 (mapcar
10651 (lambda (file)
10652 (set-buffer (find-file-noselect file))
10653 (append (org-get-buffer-tags)
10654 (mapcar (lambda (x) (if (stringp (car-safe x))
10655 (list (car-safe x)) nil))
10656 org-tag-alist)))
10657 (if (and files (car files))
10658 files
10659 (org-agenda-files))))))))
10661 (defun org-make-tags-matcher (match)
10662 "Create the TAGS//TODO matcher form for the selection string MATCH."
10663 ;; todo-only is scoped dynamically into this function, and the function
10664 ;; may change it if the matcher asks for it.
10665 (unless match
10666 ;; Get a new match request, with completion
10667 (let ((org-last-tags-completion-table
10668 (org-global-tags-completion-table)))
10669 (setq match (org-completing-read-no-ido
10670 "Match: " 'org-tags-completion-function nil nil nil
10671 'org-tags-history))))
10673 ;; Parse the string and create a lisp form
10674 (let ((match0 match)
10675 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
10676 minus tag mm
10677 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
10678 orterms term orlist re-p str-p level-p level-op time-p
10679 prop-p pn pv po cat-p gv rest)
10680 (if (string-match "/+" match)
10681 ;; match contains also a todo-matching request
10682 (progn
10683 (setq tagsmatch (substring match 0 (match-beginning 0))
10684 todomatch (substring match (match-end 0)))
10685 (if (string-match "^!" todomatch)
10686 (setq todo-only t todomatch (substring todomatch 1)))
10687 (if (string-match "^\\s-*$" todomatch)
10688 (setq todomatch nil)))
10689 ;; only matching tags
10690 (setq tagsmatch match todomatch nil))
10692 ;; Make the tags matcher
10693 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10694 (setq tagsmatcher t)
10695 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10696 (while (setq term (pop orterms))
10697 (while (and (equal (substring term -1) "\\") orterms)
10698 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10699 (while (string-match re term)
10700 (setq rest (substring term (match-end 0))
10701 minus (and (match-end 1)
10702 (equal (match-string 1 term) "-"))
10703 tag (match-string 2 term)
10704 re-p (equal (string-to-char tag) ?{)
10705 level-p (match-end 4)
10706 prop-p (match-end 5)
10707 mm (cond
10708 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10709 (level-p
10710 (setq level-op (org-op-to-function (match-string 3 term)))
10711 `(,level-op level ,(string-to-number
10712 (match-string 4 term))))
10713 (prop-p
10714 (setq pn (match-string 5 term)
10715 po (match-string 6 term)
10716 pv (match-string 7 term)
10717 cat-p (equal pn "CATEGORY")
10718 re-p (equal (string-to-char pv) ?{)
10719 str-p (equal (string-to-char pv) ?\")
10720 time-p (save-match-data
10721 (string-match "^\"[[<].*[]>]\"$" pv))
10722 pv (if (or re-p str-p) (substring pv 1 -1) pv))
10723 (if time-p (setq pv (org-matcher-time pv)))
10724 (setq po (org-op-to-function po (if time-p 'time str-p)))
10725 (cond
10726 ((equal pn "CATEGORY")
10727 (setq gv '(get-text-property (point) 'org-category)))
10728 ((equal pn "TODO")
10729 (setq gv 'todo))
10731 (setq gv `(org-cached-entry-get nil ,pn))))
10732 (if re-p
10733 (if (eq po 'org<>)
10734 `(not (string-match ,pv (or ,gv "")))
10735 `(string-match ,pv (or ,gv "")))
10736 (if str-p
10737 `(,po (or ,gv "") ,pv)
10738 `(,po (string-to-number (or ,gv ""))
10739 ,(string-to-number pv) ))))
10740 (t `(member ,tag tags-list)))
10741 mm (if minus (list 'not mm) mm)
10742 term rest)
10743 (push mm tagsmatcher))
10744 (push (if (> (length tagsmatcher) 1)
10745 (cons 'and tagsmatcher)
10746 (car tagsmatcher))
10747 orlist)
10748 (setq tagsmatcher nil))
10749 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
10750 (setq tagsmatcher
10751 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
10752 ;; Make the todo matcher
10753 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10754 (setq todomatcher t)
10755 (setq orterms (org-split-string todomatch "|") orlist nil)
10756 (while (setq term (pop orterms))
10757 (while (string-match re term)
10758 (setq minus (and (match-end 1)
10759 (equal (match-string 1 term) "-"))
10760 kwd (match-string 2 term)
10761 re-p (equal (string-to-char kwd) ?{)
10762 term (substring term (match-end 0))
10763 mm (if re-p
10764 `(string-match ,(substring kwd 1 -1) todo)
10765 (list 'equal 'todo kwd))
10766 mm (if minus (list 'not mm) mm))
10767 (push mm todomatcher))
10768 (push (if (> (length todomatcher) 1)
10769 (cons 'and todomatcher)
10770 (car todomatcher))
10771 orlist)
10772 (setq todomatcher nil))
10773 (setq todomatcher (if (> (length orlist) 1)
10774 (cons 'or orlist) (car orlist))))
10776 ;; Return the string and lisp forms of the matcher
10777 (setq matcher (if todomatcher
10778 (list 'and tagsmatcher todomatcher)
10779 tagsmatcher))
10780 (cons match0 matcher)))
10782 (defun org-op-to-function (op &optional stringp)
10783 "Turn an operator into the appropriate function."
10784 (setq op
10785 (cond
10786 ((equal op "<" ) '(< string< org-time<))
10787 ((equal op ">" ) '(> org-string> org-time>))
10788 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
10789 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
10790 ((member op '("=" "==")) '(= string= org-time=))
10791 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
10792 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
10794 (defun org<> (a b) (not (= a b)))
10795 (defun org-string<= (a b) (or (string= a b) (string< a b)))
10796 (defun org-string>= (a b) (not (string< a b)))
10797 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
10798 (defun org-string<> (a b) (not (string= a b)))
10799 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
10800 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
10801 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= 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) (org<> a b)))
10805 (defun org-2ft (s)
10806 "Convert S to a floating point time.
10807 If S is already a number, just return it. If it is a string, parse
10808 it as a time string and apply `float-time' to it. If S is nil, just return 0."
10809 (cond
10810 ((numberp s) s)
10811 ((stringp s)
10812 (condition-case nil
10813 (float-time (apply 'encode-time (org-parse-time-string s)))
10814 (error 0.)))
10815 (t 0.)))
10817 (defun org-time-today ()
10818 "Time in seconds today at 0:00.
10819 Returns the float number of seconds since the beginning of the
10820 epoch to the beginning of today (00:00)."
10821 (float-time (apply 'encode-time
10822 (append '(0 0 0) (nthcdr 3 (decode-time))))))
10824 (defun org-matcher-time (s)
10825 "Interpret a time comparison value."
10826 (save-match-data
10827 (cond
10828 ((string= s "<now>") (float-time))
10829 ((string= s "<today>") (org-time-today))
10830 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
10831 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
10832 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
10833 (+ (org-time-today)
10834 (* (string-to-number (match-string 1 s))
10835 (cdr (assoc (match-string 2 s)
10836 '(("d" . 86400.0) ("w" . 604800.0)
10837 ("m" . 2678400.0) ("y" . 31557600.0)))))))
10838 (t (org-2ft s)))))
10840 (defun org-match-any-p (re list)
10841 "Does re match any element of list?"
10842 (setq list (mapcar (lambda (x) (string-match re x)) list))
10843 (delq nil list))
10845 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
10846 (defvar org-tags-overlay (org-make-overlay 1 1))
10847 (org-detach-overlay org-tags-overlay)
10849 (defun org-get-local-tags-at (&optional pos)
10850 "Get a list of tags defined in the current headline."
10851 (org-get-tags-at pos 'local))
10853 (defun org-get-local-tags ()
10854 "Get a list of tags defined in the current headline."
10855 (org-get-tags-at nil 'local))
10857 (defun org-get-tags-at (&optional pos local)
10858 "Get a list of all headline tags applicable at POS.
10859 POS defaults to point. If tags are inherited, the list contains
10860 the targets in the same sequence as the headlines appear, i.e.
10861 the tags of the current headline come last.
10862 When LOCAL is non-nil, only return tags from the current headline,
10863 ignore inherited ones."
10864 (interactive)
10865 (if (and org-trust-scanner-tags
10866 (or (not pos) (equal pos (point)))
10867 (not local))
10868 org-scanner-tags
10869 (let (tags ltags lastpos parent)
10870 (save-excursion
10871 (save-restriction
10872 (widen)
10873 (goto-char (or pos (point)))
10874 (save-match-data
10875 (catch 'done
10876 (condition-case nil
10877 (progn
10878 (org-back-to-heading t)
10879 (while (not (equal lastpos (point)))
10880 (setq lastpos (point))
10881 (when (looking-at
10882 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
10883 (setq ltags (org-split-string
10884 (org-match-string-no-properties 1) ":"))
10885 (when parent
10886 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
10887 (setq tags (append
10888 (if parent
10889 (org-remove-uniherited-tags ltags)
10890 ltags)
10891 tags)))
10892 (or org-use-tag-inheritance (throw 'done t))
10893 (if local (throw 'done t))
10894 (or (org-up-heading-safe) (error nil))
10895 (setq parent t)))
10896 (error nil)))))
10897 (append (org-remove-uniherited-tags org-file-tags) tags)))))
10899 (defun org-add-prop-inherited (s)
10900 (add-text-properties 0 (length s) '(inherited t) s)
10903 (defun org-toggle-tag (tag &optional onoff)
10904 "Toggle the tag TAG for the current line.
10905 If ONOFF is `on' or `off', don't toggle but set to this state."
10906 (let (res current)
10907 (save-excursion
10908 (org-back-to-heading t)
10909 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
10910 (point-at-eol) t)
10911 (progn
10912 (setq current (match-string 1))
10913 (replace-match ""))
10914 (setq current ""))
10915 (setq current (nreverse (org-split-string current ":")))
10916 (cond
10917 ((eq onoff 'on)
10918 (setq res t)
10919 (or (member tag current) (push tag current)))
10920 ((eq onoff 'off)
10921 (or (not (member tag current)) (setq current (delete tag current))))
10922 (t (if (member tag current)
10923 (setq current (delete tag current))
10924 (setq res t)
10925 (push tag current))))
10926 (end-of-line 1)
10927 (if current
10928 (progn
10929 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
10930 (org-set-tags nil t))
10931 (delete-horizontal-space))
10932 (run-hooks 'org-after-tags-change-hook))
10933 res))
10935 (defun org-align-tags-here (to-col)
10936 ;; Assumes that this is a headline
10937 (let ((pos (point)) (col (current-column)) ncol tags-l p)
10938 (beginning-of-line 1)
10939 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10940 (< pos (match-beginning 2)))
10941 (progn
10942 (setq tags-l (- (match-end 2) (match-beginning 2)))
10943 (goto-char (match-beginning 1))
10944 (insert " ")
10945 (delete-region (point) (1+ (match-beginning 2)))
10946 (setq ncol (max (1+ (current-column))
10947 (1+ col)
10948 (if (> to-col 0)
10949 to-col
10950 (- (abs to-col) tags-l))))
10951 (setq p (point))
10952 (insert (make-string (- ncol (current-column)) ?\ ))
10953 (setq ncol (current-column))
10954 (when indent-tabs-mode (tabify p (point-at-eol)))
10955 (org-move-to-column (min ncol col) t))
10956 (goto-char pos))))
10958 (defun org-set-tags-command (&optional arg just-align)
10959 "Call the set-tags command for the current entry."
10960 (interactive "P")
10961 (if (org-on-heading-p)
10962 (org-set-tags arg just-align)
10963 (save-excursion
10964 (org-back-to-heading t)
10965 (org-set-tags arg just-align))))
10967 (defun org-set-tags (&optional arg just-align)
10968 "Set the tags for the current headline.
10969 With prefix ARG, realign all tags in headings in the current buffer."
10970 (interactive "P")
10971 (let* ((re (concat "^" outline-regexp))
10972 (current (org-get-tags-string))
10973 (col (current-column))
10974 (org-setting-tags t)
10975 table current-tags inherited-tags ; computed below when needed
10976 tags p0 c0 c1 rpl)
10977 (if arg
10978 (save-excursion
10979 (goto-char (point-min))
10980 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
10981 (while (re-search-forward re nil t)
10982 (org-set-tags nil t)
10983 (end-of-line 1)))
10984 (message "All tags realigned to column %d" org-tags-column))
10985 (if just-align
10986 (setq tags current)
10987 ;; Get a new set of tags from the user
10988 (save-excursion
10989 (setq table (append org-tag-persistent-alist
10990 (or org-tag-alist (org-get-buffer-tags)))
10991 org-last-tags-completion-table table
10992 current-tags (org-split-string current ":")
10993 inherited-tags (nreverse
10994 (nthcdr (length current-tags)
10995 (nreverse (org-get-tags-at))))
10996 tags
10997 (if (or (eq t org-use-fast-tag-selection)
10998 (and org-use-fast-tag-selection
10999 (delq nil (mapcar 'cdr table))))
11000 (org-fast-tag-selection
11001 current-tags inherited-tags table
11002 (if org-fast-tag-selection-include-todo org-todo-key-alist))
11003 (let ((org-add-colon-after-tag-completion t))
11004 (org-trim
11005 (org-without-partial-completion
11006 (org-ido-completing-read "Tags: " 'org-tags-completion-function
11007 nil nil current 'org-tags-history)))))))
11008 (while (string-match "[-+&]+" tags)
11009 ;; No boolean logic, just a list
11010 (setq tags (replace-match ":" t t tags))))
11012 (if org-tags-sort-function
11013 (setq tags (mapconcat 'identity
11014 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
11015 org-tags-sort-function) ":")))
11017 (if (string-match "\\`[\t ]*\\'" tags)
11018 (setq tags "")
11019 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
11020 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
11022 ;; Insert new tags at the correct column
11023 (beginning-of-line 1)
11024 (cond
11025 ((and (equal current "") (equal tags "")))
11026 ((re-search-forward
11027 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
11028 (point-at-eol) t)
11029 (if (equal tags "")
11030 (setq rpl "")
11031 (goto-char (match-beginning 0))
11032 (setq c0 (current-column) p0 (point)
11033 c1 (max (1+ c0) (if (> org-tags-column 0)
11034 org-tags-column
11035 (- (- org-tags-column) (length tags))))
11036 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
11037 (replace-match rpl t t)
11038 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
11039 tags)
11040 (t (error "Tags alignment failed")))
11041 (org-move-to-column col)
11042 (unless just-align
11043 (run-hooks 'org-after-tags-change-hook)))))
11045 (defun org-change-tag-in-region (beg end tag off)
11046 "Add or remove TAG for each entry in the region.
11047 This works in the agenda, and also in an org-mode buffer."
11048 (interactive
11049 (list (region-beginning) (region-end)
11050 (let ((org-last-tags-completion-table
11051 (if (org-mode-p)
11052 (org-get-buffer-tags)
11053 (org-global-tags-completion-table))))
11054 (org-ido-completing-read
11055 "Tag: " 'org-tags-completion-function nil nil nil
11056 'org-tags-history))
11057 (progn
11058 (message "[s]et or [r]emove? ")
11059 (equal (read-char-exclusive) ?r))))
11060 (if (fboundp 'deactivate-mark) (deactivate-mark))
11061 (let ((agendap (equal major-mode 'org-agenda-mode))
11062 l1 l2 m buf pos newhead (cnt 0))
11063 (goto-char end)
11064 (setq l2 (1- (org-current-line)))
11065 (goto-char beg)
11066 (setq l1 (org-current-line))
11067 (loop for l from l1 to l2 do
11068 (goto-line l)
11069 (setq m (get-text-property (point) 'org-hd-marker))
11070 (when (or (and (org-mode-p) (org-on-heading-p))
11071 (and agendap m))
11072 (setq buf (if agendap (marker-buffer m) (current-buffer))
11073 pos (if agendap m (point)))
11074 (with-current-buffer buf
11075 (save-excursion
11076 (save-restriction
11077 (goto-char pos)
11078 (setq cnt (1+ cnt))
11079 (org-toggle-tag tag (if off 'off 'on))
11080 (setq newhead (org-get-heading)))))
11081 (and agendap (org-agenda-change-all-lines newhead m))))
11082 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
11084 (defun org-tags-completion-function (string predicate &optional flag)
11085 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
11086 (confirm (lambda (x) (stringp (car x)))))
11087 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
11088 (setq s1 (match-string 1 string)
11089 s2 (match-string 2 string))
11090 (setq s1 "" s2 string))
11091 (cond
11092 ((eq flag nil)
11093 ;; try completion
11094 (setq rtn (try-completion s2 ctable confirm))
11095 (if (stringp rtn)
11096 (setq rtn
11097 (concat s1 s2 (substring rtn (length s2))
11098 (if (and org-add-colon-after-tag-completion
11099 (assoc rtn ctable))
11100 ":" ""))))
11101 rtn)
11102 ((eq flag t)
11103 ;; all-completions
11104 (all-completions s2 ctable confirm)
11106 ((eq flag 'lambda)
11107 ;; exact match?
11108 (assoc s2 ctable)))
11111 (defun org-fast-tag-insert (kwd tags face &optional end)
11112 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
11113 (insert (format "%-12s" (concat kwd ":"))
11114 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
11115 (or end "")))
11117 (defun org-fast-tag-show-exit (flag)
11118 (save-excursion
11119 (goto-line 3)
11120 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
11121 (replace-match ""))
11122 (when flag
11123 (end-of-line 1)
11124 (org-move-to-column (- (window-width) 19) t)
11125 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
11127 (defun org-set-current-tags-overlay (current prefix)
11128 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
11129 (if (featurep 'xemacs)
11130 (org-overlay-display org-tags-overlay (concat prefix s)
11131 'secondary-selection)
11132 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
11133 (org-overlay-display org-tags-overlay (concat prefix s)))))
11135 (defun org-fast-tag-selection (current inherited table &optional todo-table)
11136 "Fast tag selection with single keys.
11137 CURRENT is the current list of tags in the headline, INHERITED is the
11138 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
11139 possibly with grouping information. TODO-TABLE is a similar table with
11140 TODO keywords, should these have keys assigned to them.
11141 If the keys are nil, a-z are automatically assigned.
11142 Returns the new tags string, or nil to not change the current settings."
11143 (let* ((fulltable (append table todo-table))
11144 (maxlen (apply 'max (mapcar
11145 (lambda (x)
11146 (if (stringp (car x)) (string-width (car x)) 0))
11147 fulltable)))
11148 (buf (current-buffer))
11149 (expert (eq org-fast-tag-selection-single-key 'expert))
11150 (buffer-tags nil)
11151 (fwidth (+ maxlen 3 1 3))
11152 (ncol (/ (- (window-width) 4) fwidth))
11153 (i-face 'org-done)
11154 (c-face 'org-todo)
11155 tg cnt e c char c1 c2 ntable tbl rtn
11156 ov-start ov-end ov-prefix
11157 (exit-after-next org-fast-tag-selection-single-key)
11158 (done-keywords org-done-keywords)
11159 groups ingroup)
11160 (save-excursion
11161 (beginning-of-line 1)
11162 (if (looking-at
11163 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11164 (setq ov-start (match-beginning 1)
11165 ov-end (match-end 1)
11166 ov-prefix "")
11167 (setq ov-start (1- (point-at-eol))
11168 ov-end (1+ ov-start))
11169 (skip-chars-forward "^\n\r")
11170 (setq ov-prefix
11171 (concat
11172 (buffer-substring (1- (point)) (point))
11173 (if (> (current-column) org-tags-column)
11175 (make-string (- org-tags-column (current-column)) ?\ ))))))
11176 (org-move-overlay org-tags-overlay ov-start ov-end)
11177 (save-window-excursion
11178 (if expert
11179 (set-buffer (get-buffer-create " *Org tags*"))
11180 (delete-other-windows)
11181 (split-window-vertically)
11182 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
11183 (erase-buffer)
11184 (org-set-local 'org-done-keywords done-keywords)
11185 (org-fast-tag-insert "Inherited" inherited i-face "\n")
11186 (org-fast-tag-insert "Current" current c-face "\n\n")
11187 (org-fast-tag-show-exit exit-after-next)
11188 (org-set-current-tags-overlay current ov-prefix)
11189 (setq tbl fulltable char ?a cnt 0)
11190 (while (setq e (pop tbl))
11191 (cond
11192 ((equal e '(:startgroup))
11193 (push '() groups) (setq ingroup t)
11194 (when (not (= cnt 0))
11195 (setq cnt 0)
11196 (insert "\n"))
11197 (insert "{ "))
11198 ((equal e '(:endgroup))
11199 (setq ingroup nil cnt 0)
11200 (insert "}\n"))
11201 ((equal e '(:newline))
11202 (when (not (= cnt 0))
11203 (setq cnt 0)
11204 (insert "\n")
11205 (setq e (car tbl))
11206 (while (equal (car tbl) '(:newline))
11207 (insert "\n")
11208 (setq tbl (cdr tbl)))))
11210 (setq tg (car e) c2 nil)
11211 (if (cdr e)
11212 (setq c (cdr e))
11213 ;; automatically assign a character.
11214 (setq c1 (string-to-char
11215 (downcase (substring
11216 tg (if (= (string-to-char tg) ?@) 1 0)))))
11217 (if (or (rassoc c1 ntable) (rassoc c1 table))
11218 (while (or (rassoc char ntable) (rassoc char table))
11219 (setq char (1+ char)))
11220 (setq c2 c1))
11221 (setq c (or c2 char)))
11222 (if ingroup (push tg (car groups)))
11223 (setq tg (org-add-props tg nil 'face
11224 (cond
11225 ((not (assoc tg table))
11226 (org-get-todo-face tg))
11227 ((member tg current) c-face)
11228 ((member tg inherited) i-face)
11229 (t nil))))
11230 (if (and (= cnt 0) (not ingroup)) (insert " "))
11231 (insert "[" c "] " tg (make-string
11232 (- fwidth 4 (length tg)) ?\ ))
11233 (push (cons tg c) ntable)
11234 (when (= (setq cnt (1+ cnt)) ncol)
11235 (insert "\n")
11236 (if ingroup (insert " "))
11237 (setq cnt 0)))))
11238 (setq ntable (nreverse ntable))
11239 (insert "\n")
11240 (goto-char (point-min))
11241 (if (not expert) (org-fit-window-to-buffer))
11242 (setq rtn
11243 (catch 'exit
11244 (while t
11245 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
11246 (if groups " [!] no groups" " [!]groups")
11247 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
11248 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11249 (cond
11250 ((= c ?\r) (throw 'exit t))
11251 ((= c ?!)
11252 (setq groups (not groups))
11253 (goto-char (point-min))
11254 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
11255 ((= c ?\C-c)
11256 (if (not expert)
11257 (org-fast-tag-show-exit
11258 (setq exit-after-next (not exit-after-next)))
11259 (setq expert nil)
11260 (delete-other-windows)
11261 (split-window-vertically)
11262 (org-switch-to-buffer-other-window " *Org tags*")
11263 (org-fit-window-to-buffer)))
11264 ((or (= c ?\C-g)
11265 (and (= c ?q) (not (rassoc c ntable))))
11266 (org-detach-overlay org-tags-overlay)
11267 (setq quit-flag t))
11268 ((= c ?\ )
11269 (setq current nil)
11270 (if exit-after-next (setq exit-after-next 'now)))
11271 ((= c ?\t)
11272 (condition-case nil
11273 (setq tg (org-ido-completing-read
11274 "Tag: "
11275 (or buffer-tags
11276 (with-current-buffer buf
11277 (org-get-buffer-tags)))))
11278 (quit (setq tg "")))
11279 (when (string-match "\\S-" tg)
11280 (add-to-list 'buffer-tags (list tg))
11281 (if (member tg current)
11282 (setq current (delete tg current))
11283 (push tg current)))
11284 (if exit-after-next (setq exit-after-next 'now)))
11285 ((setq e (rassoc c todo-table) tg (car e))
11286 (with-current-buffer buf
11287 (save-excursion (org-todo tg)))
11288 (if exit-after-next (setq exit-after-next 'now)))
11289 ((setq e (rassoc c ntable) tg (car e))
11290 (if (member tg current)
11291 (setq current (delete tg current))
11292 (loop for g in groups do
11293 (if (member tg g)
11294 (mapc (lambda (x)
11295 (setq current (delete x current)))
11296 g)))
11297 (push tg current))
11298 (if exit-after-next (setq exit-after-next 'now))))
11300 ;; Create a sorted list
11301 (setq current
11302 (sort current
11303 (lambda (a b)
11304 (assoc b (cdr (memq (assoc a ntable) ntable))))))
11305 (if (eq exit-after-next 'now) (throw 'exit t))
11306 (goto-char (point-min))
11307 (beginning-of-line 2)
11308 (delete-region (point) (point-at-eol))
11309 (org-fast-tag-insert "Current" current c-face)
11310 (org-set-current-tags-overlay current ov-prefix)
11311 (while (re-search-forward
11312 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
11313 (setq tg (match-string 1))
11314 (add-text-properties
11315 (match-beginning 1) (match-end 1)
11316 (list 'face
11317 (cond
11318 ((member tg current) c-face)
11319 ((member tg inherited) i-face)
11320 (t (get-text-property (match-beginning 1) 'face))))))
11321 (goto-char (point-min)))))
11322 (org-detach-overlay org-tags-overlay)
11323 (if rtn
11324 (mapconcat 'identity current ":")
11325 nil))))
11327 (defun org-get-tags-string ()
11328 "Get the TAGS string in the current headline."
11329 (unless (org-on-heading-p t)
11330 (error "Not on a heading"))
11331 (save-excursion
11332 (beginning-of-line 1)
11333 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11334 (org-match-string-no-properties 1)
11335 "")))
11337 (defun org-get-tags ()
11338 "Get the list of tags specified in the current headline."
11339 (org-split-string (org-get-tags-string) ":"))
11341 (defun org-get-buffer-tags ()
11342 "Get a table of all tags used in the buffer, for completion."
11343 (let (tags)
11344 (save-excursion
11345 (goto-char (point-min))
11346 (while (re-search-forward
11347 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
11348 (when (equal (char-after (point-at-bol 0)) ?*)
11349 (mapc (lambda (x) (add-to-list 'tags x))
11350 (org-split-string (org-match-string-no-properties 1) ":")))))
11351 (mapcar 'list tags)))
11353 ;;;; The mapping API
11355 ;;;###autoload
11356 (defun org-map-entries (func &optional match scope &rest skip)
11357 "Call FUNC at each headline selected by MATCH in SCOPE.
11359 FUNC is a function or a lisp form. The function will be called without
11360 arguments, with the cursor positioned at the beginning of the headline.
11361 The return values of all calls to the function will be collected and
11362 returned as a list.
11364 The call to FUNC will be wrapped into a save-excursion form, so FUNC
11365 does not need to preserve point. After evaluation, the cursor will be
11366 moved to the end of the line (presumably of the headline of the
11367 processed entry) and search continues from there. Under some
11368 circumstances, this may not produce the wanted results. For example,
11369 if you have removed (e.g. archived) the current (sub)tree it could
11370 mean that the next entry will be skipped entirely. In such cases, you
11371 can specify the position from where search should continue by making
11372 FUNC set the variable `org-map-continue-from' to the desired buffer
11373 position.
11375 MATCH is a tags/property/todo match as it is used in the agenda tags view.
11376 Only headlines that are matched by this query will be considered during
11377 the iteration. When MATCH is nil or t, all headlines will be
11378 visited by the iteration.
11380 SCOPE determines the scope of this command. It can be any of:
11382 nil The current buffer, respecting the restriction if any
11383 tree The subtree started with the entry at point
11384 file The current buffer, without restriction
11385 file-with-archives
11386 The current buffer, and any archives associated with it
11387 agenda All agenda files
11388 agenda-with-archives
11389 All agenda files with any archive files associated with them
11390 \(file1 file2 ...)
11391 If this is a list, all files in the list will be scanned
11393 The remaining args are treated as settings for the skipping facilities of
11394 the scanner. The following items can be given here:
11396 archive skip trees with the archive tag.
11397 comment skip trees with the COMMENT keyword
11398 function or Emacs Lisp form:
11399 will be used as value for `org-agenda-skip-function', so whenever
11400 the the function returns t, FUNC will not be called for that
11401 entry and search will continue from the point where the
11402 function leaves it.
11404 If your function needs to retrieve the tags including inherited tags
11405 at the *current* entry, you can use the value of the variable
11406 `org-scanner-tags' which will be much faster than getting the value
11407 with `org-get-tags-at'. If your function gets properties with
11408 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
11409 to t around the call to `org-entry-properties' to get the same speedup.
11410 Note that if your function moves around to retrieve tags and properties at
11411 a *different* entry, you cannot use these techniques."
11412 (let* ((org-agenda-archives-mode nil) ; just to make sure
11413 (org-agenda-skip-archived-trees (memq 'archive skip))
11414 (org-agenda-skip-comment-trees (memq 'comment skip))
11415 (org-agenda-skip-function
11416 (car (org-delete-all '(comment archive) skip)))
11417 (org-tags-match-list-sublevels t)
11418 matcher file res
11419 org-todo-keywords-for-agenda
11420 org-done-keywords-for-agenda
11421 org-todo-keyword-alist-for-agenda
11422 org-tag-alist-for-agenda)
11424 (cond
11425 ((eq match t) (setq matcher t))
11426 ((eq match nil) (setq matcher t))
11427 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
11429 (save-excursion
11430 (save-restriction
11431 (when (eq scope 'tree)
11432 (org-back-to-heading t)
11433 (org-narrow-to-subtree)
11434 (setq scope nil))
11436 (if (not scope)
11437 (progn
11438 (org-prepare-agenda-buffers
11439 (list (buffer-file-name (current-buffer))))
11440 (setq res (org-scan-tags func matcher)))
11441 ;; Get the right scope
11442 (cond
11443 ((and scope (listp scope) (symbolp (car scope)))
11444 (setq scope (eval scope)))
11445 ((eq scope 'agenda)
11446 (setq scope (org-agenda-files t)))
11447 ((eq scope 'agenda-with-archives)
11448 (setq scope (org-agenda-files t))
11449 (setq scope (org-add-archive-files scope)))
11450 ((eq scope 'file)
11451 (setq scope (list (buffer-file-name))))
11452 ((eq scope 'file-with-archives)
11453 (setq scope (org-add-archive-files (list (buffer-file-name))))))
11454 (org-prepare-agenda-buffers scope)
11455 (while (setq file (pop scope))
11456 (with-current-buffer (org-find-base-buffer-visiting file)
11457 (save-excursion
11458 (save-restriction
11459 (widen)
11460 (goto-char (point-min))
11461 (setq res (append res (org-scan-tags func matcher))))))))))
11462 res))
11464 ;;;; Properties
11466 ;;; Setting and retrieving properties
11468 (defconst org-special-properties
11469 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
11470 "TIMESTAMP" "TIMESTAMP_IA")
11471 "The special properties valid in Org-mode.
11473 These are properties that are not defined in the property drawer,
11474 but in some other way.")
11476 (defconst org-default-properties
11477 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
11478 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
11479 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
11480 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
11481 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
11482 "CLOCK_MODELINE_TOTAL")
11483 "Some properties that are used by Org-mode for various purposes.
11484 Being in this list makes sure that they are offered for completion.")
11486 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
11487 "Regular expression matching the first line of a property drawer.")
11489 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
11490 "Regular expression matching the first line of a property drawer.")
11492 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
11493 "Regular expression matching the first line of a property drawer.")
11495 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
11496 "Regular expression matching the first line of a property drawer.")
11498 (defconst org-property-drawer-re
11499 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
11500 org-property-end-re "\\)\n?")
11501 "Matches an entire property drawer.")
11503 (defconst org-clock-drawer-re
11504 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
11505 org-property-end-re "\\)\n?")
11506 "Matches an entire clock drawer.")
11508 (defun org-property-action ()
11509 "Do an action on properties."
11510 (interactive)
11511 (let (c)
11512 (org-at-property-p)
11513 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
11514 (setq c (read-char-exclusive))
11515 (cond
11516 ((equal c ?s)
11517 (call-interactively 'org-set-property))
11518 ((equal c ?d)
11519 (call-interactively 'org-delete-property))
11520 ((equal c ?D)
11521 (call-interactively 'org-delete-property-globally))
11522 ((equal c ?c)
11523 (call-interactively 'org-compute-property-at-point))
11524 (t (error "No such property action %c" c)))))
11526 (defun org-at-property-p ()
11527 "Is the cursor in a property line?"
11528 ;; FIXME: Does not check if we are actually in the drawer.
11529 ;; FIXME: also returns true on any drawers.....
11530 ;; This is used by C-c C-c for property action.
11531 (save-excursion
11532 (beginning-of-line 1)
11533 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
11535 (defun org-get-property-block (&optional beg end force)
11536 "Return the (beg . end) range of the body of the property drawer.
11537 BEG and END can be beginning and end of subtree, if not given
11538 they will be found.
11539 If the drawer does not exist and FORCE is non-nil, create the drawer."
11540 (catch 'exit
11541 (save-excursion
11542 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
11543 (end (or end (progn (outline-next-heading) (point)))))
11544 (goto-char beg)
11545 (if (re-search-forward org-property-start-re end t)
11546 (setq beg (1+ (match-end 0)))
11547 (if force
11548 (save-excursion
11549 (org-insert-property-drawer)
11550 (setq end (progn (outline-next-heading) (point))))
11551 (throw 'exit nil))
11552 (goto-char beg)
11553 (if (re-search-forward org-property-start-re end t)
11554 (setq beg (1+ (match-end 0)))))
11555 (if (re-search-forward org-property-end-re end t)
11556 (setq end (match-beginning 0))
11557 (or force (throw 'exit nil))
11558 (goto-char beg)
11559 (setq end beg)
11560 (org-indent-line-function)
11561 (insert ":END:\n"))
11562 (cons beg end)))))
11564 (defun org-entry-properties (&optional pom which)
11565 "Get all properties of the entry at point-or-marker POM.
11566 This includes the TODO keyword, the tags, time strings for deadline,
11567 scheduled, and clocking, and any additional properties defined in the
11568 entry. The return value is an alist, keys may occur multiple times
11569 if the property key was used several times.
11570 POM may also be nil, in which case the current entry is used.
11571 If WHICH is nil or `all', get all properties. If WHICH is
11572 `special' or `standard', only get that subclass."
11573 (setq which (or which 'all))
11574 (org-with-point-at pom
11575 (let ((clockstr (substring org-clock-string 0 -1))
11576 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
11577 beg end range props sum-props key value string clocksum)
11578 (save-excursion
11579 (when (condition-case nil
11580 (and (org-mode-p) (org-back-to-heading t))
11581 (error nil))
11582 (setq beg (point))
11583 (setq sum-props (get-text-property (point) 'org-summaries))
11584 (setq clocksum (get-text-property (point) :org-clock-minutes))
11585 (outline-next-heading)
11586 (setq end (point))
11587 (when (memq which '(all special))
11588 ;; Get the special properties, like TODO and tags
11589 (goto-char beg)
11590 (when (and (looking-at org-todo-line-regexp) (match-end 2))
11591 (push (cons "TODO" (org-match-string-no-properties 2)) props))
11592 (when (looking-at org-priority-regexp)
11593 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
11594 (when (and (setq value (org-get-tags-string))
11595 (string-match "\\S-" value))
11596 (push (cons "TAGS" value) props))
11597 (when (setq value (org-get-tags-at))
11598 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
11599 props))
11600 (while (re-search-forward org-maybe-keyword-time-regexp end t)
11601 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
11602 string (if (equal key clockstr)
11603 (org-no-properties
11604 (org-trim
11605 (buffer-substring
11606 (match-beginning 3) (goto-char (point-at-eol)))))
11607 (substring (org-match-string-no-properties 3) 1 -1)))
11608 (unless key
11609 (if (= (char-after (match-beginning 3)) ?\[)
11610 (setq key "TIMESTAMP_IA")
11611 (setq key "TIMESTAMP")))
11612 (when (or (equal key clockstr) (not (assoc key props)))
11613 (push (cons key string) props)))
11617 (when (memq which '(all standard))
11618 ;; Get the standard properties, like :PROP: ...
11619 (setq range (org-get-property-block beg end))
11620 (when range
11621 (goto-char (car range))
11622 (while (re-search-forward
11623 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
11624 (cdr range) t)
11625 (setq key (org-match-string-no-properties 1)
11626 value (org-trim (or (org-match-string-no-properties 2) "")))
11627 (unless (member key excluded)
11628 (push (cons key (or value "")) props)))))
11629 (if clocksum
11630 (push (cons "CLOCKSUM"
11631 (org-columns-number-to-string (/ (float clocksum) 60.)
11632 'add_times))
11633 props))
11634 (unless (assoc "CATEGORY" props)
11635 (setq value (or (org-get-category)
11636 (progn (org-refresh-category-properties)
11637 (org-get-category))))
11638 (push (cons "CATEGORY" value) props))
11639 (append sum-props (nreverse props)))))))
11641 (defun org-entry-get (pom property &optional inherit)
11642 "Get value of PROPERTY for entry at point-or-marker POM.
11643 If INHERIT is non-nil and the entry does not have the property,
11644 then also check higher levels of the hierarchy.
11645 If INHERIT is the symbol `selective', use inheritance only if the setting
11646 in `org-use-property-inheritance' selects PROPERTY for inheritance.
11647 If the property is present but empty, the return value is the empty string.
11648 If the property is not present at all, nil is returned."
11649 (org-with-point-at pom
11650 (if (and inherit (if (eq inherit 'selective)
11651 (org-property-inherit-p property)
11653 (org-entry-get-with-inheritance property)
11654 (if (member property org-special-properties)
11655 ;; We need a special property. Use brute force, get all properties.
11656 (cdr (assoc property (org-entry-properties nil 'special)))
11657 (let ((range (org-get-property-block)))
11658 (if (and range
11659 (goto-char (car range))
11660 (re-search-forward
11661 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
11662 (cdr range) t))
11663 ;; Found the property, return it.
11664 (if (match-end 1)
11665 (org-match-string-no-properties 1)
11666 "")))))))
11668 (defun org-property-or-variable-value (var &optional inherit)
11669 "Check if there is a property fixing the value of VAR.
11670 If yes, return this value. If not, return the current value of the variable."
11671 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
11672 (if (and prop (stringp prop) (string-match "\\S-" prop))
11673 (read prop)
11674 (symbol-value var))))
11676 (defun org-entry-delete (pom property)
11677 "Delete the property PROPERTY from entry at point-or-marker POM."
11678 (org-with-point-at pom
11679 (if (member property org-special-properties)
11680 nil ; cannot delete these properties.
11681 (let ((range (org-get-property-block)))
11682 (if (and range
11683 (goto-char (car range))
11684 (re-search-forward
11685 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
11686 (cdr range) t))
11687 (progn
11688 (delete-region (match-beginning 0) (1+ (point-at-eol)))
11690 nil)))))
11692 ;; Multi-values properties are properties that contain multiple values
11693 ;; These values are assumed to be single words, separated by whitespace.
11694 (defun org-entry-add-to-multivalued-property (pom property value)
11695 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
11696 (let* ((old (org-entry-get pom property))
11697 (values (and old (org-split-string old "[ \t]"))))
11698 (setq value (org-entry-protect-space value))
11699 (unless (member value values)
11700 (setq values (cons value values))
11701 (org-entry-put pom property
11702 (mapconcat 'identity values " ")))))
11704 (defun org-entry-remove-from-multivalued-property (pom property value)
11705 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
11706 (let* ((old (org-entry-get pom property))
11707 (values (and old (org-split-string old "[ \t]"))))
11708 (setq value (org-entry-protect-space value))
11709 (when (member value values)
11710 (setq values (delete value values))
11711 (org-entry-put pom property
11712 (mapconcat 'identity values " ")))))
11714 (defun org-entry-member-in-multivalued-property (pom property value)
11715 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
11716 (let* ((old (org-entry-get pom property))
11717 (values (and old (org-split-string old "[ \t]"))))
11718 (setq value (org-entry-protect-space value))
11719 (member value values)))
11721 (defun org-entry-get-multivalued-property (pom property)
11722 "Return a list of values in a multivalued property."
11723 (let* ((value (org-entry-get pom property))
11724 (values (and value (org-split-string value "[ \t]"))))
11725 (mapcar 'org-entry-restore-space values)))
11727 (defun org-entry-put-multivalued-property (pom property &rest values)
11728 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
11729 VALUES should be a list of strings. Spaces will be protected."
11730 (org-entry-put pom property
11731 (mapconcat 'org-entry-protect-space values " "))
11732 (let* ((value (org-entry-get pom property))
11733 (values (and value (org-split-string value "[ \t]"))))
11734 (mapcar 'org-entry-restore-space values)))
11736 (defun org-entry-protect-space (s)
11737 "Protect spaces and newline in string S."
11738 (while (string-match " " s)
11739 (setq s (replace-match "%20" t t s)))
11740 (while (string-match "\n" s)
11741 (setq s (replace-match "%0A" t t s)))
11744 (defun org-entry-restore-space (s)
11745 "Restore spaces and newline in string S."
11746 (while (string-match "%20" s)
11747 (setq s (replace-match " " t t s)))
11748 (while (string-match "%0A" s)
11749 (setq s (replace-match "\n" t t s)))
11752 (defvar org-entry-property-inherited-from (make-marker)
11753 "Marker pointing to the entry from where a property was inherited.
11754 Each call to `org-entry-get-with-inheritance' will set this marker to the
11755 location of the entry where the inheritance search matched. If there was
11756 no match, the marker will point nowhere.
11757 Note that also `org-entry-get' calls this function, if the INHERIT flag
11758 is set.")
11760 (defun org-entry-get-with-inheritance (property)
11761 "Get entry property, and search higher levels if not present."
11762 (move-marker org-entry-property-inherited-from nil)
11763 (let (tmp)
11764 (save-excursion
11765 (save-restriction
11766 (widen)
11767 (catch 'ex
11768 (while t
11769 (when (setq tmp (org-entry-get nil property))
11770 (org-back-to-heading t)
11771 (move-marker org-entry-property-inherited-from (point))
11772 (throw 'ex tmp))
11773 (or (org-up-heading-safe) (throw 'ex nil)))))
11774 (or tmp
11775 (cdr (assoc property org-file-properties))
11776 (cdr (assoc property org-global-properties))
11777 (cdr (assoc property org-global-properties-fixed))))))
11779 (defun org-entry-put (pom property value)
11780 "Set PROPERTY to VALUE for entry at point-or-marker POM."
11781 (org-with-point-at pom
11782 (org-back-to-heading t)
11783 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
11784 range)
11785 (cond
11786 ((equal property "TODO")
11787 (when (and (stringp value) (string-match "\\S-" value)
11788 (not (member value org-todo-keywords-1)))
11789 (error "\"%s\" is not a valid TODO state" value))
11790 (if (or (not value)
11791 (not (string-match "\\S-" value)))
11792 (setq value 'none))
11793 (org-todo value)
11794 (org-set-tags nil 'align))
11795 ((equal property "PRIORITY")
11796 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
11797 (string-to-char value) ?\ ))
11798 (org-set-tags nil 'align))
11799 ((equal property "SCHEDULED")
11800 (if (re-search-forward org-scheduled-time-regexp end t)
11801 (cond
11802 ((eq value 'earlier) (org-timestamp-change -1 'day))
11803 ((eq value 'later) (org-timestamp-change 1 'day))
11804 (t (call-interactively 'org-schedule)))
11805 (call-interactively 'org-schedule)))
11806 ((equal property "DEADLINE")
11807 (if (re-search-forward org-deadline-time-regexp end t)
11808 (cond
11809 ((eq value 'earlier) (org-timestamp-change -1 'day))
11810 ((eq value 'later) (org-timestamp-change 1 'day))
11811 (t (call-interactively 'org-deadline)))
11812 (call-interactively 'org-deadline)))
11813 ((member property org-special-properties)
11814 (error "The %s property can not yet be set with `org-entry-put'"
11815 property))
11816 (t ; a non-special property
11817 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
11818 (setq range (org-get-property-block beg end 'force))
11819 (goto-char (car range))
11820 (if (re-search-forward
11821 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
11822 (progn
11823 (delete-region (match-beginning 1) (match-end 1))
11824 (goto-char (match-beginning 1)))
11825 (goto-char (cdr range))
11826 (insert "\n")
11827 (backward-char 1)
11828 (org-indent-line-function)
11829 (insert ":" property ":"))
11830 (and value (insert " " value))
11831 (org-indent-line-function)))))))
11833 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
11834 "Get all property keys in the current buffer.
11835 With INCLUDE-SPECIALS, also list the special properties that reflect things
11836 like tags and TODO state.
11837 With INCLUDE-DEFAULTS, also include properties that has special meaning
11838 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
11839 With INCLUDE-COLUMNS, also include property names given in COLUMN
11840 formats in the current buffer."
11841 (let (rtn range cfmt s p)
11842 (save-excursion
11843 (save-restriction
11844 (widen)
11845 (goto-char (point-min))
11846 (while (re-search-forward org-property-start-re nil t)
11847 (setq range (org-get-property-block))
11848 (goto-char (car range))
11849 (while (re-search-forward
11850 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
11851 (cdr range) t)
11852 (add-to-list 'rtn (org-match-string-no-properties 1)))
11853 (outline-next-heading))))
11855 (when include-specials
11856 (setq rtn (append org-special-properties rtn)))
11858 (when include-defaults
11859 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
11860 (add-to-list 'rtn org-effort-property))
11862 (when include-columns
11863 (save-excursion
11864 (save-restriction
11865 (widen)
11866 (goto-char (point-min))
11867 (while (re-search-forward
11868 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
11869 nil t)
11870 (setq cfmt (match-string 2) s 0)
11871 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
11872 cfmt s)
11873 (setq s (match-end 0)
11874 p (match-string 1 cfmt))
11875 (unless (or (equal p "ITEM")
11876 (member p org-special-properties))
11877 (add-to-list 'rtn (match-string 1 cfmt))))))))
11879 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
11881 (defun org-property-values (key)
11882 "Return a list of all values of property KEY."
11883 (save-excursion
11884 (save-restriction
11885 (widen)
11886 (goto-char (point-min))
11887 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
11888 values)
11889 (while (re-search-forward re nil t)
11890 (add-to-list 'values (org-trim (match-string 1))))
11891 (delete "" values)))))
11893 (defun org-insert-property-drawer ()
11894 "Insert a property drawer into the current entry."
11895 (interactive)
11896 (org-back-to-heading t)
11897 (looking-at outline-regexp)
11898 (let ((indent (if org-adapt-indentation
11899 (- (match-end 0)(match-beginning 0))
11901 (beg (point))
11902 (re (concat "^[ \t]*" org-keyword-time-regexp))
11903 end hiddenp)
11904 (outline-next-heading)
11905 (setq end (point))
11906 (goto-char beg)
11907 (while (re-search-forward re end t))
11908 (setq hiddenp (org-invisible-p))
11909 (end-of-line 1)
11910 (and (equal (char-after) ?\n) (forward-char 1))
11911 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
11912 (if (member (match-string 1) '("CLOCK:" ":END:"))
11913 ;; just skip this line
11914 (beginning-of-line 2)
11915 ;; Drawer start, find the end
11916 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
11917 (beginning-of-line 1)))
11918 (org-skip-over-state-notes)
11919 (skip-chars-backward " \t\n\r")
11920 (if (eq (char-before) ?*) (forward-char 1))
11921 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
11922 (beginning-of-line 0)
11923 (org-indent-to-column indent)
11924 (beginning-of-line 2)
11925 (org-indent-to-column indent)
11926 (beginning-of-line 0)
11927 (if hiddenp
11928 (save-excursion
11929 (org-back-to-heading t)
11930 (hide-entry))
11931 (org-flag-drawer t))))
11933 (defun org-set-property (property value)
11934 "In the current entry, set PROPERTY to VALUE.
11935 When called interactively, this will prompt for a property name, offering
11936 completion on existing and default properties. And then it will prompt
11937 for a value, offering completion either on allowed values (via an inherited
11938 xxx_ALL property) or on existing values in other instances of this property
11939 in the current file."
11940 (interactive
11941 (let* ((completion-ignore-case t)
11942 (keys (org-buffer-property-keys nil t t))
11943 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
11944 (prop (if (member prop0 keys)
11945 prop0
11946 (or (cdr (assoc (downcase prop0)
11947 (mapcar (lambda (x) (cons (downcase x) x))
11948 keys)))
11949 prop0)))
11950 (cur (org-entry-get nil prop))
11951 (allowed (org-property-get-allowed-values nil prop 'table))
11952 (existing (mapcar 'list (org-property-values prop)))
11953 (val (if allowed
11954 (org-completing-read "Value: " allowed nil 'req-match)
11955 (let (org-completion-use-ido)
11956 (org-completing-read
11957 (concat "Value" (if (and cur (string-match "\\S-" cur))
11958 (concat "[" cur "]") "")
11959 ": ")
11960 existing nil nil "" nil cur)))))
11961 (list prop (if (equal val "") cur val))))
11962 (unless (equal (org-entry-get nil property) value)
11963 (org-entry-put nil property value)))
11965 (defun org-delete-property (property)
11966 "In the current entry, delete PROPERTY."
11967 (interactive
11968 (let* ((completion-ignore-case t)
11969 (prop (org-ido-completing-read
11970 "Property: " (org-entry-properties nil 'standard))))
11971 (list prop)))
11972 (message "Property %s %s" property
11973 (if (org-entry-delete nil property)
11974 "deleted"
11975 "was not present in the entry")))
11977 (defun org-delete-property-globally (property)
11978 "Remove PROPERTY globally, from all entries."
11979 (interactive
11980 (let* ((completion-ignore-case t)
11981 (prop (org-ido-completing-read
11982 "Globally remove property: "
11983 (mapcar 'list (org-buffer-property-keys)))))
11984 (list prop)))
11985 (save-excursion
11986 (save-restriction
11987 (widen)
11988 (goto-char (point-min))
11989 (let ((cnt 0))
11990 (while (re-search-forward
11991 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
11992 nil t)
11993 (setq cnt (1+ cnt))
11994 (replace-match ""))
11995 (message "Property \"%s\" removed from %d entries" property cnt)))))
11997 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
11999 (defun org-compute-property-at-point ()
12000 "Compute the property at point.
12001 This looks for an enclosing column format, extracts the operator and
12002 then applies it to the property in the column format's scope."
12003 (interactive)
12004 (unless (org-at-property-p)
12005 (error "Not at a property"))
12006 (let ((prop (org-match-string-no-properties 2)))
12007 (org-columns-get-format-and-top-level)
12008 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
12009 (error "No operator defined for property %s" prop))
12010 (org-columns-compute prop)))
12012 (defun org-property-get-allowed-values (pom property &optional table)
12013 "Get allowed values for the property PROPERTY.
12014 When TABLE is non-nil, return an alist that can directly be used for
12015 completion."
12016 (let (vals)
12017 (cond
12018 ((equal property "TODO")
12019 (setq vals (org-with-point-at pom
12020 (append org-todo-keywords-1 '("")))))
12021 ((equal property "PRIORITY")
12022 (let ((n org-lowest-priority))
12023 (while (>= n org-highest-priority)
12024 (push (char-to-string n) vals)
12025 (setq n (1- n)))))
12026 ((member property org-special-properties))
12028 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
12030 (when (and vals (string-match "\\S-" vals))
12031 (setq vals (car (read-from-string (concat "(" vals ")"))))
12032 (setq vals (mapcar (lambda (x)
12033 (cond ((stringp x) x)
12034 ((numberp x) (number-to-string x))
12035 ((symbolp x) (symbol-name x))
12036 (t "???")))
12037 vals)))))
12038 (if table (mapcar 'list vals) vals)))
12040 (defun org-property-previous-allowed-value (&optional previous)
12041 "Switch to the next allowed value for this property."
12042 (interactive)
12043 (org-property-next-allowed-value t))
12045 (defun org-property-next-allowed-value (&optional previous)
12046 "Switch to the next allowed value for this property."
12047 (interactive)
12048 (unless (org-at-property-p)
12049 (error "Not at a property"))
12050 (let* ((key (match-string 2))
12051 (value (match-string 3))
12052 (allowed (or (org-property-get-allowed-values (point) key)
12053 (and (member value '("[ ]" "[-]" "[X]"))
12054 '("[ ]" "[X]"))))
12055 nval)
12056 (unless allowed
12057 (error "Allowed values for this property have not been defined"))
12058 (if previous (setq allowed (reverse allowed)))
12059 (if (member value allowed)
12060 (setq nval (car (cdr (member value allowed)))))
12061 (setq nval (or nval (car allowed)))
12062 (if (equal nval value)
12063 (error "Only one allowed value for this property"))
12064 (org-at-property-p)
12065 (replace-match (concat " :" key ": " nval) t t)
12066 (org-indent-line-function)
12067 (beginning-of-line 1)
12068 (skip-chars-forward " \t")))
12070 (defun org-find-entry-with-id (ident)
12071 "Locate the entry that contains the ID property with exact value IDENT.
12072 IDENT can be a string, a symbol or a number, this function will search for
12073 the string representation of it.
12074 Return the position where this entry starts, or nil if there is no such entry."
12075 (interactive "sID: ")
12076 (let ((id (cond
12077 ((stringp ident) ident)
12078 ((symbol-name ident) (symbol-name ident))
12079 ((numberp ident) (number-to-string ident))
12080 (t (error "IDENT %s must be a string, symbol or number" ident))))
12081 (case-fold-search nil))
12082 (save-excursion
12083 (save-restriction
12084 (widen)
12085 (goto-char (point-min))
12086 (when (re-search-forward
12087 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
12088 nil t)
12089 (org-back-to-heading t)
12090 (point))))))
12092 ;;;; Timestamps
12094 (defvar org-last-changed-timestamp nil)
12095 (defvar org-last-inserted-timestamp nil
12096 "The last time stamp inserted with `org-insert-time-stamp'.")
12097 (defvar org-time-was-given) ; dynamically scoped parameter
12098 (defvar org-end-time-was-given) ; dynamically scoped parameter
12099 (defvar org-ts-what) ; dynamically scoped parameter
12101 (defun org-time-stamp (arg &optional inactive)
12102 "Prompt for a date/time and insert a time stamp.
12103 If the user specifies a time like HH:MM, or if this command is called
12104 with a prefix argument, the time stamp will contain date and time.
12105 Otherwise, only the date will be included. All parts of a date not
12106 specified by the user will be filled in from the current date/time.
12107 So if you press just return without typing anything, the time stamp
12108 will represent the current date/time. If there is already a timestamp
12109 at the cursor, it will be modified."
12110 (interactive "P")
12111 (let* ((ts nil)
12112 (default-time
12113 ;; Default time is either today, or, when entering a range,
12114 ;; the range start.
12115 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
12116 (save-excursion
12117 (re-search-backward
12118 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
12119 (- (point) 20) t)))
12120 (apply 'encode-time (org-parse-time-string (match-string 1)))
12121 (current-time)))
12122 (default-input (and ts (org-get-compact-tod ts)))
12123 org-time-was-given org-end-time-was-given time)
12124 (cond
12125 ((and (org-at-timestamp-p t)
12126 (memq last-command '(org-time-stamp org-time-stamp-inactive))
12127 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
12128 (insert "--")
12129 (setq time (let ((this-command this-command))
12130 (org-read-date arg 'totime nil nil
12131 default-time default-input)))
12132 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
12133 ((org-at-timestamp-p t)
12134 (setq time (let ((this-command this-command))
12135 (org-read-date arg 'totime nil nil default-time default-input)))
12136 (when (org-at-timestamp-p t) ; just to get the match data
12137 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
12138 (replace-match "")
12139 (setq org-last-changed-timestamp
12140 (org-insert-time-stamp
12141 time (or org-time-was-given arg)
12142 inactive nil nil (list org-end-time-was-given))))
12143 (message "Timestamp updated"))
12145 (setq time (let ((this-command this-command))
12146 (org-read-date arg 'totime nil nil default-time default-input)))
12147 (org-insert-time-stamp time (or org-time-was-given arg) inactive
12148 nil nil (list org-end-time-was-given))))))
12150 ;; FIXME: can we use this for something else, like computing time differences?
12151 (defun org-get-compact-tod (s)
12152 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
12153 (let* ((t1 (match-string 1 s))
12154 (h1 (string-to-number (match-string 2 s)))
12155 (m1 (string-to-number (match-string 3 s)))
12156 (t2 (and (match-end 4) (match-string 5 s)))
12157 (h2 (and t2 (string-to-number (match-string 6 s))))
12158 (m2 (and t2 (string-to-number (match-string 7 s))))
12159 dh dm)
12160 (if (not t2)
12162 (setq dh (- h2 h1) dm (- m2 m1))
12163 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
12164 (concat t1 "+" (number-to-string dh)
12165 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
12167 (defun org-time-stamp-inactive (&optional arg)
12168 "Insert an inactive time stamp.
12169 An inactive time stamp is enclosed in square brackets instead of angle
12170 brackets. It is inactive in the sense that it does not trigger agenda entries,
12171 does not link to the calendar and cannot be changed with the S-cursor keys.
12172 So these are more for recording a certain time/date."
12173 (interactive "P")
12174 (org-time-stamp arg 'inactive))
12176 (defvar org-date-ovl (org-make-overlay 1 1))
12177 (org-overlay-put org-date-ovl 'face 'org-warning)
12178 (org-detach-overlay org-date-ovl)
12180 (defvar org-ans1) ; dynamically scoped parameter
12181 (defvar org-ans2) ; dynamically scoped parameter
12183 (defvar org-plain-time-of-day-regexp) ; defined below
12185 (defvar org-overriding-default-time nil) ; dynamically scoped
12186 (defvar org-read-date-overlay nil)
12187 (defvar org-dcst nil) ; dynamically scoped
12188 (defvar org-read-date-history nil)
12189 (defvar org-read-date-final-answer nil)
12191 (defun org-read-date (&optional with-time to-time from-string prompt
12192 default-time default-input)
12193 "Read a date, possibly a time, and make things smooth for the user.
12194 The prompt will suggest to enter an ISO date, but you can also enter anything
12195 which will at least partially be understood by `parse-time-string'.
12196 Unrecognized parts of the date will default to the current day, month, year,
12197 hour and minute. If this command is called to replace a timestamp at point,
12198 of to enter the second timestamp of a range, the default time is taken from the
12199 existing stamp. For example,
12200 3-2-5 --> 2003-02-05
12201 feb 15 --> currentyear-02-15
12202 sep 12 9 --> 2009-09-12
12203 12:45 --> today 12:45
12204 22 sept 0:34 --> currentyear-09-22 0:34
12205 12 --> currentyear-currentmonth-12
12206 Fri --> nearest Friday (today or later)
12207 etc.
12209 Furthermore you can specify a relative date by giving, as the *first* thing
12210 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
12211 change in days weeks, months, years.
12212 With a single plus or minus, the date is relative to today. With a double
12213 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
12214 +4d --> four days from today
12215 +4 --> same as above
12216 +2w --> two weeks from today
12217 ++5 --> five days from default date
12219 The function understands only English month and weekday abbreviations,
12220 but this can be configured with the variables `parse-time-months' and
12221 `parse-time-weekdays'.
12223 While prompting, a calendar is popped up - you can also select the
12224 date with the mouse (button 1). The calendar shows a period of three
12225 months. To scroll it to other months, use the keys `>' and `<'.
12226 If you don't like the calendar, turn it off with
12227 \(setq org-read-date-popup-calendar nil)
12229 With optional argument TO-TIME, the date will immediately be converted
12230 to an internal time.
12231 With an optional argument WITH-TIME, the prompt will suggest to also
12232 insert a time. Note that when WITH-TIME is not set, you can still
12233 enter a time, and this function will inform the calling routine about
12234 this change. The calling routine may then choose to change the format
12235 used to insert the time stamp into the buffer to include the time.
12236 With optional argument FROM-STRING, read from this string instead from
12237 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
12238 the time/date that is used for everything that is not specified by the
12239 user."
12240 (require 'parse-time)
12241 (let* ((org-time-stamp-rounding-minutes
12242 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
12243 (org-dcst org-display-custom-times)
12244 (ct (org-current-time))
12245 (def (or org-overriding-default-time default-time ct))
12246 (defdecode (decode-time def))
12247 (dummy (progn
12248 (when (< (nth 2 defdecode) org-extend-today-until)
12249 (setcar (nthcdr 2 defdecode) -1)
12250 (setcar (nthcdr 1 defdecode) 59)
12251 (setq def (apply 'encode-time defdecode)
12252 defdecode (decode-time def)))))
12253 (calendar-frame-setup nil)
12254 (calendar-move-hook nil)
12255 (calendar-view-diary-initially-flag nil)
12256 (view-diary-entries-initially nil)
12257 (calendar-view-holidays-initially-flag nil)
12258 (view-calendar-holidays-initially nil)
12259 (timestr (format-time-string
12260 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
12261 (prompt (concat (if prompt (concat prompt " ") "")
12262 (format "Date+time [%s]: " timestr)))
12263 ans (org-ans0 "") org-ans1 org-ans2 final)
12265 (cond
12266 (from-string (setq ans from-string))
12267 (org-read-date-popup-calendar
12268 (save-excursion
12269 (save-window-excursion
12270 (calendar)
12271 (calendar-forward-day (- (time-to-days def)
12272 (calendar-absolute-from-gregorian
12273 (calendar-current-date))))
12274 (org-eval-in-calendar nil t)
12275 (let* ((old-map (current-local-map))
12276 (map (copy-keymap calendar-mode-map))
12277 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12278 (org-defkey map (kbd "RET") 'org-calendar-select)
12279 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
12280 'org-calendar-select-mouse)
12281 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
12282 'org-calendar-select-mouse)
12283 (org-defkey minibuffer-local-map [(meta shift left)]
12284 (lambda () (interactive)
12285 (org-eval-in-calendar '(calendar-backward-month 1))))
12286 (org-defkey minibuffer-local-map [(meta shift right)]
12287 (lambda () (interactive)
12288 (org-eval-in-calendar '(calendar-forward-month 1))))
12289 (org-defkey minibuffer-local-map [(meta shift up)]
12290 (lambda () (interactive)
12291 (org-eval-in-calendar '(calendar-backward-year 1))))
12292 (org-defkey minibuffer-local-map [(meta shift down)]
12293 (lambda () (interactive)
12294 (org-eval-in-calendar '(calendar-forward-year 1))))
12295 (org-defkey minibuffer-local-map [?\e (shift left)]
12296 (lambda () (interactive)
12297 (org-eval-in-calendar '(calendar-backward-month 1))))
12298 (org-defkey minibuffer-local-map [?\e (shift right)]
12299 (lambda () (interactive)
12300 (org-eval-in-calendar '(calendar-forward-month 1))))
12301 (org-defkey minibuffer-local-map [?\e (shift up)]
12302 (lambda () (interactive)
12303 (org-eval-in-calendar '(calendar-backward-year 1))))
12304 (org-defkey minibuffer-local-map [?\e (shift down)]
12305 (lambda () (interactive)
12306 (org-eval-in-calendar '(calendar-forward-year 1))))
12307 (org-defkey minibuffer-local-map [(shift up)]
12308 (lambda () (interactive)
12309 (org-eval-in-calendar '(calendar-backward-week 1))))
12310 (org-defkey minibuffer-local-map [(shift down)]
12311 (lambda () (interactive)
12312 (org-eval-in-calendar '(calendar-forward-week 1))))
12313 (org-defkey minibuffer-local-map [(shift left)]
12314 (lambda () (interactive)
12315 (org-eval-in-calendar '(calendar-backward-day 1))))
12316 (org-defkey minibuffer-local-map [(shift right)]
12317 (lambda () (interactive)
12318 (org-eval-in-calendar '(calendar-forward-day 1))))
12319 (org-defkey minibuffer-local-map ">"
12320 (lambda () (interactive)
12321 (org-eval-in-calendar '(scroll-calendar-left 1))))
12322 (org-defkey minibuffer-local-map "<"
12323 (lambda () (interactive)
12324 (org-eval-in-calendar '(scroll-calendar-right 1))))
12325 (run-hooks 'org-read-date-minibuffer-setup-hook)
12326 (unwind-protect
12327 (progn
12328 (use-local-map map)
12329 (add-hook 'post-command-hook 'org-read-date-display)
12330 (setq org-ans0 (read-string prompt default-input
12331 'org-read-date-history nil))
12332 ;; org-ans0: from prompt
12333 ;; org-ans1: from mouse click
12334 ;; org-ans2: from calendar motion
12335 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
12336 (remove-hook 'post-command-hook 'org-read-date-display)
12337 (use-local-map old-map)
12338 (when org-read-date-overlay
12339 (org-delete-overlay org-read-date-overlay)
12340 (setq org-read-date-overlay nil)))))))
12342 (t ; Naked prompt only
12343 (unwind-protect
12344 (setq ans (read-string prompt default-input
12345 'org-read-date-history timestr))
12346 (when org-read-date-overlay
12347 (org-delete-overlay org-read-date-overlay)
12348 (setq org-read-date-overlay nil)))))
12350 (setq final (org-read-date-analyze ans def defdecode))
12351 (setq org-read-date-final-answer ans)
12353 (if to-time
12354 (apply 'encode-time final)
12355 (if (and (boundp 'org-time-was-given) org-time-was-given)
12356 (format "%04d-%02d-%02d %02d:%02d"
12357 (nth 5 final) (nth 4 final) (nth 3 final)
12358 (nth 2 final) (nth 1 final))
12359 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
12361 (defvar def)
12362 (defvar defdecode)
12363 (defvar with-time)
12364 (defun org-read-date-display ()
12365 "Display the current date prompt interpretation in the minibuffer."
12366 (when org-read-date-display-live
12367 (when org-read-date-overlay
12368 (org-delete-overlay org-read-date-overlay))
12369 (let ((p (point)))
12370 (end-of-line 1)
12371 (while (not (equal (buffer-substring
12372 (max (point-min) (- (point) 4)) (point))
12373 " "))
12374 (insert " "))
12375 (goto-char p))
12376 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
12377 " " (or org-ans1 org-ans2)))
12378 (org-end-time-was-given nil)
12379 (f (org-read-date-analyze ans def defdecode))
12380 (fmts (if org-dcst
12381 org-time-stamp-custom-formats
12382 org-time-stamp-formats))
12383 (fmt (if (or with-time
12384 (and (boundp 'org-time-was-given) org-time-was-given))
12385 (cdr fmts)
12386 (car fmts)))
12387 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
12388 (when (and org-end-time-was-given
12389 (string-match org-plain-time-of-day-regexp txt))
12390 (setq txt (concat (substring txt 0 (match-end 0)) "-"
12391 org-end-time-was-given
12392 (substring txt (match-end 0)))))
12393 (setq org-read-date-overlay
12394 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
12395 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
12397 (defun org-read-date-analyze (ans def defdecode)
12398 "Analyse the combined answer of the date prompt."
12399 ;; FIXME: cleanup and comment
12400 (let (delta deltan deltaw deltadef year month day
12401 hour minute second wday pm h2 m2 tl wday1
12402 iso-year iso-weekday iso-week iso-year iso-date)
12404 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
12405 (setq ans "+0"))
12407 (when (setq delta (org-read-date-get-relative ans (current-time) def))
12408 (setq ans (replace-match "" t t ans)
12409 deltan (car delta)
12410 deltaw (nth 1 delta)
12411 deltadef (nth 2 delta)))
12413 ;; Check if there is an iso week date in there
12414 ;; If yes, sore the info and postpone interpreting it until the rest
12415 ;; of the parsing is done
12416 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
12417 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
12418 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
12419 iso-week (string-to-number (match-string 2 ans)))
12420 (setq ans (replace-match "" t t ans)))
12422 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
12423 (when (string-match
12424 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
12425 (setq year (if (match-end 2)
12426 (string-to-number (match-string 2 ans))
12427 (string-to-number (format-time-string "%Y")))
12428 month (string-to-number (match-string 3 ans))
12429 day (string-to-number (match-string 4 ans)))
12430 (if (< year 100) (setq year (+ 2000 year)))
12431 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
12432 t nil ans)))
12433 ;; Help matching am/pm times, because `parse-time-string' does not do that.
12434 ;; If there is a time with am/pm, and *no* time without it, we convert
12435 ;; so that matching will be successful.
12436 (loop for i from 1 to 2 do ; twice, for end time as well
12437 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
12438 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
12439 (setq hour (string-to-number (match-string 1 ans))
12440 minute (if (match-end 3)
12441 (string-to-number (match-string 3 ans))
12443 pm (equal ?p
12444 (string-to-char (downcase (match-string 4 ans)))))
12445 (if (and (= hour 12) (not pm))
12446 (setq hour 0)
12447 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
12448 (setq ans (replace-match (format "%02d:%02d" hour minute)
12449 t t ans))))
12451 ;; Check if a time range is given as a duration
12452 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
12453 (setq hour (string-to-number (match-string 1 ans))
12454 h2 (+ hour (string-to-number (match-string 3 ans)))
12455 minute (string-to-number (match-string 2 ans))
12456 m2 (+ minute (if (match-end 5) (string-to-number
12457 (match-string 5 ans))0)))
12458 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
12459 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
12460 t t ans)))
12462 ;; Check if there is a time range
12463 (when (boundp 'org-end-time-was-given)
12464 (setq org-time-was-given nil)
12465 (when (and (string-match org-plain-time-of-day-regexp ans)
12466 (match-end 8))
12467 (setq org-end-time-was-given (match-string 8 ans))
12468 (setq ans (concat (substring ans 0 (match-beginning 7))
12469 (substring ans (match-end 7))))))
12471 (setq tl (parse-time-string ans)
12472 day (or (nth 3 tl) (nth 3 defdecode))
12473 month (or (nth 4 tl)
12474 (if (and org-read-date-prefer-future
12475 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
12476 (1+ (nth 4 defdecode))
12477 (nth 4 defdecode)))
12478 year (or (nth 5 tl)
12479 (if (and org-read-date-prefer-future
12480 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
12481 (1+ (nth 5 defdecode))
12482 (nth 5 defdecode)))
12483 hour (or (nth 2 tl) (nth 2 defdecode))
12484 minute (or (nth 1 tl) (nth 1 defdecode))
12485 second (or (nth 0 tl) 0)
12486 wday (nth 6 tl))
12488 ;; Special date definitions below
12489 (cond
12490 (iso-week
12491 ;; There was an iso week
12492 (setq year (or iso-year year)
12493 day (or iso-weekday wday 1)
12494 wday nil ; to make sure that the trigger below does not match
12495 iso-date (calendar-gregorian-from-absolute
12496 (calendar-absolute-from-iso
12497 (list iso-week day year))))
12498 ; FIXME: Should we also push ISO weeks into the future?
12499 ; (when (and org-read-date-prefer-future
12500 ; (not iso-year)
12501 ; (< (calendar-absolute-from-gregorian iso-date)
12502 ; (time-to-days (current-time))))
12503 ; (setq year (1+ year)
12504 ; iso-date (calendar-gregorian-from-absolute
12505 ; (calendar-absolute-from-iso
12506 ; (list iso-week day year)))))
12507 (setq month (car iso-date)
12508 year (nth 2 iso-date)
12509 day (nth 1 iso-date)))
12510 (deltan
12511 (unless deltadef
12512 (let ((now (decode-time (current-time))))
12513 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
12514 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
12515 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
12516 ((equal deltaw "m") (setq month (+ month deltan)))
12517 ((equal deltaw "y") (setq year (+ year deltan)))))
12518 ((and wday (not (nth 3 tl)))
12519 ;; Weekday was given, but no day, so pick that day in the week
12520 ;; on or after the derived date.
12521 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
12522 (unless (equal wday wday1)
12523 (setq day (+ day (% (- wday wday1 -7) 7))))))
12524 (if (and (boundp 'org-time-was-given)
12525 (nth 2 tl))
12526 (setq org-time-was-given t))
12527 (if (< year 100) (setq year (+ 2000 year)))
12528 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
12529 (list second minute hour day month year)))
12531 (defvar parse-time-weekdays)
12533 (defun org-read-date-get-relative (s today default)
12534 "Check string S for special relative date string.
12535 TODAY and DEFAULT are internal times, for today and for a default.
12536 Return shift list (N what def-flag)
12537 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
12538 N is the number of WHATs to shift.
12539 DEF-FLAG is t when a double ++ or -- indicates shift relative to
12540 the DEFAULT date rather than TODAY."
12541 (when (and
12542 (string-match
12543 (concat
12544 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
12545 "\\([0-9]+\\)?"
12546 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
12547 "\\([ \t]\\|$\\)") s)
12548 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
12549 (let* ((dir (if (> (match-end 1) (match-beginning 1))
12550 (string-to-char (substring (match-string 1 s) -1))
12551 ?+))
12552 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
12553 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
12554 (what (if (match-end 3) (match-string 3 s) "d"))
12555 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
12556 (date (if rel default today))
12557 (wday (nth 6 (decode-time date)))
12558 delta)
12559 (if wday1
12560 (progn
12561 (setq delta (mod (+ 7 (- wday1 wday)) 7))
12562 (if (= dir ?-) (setq delta (- delta 7)))
12563 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
12564 (list delta "d" rel))
12565 (list (* n (if (= dir ?-) -1 1)) what rel)))))
12567 (defun org-eval-in-calendar (form &optional keepdate)
12568 "Eval FORM in the calendar window and return to current window.
12569 Also, store the cursor date in variable org-ans2."
12570 (let ((sf (selected-frame))
12571 (sw (selected-window)))
12572 (select-window (get-buffer-window "*Calendar*" t))
12573 (eval form)
12574 (when (and (not keepdate) (calendar-cursor-to-date))
12575 (let* ((date (calendar-cursor-to-date))
12576 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12577 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
12578 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
12579 (select-window sw)
12580 (select-frame-set-input-focus sf)))
12582 (defun org-calendar-select ()
12583 "Return to `org-read-date' with the date currently selected.
12584 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12585 (interactive)
12586 (when (calendar-cursor-to-date)
12587 (let* ((date (calendar-cursor-to-date))
12588 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12589 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12590 (if (active-minibuffer-window) (exit-minibuffer))))
12592 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
12593 "Insert a date stamp for the date given by the internal TIME.
12594 WITH-HM means, use the stamp format that includes the time of the day.
12595 INACTIVE means use square brackets instead of angular ones, so that the
12596 stamp will not contribute to the agenda.
12597 PRE and POST are optional strings to be inserted before and after the
12598 stamp.
12599 The command returns the inserted time stamp."
12600 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
12601 stamp)
12602 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
12603 (insert-before-markers (or pre ""))
12604 (insert-before-markers (setq stamp (format-time-string fmt time)))
12605 (when (listp extra)
12606 (setq extra (car extra))
12607 (if (and (stringp extra)
12608 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
12609 (setq extra (format "-%02d:%02d"
12610 (string-to-number (match-string 1 extra))
12611 (string-to-number (match-string 2 extra))))
12612 (setq extra nil)))
12613 (when extra
12614 (backward-char 1)
12615 (insert-before-markers extra)
12616 (forward-char 1))
12617 (insert-before-markers (or post ""))
12618 (setq org-last-inserted-timestamp stamp)))
12620 (defun org-toggle-time-stamp-overlays ()
12621 "Toggle the use of custom time stamp formats."
12622 (interactive)
12623 (setq org-display-custom-times (not org-display-custom-times))
12624 (unless org-display-custom-times
12625 (let ((p (point-min)) (bmp (buffer-modified-p)))
12626 (while (setq p (next-single-property-change p 'display))
12627 (if (and (get-text-property p 'display)
12628 (eq (get-text-property p 'face) 'org-date))
12629 (remove-text-properties
12630 p (setq p (next-single-property-change p 'display))
12631 '(display t))))
12632 (set-buffer-modified-p bmp)))
12633 (if (featurep 'xemacs)
12634 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12635 (org-restart-font-lock)
12636 (setq org-table-may-need-update t)
12637 (if org-display-custom-times
12638 (message "Time stamps are overlayed with custom format")
12639 (message "Time stamp overlays removed")))
12641 (defun org-display-custom-time (beg end)
12642 "Overlay modified time stamp format over timestamp between BEG and END."
12643 (let* ((ts (buffer-substring beg end))
12644 t1 w1 with-hm tf time str w2 (off 0))
12645 (save-match-data
12646 (setq t1 (org-parse-time-string ts t))
12647 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
12648 (setq off (- (match-end 0) (match-beginning 0)))))
12649 (setq end (- end off))
12650 (setq w1 (- end beg)
12651 with-hm (and (nth 1 t1) (nth 2 t1))
12652 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
12653 time (org-fix-decoded-time t1)
12654 str (org-add-props
12655 (format-time-string
12656 (substring tf 1 -1) (apply 'encode-time time))
12657 nil 'mouse-face 'highlight)
12658 w2 (length str))
12659 (if (not (= w2 w1))
12660 (add-text-properties (1+ beg) (+ 2 beg)
12661 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12662 (if (featurep 'xemacs)
12663 (progn
12664 (put-text-property beg end 'invisible t)
12665 (put-text-property beg end 'end-glyph (make-glyph str)))
12666 (put-text-property beg end 'display str))))
12668 (defun org-translate-time (string)
12669 "Translate all timestamps in STRING to custom format.
12670 But do this only if the variable `org-display-custom-times' is set."
12671 (when org-display-custom-times
12672 (save-match-data
12673 (let* ((start 0)
12674 (re org-ts-regexp-both)
12675 t1 with-hm inactive tf time str beg end)
12676 (while (setq start (string-match re string start))
12677 (setq beg (match-beginning 0)
12678 end (match-end 0)
12679 t1 (save-match-data
12680 (org-parse-time-string (substring string beg end) t))
12681 with-hm (and (nth 1 t1) (nth 2 t1))
12682 inactive (equal (substring string beg (1+ beg)) "[")
12683 tf (funcall (if with-hm 'cdr 'car)
12684 org-time-stamp-custom-formats)
12685 time (org-fix-decoded-time t1)
12686 str (format-time-string
12687 (concat
12688 (if inactive "[" "<") (substring tf 1 -1)
12689 (if inactive "]" ">"))
12690 (apply 'encode-time time))
12691 string (replace-match str t t string)
12692 start (+ start (length str)))))))
12693 string)
12695 (defun org-fix-decoded-time (time)
12696 "Set 0 instead of nil for the first 6 elements of time.
12697 Don't touch the rest."
12698 (let ((n 0))
12699 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12701 (defun org-days-to-time (timestamp-string)
12702 "Difference between TIMESTAMP-STRING and now in days."
12703 (- (time-to-days (org-time-string-to-time timestamp-string))
12704 (time-to-days (current-time))))
12706 (defun org-deadline-close (timestamp-string &optional ndays)
12707 "Is the time in TIMESTAMP-STRING close to the current date?"
12708 (setq ndays (or ndays (org-get-wdays timestamp-string)))
12709 (and (< (org-days-to-time timestamp-string) ndays)
12710 (not (org-entry-is-done-p))))
12712 (defun org-get-wdays (ts)
12713 "Get the deadline lead time appropriate for timestring TS."
12714 (cond
12715 ((<= org-deadline-warning-days 0)
12716 ;; 0 or negative, enforce this value no matter what
12717 (- org-deadline-warning-days))
12718 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
12719 ;; lead time is specified.
12720 (floor (* (string-to-number (match-string 1 ts))
12721 (cdr (assoc (match-string 2 ts)
12722 '(("d" . 1) ("w" . 7)
12723 ("m" . 30.4) ("y" . 365.25)))))))
12724 ;; go for the default.
12725 (t org-deadline-warning-days)))
12727 (defun org-calendar-select-mouse (ev)
12728 "Return to `org-read-date' with the date currently selected.
12729 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12730 (interactive "e")
12731 (mouse-set-point ev)
12732 (when (calendar-cursor-to-date)
12733 (let* ((date (calendar-cursor-to-date))
12734 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12735 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12736 (if (active-minibuffer-window) (exit-minibuffer))))
12738 (defun org-check-deadlines (ndays)
12739 "Check if there are any deadlines due or past due.
12740 A deadline is considered due if it happens within `org-deadline-warning-days'
12741 days from today's date. If the deadline appears in an entry marked DONE,
12742 it is not shown. The prefix arg NDAYS can be used to test that many
12743 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12744 (interactive "P")
12745 (let* ((org-warn-days
12746 (cond
12747 ((equal ndays '(4)) 100000)
12748 (ndays (prefix-numeric-value ndays))
12749 (t (abs org-deadline-warning-days))))
12750 (case-fold-search nil)
12751 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12752 (callback
12753 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12755 (message "%d deadlines past-due or due within %d days"
12756 (org-occur regexp nil callback)
12757 org-warn-days)))
12759 (defun org-check-before-date (date)
12760 "Check if there are deadlines or scheduled entries before DATE."
12761 (interactive (list (org-read-date)))
12762 (let ((case-fold-search nil)
12763 (regexp (concat "\\<\\(" org-deadline-string
12764 "\\|" org-scheduled-string
12765 "\\) *<\\([^>]+\\)>"))
12766 (callback
12767 (lambda () (time-less-p
12768 (org-time-string-to-time (match-string 2))
12769 (org-time-string-to-time date)))))
12770 (message "%d entries before %s"
12771 (org-occur regexp nil callback) date)))
12773 (defun org-check-after-date (date)
12774 "Check if there are deadlines or scheduled entries after DATE."
12775 (interactive (list (org-read-date)))
12776 (let ((case-fold-search nil)
12777 (regexp (concat "\\<\\(" org-deadline-string
12778 "\\|" org-scheduled-string
12779 "\\) *<\\([^>]+\\)>"))
12780 (callback
12781 (lambda () (not
12782 (time-less-p
12783 (org-time-string-to-time (match-string 2))
12784 (org-time-string-to-time date))))))
12785 (message "%d entries after %s"
12786 (org-occur regexp nil callback) date)))
12788 (defun org-evaluate-time-range (&optional to-buffer)
12789 "Evaluate a time range by computing the difference between start and end.
12790 Normally the result is just printed in the echo area, but with prefix arg
12791 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12792 If the time range is actually in a table, the result is inserted into the
12793 next column.
12794 For time difference computation, a year is assumed to be exactly 365
12795 days in order to avoid rounding problems."
12796 (interactive "P")
12798 (org-clock-update-time-maybe)
12799 (save-excursion
12800 (unless (org-at-date-range-p t)
12801 (goto-char (point-at-bol))
12802 (re-search-forward org-tr-regexp-both (point-at-eol) t))
12803 (if (not (org-at-date-range-p t))
12804 (error "Not at a time-stamp range, and none found in current line")))
12805 (let* ((ts1 (match-string 1))
12806 (ts2 (match-string 2))
12807 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12808 (match-end (match-end 0))
12809 (time1 (org-time-string-to-time ts1))
12810 (time2 (org-time-string-to-time ts2))
12811 (t1 (time-to-seconds time1))
12812 (t2 (time-to-seconds time2))
12813 (diff (abs (- t2 t1)))
12814 (negative (< (- t2 t1) 0))
12815 ;; (ys (floor (* 365 24 60 60)))
12816 (ds (* 24 60 60))
12817 (hs (* 60 60))
12818 (fy "%dy %dd %02d:%02d")
12819 (fy1 "%dy %dd")
12820 (fd "%dd %02d:%02d")
12821 (fd1 "%dd")
12822 (fh "%02d:%02d")
12823 y d h m align)
12824 (if havetime
12825 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12827 d (floor (/ diff ds)) diff (mod diff ds)
12828 h (floor (/ diff hs)) diff (mod diff hs)
12829 m (floor (/ diff 60)))
12830 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12832 d (floor (+ (/ diff ds) 0.5))
12833 h 0 m 0))
12834 (if (not to-buffer)
12835 (message "%s" (org-make-tdiff-string y d h m))
12836 (if (org-at-table-p)
12837 (progn
12838 (goto-char match-end)
12839 (setq align t)
12840 (and (looking-at " *|") (goto-char (match-end 0))))
12841 (goto-char match-end))
12842 (if (looking-at
12843 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12844 (replace-match ""))
12845 (if negative (insert " -"))
12846 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12847 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12848 (insert " " (format fh h m))))
12849 (if align (org-table-align))
12850 (message "Time difference inserted")))))
12852 (defun org-make-tdiff-string (y d h m)
12853 (let ((fmt "")
12854 (l nil))
12855 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12856 l (push y l)))
12857 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12858 l (push d l)))
12859 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12860 l (push h l)))
12861 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12862 l (push m l)))
12863 (apply 'format fmt (nreverse l))))
12865 (defun org-time-string-to-time (s)
12866 (apply 'encode-time (org-parse-time-string s)))
12867 (defun org-time-string-to-seconds (s)
12868 (time-to-seconds (org-time-string-to-time s)))
12870 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
12871 "Convert a time stamp to an absolute day number.
12872 If there is a specifyer for a cyclic time stamp, get the closest date to
12873 DAYNR.
12874 PREFER and SHOW-ALL are passed through to `org-closest-date'.
12875 the variable date is bound by the calendar when this is called."
12876 (cond
12877 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
12878 (if (org-diary-sexp-entry (match-string 1 s) "" date)
12879 daynr
12880 (+ daynr 1000)))
12881 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
12882 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
12883 (time-to-days (current-time))) (match-string 0 s)
12884 prefer show-all))
12885 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
12887 (defun org-days-to-iso-week (days)
12888 "Return the iso week number."
12889 (require 'cal-iso)
12890 (car (calendar-iso-from-absolute days)))
12892 (defun org-small-year-to-year (year)
12893 "Convert 2-digit years into 4-digit years.
12894 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
12895 The year 2000 cannot be abbreviated. Any year larger than 99
12896 is returned unchanged."
12897 (if (< year 38)
12898 (setq year (+ 2000 year))
12899 (if (< year 100)
12900 (setq year (+ 1900 year))))
12901 year)
12903 (defun org-time-from-absolute (d)
12904 "Return the time corresponding to date D.
12905 D may be an absolute day number, or a calendar-type list (month day year)."
12906 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
12907 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
12909 (defun org-calendar-holiday ()
12910 "List of holidays, for Diary display in Org-mode."
12911 (require 'holidays)
12912 (let ((hl (funcall
12913 (if (fboundp 'calendar-check-holidays)
12914 'calendar-check-holidays 'check-calendar-holidays) date)))
12915 (if hl (mapconcat 'identity hl "; "))))
12917 (defun org-diary-sexp-entry (sexp entry date)
12918 "Process a SEXP diary ENTRY for DATE."
12919 (require 'diary-lib)
12920 (let ((result (if calendar-debug-sexp
12921 (let ((stack-trace-on-error t))
12922 (eval (car (read-from-string sexp))))
12923 (condition-case nil
12924 (eval (car (read-from-string sexp)))
12925 (error
12926 (beep)
12927 (message "Bad sexp at line %d in %s: %s"
12928 (org-current-line)
12929 (buffer-file-name) sexp)
12930 (sleep-for 2))))))
12931 (cond ((stringp result) result)
12932 ((and (consp result)
12933 (stringp (cdr result))) (cdr result))
12934 (result entry)
12935 (t nil))))
12937 (defun org-diary-to-ical-string (frombuf)
12938 "Get iCalendar entries from diary entries in buffer FROMBUF.
12939 This uses the icalendar.el library."
12940 (let* ((tmpdir (if (featurep 'xemacs)
12941 (temp-directory)
12942 temporary-file-directory))
12943 (tmpfile (make-temp-name
12944 (expand-file-name "orgics" tmpdir)))
12945 buf rtn b e)
12946 (save-excursion
12947 (set-buffer frombuf)
12948 (icalendar-export-region (point-min) (point-max) tmpfile)
12949 (setq buf (find-buffer-visiting tmpfile))
12950 (set-buffer buf)
12951 (goto-char (point-min))
12952 (if (re-search-forward "^BEGIN:VEVENT" nil t)
12953 (setq b (match-beginning 0)))
12954 (goto-char (point-max))
12955 (if (re-search-backward "^END:VEVENT" nil t)
12956 (setq e (match-end 0)))
12957 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
12958 (kill-buffer buf)
12959 (delete-file tmpfile)
12960 rtn))
12962 (defun org-closest-date (start current change prefer show-all)
12963 "Find the date closest to CURRENT that is consistent with START and CHANGE.
12964 When PREFER is `past' return a date that is either CURRENT or past.
12965 When PREFER is `future', return a date that is either CURRENT or future.
12966 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
12967 ;; Make the proper lists from the dates
12968 (catch 'exit
12969 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
12970 dn dw sday cday n1 n2 n0
12971 d m y y1 y2 date1 date2 nmonths nm ny m2)
12973 (setq start (org-date-to-gregorian start)
12974 current (org-date-to-gregorian
12975 (if show-all
12976 current
12977 (time-to-days (current-time))))
12978 sday (calendar-absolute-from-gregorian start)
12979 cday (calendar-absolute-from-gregorian current))
12981 (if (<= cday sday) (throw 'exit sday))
12983 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
12984 (setq dn (string-to-number (match-string 1 change))
12985 dw (cdr (assoc (match-string 2 change) a1)))
12986 (error "Invalid change specifyer: %s" change))
12987 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
12988 (cond
12989 ((eq dw 'day)
12990 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
12991 n2 (+ n1 dn)))
12992 ((eq dw 'year)
12993 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
12994 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
12995 (setq date1 (list m d y1)
12996 n1 (calendar-absolute-from-gregorian date1)
12997 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
12998 n2 (calendar-absolute-from-gregorian date2)))
12999 ((eq dw 'month)
13000 ;; approx number of month between the two dates
13001 (setq nmonths (floor (/ (- cday sday) 30.436875)))
13002 ;; How often does dn fit in there?
13003 (setq d (nth 1 start) m (car start) y (nth 2 start)
13004 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
13005 m (+ m nm)
13006 ny (floor (/ m 12))
13007 y (+ y ny)
13008 m (- m (* ny 12)))
13009 (while (> m 12) (setq m (- m 12) y (1+ y)))
13010 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
13011 (setq m2 (+ m dn) y2 y)
13012 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13013 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
13014 (while (<= n2 cday)
13015 (setq n1 n2 m m2 y y2)
13016 (setq m2 (+ m dn) y2 y)
13017 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13018 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
13019 ;; Make sure n1 is the earlier date
13020 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
13021 (if show-all
13022 (cond
13023 ((eq prefer 'past) n1)
13024 ((eq prefer 'future) (if (= cday n1) n1 n2))
13025 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
13026 (cond
13027 ((eq prefer 'past) n1)
13028 ((eq prefer 'future) (if (= cday n1) n1 n2))
13029 (t (if (= cday n1) n1 n2)))))))
13031 (defun org-date-to-gregorian (date)
13032 "Turn any specification of DATE into a gregorian date for the calendar."
13033 (cond ((integerp date) (calendar-gregorian-from-absolute date))
13034 ((and (listp date) (= (length date) 3)) date)
13035 ((stringp date)
13036 (setq date (org-parse-time-string date))
13037 (list (nth 4 date) (nth 3 date) (nth 5 date)))
13038 ((listp date)
13039 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
13041 (defun org-parse-time-string (s &optional nodefault)
13042 "Parse the standard Org-mode time string.
13043 This should be a lot faster than the normal `parse-time-string'.
13044 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
13045 hour and minute fields will be nil if not given."
13046 (if (string-match org-ts-regexp0 s)
13047 (list 0
13048 (if (or (match-beginning 8) (not nodefault))
13049 (string-to-number (or (match-string 8 s) "0")))
13050 (if (or (match-beginning 7) (not nodefault))
13051 (string-to-number (or (match-string 7 s) "0")))
13052 (string-to-number (match-string 4 s))
13053 (string-to-number (match-string 3 s))
13054 (string-to-number (match-string 2 s))
13055 nil nil nil)
13056 (make-list 9 0)))
13058 (defun org-timestamp-up (&optional arg)
13059 "Increase the date item at the cursor by one.
13060 If the cursor is on the year, change the year. If it is on the month or
13061 the day, change that.
13062 With prefix ARG, change by that many units."
13063 (interactive "p")
13064 (org-timestamp-change (prefix-numeric-value arg)))
13066 (defun org-timestamp-down (&optional arg)
13067 "Decrease the date item at the cursor by one.
13068 If the cursor is on the year, change the year. If it is on the month or
13069 the day, change that.
13070 With prefix ARG, change by that many units."
13071 (interactive "p")
13072 (org-timestamp-change (- (prefix-numeric-value arg))))
13074 (defun org-timestamp-up-day (&optional arg)
13075 "Increase the date in the time stamp by one day.
13076 With prefix ARG, change that many days."
13077 (interactive "p")
13078 (if (and (not (org-at-timestamp-p t))
13079 (org-on-heading-p))
13080 (org-todo 'up)
13081 (org-timestamp-change (prefix-numeric-value arg) 'day)))
13083 (defun org-timestamp-down-day (&optional arg)
13084 "Decrease the date in the time stamp by one day.
13085 With prefix ARG, change that many days."
13086 (interactive "p")
13087 (if (and (not (org-at-timestamp-p t))
13088 (org-on-heading-p))
13089 (org-todo 'down)
13090 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
13092 (defun org-at-timestamp-p (&optional inactive-ok)
13093 "Determine if the cursor is in or at a timestamp."
13094 (interactive)
13095 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
13096 (pos (point))
13097 (ans (or (looking-at tsr)
13098 (save-excursion
13099 (skip-chars-backward "^[<\n\r\t")
13100 (if (> (point) (point-min)) (backward-char 1))
13101 (and (looking-at tsr)
13102 (> (- (match-end 0) pos) -1))))))
13103 (and ans
13104 (boundp 'org-ts-what)
13105 (setq org-ts-what
13106 (cond
13107 ((= pos (match-beginning 0)) 'bracket)
13108 ((= pos (1- (match-end 0))) 'bracket)
13109 ((org-pos-in-match-range pos 2) 'year)
13110 ((org-pos-in-match-range pos 3) 'month)
13111 ((org-pos-in-match-range pos 7) 'hour)
13112 ((org-pos-in-match-range pos 8) 'minute)
13113 ((or (org-pos-in-match-range pos 4)
13114 (org-pos-in-match-range pos 5)) 'day)
13115 ((and (> pos (or (match-end 8) (match-end 5)))
13116 (< pos (match-end 0)))
13117 (- pos (or (match-end 8) (match-end 5))))
13118 (t 'day))))
13119 ans))
13121 (defun org-toggle-timestamp-type ()
13122 "Toggle the type (<active> or [inactive]) of a time stamp."
13123 (interactive)
13124 (when (org-at-timestamp-p t)
13125 (let ((beg (match-beginning 0)) (end (match-end 0))
13126 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
13127 (save-excursion
13128 (goto-char beg)
13129 (while (re-search-forward "[][<>]" end t)
13130 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
13131 t t)))
13132 (message "Timestamp is now %sactive"
13133 (if (equal (char-after beg) ?<) "" "in")))))
13135 (defun org-timestamp-change (n &optional what)
13136 "Change the date in the time stamp at point.
13137 The date will be changed by N times WHAT. WHAT can be `day', `month',
13138 `year', `minute', `second'. If WHAT is not given, the cursor position
13139 in the timestamp determines what will be changed."
13140 (let ((pos (point))
13141 with-hm inactive
13142 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
13143 org-ts-what
13144 extra rem
13145 ts time time0)
13146 (if (not (org-at-timestamp-p t))
13147 (error "Not at a timestamp"))
13148 (if (and (not what) (eq org-ts-what 'bracket))
13149 (org-toggle-timestamp-type)
13150 (if (and (not what) (not (eq org-ts-what 'day))
13151 org-display-custom-times
13152 (get-text-property (point) 'display)
13153 (not (get-text-property (1- (point)) 'display)))
13154 (setq org-ts-what 'day))
13155 (setq org-ts-what (or what org-ts-what)
13156 inactive (= (char-after (match-beginning 0)) ?\[)
13157 ts (match-string 0))
13158 (replace-match "")
13159 (if (string-match
13160 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
13162 (setq extra (match-string 1 ts)))
13163 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
13164 (setq with-hm t))
13165 (setq time0 (org-parse-time-string ts))
13166 (when (and (eq org-ts-what 'minute)
13167 (eq current-prefix-arg nil))
13168 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
13169 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
13170 (setcar (cdr time0) (+ (nth 1 time0)
13171 (if (> n 0) (- rem) (- dm rem))))))
13172 (setq time
13173 (encode-time (or (car time0) 0)
13174 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
13175 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
13176 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
13177 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
13178 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
13179 (nthcdr 6 time0)))
13180 (when (and (member org-ts-what '(hour minute))
13181 extra
13182 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
13183 (setq extra (org-modify-ts-extra
13184 extra
13185 (if (eq org-ts-what 'hour) 2 5)
13186 n dm)))
13187 (when (integerp org-ts-what)
13188 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
13189 (if (eq what 'calendar)
13190 (let ((cal-date (org-get-date-from-calendar)))
13191 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
13192 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
13193 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
13194 (setcar time0 (or (car time0) 0))
13195 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
13196 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
13197 (setq time (apply 'encode-time time0))))
13198 (setq org-last-changed-timestamp
13199 (org-insert-time-stamp time with-hm inactive nil nil extra))
13200 (org-clock-update-time-maybe)
13201 (goto-char pos)
13202 ;; Try to recenter the calendar window, if any
13203 (if (and org-calendar-follow-timestamp-change
13204 (get-buffer-window "*Calendar*" t)
13205 (memq org-ts-what '(day month year)))
13206 (org-recenter-calendar (time-to-days time))))))
13208 (defun org-modify-ts-extra (s pos n dm)
13209 "Change the different parts of the lead-time and repeat fields in timestamp."
13210 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
13211 ng h m new rem)
13212 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
13213 (cond
13214 ((or (org-pos-in-match-range pos 2)
13215 (org-pos-in-match-range pos 3))
13216 (setq m (string-to-number (match-string 3 s))
13217 h (string-to-number (match-string 2 s)))
13218 (if (org-pos-in-match-range pos 2)
13219 (setq h (+ h n))
13220 (setq n (* dm (org-no-warnings (signum n))))
13221 (when (not (= 0 (setq rem (% m dm))))
13222 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
13223 (setq m (+ m n)))
13224 (if (< m 0) (setq m (+ m 60) h (1- h)))
13225 (if (> m 59) (setq m (- m 60) h (1+ h)))
13226 (setq h (min 24 (max 0 h)))
13227 (setq ng 1 new (format "-%02d:%02d" h m)))
13228 ((org-pos-in-match-range pos 6)
13229 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
13230 ((org-pos-in-match-range pos 5)
13231 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
13233 ((org-pos-in-match-range pos 9)
13234 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
13235 ((org-pos-in-match-range pos 8)
13236 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
13238 (when ng
13239 (setq s (concat
13240 (substring s 0 (match-beginning ng))
13242 (substring s (match-end ng))))))
13245 (defun org-recenter-calendar (date)
13246 "If the calendar is visible, recenter it to DATE."
13247 (let* ((win (selected-window))
13248 (cwin (get-buffer-window "*Calendar*" t))
13249 (calendar-move-hook nil))
13250 (when cwin
13251 (select-window cwin)
13252 (calendar-goto-date (if (listp date) date
13253 (calendar-gregorian-from-absolute date)))
13254 (select-window win))))
13256 (defun org-goto-calendar (&optional arg)
13257 "Go to the Emacs calendar at the current date.
13258 If there is a time stamp in the current line, go to that date.
13259 A prefix ARG can be used to force the current date."
13260 (interactive "P")
13261 (let ((tsr org-ts-regexp) diff
13262 (calendar-move-hook nil)
13263 (calendar-view-holidays-initially-flag nil)
13264 (view-calendar-holidays-initially nil)
13265 (calendar-view-diary-initially-flag nil)
13266 (view-diary-entries-initially nil))
13267 (if (or (org-at-timestamp-p)
13268 (save-excursion
13269 (beginning-of-line 1)
13270 (looking-at (concat ".*" tsr))))
13271 (let ((d1 (time-to-days (current-time)))
13272 (d2 (time-to-days
13273 (org-time-string-to-time (match-string 1)))))
13274 (setq diff (- d2 d1))))
13275 (calendar)
13276 (calendar-goto-today)
13277 (if (and diff (not arg)) (calendar-forward-day diff))))
13279 (defun org-get-date-from-calendar ()
13280 "Return a list (month day year) of date at point in calendar."
13281 (with-current-buffer "*Calendar*"
13282 (save-match-data
13283 (calendar-cursor-to-date))))
13285 (defun org-date-from-calendar ()
13286 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
13287 If there is already a time stamp at the cursor position, update it."
13288 (interactive)
13289 (if (org-at-timestamp-p t)
13290 (org-timestamp-change 0 'calendar)
13291 (let ((cal-date (org-get-date-from-calendar)))
13292 (org-insert-time-stamp
13293 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
13295 (defun org-minutes-to-hh:mm-string (m)
13296 "Compute H:MM from a number of minutes."
13297 (let ((h (/ m 60)))
13298 (setq m (- m (* 60 h)))
13299 (format org-time-clocksum-format h m)))
13301 (defun org-hh:mm-string-to-minutes (s)
13302 "Convert a string H:MM to a number of minutes.
13303 If the string is just a number, interprete it as minutes.
13304 In fact, the first hh:mm or number in the string will be taken,
13305 there can be extra stuff in the string.
13306 If no number is found, the return value is 0."
13307 (cond
13308 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
13309 (+ (* (string-to-number (match-string 1 s)) 60)
13310 (string-to-number (match-string 2 s))))
13311 ((string-match "\\([0-9]+\\)" s)
13312 (string-to-number (match-string 1 s)))
13313 (t 0)))
13315 ;;;; Files
13317 (defun org-save-all-org-buffers ()
13318 "Save all Org-mode buffers without user confirmation."
13319 (interactive)
13320 (message "Saving all Org-mode buffers...")
13321 (save-some-buffers t 'org-mode-p)
13322 (when (featurep 'org-id) (org-id-locations-save))
13323 (message "Saving all Org-mode buffers... done"))
13325 (defun org-revert-all-org-buffers ()
13326 "Revert all Org-mode buffers.
13327 Prompt for confirmation when there are unsaved changes.
13328 Be sure you know what you are doing before letting this function
13329 overwrite your changes.
13331 This function is useful in a setup where one tracks org files
13332 with a version control system, to revert on one machine after pulling
13333 changes from another. I believe the procedure must be like this:
13335 1. M-x org-save-all-org-buffers
13336 2. Pull changes from the other machine, resolve conflicts
13337 3. M-x org-revert-all-org-buffers"
13338 (interactive)
13339 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
13340 (error "Abort"))
13341 (save-excursion
13342 (save-window-excursion
13343 (mapc
13344 (lambda (b)
13345 (when (and (with-current-buffer b (org-mode-p))
13346 (with-current-buffer b buffer-file-name))
13347 (switch-to-buffer b)
13348 (revert-buffer t 'no-confirm)))
13349 (buffer-list))
13350 (when (and (featurep 'org-id) org-id-track-globally)
13351 (org-id-locations-load)))))
13353 ;;;; Agenda files
13355 ;;;###autoload
13356 (defun org-iswitchb (&optional arg)
13357 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
13358 With a prefix argument, restrict available to files.
13359 With two prefix arguments, restrict available buffers to agenda files.
13361 Due to some yet unresolved reason, the global function
13362 `iswitchb-mode' needs to be active for this function to work."
13363 (interactive "P")
13364 (require 'iswitchb)
13365 (let ((enabled iswitchb-mode) blist)
13366 (or enabled (iswitchb-mode 1))
13367 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13368 ((equal arg '(16)) (org-buffer-list 'agenda))
13369 (t (org-buffer-list))))
13370 (unwind-protect
13371 (let ((iswitchb-make-buflist-hook
13372 (lambda ()
13373 (setq iswitchb-temp-buflist
13374 (mapcar 'buffer-name blist)))))
13375 (switch-to-buffer
13376 (iswitchb-read-buffer
13377 "Switch-to: " nil t))
13378 (or enabled (iswitchb-mode -1))))))
13380 ;;;###autoload
13381 (defun org-ido-switchb (&optional arg)
13382 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
13383 With a prefix argument, restrict available to files.
13384 With two prefix arguments, restrict available buffers to agenda files."
13385 (interactive "P")
13386 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13387 ((equal arg '(16)) (org-buffer-list 'agenda))
13388 (t (org-buffer-list)))))
13389 (switch-to-buffer
13390 (org-ido-completing-read "Org buffer: "
13391 (mapcar 'list (mapcar 'buffer-name blist))
13392 nil t))))
13394 (defun org-buffer-list (&optional predicate exclude-tmp)
13395 "Return a list of Org buffers.
13396 PREDICATE can be `export', `files' or `agenda'.
13398 export restrict the list to Export buffers.
13399 files restrict the list to buffers visiting Org files.
13400 agenda restrict the list to buffers visiting agenda files.
13402 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
13403 (let* ((bfn nil)
13404 (agenda-files (and (eq predicate 'agenda)
13405 (mapcar 'file-truename (org-agenda-files t))))
13406 (filter
13407 (cond
13408 ((eq predicate 'files)
13409 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
13410 ((eq predicate 'export)
13411 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
13412 ((eq predicate 'agenda)
13413 (lambda (b)
13414 (with-current-buffer b
13415 (and (eq major-mode 'org-mode)
13416 (setq bfn (buffer-file-name b))
13417 (member (file-truename bfn) agenda-files)))))
13418 (t (lambda (b) (with-current-buffer b
13419 (or (eq major-mode 'org-mode)
13420 (string-match "\*Org .*Export"
13421 (buffer-name b)))))))))
13422 (delq nil
13423 (mapcar
13424 (lambda(b)
13425 (if (and (funcall filter b)
13426 (or (not exclude-tmp)
13427 (not (string-match "tmp" (buffer-name b)))))
13429 nil))
13430 (buffer-list)))))
13432 (defun org-agenda-files (&optional unrestricted archives)
13433 "Get the list of agenda files.
13434 Optional UNRESTRICTED means return the full list even if a restriction
13435 is currently in place.
13436 When ARCHIVES is t, include all archive files hat are really being
13437 used by the agenda files. If ARCHIVE is `ifmode', do this only if
13438 `org-agenda-archives-mode' is t."
13439 (let ((files
13440 (cond
13441 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
13442 ((stringp org-agenda-files) (org-read-agenda-file-list))
13443 ((listp org-agenda-files) org-agenda-files)
13444 (t (error "Invalid value of `org-agenda-files'")))))
13445 (setq files (apply 'append
13446 (mapcar (lambda (f)
13447 (if (file-directory-p f)
13448 (directory-files
13449 f t org-agenda-file-regexp)
13450 (list f)))
13451 files)))
13452 (when org-agenda-skip-unavailable-files
13453 (setq files (delq nil
13454 (mapcar (function
13455 (lambda (file)
13456 (and (file-readable-p file) file)))
13457 files))))
13458 (when (or (eq archives t)
13459 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
13460 (setq files (org-add-archive-files files)))
13461 files))
13463 (defun org-edit-agenda-file-list ()
13464 "Edit the list of agenda files.
13465 Depending on setup, this either uses customize to edit the variable
13466 `org-agenda-files', or it visits the file that is holding the list. In the
13467 latter case, the buffer is set up in a way that saving it automatically kills
13468 the buffer and restores the previous window configuration."
13469 (interactive)
13470 (if (stringp org-agenda-files)
13471 (let ((cw (current-window-configuration)))
13472 (find-file org-agenda-files)
13473 (org-set-local 'org-window-configuration cw)
13474 (org-add-hook 'after-save-hook
13475 (lambda ()
13476 (set-window-configuration
13477 (prog1 org-window-configuration
13478 (kill-buffer (current-buffer))))
13479 (org-install-agenda-files-menu)
13480 (message "New agenda file list installed"))
13481 nil 'local)
13482 (message "%s" (substitute-command-keys
13483 "Edit list and finish with \\[save-buffer]")))
13484 (customize-variable 'org-agenda-files)))
13486 (defun org-store-new-agenda-file-list (list)
13487 "Set new value for the agenda file list and save it correctly."
13488 (if (stringp org-agenda-files)
13489 (let ((f org-agenda-files) b)
13490 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
13491 (with-temp-file f
13492 (insert (mapconcat 'identity list "\n") "\n")))
13493 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
13494 (setq org-agenda-files list)
13495 (customize-save-variable 'org-agenda-files org-agenda-files))))
13497 (defun org-read-agenda-file-list ()
13498 "Read the list of agenda files from a file."
13499 (when (file-directory-p org-agenda-files)
13500 (error "`org-agenda-files' cannot be a single directory"))
13501 (when (stringp org-agenda-files)
13502 (with-temp-buffer
13503 (insert-file-contents org-agenda-files)
13504 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
13507 ;;;###autoload
13508 (defun org-cycle-agenda-files ()
13509 "Cycle through the files in `org-agenda-files'.
13510 If the current buffer visits an agenda file, find the next one in the list.
13511 If the current buffer does not, find the first agenda file."
13512 (interactive)
13513 (let* ((fs (org-agenda-files t))
13514 (files (append fs (list (car fs))))
13515 (tcf (if buffer-file-name (file-truename buffer-file-name)))
13516 file)
13517 (unless files (error "No agenda files"))
13518 (catch 'exit
13519 (while (setq file (pop files))
13520 (if (equal (file-truename file) tcf)
13521 (when (car files)
13522 (find-file (car files))
13523 (throw 'exit t))))
13524 (find-file (car fs)))
13525 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
13527 (defun org-agenda-file-to-front (&optional to-end)
13528 "Move/add the current file to the top of the agenda file list.
13529 If the file is not present in the list, it is added to the front. If it is
13530 present, it is moved there. With optional argument TO-END, add/move to the
13531 end of the list."
13532 (interactive "P")
13533 (let ((org-agenda-skip-unavailable-files nil)
13534 (file-alist (mapcar (lambda (x)
13535 (cons (file-truename x) x))
13536 (org-agenda-files t)))
13537 (ctf (file-truename buffer-file-name))
13538 x had)
13539 (setq x (assoc ctf file-alist) had x)
13541 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
13542 (if to-end
13543 (setq file-alist (append (delq x file-alist) (list x)))
13544 (setq file-alist (cons x (delq x file-alist))))
13545 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
13546 (org-install-agenda-files-menu)
13547 (message "File %s to %s of agenda file list"
13548 (if had "moved" "added") (if to-end "end" "front"))))
13550 (defun org-remove-file (&optional file)
13551 "Remove current file from the list of files in variable `org-agenda-files'.
13552 These are the files which are being checked for agenda entries.
13553 Optional argument FILE means, use this file instead of the current."
13554 (interactive)
13555 (let* ((org-agenda-skip-unavailable-files nil)
13556 (file (or file buffer-file-name))
13557 (true-file (file-truename file))
13558 (afile (abbreviate-file-name file))
13559 (files (delq nil (mapcar
13560 (lambda (x)
13561 (if (equal true-file
13562 (file-truename x))
13563 nil x))
13564 (org-agenda-files t)))))
13565 (if (not (= (length files) (length (org-agenda-files t))))
13566 (progn
13567 (org-store-new-agenda-file-list files)
13568 (org-install-agenda-files-menu)
13569 (message "Removed file: %s" afile))
13570 (message "File was not in list: %s (not removed)" afile))))
13572 (defun org-file-menu-entry (file)
13573 (vector file (list 'find-file file) t))
13575 (defun org-check-agenda-file (file)
13576 "Make sure FILE exists. If not, ask user what to do."
13577 (when (not (file-exists-p file))
13578 (message "non-existent file %s. [R]emove from list or [A]bort?"
13579 (abbreviate-file-name file))
13580 (let ((r (downcase (read-char-exclusive))))
13581 (cond
13582 ((equal r ?r)
13583 (org-remove-file file)
13584 (throw 'nextfile t))
13585 (t (error "Abort"))))))
13587 (defun org-get-agenda-file-buffer (file)
13588 "Get a buffer visiting FILE. If the buffer needs to be created, add
13589 it to the list of buffers which might be released later."
13590 (let ((buf (org-find-base-buffer-visiting file)))
13591 (if buf
13592 buf ; just return it
13593 ;; Make a new buffer and remember it
13594 (setq buf (find-file-noselect file))
13595 (if buf (push buf org-agenda-new-buffers))
13596 buf)))
13598 (defun org-release-buffers (blist)
13599 "Release all buffers in list, asking the user for confirmation when needed.
13600 When a buffer is unmodified, it is just killed. When modified, it is saved
13601 \(if the user agrees) and then killed."
13602 (let (buf file)
13603 (while (setq buf (pop blist))
13604 (setq file (buffer-file-name buf))
13605 (when (and (buffer-modified-p buf)
13606 file
13607 (y-or-n-p (format "Save file %s? " file)))
13608 (with-current-buffer buf (save-buffer)))
13609 (kill-buffer buf))))
13611 (defun org-prepare-agenda-buffers (files)
13612 "Create buffers for all agenda files, protect archived trees and comments."
13613 (interactive)
13614 (let ((pa '(:org-archived t))
13615 (pc '(:org-comment t))
13616 (pall '(:org-archived t :org-comment t))
13617 (inhibit-read-only t)
13618 (rea (concat ":" org-archive-tag ":"))
13619 bmp file re)
13620 (save-excursion
13621 (save-restriction
13622 (while (setq file (pop files))
13623 (catch 'nextfile
13624 (if (bufferp file)
13625 (set-buffer file)
13626 (org-check-agenda-file file)
13627 (set-buffer (org-get-agenda-file-buffer file)))
13628 (widen)
13629 (setq bmp (buffer-modified-p))
13630 (org-refresh-category-properties)
13631 (setq org-todo-keywords-for-agenda
13632 (append org-todo-keywords-for-agenda org-todo-keywords-1))
13633 (setq org-done-keywords-for-agenda
13634 (append org-done-keywords-for-agenda org-done-keywords))
13635 (setq org-todo-keyword-alist-for-agenda
13636 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
13637 (setq org-tag-alist-for-agenda
13638 (append org-tag-alist-for-agenda org-tag-alist))
13640 (save-excursion
13641 (remove-text-properties (point-min) (point-max) pall)
13642 (when org-agenda-skip-archived-trees
13643 (goto-char (point-min))
13644 (while (re-search-forward rea nil t)
13645 (if (org-on-heading-p t)
13646 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
13647 (goto-char (point-min))
13648 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
13649 (while (re-search-forward re nil t)
13650 (add-text-properties
13651 (match-beginning 0) (org-end-of-subtree t) pc)))
13652 (set-buffer-modified-p bmp)))))
13653 (setq org-todo-keyword-alist-for-agenda
13654 (org-uniquify org-todo-keyword-alist-for-agenda)
13655 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
13657 ;;;; Embedded LaTeX
13659 (defvar org-cdlatex-mode-map (make-sparse-keymap)
13660 "Keymap for the minor `org-cdlatex-mode'.")
13662 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
13663 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
13664 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
13665 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
13666 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
13668 (defvar org-cdlatex-texmathp-advice-is-done nil
13669 "Flag remembering if we have applied the advice to texmathp already.")
13671 (define-minor-mode org-cdlatex-mode
13672 "Toggle the minor `org-cdlatex-mode'.
13673 This mode supports entering LaTeX environment and math in LaTeX fragments
13674 in Org-mode.
13675 \\{org-cdlatex-mode-map}"
13676 nil " OCDL" nil
13677 (when org-cdlatex-mode (require 'cdlatex))
13678 (unless org-cdlatex-texmathp-advice-is-done
13679 (setq org-cdlatex-texmathp-advice-is-done t)
13680 (defadvice texmathp (around org-math-always-on activate)
13681 "Always return t in org-mode buffers.
13682 This is because we want to insert math symbols without dollars even outside
13683 the LaTeX math segments. If Orgmode thinks that point is actually inside
13684 an embedded LaTeX fragment, let texmathp do its job.
13685 \\[org-cdlatex-mode-map]"
13686 (interactive)
13687 (let (p)
13688 (cond
13689 ((not (org-mode-p)) ad-do-it)
13690 ((eq this-command 'cdlatex-math-symbol)
13691 (setq ad-return-value t
13692 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
13694 (let ((p (org-inside-LaTeX-fragment-p)))
13695 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
13696 (setq ad-return-value t
13697 texmathp-why '("Org-mode embedded math" . 0))
13698 (if p ad-do-it)))))))))
13700 (defun turn-on-org-cdlatex ()
13701 "Unconditionally turn on `org-cdlatex-mode'."
13702 (org-cdlatex-mode 1))
13704 (defun org-inside-LaTeX-fragment-p ()
13705 "Test if point is inside a LaTeX fragment.
13706 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
13707 sequence appearing also before point.
13708 Even though the matchers for math are configurable, this function assumes
13709 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
13710 delimiters are skipped when they have been removed by customization.
13711 The return value is nil, or a cons cell with the delimiter and
13712 and the position of this delimiter.
13714 This function does a reasonably good job, but can locally be fooled by
13715 for example currency specifications. For example it will assume being in
13716 inline math after \"$22.34\". The LaTeX fragment formatter will only format
13717 fragments that are properly closed, but during editing, we have to live
13718 with the uncertainty caused by missing closing delimiters. This function
13719 looks only before point, not after."
13720 (catch 'exit
13721 (let ((pos (point))
13722 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
13723 (lim (progn
13724 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
13725 (point)))
13726 dd-on str (start 0) m re)
13727 (goto-char pos)
13728 (when dodollar
13729 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
13730 re (nth 1 (assoc "$" org-latex-regexps)))
13731 (while (string-match re str start)
13732 (cond
13733 ((= (match-end 0) (length str))
13734 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
13735 ((= (match-end 0) (- (length str) 5))
13736 (throw 'exit nil))
13737 (t (setq start (match-end 0))))))
13738 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
13739 (goto-char pos)
13740 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
13741 (and (match-beginning 2) (throw 'exit nil))
13742 ;; count $$
13743 (while (re-search-backward "\\$\\$" lim t)
13744 (setq dd-on (not dd-on)))
13745 (goto-char pos)
13746 (if dd-on (cons "$$" m))))))
13749 (defun org-try-cdlatex-tab ()
13750 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
13751 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
13752 - inside a LaTeX fragment, or
13753 - after the first word in a line, where an abbreviation expansion could
13754 insert a LaTeX environment."
13755 (when org-cdlatex-mode
13756 (cond
13757 ((save-excursion
13758 (skip-chars-backward "a-zA-Z0-9*")
13759 (skip-chars-backward " \t")
13760 (bolp))
13761 (cdlatex-tab) t)
13762 ((org-inside-LaTeX-fragment-p)
13763 (cdlatex-tab) t)
13764 (t nil))))
13766 (defun org-cdlatex-underscore-caret (&optional arg)
13767 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
13768 Revert to the normal definition outside of these fragments."
13769 (interactive "P")
13770 (if (org-inside-LaTeX-fragment-p)
13771 (call-interactively 'cdlatex-sub-superscript)
13772 (let (org-cdlatex-mode)
13773 (call-interactively (key-binding (vector last-input-event))))))
13775 (defun org-cdlatex-math-modify (&optional arg)
13776 "Execute `cdlatex-math-modify' in LaTeX fragments.
13777 Revert to the normal definition outside of these fragments."
13778 (interactive "P")
13779 (if (org-inside-LaTeX-fragment-p)
13780 (call-interactively 'cdlatex-math-modify)
13781 (let (org-cdlatex-mode)
13782 (call-interactively (key-binding (vector last-input-event))))))
13784 (defvar org-latex-fragment-image-overlays nil
13785 "List of overlays carrying the images of latex fragments.")
13786 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
13788 (defun org-remove-latex-fragment-image-overlays ()
13789 "Remove all overlays with LaTeX fragment images in current buffer."
13790 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
13791 (setq org-latex-fragment-image-overlays nil))
13793 (defun org-preview-latex-fragment (&optional subtree)
13794 "Preview the LaTeX fragment at point, or all locally or globally.
13795 If the cursor is in a LaTeX fragment, create the image and overlay
13796 it over the source code. If there is no fragment at point, display
13797 all fragments in the current text, from one headline to the next. With
13798 prefix SUBTREE, display all fragments in the current subtree. With a
13799 double prefix `C-u C-u', or when the cursor is before the first headline,
13800 display all fragments in the buffer.
13801 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
13802 (interactive "P")
13803 (org-remove-latex-fragment-image-overlays)
13804 (save-excursion
13805 (save-restriction
13806 (let (beg end at msg)
13807 (cond
13808 ((or (equal subtree '(16))
13809 (not (save-excursion
13810 (re-search-backward (concat "^" outline-regexp) nil t))))
13811 (setq beg (point-min) end (point-max)
13812 msg "Creating images for buffer...%s"))
13813 ((equal subtree '(4))
13814 (org-back-to-heading)
13815 (setq beg (point) end (org-end-of-subtree t)
13816 msg "Creating images for subtree...%s"))
13818 (if (setq at (org-inside-LaTeX-fragment-p))
13819 (goto-char (max (point-min) (- (cdr at) 2)))
13820 (org-back-to-heading))
13821 (setq beg (point) end (progn (outline-next-heading) (point))
13822 msg (if at "Creating image...%s"
13823 "Creating images for entry...%s"))))
13824 (message msg "")
13825 (narrow-to-region beg end)
13826 (goto-char beg)
13827 (org-format-latex
13828 (concat "ltxpng/" (file-name-sans-extension
13829 (file-name-nondirectory
13830 buffer-file-name)))
13831 default-directory 'overlays msg at 'forbuffer)
13832 (message msg "done. Use `C-c C-c' to remove images.")))))
13834 (defvar org-latex-regexps
13835 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
13836 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
13837 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
13838 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13839 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13840 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
13841 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
13842 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
13843 "Regular expressions for matching embedded LaTeX.")
13845 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
13846 "Replace LaTeX fragments with links to an image, and produce images."
13847 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
13848 (let* ((prefixnodir (file-name-nondirectory prefix))
13849 (absprefix (expand-file-name prefix dir))
13850 (todir (file-name-directory absprefix))
13851 (opt org-format-latex-options)
13852 (matchers (plist-get opt :matchers))
13853 (re-list org-latex-regexps)
13854 (cnt 0) txt link beg end re e checkdir
13855 executables-checked
13856 m n block linkfile movefile ov)
13857 ;; Check if there are old images files with this prefix, and remove them
13858 (when (file-directory-p todir)
13859 (mapc 'delete-file
13860 (directory-files
13861 todir 'full
13862 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
13863 ;; Check the different regular expressions
13864 (while (setq e (pop re-list))
13865 (setq m (car e) re (nth 1 e) n (nth 2 e)
13866 block (if (nth 3 e) "\n\n" ""))
13867 (when (member m matchers)
13868 (goto-char (point-min))
13869 (while (re-search-forward re nil t)
13870 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
13871 (not (get-text-property (match-beginning n)
13872 'org-protected)))
13873 (setq txt (match-string n)
13874 beg (match-beginning n) end (match-end n)
13875 cnt (1+ cnt)
13876 linkfile (format "%s_%04d.png" prefix cnt)
13877 movefile (format "%s_%04d.png" absprefix cnt)
13878 link (concat block "[[file:" linkfile "]]" block))
13879 (if msg (message msg cnt))
13880 (goto-char beg)
13881 (unless checkdir ; make sure the directory exists
13882 (setq checkdir t)
13883 (or (file-directory-p todir) (make-directory todir)))
13885 (unless executables-checked
13886 (org-check-external-command
13887 "latex" "needed to convert LaTeX fragments to images")
13888 (org-check-external-command
13889 "dvipng" "needed to convert LaTeX fragments to images")
13890 (setq executables-checked t))
13892 (org-create-formula-image
13893 txt movefile opt forbuffer)
13894 (if overlays
13895 (progn
13896 (setq ov (org-make-overlay beg end))
13897 (if (featurep 'xemacs)
13898 (progn
13899 (org-overlay-put ov 'invisible t)
13900 (org-overlay-put
13901 ov 'end-glyph
13902 (make-glyph (vector 'png :file movefile))))
13903 (org-overlay-put
13904 ov 'display
13905 (list 'image :type 'png :file movefile :ascent 'center)))
13906 (push ov org-latex-fragment-image-overlays)
13907 (goto-char end))
13908 (delete-region beg end)
13909 (insert link))))))))
13911 ;; This function borrows from Ganesh Swami's latex2png.el
13912 (defun org-create-formula-image (string tofile options buffer)
13913 (let* ((tmpdir (if (featurep 'xemacs)
13914 (temp-directory)
13915 temporary-file-directory))
13916 (texfilebase (make-temp-name
13917 (expand-file-name "orgtex" tmpdir)))
13918 (texfile (concat texfilebase ".tex"))
13919 (dvifile (concat texfilebase ".dvi"))
13920 (pngfile (concat texfilebase ".png"))
13921 (fnh (if (featurep 'xemacs)
13922 (font-height (get-face-font 'default))
13923 (face-attribute 'default :height nil)))
13924 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
13925 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
13926 (fg (or (plist-get options (if buffer :foreground :html-foreground))
13927 "Black"))
13928 (bg (or (plist-get options (if buffer :background :html-background))
13929 "Transparent")))
13930 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
13931 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
13932 (with-temp-file texfile
13933 (insert org-format-latex-header
13934 "\n\\begin{document}\n" string "\n\\end{document}\n"))
13935 (let ((dir default-directory))
13936 (condition-case nil
13937 (progn
13938 (cd tmpdir)
13939 (call-process "latex" nil nil nil texfile))
13940 (error nil))
13941 (cd dir))
13942 (if (not (file-exists-p dvifile))
13943 (progn (message "Failed to create dvi file from %s" texfile) nil)
13944 (condition-case nil
13945 (call-process "dvipng" nil nil nil
13946 "-E" "-fg" fg "-bg" bg
13947 "-D" dpi
13948 ;;"-x" scale "-y" scale
13949 "-T" "tight"
13950 "-o" pngfile
13951 dvifile)
13952 (error nil))
13953 (if (not (file-exists-p pngfile))
13954 (progn (message "Failed to create png file from %s" texfile) nil)
13955 ;; Use the requested file name and clean up
13956 (copy-file pngfile tofile 'replace)
13957 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
13958 (delete-file (concat texfilebase e)))
13959 pngfile))))
13961 (defun org-dvipng-color (attr)
13962 "Return an rgb color specification for dvipng."
13963 (apply 'format "rgb %s %s %s"
13964 (mapcar 'org-normalize-color
13965 (color-values (face-attribute 'default attr nil)))))
13967 (defun org-normalize-color (value)
13968 "Return string to be used as color value for an RGB component."
13969 (format "%g" (/ value 65535.0)))
13971 ;;;; Key bindings
13973 ;; Make `C-c C-x' a prefix key
13974 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
13976 ;; TAB key with modifiers
13977 (org-defkey org-mode-map "\C-i" 'org-cycle)
13978 (org-defkey org-mode-map [(tab)] 'org-cycle)
13979 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
13980 (org-defkey org-mode-map [(meta tab)] 'org-complete)
13981 (org-defkey org-mode-map "\M-\t" 'org-complete)
13982 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
13983 ;; The following line is necessary under Suse GNU/Linux
13984 (unless (featurep 'xemacs)
13985 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
13986 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
13987 (define-key org-mode-map [backtab] 'org-shifttab)
13989 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
13990 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
13991 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
13993 ;; Cursor keys with modifiers
13994 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
13995 (org-defkey org-mode-map [(meta right)] 'org-metaright)
13996 (org-defkey org-mode-map [(meta up)] 'org-metaup)
13997 (org-defkey org-mode-map [(meta down)] 'org-metadown)
13999 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
14000 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
14001 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
14002 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
14004 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
14005 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
14006 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
14007 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
14009 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
14010 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
14012 ;;; Extra keys for tty access.
14013 ;; We only set them when really needed because otherwise the
14014 ;; menus don't show the simple keys
14016 (when (or org-use-extra-keys
14017 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
14018 (not window-system))
14019 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
14020 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
14021 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
14022 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
14023 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
14024 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
14025 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
14026 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
14027 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
14028 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
14029 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
14030 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
14031 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
14032 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
14033 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
14034 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
14035 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
14036 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
14037 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
14038 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
14039 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
14040 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
14041 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
14042 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
14043 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
14044 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
14045 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
14046 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
14048 ;; All the other keys
14050 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
14051 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
14052 (if (boundp 'narrow-map)
14053 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
14054 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
14055 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
14056 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
14057 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
14058 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
14059 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
14060 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
14061 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
14062 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
14063 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
14064 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
14065 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
14066 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
14067 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
14068 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
14069 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
14070 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
14071 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
14072 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
14073 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
14074 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
14075 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
14076 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
14077 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
14078 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
14079 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
14080 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
14081 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
14082 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
14083 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
14084 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
14085 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
14086 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
14087 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
14088 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
14089 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
14090 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
14091 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
14092 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
14093 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
14094 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
14095 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
14096 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14097 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
14098 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
14099 (org-defkey org-mode-map "\C-c^" 'org-sort)
14100 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
14101 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
14102 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
14103 (org-defkey org-mode-map "\C-m" 'org-return)
14104 (org-defkey org-mode-map "\C-j" 'org-return-indent)
14105 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
14106 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
14107 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
14108 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
14109 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
14110 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
14111 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
14112 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
14113 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
14114 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
14115 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
14116 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
14117 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
14118 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
14119 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
14120 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
14121 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
14122 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
14124 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
14125 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
14126 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
14127 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
14129 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
14130 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
14131 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
14132 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
14133 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
14134 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
14135 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
14136 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
14137 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
14138 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
14139 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
14140 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
14141 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
14142 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
14144 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
14145 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
14146 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
14147 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
14149 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
14151 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
14153 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
14154 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
14156 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
14159 (when (featurep 'xemacs)
14160 (org-defkey org-mode-map 'button3 'popup-mode-menu))
14163 (defvar org-self-insert-command-undo-counter 0)
14165 (defvar org-table-auto-blank-field) ; defined in org-table.el
14166 (defun org-self-insert-command (N)
14167 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
14168 If the cursor is in a table looking at whitespace, the whitespace is
14169 overwritten, and the table is not marked as requiring realignment."
14170 (interactive "p")
14171 (if (and
14172 (org-table-p)
14173 (progn
14174 ;; check if we blank the field, and if that triggers align
14175 (and (featurep 'org-table) org-table-auto-blank-field
14176 (member last-command
14177 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
14178 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
14179 ;; got extra space, this field does not determine column width
14180 (let (org-table-may-need-update) (org-table-blank-field))
14181 ;; no extra space, this field may determine column width
14182 (org-table-blank-field)))
14184 (eq N 1)
14185 (looking-at "[^|\n]* |"))
14186 (let (org-table-may-need-update)
14187 (goto-char (1- (match-end 0)))
14188 (delete-backward-char 1)
14189 (goto-char (match-beginning 0))
14190 (self-insert-command N))
14191 (setq org-table-may-need-update t)
14192 (self-insert-command N)
14193 (org-fix-tags-on-the-fly)
14194 (if org-self-insert-cluster-for-undo
14195 (if (not (eq last-command 'org-self-insert-command))
14196 (setq org-self-insert-command-undo-counter 1)
14197 (if (>= org-self-insert-command-undo-counter 20)
14198 (setq org-self-insert-command-undo-counter 1)
14199 (and (> org-self-insert-command-undo-counter 0)
14200 buffer-undo-list
14201 (not (cadr buffer-undo-list)) ; remove nil entry
14202 (setcdr buffer-undo-list (cddr buffer-undo-list)))
14203 (setq org-self-insert-command-undo-counter
14204 (1+ org-self-insert-command-undo-counter)))))))
14206 (defun org-fix-tags-on-the-fly ()
14207 (when (and (equal (char-after (point-at-bol)) ?*)
14208 (org-on-heading-p))
14209 (org-align-tags-here org-tags-column)))
14211 (defun org-delete-backward-char (N)
14212 "Like `delete-backward-char', insert whitespace at field end in tables.
14213 When deleting backwards, in tables this function will insert whitespace in
14214 front of the next \"|\" separator, to keep the table aligned. The table will
14215 still be marked for re-alignment if the field did fill the entire column,
14216 because, in this case the deletion might narrow the column."
14217 (interactive "p")
14218 (if (and (org-table-p)
14219 (eq N 1)
14220 (string-match "|" (buffer-substring (point-at-bol) (point)))
14221 (looking-at ".*?|"))
14222 (let ((pos (point))
14223 (noalign (looking-at "[^|\n\r]* |"))
14224 (c org-table-may-need-update))
14225 (backward-delete-char N)
14226 (skip-chars-forward "^|")
14227 (insert " ")
14228 (goto-char (1- pos))
14229 ;; noalign: if there were two spaces at the end, this field
14230 ;; does not determine the width of the column.
14231 (if noalign (setq org-table-may-need-update c)))
14232 (backward-delete-char N)
14233 (org-fix-tags-on-the-fly)))
14235 (defun org-delete-char (N)
14236 "Like `delete-char', but insert whitespace at field end in tables.
14237 When deleting characters, in tables this function will insert whitespace in
14238 front of the next \"|\" separator, to keep the table aligned. The table will
14239 still be marked for re-alignment if the field did fill the entire column,
14240 because, in this case the deletion might narrow the column."
14241 (interactive "p")
14242 (if (and (org-table-p)
14243 (not (bolp))
14244 (not (= (char-after) ?|))
14245 (eq N 1))
14246 (if (looking-at ".*?|")
14247 (let ((pos (point))
14248 (noalign (looking-at "[^|\n\r]* |"))
14249 (c org-table-may-need-update))
14250 (replace-match (concat
14251 (substring (match-string 0) 1 -1)
14252 " |"))
14253 (goto-char pos)
14254 ;; noalign: if there were two spaces at the end, this field
14255 ;; does not determine the width of the column.
14256 (if noalign (setq org-table-may-need-update c)))
14257 (delete-char N))
14258 (delete-char N)
14259 (org-fix-tags-on-the-fly)))
14261 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
14262 (put 'org-self-insert-command 'delete-selection t)
14263 (put 'orgtbl-self-insert-command 'delete-selection t)
14264 (put 'org-delete-char 'delete-selection 'supersede)
14265 (put 'org-delete-backward-char 'delete-selection 'supersede)
14266 (put 'org-yank 'delete-selection 'yank)
14268 ;; Make `flyspell-mode' delay after some commands
14269 (put 'org-self-insert-command 'flyspell-delayed t)
14270 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
14271 (put 'org-delete-char 'flyspell-delayed t)
14272 (put 'org-delete-backward-char 'flyspell-delayed t)
14274 ;; Make pabbrev-mode expand after org-mode commands
14275 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
14276 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
14278 ;; How to do this: Measure non-white length of current string
14279 ;; If equal to column width, we should realign.
14281 (defun org-remap (map &rest commands)
14282 "In MAP, remap the functions given in COMMANDS.
14283 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
14284 (let (new old)
14285 (while commands
14286 (setq old (pop commands) new (pop commands))
14287 (if (fboundp 'command-remapping)
14288 (org-defkey map (vector 'remap old) new)
14289 (substitute-key-definition old new map global-map)))))
14291 (when (eq org-enable-table-editor 'optimized)
14292 ;; If the user wants maximum table support, we need to hijack
14293 ;; some standard editing functions
14294 (org-remap org-mode-map
14295 'self-insert-command 'org-self-insert-command
14296 'delete-char 'org-delete-char
14297 'delete-backward-char 'org-delete-backward-char)
14298 (org-defkey org-mode-map "|" 'org-force-self-insert))
14300 (defvar org-ctrl-c-ctrl-c-hook nil
14301 "Hook for functions attaching themselves to `C-c C-c'.
14302 This can be used to add additional functionality to the C-c C-c key which
14303 executes context-dependent commands.
14304 Each function will be called with no arguments. The function must check
14305 if the context is appropriate for it to act. If yes, it should do its
14306 thing and then return a non-nil value. If the context is wrong,
14307 just do nothing and return nil.")
14309 (defvar org-tab-first-hook nil
14310 "Hook for functions to attach themselves to TAB.
14311 See `org-ctrl-c-ctrl-c-hook' for more information.
14312 This hook runs as the first action when TAB is pressed, even before
14313 `org-cycle' messes around with the `outline-regexp' to cater for
14314 inline tasks and plain list item folding.
14315 If any function in this hook returns t, not other actions like table
14316 field motion visibility cycling will be done.")
14318 (defvar org-tab-after-check-for-table-hook nil
14319 "Hook for functions to attach themselves to TAB.
14320 See `org-ctrl-c-ctrl-c-hook' for more information.
14321 This hook runs after it has been established that the cursor is not in a
14322 table, but before checking if the cursor is in a headline or if global cycling
14323 should be done.
14324 If any function in this hook returns t, not other actions like visibility
14325 cycling will be done.")
14327 (defvar org-tab-after-check-for-cycling-hook nil
14328 "Hook for functions to attach themselves to TAB.
14329 See `org-ctrl-c-ctrl-c-hook' for more information.
14330 This hook runs after it has been established that not table field motion and
14331 not visibility should be done because of current context. This is probably
14332 the place where a package like yasnippets can hook in.")
14334 (defvar org-metaleft-hook nil
14335 "Hook for functions attaching themselves to `M-left'.
14336 See `org-ctrl-c-ctrl-c-hook' for more information.")
14337 (defvar org-metaright-hook nil
14338 "Hook for functions attaching themselves to `M-right'.
14339 See `org-ctrl-c-ctrl-c-hook' for more information.")
14340 (defvar org-metaup-hook nil
14341 "Hook for functions attaching themselves to `M-up'.
14342 See `org-ctrl-c-ctrl-c-hook' for more information.")
14343 (defvar org-metadown-hook nil
14344 "Hook for functions attaching themselves to `M-down'.
14345 See `org-ctrl-c-ctrl-c-hook' for more information.")
14346 (defvar org-shiftmetaleft-hook nil
14347 "Hook for functions attaching themselves to `M-S-left'.
14348 See `org-ctrl-c-ctrl-c-hook' for more information.")
14349 (defvar org-shiftmetaright-hook nil
14350 "Hook for functions attaching themselves to `M-S-right'.
14351 See `org-ctrl-c-ctrl-c-hook' for more information.")
14352 (defvar org-shiftmetaup-hook nil
14353 "Hook for functions attaching themselves to `M-S-up'.
14354 See `org-ctrl-c-ctrl-c-hook' for more information.")
14355 (defvar org-shiftmetadown-hook nil
14356 "Hook for functions attaching themselves to `M-S-down'.
14357 See `org-ctrl-c-ctrl-c-hook' for more information.")
14358 (defvar org-metareturn-hook nil
14359 "Hook for functions attaching themselves to `M-RET'.
14360 See `org-ctrl-c-ctrl-c-hook' for more information.")
14362 (defun org-modifier-cursor-error ()
14363 "Throw an error, a modified cursor command was applied in wrong context."
14364 (error "This command is active in special context like tables, headlines or items"))
14366 (defun org-shiftselect-error ()
14367 "Throw an error because Shift-Cursor command was applied in wrong context."
14368 (if (and (boundp 'shift-select-mode) shift-select-mode)
14369 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
14370 (error "This command works only in special context like headlines or timestamps.")))
14372 (defun org-call-for-shift-select (cmd)
14373 (let ((this-command-keys-shift-translated t))
14374 (call-interactively cmd)))
14376 (defun org-shifttab (&optional arg)
14377 "Global visibility cycling or move to previous table field.
14378 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
14379 on context.
14380 See the individual commands for more information."
14381 (interactive "P")
14382 (cond
14383 ((org-at-table-p) (call-interactively 'org-table-previous-field))
14384 ((integerp arg)
14385 (message "Content view to level: %d" arg)
14386 (org-content (prefix-numeric-value arg))
14387 (setq org-cycle-global-status 'overview))
14388 (t (call-interactively 'org-global-cycle))))
14390 (defun org-shiftmetaleft ()
14391 "Promote subtree or delete table column.
14392 Calls `org-promote-subtree', `org-outdent-item',
14393 or `org-table-delete-column', depending on context.
14394 See the individual commands for more information."
14395 (interactive)
14396 (cond
14397 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
14398 ((org-at-table-p) (call-interactively 'org-table-delete-column))
14399 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
14400 ((org-at-item-p) (call-interactively 'org-outdent-item))
14401 (t (org-modifier-cursor-error))))
14403 (defun org-shiftmetaright ()
14404 "Demote subtree or insert table column.
14405 Calls `org-demote-subtree', `org-indent-item',
14406 or `org-table-insert-column', depending on context.
14407 See the individual commands for more information."
14408 (interactive)
14409 (cond
14410 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
14411 ((org-at-table-p) (call-interactively 'org-table-insert-column))
14412 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
14413 ((org-at-item-p) (call-interactively 'org-indent-item))
14414 (t (org-modifier-cursor-error))))
14416 (defun org-shiftmetaup (&optional arg)
14417 "Move subtree up or kill table row.
14418 Calls `org-move-subtree-up' or `org-table-kill-row' or
14419 `org-move-item-up' depending on context. See the individual commands
14420 for more information."
14421 (interactive "P")
14422 (cond
14423 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
14424 ((org-at-table-p) (call-interactively 'org-table-kill-row))
14425 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14426 ((org-at-item-p) (call-interactively 'org-move-item-up))
14427 (t (org-modifier-cursor-error))))
14429 (defun org-shiftmetadown (&optional arg)
14430 "Move subtree down or insert table row.
14431 Calls `org-move-subtree-down' or `org-table-insert-row' or
14432 `org-move-item-down', depending on context. See the individual
14433 commands for more information."
14434 (interactive "P")
14435 (cond
14436 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
14437 ((org-at-table-p) (call-interactively 'org-table-insert-row))
14438 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14439 ((org-at-item-p) (call-interactively 'org-move-item-down))
14440 (t (org-modifier-cursor-error))))
14442 (defun org-metaleft (&optional arg)
14443 "Promote heading or move table column to left.
14444 Calls `org-do-promote' or `org-table-move-column', depending on context.
14445 With no specific context, calls the Emacs default `backward-word'.
14446 See the individual commands for more information."
14447 (interactive "P")
14448 (cond
14449 ((run-hook-with-args-until-success 'org-metaleft-hook))
14450 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
14451 ((or (org-on-heading-p)
14452 (and (org-region-active-p)
14453 (save-excursion
14454 (goto-char (region-beginning))
14455 (org-on-heading-p))))
14456 (call-interactively 'org-do-promote))
14457 ((or (org-at-item-p)
14458 (and (org-region-active-p)
14459 (save-excursion
14460 (goto-char (region-beginning))
14461 (org-at-item-p))))
14462 (call-interactively 'org-outdent-item))
14463 (t (call-interactively 'backward-word))))
14465 (defun org-metaright (&optional arg)
14466 "Demote subtree or move table column to right.
14467 Calls `org-do-demote' or `org-table-move-column', depending on context.
14468 With no specific context, calls the Emacs default `forward-word'.
14469 See the individual commands for more information."
14470 (interactive "P")
14471 (cond
14472 ((run-hook-with-args-until-success 'org-metaright-hook))
14473 ((org-at-table-p) (call-interactively 'org-table-move-column))
14474 ((or (org-on-heading-p)
14475 (and (org-region-active-p)
14476 (save-excursion
14477 (goto-char (region-beginning))
14478 (org-on-heading-p))))
14479 (call-interactively 'org-do-demote))
14480 ((or (org-at-item-p)
14481 (and (org-region-active-p)
14482 (save-excursion
14483 (goto-char (region-beginning))
14484 (org-at-item-p))))
14485 (call-interactively 'org-indent-item))
14486 (t (call-interactively 'forward-word))))
14488 (defun org-metaup (&optional arg)
14489 "Move subtree up or move table row up.
14490 Calls `org-move-subtree-up' or `org-table-move-row' or
14491 `org-move-item-up', depending on context. See the individual commands
14492 for more information."
14493 (interactive "P")
14494 (cond
14495 ((run-hook-with-args-until-success 'org-metaup-hook))
14496 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
14497 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14498 ((org-at-item-p) (call-interactively 'org-move-item-up))
14499 (t (transpose-lines 1) (beginning-of-line -1))))
14501 (defun org-metadown (&optional arg)
14502 "Move subtree down or move table row down.
14503 Calls `org-move-subtree-down' or `org-table-move-row' or
14504 `org-move-item-down', depending on context. See the individual
14505 commands for more information."
14506 (interactive "P")
14507 (cond
14508 ((run-hook-with-args-until-success 'org-metadown-hook))
14509 ((org-at-table-p) (call-interactively 'org-table-move-row))
14510 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14511 ((org-at-item-p) (call-interactively 'org-move-item-down))
14512 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
14514 (defun org-shiftup (&optional arg)
14515 "Increase item in timestamp or increase priority of current headline.
14516 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
14517 depending on context. See the individual commands for more information."
14518 (interactive "P")
14519 (cond
14520 ((and org-support-shift-select (org-region-active-p))
14521 (org-call-for-shift-select 'previous-line))
14522 ((org-at-timestamp-p t)
14523 (call-interactively (if org-edit-timestamp-down-means-later
14524 'org-timestamp-down 'org-timestamp-up)))
14525 ((and (not (eq org-support-shift-select 'always))
14526 org-enable-priority-commands
14527 (org-on-heading-p))
14528 (call-interactively 'org-priority-up))
14529 ((and (not org-support-shift-select) (org-at-item-p))
14530 (call-interactively 'org-previous-item))
14531 ((org-clocktable-try-shift 'up arg))
14532 (org-support-shift-select
14533 (org-call-for-shift-select 'previous-line))
14534 (t (org-shiftselect-error))))
14536 (defun org-shiftdown (&optional arg)
14537 "Decrease item in timestamp or decrease priority of current headline.
14538 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
14539 depending on context. See the individual commands for more information."
14540 (interactive "P")
14541 (cond
14542 ((and org-support-shift-select (org-region-active-p))
14543 (org-call-for-shift-select 'next-line))
14544 ((org-at-timestamp-p t)
14545 (call-interactively (if org-edit-timestamp-down-means-later
14546 'org-timestamp-up 'org-timestamp-down)))
14547 ((and (not (eq org-support-shift-select 'always))
14548 org-enable-priority-commands
14549 (org-on-heading-p))
14550 (call-interactively 'org-priority-down))
14551 ((and (not org-support-shift-select) (org-at-item-p))
14552 (call-interactively 'org-next-item))
14553 ((org-clocktable-try-shift 'down arg))
14554 (org-support-shift-select
14555 (org-call-for-shift-select 'next-line))
14556 (t (org-shiftselect-error))))
14558 (defun org-shiftright (&optional arg)
14559 "Cycle the thing at point or in the current line, depending on context.
14560 Depending on context, this does one of the following:
14562 - switch a timestamp at point one day into the future
14563 - on a headline, switch to the next TODO keyword.
14564 - on an item, switch entire list to the next bullet type
14565 - on a property line, switch to the next allowed value
14566 - on a clocktable definition line, move time block into the future"
14567 (interactive "P")
14568 (cond
14569 ((and org-support-shift-select (org-region-active-p))
14570 (org-call-for-shift-select 'forward-char))
14571 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
14572 ((and (not (eq org-support-shift-select 'always))
14573 (org-on-heading-p))
14574 (let ((org-inhibit-logging
14575 (not org-treat-S-cursor-todo-selection-as-state-change))
14576 (org-inhibit-blocking
14577 (not org-treat-S-cursor-todo-selection-as-state-change)))
14578 (org-call-with-arg 'org-todo 'right)))
14579 ((or (and org-support-shift-select
14580 (not (eq org-support-shift-select 'always))
14581 (org-at-item-bullet-p))
14582 (and (not org-support-shift-select) (org-at-item-p)))
14583 (org-call-with-arg 'org-cycle-list-bullet nil))
14584 ((and (not (eq org-support-shift-select 'always))
14585 (org-at-property-p))
14586 (call-interactively 'org-property-next-allowed-value))
14587 ((org-clocktable-try-shift 'right arg))
14588 (org-support-shift-select
14589 (org-call-for-shift-select 'forward-char))
14590 (t (org-shiftselect-error))))
14592 (defun org-shiftleft (&optional arg)
14593 "Cycle the thing at point or in the current line, depending on context.
14594 Depending on context, this does one of the following:
14596 - switch a timestamp at point one day into the past
14597 - on a headline, switch to the previous TODO keyword.
14598 - on an item, switch entire list to the previous bullet type
14599 - on a property line, switch to the previous allowed value
14600 - on a clocktable definition line, move time block into the past"
14601 (interactive "P")
14602 (cond
14603 ((and org-support-shift-select (org-region-active-p))
14604 (org-call-for-shift-select 'backward-char))
14605 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
14606 ((and (not (eq org-support-shift-select 'always))
14607 (org-on-heading-p))
14608 (let ((org-inhibit-logging
14609 (not org-treat-S-cursor-todo-selection-as-state-change))
14610 (org-inhibit-blocking
14611 (not org-treat-S-cursor-todo-selection-as-state-change)))
14612 (org-call-with-arg 'org-todo 'left)))
14613 ((or (and org-support-shift-select
14614 (not (eq org-support-shift-select 'always))
14615 (org-at-item-bullet-p))
14616 (and (not org-support-shift-select) (org-at-item-p)))
14617 (org-call-with-arg 'org-cycle-list-bullet 'previous))
14618 ((and (not (eq org-support-shift-select 'always))
14619 (org-at-property-p))
14620 (call-interactively 'org-property-previous-allowed-value))
14621 ((org-clocktable-try-shift 'left arg))
14622 (org-support-shift-select
14623 (org-call-for-shift-select 'backward-char))
14624 (t (org-shiftselect-error))))
14626 (defun org-shiftcontrolright ()
14627 "Switch to next TODO set."
14628 (interactive)
14629 (cond
14630 ((and org-support-shift-select (org-region-active-p))
14631 (org-call-for-shift-select 'forward-word))
14632 ((and (not (eq org-support-shift-select 'always))
14633 (org-on-heading-p))
14634 (org-call-with-arg 'org-todo 'nextset))
14635 (org-support-shift-select
14636 (org-call-for-shift-select 'forward-word))
14637 (t (org-shiftselect-error))))
14639 (defun org-shiftcontrolleft ()
14640 "Switch to previous TODO set."
14641 (interactive)
14642 (cond
14643 ((and org-support-shift-select (org-region-active-p))
14644 (org-call-for-shift-select 'backward-word))
14645 ((and (not (eq org-support-shift-select 'always))
14646 (org-on-heading-p))
14647 (org-call-with-arg 'org-todo 'previousset))
14648 (org-support-shift-select
14649 (org-call-for-shift-select 'backward-word))
14650 (t (org-shiftselect-error))))
14652 (defun org-ctrl-c-ret ()
14653 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
14654 (interactive)
14655 (cond
14656 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
14657 (t (call-interactively 'org-insert-heading))))
14659 (defun org-copy-special ()
14660 "Copy region in table or copy current subtree.
14661 Calls `org-table-copy' or `org-copy-subtree', depending on context.
14662 See the individual commands for more information."
14663 (interactive)
14664 (call-interactively
14665 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
14667 (defun org-cut-special ()
14668 "Cut region in table or cut current subtree.
14669 Calls `org-table-copy' or `org-cut-subtree', depending on context.
14670 See the individual commands for more information."
14671 (interactive)
14672 (call-interactively
14673 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
14675 (defun org-paste-special (arg)
14676 "Paste rectangular region into table, or past subtree relative to level.
14677 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
14678 See the individual commands for more information."
14679 (interactive "P")
14680 (if (org-at-table-p)
14681 (org-table-paste-rectangle)
14682 (org-paste-subtree arg)))
14684 (defun org-edit-special ()
14685 "Call a special editor for the stuff at point.
14686 When at a table, call the formula editor with `org-table-edit-formulas'.
14687 When at the first line of an src example, call `org-edit-src-code'.
14688 When in an #+include line, visit the include file. Otherwise call
14689 `ffap' to visit the file at point."
14690 (interactive)
14691 (cond
14692 ((org-at-table-p)
14693 (call-interactively 'org-table-edit-formulas))
14694 ((save-excursion
14695 (beginning-of-line 1)
14696 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
14697 (find-file (org-trim (match-string 1))))
14698 ((org-edit-src-code))
14699 ((org-edit-fixed-width-region))
14700 (t (call-interactively 'ffap))))
14703 (defun org-ctrl-c-ctrl-c (&optional arg)
14704 "Set tags in headline, or update according to changed information at point.
14706 This command does many different things, depending on context:
14708 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
14709 this is what we do.
14711 - If the cursor is in a headline, prompt for tags and insert them
14712 into the current line, aligned to `org-tags-column'. When called
14713 with prefix arg, realign all tags in the current buffer.
14715 - If the cursor is in one of the special #+KEYWORD lines, this
14716 triggers scanning the buffer for these lines and updating the
14717 information.
14719 - If the cursor is inside a table, realign the table. This command
14720 works even if the automatic table editor has been turned off.
14722 - If the cursor is on a #+TBLFM line, re-apply the formulas to
14723 the entire table.
14725 - If the cursor is at a footnote reference or definition, jump to
14726 the corresponding definition or references, respectively.
14728 - If the cursor is a the beginning of a dynamic block, update it.
14730 - If the cursor is inside a table created by the table.el package,
14731 activate that table.
14733 - If the current buffer is a remember buffer, close note and file
14734 it. A prefix argument of 1 files to the default location
14735 without further interaction. A prefix argument of 2 files to
14736 the currently clocking task.
14738 - If the cursor is on a <<<target>>>, update radio targets and corresponding
14739 links in this buffer.
14741 - If the cursor is on a numbered item in a plain list, renumber the
14742 ordered list.
14744 - If the cursor is on a checkbox, toggle it."
14745 (interactive "P")
14746 (let ((org-enable-table-editor t))
14747 (cond
14748 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
14749 org-occur-highlights
14750 org-latex-fragment-image-overlays)
14751 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
14752 (org-remove-occur-highlights)
14753 (org-remove-latex-fragment-image-overlays)
14754 (message "Temporary highlights/overlays removed from current buffer"))
14755 ((and (local-variable-p 'org-finish-function (current-buffer))
14756 (fboundp org-finish-function))
14757 (funcall org-finish-function))
14758 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
14759 ((org-at-property-p)
14760 (call-interactively 'org-property-action))
14761 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
14762 ((org-on-heading-p) (call-interactively 'org-set-tags))
14763 ((org-at-table.el-p)
14764 (require 'table)
14765 (beginning-of-line 1)
14766 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
14767 (call-interactively 'table-recognize-table))
14768 ((org-at-table-p)
14769 (org-table-maybe-eval-formula)
14770 (if arg
14771 (call-interactively 'org-table-recalculate)
14772 (org-table-maybe-recalculate-line))
14773 (call-interactively 'org-table-align))
14774 ((or (org-footnote-at-reference-p)
14775 (org-footnote-at-definition-p))
14776 (call-interactively 'org-footnote-action))
14777 ((org-at-item-checkbox-p)
14778 (call-interactively 'org-toggle-checkbox))
14779 ((org-at-item-p)
14780 (if arg
14781 (call-interactively 'org-toggle-checkbox)
14782 (call-interactively 'org-maybe-renumber-ordered-list)))
14783 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
14784 ;; Dynamic block
14785 (beginning-of-line 1)
14786 (save-excursion (org-update-dblock)))
14787 ((save-excursion
14788 (beginning-of-line 1)
14789 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
14790 (cond
14791 ((equal (match-string 1) "TBLFM")
14792 ;; Recalculate the table before this line
14793 (save-excursion
14794 (beginning-of-line 1)
14795 (skip-chars-backward " \r\n\t")
14796 (if (org-at-table-p)
14797 (org-call-with-arg 'org-table-recalculate t))))
14799 ; (org-set-regexps-and-options)
14800 ; (org-restart-font-lock)
14801 (let ((org-inhibit-startup t)) (org-mode-restart))
14802 (message "Local setup has been refreshed"))))
14803 ((org-clock-update-time-maybe))
14804 (t (error "C-c C-c can do nothing useful at this location.")))))
14806 (defun org-mode-restart ()
14807 "Restart Org-mode, to scan again for special lines.
14808 Also updates the keyword regular expressions."
14809 (interactive)
14810 (org-mode)
14811 (message "Org-mode restarted"))
14813 (defun org-kill-note-or-show-branches ()
14814 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
14815 (interactive)
14816 (if (not org-finish-function)
14817 (call-interactively 'show-branches)
14818 (let ((org-note-abort t))
14819 (funcall org-finish-function))))
14821 (defun org-return (&optional indent)
14822 "Goto next table row or insert a newline.
14823 Calls `org-table-next-row' or `newline', depending on context.
14824 See the individual commands for more information."
14825 (interactive)
14826 (cond
14827 ((bobp) (if indent (newline-and-indent) (newline)))
14828 ((org-at-table-p)
14829 (org-table-justify-field-maybe)
14830 (call-interactively 'org-table-next-row))
14831 ((and org-return-follows-link
14832 (eq (get-text-property (point) 'face) 'org-link))
14833 (call-interactively 'org-open-at-point))
14834 ((and (org-at-heading-p)
14835 (looking-at
14836 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
14837 (org-show-entry)
14838 (end-of-line 1)
14839 (newline))
14840 (t (if indent (newline-and-indent) (newline)))))
14842 (defun org-return-indent ()
14843 "Goto next table row or insert a newline and indent.
14844 Calls `org-table-next-row' or `newline-and-indent', depending on
14845 context. See the individual commands for more information."
14846 (interactive)
14847 (org-return t))
14849 (defun org-ctrl-c-star ()
14850 "Compute table, or change heading status of lines.
14851 Calls `org-table-recalculate' or `org-toggle-heading',
14852 depending on context."
14853 (interactive)
14854 (cond
14855 ((org-at-table-p)
14856 (call-interactively 'org-table-recalculate))
14858 ;; Convert all lines in region to list items
14859 (call-interactively 'org-toggle-heading))))
14861 (defun org-ctrl-c-minus ()
14862 "Insert separator line in table or modify bullet status of line.
14863 Also turns a plain line or a region of lines into list items.
14864 Calls `org-table-insert-hline', `org-toggle-item', or
14865 `org-cycle-list-bullet', depending on context."
14866 (interactive)
14867 (cond
14868 ((org-at-table-p)
14869 (call-interactively 'org-table-insert-hline))
14870 ((org-region-active-p)
14871 (call-interactively 'org-toggle-item))
14872 ((org-in-item-p)
14873 (call-interactively 'org-cycle-list-bullet))
14875 (call-interactively 'org-toggle-item))))
14877 (defun org-toggle-item ()
14878 "Convert headings or normal lines to items, items to normal lines.
14879 If there is no active region, only the current line is considered.
14881 If the first line in the region is a headline, convert all headlines to items.
14883 If the first line in the region is an item, convert all items to normal lines.
14885 If the first line is normal text, add an item bullet to each line."
14886 (interactive)
14887 (let (l2 l beg end)
14888 (if (org-region-active-p)
14889 (setq beg (region-beginning) end (region-end))
14890 (setq beg (point-at-bol)
14891 end (min (1+ (point-at-eol)) (point-max))))
14892 (save-excursion
14893 (goto-char end)
14894 (setq l2 (org-current-line))
14895 (goto-char beg)
14896 (beginning-of-line 1)
14897 (setq l (1- (org-current-line)))
14898 (if (org-at-item-p)
14899 ;; We already have items, de-itemize
14900 (while (< (setq l (1+ l)) l2)
14901 (when (org-at-item-p)
14902 (goto-char (match-beginning 2))
14903 (delete-region (match-beginning 2) (match-end 2))
14904 (and (looking-at "[ \t]+") (replace-match "")))
14905 (beginning-of-line 2))
14906 (if (org-on-heading-p)
14907 ;; Headings, convert to items
14908 (while (< (setq l (1+ l)) l2)
14909 (if (looking-at org-outline-regexp)
14910 (replace-match "- " t t))
14911 (beginning-of-line 2))
14912 ;; normal lines, turn them into items
14913 (while (< (setq l (1+ l)) l2)
14914 (unless (org-at-item-p)
14915 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14916 (replace-match "\\1- \\2")))
14917 (beginning-of-line 2)))))))
14919 (defun org-toggle-heading (&optional nstars)
14920 "Convert headings to normal text, or items or text to headings.
14921 If there is no active region, only the current line is considered.
14923 If the first line is a heading, remove the stars from all headlines
14924 in the region.
14926 If the first line is a plain list item, turn all plain list items
14927 into headings.
14929 If the first line is a normal line, turn each and every line in the
14930 region into a heading.
14932 When converting a line into a heading, the number of stars is chosen
14933 such that the lines become children of the current entry. However,
14934 when a prefix argument is given, its value determines the number of
14935 stars to add."
14936 (interactive "P")
14937 (let (l2 l itemp beg end)
14938 (if (org-region-active-p)
14939 (setq beg (region-beginning) end (region-end))
14940 (setq beg (point-at-bol)
14941 end (min (1+ (point-at-eol)) (point-max))))
14942 (save-excursion
14943 (goto-char end)
14944 (setq l2 (org-current-line))
14945 (goto-char beg)
14946 (beginning-of-line 1)
14947 (setq l (1- (org-current-line)))
14948 (if (org-on-heading-p)
14949 ;; We already have headlines, de-star them
14950 (while (< (setq l (1+ l)) l2)
14951 (when (org-on-heading-p t)
14952 (and (looking-at outline-regexp) (replace-match "")))
14953 (beginning-of-line 2))
14954 (setq itemp (org-at-item-p))
14955 (let* ((stars
14956 (if nstars
14957 (make-string (prefix-numeric-value current-prefix-arg)
14959 (save-excursion
14960 (if (re-search-backward org-complex-heading-regexp nil t)
14961 (match-string 1) ""))))
14962 (add-stars (cond (nstars "")
14963 ((equal stars "") "*")
14964 (org-odd-levels-only "**")
14965 (t "*")))
14966 (rpl (concat stars add-stars " ")))
14967 (while (< (setq l (1+ l)) l2)
14968 (if itemp
14969 (and (org-at-item-p) (replace-match rpl t t))
14970 (unless (org-on-heading-p)
14971 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14972 (replace-match (concat rpl (match-string 2))))))
14973 (beginning-of-line 2)))))))
14975 (defun org-meta-return (&optional arg)
14976 "Insert a new heading or wrap a region in a table.
14977 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
14978 See the individual commands for more information."
14979 (interactive "P")
14980 (cond
14981 ((run-hook-with-args-until-success 'org-metareturn-hook))
14982 ((org-at-table-p)
14983 (call-interactively 'org-table-wrap-region))
14984 (t (call-interactively 'org-insert-heading))))
14986 ;;; Menu entries
14988 ;; Define the Org-mode menus
14989 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
14990 '("Tbl"
14991 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
14992 ["Next Field" org-cycle (org-at-table-p)]
14993 ["Previous Field" org-shifttab (org-at-table-p)]
14994 ["Next Row" org-return (org-at-table-p)]
14995 "--"
14996 ["Blank Field" org-table-blank-field (org-at-table-p)]
14997 ["Edit Field" org-table-edit-field (org-at-table-p)]
14998 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
14999 "--"
15000 ("Column"
15001 ["Move Column Left" org-metaleft (org-at-table-p)]
15002 ["Move Column Right" org-metaright (org-at-table-p)]
15003 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
15004 ["Insert Column" org-shiftmetaright (org-at-table-p)])
15005 ("Row"
15006 ["Move Row Up" org-metaup (org-at-table-p)]
15007 ["Move Row Down" org-metadown (org-at-table-p)]
15008 ["Delete Row" org-shiftmetaup (org-at-table-p)]
15009 ["Insert Row" org-shiftmetadown (org-at-table-p)]
15010 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
15011 "--"
15012 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
15013 ("Rectangle"
15014 ["Copy Rectangle" org-copy-special (org-at-table-p)]
15015 ["Cut Rectangle" org-cut-special (org-at-table-p)]
15016 ["Paste Rectangle" org-paste-special (org-at-table-p)]
15017 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
15018 "--"
15019 ("Calculate"
15020 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
15021 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
15022 ["Edit Formulas" org-edit-special (org-at-table-p)]
15023 "--"
15024 ["Recalculate line" org-table-recalculate (org-at-table-p)]
15025 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
15026 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
15027 "--"
15028 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
15029 "--"
15030 ["Sum Column/Rectangle" org-table-sum
15031 (or (org-at-table-p) (org-region-active-p))]
15032 ["Which Column?" org-table-current-column (org-at-table-p)])
15033 ["Debug Formulas"
15034 org-table-toggle-formula-debugger
15035 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
15036 ["Show Col/Row Numbers"
15037 org-table-toggle-coordinate-overlays
15038 :style toggle
15039 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
15040 "--"
15041 ["Create" org-table-create (and (not (org-at-table-p))
15042 org-enable-table-editor)]
15043 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
15044 ["Import from File" org-table-import (not (org-at-table-p))]
15045 ["Export to File" org-table-export (org-at-table-p)]
15046 "--"
15047 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
15049 (easy-menu-define org-org-menu org-mode-map "Org menu"
15050 '("Org"
15051 ("Show/Hide"
15052 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
15053 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
15054 ["Sparse Tree..." org-sparse-tree t]
15055 ["Reveal Context" org-reveal t]
15056 ["Show All" show-all t]
15057 "--"
15058 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
15059 "--"
15060 ["New Heading" org-insert-heading t]
15061 ("Navigate Headings"
15062 ["Up" outline-up-heading t]
15063 ["Next" outline-next-visible-heading t]
15064 ["Previous" outline-previous-visible-heading t]
15065 ["Next Same Level" outline-forward-same-level t]
15066 ["Previous Same Level" outline-backward-same-level t]
15067 "--"
15068 ["Jump" org-goto t])
15069 ("Edit Structure"
15070 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
15071 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
15072 "--"
15073 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
15074 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
15075 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
15076 "--"
15077 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
15078 "--"
15079 ["Promote Heading" org-metaleft (not (org-at-table-p))]
15080 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
15081 ["Demote Heading" org-metaright (not (org-at-table-p))]
15082 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
15083 "--"
15084 ["Sort Region/Children" org-sort (not (org-at-table-p))]
15085 "--"
15086 ["Convert to odd levels" org-convert-to-odd-levels t]
15087 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
15088 ("Editing"
15089 ["Emphasis..." org-emphasize t]
15090 ["Edit Source Example" org-edit-special t]
15091 "--"
15092 ["Footnote new/jump" org-footnote-action t]
15093 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
15094 ("Archive"
15095 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
15096 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
15097 ; :active t :keys "C-u C-c C-x C-a"]
15098 ["Sparse trees open ARCHIVE trees"
15099 (setq org-sparse-tree-open-archived-trees
15100 (not org-sparse-tree-open-archived-trees))
15101 :style toggle :selected org-sparse-tree-open-archived-trees]
15102 ["Cycling opens ARCHIVE trees"
15103 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
15104 :style toggle :selected org-cycle-open-archived-trees]
15105 "--"
15106 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
15107 ["Move Subtree to Archive" org-advertized-archive-subtree t]
15108 ; ["Check and Move Children" (org-archive-subtree '(4))
15109 ; :active t :keys "C-u C-c C-x C-s"]
15111 "--"
15112 ("Hyperlinks"
15113 ["Store Link (Global)" org-store-link t]
15114 ["Find existing link to here" org-occur-link-in-agenda-files t]
15115 ["Insert Link" org-insert-link t]
15116 ["Follow Link" org-open-at-point t]
15117 "--"
15118 ["Next link" org-next-link t]
15119 ["Previous link" org-previous-link t]
15120 "--"
15121 ["Descriptive Links"
15122 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
15123 :style radio
15124 :selected (member '(org-link) buffer-invisibility-spec)]
15125 ["Literal Links"
15126 (progn
15127 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
15128 :style radio
15129 :selected (not (member '(org-link) buffer-invisibility-spec))])
15130 "--"
15131 ("TODO Lists"
15132 ["TODO/DONE/-" org-todo t]
15133 ("Select keyword"
15134 ["Next keyword" org-shiftright (org-on-heading-p)]
15135 ["Previous keyword" org-shiftleft (org-on-heading-p)]
15136 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
15137 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
15138 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
15139 ["Show TODO Tree" org-show-todo-tree t]
15140 ["Global TODO list" org-todo-list t]
15141 "--"
15142 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
15143 :selected org-enforce-todo-dependencies :style toggle :active t]
15144 "Settings for tree at point"
15145 ["Do Children sequentially" org-toggle-ordered-property :style radio
15146 :selected (ignore-errors (org-entry-get nil "ORDERED"))
15147 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15148 ["Do Children parallel" org-toggle-ordered-property :style radio
15149 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
15150 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15151 "--"
15152 ["Set Priority" org-priority t]
15153 ["Priority Up" org-shiftup t]
15154 ["Priority Down" org-shiftdown t]
15155 "--"
15156 ["Get news from all feeds" org-feed-update-all t]
15157 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
15158 ["Customize feeds" (customize-variable 'org-feed-alist) t])
15159 ("TAGS and Properties"
15160 ["Set Tags" org-set-tags-command t]
15161 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
15162 "--"
15163 ["Set property" org-set-property t]
15164 ["Column view of properties" org-columns t]
15165 ["Insert Column View DBlock" org-insert-columns-dblock t])
15166 ("Dates and Scheduling"
15167 ["Timestamp" org-time-stamp t]
15168 ["Timestamp (inactive)" org-time-stamp-inactive t]
15169 ("Change Date"
15170 ["1 Day Later" org-shiftright t]
15171 ["1 Day Earlier" org-shiftleft t]
15172 ["1 ... Later" org-shiftup t]
15173 ["1 ... Earlier" org-shiftdown t])
15174 ["Compute Time Range" org-evaluate-time-range t]
15175 ["Schedule Item" org-schedule t]
15176 ["Deadline" org-deadline t]
15177 "--"
15178 ["Custom time format" org-toggle-time-stamp-overlays
15179 :style radio :selected org-display-custom-times]
15180 "--"
15181 ["Goto Calendar" org-goto-calendar t]
15182 ["Date from Calendar" org-date-from-calendar t]
15183 "--"
15184 ["Start/Restart Timer" org-timer-start t]
15185 ["Pause/Continue Timer" org-timer-pause-or-continue t]
15186 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
15187 ["Insert Timer String" org-timer t]
15188 ["Insert Timer Item" org-timer-item t])
15189 ("Logging work"
15190 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
15191 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
15192 ["Clock out" org-clock-out t]
15193 ["Clock cancel" org-clock-cancel t]
15194 "--"
15195 ["Mark as default task" org-clock-mark-default-task t]
15196 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
15197 ["Goto running clock" org-clock-goto t]
15198 "--"
15199 ["Display times" org-clock-display t]
15200 ["Create clock table" org-clock-report t]
15201 "--"
15202 ["Record DONE time"
15203 (progn (setq org-log-done (not org-log-done))
15204 (message "Switching to %s will %s record a timestamp"
15205 (car org-done-keywords)
15206 (if org-log-done "automatically" "not")))
15207 :style toggle :selected org-log-done])
15208 "--"
15209 ["Agenda Command..." org-agenda t]
15210 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
15211 ("File List for Agenda")
15212 ("Special views current file"
15213 ["TODO Tree" org-show-todo-tree t]
15214 ["Check Deadlines" org-check-deadlines t]
15215 ["Timeline" org-timeline t]
15216 ["Tags/Property tree" org-match-sparse-tree t])
15217 "--"
15218 ["Export/Publish..." org-export t]
15219 ("LaTeX"
15220 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
15221 :selected org-cdlatex-mode]
15222 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
15223 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
15224 ["Modify math symbol" org-cdlatex-math-modify
15225 (org-inside-LaTeX-fragment-p)]
15226 ["Insert citation" org-reftex-citation t]
15227 "--"
15228 ["Export LaTeX fragments as images"
15229 (if (featurep 'org-exp)
15230 (setq org-export-with-LaTeX-fragments
15231 (not org-export-with-LaTeX-fragments))
15232 (require 'org-exp))
15233 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
15234 org-export-with-LaTeX-fragments)])
15235 "--"
15236 ("Documentation"
15237 ["Show Version" org-version t]
15238 ["Info Documentation" org-info t])
15239 ("Customize"
15240 ["Browse Org Group" org-customize t]
15241 "--"
15242 ["Expand This Menu" org-create-customize-menu
15243 (fboundp 'customize-menu-create)])
15244 "--"
15245 ("Refresh/Reload"
15246 ["Refresh setup current buffer" org-mode-restart t]
15247 ["Reload Org (after update)" org-reload t]
15248 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
15251 (defun org-info (&optional node)
15252 "Read documentation for Org-mode in the info system.
15253 With optional NODE, go directly to that node."
15254 (interactive)
15255 (info (format "(org)%s" (or node ""))))
15257 (defun org-install-agenda-files-menu ()
15258 (let ((bl (buffer-list)))
15259 (save-excursion
15260 (while bl
15261 (set-buffer (pop bl))
15262 (if (org-mode-p) (setq bl nil)))
15263 (when (org-mode-p)
15264 (easy-menu-change
15265 '("Org") "File List for Agenda"
15266 (append
15267 (list
15268 ["Edit File List" (org-edit-agenda-file-list) t]
15269 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
15270 ["Remove Current File from List" org-remove-file t]
15271 ["Cycle through agenda files" org-cycle-agenda-files t]
15272 ["Occur in all agenda files" org-occur-in-agenda-files t]
15273 "--")
15274 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
15276 ;;;; Documentation
15278 ;;;###autoload
15279 (defun org-require-autoloaded-modules ()
15280 (interactive)
15281 (mapc 'require
15282 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
15283 org-docbook org-exp org-html org-icalendar
15284 org-id org-latex
15285 org-publish org-remember org-table
15286 org-timer org-xoxo)))
15288 ;;;###autoload
15289 (defun org-reload (&optional uncompiled)
15290 "Reload all org lisp files.
15291 With prefix arg UNCOMPILED, load the uncompiled versions."
15292 (interactive "P")
15293 (require 'find-func)
15294 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
15295 (dir-org (file-name-directory (org-find-library-name "org")))
15296 (dir-org-contrib (ignore-errors
15297 (file-name-directory
15298 (org-find-library-name "org-contribdir"))))
15299 (files
15300 (append (directory-files dir-org t file-re)
15301 (and dir-org-contrib
15302 (directory-files dir-org-contrib t file-re))))
15303 (remove-re (concat (if (featurep 'xemacs)
15304 "org-colview" "org-colview-xemacs")
15305 "\\'")))
15306 (setq files (mapcar 'file-name-sans-extension files))
15307 (setq files (mapcar
15308 (lambda (x) (if (string-match remove-re x) nil x))
15309 files))
15310 (setq files (delq nil files))
15311 (mapc
15312 (lambda (f)
15313 (when (featurep (intern (file-name-nondirectory f)))
15314 (if (and (not uncompiled)
15315 (file-exists-p (concat f ".elc")))
15316 (load (concat f ".elc") nil nil t)
15317 (load (concat f ".el") nil nil t))))
15318 files))
15319 (org-version))
15321 ;;;###autoload
15322 (defun org-customize ()
15323 "Call the customize function with org as argument."
15324 (interactive)
15325 (org-load-modules-maybe)
15326 (org-require-autoloaded-modules)
15327 (customize-browse 'org))
15329 (defun org-create-customize-menu ()
15330 "Create a full customization menu for Org-mode, insert it into the menu."
15331 (interactive)
15332 (org-load-modules-maybe)
15333 (org-require-autoloaded-modules)
15334 (if (fboundp 'customize-menu-create)
15335 (progn
15336 (easy-menu-change
15337 '("Org") "Customize"
15338 `(["Browse Org group" org-customize t]
15339 "--"
15340 ,(customize-menu-create 'org)
15341 ["Set" Custom-set t]
15342 ["Save" Custom-save t]
15343 ["Reset to Current" Custom-reset-current t]
15344 ["Reset to Saved" Custom-reset-saved t]
15345 ["Reset to Standard Settings" Custom-reset-standard t]))
15346 (message "\"Org\"-menu now contains full customization menu"))
15347 (error "Cannot expand menu (outdated version of cus-edit.el)")))
15349 ;;;; Miscellaneous stuff
15351 ;;; Generally useful functions
15353 (defun org-find-text-property-in-string (prop s)
15354 "Return the first non-nil value of property PROP in string S."
15355 (or (get-text-property 0 prop s)
15356 (get-text-property (or (next-single-property-change 0 prop s) 0)
15357 prop s)))
15359 (defun org-display-warning (message) ;; Copied from Emacs-Muse
15360 "Display the given MESSAGE as a warning."
15361 (if (fboundp 'display-warning)
15362 (display-warning 'org message
15363 (if (featurep 'xemacs)
15364 'warning
15365 :warning))
15366 (let ((buf (get-buffer-create "*Org warnings*")))
15367 (with-current-buffer buf
15368 (goto-char (point-max))
15369 (insert "Warning (Org): " message)
15370 (unless (bolp)
15371 (newline)))
15372 (display-buffer buf)
15373 (sit-for 0))))
15375 (defun org-goto-marker-or-bmk (marker &optional bookmark)
15376 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
15377 (if (and marker (marker-buffer marker)
15378 (buffer-live-p (marker-buffer marker)))
15379 (progn
15380 (switch-to-buffer (marker-buffer marker))
15381 (if (or (> marker (point-max)) (< marker (point-min)))
15382 (widen))
15383 (goto-char marker)
15384 (org-show-context 'org-goto))
15385 (if bookmark
15386 (bookmark-jump bookmark)
15387 (error "Cannot find location"))))
15389 (defun org-quote-csv-field (s)
15390 "Quote field for inclusion in CSV material."
15391 (if (string-match "[\",]" s)
15392 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
15395 (defun org-plist-delete (plist property)
15396 "Delete PROPERTY from PLIST.
15397 This is in contrast to merely setting it to 0."
15398 (let (p)
15399 (while plist
15400 (if (not (eq property (car plist)))
15401 (setq p (plist-put p (car plist) (nth 1 plist))))
15402 (setq plist (cddr plist)))
15405 (defun org-force-self-insert (N)
15406 "Needed to enforce self-insert under remapping."
15407 (interactive "p")
15408 (self-insert-command N))
15410 (defun org-string-width (s)
15411 "Compute width of string, ignoring invisible characters.
15412 This ignores character with invisibility property `org-link', and also
15413 characters with property `org-cwidth', because these will become invisible
15414 upon the next fontification round."
15415 (let (b l)
15416 (when (or (eq t buffer-invisibility-spec)
15417 (assq 'org-link buffer-invisibility-spec))
15418 (while (setq b (text-property-any 0 (length s)
15419 'invisible 'org-link s))
15420 (setq s (concat (substring s 0 b)
15421 (substring s (or (next-single-property-change
15422 b 'invisible s) (length s)))))))
15423 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
15424 (setq s (concat (substring s 0 b)
15425 (substring s (or (next-single-property-change
15426 b 'org-cwidth s) (length s))))))
15427 (setq l (string-width s) b -1)
15428 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
15429 (setq l (- l (get-text-property b 'org-dwidth-n s))))
15432 (defun org-get-indentation (&optional line)
15433 "Get the indentation of the current line, interpreting tabs.
15434 When LINE is given, assume it represents a line and compute its indentation."
15435 (if line
15436 (if (string-match "^ *" (org-remove-tabs line))
15437 (match-end 0))
15438 (save-excursion
15439 (beginning-of-line 1)
15440 (skip-chars-forward " \t")
15441 (current-column))))
15443 (defun org-remove-tabs (s &optional width)
15444 "Replace tabulators in S with spaces.
15445 Assumes that s is a single line, starting in column 0."
15446 (setq width (or width tab-width))
15447 (while (string-match "\t" s)
15448 (setq s (replace-match
15449 (make-string
15450 (- (* width (/ (+ (match-beginning 0) width) width))
15451 (match-beginning 0)) ?\ )
15452 t t s)))
15455 (defun org-fix-indentation (line ind)
15456 "Fix indentation in LINE.
15457 IND is a cons cell with target and minimum indentation.
15458 If the current indentation in LINE is smaller than the minimum,
15459 leave it alone. If it is larger than ind, set it to the target."
15460 (let* ((l (org-remove-tabs line))
15461 (i (org-get-indentation l))
15462 (i1 (car ind)) (i2 (cdr ind)))
15463 (if (>= i i2) (setq l (substring line i2)))
15464 (if (> i1 0)
15465 (concat (make-string i1 ?\ ) l)
15466 l)))
15468 (defun org-remove-indentation (code &optional n)
15469 "Remove the maximum common indentation from the lines in CODE.
15470 N may optionally be the number of spaces to remove."
15471 (with-temp-buffer
15472 (insert code)
15473 (org-do-remove-indentation n)
15474 (buffer-string)))
15476 (defun org-do-remove-indentation (&optional n)
15477 "Remove the maximum common indentation from the buffer."
15478 (untabify (point-min) (point-max))
15479 (let ((min 10000) re)
15480 (if n
15481 (setq min n)
15482 (goto-char (point-min))
15483 (while (re-search-forward "^ *[^ \n]" nil t)
15484 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
15485 (unless (or (= min 0) (= min 10000))
15486 (setq re (format "^ \\{%d\\}" min))
15487 (goto-char (point-min))
15488 (while (re-search-forward re nil t)
15489 (replace-match "")
15490 (end-of-line 1))
15491 min)))
15493 (defun org-base-buffer (buffer)
15494 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
15495 (if (not buffer)
15496 buffer
15497 (or (buffer-base-buffer buffer)
15498 buffer)))
15500 (defun org-trim (s)
15501 "Remove whitespace at beginning and end of string."
15502 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
15503 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
15506 (defun org-wrap (string &optional width lines)
15507 "Wrap string to either a number of lines, or a width in characters.
15508 If WIDTH is non-nil, the string is wrapped to that width, however many lines
15509 that costs. If there is a word longer than WIDTH, the text is actually
15510 wrapped to the length of that word.
15511 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
15512 many lines, whatever width that takes.
15513 The return value is a list of lines, without newlines at the end."
15514 (let* ((words (org-split-string string "[ \t\n]+"))
15515 (maxword (apply 'max (mapcar 'org-string-width words)))
15516 w ll)
15517 (cond (width
15518 (org-do-wrap words (max maxword width)))
15519 (lines
15520 (setq w maxword)
15521 (setq ll (org-do-wrap words maxword))
15522 (if (<= (length ll) lines)
15524 (setq ll words)
15525 (while (> (length ll) lines)
15526 (setq w (1+ w))
15527 (setq ll (org-do-wrap words w)))
15528 ll))
15529 (t (error "Cannot wrap this")))))
15531 (defun org-do-wrap (words width)
15532 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
15533 (let (lines line)
15534 (while words
15535 (setq line (pop words))
15536 (while (and words (< (+ (length line) (length (car words))) width))
15537 (setq line (concat line " " (pop words))))
15538 (setq lines (push line lines)))
15539 (nreverse lines)))
15541 (defun org-split-string (string &optional separators)
15542 "Splits STRING into substrings at SEPARATORS.
15543 No empty strings are returned if there are matches at the beginning
15544 and end of string."
15545 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
15546 (start 0)
15547 notfirst
15548 (list nil))
15549 (while (and (string-match rexp string
15550 (if (and notfirst
15551 (= start (match-beginning 0))
15552 (< start (length string)))
15553 (1+ start) start))
15554 (< (match-beginning 0) (length string)))
15555 (setq notfirst t)
15556 (or (eq (match-beginning 0) 0)
15557 (and (eq (match-beginning 0) (match-end 0))
15558 (eq (match-beginning 0) start))
15559 (setq list
15560 (cons (substring string start (match-beginning 0))
15561 list)))
15562 (setq start (match-end 0)))
15563 (or (eq start (length string))
15564 (setq list
15565 (cons (substring string start)
15566 list)))
15567 (nreverse list)))
15569 (defun org-quote-vert (s)
15570 "Replace \"|\" with \"\\vert\"."
15571 (while (string-match "|" s)
15572 (setq s (replace-match "\\vert" t t s)))
15575 (defun org-uuidgen-p (s)
15576 "Is S an ID created by UUIDGEN?"
15577 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
15579 (defun org-context ()
15580 "Return a list of contexts of the current cursor position.
15581 If several contexts apply, all are returned.
15582 Each context entry is a list with a symbol naming the context, and
15583 two positions indicating start and end of the context. Possible
15584 contexts are:
15586 :headline anywhere in a headline
15587 :headline-stars on the leading stars in a headline
15588 :todo-keyword on a TODO keyword (including DONE) in a headline
15589 :tags on the TAGS in a headline
15590 :priority on the priority cookie in a headline
15591 :item on the first line of a plain list item
15592 :item-bullet on the bullet/number of a plain list item
15593 :checkbox on the checkbox in a plain list item
15594 :table in an org-mode table
15595 :table-special on a special filed in a table
15596 :table-table in a table.el table
15597 :link on a hyperlink
15598 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
15599 :target on a <<target>>
15600 :radio-target on a <<<radio-target>>>
15601 :latex-fragment on a LaTeX fragment
15602 :latex-preview on a LaTeX fragment with overlayed preview image
15604 This function expects the position to be visible because it uses font-lock
15605 faces as a help to recognize the following contexts: :table-special, :link,
15606 and :keyword."
15607 (let* ((f (get-text-property (point) 'face))
15608 (faces (if (listp f) f (list f)))
15609 (p (point)) clist o)
15610 ;; First the large context
15611 (cond
15612 ((org-on-heading-p t)
15613 (push (list :headline (point-at-bol) (point-at-eol)) clist)
15614 (when (progn
15615 (beginning-of-line 1)
15616 (looking-at org-todo-line-tags-regexp))
15617 (push (org-point-in-group p 1 :headline-stars) clist)
15618 (push (org-point-in-group p 2 :todo-keyword) clist)
15619 (push (org-point-in-group p 4 :tags) clist))
15620 (goto-char p)
15621 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
15622 (if (looking-at "\\[#[A-Z0-9]\\]")
15623 (push (org-point-in-group p 0 :priority) clist)))
15625 ((org-at-item-p)
15626 (push (org-point-in-group p 2 :item-bullet) clist)
15627 (push (list :item (point-at-bol)
15628 (save-excursion (org-end-of-item) (point)))
15629 clist)
15630 (and (org-at-item-checkbox-p)
15631 (push (org-point-in-group p 0 :checkbox) clist)))
15633 ((org-at-table-p)
15634 (push (list :table (org-table-begin) (org-table-end)) clist)
15635 (if (memq 'org-formula faces)
15636 (push (list :table-special
15637 (previous-single-property-change p 'face)
15638 (next-single-property-change p 'face)) clist)))
15639 ((org-at-table-p 'any)
15640 (push (list :table-table) clist)))
15641 (goto-char p)
15643 ;; Now the small context
15644 (cond
15645 ((org-at-timestamp-p)
15646 (push (org-point-in-group p 0 :timestamp) clist))
15647 ((memq 'org-link faces)
15648 (push (list :link
15649 (previous-single-property-change p 'face)
15650 (next-single-property-change p 'face)) clist))
15651 ((memq 'org-special-keyword faces)
15652 (push (list :keyword
15653 (previous-single-property-change p 'face)
15654 (next-single-property-change p 'face)) clist))
15655 ((org-on-target-p)
15656 (push (org-point-in-group p 0 :target) clist)
15657 (goto-char (1- (match-beginning 0)))
15658 (if (looking-at org-radio-target-regexp)
15659 (push (org-point-in-group p 0 :radio-target) clist))
15660 (goto-char p))
15661 ((setq o (car (delq nil
15662 (mapcar
15663 (lambda (x)
15664 (if (memq x org-latex-fragment-image-overlays) x))
15665 (org-overlays-at (point))))))
15666 (push (list :latex-fragment
15667 (org-overlay-start o) (org-overlay-end o)) clist)
15668 (push (list :latex-preview
15669 (org-overlay-start o) (org-overlay-end o)) clist))
15670 ((org-inside-LaTeX-fragment-p)
15671 ;; FIXME: positions wrong.
15672 (push (list :latex-fragment (point) (point)) clist)))
15674 (setq clist (nreverse (delq nil clist)))
15675 clist))
15677 ;; FIXME: Compare with at-regexp-p Do we need both?
15678 (defun org-in-regexp (re &optional nlines visually)
15679 "Check if point is inside a match of regexp.
15680 Normally only the current line is checked, but you can include NLINES extra
15681 lines both before and after point into the search.
15682 If VISUALLY is set, require that the cursor is not after the match but
15683 really on, so that the block visually is on the match."
15684 (catch 'exit
15685 (let ((pos (point))
15686 (eol (point-at-eol (+ 1 (or nlines 0))))
15687 (inc (if visually 1 0)))
15688 (save-excursion
15689 (beginning-of-line (- 1 (or nlines 0)))
15690 (while (re-search-forward re eol t)
15691 (if (and (<= (match-beginning 0) pos)
15692 (>= (+ inc (match-end 0)) pos))
15693 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
15695 (defun org-at-regexp-p (regexp)
15696 "Is point inside a match of REGEXP in the current line?"
15697 (catch 'exit
15698 (save-excursion
15699 (let ((pos (point)) (end (point-at-eol)))
15700 (beginning-of-line 1)
15701 (while (re-search-forward regexp end t)
15702 (if (and (<= (match-beginning 0) pos)
15703 (>= (match-end 0) pos))
15704 (throw 'exit t)))
15705 nil))))
15707 (defun org-occur-in-agenda-files (regexp &optional nlines)
15708 "Call `multi-occur' with buffers for all agenda files."
15709 (interactive "sOrg-files matching: \np")
15710 (let* ((files (org-agenda-files))
15711 (tnames (mapcar 'file-truename files))
15712 (extra org-agenda-text-search-extra-files)
15714 (when (eq (car extra) 'agenda-archives)
15715 (setq extra (cdr extra))
15716 (setq files (org-add-archive-files files)))
15717 (while (setq f (pop extra))
15718 (unless (member (file-truename f) tnames)
15719 (add-to-list 'files f 'append)
15720 (add-to-list 'tnames (file-truename f) 'append)))
15721 (multi-occur
15722 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
15723 regexp)))
15725 (if (boundp 'occur-mode-find-occurrence-hook)
15726 ;; Emacs 23
15727 (add-hook 'occur-mode-find-occurrence-hook
15728 (lambda ()
15729 (when (org-mode-p)
15730 (org-reveal))))
15731 ;; Emacs 22
15732 (defadvice occur-mode-goto-occurrence
15733 (after org-occur-reveal activate)
15734 (and (org-mode-p) (org-reveal)))
15735 (defadvice occur-mode-goto-occurrence-other-window
15736 (after org-occur-reveal activate)
15737 (and (org-mode-p) (org-reveal)))
15738 (defadvice occur-mode-display-occurrence
15739 (after org-occur-reveal activate)
15740 (when (org-mode-p)
15741 (let ((pos (occur-mode-find-occurrence)))
15742 (with-current-buffer (marker-buffer pos)
15743 (save-excursion
15744 (goto-char pos)
15745 (org-reveal)))))))
15747 (defun org-occur-link-in-agenda-files ()
15748 "Create a link and search for it in the agendas.
15749 The link is not stored in `org-stored-links', it is just created
15750 for the search purpose."
15751 (interactive)
15752 (let ((link (condition-case nil
15753 (org-store-link nil)
15754 (error "Unable to create a link to here"))))
15755 (org-occur-in-agenda-files (regexp-quote link))))
15757 (defun org-uniquify (list)
15758 "Remove duplicate elements from LIST."
15759 (let (res)
15760 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
15761 res))
15763 (defun org-delete-all (elts list)
15764 "Remove all elements in ELTS from LIST."
15765 (while elts
15766 (setq list (delete (pop elts) list)))
15767 list)
15769 (defun org-back-over-empty-lines ()
15770 "Move backwards over whitespace, to the beginning of the first empty line.
15771 Returns the number of empty lines passed."
15772 (let ((pos (point)))
15773 (skip-chars-backward " \t\n\r")
15774 (beginning-of-line 2)
15775 (goto-char (min (point) pos))
15776 (count-lines (point) pos)))
15778 (defun org-skip-whitespace ()
15779 (skip-chars-forward " \t\n\r"))
15781 (defun org-point-in-group (point group &optional context)
15782 "Check if POINT is in match-group GROUP.
15783 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
15784 match. If the match group does ot exist or point is not inside it,
15785 return nil."
15786 (and (match-beginning group)
15787 (>= point (match-beginning group))
15788 (<= point (match-end group))
15789 (if context
15790 (list context (match-beginning group) (match-end group))
15791 t)))
15793 (defun org-switch-to-buffer-other-window (&rest args)
15794 "Switch to buffer in a second window on the current frame.
15795 In particular, do not allow pop-up frames."
15796 (let (pop-up-frames special-display-buffer-names special-display-regexps
15797 special-display-function)
15798 (apply 'switch-to-buffer-other-window args)))
15800 (defun org-combine-plists (&rest plists)
15801 "Create a single property list from all plists in PLISTS.
15802 The process starts by copying the first list, and then setting properties
15803 from the other lists. Settings in the last list are the most significant
15804 ones and overrule settings in the other lists."
15805 (let ((rtn (copy-sequence (pop plists)))
15806 p v ls)
15807 (while plists
15808 (setq ls (pop plists))
15809 (while ls
15810 (setq p (pop ls) v (pop ls))
15811 (setq rtn (plist-put rtn p v))))
15812 rtn))
15814 (defun org-move-line-down (arg)
15815 "Move the current line down. With prefix argument, move it past ARG lines."
15816 (interactive "p")
15817 (let ((col (current-column))
15818 beg end pos)
15819 (beginning-of-line 1) (setq beg (point))
15820 (beginning-of-line 2) (setq end (point))
15821 (beginning-of-line (+ 1 arg))
15822 (setq pos (move-marker (make-marker) (point)))
15823 (insert (delete-and-extract-region beg end))
15824 (goto-char pos)
15825 (org-move-to-column col)))
15827 (defun org-move-line-up (arg)
15828 "Move the current line up. With prefix argument, move it past ARG lines."
15829 (interactive "p")
15830 (let ((col (current-column))
15831 beg end pos)
15832 (beginning-of-line 1) (setq beg (point))
15833 (beginning-of-line 2) (setq end (point))
15834 (beginning-of-line (- arg))
15835 (setq pos (move-marker (make-marker) (point)))
15836 (insert (delete-and-extract-region beg end))
15837 (goto-char pos)
15838 (org-move-to-column col)))
15840 (defun org-replace-escapes (string table)
15841 "Replace %-escapes in STRING with values in TABLE.
15842 TABLE is an association list with keys like \"%a\" and string values.
15843 The sequences in STRING may contain normal field width and padding information,
15844 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
15845 so values can contain further %-escapes if they are define later in TABLE."
15846 (let ((case-fold-search nil)
15847 e re rpl)
15848 (while (setq e (pop table))
15849 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
15850 (while (string-match re string)
15851 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
15852 (cdr e)))
15853 (setq string (replace-match rpl t t string))))
15854 string))
15857 (defun org-sublist (list start end)
15858 "Return a section of LIST, from START to END.
15859 Counting starts at 1."
15860 (let (rtn (c start))
15861 (setq list (nthcdr (1- start) list))
15862 (while (and list (<= c end))
15863 (push (pop list) rtn)
15864 (setq c (1+ c)))
15865 (nreverse rtn)))
15867 (defun org-find-base-buffer-visiting (file)
15868 "Like `find-buffer-visiting' but always return the base buffer and
15869 not an indirect buffer."
15870 (let ((buf (or (get-file-buffer file)
15871 (find-buffer-visiting file))))
15872 (if buf
15873 (or (buffer-base-buffer buf) buf)
15874 nil)))
15876 (defun org-image-file-name-regexp (&optional extensions)
15877 "Return regexp matching the file names of images.
15878 If EXTENSIONS is given, only match these."
15879 (if (and (not extensions) (fboundp 'image-file-name-regexp))
15880 (image-file-name-regexp)
15881 (let ((image-file-name-extensions
15882 (or extensions
15883 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
15884 "xbm" "xpm" "pbm" "pgm" "ppm"))))
15885 (concat "\\."
15886 (regexp-opt (nconc (mapcar 'upcase
15887 image-file-name-extensions)
15888 image-file-name-extensions)
15890 "\\'"))))
15892 (defun org-file-image-p (file &optional extensions)
15893 "Return non-nil if FILE is an image."
15894 (save-match-data
15895 (string-match (org-image-file-name-regexp extensions) file)))
15897 (defun org-get-cursor-date ()
15898 "Return the date at cursor in as a time.
15899 This works in the calendar and in the agenda, anywhere else it just
15900 returns the current time."
15901 (let (date day defd)
15902 (cond
15903 ((eq major-mode 'calendar-mode)
15904 (setq date (calendar-cursor-to-date)
15905 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15906 ((eq major-mode 'org-agenda-mode)
15907 (setq day (get-text-property (point) 'day))
15908 (if day
15909 (setq date (calendar-gregorian-from-absolute day)
15910 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
15911 (nth 2 date))))))
15912 (or defd (current-time))))
15914 (defvar org-agenda-action-marker (make-marker)
15915 "Marker pointing to the entry for the next agenda action.")
15917 (defun org-mark-entry-for-agenda-action ()
15918 "Mark the current entry as target of an agenda action.
15919 Agenda actions are actions executed from the agenda with the key `k',
15920 which make use of the date at the cursor."
15921 (interactive)
15922 (move-marker org-agenda-action-marker
15923 (save-excursion (org-back-to-heading t) (point))
15924 (current-buffer))
15925 (message
15926 "Entry marked for action; press `k' at desired date in agenda or calendar"))
15928 ;;; Paragraph filling stuff.
15929 ;; We want this to be just right, so use the full arsenal.
15931 (defun org-indent-line-function ()
15932 "Indent line like previous, but further if previous was headline or item."
15933 (interactive)
15934 (let* ((pos (point))
15935 (itemp (org-at-item-p))
15936 (case-fold-search t)
15937 (org-drawer-regexp (or org-drawer-regexp "\000"))
15938 column bpos bcol tpos tcol bullet btype bullet-type)
15939 ;; Find the previous relevant line
15940 (beginning-of-line 1)
15941 (cond
15942 ((looking-at "#") (setq column 0))
15943 ((looking-at "\\*+ ") (setq column 0))
15944 ((and (looking-at "[ \t]*:END:")
15945 (save-excursion (re-search-backward org-drawer-regexp nil t)))
15946 (save-excursion
15947 (goto-char (1- (match-beginning 1)))
15948 (setq column (current-column))))
15949 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
15950 (save-excursion
15951 (re-search-backward
15952 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
15953 (setq column (org-get-indentation (match-string 0))))
15955 (beginning-of-line 0)
15956 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
15957 (not (looking-at "[ \t]*:END:"))
15958 (not (looking-at org-drawer-regexp)))
15959 (beginning-of-line 0))
15960 (cond
15961 ((looking-at "\\*+[ \t]+")
15962 (if (not org-adapt-indentation)
15963 (setq column 0)
15964 (goto-char (match-end 0))
15965 (setq column (current-column))))
15966 ((looking-at org-drawer-regexp)
15967 (goto-char (1- (match-beginning 1)))
15968 (setq column (current-column)))
15969 ((looking-at "\\([ \t]*\\):END:")
15970 (goto-char (match-end 1))
15971 (setq column (current-column)))
15972 ((org-in-item-p)
15973 (org-beginning-of-item)
15974 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
15975 (setq bpos (match-beginning 1) tpos (match-end 0)
15976 bcol (progn (goto-char bpos) (current-column))
15977 tcol (progn (goto-char tpos) (current-column))
15978 bullet (match-string 1)
15979 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
15980 (if (> tcol (+ bcol org-description-max-indent))
15981 (setq tcol (+ bcol 5)))
15982 (if (not itemp)
15983 (setq column tcol)
15984 (goto-char pos)
15985 (beginning-of-line 1)
15986 (if (looking-at "\\S-")
15987 (progn
15988 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
15989 (setq bullet (match-string 1)
15990 btype (if (string-match "[0-9]" bullet) "n" bullet))
15991 (setq column (if (equal btype bullet-type) bcol tcol)))
15992 (setq column (org-get-indentation)))))
15993 (t (setq column (org-get-indentation))))))
15994 (goto-char pos)
15995 (if (<= (current-column) (current-indentation))
15996 (org-indent-line-to column)
15997 (save-excursion (org-indent-line-to column)))
15998 (setq column (current-column))
15999 (beginning-of-line 1)
16000 (if (looking-at
16001 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
16002 (replace-match (concat "\\1" (format org-property-format
16003 (match-string 2) (match-string 3)))
16004 t nil))
16005 (org-move-to-column column)))
16007 (defun org-set-autofill-regexps ()
16008 (interactive)
16009 ;; In the paragraph separator we include headlines, because filling
16010 ;; text in a line directly attached to a headline would otherwise
16011 ;; fill the headline as well.
16012 (org-set-local 'comment-start-skip "^#+[ \t]*")
16013 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
16014 ;; The paragraph starter includes hand-formatted lists.
16015 (org-set-local
16016 'paragraph-start
16017 (concat
16018 "\f" "\\|"
16019 "[ ]*$" "\\|"
16020 "\\*+ " "\\|"
16021 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
16022 "[ \t]*[:|]" "\\|"
16023 "\\$\\$" "\\|"
16024 "\\\\\\(begin\\|end\\|[][]\\)"))
16025 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
16026 ;; But only if the user has not turned off tables or fixed-width regions
16027 (org-set-local
16028 'auto-fill-inhibit-regexp
16029 (concat "\\*+ \\|#\\+"
16030 "\\|[ \t]*" org-keyword-time-regexp
16031 (if (or org-enable-table-editor org-enable-fixed-width-editor)
16032 (concat
16033 "\\|[ \t]*["
16034 (if org-enable-table-editor "|" "")
16035 (if org-enable-fixed-width-editor ":" "")
16036 "]"))))
16037 ;; We use our own fill-paragraph function, to make sure that tables
16038 ;; and fixed-width regions are not wrapped. That function will pass
16039 ;; through to `fill-paragraph' when appropriate.
16040 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
16041 ; Adaptive filling: To get full control, first make sure that
16042 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
16043 (org-set-local 'adaptive-fill-regexp "\000")
16044 (org-set-local 'adaptive-fill-function
16045 'org-adaptive-fill-function)
16046 (org-set-local
16047 'align-mode-rules-list
16048 '((org-in-buffer-settings
16049 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
16050 (modes . '(org-mode))))))
16052 (defun org-fill-paragraph (&optional justify)
16053 "Re-align a table, pass through to fill-paragraph if no table."
16054 (let ((table-p (org-at-table-p))
16055 (table.el-p (org-at-table.el-p)))
16056 (cond ((and (equal (char-after (point-at-bol)) ?*)
16057 (save-excursion (goto-char (point-at-bol))
16058 (looking-at outline-regexp)))
16059 t) ; skip headlines
16060 (table.el-p t) ; skip table.el tables
16061 (table-p (org-table-align) t) ; align org-mode tables
16062 (t nil)))) ; call paragraph-fill
16064 ;; For reference, this is the default value of adaptive-fill-regexp
16065 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
16067 (defun org-adaptive-fill-function ()
16068 "Return a fill prefix for org-mode files.
16069 In particular, this makes sure hanging paragraphs for hand-formatted lists
16070 work correctly."
16071 (cond ((looking-at "#[ \t]+")
16072 (match-string 0))
16073 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
16074 (save-excursion
16075 (if (> (match-end 1) (+ (match-beginning 1)
16076 org-description-max-indent))
16077 (goto-char (+ (match-beginning 1) 5))
16078 (goto-char (match-end 0)))
16079 (make-string (current-column) ?\ )))
16080 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
16081 (save-excursion
16082 (goto-char (match-end 0))
16083 (make-string (current-column) ?\ )))
16084 (t nil)))
16086 ;;; Other stuff.
16088 (defun org-toggle-fixed-width-section (arg)
16089 "Toggle the fixed-width export.
16090 If there is no active region, the QUOTE keyword at the current headline is
16091 inserted or removed. When present, it causes the text between this headline
16092 and the next to be exported as fixed-width text, and unmodified.
16093 If there is an active region, this command adds or removes a colon as the
16094 first character of this line. If the first character of a line is a colon,
16095 this line is also exported in fixed-width font."
16096 (interactive "P")
16097 (let* ((cc 0)
16098 (regionp (org-region-active-p))
16099 (beg (if regionp (region-beginning) (point)))
16100 (end (if regionp (region-end)))
16101 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
16102 (case-fold-search nil)
16103 (re "[ \t]*\\(: \\)")
16104 off)
16105 (if regionp
16106 (save-excursion
16107 (goto-char beg)
16108 (setq cc (current-column))
16109 (beginning-of-line 1)
16110 (setq off (looking-at re))
16111 (while (> nlines 0)
16112 (setq nlines (1- nlines))
16113 (beginning-of-line 1)
16114 (cond
16115 (arg
16116 (org-move-to-column cc t)
16117 (insert ": \n")
16118 (forward-line -1))
16119 ((and off (looking-at re))
16120 (replace-match "" t t nil 1))
16121 ((not off) (org-move-to-column cc t) (insert ": ")))
16122 (forward-line 1)))
16123 (save-excursion
16124 (org-back-to-heading)
16125 (if (looking-at (concat outline-regexp
16126 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
16127 (replace-match "" t t nil 1)
16128 (if (looking-at outline-regexp)
16129 (progn
16130 (goto-char (match-end 0))
16131 (insert org-quote-string " "))))))))
16133 (defun org-reftex-citation ()
16134 "Use reftex-citation to insert a citation into the buffer.
16135 This looks for a line like
16137 #+BIBLIOGRAPHY: foo plain option:-d
16139 and derives from it that foo.bib is the bbliography file relevant
16140 for this document. It then installs the necessary environment for RefTeX
16141 to work in this buffer and calls `reftex-citation' to insert a citation
16142 into the buffer.
16144 Export of such citations to both LaTeX and HTML is handled by the contributed
16145 package org-exp-bibtex by Taru Karttunen."
16146 (interactive)
16147 (let ((reftex-docstruct-symbol 'rds)
16148 (reftex-cite-format "\\cite{%l}")
16149 rds bib)
16150 (save-excursion
16151 (save-restriction
16152 (widen)
16153 (let ((case-fold-search t)
16154 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
16155 (if (not (save-excursion
16156 (or (re-search-forward re nil t)
16157 (re-search-backward re nil t))))
16158 (error "No bibliography defined in file")
16159 (setq bib (concat (match-string 1) ".bib")
16160 rds (list (list 'bib bib)))))))
16161 (call-interactively 'reftex-citation)))
16163 ;;;; Functions extending outline functionality
16165 (defun org-beginning-of-line (&optional arg)
16166 "Go to the beginning of the current line. If that is invisible, continue
16167 to a visible line beginning. This makes the function of C-a more intuitive.
16168 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16169 first attempt, and only move to after the tags when the cursor is already
16170 beyond the end of the headline."
16171 (interactive "P")
16172 (let ((pos (point))
16173 (special (if (consp org-special-ctrl-a/e)
16174 (car org-special-ctrl-a/e)
16175 org-special-ctrl-a/e))
16176 refpos)
16177 (if (org-bound-and-true-p line-move-visual)
16178 (beginning-of-visual-line 1)
16179 (beginning-of-line 1))
16180 (if (and arg (fboundp 'move-beginning-of-line))
16181 (call-interactively 'move-beginning-of-line)
16182 (if (bobp)
16184 (backward-char 1)
16185 (if (org-invisible-p)
16186 (while (and (not (bobp)) (org-invisible-p))
16187 (backward-char 1)
16188 (beginning-of-line 1))
16189 (forward-char 1))))
16190 (when special
16191 (cond
16192 ((and (looking-at org-complex-heading-regexp)
16193 (= (char-after (match-end 1)) ?\ ))
16194 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
16195 (point-at-eol)))
16196 (goto-char
16197 (if (eq special t)
16198 (cond ((> pos refpos) refpos)
16199 ((= pos (point)) refpos)
16200 (t (point)))
16201 (cond ((> pos (point)) (point))
16202 ((not (eq last-command this-command)) (point))
16203 (t refpos)))))
16204 ((org-at-item-p)
16205 (goto-char
16206 (if (eq special t)
16207 (cond ((> pos (match-end 4)) (match-end 4))
16208 ((= pos (point)) (match-end 4))
16209 (t (point)))
16210 (cond ((> pos (point)) (point))
16211 ((not (eq last-command this-command)) (point))
16212 (t (match-end 4))))))))
16213 (org-no-warnings
16214 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16216 (defun org-end-of-line (&optional arg)
16217 "Go to the end of the line.
16218 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16219 first attempt, and only move to after the tags when the cursor is already
16220 beyond the end of the headline."
16221 (interactive "P")
16222 (let ((special (if (consp org-special-ctrl-a/e)
16223 (cdr org-special-ctrl-a/e)
16224 org-special-ctrl-a/e)))
16225 (if (or (not special)
16226 (not (org-on-heading-p))
16227 arg)
16228 (call-interactively
16229 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
16230 ((fboundp 'move-end-of-line) 'move-end-of-line)
16231 (t 'end-of-line)))
16232 (let ((pos (point)))
16233 (beginning-of-line 1)
16234 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
16235 (if (eq special t)
16236 (if (or (< pos (match-beginning 1))
16237 (= pos (match-end 0)))
16238 (goto-char (match-beginning 1))
16239 (goto-char (match-end 0)))
16240 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
16241 (goto-char (match-end 0))
16242 (goto-char (match-beginning 1))))
16243 (call-interactively (if (fboundp 'move-end-of-line)
16244 'move-end-of-line
16245 'end-of-line)))))
16246 (org-no-warnings
16247 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16249 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
16250 (define-key org-mode-map "\C-e" 'org-end-of-line)
16252 (defun org-backward-sentence (&optional arg)
16253 "Go to beginning of sentence, or beginning of table field.
16254 This will call `backward-sentence' or `org-table-beginning-of-field',
16255 depending on context."
16256 (interactive "P")
16257 (cond
16258 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
16259 (t (call-interactively 'backward-sentence))))
16261 (defun org-forward-sentence (&optional arg)
16262 "Go to end of sentence, or end of table field.
16263 This will call `forward-sentence' or `org-table-end-of-field',
16264 depending on context."
16265 (interactive "P")
16266 (cond
16267 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
16268 (t (call-interactively 'forward-sentence))))
16270 (define-key org-mode-map "\M-a" 'org-backward-sentence)
16271 (define-key org-mode-map "\M-e" 'org-forward-sentence)
16273 (defun org-kill-line (&optional arg)
16274 "Kill line, to tags or end of line."
16275 (interactive "P")
16276 (cond
16277 ((or (not org-special-ctrl-k)
16278 (bolp)
16279 (not (org-on-heading-p)))
16280 (call-interactively 'kill-line))
16281 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
16282 (kill-region (point) (match-beginning 1))
16283 (org-set-tags nil t))
16284 (t (kill-region (point) (point-at-eol)))))
16286 (define-key org-mode-map "\C-k" 'org-kill-line)
16288 (defun org-yank (&optional arg)
16289 "Yank. If the kill is a subtree, treat it specially.
16290 This command will look at the current kill and check if is a single
16291 subtree, or a series of subtrees[1]. If it passes the test, and if the
16292 cursor is at the beginning of a line or after the stars of a currently
16293 empty headline, then the yank is handled specially. How exactly depends
16294 on the value of the following variables, both set by default.
16296 org-yank-folded-subtrees
16297 When set, the subtree(s) will be folded after insertion, but only
16298 if doing so would now swallow text after the yanked text.
16300 org-yank-adjusted-subtrees
16301 When set, the subtree will be promoted or demoted in order to
16302 fit into the local outline tree structure, which means that the level
16303 will be adjusted so that it becomes the smaller one of the two
16304 *visible* surrounding headings.
16306 Any prefix to this command will cause `yank' to be called directly with
16307 no special treatment. In particular, a simple `C-u' prefix will just
16308 plainly yank the text as it is.
16310 \[1] The test checks if the first non-white line is a heading
16311 and if there are no other headings with fewer stars."
16312 (interactive "P")
16313 (org-yank-generic 'yank arg))
16315 (defun org-yank-generic (command arg)
16316 "Perform some yank-like command.
16318 This function implements the behavior described in the `org-yank'
16319 documentation. However, it has been generalized to work for any
16320 interactive command with similar behavior."
16322 ;; pretend to be command COMMAND
16323 (setq this-command command)
16325 (if arg
16326 (call-interactively command)
16328 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
16329 (and (org-kill-is-subtree-p)
16330 (or (bolp)
16331 (and (looking-at "[ \t]*$")
16332 (string-match
16333 "\\`\\*+\\'"
16334 (buffer-substring (point-at-bol) (point)))))))
16335 swallowp)
16336 (cond
16337 ((and subtreep org-yank-folded-subtrees)
16338 (let ((beg (point))
16339 end)
16340 (if (and subtreep org-yank-adjusted-subtrees)
16341 (org-paste-subtree nil nil 'for-yank)
16342 (call-interactively command))
16344 (setq end (point))
16345 (goto-char beg)
16346 (when (and (bolp) subtreep
16347 (not (setq swallowp
16348 (org-yank-folding-would-swallow-text beg end))))
16349 (or (looking-at outline-regexp)
16350 (re-search-forward (concat "^" outline-regexp) end t))
16351 (while (and (< (point) end) (looking-at outline-regexp))
16352 (hide-subtree)
16353 (org-cycle-show-empty-lines 'folded)
16354 (condition-case nil
16355 (outline-forward-same-level 1)
16356 (error (goto-char end)))))
16357 (when swallowp
16358 (message
16359 "Inserted text not folded because that would swallow text"))
16361 (goto-char end)
16362 (skip-chars-forward " \t\n\r")
16363 (beginning-of-line 1)
16364 (push-mark beg 'nomsg)))
16365 ((and subtreep org-yank-adjusted-subtrees)
16366 (let ((beg (point-at-bol)))
16367 (org-paste-subtree nil nil 'for-yank)
16368 (push-mark beg 'nomsg)))
16370 (call-interactively command))))))
16372 (defun org-yank-folding-would-swallow-text (beg end)
16373 "Would hide-subtree at BEG swallow any text after END?"
16374 (let (level)
16375 (save-excursion
16376 (goto-char beg)
16377 (when (or (looking-at outline-regexp)
16378 (re-search-forward (concat "^" outline-regexp) end t))
16379 (setq level (org-outline-level)))
16380 (goto-char end)
16381 (skip-chars-forward " \t\r\n\v\f")
16382 (if (or (eobp)
16383 (and (bolp) (looking-at org-outline-regexp)
16384 (<= (org-outline-level) level)))
16385 nil ; Nothing would be swallowed
16386 t)))) ; something would swallow
16388 (define-key org-mode-map "\C-y" 'org-yank)
16390 (defun org-invisible-p ()
16391 "Check if point is at a character currently not visible."
16392 ;; Early versions of noutline don't have `outline-invisible-p'.
16393 (if (fboundp 'outline-invisible-p)
16394 (outline-invisible-p)
16395 (get-char-property (point) 'invisible)))
16397 (defun org-invisible-p2 ()
16398 "Check if point is at a character currently not visible."
16399 (save-excursion
16400 (if (and (eolp) (not (bobp))) (backward-char 1))
16401 ;; Early versions of noutline don't have `outline-invisible-p'.
16402 (if (fboundp 'outline-invisible-p)
16403 (outline-invisible-p)
16404 (get-char-property (point) 'invisible))))
16406 (defun org-back-to-heading (&optional invisible-ok)
16407 "Call `outline-back-to-heading', but provide a better error message."
16408 (condition-case nil
16409 (outline-back-to-heading invisible-ok)
16410 (error (error "Before first headline at position %d in buffer %s"
16411 (point) (current-buffer)))))
16413 (defun org-before-first-heading-p ()
16414 "Before first heading?"
16415 (save-excursion
16416 (null (re-search-backward "^\\*+ " nil t))))
16418 (defalias 'org-on-heading-p 'outline-on-heading-p)
16419 (defalias 'org-at-heading-p 'outline-on-heading-p)
16420 (defun org-at-heading-or-item-p ()
16421 (or (org-on-heading-p) (org-at-item-p)))
16423 (defun org-on-target-p ()
16424 (or (org-in-regexp org-radio-target-regexp)
16425 (org-in-regexp org-target-regexp)))
16427 (defun org-up-heading-all (arg)
16428 "Move to the heading line of which the present line is a subheading.
16429 This function considers both visible and invisible heading lines.
16430 With argument, move up ARG levels."
16431 (if (fboundp 'outline-up-heading-all)
16432 (outline-up-heading-all arg) ; emacs 21 version of outline.el
16433 (outline-up-heading arg t))) ; emacs 22 version of outline.el
16435 (defun org-up-heading-safe ()
16436 "Move to the heading line of which the present line is a subheading.
16437 This version will not throw an error. It will return the level of the
16438 headline found, or nil if no higher level is found.
16440 Also, this function will be a lot faster than `outline-up-heading',
16441 because it relies on stars being the outline starters. This can really
16442 make a significant difference in outlines with very many siblings."
16443 (let (start-level re)
16444 (org-back-to-heading t)
16445 (setq start-level (funcall outline-level))
16446 (if (equal start-level 1)
16448 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
16449 (if (re-search-backward re nil t)
16450 (funcall outline-level)))))
16452 (defun org-first-sibling-p ()
16453 "Is this heading the first child of its parents?"
16454 (interactive)
16455 (let ((re (concat "^" outline-regexp))
16456 level l)
16457 (unless (org-at-heading-p t)
16458 (error "Not at a heading"))
16459 (setq level (funcall outline-level))
16460 (save-excursion
16461 (if (not (re-search-backward re nil t))
16463 (setq l (funcall outline-level))
16464 (< l level)))))
16466 (defun org-goto-sibling (&optional previous)
16467 "Goto the next sibling, even if it is invisible.
16468 When PREVIOUS is set, go to the previous sibling instead. Returns t
16469 when a sibling was found. When none is found, return nil and don't
16470 move point."
16471 (let ((fun (if previous 're-search-backward 're-search-forward))
16472 (pos (point))
16473 (re (concat "^" outline-regexp))
16474 level l)
16475 (when (condition-case nil (org-back-to-heading t) (error nil))
16476 (setq level (funcall outline-level))
16477 (catch 'exit
16478 (or previous (forward-char 1))
16479 (while (funcall fun re nil t)
16480 (setq l (funcall outline-level))
16481 (when (< l level) (goto-char pos) (throw 'exit nil))
16482 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
16483 (goto-char pos)
16484 nil))))
16486 (defun org-show-siblings ()
16487 "Show all siblings of the current headline."
16488 (save-excursion
16489 (while (org-goto-sibling) (org-flag-heading nil)))
16490 (save-excursion
16491 (while (org-goto-sibling 'previous)
16492 (org-flag-heading nil))))
16494 (defun org-show-hidden-entry ()
16495 "Show an entry where even the heading is hidden."
16496 (save-excursion
16497 (org-show-entry)))
16499 (defun org-flag-heading (flag &optional entry)
16500 "Flag the current heading. FLAG non-nil means make invisible.
16501 When ENTRY is non-nil, show the entire entry."
16502 (save-excursion
16503 (org-back-to-heading t)
16504 ;; Check if we should show the entire entry
16505 (if entry
16506 (progn
16507 (org-show-entry)
16508 (save-excursion
16509 (and (outline-next-heading)
16510 (org-flag-heading nil))))
16511 (outline-flag-region (max (point-min) (1- (point)))
16512 (save-excursion (outline-end-of-heading) (point))
16513 flag))))
16515 (defun org-get-next-sibling ()
16516 "Move to next heading of the same level, and return point.
16517 If there is no such heading, return nil.
16518 This is like outline-next-sibling, but invisible headings are ok."
16519 (let ((level (funcall outline-level)))
16520 (outline-next-heading)
16521 (while (and (not (eobp)) (> (funcall outline-level) level))
16522 (outline-next-heading))
16523 (if (or (eobp) (< (funcall outline-level) level))
16525 (point))))
16527 (defun org-end-of-subtree (&optional invisible-OK to-heading)
16528 ;; This contains an exact copy of the original function, but it uses
16529 ;; `org-back-to-heading', to make it work also in invisible
16530 ;; trees. And is uses an invisible-OK argument.
16531 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
16532 ;; Furthermore, when used inside Org, finding the end of a large subtree
16533 ;; with many children and grandchildren etc, this can be much faster
16534 ;; than the outline version.
16535 (org-back-to-heading invisible-OK)
16536 (let ((first t)
16537 (level (funcall outline-level)))
16538 (if (and (org-mode-p) (< level 1000))
16539 ;; A true heading (not a plain list item), in Org-mode
16540 ;; This means we can easily find the end by looking
16541 ;; only for the right number of stars. Using a regexp to do
16542 ;; this is so much faster than using a Lisp loop.
16543 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
16544 (forward-char 1)
16545 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
16546 ;; something else, do it the slow way
16547 (while (and (not (eobp))
16548 (or first (> (funcall outline-level) level)))
16549 (setq first nil)
16550 (outline-next-heading)))
16551 (unless to-heading
16552 (if (memq (preceding-char) '(?\n ?\^M))
16553 (progn
16554 ;; Go to end of line before heading
16555 (forward-char -1)
16556 (if (memq (preceding-char) '(?\n ?\^M))
16557 ;; leave blank line before heading
16558 (forward-char -1))))))
16559 (point))
16561 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
16562 "Use Org version in org-mode, for dramatic speed-up."
16563 (if (eq major-mode 'org-mode)
16564 (org-end-of-subtree)
16565 ad-do-it))
16567 (defun org-forward-same-level (arg &optional invisible-ok)
16568 "Move forward to the arg'th subheading at same level as this one.
16569 Stop at the first and last subheadings of a superior heading."
16570 (interactive "p")
16571 (org-back-to-heading)
16572 (org-on-heading-p)
16573 (let* ((level (- (match-end 0) (match-beginning 0) 1))
16574 (re (format "^\\*\\{1,%d\\} " level))
16576 (forward-char 1)
16577 (while (> arg 0)
16578 (while (and (re-search-forward re nil 'move)
16579 (setq l (- (match-end 0) (match-beginning 0) 1))
16580 (= l level)
16581 (not invisible-ok)
16582 (org-invisible-p))
16583 (if (< l level) (setq arg 1)))
16584 (setq arg (1- arg)))
16585 (beginning-of-line 1)))
16587 (defun org-backward-same-level (arg &optional invisible-ok)
16588 "Move backward to the arg'th subheading at same level as this one.
16589 Stop at the first and last subheadings of a superior heading."
16590 (interactive "p")
16591 (org-back-to-heading)
16592 (org-on-heading-p)
16593 (let* ((level (- (match-end 0) (match-beginning 0) 1))
16594 (re (format "^\\*\\{1,%d\\} " level))
16596 (while (> arg 0)
16597 (while (and (re-search-backward re nil 'move)
16598 (setq l (- (match-end 0) (match-beginning 0) 1))
16599 (= l level)
16600 (not invisible-ok)
16601 (org-invisible-p))
16602 (if (< l level) (setq arg 1)))
16603 (setq arg (1- arg)))))
16605 (defun org-show-subtree ()
16606 "Show everything after this heading at deeper levels."
16607 (outline-flag-region
16608 (point)
16609 (save-excursion
16610 (outline-end-of-subtree) (outline-next-heading) (point))
16611 nil))
16613 (defun org-show-entry ()
16614 "Show the body directly following this heading.
16615 Show the heading too, if it is currently invisible."
16616 (interactive)
16617 (save-excursion
16618 (condition-case nil
16619 (progn
16620 (org-back-to-heading t)
16621 (outline-flag-region
16622 (max (point-min) (1- (point)))
16623 (save-excursion
16624 (if (re-search-forward
16625 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
16626 (match-beginning 1)
16627 (point-max)))
16628 nil)
16629 (org-cycle-hide-drawers 'children))
16630 (error nil))))
16632 (defun org-make-options-regexp (kwds &optional extra)
16633 "Make a regular expression for keyword lines."
16634 (concat
16636 "#?[ \t]*\\+\\("
16637 (mapconcat 'regexp-quote kwds "\\|")
16638 (if extra (concat "\\|" extra))
16639 "\\):[ \t]*"
16640 "\\(.*\\)"))
16642 ;; Make isearch reveal the necessary context
16643 (defun org-isearch-end ()
16644 "Reveal context after isearch exits."
16645 (when isearch-success ; only if search was successful
16646 (if (featurep 'xemacs)
16647 ;; Under XEmacs, the hook is run in the correct place,
16648 ;; we directly show the context.
16649 (org-show-context 'isearch)
16650 ;; In Emacs the hook runs *before* restoring the overlays.
16651 ;; So we have to use a one-time post-command-hook to do this.
16652 ;; (Emacs 22 has a special variable, see function `org-mode')
16653 (unless (and (boundp 'isearch-mode-end-hook-quit)
16654 isearch-mode-end-hook-quit)
16655 ;; Only when the isearch was not quitted.
16656 (org-add-hook 'post-command-hook 'org-isearch-post-command
16657 'append 'local)))))
16659 (defun org-isearch-post-command ()
16660 "Remove self from hook, and show context."
16661 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
16662 (org-show-context 'isearch))
16665 ;;;; Integration with and fixes for other packages
16667 ;;; Imenu support
16669 (defvar org-imenu-markers nil
16670 "All markers currently used by Imenu.")
16671 (make-variable-buffer-local 'org-imenu-markers)
16673 (defun org-imenu-new-marker (&optional pos)
16674 "Return a new marker for use by Imenu, and remember the marker."
16675 (let ((m (make-marker)))
16676 (move-marker m (or pos (point)))
16677 (push m org-imenu-markers)
16680 (defun org-imenu-get-tree ()
16681 "Produce the index for Imenu."
16682 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
16683 (setq org-imenu-markers nil)
16684 (let* ((n org-imenu-depth)
16685 (re (concat "^" outline-regexp))
16686 (subs (make-vector (1+ n) nil))
16687 (last-level 0)
16688 m level head)
16689 (save-excursion
16690 (save-restriction
16691 (widen)
16692 (goto-char (point-max))
16693 (while (re-search-backward re nil t)
16694 (setq level (org-reduced-level (funcall outline-level)))
16695 (when (<= level n)
16696 (looking-at org-complex-heading-regexp)
16697 (setq head (org-link-display-format
16698 (org-match-string-no-properties 4))
16699 m (org-imenu-new-marker))
16700 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
16701 (if (>= level last-level)
16702 (push (cons head m) (aref subs level))
16703 (push (cons head (aref subs (1+ level))) (aref subs level))
16704 (loop for i from (1+ level) to n do (aset subs i nil)))
16705 (setq last-level level)))))
16706 (aref subs 1)))
16708 (eval-after-load "imenu"
16709 '(progn
16710 (add-hook 'imenu-after-jump-hook
16711 (lambda ()
16712 (if (eq major-mode 'org-mode)
16713 (org-show-context 'org-goto))))))
16715 (defun org-link-display-format (link)
16716 "Replace a link with either the description, or the link target
16717 if no description is present"
16718 (save-match-data
16719 (if (string-match org-bracket-link-analytic-regexp link)
16720 (replace-match (or (match-string 5 link)
16721 (concat (match-string 1 link)
16722 (match-string 3 link)))
16723 nil nil link)
16724 link)))
16726 ;; Speedbar support
16728 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
16729 "Overlay marking the agenda restriction line in speedbar.")
16730 (org-overlay-put org-speedbar-restriction-lock-overlay
16731 'face 'org-agenda-restriction-lock)
16732 (org-overlay-put org-speedbar-restriction-lock-overlay
16733 'help-echo "Agendas are currently limited to this item.")
16734 (org-detach-overlay org-speedbar-restriction-lock-overlay)
16736 (defun org-speedbar-set-agenda-restriction ()
16737 "Restrict future agenda commands to the location at point in speedbar.
16738 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
16739 (interactive)
16740 (require 'org-agenda)
16741 (let (p m tp np dir txt)
16742 (cond
16743 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16744 'org-imenu t))
16745 (setq m (get-text-property p 'org-imenu-marker))
16746 (save-excursion
16747 (save-restriction
16748 (set-buffer (marker-buffer m))
16749 (goto-char m)
16750 (org-agenda-set-restriction-lock 'subtree))))
16751 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16752 'speedbar-function 'speedbar-find-file))
16753 (setq tp (previous-single-property-change
16754 (1+ p) 'speedbar-function)
16755 np (next-single-property-change
16756 tp 'speedbar-function)
16757 dir (speedbar-line-directory)
16758 txt (buffer-substring-no-properties (or tp (point-min))
16759 (or np (point-max))))
16760 (save-excursion
16761 (save-restriction
16762 (set-buffer (find-file-noselect
16763 (let ((default-directory dir))
16764 (expand-file-name txt))))
16765 (unless (org-mode-p)
16766 (error "Cannot restrict to non-Org-mode file"))
16767 (org-agenda-set-restriction-lock 'file))))
16768 (t (error "Don't know how to restrict Org-mode's agenda")))
16769 (org-move-overlay org-speedbar-restriction-lock-overlay
16770 (point-at-bol) (point-at-eol))
16771 (setq current-prefix-arg nil)
16772 (org-agenda-maybe-redo)))
16774 (eval-after-load "speedbar"
16775 '(progn
16776 (speedbar-add-supported-extension ".org")
16777 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
16778 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
16779 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
16780 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16781 (add-hook 'speedbar-visiting-tag-hook
16782 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
16785 ;;; Fixes and Hacks for problems with other packages
16787 ;; Make flyspell not check words in links, to not mess up our keymap
16788 (defun org-mode-flyspell-verify ()
16789 "Don't let flyspell put overlays at active buttons."
16790 (and (not (get-text-property (point) 'keymap))
16791 (not (get-text-property (point) 'org-no-flyspell))))
16793 (defun org-remove-flyspell-overlays-in (beg end)
16794 "Remove flyspell overlays in region."
16795 (and (org-bound-and-true-p flyspell-mode)
16796 (fboundp 'flyspell-delete-region-overlays)
16797 (flyspell-delete-region-overlays beg end))
16798 (add-text-properties beg end '(org-no-flyspell t)))
16800 ;; Make `bookmark-jump' show the jump location if it was hidden.
16801 (eval-after-load "bookmark"
16802 '(if (boundp 'bookmark-after-jump-hook)
16803 ;; We can use the hook
16804 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
16805 ;; Hook not available, use advice
16806 (defadvice bookmark-jump (after org-make-visible activate)
16807 "Make the position visible."
16808 (org-bookmark-jump-unhide))))
16810 ;; Make sure saveplace show the location if it was hidden
16811 (eval-after-load "saveplace"
16812 '(defadvice save-place-find-file-hook (after org-make-visible activate)
16813 "Make the position visible."
16814 (org-bookmark-jump-unhide)))
16816 (defun org-bookmark-jump-unhide ()
16817 "Unhide the current position, to show the bookmark location."
16818 (and (org-mode-p)
16819 (or (org-invisible-p)
16820 (save-excursion (goto-char (max (point-min) (1- (point))))
16821 (org-invisible-p)))
16822 (org-show-context 'bookmark-jump)))
16824 ;; Make session.el ignore our circular variable
16825 (eval-after-load "session"
16826 '(add-to-list 'session-globals-exclude 'org-mark-ring))
16828 ;;;; Experimental code
16830 (defun org-closed-in-range ()
16831 "Sparse tree of items closed in a certain time range.
16832 Still experimental, may disappear in the future."
16833 (interactive)
16834 ;; Get the time interval from the user.
16835 (let* ((time1 (time-to-seconds
16836 (org-read-date nil 'to-time nil "Starting date: ")))
16837 (time2 (time-to-seconds
16838 (org-read-date nil 'to-time nil "End date:")))
16839 ;; callback function
16840 (callback (lambda ()
16841 (let ((time
16842 (time-to-seconds
16843 (apply 'encode-time
16844 (org-parse-time-string
16845 (match-string 1))))))
16846 ;; check if time in interval
16847 (and (>= time time1) (<= time time2))))))
16848 ;; make tree, check each match with the callback
16849 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
16851 ;;;; Finish up
16853 (provide 'org)
16855 (run-hooks 'org-load-hook)
16857 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
16859 ;;; org.el ends here