Release 6.29a
[org-mode.git] / lisp / org.el
blobd971f7d1e5a249e78bb3593d0c264cb090a08a8d
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.29a
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.29a"
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 (when (looking-at org-table-line-regexp)
3032 (save-excursion (funcall function))
3033 (or (looking-at org-table-line-regexp)
3034 (forward-char 1)))
3035 (re-search-forward org-table-any-border-regexp nil 1))))
3036 (message "Mapping tables: done"))
3038 ;; Declare and autoload functions from org-exp.el & Co
3040 (declare-function org-default-export-plist "org-exp")
3041 (declare-function org-infile-export-plist "org-exp")
3042 (declare-function org-get-current-options "org-exp")
3043 (eval-and-compile
3044 (org-autoload "org-exp"
3045 '(org-export org-export-visible
3046 org-insert-export-options-template
3047 org-table-clean-before-export))
3048 (org-autoload "org-ascii"
3049 '(org-export-as-ascii org-export-ascii-preprocess
3050 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3051 org-export-region-as-ascii))
3052 (org-autoload "org-html"
3053 '(org-export-as-html-and-open
3054 org-export-as-html-batch org-export-as-html-to-buffer
3055 org-replace-region-by-html org-export-region-as-html
3056 org-export-as-html))
3057 (org-autoload "org-icalendar"
3058 '(org-export-icalendar-this-file
3059 org-export-icalendar-all-agenda-files
3060 org-export-icalendar-combine-agenda-files))
3061 (org-autoload "org-xoxo" '(org-export-as-xoxo)))
3063 ;; Declare and autoload functions from org-agenda.el
3065 (eval-and-compile
3066 (org-autoload "org-agenda"
3067 '(org-agenda org-agenda-list org-search-view
3068 org-todo-list org-tags-view org-agenda-list-stuck-projects
3069 org-diary org-agenda-to-appt
3070 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3072 ;; Autoload org-remember
3074 (eval-and-compile
3075 (org-autoload "org-remember"
3076 '(org-remember-insinuate org-remember-annotation
3077 org-remember-apply-template org-remember org-remember-handler)))
3079 ;; Autoload org-clock.el
3082 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3083 (beg end))
3084 (declare-function org-clock-update-mode-line "org-clock" ())
3085 (defvar org-clock-start-time)
3086 (defvar org-clock-marker (make-marker)
3087 "Marker recording the last clock-in.")
3088 (defun org-clock-is-active ()
3089 "Return non-nil if clock is currently running.
3090 The return value is actually the clock marker."
3091 (marker-buffer org-clock-marker))
3093 (eval-and-compile
3094 (org-autoload
3095 "org-clock"
3096 '(org-clock-in org-clock-out org-clock-cancel
3097 org-clock-goto org-clock-sum org-clock-display
3098 org-clock-remove-overlays org-clock-report
3099 org-clocktable-shift org-dblock-write:clocktable
3100 org-get-clocktable)))
3102 (defun org-clock-update-time-maybe ()
3103 "If this is a CLOCK line, update it and return t.
3104 Otherwise, return nil."
3105 (interactive)
3106 (save-excursion
3107 (beginning-of-line 1)
3108 (skip-chars-forward " \t")
3109 (when (looking-at org-clock-string)
3110 (let ((re (concat "[ \t]*" org-clock-string
3111 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3112 "\\([ \t]*=>.*\\)?\\)?"))
3113 ts te h m s neg)
3114 (cond
3115 ((not (looking-at re))
3116 nil)
3117 ((not (match-end 2))
3118 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3119 (> org-clock-marker (point))
3120 (<= org-clock-marker (point-at-eol)))
3121 ;; The clock is running here
3122 (setq org-clock-start-time
3123 (apply 'encode-time
3124 (org-parse-time-string (match-string 1))))
3125 (org-clock-update-mode-line)))
3127 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3128 (end-of-line 1)
3129 (setq ts (match-string 1)
3130 te (match-string 3))
3131 (setq s (- (time-to-seconds
3132 (apply 'encode-time (org-parse-time-string te)))
3133 (time-to-seconds
3134 (apply 'encode-time (org-parse-time-string ts))))
3135 neg (< s 0)
3136 s (abs s)
3137 h (floor (/ s 3600))
3138 s (- s (* 3600 h))
3139 m (floor (/ s 60))
3140 s (- s (* 60 s)))
3141 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3142 t))))))
3144 (defun org-check-running-clock ()
3145 "Check if the current buffer contains the running clock.
3146 If yes, offer to stop it and to save the buffer with the changes."
3147 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3148 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3149 (buffer-name))))
3150 (org-clock-out)
3151 (when (y-or-n-p "Save changed buffer?")
3152 (save-buffer))))
3154 (defun org-clocktable-try-shift (dir n)
3155 "Check if this line starts a clock table, if yes, shift the time block."
3156 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3157 (org-clocktable-shift dir n)))
3159 ;; Autoload org-timer.el
3161 (eval-and-compile
3162 (org-autoload
3163 "org-timer"
3164 '(org-timer-start org-timer org-timer-item
3165 org-timer-change-times-in-region
3166 org-timer-set-timer
3167 org-timer-reset-timers
3168 org-timer-show-remaining-time)))
3170 ;; Autoload org-feed.el
3172 (eval-and-compile
3173 (org-autoload
3174 "org-feed"
3175 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3178 ;; Autoload org-indent.el
3180 (eval-and-compile
3181 (org-autoload
3182 "org-indent"
3183 '(org-indent-mode)))
3185 ;; Autoload archiving code
3186 ;; The stuff that is needed for cycling and tags has to be defined here.
3188 (defgroup org-archive nil
3189 "Options concerning archiving in Org-mode."
3190 :tag "Org Archive"
3191 :group 'org-structure)
3193 (defcustom org-archive-location "%s_archive::"
3194 "The location where subtrees should be archived.
3196 The value of this variable is a string, consisting of two parts,
3197 separated by a double-colon. The first part is a filename and
3198 the second part is a headline.
3200 When the filename is omitted, archiving happens in the same file.
3201 %s in the filename will be replaced by the current file
3202 name (without the directory part). Archiving to a different file
3203 is useful to keep archived entries from contributing to the
3204 Org-mode Agenda.
3206 The archived entries will be filed as subtrees of the specified
3207 headline. When the headline is omitted, the subtrees are simply
3208 filed away at the end of the file, as top-level entries. Also in
3209 the heading you can use %s to represent the file name, this can be
3210 useful when using the same archive for a number of different files.
3212 Here are a few examples:
3213 \"%s_archive::\"
3214 If the current file is Projects.org, archive in file
3215 Projects.org_archive, as top-level trees. This is the default.
3217 \"::* Archived Tasks\"
3218 Archive in the current file, under the top-level headline
3219 \"* Archived Tasks\".
3221 \"~/org/archive.org::\"
3222 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3224 \"~/org/archive.org::From %s\"
3225 Archive in file ~/org/archive.org (absolute path), und headlines
3226 \"From FILENAME\" where file name is the current file name.
3228 \"basement::** Finished Tasks\"
3229 Archive in file ./basement (relative path), as level 3 trees
3230 below the level 2 heading \"** Finished Tasks\".
3232 You may set this option on a per-file basis by adding to the buffer a
3233 line like
3235 #+ARCHIVE: basement::** Finished Tasks
3237 You may also define it locally for a subtree by setting an ARCHIVE property
3238 in the entry. If such a property is found in an entry, or anywhere up
3239 the hierarchy, it will be used."
3240 :group 'org-archive
3241 :type 'string)
3243 (defcustom org-archive-tag "ARCHIVE"
3244 "The tag that marks a subtree as archived.
3245 An archived subtree does not open during visibility cycling, and does
3246 not contribute to the agenda listings.
3247 After changing this, font-lock must be restarted in the relevant buffers to
3248 get the proper fontification."
3249 :group 'org-archive
3250 :group 'org-keywords
3251 :type 'string)
3253 (defcustom org-agenda-skip-archived-trees t
3254 "Non-nil means, the agenda will skip any items located in archived trees.
3255 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3256 variable is no longer recommended, you should leave it at the value t.
3257 Instead, use the key `v' to cycle the archives-mode in the agenda."
3258 :group 'org-archive
3259 :group 'org-agenda-skip
3260 :type 'boolean)
3262 (defcustom org-columns-skip-arrchived-trees t
3263 "Non-nil means, irgnore archived trees when creating column view."
3264 :group 'org-archive
3265 :group 'org-properties
3266 :type 'boolean)
3268 (defcustom org-cycle-open-archived-trees nil
3269 "Non-nil means, `org-cycle' will open archived trees.
3270 An archived tree is a tree marked with the tag ARCHIVE.
3271 When nil, archived trees will stay folded. You can still open them with
3272 normal outline commands like `show-all', but not with the cycling commands."
3273 :group 'org-archive
3274 :group 'org-cycle
3275 :type 'boolean)
3277 (defcustom org-sparse-tree-open-archived-trees nil
3278 "Non-nil means sparse tree construction shows matches in archived trees.
3279 When nil, matches in these trees are highlighted, but the trees are kept in
3280 collapsed state."
3281 :group 'org-archive
3282 :group 'org-sparse-trees
3283 :type 'boolean)
3285 (defun org-cycle-hide-archived-subtrees (state)
3286 "Re-hide all archived subtrees after a visibility state change."
3287 (when (and (not org-cycle-open-archived-trees)
3288 (not (memq state '(overview folded))))
3289 (save-excursion
3290 (let* ((globalp (memq state '(contents all)))
3291 (beg (if globalp (point-min) (point)))
3292 (end (if globalp (point-max) (org-end-of-subtree t))))
3293 (org-hide-archived-subtrees beg end)
3294 (goto-char beg)
3295 (if (looking-at (concat ".*:" org-archive-tag ":"))
3296 (message "%s" (substitute-command-keys
3297 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3299 (defun org-force-cycle-archived ()
3300 "Cycle subtree even if it is archived."
3301 (interactive)
3302 (setq this-command 'org-cycle)
3303 (let ((org-cycle-open-archived-trees t))
3304 (call-interactively 'org-cycle)))
3306 (defun org-hide-archived-subtrees (beg end)
3307 "Re-hide all archived subtrees after a visibility state change."
3308 (save-excursion
3309 (let* ((re (concat ":" org-archive-tag ":")))
3310 (goto-char beg)
3311 (while (re-search-forward re end t)
3312 (and (org-on-heading-p) (hide-subtree))
3313 (org-end-of-subtree t)))))
3315 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3317 (eval-and-compile
3318 (org-autoload "org-archive"
3319 '(org-add-archive-files org-archive-subtree
3320 org-archive-to-archive-sibling org-toggle-archive-tag)))
3322 ;; Autoload Column View Code
3324 (declare-function org-columns-number-to-string "org-colview")
3325 (declare-function org-columns-get-format-and-top-level "org-colview")
3326 (declare-function org-columns-compute "org-colview")
3328 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3329 '(org-columns-number-to-string org-columns-get-format-and-top-level
3330 org-columns-compute org-agenda-columns org-columns-remove-overlays
3331 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3333 ;; Autoload ID code
3335 (declare-function org-id-store-link "org-id")
3336 (declare-function org-id-locations-load "org-id")
3337 (declare-function org-id-locations-save "org-id")
3338 (defvar org-id-track-globally)
3339 (org-autoload "org-id"
3340 '(org-id-get-create org-id-new org-id-copy org-id-get
3341 org-id-get-with-outline-path-completion
3342 org-id-get-with-outline-drilling
3343 org-id-goto org-id-find org-id-store-link))
3345 ;; Autoload Plotting Code
3347 (org-autoload "org-plot"
3348 '(org-plot/gnuplot))
3350 ;;; Variables for pre-computed regular expressions, all buffer local
3352 (defvar org-drawer-regexp nil
3353 "Matches first line of a hidden block.")
3354 (make-variable-buffer-local 'org-drawer-regexp)
3355 (defvar org-todo-regexp nil
3356 "Matches any of the TODO state keywords.")
3357 (make-variable-buffer-local 'org-todo-regexp)
3358 (defvar org-not-done-regexp nil
3359 "Matches any of the TODO state keywords except the last one.")
3360 (make-variable-buffer-local 'org-not-done-regexp)
3361 (defvar org-not-done-heading-regexp nil
3362 "Matches a TODO headline that is not done.")
3363 (make-variable-buffer-local 'org-not-done-regexp)
3364 (defvar org-todo-line-regexp nil
3365 "Matches a headline and puts TODO state into group 2 if present.")
3366 (make-variable-buffer-local 'org-todo-line-regexp)
3367 (defvar org-complex-heading-regexp nil
3368 "Matches a headline and puts everything into groups:
3369 group 1: the stars
3370 group 2: The todo keyword, maybe
3371 group 3: Priority cookie
3372 group 4: True headline
3373 group 5: Tags")
3374 (make-variable-buffer-local 'org-complex-heading-regexp)
3375 (defvar org-todo-line-tags-regexp nil
3376 "Matches a headline and puts TODO state into group 2 if present.
3377 Also put tags into group 4 if tags are present.")
3378 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3379 (defvar org-nl-done-regexp nil
3380 "Matches newline followed by a headline with the DONE keyword.")
3381 (make-variable-buffer-local 'org-nl-done-regexp)
3382 (defvar org-looking-at-done-regexp nil
3383 "Matches the DONE keyword a point.")
3384 (make-variable-buffer-local 'org-looking-at-done-regexp)
3385 (defvar org-ds-keyword-length 12
3386 "Maximum length of the Deadline and SCHEDULED keywords.")
3387 (make-variable-buffer-local 'org-ds-keyword-length)
3388 (defvar org-deadline-regexp nil
3389 "Matches the DEADLINE keyword.")
3390 (make-variable-buffer-local 'org-deadline-regexp)
3391 (defvar org-deadline-time-regexp nil
3392 "Matches the DEADLINE keyword together with a time stamp.")
3393 (make-variable-buffer-local 'org-deadline-time-regexp)
3394 (defvar org-deadline-line-regexp nil
3395 "Matches the DEADLINE keyword and the rest of the line.")
3396 (make-variable-buffer-local 'org-deadline-line-regexp)
3397 (defvar org-scheduled-regexp nil
3398 "Matches the SCHEDULED keyword.")
3399 (make-variable-buffer-local 'org-scheduled-regexp)
3400 (defvar org-scheduled-time-regexp nil
3401 "Matches the SCHEDULED keyword together with a time stamp.")
3402 (make-variable-buffer-local 'org-scheduled-time-regexp)
3403 (defvar org-closed-time-regexp nil
3404 "Matches the CLOSED keyword together with a time stamp.")
3405 (make-variable-buffer-local 'org-closed-time-regexp)
3407 (defvar org-keyword-time-regexp nil
3408 "Matches any of the 4 keywords, together with the time stamp.")
3409 (make-variable-buffer-local 'org-keyword-time-regexp)
3410 (defvar org-keyword-time-not-clock-regexp nil
3411 "Matches any of the 3 keywords, together with the time stamp.")
3412 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3413 (defvar org-maybe-keyword-time-regexp nil
3414 "Matches a timestamp, possibly preceeded by a keyword.")
3415 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3416 (defvar org-planning-or-clock-line-re nil
3417 "Matches a line with planning or clock info.")
3418 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3420 (defconst org-plain-time-of-day-regexp
3421 (concat
3422 "\\(\\<[012]?[0-9]"
3423 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3424 "\\(--?"
3425 "\\(\\<[012]?[0-9]"
3426 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3427 "\\)?")
3428 "Regular expression to match a plain time or time range.
3429 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3430 groups carry important information:
3431 0 the full match
3432 1 the first time, range or not
3433 8 the second time, if it is a range.")
3435 (defconst org-plain-time-extension-regexp
3436 (concat
3437 "\\(\\<[012]?[0-9]"
3438 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3439 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3440 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3441 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3442 groups carry important information:
3443 0 the full match
3444 7 hours of duration
3445 9 minutes of duration")
3447 (defconst org-stamp-time-of-day-regexp
3448 (concat
3449 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3450 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3451 "\\(--?"
3452 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3453 "Regular expression to match a timestamp time or time range.
3454 After a match, the following groups carry important information:
3455 0 the full match
3456 1 date plus weekday, for backreferencing to make sure both times on same day
3457 2 the first time, range or not
3458 4 the second time, if it is a range.")
3460 (defconst org-startup-options
3461 '(("fold" org-startup-folded t)
3462 ("overview" org-startup-folded t)
3463 ("nofold" org-startup-folded nil)
3464 ("showall" org-startup-folded nil)
3465 ("content" org-startup-folded content)
3466 ("indent" org-startup-indented t)
3467 ("noindent" org-startup-indented nil)
3468 ("hidestars" org-hide-leading-stars t)
3469 ("showstars" org-hide-leading-stars nil)
3470 ("odd" org-odd-levels-only t)
3471 ("oddeven" org-odd-levels-only nil)
3472 ("align" org-startup-align-all-tables t)
3473 ("noalign" org-startup-align-all-tables nil)
3474 ("customtime" org-display-custom-times t)
3475 ("logdone" org-log-done time)
3476 ("lognotedone" org-log-done note)
3477 ("nologdone" org-log-done nil)
3478 ("lognoteclock-out" org-log-note-clock-out t)
3479 ("nolognoteclock-out" org-log-note-clock-out nil)
3480 ("logrepeat" org-log-repeat state)
3481 ("lognoterepeat" org-log-repeat note)
3482 ("nologrepeat" org-log-repeat nil)
3483 ("fninline" org-footnote-define-inline t)
3484 ("nofninline" org-footnote-define-inline nil)
3485 ("fnlocal" org-footnote-section nil)
3486 ("fnauto" org-footnote-auto-label t)
3487 ("fnprompt" org-footnote-auto-label nil)
3488 ("fnconfirm" org-footnote-auto-label confirm)
3489 ("fnplain" org-footnote-auto-label plain)
3490 ("fnadjust" org-footnote-auto-adjust t)
3491 ("nofnadjust" org-footnote-auto-adjust nil)
3492 ("constcgs" constants-unit-system cgs)
3493 ("constSI" constants-unit-system SI)
3494 ("noptag" org-tag-persistent-alist nil)
3495 ("hideblocks" org-hide-block-startup t)
3496 ("nohideblocks" org-hide-block-startup nil))
3497 "Variable associated with STARTUP options for org-mode.
3498 Each element is a list of three items: The startup options as written
3499 in the #+STARTUP line, the corresponding variable, and the value to
3500 set this variable to if the option is found. An optional forth element PUSH
3501 means to push this value onto the list in the variable.")
3503 (defun org-set-regexps-and-options ()
3504 "Precompute regular expressions for current buffer."
3505 (when (org-mode-p)
3506 (org-set-local 'org-todo-kwd-alist nil)
3507 (org-set-local 'org-todo-key-alist nil)
3508 (org-set-local 'org-todo-key-trigger nil)
3509 (org-set-local 'org-todo-keywords-1 nil)
3510 (org-set-local 'org-done-keywords nil)
3511 (org-set-local 'org-todo-heads nil)
3512 (org-set-local 'org-todo-sets nil)
3513 (org-set-local 'org-todo-log-states nil)
3514 (org-set-local 'org-file-properties nil)
3515 (org-set-local 'org-file-tags nil)
3516 (let ((re (org-make-options-regexp
3517 '("CATEGORY" "TODO" "COLUMNS"
3518 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3519 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3520 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3521 (splitre "[ \t]+")
3522 kwds kws0 kwsa key log value cat arch tags const links hw dws
3523 tail sep kws1 prio props ftags drawers
3524 ext-setup-or-nil setup-contents (start 0))
3525 (save-excursion
3526 (save-restriction
3527 (widen)
3528 (goto-char (point-min))
3529 (while (or (and ext-setup-or-nil
3530 (string-match re ext-setup-or-nil start)
3531 (setq start (match-end 0)))
3532 (and (setq ext-setup-or-nil nil start 0)
3533 (re-search-forward re nil t)))
3534 (setq key (upcase (match-string 1 ext-setup-or-nil))
3535 value (org-match-string-no-properties 2 ext-setup-or-nil))
3536 (cond
3537 ((equal key "CATEGORY")
3538 (if (string-match "[ \t]+$" value)
3539 (setq value (replace-match "" t t value)))
3540 (setq cat value))
3541 ((member key '("SEQ_TODO" "TODO"))
3542 (push (cons 'sequence (org-split-string value splitre)) kwds))
3543 ((equal key "TYP_TODO")
3544 (push (cons 'type (org-split-string value splitre)) kwds))
3545 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3546 ;; general TODO-like setup
3547 (push (cons (intern (downcase (match-string 1 key)))
3548 (org-split-string value splitre)) kwds))
3549 ((equal key "TAGS")
3550 (setq tags (append tags (if tags '("\\n") nil)
3551 (org-split-string value splitre))))
3552 ((equal key "COLUMNS")
3553 (org-set-local 'org-columns-default-format value))
3554 ((equal key "LINK")
3555 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3556 (push (cons (match-string 1 value)
3557 (org-trim (match-string 2 value)))
3558 links)))
3559 ((equal key "PRIORITIES")
3560 (setq prio (org-split-string value " +")))
3561 ((equal key "PROPERTY")
3562 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3563 (push (cons (match-string 1 value) (match-string 2 value))
3564 props)))
3565 ((equal key "FILETAGS")
3566 (when (string-match "\\S-" value)
3567 (setq ftags
3568 (append
3569 ftags
3570 (apply 'append
3571 (mapcar (lambda (x) (org-split-string x ":"))
3572 (org-split-string value)))))))
3573 ((equal key "DRAWERS")
3574 (setq drawers (org-split-string value splitre)))
3575 ((equal key "CONSTANTS")
3576 (setq const (append const (org-split-string value splitre))))
3577 ((equal key "STARTUP")
3578 (let ((opts (org-split-string value splitre))
3579 l var val)
3580 (while (setq l (pop opts))
3581 (when (setq l (assoc l org-startup-options))
3582 (setq var (nth 1 l) val (nth 2 l))
3583 (if (not (nth 3 l))
3584 (set (make-local-variable var) val)
3585 (if (not (listp (symbol-value var)))
3586 (set (make-local-variable var) nil))
3587 (set (make-local-variable var) (symbol-value var))
3588 (add-to-list var val))))))
3589 ((equal key "ARCHIVE")
3590 (string-match " *$" value)
3591 (setq arch (replace-match "" t t value))
3592 (remove-text-properties 0 (length arch)
3593 '(face t fontified t) arch))
3594 ((equal key "SETUPFILE")
3595 (setq setup-contents (org-file-contents
3596 (expand-file-name
3597 (org-remove-double-quotes value))
3598 'noerror))
3599 (if (not ext-setup-or-nil)
3600 (setq ext-setup-or-nil setup-contents start 0)
3601 (setq ext-setup-or-nil
3602 (concat (substring ext-setup-or-nil 0 start)
3603 "\n" setup-contents "\n"
3604 (substring ext-setup-or-nil start)))))
3605 ))))
3606 (when cat
3607 (org-set-local 'org-category (intern cat))
3608 (push (cons "CATEGORY" cat) props))
3609 (when prio
3610 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3611 (setq prio (mapcar 'string-to-char prio))
3612 (org-set-local 'org-highest-priority (nth 0 prio))
3613 (org-set-local 'org-lowest-priority (nth 1 prio))
3614 (org-set-local 'org-default-priority (nth 2 prio)))
3615 (and props (org-set-local 'org-file-properties (nreverse props)))
3616 (and ftags (org-set-local 'org-file-tags
3617 (mapcar 'org-add-prop-inherited ftags)))
3618 (and drawers (org-set-local 'org-drawers drawers))
3619 (and arch (org-set-local 'org-archive-location arch))
3620 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3621 ;; Process the TODO keywords
3622 (unless kwds
3623 ;; Use the global values as if they had been given locally.
3624 (setq kwds (default-value 'org-todo-keywords))
3625 (if (stringp (car kwds))
3626 (setq kwds (list (cons org-todo-interpretation
3627 (default-value 'org-todo-keywords)))))
3628 (setq kwds (reverse kwds)))
3629 (setq kwds (nreverse kwds))
3630 (let (inter kws kw)
3631 (while (setq kws (pop kwds))
3632 (let ((kws (or
3633 (run-hook-with-args-until-success
3634 'org-todo-setup-filter-hook kws)
3635 kws)))
3636 (setq inter (pop kws) sep (member "|" kws)
3637 kws0 (delete "|" (copy-sequence kws))
3638 kwsa nil
3639 kws1 (mapcar
3640 (lambda (x)
3641 ;; 1 2
3642 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3643 (progn
3644 (setq kw (match-string 1 x)
3645 key (and (match-end 2) (match-string 2 x))
3646 log (org-extract-log-state-settings x))
3647 (push (cons kw (and key (string-to-char key))) kwsa)
3648 (and log (push log org-todo-log-states))
3650 (error "Invalid TODO keyword %s" x)))
3651 kws0)
3652 kwsa (if kwsa (append '((:startgroup))
3653 (nreverse kwsa)
3654 '((:endgroup))))
3655 hw (car kws1)
3656 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3657 tail (list inter hw (car dws) (org-last dws))))
3658 (add-to-list 'org-todo-heads hw 'append)
3659 (push kws1 org-todo-sets)
3660 (setq org-done-keywords (append org-done-keywords dws nil))
3661 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3662 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3663 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3664 (setq org-todo-sets (nreverse org-todo-sets)
3665 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3666 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3667 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3668 ;; Process the constants
3669 (when const
3670 (let (e cst)
3671 (while (setq e (pop const))
3672 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3673 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3674 (setq org-table-formula-constants-local cst)))
3676 ;; Process the tags.
3677 (when tags
3678 (let (e tgs)
3679 (while (setq e (pop tags))
3680 (cond
3681 ((equal e "{") (push '(:startgroup) tgs))
3682 ((equal e "}") (push '(:endgroup) tgs))
3683 ((equal e "\\n") (push '(:newline) tgs))
3684 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3685 (push (cons (match-string 1 e)
3686 (string-to-char (match-string 2 e)))
3687 tgs))
3688 (t (push (list e) tgs))))
3689 (org-set-local 'org-tag-alist nil)
3690 (while (setq e (pop tgs))
3691 (or (and (stringp (car e))
3692 (assoc (car e) org-tag-alist))
3693 (push e org-tag-alist)))))
3695 ;; Compute the regular expressions and other local variables
3696 (if (not org-done-keywords)
3697 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3698 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3699 (length org-scheduled-string)
3700 (length org-clock-string)
3701 (length org-closed-string)))
3702 org-drawer-regexp
3703 (concat "^[ \t]*:\\("
3704 (mapconcat 'regexp-quote org-drawers "\\|")
3705 "\\):[ \t]*$")
3706 org-not-done-keywords
3707 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3708 org-todo-regexp
3709 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3710 "\\|") "\\)\\>")
3711 org-not-done-regexp
3712 (concat "\\<\\("
3713 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3714 "\\)\\>")
3715 org-not-done-heading-regexp
3716 (concat "^\\(\\*+\\)[ \t]+\\("
3717 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3718 "\\)\\>")
3719 org-todo-line-regexp
3720 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3721 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3722 "\\)\\>\\)?[ \t]*\\(.*\\)")
3723 org-complex-heading-regexp
3724 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3725 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3726 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3727 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3728 org-nl-done-regexp
3729 (concat "\n\\*+[ \t]+"
3730 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3731 "\\)" "\\>")
3732 org-todo-line-tags-regexp
3733 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3734 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3735 (org-re
3736 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3737 org-looking-at-done-regexp
3738 (concat "^" "\\(?:"
3739 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3740 "\\>")
3741 org-deadline-regexp (concat "\\<" org-deadline-string)
3742 org-deadline-time-regexp
3743 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3744 org-deadline-line-regexp
3745 (concat "\\<\\(" org-deadline-string "\\).*")
3746 org-scheduled-regexp
3747 (concat "\\<" org-scheduled-string)
3748 org-scheduled-time-regexp
3749 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3750 org-closed-time-regexp
3751 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3752 org-keyword-time-regexp
3753 (concat "\\<\\(" org-scheduled-string
3754 "\\|" org-deadline-string
3755 "\\|" org-closed-string
3756 "\\|" org-clock-string "\\)"
3757 " *[[<]\\([^]>]+\\)[]>]")
3758 org-keyword-time-not-clock-regexp
3759 (concat "\\<\\(" org-scheduled-string
3760 "\\|" org-deadline-string
3761 "\\|" org-closed-string
3762 "\\)"
3763 " *[[<]\\([^]>]+\\)[]>]")
3764 org-maybe-keyword-time-regexp
3765 (concat "\\(\\<\\(" org-scheduled-string
3766 "\\|" org-deadline-string
3767 "\\|" org-closed-string
3768 "\\|" org-clock-string "\\)\\)?"
3769 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3770 org-planning-or-clock-line-re
3771 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3772 "\\|" org-deadline-string
3773 "\\|" org-closed-string "\\|" org-clock-string
3774 "\\)\\>\\)")
3776 (org-compute-latex-and-specials-regexp)
3777 (org-set-font-lock-defaults))))
3779 (defun org-file-contents (file &optional noerror)
3780 "Return the contents of FILE, as a string."
3781 (if (or (not file)
3782 (not (file-readable-p file)))
3783 (if noerror
3784 (progn
3785 (message "Cannot read file %s" file)
3786 (ding) (sit-for 2)
3788 (error "Cannot read file %s" file))
3789 (with-temp-buffer
3790 (insert-file-contents file)
3791 (buffer-string))))
3793 (defun org-extract-log-state-settings (x)
3794 "Extract the log state setting from a TODO keyword string.
3795 This will extract info from a string like \"WAIT(w@/!)\"."
3796 (let (kw key log1 log2)
3797 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3798 (setq kw (match-string 1 x)
3799 key (and (match-end 2) (match-string 2 x))
3800 log1 (and (match-end 3) (match-string 3 x))
3801 log2 (and (match-end 4) (match-string 4 x)))
3802 (and (or log1 log2)
3803 (list kw
3804 (and log1 (if (equal log1 "!") 'time 'note))
3805 (and log2 (if (equal log2 "!") 'time 'note)))))))
3807 (defun org-remove-keyword-keys (list)
3808 "Remove a pair of parenthesis at the end of each string in LIST."
3809 (mapcar (lambda (x)
3810 (if (string-match "(.*)$" x)
3811 (substring x 0 (match-beginning 0))
3813 list))
3815 ;; FIXME: this could be done much better, using second characters etc.
3816 (defun org-assign-fast-keys (alist)
3817 "Assign fast keys to a keyword-key alist.
3818 Respect keys that are already there."
3819 (let (new e k c c1 c2 (char ?a))
3820 (while (setq e (pop alist))
3821 (cond
3822 ((equal e '(:startgroup)) (push e new))
3823 ((equal e '(:endgroup)) (push e new))
3824 ((equal e '(:newline)) (push e new))
3826 (setq k (car e) c2 nil)
3827 (if (cdr e)
3828 (setq c (cdr e))
3829 ;; automatically assign a character.
3830 (setq c1 (string-to-char
3831 (downcase (substring
3832 k (if (= (string-to-char k) ?@) 1 0)))))
3833 (if (or (rassoc c1 new) (rassoc c1 alist))
3834 (while (or (rassoc char new) (rassoc char alist))
3835 (setq char (1+ char)))
3836 (setq c2 c1))
3837 (setq c (or c2 char)))
3838 (push (cons k c) new))))
3839 (nreverse new)))
3841 ;;; Some variables used in various places
3843 (defvar org-window-configuration nil
3844 "Used in various places to store a window configuration.")
3845 (defvar org-finish-function nil
3846 "Function to be called when `C-c C-c' is used.
3847 This is for getting out of special buffers like remember.")
3850 ;; FIXME: Occasionally check by commenting these, to make sure
3851 ;; no other functions uses these, forgetting to let-bind them.
3852 (defvar entry)
3853 (defvar last-state)
3854 (defvar date)
3856 ;; Defined somewhere in this file, but used before definition.
3857 (defvar org-html-entities)
3858 (defvar org-struct-menu)
3859 (defvar org-org-menu)
3860 (defvar org-tbl-menu)
3861 (defvar org-agenda-keymap)
3863 ;;;; Define the Org-mode
3865 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3866 (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."))
3869 ;; We use a before-change function to check if a table might need
3870 ;; an update.
3871 (defvar org-table-may-need-update t
3872 "Indicates that a table might need an update.
3873 This variable is set by `org-before-change-function'.
3874 `org-table-align' sets it back to nil.")
3875 (defun org-before-change-function (beg end)
3876 "Every change indicates that a table might need an update."
3877 (setq org-table-may-need-update t))
3878 (defvar org-mode-map)
3879 (defvar org-mode-hook nil
3880 "Mode hook for Org-mode, run after the mode was turned on.")
3881 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3882 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3883 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
3884 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
3885 (defvar org-table-buffer-is-an nil)
3886 (defconst org-outline-regexp "\\*+ ")
3888 ;;;###autoload
3889 (define-derived-mode org-mode outline-mode "Org"
3890 "Outline-based notes management and organizer, alias
3891 \"Carsten's outline-mode for keeping track of everything.\"
3893 Org-mode develops organizational tasks around a NOTES file which
3894 contains information about projects as plain text. Org-mode is
3895 implemented on top of outline-mode, which is ideal to keep the content
3896 of large files well structured. It supports ToDo items, deadlines and
3897 time stamps, which magically appear in the diary listing of the Emacs
3898 calendar. Tables are easily created with a built-in table editor.
3899 Plain text URL-like links connect to websites, emails (VM), Usenet
3900 messages (Gnus), BBDB entries, and any files related to the project.
3901 For printing and sharing of notes, an Org-mode file (or a part of it)
3902 can be exported as a structured ASCII or HTML file.
3904 The following commands are available:
3906 \\{org-mode-map}"
3908 ;; Get rid of Outline menus, they are not needed
3909 ;; Need to do this here because define-derived-mode sets up
3910 ;; the keymap so late. Still, it is a waste to call this each time
3911 ;; we switch another buffer into org-mode.
3912 (if (featurep 'xemacs)
3913 (when (boundp 'outline-mode-menu-heading)
3914 ;; Assume this is Greg's port, it used easymenu
3915 (easy-menu-remove outline-mode-menu-heading)
3916 (easy-menu-remove outline-mode-menu-show)
3917 (easy-menu-remove outline-mode-menu-hide))
3918 (define-key org-mode-map [menu-bar headings] 'undefined)
3919 (define-key org-mode-map [menu-bar hide] 'undefined)
3920 (define-key org-mode-map [menu-bar show] 'undefined))
3922 (org-load-modules-maybe)
3923 (easy-menu-add org-org-menu)
3924 (easy-menu-add org-tbl-menu)
3925 (org-install-agenda-files-menu)
3926 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3927 (org-add-to-invisibility-spec '(org-cwidth))
3928 (org-add-to-invisibility-spec '(org-hide-block . t))
3929 (when (featurep 'xemacs)
3930 (org-set-local 'line-move-ignore-invisible t))
3931 (org-set-local 'outline-regexp org-outline-regexp)
3932 (org-set-local 'outline-level 'org-outline-level)
3933 (when (and org-ellipsis
3934 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3935 (fboundp 'make-glyph-code))
3936 (unless org-display-table
3937 (setq org-display-table (make-display-table)))
3938 (set-display-table-slot
3939 org-display-table 4
3940 (vconcat (mapcar
3941 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3942 org-ellipsis)))
3943 (if (stringp org-ellipsis) org-ellipsis "..."))))
3944 (setq buffer-display-table org-display-table))
3945 (org-set-regexps-and-options)
3946 (when (and org-tag-faces (not org-tags-special-faces-re))
3947 ;; tag faces set outside customize.... force initialization.
3948 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3949 ;; Calc embedded
3950 (org-set-local 'calc-embedded-open-mode "# ")
3951 (modify-syntax-entry ?# "<")
3952 (modify-syntax-entry ?@ "w")
3953 (if org-startup-truncated (setq truncate-lines t))
3954 (org-set-local 'font-lock-unfontify-region-function
3955 'org-unfontify-region)
3956 ;; Activate before-change-function
3957 (org-set-local 'org-table-may-need-update t)
3958 (org-add-hook 'before-change-functions 'org-before-change-function nil
3959 'local)
3960 ;; Check for running clock before killing a buffer
3961 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3962 ;; Paragraphs and auto-filling
3963 (org-set-autofill-regexps)
3964 (setq indent-line-function 'org-indent-line-function)
3965 (org-update-radio-target-regexp)
3966 ;; Make sure dependence stuff works reliably, even for users who set it
3967 ;; too late :-(
3968 (if org-enforce-todo-dependencies
3969 (add-hook 'org-blocker-hook
3970 'org-block-todo-from-children-or-siblings-or-parent)
3971 (remove-hook 'org-blocker-hook
3972 'org-block-todo-from-children-or-siblings-or-parent))
3973 (if org-enforce-todo-checkbox-dependencies
3974 (add-hook 'org-blocker-hook
3975 'org-block-todo-from-checkboxes)
3976 (remove-hook 'org-blocker-hook
3977 'org-block-todo-from-checkboxes))
3979 ;; Comment characters
3980 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3981 (org-set-local 'comment-padding " ")
3983 ;; Align options lines
3984 (org-set-local
3985 'align-mode-rules-list
3986 '((org-in-buffer-settings
3987 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3988 (modes . '(org-mode)))))
3990 ;; Imenu
3991 (org-set-local 'imenu-create-index-function
3992 'org-imenu-get-tree)
3994 ;; Make isearch reveal context
3995 (if (or (featurep 'xemacs)
3996 (not (boundp 'outline-isearch-open-invisible-function)))
3997 ;; Emacs 21 and XEmacs make use of the hook
3998 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3999 ;; Emacs 22 deals with this through a special variable
4000 (org-set-local 'outline-isearch-open-invisible-function
4001 (lambda (&rest ignore) (org-show-context 'isearch))))
4003 ;; If empty file that did not turn on org-mode automatically, make it to.
4004 (if (and org-insert-mode-line-in-empty-file
4005 (interactive-p)
4006 (= (point-min) (point-max)))
4007 (insert "# -*- mode: org -*-\n\n"))
4009 (unless org-inhibit-startup
4010 (when org-startup-align-all-tables
4011 (let ((bmp (buffer-modified-p)))
4012 (org-table-map-tables 'org-table-align)
4013 (set-buffer-modified-p bmp)))
4014 (when org-startup-indented
4015 (require 'org-indent)
4016 (org-indent-mode 1))
4017 (org-set-startup-visibility)))
4019 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4021 (defun org-current-time ()
4022 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4023 (if (> (car org-time-stamp-rounding-minutes) 1)
4024 (let ((r (car org-time-stamp-rounding-minutes))
4025 (time (decode-time)))
4026 (apply 'encode-time
4027 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4028 (nthcdr 2 time))))
4029 (current-time)))
4031 ;;;; Font-Lock stuff, including the activators
4033 (defvar org-mouse-map (make-sparse-keymap))
4034 (org-defkey org-mouse-map
4035 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4036 (org-defkey org-mouse-map
4037 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4038 (when org-mouse-1-follows-link
4039 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4040 (when org-tab-follows-link
4041 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4042 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4044 (require 'font-lock)
4046 (defconst org-non-link-chars "]\t\n\r<>")
4047 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4048 "shell" "elisp"))
4049 (defvar org-link-types-re nil
4050 "Matches a link that has a url-like prefix like \"http:\"")
4051 (defvar org-link-re-with-space nil
4052 "Matches a link with spaces, optional angular brackets around it.")
4053 (defvar org-link-re-with-space2 nil
4054 "Matches a link with spaces, optional angular brackets around it.")
4055 (defvar org-link-re-with-space3 nil
4056 "Matches a link with spaces, only for internal part in bracket links.")
4057 (defvar org-angle-link-re nil
4058 "Matches link with angular brackets, spaces are allowed.")
4059 (defvar org-plain-link-re nil
4060 "Matches plain link, without spaces.")
4061 (defvar org-bracket-link-regexp nil
4062 "Matches a link in double brackets.")
4063 (defvar org-bracket-link-analytic-regexp nil
4064 "Regular expression used to analyze links.
4065 Here is what the match groups contain after a match:
4066 1: http:
4067 2: http
4068 3: path
4069 4: [desc]
4070 5: desc")
4071 (defvar org-bracket-link-analytic-regexp++ nil
4072 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4073 (defvar org-any-link-re nil
4074 "Regular expression matching any link.")
4076 (defun org-make-link-regexps ()
4077 "Update the link regular expressions.
4078 This should be called after the variable `org-link-types' has changed."
4079 (setq org-link-types-re
4080 (concat
4081 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
4082 org-link-re-with-space
4083 (concat
4084 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4085 "\\([^" org-non-link-chars " ]"
4086 "[^" org-non-link-chars "]*"
4087 "[^" org-non-link-chars " ]\\)>?")
4088 org-link-re-with-space2
4089 (concat
4090 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4091 "\\([^" org-non-link-chars " ]"
4092 "[^\t\n\r]*"
4093 "[^" org-non-link-chars " ]\\)>?")
4094 org-link-re-with-space3
4095 (concat
4096 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4097 "\\([^" org-non-link-chars " ]"
4098 "[^\t\n\r]*\\)")
4099 org-angle-link-re
4100 (concat
4101 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4102 "\\([^" org-non-link-chars " ]"
4103 "[^" org-non-link-chars "]*"
4104 "\\)>")
4105 org-plain-link-re
4106 (concat
4107 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4108 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4109 org-bracket-link-regexp
4110 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4111 org-bracket-link-analytic-regexp
4112 (concat
4113 "\\[\\["
4114 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4115 "\\([^]]+\\)"
4116 "\\]"
4117 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4118 "\\]")
4119 org-bracket-link-analytic-regexp++
4120 (concat
4121 "\\[\\["
4122 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4123 "\\([^]]+\\)"
4124 "\\]"
4125 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4126 "\\]")
4127 org-any-link-re
4128 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4129 org-angle-link-re "\\)\\|\\("
4130 org-plain-link-re "\\)")))
4132 (org-make-link-regexps)
4134 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4135 "Regular expression for fast time stamp matching.")
4136 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4137 "Regular expression for fast time stamp matching.")
4138 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4139 "Regular expression matching time strings for analysis.
4140 This one does not require the space after the date, so it can be used
4141 on a string that terminates immediately after the date.")
4142 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4143 "Regular expression matching time strings for analysis.")
4144 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4145 "Regular expression matching time stamps, with groups.")
4146 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4147 "Regular expression matching time stamps (also [..]), with groups.")
4148 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4149 "Regular expression matching a time stamp range.")
4150 (defconst org-tr-regexp-both
4151 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4152 "Regular expression matching a time stamp range.")
4153 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4154 org-ts-regexp "\\)?")
4155 "Regular expression matching a time stamp or time stamp range.")
4156 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4157 org-ts-regexp-both "\\)?")
4158 "Regular expression matching a time stamp or time stamp range.
4159 The time stamps may be either active or inactive.")
4161 (defvar org-emph-face nil)
4163 (defun org-do-emphasis-faces (limit)
4164 "Run through the buffer and add overlays to links."
4165 (let (rtn a)
4166 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4167 (if (not (= (char-after (match-beginning 3))
4168 (char-after (match-beginning 4))))
4169 (progn
4170 (setq rtn t)
4171 (setq a (assoc (match-string 3) org-emphasis-alist))
4172 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4173 'face
4174 (nth 1 a))
4175 (and (nth 4 a)
4176 (org-remove-flyspell-overlays-in
4177 (match-beginning 0) (match-end 0)))
4178 (add-text-properties (match-beginning 2) (match-end 2)
4179 '(font-lock-multiline t))
4180 (when org-hide-emphasis-markers
4181 (add-text-properties (match-end 4) (match-beginning 5)
4182 '(invisible org-link))
4183 (add-text-properties (match-beginning 3) (match-end 3)
4184 '(invisible org-link)))))
4185 (backward-char 1))
4186 rtn))
4188 (defun org-emphasize (&optional char)
4189 "Insert or change an emphasis, i.e. a font like bold or italic.
4190 If there is an active region, change that region to a new emphasis.
4191 If there is no region, just insert the marker characters and position
4192 the cursor between them.
4193 CHAR should be either the marker character, or the first character of the
4194 HTML tag associated with that emphasis. If CHAR is a space, the means
4195 to remove the emphasis of the selected region.
4196 If char is not given (for example in an interactive call) it
4197 will be prompted for."
4198 (interactive)
4199 (let ((eal org-emphasis-alist) e det
4200 (erc org-emphasis-regexp-components)
4201 (prompt "")
4202 (string "") beg end move tag c s)
4203 (if (org-region-active-p)
4204 (setq beg (region-beginning) end (region-end)
4205 string (buffer-substring beg end))
4206 (setq move t))
4208 (while (setq e (pop eal))
4209 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4210 c (aref tag 0))
4211 (push (cons c (string-to-char (car e))) det)
4212 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4213 (substring tag 1)))))
4214 (setq det (nreverse det))
4215 (unless char
4216 (message "%s" (concat "Emphasis marker or tag:" prompt))
4217 (setq char (read-char-exclusive)))
4218 (setq char (or (cdr (assoc char det)) char))
4219 (if (equal char ?\ )
4220 (setq s "" move nil)
4221 (unless (assoc (char-to-string char) org-emphasis-alist)
4222 (error "No such emphasis marker: \"%c\"" char))
4223 (setq s (char-to-string char)))
4224 (while (and (> (length string) 1)
4225 (equal (substring string 0 1) (substring string -1))
4226 (assoc (substring string 0 1) org-emphasis-alist))
4227 (setq string (substring string 1 -1)))
4228 (setq string (concat s string s))
4229 (if beg (delete-region beg end))
4230 (unless (or (bolp)
4231 (string-match (concat "[" (nth 0 erc) "\n]")
4232 (char-to-string (char-before (point)))))
4233 (insert " "))
4234 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4235 (char-to-string (char-after (point))))
4236 (insert " ") (backward-char 1))
4237 (insert string)
4238 (and move (backward-char 1))))
4240 (defconst org-nonsticky-props
4241 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4243 (defsubst org-rear-nonsticky-at (pos)
4244 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4246 (defun org-activate-plain-links (limit)
4247 "Run through the buffer and add overlays to links."
4248 (catch 'exit
4249 (let (f)
4250 (if (re-search-forward org-plain-link-re limit t)
4251 (progn
4252 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4253 (setq f (get-text-property (match-beginning 0) 'face))
4254 (if (or (eq f 'org-tag)
4255 (and (listp f) (memq 'org-tag f)))
4257 (add-text-properties (match-beginning 0) (match-end 0)
4258 (list 'mouse-face 'highlight
4259 'keymap org-mouse-map))
4260 (org-rear-nonsticky-at (match-end 0)))
4261 t)))))
4263 (defun org-activate-code (limit)
4264 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4265 (progn
4266 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4267 (remove-text-properties (match-beginning 0) (match-end 0)
4268 '(display t invisible t intangible t))
4269 t)))
4271 (defun org-fontify-meta-lines-and-blocks (limit)
4272 "Fontify #+ lines and blocks, in the correct ways."
4273 (let ((case-fold-search t))
4274 (if (re-search-forward
4275 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4276 limit t)
4277 (let ((beg (match-beginning 0))
4278 (beg1 (line-beginning-position 2))
4279 (dc1 (downcase (match-string 2)))
4280 (dc3 (downcase (match-string 3)))
4281 end end1 quoting)
4282 (cond
4283 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4284 ;; a single line of backend-specific content
4285 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4286 (remove-text-properties (match-beginning 0) (match-end 0)
4287 '(display t invisible t intangible t))
4288 (add-text-properties (match-beginning 1) (match-end 3)
4289 '(font-lock-fontified t face org-meta-line))
4290 (add-text-properties (match-beginning 6) (match-end 6)
4291 '(font-lock-fontified t face org-block))
4293 ((and (match-end 4) (equal dc3 "begin"))
4294 ;; Truely a block
4295 (setq quoting (member (downcase (match-string 5))
4296 org-protecting-blocks))
4297 (when (re-search-forward
4298 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4299 nil t) ;; on purpose, we look further than LIMIT
4300 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4301 (when quoting
4302 (remove-text-properties beg end
4303 '(display t invisible t intangible t)))
4304 (add-text-properties
4305 beg end
4306 '(font-lock-fontified t font-lock-multiline t))
4307 (add-text-properties beg beg1 '(face org-meta-line))
4308 (add-text-properties end1 end '(face org-meta-line))
4309 (when quoting
4310 (add-text-properties beg1 end1 '(face org-block)))
4312 ((not (member (char-after beg) '(?\ ?\t)))
4313 ;; just any other in-buffer setting, but not indented
4314 (add-text-properties
4315 beg (match-end 0)
4316 '(font-lock-fontified t face org-meta-line))
4318 ((or (member dc1 '("caption:" "label:" "orgtbl:" "tblfm:" "tblname:"))
4319 (and (match-end 4) (equal dc3 "attr")))
4320 (add-text-properties
4321 beg (match-end 0)
4322 '(font-lock-fontified t face org-meta-line))
4324 (t nil))))))
4326 (defun org-activate-angle-links (limit)
4327 "Run through the buffer and add overlays to links."
4328 (if (re-search-forward org-angle-link-re limit t)
4329 (progn
4330 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4331 (add-text-properties (match-beginning 0) (match-end 0)
4332 (list 'mouse-face 'highlight
4333 'keymap org-mouse-map))
4334 (org-rear-nonsticky-at (match-end 0))
4335 t)))
4337 (defun org-activate-footnote-links (limit)
4338 "Run through the buffer and add overlays to links."
4339 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4340 limit t)
4341 (progn
4342 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4343 (add-text-properties (match-beginning 2) (match-end 2)
4344 (list 'mouse-face 'highlight
4345 'keymap org-mouse-map
4346 'help-echo
4347 (if (= (point-at-bol) (match-beginning 2))
4348 "Footnote definition"
4349 "Footnote reference")
4351 (org-rear-nonsticky-at (match-end 2))
4352 t)))
4354 (defun org-activate-bracket-links (limit)
4355 "Run through the buffer and add overlays to bracketed links."
4356 (if (re-search-forward org-bracket-link-regexp limit t)
4357 (let* ((help (concat "LINK: "
4358 (org-match-string-no-properties 1)))
4359 ;; FIXME: above we should remove the escapes.
4360 ;; but that requires another match, protecting match data,
4361 ;; a lot of overhead for font-lock.
4362 (ip (org-maybe-intangible
4363 (list 'invisible 'org-link
4364 'keymap org-mouse-map 'mouse-face 'highlight
4365 'font-lock-multiline t 'help-echo help)))
4366 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4367 'font-lock-multiline t 'help-echo help)))
4368 ;; We need to remove the invisible property here. Table narrowing
4369 ;; may have made some of this invisible.
4370 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4371 (remove-text-properties (match-beginning 0) (match-end 0)
4372 '(invisible nil))
4373 (if (match-end 3)
4374 (progn
4375 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4376 (org-rear-nonsticky-at (match-beginning 3))
4377 (add-text-properties (match-beginning 3) (match-end 3) vp)
4378 (org-rear-nonsticky-at (match-end 3))
4379 (add-text-properties (match-end 3) (match-end 0) ip)
4380 (org-rear-nonsticky-at (match-end 0)))
4381 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4382 (org-rear-nonsticky-at (match-beginning 1))
4383 (add-text-properties (match-beginning 1) (match-end 1) vp)
4384 (org-rear-nonsticky-at (match-end 1))
4385 (add-text-properties (match-end 1) (match-end 0) ip)
4386 (org-rear-nonsticky-at (match-end 0)))
4387 t)))
4389 (defun org-activate-dates (limit)
4390 "Run through the buffer and add overlays to dates."
4391 (if (re-search-forward org-tsr-regexp-both limit t)
4392 (progn
4393 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4394 (add-text-properties (match-beginning 0) (match-end 0)
4395 (list 'mouse-face 'highlight
4396 'keymap org-mouse-map))
4397 (org-rear-nonsticky-at (match-end 0))
4398 (when org-display-custom-times
4399 (if (match-end 3)
4400 (org-display-custom-time (match-beginning 3) (match-end 3)))
4401 (org-display-custom-time (match-beginning 1) (match-end 1)))
4402 t)))
4404 (defvar org-target-link-regexp nil
4405 "Regular expression matching radio targets in plain text.")
4406 (make-variable-buffer-local 'org-target-link-regexp)
4407 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4408 "Regular expression matching a link target.")
4409 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4410 "Regular expression matching a radio target.")
4411 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4412 "Regular expression matching any target.")
4414 (defun org-activate-target-links (limit)
4415 "Run through the buffer and add overlays to target matches."
4416 (when org-target-link-regexp
4417 (let ((case-fold-search t))
4418 (if (re-search-forward org-target-link-regexp limit t)
4419 (progn
4420 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4421 (add-text-properties (match-beginning 0) (match-end 0)
4422 (list 'mouse-face 'highlight
4423 'keymap org-mouse-map
4424 'help-echo "Radio target link"
4425 'org-linked-text t))
4426 (org-rear-nonsticky-at (match-end 0))
4427 t)))))
4429 (defun org-update-radio-target-regexp ()
4430 "Find all radio targets in this file and update the regular expression."
4431 (interactive)
4432 (when (memq 'radio org-activate-links)
4433 (setq org-target-link-regexp
4434 (org-make-target-link-regexp (org-all-targets 'radio)))
4435 (org-restart-font-lock)))
4437 (defun org-hide-wide-columns (limit)
4438 (let (s e)
4439 (setq s (text-property-any (point) (or limit (point-max))
4440 'org-cwidth t))
4441 (when s
4442 (setq e (next-single-property-change s 'org-cwidth))
4443 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4444 (goto-char e)
4445 t)))
4447 (defvar org-latex-and-specials-regexp nil
4448 "Regular expression for highlighting export special stuff.")
4449 (defvar org-match-substring-regexp)
4450 (defvar org-match-substring-with-braces-regexp)
4451 (defvar org-export-html-special-string-regexps)
4453 (defun org-compute-latex-and-specials-regexp ()
4454 "Compute regular expression for stuff treated specially by exporters."
4455 (if (not org-highlight-latex-fragments-and-specials)
4456 (org-set-local 'org-latex-and-specials-regexp nil)
4457 (require 'org-exp)
4458 (let*
4459 ((matchers (plist-get org-format-latex-options :matchers))
4460 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4461 org-latex-regexps)))
4462 (options (org-combine-plists (org-default-export-plist)
4463 (org-infile-export-plist)))
4464 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4465 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4466 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4467 (org-export-html-expand (plist-get options :expand-quoted-html))
4468 (org-export-with-special-strings (plist-get options :special-strings))
4469 (re-sub
4470 (cond
4471 ((equal org-export-with-sub-superscripts '{})
4472 (list org-match-substring-with-braces-regexp))
4473 (org-export-with-sub-superscripts
4474 (list org-match-substring-regexp))
4475 (t nil)))
4476 (re-latex
4477 (if org-export-with-LaTeX-fragments
4478 (mapcar (lambda (x) (nth 1 x)) latexs)))
4479 (re-macros
4480 (if org-export-with-TeX-macros
4481 (list (concat "\\\\"
4482 (regexp-opt
4483 (append (mapcar 'car org-html-entities)
4484 (if (boundp 'org-latex-entities)
4485 (mapcar (lambda (x)
4486 (or (car-safe x) x))
4487 org-latex-entities)
4488 nil))
4489 'words))) ; FIXME
4491 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4492 (re-special (if org-export-with-special-strings
4493 (mapcar (lambda (x) (car x))
4494 org-export-html-special-string-regexps)))
4495 (re-rest
4496 (delq nil
4497 (list
4498 (if org-export-html-expand "@<[^>\n]+>")
4499 ))))
4500 (org-set-local
4501 'org-latex-and-specials-regexp
4502 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4503 re-rest) "\\|")))))
4505 (defun org-do-latex-and-special-faces (limit)
4506 "Run through the buffer and add overlays to links."
4507 (when org-latex-and-specials-regexp
4508 (let (rtn d)
4509 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4510 limit t))
4511 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4512 'face))
4513 '(org-code org-verbatim underline)))
4514 (progn
4515 (setq rtn t
4516 d (cond ((member (char-after (1+ (match-beginning 0)))
4517 '(?_ ?^)) 1)
4518 (t 0)))
4519 (font-lock-prepend-text-property
4520 (+ d (match-beginning 0)) (match-end 0)
4521 'face 'org-latex-and-export-specials)
4522 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4523 '(font-lock-multiline t)))))
4524 rtn)))
4526 (defun org-restart-font-lock ()
4527 "Restart font-lock-mode, to force refontification."
4528 (when (and (boundp 'font-lock-mode) font-lock-mode)
4529 (font-lock-mode -1)
4530 (font-lock-mode 1)))
4532 (defun org-all-targets (&optional radio)
4533 "Return a list of all targets in this file.
4534 With optional argument RADIO, only find radio targets."
4535 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4536 rtn)
4537 (save-excursion
4538 (goto-char (point-min))
4539 (while (re-search-forward re nil t)
4540 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4541 rtn)))
4543 (defun org-make-target-link-regexp (targets)
4544 "Make regular expression matching all strings in TARGETS.
4545 The regular expression finds the targets also if there is a line break
4546 between words."
4547 (and targets
4548 (concat
4549 "\\<\\("
4550 (mapconcat
4551 (lambda (x)
4552 (while (string-match " +" x)
4553 (setq x (replace-match "\\s-+" t t x)))
4555 targets
4556 "\\|")
4557 "\\)\\>")))
4559 (defun org-activate-tags (limit)
4560 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4561 (progn
4562 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4563 (add-text-properties (match-beginning 1) (match-end 1)
4564 (list 'mouse-face 'highlight
4565 'keymap org-mouse-map))
4566 (org-rear-nonsticky-at (match-end 1))
4567 t)))
4569 (defun org-outline-level ()
4570 (save-excursion
4571 (looking-at outline-regexp)
4572 (if (match-beginning 1)
4573 (+ (org-get-string-indentation (match-string 1)) 1000)
4574 (1- (- (match-end 0) (match-beginning 0))))))
4576 (defvar org-font-lock-keywords nil)
4578 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4579 "Regular expression matching a property line.")
4581 (defvar org-font-lock-hook nil
4582 "Functions to be called for special font lock stuff.")
4584 (defun org-font-lock-hook (limit)
4585 (run-hook-with-args 'org-font-lock-hook limit))
4587 (defun org-set-font-lock-defaults ()
4588 (let* ((em org-fontify-emphasized-text)
4589 (lk org-activate-links)
4590 (org-font-lock-extra-keywords
4591 (list
4592 ;; Call the hook
4593 '(org-font-lock-hook)
4594 ;; Headlines
4595 `(,(if org-fontify-whole-heading-line
4596 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
4597 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
4598 (1 (org-get-level-face 1))
4599 (2 (org-get-level-face 2))
4600 (3 (org-get-level-face 3)))
4601 ;; Table lines
4602 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4603 (1 'org-table t))
4604 ;; Table internals
4605 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4606 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4607 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4608 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
4609 ;; Drawers
4610 (list org-drawer-regexp '(0 'org-special-keyword t))
4611 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4612 ;; Properties
4613 (list org-property-re
4614 '(1 'org-special-keyword t)
4615 '(3 'org-property-value t))
4616 ;; Links
4617 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4618 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4619 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4620 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4621 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4622 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4623 (if (memq 'footnote lk) '(org-activate-footnote-links
4624 (2 'org-footnote t)))
4625 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4626 '(org-hide-wide-columns (0 nil append))
4627 ;; TODO lines
4628 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4629 '(1 (org-get-todo-face 1) t))
4630 ;; DONE
4631 (if org-fontify-done-headline
4632 (list (concat "^[*]+ +\\<\\("
4633 (mapconcat 'regexp-quote org-done-keywords "\\|")
4634 "\\)\\(.*\\)")
4635 '(2 'org-headline-done t))
4636 nil)
4637 ;; Priorities
4638 '(org-font-lock-add-priority-faces)
4639 ;; Tags
4640 '(org-font-lock-add-tag-faces)
4641 ;; Special keywords
4642 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4643 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4644 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4645 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4646 ;; Emphasis
4647 (if em
4648 (if (featurep 'xemacs)
4649 '(org-do-emphasis-faces (0 nil append))
4650 '(org-do-emphasis-faces)))
4651 ;; Checkboxes
4652 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4653 2 'org-checkbox prepend)
4654 (if org-provide-checkbox-statistics
4655 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4656 (0 (org-get-checkbox-statistics-face) t)))
4657 ;; Description list items
4658 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4659 2 'bold prepend)
4660 ;; ARCHIVEd headings
4661 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4662 '(1 'org-archived prepend))
4663 ;; Specials
4664 '(org-do-latex-and-special-faces)
4665 ;; Code
4666 '(org-activate-code (1 'org-code t))
4667 ;; COMMENT
4668 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4669 "\\|" org-quote-string "\\)\\>")
4670 '(1 'org-special-keyword t))
4671 '("^#.*" (0 'font-lock-comment-face t))
4672 ;; Blocks and meta lines
4673 '(org-fontify-meta-lines-and-blocks)
4675 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4676 ;; Now set the full font-lock-keywords
4677 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4678 (org-set-local 'font-lock-defaults
4679 '(org-font-lock-keywords t nil nil backward-paragraph))
4680 (kill-local-variable 'font-lock-keywords) nil))
4682 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
4683 "Fontify string S like in Org-mode"
4684 (with-temp-buffer
4685 (insert s)
4686 (let ((org-odd-levels-only odd-levels))
4687 (org-mode)
4688 (font-lock-fontify-buffer)
4689 (buffer-string))))
4691 (defvar org-m nil)
4692 (defvar org-l nil)
4693 (defvar org-f nil)
4694 (defun org-get-level-face (n)
4695 "Get the right face for match N in font-lock matching of headlines."
4696 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4697 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4698 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4699 (cond
4700 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4701 ((eq n 2) org-f)
4702 (t (if org-level-color-stars-only nil org-f))))
4704 (defun org-get-todo-face (kwd)
4705 "Get the right face for a TODO keyword KWD.
4706 If KWD is a number, get the corresponding match group."
4707 (if (numberp kwd) (setq kwd (match-string kwd)))
4708 (or (cdr (assoc kwd org-todo-keyword-faces))
4709 (and (member kwd org-done-keywords) 'org-done)
4710 'org-todo))
4712 (defun org-font-lock-add-tag-faces (limit)
4713 "Add the special tag faces."
4714 (when (and org-tag-faces org-tags-special-faces-re)
4715 (while (re-search-forward org-tags-special-faces-re limit t)
4716 (add-text-properties (match-beginning 1) (match-end 1)
4717 (list 'face (org-get-tag-face 1)
4718 'font-lock-fontified t))
4719 (backward-char 1))))
4721 (defun org-font-lock-add-priority-faces (limit)
4722 "Add the special priority faces."
4723 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4724 (add-text-properties
4725 (match-beginning 0) (match-end 0)
4726 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4727 org-priority-faces))
4728 'org-special-keyword)
4729 'font-lock-fontified t))))
4731 (defun org-get-tag-face (kwd)
4732 "Get the right face for a TODO keyword KWD.
4733 If KWD is a number, get the corresponding match group."
4734 (if (numberp kwd) (setq kwd (match-string kwd)))
4735 (or (cdr (assoc kwd org-tag-faces))
4736 'org-tag))
4738 (defun org-unfontify-region (beg end &optional maybe_loudly)
4739 "Remove fontification and activation overlays from links."
4740 (font-lock-default-unfontify-region beg end)
4741 (let* ((buffer-undo-list t)
4742 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4743 (inhibit-modification-hooks t)
4744 deactivate-mark buffer-file-name buffer-file-truename)
4745 (remove-text-properties beg end
4746 '(mouse-face t keymap t org-linked-text t
4747 invisible t intangible t
4748 line-prefix t wrap-prefix t
4749 org-no-flyspell t))))
4751 ;;;; Visibility cycling, including org-goto and indirect buffer
4753 ;;; Cycling
4755 (defvar org-cycle-global-status nil)
4756 (make-variable-buffer-local 'org-cycle-global-status)
4757 (defvar org-cycle-subtree-status nil)
4758 (make-variable-buffer-local 'org-cycle-subtree-status)
4760 ;;;###autoload
4762 (defvar org-inlinetask-min-level)
4764 (defun org-cycle (&optional arg)
4765 "TAB-action and visibility cycling for Org-mode.
4767 This is the command invoked in Org-moe by the TAB key. It's main purpose
4768 is outine visibility cycling, but it also invokes other actions
4769 in special contexts.
4771 - When this function is called with a prefix argument, rotate the entire
4772 buffer through 3 states (global cycling)
4773 1. OVERVIEW: Show only top-level headlines.
4774 2. CONTENTS: Show all headlines of all levels, but no body text.
4775 3. SHOW ALL: Show everything.
4776 When called with two `C-u C-u' prefixes, switch to the startup visibility,
4777 determined by the variable `org-startup-folded', and by any VISIBILITY
4778 properties in the buffer.
4779 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
4780 including any drawers.
4782 - When inside a table, re-align the table and move to the next field.
4784 - When point is at the beginning of a headline, rotate the subtree started
4785 by this line through 3 different states (local cycling)
4786 1. FOLDED: Only the main headline is shown.
4787 2. CHILDREN: The main headline and the direct children are shown.
4788 From this state, you can move to one of the children
4789 and zoom in further.
4790 3. SUBTREE: Show the entire subtree, including body text.
4791 If there is no subtree, switch directly from CHILDREN to FOLDED.
4793 - When there is a numeric prefix, go up to a heading with level ARG, do
4794 a `show-subtree' and return to the previous cursor position. If ARG
4795 is negative, go up that many levels.
4797 - When point is not at the beginning of a headline, execute the global
4798 binding for TAB, which is re-indenting the line. See the option
4799 `org-cycle-emulate-tab' for details.
4801 - Special case: if point is at the beginning of the buffer and there is
4802 no headline in line 1, this function will act as if called with prefix arg.
4803 But only if also the variable `org-cycle-global-at-bob' is t."
4804 (interactive "P")
4805 (org-load-modules-maybe)
4806 (unless (run-hook-with-args-until-success 'org-tab-first-hook)
4807 (let* ((limit-level
4808 (or org-cycle-max-level
4809 (and (boundp 'org-inlinetask-min-level)
4810 org-inlinetask-min-level
4811 (1- org-inlinetask-min-level))))
4812 (nstars (and limit-level
4813 (if org-odd-levels-only
4814 (and limit-level (1- (* limit-level 2)))
4815 limit-level)))
4816 (outline-regexp
4817 (cond
4818 ((not (org-mode-p)) outline-regexp)
4819 ((or (eq org-cycle-include-plain-lists 'integrate)
4820 (and org-cycle-include-plain-lists (org-at-item-p)))
4821 (concat "\\(?:\\*"
4822 (if nstars (format "\\{1,%d\\}" nstars) "+")
4823 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
4824 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
4825 (bob-special (and org-cycle-global-at-bob (bobp)
4826 (not (looking-at outline-regexp))))
4827 (org-cycle-hook
4828 (if bob-special
4829 (delq 'org-optimize-window-after-visibility-change
4830 (copy-sequence org-cycle-hook))
4831 org-cycle-hook))
4832 (pos (point)))
4834 (if (or bob-special (equal arg '(4)))
4835 ;; special case: use global cycling
4836 (setq arg t))
4838 (cond
4840 ((equal arg '(16))
4841 (org-set-startup-visibility)
4842 (message "Startup visibility, plus VISIBILITY properties"))
4844 ((equal arg '(64))
4845 (show-all)
4846 (message "Entire buffer visible, including drawers"))
4848 ((org-at-table-p 'any)
4849 ;; Enter the table or move to the next field in the table
4850 (or (org-table-recognize-table.el)
4851 (progn
4852 (if arg (org-table-edit-field t)
4853 (org-table-justify-field-maybe)
4854 (call-interactively 'org-table-next-field)))))
4856 ((run-hook-with-args-until-success
4857 'org-tab-after-check-for-table-hook))
4859 ((eq arg t) ;; Global cycling
4860 (org-cycle-internal-global))
4862 ((and org-drawers org-drawer-regexp
4863 (save-excursion
4864 (beginning-of-line 1)
4865 (looking-at org-drawer-regexp)))
4866 ;; Toggle block visibility
4867 (org-flag-drawer
4868 (not (get-char-property (match-end 0) 'invisible))))
4870 ((integerp arg)
4871 ;; Show-subtree, ARG levels up from here.
4872 (save-excursion
4873 (org-back-to-heading)
4874 (outline-up-heading (if (< arg 0) (- arg)
4875 (- (funcall outline-level) arg)))
4876 (org-show-subtree)))
4878 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4879 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4881 (org-cycle-internal-local))
4883 ;; TAB emulation and template completion
4884 (buffer-read-only (org-back-to-heading))
4886 ((run-hook-with-args-until-success
4887 'org-tab-after-check-for-cycling-hook))
4889 ((org-try-structure-completion))
4891 ((org-try-cdlatex-tab))
4893 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4894 (or (not (bolp))
4895 (not (looking-at outline-regexp))))
4896 (call-interactively (global-key-binding "\t")))
4898 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4899 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4900 (or (and (eq org-cycle-emulate-tab 'white)
4901 (= (match-end 0) (point-at-eol)))
4902 (and (eq org-cycle-emulate-tab 'whitestart)
4903 (>= (match-end 0) pos))))
4905 (eq org-cycle-emulate-tab t))
4906 (call-interactively (global-key-binding "\t")))
4908 (t (save-excursion
4909 (org-back-to-heading)
4910 (org-cycle)))))))
4912 (defun org-cycle-internal-global ()
4913 "Do the global cycling action."
4914 (cond
4915 ((and (eq last-command this-command)
4916 (eq org-cycle-global-status 'overview))
4917 ;; We just created the overview - now do table of contents
4918 ;; This can be slow in very large buffers, so indicate action
4919 (run-hook-with-args 'org-pre-cycle-hook 'contents)
4920 (message "CONTENTS...")
4921 (org-content)
4922 (message "CONTENTS...done")
4923 (setq org-cycle-global-status 'contents)
4924 (run-hook-with-args 'org-cycle-hook 'contents))
4926 ((and (eq last-command this-command)
4927 (eq org-cycle-global-status 'contents))
4928 ;; We just showed the table of contents - now show everything
4929 (run-hook-with-args 'org-pre-cycle-hook 'all)
4930 (show-all)
4931 (message "SHOW ALL")
4932 (setq org-cycle-global-status 'all)
4933 (run-hook-with-args 'org-cycle-hook 'all))
4936 ;; Default action: go to overview
4937 (run-hook-with-args 'org-pre-cycle-hook 'overview)
4938 (org-overview)
4939 (message "OVERVIEW")
4940 (setq org-cycle-global-status 'overview)
4941 (run-hook-with-args 'org-cycle-hook 'overview))))
4943 (defun org-cycle-internal-local ()
4944 "Do the local cycling action."
4945 (org-back-to-heading)
4946 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
4947 ;; First, some boundaries
4948 (save-excursion
4949 (org-back-to-heading)
4950 (setq level (funcall outline-level))
4951 (save-excursion
4952 (beginning-of-line 2)
4953 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
4954 ; XEmacs does not have `next-single-char-property-change'
4955 ; I'm not sure about Emacs 21.
4956 (while (and (not (eobp)) ;; this is like `next-line'
4957 (get-char-property (1- (point)) 'invisible))
4958 (beginning-of-line 2))
4959 (while (and (not (eobp)) ;; this is like `next-line'
4960 (get-char-property (1- (point)) 'invisible))
4961 (goto-char (next-single-char-property-change (point) 'invisible))
4962 ;;;??? (or (bolp) (beginning-of-line 2))))
4963 (and (eolp) (beginning-of-line 2))))
4964 (setq eol (point)))
4965 (outline-end-of-heading) (setq eoh (point))
4966 (save-excursion
4967 (outline-next-heading)
4968 (setq has-children (and (org-at-heading-p t)
4969 (> (funcall outline-level) level))))
4970 (org-end-of-subtree t)
4971 (unless (eobp)
4972 (skip-chars-forward " \t\n")
4973 (beginning-of-line 1) ; in case this is an item
4975 (setq eos (1- (point))))
4976 ;; Find out what to do next and set `this-command'
4977 (cond
4978 ((= eos eoh)
4979 ;; Nothing is hidden behind this heading
4980 (run-hook-with-args 'org-pre-cycle-hook 'empty)
4981 (message "EMPTY ENTRY")
4982 (setq org-cycle-subtree-status nil)
4983 (save-excursion
4984 (goto-char eos)
4985 (outline-next-heading)
4986 (if (org-invisible-p) (org-flag-heading nil))))
4987 ((and (or (>= eol eos)
4988 (not (string-match "\\S-" (buffer-substring eol eos))))
4989 (or has-children
4990 (not (setq children-skipped
4991 org-cycle-skip-children-state-if-no-children))))
4992 ;; Entire subtree is hidden in one line: children view
4993 (run-hook-with-args 'org-pre-cycle-hook 'children)
4994 (org-show-entry)
4995 (show-children)
4996 (message "CHILDREN")
4997 (save-excursion
4998 (goto-char eos)
4999 (outline-next-heading)
5000 (if (org-invisible-p) (org-flag-heading nil)))
5001 (setq org-cycle-subtree-status 'children)
5002 (run-hook-with-args 'org-cycle-hook 'children))
5003 ((or children-skipped
5004 (and (eq last-command this-command)
5005 (eq org-cycle-subtree-status 'children)))
5006 ;; We just showed the children, or no children are there,
5007 ;; now show everything.
5008 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5009 (org-show-subtree)
5010 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5011 (setq org-cycle-subtree-status 'subtree)
5012 (run-hook-with-args 'org-cycle-hook 'subtree))
5014 ;; Default action: hide the subtree.
5015 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5016 (hide-subtree)
5017 (message "FOLDED")
5018 (setq org-cycle-subtree-status 'folded)
5019 (run-hook-with-args 'org-cycle-hook 'folded)))))
5021 ;;;###autoload
5022 (defun org-global-cycle (&optional arg)
5023 "Cycle the global visibility. For details see `org-cycle'.
5024 With C-u prefix arg, switch to startup visibility.
5025 With a numeric prefix, show all headlines up to that level."
5026 (interactive "P")
5027 (let ((org-cycle-include-plain-lists
5028 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5029 (cond
5030 ((integerp arg)
5031 (show-all)
5032 (hide-sublevels arg)
5033 (setq org-cycle-global-status 'contents))
5034 ((equal arg '(4))
5035 (org-set-startup-visibility)
5036 (message "Startup visibility, plus VISIBILITY properties."))
5038 (org-cycle '(4))))))
5040 (defun org-set-startup-visibility ()
5041 "Set the visibility required by startup options and properties."
5042 (cond
5043 ((eq org-startup-folded t)
5044 (org-cycle '(4)))
5045 ((eq org-startup-folded 'content)
5046 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5047 (org-cycle '(4)) (org-cycle '(4)))))
5048 (if org-hide-block-startup (org-hide-block-all))
5049 (org-set-visibility-according-to-property 'no-cleanup)
5050 (org-cycle-hide-archived-subtrees 'all)
5051 (org-cycle-hide-drawers 'all)
5052 (org-cycle-show-empty-lines 'all))
5054 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5055 "Switch subtree visibilities according to :VISIBILITY: property."
5056 (interactive)
5057 (let (org-show-entry-below state)
5058 (save-excursion
5059 (goto-char (point-min))
5060 (while (re-search-forward
5061 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5062 nil t)
5063 (setq state (match-string 1))
5064 (save-excursion
5065 (org-back-to-heading t)
5066 (hide-subtree)
5067 (org-reveal)
5068 (cond
5069 ((equal state '("fold" "folded"))
5070 (hide-subtree))
5071 ((equal state "children")
5072 (org-show-hidden-entry)
5073 (show-children))
5074 ((equal state "content")
5075 (save-excursion
5076 (save-restriction
5077 (org-narrow-to-subtree)
5078 (org-content))))
5079 ((member state '("all" "showall"))
5080 (show-subtree)))))
5081 (unless no-cleanup
5082 (org-cycle-hide-archived-subtrees 'all)
5083 (org-cycle-hide-drawers 'all)
5084 (org-cycle-show-empty-lines 'all)))))
5086 (defun org-overview ()
5087 "Switch to overview mode, showing only top-level headlines.
5088 Really, this shows all headlines with level equal or greater than the level
5089 of the first headline in the buffer. This is important, because if the
5090 first headline is not level one, then (hide-sublevels 1) gives confusing
5091 results."
5092 (interactive)
5093 (let ((level (save-excursion
5094 (goto-char (point-min))
5095 (if (re-search-forward (concat "^" outline-regexp) nil t)
5096 (progn
5097 (goto-char (match-beginning 0))
5098 (funcall outline-level))))))
5099 (and level (hide-sublevels level))))
5101 (defun org-content (&optional arg)
5102 "Show all headlines in the buffer, like a table of contents.
5103 With numerical argument N, show content up to level N."
5104 (interactive "P")
5105 (save-excursion
5106 ;; Visit all headings and show their offspring
5107 (and (integerp arg) (org-overview))
5108 (goto-char (point-max))
5109 (catch 'exit
5110 (while (and (progn (condition-case nil
5111 (outline-previous-visible-heading 1)
5112 (error (goto-char (point-min))))
5114 (looking-at outline-regexp))
5115 (if (integerp arg)
5116 (show-children (1- arg))
5117 (show-branches))
5118 (if (bobp) (throw 'exit nil))))))
5121 (defun org-optimize-window-after-visibility-change (state)
5122 "Adjust the window after a change in outline visibility.
5123 This function is the default value of the hook `org-cycle-hook'."
5124 (when (get-buffer-window (current-buffer))
5125 (cond
5126 ((eq state 'content) nil)
5127 ((eq state 'all) nil)
5128 ((eq state 'folded) nil)
5129 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5130 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5132 ;; FIXME: no longer in use
5133 (defun org-compact-display-after-subtree-move ()
5134 "Show a compacter version of the tree of the entry's parent."
5135 (save-excursion
5136 (if (org-up-heading-safe)
5137 (progn
5138 (hide-subtree)
5139 (show-entry)
5140 (show-children)
5141 (org-cycle-show-empty-lines 'children)
5142 (org-cycle-hide-drawers 'children))
5143 (org-overview))))
5145 (defun org-remove-empty-overlays-at (pos)
5146 "Remove outline overlays that do not contain non-white stuff."
5147 (mapc
5148 (lambda (o)
5149 (and (eq 'outline (org-overlay-get o 'invisible))
5150 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5151 (org-overlay-end o))))
5152 (org-delete-overlay o)))
5153 (org-overlays-at pos)))
5155 (defun org-clean-visibility-after-subtree-move ()
5156 "Fix visibility issues after moving a subtree."
5157 ;; First, find a reasonable region to look at:
5158 ;; Start two siblings above, end three below
5159 (let* ((beg (save-excursion
5160 (and (outline-get-last-sibling)
5161 (outline-get-last-sibling))
5162 (point)))
5163 (end (save-excursion
5164 (and (outline-get-next-sibling)
5165 (outline-get-next-sibling)
5166 (outline-get-next-sibling))
5167 (if (org-at-heading-p)
5168 (point-at-eol)
5169 (point))))
5170 (level (looking-at "\\*+"))
5171 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5172 (save-excursion
5173 (save-restriction
5174 (narrow-to-region beg end)
5175 (when re
5176 ;; Properly fold already folded siblings
5177 (goto-char (point-min))
5178 (while (re-search-forward re nil t)
5179 (if (save-excursion (goto-char (point-at-eol)) (org-invisible-p))
5180 (hide-entry))))
5181 (org-cycle-show-empty-lines 'overview)
5182 (org-cycle-hide-drawers 'overview)))))
5184 (defun org-cycle-show-empty-lines (state)
5185 "Show empty lines above all visible headlines.
5186 The region to be covered depends on STATE when called through
5187 `org-cycle-hook'. Lisp program can use t for STATE to get the
5188 entire buffer covered. Note that an empty line is only shown if there
5189 are at least `org-cycle-separator-lines' empty lines before the headline."
5190 (when (> org-cycle-separator-lines 0)
5191 (save-excursion
5192 (let* ((n org-cycle-separator-lines)
5193 (re (cond
5194 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5195 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5196 (t (let ((ns (number-to-string (- n 2))))
5197 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5198 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5199 beg end)
5200 (cond
5201 ((memq state '(overview contents t))
5202 (setq beg (point-min) end (point-max)))
5203 ((memq state '(children folded))
5204 (setq beg (point) end (progn (org-end-of-subtree t t)
5205 (beginning-of-line 2)
5206 (point)))))
5207 (when beg
5208 (goto-char beg)
5209 (while (re-search-forward re end t)
5210 (if (not (get-char-property (match-end 1) 'invisible))
5211 (outline-flag-region
5212 (match-beginning 1) (match-end 1) nil)))))))
5213 ;; Never hide empty lines at the end of the file.
5214 (save-excursion
5215 (goto-char (point-max))
5216 (outline-previous-heading)
5217 (outline-end-of-heading)
5218 (if (and (looking-at "[ \t\n]+")
5219 (= (match-end 0) (point-max)))
5220 (outline-flag-region (point) (match-end 0) nil))))
5222 (defun org-show-empty-lines-in-parent ()
5223 "Move to the parent and re-show empty lines before visible headlines."
5224 (save-excursion
5225 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5226 (org-cycle-show-empty-lines context))))
5228 (defun org-cycle-hide-drawers (state)
5229 "Re-hide all drawers after a visibility state change."
5230 (when (and (org-mode-p)
5231 (not (memq state '(overview folded contents))))
5232 (save-excursion
5233 (let* ((globalp (memq state '(contents all)))
5234 (beg (if globalp (point-min) (point)))
5235 (end (if globalp (point-max)
5236 (if (eq state 'children)
5237 (save-excursion (outline-next-heading) (point))
5238 (org-end-of-subtree t)))))
5239 (goto-char beg)
5240 (while (re-search-forward org-drawer-regexp end t)
5241 (org-flag-drawer t))))))
5243 (defun org-flag-drawer (flag)
5244 (save-excursion
5245 (beginning-of-line 1)
5246 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5247 (let ((b (match-end 0))
5248 (outline-regexp org-outline-regexp))
5249 (if (re-search-forward
5250 "^[ \t]*:END:"
5251 (save-excursion (outline-next-heading) (point)) t)
5252 (outline-flag-region b (point-at-eol) flag)
5253 (error ":END: line missing"))))))
5255 (defun org-subtree-end-visible-p ()
5256 "Is the end of the current subtree visible?"
5257 (pos-visible-in-window-p
5258 (save-excursion (org-end-of-subtree t) (point))))
5260 (defun org-first-headline-recenter (&optional N)
5261 "Move cursor to the first headline and recenter the headline.
5262 Optional argument N means, put the headline into the Nth line of the window."
5263 (goto-char (point-min))
5264 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5265 (beginning-of-line)
5266 (recenter (prefix-numeric-value N))))
5268 ;;; Folding of blocks
5270 (defconst org-block-regexp
5272 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5273 "Regular expression for hiding blocks.")
5275 (defvar org-hide-block-overlays nil
5276 "Overays hiding blocks.")
5277 (make-variable-buffer-local 'org-hide-block-overlays)
5279 (defun org-block-map (function &optional start end)
5280 "Call func at the head of all source blocks in the current
5281 buffer. Optional arguments START and END can be used to limit
5282 the range."
5283 (let ((start (or start (point-min)))
5284 (end (or end (point-max))))
5285 (save-excursion
5286 (goto-char start)
5287 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5288 (save-excursion
5289 (save-match-data
5290 (goto-char (match-beginning 0))
5291 (funcall function)))))))
5293 (defun org-hide-block-toggle-all ()
5294 "Toggle the visibility of all blocks in the current buffer."
5295 (org-block-map #'org-hide-block-toggle))
5297 (defun org-hide-block-all ()
5298 "Fold all blocks in the current buffer."
5299 (interactive)
5300 (org-show-block-all)
5301 (org-block-map #'org-hide-block-toggle-maybe))
5303 (defun org-show-block-all ()
5304 "Unfold all blocks in the current buffer."
5305 (mapc 'org-delete-overlay org-hide-block-overlays)
5306 (setq org-hide-block-overlays nil))
5308 (defun org-hide-block-toggle-maybe ()
5309 "Toggle visibility of block at point."
5310 (interactive)
5311 (let ((case-fold-search t))
5312 (if (save-excursion
5313 (beginning-of-line 1)
5314 (looking-at org-block-regexp))
5315 (progn (org-hide-block-toggle)
5316 t) ;; to signal that we took action
5317 nil))) ;; to signal that we did not
5319 (defun org-hide-block-toggle (&optional force)
5320 "Toggle the visibility of the current block."
5321 (interactive)
5322 (save-excursion
5323 (beginning-of-line)
5324 (if (re-search-forward org-block-regexp nil t)
5325 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5326 (end (match-end 0))
5327 ov) ;; end of entire body
5328 (if (memq t (mapcar (lambda (overlay)
5329 (eq (org-overlay-get overlay 'invisible)
5330 'org-hide-block))
5331 (org-overlays-at start)))
5332 (if (or (not force) (eq force 'off))
5333 (mapc (lambda (ov)
5334 (when (member ov org-hide-block-overlays)
5335 (setq org-hide-block-overlays
5336 (delq ov org-hide-block-overlays)))
5337 (when (eq (org-overlay-get ov 'invisible)
5338 'org-hide-block)
5339 (org-delete-overlay ov)))
5340 (org-overlays-at start)))
5341 (setq ov (org-make-overlay start end))
5342 (org-overlay-put ov 'invisible 'org-hide-block)
5343 (push ov org-hide-block-overlays)))
5344 (error "Not looking at a source block"))))
5346 ;; org-tab-after-check-for-cycling-hook
5347 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5348 ;; Remove overlays when changing major mode
5349 (add-hook 'org-mode-hook
5350 (lambda () (org-add-hook 'change-major-mode-hook
5351 'org-show-block-all 'append 'local)))
5353 ;;; Org-goto
5355 (defvar org-goto-window-configuration nil)
5356 (defvar org-goto-marker nil)
5357 (defvar org-goto-map
5358 (let ((map (make-sparse-keymap)))
5359 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5360 (while (setq cmd (pop cmds))
5361 (substitute-key-definition cmd cmd map global-map)))
5362 (suppress-keymap map)
5363 (org-defkey map "\C-m" 'org-goto-ret)
5364 (org-defkey map [(return)] 'org-goto-ret)
5365 (org-defkey map [(left)] 'org-goto-left)
5366 (org-defkey map [(right)] 'org-goto-right)
5367 (org-defkey map [(control ?g)] 'org-goto-quit)
5368 (org-defkey map "\C-i" 'org-cycle)
5369 (org-defkey map [(tab)] 'org-cycle)
5370 (org-defkey map [(down)] 'outline-next-visible-heading)
5371 (org-defkey map [(up)] 'outline-previous-visible-heading)
5372 (if org-goto-auto-isearch
5373 (if (fboundp 'define-key-after)
5374 (define-key-after map [t] 'org-goto-local-auto-isearch)
5375 nil)
5376 (org-defkey map "q" 'org-goto-quit)
5377 (org-defkey map "n" 'outline-next-visible-heading)
5378 (org-defkey map "p" 'outline-previous-visible-heading)
5379 (org-defkey map "f" 'outline-forward-same-level)
5380 (org-defkey map "b" 'outline-backward-same-level)
5381 (org-defkey map "u" 'outline-up-heading))
5382 (org-defkey map "/" 'org-occur)
5383 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5384 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5385 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5386 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5387 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5388 map))
5390 (defconst org-goto-help
5391 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5392 RET=jump to location [Q]uit and return to previous location
5393 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5395 (defvar org-goto-start-pos) ; dynamically scoped parameter
5397 ;; FIXME: Docstring doe not mention both interfaces
5398 (defun org-goto (&optional alternative-interface)
5399 "Look up a different location in the current file, keeping current visibility.
5401 When you want look-up or go to a different location in a document, the
5402 fastest way is often to fold the entire buffer and then dive into the tree.
5403 This method has the disadvantage, that the previous location will be folded,
5404 which may not be what you want.
5406 This command works around this by showing a copy of the current buffer
5407 in an indirect buffer, in overview mode. You can dive into the tree in
5408 that copy, use org-occur and incremental search to find a location.
5409 When pressing RET or `Q', the command returns to the original buffer in
5410 which the visibility is still unchanged. After RET is will also jump to
5411 the location selected in the indirect buffer and expose the
5412 the headline hierarchy above."
5413 (interactive "P")
5414 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5415 (org-refile-use-outline-path t)
5416 (org-refile-target-verify-function nil)
5417 (interface
5418 (if (not alternative-interface)
5419 org-goto-interface
5420 (if (eq org-goto-interface 'outline)
5421 'outline-path-completion
5422 'outline)))
5423 (org-goto-start-pos (point))
5424 (selected-point
5425 (if (eq interface 'outline)
5426 (car (org-get-location (current-buffer) org-goto-help))
5427 (nth 3 (org-refile-get-location "Goto: ")))))
5428 (if selected-point
5429 (progn
5430 (org-mark-ring-push org-goto-start-pos)
5431 (goto-char selected-point)
5432 (if (or (org-invisible-p) (org-invisible-p2))
5433 (org-show-context 'org-goto)))
5434 (message "Quit"))))
5436 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5437 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5438 (defvar org-goto-local-auto-isearch-map) ; defined below
5440 (defun org-get-location (buf help)
5441 "Let the user select a location in the Org-mode buffer BUF.
5442 This function uses a recursive edit. It returns the selected position
5443 or nil."
5444 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5445 (isearch-hide-immediately nil)
5446 (isearch-search-fun-function
5447 (lambda () 'org-goto-local-search-headings))
5448 (org-goto-selected-point org-goto-exit-command))
5449 (save-excursion
5450 (save-window-excursion
5451 (delete-other-windows)
5452 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5453 (switch-to-buffer
5454 (condition-case nil
5455 (make-indirect-buffer (current-buffer) "*org-goto*")
5456 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5457 (with-output-to-temp-buffer "*Help*"
5458 (princ help))
5459 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5460 (setq buffer-read-only nil)
5461 (let ((org-startup-truncated t)
5462 (org-startup-folded nil)
5463 (org-startup-align-all-tables nil))
5464 (org-mode)
5465 (org-overview))
5466 (setq buffer-read-only t)
5467 (if (and (boundp 'org-goto-start-pos)
5468 (integer-or-marker-p org-goto-start-pos))
5469 (let ((org-show-hierarchy-above t)
5470 (org-show-siblings t)
5471 (org-show-following-heading t))
5472 (goto-char org-goto-start-pos)
5473 (and (org-invisible-p) (org-show-context)))
5474 (goto-char (point-min)))
5475 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5476 (message "Select location and press RET")
5477 (use-local-map org-goto-map)
5478 (recursive-edit)
5480 (kill-buffer "*org-goto*")
5481 (cons org-goto-selected-point org-goto-exit-command)))
5483 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5484 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5485 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5486 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5488 (defun org-goto-local-search-headings (string bound noerror)
5489 "Search and make sure that any matches are in headlines."
5490 (catch 'return
5491 (while (if isearch-forward
5492 (search-forward string bound noerror)
5493 (search-backward string bound noerror))
5494 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5495 (and (member :headline context)
5496 (not (member :tags context))))
5497 (throw 'return (point))))))
5499 (defun org-goto-local-auto-isearch ()
5500 "Start isearch."
5501 (interactive)
5502 (goto-char (point-min))
5503 (let ((keys (this-command-keys)))
5504 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5505 (isearch-mode t)
5506 (isearch-process-search-char (string-to-char keys)))))
5508 (defun org-goto-ret (&optional arg)
5509 "Finish `org-goto' by going to the new location."
5510 (interactive "P")
5511 (setq org-goto-selected-point (point)
5512 org-goto-exit-command 'return)
5513 (throw 'exit nil))
5515 (defun org-goto-left ()
5516 "Finish `org-goto' by going to the new location."
5517 (interactive)
5518 (if (org-on-heading-p)
5519 (progn
5520 (beginning-of-line 1)
5521 (setq org-goto-selected-point (point)
5522 org-goto-exit-command 'left)
5523 (throw 'exit nil))
5524 (error "Not on a heading")))
5526 (defun org-goto-right ()
5527 "Finish `org-goto' by going to the new location."
5528 (interactive)
5529 (if (org-on-heading-p)
5530 (progn
5531 (setq org-goto-selected-point (point)
5532 org-goto-exit-command 'right)
5533 (throw 'exit nil))
5534 (error "Not on a heading")))
5536 (defun org-goto-quit ()
5537 "Finish `org-goto' without cursor motion."
5538 (interactive)
5539 (setq org-goto-selected-point nil)
5540 (setq org-goto-exit-command 'quit)
5541 (throw 'exit nil))
5543 ;;; Indirect buffer display of subtrees
5545 (defvar org-indirect-dedicated-frame nil
5546 "This is the frame being used for indirect tree display.")
5547 (defvar org-last-indirect-buffer nil)
5549 (defun org-tree-to-indirect-buffer (&optional arg)
5550 "Create indirect buffer and narrow it to current subtree.
5551 With numerical prefix ARG, go up to this level and then take that tree.
5552 If ARG is negative, go up that many levels.
5553 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5554 indirect buffer previously made with this command, to avoid proliferation of
5555 indirect buffers. However, when you call the command with a `C-u' prefix, or
5556 when `org-indirect-buffer-display' is `new-frame', the last buffer
5557 is kept so that you can work with several indirect buffers at the same time.
5558 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5559 requests that a new frame be made for the new buffer, so that the dedicated
5560 frame is not changed."
5561 (interactive "P")
5562 (let ((cbuf (current-buffer))
5563 (cwin (selected-window))
5564 (pos (point))
5565 beg end level heading ibuf)
5566 (save-excursion
5567 (org-back-to-heading t)
5568 (when (numberp arg)
5569 (setq level (org-outline-level))
5570 (if (< arg 0) (setq arg (+ level arg)))
5571 (while (> (setq level (org-outline-level)) arg)
5572 (outline-up-heading 1 t)))
5573 (setq beg (point)
5574 heading (org-get-heading))
5575 (org-end-of-subtree t) (setq end (point)))
5576 (if (and (buffer-live-p org-last-indirect-buffer)
5577 (not (eq org-indirect-buffer-display 'new-frame))
5578 (not arg))
5579 (kill-buffer org-last-indirect-buffer))
5580 (setq ibuf (org-get-indirect-buffer cbuf)
5581 org-last-indirect-buffer ibuf)
5582 (cond
5583 ((or (eq org-indirect-buffer-display 'new-frame)
5584 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5585 (select-frame (make-frame))
5586 (delete-other-windows)
5587 (switch-to-buffer ibuf)
5588 (org-set-frame-title heading))
5589 ((eq org-indirect-buffer-display 'dedicated-frame)
5590 (raise-frame
5591 (select-frame (or (and org-indirect-dedicated-frame
5592 (frame-live-p org-indirect-dedicated-frame)
5593 org-indirect-dedicated-frame)
5594 (setq org-indirect-dedicated-frame (make-frame)))))
5595 (delete-other-windows)
5596 (switch-to-buffer ibuf)
5597 (org-set-frame-title (concat "Indirect: " heading)))
5598 ((eq org-indirect-buffer-display 'current-window)
5599 (switch-to-buffer ibuf))
5600 ((eq org-indirect-buffer-display 'other-window)
5601 (pop-to-buffer ibuf))
5602 (t (error "Invalid value.")))
5603 (if (featurep 'xemacs)
5604 (save-excursion (org-mode) (turn-on-font-lock)))
5605 (narrow-to-region beg end)
5606 (show-all)
5607 (goto-char pos)
5608 (and (window-live-p cwin) (select-window cwin))))
5610 (defun org-get-indirect-buffer (&optional buffer)
5611 (setq buffer (or buffer (current-buffer)))
5612 (let ((n 1) (base (buffer-name buffer)) bname)
5613 (while (buffer-live-p
5614 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5615 (setq n (1+ n)))
5616 (condition-case nil
5617 (make-indirect-buffer buffer bname 'clone)
5618 (error (make-indirect-buffer buffer bname)))))
5620 (defun org-set-frame-title (title)
5621 "Set the title of the current frame to the string TITLE."
5622 ;; FIXME: how to name a single frame in XEmacs???
5623 (unless (featurep 'xemacs)
5624 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5626 ;;;; Structure editing
5628 ;;; Inserting headlines
5630 (defun org-previous-line-empty-p ()
5631 (save-excursion
5632 (and (not (bobp))
5633 (or (beginning-of-line 0) t)
5634 (save-match-data
5635 (looking-at "[ \t]*$")))))
5637 (defun org-insert-heading (&optional force-heading)
5638 "Insert a new heading or item with same depth at point.
5639 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5640 If point is at the beginning of a headline, insert a sibling before the
5641 current headline. If point is not at the beginning, do not split the line,
5642 but create the new headline after the current line."
5643 (interactive "P")
5644 (if (= (buffer-size) 0)
5645 (insert "\n* ")
5646 (when (or force-heading (not (org-insert-item)))
5647 (let* ((empty-line-p nil)
5648 (head (save-excursion
5649 (condition-case nil
5650 (progn
5651 (org-back-to-heading)
5652 (setq empty-line-p (org-previous-line-empty-p))
5653 (match-string 0))
5654 (error "*"))))
5655 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5656 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5657 pos hide-previous previous-pos)
5658 (cond
5659 ((and (org-on-heading-p) (bolp)
5660 (or (bobp)
5661 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5662 ;; insert before the current line
5663 (open-line (if blank 2 1)))
5664 ((and (bolp)
5665 (or (bobp)
5666 (save-excursion
5667 (backward-char 1) (not (org-invisible-p)))))
5668 ;; insert right here
5669 nil)
5671 ;; somewhere in the line
5672 (save-excursion
5673 (setq previous-pos (point-at-bol))
5674 (end-of-line)
5675 (setq hide-previous (org-invisible-p)))
5676 (and org-insert-heading-respect-content (org-show-subtree))
5677 (let ((split
5678 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5679 (save-excursion
5680 (let ((p (point)))
5681 (goto-char (point-at-bol))
5682 (and (looking-at org-complex-heading-regexp)
5683 (> p (match-beginning 4)))))))
5684 tags pos)
5685 (cond
5686 (org-insert-heading-respect-content
5687 (org-end-of-subtree nil t)
5688 (or (bolp) (newline))
5689 (or (org-previous-line-empty-p)
5690 (and blank (newline)))
5691 (open-line 1))
5692 ((org-on-heading-p)
5693 (when hide-previous
5694 (show-children)
5695 (org-show-entry))
5696 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5697 (setq tags (and (match-end 2) (match-string 2)))
5698 (and (match-end 1)
5699 (delete-region (match-beginning 1) (match-end 1)))
5700 (setq pos (point-at-bol))
5701 (or split (end-of-line 1))
5702 (delete-horizontal-space)
5703 (newline (if blank 2 1))
5704 (when tags
5705 (save-excursion
5706 (goto-char pos)
5707 (end-of-line 1)
5708 (insert " " tags)
5709 (org-set-tags nil 'align))))
5711 (or split (end-of-line 1))
5712 (newline (if blank 2 1)))))))
5713 (insert head) (just-one-space)
5714 (setq pos (point))
5715 (end-of-line 1)
5716 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5717 (when (and org-insert-heading-respect-content hide-previous)
5718 (save-excursion
5719 (goto-char previous-pos)
5720 (hide-subtree)))
5721 (run-hooks 'org-insert-heading-hook)))))
5723 (defun org-get-heading (&optional no-tags)
5724 "Return the heading of the current entry, without the stars."
5725 (save-excursion
5726 (org-back-to-heading t)
5727 (if (looking-at
5728 (if no-tags
5729 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5730 "\\*+[ \t]+\\([^\r\n]*\\)"))
5731 (match-string 1) "")))
5733 (defun org-heading-components ()
5734 "Return the components of the current heading.
5735 This is a list with the following elements:
5736 - the level as an integer
5737 - the reduced level, different if `org-odd-levels-only' is set.
5738 - the TODO keyword, or nil
5739 - the priority character, like ?A, or nil if no priority is given
5740 - the headline text itself, or the tags string if no headline text
5741 - the tags string, or nil."
5742 (save-excursion
5743 (org-back-to-heading t)
5744 (if (looking-at org-complex-heading-regexp)
5745 (list (length (match-string 1))
5746 (org-reduced-level (length (match-string 1)))
5747 (org-match-string-no-properties 2)
5748 (and (match-end 3) (aref (match-string 3) 2))
5749 (org-match-string-no-properties 4)
5750 (org-match-string-no-properties 5)))))
5752 (defun org-get-entry ()
5753 "Get the entry text, after heading, entire subtree."
5754 (save-excursion
5755 (org-back-to-heading t)
5756 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
5758 (defun org-insert-heading-after-current ()
5759 "Insert a new heading with same level as current, after current subtree."
5760 (interactive)
5761 (org-back-to-heading)
5762 (org-insert-heading)
5763 (org-move-subtree-down)
5764 (end-of-line 1))
5766 (defun org-insert-heading-respect-content ()
5767 (interactive)
5768 (let ((org-insert-heading-respect-content t))
5769 (org-insert-heading t)))
5771 (defun org-insert-todo-heading-respect-content (&optional force-state)
5772 (interactive "P")
5773 (let ((org-insert-heading-respect-content t))
5774 (org-insert-todo-heading force-state t)))
5776 (defun org-insert-todo-heading (arg &optional force-heading)
5777 "Insert a new heading with the same level and TODO state as current heading.
5778 If the heading has no TODO state, or if the state is DONE, use the first
5779 state (TODO by default). Also with prefix arg, force first state."
5780 (interactive "P")
5781 (when (or force-heading (not (org-insert-item 'checkbox)))
5782 (org-insert-heading force-heading)
5783 (save-excursion
5784 (org-back-to-heading)
5785 (outline-previous-heading)
5786 (looking-at org-todo-line-regexp))
5787 (let*
5788 ((new-mark-x
5789 (if (or arg
5790 (not (match-beginning 2))
5791 (member (match-string 2) org-done-keywords))
5792 (car org-todo-keywords-1)
5793 (match-string 2)))
5794 (new-mark
5796 (run-hook-with-args-until-success
5797 'org-todo-get-default-hook new-mark-x nil)
5798 new-mark-x)))
5799 (beginning-of-line 1)
5800 (and (looking-at "\\*+ ") (goto-char (match-end 0))
5801 (if org-treat-insert-todo-heading-as-state-change
5802 (org-todo new-mark)
5803 (insert new-mark " "))))
5804 (when org-provide-todo-statistics
5805 (org-update-parent-todo-statistics))))
5807 (defun org-insert-subheading (arg)
5808 "Insert a new subheading and demote it.
5809 Works for outline headings and for plain lists alike."
5810 (interactive "P")
5811 (org-insert-heading arg)
5812 (cond
5813 ((org-on-heading-p) (org-do-demote))
5814 ((org-at-item-p) (org-indent-item 1))))
5816 (defun org-insert-todo-subheading (arg)
5817 "Insert a new subheading with TODO keyword or checkbox and demote it.
5818 Works for outline headings and for plain lists alike."
5819 (interactive "P")
5820 (org-insert-todo-heading arg)
5821 (cond
5822 ((org-on-heading-p) (org-do-demote))
5823 ((org-at-item-p) (org-indent-item 1))))
5825 ;;; Promotion and Demotion
5827 (defvar org-after-demote-entry-hook nil
5828 "Hook run after an entry has been demoted.
5829 The cursor will be at the beginning of the entry.
5830 When a subtree is being demoted, the hook will be called for each node.")
5832 (defvar org-after-promote-entry-hook nil
5833 "Hook run after an entry has been promoted.
5834 The cursor will be at the beginning of the entry.
5835 When a subtree is being promoted, the hook will be called for each node.")
5837 (defun org-promote-subtree ()
5838 "Promote the entire subtree.
5839 See also `org-promote'."
5840 (interactive)
5841 (save-excursion
5842 (org-map-tree 'org-promote))
5843 (org-fix-position-after-promote))
5845 (defun org-demote-subtree ()
5846 "Demote the entire subtree. See `org-demote'.
5847 See also `org-promote'."
5848 (interactive)
5849 (save-excursion
5850 (org-map-tree 'org-demote))
5851 (org-fix-position-after-promote))
5854 (defun org-do-promote ()
5855 "Promote the current heading higher up the tree.
5856 If the region is active in `transient-mark-mode', promote all headings
5857 in the region."
5858 (interactive)
5859 (save-excursion
5860 (if (org-region-active-p)
5861 (org-map-region 'org-promote (region-beginning) (region-end))
5862 (org-promote)))
5863 (org-fix-position-after-promote))
5865 (defun org-do-demote ()
5866 "Demote the current heading lower down the tree.
5867 If the region is active in `transient-mark-mode', demote all headings
5868 in the region."
5869 (interactive)
5870 (save-excursion
5871 (if (org-region-active-p)
5872 (org-map-region 'org-demote (region-beginning) (region-end))
5873 (org-demote)))
5874 (org-fix-position-after-promote))
5876 (defun org-fix-position-after-promote ()
5877 "Make sure that after pro/demotion cursor position is right."
5878 (let ((pos (point)))
5879 (when (save-excursion
5880 (beginning-of-line 1)
5881 (looking-at org-todo-line-regexp)
5882 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5883 (cond ((eobp) (insert " "))
5884 ((eolp) (insert " "))
5885 ((equal (char-after) ?\ ) (forward-char 1))))))
5887 (defun org-reduced-level (l)
5888 "Compute the effective level of a heading.
5889 This takes into account the setting of `org-odd-levels-only'."
5890 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5892 (defun org-get-valid-level (level &optional change)
5893 "Rectify a level change under the influence of `org-odd-levels-only'
5894 LEVEL is a current level, CHANGE is by how much the level should be
5895 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5896 even level numbers will become the next higher odd number."
5897 (if org-odd-levels-only
5898 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5899 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5900 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5901 (max 1 (+ level (or change 0)))))
5903 (if (boundp 'define-obsolete-function-alias)
5904 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5905 (define-obsolete-function-alias 'org-get-legal-level
5906 'org-get-valid-level)
5907 (define-obsolete-function-alias 'org-get-legal-level
5908 'org-get-valid-level "23.1")))
5910 (defun org-promote ()
5911 "Promote the current heading higher up the tree.
5912 If the region is active in `transient-mark-mode', promote all headings
5913 in the region."
5914 (org-back-to-heading t)
5915 (let* ((level (save-match-data (funcall outline-level)))
5916 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5917 (diff (abs (- level (length up-head) -1))))
5918 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5919 (replace-match up-head nil t)
5920 ;; Fixup tag positioning
5921 (and org-auto-align-tags (org-set-tags nil t))
5922 (if org-adapt-indentation (org-fixup-indentation (- diff)))
5923 (run-hooks 'org-after-promote-entry-hook)))
5925 (defun org-demote ()
5926 "Demote the current heading lower down the tree.
5927 If the region is active in `transient-mark-mode', demote all headings
5928 in the region."
5929 (org-back-to-heading t)
5930 (let* ((level (save-match-data (funcall outline-level)))
5931 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5932 (diff (abs (- level (length down-head) -1))))
5933 (replace-match down-head nil t)
5934 ;; Fixup tag positioning
5935 (and org-auto-align-tags (org-set-tags nil t))
5936 (if org-adapt-indentation (org-fixup-indentation diff))
5937 (run-hooks 'org-after-demote-entry-hook)))
5939 (defun org-map-tree (fun)
5940 "Call FUN for every heading underneath the current one."
5941 (org-back-to-heading)
5942 (let ((level (funcall outline-level)))
5943 (save-excursion
5944 (funcall fun)
5945 (while (and (progn
5946 (outline-next-heading)
5947 (> (funcall outline-level) level))
5948 (not (eobp)))
5949 (funcall fun)))))
5951 (defun org-map-region (fun beg end)
5952 "Call FUN for every heading between BEG and END."
5953 (let ((org-ignore-region t))
5954 (save-excursion
5955 (setq end (copy-marker end))
5956 (goto-char beg)
5957 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5958 (< (point) end))
5959 (funcall fun))
5960 (while (and (progn
5961 (outline-next-heading)
5962 (< (point) end))
5963 (not (eobp)))
5964 (funcall fun)))))
5966 (defun org-fixup-indentation (diff)
5967 "Change the indentation in the current entry by DIFF
5968 However, if any line in the current entry has no indentation, or if it
5969 would end up with no indentation after the change, nothing at all is done."
5970 (save-excursion
5971 (let ((end (save-excursion (outline-next-heading)
5972 (point-marker)))
5973 (prohibit (if (> diff 0)
5974 "^\\S-"
5975 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5976 col)
5977 (unless (save-excursion (end-of-line 1)
5978 (re-search-forward prohibit end t))
5979 (while (and (< (point) end)
5980 (re-search-forward "^[ \t]+" end t))
5981 (goto-char (match-end 0))
5982 (setq col (current-column))
5983 (if (< diff 0) (replace-match ""))
5984 (org-indent-to-column (+ diff col))))
5985 (move-marker end nil))))
5987 (defun org-convert-to-odd-levels ()
5988 "Convert an org-mode file with all levels allowed to one with odd levels.
5989 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5990 level 5 etc."
5991 (interactive)
5992 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5993 (let ((org-odd-levels-only nil) n)
5994 (save-excursion
5995 (goto-char (point-min))
5996 (while (re-search-forward "^\\*\\*+ " nil t)
5997 (setq n (- (length (match-string 0)) 2))
5998 (while (>= (setq n (1- n)) 0)
5999 (org-demote))
6000 (end-of-line 1))))))
6003 (defun org-convert-to-oddeven-levels ()
6004 "Convert an org-mode file with only odd levels to one with odd and even levels.
6005 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6006 section with an even level, conversion would destroy the structure of the file. An error
6007 is signaled in this case."
6008 (interactive)
6009 (goto-char (point-min))
6010 ;; First check if there are no even levels
6011 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6012 (org-show-context t)
6013 (error "Not all levels are odd in this file. Conversion not possible."))
6014 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6015 (let ((org-odd-levels-only nil) n)
6016 (save-excursion
6017 (goto-char (point-min))
6018 (while (re-search-forward "^\\*\\*+ " nil t)
6019 (setq n (/ (1- (length (match-string 0))) 2))
6020 (while (>= (setq n (1- n)) 0)
6021 (org-promote))
6022 (end-of-line 1))))))
6024 (defun org-tr-level (n)
6025 "Make N odd if required."
6026 (if org-odd-levels-only (1+ (/ n 2)) n))
6028 ;;; Vertical tree motion, cutting and pasting of subtrees
6030 (defun org-move-subtree-up (&optional arg)
6031 "Move the current subtree up past ARG headlines of the same level."
6032 (interactive "p")
6033 (org-move-subtree-down (- (prefix-numeric-value arg))))
6035 (defun org-move-subtree-down (&optional arg)
6036 "Move the current subtree down past ARG headlines of the same level."
6037 (interactive "p")
6038 (setq arg (prefix-numeric-value arg))
6039 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6040 'outline-get-last-sibling))
6041 (ins-point (make-marker))
6042 (cnt (abs arg))
6043 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6044 ;; Select the tree
6045 (org-back-to-heading)
6046 (setq beg0 (point))
6047 (save-excursion
6048 (setq ne-beg (org-back-over-empty-lines))
6049 (setq beg (point)))
6050 (save-match-data
6051 (save-excursion (outline-end-of-heading)
6052 (setq folded (org-invisible-p)))
6053 (outline-end-of-subtree))
6054 (outline-next-heading)
6055 (setq ne-end (org-back-over-empty-lines))
6056 (setq end (point))
6057 (goto-char beg0)
6058 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6059 ;; include less whitespace
6060 (save-excursion
6061 (goto-char beg)
6062 (forward-line (- ne-beg ne-end))
6063 (setq beg (point))))
6064 ;; Find insertion point, with error handling
6065 (while (> cnt 0)
6066 (or (and (funcall movfunc) (looking-at outline-regexp))
6067 (progn (goto-char beg0)
6068 (error "Cannot move past superior level or buffer limit")))
6069 (setq cnt (1- cnt)))
6070 (if (> arg 0)
6071 ;; Moving forward - still need to move over subtree
6072 (progn (org-end-of-subtree t t)
6073 (save-excursion
6074 (org-back-over-empty-lines)
6075 (or (bolp) (newline)))))
6076 (setq ne-ins (org-back-over-empty-lines))
6077 (move-marker ins-point (point))
6078 (setq txt (buffer-substring beg end))
6079 (org-save-markers-in-region beg end)
6080 (delete-region beg end)
6081 (org-remove-empty-overlays-at beg)
6082 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6083 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6084 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6085 (let ((bbb (point)))
6086 (insert-before-markers txt)
6087 (org-reinstall-markers-in-region bbb)
6088 (move-marker ins-point bbb))
6089 (or (bolp) (insert "\n"))
6090 (setq ins-end (point))
6091 (goto-char ins-point)
6092 (org-skip-whitespace)
6093 (when (and (< arg 0)
6094 (org-first-sibling-p)
6095 (> ne-ins ne-beg))
6096 ;; Move whitespace back to beginning
6097 (save-excursion
6098 (goto-char ins-end)
6099 (let ((kill-whole-line t))
6100 (kill-line (- ne-ins ne-beg)) (point)))
6101 (insert (make-string (- ne-ins ne-beg) ?\n)))
6102 (move-marker ins-point nil)
6103 (if folded
6104 (hide-entry)
6105 (org-show-entry)
6106 (show-children)
6107 (org-cycle-hide-drawers 'children))
6108 (org-clean-visibility-after-subtree-move)))
6110 (defvar org-subtree-clip ""
6111 "Clipboard for cut and paste of subtrees.
6112 This is actually only a copy of the kill, because we use the normal kill
6113 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6115 (defvar org-subtree-clip-folded nil
6116 "Was the last copied subtree folded?
6117 This is used to fold the tree back after pasting.")
6119 (defun org-cut-subtree (&optional n)
6120 "Cut the current subtree into the clipboard.
6121 With prefix arg N, cut this many sequential subtrees.
6122 This is a short-hand for marking the subtree and then cutting it."
6123 (interactive "p")
6124 (org-copy-subtree n 'cut))
6126 (defun org-copy-subtree (&optional n cut force-store-markers)
6127 "Cut the current subtree into the clipboard.
6128 With prefix arg N, cut this many sequential subtrees.
6129 This is a short-hand for marking the subtree and then copying it.
6130 If CUT is non-nil, actually cut the subtree.
6131 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6132 of some markers in the region, even if CUT is non-nil. This is
6133 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6134 (interactive "p")
6135 (let (beg end folded (beg0 (point)))
6136 (if (interactive-p)
6137 (org-back-to-heading nil) ; take what looks like a subtree
6138 (org-back-to-heading t)) ; take what is really there
6139 (org-back-over-empty-lines)
6140 (setq beg (point))
6141 (skip-chars-forward " \t\r\n")
6142 (save-match-data
6143 (save-excursion (outline-end-of-heading)
6144 (setq folded (org-invisible-p)))
6145 (condition-case nil
6146 (outline-forward-same-level (1- n))
6147 (error nil))
6148 (org-end-of-subtree t t))
6149 (org-back-over-empty-lines)
6150 (setq end (point))
6151 (goto-char beg0)
6152 (when (> end beg)
6153 (setq org-subtree-clip-folded folded)
6154 (when (or cut force-store-markers)
6155 (org-save-markers-in-region beg end))
6156 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6157 (setq org-subtree-clip (current-kill 0))
6158 (message "%s: Subtree(s) with %d characters"
6159 (if cut "Cut" "Copied")
6160 (length org-subtree-clip)))))
6162 (defun org-paste-subtree (&optional level tree for-yank)
6163 "Paste the clipboard as a subtree, with modification of headline level.
6164 The entire subtree is promoted or demoted in order to match a new headline
6165 level.
6167 If the cursor is at the beginning of a headline, the same level as
6168 that headline is used to paste the tree
6170 If not, the new level is derived from the *visible* headings
6171 before and after the insertion point, and taken to be the inferior headline
6172 level of the two. So if the previous visible heading is level 3 and the
6173 next is level 4 (or vice versa), level 4 will be used for insertion.
6174 This makes sure that the subtree remains an independent subtree and does
6175 not swallow low level entries.
6177 You can also force a different level, either by using a numeric prefix
6178 argument, or by inserting the heading marker by hand. For example, if the
6179 cursor is after \"*****\", then the tree will be shifted to level 5.
6181 If optional TREE is given, use this text instead of the kill ring.
6183 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6184 move back over whitespace before inserting, and move point to the end of
6185 the inserted text when done."
6186 (interactive "P")
6187 (unless (org-kill-is-subtree-p tree)
6188 (error "%s"
6189 (substitute-command-keys
6190 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6191 (let* ((visp (not (org-invisible-p)))
6192 (txt (or tree (and kill-ring (current-kill 0))))
6193 (^re (concat "^\\(" outline-regexp "\\)"))
6194 (re (concat "\\(" outline-regexp "\\)"))
6195 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6197 (old-level (if (string-match ^re txt)
6198 (- (match-end 0) (match-beginning 0) 1)
6199 -1))
6200 (force-level (cond (level (prefix-numeric-value level))
6201 ((and (looking-at "[ \t]*$")
6202 (string-match
6203 ^re_ (buffer-substring
6204 (point-at-bol) (point))))
6205 (- (match-end 1) (match-beginning 1)))
6206 ((and (bolp)
6207 (looking-at org-outline-regexp))
6208 (- (match-end 0) (point) 1))
6209 (t nil)))
6210 (previous-level (save-excursion
6211 (condition-case nil
6212 (progn
6213 (outline-previous-visible-heading 1)
6214 (if (looking-at re)
6215 (- (match-end 0) (match-beginning 0) 1)
6217 (error 1))))
6218 (next-level (save-excursion
6219 (condition-case nil
6220 (progn
6221 (or (looking-at outline-regexp)
6222 (outline-next-visible-heading 1))
6223 (if (looking-at re)
6224 (- (match-end 0) (match-beginning 0) 1)
6226 (error 1))))
6227 (new-level (or force-level (max previous-level next-level)))
6228 (shift (if (or (= old-level -1)
6229 (= new-level -1)
6230 (= old-level new-level))
6232 (- new-level old-level)))
6233 (delta (if (> shift 0) -1 1))
6234 (func (if (> shift 0) 'org-demote 'org-promote))
6235 (org-odd-levels-only nil)
6236 beg end newend)
6237 ;; Remove the forced level indicator
6238 (if force-level
6239 (delete-region (point-at-bol) (point)))
6240 ;; Paste
6241 (beginning-of-line 1)
6242 (unless for-yank (org-back-over-empty-lines))
6243 (setq beg (point))
6244 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6245 (insert-before-markers txt)
6246 (unless (string-match "\n\\'" txt) (insert "\n"))
6247 (setq newend (point))
6248 (org-reinstall-markers-in-region beg)
6249 (setq end (point))
6250 (goto-char beg)
6251 (skip-chars-forward " \t\n\r")
6252 (setq beg (point))
6253 (if (and (org-invisible-p) visp)
6254 (save-excursion (outline-show-heading)))
6255 ;; Shift if necessary
6256 (unless (= shift 0)
6257 (save-restriction
6258 (narrow-to-region beg end)
6259 (while (not (= shift 0))
6260 (org-map-region func (point-min) (point-max))
6261 (setq shift (+ delta shift)))
6262 (goto-char (point-min))
6263 (setq newend (point-max))))
6264 (when (or (interactive-p) for-yank)
6265 (message "Clipboard pasted as level %d subtree" new-level))
6266 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6267 kill-ring
6268 (eq org-subtree-clip (current-kill 0))
6269 org-subtree-clip-folded)
6270 ;; The tree was folded before it was killed/copied
6271 (hide-subtree))
6272 (and for-yank (goto-char newend))))
6274 (defun org-kill-is-subtree-p (&optional txt)
6275 "Check if the current kill is an outline subtree, or a set of trees.
6276 Returns nil if kill does not start with a headline, or if the first
6277 headline level is not the largest headline level in the tree.
6278 So this will actually accept several entries of equal levels as well,
6279 which is OK for `org-paste-subtree'.
6280 If optional TXT is given, check this string instead of the current kill."
6281 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6282 (start-level (and kill
6283 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6284 org-outline-regexp "\\)")
6285 kill)
6286 (- (match-end 2) (match-beginning 2) 1)))
6287 (re (concat "^" org-outline-regexp))
6288 (start (1+ (or (match-beginning 2) -1))))
6289 (if (not start-level)
6290 (progn
6291 nil) ;; does not even start with a heading
6292 (catch 'exit
6293 (while (setq start (string-match re kill (1+ start)))
6294 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6295 (throw 'exit nil)))
6296 t))))
6298 (defvar org-markers-to-move nil
6299 "Markers that should be moved with a cut-and-paste operation.
6300 Those markers are stored together with their positions relative to
6301 the start of the region.")
6303 (defun org-save-markers-in-region (beg end)
6304 "Check markers in region.
6305 If these markers are between BEG and END, record their position relative
6306 to BEG, so that after moving the block of text, we can put the markers back
6307 into place.
6308 This function gets called just before an entry or tree gets cut from the
6309 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6310 called immediately, to move the markers with the entries."
6311 (setq org-markers-to-move nil)
6312 (when (featurep 'org-clock)
6313 (org-clock-save-markers-for-cut-and-paste beg end))
6314 (when (featurep 'org-agenda)
6315 (org-agenda-save-markers-for-cut-and-paste beg end)))
6317 (defun org-check-and-save-marker (marker beg end)
6318 "Check if MARKER is between BEG and END.
6319 If yes, remember the marker and the distance to BEG."
6320 (when (and (marker-buffer marker)
6321 (equal (marker-buffer marker) (current-buffer)))
6322 (if (and (>= marker beg) (< marker end))
6323 (push (cons marker (- marker beg)) org-markers-to-move))))
6325 (defun org-reinstall-markers-in-region (beg)
6326 "Move all remembered markers to their position relative to BEG."
6327 (mapc (lambda (x)
6328 (move-marker (car x) (+ beg (cdr x))))
6329 org-markers-to-move)
6330 (setq org-markers-to-move nil))
6332 (defun org-narrow-to-subtree ()
6333 "Narrow buffer to the current subtree."
6334 (interactive)
6335 (save-excursion
6336 (save-match-data
6337 (narrow-to-region
6338 (progn (org-back-to-heading t) (point))
6339 (progn (org-end-of-subtree t) (point))))))
6341 (defun org-clone-subtree-with-time-shift (n &optional shift)
6342 "Clone the task (subtree) at point N times.
6343 The clones will be inserted as siblings.
6345 In interactive use, the user will be prompted for the number of clones
6346 to be produced, and for a time SHIFT, which may be a repeater as used
6347 in time stamps, for example `+3d'.
6349 When a valid repeater is given and the entry contains any time stamps,
6350 the clones will become a sequence in time, with time stamps in the
6351 subtree shifted for each clone produced. If SHIFT is nil or the
6352 empty string, time stamps will be left alone.
6354 If the original subtree did contain time stamps with a repeater,
6355 the following will happen:
6356 - the repeater will be removed in each clone
6357 - an additional clone will be produced, with the current, unshifted
6358 date(s) in the entry.
6359 - the original entry will be placed *after* all the clones, with
6360 repeater intact.
6361 - the start days in the repeater in the original entry will be shifted
6362 to past the last clone.
6363 I this way you can spell out a number of instances of a repeating task,
6364 and still retain the repeater to cover future instances of the task."
6365 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6366 (let (beg end template task
6367 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6368 (if (not (and (integerp n) (> n 0)))
6369 (error "Invalid number of replications %s" n))
6370 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6371 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6372 shift)))
6373 (error "Invalid shift specification %s" shift))
6374 (when doshift
6375 (setq shift-n (string-to-number (match-string 1 shift))
6376 shift-what (cdr (assoc (match-string 2 shift)
6377 '(("d" . day) ("w" . week)
6378 ("m" . month) ("y" . year))))))
6379 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6380 (setq nmin 1 nmax n)
6381 (org-back-to-heading t)
6382 (setq beg (point))
6383 (org-end-of-subtree t t)
6384 (setq end (point))
6385 (setq template (buffer-substring beg end))
6386 (when (and doshift
6387 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6388 (delete-region beg end)
6389 (setq end beg)
6390 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6391 (goto-char end)
6392 (loop for n from nmin to nmax do
6393 (if (not doshift)
6394 (setq task template)
6395 (with-temp-buffer
6396 (insert template)
6397 (org-mode)
6398 (goto-char (point-min))
6399 (while (re-search-forward org-ts-regexp-both nil t)
6400 (org-timestamp-change (* n shift-n) shift-what))
6401 (unless (= n n-no-remove)
6402 (goto-char (point-min))
6403 (while (re-search-forward org-ts-regexp nil t)
6404 (save-excursion
6405 (goto-char (match-beginning 0))
6406 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6407 (delete-region (match-beginning 1) (match-end 1))))))
6408 (setq task (buffer-string))))
6409 (insert task))
6410 (goto-char beg)))
6412 ;;; Outline Sorting
6414 (defun org-sort (with-case)
6415 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6416 Optional argument WITH-CASE means sort case-sensitively.
6417 With a double prefix argument, also remove duplicate entries."
6418 (interactive "P")
6419 (if (org-at-table-p)
6420 (org-call-with-arg 'org-table-sort-lines with-case)
6421 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6423 (defun org-sort-remove-invisible (s)
6424 (remove-text-properties 0 (length s) org-rm-props s)
6425 (while (string-match org-bracket-link-regexp s)
6426 (setq s (replace-match (if (match-end 2)
6427 (match-string 3 s)
6428 (match-string 1 s)) t t s)))
6431 (defvar org-priority-regexp) ; defined later in the file
6433 (defvar org-after-sorting-entries-or-items-hook nil
6434 "Hook that is run after a bunch of entries or items have been sorted.
6435 When children are sorted, the cursor is in the parent line when this
6436 hook gets called. When a region or a plain list is sorted, the cursor
6437 will be in the first entry of the sorted region/list.")
6439 (defun org-sort-entries-or-items
6440 (&optional with-case sorting-type getkey-func compare-func property)
6441 "Sort entries on a certain level of an outline tree, or plain list items.
6442 If there is an active region, the entries in the region are sorted.
6443 Else, if the cursor is before the first entry, sort the top-level items.
6444 Else, the children of the entry at point are sorted.
6445 If the cursor is at the first item in a plain list, the list items will be
6446 sorted.
6448 Sorting can be alphabetically, numerically, by date/time as given by
6449 a time stamp, by a property or by priority.
6451 The command prompts for the sorting type unless it has been given to the
6452 function through the SORTING-TYPE argument, which needs to a character,
6453 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6454 precise meaning of each character:
6456 n Numerically, by converting the beginning of the entry/item to a number.
6457 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6458 t By date/time, either the first active time stamp in the entry, or, if
6459 none exist, by the first inactive one.
6460 In items, only the first line will be chekced.
6461 s By the scheduled date/time.
6462 d By deadline date/time.
6463 c By creation time, which is assumed to be the first inactive time stamp
6464 at the beginning of a line.
6465 p By priority according to the cookie.
6466 r By the value of a property.
6468 Capital letters will reverse the sort order.
6470 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6471 called with point at the beginning of the record. It must return either
6472 a string or a number that should serve as the sorting key for that record.
6474 Comparing entries ignores case by default. However, with an optional argument
6475 WITH-CASE, the sorting considers case as well."
6476 (interactive "P")
6477 (let ((case-func (if with-case 'identity 'downcase))
6478 start beg end stars re re2
6479 txt what tmp plain-list-p)
6480 ;; Find beginning and end of region to sort
6481 (cond
6482 ((org-region-active-p)
6483 ;; we will sort the region
6484 (setq end (region-end)
6485 what "region")
6486 (goto-char (region-beginning))
6487 (if (not (org-on-heading-p)) (outline-next-heading))
6488 (setq start (point)))
6489 ((org-at-item-p)
6490 ;; we will sort this plain list
6491 (org-beginning-of-item-list) (setq start (point))
6492 (org-end-of-item-list) (setq end (point))
6493 (goto-char start)
6494 (setq plain-list-p t
6495 what "plain list"))
6496 ((or (org-on-heading-p)
6497 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6498 ;; we will sort the children of the current headline
6499 (org-back-to-heading)
6500 (setq start (point)
6501 end (progn (org-end-of-subtree t t)
6502 (org-back-over-empty-lines)
6503 (point))
6504 what "children")
6505 (goto-char start)
6506 (show-subtree)
6507 (outline-next-heading))
6509 ;; we will sort the top-level entries in this file
6510 (goto-char (point-min))
6511 (or (org-on-heading-p) (outline-next-heading))
6512 (setq start (point) end (point-max) what "top-level")
6513 (goto-char start)
6514 (show-all)))
6516 (setq beg (point))
6517 (if (>= beg end) (error "Nothing to sort"))
6519 (unless plain-list-p
6520 (looking-at "\\(\\*+\\)")
6521 (setq stars (match-string 1)
6522 re (concat "^" (regexp-quote stars) " +")
6523 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6524 txt (buffer-substring beg end))
6525 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6526 (if (and (not (equal stars "*")) (string-match re2 txt))
6527 (error "Region to sort contains a level above the first entry")))
6529 (unless sorting-type
6530 (message
6531 (if plain-list-p
6532 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6533 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
6534 [t]ime [s]cheduled [d]eadline [c]reated
6535 A/N/T/S/D/C/P/O/F means reversed:")
6536 what)
6537 (setq sorting-type (read-char-exclusive))
6539 (and (= (downcase sorting-type) ?f)
6540 (setq getkey-func
6541 (org-ido-completing-read "Sort using function: "
6542 obarray 'fboundp t nil nil))
6543 (setq getkey-func (intern getkey-func)))
6545 (and (= (downcase sorting-type) ?r)
6546 (setq property
6547 (org-ido-completing-read "Property: "
6548 (mapcar 'list (org-buffer-property-keys t))
6549 nil t))))
6551 (message "Sorting entries...")
6553 (save-restriction
6554 (narrow-to-region start end)
6556 (let ((dcst (downcase sorting-type))
6557 (case-fold-search nil)
6558 (now (current-time)))
6559 (sort-subr
6560 (/= dcst sorting-type)
6561 ;; This function moves to the beginning character of the "record" to
6562 ;; be sorted.
6563 (if plain-list-p
6564 (lambda nil
6565 (if (org-at-item-p) t (goto-char (point-max))))
6566 (lambda nil
6567 (if (re-search-forward re nil t)
6568 (goto-char (match-beginning 0))
6569 (goto-char (point-max)))))
6570 ;; This function moves to the last character of the "record" being
6571 ;; sorted.
6572 (if plain-list-p
6573 'org-end-of-item
6574 (lambda nil
6575 (save-match-data
6576 (condition-case nil
6577 (outline-forward-same-level 1)
6578 (error
6579 (goto-char (point-max)))))))
6581 ;; This function returns the value that gets sorted against.
6582 (if plain-list-p
6583 (lambda nil
6584 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6585 (cond
6586 ((= dcst ?n)
6587 (string-to-number (buffer-substring (match-end 0)
6588 (point-at-eol))))
6589 ((= dcst ?a)
6590 (buffer-substring (match-end 0) (point-at-eol)))
6591 ((= dcst ?t)
6592 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
6593 (re-search-forward org-ts-regexp-both
6594 (point-at-eol) t))
6595 (org-time-string-to-seconds (match-string 0))
6596 (time-to-seconds now)))
6597 ((= dcst ?f)
6598 (if getkey-func
6599 (progn
6600 (setq tmp (funcall getkey-func))
6601 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6602 tmp)
6603 (error "Invalid key function `%s'" getkey-func)))
6604 (t (error "Invalid sorting type `%c'" sorting-type)))))
6605 (lambda nil
6606 (cond
6607 ((= dcst ?n)
6608 (if (looking-at org-complex-heading-regexp)
6609 (string-to-number (match-string 4))
6610 nil))
6611 ((= dcst ?a)
6612 (if (looking-at org-complex-heading-regexp)
6613 (funcall case-func (match-string 4))
6614 nil))
6615 ((= dcst ?t)
6616 (let ((end (save-excursion (outline-next-heading) (point))))
6617 (if (or (re-search-forward org-ts-regexp end t)
6618 (re-search-forward org-ts-regexp-both end t))
6619 (org-time-string-to-seconds (match-string 0))
6620 (time-to-seconds now))))
6621 ((= dcst ?c)
6622 (let ((end (save-excursion (outline-next-heading) (point))))
6623 (if (re-search-forward
6624 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
6625 end t)
6626 (org-time-string-to-seconds (match-string 0))
6627 (time-to-seconds now))))
6628 ((= dcst ?s)
6629 (let ((end (save-excursion (outline-next-heading) (point))))
6630 (if (re-search-forward org-scheduled-time-regexp end t)
6631 (org-time-string-to-seconds (match-string 1))
6632 (time-to-seconds now))))
6633 ((= dcst ?d)
6634 (let ((end (save-excursion (outline-next-heading) (point))))
6635 (if (re-search-forward org-deadline-time-regexp end t)
6636 (org-time-string-to-seconds (match-string 1))
6637 (time-to-seconds now))))
6638 ((= dcst ?p)
6639 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6640 (string-to-char (match-string 2))
6641 org-default-priority))
6642 ((= dcst ?r)
6643 (or (org-entry-get nil property) ""))
6644 ((= dcst ?o)
6645 (if (looking-at org-complex-heading-regexp)
6646 (- 9999 (length (member (match-string 2)
6647 org-todo-keywords-1)))))
6648 ((= dcst ?f)
6649 (if getkey-func
6650 (progn
6651 (setq tmp (funcall getkey-func))
6652 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6653 tmp)
6654 (error "Invalid key function `%s'" getkey-func)))
6655 (t (error "Invalid sorting type `%c'" sorting-type)))))
6657 (cond
6658 ((= dcst ?a) 'string<)
6659 ((= dcst ?f) compare-func)
6660 ((member dcst '(?p ?t ?s ?d ?c)) '<)
6661 (t nil)))))
6662 (run-hooks 'org-after-sorting-entries-or-items-hook)
6663 (message "Sorting entries...done")))
6665 (defun org-do-sort (table what &optional with-case sorting-type)
6666 "Sort TABLE of WHAT according to SORTING-TYPE.
6667 The user will be prompted for the SORTING-TYPE if the call to this
6668 function does not specify it. WHAT is only for the prompt, to indicate
6669 what is being sorted. The sorting key will be extracted from
6670 the car of the elements of the table.
6671 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6672 (unless sorting-type
6673 (message
6674 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6675 what)
6676 (setq sorting-type (read-char-exclusive)))
6677 (let ((dcst (downcase sorting-type))
6678 extractfun comparefun)
6679 ;; Define the appropriate functions
6680 (cond
6681 ((= dcst ?n)
6682 (setq extractfun 'string-to-number
6683 comparefun (if (= dcst sorting-type) '< '>)))
6684 ((= dcst ?a)
6685 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6686 (lambda(x) (downcase (org-sort-remove-invisible x))))
6687 comparefun (if (= dcst sorting-type)
6688 'string<
6689 (lambda (a b) (and (not (string< a b))
6690 (not (string= a b)))))))
6691 ((= dcst ?t)
6692 (setq extractfun
6693 (lambda (x)
6694 (if (or (string-match org-ts-regexp x)
6695 (string-match org-ts-regexp-both x))
6696 (time-to-seconds
6697 (org-time-string-to-time (match-string 0 x)))
6699 comparefun (if (= dcst sorting-type) '< '>)))
6700 (t (error "Invalid sorting type `%c'" sorting-type)))
6702 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6703 table)
6704 (lambda (a b) (funcall comparefun (car a) (car b))))))
6707 ;;; The orgstruct minor mode
6709 ;; Define a minor mode which can be used in other modes in order to
6710 ;; integrate the org-mode structure editing commands.
6712 ;; This is really a hack, because the org-mode structure commands use
6713 ;; keys which normally belong to the major mode. Here is how it
6714 ;; works: The minor mode defines all the keys necessary to operate the
6715 ;; structure commands, but wraps the commands into a function which
6716 ;; tests if the cursor is currently at a headline or a plain list
6717 ;; item. If that is the case, the structure command is used,
6718 ;; temporarily setting many Org-mode variables like regular
6719 ;; expressions for filling etc. However, when any of those keys is
6720 ;; used at a different location, function uses `key-binding' to look
6721 ;; up if the key has an associated command in another currently active
6722 ;; keymap (minor modes, major mode, global), and executes that
6723 ;; command. There might be problems if any of the keys is otherwise
6724 ;; used as a prefix key.
6726 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6727 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6728 ;; addresses this by checking explicitly for both bindings.
6730 (defvar orgstruct-mode-map (make-sparse-keymap)
6731 "Keymap for the minor `orgstruct-mode'.")
6733 (defvar org-local-vars nil
6734 "List of local variables, for use by `orgstruct-mode'")
6736 ;;;###autoload
6737 (define-minor-mode orgstruct-mode
6738 "Toggle the minor more `orgstruct-mode'.
6739 This mode is for using Org-mode structure commands in other modes.
6740 The following key behave as if Org-mode was active, if the cursor
6741 is on a headline, or on a plain list item (both in the definition
6742 of Org-mode).
6744 M-up Move entry/item up
6745 M-down Move entry/item down
6746 M-left Promote
6747 M-right Demote
6748 M-S-up Move entry/item up
6749 M-S-down Move entry/item down
6750 M-S-left Promote subtree
6751 M-S-right Demote subtree
6752 M-q Fill paragraph and items like in Org-mode
6753 C-c ^ Sort entries
6754 C-c - Cycle list bullet
6755 TAB Cycle item visibility
6756 M-RET Insert new heading/item
6757 S-M-RET Insert new TODO heading / Checkbox item
6758 C-c C-c Set tags / toggle checkbox"
6759 nil " OrgStruct" nil
6760 (org-load-modules-maybe)
6761 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6763 ;;;###autoload
6764 (defun turn-on-orgstruct ()
6765 "Unconditionally turn on `orgstruct-mode'."
6766 (orgstruct-mode 1))
6768 (defun orgstruct++-mode (&optional arg)
6769 "Toggle `orgstruct-mode', the enhanced version of it.
6770 In addition to setting orgstruct-mode, this also exports all indentation
6771 and autofilling variables from org-mode into the buffer. It will also
6772 recognize item context in multiline items.
6773 Note that turning off orgstruct-mode will *not* remove the
6774 indentation/paragraph settings. This can only be done by refreshing the
6775 major mode, for example with \\[normal-mode]."
6776 (interactive "P")
6777 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6778 (if (< arg 1)
6779 (orgstruct-mode -1)
6780 (orgstruct-mode 1)
6781 (let (var val)
6782 (mapc
6783 (lambda (x)
6784 (when (string-match
6785 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6786 (symbol-name (car x)))
6787 (setq var (car x) val (nth 1 x))
6788 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6789 org-local-vars)
6790 (org-set-local 'orgstruct-is-++ t))))
6792 (defvar orgstruct-is-++ nil
6793 "Is orgstruct-mode in ++ version in the current-buffer?")
6794 (make-variable-buffer-local 'orgstruct-is-++)
6796 ;;;###autoload
6797 (defun turn-on-orgstruct++ ()
6798 "Unconditionally turn on `orgstruct++-mode'."
6799 (orgstruct++-mode 1))
6801 (defun orgstruct-error ()
6802 "Error when there is no default binding for a structure key."
6803 (interactive)
6804 (error "This key has no function outside structure elements"))
6806 (defun orgstruct-setup ()
6807 "Setup orgstruct keymaps."
6808 (let ((nfunc 0)
6809 (bindings
6810 (list
6811 '([(meta up)] org-metaup)
6812 '([(meta down)] org-metadown)
6813 '([(meta left)] org-metaleft)
6814 '([(meta right)] org-metaright)
6815 '([(meta shift up)] org-shiftmetaup)
6816 '([(meta shift down)] org-shiftmetadown)
6817 '([(meta shift left)] org-shiftmetaleft)
6818 '([(meta shift right)] org-shiftmetaright)
6819 '([?\e (up)] org-metaup)
6820 '([?\e (down)] org-metadown)
6821 '([?\e (left)] org-metaleft)
6822 '([?\e (right)] org-metaright)
6823 '([?\e (shift up)] org-shiftmetaup)
6824 '([?\e (shift down)] org-shiftmetadown)
6825 '([?\e (shift left)] org-shiftmetaleft)
6826 '([?\e (shift right)] org-shiftmetaright)
6827 '([(shift up)] org-shiftup)
6828 '([(shift down)] org-shiftdown)
6829 '([(shift left)] org-shiftleft)
6830 '([(shift right)] org-shiftright)
6831 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6832 '("\M-q" fill-paragraph)
6833 '("\C-c^" org-sort)
6834 '("\C-c-" org-cycle-list-bullet)))
6835 elt key fun cmd)
6836 (while (setq elt (pop bindings))
6837 (setq nfunc (1+ nfunc))
6838 (setq key (org-key (car elt))
6839 fun (nth 1 elt)
6840 cmd (orgstruct-make-binding fun nfunc key))
6841 (org-defkey orgstruct-mode-map key cmd))
6843 ;; Special treatment needed for TAB and RET
6844 (org-defkey orgstruct-mode-map [(tab)]
6845 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6846 (org-defkey orgstruct-mode-map "\C-i"
6847 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6849 (org-defkey orgstruct-mode-map "\M-\C-m"
6850 (orgstruct-make-binding 'org-insert-heading 105
6851 "\M-\C-m" [(meta return)]))
6852 (org-defkey orgstruct-mode-map [(meta return)]
6853 (orgstruct-make-binding 'org-insert-heading 106
6854 [(meta return)] "\M-\C-m"))
6856 (org-defkey orgstruct-mode-map [(shift meta return)]
6857 (orgstruct-make-binding 'org-insert-todo-heading 107
6858 [(meta return)] "\M-\C-m"))
6860 (org-defkey orgstruct-mode-map "\e\C-m"
6861 (orgstruct-make-binding 'org-insert-heading 108
6862 "\e\C-m" [?\e (return)]))
6863 (org-defkey orgstruct-mode-map [?\e (return)]
6864 (orgstruct-make-binding 'org-insert-heading 109
6865 [?\e (return)] "\e\C-m"))
6866 (org-defkey orgstruct-mode-map [?\e (shift return)]
6867 (orgstruct-make-binding 'org-insert-todo-heading 110
6868 [?\e (return)] "\e\C-m"))
6870 (unless org-local-vars
6871 (setq org-local-vars (org-get-local-variables)))
6875 (defun orgstruct-make-binding (fun n &rest keys)
6876 "Create a function for binding in the structure minor mode.
6877 FUN is the command to call inside a table. N is used to create a unique
6878 command name. KEYS are keys that should be checked in for a command
6879 to execute outside of tables."
6880 (eval
6881 (list 'defun
6882 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6883 '(arg)
6884 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6885 "Outside of structure, run the binding of `"
6886 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6887 "'.")
6888 '(interactive "p")
6889 (list 'if
6890 `(org-context-p 'headline 'item
6891 (and orgstruct-is-++
6892 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
6893 'item-body))
6894 (list 'org-run-like-in-org-mode (list 'quote fun))
6895 (list 'let '(orgstruct-mode)
6896 (list 'call-interactively
6897 (append '(or)
6898 (mapcar (lambda (k)
6899 (list 'key-binding k))
6900 keys)
6901 '('orgstruct-error))))))))
6903 (defun org-context-p (&rest contexts)
6904 "Check if local context is any of CONTEXTS.
6905 Possible values in the list of contexts are `table', `headline', and `item'."
6906 (let ((pos (point)))
6907 (goto-char (point-at-bol))
6908 (prog1 (or (and (memq 'table contexts)
6909 (looking-at "[ \t]*|"))
6910 (and (memq 'headline contexts)
6911 ;;????????? (looking-at "\\*+"))
6912 (looking-at outline-regexp))
6913 (and (memq 'item contexts)
6914 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
6915 (and (memq 'item-body contexts)
6916 (org-in-item-p)))
6917 (goto-char pos))))
6919 (defun org-get-local-variables ()
6920 "Return a list of all local variables in an org-mode buffer."
6921 (let (varlist)
6922 (with-current-buffer (get-buffer-create "*Org tmp*")
6923 (erase-buffer)
6924 (org-mode)
6925 (setq varlist (buffer-local-variables)))
6926 (kill-buffer "*Org tmp*")
6927 (delq nil
6928 (mapcar
6929 (lambda (x)
6930 (setq x
6931 (if (symbolp x)
6932 (list x)
6933 (list (car x) (list 'quote (cdr x)))))
6934 (if (string-match
6935 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6936 (symbol-name (car x)))
6937 x nil))
6938 varlist))))
6940 ;;;###autoload
6941 (defun org-run-like-in-org-mode (cmd)
6942 "Run a command, pretending that the current buffer is in Org-mode.
6943 This will temporarily bind local variables that are typically bound in
6944 Org-mode to the values they have in Org-mode, and then interactively
6945 call CMD."
6946 (org-load-modules-maybe)
6947 (unless org-local-vars
6948 (setq org-local-vars (org-get-local-variables)))
6949 (eval (list 'let org-local-vars
6950 (list 'call-interactively (list 'quote cmd)))))
6952 ;;;; Archiving
6954 (defun org-get-category (&optional pos)
6955 "Get the category applying to position POS."
6956 (get-text-property (or pos (point)) 'org-category))
6958 (defun org-refresh-category-properties ()
6959 "Refresh category text properties in the buffer."
6960 (let ((def-cat (cond
6961 ((null org-category)
6962 (if buffer-file-name
6963 (file-name-sans-extension
6964 (file-name-nondirectory buffer-file-name))
6965 "???"))
6966 ((symbolp org-category) (symbol-name org-category))
6967 (t org-category)))
6968 beg end cat pos optionp)
6969 (org-unmodified
6970 (save-excursion
6971 (save-restriction
6972 (widen)
6973 (goto-char (point-min))
6974 (put-text-property (point) (point-max) 'org-category def-cat)
6975 (while (re-search-forward
6976 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6977 (setq pos (match-end 0)
6978 optionp (equal (char-after (match-beginning 0)) ?#)
6979 cat (org-trim (match-string 2)))
6980 (if optionp
6981 (setq beg (point-at-bol) end (point-max))
6982 (org-back-to-heading t)
6983 (setq beg (point) end (org-end-of-subtree t t)))
6984 (put-text-property beg end 'org-category cat)
6985 (goto-char pos)))))))
6988 ;;;; Link Stuff
6990 ;;; Link abbreviations
6992 (defun org-link-expand-abbrev (link)
6993 "Apply replacements as defined in `org-link-abbrev-alist."
6994 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6995 (let* ((key (match-string 1 link))
6996 (as (or (assoc key org-link-abbrev-alist-local)
6997 (assoc key org-link-abbrev-alist)))
6998 (tag (and (match-end 2) (match-string 3 link)))
6999 rpl)
7000 (if (not as)
7001 link
7002 (setq rpl (cdr as))
7003 (cond
7004 ((symbolp rpl) (funcall rpl tag))
7005 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7006 ((string-match "%h" rpl)
7007 (replace-match (url-hexify-string (or tag "")) t t rpl))
7008 (t (concat rpl tag)))))
7009 link))
7011 ;;; Storing and inserting links
7013 (defvar org-insert-link-history nil
7014 "Minibuffer history for links inserted with `org-insert-link'.")
7016 (defvar org-stored-links nil
7017 "Contains the links stored with `org-store-link'.")
7019 (defvar org-store-link-plist nil
7020 "Plist with info about the most recently link created with `org-store-link'.")
7022 (defvar org-link-protocols nil
7023 "Link protocols added to Org-mode using `org-add-link-type'.")
7025 (defvar org-store-link-functions nil
7026 "List of functions that are called to create and store a link.
7027 Each function will be called in turn until one returns a non-nil
7028 value. Each function should check if it is responsible for creating
7029 this link (for example by looking at the major mode).
7030 If not, it must exit and return nil.
7031 If yes, it should return a non-nil value after a calling
7032 `org-store-link-props' with a list of properties and values.
7033 Special properties are:
7035 :type The link prefix. like \"http\". This must be given.
7036 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7037 This is obligatory as well.
7038 :description Optional default description for the second pair
7039 of brackets in an Org-mode link. The user can still change
7040 this when inserting this link into an Org-mode buffer.
7042 In addition to these, any additional properties can be specified
7043 and then used in remember templates.")
7045 (defun org-add-link-type (type &optional follow export)
7046 "Add TYPE to the list of `org-link-types'.
7047 Re-compute all regular expressions depending on `org-link-types'
7049 FOLLOW and EXPORT are two functions.
7051 FOLLOW should take the link path as the single argument and do whatever
7052 is necessary to follow the link, for example find a file or display
7053 a mail message.
7055 EXPORT should format the link path for export to one of the export formats.
7056 It should be a function accepting three arguments:
7058 path the path of the link, the text after the prefix (like \"http:\")
7059 desc the description of the link, if any, nil if there was no description
7060 format the export format, a symbol like `html' or `latex'.
7062 The function may use the FORMAT information to return different values
7063 depending on the format. The return value will be put literally into
7064 the exported file.
7065 Org-mode has a built-in default for exporting links. If you are happy with
7066 this default, there is no need to define an export function for the link
7067 type. For a simple example of an export function, see `org-bbdb.el'."
7068 (add-to-list 'org-link-types type t)
7069 (org-make-link-regexps)
7070 (if (assoc type org-link-protocols)
7071 (setcdr (assoc type org-link-protocols) (list follow export))
7072 (push (list type follow export) org-link-protocols)))
7074 ;;;###autoload
7075 (defun org-store-link (arg)
7076 "\\<org-mode-map>Store an org-link to the current location.
7077 This link is added to `org-stored-links' and can later be inserted
7078 into an org-buffer with \\[org-insert-link].
7080 For some link types, a prefix arg is interpreted:
7081 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7082 For file links, arg negates `org-context-in-file-links'."
7083 (interactive "P")
7084 (org-load-modules-maybe)
7085 (setq org-store-link-plist nil) ; reset
7086 (let ((outline-regexp (org-get-limited-outline-regexp))
7087 link cpltxt desc description search txt custom-id)
7088 (cond
7090 ((run-hook-with-args-until-success 'org-store-link-functions)
7091 (setq link (plist-get org-store-link-plist :link)
7092 desc (or (plist-get org-store-link-plist :description) link)))
7094 ((equal (buffer-name) "*Org Edit Src Example*")
7095 (let (label gc)
7096 (while (or (not label)
7097 (save-excursion
7098 (save-restriction
7099 (widen)
7100 (goto-char (point-min))
7101 (re-search-forward
7102 (regexp-quote (format org-coderef-label-format label))
7103 nil t))))
7104 (when label (message "Label exists already") (sit-for 2))
7105 (setq label (read-string "Code line label: " label)))
7106 (end-of-line 1)
7107 (setq link (format org-coderef-label-format label))
7108 (setq gc (- 79 (length link)))
7109 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7110 (insert link)
7111 (setq link (concat "(" label ")") desc nil)))
7113 ((eq major-mode 'calendar-mode)
7114 (let ((cd (calendar-cursor-to-date)))
7115 (setq link
7116 (format-time-string
7117 (car org-time-stamp-formats)
7118 (apply 'encode-time
7119 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7120 nil nil nil))))
7121 (org-store-link-props :type "calendar" :date cd)))
7123 ((eq major-mode 'w3-mode)
7124 (setq cpltxt (if (and (buffer-name)
7125 (not (string-match "Untitled" (buffer-name))))
7126 (buffer-name)
7127 (url-view-url t))
7128 link (org-make-link (url-view-url t)))
7129 (org-store-link-props :type "w3" :url (url-view-url t)))
7131 ((eq major-mode 'w3m-mode)
7132 (setq cpltxt (or w3m-current-title w3m-current-url)
7133 link (org-make-link w3m-current-url))
7134 (org-store-link-props :type "w3m" :url (url-view-url t)))
7136 ((setq search (run-hook-with-args-until-success
7137 'org-create-file-search-functions))
7138 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7139 "::" search))
7140 (setq cpltxt (or description link)))
7142 ((eq major-mode 'image-mode)
7143 (setq cpltxt (concat "file:"
7144 (abbreviate-file-name buffer-file-name))
7145 link (org-make-link cpltxt))
7146 (org-store-link-props :type "image" :file buffer-file-name))
7148 ((eq major-mode 'dired-mode)
7149 ;; link to the file in the current line
7150 (setq cpltxt (concat "file:"
7151 (abbreviate-file-name
7152 (expand-file-name
7153 (dired-get-filename nil t))))
7154 link (org-make-link cpltxt)))
7156 ((and buffer-file-name (org-mode-p))
7157 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7158 (cond
7159 ((org-in-regexp "<<\\(.*?\\)>>")
7160 (setq cpltxt
7161 (concat "file:"
7162 (abbreviate-file-name buffer-file-name)
7163 "::" (match-string 1))
7164 link (org-make-link cpltxt)))
7165 ((and (featurep 'org-id)
7166 (or (eq org-link-to-org-use-id t)
7167 (and (eq org-link-to-org-use-id 'create-if-interactive)
7168 (interactive-p))
7169 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7170 (interactive-p)
7171 (not custom-id))
7172 (and org-link-to-org-use-id
7173 (condition-case nil
7174 (org-entry-get nil "ID")
7175 (error nil)))))
7176 ;; We can make a link using the ID.
7177 (setq link (condition-case nil
7178 (prog1 (org-id-store-link)
7179 (setq desc (plist-get org-store-link-plist
7180 :description)))
7181 (error
7182 ;; probably before first headline, link to file only
7183 (concat "file:"
7184 (abbreviate-file-name buffer-file-name))))))
7186 ;; Just link to current headline
7187 (setq cpltxt (concat "file:"
7188 (abbreviate-file-name buffer-file-name)))
7189 ;; Add a context search string
7190 (when (org-xor org-context-in-file-links arg)
7191 (setq txt (cond
7192 ((org-on-heading-p) nil)
7193 ((org-region-active-p)
7194 (buffer-substring (region-beginning) (region-end)))
7195 (t nil)))
7196 (when (or (null txt) (string-match "\\S-" txt))
7197 (setq cpltxt
7198 (concat cpltxt "::"
7199 (condition-case nil
7200 (org-make-org-heading-search-string txt)
7201 (error "")))
7202 desc (or (nth 4 (org-heading-components)) "NONE"))))
7203 (if (string-match "::\\'" cpltxt)
7204 (setq cpltxt (substring cpltxt 0 -2)))
7205 (setq link (org-make-link cpltxt)))))
7207 ((buffer-file-name (buffer-base-buffer))
7208 ;; Just link to this file here.
7209 (setq cpltxt (concat "file:"
7210 (abbreviate-file-name
7211 (buffer-file-name (buffer-base-buffer)))))
7212 ;; Add a context string
7213 (when (org-xor org-context-in-file-links arg)
7214 (setq txt (if (org-region-active-p)
7215 (buffer-substring (region-beginning) (region-end))
7216 (buffer-substring (point-at-bol) (point-at-eol))))
7217 ;; Only use search option if there is some text.
7218 (when (string-match "\\S-" txt)
7219 (setq cpltxt
7220 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7221 desc "NONE")))
7222 (setq link (org-make-link cpltxt)))
7224 ((interactive-p)
7225 (error "Cannot link to a buffer which is not visiting a file"))
7227 (t (setq link nil)))
7229 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7230 (setq link (or link cpltxt)
7231 desc (or desc cpltxt))
7232 (if (equal desc "NONE") (setq desc nil))
7234 (if (and (or (interactive-p) executing-kbd-macro) link)
7235 (progn
7236 (setq org-stored-links
7237 (cons (list link desc) org-stored-links))
7238 (message "Stored: %s" (or desc link))
7239 (when custom-id
7240 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7241 "::#" custom-id))
7242 (setq org-stored-links
7243 (cons (list link desc) org-stored-links))))
7244 (and link (org-make-link-string link desc)))))
7246 (defun org-store-link-props (&rest plist)
7247 "Store link properties, extract names and addresses."
7248 (let (x adr)
7249 (when (setq x (plist-get plist :from))
7250 (setq adr (mail-extract-address-components x))
7251 (setq plist (plist-put plist :fromname (car adr)))
7252 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7253 (when (setq x (plist-get plist :to))
7254 (setq adr (mail-extract-address-components x))
7255 (setq plist (plist-put plist :toname (car adr)))
7256 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7257 (let ((from (plist-get plist :from))
7258 (to (plist-get plist :to)))
7259 (when (and from to org-from-is-user-regexp)
7260 (setq plist
7261 (plist-put plist :fromto
7262 (if (string-match org-from-is-user-regexp from)
7263 (concat "to %t")
7264 (concat "from %f"))))))
7265 (setq org-store-link-plist plist))
7267 (defun org-add-link-props (&rest plist)
7268 "Add these properties to the link property list."
7269 (let (key value)
7270 (while plist
7271 (setq key (pop plist) value (pop plist))
7272 (setq org-store-link-plist
7273 (plist-put org-store-link-plist key value)))))
7275 (defun org-email-link-description (&optional fmt)
7276 "Return the description part of an email link.
7277 This takes information from `org-store-link-plist' and formats it
7278 according to FMT (default from `org-email-link-description-format')."
7279 (setq fmt (or fmt org-email-link-description-format))
7280 (let* ((p org-store-link-plist)
7281 (to (plist-get p :toaddress))
7282 (from (plist-get p :fromaddress))
7283 (table
7284 (list
7285 (cons "%c" (plist-get p :fromto))
7286 (cons "%F" (plist-get p :from))
7287 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7288 (cons "%T" (plist-get p :to))
7289 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7290 (cons "%s" (plist-get p :subject))
7291 (cons "%m" (plist-get p :message-id)))))
7292 (when (string-match "%c" fmt)
7293 ;; Check if the user wrote this message
7294 (if (and org-from-is-user-regexp from to
7295 (save-match-data (string-match org-from-is-user-regexp from)))
7296 (setq fmt (replace-match "to %t" t t fmt))
7297 (setq fmt (replace-match "from %f" t t fmt))))
7298 (org-replace-escapes fmt table)))
7300 (defun org-make-org-heading-search-string (&optional string heading)
7301 "Make search string for STRING or current headline."
7302 (interactive)
7303 (let ((s (or string (org-get-heading))))
7304 (unless (and string (not heading))
7305 ;; We are using a headline, clean up garbage in there.
7306 (if (string-match org-todo-regexp s)
7307 (setq s (replace-match "" t t s)))
7308 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7309 (setq s (replace-match "" t t s)))
7310 (setq s (org-trim s))
7311 (if (string-match (concat "^\\(" org-quote-string "\\|"
7312 org-comment-string "\\)") s)
7313 (setq s (replace-match "" t t s)))
7314 (while (string-match org-ts-regexp s)
7315 (setq s (replace-match "" t t s))))
7316 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7317 (setq s (replace-match " " t t s)))
7318 (or string (setq s (concat "*" s))) ; Add * for headlines
7319 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7321 (defun org-make-link (&rest strings)
7322 "Concatenate STRINGS."
7323 (apply 'concat strings))
7325 (defun org-make-link-string (link &optional description)
7326 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7327 (unless (string-match "\\S-" link)
7328 (error "Empty link"))
7329 (when (stringp description)
7330 ;; Remove brackets from the description, they are fatal.
7331 (while (string-match "\\[" description)
7332 (setq description (replace-match "{" t t description)))
7333 (while (string-match "\\]" description)
7334 (setq description (replace-match "}" t t description))))
7335 (when (equal (org-link-escape link) description)
7336 ;; No description needed, it is identical
7337 (setq description nil))
7338 (when (and (not description)
7339 (not (equal link (org-link-escape link))))
7340 (setq description (org-extract-attributes link)))
7341 (concat "[[" (org-link-escape link) "]"
7342 (if description (concat "[" description "]") "")
7343 "]"))
7345 (defconst org-link-escape-chars
7346 '((?\ . "%20")
7347 (?\[ . "%5B")
7348 (?\] . "%5D")
7349 (?\340 . "%E0") ; `a
7350 (?\342 . "%E2") ; ^a
7351 (?\347 . "%E7") ; ,c
7352 (?\350 . "%E8") ; `e
7353 (?\351 . "%E9") ; 'e
7354 (?\352 . "%EA") ; ^e
7355 (?\356 . "%EE") ; ^i
7356 (?\364 . "%F4") ; ^o
7357 (?\371 . "%F9") ; `u
7358 (?\373 . "%FB") ; ^u
7359 (?\; . "%3B")
7360 (?? . "%3F")
7361 (?= . "%3D")
7362 (?+ . "%2B")
7364 "Association list of escapes for some characters problematic in links.
7365 This is the list that is used for internal purposes.")
7367 (defvar org-url-encoding-use-url-hexify nil)
7369 (defconst org-link-escape-chars-browser
7370 '((?\ . "%20")) ; 32 for the SPC char
7371 "Association list of escapes for some characters problematic in links.
7372 This is the list that is used before handing over to the browser.")
7374 (defun org-link-escape (text &optional table)
7375 "Escape characters in TEXT that are problematic for links."
7376 (if org-url-encoding-use-url-hexify
7377 (url-hexify-string text)
7378 (setq table (or table org-link-escape-chars))
7379 (when text
7380 (let ((re (mapconcat (lambda (x) (regexp-quote
7381 (char-to-string (car x))))
7382 table "\\|")))
7383 (while (string-match re text)
7384 (setq text
7385 (replace-match
7386 (cdr (assoc (string-to-char (match-string 0 text))
7387 table))
7388 t t text)))
7389 text))))
7391 (defun org-link-unescape (text &optional table)
7392 "Reverse the action of `org-link-escape'."
7393 (if org-url-encoding-use-url-hexify
7394 (url-unhex-string text)
7395 (setq table (or table org-link-escape-chars))
7396 (when text
7397 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7398 table "\\|")))
7399 (while (string-match re text)
7400 (setq text
7401 (replace-match
7402 (char-to-string (car (rassoc (match-string 0 text) table)))
7403 t t text)))
7404 text))))
7406 (defun org-xor (a b)
7407 "Exclusive or."
7408 (if a (not b) b))
7410 (defun org-fixup-message-id-for-http (s)
7411 "Replace special characters in a message id, so it can be used in an http query."
7412 (while (string-match "<" s)
7413 (setq s (replace-match "%3C" t t s)))
7414 (while (string-match ">" s)
7415 (setq s (replace-match "%3E" t t s)))
7416 (while (string-match "@" s)
7417 (setq s (replace-match "%40" t t s)))
7420 ;;;###autoload
7421 (defun org-insert-link-global ()
7422 "Insert a link like Org-mode does.
7423 This command can be called in any mode to insert a link in Org-mode syntax."
7424 (interactive)
7425 (org-load-modules-maybe)
7426 (org-run-like-in-org-mode 'org-insert-link))
7428 (defun org-insert-link (&optional complete-file link-location)
7429 "Insert a link. At the prompt, enter the link.
7431 Completion can be used to insert any of the link protocol prefixes like
7432 http or ftp in use.
7434 The history can be used to select a link previously stored with
7435 `org-store-link'. When the empty string is entered (i.e. if you just
7436 press RET at the prompt), the link defaults to the most recently
7437 stored link. As SPC triggers completion in the minibuffer, you need to
7438 use M-SPC or C-q SPC to force the insertion of a space character.
7440 You will also be prompted for a description, and if one is given, it will
7441 be displayed in the buffer instead of the link.
7443 If there is already a link at point, this command will allow you to edit link
7444 and description parts.
7446 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7447 be selected using completion. The path to the file will be relative to the
7448 current directory if the file is in the current directory or a subdirectory.
7449 Otherwise, the link will be the absolute path as completed in the minibuffer
7450 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7451 option `org-link-file-path-type'.
7453 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7454 the current directory or below.
7456 With three \\[universal-argument] prefixes, negate the meaning of
7457 `org-keep-stored-link-after-insertion'.
7459 If `org-make-link-description-function' is non-nil, this function will be
7460 called with the link target, and the result will be the default
7461 link description.
7463 If the LINK-LOCATION parameter is non-nil, this value will be
7464 used as the link location instead of reading one interactively."
7465 (interactive "P")
7466 (let* ((wcf (current-window-configuration))
7467 (region (if (org-region-active-p)
7468 (buffer-substring (region-beginning) (region-end))))
7469 (remove (and region (list (region-beginning) (region-end))))
7470 (desc region)
7471 tmphist ; byte-compile incorrectly complains about this
7472 (link link-location)
7473 entry file all-prefixes)
7474 (cond
7475 (link-location) ; specified by arg, just use it.
7476 ((org-in-regexp org-bracket-link-regexp 1)
7477 ;; We do have a link at point, and we are going to edit it.
7478 (setq remove (list (match-beginning 0) (match-end 0)))
7479 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7480 (setq link (read-string "Link: "
7481 (org-link-unescape
7482 (org-match-string-no-properties 1)))))
7483 ((or (org-in-regexp org-angle-link-re)
7484 (org-in-regexp org-plain-link-re))
7485 ;; Convert to bracket link
7486 (setq remove (list (match-beginning 0) (match-end 0))
7487 link (read-string "Link: "
7488 (org-remove-angle-brackets (match-string 0)))))
7489 ((member complete-file '((4) (16)))
7490 ;; Completing read for file names.
7491 (setq link (org-file-complete-link complete-file)))
7493 ;; Read link, with completion for stored links.
7494 (with-output-to-temp-buffer "*Org Links*"
7495 (princ "Insert a link.
7496 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
7497 (when org-stored-links
7498 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7499 (princ (mapconcat
7500 (lambda (x)
7501 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7502 (reverse org-stored-links) "\n"))))
7503 (let ((cw (selected-window)))
7504 (select-window (get-buffer-window "*Org Links*"))
7505 (setq truncate-lines t)
7506 (unless (pos-visible-in-window-p (point-max))
7507 (org-fit-window-to-buffer))
7508 (and (window-live-p cw) (select-window cw)))
7509 ;; Fake a link history, containing the stored links.
7510 (setq tmphist (append (mapcar 'car org-stored-links)
7511 org-insert-link-history))
7512 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
7513 (mapcar 'car org-link-abbrev-alist)
7514 org-link-types))
7515 (unwind-protect
7516 (progn
7517 (setq link
7518 (let ((org-completion-use-ido nil))
7519 (org-completing-read
7520 "Link: "
7521 (append
7522 (mapcar (lambda (x) (list (concat x ":")))
7523 all-prefixes)
7524 (mapcar 'car org-stored-links))
7525 nil nil nil
7526 'tmphist
7527 (car (car org-stored-links)))))
7528 (if (or (member link all-prefixes)
7529 (and (equal ":" (substring link -1))
7530 (member (substring link 0 -1) all-prefixes)
7531 (setq link (substring link 0 -1))))
7532 (setq link (org-link-try-special-completion link))))
7533 (set-window-configuration wcf)
7534 (kill-buffer "*Org Links*"))
7535 (setq entry (assoc link org-stored-links))
7536 (or entry (push link org-insert-link-history))
7537 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7538 (not org-keep-stored-link-after-insertion))
7539 (setq org-stored-links (delq (assoc link org-stored-links)
7540 org-stored-links)))
7541 (setq desc (or desc (nth 1 entry)))))
7543 (if (string-match org-plain-link-re link)
7544 ;; URL-like link, normalize the use of angular brackets.
7545 (setq link (org-make-link (org-remove-angle-brackets link))))
7547 ;; Check if we are linking to the current file with a search option
7548 ;; If yes, simplify the link by using only the search option.
7549 (when (and buffer-file-name
7550 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7551 (let* ((path (match-string 1 link))
7552 (case-fold-search nil)
7553 (search (match-string 2 link)))
7554 (save-match-data
7555 (if (equal (file-truename buffer-file-name) (file-truename path))
7556 ;; We are linking to this same file, with a search option
7557 (setq link search)))))
7559 ;; Check if we can/should use a relative path. If yes, simplify the link
7560 (when (string-match "^file:\\(.*\\)" link)
7561 (let* ((path (match-string 1 link))
7562 (origpath path)
7563 (case-fold-search nil))
7564 (cond
7565 ((or (eq org-link-file-path-type 'absolute)
7566 (equal complete-file '(16)))
7567 (setq path (abbreviate-file-name (expand-file-name path))))
7568 ((eq org-link-file-path-type 'noabbrev)
7569 (setq path (expand-file-name path)))
7570 ((eq org-link-file-path-type 'relative)
7571 (setq path (file-relative-name path)))
7573 (save-match-data
7574 (if (string-match (concat "^" (regexp-quote
7575 (file-name-as-directory
7576 (expand-file-name "."))))
7577 (expand-file-name path))
7578 ;; We are linking a file with relative path name.
7579 (setq path (substring (expand-file-name path)
7580 (match-end 0)))
7581 (setq path (abbreviate-file-name (expand-file-name path)))))))
7582 (setq link (concat "file:" path))
7583 (if (equal desc origpath)
7584 (setq desc path))))
7586 (if org-make-link-description-function
7587 (setq desc (funcall org-make-link-description-function link desc)))
7589 (setq desc (read-string "Description: " desc))
7590 (unless (string-match "\\S-" desc) (setq desc nil))
7591 (if remove (apply 'delete-region remove))
7592 (insert (org-make-link-string link desc))))
7594 (defun org-link-try-special-completion (type)
7595 "If there is completion support for link type TYPE, offer it."
7596 (let ((fun (intern (concat "org-" type "-complete-link"))))
7597 (if (functionp fun)
7598 (funcall fun)
7599 (read-string "Link (no completion support): " (concat type ":")))))
7601 (defun org-file-complete-link (&optional arg)
7602 "Create a file link using completion."
7603 (let (file link)
7604 (setq file (read-file-name "File: "))
7605 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7606 (pwd1 (file-name-as-directory (abbreviate-file-name
7607 (expand-file-name ".")))))
7608 (cond
7609 ((equal arg '(16))
7610 (setq link (org-make-link
7611 "file:"
7612 (abbreviate-file-name (expand-file-name file)))))
7613 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7614 (setq link (org-make-link "file:" (match-string 1 file))))
7615 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7616 (expand-file-name file))
7617 (setq link (org-make-link
7618 "file:" (match-string 1 (expand-file-name file)))))
7619 (t (setq link (org-make-link "file:" file)))))
7620 link))
7622 (defun org-completing-read (&rest args)
7623 "Completing-read with SPACE being a normal character."
7624 (let ((minibuffer-local-completion-map
7625 (copy-keymap minibuffer-local-completion-map)))
7626 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7627 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7628 (apply 'org-ido-completing-read args)))
7630 (defun org-completing-read-no-ido (&rest args)
7631 (let (org-completion-use-ido)
7632 (apply 'org-completing-read args)))
7634 (defun org-ido-completing-read (&rest args)
7635 "Completing-read using `ido-mode' speedups if available"
7636 (if (and org-completion-use-ido
7637 (fboundp 'ido-completing-read)
7638 (boundp 'ido-mode) ido-mode
7639 (listp (second args)))
7640 (let ((ido-enter-matching-directory nil))
7641 (apply 'ido-completing-read (concat (car args))
7642 (if (consp (car (nth 1 args)))
7643 (mapcar (lambda (x) (car x)) (nth 1 args))
7644 (nth 1 args))
7645 (cddr args)))
7646 (apply 'completing-read args)))
7648 (defun org-extract-attributes (s)
7649 "Extract the attributes cookie from a string and set as text property."
7650 (let (a attr (start 0) key value)
7651 (save-match-data
7652 (when (string-match "{{\\([^}]+\\)}}$" s)
7653 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7654 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7655 (setq key (match-string 1 a) value (match-string 2 a)
7656 start (match-end 0)
7657 attr (plist-put attr (intern key) value))))
7658 (org-add-props s nil 'org-attr attr))
7661 (defun org-extract-attributes-from-string (tag)
7662 (let (key value attr)
7663 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
7664 (setq key (match-string 1 tag) value (match-string 2 tag)
7665 tag (replace-match "" t t tag)
7666 attr (plist-put attr (intern key) value)))
7667 (cons tag attr)))
7669 (defun org-attributes-to-string (plist)
7670 "Format a property list into an HTML attribute list."
7671 (let ((s "") key value)
7672 (while plist
7673 (setq key (pop plist) value (pop plist))
7674 (and value
7675 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7678 ;;; Opening/following a link
7680 (defvar org-link-search-failed nil)
7682 (defun org-next-link ()
7683 "Move forward to the next link.
7684 If the link is in hidden text, expose it."
7685 (interactive)
7686 (when (and org-link-search-failed (eq this-command last-command))
7687 (goto-char (point-min))
7688 (message "Link search wrapped back to beginning of buffer"))
7689 (setq org-link-search-failed nil)
7690 (let* ((pos (point))
7691 (ct (org-context))
7692 (a (assoc :link ct)))
7693 (if a (goto-char (nth 2 a)))
7694 (if (re-search-forward org-any-link-re nil t)
7695 (progn
7696 (goto-char (match-beginning 0))
7697 (if (org-invisible-p) (org-show-context)))
7698 (goto-char pos)
7699 (setq org-link-search-failed t)
7700 (error "No further link found"))))
7702 (defun org-previous-link ()
7703 "Move backward to the previous link.
7704 If the link is in hidden text, expose it."
7705 (interactive)
7706 (when (and org-link-search-failed (eq this-command last-command))
7707 (goto-char (point-max))
7708 (message "Link search wrapped back to end of buffer"))
7709 (setq org-link-search-failed nil)
7710 (let* ((pos (point))
7711 (ct (org-context))
7712 (a (assoc :link ct)))
7713 (if a (goto-char (nth 1 a)))
7714 (if (re-search-backward org-any-link-re nil t)
7715 (progn
7716 (goto-char (match-beginning 0))
7717 (if (org-invisible-p) (org-show-context)))
7718 (goto-char pos)
7719 (setq org-link-search-failed t)
7720 (error "No further link found"))))
7722 (defun org-translate-link (s)
7723 "Translate a link string if a translation function has been defined."
7724 (if (and org-link-translation-function
7725 (fboundp org-link-translation-function)
7726 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7727 (progn
7728 (setq s (funcall org-link-translation-function
7729 (match-string 1) (match-string 2)))
7730 (concat (car s) ":" (cdr s)))
7733 (defun org-translate-link-from-planner (type path)
7734 "Translate a link from Emacs Planner syntax so that Org can follow it.
7735 This is still an experimental function, your mileage may vary."
7736 (cond
7737 ((member type '("http" "https" "news" "ftp"))
7738 ;; standard Internet links are the same.
7739 nil)
7740 ((and (equal type "irc") (string-match "^//" path))
7741 ;; Planner has two / at the beginning of an irc link, we have 1.
7742 ;; We should have zero, actually....
7743 (setq path (substring path 1)))
7744 ((and (equal type "lisp") (string-match "^/" path))
7745 ;; Planner has a slash, we do not.
7746 (setq type "elisp" path (substring path 1)))
7747 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7748 ;; A typical message link. Planner has the id after the fina slash,
7749 ;; we separate it with a hash mark
7750 (setq path (concat (match-string 1 path) "#"
7751 (org-remove-angle-brackets (match-string 2 path)))))
7753 (cons type path))
7755 (defun org-find-file-at-mouse (ev)
7756 "Open file link or URL at mouse."
7757 (interactive "e")
7758 (mouse-set-point ev)
7759 (org-open-at-point 'in-emacs))
7761 (defun org-open-at-mouse (ev)
7762 "Open file link or URL at mouse."
7763 (interactive "e")
7764 (mouse-set-point ev)
7765 (if (eq major-mode 'org-agenda-mode)
7766 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7767 (org-open-at-point))
7769 (defvar org-window-config-before-follow-link nil
7770 "The window configuration before following a link.
7771 This is saved in case the need arises to restore it.")
7773 (defvar org-open-link-marker (make-marker)
7774 "Marker pointing to the location where `org-open-at-point; was called.")
7776 ;;;###autoload
7777 (defun org-open-at-point-global ()
7778 "Follow a link like Org-mode does.
7779 This command can be called in any mode to follow a link that has
7780 Org-mode syntax."
7781 (interactive)
7782 (org-run-like-in-org-mode 'org-open-at-point))
7784 ;;;###autoload
7785 (defun org-open-link-from-string (s &optional arg)
7786 "Open a link in the string S, as if it was in Org-mode."
7787 (interactive "sLink: \nP")
7788 (let ((reference-buffer (current-buffer)))
7789 (with-temp-buffer
7790 (let ((org-inhibit-startup t))
7791 (org-mode)
7792 (insert s)
7793 (goto-char (point-min))
7794 (org-open-at-point arg reference-buffer)))))
7796 (defun org-open-at-point (&optional in-emacs reference-buffer)
7797 "Open link at or after point.
7798 If there is no link at point, this function will search forward up to
7799 the end of the current line.
7800 Normally, files will be opened by an appropriate application. If the
7801 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7802 With a double prefix argument, try to open outside of Emacs, in the
7803 application the system uses for this file type."
7804 (interactive "P")
7805 (org-load-modules-maybe)
7806 (move-marker org-open-link-marker (point))
7807 (setq org-window-config-before-follow-link (current-window-configuration))
7808 (org-remove-occur-highlights nil nil t)
7809 (cond
7810 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7811 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7812 (org-footnote-action))
7814 (let (type path link line search (pos (point)))
7815 (catch 'match
7816 (save-excursion
7817 (skip-chars-forward "^]\n\r")
7818 (when (org-in-regexp org-bracket-link-regexp)
7819 (setq link (org-extract-attributes
7820 (org-link-unescape (org-match-string-no-properties 1))))
7821 (while (string-match " *\n *" link)
7822 (setq link (replace-match " " t t link)))
7823 (setq link (org-link-expand-abbrev link))
7824 (cond
7825 ((or (file-name-absolute-p link)
7826 (string-match "^\\.\\.?/" link))
7827 (setq type "file" path link))
7828 ((string-match org-link-re-with-space3 link)
7829 (setq type (match-string 1 link) path (match-string 2 link)))
7830 (t (setq type "thisfile" path link)))
7831 (throw 'match t)))
7833 (when (get-text-property (point) 'org-linked-text)
7834 (setq type "thisfile"
7835 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7836 (1+ (point)) (point))
7837 path (buffer-substring
7838 (previous-single-property-change pos 'org-linked-text)
7839 (next-single-property-change pos 'org-linked-text)))
7840 (throw 'match t))
7842 (save-excursion
7843 (when (or (org-in-regexp org-angle-link-re)
7844 (org-in-regexp org-plain-link-re))
7845 (setq type (match-string 1) path (match-string 2))
7846 (throw 'match t)))
7847 (save-excursion
7848 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7849 (setq type "tags"
7850 path (match-string 1))
7851 (while (string-match ":" path)
7852 (setq path (replace-match "+" t t path)))
7853 (throw 'match t)))
7854 (when (org-in-regexp "<\\([^><\n]+\\)>")
7855 (setq type "tree-match"
7856 path (match-string 1))
7857 (throw 'match t)))
7858 (unless path
7859 (error "No link found"))
7861 ;; switch back to reference buffer
7862 ;; needed when if called in a temporary buffer through
7863 ;; org-open-link-from-string
7864 (and reference-buffer (switch-to-buffer reference-buffer))
7866 ;; Remove any trailing spaces in path
7867 (if (string-match " +\\'" path)
7868 (setq path (replace-match "" t t path)))
7869 (if (and org-link-translation-function
7870 (fboundp org-link-translation-function))
7871 ;; Check if we need to translate the link
7872 (let ((tmp (funcall org-link-translation-function type path)))
7873 (setq type (car tmp) path (cdr tmp))))
7875 (cond
7877 ((assoc type org-link-protocols)
7878 (funcall (nth 1 (assoc type org-link-protocols)) path))
7880 ((equal type "mailto")
7881 (let ((cmd (car org-link-mailto-program))
7882 (args (cdr org-link-mailto-program)) args1
7883 (address path) (subject "") a)
7884 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7885 (setq address (match-string 1 path)
7886 subject (org-link-escape (match-string 2 path))))
7887 (while args
7888 (cond
7889 ((not (stringp (car args))) (push (pop args) args1))
7890 (t (setq a (pop args))
7891 (if (string-match "%a" a)
7892 (setq a (replace-match address t t a)))
7893 (if (string-match "%s" a)
7894 (setq a (replace-match subject t t a)))
7895 (push a args1))))
7896 (apply cmd (nreverse args1))))
7898 ((member type '("http" "https" "ftp" "news"))
7899 (browse-url (concat type ":" (org-link-escape
7900 path org-link-escape-chars-browser))))
7902 ((member type '("message"))
7903 (browse-url (concat type ":" path)))
7905 ((string= type "tags")
7906 (org-tags-view in-emacs path))
7907 ((string= type "thisfile")
7908 (if in-emacs
7909 (switch-to-buffer-other-window
7910 (org-get-buffer-for-internal-link (current-buffer)))
7911 (org-mark-ring-push))
7912 (let ((cmd `(org-link-search
7913 ,path
7914 ,(cond ((equal in-emacs '(4)) 'occur)
7915 ((equal in-emacs '(16)) 'org-occur)
7916 (t nil))
7917 ,pos)))
7918 (condition-case nil (eval cmd)
7919 (error (progn (widen) (eval cmd))))))
7921 ((string= type "tree-match")
7922 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7924 ((string= type "file")
7925 (if (string-match "::\\([0-9]+\\)\\'" path)
7926 (setq line (string-to-number (match-string 1 path))
7927 path (substring path 0 (match-beginning 0)))
7928 (if (string-match "::\\(.+\\)\\'" path)
7929 (setq search (match-string 1 path)
7930 path (substring path 0 (match-beginning 0)))))
7931 (if (string-match "[*?{]" (file-name-nondirectory path))
7932 (dired path)
7933 (org-open-file path in-emacs line search)))
7935 ((string= type "news")
7936 (require 'org-gnus)
7937 (org-gnus-follow-link path))
7939 ((string= type "shell")
7940 (let ((cmd path))
7941 (if (or (not org-confirm-shell-link-function)
7942 (funcall org-confirm-shell-link-function
7943 (format "Execute \"%s\" in shell? "
7944 (org-add-props cmd nil
7945 'face 'org-warning))))
7946 (progn
7947 (message "Executing %s" cmd)
7948 (shell-command cmd))
7949 (error "Abort"))))
7951 ((string= type "elisp")
7952 (let ((cmd path))
7953 (if (or (not org-confirm-elisp-link-function)
7954 (funcall org-confirm-elisp-link-function
7955 (format "Execute \"%s\" as elisp? "
7956 (org-add-props cmd nil
7957 'face 'org-warning))))
7958 (message "%s => %s" cmd
7959 (if (equal (string-to-char cmd) ?\()
7960 (eval (read cmd))
7961 (call-interactively (read cmd))))
7962 (error "Abort"))))
7965 (browse-url-at-point))))))
7966 (move-marker org-open-link-marker nil)
7967 (run-hook-with-args 'org-follow-link-hook))
7969 ;;;; Time estimates
7971 (defun org-get-effort (&optional pom)
7972 "Get the effort estimate for the current entry."
7973 (org-entry-get pom org-effort-property))
7975 ;;; File search
7977 (defvar org-create-file-search-functions nil
7978 "List of functions to construct the right search string for a file link.
7979 These functions are called in turn with point at the location to
7980 which the link should point.
7982 A function in the hook should first test if it would like to
7983 handle this file type, for example by checking the major-mode or
7984 the file extension. If it decides not to handle this file, it
7985 should just return nil to give other functions a chance. If it
7986 does handle the file, it must return the search string to be used
7987 when following the link. The search string will be part of the
7988 file link, given after a double colon, and `org-open-at-point'
7989 will automatically search for it. If special measures must be
7990 taken to make the search successful, another function should be
7991 added to the companion hook `org-execute-file-search-functions',
7992 which see.
7994 A function in this hook may also use `setq' to set the variable
7995 `description' to provide a suggestion for the descriptive text to
7996 be used for this link when it gets inserted into an Org-mode
7997 buffer with \\[org-insert-link].")
7999 (defvar org-execute-file-search-functions nil
8000 "List of functions to execute a file search triggered by a link.
8002 Functions added to this hook must accept a single argument, the
8003 search string that was part of the file link, the part after the
8004 double colon. The function must first check if it would like to
8005 handle this search, for example by checking the major-mode or the
8006 file extension. If it decides not to handle this search, it
8007 should just return nil to give other functions a chance. If it
8008 does handle the search, it must return a non-nil value to keep
8009 other functions from trying.
8011 Each function can access the current prefix argument through the
8012 variable `current-prefix-argument'. Note that a single prefix is
8013 used to force opening a link in Emacs, so it may be good to only
8014 use a numeric or double prefix to guide the search function.
8016 In case this is needed, a function in this hook can also restore
8017 the window configuration before `org-open-at-point' was called using:
8019 (set-window-configuration org-window-config-before-follow-link)")
8021 (defun org-link-search (s &optional type avoid-pos)
8022 "Search for a link search option.
8023 If S is surrounded by forward slashes, it is interpreted as a
8024 regular expression. In org-mode files, this will create an `org-occur'
8025 sparse tree. In ordinary files, `occur' will be used to list matches.
8026 If the current buffer is in `dired-mode', grep will be used to search
8027 in all files. If AVOID-POS is given, ignore matches near that position."
8028 (let ((case-fold-search t)
8029 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8030 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8031 (append '(("") (" ") ("\t") ("\n"))
8032 org-emphasis-alist)
8033 "\\|") "\\)"))
8034 (pos (point))
8035 (pre nil) (post nil)
8036 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8037 (cond
8038 ;; First check if there are any special
8039 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8040 ;; Now try the builtin stuff
8041 ((and (equal (string-to-char s0) ?#)
8042 (> (length s0) 1)
8043 (save-excursion
8044 (goto-char (point-min))
8045 (and
8046 (re-search-forward
8047 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8048 (setq type 'dedicated
8049 pos (match-beginning 0))))
8050 ;; There is an exact target for this
8051 (goto-char pos)
8052 (org-back-to-heading t)))
8053 ((save-excursion
8054 (goto-char (point-min))
8055 (and
8056 (re-search-forward
8057 (concat "<<" (regexp-quote s0) ">>") nil t)
8058 (setq type 'dedicated
8059 pos (match-beginning 0))))
8060 ;; There is an exact target for this
8061 (goto-char pos))
8062 ((and (string-match "^(\\(.*\\))$" s0)
8063 (save-excursion
8064 (goto-char (point-min))
8065 (and
8066 (re-search-forward
8067 (concat "[^[]" (regexp-quote
8068 (format org-coderef-label-format
8069 (match-string 1 s0))))
8070 nil t)
8071 (setq type 'dedicated
8072 pos (1+ (match-beginning 0))))))
8073 ;; There is a coderef target for this
8074 (goto-char pos))
8075 ((string-match "^/\\(.*\\)/$" s)
8076 ;; A regular expression
8077 (cond
8078 ((org-mode-p)
8079 (org-occur (match-string 1 s)))
8080 ;;((eq major-mode 'dired-mode)
8081 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8082 (t (org-do-occur (match-string 1 s)))))
8084 ;; A normal search strings
8085 (when (equal (string-to-char s) ?*)
8086 ;; Anchor on headlines, post may include tags.
8087 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8088 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8089 s (substring s 1)))
8090 (remove-text-properties
8091 0 (length s)
8092 '(face nil mouse-face nil keymap nil fontified nil) s)
8093 ;; Make a series of regular expressions to find a match
8094 (setq words (org-split-string s "[ \n\r\t]+")
8096 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8097 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8098 "\\)" markers)
8099 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8100 re2a (concat "[ \t\r\n]" re2a_)
8101 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8102 re4 (concat "[^a-zA-Z_]" re4_)
8104 re1 (concat pre re2 post)
8105 re3 (concat pre (if pre re4_ re4) post)
8106 re5 (concat pre ".*" re4)
8107 re2 (concat pre re2)
8108 re2a (concat pre (if pre re2a_ re2a))
8109 re4 (concat pre (if pre re4_ re4))
8110 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8111 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8112 re5 "\\)"
8114 (cond
8115 ((eq type 'org-occur) (org-occur reall))
8116 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8117 (t (goto-char (point-min))
8118 (setq type 'fuzzy)
8119 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8120 (org-search-not-self 1 re1 nil t)
8121 (org-search-not-self 1 re2 nil t)
8122 (org-search-not-self 1 re2a nil t)
8123 (org-search-not-self 1 re3 nil t)
8124 (org-search-not-self 1 re4 nil t)
8125 (org-search-not-self 1 re5 nil t)
8127 (goto-char (match-beginning 1))
8128 (goto-char pos)
8129 (error "No match")))))
8131 ;; Normal string-search
8132 (goto-char (point-min))
8133 (if (search-forward s nil t)
8134 (goto-char (match-beginning 0))
8135 (error "No match"))))
8136 (and (org-mode-p) (org-show-context 'link-search))
8137 type))
8139 (defun org-search-not-self (group &rest args)
8140 "Execute `re-search-forward', but only accept matches that do not
8141 enclose the position of `org-open-link-marker'."
8142 (let ((m org-open-link-marker))
8143 (catch 'exit
8144 (while (apply 're-search-forward args)
8145 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8146 (goto-char (match-end group))
8147 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8148 (> (match-beginning 0) (marker-position m))
8149 (< (match-end 0) (marker-position m)))
8150 (save-match-data
8151 (or (not (org-in-regexp
8152 org-bracket-link-analytic-regexp 1))
8153 (not (match-end 4)) ; no description
8154 (and (<= (match-beginning 4) (point))
8155 (>= (match-end 4) (point))))))
8156 (throw 'exit (point))))))))
8158 (defun org-get-buffer-for-internal-link (buffer)
8159 "Return a buffer to be used for displaying the link target of internal links."
8160 (cond
8161 ((not org-display-internal-link-with-indirect-buffer)
8162 buffer)
8163 ((string-match "(Clone)$" (buffer-name buffer))
8164 (message "Buffer is already a clone, not making another one")
8165 ;; we also do not modify visibility in this case
8166 buffer)
8167 (t ; make a new indirect buffer for displaying the link
8168 (let* ((bn (buffer-name buffer))
8169 (ibn (concat bn "(Clone)"))
8170 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8171 (with-current-buffer ib (org-overview))
8172 ib))))
8174 (defun org-do-occur (regexp &optional cleanup)
8175 "Call the Emacs command `occur'.
8176 If CLEANUP is non-nil, remove the printout of the regular expression
8177 in the *Occur* buffer. This is useful if the regex is long and not useful
8178 to read."
8179 (occur regexp)
8180 (when cleanup
8181 (let ((cwin (selected-window)) win beg end)
8182 (when (setq win (get-buffer-window "*Occur*"))
8183 (select-window win))
8184 (goto-char (point-min))
8185 (when (re-search-forward "match[a-z]+" nil t)
8186 (setq beg (match-end 0))
8187 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8188 (setq end (1- (match-beginning 0)))))
8189 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8190 (goto-char (point-min))
8191 (select-window cwin))))
8193 ;;; The mark ring for links jumps
8195 (defvar org-mark-ring nil
8196 "Mark ring for positions before jumps in Org-mode.")
8197 (defvar org-mark-ring-last-goto nil
8198 "Last position in the mark ring used to go back.")
8199 ;; Fill and close the ring
8200 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8201 (loop for i from 1 to org-mark-ring-length do
8202 (push (make-marker) org-mark-ring))
8203 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8204 org-mark-ring)
8206 (defun org-mark-ring-push (&optional pos buffer)
8207 "Put the current position or POS into the mark ring and rotate it."
8208 (interactive)
8209 (setq pos (or pos (point)))
8210 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8211 (move-marker (car org-mark-ring)
8212 (or pos (point))
8213 (or buffer (current-buffer)))
8214 (message "%s"
8215 (substitute-command-keys
8216 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8218 (defun org-mark-ring-goto (&optional n)
8219 "Jump to the previous position in the mark ring.
8220 With prefix arg N, jump back that many stored positions. When
8221 called several times in succession, walk through the entire ring.
8222 Org-mode commands jumping to a different position in the current file,
8223 or to another Org-mode file, automatically push the old position
8224 onto the ring."
8225 (interactive "p")
8226 (let (p m)
8227 (if (eq last-command this-command)
8228 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8229 (setq p org-mark-ring))
8230 (setq org-mark-ring-last-goto p)
8231 (setq m (car p))
8232 (switch-to-buffer (marker-buffer m))
8233 (goto-char m)
8234 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8236 (defun org-remove-angle-brackets (s)
8237 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8238 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8240 (defun org-add-angle-brackets (s)
8241 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8242 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8244 (defun org-remove-double-quotes (s)
8245 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8246 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8249 ;;; Following specific links
8251 (defun org-follow-timestamp-link ()
8252 (cond
8253 ((org-at-date-range-p t)
8254 (let ((org-agenda-start-on-weekday)
8255 (t1 (match-string 1))
8256 (t2 (match-string 2)))
8257 (setq t1 (time-to-days (org-time-string-to-time t1))
8258 t2 (time-to-days (org-time-string-to-time t2)))
8259 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8260 ((org-at-timestamp-p t)
8261 (org-agenda-list nil (time-to-days (org-time-string-to-time
8262 (substring (match-string 1) 0 10)))
8264 (t (error "This should not happen"))))
8267 ;;; Following file links
8268 (defvar org-wait nil)
8269 (defun org-open-file (path &optional in-emacs line search)
8270 "Open the file at PATH.
8271 First, this expands any special file name abbreviations. Then the
8272 configuration variable `org-file-apps' is checked if it contains an
8273 entry for this file type, and if yes, the corresponding command is launched.
8275 If no application is found, Emacs simply visits the file.
8277 With optional prefix argument IN-EMACS, Emacs will visit the file.
8278 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8279 and o use an external application to visit the file.
8281 Optional LINE specifies a line to go to, optional SEARCH a string to
8282 search for. If LINE or SEARCH is given, the file will always be
8283 opened in Emacs.
8284 If the file does not exist, an error is thrown."
8285 (setq in-emacs (or in-emacs line search))
8286 (let* ((file (if (equal path "")
8287 buffer-file-name
8288 (substitute-in-file-name (expand-file-name path))))
8289 (apps (append org-file-apps (org-default-apps)))
8290 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8291 (dirp (if remp nil (file-directory-p file)))
8292 (file (if (and dirp org-open-directory-means-index-dot-org)
8293 (concat (file-name-as-directory file) "index.org")
8294 file))
8295 (a-m-a-p (assq 'auto-mode apps))
8296 (dfile (downcase file))
8297 (old-buffer (current-buffer))
8298 (old-pos (point))
8299 (old-mode major-mode)
8300 ext cmd)
8301 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8302 (setq ext (match-string 1 dfile))
8303 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8304 (setq ext (match-string 1 dfile))))
8305 (cond
8306 ((equal in-emacs '(16))
8307 (setq cmd (cdr (assoc 'system apps))))
8308 (in-emacs (setq cmd 'emacs))
8310 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8311 (and dirp (cdr (assoc 'directory apps)))
8312 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8313 'string-match)
8314 (cdr (assoc ext apps))
8315 (cdr (assoc t apps))))))
8316 (when (eq cmd 'system)
8317 (setq cmd (cdr (assoc 'system apps))))
8318 (when (eq cmd 'default)
8319 (setq cmd (cdr (assoc t apps))))
8320 (when (eq cmd 'mailcap)
8321 (require 'mailcap)
8322 (mailcap-parse-mailcaps)
8323 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8324 (command (mailcap-mime-info mime-type)))
8325 (if (stringp command)
8326 (setq cmd command)
8327 (setq cmd 'emacs))))
8328 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8329 (not (file-exists-p file))
8330 (not org-open-non-existing-files))
8331 (error "No such file: %s" file))
8332 (cond
8333 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8334 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8335 (while (string-match "['\"]%s['\"]" cmd)
8336 (setq cmd (replace-match "%s" t t cmd)))
8337 (while (string-match "%s" cmd)
8338 (setq cmd (replace-match
8339 (save-match-data
8340 (shell-quote-argument
8341 (convert-standard-filename file)))
8342 t t cmd)))
8343 (save-window-excursion
8344 (start-process-shell-command cmd nil cmd)
8345 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8347 ((or (stringp cmd)
8348 (eq cmd 'emacs))
8349 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8350 (widen)
8351 (if line (goto-line line)
8352 (if search (org-link-search search))))
8353 ((consp cmd)
8354 (let ((file (convert-standard-filename file)))
8355 (eval cmd)))
8356 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8357 (and (org-mode-p) (eq old-mode 'org-mode)
8358 (or (not (equal old-buffer (current-buffer)))
8359 (not (equal old-pos (point))))
8360 (org-mark-ring-push old-pos old-buffer))))
8362 (defun org-default-apps ()
8363 "Return the default applications for this operating system."
8364 (cond
8365 ((eq system-type 'darwin)
8366 org-file-apps-defaults-macosx)
8367 ((eq system-type 'windows-nt)
8368 org-file-apps-defaults-windowsnt)
8369 (t org-file-apps-defaults-gnu)))
8371 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8372 "Convert extensions to regular expressions in the cars of LIST.
8373 Also, weed out any non-string entries, because the return value is used
8374 only for regexp matching.
8375 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8376 point to the symbol `emacs', indicating that the file should
8377 be opened in Emacs."
8378 (append
8379 (delq nil
8380 (mapcar (lambda (x)
8381 (if (not (stringp (car x)))
8383 (if (string-match "\\W" (car x))
8385 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8386 list))
8387 (if add-auto-mode
8388 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8390 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8391 (defun org-file-remote-p (file)
8392 "Test whether FILE specifies a location on a remote system.
8393 Return non-nil if the location is indeed remote.
8395 For example, the filename \"/user@host:/foo\" specifies a location
8396 on the system \"/user@host:\"."
8397 (cond ((fboundp 'file-remote-p)
8398 (file-remote-p file))
8399 ((fboundp 'tramp-handle-file-remote-p)
8400 (tramp-handle-file-remote-p file))
8401 ((and (boundp 'ange-ftp-name-format)
8402 (string-match (car ange-ftp-name-format) file))
8404 (t nil)))
8407 ;;;; Refiling
8409 (defun org-get-org-file ()
8410 "Read a filename, with default directory `org-directory'."
8411 (let ((default (or org-default-notes-file remember-data-file)))
8412 (read-file-name (format "File name [%s]: " default)
8413 (file-name-as-directory org-directory)
8414 default)))
8416 (defun org-notes-order-reversed-p ()
8417 "Check if the current file should receive notes in reversed order."
8418 (cond
8419 ((not org-reverse-note-order) nil)
8420 ((eq t org-reverse-note-order) t)
8421 ((not (listp org-reverse-note-order)) nil)
8422 (t (catch 'exit
8423 (let ((all org-reverse-note-order)
8424 entry)
8425 (while (setq entry (pop all))
8426 (if (string-match (car entry) buffer-file-name)
8427 (throw 'exit (cdr entry))))
8428 nil)))))
8430 (defvar org-refile-target-table nil
8431 "The list of refile targets, created by `org-refile'.")
8433 (defvar org-agenda-new-buffers nil
8434 "Buffers created to visit agenda files.")
8436 (defun org-get-refile-targets (&optional default-buffer)
8437 "Produce a table with refile targets."
8438 (let ((case-fold-search nil)
8439 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
8440 (entries (or org-refile-targets '((nil . (:level . 1)))))
8441 targets txt re files f desc descre fast-path-p level pos0)
8442 (message "Getting targets...")
8443 (with-current-buffer (or default-buffer (current-buffer))
8444 (while (setq entry (pop entries))
8445 (setq files (car entry) desc (cdr entry))
8446 (setq fast-path-p nil)
8447 (cond
8448 ((null files) (setq files (list (current-buffer))))
8449 ((eq files 'org-agenda-files)
8450 (setq files (org-agenda-files 'unrestricted)))
8451 ((and (symbolp files) (fboundp files))
8452 (setq files (funcall files)))
8453 ((and (symbolp files) (boundp files))
8454 (setq files (symbol-value files))))
8455 (if (stringp files) (setq files (list files)))
8456 (cond
8457 ((eq (car desc) :tag)
8458 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8459 ((eq (car desc) :todo)
8460 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8461 ((eq (car desc) :regexp)
8462 (setq descre (cdr desc)))
8463 ((eq (car desc) :level)
8464 (setq descre (concat "^\\*\\{" (number-to-string
8465 (if org-odd-levels-only
8466 (1- (* 2 (cdr desc)))
8467 (cdr desc)))
8468 "\\}[ \t]")))
8469 ((eq (car desc) :maxlevel)
8470 (setq fast-path-p t)
8471 (setq descre (concat "^\\*\\{1," (number-to-string
8472 (if org-odd-levels-only
8473 (1- (* 2 (cdr desc)))
8474 (cdr desc)))
8475 "\\}[ \t]")))
8476 (t (error "Bad refiling target description %s" desc)))
8477 (while (setq f (pop files))
8478 (save-excursion
8479 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
8480 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8481 (setq f (expand-file-name f))
8482 (if (eq org-refile-use-outline-path 'file)
8483 (push (list (file-name-nondirectory f) f nil nil) targets))
8484 (save-excursion
8485 (save-restriction
8486 (widen)
8487 (goto-char (point-min))
8488 (while (re-search-forward descre nil t)
8489 (goto-char (setq pos0 (point-at-bol)))
8490 (catch 'next
8491 (when org-refile-target-verify-function
8492 (save-match-data
8493 (or (funcall org-refile-target-verify-function)
8494 (throw 'next t))))
8495 (when (looking-at org-complex-heading-regexp)
8496 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8497 txt (org-link-display-format (match-string 4))
8498 re (concat "^" (regexp-quote
8499 (buffer-substring (match-beginning 1)
8500 (match-end 4)))))
8501 (if (match-end 5) (setq re (concat re "[ \t]+"
8502 (regexp-quote
8503 (match-string 5)))))
8504 (setq re (concat re "[ \t]*$"))
8505 (when org-refile-use-outline-path
8506 (setq txt (mapconcat 'org-protect-slash
8507 (append
8508 (if (eq org-refile-use-outline-path 'file)
8509 (list (file-name-nondirectory
8510 (buffer-file-name (buffer-base-buffer))))
8511 (if (eq org-refile-use-outline-path 'full-file-path)
8512 (list (buffer-file-name (buffer-base-buffer)))))
8513 (org-get-outline-path fast-path-p level txt)
8514 (list txt))
8515 "/")))
8516 (push (list txt f re (point)) targets)))
8517 (when (= (point) pos0)
8518 ;; verification function has not moved point
8519 (goto-char (point-at-eol))))))))))
8520 (message "Getting targets...done")
8521 (nreverse targets)))
8523 (defun org-protect-slash (s)
8524 (while (string-match "/" s)
8525 (setq s (replace-match "\\" t t s)))
8528 (defvar org-olpa (make-vector 20 nil))
8530 (defun org-get-outline-path (&optional fastp level heading)
8531 "Return the outline path to the current entry, as a list."
8532 (if fastp
8533 (progn
8534 (if (> level 19)
8535 (error "Outline path failure, more than 19 levels."))
8536 (loop for i from level upto 19 do
8537 (aset org-olpa i nil))
8538 (prog1
8539 (delq nil (append org-olpa nil))
8540 (aset org-olpa level heading)))
8541 (let (rtn)
8542 (save-excursion
8543 (while (org-up-heading-safe)
8544 (when (looking-at org-complex-heading-regexp)
8545 (push (org-match-string-no-properties 4) rtn)))
8546 rtn))))
8548 (defvar org-refile-history nil
8549 "History for refiling operations.")
8551 (defvar org-after-refile-insert-hook nil
8552 "Hook run after `org-refile' has inserted its stuff at the new location.
8553 Note that this is still *before* the stuff will be removed from
8554 the *old* location.")
8556 (defun org-refile (&optional goto default-buffer rfloc)
8557 "Move the entry at point to another heading.
8558 The list of target headings is compiled using the information in
8559 `org-refile-targets', which see. This list is created before each use
8560 and will therefore always be up-to-date.
8562 At the target location, the entry is filed as a subitem of the target heading.
8563 Depending on `org-reverse-note-order', the new subitem will either be the
8564 first or the last subitem.
8566 If there is an active region, all entries in that region will be moved.
8567 However, the region must fulfil the requirement that the first heading
8568 is the first one sets the top-level of the moved text - at most siblings
8569 below it are allowed.
8571 With prefix arg GOTO, the command will only visit the target location,
8572 not actually move anything.
8573 With a double prefix `C-u C-u', go to the location where the last refiling
8574 operation has put the subtree.
8576 RFLOC can be a refile location obtained in a different way.
8578 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
8579 (interactive "P")
8580 (let* ((cbuf (current-buffer))
8581 (regionp (org-region-active-p))
8582 (region-start (and regionp (region-beginning)))
8583 (region-end (and regionp (region-end)))
8584 (region-length (and regionp (- region-end region-start)))
8585 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8586 pos it nbuf file re level reversed)
8587 (when regionp
8588 (goto-char region-start)
8589 (or (bolp) (goto-char (point-at-bol)))
8590 (setq region-start (point))
8591 (unless (org-kill-is-subtree-p
8592 (buffer-substring region-start region-end))
8593 (error "The region is not a (sequence of) subtree(s)")))
8594 (if (equal goto '(16))
8595 (org-refile-goto-last-stored)
8596 (when (setq it (or rfloc
8597 (save-excursion
8598 (org-refile-get-location
8599 (if goto "Goto: " "Refile to: ") default-buffer
8600 org-refile-allow-creating-parent-nodes))))
8601 (setq file (nth 1 it)
8602 re (nth 2 it)
8603 pos (nth 3 it))
8604 (if (and (not goto)
8606 (equal (buffer-file-name) file)
8607 (if regionp
8608 (and (>= pos region-start)
8609 (<= pos region-end))
8610 (and (>= pos (point))
8611 (< pos (save-excursion
8612 (org-end-of-subtree t t))))))
8613 (error "Cannot refile to position inside the tree or region"))
8615 (setq nbuf (or (find-buffer-visiting file)
8616 (find-file-noselect file)))
8617 (if goto
8618 (progn
8619 (switch-to-buffer nbuf)
8620 (goto-char pos)
8621 (org-show-context 'org-goto))
8622 (if regionp
8623 (progn
8624 (org-kill-new (buffer-substring region-start region-end))
8625 (org-save-markers-in-region region-start region-end))
8626 (org-copy-subtree 1 nil t))
8627 (save-excursion
8628 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8629 (find-file-noselect file))))
8630 (setq reversed (org-notes-order-reversed-p))
8631 (save-excursion
8632 (save-restriction
8633 (widen)
8634 (if pos
8635 (progn
8636 (goto-char pos)
8637 (looking-at outline-regexp)
8638 (setq level (org-get-valid-level (funcall outline-level) 1))
8639 (goto-char
8640 (if reversed
8641 (or (outline-next-heading) (point-max))
8642 (or (save-excursion (outline-get-next-sibling))
8643 (org-end-of-subtree t t)
8644 (point-max)))))
8645 (setq level 1)
8646 (if (not reversed)
8647 (goto-char (point-max))
8648 (goto-char (point-min))
8649 (or (outline-next-heading) (goto-char (point-max)))))
8650 (if (not (bolp)) (newline))
8651 (bookmark-set "org-refile-last-stored")
8652 (org-paste-subtree level)
8653 (if (fboundp 'deactivate-mark) (deactivate-mark))
8654 (run-hooks 'org-after-refile-insert-hook))))
8655 (if regionp
8656 (delete-region (point) (+ (point) region-length))
8657 (org-cut-subtree))
8658 (when (featurep 'org-inlinetask)
8659 (org-inlinetask-remove-END-maybe))
8660 (setq org-markers-to-move nil)
8661 (message "Refiled to \"%s\"" (car it))))))
8662 (org-reveal))
8664 (defun org-refile-goto-last-stored ()
8665 "Go to the location where the last refile was stored."
8666 (interactive)
8667 (bookmark-jump "org-refile-last-stored")
8668 (message "This is the location of the last refile"))
8670 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
8671 "Prompt the user for a refile location, using PROMPT."
8672 (let ((org-refile-targets org-refile-targets)
8673 (org-refile-use-outline-path org-refile-use-outline-path))
8674 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8675 (unless org-refile-target-table
8676 (error "No refile targets"))
8677 (let* ((cbuf (current-buffer))
8678 (partial-completion-mode nil)
8679 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8680 (cfunc (if (and org-refile-use-outline-path
8681 org-outline-path-complete-in-steps)
8682 'org-olpath-completing-read
8683 'org-ido-completing-read))
8684 (extra (if org-refile-use-outline-path "/" ""))
8685 (filename (and cfn (expand-file-name cfn)))
8686 (tbl (mapcar
8687 (lambda (x)
8688 (if (and (not (member org-refile-use-outline-path
8689 '(file full-file-path)))
8690 (not (equal filename (nth 1 x))))
8691 (cons (concat (car x) extra " ("
8692 (file-name-nondirectory (nth 1 x)) ")")
8693 (cdr x))
8694 (cons (concat (car x) extra) (cdr x))))
8695 org-refile-target-table))
8696 (completion-ignore-case t)
8697 pa answ parent-target child parent old-hist)
8698 (setq old-hist org-refile-history)
8699 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
8700 nil 'org-refile-history))
8701 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
8702 (if pa
8703 (progn
8704 (when (or (not org-refile-history)
8705 (not (eq old-hist org-refile-history))
8706 (not (equal (car pa) (car org-refile-history))))
8707 (setq org-refile-history
8708 (cons (car pa) (if (assoc (car org-refile-history) tbl)
8709 org-refile-history
8710 (cdr org-refile-history))))
8711 (if (equal (car org-refile-history) (nth 1 org-refile-history))
8712 (pop org-refile-history)))
8714 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
8715 (setq parent (match-string 1 answ)
8716 child (match-string 2 answ))
8717 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
8718 (when (and parent-target
8719 (or (eq new-nodes t)
8720 (and (eq new-nodes 'confirm)
8721 (y-or-n-p (format "Create new node \"%s\"? " child)))))
8722 (org-refile-new-child parent-target child))))))
8724 (defun org-refile-new-child (parent-target child)
8725 "Use refile target PARENT-TARGET to add new CHILD below it."
8726 (unless parent-target
8727 (error "Cannot find parent for new node"))
8728 (let ((file (nth 1 parent-target))
8729 (pos (nth 3 parent-target))
8730 level)
8731 (with-current-buffer (or (find-buffer-visiting file)
8732 (find-file-noselect file))
8733 (save-excursion
8734 (save-restriction
8735 (widen)
8736 (if pos
8737 (goto-char pos)
8738 (goto-char (point-max))
8739 (if (not (bolp)) (newline)))
8740 (when (looking-at outline-regexp)
8741 (setq level (funcall outline-level))
8742 (org-end-of-subtree t t))
8743 (org-back-over-empty-lines)
8744 (insert "\n" (make-string
8745 (if pos (org-get-valid-level level 1) 1) ?*)
8746 " " child "\n")
8747 (beginning-of-line 0)
8748 (list (concat (car parent-target) "/" child) file "" (point)))))))
8750 (defun org-olpath-completing-read (prompt collection &rest args)
8751 "Read an outline path like a file name."
8752 (let ((thetable collection)
8753 (org-completion-use-ido nil)) ; does not work with ido.
8754 (apply
8755 'org-ido-completing-read prompt
8756 (lambda (string predicate &optional flag)
8757 (let (rtn r f (l (length string)))
8758 (cond
8759 ((eq flag nil)
8760 ;; try completion
8761 (try-completion string thetable))
8762 ((eq flag t)
8763 ;; all-completions
8764 (setq rtn (all-completions string thetable predicate))
8765 (mapcar
8766 (lambda (x)
8767 (setq r (substring x l))
8768 (if (string-match " ([^)]*)$" x)
8769 (setq f (match-string 0 x))
8770 (setq f ""))
8771 (if (string-match "/" r)
8772 (concat string (substring r 0 (match-end 0)) f)
8774 rtn))
8775 ((eq flag 'lambda)
8776 ;; exact match?
8777 (assoc string thetable)))
8779 args)))
8781 ;;;; Dynamic blocks
8783 (defun org-find-dblock (name)
8784 "Find the first dynamic block with name NAME in the buffer.
8785 If not found, stay at current position and return nil."
8786 (let (pos)
8787 (save-excursion
8788 (goto-char (point-min))
8789 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8790 nil t)
8791 (match-beginning 0))))
8792 (if pos (goto-char pos))
8793 pos))
8795 (defconst org-dblock-start-re
8796 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8797 "Matches the startline of a dynamic block, with parameters.")
8799 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8800 "Matches the end of a dynamic block.")
8802 (defun org-create-dblock (plist)
8803 "Create a dynamic block section, with parameters taken from PLIST.
8804 PLIST must contain a :name entry which is used as name of the block."
8805 (unless (bolp) (newline))
8806 (let ((name (plist-get plist :name)))
8807 (insert "#+BEGIN: " name)
8808 (while plist
8809 (if (eq (car plist) :name)
8810 (setq plist (cddr plist))
8811 (insert " " (prin1-to-string (pop plist)))))
8812 (insert "\n\n#+END:\n")
8813 (beginning-of-line -2)))
8815 (defun org-prepare-dblock ()
8816 "Prepare dynamic block for refresh.
8817 This empties the block, puts the cursor at the insert position and returns
8818 the property list including an extra property :name with the block name."
8819 (unless (looking-at org-dblock-start-re)
8820 (error "Not at a dynamic block"))
8821 (let* ((begdel (1+ (match-end 0)))
8822 (name (org-no-properties (match-string 1)))
8823 (params (append (list :name name)
8824 (read (concat "(" (match-string 3) ")")))))
8825 (unless (re-search-forward org-dblock-end-re nil t)
8826 (error "Dynamic block not terminated"))
8827 (setq params
8828 (append params
8829 (list :content (buffer-substring
8830 begdel (match-beginning 0)))))
8831 (delete-region begdel (match-beginning 0))
8832 (goto-char begdel)
8833 (open-line 1)
8834 params))
8836 (defun org-map-dblocks (&optional command)
8837 "Apply COMMAND to all dynamic blocks in the current buffer.
8838 If COMMAND is not given, use `org-update-dblock'."
8839 (let ((cmd (or command 'org-update-dblock))
8840 pos)
8841 (save-excursion
8842 (goto-char (point-min))
8843 (while (re-search-forward org-dblock-start-re nil t)
8844 (goto-char (setq pos (match-beginning 0)))
8845 (condition-case nil
8846 (funcall cmd)
8847 (error (message "Error during update of dynamic block")))
8848 (goto-char pos)
8849 (unless (re-search-forward org-dblock-end-re nil t)
8850 (error "Dynamic block not terminated"))))))
8852 (defun org-dblock-update (&optional arg)
8853 "User command for updating dynamic blocks.
8854 Update the dynamic block at point. With prefix ARG, update all dynamic
8855 blocks in the buffer."
8856 (interactive "P")
8857 (if arg
8858 (org-update-all-dblocks)
8859 (or (looking-at org-dblock-start-re)
8860 (org-beginning-of-dblock))
8861 (org-update-dblock)))
8863 (defun org-update-dblock ()
8864 "Update the dynamic block at point
8865 This means to empty the block, parse for parameters and then call
8866 the correct writing function."
8867 (save-window-excursion
8868 (let* ((pos (point))
8869 (line (org-current-line))
8870 (params (org-prepare-dblock))
8871 (name (plist-get params :name))
8872 (cmd (intern (concat "org-dblock-write:" name))))
8873 (message "Updating dynamic block `%s' at line %d..." name line)
8874 (funcall cmd params)
8875 (message "Updating dynamic block `%s' at line %d...done" name line)
8876 (goto-char pos))))
8878 (defun org-beginning-of-dblock ()
8879 "Find the beginning of the dynamic block at point.
8880 Error if there is no such block at point."
8881 (let ((pos (point))
8882 beg)
8883 (end-of-line 1)
8884 (if (and (re-search-backward org-dblock-start-re nil t)
8885 (setq beg (match-beginning 0))
8886 (re-search-forward org-dblock-end-re nil t)
8887 (> (match-end 0) pos))
8888 (goto-char beg)
8889 (goto-char pos)
8890 (error "Not in a dynamic block"))))
8892 (defun org-update-all-dblocks ()
8893 "Update all dynamic blocks in the buffer.
8894 This function can be used in a hook."
8895 (when (org-mode-p)
8896 (org-map-dblocks 'org-update-dblock)))
8899 ;;;; Completion
8901 (defconst org-additional-option-like-keywords
8902 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
8903 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
8904 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:" "ATTR_LaTeX"
8905 "BEGIN:" "END:"
8906 "ORGTBL" "TBLFM:" "TBLNAME:"
8907 "BEGIN_EXAMPLE" "END_EXAMPLE"
8908 "BEGIN_QUOTE" "END_QUOTE"
8909 "BEGIN_VERSE" "END_VERSE"
8910 "BEGIN_CENTER" "END_CENTER"
8911 "BEGIN_SRC" "END_SRC"
8912 "CATEGORY" "COLUMNS"
8913 "CAPTION" "LABEL"
8914 "BIND"))
8916 (defcustom org-structure-template-alist
8918 ("s" "#+begin_src ?\n\n#+end_src"
8919 "<src lang=\"?\">\n\n</src>")
8920 ("e" "#+begin_example\n?\n#+end_example"
8921 "<example>\n?\n</example>")
8922 ("q" "#+begin_quote\n?\n#+end_quote"
8923 "<quote>\n?\n</quote>")
8924 ("v" "#+begin_verse\n?\n#+end_verse"
8925 "<verse>\n?\n/verse>")
8926 ("c" "#+begin_center\n?\n#+end_center"
8927 "<center>\n?\n/center>")
8928 ("l" "#+begin_latex\n?\n#+end_latex"
8929 "<literal style=\"latex\">\n?\n</literal>")
8930 ("L" "#+latex: "
8931 "<literal style=\"latex\">?</literal>")
8932 ("h" "#+begin_html\n?\n#+end_html"
8933 "<literal style=\"html\">\n?\n</literal>")
8934 ("H" "#+html: "
8935 "<literal style=\"html\">?</literal>")
8936 ("a" "#+begin_ascii\n?\n#+end_ascii")
8937 ("A" "#+ascii: ")
8938 ("i" "#+include %file ?"
8939 "<include file=%file markup=\"?\">")
8941 "Structure completion elements.
8942 This is a list of abbreviation keys and values. The value gets inserted
8943 it you type @samp{.} followed by the key and then the completion key,
8944 usually `M-TAB'. %file will be replaced by a file name after prompting
8945 for the file using completion.
8946 There are two templates for each key, the first uses the original Org syntax,
8947 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8948 the default when the /org-mtags.el/ module has been loaded. See also the
8949 variable `org-mtags-prefer-muse-templates'.
8950 This is an experimental feature, it is undecided if it is going to stay in."
8951 :group 'org-completion
8952 :type '(repeat
8953 (string :tag "Key")
8954 (string :tag "Template")
8955 (string :tag "Muse Template")))
8957 (defun org-try-structure-completion ()
8958 "Try to complete a structure template before point.
8959 This looks for strings like \"<e\" on an otherwise empty line and
8960 expands them."
8961 (let ((l (buffer-substring (point-at-bol) (point)))
8963 (when (and (looking-at "[ \t]*$")
8964 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8965 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8966 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8967 (match-beginning 1)) a)
8968 t)))
8970 (defun org-complete-expand-structure-template (start cell)
8971 "Expand a structure template."
8972 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8973 (rpl (nth (if musep 2 1) cell))
8974 (ind ""))
8975 (delete-region start (point))
8976 (when (string-match "\\`#\\+" rpl)
8977 (cond
8978 ((bolp))
8979 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8980 (setq ind (buffer-substring (point-at-bol) (point))))
8981 (t (newline))))
8982 (setq start (point))
8983 (if (string-match "%file" rpl)
8984 (setq rpl (replace-match
8985 (concat
8986 "\""
8987 (save-match-data
8988 (abbreviate-file-name (read-file-name "Include file: ")))
8989 "\"")
8990 t t rpl)))
8991 (setq rpl (mapconcat 'identity (split-string rpl "\n")
8992 (concat "\n" ind)))
8993 (insert rpl)
8994 (if (re-search-backward "\\?" start t) (delete-char 1))))
8997 (defun org-complete (&optional arg)
8998 "Perform completion on word at point.
8999 At the beginning of a headline, this completes TODO keywords as given in
9000 `org-todo-keywords'.
9001 If the current word is preceded by a backslash, completes the TeX symbols
9002 that are supported for HTML support.
9003 If the current word is preceded by \"#+\", completes special words for
9004 setting file options.
9005 In the line after \"#+STARTUP:, complete valid keywords.\"
9006 At all other locations, this simply calls the value of
9007 `org-completion-fallback-command'."
9008 (interactive "P")
9009 (org-without-partial-completion
9010 (catch 'exit
9011 (let* ((a nil)
9012 (end (point))
9013 (beg1 (save-excursion
9014 (skip-chars-backward (org-re "[:alnum:]_@"))
9015 (point)))
9016 (beg (save-excursion
9017 (skip-chars-backward "a-zA-Z0-9_:$")
9018 (point)))
9019 (confirm (lambda (x) (stringp (car x))))
9020 (searchhead (equal (char-before beg) ?*))
9021 (struct
9022 (when (and (member (char-before beg1) '(?. ?<))
9023 (setq a (assoc (buffer-substring beg1 (point))
9024 org-structure-template-alist)))
9025 (org-complete-expand-structure-template (1- beg1) a)
9026 (throw 'exit t)))
9027 (tag (and (equal (char-before beg1) ?:)
9028 (equal (char-after (point-at-bol)) ?*)))
9029 (prop (and (equal (char-before beg1) ?:)
9030 (not (equal (char-after (point-at-bol)) ?*))))
9031 (texp (equal (char-before beg) ?\\))
9032 (link (equal (char-before beg) ?\[))
9033 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9034 beg)
9035 "#+"))
9036 (startup (string-match "^#\\+STARTUP:.*"
9037 (buffer-substring (point-at-bol) (point))))
9038 (completion-ignore-case opt)
9039 (type nil)
9040 (tbl nil)
9041 (table (cond
9042 (opt
9043 (setq type :opt)
9044 (require 'org-exp)
9045 (append
9046 (mapcar
9047 (lambda (x)
9048 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9049 (cons (match-string 2 x) (match-string 1 x)))
9050 (org-split-string (org-get-current-options) "\n"))
9051 (mapcar 'list org-additional-option-like-keywords)))
9052 (startup
9053 (setq type :startup)
9054 org-startup-options)
9055 (link (append org-link-abbrev-alist-local
9056 org-link-abbrev-alist))
9057 (texp
9058 (setq type :tex)
9059 org-html-entities)
9060 ((string-match "\\`\\*+[ \t]+\\'"
9061 (buffer-substring (point-at-bol) beg))
9062 (setq type :todo)
9063 (mapcar 'list org-todo-keywords-1))
9064 (searchhead
9065 (setq type :searchhead)
9066 (save-excursion
9067 (goto-char (point-min))
9068 (while (re-search-forward org-todo-line-regexp nil t)
9069 (push (list
9070 (org-make-org-heading-search-string
9071 (match-string 3) t))
9072 tbl)))
9073 tbl)
9074 (tag (setq type :tag beg beg1)
9075 (or org-tag-alist (org-get-buffer-tags)))
9076 (prop (setq type :prop beg beg1)
9077 (mapcar 'list (org-buffer-property-keys nil t t)))
9078 (t (progn
9079 (call-interactively org-completion-fallback-command)
9080 (throw 'exit nil)))))
9081 (pattern (buffer-substring-no-properties beg end))
9082 (completion (try-completion pattern table confirm)))
9083 (cond ((eq completion t)
9084 (if (not (assoc (upcase pattern) table))
9085 (message "Already complete")
9086 (if (and (equal type :opt)
9087 (not (member (car (assoc (upcase pattern) table))
9088 org-additional-option-like-keywords)))
9089 (insert (substring (cdr (assoc (upcase pattern) table))
9090 (length pattern)))
9091 (if (memq type '(:tag :prop)) (insert ":")))))
9092 ((null completion)
9093 (message "Can't find completion for \"%s\"" pattern)
9094 (ding))
9095 ((not (string= pattern completion))
9096 (delete-region beg end)
9097 (if (string-match " +$" completion)
9098 (setq completion (replace-match "" t t completion)))
9099 (insert completion)
9100 (if (get-buffer-window "*Completions*")
9101 (delete-window (get-buffer-window "*Completions*")))
9102 (if (assoc completion table)
9103 (if (eq type :todo) (insert " ")
9104 (if (memq type '(:tag :prop)) (insert ":"))))
9105 (if (and (equal type :opt) (assoc completion table))
9106 (message "%s" (substitute-command-keys
9107 "Press \\[org-complete] again to insert example settings"))))
9109 (message "Making completion list...")
9110 (let ((list (sort (all-completions pattern table confirm)
9111 'string<)))
9112 (with-output-to-temp-buffer "*Completions*"
9113 (condition-case nil
9114 ;; Protection needed for XEmacs and emacs 21
9115 (display-completion-list list pattern)
9116 (error (display-completion-list list)))))
9117 (message "Making completion list...%s" "done")))))))
9119 ;;;; TODO, DEADLINE, Comments
9121 (defun org-toggle-comment ()
9122 "Change the COMMENT state of an entry."
9123 (interactive)
9124 (save-excursion
9125 (org-back-to-heading)
9126 (let (case-fold-search)
9127 (if (looking-at (concat outline-regexp
9128 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9129 (replace-match "" t t nil 1)
9130 (if (looking-at outline-regexp)
9131 (progn
9132 (goto-char (match-end 0))
9133 (insert org-comment-string " ")))))))
9135 (defvar org-last-todo-state-is-todo nil
9136 "This is non-nil when the last TODO state change led to a TODO state.
9137 If the last change removed the TODO tag or switched to DONE, then
9138 this is nil.")
9140 (defvar org-setting-tags nil) ; dynamically skipped
9142 (defun org-parse-local-options (string var)
9143 "Parse STRING for startup setting relevant for variable VAR."
9144 (let ((rtn (symbol-value var))
9145 e opts)
9146 (save-match-data
9147 (if (or (not string) (not (string-match "\\S-" string)))
9149 (setq opts (delq nil (mapcar (lambda (x)
9150 (setq e (assoc x org-startup-options))
9151 (if (eq (nth 1 e) var) e nil))
9152 (org-split-string string "[ \t]+"))))
9153 (if (not opts)
9155 (setq rtn nil)
9156 (while (setq e (pop opts))
9157 (if (not (nth 3 e))
9158 (setq rtn (nth 2 e))
9159 (if (not (listp rtn)) (setq rtn nil))
9160 (push (nth 2 e) rtn)))
9161 rtn)))))
9163 (defvar org-todo-setup-filter-hook nil
9164 "Hook for functions that pre-filter todo specs.
9166 Each function takes a todo spec and returns either `nil' or the spec
9167 transformed into canonical form." )
9169 (defvar org-todo-get-default-hook nil
9170 "Hook for functions that get a default item for todo.
9172 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9173 `nil' or a string to be used for the todo mark." )
9175 (defvar org-agenda-headline-snapshot-before-repeat)
9177 (defun org-todo (&optional arg)
9178 "Change the TODO state of an item.
9179 The state of an item is given by a keyword at the start of the heading,
9180 like
9181 *** TODO Write paper
9182 *** DONE Call mom
9184 The different keywords are specified in the variable `org-todo-keywords'.
9185 By default the available states are \"TODO\" and \"DONE\".
9186 So for this example: when the item starts with TODO, it is changed to DONE.
9187 When it starts with DONE, the DONE is removed. And when neither TODO nor
9188 DONE are present, add TODO at the beginning of the heading.
9190 With C-u prefix arg, use completion to determine the new state.
9191 With numeric prefix arg, switch to that state.
9192 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9193 With a tripple C-u prefix, circumvent any state blocking.
9195 For calling through lisp, arg is also interpreted in the following way:
9196 'none -> empty state
9197 \"\"(empty string) -> switch to empty state
9198 'done -> switch to DONE
9199 'nextset -> switch to the next set of keywords
9200 'previousset -> switch to the previous set of keywords
9201 \"WAITING\" -> switch to the specified keyword, but only if it
9202 really is a member of `org-todo-keywords'."
9203 (interactive "P")
9204 (if (equal arg '(16)) (setq arg 'nextset))
9205 (let ((org-blocker-hook org-blocker-hook)
9206 (case-fold-search nil))
9207 (when (equal arg '(64))
9208 (setq arg nil org-blocker-hook nil))
9209 (when (and org-blocker-hook
9210 (or org-inhibit-blocking
9211 (org-entry-get nil "NOBLOCKING")))
9212 (setq org-blocker-hook nil))
9213 (save-excursion
9214 (catch 'exit
9215 (org-back-to-heading)
9216 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9217 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9218 (looking-at " *"))
9219 (let* ((match-data (match-data))
9220 (startpos (point-at-bol))
9221 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9222 (org-log-done org-log-done)
9223 (org-log-repeat org-log-repeat)
9224 (org-todo-log-states org-todo-log-states)
9225 (this (match-string 1))
9226 (hl-pos (match-beginning 0))
9227 (head (org-get-todo-sequence-head this))
9228 (ass (assoc head org-todo-kwd-alist))
9229 (interpret (nth 1 ass))
9230 (done-word (nth 3 ass))
9231 (final-done-word (nth 4 ass))
9232 (last-state (or this ""))
9233 (completion-ignore-case t)
9234 (member (member this org-todo-keywords-1))
9235 (tail (cdr member))
9236 (state (cond
9237 ((and org-todo-key-trigger
9238 (or (and (equal arg '(4))
9239 (eq org-use-fast-todo-selection 'prefix))
9240 (and (not arg) org-use-fast-todo-selection
9241 (not (eq org-use-fast-todo-selection
9242 'prefix)))))
9243 ;; Use fast selection
9244 (org-fast-todo-selection))
9245 ((and (equal arg '(4))
9246 (or (not org-use-fast-todo-selection)
9247 (not org-todo-key-trigger)))
9248 ;; Read a state with completion
9249 (org-ido-completing-read
9250 "State: " (mapcar (lambda(x) (list x))
9251 org-todo-keywords-1)
9252 nil t))
9253 ((eq arg 'right)
9254 (if this
9255 (if tail (car tail) nil)
9256 (car org-todo-keywords-1)))
9257 ((eq arg 'left)
9258 (if (equal member org-todo-keywords-1)
9260 (if this
9261 (nth (- (length org-todo-keywords-1)
9262 (length tail) 2)
9263 org-todo-keywords-1)
9264 (org-last org-todo-keywords-1))))
9265 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9266 (setq arg nil))) ; hack to fall back to cycling
9267 (arg
9268 ;; user or caller requests a specific state
9269 (cond
9270 ((equal arg "") nil)
9271 ((eq arg 'none) nil)
9272 ((eq arg 'done) (or done-word (car org-done-keywords)))
9273 ((eq arg 'nextset)
9274 (or (car (cdr (member head org-todo-heads)))
9275 (car org-todo-heads)))
9276 ((eq arg 'previousset)
9277 (let ((org-todo-heads (reverse org-todo-heads)))
9278 (or (car (cdr (member head org-todo-heads)))
9279 (car org-todo-heads))))
9280 ((car (member arg org-todo-keywords-1)))
9281 ((nth (1- (prefix-numeric-value arg))
9282 org-todo-keywords-1))))
9283 ((null member) (or head (car org-todo-keywords-1)))
9284 ((equal this final-done-word) nil) ;; -> make empty
9285 ((null tail) nil) ;; -> first entry
9286 ((memq interpret '(type priority))
9287 (if (eq this-command last-command)
9288 (car tail)
9289 (if (> (length tail) 0)
9290 (or done-word (car org-done-keywords))
9291 nil)))
9293 (car tail))))
9294 (state (or
9295 (run-hook-with-args-until-success
9296 'org-todo-get-default-hook state last-state)
9297 state))
9298 (next (if state (concat " " state " ") " "))
9299 (change-plist (list :type 'todo-state-change :from this :to state
9300 :position startpos))
9301 dolog now-done-p)
9302 (when org-blocker-hook
9303 (setq org-last-todo-state-is-todo
9304 (not (member this org-done-keywords)))
9305 (unless (save-excursion
9306 (save-match-data
9307 (run-hook-with-args-until-failure
9308 'org-blocker-hook change-plist)))
9309 (if (interactive-p)
9310 (error "TODO state change from %s to %s blocked" this state)
9311 ;; fail silently
9312 (message "TODO state change from %s to %s blocked" this state)
9313 (throw 'exit nil))))
9314 (store-match-data match-data)
9315 (replace-match next t t)
9316 (unless (pos-visible-in-window-p hl-pos)
9317 (message "TODO state changed to %s" (org-trim next)))
9318 (unless head
9319 (setq head (org-get-todo-sequence-head state)
9320 ass (assoc head org-todo-kwd-alist)
9321 interpret (nth 1 ass)
9322 done-word (nth 3 ass)
9323 final-done-word (nth 4 ass)))
9324 (when (memq arg '(nextset previousset))
9325 (message "Keyword-Set %d/%d: %s"
9326 (- (length org-todo-sets) -1
9327 (length (memq (assoc state org-todo-sets) org-todo-sets)))
9328 (length org-todo-sets)
9329 (mapconcat 'identity (assoc state org-todo-sets) " ")))
9330 (setq org-last-todo-state-is-todo
9331 (not (member state org-done-keywords)))
9332 (setq now-done-p (and (member state org-done-keywords)
9333 (not (member this org-done-keywords))))
9334 (and logging (org-local-logging logging))
9335 (when (and (or org-todo-log-states org-log-done)
9336 (not (eq org-inhibit-logging t))
9337 (not (memq arg '(nextset previousset))))
9338 ;; we need to look at recording a time and note
9339 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
9340 (nth 2 (assoc this org-todo-log-states))))
9341 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
9342 (setq dolog 'time))
9343 (when (and state
9344 (member state org-not-done-keywords)
9345 (not (member this org-not-done-keywords)))
9346 ;; This is now a todo state and was not one before
9347 ;; If there was a CLOSED time stamp, get rid of it.
9348 (org-add-planning-info nil nil 'closed))
9349 (when (and now-done-p org-log-done)
9350 ;; It is now done, and it was not done before
9351 (org-add-planning-info 'closed (org-current-time))
9352 (if (and (not dolog) (eq 'note org-log-done))
9353 (org-add-log-setup 'done state this 'findpos 'note)))
9354 (when (and state dolog)
9355 ;; This is a non-nil state, and we need to log it
9356 (org-add-log-setup 'state state this 'findpos dolog)))
9357 ;; Fixup tag positioning
9358 (org-todo-trigger-tag-changes state)
9359 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
9360 (when org-provide-todo-statistics
9361 (org-update-parent-todo-statistics))
9362 (run-hooks 'org-after-todo-state-change-hook)
9363 (if (and arg (not (member state org-done-keywords)))
9364 (setq head (org-get-todo-sequence-head state)))
9365 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9366 ;; Do we need to trigger a repeat?
9367 (when now-done-p
9368 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
9369 ;; This is for the agenda, take a snapshot of the headline.
9370 (save-match-data
9371 (setq org-agenda-headline-snapshot-before-repeat
9372 (org-get-heading))))
9373 (org-auto-repeat-maybe state))
9374 ;; Fixup cursor location if close to the keyword
9375 (if (and (outline-on-heading-p)
9376 (not (bolp))
9377 (save-excursion (beginning-of-line 1)
9378 (looking-at org-todo-line-regexp))
9379 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9380 (progn
9381 (goto-char (or (match-end 2) (match-end 1)))
9382 (and (looking-at " ") (just-one-space))))
9383 (when org-trigger-hook
9384 (save-excursion
9385 (run-hook-with-args 'org-trigger-hook change-plist))))))))
9387 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
9388 "Block turning an entry into a TODO, using the hierarchy.
9389 This checks whether the current task should be blocked from state
9390 changes. Such blocking occurs when:
9392 1. The task has children which are not all in a completed state.
9394 2. A task has a parent with the property :ORDERED:, and there
9395 are siblings prior to the current task with incomplete
9396 status.
9398 3. The parent of the task is blocked because it has siblings that should
9399 be done first, or is child of a block grandparent TODO entry."
9401 (catch 'dont-block
9402 ;; If this is not a todo state change, or if this entry is already DONE,
9403 ;; do not block
9404 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9405 (member (plist-get change-plist :from)
9406 (cons 'done org-done-keywords))
9407 (member (plist-get change-plist :to)
9408 (cons 'todo org-not-done-keywords)))
9409 (throw 'dont-block t))
9410 ;; If this task has children, and any are undone, it's blocked
9411 (save-excursion
9412 (org-back-to-heading t)
9413 (let ((this-level (funcall outline-level)))
9414 (outline-next-heading)
9415 (let ((child-level (funcall outline-level)))
9416 (while (and (not (eobp))
9417 (> child-level this-level))
9418 ;; this todo has children, check whether they are all
9419 ;; completed
9420 (if (and (not (org-entry-is-done-p))
9421 (org-entry-is-todo-p))
9422 (throw 'dont-block nil))
9423 (outline-next-heading)
9424 (setq child-level (funcall outline-level))))))
9425 ;; Otherwise, if the task's parent has the :ORDERED: property, and
9426 ;; any previous siblings are undone, it's blocked
9427 (save-excursion
9428 (org-back-to-heading t)
9429 (let* ((pos (point))
9430 (parent-pos (and (org-up-heading-safe) (point))))
9431 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9432 (when (and (org-entry-get (point) "ORDERED")
9433 (forward-line 1)
9434 (re-search-forward org-not-done-heading-regexp pos t))
9435 (throw 'dont-block nil)) ; block, there is an older sibling not done.
9436 ;; Search further up the hierarchy, to see if an anchestor is blocked
9437 (while t
9438 (goto-char parent-pos)
9439 (if (not (looking-at org-not-done-heading-regexp))
9440 (throw 'dont-block t)) ; do not block, parent is not a TODO
9441 (setq pos (point))
9442 (setq parent-pos (and (org-up-heading-safe) (point)))
9443 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9444 (when (and (org-entry-get (point) "ORDERED")
9445 (forward-line 1)
9446 (re-search-forward org-not-done-heading-regexp pos t))
9447 (throw 'dont-block nil))))))) ; block, older sibling not done.
9449 (defcustom org-track-ordered-property-with-tag nil
9450 "Should the ORDERED property also be shown as a tag?
9451 The ORDERED property decides if an entry should require subtasks to be
9452 completed in sequence. Since a property is not very visible, setting
9453 this option means that toggling the ORDERED property with the command
9454 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
9455 not relevant for the behavior, but it makes things more visible.
9457 Note that toggling the tag with tags commands will not change the property
9458 and therefore not influence behavior!
9460 This can be t, meaning the tag ORDERED should be used, It can also be a
9461 string to select a different tag for this task."
9462 :group 'org-todo
9463 :type '(choice
9464 (const :tag "No tracking" nil)
9465 (const :tag "Track with ORDERED tag" t)
9466 (string :tag "Use other tag")))
9468 (defun org-toggle-ordered-property ()
9469 "Toggle the ORDERED property of the current entry.
9470 For better visibility, you can track the value of this property with a tag.
9471 See variable `org-track-ordered-property-with-tag'."
9472 (interactive)
9473 (let* ((t1 org-track-ordered-property-with-tag)
9474 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
9475 (save-excursion
9476 (org-back-to-heading)
9477 (if (org-entry-get nil "ORDERED")
9478 (progn
9479 (org-delete-property "ORDERED")
9480 (and tag (org-toggle-tag tag 'off))
9481 (message "Subtasks can be completed in arbitrary order"))
9482 (org-entry-put nil "ORDERED" "t")
9483 (and tag (org-toggle-tag tag 'on))
9484 (message "Subtasks must be completed in sequence")))))
9486 (defvar org-blocked-by-checkboxes) ; dynamically scoped
9487 (defun org-block-todo-from-checkboxes (change-plist)
9488 "Block turning an entry into a TODO, using checkboxes.
9489 This checks whether the current task should be blocked from state
9490 changes because there are uncheckd boxes in this entry."
9491 (catch 'dont-block
9492 ;; If this is not a todo state change, or if this entry is already DONE,
9493 ;; do not block
9494 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9495 (member (plist-get change-plist :from)
9496 (cons 'done org-done-keywords))
9497 (member (plist-get change-plist :to)
9498 (cons 'todo org-not-done-keywords)))
9499 (throw 'dont-block t))
9500 ;; If this task has checkboxes that are not checked, it's blocked
9501 (save-excursion
9502 (org-back-to-heading t)
9503 (let ((beg (point)) end)
9504 (outline-next-heading)
9505 (setq end (point))
9506 (goto-char beg)
9507 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
9508 end t)
9509 (progn
9510 (if (boundp 'org-blocked-by-checkboxes)
9511 (setq org-blocked-by-checkboxes t))
9512 (throw 'dont-block nil)))))
9513 t)) ; do not block
9515 (defvar org-entry-property-inherited-from) ;; defined below
9516 (defun org-update-parent-todo-statistics ()
9517 "Update any statistics cookie in the parent of the current headline.
9518 When `org-hierarchical-todo-statistics' is nil, statistics will cover
9519 the entire subtree and this will travel up the hierarchy and update
9520 statistics everywhere."
9521 (interactive)
9522 (let* ((lim 0) prop
9523 (recursive (or (not org-hierarchical-todo-statistics)
9524 (string-match
9525 "\\<recursive\\>"
9526 (or (setq prop (org-entry-get
9527 nil "COOKIE_DATA" 'inherit)) ""))))
9528 (lim (or (and prop (marker-position
9529 org-entry-property-inherited-from))
9530 lim))
9531 (first t)
9532 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
9533 level ltoggle l1
9534 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
9535 (catch 'exit
9536 (save-excursion
9537 (beginning-of-line 1)
9538 (if (org-at-heading-p)
9539 (setq ltoggle (funcall outline-level))
9540 (error "This should not happen"))
9541 (while (and (setq level (org-up-heading-safe))
9542 (or recursive first)
9543 (>= (point) lim))
9544 (setq first nil)
9545 (unless (and level
9546 (not (string-match
9547 "\\<checkbox\\>"
9548 (downcase
9549 (or (org-entry-get
9550 nil "COOKIE_DATA")
9551 "")))))
9552 (throw 'exit nil))
9553 (while (re-search-forward box-re (point-at-eol) t)
9554 (setq cnt-all 0 cnt-done 0 cookie-present t)
9555 (setq is-percent (match-end 2))
9556 (save-match-data
9557 (unless (outline-next-heading) (throw 'exit nil))
9558 (while (and (looking-at org-complex-heading-regexp)
9559 (> (setq l1 (length (match-string 1))) level))
9560 (setq kwd (and (or recursive (= l1 ltoggle))
9561 (match-string 2)))
9562 (if (or (eq org-provide-todo-statistics 'all-headlines)
9563 (and (listp org-provide-todo-statistics)
9564 (or (member kwd org-provide-todo-statistics)
9565 (member kwd org-done-keywords))))
9566 (setq cnt-all (1+ cnt-all))
9567 (if (eq org-provide-todo-statistics t)
9568 (and kwd (setq cnt-all (1+ cnt-all)))))
9569 (and (member kwd org-done-keywords)
9570 (setq cnt-done (1+ cnt-done)))
9571 (outline-next-heading)))
9572 (replace-match
9573 (if is-percent
9574 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
9575 (format "[%d/%d]" cnt-done cnt-all)))))
9576 (when cookie-present
9577 (run-hook-with-args 'org-after-todo-statistics-hook
9578 cnt-done (- cnt-all cnt-done)))))
9579 (run-hooks 'org-todo-statistics-hook)))
9581 (defvar org-after-todo-statistics-hook nil
9582 "Hook that is called after a TODO statistics cookie has been updated.
9583 Each function is called with two arguments: the number of not-done entries
9584 and the number of done entries.
9586 For example, the following function, when added to this hook, will switch
9587 an entry to DONE when all children are done, and back to TODO when new
9588 entries are set to a TODO status. Note that this hook is only called
9589 when there is a statistics cookie in the headline!
9591 (defun org-summary-todo (n-done n-not-done)
9592 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
9593 (let (org-log-done org-log-states) ; turn off logging
9594 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
9597 (defvar org-todo-statistics-hook nil
9598 "Hook that is run whenever Org thinks TODO statistics should be updated.
9599 This hook runs even if there is no statisics cookie present, in which case
9600 `org-after-todo-statistics-hook' would not run.")
9602 (defun org-todo-trigger-tag-changes (state)
9603 "Apply the changes defined in `org-todo-state-tags-triggers'."
9604 (let ((l org-todo-state-tags-triggers)
9605 changes)
9606 (when (or (not state) (equal state ""))
9607 (setq changes (append changes (cdr (assoc "" l)))))
9608 (when (and (stringp state) (> (length state) 0))
9609 (setq changes (append changes (cdr (assoc state l)))))
9610 (when (member state org-not-done-keywords)
9611 (setq changes (append changes (cdr (assoc 'todo l)))))
9612 (when (member state org-done-keywords)
9613 (setq changes (append changes (cdr (assoc 'done l)))))
9614 (dolist (c changes)
9615 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
9617 (defun org-local-logging (value)
9618 "Get logging settings from a property VALUE."
9619 (let* (words w a)
9620 ;; directly set the variables, they are already local.
9621 (setq org-log-done nil
9622 org-log-repeat nil
9623 org-todo-log-states nil)
9624 (setq words (org-split-string value))
9625 (while (setq w (pop words))
9626 (cond
9627 ((setq a (assoc w org-startup-options))
9628 (and (member (nth 1 a) '(org-log-done org-log-repeat))
9629 (set (nth 1 a) (nth 2 a))))
9630 ((setq a (org-extract-log-state-settings w))
9631 (and (member (car a) org-todo-keywords-1)
9632 (push a org-todo-log-states)))))))
9634 (defun org-get-todo-sequence-head (kwd)
9635 "Return the head of the TODO sequence to which KWD belongs.
9636 If KWD is not set, check if there is a text property remembering the
9637 right sequence."
9638 (let (p)
9639 (cond
9640 ((not kwd)
9641 (or (get-text-property (point-at-bol) 'org-todo-head)
9642 (progn
9643 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
9644 nil (point-at-eol)))
9645 (get-text-property p 'org-todo-head))))
9646 ((not (member kwd org-todo-keywords-1))
9647 (car org-todo-keywords-1))
9648 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
9650 (defun org-fast-todo-selection ()
9651 "Fast TODO keyword selection with single keys.
9652 Returns the new TODO keyword, or nil if no state change should occur."
9653 (let* ((fulltable org-todo-key-alist)
9654 (done-keywords org-done-keywords) ;; needed for the faces.
9655 (maxlen (apply 'max (mapcar
9656 (lambda (x)
9657 (if (stringp (car x)) (string-width (car x)) 0))
9658 fulltable)))
9659 (expert nil)
9660 (fwidth (+ maxlen 3 1 3))
9661 (ncol (/ (- (window-width) 4) fwidth))
9662 tg cnt e c tbl
9663 groups ingroup)
9664 (save-excursion
9665 (save-window-excursion
9666 (if expert
9667 (set-buffer (get-buffer-create " *Org todo*"))
9668 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
9669 (erase-buffer)
9670 (org-set-local 'org-done-keywords done-keywords)
9671 (setq tbl fulltable cnt 0)
9672 (while (setq e (pop tbl))
9673 (cond
9674 ((equal e '(:startgroup))
9675 (push '() groups) (setq ingroup t)
9676 (when (not (= cnt 0))
9677 (setq cnt 0)
9678 (insert "\n"))
9679 (insert "{ "))
9680 ((equal e '(:endgroup))
9681 (setq ingroup nil cnt 0)
9682 (insert "}\n"))
9683 ((equal e '(:newline))
9684 (when (not (= cnt 0))
9685 (setq cnt 0)
9686 (insert "\n")
9687 (setq e (car tbl))
9688 (while (equal (car tbl) '(:newline))
9689 (insert "\n")
9690 (setq tbl (cdr tbl)))))
9692 (setq tg (car e) c (cdr e))
9693 (if ingroup (push tg (car groups)))
9694 (setq tg (org-add-props tg nil 'face
9695 (org-get-todo-face tg)))
9696 (if (and (= cnt 0) (not ingroup)) (insert " "))
9697 (insert "[" c "] " tg (make-string
9698 (- fwidth 4 (length tg)) ?\ ))
9699 (when (= (setq cnt (1+ cnt)) ncol)
9700 (insert "\n")
9701 (if ingroup (insert " "))
9702 (setq cnt 0)))))
9703 (insert "\n")
9704 (goto-char (point-min))
9705 (if (not expert) (org-fit-window-to-buffer))
9706 (message "[a-z..]:Set [SPC]:clear")
9707 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9708 (cond
9709 ((or (= c ?\C-g)
9710 (and (= c ?q) (not (rassoc c fulltable))))
9711 (setq quit-flag t))
9712 ((= c ?\ ) nil)
9713 ((setq e (rassoc c fulltable) tg (car e))
9715 (t (setq quit-flag t)))))))
9717 (defun org-entry-is-todo-p ()
9718 (member (org-get-todo-state) org-not-done-keywords))
9720 (defun org-entry-is-done-p ()
9721 (member (org-get-todo-state) org-done-keywords))
9723 (defun org-get-todo-state ()
9724 (save-excursion
9725 (org-back-to-heading t)
9726 (and (looking-at org-todo-line-regexp)
9727 (match-end 2)
9728 (match-string 2))))
9730 (defun org-at-date-range-p (&optional inactive-ok)
9731 "Is the cursor inside a date range?"
9732 (interactive)
9733 (save-excursion
9734 (catch 'exit
9735 (let ((pos (point)))
9736 (skip-chars-backward "^[<\r\n")
9737 (skip-chars-backward "<[")
9738 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9739 (>= (match-end 0) pos)
9740 (throw 'exit t))
9741 (skip-chars-backward "^<[\r\n")
9742 (skip-chars-backward "<[")
9743 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9744 (>= (match-end 0) pos)
9745 (throw 'exit t)))
9746 nil)))
9748 (defun org-get-repeat ()
9749 "Check if there is a deadline/schedule with repeater in this entry."
9750 (save-match-data
9751 (save-excursion
9752 (org-back-to-heading t)
9753 (if (re-search-forward
9754 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9755 (match-string 1)))))
9757 (defvar org-last-changed-timestamp)
9758 (defvar org-last-inserted-timestamp)
9759 (defvar org-log-post-message)
9760 (defvar org-log-note-purpose)
9761 (defvar org-log-note-how)
9762 (defvar org-log-note-extra)
9763 (defun org-auto-repeat-maybe (done-word)
9764 "Check if the current headline contains a repeated deadline/schedule.
9765 If yes, set TODO state back to what it was and change the base date
9766 of repeating deadline/scheduled time stamps to new date.
9767 This function is run automatically after each state change to a DONE state."
9768 ;; last-state is dynamically scoped into this function
9769 (let* ((repeat (org-get-repeat))
9770 (aa (assoc last-state org-todo-kwd-alist))
9771 (interpret (nth 1 aa))
9772 (head (nth 2 aa))
9773 (whata '(("d" . day) ("m" . month) ("y" . year)))
9774 (msg "Entry repeats: ")
9775 (org-log-done nil)
9776 (org-todo-log-states nil)
9777 (nshiftmax 10) (nshift 0)
9778 re type n what ts time)
9779 (when repeat
9780 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9781 (org-todo (if (eq interpret 'type) last-state head))
9782 (org-entry-put nil "LAST_REPEAT" (format-time-string
9783 (org-time-stamp-format t t)))
9784 (when org-log-repeat
9785 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9786 (memq 'org-add-log-note post-command-hook))
9787 ;; OK, we are already setup for some record
9788 (if (eq org-log-repeat 'note)
9789 ;; make sure we take a note, not only a time stamp
9790 (setq org-log-note-how 'note))
9791 ;; Set up for taking a record
9792 (org-add-log-setup 'state (or done-word (car org-done-keywords))
9793 last-state
9794 'findpos org-log-repeat)))
9795 (org-back-to-heading t)
9796 (org-add-planning-info nil nil 'closed)
9797 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9798 org-deadline-time-regexp "\\)\\|\\("
9799 org-ts-regexp "\\)"))
9800 (while (re-search-forward
9801 re (save-excursion (outline-next-heading) (point)) t)
9802 (setq type (if (match-end 1) org-scheduled-string
9803 (if (match-end 3) org-deadline-string "Plain:"))
9804 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
9805 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
9806 (setq n (string-to-number (match-string 2 ts))
9807 what (match-string 3 ts))
9808 (if (equal what "w") (setq n (* n 7) what "d"))
9809 ;; Preparation, see if we need to modify the start date for the change
9810 (when (match-end 1)
9811 (setq time (save-match-data (org-time-string-to-time ts)))
9812 (cond
9813 ((equal (match-string 1 ts) ".")
9814 ;; Shift starting date to today
9815 (org-timestamp-change
9816 (- (time-to-days (current-time)) (time-to-days time))
9817 'day))
9818 ((equal (match-string 1 ts) "+")
9819 (while (or (= nshift 0)
9820 (<= (time-to-days time) (time-to-days (current-time))))
9821 (when (= (incf nshift) nshiftmax)
9822 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
9823 (error "Abort")))
9824 (org-timestamp-change n (cdr (assoc what whata)))
9825 (org-at-timestamp-p t)
9826 (setq ts (match-string 1))
9827 (setq time (save-match-data (org-time-string-to-time ts))))
9828 (org-timestamp-change (- n) (cdr (assoc what whata)))
9829 ;; rematch, so that we have everything in place for the real shift
9830 (org-at-timestamp-p t)
9831 (setq ts (match-string 1))
9832 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
9833 (org-timestamp-change n (cdr (assoc what whata)))
9834 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
9835 (setq org-log-post-message msg)
9836 (message "%s" msg))))
9838 (defun org-show-todo-tree (arg)
9839 "Make a compact tree which shows all headlines marked with TODO.
9840 The tree will show the lines where the regexp matches, and all higher
9841 headlines above the match.
9842 With a \\[universal-argument] prefix, prompt for a regexp to match.
9843 With a numeric prefix N, construct a sparse tree for the Nth element
9844 of `org-todo-keywords-1'."
9845 (interactive "P")
9846 (let ((case-fold-search nil)
9847 (kwd-re
9848 (cond ((null arg) org-not-done-regexp)
9849 ((equal arg '(4))
9850 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
9851 (mapcar 'list org-todo-keywords-1))))
9852 (concat "\\("
9853 (mapconcat 'identity (org-split-string kwd "|") "\\|")
9854 "\\)\\>")))
9855 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
9856 (regexp-quote (nth (1- (prefix-numeric-value arg))
9857 org-todo-keywords-1)))
9858 (t (error "Invalid prefix argument: %s" arg)))))
9859 (message "%d TODO entries found"
9860 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
9862 (defun org-deadline (&optional remove time)
9863 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
9864 With argument REMOVE, remove any deadline from the item.
9865 When TIME is set, it should be an internal time specification, and the
9866 scheduling will use the corresponding date."
9867 (interactive "P")
9868 (if remove
9869 (progn
9870 (org-remove-timestamp-with-keyword org-deadline-string)
9871 (message "Item no longer has a deadline."))
9872 (if (org-get-repeat)
9873 (error "Cannot change deadline on task with repeater, please do that by hand")
9874 (org-add-planning-info 'deadline time 'closed)
9875 (message "Deadline on %s" org-last-inserted-timestamp))))
9877 (defun org-schedule (&optional remove time)
9878 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
9879 With argument REMOVE, remove any scheduling date from the item.
9880 When TIME is set, it should be an internal time specification, and the
9881 scheduling will use the corresponding date."
9882 (interactive "P")
9883 (if remove
9884 (progn
9885 (org-remove-timestamp-with-keyword org-scheduled-string)
9886 (message "Item is no longer scheduled."))
9887 (if (org-get-repeat)
9888 (error "Cannot reschedule task with repeater, please do that by hand")
9889 (org-add-planning-info 'scheduled time 'closed)
9890 (message "Scheduled to %s" org-last-inserted-timestamp))))
9892 (defun org-get-scheduled-time (pom &optional inherit)
9893 "Get the scheduled time as a time tuple, of a format suitable
9894 for calling org-schedule with, or if there is no scheduling,
9895 returns nil."
9896 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
9897 (when time
9898 (apply 'encode-time (org-parse-time-string time)))))
9900 (defun org-get-deadline-time (pom &optional inherit)
9901 "Get the deadine as a time tuple, of a format suitable for
9902 calling org-deadlin with, or if there is no scheduling, returns
9903 nil."
9904 (let ((time (org-entry-get pom "DEADLINE" inherit)))
9905 (when time
9906 (apply 'encode-time (org-parse-time-string time)))))
9908 (defun org-remove-timestamp-with-keyword (keyword)
9909 "Remove all time stamps with KEYWORD in the current entry."
9910 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
9911 beg)
9912 (save-excursion
9913 (org-back-to-heading t)
9914 (setq beg (point))
9915 (org-end-of-subtree t t)
9916 (while (re-search-backward re beg t)
9917 (replace-match "")
9918 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9919 (equal (char-before) ?\ ))
9920 (backward-delete-char 1)
9921 (if (string-match "^[ \t]*$" (buffer-substring
9922 (point-at-bol) (point-at-eol)))
9923 (delete-region (point-at-bol)
9924 (min (point-max) (1+ (point-at-eol))))))))))
9926 (defun org-add-planning-info (what &optional time &rest remove)
9927 "Insert new timestamp with keyword in the line directly after the headline.
9928 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9929 If non is given, the user is prompted for a date.
9930 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9931 be removed."
9932 (interactive)
9933 (let (org-time-was-given org-end-time-was-given ts
9934 end default-time default-input)
9936 (catch 'exit
9937 (when (and (not time) (memq what '(scheduled deadline)))
9938 ;; Try to get a default date/time from existing timestamp
9939 (save-excursion
9940 (org-back-to-heading t)
9941 (setq end (save-excursion (outline-next-heading) (point)))
9942 (when (re-search-forward (if (eq what 'scheduled)
9943 org-scheduled-time-regexp
9944 org-deadline-time-regexp)
9945 end t)
9946 (setq ts (match-string 1)
9947 default-time
9948 (apply 'encode-time (org-parse-time-string ts))
9949 default-input (and ts (org-get-compact-tod ts))))))
9950 (when what
9951 ;; If necessary, get the time from the user
9952 (setq time (or time (org-read-date nil 'to-time nil nil
9953 default-time default-input))))
9955 (when (and org-insert-labeled-timestamps-at-point
9956 (member what '(scheduled deadline)))
9957 (insert
9958 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9959 (org-insert-time-stamp time org-time-was-given
9960 nil nil nil (list org-end-time-was-given))
9961 (setq what nil))
9962 (save-excursion
9963 (save-restriction
9964 (let (col list elt ts buffer-invisibility-spec)
9965 (org-back-to-heading t)
9966 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9967 (goto-char (match-end 1))
9968 (setq col (current-column))
9969 (goto-char (match-end 0))
9970 (if (eobp) (insert "\n") (forward-char 1))
9971 (when (and (not what)
9972 (not (looking-at
9973 (concat "[ \t]*"
9974 org-keyword-time-not-clock-regexp))))
9975 ;; Nothing to add, nothing to remove...... :-)
9976 (throw 'exit nil))
9977 (if (and (not (looking-at outline-regexp))
9978 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9979 "[^\r\n]*"))
9980 (not (equal (match-string 1) org-clock-string)))
9981 (narrow-to-region (match-beginning 0) (match-end 0))
9982 (insert-before-markers "\n")
9983 (backward-char 1)
9984 (narrow-to-region (point) (point))
9985 (and org-adapt-indentation (org-indent-to-column col)))
9986 ;; Check if we have to remove something.
9987 (setq list (cons what remove))
9988 (while list
9989 (setq elt (pop list))
9990 (goto-char (point-min))
9991 (when (or (and (eq elt 'scheduled)
9992 (re-search-forward org-scheduled-time-regexp nil t))
9993 (and (eq elt 'deadline)
9994 (re-search-forward org-deadline-time-regexp nil t))
9995 (and (eq elt 'closed)
9996 (re-search-forward org-closed-time-regexp nil t)))
9997 (replace-match "")
9998 (if (looking-at "--+<[^>]+>") (replace-match ""))
9999 (if (looking-at " +") (replace-match ""))))
10000 (goto-char (point-max))
10001 (when what
10002 (insert
10003 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
10004 (cond ((eq what 'scheduled) org-scheduled-string)
10005 ((eq what 'deadline) org-deadline-string)
10006 ((eq what 'closed) org-closed-string))
10007 " ")
10008 (setq ts (org-insert-time-stamp
10009 time
10010 (or org-time-was-given
10011 (and (eq what 'closed) org-log-done-with-time))
10012 (eq what 'closed)
10013 nil nil (list org-end-time-was-given)))
10014 (end-of-line 1))
10015 (goto-char (point-min))
10016 (widen)
10017 (if (and (looking-at "[ \t]+\n")
10018 (equal (char-before) ?\n))
10019 (delete-region (1- (point)) (point-at-eol)))
10020 ts))))))
10022 (defvar org-log-note-marker (make-marker))
10023 (defvar org-log-note-purpose nil)
10024 (defvar org-log-note-state nil)
10025 (defvar org-log-note-previous-state nil)
10026 (defvar org-log-note-how nil)
10027 (defvar org-log-note-extra nil)
10028 (defvar org-log-note-window-configuration nil)
10029 (defvar org-log-note-return-to (make-marker))
10030 (defvar org-log-post-message nil
10031 "Message to be displayed after a log note has been stored.
10032 The auto-repeater uses this.")
10034 (defun org-add-note ()
10035 "Add a note to the current entry.
10036 This is done in the same way as adding a state change note."
10037 (interactive)
10038 (org-add-log-setup 'note nil nil 'findpos nil))
10040 (defvar org-property-end-re)
10041 (defun org-add-log-setup (&optional purpose state prev-state
10042 findpos how &optional extra)
10043 "Set up the post command hook to take a note.
10044 If this is about to TODO state change, the new state is expected in STATE.
10045 When FINDPOS is non-nil, find the correct position for the note in
10046 the current entry. If not, assume that it can be inserted at point.
10047 HOW is an indicator what kind of note should be created.
10048 EXTRA is additional text that will be inserted into the notes buffer."
10049 (let* ((org-log-into-drawer (org-log-into-drawer))
10050 (drawer (cond ((stringp org-log-into-drawer)
10051 org-log-into-drawer)
10052 (org-log-into-drawer "LOGBOOK")
10053 (t nil))))
10054 (save-restriction
10055 (save-excursion
10056 (when findpos
10057 (org-back-to-heading t)
10058 (narrow-to-region (point) (save-excursion
10059 (outline-next-heading) (point)))
10060 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
10061 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
10062 "[^\r\n]*\\)?"))
10063 (goto-char (match-end 0))
10064 (cond
10065 (drawer
10066 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
10067 nil t)
10068 (progn
10069 (goto-char (match-end 0))
10070 (or org-log-states-order-reversed
10071 (and (re-search-forward org-property-end-re nil t)
10072 (goto-char (1- (match-beginning 0))))))
10073 (insert "\n:" drawer ":\n:END:")
10074 (beginning-of-line 0)
10075 (org-indent-line-function)
10076 (beginning-of-line 2)
10077 (org-indent-line-function)
10078 (end-of-line 0)))
10079 ((and org-log-state-notes-insert-after-drawers
10080 (save-excursion
10081 (forward-line) (looking-at org-drawer-regexp)))
10082 (forward-line)
10083 (while (looking-at org-drawer-regexp)
10084 (goto-char (match-end 0))
10085 (re-search-forward org-property-end-re (point-max) t)
10086 (forward-line))
10087 (forward-line -1)))
10088 (unless org-log-states-order-reversed
10089 (and (= (char-after) ?\n) (forward-char 1))
10090 (org-skip-over-state-notes)
10091 (skip-chars-backward " \t\n\r")))
10092 (move-marker org-log-note-marker (point))
10093 (setq org-log-note-purpose purpose
10094 org-log-note-state state
10095 org-log-note-previous-state prev-state
10096 org-log-note-how how
10097 org-log-note-extra extra)
10098 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
10100 (defun org-skip-over-state-notes ()
10101 "Skip past the list of State notes in an entry."
10102 (if (looking-at "\n[ \t]*- State") (forward-char 1))
10103 (while (looking-at "[ \t]*- State")
10104 (condition-case nil
10105 (org-next-item)
10106 (error (org-end-of-item)))))
10108 (defun org-add-log-note (&optional purpose)
10109 "Pop up a window for taking a note, and add this note later at point."
10110 (remove-hook 'post-command-hook 'org-add-log-note)
10111 (setq org-log-note-window-configuration (current-window-configuration))
10112 (delete-other-windows)
10113 (move-marker org-log-note-return-to (point))
10114 (switch-to-buffer (marker-buffer org-log-note-marker))
10115 (goto-char org-log-note-marker)
10116 (org-switch-to-buffer-other-window "*Org Note*")
10117 (erase-buffer)
10118 (if (memq org-log-note-how '(time state))
10119 (let (current-prefix-arg) (org-store-log-note))
10120 (let ((org-inhibit-startup t)) (org-mode))
10121 (insert (format "# Insert note for %s.
10122 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10123 (cond
10124 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10125 ((eq org-log-note-purpose 'done) "closed todo item")
10126 ((eq org-log-note-purpose 'state)
10127 (format "state change from \"%s\" to \"%s\""
10128 (or org-log-note-previous-state "")
10129 (or org-log-note-state "")))
10130 ((eq org-log-note-purpose 'note)
10131 "this entry")
10132 (t (error "This should not happen")))))
10133 (if org-log-note-extra (insert org-log-note-extra))
10134 (org-set-local 'org-finish-function 'org-store-log-note)))
10136 (defvar org-note-abort nil) ; dynamically scoped
10137 (defun org-store-log-note ()
10138 "Finish taking a log note, and insert it to where it belongs."
10139 (let ((txt (buffer-string))
10140 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10141 lines ind)
10142 (kill-buffer (current-buffer))
10143 (while (string-match "\\`#.*\n[ \t\n]*" txt)
10144 (setq txt (replace-match "" t t txt)))
10145 (if (string-match "\\s-+\\'" txt)
10146 (setq txt (replace-match "" t t txt)))
10147 (setq lines (org-split-string txt "\n"))
10148 (when (and note (string-match "\\S-" note))
10149 (setq note
10150 (org-replace-escapes
10151 note
10152 (list (cons "%u" (user-login-name))
10153 (cons "%U" user-full-name)
10154 (cons "%t" (format-time-string
10155 (org-time-stamp-format 'long 'inactive)
10156 (current-time)))
10157 (cons "%s" (if org-log-note-state
10158 (concat "\"" org-log-note-state "\"")
10159 ""))
10160 (cons "%S" (if org-log-note-previous-state
10161 (concat "\"" org-log-note-previous-state "\"")
10162 "\"\"")))))
10163 (if lines (setq note (concat note " \\\\")))
10164 (push note lines))
10165 (when (or current-prefix-arg org-note-abort)
10166 (when org-log-into-drawer
10167 (org-remove-empty-drawer-at
10168 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
10169 org-log-note-marker))
10170 (setq lines nil))
10171 (when lines
10172 (save-excursion
10173 (set-buffer (marker-buffer org-log-note-marker))
10174 (save-excursion
10175 (goto-char org-log-note-marker)
10176 (move-marker org-log-note-marker nil)
10177 (end-of-line 1)
10178 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
10179 (insert "- " (pop lines))
10180 (org-indent-line-function)
10181 (beginning-of-line 1)
10182 (looking-at "[ \t]*")
10183 (setq ind (concat (match-string 0) " "))
10184 (end-of-line 1)
10185 (while lines (insert "\n" ind (pop lines)))
10186 (message "Note stored")
10187 (org-back-to-heading t)
10188 (org-cycle-hide-drawers 'children)))))
10189 (set-window-configuration org-log-note-window-configuration)
10190 (with-current-buffer (marker-buffer org-log-note-return-to)
10191 (goto-char org-log-note-return-to))
10192 (move-marker org-log-note-return-to nil)
10193 (and org-log-post-message (message "%s" org-log-post-message)))
10195 (defun org-remove-empty-drawer-at (drawer pos)
10196 "Remove an emptyr DARWER drawer at position POS.
10197 POS may also be a marker."
10198 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
10199 (save-excursion
10200 (save-restriction
10201 (widen)
10202 (goto-char pos)
10203 (if (org-in-regexp
10204 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
10205 (replace-match ""))))))
10207 (defun org-sparse-tree (&optional arg)
10208 "Create a sparse tree, prompt for the details.
10209 This command can create sparse trees. You first need to select the type
10210 of match used to create the tree:
10212 t Show entries with a specific TODO keyword.
10213 m Show entries selected by a tags/property match.
10214 p Enter a property name and its value (both with completion on existing
10215 names/values) and show entries with that property.
10216 r Show entries matching a regular expression.
10217 d Show deadlines due within `org-deadline-warning-days'.
10218 b Show deadlines and scheduled items before a date.
10219 a Show deadlines and scheduled items after a date."
10220 (interactive "P")
10221 (let (ans kwd value)
10222 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
10223 (setq ans (read-char-exclusive))
10224 (cond
10225 ((equal ans ?d)
10226 (call-interactively 'org-check-deadlines))
10227 ((equal ans ?b)
10228 (call-interactively 'org-check-before-date))
10229 ((equal ans ?a)
10230 (call-interactively 'org-check-after-date))
10231 ((equal ans ?t)
10232 (org-show-todo-tree '(4)))
10233 ((member ans '(?T ?m))
10234 (call-interactively 'org-match-sparse-tree))
10235 ((member ans '(?p ?P))
10236 (setq kwd (org-ido-completing-read "Property: "
10237 (mapcar 'list (org-buffer-property-keys))))
10238 (setq value (org-ido-completing-read "Value: "
10239 (mapcar 'list (org-property-values kwd))))
10240 (unless (string-match "\\`{.*}\\'" value)
10241 (setq value (concat "\"" value "\"")))
10242 (org-match-sparse-tree arg (concat kwd "=" value)))
10243 ((member ans '(?r ?R ?/))
10244 (call-interactively 'org-occur))
10245 (t (error "No such sparse tree command \"%c\"" ans)))))
10247 (defvar org-occur-highlights nil
10248 "List of overlays used for occur matches.")
10249 (make-variable-buffer-local 'org-occur-highlights)
10250 (defvar org-occur-parameters nil
10251 "Parameters of the active org-occur calls.
10252 This is a list, each call to org-occur pushes as cons cell,
10253 containing the regular expression and the callback, onto the list.
10254 The list can contain several entries if `org-occur' has been called
10255 several time with the KEEP-PREVIOUS argument. Otherwise, this list
10256 will only contain one set of parameters. When the highlights are
10257 removed (for example with `C-c C-c', or with the next edit (depending
10258 on `org-remove-highlights-with-change'), this variable is emptied
10259 as well.")
10260 (make-variable-buffer-local 'org-occur-parameters)
10262 (defun org-occur (regexp &optional keep-previous callback)
10263 "Make a compact tree which shows all matches of REGEXP.
10264 The tree will show the lines where the regexp matches, and all higher
10265 headlines above the match. It will also show the heading after the match,
10266 to make sure editing the matching entry is easy.
10267 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
10268 call to `org-occur' will be kept, to allow stacking of calls to this
10269 command.
10270 If CALLBACK is non-nil, it is a function which is called to confirm
10271 that the match should indeed be shown."
10272 (interactive "sRegexp: \nP")
10273 (when (equal regexp "")
10274 (error "Regexp cannot be empty"))
10275 (unless keep-previous
10276 (org-remove-occur-highlights nil nil t))
10277 (push (cons regexp callback) org-occur-parameters)
10278 (let ((cnt 0))
10279 (save-excursion
10280 (goto-char (point-min))
10281 (if (or (not keep-previous) ; do not want to keep
10282 (not org-occur-highlights)) ; no previous matches
10283 ;; hide everything
10284 (org-overview))
10285 (while (re-search-forward regexp nil t)
10286 (when (or (not callback)
10287 (save-match-data (funcall callback)))
10288 (setq cnt (1+ cnt))
10289 (when org-highlight-sparse-tree-matches
10290 (org-highlight-new-match (match-beginning 0) (match-end 0)))
10291 (org-show-context 'occur-tree))))
10292 (when org-remove-highlights-with-change
10293 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10294 nil 'local))
10295 (unless org-sparse-tree-open-archived-trees
10296 (org-hide-archived-subtrees (point-min) (point-max)))
10297 (run-hooks 'org-occur-hook)
10298 (if (interactive-p)
10299 (message "%d match(es) for regexp %s" cnt regexp))
10300 cnt))
10302 (defun org-show-context (&optional key)
10303 "Make sure point and context and visible.
10304 How much context is shown depends upon the variables
10305 `org-show-hierarchy-above', `org-show-following-heading'. and
10306 `org-show-siblings'."
10307 (let ((heading-p (org-on-heading-p t))
10308 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
10309 (following-p (org-get-alist-option org-show-following-heading key))
10310 (entry-p (org-get-alist-option org-show-entry-below key))
10311 (siblings-p (org-get-alist-option org-show-siblings key)))
10312 (catch 'exit
10313 ;; Show heading or entry text
10314 (if (and heading-p (not entry-p))
10315 (org-flag-heading nil) ; only show the heading
10316 (and (or entry-p (org-invisible-p) (org-invisible-p2))
10317 (org-show-hidden-entry))) ; show entire entry
10318 (when following-p
10319 ;; Show next sibling, or heading below text
10320 (save-excursion
10321 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10322 (org-flag-heading nil))))
10323 (when siblings-p (org-show-siblings))
10324 (when hierarchy-p
10325 ;; show all higher headings, possibly with siblings
10326 (save-excursion
10327 (while (and (condition-case nil
10328 (progn (org-up-heading-all 1) t)
10329 (error nil))
10330 (not (bobp)))
10331 (org-flag-heading nil)
10332 (when siblings-p (org-show-siblings))))))))
10334 (defun org-reveal (&optional siblings)
10335 "Show current entry, hierarchy above it, and the following headline.
10336 This can be used to show a consistent set of context around locations
10337 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10338 not t for the search context.
10340 With optional argument SIBLINGS, on each level of the hierarchy all
10341 siblings are shown. This repairs the tree structure to what it would
10342 look like when opened with hierarchical calls to `org-cycle'."
10343 (interactive "P")
10344 (let ((org-show-hierarchy-above t)
10345 (org-show-following-heading t)
10346 (org-show-siblings (if siblings t org-show-siblings)))
10347 (org-show-context nil)))
10349 (defun org-highlight-new-match (beg end)
10350 "Highlight from BEG to END and mark the highlight is an occur headline."
10351 (let ((ov (org-make-overlay beg end)))
10352 (org-overlay-put ov 'face 'secondary-selection)
10353 (push ov org-occur-highlights)))
10355 (defun org-remove-occur-highlights (&optional beg end noremove)
10356 "Remove the occur highlights from the buffer.
10357 BEG and END are ignored. If NOREMOVE is nil, remove this function
10358 from the `before-change-functions' in the current buffer."
10359 (interactive)
10360 (unless org-inhibit-highlight-removal
10361 (mapc 'org-delete-overlay org-occur-highlights)
10362 (setq org-occur-highlights nil)
10363 (setq org-occur-parameters nil)
10364 (unless noremove
10365 (remove-hook 'before-change-functions
10366 'org-remove-occur-highlights 'local))))
10368 ;;;; Priorities
10370 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
10371 "Regular expression matching the priority indicator.")
10373 (defvar org-remove-priority-next-time nil)
10375 (defun org-priority-up ()
10376 "Increase the priority of the current item."
10377 (interactive)
10378 (org-priority 'up))
10380 (defun org-priority-down ()
10381 "Decrease the priority of the current item."
10382 (interactive)
10383 (org-priority 'down))
10385 (defun org-priority (&optional action)
10386 "Change the priority of an item by ARG.
10387 ACTION can be `set', `up', `down', or a character."
10388 (interactive)
10389 (unless org-enable-priority-commands
10390 (error "Priority commands are disabled"))
10391 (setq action (or action 'set))
10392 (let (current new news have remove)
10393 (save-excursion
10394 (org-back-to-heading t)
10395 (if (looking-at org-priority-regexp)
10396 (setq current (string-to-char (match-string 2))
10397 have t)
10398 (setq current org-default-priority))
10399 (cond
10400 ((or (eq action 'set)
10401 (if (featurep 'xemacs) (characterp action) (integerp action)))
10402 (if (not (eq action 'set))
10403 (setq new action)
10404 (message "Priority %c-%c, SPC to remove: "
10405 org-highest-priority org-lowest-priority)
10406 (setq new (read-char-exclusive)))
10407 (if (and (= (upcase org-highest-priority) org-highest-priority)
10408 (= (upcase org-lowest-priority) org-lowest-priority))
10409 (setq new (upcase new)))
10410 (cond ((equal new ?\ ) (setq remove t))
10411 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
10412 (error "Priority must be between `%c' and `%c'"
10413 org-highest-priority org-lowest-priority))))
10414 ((eq action 'up)
10415 (if (and (not have) (eq last-command this-command))
10416 (setq new org-lowest-priority)
10417 (setq new (if (and org-priority-start-cycle-with-default (not have))
10418 org-default-priority (1- current)))))
10419 ((eq action 'down)
10420 (if (and (not have) (eq last-command this-command))
10421 (setq new org-highest-priority)
10422 (setq new (if (and org-priority-start-cycle-with-default (not have))
10423 org-default-priority (1+ current)))))
10424 (t (error "Invalid action")))
10425 (if (or (< (upcase new) org-highest-priority)
10426 (> (upcase new) org-lowest-priority))
10427 (setq remove t))
10428 (setq news (format "%c" new))
10429 (if have
10430 (if remove
10431 (replace-match "" t t nil 1)
10432 (replace-match news t t nil 2))
10433 (if remove
10434 (error "No priority cookie found in line")
10435 (let ((case-fold-search nil))
10436 (looking-at org-todo-line-regexp))
10437 (if (match-end 2)
10438 (progn
10439 (goto-char (match-end 2))
10440 (insert " [#" news "]"))
10441 (goto-char (match-beginning 3))
10442 (insert "[#" news "] "))))
10443 (org-preserve-lc (org-set-tags nil 'align)))
10444 (if remove
10445 (message "Priority removed")
10446 (message "Priority of current item set to %s" news))))
10448 (defun org-get-priority (s)
10449 "Find priority cookie and return priority."
10450 (save-match-data
10451 (if (not (string-match org-priority-regexp s))
10452 (* 1000 (- org-lowest-priority org-default-priority))
10453 (* 1000 (- org-lowest-priority
10454 (string-to-char (match-string 2 s)))))))
10456 ;;;; Tags
10458 (defvar org-agenda-archives-mode)
10459 (defvar org-map-continue-from nil
10460 "Position from where mapping should continue.
10461 Can be set byt the action argument to `org-scan-tag's and `org-map-entries'.")
10463 (defvar org-scanner-tags nil
10464 "The current tag list while the tags scanner is running.")
10465 (defvar org-trust-scanner-tags nil
10466 "Should `org-get-tags-at' use the tags fro the scanner.
10467 This is for internal dynamical scoping only.
10468 When this is non-nil, the function `org-get-tags-at' will return the value
10469 of `org-scanner-tags' instead of building the list by itself. This
10470 can lead to large speed-ups when the tags scanner is used in a file with
10471 many entries, and when the list of tags is retrieved, for example to
10472 obtain a list of properties. Building the tags list for each entry in such
10473 a file becomes an N^2 operation - but with this variable set, it scales
10474 as N.")
10476 (defun org-scan-tags (action matcher &optional todo-only)
10477 "Scan headline tags with inheritance and produce output ACTION.
10479 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
10480 or `agenda' to produce an entry list for an agenda view. It can also be
10481 a Lisp form or a function that should be called at each matched headline, in
10482 this case the return value is a list of all return values from these calls.
10484 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
10485 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
10486 only lines with a TODO keyword are included in the output."
10487 (require 'org-agenda)
10488 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
10489 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
10490 (org-re
10491 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
10492 (props (list 'face 'default
10493 'done-face 'org-agenda-done
10494 'undone-face 'default
10495 'mouse-face 'highlight
10496 'org-not-done-regexp org-not-done-regexp
10497 'org-todo-regexp org-todo-regexp
10498 'keymap org-agenda-keymap
10499 'help-echo
10500 (format "mouse-2 or RET jump to org file %s"
10501 (abbreviate-file-name
10502 (or (buffer-file-name (buffer-base-buffer))
10503 (buffer-name (buffer-base-buffer)))))))
10504 (case-fold-search nil)
10505 (org-map-continue-from nil)
10506 lspos tags tags-list
10507 (tags-alist (list (cons 0 org-file-tags)))
10508 (llast 0) rtn rtn1 level category i txt
10509 todo marker entry priority)
10510 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
10511 (setq action (list 'lambda nil action)))
10512 (save-excursion
10513 (goto-char (point-min))
10514 (when (eq action 'sparse-tree)
10515 (org-overview)
10516 (org-remove-occur-highlights))
10517 (while (re-search-forward re nil t)
10518 (catch :skip
10519 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
10520 tags (if (match-end 4) (org-match-string-no-properties 4)))
10521 (goto-char (setq lspos (match-beginning 0)))
10522 (setq level (org-reduced-level (funcall outline-level))
10523 category (org-get-category))
10524 (setq i llast llast level)
10525 ;; remove tag lists from same and sublevels
10526 (while (>= i level)
10527 (when (setq entry (assoc i tags-alist))
10528 (setq tags-alist (delete entry tags-alist)))
10529 (setq i (1- i)))
10530 ;; add the next tags
10531 (when tags
10532 (setq tags (org-split-string tags ":")
10533 tags-alist
10534 (cons (cons level tags) tags-alist)))
10535 ;; compile tags for current headline
10536 (setq tags-list
10537 (if org-use-tag-inheritance
10538 (apply 'append (mapcar 'cdr (reverse tags-alist)))
10539 tags)
10540 org-scanner-tags tags-list)
10541 (when org-use-tag-inheritance
10542 (setcdr (car tags-alist)
10543 (mapcar (lambda (x)
10544 (setq x (copy-sequence x))
10545 (org-add-prop-inherited x))
10546 (cdar tags-alist))))
10547 (when (and tags org-use-tag-inheritance
10548 (or (not (eq t org-use-tag-inheritance))
10549 org-tags-exclude-from-inheritance))
10550 ;; selective inheritance, remove uninherited ones
10551 (setcdr (car tags-alist)
10552 (org-remove-uniherited-tags (cdar tags-alist))))
10553 (when (and (or (not todo-only)
10554 (and (member todo org-not-done-keywords)
10555 (or (not org-agenda-tags-todo-honor-ignore-options)
10556 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
10557 (let ((case-fold-search t)) (eval matcher))
10559 (not (member org-archive-tag tags-list))
10560 ;; we have an archive tag, should we use this anyway?
10561 (or (not org-agenda-skip-archived-trees)
10562 (and (eq action 'agenda) org-agenda-archives-mode))))
10563 (unless (eq action 'sparse-tree) (org-agenda-skip))
10565 ;; select this headline
10567 (cond
10568 ((eq action 'sparse-tree)
10569 (and org-highlight-sparse-tree-matches
10570 (org-get-heading) (match-end 0)
10571 (org-highlight-new-match
10572 (match-beginning 0) (match-beginning 1)))
10573 (org-show-context 'tags-tree))
10574 ((eq action 'agenda)
10575 (setq txt (org-format-agenda-item
10577 (concat
10578 (if (eq org-tags-match-list-sublevels 'indented)
10579 (make-string (1- level) ?.) "")
10580 (org-get-heading))
10581 category
10582 tags-list
10584 priority (org-get-priority txt))
10585 (goto-char lspos)
10586 (setq marker (org-agenda-new-marker))
10587 (org-add-props txt props
10588 'org-marker marker 'org-hd-marker marker 'org-category category
10589 'todo-state todo
10590 'priority priority 'type "tagsmatch")
10591 (push txt rtn))
10592 ((functionp action)
10593 (setq org-map-continue-from nil)
10594 (save-excursion
10595 (setq rtn1 (funcall action))
10596 (push rtn1 rtn)))
10597 (t (error "Invalid action")))
10599 ;; if we are to skip sublevels, jump to end of subtree
10600 (unless org-tags-match-list-sublevels
10601 (org-end-of-subtree t)
10602 (backward-char 1))))
10603 ;; Get the correct position from where to continue
10604 (if org-map-continue-from
10605 (goto-char org-map-continue-from)
10606 (and (= (point) lspos) (end-of-line 1)))))
10607 (when (and (eq action 'sparse-tree)
10608 (not org-sparse-tree-open-archived-trees))
10609 (org-hide-archived-subtrees (point-min) (point-max)))
10610 (nreverse rtn)))
10612 (defun org-remove-uniherited-tags (tags)
10613 "Remove all tags that are not inherited from the list TAGS."
10614 (cond
10615 ((eq org-use-tag-inheritance t)
10616 (if org-tags-exclude-from-inheritance
10617 (org-delete-all org-tags-exclude-from-inheritance tags)
10618 tags))
10619 ((not org-use-tag-inheritance) nil)
10620 ((stringp org-use-tag-inheritance)
10621 (delq nil (mapcar
10622 (lambda (x)
10623 (if (and (string-match org-use-tag-inheritance x)
10624 (not (member x org-tags-exclude-from-inheritance)))
10625 x nil))
10626 tags)))
10627 ((listp org-use-tag-inheritance)
10628 (delq nil (mapcar
10629 (lambda (x)
10630 (if (member x org-use-tag-inheritance) x nil))
10631 tags)))))
10633 (defvar todo-only) ;; dynamically scoped
10635 (defun org-match-sparse-tree (&optional todo-only match)
10636 "Create a sparse tree according to tags string MATCH.
10637 MATCH can contain positive and negative selection of tags, like
10638 \"+WORK+URGENT-WITHBOSS\".
10639 If optional argument TODO-ONLY is non-nil, only select lines that are
10640 also TODO lines."
10641 (interactive "P")
10642 (org-prepare-agenda-buffers (list (current-buffer)))
10643 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
10645 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
10647 (defvar org-cached-props nil)
10648 (defun org-cached-entry-get (pom property)
10649 (if (or (eq t org-use-property-inheritance)
10650 (and (stringp org-use-property-inheritance)
10651 (string-match org-use-property-inheritance property))
10652 (and (listp org-use-property-inheritance)
10653 (member property org-use-property-inheritance)))
10654 ;; Caching is not possible, check it directly
10655 (org-entry-get pom property 'inherit)
10656 ;; Get all properties, so that we can do complicated checks easily
10657 (cdr (assoc property (or org-cached-props
10658 (setq org-cached-props
10659 (org-entry-properties pom)))))))
10661 (defun org-global-tags-completion-table (&optional files)
10662 "Return the list of all tags in all agenda buffer/files."
10663 (save-excursion
10664 (org-uniquify
10665 (delq nil
10666 (apply 'append
10667 (mapcar
10668 (lambda (file)
10669 (set-buffer (find-file-noselect file))
10670 (append (org-get-buffer-tags)
10671 (mapcar (lambda (x) (if (stringp (car-safe x))
10672 (list (car-safe x)) nil))
10673 org-tag-alist)))
10674 (if (and files (car files))
10675 files
10676 (org-agenda-files))))))))
10678 (defun org-make-tags-matcher (match)
10679 "Create the TAGS//TODO matcher form for the selection string MATCH."
10680 ;; todo-only is scoped dynamically into this function, and the function
10681 ;; may change it if the matcher asks for it.
10682 (unless match
10683 ;; Get a new match request, with completion
10684 (let ((org-last-tags-completion-table
10685 (org-global-tags-completion-table)))
10686 (setq match (org-completing-read-no-ido
10687 "Match: " 'org-tags-completion-function nil nil nil
10688 'org-tags-history))))
10690 ;; Parse the string and create a lisp form
10691 (let ((match0 match)
10692 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
10693 minus tag mm
10694 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
10695 orterms term orlist re-p str-p level-p level-op time-p
10696 prop-p pn pv po cat-p gv rest)
10697 (if (string-match "/+" match)
10698 ;; match contains also a todo-matching request
10699 (progn
10700 (setq tagsmatch (substring match 0 (match-beginning 0))
10701 todomatch (substring match (match-end 0)))
10702 (if (string-match "^!" todomatch)
10703 (setq todo-only t todomatch (substring todomatch 1)))
10704 (if (string-match "^\\s-*$" todomatch)
10705 (setq todomatch nil)))
10706 ;; only matching tags
10707 (setq tagsmatch match todomatch nil))
10709 ;; Make the tags matcher
10710 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10711 (setq tagsmatcher t)
10712 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10713 (while (setq term (pop orterms))
10714 (while (and (equal (substring term -1) "\\") orterms)
10715 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10716 (while (string-match re term)
10717 (setq rest (substring term (match-end 0))
10718 minus (and (match-end 1)
10719 (equal (match-string 1 term) "-"))
10720 tag (match-string 2 term)
10721 re-p (equal (string-to-char tag) ?{)
10722 level-p (match-end 4)
10723 prop-p (match-end 5)
10724 mm (cond
10725 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10726 (level-p
10727 (setq level-op (org-op-to-function (match-string 3 term)))
10728 `(,level-op level ,(string-to-number
10729 (match-string 4 term))))
10730 (prop-p
10731 (setq pn (match-string 5 term)
10732 po (match-string 6 term)
10733 pv (match-string 7 term)
10734 cat-p (equal pn "CATEGORY")
10735 re-p (equal (string-to-char pv) ?{)
10736 str-p (equal (string-to-char pv) ?\")
10737 time-p (save-match-data
10738 (string-match "^\"[[<].*[]>]\"$" pv))
10739 pv (if (or re-p str-p) (substring pv 1 -1) pv))
10740 (if time-p (setq pv (org-matcher-time pv)))
10741 (setq po (org-op-to-function po (if time-p 'time str-p)))
10742 (cond
10743 ((equal pn "CATEGORY")
10744 (setq gv '(get-text-property (point) 'org-category)))
10745 ((equal pn "TODO")
10746 (setq gv 'todo))
10748 (setq gv `(org-cached-entry-get nil ,pn))))
10749 (if re-p
10750 (if (eq po 'org<>)
10751 `(not (string-match ,pv (or ,gv "")))
10752 `(string-match ,pv (or ,gv "")))
10753 (if str-p
10754 `(,po (or ,gv "") ,pv)
10755 `(,po (string-to-number (or ,gv ""))
10756 ,(string-to-number pv) ))))
10757 (t `(member ,tag tags-list)))
10758 mm (if minus (list 'not mm) mm)
10759 term rest)
10760 (push mm tagsmatcher))
10761 (push (if (> (length tagsmatcher) 1)
10762 (cons 'and tagsmatcher)
10763 (car tagsmatcher))
10764 orlist)
10765 (setq tagsmatcher nil))
10766 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
10767 (setq tagsmatcher
10768 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
10769 ;; Make the todo matcher
10770 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10771 (setq todomatcher t)
10772 (setq orterms (org-split-string todomatch "|") orlist nil)
10773 (while (setq term (pop orterms))
10774 (while (string-match re term)
10775 (setq minus (and (match-end 1)
10776 (equal (match-string 1 term) "-"))
10777 kwd (match-string 2 term)
10778 re-p (equal (string-to-char kwd) ?{)
10779 term (substring term (match-end 0))
10780 mm (if re-p
10781 `(string-match ,(substring kwd 1 -1) todo)
10782 (list 'equal 'todo kwd))
10783 mm (if minus (list 'not mm) mm))
10784 (push mm todomatcher))
10785 (push (if (> (length todomatcher) 1)
10786 (cons 'and todomatcher)
10787 (car todomatcher))
10788 orlist)
10789 (setq todomatcher nil))
10790 (setq todomatcher (if (> (length orlist) 1)
10791 (cons 'or orlist) (car orlist))))
10793 ;; Return the string and lisp forms of the matcher
10794 (setq matcher (if todomatcher
10795 (list 'and tagsmatcher todomatcher)
10796 tagsmatcher))
10797 (cons match0 matcher)))
10799 (defun org-op-to-function (op &optional stringp)
10800 "Turn an operator into the appropriate function."
10801 (setq op
10802 (cond
10803 ((equal op "<" ) '(< string< org-time<))
10804 ((equal op ">" ) '(> org-string> org-time>))
10805 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
10806 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
10807 ((member op '("=" "==")) '(= string= org-time=))
10808 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
10809 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
10811 (defun org<> (a b) (not (= a b)))
10812 (defun org-string<= (a b) (or (string= a b) (string< a b)))
10813 (defun org-string>= (a b) (not (string< a b)))
10814 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
10815 (defun org-string<> (a b) (not (string= a b)))
10816 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
10817 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
10818 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
10819 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
10820 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
10821 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
10822 (defun org-2ft (s)
10823 "Convert S to a floating point time.
10824 If S is already a number, just return it. If it is a string, parse
10825 it as a time string and apply `float-time' to it. If S is nil, just return 0."
10826 (cond
10827 ((numberp s) s)
10828 ((stringp s)
10829 (condition-case nil
10830 (float-time (apply 'encode-time (org-parse-time-string s)))
10831 (error 0.)))
10832 (t 0.)))
10834 (defun org-time-today ()
10835 "Time in seconds today at 0:00.
10836 Returns the float number of seconds since the beginning of the
10837 epoch to the beginning of today (00:00)."
10838 (float-time (apply 'encode-time
10839 (append '(0 0 0) (nthcdr 3 (decode-time))))))
10841 (defun org-matcher-time (s)
10842 "Interpret a time comparison value."
10843 (save-match-data
10844 (cond
10845 ((string= s "<now>") (float-time))
10846 ((string= s "<today>") (org-time-today))
10847 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
10848 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
10849 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
10850 (+ (org-time-today)
10851 (* (string-to-number (match-string 1 s))
10852 (cdr (assoc (match-string 2 s)
10853 '(("d" . 86400.0) ("w" . 604800.0)
10854 ("m" . 2678400.0) ("y" . 31557600.0)))))))
10855 (t (org-2ft s)))))
10857 (defun org-match-any-p (re list)
10858 "Does re match any element of list?"
10859 (setq list (mapcar (lambda (x) (string-match re x)) list))
10860 (delq nil list))
10862 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
10863 (defvar org-tags-overlay (org-make-overlay 1 1))
10864 (org-detach-overlay org-tags-overlay)
10866 (defun org-get-local-tags-at (&optional pos)
10867 "Get a list of tags defined in the current headline."
10868 (org-get-tags-at pos 'local))
10870 (defun org-get-local-tags ()
10871 "Get a list of tags defined in the current headline."
10872 (org-get-tags-at nil 'local))
10874 (defun org-get-tags-at (&optional pos local)
10875 "Get a list of all headline tags applicable at POS.
10876 POS defaults to point. If tags are inherited, the list contains
10877 the targets in the same sequence as the headlines appear, i.e.
10878 the tags of the current headline come last.
10879 When LOCAL is non-nil, only return tags from the current headline,
10880 ignore inherited ones."
10881 (interactive)
10882 (if (and org-trust-scanner-tags
10883 (or (not pos) (equal pos (point)))
10884 (not local))
10885 org-scanner-tags
10886 (let (tags ltags lastpos parent)
10887 (save-excursion
10888 (save-restriction
10889 (widen)
10890 (goto-char (or pos (point)))
10891 (save-match-data
10892 (catch 'done
10893 (condition-case nil
10894 (progn
10895 (org-back-to-heading t)
10896 (while (not (equal lastpos (point)))
10897 (setq lastpos (point))
10898 (when (looking-at
10899 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
10900 (setq ltags (org-split-string
10901 (org-match-string-no-properties 1) ":"))
10902 (when parent
10903 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
10904 (setq tags (append
10905 (if parent
10906 (org-remove-uniherited-tags ltags)
10907 ltags)
10908 tags)))
10909 (or org-use-tag-inheritance (throw 'done t))
10910 (if local (throw 'done t))
10911 (or (org-up-heading-safe) (error nil))
10912 (setq parent t)))
10913 (error nil)))))
10914 (append (org-remove-uniherited-tags org-file-tags) tags)))))
10916 (defun org-add-prop-inherited (s)
10917 (add-text-properties 0 (length s) '(inherited t) s)
10920 (defun org-toggle-tag (tag &optional onoff)
10921 "Toggle the tag TAG for the current line.
10922 If ONOFF is `on' or `off', don't toggle but set to this state."
10923 (let (res current)
10924 (save-excursion
10925 (org-back-to-heading t)
10926 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
10927 (point-at-eol) t)
10928 (progn
10929 (setq current (match-string 1))
10930 (replace-match ""))
10931 (setq current ""))
10932 (setq current (nreverse (org-split-string current ":")))
10933 (cond
10934 ((eq onoff 'on)
10935 (setq res t)
10936 (or (member tag current) (push tag current)))
10937 ((eq onoff 'off)
10938 (or (not (member tag current)) (setq current (delete tag current))))
10939 (t (if (member tag current)
10940 (setq current (delete tag current))
10941 (setq res t)
10942 (push tag current))))
10943 (end-of-line 1)
10944 (if current
10945 (progn
10946 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
10947 (org-set-tags nil t))
10948 (delete-horizontal-space))
10949 (run-hooks 'org-after-tags-change-hook))
10950 res))
10952 (defun org-align-tags-here (to-col)
10953 ;; Assumes that this is a headline
10954 (let ((pos (point)) (col (current-column)) ncol tags-l p)
10955 (beginning-of-line 1)
10956 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10957 (< pos (match-beginning 2)))
10958 (progn
10959 (setq tags-l (- (match-end 2) (match-beginning 2)))
10960 (goto-char (match-beginning 1))
10961 (insert " ")
10962 (delete-region (point) (1+ (match-beginning 2)))
10963 (setq ncol (max (1+ (current-column))
10964 (1+ col)
10965 (if (> to-col 0)
10966 to-col
10967 (- (abs to-col) tags-l))))
10968 (setq p (point))
10969 (insert (make-string (- ncol (current-column)) ?\ ))
10970 (setq ncol (current-column))
10971 (when indent-tabs-mode (tabify p (point-at-eol)))
10972 (org-move-to-column (min ncol col) t))
10973 (goto-char pos))))
10975 (defun org-set-tags-command (&optional arg just-align)
10976 "Call the set-tags command for the current entry."
10977 (interactive "P")
10978 (if (org-on-heading-p)
10979 (org-set-tags arg just-align)
10980 (save-excursion
10981 (org-back-to-heading t)
10982 (org-set-tags arg just-align))))
10984 (defun org-set-tags (&optional arg just-align)
10985 "Set the tags for the current headline.
10986 With prefix ARG, realign all tags in headings in the current buffer."
10987 (interactive "P")
10988 (let* ((re (concat "^" outline-regexp))
10989 (current (org-get-tags-string))
10990 (col (current-column))
10991 (org-setting-tags t)
10992 table current-tags inherited-tags ; computed below when needed
10993 tags p0 c0 c1 rpl)
10994 (if arg
10995 (save-excursion
10996 (goto-char (point-min))
10997 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
10998 (while (re-search-forward re nil t)
10999 (org-set-tags nil t)
11000 (end-of-line 1)))
11001 (message "All tags realigned to column %d" org-tags-column))
11002 (if just-align
11003 (setq tags current)
11004 ;; Get a new set of tags from the user
11005 (save-excursion
11006 (setq table (append org-tag-persistent-alist
11007 (or org-tag-alist (org-get-buffer-tags)))
11008 org-last-tags-completion-table table
11009 current-tags (org-split-string current ":")
11010 inherited-tags (nreverse
11011 (nthcdr (length current-tags)
11012 (nreverse (org-get-tags-at))))
11013 tags
11014 (if (or (eq t org-use-fast-tag-selection)
11015 (and org-use-fast-tag-selection
11016 (delq nil (mapcar 'cdr table))))
11017 (org-fast-tag-selection
11018 current-tags inherited-tags table
11019 (if org-fast-tag-selection-include-todo org-todo-key-alist))
11020 (let ((org-add-colon-after-tag-completion t))
11021 (org-trim
11022 (org-without-partial-completion
11023 (org-ido-completing-read "Tags: " 'org-tags-completion-function
11024 nil nil current 'org-tags-history)))))))
11025 (while (string-match "[-+&]+" tags)
11026 ;; No boolean logic, just a list
11027 (setq tags (replace-match ":" t t tags))))
11029 (if org-tags-sort-function
11030 (setq tags (mapconcat 'identity
11031 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
11032 org-tags-sort-function) ":")))
11034 (if (string-match "\\`[\t ]*\\'" tags)
11035 (setq tags "")
11036 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
11037 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
11039 ;; Insert new tags at the correct column
11040 (beginning-of-line 1)
11041 (cond
11042 ((and (equal current "") (equal tags "")))
11043 ((re-search-forward
11044 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
11045 (point-at-eol) t)
11046 (if (equal tags "")
11047 (setq rpl "")
11048 (goto-char (match-beginning 0))
11049 (setq c0 (current-column) p0 (point)
11050 c1 (max (1+ c0) (if (> org-tags-column 0)
11051 org-tags-column
11052 (- (- org-tags-column) (length tags))))
11053 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
11054 (replace-match rpl t t)
11055 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
11056 tags)
11057 (t (error "Tags alignment failed")))
11058 (org-move-to-column col)
11059 (unless just-align
11060 (run-hooks 'org-after-tags-change-hook)))))
11062 (defun org-change-tag-in-region (beg end tag off)
11063 "Add or remove TAG for each entry in the region.
11064 This works in the agenda, and also in an org-mode buffer."
11065 (interactive
11066 (list (region-beginning) (region-end)
11067 (let ((org-last-tags-completion-table
11068 (if (org-mode-p)
11069 (org-get-buffer-tags)
11070 (org-global-tags-completion-table))))
11071 (org-ido-completing-read
11072 "Tag: " 'org-tags-completion-function nil nil nil
11073 'org-tags-history))
11074 (progn
11075 (message "[s]et or [r]emove? ")
11076 (equal (read-char-exclusive) ?r))))
11077 (if (fboundp 'deactivate-mark) (deactivate-mark))
11078 (let ((agendap (equal major-mode 'org-agenda-mode))
11079 l1 l2 m buf pos newhead (cnt 0))
11080 (goto-char end)
11081 (setq l2 (1- (org-current-line)))
11082 (goto-char beg)
11083 (setq l1 (org-current-line))
11084 (loop for l from l1 to l2 do
11085 (goto-line l)
11086 (setq m (get-text-property (point) 'org-hd-marker))
11087 (when (or (and (org-mode-p) (org-on-heading-p))
11088 (and agendap m))
11089 (setq buf (if agendap (marker-buffer m) (current-buffer))
11090 pos (if agendap m (point)))
11091 (with-current-buffer buf
11092 (save-excursion
11093 (save-restriction
11094 (goto-char pos)
11095 (setq cnt (1+ cnt))
11096 (org-toggle-tag tag (if off 'off 'on))
11097 (setq newhead (org-get-heading)))))
11098 (and agendap (org-agenda-change-all-lines newhead m))))
11099 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
11101 (defun org-tags-completion-function (string predicate &optional flag)
11102 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
11103 (confirm (lambda (x) (stringp (car x)))))
11104 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
11105 (setq s1 (match-string 1 string)
11106 s2 (match-string 2 string))
11107 (setq s1 "" s2 string))
11108 (cond
11109 ((eq flag nil)
11110 ;; try completion
11111 (setq rtn (try-completion s2 ctable confirm))
11112 (if (stringp rtn)
11113 (setq rtn
11114 (concat s1 s2 (substring rtn (length s2))
11115 (if (and org-add-colon-after-tag-completion
11116 (assoc rtn ctable))
11117 ":" ""))))
11118 rtn)
11119 ((eq flag t)
11120 ;; all-completions
11121 (all-completions s2 ctable confirm)
11123 ((eq flag 'lambda)
11124 ;; exact match?
11125 (assoc s2 ctable)))
11128 (defun org-fast-tag-insert (kwd tags face &optional end)
11129 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
11130 (insert (format "%-12s" (concat kwd ":"))
11131 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
11132 (or end "")))
11134 (defun org-fast-tag-show-exit (flag)
11135 (save-excursion
11136 (goto-line 3)
11137 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
11138 (replace-match ""))
11139 (when flag
11140 (end-of-line 1)
11141 (org-move-to-column (- (window-width) 19) t)
11142 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
11144 (defun org-set-current-tags-overlay (current prefix)
11145 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
11146 (if (featurep 'xemacs)
11147 (org-overlay-display org-tags-overlay (concat prefix s)
11148 'secondary-selection)
11149 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
11150 (org-overlay-display org-tags-overlay (concat prefix s)))))
11152 (defun org-fast-tag-selection (current inherited table &optional todo-table)
11153 "Fast tag selection with single keys.
11154 CURRENT is the current list of tags in the headline, INHERITED is the
11155 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
11156 possibly with grouping information. TODO-TABLE is a similar table with
11157 TODO keywords, should these have keys assigned to them.
11158 If the keys are nil, a-z are automatically assigned.
11159 Returns the new tags string, or nil to not change the current settings."
11160 (let* ((fulltable (append table todo-table))
11161 (maxlen (apply 'max (mapcar
11162 (lambda (x)
11163 (if (stringp (car x)) (string-width (car x)) 0))
11164 fulltable)))
11165 (buf (current-buffer))
11166 (expert (eq org-fast-tag-selection-single-key 'expert))
11167 (buffer-tags nil)
11168 (fwidth (+ maxlen 3 1 3))
11169 (ncol (/ (- (window-width) 4) fwidth))
11170 (i-face 'org-done)
11171 (c-face 'org-todo)
11172 tg cnt e c char c1 c2 ntable tbl rtn
11173 ov-start ov-end ov-prefix
11174 (exit-after-next org-fast-tag-selection-single-key)
11175 (done-keywords org-done-keywords)
11176 groups ingroup)
11177 (save-excursion
11178 (beginning-of-line 1)
11179 (if (looking-at
11180 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11181 (setq ov-start (match-beginning 1)
11182 ov-end (match-end 1)
11183 ov-prefix "")
11184 (setq ov-start (1- (point-at-eol))
11185 ov-end (1+ ov-start))
11186 (skip-chars-forward "^\n\r")
11187 (setq ov-prefix
11188 (concat
11189 (buffer-substring (1- (point)) (point))
11190 (if (> (current-column) org-tags-column)
11192 (make-string (- org-tags-column (current-column)) ?\ ))))))
11193 (org-move-overlay org-tags-overlay ov-start ov-end)
11194 (save-window-excursion
11195 (if expert
11196 (set-buffer (get-buffer-create " *Org tags*"))
11197 (delete-other-windows)
11198 (split-window-vertically)
11199 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
11200 (erase-buffer)
11201 (org-set-local 'org-done-keywords done-keywords)
11202 (org-fast-tag-insert "Inherited" inherited i-face "\n")
11203 (org-fast-tag-insert "Current" current c-face "\n\n")
11204 (org-fast-tag-show-exit exit-after-next)
11205 (org-set-current-tags-overlay current ov-prefix)
11206 (setq tbl fulltable char ?a cnt 0)
11207 (while (setq e (pop tbl))
11208 (cond
11209 ((equal e '(:startgroup))
11210 (push '() groups) (setq ingroup t)
11211 (when (not (= cnt 0))
11212 (setq cnt 0)
11213 (insert "\n"))
11214 (insert "{ "))
11215 ((equal e '(:endgroup))
11216 (setq ingroup nil cnt 0)
11217 (insert "}\n"))
11218 ((equal e '(:newline))
11219 (when (not (= cnt 0))
11220 (setq cnt 0)
11221 (insert "\n")
11222 (setq e (car tbl))
11223 (while (equal (car tbl) '(:newline))
11224 (insert "\n")
11225 (setq tbl (cdr tbl)))))
11227 (setq tg (car e) c2 nil)
11228 (if (cdr e)
11229 (setq c (cdr e))
11230 ;; automatically assign a character.
11231 (setq c1 (string-to-char
11232 (downcase (substring
11233 tg (if (= (string-to-char tg) ?@) 1 0)))))
11234 (if (or (rassoc c1 ntable) (rassoc c1 table))
11235 (while (or (rassoc char ntable) (rassoc char table))
11236 (setq char (1+ char)))
11237 (setq c2 c1))
11238 (setq c (or c2 char)))
11239 (if ingroup (push tg (car groups)))
11240 (setq tg (org-add-props tg nil 'face
11241 (cond
11242 ((not (assoc tg table))
11243 (org-get-todo-face tg))
11244 ((member tg current) c-face)
11245 ((member tg inherited) i-face)
11246 (t nil))))
11247 (if (and (= cnt 0) (not ingroup)) (insert " "))
11248 (insert "[" c "] " tg (make-string
11249 (- fwidth 4 (length tg)) ?\ ))
11250 (push (cons tg c) ntable)
11251 (when (= (setq cnt (1+ cnt)) ncol)
11252 (insert "\n")
11253 (if ingroup (insert " "))
11254 (setq cnt 0)))))
11255 (setq ntable (nreverse ntable))
11256 (insert "\n")
11257 (goto-char (point-min))
11258 (if (not expert) (org-fit-window-to-buffer))
11259 (setq rtn
11260 (catch 'exit
11261 (while t
11262 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
11263 (if groups " [!] no groups" " [!]groups")
11264 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
11265 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11266 (cond
11267 ((= c ?\r) (throw 'exit t))
11268 ((= c ?!)
11269 (setq groups (not groups))
11270 (goto-char (point-min))
11271 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
11272 ((= c ?\C-c)
11273 (if (not expert)
11274 (org-fast-tag-show-exit
11275 (setq exit-after-next (not exit-after-next)))
11276 (setq expert nil)
11277 (delete-other-windows)
11278 (split-window-vertically)
11279 (org-switch-to-buffer-other-window " *Org tags*")
11280 (org-fit-window-to-buffer)))
11281 ((or (= c ?\C-g)
11282 (and (= c ?q) (not (rassoc c ntable))))
11283 (org-detach-overlay org-tags-overlay)
11284 (setq quit-flag t))
11285 ((= c ?\ )
11286 (setq current nil)
11287 (if exit-after-next (setq exit-after-next 'now)))
11288 ((= c ?\t)
11289 (condition-case nil
11290 (setq tg (org-ido-completing-read
11291 "Tag: "
11292 (or buffer-tags
11293 (with-current-buffer buf
11294 (org-get-buffer-tags)))))
11295 (quit (setq tg "")))
11296 (when (string-match "\\S-" tg)
11297 (add-to-list 'buffer-tags (list tg))
11298 (if (member tg current)
11299 (setq current (delete tg current))
11300 (push tg current)))
11301 (if exit-after-next (setq exit-after-next 'now)))
11302 ((setq e (rassoc c todo-table) tg (car e))
11303 (with-current-buffer buf
11304 (save-excursion (org-todo tg)))
11305 (if exit-after-next (setq exit-after-next 'now)))
11306 ((setq e (rassoc c ntable) tg (car e))
11307 (if (member tg current)
11308 (setq current (delete tg current))
11309 (loop for g in groups do
11310 (if (member tg g)
11311 (mapc (lambda (x)
11312 (setq current (delete x current)))
11313 g)))
11314 (push tg current))
11315 (if exit-after-next (setq exit-after-next 'now))))
11317 ;; Create a sorted list
11318 (setq current
11319 (sort current
11320 (lambda (a b)
11321 (assoc b (cdr (memq (assoc a ntable) ntable))))))
11322 (if (eq exit-after-next 'now) (throw 'exit t))
11323 (goto-char (point-min))
11324 (beginning-of-line 2)
11325 (delete-region (point) (point-at-eol))
11326 (org-fast-tag-insert "Current" current c-face)
11327 (org-set-current-tags-overlay current ov-prefix)
11328 (while (re-search-forward
11329 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
11330 (setq tg (match-string 1))
11331 (add-text-properties
11332 (match-beginning 1) (match-end 1)
11333 (list 'face
11334 (cond
11335 ((member tg current) c-face)
11336 ((member tg inherited) i-face)
11337 (t (get-text-property (match-beginning 1) 'face))))))
11338 (goto-char (point-min)))))
11339 (org-detach-overlay org-tags-overlay)
11340 (if rtn
11341 (mapconcat 'identity current ":")
11342 nil))))
11344 (defun org-get-tags-string ()
11345 "Get the TAGS string in the current headline."
11346 (unless (org-on-heading-p t)
11347 (error "Not on a heading"))
11348 (save-excursion
11349 (beginning-of-line 1)
11350 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11351 (org-match-string-no-properties 1)
11352 "")))
11354 (defun org-get-tags ()
11355 "Get the list of tags specified in the current headline."
11356 (org-split-string (org-get-tags-string) ":"))
11358 (defun org-get-buffer-tags ()
11359 "Get a table of all tags used in the buffer, for completion."
11360 (let (tags)
11361 (save-excursion
11362 (goto-char (point-min))
11363 (while (re-search-forward
11364 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
11365 (when (equal (char-after (point-at-bol 0)) ?*)
11366 (mapc (lambda (x) (add-to-list 'tags x))
11367 (org-split-string (org-match-string-no-properties 1) ":")))))
11368 (mapcar 'list tags)))
11370 ;;;; The mapping API
11372 ;;;###autoload
11373 (defun org-map-entries (func &optional match scope &rest skip)
11374 "Call FUNC at each headline selected by MATCH in SCOPE.
11376 FUNC is a function or a lisp form. The function will be called without
11377 arguments, with the cursor positioned at the beginning of the headline.
11378 The return values of all calls to the function will be collected and
11379 returned as a list.
11381 The call to FUNC will be wrapped into a save-excursion form, so FUNC
11382 does not need to preserve point. After evaluation, the cursor will be
11383 moved to the end of the line (presumably of the headline of the
11384 processed entry) and search continues from there. Under some
11385 circumstances, this may not produce the wanted results. For example,
11386 if you have removed (e.g. archived) the current (sub)tree it could
11387 mean that the next entry will be skipped entirely. In such cases, you
11388 can specify the position from where search should continue by making
11389 FUNC set the variable `org-map-continue-from' to the desired buffer
11390 position.
11392 MATCH is a tags/property/todo match as it is used in the agenda tags view.
11393 Only headlines that are matched by this query will be considered during
11394 the iteration. When MATCH is nil or t, all headlines will be
11395 visited by the iteration.
11397 SCOPE determines the scope of this command. It can be any of:
11399 nil The current buffer, respecting the restriction if any
11400 tree The subtree started with the entry at point
11401 file The current buffer, without restriction
11402 file-with-archives
11403 The current buffer, and any archives associated with it
11404 agenda All agenda files
11405 agenda-with-archives
11406 All agenda files with any archive files associated with them
11407 \(file1 file2 ...)
11408 If this is a list, all files in the list will be scanned
11410 The remaining args are treated as settings for the skipping facilities of
11411 the scanner. The following items can be given here:
11413 archive skip trees with the archive tag.
11414 comment skip trees with the COMMENT keyword
11415 function or Emacs Lisp form:
11416 will be used as value for `org-agenda-skip-function', so whenever
11417 the the function returns t, FUNC will not be called for that
11418 entry and search will continue from the point where the
11419 function leaves it.
11421 If your function needs to retrieve the tags including inherited tags
11422 at the *current* entry, you can use the value of the variable
11423 `org-scanner-tags' which will be much faster than getting the value
11424 with `org-get-tags-at'. If your function gets properties with
11425 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
11426 to t around the call to `org-entry-properties' to get the same speedup.
11427 Note that if your function moves around to retrieve tags and properties at
11428 a *different* entry, you cannot use these techniques."
11429 (let* ((org-agenda-archives-mode nil) ; just to make sure
11430 (org-agenda-skip-archived-trees (memq 'archive skip))
11431 (org-agenda-skip-comment-trees (memq 'comment skip))
11432 (org-agenda-skip-function
11433 (car (org-delete-all '(comment archive) skip)))
11434 (org-tags-match-list-sublevels t)
11435 matcher file res
11436 org-todo-keywords-for-agenda
11437 org-done-keywords-for-agenda
11438 org-todo-keyword-alist-for-agenda
11439 org-tag-alist-for-agenda)
11441 (cond
11442 ((eq match t) (setq matcher t))
11443 ((eq match nil) (setq matcher t))
11444 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
11446 (save-excursion
11447 (save-restriction
11448 (when (eq scope 'tree)
11449 (org-back-to-heading t)
11450 (org-narrow-to-subtree)
11451 (setq scope nil))
11453 (if (not scope)
11454 (progn
11455 (org-prepare-agenda-buffers
11456 (list (buffer-file-name (current-buffer))))
11457 (setq res (org-scan-tags func matcher)))
11458 ;; Get the right scope
11459 (cond
11460 ((and scope (listp scope) (symbolp (car scope)))
11461 (setq scope (eval scope)))
11462 ((eq scope 'agenda)
11463 (setq scope (org-agenda-files t)))
11464 ((eq scope 'agenda-with-archives)
11465 (setq scope (org-agenda-files t))
11466 (setq scope (org-add-archive-files scope)))
11467 ((eq scope 'file)
11468 (setq scope (list (buffer-file-name))))
11469 ((eq scope 'file-with-archives)
11470 (setq scope (org-add-archive-files (list (buffer-file-name))))))
11471 (org-prepare-agenda-buffers scope)
11472 (while (setq file (pop scope))
11473 (with-current-buffer (org-find-base-buffer-visiting file)
11474 (save-excursion
11475 (save-restriction
11476 (widen)
11477 (goto-char (point-min))
11478 (setq res (append res (org-scan-tags func matcher))))))))))
11479 res))
11481 ;;;; Properties
11483 ;;; Setting and retrieving properties
11485 (defconst org-special-properties
11486 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
11487 "TIMESTAMP" "TIMESTAMP_IA")
11488 "The special properties valid in Org-mode.
11490 These are properties that are not defined in the property drawer,
11491 but in some other way.")
11493 (defconst org-default-properties
11494 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
11495 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
11496 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
11497 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
11498 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
11499 "CLOCK_MODELINE_TOTAL")
11500 "Some properties that are used by Org-mode for various purposes.
11501 Being in this list makes sure that they are offered for completion.")
11503 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
11504 "Regular expression matching the first line of a property drawer.")
11506 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
11507 "Regular expression matching the first line of a property drawer.")
11509 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
11510 "Regular expression matching the first line of a property drawer.")
11512 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
11513 "Regular expression matching the first line of a property drawer.")
11515 (defconst org-property-drawer-re
11516 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
11517 org-property-end-re "\\)\n?")
11518 "Matches an entire property drawer.")
11520 (defconst org-clock-drawer-re
11521 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
11522 org-property-end-re "\\)\n?")
11523 "Matches an entire clock drawer.")
11525 (defun org-property-action ()
11526 "Do an action on properties."
11527 (interactive)
11528 (let (c)
11529 (org-at-property-p)
11530 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
11531 (setq c (read-char-exclusive))
11532 (cond
11533 ((equal c ?s)
11534 (call-interactively 'org-set-property))
11535 ((equal c ?d)
11536 (call-interactively 'org-delete-property))
11537 ((equal c ?D)
11538 (call-interactively 'org-delete-property-globally))
11539 ((equal c ?c)
11540 (call-interactively 'org-compute-property-at-point))
11541 (t (error "No such property action %c" c)))))
11543 (defun org-at-property-p ()
11544 "Is the cursor in a property line?"
11545 ;; FIXME: Does not check if we are actually in the drawer.
11546 ;; FIXME: also returns true on any drawers.....
11547 ;; This is used by C-c C-c for property action.
11548 (save-excursion
11549 (beginning-of-line 1)
11550 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
11552 (defun org-get-property-block (&optional beg end force)
11553 "Return the (beg . end) range of the body of the property drawer.
11554 BEG and END can be beginning and end of subtree, if not given
11555 they will be found.
11556 If the drawer does not exist and FORCE is non-nil, create the drawer."
11557 (catch 'exit
11558 (save-excursion
11559 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
11560 (end (or end (progn (outline-next-heading) (point)))))
11561 (goto-char beg)
11562 (if (re-search-forward org-property-start-re end t)
11563 (setq beg (1+ (match-end 0)))
11564 (if force
11565 (save-excursion
11566 (org-insert-property-drawer)
11567 (setq end (progn (outline-next-heading) (point))))
11568 (throw 'exit nil))
11569 (goto-char beg)
11570 (if (re-search-forward org-property-start-re end t)
11571 (setq beg (1+ (match-end 0)))))
11572 (if (re-search-forward org-property-end-re end t)
11573 (setq end (match-beginning 0))
11574 (or force (throw 'exit nil))
11575 (goto-char beg)
11576 (setq end beg)
11577 (org-indent-line-function)
11578 (insert ":END:\n"))
11579 (cons beg end)))))
11581 (defun org-entry-properties (&optional pom which)
11582 "Get all properties of the entry at point-or-marker POM.
11583 This includes the TODO keyword, the tags, time strings for deadline,
11584 scheduled, and clocking, and any additional properties defined in the
11585 entry. The return value is an alist, keys may occur multiple times
11586 if the property key was used several times.
11587 POM may also be nil, in which case the current entry is used.
11588 If WHICH is nil or `all', get all properties. If WHICH is
11589 `special' or `standard', only get that subclass."
11590 (setq which (or which 'all))
11591 (org-with-point-at pom
11592 (let ((clockstr (substring org-clock-string 0 -1))
11593 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
11594 beg end range props sum-props key value string clocksum)
11595 (save-excursion
11596 (when (condition-case nil
11597 (and (org-mode-p) (org-back-to-heading t))
11598 (error nil))
11599 (setq beg (point))
11600 (setq sum-props (get-text-property (point) 'org-summaries))
11601 (setq clocksum (get-text-property (point) :org-clock-minutes))
11602 (outline-next-heading)
11603 (setq end (point))
11604 (when (memq which '(all special))
11605 ;; Get the special properties, like TODO and tags
11606 (goto-char beg)
11607 (when (and (looking-at org-todo-line-regexp) (match-end 2))
11608 (push (cons "TODO" (org-match-string-no-properties 2)) props))
11609 (when (looking-at org-priority-regexp)
11610 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
11611 (when (and (setq value (org-get-tags-string))
11612 (string-match "\\S-" value))
11613 (push (cons "TAGS" value) props))
11614 (when (setq value (org-get-tags-at))
11615 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
11616 props))
11617 (while (re-search-forward org-maybe-keyword-time-regexp end t)
11618 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
11619 string (if (equal key clockstr)
11620 (org-no-properties
11621 (org-trim
11622 (buffer-substring
11623 (match-beginning 3) (goto-char (point-at-eol)))))
11624 (substring (org-match-string-no-properties 3) 1 -1)))
11625 (unless key
11626 (if (= (char-after (match-beginning 3)) ?\[)
11627 (setq key "TIMESTAMP_IA")
11628 (setq key "TIMESTAMP")))
11629 (when (or (equal key clockstr) (not (assoc key props)))
11630 (push (cons key string) props)))
11634 (when (memq which '(all standard))
11635 ;; Get the standard properties, like :PROP: ...
11636 (setq range (org-get-property-block beg end))
11637 (when range
11638 (goto-char (car range))
11639 (while (re-search-forward
11640 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
11641 (cdr range) t)
11642 (setq key (org-match-string-no-properties 1)
11643 value (org-trim (or (org-match-string-no-properties 2) "")))
11644 (unless (member key excluded)
11645 (push (cons key (or value "")) props)))))
11646 (if clocksum
11647 (push (cons "CLOCKSUM"
11648 (org-columns-number-to-string (/ (float clocksum) 60.)
11649 'add_times))
11650 props))
11651 (unless (assoc "CATEGORY" props)
11652 (setq value (or (org-get-category)
11653 (progn (org-refresh-category-properties)
11654 (org-get-category))))
11655 (push (cons "CATEGORY" value) props))
11656 (append sum-props (nreverse props)))))))
11658 (defun org-entry-get (pom property &optional inherit)
11659 "Get value of PROPERTY for entry at point-or-marker POM.
11660 If INHERIT is non-nil and the entry does not have the property,
11661 then also check higher levels of the hierarchy.
11662 If INHERIT is the symbol `selective', use inheritance only if the setting
11663 in `org-use-property-inheritance' selects PROPERTY for inheritance.
11664 If the property is present but empty, the return value is the empty string.
11665 If the property is not present at all, nil is returned."
11666 (org-with-point-at pom
11667 (if (and inherit (if (eq inherit 'selective)
11668 (org-property-inherit-p property)
11670 (org-entry-get-with-inheritance property)
11671 (if (member property org-special-properties)
11672 ;; We need a special property. Use brute force, get all properties.
11673 (cdr (assoc property (org-entry-properties nil 'special)))
11674 (let ((range (org-get-property-block)))
11675 (if (and range
11676 (goto-char (car range))
11677 (re-search-forward
11678 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
11679 (cdr range) t))
11680 ;; Found the property, return it.
11681 (if (match-end 1)
11682 (org-match-string-no-properties 1)
11683 "")))))))
11685 (defun org-property-or-variable-value (var &optional inherit)
11686 "Check if there is a property fixing the value of VAR.
11687 If yes, return this value. If not, return the current value of the variable."
11688 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
11689 (if (and prop (stringp prop) (string-match "\\S-" prop))
11690 (read prop)
11691 (symbol-value var))))
11693 (defun org-entry-delete (pom property)
11694 "Delete the property PROPERTY from entry at point-or-marker POM."
11695 (org-with-point-at pom
11696 (if (member property org-special-properties)
11697 nil ; cannot delete these properties.
11698 (let ((range (org-get-property-block)))
11699 (if (and range
11700 (goto-char (car range))
11701 (re-search-forward
11702 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
11703 (cdr range) t))
11704 (progn
11705 (delete-region (match-beginning 0) (1+ (point-at-eol)))
11707 nil)))))
11709 ;; Multi-values properties are properties that contain multiple values
11710 ;; These values are assumed to be single words, separated by whitespace.
11711 (defun org-entry-add-to-multivalued-property (pom property value)
11712 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
11713 (let* ((old (org-entry-get pom property))
11714 (values (and old (org-split-string old "[ \t]"))))
11715 (setq value (org-entry-protect-space value))
11716 (unless (member value values)
11717 (setq values (cons value values))
11718 (org-entry-put pom property
11719 (mapconcat 'identity values " ")))))
11721 (defun org-entry-remove-from-multivalued-property (pom property value)
11722 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
11723 (let* ((old (org-entry-get pom property))
11724 (values (and old (org-split-string old "[ \t]"))))
11725 (setq value (org-entry-protect-space value))
11726 (when (member value values)
11727 (setq values (delete value values))
11728 (org-entry-put pom property
11729 (mapconcat 'identity values " ")))))
11731 (defun org-entry-member-in-multivalued-property (pom property value)
11732 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
11733 (let* ((old (org-entry-get pom property))
11734 (values (and old (org-split-string old "[ \t]"))))
11735 (setq value (org-entry-protect-space value))
11736 (member value values)))
11738 (defun org-entry-get-multivalued-property (pom property)
11739 "Return a list of values in a multivalued property."
11740 (let* ((value (org-entry-get pom property))
11741 (values (and value (org-split-string value "[ \t]"))))
11742 (mapcar 'org-entry-restore-space values)))
11744 (defun org-entry-put-multivalued-property (pom property &rest values)
11745 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
11746 VALUES should be a list of strings. Spaces will be protected."
11747 (org-entry-put pom property
11748 (mapconcat 'org-entry-protect-space values " "))
11749 (let* ((value (org-entry-get pom property))
11750 (values (and value (org-split-string value "[ \t]"))))
11751 (mapcar 'org-entry-restore-space values)))
11753 (defun org-entry-protect-space (s)
11754 "Protect spaces and newline in string S."
11755 (while (string-match " " s)
11756 (setq s (replace-match "%20" t t s)))
11757 (while (string-match "\n" s)
11758 (setq s (replace-match "%0A" t t s)))
11761 (defun org-entry-restore-space (s)
11762 "Restore spaces and newline in string S."
11763 (while (string-match "%20" s)
11764 (setq s (replace-match " " t t s)))
11765 (while (string-match "%0A" s)
11766 (setq s (replace-match "\n" t t s)))
11769 (defvar org-entry-property-inherited-from (make-marker)
11770 "Marker pointing to the entry from where a property was inherited.
11771 Each call to `org-entry-get-with-inheritance' will set this marker to the
11772 location of the entry where the inheritance search matched. If there was
11773 no match, the marker will point nowhere.
11774 Note that also `org-entry-get' calls this function, if the INHERIT flag
11775 is set.")
11777 (defun org-entry-get-with-inheritance (property)
11778 "Get entry property, and search higher levels if not present."
11779 (move-marker org-entry-property-inherited-from nil)
11780 (let (tmp)
11781 (save-excursion
11782 (save-restriction
11783 (widen)
11784 (catch 'ex
11785 (while t
11786 (when (setq tmp (org-entry-get nil property))
11787 (org-back-to-heading t)
11788 (move-marker org-entry-property-inherited-from (point))
11789 (throw 'ex tmp))
11790 (or (org-up-heading-safe) (throw 'ex nil)))))
11791 (or tmp
11792 (cdr (assoc property org-file-properties))
11793 (cdr (assoc property org-global-properties))
11794 (cdr (assoc property org-global-properties-fixed))))))
11796 (defun org-entry-put (pom property value)
11797 "Set PROPERTY to VALUE for entry at point-or-marker POM."
11798 (org-with-point-at pom
11799 (org-back-to-heading t)
11800 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
11801 range)
11802 (cond
11803 ((equal property "TODO")
11804 (when (and (stringp value) (string-match "\\S-" value)
11805 (not (member value org-todo-keywords-1)))
11806 (error "\"%s\" is not a valid TODO state" value))
11807 (if (or (not value)
11808 (not (string-match "\\S-" value)))
11809 (setq value 'none))
11810 (org-todo value)
11811 (org-set-tags nil 'align))
11812 ((equal property "PRIORITY")
11813 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
11814 (string-to-char value) ?\ ))
11815 (org-set-tags nil 'align))
11816 ((equal property "SCHEDULED")
11817 (if (re-search-forward org-scheduled-time-regexp end t)
11818 (cond
11819 ((eq value 'earlier) (org-timestamp-change -1 'day))
11820 ((eq value 'later) (org-timestamp-change 1 'day))
11821 (t (call-interactively 'org-schedule)))
11822 (call-interactively 'org-schedule)))
11823 ((equal property "DEADLINE")
11824 (if (re-search-forward org-deadline-time-regexp end t)
11825 (cond
11826 ((eq value 'earlier) (org-timestamp-change -1 'day))
11827 ((eq value 'later) (org-timestamp-change 1 'day))
11828 (t (call-interactively 'org-deadline)))
11829 (call-interactively 'org-deadline)))
11830 ((member property org-special-properties)
11831 (error "The %s property can not yet be set with `org-entry-put'"
11832 property))
11833 (t ; a non-special property
11834 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
11835 (setq range (org-get-property-block beg end 'force))
11836 (goto-char (car range))
11837 (if (re-search-forward
11838 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
11839 (progn
11840 (delete-region (match-beginning 1) (match-end 1))
11841 (goto-char (match-beginning 1)))
11842 (goto-char (cdr range))
11843 (insert "\n")
11844 (backward-char 1)
11845 (org-indent-line-function)
11846 (insert ":" property ":"))
11847 (and value (insert " " value))
11848 (org-indent-line-function)))))))
11850 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
11851 "Get all property keys in the current buffer.
11852 With INCLUDE-SPECIALS, also list the special properties that reflect things
11853 like tags and TODO state.
11854 With INCLUDE-DEFAULTS, also include properties that has special meaning
11855 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
11856 With INCLUDE-COLUMNS, also include property names given in COLUMN
11857 formats in the current buffer."
11858 (let (rtn range cfmt s p)
11859 (save-excursion
11860 (save-restriction
11861 (widen)
11862 (goto-char (point-min))
11863 (while (re-search-forward org-property-start-re nil t)
11864 (setq range (org-get-property-block))
11865 (goto-char (car range))
11866 (while (re-search-forward
11867 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
11868 (cdr range) t)
11869 (add-to-list 'rtn (org-match-string-no-properties 1)))
11870 (outline-next-heading))))
11872 (when include-specials
11873 (setq rtn (append org-special-properties rtn)))
11875 (when include-defaults
11876 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
11877 (add-to-list 'rtn org-effort-property))
11879 (when include-columns
11880 (save-excursion
11881 (save-restriction
11882 (widen)
11883 (goto-char (point-min))
11884 (while (re-search-forward
11885 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
11886 nil t)
11887 (setq cfmt (match-string 2) s 0)
11888 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
11889 cfmt s)
11890 (setq s (match-end 0)
11891 p (match-string 1 cfmt))
11892 (unless (or (equal p "ITEM")
11893 (member p org-special-properties))
11894 (add-to-list 'rtn (match-string 1 cfmt))))))))
11896 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
11898 (defun org-property-values (key)
11899 "Return a list of all values of property KEY."
11900 (save-excursion
11901 (save-restriction
11902 (widen)
11903 (goto-char (point-min))
11904 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
11905 values)
11906 (while (re-search-forward re nil t)
11907 (add-to-list 'values (org-trim (match-string 1))))
11908 (delete "" values)))))
11910 (defun org-insert-property-drawer ()
11911 "Insert a property drawer into the current entry."
11912 (interactive)
11913 (org-back-to-heading t)
11914 (looking-at outline-regexp)
11915 (let ((indent (if org-adapt-indentation
11916 (- (match-end 0)(match-beginning 0))
11918 (beg (point))
11919 (re (concat "^[ \t]*" org-keyword-time-regexp))
11920 end hiddenp)
11921 (outline-next-heading)
11922 (setq end (point))
11923 (goto-char beg)
11924 (while (re-search-forward re end t))
11925 (setq hiddenp (org-invisible-p))
11926 (end-of-line 1)
11927 (and (equal (char-after) ?\n) (forward-char 1))
11928 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
11929 (if (member (match-string 1) '("CLOCK:" ":END:"))
11930 ;; just skip this line
11931 (beginning-of-line 2)
11932 ;; Drawer start, find the end
11933 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
11934 (beginning-of-line 1)))
11935 (org-skip-over-state-notes)
11936 (skip-chars-backward " \t\n\r")
11937 (if (eq (char-before) ?*) (forward-char 1))
11938 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
11939 (beginning-of-line 0)
11940 (org-indent-to-column indent)
11941 (beginning-of-line 2)
11942 (org-indent-to-column indent)
11943 (beginning-of-line 0)
11944 (if hiddenp
11945 (save-excursion
11946 (org-back-to-heading t)
11947 (hide-entry))
11948 (org-flag-drawer t))))
11950 (defun org-set-property (property value)
11951 "In the current entry, set PROPERTY to VALUE.
11952 When called interactively, this will prompt for a property name, offering
11953 completion on existing and default properties. And then it will prompt
11954 for a value, offering completion either on allowed values (via an inherited
11955 xxx_ALL property) or on existing values in other instances of this property
11956 in the current file."
11957 (interactive
11958 (let* ((completion-ignore-case t)
11959 (keys (org-buffer-property-keys nil t t))
11960 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
11961 (prop (if (member prop0 keys)
11962 prop0
11963 (or (cdr (assoc (downcase prop0)
11964 (mapcar (lambda (x) (cons (downcase x) x))
11965 keys)))
11966 prop0)))
11967 (cur (org-entry-get nil prop))
11968 (allowed (org-property-get-allowed-values nil prop 'table))
11969 (existing (mapcar 'list (org-property-values prop)))
11970 (val (if allowed
11971 (org-completing-read "Value: " allowed nil 'req-match)
11972 (let (org-completion-use-ido)
11973 (org-completing-read
11974 (concat "Value" (if (and cur (string-match "\\S-" cur))
11975 (concat "[" cur "]") "")
11976 ": ")
11977 existing nil nil "" nil cur)))))
11978 (list prop (if (equal val "") cur val))))
11979 (unless (equal (org-entry-get nil property) value)
11980 (org-entry-put nil property value)))
11982 (defun org-delete-property (property)
11983 "In the current entry, delete PROPERTY."
11984 (interactive
11985 (let* ((completion-ignore-case t)
11986 (prop (org-ido-completing-read
11987 "Property: " (org-entry-properties nil 'standard))))
11988 (list prop)))
11989 (message "Property %s %s" property
11990 (if (org-entry-delete nil property)
11991 "deleted"
11992 "was not present in the entry")))
11994 (defun org-delete-property-globally (property)
11995 "Remove PROPERTY globally, from all entries."
11996 (interactive
11997 (let* ((completion-ignore-case t)
11998 (prop (org-ido-completing-read
11999 "Globally remove property: "
12000 (mapcar 'list (org-buffer-property-keys)))))
12001 (list prop)))
12002 (save-excursion
12003 (save-restriction
12004 (widen)
12005 (goto-char (point-min))
12006 (let ((cnt 0))
12007 (while (re-search-forward
12008 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
12009 nil t)
12010 (setq cnt (1+ cnt))
12011 (replace-match ""))
12012 (message "Property \"%s\" removed from %d entries" property cnt)))))
12014 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
12016 (defun org-compute-property-at-point ()
12017 "Compute the property at point.
12018 This looks for an enclosing column format, extracts the operator and
12019 then applies it to the property in the column format's scope."
12020 (interactive)
12021 (unless (org-at-property-p)
12022 (error "Not at a property"))
12023 (let ((prop (org-match-string-no-properties 2)))
12024 (org-columns-get-format-and-top-level)
12025 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
12026 (error "No operator defined for property %s" prop))
12027 (org-columns-compute prop)))
12029 (defun org-property-get-allowed-values (pom property &optional table)
12030 "Get allowed values for the property PROPERTY.
12031 When TABLE is non-nil, return an alist that can directly be used for
12032 completion."
12033 (let (vals)
12034 (cond
12035 ((equal property "TODO")
12036 (setq vals (org-with-point-at pom
12037 (append org-todo-keywords-1 '("")))))
12038 ((equal property "PRIORITY")
12039 (let ((n org-lowest-priority))
12040 (while (>= n org-highest-priority)
12041 (push (char-to-string n) vals)
12042 (setq n (1- n)))))
12043 ((member property org-special-properties))
12045 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
12047 (when (and vals (string-match "\\S-" vals))
12048 (setq vals (car (read-from-string (concat "(" vals ")"))))
12049 (setq vals (mapcar (lambda (x)
12050 (cond ((stringp x) x)
12051 ((numberp x) (number-to-string x))
12052 ((symbolp x) (symbol-name x))
12053 (t "???")))
12054 vals)))))
12055 (if table (mapcar 'list vals) vals)))
12057 (defun org-property-previous-allowed-value (&optional previous)
12058 "Switch to the next allowed value for this property."
12059 (interactive)
12060 (org-property-next-allowed-value t))
12062 (defun org-property-next-allowed-value (&optional previous)
12063 "Switch to the next allowed value for this property."
12064 (interactive)
12065 (unless (org-at-property-p)
12066 (error "Not at a property"))
12067 (let* ((key (match-string 2))
12068 (value (match-string 3))
12069 (allowed (or (org-property-get-allowed-values (point) key)
12070 (and (member value '("[ ]" "[-]" "[X]"))
12071 '("[ ]" "[X]"))))
12072 nval)
12073 (unless allowed
12074 (error "Allowed values for this property have not been defined"))
12075 (if previous (setq allowed (reverse allowed)))
12076 (if (member value allowed)
12077 (setq nval (car (cdr (member value allowed)))))
12078 (setq nval (or nval (car allowed)))
12079 (if (equal nval value)
12080 (error "Only one allowed value for this property"))
12081 (org-at-property-p)
12082 (replace-match (concat " :" key ": " nval) t t)
12083 (org-indent-line-function)
12084 (beginning-of-line 1)
12085 (skip-chars-forward " \t")))
12087 (defun org-find-entry-with-id (ident)
12088 "Locate the entry that contains the ID property with exact value IDENT.
12089 IDENT can be a string, a symbol or a number, this function will search for
12090 the string representation of it.
12091 Return the position where this entry starts, or nil if there is no such entry."
12092 (interactive "sID: ")
12093 (let ((id (cond
12094 ((stringp ident) ident)
12095 ((symbol-name ident) (symbol-name ident))
12096 ((numberp ident) (number-to-string ident))
12097 (t (error "IDENT %s must be a string, symbol or number" ident))))
12098 (case-fold-search nil))
12099 (save-excursion
12100 (save-restriction
12101 (widen)
12102 (goto-char (point-min))
12103 (when (re-search-forward
12104 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
12105 nil t)
12106 (org-back-to-heading t)
12107 (point))))))
12109 ;;;; Timestamps
12111 (defvar org-last-changed-timestamp nil)
12112 (defvar org-last-inserted-timestamp nil
12113 "The last time stamp inserted with `org-insert-time-stamp'.")
12114 (defvar org-time-was-given) ; dynamically scoped parameter
12115 (defvar org-end-time-was-given) ; dynamically scoped parameter
12116 (defvar org-ts-what) ; dynamically scoped parameter
12118 (defun org-time-stamp (arg &optional inactive)
12119 "Prompt for a date/time and insert a time stamp.
12120 If the user specifies a time like HH:MM, or if this command is called
12121 with a prefix argument, the time stamp will contain date and time.
12122 Otherwise, only the date will be included. All parts of a date not
12123 specified by the user will be filled in from the current date/time.
12124 So if you press just return without typing anything, the time stamp
12125 will represent the current date/time. If there is already a timestamp
12126 at the cursor, it will be modified."
12127 (interactive "P")
12128 (let* ((ts nil)
12129 (default-time
12130 ;; Default time is either today, or, when entering a range,
12131 ;; the range start.
12132 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
12133 (save-excursion
12134 (re-search-backward
12135 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
12136 (- (point) 20) t)))
12137 (apply 'encode-time (org-parse-time-string (match-string 1)))
12138 (current-time)))
12139 (default-input (and ts (org-get-compact-tod ts)))
12140 org-time-was-given org-end-time-was-given time)
12141 (cond
12142 ((and (org-at-timestamp-p t)
12143 (memq last-command '(org-time-stamp org-time-stamp-inactive))
12144 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
12145 (insert "--")
12146 (setq time (let ((this-command this-command))
12147 (org-read-date arg 'totime nil nil
12148 default-time default-input)))
12149 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
12150 ((org-at-timestamp-p t)
12151 (setq time (let ((this-command this-command))
12152 (org-read-date arg 'totime nil nil default-time default-input)))
12153 (when (org-at-timestamp-p t) ; just to get the match data
12154 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
12155 (replace-match "")
12156 (setq org-last-changed-timestamp
12157 (org-insert-time-stamp
12158 time (or org-time-was-given arg)
12159 inactive nil nil (list org-end-time-was-given))))
12160 (message "Timestamp updated"))
12162 (setq time (let ((this-command this-command))
12163 (org-read-date arg 'totime nil nil default-time default-input)))
12164 (org-insert-time-stamp time (or org-time-was-given arg) inactive
12165 nil nil (list org-end-time-was-given))))))
12167 ;; FIXME: can we use this for something else, like computing time differences?
12168 (defun org-get-compact-tod (s)
12169 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
12170 (let* ((t1 (match-string 1 s))
12171 (h1 (string-to-number (match-string 2 s)))
12172 (m1 (string-to-number (match-string 3 s)))
12173 (t2 (and (match-end 4) (match-string 5 s)))
12174 (h2 (and t2 (string-to-number (match-string 6 s))))
12175 (m2 (and t2 (string-to-number (match-string 7 s))))
12176 dh dm)
12177 (if (not t2)
12179 (setq dh (- h2 h1) dm (- m2 m1))
12180 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
12181 (concat t1 "+" (number-to-string dh)
12182 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
12184 (defun org-time-stamp-inactive (&optional arg)
12185 "Insert an inactive time stamp.
12186 An inactive time stamp is enclosed in square brackets instead of angle
12187 brackets. It is inactive in the sense that it does not trigger agenda entries,
12188 does not link to the calendar and cannot be changed with the S-cursor keys.
12189 So these are more for recording a certain time/date."
12190 (interactive "P")
12191 (org-time-stamp arg 'inactive))
12193 (defvar org-date-ovl (org-make-overlay 1 1))
12194 (org-overlay-put org-date-ovl 'face 'org-warning)
12195 (org-detach-overlay org-date-ovl)
12197 (defvar org-ans1) ; dynamically scoped parameter
12198 (defvar org-ans2) ; dynamically scoped parameter
12200 (defvar org-plain-time-of-day-regexp) ; defined below
12202 (defvar org-overriding-default-time nil) ; dynamically scoped
12203 (defvar org-read-date-overlay nil)
12204 (defvar org-dcst nil) ; dynamically scoped
12205 (defvar org-read-date-history nil)
12206 (defvar org-read-date-final-answer nil)
12208 (defun org-read-date (&optional with-time to-time from-string prompt
12209 default-time default-input)
12210 "Read a date, possibly a time, and make things smooth for the user.
12211 The prompt will suggest to enter an ISO date, but you can also enter anything
12212 which will at least partially be understood by `parse-time-string'.
12213 Unrecognized parts of the date will default to the current day, month, year,
12214 hour and minute. If this command is called to replace a timestamp at point,
12215 of to enter the second timestamp of a range, the default time is taken from the
12216 existing stamp. For example,
12217 3-2-5 --> 2003-02-05
12218 feb 15 --> currentyear-02-15
12219 sep 12 9 --> 2009-09-12
12220 12:45 --> today 12:45
12221 22 sept 0:34 --> currentyear-09-22 0:34
12222 12 --> currentyear-currentmonth-12
12223 Fri --> nearest Friday (today or later)
12224 etc.
12226 Furthermore you can specify a relative date by giving, as the *first* thing
12227 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
12228 change in days weeks, months, years.
12229 With a single plus or minus, the date is relative to today. With a double
12230 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
12231 +4d --> four days from today
12232 +4 --> same as above
12233 +2w --> two weeks from today
12234 ++5 --> five days from default date
12236 The function understands only English month and weekday abbreviations,
12237 but this can be configured with the variables `parse-time-months' and
12238 `parse-time-weekdays'.
12240 While prompting, a calendar is popped up - you can also select the
12241 date with the mouse (button 1). The calendar shows a period of three
12242 months. To scroll it to other months, use the keys `>' and `<'.
12243 If you don't like the calendar, turn it off with
12244 \(setq org-read-date-popup-calendar nil)
12246 With optional argument TO-TIME, the date will immediately be converted
12247 to an internal time.
12248 With an optional argument WITH-TIME, the prompt will suggest to also
12249 insert a time. Note that when WITH-TIME is not set, you can still
12250 enter a time, and this function will inform the calling routine about
12251 this change. The calling routine may then choose to change the format
12252 used to insert the time stamp into the buffer to include the time.
12253 With optional argument FROM-STRING, read from this string instead from
12254 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
12255 the time/date that is used for everything that is not specified by the
12256 user."
12257 (require 'parse-time)
12258 (let* ((org-time-stamp-rounding-minutes
12259 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
12260 (org-dcst org-display-custom-times)
12261 (ct (org-current-time))
12262 (def (or org-overriding-default-time default-time ct))
12263 (defdecode (decode-time def))
12264 (dummy (progn
12265 (when (< (nth 2 defdecode) org-extend-today-until)
12266 (setcar (nthcdr 2 defdecode) -1)
12267 (setcar (nthcdr 1 defdecode) 59)
12268 (setq def (apply 'encode-time defdecode)
12269 defdecode (decode-time def)))))
12270 (calendar-frame-setup nil)
12271 (calendar-move-hook nil)
12272 (calendar-view-diary-initially-flag nil)
12273 (view-diary-entries-initially nil)
12274 (calendar-view-holidays-initially-flag nil)
12275 (view-calendar-holidays-initially nil)
12276 (timestr (format-time-string
12277 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
12278 (prompt (concat (if prompt (concat prompt " ") "")
12279 (format "Date+time [%s]: " timestr)))
12280 ans (org-ans0 "") org-ans1 org-ans2 final)
12282 (cond
12283 (from-string (setq ans from-string))
12284 (org-read-date-popup-calendar
12285 (save-excursion
12286 (save-window-excursion
12287 (calendar)
12288 (calendar-forward-day (- (time-to-days def)
12289 (calendar-absolute-from-gregorian
12290 (calendar-current-date))))
12291 (org-eval-in-calendar nil t)
12292 (let* ((old-map (current-local-map))
12293 (map (copy-keymap calendar-mode-map))
12294 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12295 (org-defkey map (kbd "RET") 'org-calendar-select)
12296 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
12297 'org-calendar-select-mouse)
12298 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
12299 'org-calendar-select-mouse)
12300 (org-defkey minibuffer-local-map [(meta shift left)]
12301 (lambda () (interactive)
12302 (org-eval-in-calendar '(calendar-backward-month 1))))
12303 (org-defkey minibuffer-local-map [(meta shift right)]
12304 (lambda () (interactive)
12305 (org-eval-in-calendar '(calendar-forward-month 1))))
12306 (org-defkey minibuffer-local-map [(meta shift up)]
12307 (lambda () (interactive)
12308 (org-eval-in-calendar '(calendar-backward-year 1))))
12309 (org-defkey minibuffer-local-map [(meta shift down)]
12310 (lambda () (interactive)
12311 (org-eval-in-calendar '(calendar-forward-year 1))))
12312 (org-defkey minibuffer-local-map [?\e (shift left)]
12313 (lambda () (interactive)
12314 (org-eval-in-calendar '(calendar-backward-month 1))))
12315 (org-defkey minibuffer-local-map [?\e (shift right)]
12316 (lambda () (interactive)
12317 (org-eval-in-calendar '(calendar-forward-month 1))))
12318 (org-defkey minibuffer-local-map [?\e (shift up)]
12319 (lambda () (interactive)
12320 (org-eval-in-calendar '(calendar-backward-year 1))))
12321 (org-defkey minibuffer-local-map [?\e (shift down)]
12322 (lambda () (interactive)
12323 (org-eval-in-calendar '(calendar-forward-year 1))))
12324 (org-defkey minibuffer-local-map [(shift up)]
12325 (lambda () (interactive)
12326 (org-eval-in-calendar '(calendar-backward-week 1))))
12327 (org-defkey minibuffer-local-map [(shift down)]
12328 (lambda () (interactive)
12329 (org-eval-in-calendar '(calendar-forward-week 1))))
12330 (org-defkey minibuffer-local-map [(shift left)]
12331 (lambda () (interactive)
12332 (org-eval-in-calendar '(calendar-backward-day 1))))
12333 (org-defkey minibuffer-local-map [(shift right)]
12334 (lambda () (interactive)
12335 (org-eval-in-calendar '(calendar-forward-day 1))))
12336 (org-defkey minibuffer-local-map ">"
12337 (lambda () (interactive)
12338 (org-eval-in-calendar '(scroll-calendar-left 1))))
12339 (org-defkey minibuffer-local-map "<"
12340 (lambda () (interactive)
12341 (org-eval-in-calendar '(scroll-calendar-right 1))))
12342 (run-hooks 'org-read-date-minibuffer-setup-hook)
12343 (unwind-protect
12344 (progn
12345 (use-local-map map)
12346 (add-hook 'post-command-hook 'org-read-date-display)
12347 (setq org-ans0 (read-string prompt default-input
12348 'org-read-date-history nil))
12349 ;; org-ans0: from prompt
12350 ;; org-ans1: from mouse click
12351 ;; org-ans2: from calendar motion
12352 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
12353 (remove-hook 'post-command-hook 'org-read-date-display)
12354 (use-local-map old-map)
12355 (when org-read-date-overlay
12356 (org-delete-overlay org-read-date-overlay)
12357 (setq org-read-date-overlay nil)))))))
12359 (t ; Naked prompt only
12360 (unwind-protect
12361 (setq ans (read-string prompt default-input
12362 'org-read-date-history timestr))
12363 (when org-read-date-overlay
12364 (org-delete-overlay org-read-date-overlay)
12365 (setq org-read-date-overlay nil)))))
12367 (setq final (org-read-date-analyze ans def defdecode))
12368 (setq org-read-date-final-answer ans)
12370 (if to-time
12371 (apply 'encode-time final)
12372 (if (and (boundp 'org-time-was-given) org-time-was-given)
12373 (format "%04d-%02d-%02d %02d:%02d"
12374 (nth 5 final) (nth 4 final) (nth 3 final)
12375 (nth 2 final) (nth 1 final))
12376 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
12378 (defvar def)
12379 (defvar defdecode)
12380 (defvar with-time)
12381 (defun org-read-date-display ()
12382 "Display the current date prompt interpretation in the minibuffer."
12383 (when org-read-date-display-live
12384 (when org-read-date-overlay
12385 (org-delete-overlay org-read-date-overlay))
12386 (let ((p (point)))
12387 (end-of-line 1)
12388 (while (not (equal (buffer-substring
12389 (max (point-min) (- (point) 4)) (point))
12390 " "))
12391 (insert " "))
12392 (goto-char p))
12393 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
12394 " " (or org-ans1 org-ans2)))
12395 (org-end-time-was-given nil)
12396 (f (org-read-date-analyze ans def defdecode))
12397 (fmts (if org-dcst
12398 org-time-stamp-custom-formats
12399 org-time-stamp-formats))
12400 (fmt (if (or with-time
12401 (and (boundp 'org-time-was-given) org-time-was-given))
12402 (cdr fmts)
12403 (car fmts)))
12404 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
12405 (when (and org-end-time-was-given
12406 (string-match org-plain-time-of-day-regexp txt))
12407 (setq txt (concat (substring txt 0 (match-end 0)) "-"
12408 org-end-time-was-given
12409 (substring txt (match-end 0)))))
12410 (setq org-read-date-overlay
12411 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
12412 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
12414 (defun org-read-date-analyze (ans def defdecode)
12415 "Analyse the combined answer of the date prompt."
12416 ;; FIXME: cleanup and comment
12417 (let (delta deltan deltaw deltadef year month day
12418 hour minute second wday pm h2 m2 tl wday1
12419 iso-year iso-weekday iso-week iso-year iso-date)
12421 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
12422 (setq ans "+0"))
12424 (when (setq delta (org-read-date-get-relative ans (current-time) def))
12425 (setq ans (replace-match "" t t ans)
12426 deltan (car delta)
12427 deltaw (nth 1 delta)
12428 deltadef (nth 2 delta)))
12430 ;; Check if there is an iso week date in there
12431 ;; If yes, sore the info and postpone interpreting it until the rest
12432 ;; of the parsing is done
12433 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
12434 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
12435 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
12436 iso-week (string-to-number (match-string 2 ans)))
12437 (setq ans (replace-match "" t t ans)))
12439 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
12440 (when (string-match
12441 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
12442 (setq year (if (match-end 2)
12443 (string-to-number (match-string 2 ans))
12444 (string-to-number (format-time-string "%Y")))
12445 month (string-to-number (match-string 3 ans))
12446 day (string-to-number (match-string 4 ans)))
12447 (if (< year 100) (setq year (+ 2000 year)))
12448 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
12449 t nil ans)))
12450 ;; Help matching am/pm times, because `parse-time-string' does not do that.
12451 ;; If there is a time with am/pm, and *no* time without it, we convert
12452 ;; so that matching will be successful.
12453 (loop for i from 1 to 2 do ; twice, for end time as well
12454 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
12455 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
12456 (setq hour (string-to-number (match-string 1 ans))
12457 minute (if (match-end 3)
12458 (string-to-number (match-string 3 ans))
12460 pm (equal ?p
12461 (string-to-char (downcase (match-string 4 ans)))))
12462 (if (and (= hour 12) (not pm))
12463 (setq hour 0)
12464 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
12465 (setq ans (replace-match (format "%02d:%02d" hour minute)
12466 t t ans))))
12468 ;; Check if a time range is given as a duration
12469 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
12470 (setq hour (string-to-number (match-string 1 ans))
12471 h2 (+ hour (string-to-number (match-string 3 ans)))
12472 minute (string-to-number (match-string 2 ans))
12473 m2 (+ minute (if (match-end 5) (string-to-number
12474 (match-string 5 ans))0)))
12475 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
12476 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
12477 t t ans)))
12479 ;; Check if there is a time range
12480 (when (boundp 'org-end-time-was-given)
12481 (setq org-time-was-given nil)
12482 (when (and (string-match org-plain-time-of-day-regexp ans)
12483 (match-end 8))
12484 (setq org-end-time-was-given (match-string 8 ans))
12485 (setq ans (concat (substring ans 0 (match-beginning 7))
12486 (substring ans (match-end 7))))))
12488 (setq tl (parse-time-string ans)
12489 day (or (nth 3 tl) (nth 3 defdecode))
12490 month (or (nth 4 tl)
12491 (if (and org-read-date-prefer-future
12492 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
12493 (1+ (nth 4 defdecode))
12494 (nth 4 defdecode)))
12495 year (or (nth 5 tl)
12496 (if (and org-read-date-prefer-future
12497 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
12498 (1+ (nth 5 defdecode))
12499 (nth 5 defdecode)))
12500 hour (or (nth 2 tl) (nth 2 defdecode))
12501 minute (or (nth 1 tl) (nth 1 defdecode))
12502 second (or (nth 0 tl) 0)
12503 wday (nth 6 tl))
12505 ;; Special date definitions below
12506 (cond
12507 (iso-week
12508 ;; There was an iso week
12509 (setq year (or iso-year year)
12510 day (or iso-weekday wday 1)
12511 wday nil ; to make sure that the trigger below does not match
12512 iso-date (calendar-gregorian-from-absolute
12513 (calendar-absolute-from-iso
12514 (list iso-week day year))))
12515 ; FIXME: Should we also push ISO weeks into the future?
12516 ; (when (and org-read-date-prefer-future
12517 ; (not iso-year)
12518 ; (< (calendar-absolute-from-gregorian iso-date)
12519 ; (time-to-days (current-time))))
12520 ; (setq year (1+ year)
12521 ; iso-date (calendar-gregorian-from-absolute
12522 ; (calendar-absolute-from-iso
12523 ; (list iso-week day year)))))
12524 (setq month (car iso-date)
12525 year (nth 2 iso-date)
12526 day (nth 1 iso-date)))
12527 (deltan
12528 (unless deltadef
12529 (let ((now (decode-time (current-time))))
12530 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
12531 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
12532 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
12533 ((equal deltaw "m") (setq month (+ month deltan)))
12534 ((equal deltaw "y") (setq year (+ year deltan)))))
12535 ((and wday (not (nth 3 tl)))
12536 ;; Weekday was given, but no day, so pick that day in the week
12537 ;; on or after the derived date.
12538 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
12539 (unless (equal wday wday1)
12540 (setq day (+ day (% (- wday wday1 -7) 7))))))
12541 (if (and (boundp 'org-time-was-given)
12542 (nth 2 tl))
12543 (setq org-time-was-given t))
12544 (if (< year 100) (setq year (+ 2000 year)))
12545 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
12546 (list second minute hour day month year)))
12548 (defvar parse-time-weekdays)
12550 (defun org-read-date-get-relative (s today default)
12551 "Check string S for special relative date string.
12552 TODAY and DEFAULT are internal times, for today and for a default.
12553 Return shift list (N what def-flag)
12554 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
12555 N is the number of WHATs to shift.
12556 DEF-FLAG is t when a double ++ or -- indicates shift relative to
12557 the DEFAULT date rather than TODAY."
12558 (when (and
12559 (string-match
12560 (concat
12561 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
12562 "\\([0-9]+\\)?"
12563 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
12564 "\\([ \t]\\|$\\)") s)
12565 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
12566 (let* ((dir (if (> (match-end 1) (match-beginning 1))
12567 (string-to-char (substring (match-string 1 s) -1))
12568 ?+))
12569 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
12570 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
12571 (what (if (match-end 3) (match-string 3 s) "d"))
12572 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
12573 (date (if rel default today))
12574 (wday (nth 6 (decode-time date)))
12575 delta)
12576 (if wday1
12577 (progn
12578 (setq delta (mod (+ 7 (- wday1 wday)) 7))
12579 (if (= dir ?-) (setq delta (- delta 7)))
12580 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
12581 (list delta "d" rel))
12582 (list (* n (if (= dir ?-) -1 1)) what rel)))))
12584 (defun org-eval-in-calendar (form &optional keepdate)
12585 "Eval FORM in the calendar window and return to current window.
12586 Also, store the cursor date in variable org-ans2."
12587 (let ((sf (selected-frame))
12588 (sw (selected-window)))
12589 (select-window (get-buffer-window "*Calendar*" t))
12590 (eval form)
12591 (when (and (not keepdate) (calendar-cursor-to-date))
12592 (let* ((date (calendar-cursor-to-date))
12593 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12594 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
12595 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
12596 (select-window sw)
12597 (select-frame-set-input-focus sf)))
12599 (defun org-calendar-select ()
12600 "Return to `org-read-date' with the date currently selected.
12601 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12602 (interactive)
12603 (when (calendar-cursor-to-date)
12604 (let* ((date (calendar-cursor-to-date))
12605 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12606 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12607 (if (active-minibuffer-window) (exit-minibuffer))))
12609 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
12610 "Insert a date stamp for the date given by the internal TIME.
12611 WITH-HM means, use the stamp format that includes the time of the day.
12612 INACTIVE means use square brackets instead of angular ones, so that the
12613 stamp will not contribute to the agenda.
12614 PRE and POST are optional strings to be inserted before and after the
12615 stamp.
12616 The command returns the inserted time stamp."
12617 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
12618 stamp)
12619 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
12620 (insert-before-markers (or pre ""))
12621 (insert-before-markers (setq stamp (format-time-string fmt time)))
12622 (when (listp extra)
12623 (setq extra (car extra))
12624 (if (and (stringp extra)
12625 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
12626 (setq extra (format "-%02d:%02d"
12627 (string-to-number (match-string 1 extra))
12628 (string-to-number (match-string 2 extra))))
12629 (setq extra nil)))
12630 (when extra
12631 (backward-char 1)
12632 (insert-before-markers extra)
12633 (forward-char 1))
12634 (insert-before-markers (or post ""))
12635 (setq org-last-inserted-timestamp stamp)))
12637 (defun org-toggle-time-stamp-overlays ()
12638 "Toggle the use of custom time stamp formats."
12639 (interactive)
12640 (setq org-display-custom-times (not org-display-custom-times))
12641 (unless org-display-custom-times
12642 (let ((p (point-min)) (bmp (buffer-modified-p)))
12643 (while (setq p (next-single-property-change p 'display))
12644 (if (and (get-text-property p 'display)
12645 (eq (get-text-property p 'face) 'org-date))
12646 (remove-text-properties
12647 p (setq p (next-single-property-change p 'display))
12648 '(display t))))
12649 (set-buffer-modified-p bmp)))
12650 (if (featurep 'xemacs)
12651 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12652 (org-restart-font-lock)
12653 (setq org-table-may-need-update t)
12654 (if org-display-custom-times
12655 (message "Time stamps are overlayed with custom format")
12656 (message "Time stamp overlays removed")))
12658 (defun org-display-custom-time (beg end)
12659 "Overlay modified time stamp format over timestamp between BEG and END."
12660 (let* ((ts (buffer-substring beg end))
12661 t1 w1 with-hm tf time str w2 (off 0))
12662 (save-match-data
12663 (setq t1 (org-parse-time-string ts t))
12664 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
12665 (setq off (- (match-end 0) (match-beginning 0)))))
12666 (setq end (- end off))
12667 (setq w1 (- end beg)
12668 with-hm (and (nth 1 t1) (nth 2 t1))
12669 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
12670 time (org-fix-decoded-time t1)
12671 str (org-add-props
12672 (format-time-string
12673 (substring tf 1 -1) (apply 'encode-time time))
12674 nil 'mouse-face 'highlight)
12675 w2 (length str))
12676 (if (not (= w2 w1))
12677 (add-text-properties (1+ beg) (+ 2 beg)
12678 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12679 (if (featurep 'xemacs)
12680 (progn
12681 (put-text-property beg end 'invisible t)
12682 (put-text-property beg end 'end-glyph (make-glyph str)))
12683 (put-text-property beg end 'display str))))
12685 (defun org-translate-time (string)
12686 "Translate all timestamps in STRING to custom format.
12687 But do this only if the variable `org-display-custom-times' is set."
12688 (when org-display-custom-times
12689 (save-match-data
12690 (let* ((start 0)
12691 (re org-ts-regexp-both)
12692 t1 with-hm inactive tf time str beg end)
12693 (while (setq start (string-match re string start))
12694 (setq beg (match-beginning 0)
12695 end (match-end 0)
12696 t1 (save-match-data
12697 (org-parse-time-string (substring string beg end) t))
12698 with-hm (and (nth 1 t1) (nth 2 t1))
12699 inactive (equal (substring string beg (1+ beg)) "[")
12700 tf (funcall (if with-hm 'cdr 'car)
12701 org-time-stamp-custom-formats)
12702 time (org-fix-decoded-time t1)
12703 str (format-time-string
12704 (concat
12705 (if inactive "[" "<") (substring tf 1 -1)
12706 (if inactive "]" ">"))
12707 (apply 'encode-time time))
12708 string (replace-match str t t string)
12709 start (+ start (length str)))))))
12710 string)
12712 (defun org-fix-decoded-time (time)
12713 "Set 0 instead of nil for the first 6 elements of time.
12714 Don't touch the rest."
12715 (let ((n 0))
12716 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12718 (defun org-days-to-time (timestamp-string)
12719 "Difference between TIMESTAMP-STRING and now in days."
12720 (- (time-to-days (org-time-string-to-time timestamp-string))
12721 (time-to-days (current-time))))
12723 (defun org-deadline-close (timestamp-string &optional ndays)
12724 "Is the time in TIMESTAMP-STRING close to the current date?"
12725 (setq ndays (or ndays (org-get-wdays timestamp-string)))
12726 (and (< (org-days-to-time timestamp-string) ndays)
12727 (not (org-entry-is-done-p))))
12729 (defun org-get-wdays (ts)
12730 "Get the deadline lead time appropriate for timestring TS."
12731 (cond
12732 ((<= org-deadline-warning-days 0)
12733 ;; 0 or negative, enforce this value no matter what
12734 (- org-deadline-warning-days))
12735 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
12736 ;; lead time is specified.
12737 (floor (* (string-to-number (match-string 1 ts))
12738 (cdr (assoc (match-string 2 ts)
12739 '(("d" . 1) ("w" . 7)
12740 ("m" . 30.4) ("y" . 365.25)))))))
12741 ;; go for the default.
12742 (t org-deadline-warning-days)))
12744 (defun org-calendar-select-mouse (ev)
12745 "Return to `org-read-date' with the date currently selected.
12746 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12747 (interactive "e")
12748 (mouse-set-point ev)
12749 (when (calendar-cursor-to-date)
12750 (let* ((date (calendar-cursor-to-date))
12751 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12752 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12753 (if (active-minibuffer-window) (exit-minibuffer))))
12755 (defun org-check-deadlines (ndays)
12756 "Check if there are any deadlines due or past due.
12757 A deadline is considered due if it happens within `org-deadline-warning-days'
12758 days from today's date. If the deadline appears in an entry marked DONE,
12759 it is not shown. The prefix arg NDAYS can be used to test that many
12760 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12761 (interactive "P")
12762 (let* ((org-warn-days
12763 (cond
12764 ((equal ndays '(4)) 100000)
12765 (ndays (prefix-numeric-value ndays))
12766 (t (abs org-deadline-warning-days))))
12767 (case-fold-search nil)
12768 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12769 (callback
12770 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12772 (message "%d deadlines past-due or due within %d days"
12773 (org-occur regexp nil callback)
12774 org-warn-days)))
12776 (defun org-check-before-date (date)
12777 "Check if there are deadlines or scheduled entries before DATE."
12778 (interactive (list (org-read-date)))
12779 (let ((case-fold-search nil)
12780 (regexp (concat "\\<\\(" org-deadline-string
12781 "\\|" org-scheduled-string
12782 "\\) *<\\([^>]+\\)>"))
12783 (callback
12784 (lambda () (time-less-p
12785 (org-time-string-to-time (match-string 2))
12786 (org-time-string-to-time date)))))
12787 (message "%d entries before %s"
12788 (org-occur regexp nil callback) date)))
12790 (defun org-check-after-date (date)
12791 "Check if there are deadlines or scheduled entries after DATE."
12792 (interactive (list (org-read-date)))
12793 (let ((case-fold-search nil)
12794 (regexp (concat "\\<\\(" org-deadline-string
12795 "\\|" org-scheduled-string
12796 "\\) *<\\([^>]+\\)>"))
12797 (callback
12798 (lambda () (not
12799 (time-less-p
12800 (org-time-string-to-time (match-string 2))
12801 (org-time-string-to-time date))))))
12802 (message "%d entries after %s"
12803 (org-occur regexp nil callback) date)))
12805 (defun org-evaluate-time-range (&optional to-buffer)
12806 "Evaluate a time range by computing the difference between start and end.
12807 Normally the result is just printed in the echo area, but with prefix arg
12808 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12809 If the time range is actually in a table, the result is inserted into the
12810 next column.
12811 For time difference computation, a year is assumed to be exactly 365
12812 days in order to avoid rounding problems."
12813 (interactive "P")
12815 (org-clock-update-time-maybe)
12816 (save-excursion
12817 (unless (org-at-date-range-p t)
12818 (goto-char (point-at-bol))
12819 (re-search-forward org-tr-regexp-both (point-at-eol) t))
12820 (if (not (org-at-date-range-p t))
12821 (error "Not at a time-stamp range, and none found in current line")))
12822 (let* ((ts1 (match-string 1))
12823 (ts2 (match-string 2))
12824 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12825 (match-end (match-end 0))
12826 (time1 (org-time-string-to-time ts1))
12827 (time2 (org-time-string-to-time ts2))
12828 (t1 (time-to-seconds time1))
12829 (t2 (time-to-seconds time2))
12830 (diff (abs (- t2 t1)))
12831 (negative (< (- t2 t1) 0))
12832 ;; (ys (floor (* 365 24 60 60)))
12833 (ds (* 24 60 60))
12834 (hs (* 60 60))
12835 (fy "%dy %dd %02d:%02d")
12836 (fy1 "%dy %dd")
12837 (fd "%dd %02d:%02d")
12838 (fd1 "%dd")
12839 (fh "%02d:%02d")
12840 y d h m align)
12841 (if havetime
12842 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12844 d (floor (/ diff ds)) diff (mod diff ds)
12845 h (floor (/ diff hs)) diff (mod diff hs)
12846 m (floor (/ diff 60)))
12847 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12849 d (floor (+ (/ diff ds) 0.5))
12850 h 0 m 0))
12851 (if (not to-buffer)
12852 (message "%s" (org-make-tdiff-string y d h m))
12853 (if (org-at-table-p)
12854 (progn
12855 (goto-char match-end)
12856 (setq align t)
12857 (and (looking-at " *|") (goto-char (match-end 0))))
12858 (goto-char match-end))
12859 (if (looking-at
12860 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12861 (replace-match ""))
12862 (if negative (insert " -"))
12863 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12864 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12865 (insert " " (format fh h m))))
12866 (if align (org-table-align))
12867 (message "Time difference inserted")))))
12869 (defun org-make-tdiff-string (y d h m)
12870 (let ((fmt "")
12871 (l nil))
12872 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12873 l (push y l)))
12874 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12875 l (push d l)))
12876 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12877 l (push h l)))
12878 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12879 l (push m l)))
12880 (apply 'format fmt (nreverse l))))
12882 (defun org-time-string-to-time (s)
12883 (apply 'encode-time (org-parse-time-string s)))
12884 (defun org-time-string-to-seconds (s)
12885 (time-to-seconds (org-time-string-to-time s)))
12887 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
12888 "Convert a time stamp to an absolute day number.
12889 If there is a specifyer for a cyclic time stamp, get the closest date to
12890 DAYNR.
12891 PREFER and SHOW-ALL are passed through to `org-closest-date'.
12892 the variable date is bound by the calendar when this is called."
12893 (cond
12894 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
12895 (if (org-diary-sexp-entry (match-string 1 s) "" date)
12896 daynr
12897 (+ daynr 1000)))
12898 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
12899 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
12900 (time-to-days (current-time))) (match-string 0 s)
12901 prefer show-all))
12902 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
12904 (defun org-days-to-iso-week (days)
12905 "Return the iso week number."
12906 (require 'cal-iso)
12907 (car (calendar-iso-from-absolute days)))
12909 (defun org-small-year-to-year (year)
12910 "Convert 2-digit years into 4-digit years.
12911 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
12912 The year 2000 cannot be abbreviated. Any year larger than 99
12913 is returned unchanged."
12914 (if (< year 38)
12915 (setq year (+ 2000 year))
12916 (if (< year 100)
12917 (setq year (+ 1900 year))))
12918 year)
12920 (defun org-time-from-absolute (d)
12921 "Return the time corresponding to date D.
12922 D may be an absolute day number, or a calendar-type list (month day year)."
12923 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
12924 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
12926 (defun org-calendar-holiday ()
12927 "List of holidays, for Diary display in Org-mode."
12928 (require 'holidays)
12929 (let ((hl (funcall
12930 (if (fboundp 'calendar-check-holidays)
12931 'calendar-check-holidays 'check-calendar-holidays) date)))
12932 (if hl (mapconcat 'identity hl "; "))))
12934 (defun org-diary-sexp-entry (sexp entry date)
12935 "Process a SEXP diary ENTRY for DATE."
12936 (require 'diary-lib)
12937 (let ((result (if calendar-debug-sexp
12938 (let ((stack-trace-on-error t))
12939 (eval (car (read-from-string sexp))))
12940 (condition-case nil
12941 (eval (car (read-from-string sexp)))
12942 (error
12943 (beep)
12944 (message "Bad sexp at line %d in %s: %s"
12945 (org-current-line)
12946 (buffer-file-name) sexp)
12947 (sleep-for 2))))))
12948 (cond ((stringp result) result)
12949 ((and (consp result)
12950 (stringp (cdr result))) (cdr result))
12951 (result entry)
12952 (t nil))))
12954 (defun org-diary-to-ical-string (frombuf)
12955 "Get iCalendar entries from diary entries in buffer FROMBUF.
12956 This uses the icalendar.el library."
12957 (let* ((tmpdir (if (featurep 'xemacs)
12958 (temp-directory)
12959 temporary-file-directory))
12960 (tmpfile (make-temp-name
12961 (expand-file-name "orgics" tmpdir)))
12962 buf rtn b e)
12963 (save-excursion
12964 (set-buffer frombuf)
12965 (icalendar-export-region (point-min) (point-max) tmpfile)
12966 (setq buf (find-buffer-visiting tmpfile))
12967 (set-buffer buf)
12968 (goto-char (point-min))
12969 (if (re-search-forward "^BEGIN:VEVENT" nil t)
12970 (setq b (match-beginning 0)))
12971 (goto-char (point-max))
12972 (if (re-search-backward "^END:VEVENT" nil t)
12973 (setq e (match-end 0)))
12974 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
12975 (kill-buffer buf)
12976 (delete-file tmpfile)
12977 rtn))
12979 (defun org-closest-date (start current change prefer show-all)
12980 "Find the date closest to CURRENT that is consistent with START and CHANGE.
12981 When PREFER is `past' return a date that is either CURRENT or past.
12982 When PREFER is `future', return a date that is either CURRENT or future.
12983 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
12984 ;; Make the proper lists from the dates
12985 (catch 'exit
12986 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
12987 dn dw sday cday n1 n2 n0
12988 d m y y1 y2 date1 date2 nmonths nm ny m2)
12990 (setq start (org-date-to-gregorian start)
12991 current (org-date-to-gregorian
12992 (if show-all
12993 current
12994 (time-to-days (current-time))))
12995 sday (calendar-absolute-from-gregorian start)
12996 cday (calendar-absolute-from-gregorian current))
12998 (if (<= cday sday) (throw 'exit sday))
13000 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
13001 (setq dn (string-to-number (match-string 1 change))
13002 dw (cdr (assoc (match-string 2 change) a1)))
13003 (error "Invalid change specifyer: %s" change))
13004 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
13005 (cond
13006 ((eq dw 'day)
13007 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
13008 n2 (+ n1 dn)))
13009 ((eq dw 'year)
13010 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
13011 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
13012 (setq date1 (list m d y1)
13013 n1 (calendar-absolute-from-gregorian date1)
13014 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
13015 n2 (calendar-absolute-from-gregorian date2)))
13016 ((eq dw 'month)
13017 ;; approx number of month between the two dates
13018 (setq nmonths (floor (/ (- cday sday) 30.436875)))
13019 ;; How often does dn fit in there?
13020 (setq d (nth 1 start) m (car start) y (nth 2 start)
13021 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
13022 m (+ m nm)
13023 ny (floor (/ m 12))
13024 y (+ y ny)
13025 m (- m (* ny 12)))
13026 (while (> m 12) (setq m (- m 12) y (1+ y)))
13027 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
13028 (setq m2 (+ m dn) y2 y)
13029 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13030 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
13031 (while (<= n2 cday)
13032 (setq n1 n2 m m2 y y2)
13033 (setq m2 (+ m dn) y2 y)
13034 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13035 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
13036 ;; Make sure n1 is the earlier date
13037 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
13038 (if show-all
13039 (cond
13040 ((eq prefer 'past) n1)
13041 ((eq prefer 'future) (if (= cday n1) n1 n2))
13042 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
13043 (cond
13044 ((eq prefer 'past) n1)
13045 ((eq prefer 'future) (if (= cday n1) n1 n2))
13046 (t (if (= cday n1) n1 n2)))))))
13048 (defun org-date-to-gregorian (date)
13049 "Turn any specification of DATE into a gregorian date for the calendar."
13050 (cond ((integerp date) (calendar-gregorian-from-absolute date))
13051 ((and (listp date) (= (length date) 3)) date)
13052 ((stringp date)
13053 (setq date (org-parse-time-string date))
13054 (list (nth 4 date) (nth 3 date) (nth 5 date)))
13055 ((listp date)
13056 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
13058 (defun org-parse-time-string (s &optional nodefault)
13059 "Parse the standard Org-mode time string.
13060 This should be a lot faster than the normal `parse-time-string'.
13061 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
13062 hour and minute fields will be nil if not given."
13063 (if (string-match org-ts-regexp0 s)
13064 (list 0
13065 (if (or (match-beginning 8) (not nodefault))
13066 (string-to-number (or (match-string 8 s) "0")))
13067 (if (or (match-beginning 7) (not nodefault))
13068 (string-to-number (or (match-string 7 s) "0")))
13069 (string-to-number (match-string 4 s))
13070 (string-to-number (match-string 3 s))
13071 (string-to-number (match-string 2 s))
13072 nil nil nil)
13073 (make-list 9 0)))
13075 (defun org-timestamp-up (&optional arg)
13076 "Increase the date item at the cursor by one.
13077 If the cursor is on the year, change the year. If it is on the month or
13078 the day, change that.
13079 With prefix ARG, change by that many units."
13080 (interactive "p")
13081 (org-timestamp-change (prefix-numeric-value arg)))
13083 (defun org-timestamp-down (&optional arg)
13084 "Decrease the date item at the cursor by one.
13085 If the cursor is on the year, change the year. If it is on the month or
13086 the day, change that.
13087 With prefix ARG, change by that many units."
13088 (interactive "p")
13089 (org-timestamp-change (- (prefix-numeric-value arg))))
13091 (defun org-timestamp-up-day (&optional arg)
13092 "Increase the date in the time stamp by one day.
13093 With prefix ARG, change that many days."
13094 (interactive "p")
13095 (if (and (not (org-at-timestamp-p t))
13096 (org-on-heading-p))
13097 (org-todo 'up)
13098 (org-timestamp-change (prefix-numeric-value arg) 'day)))
13100 (defun org-timestamp-down-day (&optional arg)
13101 "Decrease the date in the time stamp by one day.
13102 With prefix ARG, change that many days."
13103 (interactive "p")
13104 (if (and (not (org-at-timestamp-p t))
13105 (org-on-heading-p))
13106 (org-todo 'down)
13107 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
13109 (defun org-at-timestamp-p (&optional inactive-ok)
13110 "Determine if the cursor is in or at a timestamp."
13111 (interactive)
13112 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
13113 (pos (point))
13114 (ans (or (looking-at tsr)
13115 (save-excursion
13116 (skip-chars-backward "^[<\n\r\t")
13117 (if (> (point) (point-min)) (backward-char 1))
13118 (and (looking-at tsr)
13119 (> (- (match-end 0) pos) -1))))))
13120 (and ans
13121 (boundp 'org-ts-what)
13122 (setq org-ts-what
13123 (cond
13124 ((= pos (match-beginning 0)) 'bracket)
13125 ((= pos (1- (match-end 0))) 'bracket)
13126 ((org-pos-in-match-range pos 2) 'year)
13127 ((org-pos-in-match-range pos 3) 'month)
13128 ((org-pos-in-match-range pos 7) 'hour)
13129 ((org-pos-in-match-range pos 8) 'minute)
13130 ((or (org-pos-in-match-range pos 4)
13131 (org-pos-in-match-range pos 5)) 'day)
13132 ((and (> pos (or (match-end 8) (match-end 5)))
13133 (< pos (match-end 0)))
13134 (- pos (or (match-end 8) (match-end 5))))
13135 (t 'day))))
13136 ans))
13138 (defun org-toggle-timestamp-type ()
13139 "Toggle the type (<active> or [inactive]) of a time stamp."
13140 (interactive)
13141 (when (org-at-timestamp-p t)
13142 (let ((beg (match-beginning 0)) (end (match-end 0))
13143 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
13144 (save-excursion
13145 (goto-char beg)
13146 (while (re-search-forward "[][<>]" end t)
13147 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
13148 t t)))
13149 (message "Timestamp is now %sactive"
13150 (if (equal (char-after beg) ?<) "" "in")))))
13152 (defun org-timestamp-change (n &optional what)
13153 "Change the date in the time stamp at point.
13154 The date will be changed by N times WHAT. WHAT can be `day', `month',
13155 `year', `minute', `second'. If WHAT is not given, the cursor position
13156 in the timestamp determines what will be changed."
13157 (let ((pos (point))
13158 with-hm inactive
13159 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
13160 org-ts-what
13161 extra rem
13162 ts time time0)
13163 (if (not (org-at-timestamp-p t))
13164 (error "Not at a timestamp"))
13165 (if (and (not what) (eq org-ts-what 'bracket))
13166 (org-toggle-timestamp-type)
13167 (if (and (not what) (not (eq org-ts-what 'day))
13168 org-display-custom-times
13169 (get-text-property (point) 'display)
13170 (not (get-text-property (1- (point)) 'display)))
13171 (setq org-ts-what 'day))
13172 (setq org-ts-what (or what org-ts-what)
13173 inactive (= (char-after (match-beginning 0)) ?\[)
13174 ts (match-string 0))
13175 (replace-match "")
13176 (if (string-match
13177 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
13179 (setq extra (match-string 1 ts)))
13180 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
13181 (setq with-hm t))
13182 (setq time0 (org-parse-time-string ts))
13183 (when (and (eq org-ts-what 'minute)
13184 (eq current-prefix-arg nil))
13185 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
13186 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
13187 (setcar (cdr time0) (+ (nth 1 time0)
13188 (if (> n 0) (- rem) (- dm rem))))))
13189 (setq time
13190 (encode-time (or (car time0) 0)
13191 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
13192 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
13193 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
13194 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
13195 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
13196 (nthcdr 6 time0)))
13197 (when (and (member org-ts-what '(hour minute))
13198 extra
13199 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
13200 (setq extra (org-modify-ts-extra
13201 extra
13202 (if (eq org-ts-what 'hour) 2 5)
13203 n dm)))
13204 (when (integerp org-ts-what)
13205 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
13206 (if (eq what 'calendar)
13207 (let ((cal-date (org-get-date-from-calendar)))
13208 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
13209 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
13210 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
13211 (setcar time0 (or (car time0) 0))
13212 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
13213 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
13214 (setq time (apply 'encode-time time0))))
13215 (setq org-last-changed-timestamp
13216 (org-insert-time-stamp time with-hm inactive nil nil extra))
13217 (org-clock-update-time-maybe)
13218 (goto-char pos)
13219 ;; Try to recenter the calendar window, if any
13220 (if (and org-calendar-follow-timestamp-change
13221 (get-buffer-window "*Calendar*" t)
13222 (memq org-ts-what '(day month year)))
13223 (org-recenter-calendar (time-to-days time))))))
13225 (defun org-modify-ts-extra (s pos n dm)
13226 "Change the different parts of the lead-time and repeat fields in timestamp."
13227 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
13228 ng h m new rem)
13229 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
13230 (cond
13231 ((or (org-pos-in-match-range pos 2)
13232 (org-pos-in-match-range pos 3))
13233 (setq m (string-to-number (match-string 3 s))
13234 h (string-to-number (match-string 2 s)))
13235 (if (org-pos-in-match-range pos 2)
13236 (setq h (+ h n))
13237 (setq n (* dm (org-no-warnings (signum n))))
13238 (when (not (= 0 (setq rem (% m dm))))
13239 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
13240 (setq m (+ m n)))
13241 (if (< m 0) (setq m (+ m 60) h (1- h)))
13242 (if (> m 59) (setq m (- m 60) h (1+ h)))
13243 (setq h (min 24 (max 0 h)))
13244 (setq ng 1 new (format "-%02d:%02d" h m)))
13245 ((org-pos-in-match-range pos 6)
13246 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
13247 ((org-pos-in-match-range pos 5)
13248 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
13250 ((org-pos-in-match-range pos 9)
13251 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
13252 ((org-pos-in-match-range pos 8)
13253 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
13255 (when ng
13256 (setq s (concat
13257 (substring s 0 (match-beginning ng))
13259 (substring s (match-end ng))))))
13262 (defun org-recenter-calendar (date)
13263 "If the calendar is visible, recenter it to DATE."
13264 (let* ((win (selected-window))
13265 (cwin (get-buffer-window "*Calendar*" t))
13266 (calendar-move-hook nil))
13267 (when cwin
13268 (select-window cwin)
13269 (calendar-goto-date (if (listp date) date
13270 (calendar-gregorian-from-absolute date)))
13271 (select-window win))))
13273 (defun org-goto-calendar (&optional arg)
13274 "Go to the Emacs calendar at the current date.
13275 If there is a time stamp in the current line, go to that date.
13276 A prefix ARG can be used to force the current date."
13277 (interactive "P")
13278 (let ((tsr org-ts-regexp) diff
13279 (calendar-move-hook nil)
13280 (calendar-view-holidays-initially-flag nil)
13281 (view-calendar-holidays-initially nil)
13282 (calendar-view-diary-initially-flag nil)
13283 (view-diary-entries-initially nil))
13284 (if (or (org-at-timestamp-p)
13285 (save-excursion
13286 (beginning-of-line 1)
13287 (looking-at (concat ".*" tsr))))
13288 (let ((d1 (time-to-days (current-time)))
13289 (d2 (time-to-days
13290 (org-time-string-to-time (match-string 1)))))
13291 (setq diff (- d2 d1))))
13292 (calendar)
13293 (calendar-goto-today)
13294 (if (and diff (not arg)) (calendar-forward-day diff))))
13296 (defun org-get-date-from-calendar ()
13297 "Return a list (month day year) of date at point in calendar."
13298 (with-current-buffer "*Calendar*"
13299 (save-match-data
13300 (calendar-cursor-to-date))))
13302 (defun org-date-from-calendar ()
13303 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
13304 If there is already a time stamp at the cursor position, update it."
13305 (interactive)
13306 (if (org-at-timestamp-p t)
13307 (org-timestamp-change 0 'calendar)
13308 (let ((cal-date (org-get-date-from-calendar)))
13309 (org-insert-time-stamp
13310 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
13312 (defun org-minutes-to-hh:mm-string (m)
13313 "Compute H:MM from a number of minutes."
13314 (let ((h (/ m 60)))
13315 (setq m (- m (* 60 h)))
13316 (format org-time-clocksum-format h m)))
13318 (defun org-hh:mm-string-to-minutes (s)
13319 "Convert a string H:MM to a number of minutes.
13320 If the string is just a number, interprete it as minutes.
13321 In fact, the first hh:mm or number in the string will be taken,
13322 there can be extra stuff in the string.
13323 If no number is found, the return value is 0."
13324 (cond
13325 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
13326 (+ (* (string-to-number (match-string 1 s)) 60)
13327 (string-to-number (match-string 2 s))))
13328 ((string-match "\\([0-9]+\\)" s)
13329 (string-to-number (match-string 1 s)))
13330 (t 0)))
13332 ;;;; Files
13334 (defun org-save-all-org-buffers ()
13335 "Save all Org-mode buffers without user confirmation."
13336 (interactive)
13337 (message "Saving all Org-mode buffers...")
13338 (save-some-buffers t 'org-mode-p)
13339 (when (featurep 'org-id) (org-id-locations-save))
13340 (message "Saving all Org-mode buffers... done"))
13342 (defun org-revert-all-org-buffers ()
13343 "Revert all Org-mode buffers.
13344 Prompt for confirmation when there are unsaved changes.
13345 Be sure you know what you are doing before letting this function
13346 overwrite your changes.
13348 This function is useful in a setup where one tracks org files
13349 with a version control system, to revert on one machine after pulling
13350 changes from another. I believe the procedure must be like this:
13352 1. M-x org-save-all-org-buffers
13353 2. Pull changes from the other machine, resolve conflicts
13354 3. M-x org-revert-all-org-buffers"
13355 (interactive)
13356 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
13357 (error "Abort"))
13358 (save-excursion
13359 (save-window-excursion
13360 (mapc
13361 (lambda (b)
13362 (when (and (with-current-buffer b (org-mode-p))
13363 (with-current-buffer b buffer-file-name))
13364 (switch-to-buffer b)
13365 (revert-buffer t 'no-confirm)))
13366 (buffer-list))
13367 (when (and (featurep 'org-id) org-id-track-globally)
13368 (org-id-locations-load)))))
13370 ;;;; Agenda files
13372 ;;;###autoload
13373 (defun org-iswitchb (&optional arg)
13374 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
13375 With a prefix argument, restrict available to files.
13376 With two prefix arguments, restrict available buffers to agenda files.
13378 Due to some yet unresolved reason, the global function
13379 `iswitchb-mode' needs to be active for this function to work."
13380 (interactive "P")
13381 (require 'iswitchb)
13382 (let ((enabled iswitchb-mode) blist)
13383 (or enabled (iswitchb-mode 1))
13384 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13385 ((equal arg '(16)) (org-buffer-list 'agenda))
13386 (t (org-buffer-list))))
13387 (unwind-protect
13388 (let ((iswitchb-make-buflist-hook
13389 (lambda ()
13390 (setq iswitchb-temp-buflist
13391 (mapcar 'buffer-name blist)))))
13392 (switch-to-buffer
13393 (iswitchb-read-buffer
13394 "Switch-to: " nil t))
13395 (or enabled (iswitchb-mode -1))))))
13397 ;;;###autoload
13398 (defun org-ido-switchb (&optional arg)
13399 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
13400 With a prefix argument, restrict available to files.
13401 With two prefix arguments, restrict available buffers to agenda files."
13402 (interactive "P")
13403 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13404 ((equal arg '(16)) (org-buffer-list 'agenda))
13405 (t (org-buffer-list)))))
13406 (switch-to-buffer
13407 (org-ido-completing-read "Org buffer: "
13408 (mapcar 'list (mapcar 'buffer-name blist))
13409 nil t))))
13411 (defun org-buffer-list (&optional predicate exclude-tmp)
13412 "Return a list of Org buffers.
13413 PREDICATE can be `export', `files' or `agenda'.
13415 export restrict the list to Export buffers.
13416 files restrict the list to buffers visiting Org files.
13417 agenda restrict the list to buffers visiting agenda files.
13419 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
13420 (let* ((bfn nil)
13421 (agenda-files (and (eq predicate 'agenda)
13422 (mapcar 'file-truename (org-agenda-files t))))
13423 (filter
13424 (cond
13425 ((eq predicate 'files)
13426 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
13427 ((eq predicate 'export)
13428 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
13429 ((eq predicate 'agenda)
13430 (lambda (b)
13431 (with-current-buffer b
13432 (and (eq major-mode 'org-mode)
13433 (setq bfn (buffer-file-name b))
13434 (member (file-truename bfn) agenda-files)))))
13435 (t (lambda (b) (with-current-buffer b
13436 (or (eq major-mode 'org-mode)
13437 (string-match "\*Org .*Export"
13438 (buffer-name b)))))))))
13439 (delq nil
13440 (mapcar
13441 (lambda(b)
13442 (if (and (funcall filter b)
13443 (or (not exclude-tmp)
13444 (not (string-match "tmp" (buffer-name b)))))
13446 nil))
13447 (buffer-list)))))
13449 (defun org-agenda-files (&optional unrestricted archives)
13450 "Get the list of agenda files.
13451 Optional UNRESTRICTED means return the full list even if a restriction
13452 is currently in place.
13453 When ARCHIVES is t, include all archive files hat are really being
13454 used by the agenda files. If ARCHIVE is `ifmode', do this only if
13455 `org-agenda-archives-mode' is t."
13456 (let ((files
13457 (cond
13458 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
13459 ((stringp org-agenda-files) (org-read-agenda-file-list))
13460 ((listp org-agenda-files) org-agenda-files)
13461 (t (error "Invalid value of `org-agenda-files'")))))
13462 (setq files (apply 'append
13463 (mapcar (lambda (f)
13464 (if (file-directory-p f)
13465 (directory-files
13466 f t org-agenda-file-regexp)
13467 (list f)))
13468 files)))
13469 (when org-agenda-skip-unavailable-files
13470 (setq files (delq nil
13471 (mapcar (function
13472 (lambda (file)
13473 (and (file-readable-p file) file)))
13474 files))))
13475 (when (or (eq archives t)
13476 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
13477 (setq files (org-add-archive-files files)))
13478 files))
13480 (defun org-edit-agenda-file-list ()
13481 "Edit the list of agenda files.
13482 Depending on setup, this either uses customize to edit the variable
13483 `org-agenda-files', or it visits the file that is holding the list. In the
13484 latter case, the buffer is set up in a way that saving it automatically kills
13485 the buffer and restores the previous window configuration."
13486 (interactive)
13487 (if (stringp org-agenda-files)
13488 (let ((cw (current-window-configuration)))
13489 (find-file org-agenda-files)
13490 (org-set-local 'org-window-configuration cw)
13491 (org-add-hook 'after-save-hook
13492 (lambda ()
13493 (set-window-configuration
13494 (prog1 org-window-configuration
13495 (kill-buffer (current-buffer))))
13496 (org-install-agenda-files-menu)
13497 (message "New agenda file list installed"))
13498 nil 'local)
13499 (message "%s" (substitute-command-keys
13500 "Edit list and finish with \\[save-buffer]")))
13501 (customize-variable 'org-agenda-files)))
13503 (defun org-store-new-agenda-file-list (list)
13504 "Set new value for the agenda file list and save it correctly."
13505 (if (stringp org-agenda-files)
13506 (let ((f org-agenda-files) b)
13507 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
13508 (with-temp-file f
13509 (insert (mapconcat 'identity list "\n") "\n")))
13510 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
13511 (setq org-agenda-files list)
13512 (customize-save-variable 'org-agenda-files org-agenda-files))))
13514 (defun org-read-agenda-file-list ()
13515 "Read the list of agenda files from a file."
13516 (when (file-directory-p org-agenda-files)
13517 (error "`org-agenda-files' cannot be a single directory"))
13518 (when (stringp org-agenda-files)
13519 (with-temp-buffer
13520 (insert-file-contents org-agenda-files)
13521 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
13524 ;;;###autoload
13525 (defun org-cycle-agenda-files ()
13526 "Cycle through the files in `org-agenda-files'.
13527 If the current buffer visits an agenda file, find the next one in the list.
13528 If the current buffer does not, find the first agenda file."
13529 (interactive)
13530 (let* ((fs (org-agenda-files t))
13531 (files (append fs (list (car fs))))
13532 (tcf (if buffer-file-name (file-truename buffer-file-name)))
13533 file)
13534 (unless files (error "No agenda files"))
13535 (catch 'exit
13536 (while (setq file (pop files))
13537 (if (equal (file-truename file) tcf)
13538 (when (car files)
13539 (find-file (car files))
13540 (throw 'exit t))))
13541 (find-file (car fs)))
13542 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
13544 (defun org-agenda-file-to-front (&optional to-end)
13545 "Move/add the current file to the top of the agenda file list.
13546 If the file is not present in the list, it is added to the front. If it is
13547 present, it is moved there. With optional argument TO-END, add/move to the
13548 end of the list."
13549 (interactive "P")
13550 (let ((org-agenda-skip-unavailable-files nil)
13551 (file-alist (mapcar (lambda (x)
13552 (cons (file-truename x) x))
13553 (org-agenda-files t)))
13554 (ctf (file-truename buffer-file-name))
13555 x had)
13556 (setq x (assoc ctf file-alist) had x)
13558 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
13559 (if to-end
13560 (setq file-alist (append (delq x file-alist) (list x)))
13561 (setq file-alist (cons x (delq x file-alist))))
13562 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
13563 (org-install-agenda-files-menu)
13564 (message "File %s to %s of agenda file list"
13565 (if had "moved" "added") (if to-end "end" "front"))))
13567 (defun org-remove-file (&optional file)
13568 "Remove current file from the list of files in variable `org-agenda-files'.
13569 These are the files which are being checked for agenda entries.
13570 Optional argument FILE means, use this file instead of the current."
13571 (interactive)
13572 (let* ((org-agenda-skip-unavailable-files nil)
13573 (file (or file buffer-file-name))
13574 (true-file (file-truename file))
13575 (afile (abbreviate-file-name file))
13576 (files (delq nil (mapcar
13577 (lambda (x)
13578 (if (equal true-file
13579 (file-truename x))
13580 nil x))
13581 (org-agenda-files t)))))
13582 (if (not (= (length files) (length (org-agenda-files t))))
13583 (progn
13584 (org-store-new-agenda-file-list files)
13585 (org-install-agenda-files-menu)
13586 (message "Removed file: %s" afile))
13587 (message "File was not in list: %s (not removed)" afile))))
13589 (defun org-file-menu-entry (file)
13590 (vector file (list 'find-file file) t))
13592 (defun org-check-agenda-file (file)
13593 "Make sure FILE exists. If not, ask user what to do."
13594 (when (not (file-exists-p file))
13595 (message "non-existent file %s. [R]emove from list or [A]bort?"
13596 (abbreviate-file-name file))
13597 (let ((r (downcase (read-char-exclusive))))
13598 (cond
13599 ((equal r ?r)
13600 (org-remove-file file)
13601 (throw 'nextfile t))
13602 (t (error "Abort"))))))
13604 (defun org-get-agenda-file-buffer (file)
13605 "Get a buffer visiting FILE. If the buffer needs to be created, add
13606 it to the list of buffers which might be released later."
13607 (let ((buf (org-find-base-buffer-visiting file)))
13608 (if buf
13609 buf ; just return it
13610 ;; Make a new buffer and remember it
13611 (setq buf (find-file-noselect file))
13612 (if buf (push buf org-agenda-new-buffers))
13613 buf)))
13615 (defun org-release-buffers (blist)
13616 "Release all buffers in list, asking the user for confirmation when needed.
13617 When a buffer is unmodified, it is just killed. When modified, it is saved
13618 \(if the user agrees) and then killed."
13619 (let (buf file)
13620 (while (setq buf (pop blist))
13621 (setq file (buffer-file-name buf))
13622 (when (and (buffer-modified-p buf)
13623 file
13624 (y-or-n-p (format "Save file %s? " file)))
13625 (with-current-buffer buf (save-buffer)))
13626 (kill-buffer buf))))
13628 (defun org-prepare-agenda-buffers (files)
13629 "Create buffers for all agenda files, protect archived trees and comments."
13630 (interactive)
13631 (let ((pa '(:org-archived t))
13632 (pc '(:org-comment t))
13633 (pall '(:org-archived t :org-comment t))
13634 (inhibit-read-only t)
13635 (rea (concat ":" org-archive-tag ":"))
13636 bmp file re)
13637 (save-excursion
13638 (save-restriction
13639 (while (setq file (pop files))
13640 (catch 'nextfile
13641 (if (bufferp file)
13642 (set-buffer file)
13643 (org-check-agenda-file file)
13644 (set-buffer (org-get-agenda-file-buffer file)))
13645 (widen)
13646 (setq bmp (buffer-modified-p))
13647 (org-refresh-category-properties)
13648 (setq org-todo-keywords-for-agenda
13649 (append org-todo-keywords-for-agenda org-todo-keywords-1))
13650 (setq org-done-keywords-for-agenda
13651 (append org-done-keywords-for-agenda org-done-keywords))
13652 (setq org-todo-keyword-alist-for-agenda
13653 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
13654 (setq org-tag-alist-for-agenda
13655 (append org-tag-alist-for-agenda org-tag-alist))
13657 (save-excursion
13658 (remove-text-properties (point-min) (point-max) pall)
13659 (when org-agenda-skip-archived-trees
13660 (goto-char (point-min))
13661 (while (re-search-forward rea nil t)
13662 (if (org-on-heading-p t)
13663 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
13664 (goto-char (point-min))
13665 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
13666 (while (re-search-forward re nil t)
13667 (add-text-properties
13668 (match-beginning 0) (org-end-of-subtree t) pc)))
13669 (set-buffer-modified-p bmp)))))
13670 (setq org-todo-keyword-alist-for-agenda
13671 (org-uniquify org-todo-keyword-alist-for-agenda)
13672 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
13674 ;;;; Embedded LaTeX
13676 (defvar org-cdlatex-mode-map (make-sparse-keymap)
13677 "Keymap for the minor `org-cdlatex-mode'.")
13679 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
13680 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
13681 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
13682 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
13683 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
13685 (defvar org-cdlatex-texmathp-advice-is-done nil
13686 "Flag remembering if we have applied the advice to texmathp already.")
13688 (define-minor-mode org-cdlatex-mode
13689 "Toggle the minor `org-cdlatex-mode'.
13690 This mode supports entering LaTeX environment and math in LaTeX fragments
13691 in Org-mode.
13692 \\{org-cdlatex-mode-map}"
13693 nil " OCDL" nil
13694 (when org-cdlatex-mode (require 'cdlatex))
13695 (unless org-cdlatex-texmathp-advice-is-done
13696 (setq org-cdlatex-texmathp-advice-is-done t)
13697 (defadvice texmathp (around org-math-always-on activate)
13698 "Always return t in org-mode buffers.
13699 This is because we want to insert math symbols without dollars even outside
13700 the LaTeX math segments. If Orgmode thinks that point is actually inside
13701 an embedded LaTeX fragment, let texmathp do its job.
13702 \\[org-cdlatex-mode-map]"
13703 (interactive)
13704 (let (p)
13705 (cond
13706 ((not (org-mode-p)) ad-do-it)
13707 ((eq this-command 'cdlatex-math-symbol)
13708 (setq ad-return-value t
13709 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
13711 (let ((p (org-inside-LaTeX-fragment-p)))
13712 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
13713 (setq ad-return-value t
13714 texmathp-why '("Org-mode embedded math" . 0))
13715 (if p ad-do-it)))))))))
13717 (defun turn-on-org-cdlatex ()
13718 "Unconditionally turn on `org-cdlatex-mode'."
13719 (org-cdlatex-mode 1))
13721 (defun org-inside-LaTeX-fragment-p ()
13722 "Test if point is inside a LaTeX fragment.
13723 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
13724 sequence appearing also before point.
13725 Even though the matchers for math are configurable, this function assumes
13726 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
13727 delimiters are skipped when they have been removed by customization.
13728 The return value is nil, or a cons cell with the delimiter and
13729 and the position of this delimiter.
13731 This function does a reasonably good job, but can locally be fooled by
13732 for example currency specifications. For example it will assume being in
13733 inline math after \"$22.34\". The LaTeX fragment formatter will only format
13734 fragments that are properly closed, but during editing, we have to live
13735 with the uncertainty caused by missing closing delimiters. This function
13736 looks only before point, not after."
13737 (catch 'exit
13738 (let ((pos (point))
13739 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
13740 (lim (progn
13741 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
13742 (point)))
13743 dd-on str (start 0) m re)
13744 (goto-char pos)
13745 (when dodollar
13746 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
13747 re (nth 1 (assoc "$" org-latex-regexps)))
13748 (while (string-match re str start)
13749 (cond
13750 ((= (match-end 0) (length str))
13751 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
13752 ((= (match-end 0) (- (length str) 5))
13753 (throw 'exit nil))
13754 (t (setq start (match-end 0))))))
13755 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
13756 (goto-char pos)
13757 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
13758 (and (match-beginning 2) (throw 'exit nil))
13759 ;; count $$
13760 (while (re-search-backward "\\$\\$" lim t)
13761 (setq dd-on (not dd-on)))
13762 (goto-char pos)
13763 (if dd-on (cons "$$" m))))))
13766 (defun org-try-cdlatex-tab ()
13767 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
13768 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
13769 - inside a LaTeX fragment, or
13770 - after the first word in a line, where an abbreviation expansion could
13771 insert a LaTeX environment."
13772 (when org-cdlatex-mode
13773 (cond
13774 ((save-excursion
13775 (skip-chars-backward "a-zA-Z0-9*")
13776 (skip-chars-backward " \t")
13777 (bolp))
13778 (cdlatex-tab) t)
13779 ((org-inside-LaTeX-fragment-p)
13780 (cdlatex-tab) t)
13781 (t nil))))
13783 (defun org-cdlatex-underscore-caret (&optional arg)
13784 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
13785 Revert to the normal definition outside of these fragments."
13786 (interactive "P")
13787 (if (org-inside-LaTeX-fragment-p)
13788 (call-interactively 'cdlatex-sub-superscript)
13789 (let (org-cdlatex-mode)
13790 (call-interactively (key-binding (vector last-input-event))))))
13792 (defun org-cdlatex-math-modify (&optional arg)
13793 "Execute `cdlatex-math-modify' in LaTeX fragments.
13794 Revert to the normal definition outside of these fragments."
13795 (interactive "P")
13796 (if (org-inside-LaTeX-fragment-p)
13797 (call-interactively 'cdlatex-math-modify)
13798 (let (org-cdlatex-mode)
13799 (call-interactively (key-binding (vector last-input-event))))))
13801 (defvar org-latex-fragment-image-overlays nil
13802 "List of overlays carrying the images of latex fragments.")
13803 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
13805 (defun org-remove-latex-fragment-image-overlays ()
13806 "Remove all overlays with LaTeX fragment images in current buffer."
13807 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
13808 (setq org-latex-fragment-image-overlays nil))
13810 (defun org-preview-latex-fragment (&optional subtree)
13811 "Preview the LaTeX fragment at point, or all locally or globally.
13812 If the cursor is in a LaTeX fragment, create the image and overlay
13813 it over the source code. If there is no fragment at point, display
13814 all fragments in the current text, from one headline to the next. With
13815 prefix SUBTREE, display all fragments in the current subtree. With a
13816 double prefix `C-u C-u', or when the cursor is before the first headline,
13817 display all fragments in the buffer.
13818 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
13819 (interactive "P")
13820 (org-remove-latex-fragment-image-overlays)
13821 (save-excursion
13822 (save-restriction
13823 (let (beg end at msg)
13824 (cond
13825 ((or (equal subtree '(16))
13826 (not (save-excursion
13827 (re-search-backward (concat "^" outline-regexp) nil t))))
13828 (setq beg (point-min) end (point-max)
13829 msg "Creating images for buffer...%s"))
13830 ((equal subtree '(4))
13831 (org-back-to-heading)
13832 (setq beg (point) end (org-end-of-subtree t)
13833 msg "Creating images for subtree...%s"))
13835 (if (setq at (org-inside-LaTeX-fragment-p))
13836 (goto-char (max (point-min) (- (cdr at) 2)))
13837 (org-back-to-heading))
13838 (setq beg (point) end (progn (outline-next-heading) (point))
13839 msg (if at "Creating image...%s"
13840 "Creating images for entry...%s"))))
13841 (message msg "")
13842 (narrow-to-region beg end)
13843 (goto-char beg)
13844 (org-format-latex
13845 (concat "ltxpng/" (file-name-sans-extension
13846 (file-name-nondirectory
13847 buffer-file-name)))
13848 default-directory 'overlays msg at 'forbuffer)
13849 (message msg "done. Use `C-c C-c' to remove images.")))))
13851 (defvar org-latex-regexps
13852 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
13853 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
13854 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
13855 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13856 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13857 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
13858 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
13859 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
13860 "Regular expressions for matching embedded LaTeX.")
13862 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
13863 "Replace LaTeX fragments with links to an image, and produce images."
13864 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
13865 (let* ((prefixnodir (file-name-nondirectory prefix))
13866 (absprefix (expand-file-name prefix dir))
13867 (todir (file-name-directory absprefix))
13868 (opt org-format-latex-options)
13869 (matchers (plist-get opt :matchers))
13870 (re-list org-latex-regexps)
13871 (cnt 0) txt link beg end re e checkdir
13872 executables-checked
13873 m n block linkfile movefile ov)
13874 ;; Check if there are old images files with this prefix, and remove them
13875 (when (file-directory-p todir)
13876 (mapc 'delete-file
13877 (directory-files
13878 todir 'full
13879 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
13880 ;; Check the different regular expressions
13881 (while (setq e (pop re-list))
13882 (setq m (car e) re (nth 1 e) n (nth 2 e)
13883 block (if (nth 3 e) "\n\n" ""))
13884 (when (member m matchers)
13885 (goto-char (point-min))
13886 (while (re-search-forward re nil t)
13887 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
13888 (not (get-text-property (match-beginning n)
13889 'org-protected)))
13890 (setq txt (match-string n)
13891 beg (match-beginning n) end (match-end n)
13892 cnt (1+ cnt)
13893 linkfile (format "%s_%04d.png" prefix cnt)
13894 movefile (format "%s_%04d.png" absprefix cnt)
13895 link (concat block "[[file:" linkfile "]]" block))
13896 (if msg (message msg cnt))
13897 (goto-char beg)
13898 (unless checkdir ; make sure the directory exists
13899 (setq checkdir t)
13900 (or (file-directory-p todir) (make-directory todir)))
13902 (unless executables-checked
13903 (org-check-external-command
13904 "latex" "needed to convert LaTeX fragments to images")
13905 (org-check-external-command
13906 "dvipng" "needed to convert LaTeX fragments to images")
13907 (setq executables-checked t))
13909 (org-create-formula-image
13910 txt movefile opt forbuffer)
13911 (if overlays
13912 (progn
13913 (setq ov (org-make-overlay beg end))
13914 (if (featurep 'xemacs)
13915 (progn
13916 (org-overlay-put ov 'invisible t)
13917 (org-overlay-put
13918 ov 'end-glyph
13919 (make-glyph (vector 'png :file movefile))))
13920 (org-overlay-put
13921 ov 'display
13922 (list 'image :type 'png :file movefile :ascent 'center)))
13923 (push ov org-latex-fragment-image-overlays)
13924 (goto-char end))
13925 (delete-region beg end)
13926 (insert link))))))))
13928 ;; This function borrows from Ganesh Swami's latex2png.el
13929 (defun org-create-formula-image (string tofile options buffer)
13930 (let* ((tmpdir (if (featurep 'xemacs)
13931 (temp-directory)
13932 temporary-file-directory))
13933 (texfilebase (make-temp-name
13934 (expand-file-name "orgtex" tmpdir)))
13935 (texfile (concat texfilebase ".tex"))
13936 (dvifile (concat texfilebase ".dvi"))
13937 (pngfile (concat texfilebase ".png"))
13938 (fnh (if (featurep 'xemacs)
13939 (font-height (get-face-font 'default))
13940 (face-attribute 'default :height nil)))
13941 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
13942 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
13943 (fg (or (plist-get options (if buffer :foreground :html-foreground))
13944 "Black"))
13945 (bg (or (plist-get options (if buffer :background :html-background))
13946 "Transparent")))
13947 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
13948 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
13949 (with-temp-file texfile
13950 (insert org-format-latex-header
13951 "\n\\begin{document}\n" string "\n\\end{document}\n"))
13952 (let ((dir default-directory))
13953 (condition-case nil
13954 (progn
13955 (cd tmpdir)
13956 (call-process "latex" nil nil nil texfile))
13957 (error nil))
13958 (cd dir))
13959 (if (not (file-exists-p dvifile))
13960 (progn (message "Failed to create dvi file from %s" texfile) nil)
13961 (condition-case nil
13962 (call-process "dvipng" nil nil nil
13963 "-E" "-fg" fg "-bg" bg
13964 "-D" dpi
13965 ;;"-x" scale "-y" scale
13966 "-T" "tight"
13967 "-o" pngfile
13968 dvifile)
13969 (error nil))
13970 (if (not (file-exists-p pngfile))
13971 (progn (message "Failed to create png file from %s" texfile) nil)
13972 ;; Use the requested file name and clean up
13973 (copy-file pngfile tofile 'replace)
13974 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
13975 (delete-file (concat texfilebase e)))
13976 pngfile))))
13978 (defun org-dvipng-color (attr)
13979 "Return an rgb color specification for dvipng."
13980 (apply 'format "rgb %s %s %s"
13981 (mapcar 'org-normalize-color
13982 (color-values (face-attribute 'default attr nil)))))
13984 (defun org-normalize-color (value)
13985 "Return string to be used as color value for an RGB component."
13986 (format "%g" (/ value 65535.0)))
13988 ;;;; Key bindings
13990 ;; Make `C-c C-x' a prefix key
13991 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
13993 ;; TAB key with modifiers
13994 (org-defkey org-mode-map "\C-i" 'org-cycle)
13995 (org-defkey org-mode-map [(tab)] 'org-cycle)
13996 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
13997 (org-defkey org-mode-map [(meta tab)] 'org-complete)
13998 (org-defkey org-mode-map "\M-\t" 'org-complete)
13999 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
14000 ;; The following line is necessary under Suse GNU/Linux
14001 (unless (featurep 'xemacs)
14002 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
14003 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
14004 (define-key org-mode-map [backtab] 'org-shifttab)
14006 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
14007 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
14008 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
14010 ;; Cursor keys with modifiers
14011 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
14012 (org-defkey org-mode-map [(meta right)] 'org-metaright)
14013 (org-defkey org-mode-map [(meta up)] 'org-metaup)
14014 (org-defkey org-mode-map [(meta down)] 'org-metadown)
14016 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
14017 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
14018 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
14019 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
14021 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
14022 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
14023 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
14024 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
14026 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
14027 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
14029 ;;; Extra keys for tty access.
14030 ;; We only set them when really needed because otherwise the
14031 ;; menus don't show the simple keys
14033 (when (or org-use-extra-keys
14034 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
14035 (not window-system))
14036 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
14037 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
14038 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
14039 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
14040 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
14041 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
14042 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
14043 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
14044 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
14045 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
14046 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
14047 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
14048 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
14049 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
14050 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
14051 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
14052 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
14053 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
14054 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
14055 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
14056 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
14057 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
14058 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
14059 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
14060 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
14061 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
14062 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
14063 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
14065 ;; All the other keys
14067 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
14068 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
14069 (if (boundp 'narrow-map)
14070 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
14071 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
14072 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
14073 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
14074 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
14075 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
14076 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
14077 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
14078 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
14079 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
14080 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
14081 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
14082 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
14083 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
14084 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
14085 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
14086 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
14087 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
14088 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
14089 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
14090 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
14091 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
14092 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
14093 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
14094 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
14095 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
14096 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
14097 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
14098 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
14099 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
14100 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
14101 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
14102 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
14103 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
14104 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
14105 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
14106 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
14107 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
14108 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
14109 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
14110 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
14111 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
14112 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
14113 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14114 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
14115 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
14116 (org-defkey org-mode-map "\C-c^" 'org-sort)
14117 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
14118 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
14119 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
14120 (org-defkey org-mode-map "\C-m" 'org-return)
14121 (org-defkey org-mode-map "\C-j" 'org-return-indent)
14122 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
14123 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
14124 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
14125 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
14126 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
14127 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
14128 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
14129 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
14130 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
14131 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
14132 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
14133 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
14134 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
14135 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
14136 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
14137 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
14138 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
14139 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
14141 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
14142 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
14143 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
14144 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
14146 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
14147 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
14148 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
14149 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
14150 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
14151 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
14152 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
14153 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
14154 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
14155 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
14156 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
14157 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
14158 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
14159 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
14161 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
14162 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
14163 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
14164 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
14166 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
14168 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
14170 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
14171 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
14173 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
14176 (when (featurep 'xemacs)
14177 (org-defkey org-mode-map 'button3 'popup-mode-menu))
14180 (defvar org-self-insert-command-undo-counter 0)
14182 (defvar org-table-auto-blank-field) ; defined in org-table.el
14183 (defun org-self-insert-command (N)
14184 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
14185 If the cursor is in a table looking at whitespace, the whitespace is
14186 overwritten, and the table is not marked as requiring realignment."
14187 (interactive "p")
14188 (if (and
14189 (org-table-p)
14190 (progn
14191 ;; check if we blank the field, and if that triggers align
14192 (and (featurep 'org-table) org-table-auto-blank-field
14193 (member last-command
14194 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
14195 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
14196 ;; got extra space, this field does not determine column width
14197 (let (org-table-may-need-update) (org-table-blank-field))
14198 ;; no extra space, this field may determine column width
14199 (org-table-blank-field)))
14201 (eq N 1)
14202 (looking-at "[^|\n]* |"))
14203 (let (org-table-may-need-update)
14204 (goto-char (1- (match-end 0)))
14205 (delete-backward-char 1)
14206 (goto-char (match-beginning 0))
14207 (self-insert-command N))
14208 (setq org-table-may-need-update t)
14209 (self-insert-command N)
14210 (org-fix-tags-on-the-fly)
14211 (if org-self-insert-cluster-for-undo
14212 (if (not (eq last-command 'org-self-insert-command))
14213 (setq org-self-insert-command-undo-counter 1)
14214 (if (>= org-self-insert-command-undo-counter 20)
14215 (setq org-self-insert-command-undo-counter 1)
14216 (and (> org-self-insert-command-undo-counter 0)
14217 buffer-undo-list
14218 (not (cadr buffer-undo-list)) ; remove nil entry
14219 (setcdr buffer-undo-list (cddr buffer-undo-list)))
14220 (setq org-self-insert-command-undo-counter
14221 (1+ org-self-insert-command-undo-counter)))))))
14223 (defun org-fix-tags-on-the-fly ()
14224 (when (and (equal (char-after (point-at-bol)) ?*)
14225 (org-on-heading-p))
14226 (org-align-tags-here org-tags-column)))
14228 (defun org-delete-backward-char (N)
14229 "Like `delete-backward-char', insert whitespace at field end in tables.
14230 When deleting backwards, in tables this function will insert whitespace in
14231 front of the next \"|\" separator, to keep the table aligned. The table will
14232 still be marked for re-alignment if the field did fill the entire column,
14233 because, in this case the deletion might narrow the column."
14234 (interactive "p")
14235 (if (and (org-table-p)
14236 (eq N 1)
14237 (string-match "|" (buffer-substring (point-at-bol) (point)))
14238 (looking-at ".*?|"))
14239 (let ((pos (point))
14240 (noalign (looking-at "[^|\n\r]* |"))
14241 (c org-table-may-need-update))
14242 (backward-delete-char N)
14243 (skip-chars-forward "^|")
14244 (insert " ")
14245 (goto-char (1- pos))
14246 ;; noalign: if there were two spaces at the end, this field
14247 ;; does not determine the width of the column.
14248 (if noalign (setq org-table-may-need-update c)))
14249 (backward-delete-char N)
14250 (org-fix-tags-on-the-fly)))
14252 (defun org-delete-char (N)
14253 "Like `delete-char', but insert whitespace at field end in tables.
14254 When deleting characters, in tables this function will insert whitespace in
14255 front of the next \"|\" separator, to keep the table aligned. The table will
14256 still be marked for re-alignment if the field did fill the entire column,
14257 because, in this case the deletion might narrow the column."
14258 (interactive "p")
14259 (if (and (org-table-p)
14260 (not (bolp))
14261 (not (= (char-after) ?|))
14262 (eq N 1))
14263 (if (looking-at ".*?|")
14264 (let ((pos (point))
14265 (noalign (looking-at "[^|\n\r]* |"))
14266 (c org-table-may-need-update))
14267 (replace-match (concat
14268 (substring (match-string 0) 1 -1)
14269 " |"))
14270 (goto-char pos)
14271 ;; noalign: if there were two spaces at the end, this field
14272 ;; does not determine the width of the column.
14273 (if noalign (setq org-table-may-need-update c)))
14274 (delete-char N))
14275 (delete-char N)
14276 (org-fix-tags-on-the-fly)))
14278 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
14279 (put 'org-self-insert-command 'delete-selection t)
14280 (put 'orgtbl-self-insert-command 'delete-selection t)
14281 (put 'org-delete-char 'delete-selection 'supersede)
14282 (put 'org-delete-backward-char 'delete-selection 'supersede)
14283 (put 'org-yank 'delete-selection 'yank)
14285 ;; Make `flyspell-mode' delay after some commands
14286 (put 'org-self-insert-command 'flyspell-delayed t)
14287 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
14288 (put 'org-delete-char 'flyspell-delayed t)
14289 (put 'org-delete-backward-char 'flyspell-delayed t)
14291 ;; Make pabbrev-mode expand after org-mode commands
14292 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
14293 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
14295 ;; How to do this: Measure non-white length of current string
14296 ;; If equal to column width, we should realign.
14298 (defun org-remap (map &rest commands)
14299 "In MAP, remap the functions given in COMMANDS.
14300 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
14301 (let (new old)
14302 (while commands
14303 (setq old (pop commands) new (pop commands))
14304 (if (fboundp 'command-remapping)
14305 (org-defkey map (vector 'remap old) new)
14306 (substitute-key-definition old new map global-map)))))
14308 (when (eq org-enable-table-editor 'optimized)
14309 ;; If the user wants maximum table support, we need to hijack
14310 ;; some standard editing functions
14311 (org-remap org-mode-map
14312 'self-insert-command 'org-self-insert-command
14313 'delete-char 'org-delete-char
14314 'delete-backward-char 'org-delete-backward-char)
14315 (org-defkey org-mode-map "|" 'org-force-self-insert))
14317 (defvar org-ctrl-c-ctrl-c-hook nil
14318 "Hook for functions attaching themselves to `C-c C-c'.
14319 This can be used to add additional functionality to the C-c C-c key which
14320 executes context-dependent commands.
14321 Each function will be called with no arguments. The function must check
14322 if the context is appropriate for it to act. If yes, it should do its
14323 thing and then return a non-nil value. If the context is wrong,
14324 just do nothing and return nil.")
14326 (defvar org-tab-first-hook nil
14327 "Hook for functions to attach themselves to TAB.
14328 See `org-ctrl-c-ctrl-c-hook' for more information.
14329 This hook runs as the first action when TAB is pressed, even before
14330 `org-cycle' messes around with the `outline-regexp' to cater for
14331 inline tasks and plain list item folding.
14332 If any function in this hook returns t, not other actions like table
14333 field motion visibility cycling will be done.")
14335 (defvar org-tab-after-check-for-table-hook nil
14336 "Hook for functions to attach themselves to TAB.
14337 See `org-ctrl-c-ctrl-c-hook' for more information.
14338 This hook runs after it has been established that the cursor is not in a
14339 table, but before checking if the cursor is in a headline or if global cycling
14340 should be done.
14341 If any function in this hook returns t, not other actions like visibility
14342 cycling will be done.")
14344 (defvar org-tab-after-check-for-cycling-hook nil
14345 "Hook for functions to attach themselves to TAB.
14346 See `org-ctrl-c-ctrl-c-hook' for more information.
14347 This hook runs after it has been established that not table field motion and
14348 not visibility should be done because of current context. This is probably
14349 the place where a package like yasnippets can hook in.")
14351 (defvar org-metaleft-hook nil
14352 "Hook for functions attaching themselves to `M-left'.
14353 See `org-ctrl-c-ctrl-c-hook' for more information.")
14354 (defvar org-metaright-hook nil
14355 "Hook for functions attaching themselves to `M-right'.
14356 See `org-ctrl-c-ctrl-c-hook' for more information.")
14357 (defvar org-metaup-hook nil
14358 "Hook for functions attaching themselves to `M-up'.
14359 See `org-ctrl-c-ctrl-c-hook' for more information.")
14360 (defvar org-metadown-hook nil
14361 "Hook for functions attaching themselves to `M-down'.
14362 See `org-ctrl-c-ctrl-c-hook' for more information.")
14363 (defvar org-shiftmetaleft-hook nil
14364 "Hook for functions attaching themselves to `M-S-left'.
14365 See `org-ctrl-c-ctrl-c-hook' for more information.")
14366 (defvar org-shiftmetaright-hook nil
14367 "Hook for functions attaching themselves to `M-S-right'.
14368 See `org-ctrl-c-ctrl-c-hook' for more information.")
14369 (defvar org-shiftmetaup-hook nil
14370 "Hook for functions attaching themselves to `M-S-up'.
14371 See `org-ctrl-c-ctrl-c-hook' for more information.")
14372 (defvar org-shiftmetadown-hook nil
14373 "Hook for functions attaching themselves to `M-S-down'.
14374 See `org-ctrl-c-ctrl-c-hook' for more information.")
14375 (defvar org-metareturn-hook nil
14376 "Hook for functions attaching themselves to `M-RET'.
14377 See `org-ctrl-c-ctrl-c-hook' for more information.")
14379 (defun org-modifier-cursor-error ()
14380 "Throw an error, a modified cursor command was applied in wrong context."
14381 (error "This command is active in special context like tables, headlines or items"))
14383 (defun org-shiftselect-error ()
14384 "Throw an error because Shift-Cursor command was applied in wrong context."
14385 (if (and (boundp 'shift-select-mode) shift-select-mode)
14386 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
14387 (error "This command works only in special context like headlines or timestamps.")))
14389 (defun org-call-for-shift-select (cmd)
14390 (let ((this-command-keys-shift-translated t))
14391 (call-interactively cmd)))
14393 (defun org-shifttab (&optional arg)
14394 "Global visibility cycling or move to previous table field.
14395 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
14396 on context.
14397 See the individual commands for more information."
14398 (interactive "P")
14399 (cond
14400 ((org-at-table-p) (call-interactively 'org-table-previous-field))
14401 ((integerp arg)
14402 (message "Content view to level: %d" arg)
14403 (org-content (prefix-numeric-value arg))
14404 (setq org-cycle-global-status 'overview))
14405 (t (call-interactively 'org-global-cycle))))
14407 (defun org-shiftmetaleft ()
14408 "Promote subtree or delete table column.
14409 Calls `org-promote-subtree', `org-outdent-item',
14410 or `org-table-delete-column', depending on context.
14411 See the individual commands for more information."
14412 (interactive)
14413 (cond
14414 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
14415 ((org-at-table-p) (call-interactively 'org-table-delete-column))
14416 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
14417 ((org-at-item-p) (call-interactively 'org-outdent-item))
14418 (t (org-modifier-cursor-error))))
14420 (defun org-shiftmetaright ()
14421 "Demote subtree or insert table column.
14422 Calls `org-demote-subtree', `org-indent-item',
14423 or `org-table-insert-column', depending on context.
14424 See the individual commands for more information."
14425 (interactive)
14426 (cond
14427 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
14428 ((org-at-table-p) (call-interactively 'org-table-insert-column))
14429 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
14430 ((org-at-item-p) (call-interactively 'org-indent-item))
14431 (t (org-modifier-cursor-error))))
14433 (defun org-shiftmetaup (&optional arg)
14434 "Move subtree up or kill table row.
14435 Calls `org-move-subtree-up' or `org-table-kill-row' or
14436 `org-move-item-up' depending on context. See the individual commands
14437 for more information."
14438 (interactive "P")
14439 (cond
14440 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
14441 ((org-at-table-p) (call-interactively 'org-table-kill-row))
14442 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14443 ((org-at-item-p) (call-interactively 'org-move-item-up))
14444 (t (org-modifier-cursor-error))))
14446 (defun org-shiftmetadown (&optional arg)
14447 "Move subtree down or insert table row.
14448 Calls `org-move-subtree-down' or `org-table-insert-row' or
14449 `org-move-item-down', depending on context. See the individual
14450 commands for more information."
14451 (interactive "P")
14452 (cond
14453 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
14454 ((org-at-table-p) (call-interactively 'org-table-insert-row))
14455 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14456 ((org-at-item-p) (call-interactively 'org-move-item-down))
14457 (t (org-modifier-cursor-error))))
14459 (defun org-metaleft (&optional arg)
14460 "Promote heading or move table column to left.
14461 Calls `org-do-promote' or `org-table-move-column', depending on context.
14462 With no specific context, calls the Emacs default `backward-word'.
14463 See the individual commands for more information."
14464 (interactive "P")
14465 (cond
14466 ((run-hook-with-args-until-success 'org-metaleft-hook))
14467 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
14468 ((or (org-on-heading-p)
14469 (and (org-region-active-p)
14470 (save-excursion
14471 (goto-char (region-beginning))
14472 (org-on-heading-p))))
14473 (call-interactively 'org-do-promote))
14474 ((or (org-at-item-p)
14475 (and (org-region-active-p)
14476 (save-excursion
14477 (goto-char (region-beginning))
14478 (org-at-item-p))))
14479 (call-interactively 'org-outdent-item))
14480 (t (call-interactively 'backward-word))))
14482 (defun org-metaright (&optional arg)
14483 "Demote subtree or move table column to right.
14484 Calls `org-do-demote' or `org-table-move-column', depending on context.
14485 With no specific context, calls the Emacs default `forward-word'.
14486 See the individual commands for more information."
14487 (interactive "P")
14488 (cond
14489 ((run-hook-with-args-until-success 'org-metaright-hook))
14490 ((org-at-table-p) (call-interactively 'org-table-move-column))
14491 ((or (org-on-heading-p)
14492 (and (org-region-active-p)
14493 (save-excursion
14494 (goto-char (region-beginning))
14495 (org-on-heading-p))))
14496 (call-interactively 'org-do-demote))
14497 ((or (org-at-item-p)
14498 (and (org-region-active-p)
14499 (save-excursion
14500 (goto-char (region-beginning))
14501 (org-at-item-p))))
14502 (call-interactively 'org-indent-item))
14503 (t (call-interactively 'forward-word))))
14505 (defun org-metaup (&optional arg)
14506 "Move subtree up or move table row up.
14507 Calls `org-move-subtree-up' or `org-table-move-row' or
14508 `org-move-item-up', depending on context. See the individual commands
14509 for more information."
14510 (interactive "P")
14511 (cond
14512 ((run-hook-with-args-until-success 'org-metaup-hook))
14513 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
14514 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14515 ((org-at-item-p) (call-interactively 'org-move-item-up))
14516 (t (transpose-lines 1) (beginning-of-line -1))))
14518 (defun org-metadown (&optional arg)
14519 "Move subtree down or move table row down.
14520 Calls `org-move-subtree-down' or `org-table-move-row' or
14521 `org-move-item-down', depending on context. See the individual
14522 commands for more information."
14523 (interactive "P")
14524 (cond
14525 ((run-hook-with-args-until-success 'org-metadown-hook))
14526 ((org-at-table-p) (call-interactively 'org-table-move-row))
14527 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14528 ((org-at-item-p) (call-interactively 'org-move-item-down))
14529 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
14531 (defun org-shiftup (&optional arg)
14532 "Increase item in timestamp or increase priority of current headline.
14533 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
14534 depending on context. See the individual commands for more information."
14535 (interactive "P")
14536 (cond
14537 ((and org-support-shift-select (org-region-active-p))
14538 (org-call-for-shift-select 'previous-line))
14539 ((org-at-timestamp-p t)
14540 (call-interactively (if org-edit-timestamp-down-means-later
14541 'org-timestamp-down 'org-timestamp-up)))
14542 ((and (not (eq org-support-shift-select 'always))
14543 org-enable-priority-commands
14544 (org-on-heading-p))
14545 (call-interactively 'org-priority-up))
14546 ((and (not org-support-shift-select) (org-at-item-p))
14547 (call-interactively 'org-previous-item))
14548 ((org-clocktable-try-shift 'up arg))
14549 (org-support-shift-select
14550 (org-call-for-shift-select 'previous-line))
14551 (t (org-shiftselect-error))))
14553 (defun org-shiftdown (&optional arg)
14554 "Decrease item in timestamp or decrease priority of current headline.
14555 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
14556 depending on context. See the individual commands for more information."
14557 (interactive "P")
14558 (cond
14559 ((and org-support-shift-select (org-region-active-p))
14560 (org-call-for-shift-select 'next-line))
14561 ((org-at-timestamp-p t)
14562 (call-interactively (if org-edit-timestamp-down-means-later
14563 'org-timestamp-up 'org-timestamp-down)))
14564 ((and (not (eq org-support-shift-select 'always))
14565 org-enable-priority-commands
14566 (org-on-heading-p))
14567 (call-interactively 'org-priority-down))
14568 ((and (not org-support-shift-select) (org-at-item-p))
14569 (call-interactively 'org-next-item))
14570 ((org-clocktable-try-shift 'down arg))
14571 (org-support-shift-select
14572 (org-call-for-shift-select 'next-line))
14573 (t (org-shiftselect-error))))
14575 (defun org-shiftright (&optional arg)
14576 "Cycle the thing at point or in the current line, depending on context.
14577 Depending on context, this does one of the following:
14579 - switch a timestamp at point one day into the future
14580 - on a headline, switch to the next TODO keyword.
14581 - on an item, switch entire list to the next bullet type
14582 - on a property line, switch to the next allowed value
14583 - on a clocktable definition line, move time block into the future"
14584 (interactive "P")
14585 (cond
14586 ((and org-support-shift-select (org-region-active-p))
14587 (org-call-for-shift-select 'forward-char))
14588 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
14589 ((and (not (eq org-support-shift-select 'always))
14590 (org-on-heading-p))
14591 (let ((org-inhibit-logging
14592 (not org-treat-S-cursor-todo-selection-as-state-change))
14593 (org-inhibit-blocking
14594 (not org-treat-S-cursor-todo-selection-as-state-change)))
14595 (org-call-with-arg 'org-todo 'right)))
14596 ((or (and org-support-shift-select
14597 (not (eq org-support-shift-select 'always))
14598 (org-at-item-bullet-p))
14599 (and (not org-support-shift-select) (org-at-item-p)))
14600 (org-call-with-arg 'org-cycle-list-bullet nil))
14601 ((and (not (eq org-support-shift-select 'always))
14602 (org-at-property-p))
14603 (call-interactively 'org-property-next-allowed-value))
14604 ((org-clocktable-try-shift 'right arg))
14605 (org-support-shift-select
14606 (org-call-for-shift-select 'forward-char))
14607 (t (org-shiftselect-error))))
14609 (defun org-shiftleft (&optional arg)
14610 "Cycle the thing at point or in the current line, depending on context.
14611 Depending on context, this does one of the following:
14613 - switch a timestamp at point one day into the past
14614 - on a headline, switch to the previous TODO keyword.
14615 - on an item, switch entire list to the previous bullet type
14616 - on a property line, switch to the previous allowed value
14617 - on a clocktable definition line, move time block into the past"
14618 (interactive "P")
14619 (cond
14620 ((and org-support-shift-select (org-region-active-p))
14621 (org-call-for-shift-select 'backward-char))
14622 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
14623 ((and (not (eq org-support-shift-select 'always))
14624 (org-on-heading-p))
14625 (let ((org-inhibit-logging
14626 (not org-treat-S-cursor-todo-selection-as-state-change))
14627 (org-inhibit-blocking
14628 (not org-treat-S-cursor-todo-selection-as-state-change)))
14629 (org-call-with-arg 'org-todo 'left)))
14630 ((or (and org-support-shift-select
14631 (not (eq org-support-shift-select 'always))
14632 (org-at-item-bullet-p))
14633 (and (not org-support-shift-select) (org-at-item-p)))
14634 (org-call-with-arg 'org-cycle-list-bullet 'previous))
14635 ((and (not (eq org-support-shift-select 'always))
14636 (org-at-property-p))
14637 (call-interactively 'org-property-previous-allowed-value))
14638 ((org-clocktable-try-shift 'left arg))
14639 (org-support-shift-select
14640 (org-call-for-shift-select 'backward-char))
14641 (t (org-shiftselect-error))))
14643 (defun org-shiftcontrolright ()
14644 "Switch to next TODO set."
14645 (interactive)
14646 (cond
14647 ((and org-support-shift-select (org-region-active-p))
14648 (org-call-for-shift-select 'forward-word))
14649 ((and (not (eq org-support-shift-select 'always))
14650 (org-on-heading-p))
14651 (org-call-with-arg 'org-todo 'nextset))
14652 (org-support-shift-select
14653 (org-call-for-shift-select 'forward-word))
14654 (t (org-shiftselect-error))))
14656 (defun org-shiftcontrolleft ()
14657 "Switch to previous TODO set."
14658 (interactive)
14659 (cond
14660 ((and org-support-shift-select (org-region-active-p))
14661 (org-call-for-shift-select 'backward-word))
14662 ((and (not (eq org-support-shift-select 'always))
14663 (org-on-heading-p))
14664 (org-call-with-arg 'org-todo 'previousset))
14665 (org-support-shift-select
14666 (org-call-for-shift-select 'backward-word))
14667 (t (org-shiftselect-error))))
14669 (defun org-ctrl-c-ret ()
14670 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
14671 (interactive)
14672 (cond
14673 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
14674 (t (call-interactively 'org-insert-heading))))
14676 (defun org-copy-special ()
14677 "Copy region in table or copy current subtree.
14678 Calls `org-table-copy' or `org-copy-subtree', depending on context.
14679 See the individual commands for more information."
14680 (interactive)
14681 (call-interactively
14682 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
14684 (defun org-cut-special ()
14685 "Cut region in table or cut current subtree.
14686 Calls `org-table-copy' or `org-cut-subtree', depending on context.
14687 See the individual commands for more information."
14688 (interactive)
14689 (call-interactively
14690 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
14692 (defun org-paste-special (arg)
14693 "Paste rectangular region into table, or past subtree relative to level.
14694 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
14695 See the individual commands for more information."
14696 (interactive "P")
14697 (if (org-at-table-p)
14698 (org-table-paste-rectangle)
14699 (org-paste-subtree arg)))
14701 (defun org-edit-special ()
14702 "Call a special editor for the stuff at point.
14703 When at a table, call the formula editor with `org-table-edit-formulas'.
14704 When at the first line of an src example, call `org-edit-src-code'.
14705 When in an #+include line, visit the include file. Otherwise call
14706 `ffap' to visit the file at point."
14707 (interactive)
14708 (cond
14709 ((org-at-table-p)
14710 (call-interactively 'org-table-edit-formulas))
14711 ((save-excursion
14712 (beginning-of-line 1)
14713 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
14714 (find-file (org-trim (match-string 1))))
14715 ((org-edit-src-code))
14716 ((org-edit-fixed-width-region))
14717 (t (call-interactively 'ffap))))
14720 (defun org-ctrl-c-ctrl-c (&optional arg)
14721 "Set tags in headline, or update according to changed information at point.
14723 This command does many different things, depending on context:
14725 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
14726 this is what we do.
14728 - If the cursor is in a headline, prompt for tags and insert them
14729 into the current line, aligned to `org-tags-column'. When called
14730 with prefix arg, realign all tags in the current buffer.
14732 - If the cursor is in one of the special #+KEYWORD lines, this
14733 triggers scanning the buffer for these lines and updating the
14734 information.
14736 - If the cursor is inside a table, realign the table. This command
14737 works even if the automatic table editor has been turned off.
14739 - If the cursor is on a #+TBLFM line, re-apply the formulas to
14740 the entire table.
14742 - If the cursor is at a footnote reference or definition, jump to
14743 the corresponding definition or references, respectively.
14745 - If the cursor is a the beginning of a dynamic block, update it.
14747 - If the cursor is inside a table created by the table.el package,
14748 activate that table.
14750 - If the current buffer is a remember buffer, close note and file
14751 it. A prefix argument of 1 files to the default location
14752 without further interaction. A prefix argument of 2 files to
14753 the currently clocking task.
14755 - If the cursor is on a <<<target>>>, update radio targets and corresponding
14756 links in this buffer.
14758 - If the cursor is on a numbered item in a plain list, renumber the
14759 ordered list.
14761 - If the cursor is on a checkbox, toggle it."
14762 (interactive "P")
14763 (let ((org-enable-table-editor t))
14764 (cond
14765 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
14766 org-occur-highlights
14767 org-latex-fragment-image-overlays)
14768 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
14769 (org-remove-occur-highlights)
14770 (org-remove-latex-fragment-image-overlays)
14771 (message "Temporary highlights/overlays removed from current buffer"))
14772 ((and (local-variable-p 'org-finish-function (current-buffer))
14773 (fboundp org-finish-function))
14774 (funcall org-finish-function))
14775 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
14776 ((org-at-property-p)
14777 (call-interactively 'org-property-action))
14778 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
14779 ((org-on-heading-p) (call-interactively 'org-set-tags))
14780 ((org-at-table.el-p)
14781 (require 'table)
14782 (beginning-of-line 1)
14783 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
14784 (call-interactively 'table-recognize-table))
14785 ((org-at-table-p)
14786 (org-table-maybe-eval-formula)
14787 (if arg
14788 (call-interactively 'org-table-recalculate)
14789 (org-table-maybe-recalculate-line))
14790 (call-interactively 'org-table-align))
14791 ((or (org-footnote-at-reference-p)
14792 (org-footnote-at-definition-p))
14793 (call-interactively 'org-footnote-action))
14794 ((org-at-item-checkbox-p)
14795 (call-interactively 'org-toggle-checkbox))
14796 ((org-at-item-p)
14797 (if arg
14798 (call-interactively 'org-toggle-checkbox)
14799 (call-interactively 'org-maybe-renumber-ordered-list)))
14800 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
14801 ;; Dynamic block
14802 (beginning-of-line 1)
14803 (save-excursion (org-update-dblock)))
14804 ((save-excursion
14805 (beginning-of-line 1)
14806 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
14807 (cond
14808 ((equal (match-string 1) "TBLFM")
14809 ;; Recalculate the table before this line
14810 (save-excursion
14811 (beginning-of-line 1)
14812 (skip-chars-backward " \r\n\t")
14813 (if (org-at-table-p)
14814 (org-call-with-arg 'org-table-recalculate t))))
14816 ; (org-set-regexps-and-options)
14817 ; (org-restart-font-lock)
14818 (let ((org-inhibit-startup t)) (org-mode-restart))
14819 (message "Local setup has been refreshed"))))
14820 ((org-clock-update-time-maybe))
14821 (t (error "C-c C-c can do nothing useful at this location.")))))
14823 (defun org-mode-restart ()
14824 "Restart Org-mode, to scan again for special lines.
14825 Also updates the keyword regular expressions."
14826 (interactive)
14827 (org-mode)
14828 (message "Org-mode restarted"))
14830 (defun org-kill-note-or-show-branches ()
14831 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
14832 (interactive)
14833 (if (not org-finish-function)
14834 (call-interactively 'show-branches)
14835 (let ((org-note-abort t))
14836 (funcall org-finish-function))))
14838 (defun org-return (&optional indent)
14839 "Goto next table row or insert a newline.
14840 Calls `org-table-next-row' or `newline', depending on context.
14841 See the individual commands for more information."
14842 (interactive)
14843 (cond
14844 ((bobp) (if indent (newline-and-indent) (newline)))
14845 ((org-at-table-p)
14846 (org-table-justify-field-maybe)
14847 (call-interactively 'org-table-next-row))
14848 ((and org-return-follows-link
14849 (eq (get-text-property (point) 'face) 'org-link))
14850 (call-interactively 'org-open-at-point))
14851 ((and (org-at-heading-p)
14852 (looking-at
14853 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
14854 (org-show-entry)
14855 (end-of-line 1)
14856 (newline))
14857 (t (if indent (newline-and-indent) (newline)))))
14859 (defun org-return-indent ()
14860 "Goto next table row or insert a newline and indent.
14861 Calls `org-table-next-row' or `newline-and-indent', depending on
14862 context. See the individual commands for more information."
14863 (interactive)
14864 (org-return t))
14866 (defun org-ctrl-c-star ()
14867 "Compute table, or change heading status of lines.
14868 Calls `org-table-recalculate' or `org-toggle-heading',
14869 depending on context."
14870 (interactive)
14871 (cond
14872 ((org-at-table-p)
14873 (call-interactively 'org-table-recalculate))
14875 ;; Convert all lines in region to list items
14876 (call-interactively 'org-toggle-heading))))
14878 (defun org-ctrl-c-minus ()
14879 "Insert separator line in table or modify bullet status of line.
14880 Also turns a plain line or a region of lines into list items.
14881 Calls `org-table-insert-hline', `org-toggle-item', or
14882 `org-cycle-list-bullet', depending on context."
14883 (interactive)
14884 (cond
14885 ((org-at-table-p)
14886 (call-interactively 'org-table-insert-hline))
14887 ((org-region-active-p)
14888 (call-interactively 'org-toggle-item))
14889 ((org-in-item-p)
14890 (call-interactively 'org-cycle-list-bullet))
14892 (call-interactively 'org-toggle-item))))
14894 (defun org-toggle-item ()
14895 "Convert headings or normal lines to items, items to normal lines.
14896 If there is no active region, only the current line is considered.
14898 If the first line in the region is a headline, convert all headlines to items.
14900 If the first line in the region is an item, convert all items to normal lines.
14902 If the first line is normal text, add an item bullet to each line."
14903 (interactive)
14904 (let (l2 l beg end)
14905 (if (org-region-active-p)
14906 (setq beg (region-beginning) end (region-end))
14907 (setq beg (point-at-bol)
14908 end (min (1+ (point-at-eol)) (point-max))))
14909 (save-excursion
14910 (goto-char end)
14911 (setq l2 (org-current-line))
14912 (goto-char beg)
14913 (beginning-of-line 1)
14914 (setq l (1- (org-current-line)))
14915 (if (org-at-item-p)
14916 ;; We already have items, de-itemize
14917 (while (< (setq l (1+ l)) l2)
14918 (when (org-at-item-p)
14919 (goto-char (match-beginning 2))
14920 (delete-region (match-beginning 2) (match-end 2))
14921 (and (looking-at "[ \t]+") (replace-match "")))
14922 (beginning-of-line 2))
14923 (if (org-on-heading-p)
14924 ;; Headings, convert to items
14925 (while (< (setq l (1+ l)) l2)
14926 (if (looking-at org-outline-regexp)
14927 (replace-match "- " t t))
14928 (beginning-of-line 2))
14929 ;; normal lines, turn them into items
14930 (while (< (setq l (1+ l)) l2)
14931 (unless (org-at-item-p)
14932 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14933 (replace-match "\\1- \\2")))
14934 (beginning-of-line 2)))))))
14936 (defun org-toggle-heading (&optional nstars)
14937 "Convert headings to normal text, or items or text to headings.
14938 If there is no active region, only the current line is considered.
14940 If the first line is a heading, remove the stars from all headlines
14941 in the region.
14943 If the first line is a plain list item, turn all plain list items
14944 into headings.
14946 If the first line is a normal line, turn each and every line in the
14947 region into a heading.
14949 When converting a line into a heading, the number of stars is chosen
14950 such that the lines become children of the current entry. However,
14951 when a prefix argument is given, its value determines the number of
14952 stars to add."
14953 (interactive "P")
14954 (let (l2 l itemp beg end)
14955 (if (org-region-active-p)
14956 (setq beg (region-beginning) end (region-end))
14957 (setq beg (point-at-bol)
14958 end (min (1+ (point-at-eol)) (point-max))))
14959 (save-excursion
14960 (goto-char end)
14961 (setq l2 (org-current-line))
14962 (goto-char beg)
14963 (beginning-of-line 1)
14964 (setq l (1- (org-current-line)))
14965 (if (org-on-heading-p)
14966 ;; We already have headlines, de-star them
14967 (while (< (setq l (1+ l)) l2)
14968 (when (org-on-heading-p t)
14969 (and (looking-at outline-regexp) (replace-match "")))
14970 (beginning-of-line 2))
14971 (setq itemp (org-at-item-p))
14972 (let* ((stars
14973 (if nstars
14974 (make-string (prefix-numeric-value current-prefix-arg)
14976 (save-excursion
14977 (if (re-search-backward org-complex-heading-regexp nil t)
14978 (match-string 1) ""))))
14979 (add-stars (cond (nstars "")
14980 ((equal stars "") "*")
14981 (org-odd-levels-only "**")
14982 (t "*")))
14983 (rpl (concat stars add-stars " ")))
14984 (while (< (setq l (1+ l)) l2)
14985 (if itemp
14986 (and (org-at-item-p) (replace-match rpl t t))
14987 (unless (org-on-heading-p)
14988 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14989 (replace-match (concat rpl (match-string 2))))))
14990 (beginning-of-line 2)))))))
14992 (defun org-meta-return (&optional arg)
14993 "Insert a new heading or wrap a region in a table.
14994 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
14995 See the individual commands for more information."
14996 (interactive "P")
14997 (cond
14998 ((run-hook-with-args-until-success 'org-metareturn-hook))
14999 ((org-at-table-p)
15000 (call-interactively 'org-table-wrap-region))
15001 (t (call-interactively 'org-insert-heading))))
15003 ;;; Menu entries
15005 ;; Define the Org-mode menus
15006 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
15007 '("Tbl"
15008 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
15009 ["Next Field" org-cycle (org-at-table-p)]
15010 ["Previous Field" org-shifttab (org-at-table-p)]
15011 ["Next Row" org-return (org-at-table-p)]
15012 "--"
15013 ["Blank Field" org-table-blank-field (org-at-table-p)]
15014 ["Edit Field" org-table-edit-field (org-at-table-p)]
15015 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
15016 "--"
15017 ("Column"
15018 ["Move Column Left" org-metaleft (org-at-table-p)]
15019 ["Move Column Right" org-metaright (org-at-table-p)]
15020 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
15021 ["Insert Column" org-shiftmetaright (org-at-table-p)])
15022 ("Row"
15023 ["Move Row Up" org-metaup (org-at-table-p)]
15024 ["Move Row Down" org-metadown (org-at-table-p)]
15025 ["Delete Row" org-shiftmetaup (org-at-table-p)]
15026 ["Insert Row" org-shiftmetadown (org-at-table-p)]
15027 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
15028 "--"
15029 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
15030 ("Rectangle"
15031 ["Copy Rectangle" org-copy-special (org-at-table-p)]
15032 ["Cut Rectangle" org-cut-special (org-at-table-p)]
15033 ["Paste Rectangle" org-paste-special (org-at-table-p)]
15034 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
15035 "--"
15036 ("Calculate"
15037 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
15038 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
15039 ["Edit Formulas" org-edit-special (org-at-table-p)]
15040 "--"
15041 ["Recalculate line" org-table-recalculate (org-at-table-p)]
15042 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
15043 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
15044 "--"
15045 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
15046 "--"
15047 ["Sum Column/Rectangle" org-table-sum
15048 (or (org-at-table-p) (org-region-active-p))]
15049 ["Which Column?" org-table-current-column (org-at-table-p)])
15050 ["Debug Formulas"
15051 org-table-toggle-formula-debugger
15052 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
15053 ["Show Col/Row Numbers"
15054 org-table-toggle-coordinate-overlays
15055 :style toggle
15056 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
15057 "--"
15058 ["Create" org-table-create (and (not (org-at-table-p))
15059 org-enable-table-editor)]
15060 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
15061 ["Import from File" org-table-import (not (org-at-table-p))]
15062 ["Export to File" org-table-export (org-at-table-p)]
15063 "--"
15064 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
15066 (easy-menu-define org-org-menu org-mode-map "Org menu"
15067 '("Org"
15068 ("Show/Hide"
15069 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
15070 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
15071 ["Sparse Tree..." org-sparse-tree t]
15072 ["Reveal Context" org-reveal t]
15073 ["Show All" show-all t]
15074 "--"
15075 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
15076 "--"
15077 ["New Heading" org-insert-heading t]
15078 ("Navigate Headings"
15079 ["Up" outline-up-heading t]
15080 ["Next" outline-next-visible-heading t]
15081 ["Previous" outline-previous-visible-heading t]
15082 ["Next Same Level" outline-forward-same-level t]
15083 ["Previous Same Level" outline-backward-same-level t]
15084 "--"
15085 ["Jump" org-goto t])
15086 ("Edit Structure"
15087 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
15088 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
15089 "--"
15090 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
15091 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
15092 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
15093 "--"
15094 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
15095 "--"
15096 ["Promote Heading" org-metaleft (not (org-at-table-p))]
15097 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
15098 ["Demote Heading" org-metaright (not (org-at-table-p))]
15099 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
15100 "--"
15101 ["Sort Region/Children" org-sort (not (org-at-table-p))]
15102 "--"
15103 ["Convert to odd levels" org-convert-to-odd-levels t]
15104 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
15105 ("Editing"
15106 ["Emphasis..." org-emphasize t]
15107 ["Edit Source Example" org-edit-special t]
15108 "--"
15109 ["Footnote new/jump" org-footnote-action t]
15110 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
15111 ("Archive"
15112 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
15113 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
15114 ; :active t :keys "C-u C-c C-x C-a"]
15115 ["Sparse trees open ARCHIVE trees"
15116 (setq org-sparse-tree-open-archived-trees
15117 (not org-sparse-tree-open-archived-trees))
15118 :style toggle :selected org-sparse-tree-open-archived-trees]
15119 ["Cycling opens ARCHIVE trees"
15120 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
15121 :style toggle :selected org-cycle-open-archived-trees]
15122 "--"
15123 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
15124 ["Move Subtree to Archive" org-advertized-archive-subtree t]
15125 ; ["Check and Move Children" (org-archive-subtree '(4))
15126 ; :active t :keys "C-u C-c C-x C-s"]
15128 "--"
15129 ("Hyperlinks"
15130 ["Store Link (Global)" org-store-link t]
15131 ["Find existing link to here" org-occur-link-in-agenda-files t]
15132 ["Insert Link" org-insert-link t]
15133 ["Follow Link" org-open-at-point t]
15134 "--"
15135 ["Next link" org-next-link t]
15136 ["Previous link" org-previous-link t]
15137 "--"
15138 ["Descriptive Links"
15139 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
15140 :style radio
15141 :selected (member '(org-link) buffer-invisibility-spec)]
15142 ["Literal Links"
15143 (progn
15144 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
15145 :style radio
15146 :selected (not (member '(org-link) buffer-invisibility-spec))])
15147 "--"
15148 ("TODO Lists"
15149 ["TODO/DONE/-" org-todo t]
15150 ("Select keyword"
15151 ["Next keyword" org-shiftright (org-on-heading-p)]
15152 ["Previous keyword" org-shiftleft (org-on-heading-p)]
15153 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
15154 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
15155 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
15156 ["Show TODO Tree" org-show-todo-tree t]
15157 ["Global TODO list" org-todo-list t]
15158 "--"
15159 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
15160 :selected org-enforce-todo-dependencies :style toggle :active t]
15161 "Settings for tree at point"
15162 ["Do Children sequentially" org-toggle-ordered-property :style radio
15163 :selected (ignore-errors (org-entry-get nil "ORDERED"))
15164 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15165 ["Do Children parallel" org-toggle-ordered-property :style radio
15166 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
15167 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15168 "--"
15169 ["Set Priority" org-priority t]
15170 ["Priority Up" org-shiftup t]
15171 ["Priority Down" org-shiftdown t]
15172 "--"
15173 ["Get news from all feeds" org-feed-update-all t]
15174 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
15175 ["Customize feeds" (customize-variable 'org-feed-alist) t])
15176 ("TAGS and Properties"
15177 ["Set Tags" org-set-tags-command t]
15178 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
15179 "--"
15180 ["Set property" org-set-property t]
15181 ["Column view of properties" org-columns t]
15182 ["Insert Column View DBlock" org-insert-columns-dblock t])
15183 ("Dates and Scheduling"
15184 ["Timestamp" org-time-stamp t]
15185 ["Timestamp (inactive)" org-time-stamp-inactive t]
15186 ("Change Date"
15187 ["1 Day Later" org-shiftright t]
15188 ["1 Day Earlier" org-shiftleft t]
15189 ["1 ... Later" org-shiftup t]
15190 ["1 ... Earlier" org-shiftdown t])
15191 ["Compute Time Range" org-evaluate-time-range t]
15192 ["Schedule Item" org-schedule t]
15193 ["Deadline" org-deadline t]
15194 "--"
15195 ["Custom time format" org-toggle-time-stamp-overlays
15196 :style radio :selected org-display-custom-times]
15197 "--"
15198 ["Goto Calendar" org-goto-calendar t]
15199 ["Date from Calendar" org-date-from-calendar t]
15200 "--"
15201 ["Start/Restart Timer" org-timer-start t]
15202 ["Pause/Continue Timer" org-timer-pause-or-continue t]
15203 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
15204 ["Insert Timer String" org-timer t]
15205 ["Insert Timer Item" org-timer-item t])
15206 ("Logging work"
15207 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
15208 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
15209 ["Clock out" org-clock-out t]
15210 ["Clock cancel" org-clock-cancel t]
15211 "--"
15212 ["Mark as default task" org-clock-mark-default-task t]
15213 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
15214 ["Goto running clock" org-clock-goto t]
15215 "--"
15216 ["Display times" org-clock-display t]
15217 ["Create clock table" org-clock-report t]
15218 "--"
15219 ["Record DONE time"
15220 (progn (setq org-log-done (not org-log-done))
15221 (message "Switching to %s will %s record a timestamp"
15222 (car org-done-keywords)
15223 (if org-log-done "automatically" "not")))
15224 :style toggle :selected org-log-done])
15225 "--"
15226 ["Agenda Command..." org-agenda t]
15227 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
15228 ("File List for Agenda")
15229 ("Special views current file"
15230 ["TODO Tree" org-show-todo-tree t]
15231 ["Check Deadlines" org-check-deadlines t]
15232 ["Timeline" org-timeline t]
15233 ["Tags/Property tree" org-match-sparse-tree t])
15234 "--"
15235 ["Export/Publish..." org-export t]
15236 ("LaTeX"
15237 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
15238 :selected org-cdlatex-mode]
15239 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
15240 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
15241 ["Modify math symbol" org-cdlatex-math-modify
15242 (org-inside-LaTeX-fragment-p)]
15243 ["Insert citation" org-reftex-citation t]
15244 "--"
15245 ["Export LaTeX fragments as images"
15246 (if (featurep 'org-exp)
15247 (setq org-export-with-LaTeX-fragments
15248 (not org-export-with-LaTeX-fragments))
15249 (require 'org-exp))
15250 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
15251 org-export-with-LaTeX-fragments)])
15252 "--"
15253 ("Documentation"
15254 ["Show Version" org-version t]
15255 ["Info Documentation" org-info t])
15256 ("Customize"
15257 ["Browse Org Group" org-customize t]
15258 "--"
15259 ["Expand This Menu" org-create-customize-menu
15260 (fboundp 'customize-menu-create)])
15261 "--"
15262 ("Refresh/Reload"
15263 ["Refresh setup current buffer" org-mode-restart t]
15264 ["Reload Org (after update)" org-reload t]
15265 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
15268 (defun org-info (&optional node)
15269 "Read documentation for Org-mode in the info system.
15270 With optional NODE, go directly to that node."
15271 (interactive)
15272 (info (format "(org)%s" (or node ""))))
15274 (defun org-install-agenda-files-menu ()
15275 (let ((bl (buffer-list)))
15276 (save-excursion
15277 (while bl
15278 (set-buffer (pop bl))
15279 (if (org-mode-p) (setq bl nil)))
15280 (when (org-mode-p)
15281 (easy-menu-change
15282 '("Org") "File List for Agenda"
15283 (append
15284 (list
15285 ["Edit File List" (org-edit-agenda-file-list) t]
15286 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
15287 ["Remove Current File from List" org-remove-file t]
15288 ["Cycle through agenda files" org-cycle-agenda-files t]
15289 ["Occur in all agenda files" org-occur-in-agenda-files t]
15290 "--")
15291 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
15293 ;;;; Documentation
15295 ;;;###autoload
15296 (defun org-require-autoloaded-modules ()
15297 (interactive)
15298 (mapc 'require
15299 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
15300 org-docbook org-exp org-html org-icalendar
15301 org-id org-latex
15302 org-publish org-remember org-table
15303 org-timer org-xoxo)))
15305 ;;;###autoload
15306 (defun org-reload (&optional uncompiled)
15307 "Reload all org lisp files.
15308 With prefix arg UNCOMPILED, load the uncompiled versions."
15309 (interactive "P")
15310 (require 'find-func)
15311 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
15312 (dir-org (file-name-directory (org-find-library-name "org")))
15313 (dir-org-contrib (ignore-errors
15314 (file-name-directory
15315 (org-find-library-name "org-contribdir"))))
15316 (files
15317 (append (directory-files dir-org t file-re)
15318 (and dir-org-contrib
15319 (directory-files dir-org-contrib t file-re))))
15320 (remove-re (concat (if (featurep 'xemacs)
15321 "org-colview" "org-colview-xemacs")
15322 "\\'")))
15323 (setq files (mapcar 'file-name-sans-extension files))
15324 (setq files (mapcar
15325 (lambda (x) (if (string-match remove-re x) nil x))
15326 files))
15327 (setq files (delq nil files))
15328 (mapc
15329 (lambda (f)
15330 (when (featurep (intern (file-name-nondirectory f)))
15331 (if (and (not uncompiled)
15332 (file-exists-p (concat f ".elc")))
15333 (load (concat f ".elc") nil nil t)
15334 (load (concat f ".el") nil nil t))))
15335 files))
15336 (org-version))
15338 ;;;###autoload
15339 (defun org-customize ()
15340 "Call the customize function with org as argument."
15341 (interactive)
15342 (org-load-modules-maybe)
15343 (org-require-autoloaded-modules)
15344 (customize-browse 'org))
15346 (defun org-create-customize-menu ()
15347 "Create a full customization menu for Org-mode, insert it into the menu."
15348 (interactive)
15349 (org-load-modules-maybe)
15350 (org-require-autoloaded-modules)
15351 (if (fboundp 'customize-menu-create)
15352 (progn
15353 (easy-menu-change
15354 '("Org") "Customize"
15355 `(["Browse Org group" org-customize t]
15356 "--"
15357 ,(customize-menu-create 'org)
15358 ["Set" Custom-set t]
15359 ["Save" Custom-save t]
15360 ["Reset to Current" Custom-reset-current t]
15361 ["Reset to Saved" Custom-reset-saved t]
15362 ["Reset to Standard Settings" Custom-reset-standard t]))
15363 (message "\"Org\"-menu now contains full customization menu"))
15364 (error "Cannot expand menu (outdated version of cus-edit.el)")))
15366 ;;;; Miscellaneous stuff
15368 ;;; Generally useful functions
15370 (defun org-find-text-property-in-string (prop s)
15371 "Return the first non-nil value of property PROP in string S."
15372 (or (get-text-property 0 prop s)
15373 (get-text-property (or (next-single-property-change 0 prop s) 0)
15374 prop s)))
15376 (defun org-display-warning (message) ;; Copied from Emacs-Muse
15377 "Display the given MESSAGE as a warning."
15378 (if (fboundp 'display-warning)
15379 (display-warning 'org message
15380 (if (featurep 'xemacs)
15381 'warning
15382 :warning))
15383 (let ((buf (get-buffer-create "*Org warnings*")))
15384 (with-current-buffer buf
15385 (goto-char (point-max))
15386 (insert "Warning (Org): " message)
15387 (unless (bolp)
15388 (newline)))
15389 (display-buffer buf)
15390 (sit-for 0))))
15392 (defun org-goto-marker-or-bmk (marker &optional bookmark)
15393 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
15394 (if (and marker (marker-buffer marker)
15395 (buffer-live-p (marker-buffer marker)))
15396 (progn
15397 (switch-to-buffer (marker-buffer marker))
15398 (if (or (> marker (point-max)) (< marker (point-min)))
15399 (widen))
15400 (goto-char marker)
15401 (org-show-context 'org-goto))
15402 (if bookmark
15403 (bookmark-jump bookmark)
15404 (error "Cannot find location"))))
15406 (defun org-quote-csv-field (s)
15407 "Quote field for inclusion in CSV material."
15408 (if (string-match "[\",]" s)
15409 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
15412 (defun org-plist-delete (plist property)
15413 "Delete PROPERTY from PLIST.
15414 This is in contrast to merely setting it to 0."
15415 (let (p)
15416 (while plist
15417 (if (not (eq property (car plist)))
15418 (setq p (plist-put p (car plist) (nth 1 plist))))
15419 (setq plist (cddr plist)))
15422 (defun org-force-self-insert (N)
15423 "Needed to enforce self-insert under remapping."
15424 (interactive "p")
15425 (self-insert-command N))
15427 (defun org-string-width (s)
15428 "Compute width of string, ignoring invisible characters.
15429 This ignores character with invisibility property `org-link', and also
15430 characters with property `org-cwidth', because these will become invisible
15431 upon the next fontification round."
15432 (let (b l)
15433 (when (or (eq t buffer-invisibility-spec)
15434 (assq 'org-link buffer-invisibility-spec))
15435 (while (setq b (text-property-any 0 (length s)
15436 'invisible 'org-link s))
15437 (setq s (concat (substring s 0 b)
15438 (substring s (or (next-single-property-change
15439 b 'invisible s) (length s)))))))
15440 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
15441 (setq s (concat (substring s 0 b)
15442 (substring s (or (next-single-property-change
15443 b 'org-cwidth s) (length s))))))
15444 (setq l (string-width s) b -1)
15445 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
15446 (setq l (- l (get-text-property b 'org-dwidth-n s))))
15449 (defun org-get-indentation (&optional line)
15450 "Get the indentation of the current line, interpreting tabs.
15451 When LINE is given, assume it represents a line and compute its indentation."
15452 (if line
15453 (if (string-match "^ *" (org-remove-tabs line))
15454 (match-end 0))
15455 (save-excursion
15456 (beginning-of-line 1)
15457 (skip-chars-forward " \t")
15458 (current-column))))
15460 (defun org-remove-tabs (s &optional width)
15461 "Replace tabulators in S with spaces.
15462 Assumes that s is a single line, starting in column 0."
15463 (setq width (or width tab-width))
15464 (while (string-match "\t" s)
15465 (setq s (replace-match
15466 (make-string
15467 (- (* width (/ (+ (match-beginning 0) width) width))
15468 (match-beginning 0)) ?\ )
15469 t t s)))
15472 (defun org-fix-indentation (line ind)
15473 "Fix indentation in LINE.
15474 IND is a cons cell with target and minimum indentation.
15475 If the current indentation in LINE is smaller than the minimum,
15476 leave it alone. If it is larger than ind, set it to the target."
15477 (let* ((l (org-remove-tabs line))
15478 (i (org-get-indentation l))
15479 (i1 (car ind)) (i2 (cdr ind)))
15480 (if (>= i i2) (setq l (substring line i2)))
15481 (if (> i1 0)
15482 (concat (make-string i1 ?\ ) l)
15483 l)))
15485 (defun org-remove-indentation (code &optional n)
15486 "Remove the maximum common indentation from the lines in CODE.
15487 N may optionally be the number of spaces to remove."
15488 (with-temp-buffer
15489 (insert code)
15490 (org-do-remove-indentation n)
15491 (buffer-string)))
15493 (defun org-do-remove-indentation (&optional n)
15494 "Remove the maximum common indentation from the buffer."
15495 (untabify (point-min) (point-max))
15496 (let ((min 10000) re)
15497 (if n
15498 (setq min n)
15499 (goto-char (point-min))
15500 (while (re-search-forward "^ *[^ \n]" nil t)
15501 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
15502 (unless (or (= min 0) (= min 10000))
15503 (setq re (format "^ \\{%d\\}" min))
15504 (goto-char (point-min))
15505 (while (re-search-forward re nil t)
15506 (replace-match "")
15507 (end-of-line 1))
15508 min)))
15510 (defun org-base-buffer (buffer)
15511 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
15512 (if (not buffer)
15513 buffer
15514 (or (buffer-base-buffer buffer)
15515 buffer)))
15517 (defun org-trim (s)
15518 "Remove whitespace at beginning and end of string."
15519 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
15520 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
15523 (defun org-wrap (string &optional width lines)
15524 "Wrap string to either a number of lines, or a width in characters.
15525 If WIDTH is non-nil, the string is wrapped to that width, however many lines
15526 that costs. If there is a word longer than WIDTH, the text is actually
15527 wrapped to the length of that word.
15528 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
15529 many lines, whatever width that takes.
15530 The return value is a list of lines, without newlines at the end."
15531 (let* ((words (org-split-string string "[ \t\n]+"))
15532 (maxword (apply 'max (mapcar 'org-string-width words)))
15533 w ll)
15534 (cond (width
15535 (org-do-wrap words (max maxword width)))
15536 (lines
15537 (setq w maxword)
15538 (setq ll (org-do-wrap words maxword))
15539 (if (<= (length ll) lines)
15541 (setq ll words)
15542 (while (> (length ll) lines)
15543 (setq w (1+ w))
15544 (setq ll (org-do-wrap words w)))
15545 ll))
15546 (t (error "Cannot wrap this")))))
15548 (defun org-do-wrap (words width)
15549 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
15550 (let (lines line)
15551 (while words
15552 (setq line (pop words))
15553 (while (and words (< (+ (length line) (length (car words))) width))
15554 (setq line (concat line " " (pop words))))
15555 (setq lines (push line lines)))
15556 (nreverse lines)))
15558 (defun org-split-string (string &optional separators)
15559 "Splits STRING into substrings at SEPARATORS.
15560 No empty strings are returned if there are matches at the beginning
15561 and end of string."
15562 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
15563 (start 0)
15564 notfirst
15565 (list nil))
15566 (while (and (string-match rexp string
15567 (if (and notfirst
15568 (= start (match-beginning 0))
15569 (< start (length string)))
15570 (1+ start) start))
15571 (< (match-beginning 0) (length string)))
15572 (setq notfirst t)
15573 (or (eq (match-beginning 0) 0)
15574 (and (eq (match-beginning 0) (match-end 0))
15575 (eq (match-beginning 0) start))
15576 (setq list
15577 (cons (substring string start (match-beginning 0))
15578 list)))
15579 (setq start (match-end 0)))
15580 (or (eq start (length string))
15581 (setq list
15582 (cons (substring string start)
15583 list)))
15584 (nreverse list)))
15586 (defun org-quote-vert (s)
15587 "Replace \"|\" with \"\\vert\"."
15588 (while (string-match "|" s)
15589 (setq s (replace-match "\\vert" t t s)))
15592 (defun org-uuidgen-p (s)
15593 "Is S an ID created by UUIDGEN?"
15594 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
15596 (defun org-context ()
15597 "Return a list of contexts of the current cursor position.
15598 If several contexts apply, all are returned.
15599 Each context entry is a list with a symbol naming the context, and
15600 two positions indicating start and end of the context. Possible
15601 contexts are:
15603 :headline anywhere in a headline
15604 :headline-stars on the leading stars in a headline
15605 :todo-keyword on a TODO keyword (including DONE) in a headline
15606 :tags on the TAGS in a headline
15607 :priority on the priority cookie in a headline
15608 :item on the first line of a plain list item
15609 :item-bullet on the bullet/number of a plain list item
15610 :checkbox on the checkbox in a plain list item
15611 :table in an org-mode table
15612 :table-special on a special filed in a table
15613 :table-table in a table.el table
15614 :link on a hyperlink
15615 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
15616 :target on a <<target>>
15617 :radio-target on a <<<radio-target>>>
15618 :latex-fragment on a LaTeX fragment
15619 :latex-preview on a LaTeX fragment with overlayed preview image
15621 This function expects the position to be visible because it uses font-lock
15622 faces as a help to recognize the following contexts: :table-special, :link,
15623 and :keyword."
15624 (let* ((f (get-text-property (point) 'face))
15625 (faces (if (listp f) f (list f)))
15626 (p (point)) clist o)
15627 ;; First the large context
15628 (cond
15629 ((org-on-heading-p t)
15630 (push (list :headline (point-at-bol) (point-at-eol)) clist)
15631 (when (progn
15632 (beginning-of-line 1)
15633 (looking-at org-todo-line-tags-regexp))
15634 (push (org-point-in-group p 1 :headline-stars) clist)
15635 (push (org-point-in-group p 2 :todo-keyword) clist)
15636 (push (org-point-in-group p 4 :tags) clist))
15637 (goto-char p)
15638 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
15639 (if (looking-at "\\[#[A-Z0-9]\\]")
15640 (push (org-point-in-group p 0 :priority) clist)))
15642 ((org-at-item-p)
15643 (push (org-point-in-group p 2 :item-bullet) clist)
15644 (push (list :item (point-at-bol)
15645 (save-excursion (org-end-of-item) (point)))
15646 clist)
15647 (and (org-at-item-checkbox-p)
15648 (push (org-point-in-group p 0 :checkbox) clist)))
15650 ((org-at-table-p)
15651 (push (list :table (org-table-begin) (org-table-end)) clist)
15652 (if (memq 'org-formula faces)
15653 (push (list :table-special
15654 (previous-single-property-change p 'face)
15655 (next-single-property-change p 'face)) clist)))
15656 ((org-at-table-p 'any)
15657 (push (list :table-table) clist)))
15658 (goto-char p)
15660 ;; Now the small context
15661 (cond
15662 ((org-at-timestamp-p)
15663 (push (org-point-in-group p 0 :timestamp) clist))
15664 ((memq 'org-link faces)
15665 (push (list :link
15666 (previous-single-property-change p 'face)
15667 (next-single-property-change p 'face)) clist))
15668 ((memq 'org-special-keyword faces)
15669 (push (list :keyword
15670 (previous-single-property-change p 'face)
15671 (next-single-property-change p 'face)) clist))
15672 ((org-on-target-p)
15673 (push (org-point-in-group p 0 :target) clist)
15674 (goto-char (1- (match-beginning 0)))
15675 (if (looking-at org-radio-target-regexp)
15676 (push (org-point-in-group p 0 :radio-target) clist))
15677 (goto-char p))
15678 ((setq o (car (delq nil
15679 (mapcar
15680 (lambda (x)
15681 (if (memq x org-latex-fragment-image-overlays) x))
15682 (org-overlays-at (point))))))
15683 (push (list :latex-fragment
15684 (org-overlay-start o) (org-overlay-end o)) clist)
15685 (push (list :latex-preview
15686 (org-overlay-start o) (org-overlay-end o)) clist))
15687 ((org-inside-LaTeX-fragment-p)
15688 ;; FIXME: positions wrong.
15689 (push (list :latex-fragment (point) (point)) clist)))
15691 (setq clist (nreverse (delq nil clist)))
15692 clist))
15694 ;; FIXME: Compare with at-regexp-p Do we need both?
15695 (defun org-in-regexp (re &optional nlines visually)
15696 "Check if point is inside a match of regexp.
15697 Normally only the current line is checked, but you can include NLINES extra
15698 lines both before and after point into the search.
15699 If VISUALLY is set, require that the cursor is not after the match but
15700 really on, so that the block visually is on the match."
15701 (catch 'exit
15702 (let ((pos (point))
15703 (eol (point-at-eol (+ 1 (or nlines 0))))
15704 (inc (if visually 1 0)))
15705 (save-excursion
15706 (beginning-of-line (- 1 (or nlines 0)))
15707 (while (re-search-forward re eol t)
15708 (if (and (<= (match-beginning 0) pos)
15709 (>= (+ inc (match-end 0)) pos))
15710 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
15712 (defun org-at-regexp-p (regexp)
15713 "Is point inside a match of REGEXP in the current line?"
15714 (catch 'exit
15715 (save-excursion
15716 (let ((pos (point)) (end (point-at-eol)))
15717 (beginning-of-line 1)
15718 (while (re-search-forward regexp end t)
15719 (if (and (<= (match-beginning 0) pos)
15720 (>= (match-end 0) pos))
15721 (throw 'exit t)))
15722 nil))))
15724 (defun org-occur-in-agenda-files (regexp &optional nlines)
15725 "Call `multi-occur' with buffers for all agenda files."
15726 (interactive "sOrg-files matching: \np")
15727 (let* ((files (org-agenda-files))
15728 (tnames (mapcar 'file-truename files))
15729 (extra org-agenda-text-search-extra-files)
15731 (when (eq (car extra) 'agenda-archives)
15732 (setq extra (cdr extra))
15733 (setq files (org-add-archive-files files)))
15734 (while (setq f (pop extra))
15735 (unless (member (file-truename f) tnames)
15736 (add-to-list 'files f 'append)
15737 (add-to-list 'tnames (file-truename f) 'append)))
15738 (multi-occur
15739 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
15740 regexp)))
15742 (if (boundp 'occur-mode-find-occurrence-hook)
15743 ;; Emacs 23
15744 (add-hook 'occur-mode-find-occurrence-hook
15745 (lambda ()
15746 (when (org-mode-p)
15747 (org-reveal))))
15748 ;; Emacs 22
15749 (defadvice occur-mode-goto-occurrence
15750 (after org-occur-reveal activate)
15751 (and (org-mode-p) (org-reveal)))
15752 (defadvice occur-mode-goto-occurrence-other-window
15753 (after org-occur-reveal activate)
15754 (and (org-mode-p) (org-reveal)))
15755 (defadvice occur-mode-display-occurrence
15756 (after org-occur-reveal activate)
15757 (when (org-mode-p)
15758 (let ((pos (occur-mode-find-occurrence)))
15759 (with-current-buffer (marker-buffer pos)
15760 (save-excursion
15761 (goto-char pos)
15762 (org-reveal)))))))
15764 (defun org-occur-link-in-agenda-files ()
15765 "Create a link and search for it in the agendas.
15766 The link is not stored in `org-stored-links', it is just created
15767 for the search purpose."
15768 (interactive)
15769 (let ((link (condition-case nil
15770 (org-store-link nil)
15771 (error "Unable to create a link to here"))))
15772 (org-occur-in-agenda-files (regexp-quote link))))
15774 (defun org-uniquify (list)
15775 "Remove duplicate elements from LIST."
15776 (let (res)
15777 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
15778 res))
15780 (defun org-delete-all (elts list)
15781 "Remove all elements in ELTS from LIST."
15782 (while elts
15783 (setq list (delete (pop elts) list)))
15784 list)
15786 (defun org-back-over-empty-lines ()
15787 "Move backwards over whitespace, to the beginning of the first empty line.
15788 Returns the number of empty lines passed."
15789 (let ((pos (point)))
15790 (skip-chars-backward " \t\n\r")
15791 (beginning-of-line 2)
15792 (goto-char (min (point) pos))
15793 (count-lines (point) pos)))
15795 (defun org-skip-whitespace ()
15796 (skip-chars-forward " \t\n\r"))
15798 (defun org-point-in-group (point group &optional context)
15799 "Check if POINT is in match-group GROUP.
15800 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
15801 match. If the match group does ot exist or point is not inside it,
15802 return nil."
15803 (and (match-beginning group)
15804 (>= point (match-beginning group))
15805 (<= point (match-end group))
15806 (if context
15807 (list context (match-beginning group) (match-end group))
15808 t)))
15810 (defun org-switch-to-buffer-other-window (&rest args)
15811 "Switch to buffer in a second window on the current frame.
15812 In particular, do not allow pop-up frames."
15813 (let (pop-up-frames special-display-buffer-names special-display-regexps
15814 special-display-function)
15815 (apply 'switch-to-buffer-other-window args)))
15817 (defun org-combine-plists (&rest plists)
15818 "Create a single property list from all plists in PLISTS.
15819 The process starts by copying the first list, and then setting properties
15820 from the other lists. Settings in the last list are the most significant
15821 ones and overrule settings in the other lists."
15822 (let ((rtn (copy-sequence (pop plists)))
15823 p v ls)
15824 (while plists
15825 (setq ls (pop plists))
15826 (while ls
15827 (setq p (pop ls) v (pop ls))
15828 (setq rtn (plist-put rtn p v))))
15829 rtn))
15831 (defun org-move-line-down (arg)
15832 "Move the current line down. With prefix argument, move it past ARG lines."
15833 (interactive "p")
15834 (let ((col (current-column))
15835 beg end pos)
15836 (beginning-of-line 1) (setq beg (point))
15837 (beginning-of-line 2) (setq end (point))
15838 (beginning-of-line (+ 1 arg))
15839 (setq pos (move-marker (make-marker) (point)))
15840 (insert (delete-and-extract-region beg end))
15841 (goto-char pos)
15842 (org-move-to-column col)))
15844 (defun org-move-line-up (arg)
15845 "Move the current line up. With prefix argument, move it past ARG lines."
15846 (interactive "p")
15847 (let ((col (current-column))
15848 beg end pos)
15849 (beginning-of-line 1) (setq beg (point))
15850 (beginning-of-line 2) (setq end (point))
15851 (beginning-of-line (- arg))
15852 (setq pos (move-marker (make-marker) (point)))
15853 (insert (delete-and-extract-region beg end))
15854 (goto-char pos)
15855 (org-move-to-column col)))
15857 (defun org-replace-escapes (string table)
15858 "Replace %-escapes in STRING with values in TABLE.
15859 TABLE is an association list with keys like \"%a\" and string values.
15860 The sequences in STRING may contain normal field width and padding information,
15861 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
15862 so values can contain further %-escapes if they are define later in TABLE."
15863 (let ((case-fold-search nil)
15864 e re rpl)
15865 (while (setq e (pop table))
15866 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
15867 (while (string-match re string)
15868 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
15869 (cdr e)))
15870 (setq string (replace-match rpl t t string))))
15871 string))
15874 (defun org-sublist (list start end)
15875 "Return a section of LIST, from START to END.
15876 Counting starts at 1."
15877 (let (rtn (c start))
15878 (setq list (nthcdr (1- start) list))
15879 (while (and list (<= c end))
15880 (push (pop list) rtn)
15881 (setq c (1+ c)))
15882 (nreverse rtn)))
15884 (defun org-find-base-buffer-visiting (file)
15885 "Like `find-buffer-visiting' but always return the base buffer and
15886 not an indirect buffer."
15887 (let ((buf (or (get-file-buffer file)
15888 (find-buffer-visiting file))))
15889 (if buf
15890 (or (buffer-base-buffer buf) buf)
15891 nil)))
15893 (defun org-image-file-name-regexp (&optional extensions)
15894 "Return regexp matching the file names of images.
15895 If EXTENSIONS is given, only match these."
15896 (if (and (not extensions) (fboundp 'image-file-name-regexp))
15897 (image-file-name-regexp)
15898 (let ((image-file-name-extensions
15899 (or extensions
15900 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
15901 "xbm" "xpm" "pbm" "pgm" "ppm"))))
15902 (concat "\\."
15903 (regexp-opt (nconc (mapcar 'upcase
15904 image-file-name-extensions)
15905 image-file-name-extensions)
15907 "\\'"))))
15909 (defun org-file-image-p (file &optional extensions)
15910 "Return non-nil if FILE is an image."
15911 (save-match-data
15912 (string-match (org-image-file-name-regexp extensions) file)))
15914 (defun org-get-cursor-date ()
15915 "Return the date at cursor in as a time.
15916 This works in the calendar and in the agenda, anywhere else it just
15917 returns the current time."
15918 (let (date day defd)
15919 (cond
15920 ((eq major-mode 'calendar-mode)
15921 (setq date (calendar-cursor-to-date)
15922 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15923 ((eq major-mode 'org-agenda-mode)
15924 (setq day (get-text-property (point) 'day))
15925 (if day
15926 (setq date (calendar-gregorian-from-absolute day)
15927 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
15928 (nth 2 date))))))
15929 (or defd (current-time))))
15931 (defvar org-agenda-action-marker (make-marker)
15932 "Marker pointing to the entry for the next agenda action.")
15934 (defun org-mark-entry-for-agenda-action ()
15935 "Mark the current entry as target of an agenda action.
15936 Agenda actions are actions executed from the agenda with the key `k',
15937 which make use of the date at the cursor."
15938 (interactive)
15939 (move-marker org-agenda-action-marker
15940 (save-excursion (org-back-to-heading t) (point))
15941 (current-buffer))
15942 (message
15943 "Entry marked for action; press `k' at desired date in agenda or calendar"))
15945 ;;; Paragraph filling stuff.
15946 ;; We want this to be just right, so use the full arsenal.
15948 (defun org-indent-line-function ()
15949 "Indent line like previous, but further if previous was headline or item."
15950 (interactive)
15951 (let* ((pos (point))
15952 (itemp (org-at-item-p))
15953 (case-fold-search t)
15954 (org-drawer-regexp (or org-drawer-regexp "\000"))
15955 column bpos bcol tpos tcol bullet btype bullet-type)
15956 ;; Find the previous relevant line
15957 (beginning-of-line 1)
15958 (cond
15959 ((looking-at "#") (setq column 0))
15960 ((looking-at "\\*+ ") (setq column 0))
15961 ((and (looking-at "[ \t]*:END:")
15962 (save-excursion (re-search-backward org-drawer-regexp nil t)))
15963 (save-excursion
15964 (goto-char (1- (match-beginning 1)))
15965 (setq column (current-column))))
15966 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
15967 (save-excursion
15968 (re-search-backward
15969 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
15970 (setq column (org-get-indentation (match-string 0))))
15972 (beginning-of-line 0)
15973 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
15974 (not (looking-at "[ \t]*:END:"))
15975 (not (looking-at org-drawer-regexp)))
15976 (beginning-of-line 0))
15977 (cond
15978 ((looking-at "\\*+[ \t]+")
15979 (if (not org-adapt-indentation)
15980 (setq column 0)
15981 (goto-char (match-end 0))
15982 (setq column (current-column))))
15983 ((looking-at org-drawer-regexp)
15984 (goto-char (1- (match-beginning 1)))
15985 (setq column (current-column)))
15986 ((looking-at "\\([ \t]*\\):END:")
15987 (goto-char (match-end 1))
15988 (setq column (current-column)))
15989 ((org-in-item-p)
15990 (org-beginning-of-item)
15991 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
15992 (setq bpos (match-beginning 1) tpos (match-end 0)
15993 bcol (progn (goto-char bpos) (current-column))
15994 tcol (progn (goto-char tpos) (current-column))
15995 bullet (match-string 1)
15996 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
15997 (if (> tcol (+ bcol org-description-max-indent))
15998 (setq tcol (+ bcol 5)))
15999 (if (not itemp)
16000 (setq column tcol)
16001 (goto-char pos)
16002 (beginning-of-line 1)
16003 (if (looking-at "\\S-")
16004 (progn
16005 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
16006 (setq bullet (match-string 1)
16007 btype (if (string-match "[0-9]" bullet) "n" bullet))
16008 (setq column (if (equal btype bullet-type) bcol tcol)))
16009 (setq column (org-get-indentation)))))
16010 (t (setq column (org-get-indentation))))))
16011 (goto-char pos)
16012 (if (<= (current-column) (current-indentation))
16013 (org-indent-line-to column)
16014 (save-excursion (org-indent-line-to column)))
16015 (setq column (current-column))
16016 (beginning-of-line 1)
16017 (if (looking-at
16018 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
16019 (replace-match (concat "\\1" (format org-property-format
16020 (match-string 2) (match-string 3)))
16021 t nil))
16022 (org-move-to-column column)))
16024 (defun org-set-autofill-regexps ()
16025 (interactive)
16026 ;; In the paragraph separator we include headlines, because filling
16027 ;; text in a line directly attached to a headline would otherwise
16028 ;; fill the headline as well.
16029 (org-set-local 'comment-start-skip "^#+[ \t]*")
16030 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
16031 ;; The paragraph starter includes hand-formatted lists.
16032 (org-set-local
16033 'paragraph-start
16034 (concat
16035 "\f" "\\|"
16036 "[ ]*$" "\\|"
16037 "\\*+ " "\\|"
16038 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
16039 "[ \t]*[:|]" "\\|"
16040 "\\$\\$" "\\|"
16041 "\\\\\\(begin\\|end\\|[][]\\)"))
16042 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
16043 ;; But only if the user has not turned off tables or fixed-width regions
16044 (org-set-local
16045 'auto-fill-inhibit-regexp
16046 (concat "\\*+ \\|#\\+"
16047 "\\|[ \t]*" org-keyword-time-regexp
16048 (if (or org-enable-table-editor org-enable-fixed-width-editor)
16049 (concat
16050 "\\|[ \t]*["
16051 (if org-enable-table-editor "|" "")
16052 (if org-enable-fixed-width-editor ":" "")
16053 "]"))))
16054 ;; We use our own fill-paragraph function, to make sure that tables
16055 ;; and fixed-width regions are not wrapped. That function will pass
16056 ;; through to `fill-paragraph' when appropriate.
16057 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
16058 ; Adaptive filling: To get full control, first make sure that
16059 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
16060 (org-set-local 'adaptive-fill-regexp "\000")
16061 (org-set-local 'adaptive-fill-function
16062 'org-adaptive-fill-function)
16063 (org-set-local
16064 'align-mode-rules-list
16065 '((org-in-buffer-settings
16066 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
16067 (modes . '(org-mode))))))
16069 (defun org-fill-paragraph (&optional justify)
16070 "Re-align a table, pass through to fill-paragraph if no table."
16071 (let ((table-p (org-at-table-p))
16072 (table.el-p (org-at-table.el-p)))
16073 (cond ((and (equal (char-after (point-at-bol)) ?*)
16074 (save-excursion (goto-char (point-at-bol))
16075 (looking-at outline-regexp)))
16076 t) ; skip headlines
16077 (table.el-p t) ; skip table.el tables
16078 (table-p (org-table-align) t) ; align org-mode tables
16079 (t nil)))) ; call paragraph-fill
16081 ;; For reference, this is the default value of adaptive-fill-regexp
16082 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
16084 (defun org-adaptive-fill-function ()
16085 "Return a fill prefix for org-mode files.
16086 In particular, this makes sure hanging paragraphs for hand-formatted lists
16087 work correctly."
16088 (cond ((looking-at "#[ \t]+")
16089 (match-string 0))
16090 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
16091 (save-excursion
16092 (if (> (match-end 1) (+ (match-beginning 1)
16093 org-description-max-indent))
16094 (goto-char (+ (match-beginning 1) 5))
16095 (goto-char (match-end 0)))
16096 (make-string (current-column) ?\ )))
16097 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
16098 (save-excursion
16099 (goto-char (match-end 0))
16100 (make-string (current-column) ?\ )))
16101 (t nil)))
16103 ;;; Other stuff.
16105 (defun org-toggle-fixed-width-section (arg)
16106 "Toggle the fixed-width export.
16107 If there is no active region, the QUOTE keyword at the current headline is
16108 inserted or removed. When present, it causes the text between this headline
16109 and the next to be exported as fixed-width text, and unmodified.
16110 If there is an active region, this command adds or removes a colon as the
16111 first character of this line. If the first character of a line is a colon,
16112 this line is also exported in fixed-width font."
16113 (interactive "P")
16114 (let* ((cc 0)
16115 (regionp (org-region-active-p))
16116 (beg (if regionp (region-beginning) (point)))
16117 (end (if regionp (region-end)))
16118 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
16119 (case-fold-search nil)
16120 (re "[ \t]*\\(: \\)")
16121 off)
16122 (if regionp
16123 (save-excursion
16124 (goto-char beg)
16125 (setq cc (current-column))
16126 (beginning-of-line 1)
16127 (setq off (looking-at re))
16128 (while (> nlines 0)
16129 (setq nlines (1- nlines))
16130 (beginning-of-line 1)
16131 (cond
16132 (arg
16133 (org-move-to-column cc t)
16134 (insert ": \n")
16135 (forward-line -1))
16136 ((and off (looking-at re))
16137 (replace-match "" t t nil 1))
16138 ((not off) (org-move-to-column cc t) (insert ": ")))
16139 (forward-line 1)))
16140 (save-excursion
16141 (org-back-to-heading)
16142 (if (looking-at (concat outline-regexp
16143 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
16144 (replace-match "" t t nil 1)
16145 (if (looking-at outline-regexp)
16146 (progn
16147 (goto-char (match-end 0))
16148 (insert org-quote-string " "))))))))
16150 (defun org-reftex-citation ()
16151 "Use reftex-citation to insert a citation into the buffer.
16152 This looks for a line like
16154 #+BIBLIOGRAPHY: foo plain option:-d
16156 and derives from it that foo.bib is the bbliography file relevant
16157 for this document. It then installs the necessary environment for RefTeX
16158 to work in this buffer and calls `reftex-citation' to insert a citation
16159 into the buffer.
16161 Export of such citations to both LaTeX and HTML is handled by the contributed
16162 package org-exp-bibtex by Taru Karttunen."
16163 (interactive)
16164 (let ((reftex-docstruct-symbol 'rds)
16165 (reftex-cite-format "\\cite{%l}")
16166 rds bib)
16167 (save-excursion
16168 (save-restriction
16169 (widen)
16170 (let ((case-fold-search t)
16171 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
16172 (if (not (save-excursion
16173 (or (re-search-forward re nil t)
16174 (re-search-backward re nil t))))
16175 (error "No bibliography defined in file")
16176 (setq bib (concat (match-string 1) ".bib")
16177 rds (list (list 'bib bib)))))))
16178 (call-interactively 'reftex-citation)))
16180 ;;;; Functions extending outline functionality
16182 (defun org-beginning-of-line (&optional arg)
16183 "Go to the beginning of the current line. If that is invisible, continue
16184 to a visible line beginning. This makes the function of C-a more intuitive.
16185 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16186 first attempt, and only move to after the tags when the cursor is already
16187 beyond the end of the headline."
16188 (interactive "P")
16189 (let ((pos (point))
16190 (special (if (consp org-special-ctrl-a/e)
16191 (car org-special-ctrl-a/e)
16192 org-special-ctrl-a/e))
16193 refpos)
16194 (if (org-bound-and-true-p line-move-visual)
16195 (beginning-of-visual-line 1)
16196 (beginning-of-line 1))
16197 (if (and arg (fboundp 'move-beginning-of-line))
16198 (call-interactively 'move-beginning-of-line)
16199 (if (bobp)
16201 (backward-char 1)
16202 (if (org-invisible-p)
16203 (while (and (not (bobp)) (org-invisible-p))
16204 (backward-char 1)
16205 (beginning-of-line 1))
16206 (forward-char 1))))
16207 (when special
16208 (cond
16209 ((and (looking-at org-complex-heading-regexp)
16210 (= (char-after (match-end 1)) ?\ ))
16211 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
16212 (point-at-eol)))
16213 (goto-char
16214 (if (eq special t)
16215 (cond ((> pos refpos) refpos)
16216 ((= pos (point)) refpos)
16217 (t (point)))
16218 (cond ((> pos (point)) (point))
16219 ((not (eq last-command this-command)) (point))
16220 (t refpos)))))
16221 ((org-at-item-p)
16222 (goto-char
16223 (if (eq special t)
16224 (cond ((> pos (match-end 4)) (match-end 4))
16225 ((= pos (point)) (match-end 4))
16226 (t (point)))
16227 (cond ((> pos (point)) (point))
16228 ((not (eq last-command this-command)) (point))
16229 (t (match-end 4))))))))
16230 (org-no-warnings
16231 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16233 (defun org-end-of-line (&optional arg)
16234 "Go to the end of the line.
16235 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16236 first attempt, and only move to after the tags when the cursor is already
16237 beyond the end of the headline."
16238 (interactive "P")
16239 (let ((special (if (consp org-special-ctrl-a/e)
16240 (cdr org-special-ctrl-a/e)
16241 org-special-ctrl-a/e)))
16242 (if (or (not special)
16243 (not (org-on-heading-p))
16244 arg)
16245 (call-interactively
16246 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
16247 ((fboundp 'move-end-of-line) 'move-end-of-line)
16248 (t 'end-of-line)))
16249 (let ((pos (point)))
16250 (beginning-of-line 1)
16251 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
16252 (if (eq special t)
16253 (if (or (< pos (match-beginning 1))
16254 (= pos (match-end 0)))
16255 (goto-char (match-beginning 1))
16256 (goto-char (match-end 0)))
16257 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
16258 (goto-char (match-end 0))
16259 (goto-char (match-beginning 1))))
16260 (call-interactively (if (fboundp 'move-end-of-line)
16261 'move-end-of-line
16262 'end-of-line)))))
16263 (org-no-warnings
16264 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16266 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
16267 (define-key org-mode-map "\C-e" 'org-end-of-line)
16269 (defun org-backward-sentence (&optional arg)
16270 "Go to beginning of sentence, or beginning of table field.
16271 This will call `backward-sentence' or `org-table-beginning-of-field',
16272 depending on context."
16273 (interactive "P")
16274 (cond
16275 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
16276 (t (call-interactively 'backward-sentence))))
16278 (defun org-forward-sentence (&optional arg)
16279 "Go to end of sentence, or end of table field.
16280 This will call `forward-sentence' or `org-table-end-of-field',
16281 depending on context."
16282 (interactive "P")
16283 (cond
16284 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
16285 (t (call-interactively 'forward-sentence))))
16287 (define-key org-mode-map "\M-a" 'org-backward-sentence)
16288 (define-key org-mode-map "\M-e" 'org-forward-sentence)
16290 (defun org-kill-line (&optional arg)
16291 "Kill line, to tags or end of line."
16292 (interactive "P")
16293 (cond
16294 ((or (not org-special-ctrl-k)
16295 (bolp)
16296 (not (org-on-heading-p)))
16297 (call-interactively 'kill-line))
16298 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
16299 (kill-region (point) (match-beginning 1))
16300 (org-set-tags nil t))
16301 (t (kill-region (point) (point-at-eol)))))
16303 (define-key org-mode-map "\C-k" 'org-kill-line)
16305 (defun org-yank (&optional arg)
16306 "Yank. If the kill is a subtree, treat it specially.
16307 This command will look at the current kill and check if is a single
16308 subtree, or a series of subtrees[1]. If it passes the test, and if the
16309 cursor is at the beginning of a line or after the stars of a currently
16310 empty headline, then the yank is handled specially. How exactly depends
16311 on the value of the following variables, both set by default.
16313 org-yank-folded-subtrees
16314 When set, the subtree(s) will be folded after insertion, but only
16315 if doing so would now swallow text after the yanked text.
16317 org-yank-adjusted-subtrees
16318 When set, the subtree will be promoted or demoted in order to
16319 fit into the local outline tree structure, which means that the level
16320 will be adjusted so that it becomes the smaller one of the two
16321 *visible* surrounding headings.
16323 Any prefix to this command will cause `yank' to be called directly with
16324 no special treatment. In particular, a simple `C-u' prefix will just
16325 plainly yank the text as it is.
16327 \[1] The test checks if the first non-white line is a heading
16328 and if there are no other headings with fewer stars."
16329 (interactive "P")
16330 (org-yank-generic 'yank arg))
16332 (defun org-yank-generic (command arg)
16333 "Perform some yank-like command.
16335 This function implements the behavior described in the `org-yank'
16336 documentation. However, it has been generalized to work for any
16337 interactive command with similar behavior."
16339 ;; pretend to be command COMMAND
16340 (setq this-command command)
16342 (if arg
16343 (call-interactively command)
16345 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
16346 (and (org-kill-is-subtree-p)
16347 (or (bolp)
16348 (and (looking-at "[ \t]*$")
16349 (string-match
16350 "\\`\\*+\\'"
16351 (buffer-substring (point-at-bol) (point)))))))
16352 swallowp)
16353 (cond
16354 ((and subtreep org-yank-folded-subtrees)
16355 (let ((beg (point))
16356 end)
16357 (if (and subtreep org-yank-adjusted-subtrees)
16358 (org-paste-subtree nil nil 'for-yank)
16359 (call-interactively command))
16361 (setq end (point))
16362 (goto-char beg)
16363 (when (and (bolp) subtreep
16364 (not (setq swallowp
16365 (org-yank-folding-would-swallow-text beg end))))
16366 (or (looking-at outline-regexp)
16367 (re-search-forward (concat "^" outline-regexp) end t))
16368 (while (and (< (point) end) (looking-at outline-regexp))
16369 (hide-subtree)
16370 (org-cycle-show-empty-lines 'folded)
16371 (condition-case nil
16372 (outline-forward-same-level 1)
16373 (error (goto-char end)))))
16374 (when swallowp
16375 (message
16376 "Inserted text not folded because that would swallow text"))
16378 (goto-char end)
16379 (skip-chars-forward " \t\n\r")
16380 (beginning-of-line 1)
16381 (push-mark beg 'nomsg)))
16382 ((and subtreep org-yank-adjusted-subtrees)
16383 (let ((beg (point-at-bol)))
16384 (org-paste-subtree nil nil 'for-yank)
16385 (push-mark beg 'nomsg)))
16387 (call-interactively command))))))
16389 (defun org-yank-folding-would-swallow-text (beg end)
16390 "Would hide-subtree at BEG swallow any text after END?"
16391 (let (level)
16392 (save-excursion
16393 (goto-char beg)
16394 (when (or (looking-at outline-regexp)
16395 (re-search-forward (concat "^" outline-regexp) end t))
16396 (setq level (org-outline-level)))
16397 (goto-char end)
16398 (skip-chars-forward " \t\r\n\v\f")
16399 (if (or (eobp)
16400 (and (bolp) (looking-at org-outline-regexp)
16401 (<= (org-outline-level) level)))
16402 nil ; Nothing would be swallowed
16403 t)))) ; something would swallow
16405 (define-key org-mode-map "\C-y" 'org-yank)
16407 (defun org-invisible-p ()
16408 "Check if point is at a character currently not visible."
16409 ;; Early versions of noutline don't have `outline-invisible-p'.
16410 (if (fboundp 'outline-invisible-p)
16411 (outline-invisible-p)
16412 (get-char-property (point) 'invisible)))
16414 (defun org-invisible-p2 ()
16415 "Check if point is at a character currently not visible."
16416 (save-excursion
16417 (if (and (eolp) (not (bobp))) (backward-char 1))
16418 ;; Early versions of noutline don't have `outline-invisible-p'.
16419 (if (fboundp 'outline-invisible-p)
16420 (outline-invisible-p)
16421 (get-char-property (point) 'invisible))))
16423 (defun org-back-to-heading (&optional invisible-ok)
16424 "Call `outline-back-to-heading', but provide a better error message."
16425 (condition-case nil
16426 (outline-back-to-heading invisible-ok)
16427 (error (error "Before first headline at position %d in buffer %s"
16428 (point) (current-buffer)))))
16430 (defun org-before-first-heading-p ()
16431 "Before first heading?"
16432 (save-excursion
16433 (null (re-search-backward "^\\*+ " nil t))))
16435 (defalias 'org-on-heading-p 'outline-on-heading-p)
16436 (defalias 'org-at-heading-p 'outline-on-heading-p)
16437 (defun org-at-heading-or-item-p ()
16438 (or (org-on-heading-p) (org-at-item-p)))
16440 (defun org-on-target-p ()
16441 (or (org-in-regexp org-radio-target-regexp)
16442 (org-in-regexp org-target-regexp)))
16444 (defun org-up-heading-all (arg)
16445 "Move to the heading line of which the present line is a subheading.
16446 This function considers both visible and invisible heading lines.
16447 With argument, move up ARG levels."
16448 (if (fboundp 'outline-up-heading-all)
16449 (outline-up-heading-all arg) ; emacs 21 version of outline.el
16450 (outline-up-heading arg t))) ; emacs 22 version of outline.el
16452 (defun org-up-heading-safe ()
16453 "Move to the heading line of which the present line is a subheading.
16454 This version will not throw an error. It will return the level of the
16455 headline found, or nil if no higher level is found.
16457 Also, this function will be a lot faster than `outline-up-heading',
16458 because it relies on stars being the outline starters. This can really
16459 make a significant difference in outlines with very many siblings."
16460 (let (start-level re)
16461 (org-back-to-heading t)
16462 (setq start-level (funcall outline-level))
16463 (if (equal start-level 1)
16465 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
16466 (if (re-search-backward re nil t)
16467 (funcall outline-level)))))
16469 (defun org-first-sibling-p ()
16470 "Is this heading the first child of its parents?"
16471 (interactive)
16472 (let ((re (concat "^" outline-regexp))
16473 level l)
16474 (unless (org-at-heading-p t)
16475 (error "Not at a heading"))
16476 (setq level (funcall outline-level))
16477 (save-excursion
16478 (if (not (re-search-backward re nil t))
16480 (setq l (funcall outline-level))
16481 (< l level)))))
16483 (defun org-goto-sibling (&optional previous)
16484 "Goto the next sibling, even if it is invisible.
16485 When PREVIOUS is set, go to the previous sibling instead. Returns t
16486 when a sibling was found. When none is found, return nil and don't
16487 move point."
16488 (let ((fun (if previous 're-search-backward 're-search-forward))
16489 (pos (point))
16490 (re (concat "^" outline-regexp))
16491 level l)
16492 (when (condition-case nil (org-back-to-heading t) (error nil))
16493 (setq level (funcall outline-level))
16494 (catch 'exit
16495 (or previous (forward-char 1))
16496 (while (funcall fun re nil t)
16497 (setq l (funcall outline-level))
16498 (when (< l level) (goto-char pos) (throw 'exit nil))
16499 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
16500 (goto-char pos)
16501 nil))))
16503 (defun org-show-siblings ()
16504 "Show all siblings of the current headline."
16505 (save-excursion
16506 (while (org-goto-sibling) (org-flag-heading nil)))
16507 (save-excursion
16508 (while (org-goto-sibling 'previous)
16509 (org-flag-heading nil))))
16511 (defun org-show-hidden-entry ()
16512 "Show an entry where even the heading is hidden."
16513 (save-excursion
16514 (org-show-entry)))
16516 (defun org-flag-heading (flag &optional entry)
16517 "Flag the current heading. FLAG non-nil means make invisible.
16518 When ENTRY is non-nil, show the entire entry."
16519 (save-excursion
16520 (org-back-to-heading t)
16521 ;; Check if we should show the entire entry
16522 (if entry
16523 (progn
16524 (org-show-entry)
16525 (save-excursion
16526 (and (outline-next-heading)
16527 (org-flag-heading nil))))
16528 (outline-flag-region (max (point-min) (1- (point)))
16529 (save-excursion (outline-end-of-heading) (point))
16530 flag))))
16532 (defun org-get-next-sibling ()
16533 "Move to next heading of the same level, and return point.
16534 If there is no such heading, return nil.
16535 This is like outline-next-sibling, but invisible headings are ok."
16536 (let ((level (funcall outline-level)))
16537 (outline-next-heading)
16538 (while (and (not (eobp)) (> (funcall outline-level) level))
16539 (outline-next-heading))
16540 (if (or (eobp) (< (funcall outline-level) level))
16542 (point))))
16544 (defun org-end-of-subtree (&optional invisible-OK to-heading)
16545 ;; This contains an exact copy of the original function, but it uses
16546 ;; `org-back-to-heading', to make it work also in invisible
16547 ;; trees. And is uses an invisible-OK argument.
16548 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
16549 ;; Furthermore, when used inside Org, finding the end of a large subtree
16550 ;; with many children and grandchildren etc, this can be much faster
16551 ;; than the outline version.
16552 (org-back-to-heading invisible-OK)
16553 (let ((first t)
16554 (level (funcall outline-level)))
16555 (if (and (org-mode-p) (< level 1000))
16556 ;; A true heading (not a plain list item), in Org-mode
16557 ;; This means we can easily find the end by looking
16558 ;; only for the right number of stars. Using a regexp to do
16559 ;; this is so much faster than using a Lisp loop.
16560 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
16561 (forward-char 1)
16562 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
16563 ;; something else, do it the slow way
16564 (while (and (not (eobp))
16565 (or first (> (funcall outline-level) level)))
16566 (setq first nil)
16567 (outline-next-heading)))
16568 (unless to-heading
16569 (if (memq (preceding-char) '(?\n ?\^M))
16570 (progn
16571 ;; Go to end of line before heading
16572 (forward-char -1)
16573 (if (memq (preceding-char) '(?\n ?\^M))
16574 ;; leave blank line before heading
16575 (forward-char -1))))))
16576 (point))
16578 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
16579 "Use Org version in org-mode, for dramatic speed-up."
16580 (if (eq major-mode 'org-mode)
16581 (progn
16582 (org-end-of-subtree nil t)
16583 (backward-char 1))
16584 ad-do-it))
16586 (defun org-forward-same-level (arg &optional invisible-ok)
16587 "Move forward to the arg'th subheading at same level as this one.
16588 Stop at the first and last subheadings of a superior heading."
16589 (interactive "p")
16590 (org-back-to-heading)
16591 (org-on-heading-p)
16592 (let* ((level (- (match-end 0) (match-beginning 0) 1))
16593 (re (format "^\\*\\{1,%d\\} " level))
16595 (forward-char 1)
16596 (while (> arg 0)
16597 (while (and (re-search-forward 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)))
16604 (beginning-of-line 1)))
16606 (defun org-backward-same-level (arg &optional invisible-ok)
16607 "Move backward to the arg'th subheading at same level as this one.
16608 Stop at the first and last subheadings of a superior heading."
16609 (interactive "p")
16610 (org-back-to-heading)
16611 (org-on-heading-p)
16612 (let* ((level (- (match-end 0) (match-beginning 0) 1))
16613 (re (format "^\\*\\{1,%d\\} " level))
16615 (while (> arg 0)
16616 (while (and (re-search-backward re nil 'move)
16617 (setq l (- (match-end 0) (match-beginning 0) 1))
16618 (= l level)
16619 (not invisible-ok)
16620 (org-invisible-p))
16621 (if (< l level) (setq arg 1)))
16622 (setq arg (1- arg)))))
16624 (defun org-show-subtree ()
16625 "Show everything after this heading at deeper levels."
16626 (outline-flag-region
16627 (point)
16628 (save-excursion
16629 (outline-end-of-subtree) (outline-next-heading) (point))
16630 nil))
16632 (defun org-show-entry ()
16633 "Show the body directly following this heading.
16634 Show the heading too, if it is currently invisible."
16635 (interactive)
16636 (save-excursion
16637 (condition-case nil
16638 (progn
16639 (org-back-to-heading t)
16640 (outline-flag-region
16641 (max (point-min) (1- (point)))
16642 (save-excursion
16643 (if (re-search-forward
16644 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
16645 (match-beginning 1)
16646 (point-max)))
16647 nil)
16648 (org-cycle-hide-drawers 'children))
16649 (error nil))))
16651 (defun org-make-options-regexp (kwds &optional extra)
16652 "Make a regular expression for keyword lines."
16653 (concat
16655 "#?[ \t]*\\+\\("
16656 (mapconcat 'regexp-quote kwds "\\|")
16657 (if extra (concat "\\|" extra))
16658 "\\):[ \t]*"
16659 "\\(.*\\)"))
16661 ;; Make isearch reveal the necessary context
16662 (defun org-isearch-end ()
16663 "Reveal context after isearch exits."
16664 (when isearch-success ; only if search was successful
16665 (if (featurep 'xemacs)
16666 ;; Under XEmacs, the hook is run in the correct place,
16667 ;; we directly show the context.
16668 (org-show-context 'isearch)
16669 ;; In Emacs the hook runs *before* restoring the overlays.
16670 ;; So we have to use a one-time post-command-hook to do this.
16671 ;; (Emacs 22 has a special variable, see function `org-mode')
16672 (unless (and (boundp 'isearch-mode-end-hook-quit)
16673 isearch-mode-end-hook-quit)
16674 ;; Only when the isearch was not quitted.
16675 (org-add-hook 'post-command-hook 'org-isearch-post-command
16676 'append 'local)))))
16678 (defun org-isearch-post-command ()
16679 "Remove self from hook, and show context."
16680 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
16681 (org-show-context 'isearch))
16684 ;;;; Integration with and fixes for other packages
16686 ;;; Imenu support
16688 (defvar org-imenu-markers nil
16689 "All markers currently used by Imenu.")
16690 (make-variable-buffer-local 'org-imenu-markers)
16692 (defun org-imenu-new-marker (&optional pos)
16693 "Return a new marker for use by Imenu, and remember the marker."
16694 (let ((m (make-marker)))
16695 (move-marker m (or pos (point)))
16696 (push m org-imenu-markers)
16699 (defun org-imenu-get-tree ()
16700 "Produce the index for Imenu."
16701 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
16702 (setq org-imenu-markers nil)
16703 (let* ((n org-imenu-depth)
16704 (re (concat "^" outline-regexp))
16705 (subs (make-vector (1+ n) nil))
16706 (last-level 0)
16707 m level head)
16708 (save-excursion
16709 (save-restriction
16710 (widen)
16711 (goto-char (point-max))
16712 (while (re-search-backward re nil t)
16713 (setq level (org-reduced-level (funcall outline-level)))
16714 (when (<= level n)
16715 (looking-at org-complex-heading-regexp)
16716 (setq head (org-link-display-format
16717 (org-match-string-no-properties 4))
16718 m (org-imenu-new-marker))
16719 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
16720 (if (>= level last-level)
16721 (push (cons head m) (aref subs level))
16722 (push (cons head (aref subs (1+ level))) (aref subs level))
16723 (loop for i from (1+ level) to n do (aset subs i nil)))
16724 (setq last-level level)))))
16725 (aref subs 1)))
16727 (eval-after-load "imenu"
16728 '(progn
16729 (add-hook 'imenu-after-jump-hook
16730 (lambda ()
16731 (if (eq major-mode 'org-mode)
16732 (org-show-context 'org-goto))))))
16734 (defun org-link-display-format (link)
16735 "Replace a link with either the description, or the link target
16736 if no description is present"
16737 (save-match-data
16738 (if (string-match org-bracket-link-analytic-regexp link)
16739 (replace-match (or (match-string 5 link)
16740 (concat (match-string 1 link)
16741 (match-string 3 link)))
16742 nil nil link)
16743 link)))
16745 ;; Speedbar support
16747 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
16748 "Overlay marking the agenda restriction line in speedbar.")
16749 (org-overlay-put org-speedbar-restriction-lock-overlay
16750 'face 'org-agenda-restriction-lock)
16751 (org-overlay-put org-speedbar-restriction-lock-overlay
16752 'help-echo "Agendas are currently limited to this item.")
16753 (org-detach-overlay org-speedbar-restriction-lock-overlay)
16755 (defun org-speedbar-set-agenda-restriction ()
16756 "Restrict future agenda commands to the location at point in speedbar.
16757 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
16758 (interactive)
16759 (require 'org-agenda)
16760 (let (p m tp np dir txt)
16761 (cond
16762 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16763 'org-imenu t))
16764 (setq m (get-text-property p 'org-imenu-marker))
16765 (save-excursion
16766 (save-restriction
16767 (set-buffer (marker-buffer m))
16768 (goto-char m)
16769 (org-agenda-set-restriction-lock 'subtree))))
16770 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16771 'speedbar-function 'speedbar-find-file))
16772 (setq tp (previous-single-property-change
16773 (1+ p) 'speedbar-function)
16774 np (next-single-property-change
16775 tp 'speedbar-function)
16776 dir (speedbar-line-directory)
16777 txt (buffer-substring-no-properties (or tp (point-min))
16778 (or np (point-max))))
16779 (save-excursion
16780 (save-restriction
16781 (set-buffer (find-file-noselect
16782 (let ((default-directory dir))
16783 (expand-file-name txt))))
16784 (unless (org-mode-p)
16785 (error "Cannot restrict to non-Org-mode file"))
16786 (org-agenda-set-restriction-lock 'file))))
16787 (t (error "Don't know how to restrict Org-mode's agenda")))
16788 (org-move-overlay org-speedbar-restriction-lock-overlay
16789 (point-at-bol) (point-at-eol))
16790 (setq current-prefix-arg nil)
16791 (org-agenda-maybe-redo)))
16793 (eval-after-load "speedbar"
16794 '(progn
16795 (speedbar-add-supported-extension ".org")
16796 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
16797 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
16798 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
16799 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16800 (add-hook 'speedbar-visiting-tag-hook
16801 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
16804 ;;; Fixes and Hacks for problems with other packages
16806 ;; Make flyspell not check words in links, to not mess up our keymap
16807 (defun org-mode-flyspell-verify ()
16808 "Don't let flyspell put overlays at active buttons."
16809 (and (not (get-text-property (point) 'keymap))
16810 (not (get-text-property (point) 'org-no-flyspell))))
16812 (defun org-remove-flyspell-overlays-in (beg end)
16813 "Remove flyspell overlays in region."
16814 (and (org-bound-and-true-p flyspell-mode)
16815 (fboundp 'flyspell-delete-region-overlays)
16816 (flyspell-delete-region-overlays beg end))
16817 (add-text-properties beg end '(org-no-flyspell t)))
16819 ;; Make `bookmark-jump' show the jump location if it was hidden.
16820 (eval-after-load "bookmark"
16821 '(if (boundp 'bookmark-after-jump-hook)
16822 ;; We can use the hook
16823 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
16824 ;; Hook not available, use advice
16825 (defadvice bookmark-jump (after org-make-visible activate)
16826 "Make the position visible."
16827 (org-bookmark-jump-unhide))))
16829 ;; Make sure saveplace show the location if it was hidden
16830 (eval-after-load "saveplace"
16831 '(defadvice save-place-find-file-hook (after org-make-visible activate)
16832 "Make the position visible."
16833 (org-bookmark-jump-unhide)))
16835 (defun org-bookmark-jump-unhide ()
16836 "Unhide the current position, to show the bookmark location."
16837 (and (org-mode-p)
16838 (or (org-invisible-p)
16839 (save-excursion (goto-char (max (point-min) (1- (point))))
16840 (org-invisible-p)))
16841 (org-show-context 'bookmark-jump)))
16843 ;; Make session.el ignore our circular variable
16844 (eval-after-load "session"
16845 '(add-to-list 'session-globals-exclude 'org-mark-ring))
16847 ;;;; Experimental code
16849 (defun org-closed-in-range ()
16850 "Sparse tree of items closed in a certain time range.
16851 Still experimental, may disappear in the future."
16852 (interactive)
16853 ;; Get the time interval from the user.
16854 (let* ((time1 (time-to-seconds
16855 (org-read-date nil 'to-time nil "Starting date: ")))
16856 (time2 (time-to-seconds
16857 (org-read-date nil 'to-time nil "End date:")))
16858 ;; callback function
16859 (callback (lambda ()
16860 (let ((time
16861 (time-to-seconds
16862 (apply 'encode-time
16863 (org-parse-time-string
16864 (match-string 1))))))
16865 ;; check if time in interval
16866 (and (>= time time1) (<= time time2))))))
16867 ;; make tree, check each match with the callback
16868 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
16870 ;;;; Finish up
16872 (provide 'org)
16874 (run-hooks 'org-load-hook)
16876 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
16878 ;;; org.el ends here