Make latex preview also use the packages in `org-export-latex-packages-alist'.
[org-mode.git] / lisp / org.el
blob50cc3eacc27cfd081b88ab23a885f5c863c111bd
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009
4 ;; Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;; Version: 6.29trans
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum)
76 (require 'calendar))
77 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
78 ;; the file noutline.el being loaded.
79 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
80 ;; We require noutline, which might be provided in outline.el
81 (require 'outline) (require 'noutline)
82 ;; Other stuff we need.
83 (require 'time-date)
84 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
85 (require 'easymenu)
87 (require 'org-macs)
88 (require 'org-compat)
89 (require 'org-faces)
90 (require 'org-list)
91 (require 'org-src)
92 (require 'org-footnote)
94 ;;;; Customization variables
96 ;;; Version
98 (defconst org-version "6.29trans"
99 "The version number of the file org.el.")
101 (defun org-version (&optional here)
102 "Show the org-mode version in the echo area.
103 With prefix arg HERE, insert it at point."
104 (interactive "P")
105 (let ((version (format "Org-mode version %s" org-version)))
106 (message version)
107 (if here
108 (insert version))))
110 ;;; Compatibility constants
112 ;;; The custom variables
114 (defgroup org nil
115 "Outline-based notes management and organizer."
116 :tag "Org"
117 :group 'outlines
118 :group 'hypermedia
119 :group 'calendar)
121 (defcustom org-load-hook nil
122 "Hook that is run after org.el has been loaded."
123 :group 'org
124 :type 'hook)
126 (defvar org-modules) ; defined below
127 (defvar org-modules-loaded nil
128 "Have the modules been loaded already?")
130 (defun org-load-modules-maybe (&optional force)
131 "Load all extensions listed in `org-modules'."
132 (when (or force (not org-modules-loaded))
133 (mapc (lambda (ext)
134 (condition-case nil (require ext)
135 (error (message "Problems while trying to load feature `%s'" ext))))
136 org-modules)
137 (setq org-modules-loaded t)))
139 (defun org-set-modules (var value)
140 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
141 (set var value)
142 (when (featurep 'org)
143 (org-load-modules-maybe 'force)))
145 (when (org-bound-and-true-p org-modules)
146 (let ((a (member 'org-infojs org-modules)))
147 (and a (setcar a 'org-jsinfo))))
149 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
150 "Modules that should always be loaded together with org.el.
151 If a description starts with <C>, the file is not part of Emacs
152 and loading it will require that you have downloaded and properly installed
153 the org-mode distribution.
155 You can also use this system to load external packages (i.e. neither Org
156 core modules, not modules from the CONTRIB directory). Just add symbols
157 to the end of the list. If the package is called org-xyz.el, then you need
158 to add the symbol `xyz', and the package must have a call to
160 (provide 'org-xyz)"
161 :group 'org
162 :set 'org-set-modules
163 :type
164 '(set :greedy t
165 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
166 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
167 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
168 (const :tag " id: Global IDs for identifying entries" org-id)
169 (const :tag " info: Links to Info nodes" org-info)
170 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
171 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
172 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
173 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
174 (const :tag " mew Links to Mew folders/messages" org-mew)
175 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
176 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
177 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
178 (const :tag " vm: Links to VM folders/messages" org-vm)
179 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
180 (const :tag " w3m: Special cut/paste from w3m to Org." org-w3m)
181 (const :tag " mouse: Additional mouse support" org-mouse)
183 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
184 (const :tag "C annotation-helper: Call Remember directly from Browser (OBSOLETE, use org-protocol)" org-annotation-helper)
185 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
186 (const :tag "C browser-url: Store link, directly from Browser (OBSOLETE, use org-protocol)" org-browser-url)
187 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
188 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
189 (const :tag "C collector: Collect properties into tables" org-collector)
190 (const :tag "C depend: TODO dependencies for Org-mode (PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
191 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
192 (const :tag "C eval: Include command output as text" org-eval)
193 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
194 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
195 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
196 (const :tag "C interactive-query: Interactive modification of tags query (PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
197 (const :tag "C jira Add a jira:ticket protocol to Org" org-jira)
198 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
199 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
200 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
201 (const :tag "C mtags: Support for muse-like tags" org-mtags)
202 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
203 (const :tag "C R: Computation using the R language" org-R)
204 (const :tag "C registry: A registry for Org links" org-registry)
205 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
206 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
207 (const :tag "C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
208 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
209 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
210 (const :tag "C track: Keep up with Org development" org-track)
211 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
213 (defcustom org-support-shift-select nil
214 "Non-nil means, make shift-cursor commands select text when possible.
216 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
217 selecting a region, or enlarge thusly regions started in this way.
218 In Org-mode, in special contexts, these same keys are used for other
219 purposes, important enough to compete with shift selection. Org tries
220 to balance these needs by supporting `shift-select-mode' outside these
221 special contexts, under control of this variable.
223 The default of this variable is nil, to avoid confusing behavior. Shifted
224 cursor keys will then execute Org commands in the following contexts:
225 - on a headline, changing TODO state (left/right) and priority (up/down)
226 - on a time stamp, changing the time
227 - in a plain list item, changing the bullet type
228 - in a property definition line, switching between allowed values
229 - in the BEGIN line of a clock table (changing the time block).
230 Outside these contexts, the commands will throw an error.
232 When this variable is t and the cursor is not in a special context,
233 Org-mode will support shift-selection for making and enlarging regions.
234 To make this more effective, the bullet cycling will no longer happen
235 anywhere in an item line, but only if the cursor is exactly on the bullet.
237 If you set this variable to the symbol `always', then the keys
238 will not be special in headlines, property lines, and item lines, to make
239 shift selection work there as well. If this is what you want, you can
240 use the following alternative commands: `C-c C-t' and `C-c ,' to
241 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
242 TODO sets, `C-c -' to cycle item bullet types, and properties can be
243 edited by hand or in column view.
245 However, when the cursor is on a timestamp, shift-cursor commands
246 will still edit the time stamp - this is just too good to give up.
248 XEmacs user should have this variable set to nil, because shift-select-mode
249 is Emacs 23 only."
250 :group 'org
251 :type '(choice
252 (const :tag "Never" nil)
253 (const :tag "When outside special context" t)
254 (const :tag "Everywhere except timestamps" always)))
256 (defgroup org-startup nil
257 "Options concerning startup of Org-mode."
258 :tag "Org Startup"
259 :group 'org)
261 (defcustom org-startup-folded t
262 "Non-nil means, entering Org-mode will switch to OVERVIEW.
263 This can also be configured on a per-file basis by adding one of
264 the following lines anywhere in the buffer:
266 #+STARTUP: fold
267 #+STARTUP: nofold
268 #+STARTUP: content"
269 :group 'org-startup
270 :type '(choice
271 (const :tag "nofold: show all" nil)
272 (const :tag "fold: overview" t)
273 (const :tag "content: all headlines" content)))
275 (defcustom org-startup-truncated t
276 "Non-nil means, entering Org-mode will set `truncate-lines'.
277 This is useful since some lines containing links can be very long and
278 uninteresting. Also tables look terrible when wrapped."
279 :group 'org-startup
280 :type 'boolean)
282 (defcustom org-startup-indented nil
283 "Non-nil means, turn on `org-indent-mode' on startup.
284 This can also be configured on a per-file basis by adding one of
285 the following lines anywhere in the buffer:
287 #+STARTUP: indent
288 #+STARTUP: noindent"
289 :group 'org-structure
290 :type '(choice
291 (const :tag "Not" nil)
292 (const :tag "Globally (slow on startup in large files)" t)))
294 (defcustom org-startup-align-all-tables nil
295 "Non-nil means, align all tables when visiting a file.
296 This is useful when the column width in tables is forced with <N> cookies
297 in table fields. Such tables will look correct only after the first re-align.
298 This can also be configured on a per-file basis by adding one of
299 the following lines anywhere in the buffer:
300 #+STARTUP: align
301 #+STARTUP: noalign"
302 :group 'org-startup
303 :type 'boolean)
305 (defcustom org-insert-mode-line-in-empty-file nil
306 "Non-nil means insert the first line setting Org-mode in empty files.
307 When the function `org-mode' is called interactively in an empty file, this
308 normally means that the file name does not automatically trigger Org-mode.
309 To ensure that the file will always be in Org-mode in the future, a
310 line enforcing Org-mode will be inserted into the buffer, if this option
311 has been set."
312 :group 'org-startup
313 :type 'boolean)
315 (defcustom org-replace-disputed-keys nil
316 "Non-nil means use alternative key bindings for some keys.
317 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
318 These keys are also used by other packages like shift-selection-mode'
319 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
320 If you want to use Org-mode together with one of these other modes,
321 or more generally if you would like to move some Org-mode commands to
322 other keys, set this variable and configure the keys with the variable
323 `org-disputed-keys'.
325 This option is only relevant at load-time of Org-mode, and must be set
326 *before* org.el is loaded. Changing it requires a restart of Emacs to
327 become effective."
328 :group 'org-startup
329 :type 'boolean)
331 (defcustom org-use-extra-keys nil
332 "Non-nil means use extra key sequence definitions for certain
333 commands. This happens automatically if you run XEmacs or if
334 window-system is nil. This variable lets you do the same
335 manually. You must set it before loading org.
337 Example: on Carbon Emacs 22 running graphically, with an external
338 keyboard on a Powerbook, the default way of setting M-left might
339 not work for either Alt or ESC. Setting this variable will make
340 it work for ESC."
341 :group 'org-startup
342 :type 'boolean)
344 (if (fboundp 'defvaralias)
345 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
347 (defcustom org-disputed-keys
348 '(([(shift up)] . [(meta p)])
349 ([(shift down)] . [(meta n)])
350 ([(shift left)] . [(meta -)])
351 ([(shift right)] . [(meta +)])
352 ([(control shift right)] . [(meta shift +)])
353 ([(control shift left)] . [(meta shift -)]))
354 "Keys for which Org-mode and other modes compete.
355 This is an alist, cars are the default keys, second element specifies
356 the alternative to use when `org-replace-disputed-keys' is t.
358 Keys can be specified in any syntax supported by `define-key'.
359 The value of this option takes effect only at Org-mode's startup,
360 therefore you'll have to restart Emacs to apply it after changing."
361 :group 'org-startup
362 :type 'alist)
364 (defun org-key (key)
365 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
366 Or return the original if not disputed."
367 (if org-replace-disputed-keys
368 (let* ((nkey (key-description key))
369 (x (org-find-if (lambda (x)
370 (equal (key-description (car x)) nkey))
371 org-disputed-keys)))
372 (if x (cdr x) key))
373 key))
375 (defun org-find-if (predicate seq)
376 (catch 'exit
377 (while seq
378 (if (funcall predicate (car seq))
379 (throw 'exit (car seq))
380 (pop seq)))))
382 (defun org-defkey (keymap key def)
383 "Define a key, possibly translated, as returned by `org-key'."
384 (define-key keymap (org-key key) def))
386 (defcustom org-ellipsis nil
387 "The ellipsis to use in the Org-mode outline.
388 When nil, just use the standard three dots. When a string, use that instead,
389 When a face, use the standard 3 dots, but with the specified face.
390 The change affects only Org-mode (which will then use its own display table).
391 Changing this requires executing `M-x org-mode' in a buffer to become
392 effective."
393 :group 'org-startup
394 :type '(choice (const :tag "Default" nil)
395 (face :tag "Face" :value org-warning)
396 (string :tag "String" :value "...#")))
398 (defvar org-display-table nil
399 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
401 (defgroup org-keywords nil
402 "Keywords in Org-mode."
403 :tag "Org Keywords"
404 :group 'org)
406 (defcustom org-deadline-string "DEADLINE:"
407 "String to mark deadline entries.
408 A deadline is this string, followed by a time stamp. Should be a word,
409 terminated by a colon. You can insert a schedule keyword and
410 a timestamp with \\[org-deadline].
411 Changes become only effective after restarting Emacs."
412 :group 'org-keywords
413 :type 'string)
415 (defcustom org-scheduled-string "SCHEDULED:"
416 "String to mark scheduled TODO entries.
417 A schedule is this string, followed by a time stamp. Should be a word,
418 terminated by a colon. You can insert a schedule keyword and
419 a timestamp with \\[org-schedule].
420 Changes become only effective after restarting Emacs."
421 :group 'org-keywords
422 :type 'string)
424 (defcustom org-closed-string "CLOSED:"
425 "String used as the prefix for timestamps logging closing a TODO entry."
426 :group 'org-keywords
427 :type 'string)
429 (defcustom org-clock-string "CLOCK:"
430 "String used as prefix for timestamps clocking work hours on an item."
431 :group 'org-keywords
432 :type 'string)
434 (defcustom org-comment-string "COMMENT"
435 "Entries starting with this keyword will never be exported.
436 An entry can be toggled between COMMENT and normal with
437 \\[org-toggle-comment].
438 Changes become only effective after restarting Emacs."
439 :group 'org-keywords
440 :type 'string)
442 (defcustom org-quote-string "QUOTE"
443 "Entries starting with this keyword will be exported in fixed-width font.
444 Quoting applies only to the text in the entry following the headline, and does
445 not extend beyond the next headline, even if that is lower level.
446 An entry can be toggled between QUOTE and normal with
447 \\[org-toggle-fixed-width-section]."
448 :group 'org-keywords
449 :type 'string)
451 (defconst org-repeat-re
452 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
453 "Regular expression for specifying repeated events.
454 After a match, group 1 contains the repeat expression.")
456 (defgroup org-structure nil
457 "Options concerning the general structure of Org-mode files."
458 :tag "Org Structure"
459 :group 'org)
461 (defgroup org-reveal-location nil
462 "Options about how to make context of a location visible."
463 :tag "Org Reveal Location"
464 :group 'org-structure)
466 (defconst org-context-choice
467 '(choice
468 (const :tag "Always" t)
469 (const :tag "Never" nil)
470 (repeat :greedy t :tag "Individual contexts"
471 (cons
472 (choice :tag "Context"
473 (const agenda)
474 (const org-goto)
475 (const occur-tree)
476 (const tags-tree)
477 (const link-search)
478 (const mark-goto)
479 (const bookmark-jump)
480 (const isearch)
481 (const default))
482 (boolean))))
483 "Contexts for the reveal options.")
485 (defcustom org-show-hierarchy-above '((default . t))
486 "Non-nil means, show full hierarchy when revealing a location.
487 Org-mode often shows locations in an org-mode file which might have
488 been invisible before. When this is set, the hierarchy of headings
489 above the exposed location is shown.
490 Turning this off for example for sparse trees makes them very compact.
491 Instead of t, this can also be an alist specifying this option for different
492 contexts. Valid contexts are
493 agenda when exposing an entry from the agenda
494 org-goto when using the command `org-goto' on key C-c C-j
495 occur-tree when using the command `org-occur' on key C-c /
496 tags-tree when constructing a sparse tree based on tags matches
497 link-search when exposing search matches associated with a link
498 mark-goto when exposing the jump goal of a mark
499 bookmark-jump when exposing a bookmark location
500 isearch when exiting from an incremental search
501 default default for all contexts not set explicitly"
502 :group 'org-reveal-location
503 :type org-context-choice)
505 (defcustom org-show-following-heading '((default . nil))
506 "Non-nil means, show following heading when revealing a location.
507 Org-mode often shows locations in an org-mode file which might have
508 been invisible before. When this is set, the heading following the
509 match is shown.
510 Turning this off for example for sparse trees makes them very compact,
511 but makes it harder to edit the location of the match. In such a case,
512 use the command \\[org-reveal] to show more context.
513 Instead of t, this can also be an alist specifying this option for different
514 contexts. See `org-show-hierarchy-above' for valid contexts."
515 :group 'org-reveal-location
516 :type org-context-choice)
518 (defcustom org-show-siblings '((default . nil) (isearch t))
519 "Non-nil means, show all sibling heading when revealing a location.
520 Org-mode often shows locations in an org-mode file which might have
521 been invisible before. When this is set, the sibling of the current entry
522 heading are all made visible. If `org-show-hierarchy-above' is t,
523 the same happens on each level of the hierarchy above the current entry.
525 By default this is on for the isearch context, off for all other contexts.
526 Turning this off for example for sparse trees makes them very compact,
527 but makes it harder to edit the location of the match. In such a case,
528 use the command \\[org-reveal] to show more context.
529 Instead of t, this can also be an alist specifying this option for different
530 contexts. See `org-show-hierarchy-above' for valid contexts."
531 :group 'org-reveal-location
532 :type org-context-choice)
534 (defcustom org-show-entry-below '((default . nil))
535 "Non-nil means, show the entry below a headline when revealing a location.
536 Org-mode often shows locations in an org-mode file which might have
537 been invisible before. When this is set, the text below the headline that is
538 exposed is also shown.
540 By default this is off for all contexts.
541 Instead of t, this can also be an alist specifying this option for different
542 contexts. See `org-show-hierarchy-above' for valid contexts."
543 :group 'org-reveal-location
544 :type org-context-choice)
546 (defcustom org-indirect-buffer-display 'other-window
547 "How should indirect tree buffers be displayed?
548 This applies to indirect buffers created with the commands
549 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
550 Valid values are:
551 current-window Display in the current window
552 other-window Just display in another window.
553 dedicated-frame Create one new frame, and re-use it each time.
554 new-frame Make a new frame each time. Note that in this case
555 previously-made indirect buffers are kept, and you need to
556 kill these buffers yourself."
557 :group 'org-structure
558 :group 'org-agenda-windows
559 :type '(choice
560 (const :tag "In current window" current-window)
561 (const :tag "In current frame, other window" other-window)
562 (const :tag "Each time a new frame" new-frame)
563 (const :tag "One dedicated frame" dedicated-frame)))
565 (defgroup org-cycle nil
566 "Options concerning visibility cycling in Org-mode."
567 :tag "Org Cycle"
568 :group 'org-structure)
570 (defcustom org-cycle-skip-children-state-if-no-children t
571 "Non-nil means, skip CHILDREN state in entries that don't have any."
572 :group 'org-cycle
573 :type 'boolean)
575 (defcustom org-cycle-max-level nil
576 "Maximum level which should still be subject to visibility cycling.
577 Levels higher than this will, for cycling, be treated as text, not a headline.
578 When `org-odd-levels-only' is set, a value of N in this variable actually
579 means 2N-1 stars as the limiting headline.
580 When nil, cycle all levels.
581 Note that the limiting level of cycling is also influenced by
582 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
583 `org-inlinetask-min-level' is, cycling will be limited to levels one less
584 than its value."
585 :group 'org-cycle
586 :type '(choice
587 (const :tag "No limit" nil)
588 (integer :tag "Maximum level")))
590 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
591 "Names of drawers. Drawers are not opened by cycling on the headline above.
592 Drawers only open with a TAB on the drawer line itself. A drawer looks like
593 this:
594 :DRAWERNAME:
595 .....
596 :END:
597 The drawer \"PROPERTIES\" is special for capturing properties through
598 the property API.
600 Drawers can be defined on the per-file basis with a line like:
602 #+DRAWERS: HIDDEN STATE PROPERTIES"
603 :group 'org-structure
604 :group 'org-cycle
605 :type '(repeat (string :tag "Drawer Name")))
607 (defcustom org-hide-block-startup nil
608 "Non-nil means, , entering Org-mode will fold all blocks.
609 This can also be set in on a per-file basis with
611 #+STARTUP: hideblocks
612 #+STARTUP: showblocks"
613 :group 'org-startup
614 :group 'org-cycle
615 :type 'boolean)
617 (defcustom org-cycle-global-at-bob nil
618 "Cycle globally if cursor is at beginning of buffer and not at a headline.
619 This makes it possible to do global cycling without having to use S-TAB or
620 C-u TAB. For this special case to work, the first line of the buffer
621 must not be a headline - it may be empty or some other text. When used in
622 this way, `org-cycle-hook' is disables temporarily, to make sure the
623 cursor stays at the beginning of the buffer.
624 When this option is nil, don't do anything special at the beginning
625 of the buffer."
626 :group 'org-cycle
627 :type 'boolean)
629 (defcustom org-cycle-emulate-tab t
630 "Where should `org-cycle' emulate TAB.
631 nil Never
632 white Only in completely white lines
633 whitestart Only at the beginning of lines, before the first non-white char
634 t Everywhere except in headlines
635 exc-hl-bol Everywhere except at the start of a headline
636 If TAB is used in a place where it does not emulate TAB, the current subtree
637 visibility is cycled."
638 :group 'org-cycle
639 :type '(choice (const :tag "Never" nil)
640 (const :tag "Only in completely white lines" white)
641 (const :tag "Before first char in a line" whitestart)
642 (const :tag "Everywhere except in headlines" t)
643 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
646 (defcustom org-cycle-separator-lines 2
647 "Number of empty lines needed to keep an empty line between collapsed trees.
648 If you leave an empty line between the end of a subtree and the following
649 headline, this empty line is hidden when the subtree is folded.
650 Org-mode will leave (exactly) one empty line visible if the number of
651 empty lines is equal or larger to the number given in this variable.
652 So the default 2 means, at least 2 empty lines after the end of a subtree
653 are needed to produce free space between a collapsed subtree and the
654 following headline.
656 Special case: when 0, never leave empty lines in collapsed view."
657 :group 'org-cycle
658 :type 'integer)
659 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
661 (defcustom org-pre-cycle-hook nil
662 "Hook that is run before visibility cycling is happening.
663 The function(s) in this hook must accept a single argument which indicates
664 the new state that will be set right after running this hook. The
665 argument is a symbol. Before a global state change, it can have the values
666 `overview', `content', or `all'. Before a local state change, it can have
667 the values `folded', `children', or `subtree'."
668 :group 'org-cycle
669 :type 'hook)
671 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
672 org-cycle-hide-drawers
673 org-cycle-show-empty-lines
674 org-optimize-window-after-visibility-change)
675 "Hook that is run after `org-cycle' has changed the buffer visibility.
676 The function(s) in this hook must accept a single argument which indicates
677 the new state that was set by the most recent `org-cycle' command. The
678 argument is a symbol. After a global state change, it can have the values
679 `overview', `content', or `all'. After a local state change, it can have
680 the values `folded', `children', or `subtree'."
681 :group 'org-cycle
682 :type 'hook)
684 (defgroup org-edit-structure nil
685 "Options concerning structure editing in Org-mode."
686 :tag "Org Edit Structure"
687 :group 'org-structure)
689 (defcustom org-odd-levels-only nil
690 "Non-nil means, skip even levels and only use odd levels for the outline.
691 This has the effect that two stars are being added/taken away in
692 promotion/demotion commands. It also influences how levels are
693 handled by the exporters.
694 Changing it requires restart of `font-lock-mode' to become effective
695 for fontification also in regions already fontified.
696 You may also set this on a per-file basis by adding one of the following
697 lines to the buffer:
699 #+STARTUP: odd
700 #+STARTUP: oddeven"
701 :group 'org-edit-structure
702 :group 'org-font-lock
703 :type 'boolean)
705 (defcustom org-adapt-indentation t
706 "Non-nil means, adapt indentation to outline node level.
708 When this variable is set, Org assumes that you write outlines by
709 indenting text in each node to align with the headline (after the stars).
710 The following issues are influenced by this variable:
712 - When this is set and the *entire* text in an entry is indented, the
713 indentation is increased by one space in a demotion command, and
714 decreased by one in a promotion command. If any line in the entry
715 body starts with text at column 0, indentation is not changed at all.
717 - Property drawers and planning information is inserted indented when
718 this variable s set. When nil, they will not be indented.
720 - TAB indents a line relative to context. The lines below a headline
721 will be indented when this variable is set.
723 Note that this is all about true indentation, by adding and removing
724 space characters. See also `org-indent.el' which does level-dependent
725 indentation in a virtual way, i.e. at display time in Emacs."
726 :group 'org-edit-structure
727 :type 'boolean)
729 (defcustom org-special-ctrl-a/e nil
730 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
732 When t, `C-a' will bring back the cursor to the beginning of the
733 headline text, i.e. after the stars and after a possible TODO keyword.
734 In an item, this will be the position after the bullet.
735 When the cursor is already at that position, another `C-a' will bring
736 it to the beginning of the line.
738 `C-e' will jump to the end of the headline, ignoring the presence of tags
739 in the headline. A second `C-e' will then jump to the true end of the
740 line, after any tags.
742 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
743 going to the true line boundary first. Only a directly following, identical
744 keypress will bring the cursor to the special positions.
746 This may also be a cons cell where the behavior for `C-a' and `C-e' is
747 set separately."
748 :group 'org-edit-structure
749 :type '(choice
750 (const :tag "off" nil)
751 (const :tag "after stars/bullet and before tags first" t)
752 (const :tag "true line boundary first" reversed)
753 (cons :tag "Set C-a and C-e separately"
754 (choice :tag "Special C-a"
755 (const :tag "off" nil)
756 (const :tag "after stars/bullet first" t)
757 (const :tag "before stars/bullet first" reversed))
758 (choice :tag "Special C-e"
759 (const :tag "off" nil)
760 (const :tag "before tags first" t)
761 (const :tag "after tags first" reversed)))))
762 (if (fboundp 'defvaralias)
763 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
765 (defcustom org-special-ctrl-k nil
766 "Non-nil means `C-k' will behave specially in headlines.
767 When nil, `C-k' will call the default `kill-line' command.
768 When t, the following will happen while the cursor is in the headline:
770 - When the cursor is at the beginning of a headline, kill the entire
771 line and possible the folded subtree below the line.
772 - When in the middle of the headline text, kill the headline up to the tags.
773 - When after the headline text, kill the tags."
774 :group 'org-edit-structure
775 :type 'boolean)
777 (defcustom org-yank-folded-subtrees t
778 "Non-nil means, when yanking subtrees, fold them.
779 If the kill is a single subtree, or a sequence of subtrees, i.e. if
780 it starts with a heading and all other headings in it are either children
781 or siblings, then fold all the subtrees. However, do this only if no
782 text after the yank would be swallowed into a folded tree by this action."
783 :group 'org-edit-structure
784 :type 'boolean)
786 (defcustom org-yank-adjusted-subtrees nil
787 "Non-nil means, when yanking subtrees, adjust the level.
788 With this setting, `org-paste-subtree' is used to insert the subtree, see
789 this function for details."
790 :group 'org-edit-structure
791 :type 'boolean)
793 (defcustom org-M-RET-may-split-line '((default . t))
794 "Non-nil means, M-RET will split the line at the cursor position.
795 When nil, it will go to the end of the line before making a
796 new line.
797 You may also set this option in a different way for different
798 contexts. Valid contexts are:
800 headline when creating a new headline
801 item when creating a new item
802 table in a table field
803 default the value to be used for all contexts not explicitly
804 customized"
805 :group 'org-structure
806 :group 'org-table
807 :type '(choice
808 (const :tag "Always" t)
809 (const :tag "Never" nil)
810 (repeat :greedy t :tag "Individual contexts"
811 (cons
812 (choice :tag "Context"
813 (const headline)
814 (const item)
815 (const table)
816 (const default))
817 (boolean)))))
820 (defcustom org-insert-heading-respect-content nil
821 "Non-nil means, insert new headings after the current subtree.
822 When nil, the new heading is created directly after the current line.
823 The commands \\[org-insert-heading-respect-content] and
824 \\[org-insert-todo-heading-respect-content] turn this variable on
825 for the duration of the command."
826 :group 'org-structure
827 :type 'boolean)
829 (defcustom org-blank-before-new-entry '((heading . auto)
830 (plain-list-item . auto))
831 "Should `org-insert-heading' leave a blank line before new heading/item?
832 The value is an alist, with `heading' and `plain-list-item' as car,
833 and a boolean flag as cdr. For plain lists, if the variable
834 `org-empty-line-terminates-plain-lists' is set, the setting here
835 is ignored and no empty line is inserted, to keep the list in tact."
836 :group 'org-edit-structure
837 :type '(list
838 (cons (const heading)
839 (choice (const :tag "Never" nil)
840 (const :tag "Always" t)
841 (const :tag "Auto" auto)))
842 (cons (const plain-list-item)
843 (choice (const :tag "Never" nil)
844 (const :tag "Always" t)
845 (const :tag "Auto" auto)))))
847 (defcustom org-insert-heading-hook nil
848 "Hook being run after inserting a new heading."
849 :group 'org-edit-structure
850 :type 'hook)
852 (defcustom org-enable-fixed-width-editor t
853 "Non-nil means, lines starting with \":\" are treated as fixed-width.
854 This currently only means, they are never auto-wrapped.
855 When nil, such lines will be treated like ordinary lines.
856 See also the QUOTE keyword."
857 :group 'org-edit-structure
858 :type 'boolean)
861 (defcustom org-goto-auto-isearch t
862 "Non-nil means, typing characters in org-goto starts incremental search."
863 :group 'org-edit-structure
864 :type 'boolean)
866 (defgroup org-sparse-trees nil
867 "Options concerning sparse trees in Org-mode."
868 :tag "Org Sparse Trees"
869 :group 'org-structure)
871 (defcustom org-highlight-sparse-tree-matches t
872 "Non-nil means, highlight all matches that define a sparse tree.
873 The highlights will automatically disappear the next time the buffer is
874 changed by an edit command."
875 :group 'org-sparse-trees
876 :type 'boolean)
878 (defcustom org-remove-highlights-with-change t
879 "Non-nil means, any change to the buffer will remove temporary highlights.
880 Such highlights are created by `org-occur' and `org-clock-display'.
881 When nil, `C-c C-c needs to be used to get rid of the highlights.
882 The highlights created by `org-preview-latex-fragment' always need
883 `C-c C-c' to be removed."
884 :group 'org-sparse-trees
885 :group 'org-time
886 :type 'boolean)
889 (defcustom org-occur-hook '(org-first-headline-recenter)
890 "Hook that is run after `org-occur' has constructed a sparse tree.
891 This can be used to recenter the window to show as much of the structure
892 as possible."
893 :group 'org-sparse-trees
894 :type 'hook)
896 (defgroup org-imenu-and-speedbar nil
897 "Options concerning imenu and speedbar in Org-mode."
898 :tag "Org Imenu and Speedbar"
899 :group 'org-structure)
901 (defcustom org-imenu-depth 2
902 "The maximum level for Imenu access to Org-mode headlines.
903 This also applied for speedbar access."
904 :group 'org-imenu-and-speedbar
905 :type 'integer)
907 (defgroup org-table nil
908 "Options concerning tables in Org-mode."
909 :tag "Org Table"
910 :group 'org)
912 (defcustom org-enable-table-editor 'optimized
913 "Non-nil means, lines starting with \"|\" are handled by the table editor.
914 When nil, such lines will be treated like ordinary lines.
916 When equal to the symbol `optimized', the table editor will be optimized to
917 do the following:
918 - Automatic overwrite mode in front of whitespace in table fields.
919 This makes the structure of the table stay in tact as long as the edited
920 field does not exceed the column width.
921 - Minimize the number of realigns. Normally, the table is aligned each time
922 TAB or RET are pressed to move to another field. With optimization this
923 happens only if changes to a field might have changed the column width.
924 Optimization requires replacing the functions `self-insert-command',
925 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
926 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
927 very good at guessing when a re-align will be necessary, but you can always
928 force one with \\[org-ctrl-c-ctrl-c].
930 If you would like to use the optimized version in Org-mode, but the
931 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
933 This variable can be used to turn on and off the table editor during a session,
934 but in order to toggle optimization, a restart is required.
936 See also the variable `org-table-auto-blank-field'."
937 :group 'org-table
938 :type '(choice
939 (const :tag "off" nil)
940 (const :tag "on" t)
941 (const :tag "on, optimized" optimized)))
943 (defcustom org-self-insert-cluster-for-undo t
944 "Non-nil means cluster self-insert commands for undo when possible.
945 If this is set, then, like in the Emacs command loop, 20 consequtive
946 characters will be undone together.
947 This is configurable, because there is some impact on typing performance."
948 :group 'org-table
949 :type 'boolean)
951 (defcustom org-table-tab-recognizes-table.el t
952 "Non-nil means, TAB will automatically notice a table.el table.
953 When it sees such a table, it moves point into it and - if necessary -
954 calls `table-recognize-table'."
955 :group 'org-table-editing
956 :type 'boolean)
958 (defgroup org-link nil
959 "Options concerning links in Org-mode."
960 :tag "Org Link"
961 :group 'org)
963 (defvar org-link-abbrev-alist-local nil
964 "Buffer-local version of `org-link-abbrev-alist', which see.
965 The value of this is taken from the #+LINK lines.")
966 (make-variable-buffer-local 'org-link-abbrev-alist-local)
968 (defcustom org-link-abbrev-alist nil
969 "Alist of link abbreviations.
970 The car of each element is a string, to be replaced at the start of a link.
971 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
972 links in Org-mode buffers can have an optional tag after a double colon, e.g.
974 [[linkkey:tag][description]]
976 The 'linkkey' must be a word word, starting with a letter, followed
977 by letters, numbers, '-' or '_'.
979 If REPLACE is a string, the tag will simply be appended to create the link.
980 If the string contains \"%s\", the tag will be inserted there. Alternatively,
981 the placeholder \"%h\" will cause a url-encoded version of the tag to
982 be inserted at that point (see the function `url-hexify-string').
984 REPLACE may also be a function that will be called with the tag as the
985 only argument to create the link, which should be returned as a string.
987 See the manual for examples."
988 :group 'org-link
989 :type '(repeat
990 (cons
991 (string :tag "Protocol")
992 (choice
993 (string :tag "Format")
994 (function)))))
996 (defcustom org-descriptive-links t
997 "Non-nil means, hide link part and only show description of bracket links.
998 Bracket links are like [[link][description]]. This variable sets the initial
999 state in new org-mode buffers. The setting can then be toggled on a
1000 per-buffer basis from the Org->Hyperlinks menu."
1001 :group 'org-link
1002 :type 'boolean)
1004 (defcustom org-link-file-path-type 'adaptive
1005 "How the path name in file links should be stored.
1006 Valid values are:
1008 relative Relative to the current directory, i.e. the directory of the file
1009 into which the link is being inserted.
1010 absolute Absolute path, if possible with ~ for home directory.
1011 noabbrev Absolute path, no abbreviation of home directory.
1012 adaptive Use relative path for files in the current directory and sub-
1013 directories of it. For other files, use an absolute path."
1014 :group 'org-link
1015 :type '(choice
1016 (const relative)
1017 (const absolute)
1018 (const noabbrev)
1019 (const adaptive)))
1021 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1022 "Types of links that should be activated in Org-mode files.
1023 This is a list of symbols, each leading to the activation of a certain link
1024 type. In principle, it does not hurt to turn on most link types - there may
1025 be a small gain when turning off unused link types. The types are:
1027 bracket The recommended [[link][description]] or [[link]] links with hiding.
1028 angular Links in angular brackets that may contain whitespace like
1029 <bbdb:Carsten Dominik>.
1030 plain Plain links in normal text, no whitespace, like http://google.com.
1031 radio Text that is matched by a radio target, see manual for details.
1032 tag Tag settings in a headline (link to tag search).
1033 date Time stamps (link to calendar).
1034 footnote Footnote labels.
1036 Changing this variable requires a restart of Emacs to become effective."
1037 :group 'org-link
1038 :type '(set :greedy t
1039 (const :tag "Double bracket links (new style)" bracket)
1040 (const :tag "Angular bracket links (old style)" angular)
1041 (const :tag "Plain text links" plain)
1042 (const :tag "Radio target matches" radio)
1043 (const :tag "Tags" tag)
1044 (const :tag "Timestamps" date)
1045 (const :tag "Footnotes" footnote)))
1047 (defcustom org-make-link-description-function nil
1048 "Function to use to generate link descriptions from links. If
1049 nil the link location will be used. This function must take two
1050 parameters; the first is the link and the second the description
1051 org-insert-link has generated, and should return the description
1052 to use."
1053 :group 'org-link
1054 :type 'function)
1056 (defgroup org-link-store nil
1057 "Options concerning storing links in Org-mode."
1058 :tag "Org Store Link"
1059 :group 'org-link)
1061 (defcustom org-email-link-description-format "Email %c: %.30s"
1062 "Format of the description part of a link to an email or usenet message.
1063 The following %-escapes will be replaced by corresponding information:
1065 %F full \"From\" field
1066 %f name, taken from \"From\" field, address if no name
1067 %T full \"To\" field
1068 %t first name in \"To\" field, address if no name
1069 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1070 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1071 %s subject
1072 %m message-id.
1074 You may use normal field width specification between the % and the letter.
1075 This is for example useful to limit the length of the subject.
1077 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1078 :group 'org-link-store
1079 :type 'string)
1081 (defcustom org-from-is-user-regexp
1082 (let (r1 r2)
1083 (when (and user-mail-address (not (string= user-mail-address "")))
1084 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1085 (when (and user-full-name (not (string= user-full-name "")))
1086 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1087 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1088 "Regexp matched against the \"From:\" header of an email or usenet message.
1089 It should match if the message is from the user him/herself."
1090 :group 'org-link-store
1091 :type 'regexp)
1093 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1094 "Non-nil means, storing a link to an Org file will use entry IDs.
1096 Note that before this variable is even considered, org-id must be loaded,
1097 so please customize `org-modules' and turn it on.
1099 The variable can have the following values:
1101 t Create an ID if needed to make a link to the current entry.
1103 create-if-interactive
1104 If `org-store-link' is called directly (interactively, as a user
1105 command), do create an ID to support the link. But when doing the
1106 job for remember, only use the ID if it already exists. The
1107 purpose of this setting is to avoid proliferation of unwanted
1108 IDs, just because you happen to be in an Org file when you
1109 call `org-remember' that automatically and preemptively
1110 creates a link. If you do want to get an ID link in a remember
1111 template to an entry not having an ID, create it first by
1112 explicitly creating a link to it, using `C-c C-l' first.
1114 create-if-interactive-and-no-custom-id
1115 Like create-if-interactive, but do not create an ID if there is
1116 a CUSTOM_ID property defined in the entry. This is the default.
1118 use-existing
1119 Use existing ID, do not create one.
1121 nil Never use an ID to make a link, instead link using a text search for
1122 the headline text."
1123 :group 'org-link-store
1124 :type '(choice
1125 (const :tag "Create ID to make link" t)
1126 (const :tag "Create if storing link interactively"
1127 create-if-interactive)
1128 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1129 create-if-interactive-and-no-custom-id)
1130 (const :tag "Only use existing" use-existing)
1131 (const :tag "Do not use ID to create link" nil)))
1133 (defcustom org-context-in-file-links t
1134 "Non-nil means, file links from `org-store-link' contain context.
1135 A search string will be added to the file name with :: as separator and
1136 used to find the context when the link is activated by the command
1137 `org-open-at-point'.
1138 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1139 negates this setting for the duration of the command."
1140 :group 'org-link-store
1141 :type 'boolean)
1143 (defcustom org-keep-stored-link-after-insertion nil
1144 "Non-nil means, keep link in list for entire session.
1146 The command `org-store-link' adds a link pointing to the current
1147 location to an internal list. These links accumulate during a session.
1148 The command `org-insert-link' can be used to insert links into any
1149 Org-mode file (offering completion for all stored links). When this
1150 option is nil, every link which has been inserted once using \\[org-insert-link]
1151 will be removed from the list, to make completing the unused links
1152 more efficient."
1153 :group 'org-link-store
1154 :type 'boolean)
1156 (defgroup org-link-follow nil
1157 "Options concerning following links in Org-mode."
1158 :tag "Org Follow Link"
1159 :group 'org-link)
1161 (defcustom org-link-translation-function nil
1162 "Function to translate links with different syntax to Org syntax.
1163 This can be used to translate links created for example by the Planner
1164 or emacs-wiki packages to Org syntax.
1165 The function must accept two parameters, a TYPE containing the link
1166 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1167 which is everything after the link protocol. It should return a cons
1168 with possibly modified values of type and path.
1169 Org contains a function for this, so if you set this variable to
1170 `org-translate-link-from-planner', you should be able follow many
1171 links created by planner."
1172 :group 'org-link-follow
1173 :type 'function)
1175 (defcustom org-follow-link-hook nil
1176 "Hook that is run after a link has been followed."
1177 :group 'org-link-follow
1178 :type 'hook)
1180 (defcustom org-tab-follows-link nil
1181 "Non-nil means, on links TAB will follow the link.
1182 Needs to be set before org.el is loaded.
1183 This really should not be used, it does not make sense, and the
1184 implementation is bad."
1185 :group 'org-link-follow
1186 :type 'boolean)
1188 (defcustom org-return-follows-link nil
1189 "Non-nil means, on links RET will follow the link.
1190 Needs to be set before org.el is loaded."
1191 :group 'org-link-follow
1192 :type 'boolean)
1194 (defcustom org-mouse-1-follows-link
1195 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1196 "Non-nil means, mouse-1 on a link will follow the link.
1197 A longer mouse click will still set point. Does not work on XEmacs.
1198 Needs to be set before org.el is loaded."
1199 :group 'org-link-follow
1200 :type 'boolean)
1202 (defcustom org-mark-ring-length 4
1203 "Number of different positions to be recorded in the ring
1204 Changing this requires a restart of Emacs to work correctly."
1205 :group 'org-link-follow
1206 :type 'integer)
1208 (defcustom org-link-frame-setup
1209 '((vm . vm-visit-folder-other-frame)
1210 (gnus . gnus-other-frame)
1211 (file . find-file-other-window))
1212 "Setup the frame configuration for following links.
1213 When following a link with Emacs, it may often be useful to display
1214 this link in another window or frame. This variable can be used to
1215 set this up for the different types of links.
1216 For VM, use any of
1217 `vm-visit-folder'
1218 `vm-visit-folder-other-frame'
1219 For Gnus, use any of
1220 `gnus'
1221 `gnus-other-frame'
1222 `org-gnus-no-new-news'
1223 For FILE, use any of
1224 `find-file'
1225 `find-file-other-window'
1226 `find-file-other-frame'
1227 For the calendar, use the variable `calendar-setup'.
1228 For BBDB, it is currently only possible to display the matches in
1229 another window."
1230 :group 'org-link-follow
1231 :type '(list
1232 (cons (const vm)
1233 (choice
1234 (const vm-visit-folder)
1235 (const vm-visit-folder-other-window)
1236 (const vm-visit-folder-other-frame)))
1237 (cons (const gnus)
1238 (choice
1239 (const gnus)
1240 (const gnus-other-frame)
1241 (const org-gnus-no-new-news)))
1242 (cons (const file)
1243 (choice
1244 (const find-file)
1245 (const find-file-other-window)
1246 (const find-file-other-frame)))))
1248 (defcustom org-display-internal-link-with-indirect-buffer nil
1249 "Non-nil means, use indirect buffer to display infile links.
1250 Activating internal links (from one location in a file to another location
1251 in the same file) normally just jumps to the location. When the link is
1252 activated with a C-u prefix (or with mouse-3), the link is displayed in
1253 another window. When this option is set, the other window actually displays
1254 an indirect buffer clone of the current buffer, to avoid any visibility
1255 changes to the current buffer."
1256 :group 'org-link-follow
1257 :type 'boolean)
1259 (defcustom org-open-non-existing-files nil
1260 "Non-nil means, `org-open-file' will open non-existing files.
1261 When nil, an error will be generated.
1262 This variable applies only to external applications because they
1263 might choke on non-existing files. If the link is to a file that
1264 will be openend in Emacs, the variable is ignored."
1265 :group 'org-link-follow
1266 :type 'boolean)
1268 (defcustom org-open-directory-means-index-dot-org nil
1269 "Non-nil means, a link to a directory really means to index.org.
1270 When nil, following a directory link will run dired or open a finder/explorer
1271 window on that directory."
1272 :group 'org-link-follow
1273 :type 'boolean)
1275 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1276 "Function and arguments to call for following mailto links.
1277 This is a list with the first element being a lisp function, and the
1278 remaining elements being arguments to the function. In string arguments,
1279 %a will be replaced by the address, and %s will be replaced by the subject
1280 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1281 :group 'org-link-follow
1282 :type '(choice
1283 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1284 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1285 (const :tag "message-mail" (message-mail "%a" "%s"))
1286 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1288 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1289 "Non-nil means, ask for confirmation before executing shell links.
1290 Shell links can be dangerous: just think about a link
1292 [[shell:rm -rf ~/*][Google Search]]
1294 This link would show up in your Org-mode document as \"Google Search\",
1295 but really it would remove your entire home directory.
1296 Therefore we advise against setting this variable to nil.
1297 Just change it to `y-or-n-p' if you want to confirm with a
1298 single keystroke rather than having to type \"yes\"."
1299 :group 'org-link-follow
1300 :type '(choice
1301 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1302 (const :tag "with y-or-n (faster)" y-or-n-p)
1303 (const :tag "no confirmation (dangerous)" nil)))
1305 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1306 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1307 Elisp links can be dangerous: just think about a link
1309 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1311 This link would show up in your Org-mode document as \"Google Search\",
1312 but really it would remove your entire home directory.
1313 Therefore we advise against setting this variable to nil.
1314 Just change it to `y-or-n-p' if you want to confirm with a
1315 single keystroke rather than having to type \"yes\"."
1316 :group 'org-link-follow
1317 :type '(choice
1318 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1319 (const :tag "with y-or-n (faster)" y-or-n-p)
1320 (const :tag "no confirmation (dangerous)" nil)))
1322 (defconst org-file-apps-defaults-gnu
1323 '((remote . emacs)
1324 (system . mailcap)
1325 (t . mailcap))
1326 "Default file applications on a UNIX or GNU/Linux system.
1327 See `org-file-apps'.")
1329 (defconst org-file-apps-defaults-macosx
1330 '((remote . emacs)
1331 (t . "open %s")
1332 (system . "open %s")
1333 ("ps.gz" . "gv %s")
1334 ("eps.gz" . "gv %s")
1335 ("dvi" . "xdvi %s")
1336 ("fig" . "xfig %s"))
1337 "Default file applications on a MacOS X system.
1338 The system \"open\" is known as a default, but we use X11 applications
1339 for some files for which the OS does not have a good default.
1340 See `org-file-apps'.")
1342 (defconst org-file-apps-defaults-windowsnt
1343 (list
1344 '(remote . emacs)
1345 (cons t
1346 (list (if (featurep 'xemacs)
1347 'mswindows-shell-execute
1348 'w32-shell-execute)
1349 "open" 'file))
1350 (cons 'system
1351 (list (if (featurep 'xemacs)
1352 'mswindows-shell-execute
1353 'w32-shell-execute)
1354 "open" 'file)))
1355 "Default file applications on a Windows NT system.
1356 The system \"open\" is used for most files.
1357 See `org-file-apps'.")
1359 (defcustom org-file-apps
1361 (auto-mode . emacs)
1362 ("\\.x?html?\\'" . default)
1363 ("\\.pdf\\'" . default)
1365 "External applications for opening `file:path' items in a document.
1366 Org-mode uses system defaults for different file types, but
1367 you can use this variable to set the application for a given file
1368 extension. The entries in this list are cons cells where the car identifies
1369 files and the cdr the corresponding command. Possible values for the
1370 file identifier are
1371 \"regex\" Regular expression matched against the file name. For backward
1372 compatibility, this can also be a string with only alphanumeric
1373 characters, which is then interpreted as an extension.
1374 `directory' Matches a directory
1375 `remote' Matches a remote file, accessible through tramp or efs.
1376 Remote files most likely should be visited through Emacs
1377 because external applications cannot handle such paths.
1378 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1379 so all files Emacs knows how to handle. Using this with
1380 command `emacs' will open most files in Emacs. Beware that this
1381 will also open html files inside Emacs, unless you add
1382 (\"html\" . default) to the list as well.
1383 t Default for files not matched by any of the other options.
1384 `system' The system command to open files, like `open' on Windows
1385 and Mac OS X, and mailcap under GNU/Linux. This is the command
1386 that will be selected if you call `C-c C-o' with a double
1387 `C-u C-u' prefix.
1389 Possible values for the command are:
1390 `emacs' The file will be visited by the current Emacs process.
1391 `default' Use the default application for this file type, which is the
1392 association for t in the list, most likely in the system-specific
1393 part.
1394 This can be used to overrule an unwanted setting in the
1395 system-specific variable.
1396 `system' Use the system command for opening files, like \"open\".
1397 This command is specified by the entry whose car is `system'.
1398 Most likely, the system-specific version of this variable
1399 does define this command, but you can overrule/replace it
1400 here.
1401 string A command to be executed by a shell; %s will be replaced
1402 by the path to the file.
1403 sexp A Lisp form which will be evaluated. The file path will
1404 be available in the Lisp variable `file'.
1405 For more examples, see the system specific constants
1406 `org-file-apps-defaults-macosx'
1407 `org-file-apps-defaults-windowsnt'
1408 `org-file-apps-defaults-gnu'."
1409 :group 'org-link-follow
1410 :type '(repeat
1411 (cons (choice :value ""
1412 (string :tag "Extension")
1413 (const :tag "System command to open files" system)
1414 (const :tag "Default for unrecognized files" t)
1415 (const :tag "Remote file" remote)
1416 (const :tag "Links to a directory" directory)
1417 (const :tag "Any files that have Emacs modes"
1418 auto-mode))
1419 (choice :value ""
1420 (const :tag "Visit with Emacs" emacs)
1421 (const :tag "Use default" default)
1422 (const :tag "Use the system command" system)
1423 (string :tag "Command")
1424 (sexp :tag "Lisp form")))))
1426 (defgroup org-refile nil
1427 "Options concerning refiling entries in Org-mode."
1428 :tag "Org Refile"
1429 :group 'org)
1431 (defcustom org-directory "~/org"
1432 "Directory with org files.
1433 This is just a default location to look for Org files. There is no need
1434 at all to put your files into this directory. It is only used in the
1435 following situations:
1437 1. When a remember template specifies a target file that is not an
1438 absolute path. The path will then be interpreted relative to
1439 `org-directory'
1440 2. When a remember note is filed away in an interactive way (when exiting the
1441 note buffer with `C-1 C-c C-c'. The the user is prompted for an org file,
1442 with `org-directory' as the default path."
1443 :group 'org-refile
1444 :group 'org-remember
1445 :type 'directory)
1447 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1448 "Default target for storing notes.
1449 Used by the hooks for remember.el. This can be a string, or nil to mean
1450 the value of `remember-data-file'.
1451 You can set this on a per-template basis with the variable
1452 `org-remember-templates'."
1453 :group 'org-refile
1454 :group 'org-remember
1455 :type '(choice
1456 (const :tag "Default from remember-data-file" nil)
1457 file))
1459 (defcustom org-goto-interface 'outline
1460 "The default interface to be used for `org-goto'.
1461 Allowed values are:
1462 outline The interface shows an outline of the relevant file
1463 and the correct heading is found by moving through
1464 the outline or by searching with incremental search.
1465 outline-path-completion Headlines in the current buffer are offered via
1466 completion. This is the interface also used by
1467 the refile command."
1468 :group 'org-refile
1469 :type '(choice
1470 (const :tag "Outline" outline)
1471 (const :tag "Outline-path-completion" outline-path-completion)))
1473 (defcustom org-goto-max-level 5
1474 "Maximum level to be considered when running org-goto with refile interface."
1475 :group 'org-refile
1476 :type 'integer)
1478 (defcustom org-reverse-note-order nil
1479 "Non-nil means, store new notes at the beginning of a file or entry.
1480 When nil, new notes will be filed to the end of a file or entry.
1481 This can also be a list with cons cells of regular expressions that
1482 are matched against file names, and values."
1483 :group 'org-remember
1484 :group 'org-refile
1485 :type '(choice
1486 (const :tag "Reverse always" t)
1487 (const :tag "Reverse never" nil)
1488 (repeat :tag "By file name regexp"
1489 (cons regexp boolean))))
1491 (defcustom org-refile-targets nil
1492 "Targets for refiling entries with \\[org-refile].
1493 This is list of cons cells. Each cell contains:
1494 - a specification of the files to be considered, either a list of files,
1495 or a symbol whose function or variable value will be used to retrieve
1496 a file name or a list of file names. If you use `org-agenda-files' for
1497 that, all agenda files will be scanned for targets. Nil means, consider
1498 headings in the current buffer.
1499 - A specification of how to find candidate refile targets. This may be
1500 any of:
1501 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1502 This tag has to be present in all target headlines, inheritance will
1503 not be considered.
1504 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1505 todo keyword.
1506 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1507 headlines that are refiling targets.
1508 - a cons cell (:level . N). Any headline of level N is considered a target.
1509 Note that, when `org-odd-levels-only' is set, level corresponds to
1510 order in hierarchy, not to the number of stars.
1511 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1512 Note that, when `org-odd-levels-only' is set, level corresponds to
1513 order in hierarchy, not to the number of stars.
1515 You can set the variable `org-refile-target-verify-function' to a function
1516 to verify each headline found by the simple critery above.
1518 When this variable is nil, all top-level headlines in the current buffer
1519 are used, equivalent to the value `((nil . (:level . 1))'."
1520 :group 'org-refile
1521 :type '(repeat
1522 (cons
1523 (choice :value org-agenda-files
1524 (const :tag "All agenda files" org-agenda-files)
1525 (const :tag "Current buffer" nil)
1526 (function) (variable) (file))
1527 (choice :tag "Identify target headline by"
1528 (cons :tag "Specific tag" (const :value :tag) (string))
1529 (cons :tag "TODO keyword" (const :value :todo) (string))
1530 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1531 (cons :tag "Level number" (const :value :level) (integer))
1532 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1534 (defcustom org-refile-target-verify-function nil
1535 "Function to verify if the headline at point should be a refile target.
1536 The function will be called without arguments, with point at the
1537 beginning of the headline. It should return t and leave point
1538 where it is if the headline is a valid target for refiling.
1540 If the target should not be selected, the function must return nil.
1541 In addition to this, it may move point to a place from where the search
1542 should be continued. For example, the function may decide that the entire
1543 subtree of the current entry should be excluded and move point to the end
1544 of the subtree."
1545 :group 'org-refile
1546 :type 'function)
1548 (defcustom org-refile-use-outline-path nil
1549 "Non-nil means, provide refile targets as paths.
1550 So a level 3 headline will be available as level1/level2/level3.
1552 When the value is `file', also include the file name (without directory)
1553 into the path. In this case, you can also stop the completion after
1554 the file name, to get entries inserted as top level in the file.
1556 When `full-file-path', include the full file path."
1557 :group 'org-refile
1558 :type '(choice
1559 (const :tag "Not" nil)
1560 (const :tag "Yes" t)
1561 (const :tag "Start with file name" file)
1562 (const :tag "Start with full file path" full-file-path)))
1564 (defcustom org-outline-path-complete-in-steps t
1565 "Non-nil means, complete the outline path in hierarchical steps.
1566 When Org-mode uses the refile interface to select an outline path
1567 \(see variable `org-refile-use-outline-path'), the completion of
1568 the path can be done is a single go, or if can be done in steps down
1569 the headline hierarchy. Going in steps is probably the best if you
1570 do not use a special completion package like `ido' or `icicles'.
1571 However, when using these packages, going in one step can be very
1572 fast, while still showing the whole path to the entry."
1573 :group 'org-refile
1574 :type 'boolean)
1576 (defcustom org-refile-allow-creating-parent-nodes nil
1577 "Non-nil means, allow to create new nodes as refile targets.
1578 New nodes are then created by adding \"/new node name\" to the completion
1579 of an existing node. When the value of this variable is `confirm',
1580 new node creation must be confirmed by the user (recommended)
1581 When nil, the completion must match an existing entry.
1583 Note that, if the new heading is not seen by the criteria
1584 listed in `org-refile-targets', multiple instances of the same
1585 heading would be created by trying again to file under the new
1586 heading."
1587 :group 'org-refile
1588 :type '(choice
1589 (const :tag "Never" nil)
1590 (const :tag "Always" t)
1591 (const :tag "Prompt for confirmation" confirm)))
1593 (defgroup org-todo nil
1594 "Options concerning TODO items in Org-mode."
1595 :tag "Org TODO"
1596 :group 'org)
1598 (defgroup org-progress nil
1599 "Options concerning Progress logging in Org-mode."
1600 :tag "Org Progress"
1601 :group 'org-time)
1603 (defvar org-todo-interpretation-widgets
1605 (:tag "Sequence (cycling hits every state)" sequence)
1606 (:tag "Type (cycling directly to DONE)" type))
1607 "The available interpretation symbols for customizing
1608 `org-todo-keywords'.
1609 Interested libraries should add to this list.")
1611 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1612 "List of TODO entry keyword sequences and their interpretation.
1613 \\<org-mode-map>This is a list of sequences.
1615 Each sequence starts with a symbol, either `sequence' or `type',
1616 indicating if the keywords should be interpreted as a sequence of
1617 action steps, or as different types of TODO items. The first
1618 keywords are states requiring action - these states will select a headline
1619 for inclusion into the global TODO list Org-mode produces. If one of
1620 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1621 signify that no further action is necessary. If \"|\" is not found,
1622 the last keyword is treated as the only DONE state of the sequence.
1624 The command \\[org-todo] cycles an entry through these states, and one
1625 additional state where no keyword is present. For details about this
1626 cycling, see the manual.
1628 TODO keywords and interpretation can also be set on a per-file basis with
1629 the special #+SEQ_TODO and #+TYP_TODO lines.
1631 Each keyword can optionally specify a character for fast state selection
1632 \(in combination with the variable `org-use-fast-todo-selection')
1633 and specifiers for state change logging, using the same syntax
1634 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1635 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1636 indicates to record a time stamp each time this state is selected.
1638 Each keyword may also specify if a timestamp or a note should be
1639 recorded when entering or leaving the state, by adding additional
1640 characters in the parenthesis after the keyword. This looks like this:
1641 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1642 record only the time of the state change. With X and Y being either
1643 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1644 Y when leaving the state if and only if the *target* state does not
1645 define X. You may omit any of the fast-selection key or X or /Y,
1646 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1648 For backward compatibility, this variable may also be just a list
1649 of keywords - in this case the interpretation (sequence or type) will be
1650 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1651 :group 'org-todo
1652 :group 'org-keywords
1653 :type '(choice
1654 (repeat :tag "Old syntax, just keywords"
1655 (string :tag "Keyword"))
1656 (repeat :tag "New syntax"
1657 (cons
1658 (choice
1659 :tag "Interpretation"
1660 ;;Quick and dirty way to see
1661 ;;`org-todo-interpretations'. This takes the
1662 ;;place of item arguments
1663 :convert-widget
1664 (lambda (widget)
1665 (widget-put widget
1666 :args (mapcar
1667 #'(lambda (x)
1668 (widget-convert
1669 (cons 'const x)))
1670 org-todo-interpretation-widgets))
1671 widget))
1672 (repeat
1673 (string :tag "Keyword"))))))
1675 (defvar org-todo-keywords-1 nil
1676 "All TODO and DONE keywords active in a buffer.")
1677 (make-variable-buffer-local 'org-todo-keywords-1)
1678 (defvar org-todo-keywords-for-agenda nil)
1679 (defvar org-done-keywords-for-agenda nil)
1680 (defvar org-todo-keyword-alist-for-agenda nil)
1681 (defvar org-tag-alist-for-agenda nil)
1682 (defvar org-agenda-contributing-files nil)
1683 (defvar org-not-done-keywords nil)
1684 (make-variable-buffer-local 'org-not-done-keywords)
1685 (defvar org-done-keywords nil)
1686 (make-variable-buffer-local 'org-done-keywords)
1687 (defvar org-todo-heads nil)
1688 (make-variable-buffer-local 'org-todo-heads)
1689 (defvar org-todo-sets nil)
1690 (make-variable-buffer-local 'org-todo-sets)
1691 (defvar org-todo-log-states nil)
1692 (make-variable-buffer-local 'org-todo-log-states)
1693 (defvar org-todo-kwd-alist nil)
1694 (make-variable-buffer-local 'org-todo-kwd-alist)
1695 (defvar org-todo-key-alist nil)
1696 (make-variable-buffer-local 'org-todo-key-alist)
1697 (defvar org-todo-key-trigger nil)
1698 (make-variable-buffer-local 'org-todo-key-trigger)
1700 (defcustom org-todo-interpretation 'sequence
1701 "Controls how TODO keywords are interpreted.
1702 This variable is in principle obsolete and is only used for
1703 backward compatibility, if the interpretation of todo keywords is
1704 not given already in `org-todo-keywords'. See that variable for
1705 more information."
1706 :group 'org-todo
1707 :group 'org-keywords
1708 :type '(choice (const sequence)
1709 (const type)))
1711 (defcustom org-use-fast-todo-selection t
1712 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1713 This variable describes if and under what circumstances the cycling
1714 mechanism for TODO keywords will be replaced by a single-key, direct
1715 selection scheme.
1717 When nil, fast selection is never used.
1719 When the symbol `prefix', it will be used when `org-todo' is called with
1720 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1721 in an agenda buffer.
1723 When t, fast selection is used by default. In this case, the prefix
1724 argument forces cycling instead.
1726 In all cases, the special interface is only used if access keys have actually
1727 been assigned by the user, i.e. if keywords in the configuration are followed
1728 by a letter in parenthesis, like TODO(t)."
1729 :group 'org-todo
1730 :type '(choice
1731 (const :tag "Never" nil)
1732 (const :tag "By default" t)
1733 (const :tag "Only with C-u C-c C-t" prefix)))
1735 (defcustom org-provide-todo-statistics t
1736 "Non-nil means, update todo statistics after insert and toggle.
1737 ALL-HEADLINES means update todo statistics by including headlines
1738 with no TODO keyword as well, counting them as not done.
1739 A list of TODO keywords means the same, but skip keywords that are
1740 not in this list.
1742 When this is set, todo statistics is updated in the parent of the
1743 current entry each time a todo state is changed."
1744 :group 'org-todo
1745 :type '(choice
1746 (const :tag "Yes, only for TODO entries" t)
1747 (const :tag "Yes, including all entries" 'all-headlines)
1748 (repeat :tag "Yes, for TODOs in this list"
1749 (string :tag "TODO keyword"))
1750 (other :tag "No TODO statistics" nil)))
1752 (defcustom org-hierarchical-todo-statistics t
1753 "Non-nil means, TODO statistics covers just direct children.
1754 When nil, all entries in the subtree are considered.
1755 This has only an effect if `org-provide-todo-statistics' is set."
1756 :group 'org-todo
1757 :type 'boolean)
1759 (defcustom org-after-todo-state-change-hook nil
1760 "Hook which is run after the state of a TODO item was changed.
1761 The new state (a string with a TODO keyword, or nil) is available in the
1762 Lisp variable `state'."
1763 :group 'org-todo
1764 :type 'hook)
1766 (defvar org-blocker-hook nil
1767 "Hook for functions that are allowed to block a state change.
1769 Each function gets as its single argument a property list, see
1770 `org-trigger-hook' for more information about this list.
1772 If any of the functions in this hook returns nil, the state change
1773 is blocked.")
1775 (defvar org-trigger-hook nil
1776 "Hook for functions that are triggered by a state change.
1778 Each function gets as its single argument a property list with at least
1779 the following elements:
1781 (:type type-of-change :position pos-at-entry-start
1782 :from old-state :to new-state)
1784 Depending on the type, more properties may be present.
1786 This mechanism is currently implemented for:
1788 TODO state changes
1789 ------------------
1790 :type todo-state-change
1791 :from previous state (keyword as a string), or nil, or a symbol
1792 'todo' or 'done', to indicate the general type of state.
1793 :to new state, like in :from")
1795 (defcustom org-enforce-todo-dependencies nil
1796 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1797 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1798 be blocked if any prior sibling is not yet done.
1799 Finally, if the parent is blocked because of ordered siblings of its own,
1800 the child will also be blocked.
1801 This variable needs to be set before org.el is loaded, and you need to
1802 restart Emacs after a change to make the change effective. The only way
1803 to change is while Emacs is running is through the customize interface."
1804 :set (lambda (var val)
1805 (set var val)
1806 (if val
1807 (add-hook 'org-blocker-hook
1808 'org-block-todo-from-children-or-siblings-or-parent)
1809 (remove-hook 'org-blocker-hook
1810 'org-block-todo-from-children-or-siblings-or-parent)))
1811 :group 'org-todo
1812 :type 'boolean)
1814 (defcustom org-enforce-todo-checkbox-dependencies nil
1815 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1816 When this is nil, checkboxes have no influence on switching TODO states.
1817 When non-nil, you first need to check off all check boxes before the TODO
1818 entry can be switched to DONE.
1819 This variable needs to be set before org.el is loaded, and you need to
1820 restart Emacs after a change to make the change effective. The only way
1821 to change is while Emacs is running is through the customize interface."
1822 :set (lambda (var val)
1823 (set var val)
1824 (if val
1825 (add-hook 'org-blocker-hook
1826 'org-block-todo-from-checkboxes)
1827 (remove-hook 'org-blocker-hook
1828 'org-block-todo-from-checkboxes)))
1829 :group 'org-todo
1830 :type 'boolean)
1832 (defcustom org-treat-insert-todo-heading-as-state-change nil
1833 "Non-nil means, inserting a TODO heading is treated as state change.
1834 So when the command \\[org-insert-todo-heading] is used, state change
1835 logging will apply if appropriate. When nil, the new TODO item will
1836 be inserted directly, and no logging will take place."
1837 :group 'org-todo
1838 :type 'boolean)
1840 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1841 "Non-nil means, switching TODO states with S-cursor counts as state change.
1842 This is the default behavior. However, setting this to nil allows a
1843 convenient way to select a TODO state and bypass any logging associated
1844 with that."
1845 :group 'org-todo
1846 :type 'boolean)
1848 (defcustom org-todo-state-tags-triggers nil
1849 "Tag changes that should be triggered by TODO state changes.
1850 This is a list. Each entry is
1852 (state-change (tag . flag) .......)
1854 State-change can be a string with a state, and empty string to indicate the
1855 state that has no TODO keyword, or it can be one of the symbols `todo'
1856 or `done', meaning any not-done or done state, respectively."
1857 :group 'org-todo
1858 :group 'org-tags
1859 :type '(repeat
1860 (cons (choice :tag "When changing to"
1861 (const :tag "Not-done state" todo)
1862 (const :tag "Done state" done)
1863 (string :tag "State"))
1864 (repeat
1865 (cons :tag "Tag action"
1866 (string :tag "Tag")
1867 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1869 (defcustom org-log-done nil
1870 "Information to record when a task moves to the DONE state.
1872 Possible values are:
1874 nil Don't add anything, just change the keyword
1875 time Add a time stamp to the task
1876 note Prompt a closing note and add it with template `org-log-note-headings'
1878 This option can also be set with on a per-file-basis with
1880 #+STARTUP: nologdone
1881 #+STARTUP: logdone
1882 #+STARTUP: lognotedone
1884 You can have local logging settings for a subtree by setting the LOGGING
1885 property to one or more of these keywords."
1886 :group 'org-todo
1887 :group 'org-progress
1888 :type '(choice
1889 (const :tag "No logging" nil)
1890 (const :tag "Record CLOSED timestamp" time)
1891 (const :tag "Record CLOSED timestamp with closing note." note)))
1893 ;; Normalize old uses of org-log-done.
1894 (cond
1895 ((eq org-log-done t) (setq org-log-done 'time))
1896 ((and (listp org-log-done) (memq 'done org-log-done))
1897 (setq org-log-done 'note)))
1899 (defcustom org-log-note-clock-out nil
1900 "Non-nil means, record a note when clocking out of an item.
1901 This can also be configured on a per-file basis by adding one of
1902 the following lines anywhere in the buffer:
1904 #+STARTUP: lognoteclock-out
1905 #+STARTUP: nolognoteclock-out"
1906 :group 'org-todo
1907 :group 'org-progress
1908 :type 'boolean)
1910 (defcustom org-log-done-with-time t
1911 "Non-nil means, the CLOSED time stamp will contain date and time.
1912 When nil, only the date will be recorded."
1913 :group 'org-progress
1914 :type 'boolean)
1916 (defcustom org-log-note-headings
1917 '((done . "CLOSING NOTE %t")
1918 (state . "State %-12s from %-12S %t")
1919 (note . "Note taken on %t")
1920 (clock-out . ""))
1921 "Headings for notes added to entries.
1922 The value is an alist, with the car being a symbol indicating the note
1923 context, and the cdr is the heading to be used. The heading may also be the
1924 empty string.
1925 %t in the heading will be replaced by a time stamp.
1926 %s will be replaced by the new TODO state, in double quotes.
1927 %S will be replaced by the old TODO state, in double quotes.
1928 %u will be replaced by the user name.
1929 %U will be replaced by the full user name."
1930 :group 'org-todo
1931 :group 'org-progress
1932 :type '(list :greedy t
1933 (cons (const :tag "Heading when closing an item" done) string)
1934 (cons (const :tag
1935 "Heading when changing todo state (todo sequence only)"
1936 state) string)
1937 (cons (const :tag "Heading when just taking a note" note) string)
1938 (cons (const :tag "Heading when clocking out" clock-out) string)))
1940 (unless (assq 'note org-log-note-headings)
1941 (push '(note . "%t") org-log-note-headings))
1943 (defcustom org-log-into-drawer nil
1944 "Non-nil means, insert state change notes and time stamps into a drawer.
1945 When nil, state changes notes will be inserted after the headline and
1946 any scheduling and clock lines, but not inside a drawer.
1948 The value of this variable should be the name of the drawer to use.
1949 LOGBOOK is proposed at the default drawer for this purpose, you can
1950 also set this to a string to define the drawer of your choice.
1952 A value of t is also allowed, representing \"LOGBOOK\".
1954 If this variable is set, `org-log-state-notes-insert-after-drawers'
1955 will be ignored.
1957 You can set the property LOG_INTO_DRAWER to overrule this setting for
1958 a subtree."
1959 :group 'org-todo
1960 :group 'org-progress
1961 :type '(choice
1962 (const :tag "Not into a drawer" nil)
1963 (const :tag "LOGBOOK" t)
1964 (string :tag "Other")))
1966 (if (fboundp 'defvaralias)
1967 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
1969 (defun org-log-into-drawer ()
1970 "Return the value of `org-log-into-drawer', but let properties overrule.
1971 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
1972 used instead of the default value."
1973 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
1974 (cond
1975 ((or (not p) (equal p "nil")) org-log-into-drawer)
1976 ((equal p "t") "LOGBOOK")
1977 (t p))))
1979 (defcustom org-log-state-notes-insert-after-drawers nil
1980 "Non-nil means, insert state change notes after any drawers in entry.
1981 Only the drawers that *immediately* follow the headline and the
1982 deadline/scheduled line are skipped.
1983 When nil, insert notes right after the heading and perhaps the line
1984 with deadline/scheduling if present.
1986 This variable will have no effect if `org-log-into-drawer' is
1987 set."
1988 :group 'org-todo
1989 :group 'org-progress
1990 :type 'boolean)
1992 (defcustom org-log-states-order-reversed t
1993 "Non-nil means, the latest state change note will be directly after heading.
1994 When nil, the notes will be orderer according to time."
1995 :group 'org-todo
1996 :group 'org-progress
1997 :type 'boolean)
1999 (defcustom org-log-repeat 'time
2000 "Non-nil means, record moving through the DONE state when triggering repeat.
2001 An auto-repeating tasks is immediately switched back to TODO when marked
2002 done. If you are not logging state changes (by adding \"@\" or \"!\" to
2003 the TODO keyword definition, or recording a closing note by setting
2004 `org-log-done', there will be no record of the task moving through DONE.
2005 This variable forces taking a note anyway. Possible values are:
2007 nil Don't force a record
2008 time Record a time stamp
2009 note Record a note
2011 This option can also be set with on a per-file-basis with
2013 #+STARTUP: logrepeat
2014 #+STARTUP: lognoterepeat
2015 #+STARTUP: nologrepeat
2017 You can have local logging settings for a subtree by setting the LOGGING
2018 property to one or more of these keywords."
2019 :group 'org-todo
2020 :group 'org-progress
2021 :type '(choice
2022 (const :tag "Don't force a record" nil)
2023 (const :tag "Force recording the DONE state" time)
2024 (const :tag "Force recording a note with the DONE state" note)))
2027 (defgroup org-priorities nil
2028 "Priorities in Org-mode."
2029 :tag "Org Priorities"
2030 :group 'org-todo)
2032 (defcustom org-enable-priority-commands t
2033 "Non-nil means, priority commands are active.
2034 When nil, these commands will be disabled, so that you never accidentally
2035 set a priority."
2036 :group 'org-priorities
2037 :type 'boolean)
2039 (defcustom org-highest-priority ?A
2040 "The highest priority of TODO items. A character like ?A, ?B etc.
2041 Must have a smaller ASCII number than `org-lowest-priority'."
2042 :group 'org-priorities
2043 :type 'character)
2045 (defcustom org-lowest-priority ?C
2046 "The lowest priority of TODO items. A character like ?A, ?B etc.
2047 Must have a larger ASCII number than `org-highest-priority'."
2048 :group 'org-priorities
2049 :type 'character)
2051 (defcustom org-default-priority ?B
2052 "The default priority of TODO items.
2053 This is the priority an item get if no explicit priority is given."
2054 :group 'org-priorities
2055 :type 'character)
2057 (defcustom org-priority-start-cycle-with-default t
2058 "Non-nil means, start with default priority when starting to cycle.
2059 When this is nil, the first step in the cycle will be (depending on the
2060 command used) one higher or lower that the default priority."
2061 :group 'org-priorities
2062 :type 'boolean)
2064 (defgroup org-time nil
2065 "Options concerning time stamps and deadlines in Org-mode."
2066 :tag "Org Time"
2067 :group 'org)
2069 (defcustom org-insert-labeled-timestamps-at-point nil
2070 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
2071 When nil, these labeled time stamps are forces into the second line of an
2072 entry, just after the headline. When scheduling from the global TODO list,
2073 the time stamp will always be forced into the second line."
2074 :group 'org-time
2075 :type 'boolean)
2077 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2078 "Formats for `format-time-string' which are used for time stamps.
2079 It is not recommended to change this constant.")
2081 (defcustom org-time-stamp-rounding-minutes '(0 5)
2082 "Number of minutes to round time stamps to.
2083 These are two values, the first applies when first creating a time stamp.
2084 The second applies when changing it with the commands `S-up' and `S-down'.
2085 When changing the time stamp, this means that it will change in steps
2086 of N minutes, as given by the second value.
2088 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2089 numbers should be factors of 60, so for example 5, 10, 15.
2091 When this is larger than 1, you can still force an exact time-stamp by using
2092 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2093 and by using a prefix arg to `S-up/down' to specify the exact number
2094 of minutes to shift."
2095 :group 'org-time
2096 :get '(lambda (var) ; Make sure all entries have 5 elements
2097 (if (integerp (default-value var))
2098 (list (default-value var) 5)
2099 (default-value var)))
2100 :type '(list
2101 (integer :tag "when inserting times")
2102 (integer :tag "when modifying times")))
2104 ;; Normalize old customizations of this variable.
2105 (when (integerp org-time-stamp-rounding-minutes)
2106 (setq org-time-stamp-rounding-minutes
2107 (list org-time-stamp-rounding-minutes
2108 org-time-stamp-rounding-minutes)))
2110 (defcustom org-display-custom-times nil
2111 "Non-nil means, overlay custom formats over all time stamps.
2112 The formats are defined through the variable `org-time-stamp-custom-formats'.
2113 To turn this on on a per-file basis, insert anywhere in the file:
2114 #+STARTUP: customtime"
2115 :group 'org-time
2116 :set 'set-default
2117 :type 'sexp)
2118 (make-variable-buffer-local 'org-display-custom-times)
2120 (defcustom org-time-stamp-custom-formats
2121 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2122 "Custom formats for time stamps. See `format-time-string' for the syntax.
2123 These are overlayed over the default ISO format if the variable
2124 `org-display-custom-times' is set. Time like %H:%M should be at the
2125 end of the second format. The custom formats are also honored by export
2126 commands, if custom time display is turned on at the time of export."
2127 :group 'org-time
2128 :type 'sexp)
2130 (defun org-time-stamp-format (&optional long inactive)
2131 "Get the right format for a time string."
2132 (let ((f (if long (cdr org-time-stamp-formats)
2133 (car org-time-stamp-formats))))
2134 (if inactive
2135 (concat "[" (substring f 1 -1) "]")
2136 f)))
2138 (defcustom org-time-clocksum-format "%d:%02d"
2139 "The format string used when creating CLOCKSUM lines, or when
2140 org-mode generates a time duration."
2141 :group 'org-time
2142 :type 'string)
2144 (defcustom org-deadline-warning-days 14
2145 "No. of days before expiration during which a deadline becomes active.
2146 This variable governs the display in sparse trees and in the agenda.
2147 When 0 or negative, it means use this number (the absolute value of it)
2148 even if a deadline has a different individual lead time specified.
2150 Custom commands can set this variable in the options section."
2151 :group 'org-time
2152 :group 'org-agenda-daily/weekly
2153 :type 'integer)
2155 (defcustom org-read-date-prefer-future t
2156 "Non-nil means, assume future for incomplete date input from user.
2157 This affects the following situations:
2158 1. The user gives a day, but no month.
2159 For example, if today is the 15th, and you enter \"3\", Org-mode will
2160 read this as the third of *next* month. However, if you enter \"17\",
2161 it will be considered as *this* month.
2162 2. The user gives a month but not a year.
2163 For example, if it is april and you enter \"feb 2\", this will be read
2164 as feb 2, *next* year. \"May 5\", however, will be this year.
2166 Currently this does not work for ISO week specifications.
2168 When this option is nil, the current month and year will always be used
2169 as defaults."
2170 :group 'org-time
2171 :type 'boolean)
2173 (defcustom org-read-date-display-live t
2174 "Non-nil means, display current interpretation of date prompt live.
2175 This display will be in an overlay, in the minibuffer."
2176 :group 'org-time
2177 :type 'boolean)
2179 (defcustom org-read-date-popup-calendar t
2180 "Non-nil means, pop up a calendar when prompting for a date.
2181 In the calendar, the date can be selected with mouse-1. However, the
2182 minibuffer will also be active, and you can simply enter the date as well.
2183 When nil, only the minibuffer will be available."
2184 :group 'org-time
2185 :type 'boolean)
2186 (if (fboundp 'defvaralias)
2187 (defvaralias 'org-popup-calendar-for-date-prompt
2188 'org-read-date-popup-calendar))
2190 (defcustom org-read-date-minibuffer-setup-hook nil
2191 "Hook to be used to set up keys for the date/time interface.
2192 Add key definitions to `minibuffer-local-map', which will be a temporary
2193 copy."
2194 :group 'org-time
2195 :type 'hook)
2197 (defcustom org-extend-today-until 0
2198 "The hour when your day really ends. Must be an integer.
2199 This has influence for the following applications:
2200 - When switching the agenda to \"today\". It it is still earlier than
2201 the time given here, the day recognized as TODAY is actually yesterday.
2202 - When a date is read from the user and it is still before the time given
2203 here, the current date and time will be assumed to be yesterday, 23:59.
2204 Also, timestamps inserted in remember templates follow this rule.
2206 IMPORTANT: This is a feature whose implementation is and likely will
2207 remain incomplete. Really, it is only here because past midnight seems to
2208 be the favorite working time of John Wiegley :-)"
2209 :group 'org-time
2210 :type 'integer)
2212 (defcustom org-edit-timestamp-down-means-later nil
2213 "Non-nil means, S-down will increase the time in a time stamp.
2214 When nil, S-up will increase."
2215 :group 'org-time
2216 :type 'boolean)
2218 (defcustom org-calendar-follow-timestamp-change t
2219 "Non-nil means, make the calendar window follow timestamp changes.
2220 When a timestamp is modified and the calendar window is visible, it will be
2221 moved to the new date."
2222 :group 'org-time
2223 :type 'boolean)
2225 (defgroup org-tags nil
2226 "Options concerning tags in Org-mode."
2227 :tag "Org Tags"
2228 :group 'org)
2230 (defcustom org-tag-alist nil
2231 "List of tags allowed in Org-mode files.
2232 When this list is nil, Org-mode will base TAG input on what is already in the
2233 buffer.
2234 The value of this variable is an alist, the car of each entry must be a
2235 keyword as a string, the cdr may be a character that is used to select
2236 that tag through the fast-tag-selection interface.
2237 See the manual for details."
2238 :group 'org-tags
2239 :type '(repeat
2240 (choice
2241 (cons (string :tag "Tag name")
2242 (character :tag "Access char"))
2243 (const :tag "Start radio group" (:startgroup))
2244 (const :tag "End radio group" (:endgroup))
2245 (const :tag "New line" (:newline)))))
2247 (defcustom org-tag-persistent-alist nil
2248 "List of tags that will always appear in all Org-mode files.
2249 This is in addition to any in buffer settings or customizations
2250 of `org-tag-alist'.
2251 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2252 The value of this variable is an alist, the car of each entry must be a
2253 keyword as a string, the cdr may be a character that is used to select
2254 that tag through the fast-tag-selection interface.
2255 See the manual for details.
2256 To disable these tags on a per-file basis, insert anywhere in the file:
2257 #+STARTUP: noptag"
2258 :group 'org-tags
2259 :type '(repeat
2260 (choice
2261 (cons (string :tag "Tag name")
2262 (character :tag "Access char"))
2263 (const :tag "Start radio group" (:startgroup))
2264 (const :tag "End radio group" (:endgroup))
2265 (const :tag "New line" (:newline)))))
2267 (defvar org-file-tags nil
2268 "List of tags that can be inherited by all entries in the file.
2269 The tags will be inherited if the variable `org-use-tag-inheritance'
2270 says they should be.
2271 This variable is populated from #+TAG lines.")
2273 (defcustom org-use-fast-tag-selection 'auto
2274 "Non-nil means, use fast tag selection scheme.
2275 This is a special interface to select and deselect tags with single keys.
2276 When nil, fast selection is never used.
2277 When the symbol `auto', fast selection is used if and only if selection
2278 characters for tags have been configured, either through the variable
2279 `org-tag-alist' or through a #+TAGS line in the buffer.
2280 When t, fast selection is always used and selection keys are assigned
2281 automatically if necessary."
2282 :group 'org-tags
2283 :type '(choice
2284 (const :tag "Always" t)
2285 (const :tag "Never" nil)
2286 (const :tag "When selection characters are configured" 'auto)))
2288 (defcustom org-fast-tag-selection-single-key nil
2289 "Non-nil means, fast tag selection exits after first change.
2290 When nil, you have to press RET to exit it.
2291 During fast tag selection, you can toggle this flag with `C-c'.
2292 This variable can also have the value `expert'. In this case, the window
2293 displaying the tags menu is not even shown, until you press C-c again."
2294 :group 'org-tags
2295 :type '(choice
2296 (const :tag "No" nil)
2297 (const :tag "Yes" t)
2298 (const :tag "Expert" expert)))
2300 (defvar org-fast-tag-selection-include-todo nil
2301 "Non-nil means, fast tags selection interface will also offer TODO states.
2302 This is an undocumented feature, you should not rely on it.")
2304 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2305 "The column to which tags should be indented in a headline.
2306 If this number is positive, it specifies the column. If it is negative,
2307 it means that the tags should be flushright to that column. For example,
2308 -80 works well for a normal 80 character screen."
2309 :group 'org-tags
2310 :type 'integer)
2312 (defcustom org-auto-align-tags t
2313 "Non-nil means, realign tags after pro/demotion of TODO state change.
2314 These operations change the length of a headline and therefore shift
2315 the tags around. With this options turned on, after each such operation
2316 the tags are again aligned to `org-tags-column'."
2317 :group 'org-tags
2318 :type 'boolean)
2320 (defcustom org-use-tag-inheritance t
2321 "Non-nil means, tags in levels apply also for sublevels.
2322 When nil, only the tags directly given in a specific line apply there.
2323 This may also be a list of tags that should be inherited, or a regexp that
2324 matches tags that should be inherited. Additional control is possible
2325 with the variable `org-tags-exclude-from-inheritance' which gives an
2326 explicit list of tags to be excluded from inheritance., even if the value of
2327 `org-use-tag-inheritance' would select it for inheritance.
2329 If this option is t, a match early-on in a tree can lead to a large
2330 number of matches in the subtree when constructing the agenda or creating
2331 a sparse tree. If you only want to see the first match in a tree during
2332 a search, check out the variable `org-tags-match-list-sublevels'."
2333 :group 'org-tags
2334 :type '(choice
2335 (const :tag "Not" nil)
2336 (const :tag "Always" t)
2337 (repeat :tag "Specific tags" (string :tag "Tag"))
2338 (regexp :tag "Tags matched by regexp")))
2340 (defcustom org-tags-exclude-from-inheritance nil
2341 "List of tags that should never be inherited.
2342 This is a way to exclude a few tags from inheritance. For way to do
2343 the opposite, to actively allow inheritance for selected tags,
2344 see the variable `org-use-tag-inheritance'."
2345 :group 'org-tags
2346 :type '(repeat (string :tag "Tag")))
2348 (defun org-tag-inherit-p (tag)
2349 "Check if TAG is one that should be inherited."
2350 (cond
2351 ((member tag org-tags-exclude-from-inheritance) nil)
2352 ((eq org-use-tag-inheritance t) t)
2353 ((not org-use-tag-inheritance) nil)
2354 ((stringp org-use-tag-inheritance)
2355 (string-match org-use-tag-inheritance tag))
2356 ((listp org-use-tag-inheritance)
2357 (member tag org-use-tag-inheritance))
2358 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2360 (defcustom org-tags-match-list-sublevels t
2361 "Non-nil means list also sublevels of headlines matching a search.
2362 This variable applies to tags/property searches, and also to stuck
2363 projects because this search is based on a tags match as well.
2365 When set to the symbol `indented', sublevels are indented with
2366 leading dots.
2368 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2369 the sublevels of a headline matching a tag search often also match
2370 the same search. Listing all of them can create very long lists.
2371 Setting this variable to nil causes subtrees of a match to be skipped.
2373 This variable is semi-obsolete and probably should always be true. It
2374 is better to limit inheritance to certain tags using the variables
2375 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2376 :group 'org-tags
2377 :type '(choice
2378 (const :tag "No, don't list them" nil)
2379 (const :tag "Yes, do list them" t)
2380 (const :tag "List them, indented with leading dots" indented)))
2382 (defcustom org-tags-sort-function nil
2383 "When set, tags are sorted using this function as a comparator"
2384 :group 'org-tags
2385 :type '(choice
2386 (const :tag "No sorting" nil)
2387 (const :tag "Alphabetical" string<)
2388 (const :tag "Reverse alphabetical" string>)
2389 (function :tag "Custom function" nil)))
2391 (defvar org-tags-history nil
2392 "History of minibuffer reads for tags.")
2393 (defvar org-last-tags-completion-table nil
2394 "The last used completion table for tags.")
2395 (defvar org-after-tags-change-hook nil
2396 "Hook that is run after the tags in a line have changed.")
2398 (defgroup org-properties nil
2399 "Options concerning properties in Org-mode."
2400 :tag "Org Properties"
2401 :group 'org)
2403 (defcustom org-property-format "%-10s %s"
2404 "How property key/value pairs should be formatted by `indent-line'.
2405 When `indent-line' hits a property definition, it will format the line
2406 according to this format, mainly to make sure that the values are
2407 lined-up with respect to each other."
2408 :group 'org-properties
2409 :type 'string)
2411 (defcustom org-use-property-inheritance nil
2412 "Non-nil means, properties apply also for sublevels.
2414 This setting is chiefly used during property searches. Turning it on can
2415 cause significant overhead when doing a search, which is why it is not
2416 on by default.
2418 When nil, only the properties directly given in the current entry count.
2419 When t, every property is inherited. The value may also be a list of
2420 properties that should have inheritance, or a regular expression matching
2421 properties that should be inherited.
2423 However, note that some special properties use inheritance under special
2424 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2425 and the properties ending in \"_ALL\" when they are used as descriptor
2426 for valid values of a property.
2428 Note for programmers:
2429 When querying an entry with `org-entry-get', you can control if inheritance
2430 should be used. By default, `org-entry-get' looks only at the local
2431 properties. You can request inheritance by setting the inherit argument
2432 to t (to force inheritance) or to `selective' (to respect the setting
2433 in this variable)."
2434 :group 'org-properties
2435 :type '(choice
2436 (const :tag "Not" nil)
2437 (const :tag "Always" t)
2438 (repeat :tag "Specific properties" (string :tag "Property"))
2439 (regexp :tag "Properties matched by regexp")))
2441 (defun org-property-inherit-p (property)
2442 "Check if PROPERTY is one that should be inherited."
2443 (cond
2444 ((eq org-use-property-inheritance t) t)
2445 ((not org-use-property-inheritance) nil)
2446 ((stringp org-use-property-inheritance)
2447 (string-match org-use-property-inheritance property))
2448 ((listp org-use-property-inheritance)
2449 (member property org-use-property-inheritance))
2450 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2452 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2453 "The default column format, if no other format has been defined.
2454 This variable can be set on the per-file basis by inserting a line
2456 #+COLUMNS: %25ITEM ....."
2457 :group 'org-properties
2458 :type 'string)
2460 (defcustom org-columns-ellipses ".."
2461 "The ellipses to be used when a field in column view is truncated.
2462 When this is the empty string, as many characters as possible are shown,
2463 but then there will be no visual indication that the field has been truncated.
2464 When this is a string of length N, the last N characters of a truncated
2465 field are replaced by this string. If the column is narrower than the
2466 ellipses string, only part of the ellipses string will be shown."
2467 :group 'org-properties
2468 :type 'string)
2470 (defcustom org-columns-modify-value-for-display-function nil
2471 "Function that modifies values for display in column view.
2472 For example, it can be used to cut out a certain part from a time stamp.
2473 The function must take 2 arguments:
2475 column-title The title of the column (*not* the property name)
2476 value The value that should be modified.
2478 The function should return the value that should be displayed,
2479 or nil if the normal value should be used."
2480 :group 'org-properties
2481 :type 'function)
2483 (defcustom org-effort-property "Effort"
2484 "The property that is being used to keep track of effort estimates.
2485 Effort estimates given in this property need to have the format H:MM."
2486 :group 'org-properties
2487 :group 'org-progress
2488 :type '(string :tag "Property"))
2490 (defconst org-global-properties-fixed
2491 '(("VISIBILITY_ALL" . "folded children content all")
2492 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2493 "List of property/value pairs that can be inherited by any entry.
2495 These are fixed values, for the preset properties. The user variable
2496 that can be used to add to this list is `org-global-properties'.
2498 The entries in this list are cons cells where the car is a property
2499 name and cdr is a string with the value. If the value represents
2500 multiple items like an \"_ALL\" property, separate the items by
2501 spaces.")
2503 (defcustom org-global-properties nil
2504 "List of property/value pairs that can be inherited by any entry.
2506 This list will be combined with the constant `org-global-properties-fixed'.
2508 The entries in this list are cons cells where the car is a property
2509 name and cdr is a string with the value.
2511 You can set buffer-local values for the same purpose in the variable
2512 `org-file-properties' this by adding lines like
2514 #+PROPERTY: NAME VALUE"
2515 :group 'org-properties
2516 :type '(repeat
2517 (cons (string :tag "Property")
2518 (string :tag "Value"))))
2520 (defvar org-file-properties nil
2521 "List of property/value pairs that can be inherited by any entry.
2522 Valid for the current buffer.
2523 This variable is populated from #+PROPERTY lines.")
2524 (make-variable-buffer-local 'org-file-properties)
2526 (defgroup org-agenda nil
2527 "Options concerning agenda views in Org-mode."
2528 :tag "Org Agenda"
2529 :group 'org)
2531 (defvar org-category nil
2532 "Variable used by org files to set a category for agenda display.
2533 Such files should use a file variable to set it, for example
2535 # -*- mode: org; org-category: \"ELisp\"
2537 or contain a special line
2539 #+CATEGORY: ELisp
2541 If the file does not specify a category, then file's base name
2542 is used instead.")
2543 (make-variable-buffer-local 'org-category)
2544 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2546 (defcustom org-agenda-files nil
2547 "The files to be used for agenda display.
2548 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2549 \\[org-remove-file]. You can also use customize to edit the list.
2551 If an entry is a directory, all files in that directory that are matched by
2552 `org-agenda-file-regexp' will be part of the file list.
2554 If the value of the variable is not a list but a single file name, then
2555 the list of agenda files is actually stored and maintained in that file, one
2556 agenda file per line."
2557 :group 'org-agenda
2558 :type '(choice
2559 (repeat :tag "List of files and directories" file)
2560 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2562 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2563 "Regular expression to match files for `org-agenda-files'.
2564 If any element in the list in that variable contains a directory instead
2565 of a normal file, all files in that directory that are matched by this
2566 regular expression will be included."
2567 :group 'org-agenda
2568 :type 'regexp)
2570 (defcustom org-agenda-text-search-extra-files nil
2571 "List of extra files to be searched by text search commands.
2572 These files will be search in addition to the agenda files by the
2573 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2574 Note that these files will only be searched for text search commands,
2575 not for the other agenda views like todo lists, tag searches or the weekly
2576 agenda. This variable is intended to list notes and possibly archive files
2577 that should also be searched by these two commands.
2578 In fact, if the first element in the list is the symbol `agenda-archives',
2579 than all archive files of all agenda files will be added to the search
2580 scope."
2581 :group 'org-agenda
2582 :type '(set :greedy t
2583 (const :tag "Agenda Archives" agenda-archives)
2584 (repeat :inline t (file))))
2586 (if (fboundp 'defvaralias)
2587 (defvaralias 'org-agenda-multi-occur-extra-files
2588 'org-agenda-text-search-extra-files))
2590 (defcustom org-agenda-skip-unavailable-files nil
2591 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2592 A nil value means to remove them, after a query, from the list."
2593 :group 'org-agenda
2594 :type 'boolean)
2596 (defcustom org-calendar-to-agenda-key [?c]
2597 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2598 The command `org-calendar-goto-agenda' will be bound to this key. The
2599 default is the character `c' because then `c' can be used to switch back and
2600 forth between agenda and calendar."
2601 :group 'org-agenda
2602 :type 'sexp)
2604 (defcustom org-calendar-agenda-action-key [?k]
2605 "The key to be installed in `calendar-mode-map' for agenda-action.
2606 The command `org-agenda-action' will be bound to this key. The
2607 default is the character `k' because we use the same key in the agenda."
2608 :group 'org-agenda
2609 :type 'sexp)
2611 (eval-after-load "calendar"
2612 '(progn
2613 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2614 'org-calendar-goto-agenda)
2615 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2616 'org-agenda-action)))
2618 (defgroup org-latex nil
2619 "Options for embedding LaTeX code into Org-mode."
2620 :tag "Org LaTeX"
2621 :group 'org)
2623 (defcustom org-format-latex-options
2624 '(:foreground default :background default :scale 1.0
2625 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2626 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2627 "Options for creating images from LaTeX fragments.
2628 This is a property list with the following properties:
2629 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2630 `default' means use the foreground of the default face.
2631 :background the background color, or \"Transparent\".
2632 `default' means use the background of the default face.
2633 :scale a scaling factor for the size of the images.
2634 :html-foreground, :html-background, :html-scale
2635 the same numbers for HTML export.
2636 :matchers a list indicating which matchers should be used to
2637 find LaTeX fragments. Valid members of this list are:
2638 \"begin\" find environments
2639 \"$1\" find single characters surrounded by $.$
2640 \"$\" find math expressions surrounded by $...$
2641 \"$$\" find math expressions surrounded by $$....$$
2642 \"\\(\" find math expressions surrounded by \\(...\\)
2643 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2644 :group 'org-latex
2645 :type 'plist)
2647 (defcustom org-format-latex-header "\\documentclass{article}
2648 \\usepackage{fullpage} % do not remove
2649 \\usepackage{amssymb}
2650 \\usepackage[usenames]{color}
2651 \\usepackage{amsmath}
2652 \\usepackage{latexsym}
2653 \\usepackage[mathscr]{eucal}
2654 \\pagestyle{empty} % do not remove"
2655 "The document header used for processing LaTeX fragments."
2656 :group 'org-latex
2657 :type 'string)
2660 (defgroup org-font-lock nil
2661 "Font-lock settings for highlighting in Org-mode."
2662 :tag "Org Font Lock"
2663 :group 'org)
2665 (defcustom org-level-color-stars-only nil
2666 "Non-nil means fontify only the stars in each headline.
2667 When nil, the entire headline is fontified.
2668 Changing it requires restart of `font-lock-mode' to become effective
2669 also in regions already fontified."
2670 :group 'org-font-lock
2671 :type 'boolean)
2673 (defcustom org-hide-leading-stars nil
2674 "Non-nil means, hide the first N-1 stars in a headline.
2675 This works by using the face `org-hide' for these stars. This
2676 face is white for a light background, and black for a dark
2677 background. You may have to customize the face `org-hide' to
2678 make this work.
2679 Changing it requires restart of `font-lock-mode' to become effective
2680 also in regions already fontified.
2681 You may also set this on a per-file basis by adding one of the following
2682 lines to the buffer:
2684 #+STARTUP: hidestars
2685 #+STARTUP: showstars"
2686 :group 'org-font-lock
2687 :type 'boolean)
2689 (defcustom org-fontify-done-headline nil
2690 "Non-nil means, change the face of a headline if it is marked DONE.
2691 Normally, only the TODO/DONE keyword indicates the state of a headline.
2692 When this is non-nil, the headline after the keyword is set to the
2693 `org-headline-done' as an additional indication."
2694 :group 'org-font-lock
2695 :type 'boolean)
2697 (defcustom org-fontify-emphasized-text t
2698 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2699 Changing this variable requires a restart of Emacs to take effect."
2700 :group 'org-font-lock
2701 :type 'boolean)
2703 (defcustom org-fontify-whole-heading-line nil
2704 "Non-nil means fontify the whole line for headings.
2705 This is useful when setting a background color for the
2706 org-leve-* faces."
2707 :group 'org-font-lock
2708 :type 'boolean)
2710 (defcustom org-highlight-latex-fragments-and-specials nil
2711 "Non-nil means, fontify what is treated specially by the exporters."
2712 :group 'org-font-lock
2713 :type 'boolean)
2715 (defcustom org-hide-emphasis-markers nil
2716 "Non-nil mean font-lock should hide the emphasis marker characters."
2717 :group 'org-font-lock
2718 :type 'boolean)
2720 (defvar org-emph-re nil
2721 "Regular expression for matching emphasis.")
2722 (defvar org-verbatim-re nil
2723 "Regular expression for matching verbatim text.")
2724 (defvar org-emphasis-regexp-components) ; defined just below
2725 (defvar org-emphasis-alist) ; defined just below
2726 (defun org-set-emph-re (var val)
2727 "Set variable and compute the emphasis regular expression."
2728 (set var val)
2729 (when (and (boundp 'org-emphasis-alist)
2730 (boundp 'org-emphasis-regexp-components)
2731 org-emphasis-alist org-emphasis-regexp-components)
2732 (let* ((e org-emphasis-regexp-components)
2733 (pre (car e))
2734 (post (nth 1 e))
2735 (border (nth 2 e))
2736 (body (nth 3 e))
2737 (nl (nth 4 e))
2738 (body1 (concat body "*?"))
2739 (markers (mapconcat 'car org-emphasis-alist ""))
2740 (vmarkers (mapconcat
2741 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2742 org-emphasis-alist "")))
2743 ;; make sure special characters appear at the right position in the class
2744 (if (string-match "\\^" markers)
2745 (setq markers (concat (replace-match "" t t markers) "^")))
2746 (if (string-match "-" markers)
2747 (setq markers (concat (replace-match "" t t markers) "-")))
2748 (if (string-match "\\^" vmarkers)
2749 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2750 (if (string-match "-" vmarkers)
2751 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2752 (if (> nl 0)
2753 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2754 (int-to-string nl) "\\}")))
2755 ;; Make the regexp
2756 (setq org-emph-re
2757 (concat "\\([" pre "]\\|^\\)"
2758 "\\("
2759 "\\([" markers "]\\)"
2760 "\\("
2761 "[^" border "]\\|"
2762 "[^" border "]"
2763 body1
2764 "[^" border "]"
2765 "\\)"
2766 "\\3\\)"
2767 "\\([" post "]\\|$\\)"))
2768 (setq org-verbatim-re
2769 (concat "\\([" pre "]\\|^\\)"
2770 "\\("
2771 "\\([" vmarkers "]\\)"
2772 "\\("
2773 "[^" border "]\\|"
2774 "[^" border "]"
2775 body1
2776 "[^" border "]"
2777 "\\)"
2778 "\\3\\)"
2779 "\\([" post "]\\|$\\)")))))
2781 (defcustom org-emphasis-regexp-components
2782 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
2783 "Components used to build the regular expression for emphasis.
2784 This is a list with 6 entries. Terminology: In an emphasis string
2785 like \" *strong word* \", we call the initial space PREMATCH, the final
2786 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2787 and \"trong wor\" is the body. The different components in this variable
2788 specify what is allowed/forbidden in each part:
2790 pre Chars allowed as prematch. Beginning of line will be allowed too.
2791 post Chars allowed as postmatch. End of line will be allowed too.
2792 border The chars *forbidden* as border characters.
2793 body-regexp A regexp like \".\" to match a body character. Don't use
2794 non-shy groups here, and don't allow newline here.
2795 newline The maximum number of newlines allowed in an emphasis exp.
2797 Use customize to modify this, or restart Emacs after changing it."
2798 :group 'org-font-lock
2799 :set 'org-set-emph-re
2800 :type '(list
2801 (sexp :tag "Allowed chars in pre ")
2802 (sexp :tag "Allowed chars in post ")
2803 (sexp :tag "Forbidden chars in border ")
2804 (sexp :tag "Regexp for body ")
2805 (integer :tag "number of newlines allowed")
2806 (option (boolean :tag "Please ignore this button"))))
2808 (defcustom org-emphasis-alist
2809 `(("*" bold "<b>" "</b>")
2810 ("/" italic "<i>" "</i>")
2811 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2812 ("=" org-code "<code>" "</code>" verbatim)
2813 ("~" org-verbatim "<code>" "</code>" verbatim)
2814 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2815 "<del>" "</del>")
2817 "Special syntax for emphasized text.
2818 Text starting and ending with a special character will be emphasized, for
2819 example *bold*, _underlined_ and /italic/. This variable sets the marker
2820 characters, the face to be used by font-lock for highlighting in Org-mode
2821 Emacs buffers, and the HTML tags to be used for this.
2822 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
2823 Use customize to modify this, or restart Emacs after changing it."
2824 :group 'org-font-lock
2825 :set 'org-set-emph-re
2826 :type '(repeat
2827 (list
2828 (string :tag "Marker character")
2829 (choice
2830 (face :tag "Font-lock-face")
2831 (plist :tag "Face property list"))
2832 (string :tag "HTML start tag")
2833 (string :tag "HTML end tag")
2834 (option (const verbatim)))))
2836 (defvar org-protecting-blocks
2837 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
2838 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
2839 This is needed for font-lock setup.")
2841 ;;; Miscellaneous options
2843 (defgroup org-completion nil
2844 "Completion in Org-mode."
2845 :tag "Org Completion"
2846 :group 'org)
2848 (defcustom org-completion-use-ido nil
2849 "Non-nil means, use ido completion wherever possible.
2850 Note that `ido-mode' must be active for this variable to be relevant.
2851 If you decide to turn this variable on, you might well want to turn off
2852 `org-outline-path-complete-in-steps'.
2853 See also `org-completion-use-iswitchb'."
2854 :group 'org-completion
2855 :type 'boolean)
2857 (defcustom org-completion-use-iswitchb nil
2858 "Non-nil means, use iswitchb completion wherever possible.
2859 Note that `iswitchb-mode' must be active for this variable to be relevant.
2860 If you decide to turn this variable on, you might well want to turn off
2861 `org-outline-path-complete-in-steps'.
2862 Note that thi variable has only an effect if `org-completion-use-ido' is nil."
2863 :group 'org-completion
2864 :type 'boolean)
2866 (defcustom org-completion-fallback-command 'hippie-expand
2867 "The expansion command called by \\[org-complete] in normal context.
2868 Normal means, no org-mode-specific context."
2869 :group 'org-completion
2870 :type 'function)
2872 ;;; Functions and variables from ther packages
2873 ;; Declared here to avoid compiler warnings
2875 ;; XEmacs only
2876 (defvar outline-mode-menu-heading)
2877 (defvar outline-mode-menu-show)
2878 (defvar outline-mode-menu-hide)
2879 (defvar zmacs-regions) ; XEmacs regions
2881 ;; Emacs only
2882 (defvar mark-active)
2884 ;; Various packages
2885 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2886 (declare-function calendar-forward-day "cal-move" (arg))
2887 (declare-function calendar-goto-date "cal-move" (date))
2888 (declare-function calendar-goto-today "cal-move" ())
2889 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2890 (defvar calc-embedded-close-formula)
2891 (defvar calc-embedded-open-formula)
2892 (declare-function cdlatex-tab "ext:cdlatex" ())
2893 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2894 (defvar font-lock-unfontify-region-function)
2895 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2896 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2897 (defvar iswitchb-temp-buflist)
2898 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2899 (defvar org-agenda-tags-todo-honor-ignore-options)
2900 (declare-function org-agenda-skip "org-agenda" ())
2901 (declare-function org-format-agenda-item "org-agenda"
2902 (extra txt &optional category tags dotime noprefix remove-re))
2903 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2904 (declare-function org-agenda-change-all-lines "org-agenda"
2905 (newhead hdmarker &optional fixface just-this))
2906 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2907 (declare-function org-agenda-maybe-redo "org-agenda" ())
2908 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2909 (beg end))
2910 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2911 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2912 "org-agenda" (&optional end))
2913 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
2914 (declare-function org-indent-mode "org-indent" (arg))
2915 (declare-function parse-time-string "parse-time" (string))
2916 (declare-function remember "remember" (&optional initial))
2917 (declare-function remember-buffer-desc "remember" ())
2918 (declare-function remember-finalize "remember" ())
2919 (defvar remember-save-after-remembering)
2920 (defvar remember-data-file)
2921 (defvar remember-register)
2922 (defvar remember-buffer)
2923 (defvar remember-handler-functions)
2924 (defvar remember-annotation-functions)
2925 (defvar texmathp-why)
2926 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2927 (declare-function table--at-cell-p "table" (position &optional object at-column))
2929 (defvar w3m-current-url)
2930 (defvar w3m-current-title)
2932 (defvar org-latex-regexps)
2934 ;;; Autoload and prepare some org modules
2936 ;; Some table stuff that needs to be defined here, because it is used
2937 ;; by the functions setting up org-mode or checking for table context.
2939 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2940 "Detects an org-type or table-type table.")
2941 (defconst org-table-line-regexp "^[ \t]*|"
2942 "Detects an org-type table line.")
2943 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2944 "Detects an org-type table line.")
2945 (defconst org-table-hline-regexp "^[ \t]*|-"
2946 "Detects an org-type table hline.")
2947 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2948 "Detects a table-type table hline.")
2949 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2950 "Searching from within a table (any type) this finds the first line
2951 outside the table.")
2953 ;; Autoload the functions in org-table.el that are needed by functions here.
2955 (eval-and-compile
2956 (org-autoload "org-table"
2957 '(org-table-align org-table-begin org-table-blank-field
2958 org-table-convert org-table-convert-region org-table-copy-down
2959 org-table-copy-region org-table-create
2960 org-table-create-or-convert-from-region
2961 org-table-create-with-table.el org-table-current-dline
2962 org-table-cut-region org-table-delete-column org-table-edit-field
2963 org-table-edit-formulas org-table-end org-table-eval-formula
2964 org-table-export org-table-field-info
2965 org-table-get-stored-formulas org-table-goto-column
2966 org-table-hline-and-move org-table-import org-table-insert-column
2967 org-table-insert-hline org-table-insert-row org-table-iterate
2968 org-table-justify-field-maybe org-table-kill-row
2969 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2970 org-table-move-column org-table-move-column-left
2971 org-table-move-column-right org-table-move-row
2972 org-table-move-row-down org-table-move-row-up
2973 org-table-next-field org-table-next-row org-table-paste-rectangle
2974 org-table-previous-field org-table-recalculate
2975 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2976 org-table-toggle-coordinate-overlays
2977 org-table-toggle-formula-debugger org-table-wrap-region
2978 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2980 (defun org-at-table-p (&optional table-type)
2981 "Return t if the cursor is inside an org-type table.
2982 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2983 (if org-enable-table-editor
2984 (save-excursion
2985 (beginning-of-line 1)
2986 (looking-at (if table-type org-table-any-line-regexp
2987 org-table-line-regexp)))
2988 nil))
2989 (defsubst org-table-p () (org-at-table-p))
2991 (defun org-at-table.el-p ()
2992 "Return t if and only if we are at a table.el table."
2993 (and (org-at-table-p 'any)
2994 (save-excursion
2995 (goto-char (org-table-begin 'any))
2996 (looking-at org-table1-hline-regexp))))
2997 (defun org-table-recognize-table.el ()
2998 "If there is a table.el table nearby, recognize it and move into it."
2999 (if org-table-tab-recognizes-table.el
3000 (if (org-at-table.el-p)
3001 (progn
3002 (beginning-of-line 1)
3003 (if (looking-at org-table-dataline-regexp)
3005 (if (looking-at org-table1-hline-regexp)
3006 (progn
3007 (beginning-of-line 2)
3008 (if (looking-at org-table-any-border-regexp)
3009 (beginning-of-line -1)))))
3010 (if (re-search-forward "|" (org-table-end t) t)
3011 (progn
3012 (require 'table)
3013 (if (table--at-cell-p (point))
3015 (message "recognizing table.el table...")
3016 (table-recognize-table)
3017 (message "recognizing table.el table...done")))
3018 (error "This should not happen..."))
3020 nil)
3021 nil))
3023 (defun org-at-table-hline-p ()
3024 "Return t if the cursor is inside a hline in a table."
3025 (if org-enable-table-editor
3026 (save-excursion
3027 (beginning-of-line 1)
3028 (looking-at org-table-hline-regexp))
3029 nil))
3031 (defvar org-table-clean-did-remove-column nil)
3033 (defun org-table-map-tables (function)
3034 "Apply FUNCTION to the start of all tables in the buffer."
3035 (save-excursion
3036 (save-restriction
3037 (widen)
3038 (goto-char (point-min))
3039 (while (re-search-forward org-table-any-line-regexp nil t)
3040 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
3041 (beginning-of-line 1)
3042 (when (looking-at org-table-line-regexp)
3043 (save-excursion (funcall function))
3044 (or (looking-at org-table-line-regexp)
3045 (forward-char 1)))
3046 (re-search-forward org-table-any-border-regexp nil 1))))
3047 (message "Mapping tables: done"))
3049 ;; Declare and autoload functions from org-exp.el & Co
3051 (declare-function org-default-export-plist "org-exp")
3052 (declare-function org-infile-export-plist "org-exp")
3053 (declare-function org-get-current-options "org-exp")
3054 (eval-and-compile
3055 (org-autoload "org-exp"
3056 '(org-export org-export-visible
3057 org-insert-export-options-template
3058 org-table-clean-before-export))
3059 (org-autoload "org-ascii"
3060 '(org-export-as-ascii org-export-ascii-preprocess
3061 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3062 org-export-region-as-ascii))
3063 (org-autoload "org-html"
3064 '(org-export-as-html-and-open
3065 org-export-as-html-batch org-export-as-html-to-buffer
3066 org-replace-region-by-html org-export-region-as-html
3067 org-export-as-html))
3068 (org-autoload "org-icalendar"
3069 '(org-export-icalendar-this-file
3070 org-export-icalendar-all-agenda-files
3071 org-export-icalendar-combine-agenda-files))
3072 (org-autoload "org-xoxo" '(org-export-as-xoxo)))
3074 ;; Declare and autoload functions from org-agenda.el
3076 (eval-and-compile
3077 (org-autoload "org-agenda"
3078 '(org-agenda org-agenda-list org-search-view
3079 org-todo-list org-tags-view org-agenda-list-stuck-projects
3080 org-diary org-agenda-to-appt
3081 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3083 ;; Autoload org-remember
3085 (eval-and-compile
3086 (org-autoload "org-remember"
3087 '(org-remember-insinuate org-remember-annotation
3088 org-remember-apply-template org-remember org-remember-handler)))
3090 ;; Autoload org-clock.el
3093 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3094 (beg end))
3095 (declare-function org-clock-update-mode-line "org-clock" ())
3096 (defvar org-clock-start-time)
3097 (defvar org-clock-marker (make-marker)
3098 "Marker recording the last clock-in.")
3099 (defvar org-clock-hd-marker (make-marker)
3100 "Marker recording the last clock-in, but the headline position.")
3101 (defun org-clock-is-active ()
3102 "Return non-nil if clock is currently running.
3103 The return value is actually the clock marker."
3104 (marker-buffer org-clock-marker))
3106 (eval-and-compile
3107 (org-autoload
3108 "org-clock"
3109 '(org-clock-in org-clock-out org-clock-cancel
3110 org-clock-goto org-clock-sum org-clock-display
3111 org-clock-remove-overlays org-clock-report
3112 org-clocktable-shift org-dblock-write:clocktable
3113 org-get-clocktable)))
3115 (defun org-clock-update-time-maybe ()
3116 "If this is a CLOCK line, update it and return t.
3117 Otherwise, return nil."
3118 (interactive)
3119 (save-excursion
3120 (beginning-of-line 1)
3121 (skip-chars-forward " \t")
3122 (when (looking-at org-clock-string)
3123 (let ((re (concat "[ \t]*" org-clock-string
3124 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3125 "\\([ \t]*=>.*\\)?\\)?"))
3126 ts te h m s neg)
3127 (cond
3128 ((not (looking-at re))
3129 nil)
3130 ((not (match-end 2))
3131 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3132 (> org-clock-marker (point))
3133 (<= org-clock-marker (point-at-eol)))
3134 ;; The clock is running here
3135 (setq org-clock-start-time
3136 (apply 'encode-time
3137 (org-parse-time-string (match-string 1))))
3138 (org-clock-update-mode-line)))
3140 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3141 (end-of-line 1)
3142 (setq ts (match-string 1)
3143 te (match-string 3))
3144 (setq s (- (time-to-seconds
3145 (apply 'encode-time (org-parse-time-string te)))
3146 (time-to-seconds
3147 (apply 'encode-time (org-parse-time-string ts))))
3148 neg (< s 0)
3149 s (abs s)
3150 h (floor (/ s 3600))
3151 s (- s (* 3600 h))
3152 m (floor (/ s 60))
3153 s (- s (* 60 s)))
3154 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3155 t))))))
3157 (defun org-check-running-clock ()
3158 "Check if the current buffer contains the running clock.
3159 If yes, offer to stop it and to save the buffer with the changes."
3160 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3161 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3162 (buffer-name))))
3163 (org-clock-out)
3164 (when (y-or-n-p "Save changed buffer?")
3165 (save-buffer))))
3167 (defun org-clocktable-try-shift (dir n)
3168 "Check if this line starts a clock table, if yes, shift the time block."
3169 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3170 (org-clocktable-shift dir n)))
3172 ;; Autoload org-timer.el
3174 (eval-and-compile
3175 (org-autoload
3176 "org-timer"
3177 '(org-timer-start org-timer org-timer-item
3178 org-timer-change-times-in-region
3179 org-timer-set-timer
3180 org-timer-reset-timers
3181 org-timer-show-remaining-time)))
3183 ;; Autoload org-feed.el
3185 (eval-and-compile
3186 (org-autoload
3187 "org-feed"
3188 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3191 ;; Autoload org-indent.el
3193 (eval-and-compile
3194 (org-autoload
3195 "org-indent"
3196 '(org-indent-mode)))
3198 ;; Autoload archiving code
3199 ;; The stuff that is needed for cycling and tags has to be defined here.
3201 (defgroup org-archive nil
3202 "Options concerning archiving in Org-mode."
3203 :tag "Org Archive"
3204 :group 'org-structure)
3206 (defcustom org-archive-location "%s_archive::"
3207 "The location where subtrees should be archived.
3209 The value of this variable is a string, consisting of two parts,
3210 separated by a double-colon. The first part is a filename and
3211 the second part is a headline.
3213 When the filename is omitted, archiving happens in the same file.
3214 %s in the filename will be replaced by the current file
3215 name (without the directory part). Archiving to a different file
3216 is useful to keep archived entries from contributing to the
3217 Org-mode Agenda.
3219 The archived entries will be filed as subtrees of the specified
3220 headline. When the headline is omitted, the subtrees are simply
3221 filed away at the end of the file, as top-level entries. Also in
3222 the heading you can use %s to represent the file name, this can be
3223 useful when using the same archive for a number of different files.
3225 Here are a few examples:
3226 \"%s_archive::\"
3227 If the current file is Projects.org, archive in file
3228 Projects.org_archive, as top-level trees. This is the default.
3230 \"::* Archived Tasks\"
3231 Archive in the current file, under the top-level headline
3232 \"* Archived Tasks\".
3234 \"~/org/archive.org::\"
3235 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3237 \"~/org/archive.org::From %s\"
3238 Archive in file ~/org/archive.org (absolute path), und headlines
3239 \"From FILENAME\" where file name is the current file name.
3241 \"basement::** Finished Tasks\"
3242 Archive in file ./basement (relative path), as level 3 trees
3243 below the level 2 heading \"** Finished Tasks\".
3245 You may set this option on a per-file basis by adding to the buffer a
3246 line like
3248 #+ARCHIVE: basement::** Finished Tasks
3250 You may also define it locally for a subtree by setting an ARCHIVE property
3251 in the entry. If such a property is found in an entry, or anywhere up
3252 the hierarchy, it will be used."
3253 :group 'org-archive
3254 :type 'string)
3256 (defcustom org-archive-tag "ARCHIVE"
3257 "The tag that marks a subtree as archived.
3258 An archived subtree does not open during visibility cycling, and does
3259 not contribute to the agenda listings.
3260 After changing this, font-lock must be restarted in the relevant buffers to
3261 get the proper fontification."
3262 :group 'org-archive
3263 :group 'org-keywords
3264 :type 'string)
3266 (defcustom org-agenda-skip-archived-trees t
3267 "Non-nil means, the agenda will skip any items located in archived trees.
3268 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3269 variable is no longer recommended, you should leave it at the value t.
3270 Instead, use the key `v' to cycle the archives-mode in the agenda."
3271 :group 'org-archive
3272 :group 'org-agenda-skip
3273 :type 'boolean)
3275 (defcustom org-columns-skip-arrchived-trees t
3276 "Non-nil means, irgnore archived trees when creating column view."
3277 :group 'org-archive
3278 :group 'org-properties
3279 :type 'boolean)
3281 (defcustom org-cycle-open-archived-trees nil
3282 "Non-nil means, `org-cycle' will open archived trees.
3283 An archived tree is a tree marked with the tag ARCHIVE.
3284 When nil, archived trees will stay folded. You can still open them with
3285 normal outline commands like `show-all', but not with the cycling commands."
3286 :group 'org-archive
3287 :group 'org-cycle
3288 :type 'boolean)
3290 (defcustom org-sparse-tree-open-archived-trees nil
3291 "Non-nil means sparse tree construction shows matches in archived trees.
3292 When nil, matches in these trees are highlighted, but the trees are kept in
3293 collapsed state."
3294 :group 'org-archive
3295 :group 'org-sparse-trees
3296 :type 'boolean)
3298 (defun org-cycle-hide-archived-subtrees (state)
3299 "Re-hide all archived subtrees after a visibility state change."
3300 (when (and (not org-cycle-open-archived-trees)
3301 (not (memq state '(overview folded))))
3302 (save-excursion
3303 (let* ((globalp (memq state '(contents all)))
3304 (beg (if globalp (point-min) (point)))
3305 (end (if globalp (point-max) (org-end-of-subtree t))))
3306 (org-hide-archived-subtrees beg end)
3307 (goto-char beg)
3308 (if (looking-at (concat ".*:" org-archive-tag ":"))
3309 (message "%s" (substitute-command-keys
3310 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3312 (defun org-force-cycle-archived ()
3313 "Cycle subtree even if it is archived."
3314 (interactive)
3315 (setq this-command 'org-cycle)
3316 (let ((org-cycle-open-archived-trees t))
3317 (call-interactively 'org-cycle)))
3319 (defun org-hide-archived-subtrees (beg end)
3320 "Re-hide all archived subtrees after a visibility state change."
3321 (save-excursion
3322 (let* ((re (concat ":" org-archive-tag ":")))
3323 (goto-char beg)
3324 (while (re-search-forward re end t)
3325 (and (org-on-heading-p) (hide-subtree))
3326 (org-end-of-subtree t)))))
3328 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3330 (eval-and-compile
3331 (org-autoload "org-archive"
3332 '(org-add-archive-files org-archive-subtree
3333 org-archive-to-archive-sibling org-toggle-archive-tag)))
3335 ;; Autoload Column View Code
3337 (declare-function org-columns-number-to-string "org-colview")
3338 (declare-function org-columns-get-format-and-top-level "org-colview")
3339 (declare-function org-columns-compute "org-colview")
3341 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3342 '(org-columns-number-to-string org-columns-get-format-and-top-level
3343 org-columns-compute org-agenda-columns org-columns-remove-overlays
3344 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3346 ;; Autoload ID code
3348 (declare-function org-id-store-link "org-id")
3349 (declare-function org-id-locations-load "org-id")
3350 (declare-function org-id-locations-save "org-id")
3351 (defvar org-id-track-globally)
3352 (org-autoload "org-id"
3353 '(org-id-get-create org-id-new org-id-copy org-id-get
3354 org-id-get-with-outline-path-completion
3355 org-id-get-with-outline-drilling
3356 org-id-goto org-id-find org-id-store-link))
3358 ;; Autoload Plotting Code
3360 (org-autoload "org-plot"
3361 '(org-plot/gnuplot))
3363 ;;; Variables for pre-computed regular expressions, all buffer local
3365 (defvar org-drawer-regexp nil
3366 "Matches first line of a hidden block.")
3367 (make-variable-buffer-local 'org-drawer-regexp)
3368 (defvar org-todo-regexp nil
3369 "Matches any of the TODO state keywords.")
3370 (make-variable-buffer-local 'org-todo-regexp)
3371 (defvar org-not-done-regexp nil
3372 "Matches any of the TODO state keywords except the last one.")
3373 (make-variable-buffer-local 'org-not-done-regexp)
3374 (defvar org-not-done-heading-regexp nil
3375 "Matches a TODO headline that is not done.")
3376 (make-variable-buffer-local 'org-not-done-regexp)
3377 (defvar org-todo-line-regexp nil
3378 "Matches a headline and puts TODO state into group 2 if present.")
3379 (make-variable-buffer-local 'org-todo-line-regexp)
3380 (defvar org-complex-heading-regexp nil
3381 "Matches a headline and puts everything into groups:
3382 group 1: the stars
3383 group 2: The todo keyword, maybe
3384 group 3: Priority cookie
3385 group 4: True headline
3386 group 5: Tags")
3387 (make-variable-buffer-local 'org-complex-heading-regexp)
3388 (defvar org-todo-line-tags-regexp nil
3389 "Matches a headline and puts TODO state into group 2 if present.
3390 Also put tags into group 4 if tags are present.")
3391 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3392 (defvar org-nl-done-regexp nil
3393 "Matches newline followed by a headline with the DONE keyword.")
3394 (make-variable-buffer-local 'org-nl-done-regexp)
3395 (defvar org-looking-at-done-regexp nil
3396 "Matches the DONE keyword a point.")
3397 (make-variable-buffer-local 'org-looking-at-done-regexp)
3398 (defvar org-ds-keyword-length 12
3399 "Maximum length of the Deadline and SCHEDULED keywords.")
3400 (make-variable-buffer-local 'org-ds-keyword-length)
3401 (defvar org-deadline-regexp nil
3402 "Matches the DEADLINE keyword.")
3403 (make-variable-buffer-local 'org-deadline-regexp)
3404 (defvar org-deadline-time-regexp nil
3405 "Matches the DEADLINE keyword together with a time stamp.")
3406 (make-variable-buffer-local 'org-deadline-time-regexp)
3407 (defvar org-deadline-line-regexp nil
3408 "Matches the DEADLINE keyword and the rest of the line.")
3409 (make-variable-buffer-local 'org-deadline-line-regexp)
3410 (defvar org-scheduled-regexp nil
3411 "Matches the SCHEDULED keyword.")
3412 (make-variable-buffer-local 'org-scheduled-regexp)
3413 (defvar org-scheduled-time-regexp nil
3414 "Matches the SCHEDULED keyword together with a time stamp.")
3415 (make-variable-buffer-local 'org-scheduled-time-regexp)
3416 (defvar org-closed-time-regexp nil
3417 "Matches the CLOSED keyword together with a time stamp.")
3418 (make-variable-buffer-local 'org-closed-time-regexp)
3420 (defvar org-keyword-time-regexp nil
3421 "Matches any of the 4 keywords, together with the time stamp.")
3422 (make-variable-buffer-local 'org-keyword-time-regexp)
3423 (defvar org-keyword-time-not-clock-regexp nil
3424 "Matches any of the 3 keywords, together with the time stamp.")
3425 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3426 (defvar org-maybe-keyword-time-regexp nil
3427 "Matches a timestamp, possibly preceeded by a keyword.")
3428 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3429 (defvar org-planning-or-clock-line-re nil
3430 "Matches a line with planning or clock info.")
3431 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3433 (defconst org-plain-time-of-day-regexp
3434 (concat
3435 "\\(\\<[012]?[0-9]"
3436 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3437 "\\(--?"
3438 "\\(\\<[012]?[0-9]"
3439 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3440 "\\)?")
3441 "Regular expression to match a plain time or time range.
3442 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3443 groups carry important information:
3444 0 the full match
3445 1 the first time, range or not
3446 8 the second time, if it is a range.")
3448 (defconst org-plain-time-extension-regexp
3449 (concat
3450 "\\(\\<[012]?[0-9]"
3451 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3452 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3453 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3454 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3455 groups carry important information:
3456 0 the full match
3457 7 hours of duration
3458 9 minutes of duration")
3460 (defconst org-stamp-time-of-day-regexp
3461 (concat
3462 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3463 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3464 "\\(--?"
3465 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3466 "Regular expression to match a timestamp time or time range.
3467 After a match, the following groups carry important information:
3468 0 the full match
3469 1 date plus weekday, for backreferencing to make sure both times on same day
3470 2 the first time, range or not
3471 4 the second time, if it is a range.")
3473 (defconst org-startup-options
3474 '(("fold" org-startup-folded t)
3475 ("overview" org-startup-folded t)
3476 ("nofold" org-startup-folded nil)
3477 ("showall" org-startup-folded nil)
3478 ("content" org-startup-folded content)
3479 ("indent" org-startup-indented t)
3480 ("noindent" org-startup-indented nil)
3481 ("hidestars" org-hide-leading-stars t)
3482 ("showstars" org-hide-leading-stars nil)
3483 ("odd" org-odd-levels-only t)
3484 ("oddeven" org-odd-levels-only nil)
3485 ("align" org-startup-align-all-tables t)
3486 ("noalign" org-startup-align-all-tables nil)
3487 ("customtime" org-display-custom-times t)
3488 ("logdone" org-log-done time)
3489 ("lognotedone" org-log-done note)
3490 ("nologdone" org-log-done nil)
3491 ("lognoteclock-out" org-log-note-clock-out t)
3492 ("nolognoteclock-out" org-log-note-clock-out nil)
3493 ("logrepeat" org-log-repeat state)
3494 ("lognoterepeat" org-log-repeat note)
3495 ("nologrepeat" org-log-repeat nil)
3496 ("fninline" org-footnote-define-inline t)
3497 ("nofninline" org-footnote-define-inline nil)
3498 ("fnlocal" org-footnote-section nil)
3499 ("fnauto" org-footnote-auto-label t)
3500 ("fnprompt" org-footnote-auto-label nil)
3501 ("fnconfirm" org-footnote-auto-label confirm)
3502 ("fnplain" org-footnote-auto-label plain)
3503 ("fnadjust" org-footnote-auto-adjust t)
3504 ("nofnadjust" org-footnote-auto-adjust nil)
3505 ("constcgs" constants-unit-system cgs)
3506 ("constSI" constants-unit-system SI)
3507 ("noptag" org-tag-persistent-alist nil)
3508 ("hideblocks" org-hide-block-startup t)
3509 ("nohideblocks" org-hide-block-startup nil))
3510 "Variable associated with STARTUP options for org-mode.
3511 Each element is a list of three items: The startup options as written
3512 in the #+STARTUP line, the corresponding variable, and the value to
3513 set this variable to if the option is found. An optional forth element PUSH
3514 means to push this value onto the list in the variable.")
3516 (defun org-set-regexps-and-options ()
3517 "Precompute regular expressions for current buffer."
3518 (when (org-mode-p)
3519 (org-set-local 'org-todo-kwd-alist nil)
3520 (org-set-local 'org-todo-key-alist nil)
3521 (org-set-local 'org-todo-key-trigger nil)
3522 (org-set-local 'org-todo-keywords-1 nil)
3523 (org-set-local 'org-done-keywords nil)
3524 (org-set-local 'org-todo-heads nil)
3525 (org-set-local 'org-todo-sets nil)
3526 (org-set-local 'org-todo-log-states nil)
3527 (org-set-local 'org-file-properties nil)
3528 (org-set-local 'org-file-tags nil)
3529 (let ((re (org-make-options-regexp
3530 '("CATEGORY" "TODO" "COLUMNS"
3531 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3532 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3533 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3534 (splitre "[ \t]+")
3535 kwds kws0 kwsa key log value cat arch tags const links hw dws
3536 tail sep kws1 prio props ftags drawers
3537 ext-setup-or-nil setup-contents (start 0))
3538 (save-excursion
3539 (save-restriction
3540 (widen)
3541 (goto-char (point-min))
3542 (while (or (and ext-setup-or-nil
3543 (string-match re ext-setup-or-nil start)
3544 (setq start (match-end 0)))
3545 (and (setq ext-setup-or-nil nil start 0)
3546 (re-search-forward re nil t)))
3547 (setq key (upcase (match-string 1 ext-setup-or-nil))
3548 value (org-match-string-no-properties 2 ext-setup-or-nil))
3549 (cond
3550 ((equal key "CATEGORY")
3551 (if (string-match "[ \t]+$" value)
3552 (setq value (replace-match "" t t value)))
3553 (setq cat value))
3554 ((member key '("SEQ_TODO" "TODO"))
3555 (push (cons 'sequence (org-split-string value splitre)) kwds))
3556 ((equal key "TYP_TODO")
3557 (push (cons 'type (org-split-string value splitre)) kwds))
3558 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3559 ;; general TODO-like setup
3560 (push (cons (intern (downcase (match-string 1 key)))
3561 (org-split-string value splitre)) kwds))
3562 ((equal key "TAGS")
3563 (setq tags (append tags (if tags '("\\n") nil)
3564 (org-split-string value splitre))))
3565 ((equal key "COLUMNS")
3566 (org-set-local 'org-columns-default-format value))
3567 ((equal key "LINK")
3568 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3569 (push (cons (match-string 1 value)
3570 (org-trim (match-string 2 value)))
3571 links)))
3572 ((equal key "PRIORITIES")
3573 (setq prio (org-split-string value " +")))
3574 ((equal key "PROPERTY")
3575 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3576 (push (cons (match-string 1 value) (match-string 2 value))
3577 props)))
3578 ((equal key "FILETAGS")
3579 (when (string-match "\\S-" value)
3580 (setq ftags
3581 (append
3582 ftags
3583 (apply 'append
3584 (mapcar (lambda (x) (org-split-string x ":"))
3585 (org-split-string value)))))))
3586 ((equal key "DRAWERS")
3587 (setq drawers (org-split-string value splitre)))
3588 ((equal key "CONSTANTS")
3589 (setq const (append const (org-split-string value splitre))))
3590 ((equal key "STARTUP")
3591 (let ((opts (org-split-string value splitre))
3592 l var val)
3593 (while (setq l (pop opts))
3594 (when (setq l (assoc l org-startup-options))
3595 (setq var (nth 1 l) val (nth 2 l))
3596 (if (not (nth 3 l))
3597 (set (make-local-variable var) val)
3598 (if (not (listp (symbol-value var)))
3599 (set (make-local-variable var) nil))
3600 (set (make-local-variable var) (symbol-value var))
3601 (add-to-list var val))))))
3602 ((equal key "ARCHIVE")
3603 (string-match " *$" value)
3604 (setq arch (replace-match "" t t value))
3605 (remove-text-properties 0 (length arch)
3606 '(face t fontified t) arch))
3607 ((equal key "SETUPFILE")
3608 (setq setup-contents (org-file-contents
3609 (expand-file-name
3610 (org-remove-double-quotes value))
3611 'noerror))
3612 (if (not ext-setup-or-nil)
3613 (setq ext-setup-or-nil setup-contents start 0)
3614 (setq ext-setup-or-nil
3615 (concat (substring ext-setup-or-nil 0 start)
3616 "\n" setup-contents "\n"
3617 (substring ext-setup-or-nil start)))))
3618 ))))
3619 (when cat
3620 (org-set-local 'org-category (intern cat))
3621 (push (cons "CATEGORY" cat) props))
3622 (when prio
3623 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3624 (setq prio (mapcar 'string-to-char prio))
3625 (org-set-local 'org-highest-priority (nth 0 prio))
3626 (org-set-local 'org-lowest-priority (nth 1 prio))
3627 (org-set-local 'org-default-priority (nth 2 prio)))
3628 (and props (org-set-local 'org-file-properties (nreverse props)))
3629 (and ftags (org-set-local 'org-file-tags
3630 (mapcar 'org-add-prop-inherited ftags)))
3631 (and drawers (org-set-local 'org-drawers drawers))
3632 (and arch (org-set-local 'org-archive-location arch))
3633 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3634 ;; Process the TODO keywords
3635 (unless kwds
3636 ;; Use the global values as if they had been given locally.
3637 (setq kwds (default-value 'org-todo-keywords))
3638 (if (stringp (car kwds))
3639 (setq kwds (list (cons org-todo-interpretation
3640 (default-value 'org-todo-keywords)))))
3641 (setq kwds (reverse kwds)))
3642 (setq kwds (nreverse kwds))
3643 (let (inter kws kw)
3644 (while (setq kws (pop kwds))
3645 (let ((kws (or
3646 (run-hook-with-args-until-success
3647 'org-todo-setup-filter-hook kws)
3648 kws)))
3649 (setq inter (pop kws) sep (member "|" kws)
3650 kws0 (delete "|" (copy-sequence kws))
3651 kwsa nil
3652 kws1 (mapcar
3653 (lambda (x)
3654 ;; 1 2
3655 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3656 (progn
3657 (setq kw (match-string 1 x)
3658 key (and (match-end 2) (match-string 2 x))
3659 log (org-extract-log-state-settings x))
3660 (push (cons kw (and key (string-to-char key))) kwsa)
3661 (and log (push log org-todo-log-states))
3663 (error "Invalid TODO keyword %s" x)))
3664 kws0)
3665 kwsa (if kwsa (append '((:startgroup))
3666 (nreverse kwsa)
3667 '((:endgroup))))
3668 hw (car kws1)
3669 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3670 tail (list inter hw (car dws) (org-last dws))))
3671 (add-to-list 'org-todo-heads hw 'append)
3672 (push kws1 org-todo-sets)
3673 (setq org-done-keywords (append org-done-keywords dws nil))
3674 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3675 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3676 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3677 (setq org-todo-sets (nreverse org-todo-sets)
3678 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3679 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3680 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3681 ;; Process the constants
3682 (when const
3683 (let (e cst)
3684 (while (setq e (pop const))
3685 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3686 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3687 (setq org-table-formula-constants-local cst)))
3689 ;; Process the tags.
3690 (when tags
3691 (let (e tgs)
3692 (while (setq e (pop tags))
3693 (cond
3694 ((equal e "{") (push '(:startgroup) tgs))
3695 ((equal e "}") (push '(:endgroup) tgs))
3696 ((equal e "\\n") (push '(:newline) tgs))
3697 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3698 (push (cons (match-string 1 e)
3699 (string-to-char (match-string 2 e)))
3700 tgs))
3701 (t (push (list e) tgs))))
3702 (org-set-local 'org-tag-alist nil)
3703 (while (setq e (pop tgs))
3704 (or (and (stringp (car e))
3705 (assoc (car e) org-tag-alist))
3706 (push e org-tag-alist)))))
3708 ;; Compute the regular expressions and other local variables
3709 (if (not org-done-keywords)
3710 (setq org-done-keywords (and org-todo-keywords-1
3711 (list (org-last org-todo-keywords-1)))))
3712 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3713 (length org-scheduled-string)
3714 (length org-clock-string)
3715 (length org-closed-string)))
3716 org-drawer-regexp
3717 (concat "^[ \t]*:\\("
3718 (mapconcat 'regexp-quote org-drawers "\\|")
3719 "\\):[ \t]*$")
3720 org-not-done-keywords
3721 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3722 org-todo-regexp
3723 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3724 "\\|") "\\)\\>")
3725 org-not-done-regexp
3726 (concat "\\<\\("
3727 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3728 "\\)\\>")
3729 org-not-done-heading-regexp
3730 (concat "^\\(\\*+\\)[ \t]+\\("
3731 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3732 "\\)\\>")
3733 org-todo-line-regexp
3734 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3735 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3736 "\\)\\>\\)?[ \t]*\\(.*\\)")
3737 org-complex-heading-regexp
3738 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3739 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3740 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3741 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3742 org-nl-done-regexp
3743 (concat "\n\\*+[ \t]+"
3744 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3745 "\\)" "\\>")
3746 org-todo-line-tags-regexp
3747 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3748 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3749 (org-re
3750 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3751 org-looking-at-done-regexp
3752 (concat "^" "\\(?:"
3753 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3754 "\\>")
3755 org-deadline-regexp (concat "\\<" org-deadline-string)
3756 org-deadline-time-regexp
3757 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3758 org-deadline-line-regexp
3759 (concat "\\<\\(" org-deadline-string "\\).*")
3760 org-scheduled-regexp
3761 (concat "\\<" org-scheduled-string)
3762 org-scheduled-time-regexp
3763 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3764 org-closed-time-regexp
3765 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3766 org-keyword-time-regexp
3767 (concat "\\<\\(" org-scheduled-string
3768 "\\|" org-deadline-string
3769 "\\|" org-closed-string
3770 "\\|" org-clock-string "\\)"
3771 " *[[<]\\([^]>]+\\)[]>]")
3772 org-keyword-time-not-clock-regexp
3773 (concat "\\<\\(" org-scheduled-string
3774 "\\|" org-deadline-string
3775 "\\|" org-closed-string
3776 "\\)"
3777 " *[[<]\\([^]>]+\\)[]>]")
3778 org-maybe-keyword-time-regexp
3779 (concat "\\(\\<\\(" org-scheduled-string
3780 "\\|" org-deadline-string
3781 "\\|" org-closed-string
3782 "\\|" org-clock-string "\\)\\)?"
3783 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3784 org-planning-or-clock-line-re
3785 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3786 "\\|" org-deadline-string
3787 "\\|" org-closed-string "\\|" org-clock-string
3788 "\\)\\>\\)")
3790 (org-compute-latex-and-specials-regexp)
3791 (org-set-font-lock-defaults))))
3793 (defun org-file-contents (file &optional noerror)
3794 "Return the contents of FILE, as a string."
3795 (if (or (not file)
3796 (not (file-readable-p file)))
3797 (if noerror
3798 (progn
3799 (message "Cannot read file %s" file)
3800 (ding) (sit-for 2)
3802 (error "Cannot read file %s" file))
3803 (with-temp-buffer
3804 (insert-file-contents file)
3805 (buffer-string))))
3807 (defun org-extract-log-state-settings (x)
3808 "Extract the log state setting from a TODO keyword string.
3809 This will extract info from a string like \"WAIT(w@/!)\"."
3810 (let (kw key log1 log2)
3811 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3812 (setq kw (match-string 1 x)
3813 key (and (match-end 2) (match-string 2 x))
3814 log1 (and (match-end 3) (match-string 3 x))
3815 log2 (and (match-end 4) (match-string 4 x)))
3816 (and (or log1 log2)
3817 (list kw
3818 (and log1 (if (equal log1 "!") 'time 'note))
3819 (and log2 (if (equal log2 "!") 'time 'note)))))))
3821 (defun org-remove-keyword-keys (list)
3822 "Remove a pair of parenthesis at the end of each string in LIST."
3823 (mapcar (lambda (x)
3824 (if (string-match "(.*)$" x)
3825 (substring x 0 (match-beginning 0))
3827 list))
3829 ;; FIXME: this could be done much better, using second characters etc.
3830 (defun org-assign-fast-keys (alist)
3831 "Assign fast keys to a keyword-key alist.
3832 Respect keys that are already there."
3833 (let (new e k c c1 c2 (char ?a))
3834 (while (setq e (pop alist))
3835 (cond
3836 ((equal e '(:startgroup)) (push e new))
3837 ((equal e '(:endgroup)) (push e new))
3838 ((equal e '(:newline)) (push e new))
3840 (setq k (car e) c2 nil)
3841 (if (cdr e)
3842 (setq c (cdr e))
3843 ;; automatically assign a character.
3844 (setq c1 (string-to-char
3845 (downcase (substring
3846 k (if (= (string-to-char k) ?@) 1 0)))))
3847 (if (or (rassoc c1 new) (rassoc c1 alist))
3848 (while (or (rassoc char new) (rassoc char alist))
3849 (setq char (1+ char)))
3850 (setq c2 c1))
3851 (setq c (or c2 char)))
3852 (push (cons k c) new))))
3853 (nreverse new)))
3855 ;;; Some variables used in various places
3857 (defvar org-window-configuration nil
3858 "Used in various places to store a window configuration.")
3859 (defvar org-finish-function nil
3860 "Function to be called when `C-c C-c' is used.
3861 This is for getting out of special buffers like remember.")
3864 ;; FIXME: Occasionally check by commenting these, to make sure
3865 ;; no other functions uses these, forgetting to let-bind them.
3866 (defvar entry)
3867 (defvar last-state)
3868 (defvar date)
3870 ;; Defined somewhere in this file, but used before definition.
3871 (defvar org-html-entities)
3872 (defvar org-struct-menu)
3873 (defvar org-org-menu)
3874 (defvar org-tbl-menu)
3875 (defvar org-agenda-keymap)
3877 ;;;; Define the Org-mode
3879 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3880 (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."))
3883 ;; We use a before-change function to check if a table might need
3884 ;; an update.
3885 (defvar org-table-may-need-update t
3886 "Indicates that a table might need an update.
3887 This variable is set by `org-before-change-function'.
3888 `org-table-align' sets it back to nil.")
3889 (defun org-before-change-function (beg end)
3890 "Every change indicates that a table might need an update."
3891 (setq org-table-may-need-update t))
3892 (defvar org-mode-map)
3893 (defvar org-mode-hook nil
3894 "Mode hook for Org-mode, run after the mode was turned on.")
3895 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3896 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3897 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
3898 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
3899 (defvar org-table-buffer-is-an nil)
3900 (defconst org-outline-regexp "\\*+ ")
3902 ;;;###autoload
3903 (define-derived-mode org-mode outline-mode "Org"
3904 "Outline-based notes management and organizer, alias
3905 \"Carsten's outline-mode for keeping track of everything.\"
3907 Org-mode develops organizational tasks around a NOTES file which
3908 contains information about projects as plain text. Org-mode is
3909 implemented on top of outline-mode, which is ideal to keep the content
3910 of large files well structured. It supports ToDo items, deadlines and
3911 time stamps, which magically appear in the diary listing of the Emacs
3912 calendar. Tables are easily created with a built-in table editor.
3913 Plain text URL-like links connect to websites, emails (VM), Usenet
3914 messages (Gnus), BBDB entries, and any files related to the project.
3915 For printing and sharing of notes, an Org-mode file (or a part of it)
3916 can be exported as a structured ASCII or HTML file.
3918 The following commands are available:
3920 \\{org-mode-map}"
3922 ;; Get rid of Outline menus, they are not needed
3923 ;; Need to do this here because define-derived-mode sets up
3924 ;; the keymap so late. Still, it is a waste to call this each time
3925 ;; we switch another buffer into org-mode.
3926 (if (featurep 'xemacs)
3927 (when (boundp 'outline-mode-menu-heading)
3928 ;; Assume this is Greg's port, it used easymenu
3929 (easy-menu-remove outline-mode-menu-heading)
3930 (easy-menu-remove outline-mode-menu-show)
3931 (easy-menu-remove outline-mode-menu-hide))
3932 (define-key org-mode-map [menu-bar headings] 'undefined)
3933 (define-key org-mode-map [menu-bar hide] 'undefined)
3934 (define-key org-mode-map [menu-bar show] 'undefined))
3936 (org-load-modules-maybe)
3937 (easy-menu-add org-org-menu)
3938 (easy-menu-add org-tbl-menu)
3939 (org-install-agenda-files-menu)
3940 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3941 (org-add-to-invisibility-spec '(org-cwidth))
3942 (org-add-to-invisibility-spec '(org-hide-block . t))
3943 (when (featurep 'xemacs)
3944 (org-set-local 'line-move-ignore-invisible t))
3945 (org-set-local 'outline-regexp org-outline-regexp)
3946 (org-set-local 'outline-level 'org-outline-level)
3947 (when (and org-ellipsis
3948 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3949 (fboundp 'make-glyph-code))
3950 (unless org-display-table
3951 (setq org-display-table (make-display-table)))
3952 (set-display-table-slot
3953 org-display-table 4
3954 (vconcat (mapcar
3955 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3956 org-ellipsis)))
3957 (if (stringp org-ellipsis) org-ellipsis "..."))))
3958 (setq buffer-display-table org-display-table))
3959 (org-set-regexps-and-options)
3960 (when (and org-tag-faces (not org-tags-special-faces-re))
3961 ;; tag faces set outside customize.... force initialization.
3962 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3963 ;; Calc embedded
3964 (org-set-local 'calc-embedded-open-mode "# ")
3965 (modify-syntax-entry ?# "<")
3966 (modify-syntax-entry ?@ "w")
3967 (if org-startup-truncated (setq truncate-lines t))
3968 (org-set-local 'font-lock-unfontify-region-function
3969 'org-unfontify-region)
3970 ;; Activate before-change-function
3971 (org-set-local 'org-table-may-need-update t)
3972 (org-add-hook 'before-change-functions 'org-before-change-function nil
3973 'local)
3974 ;; Check for running clock before killing a buffer
3975 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3976 ;; Paragraphs and auto-filling
3977 (org-set-autofill-regexps)
3978 (setq indent-line-function 'org-indent-line-function)
3979 (org-update-radio-target-regexp)
3980 ;; Make sure dependence stuff works reliably, even for users who set it
3981 ;; too late :-(
3982 (if org-enforce-todo-dependencies
3983 (add-hook 'org-blocker-hook
3984 'org-block-todo-from-children-or-siblings-or-parent)
3985 (remove-hook 'org-blocker-hook
3986 'org-block-todo-from-children-or-siblings-or-parent))
3987 (if org-enforce-todo-checkbox-dependencies
3988 (add-hook 'org-blocker-hook
3989 'org-block-todo-from-checkboxes)
3990 (remove-hook 'org-blocker-hook
3991 'org-block-todo-from-checkboxes))
3993 ;; Comment characters
3994 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3995 (org-set-local 'comment-padding " ")
3997 ;; Align options lines
3998 (org-set-local
3999 'align-mode-rules-list
4000 '((org-in-buffer-settings
4001 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4002 (modes . '(org-mode)))))
4004 ;; Imenu
4005 (org-set-local 'imenu-create-index-function
4006 'org-imenu-get-tree)
4008 ;; Make isearch reveal context
4009 (if (or (featurep 'xemacs)
4010 (not (boundp 'outline-isearch-open-invisible-function)))
4011 ;; Emacs 21 and XEmacs make use of the hook
4012 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4013 ;; Emacs 22 deals with this through a special variable
4014 (org-set-local 'outline-isearch-open-invisible-function
4015 (lambda (&rest ignore) (org-show-context 'isearch))))
4017 ;; If empty file that did not turn on org-mode automatically, make it to.
4018 (if (and org-insert-mode-line-in-empty-file
4019 (interactive-p)
4020 (= (point-min) (point-max)))
4021 (insert "# -*- mode: org -*-\n\n"))
4023 (unless org-inhibit-startup
4024 (when org-startup-align-all-tables
4025 (let ((bmp (buffer-modified-p)))
4026 (org-table-map-tables 'org-table-align)
4027 (set-buffer-modified-p bmp)))
4028 (when org-startup-indented
4029 (require 'org-indent)
4030 (org-indent-mode 1))
4031 (org-set-startup-visibility)))
4033 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4035 (defun org-current-time ()
4036 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4037 (if (> (car org-time-stamp-rounding-minutes) 1)
4038 (let ((r (car org-time-stamp-rounding-minutes))
4039 (time (decode-time)))
4040 (apply 'encode-time
4041 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4042 (nthcdr 2 time))))
4043 (current-time)))
4045 ;;;; Font-Lock stuff, including the activators
4047 (defvar org-mouse-map (make-sparse-keymap))
4048 (org-defkey org-mouse-map
4049 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4050 (org-defkey org-mouse-map
4051 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4052 (when org-mouse-1-follows-link
4053 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4054 (when org-tab-follows-link
4055 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4056 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4058 (require 'font-lock)
4060 (defconst org-non-link-chars "]\t\n\r<>")
4061 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4062 "shell" "elisp"))
4063 (defvar org-link-types-re nil
4064 "Matches a link that has a url-like prefix like \"http:\"")
4065 (defvar org-link-re-with-space nil
4066 "Matches a link with spaces, optional angular brackets around it.")
4067 (defvar org-link-re-with-space2 nil
4068 "Matches a link with spaces, optional angular brackets around it.")
4069 (defvar org-link-re-with-space3 nil
4070 "Matches a link with spaces, only for internal part in bracket links.")
4071 (defvar org-angle-link-re nil
4072 "Matches link with angular brackets, spaces are allowed.")
4073 (defvar org-plain-link-re nil
4074 "Matches plain link, without spaces.")
4075 (defvar org-bracket-link-regexp nil
4076 "Matches a link in double brackets.")
4077 (defvar org-bracket-link-analytic-regexp nil
4078 "Regular expression used to analyze links.
4079 Here is what the match groups contain after a match:
4080 1: http:
4081 2: http
4082 3: path
4083 4: [desc]
4084 5: desc")
4085 (defvar org-bracket-link-analytic-regexp++ nil
4086 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4087 (defvar org-any-link-re nil
4088 "Regular expression matching any link.")
4090 (defun org-make-link-regexps ()
4091 "Update the link regular expressions.
4092 This should be called after the variable `org-link-types' has changed."
4093 (setq org-link-types-re
4094 (concat
4095 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
4096 org-link-re-with-space
4097 (concat
4098 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4099 "\\([^" org-non-link-chars " ]"
4100 "[^" org-non-link-chars "]*"
4101 "[^" org-non-link-chars " ]\\)>?")
4102 org-link-re-with-space2
4103 (concat
4104 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4105 "\\([^" org-non-link-chars " ]"
4106 "[^\t\n\r]*"
4107 "[^" org-non-link-chars " ]\\)>?")
4108 org-link-re-with-space3
4109 (concat
4110 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4111 "\\([^" org-non-link-chars " ]"
4112 "[^\t\n\r]*\\)")
4113 org-angle-link-re
4114 (concat
4115 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4116 "\\([^" org-non-link-chars " ]"
4117 "[^" org-non-link-chars "]*"
4118 "\\)>")
4119 org-plain-link-re
4120 (concat
4121 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4122 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4123 org-bracket-link-regexp
4124 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4125 org-bracket-link-analytic-regexp
4126 (concat
4127 "\\[\\["
4128 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4129 "\\([^]]+\\)"
4130 "\\]"
4131 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4132 "\\]")
4133 org-bracket-link-analytic-regexp++
4134 (concat
4135 "\\[\\["
4136 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4137 "\\([^]]+\\)"
4138 "\\]"
4139 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4140 "\\]")
4141 org-any-link-re
4142 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4143 org-angle-link-re "\\)\\|\\("
4144 org-plain-link-re "\\)")))
4146 (org-make-link-regexps)
4148 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4149 "Regular expression for fast time stamp matching.")
4150 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4151 "Regular expression for fast time stamp matching.")
4152 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4153 "Regular expression matching time strings for analysis.
4154 This one does not require the space after the date, so it can be used
4155 on a string that terminates immediately after the date.")
4156 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4157 "Regular expression matching time strings for analysis.")
4158 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4159 "Regular expression matching time stamps, with groups.")
4160 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4161 "Regular expression matching time stamps (also [..]), with groups.")
4162 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4163 "Regular expression matching a time stamp range.")
4164 (defconst org-tr-regexp-both
4165 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4166 "Regular expression matching a time stamp range.")
4167 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4168 org-ts-regexp "\\)?")
4169 "Regular expression matching a time stamp or time stamp range.")
4170 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4171 org-ts-regexp-both "\\)?")
4172 "Regular expression matching a time stamp or time stamp range.
4173 The time stamps may be either active or inactive.")
4175 (defvar org-emph-face nil)
4177 (defun org-do-emphasis-faces (limit)
4178 "Run through the buffer and add overlays to links."
4179 (let (rtn a)
4180 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4181 (if (not (= (char-after (match-beginning 3))
4182 (char-after (match-beginning 4))))
4183 (progn
4184 (setq rtn t)
4185 (setq a (assoc (match-string 3) org-emphasis-alist))
4186 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4187 'face
4188 (nth 1 a))
4189 (and (nth 4 a)
4190 (org-remove-flyspell-overlays-in
4191 (match-beginning 0) (match-end 0)))
4192 (add-text-properties (match-beginning 2) (match-end 2)
4193 '(font-lock-multiline t))
4194 (when org-hide-emphasis-markers
4195 (add-text-properties (match-end 4) (match-beginning 5)
4196 '(invisible org-link))
4197 (add-text-properties (match-beginning 3) (match-end 3)
4198 '(invisible org-link)))))
4199 (backward-char 1))
4200 rtn))
4202 (defun org-emphasize (&optional char)
4203 "Insert or change an emphasis, i.e. a font like bold or italic.
4204 If there is an active region, change that region to a new emphasis.
4205 If there is no region, just insert the marker characters and position
4206 the cursor between them.
4207 CHAR should be either the marker character, or the first character of the
4208 HTML tag associated with that emphasis. If CHAR is a space, the means
4209 to remove the emphasis of the selected region.
4210 If char is not given (for example in an interactive call) it
4211 will be prompted for."
4212 (interactive)
4213 (let ((eal org-emphasis-alist) e det
4214 (erc org-emphasis-regexp-components)
4215 (prompt "")
4216 (string "") beg end move tag c s)
4217 (if (org-region-active-p)
4218 (setq beg (region-beginning) end (region-end)
4219 string (buffer-substring beg end))
4220 (setq move t))
4222 (while (setq e (pop eal))
4223 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4224 c (aref tag 0))
4225 (push (cons c (string-to-char (car e))) det)
4226 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4227 (substring tag 1)))))
4228 (setq det (nreverse det))
4229 (unless char
4230 (message "%s" (concat "Emphasis marker or tag:" prompt))
4231 (setq char (read-char-exclusive)))
4232 (setq char (or (cdr (assoc char det)) char))
4233 (if (equal char ?\ )
4234 (setq s "" move nil)
4235 (unless (assoc (char-to-string char) org-emphasis-alist)
4236 (error "No such emphasis marker: \"%c\"" char))
4237 (setq s (char-to-string char)))
4238 (while (and (> (length string) 1)
4239 (equal (substring string 0 1) (substring string -1))
4240 (assoc (substring string 0 1) org-emphasis-alist))
4241 (setq string (substring string 1 -1)))
4242 (setq string (concat s string s))
4243 (if beg (delete-region beg end))
4244 (unless (or (bolp)
4245 (string-match (concat "[" (nth 0 erc) "\n]")
4246 (char-to-string (char-before (point)))))
4247 (insert " "))
4248 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4249 (char-to-string (char-after (point))))
4250 (insert " ") (backward-char 1))
4251 (insert string)
4252 (and move (backward-char 1))))
4254 (defconst org-nonsticky-props
4255 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4257 (defsubst org-rear-nonsticky-at (pos)
4258 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4260 (defun org-activate-plain-links (limit)
4261 "Run through the buffer and add overlays to links."
4262 (catch 'exit
4263 (let (f)
4264 (if (re-search-forward org-plain-link-re limit t)
4265 (progn
4266 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4267 (setq f (get-text-property (match-beginning 0) 'face))
4268 (if (or (eq f 'org-tag)
4269 (and (listp f) (memq 'org-tag f)))
4271 (add-text-properties (match-beginning 0) (match-end 0)
4272 (list 'mouse-face 'highlight
4273 'keymap org-mouse-map))
4274 (org-rear-nonsticky-at (match-end 0)))
4275 t)))))
4277 (defun org-activate-code (limit)
4278 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4279 (progn
4280 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4281 (remove-text-properties (match-beginning 0) (match-end 0)
4282 '(display t invisible t intangible t))
4283 t)))
4285 (defun org-fontify-meta-lines-and-blocks (limit)
4286 "Fontify #+ lines and blocks, in the correct ways."
4287 (let ((case-fold-search t))
4288 (if (re-search-forward
4289 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4290 limit t)
4291 (let ((beg (match-beginning 0))
4292 (beg1 (line-beginning-position 2))
4293 (dc1 (downcase (match-string 2)))
4294 (dc3 (downcase (match-string 3)))
4295 end end1 quoting)
4296 (cond
4297 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4298 ;; a single line of backend-specific content
4299 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4300 (remove-text-properties (match-beginning 0) (match-end 0)
4301 '(display t invisible t intangible t))
4302 (add-text-properties (match-beginning 1) (match-end 3)
4303 '(font-lock-fontified t face org-meta-line))
4304 (add-text-properties (match-beginning 6) (match-end 6)
4305 '(font-lock-fontified t face org-block))
4307 ((and (match-end 4) (equal dc3 "begin"))
4308 ;; Truely a block
4309 (setq quoting (member (downcase (match-string 5))
4310 org-protecting-blocks))
4311 (when (re-search-forward
4312 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4313 nil t) ;; on purpose, we look further than LIMIT
4314 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4315 (when quoting
4316 (remove-text-properties beg end
4317 '(display t invisible t intangible t)))
4318 (add-text-properties
4319 beg end
4320 '(font-lock-fontified t font-lock-multiline t))
4321 (add-text-properties beg beg1 '(face org-meta-line))
4322 (add-text-properties end1 end '(face org-meta-line))
4323 (when quoting
4324 (add-text-properties beg1 end1 '(face org-block)))
4326 ((not (member (char-after beg) '(?\ ?\t)))
4327 ;; just any other in-buffer setting, but not indented
4328 (add-text-properties
4329 beg (match-end 0)
4330 '(font-lock-fontified t face org-meta-line))
4332 ((or (member dc1 '("caption:" "label:" "orgtbl:" "tblfm:" "tblname:"))
4333 (and (match-end 4) (equal dc3 "attr")))
4334 (add-text-properties
4335 beg (match-end 0)
4336 '(font-lock-fontified t face org-meta-line))
4338 (t nil))))))
4340 (defun org-activate-angle-links (limit)
4341 "Run through the buffer and add overlays to links."
4342 (if (re-search-forward org-angle-link-re limit t)
4343 (progn
4344 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4345 (add-text-properties (match-beginning 0) (match-end 0)
4346 (list 'mouse-face 'highlight
4347 'keymap org-mouse-map))
4348 (org-rear-nonsticky-at (match-end 0))
4349 t)))
4351 (defun org-activate-footnote-links (limit)
4352 "Run through the buffer and add overlays to links."
4353 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4354 limit t)
4355 (progn
4356 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4357 (add-text-properties (match-beginning 2) (match-end 2)
4358 (list 'mouse-face 'highlight
4359 'keymap org-mouse-map
4360 'help-echo
4361 (if (= (point-at-bol) (match-beginning 2))
4362 "Footnote definition"
4363 "Footnote reference")
4365 (org-rear-nonsticky-at (match-end 2))
4366 t)))
4368 (defun org-activate-bracket-links (limit)
4369 "Run through the buffer and add overlays to bracketed links."
4370 (if (re-search-forward org-bracket-link-regexp limit t)
4371 (let* ((help (concat "LINK: "
4372 (org-match-string-no-properties 1)))
4373 ;; FIXME: above we should remove the escapes.
4374 ;; but that requires another match, protecting match data,
4375 ;; a lot of overhead for font-lock.
4376 (ip (org-maybe-intangible
4377 (list 'invisible 'org-link
4378 'keymap org-mouse-map 'mouse-face 'highlight
4379 'font-lock-multiline t 'help-echo help)))
4380 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4381 'font-lock-multiline t 'help-echo help)))
4382 ;; We need to remove the invisible property here. Table narrowing
4383 ;; may have made some of this invisible.
4384 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4385 (remove-text-properties (match-beginning 0) (match-end 0)
4386 '(invisible nil))
4387 (if (match-end 3)
4388 (progn
4389 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4390 (org-rear-nonsticky-at (match-beginning 3))
4391 (add-text-properties (match-beginning 3) (match-end 3) vp)
4392 (org-rear-nonsticky-at (match-end 3))
4393 (add-text-properties (match-end 3) (match-end 0) ip)
4394 (org-rear-nonsticky-at (match-end 0)))
4395 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4396 (org-rear-nonsticky-at (match-beginning 1))
4397 (add-text-properties (match-beginning 1) (match-end 1) vp)
4398 (org-rear-nonsticky-at (match-end 1))
4399 (add-text-properties (match-end 1) (match-end 0) ip)
4400 (org-rear-nonsticky-at (match-end 0)))
4401 t)))
4403 (defun org-activate-dates (limit)
4404 "Run through the buffer and add overlays to dates."
4405 (if (re-search-forward org-tsr-regexp-both limit t)
4406 (progn
4407 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4408 (add-text-properties (match-beginning 0) (match-end 0)
4409 (list 'mouse-face 'highlight
4410 'keymap org-mouse-map))
4411 (org-rear-nonsticky-at (match-end 0))
4412 (when org-display-custom-times
4413 (if (match-end 3)
4414 (org-display-custom-time (match-beginning 3) (match-end 3)))
4415 (org-display-custom-time (match-beginning 1) (match-end 1)))
4416 t)))
4418 (defvar org-target-link-regexp nil
4419 "Regular expression matching radio targets in plain text.")
4420 (make-variable-buffer-local 'org-target-link-regexp)
4421 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4422 "Regular expression matching a link target.")
4423 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4424 "Regular expression matching a radio target.")
4425 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4426 "Regular expression matching any target.")
4428 (defun org-activate-target-links (limit)
4429 "Run through the buffer and add overlays to target matches."
4430 (when org-target-link-regexp
4431 (let ((case-fold-search t))
4432 (if (re-search-forward org-target-link-regexp limit t)
4433 (progn
4434 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4435 (add-text-properties (match-beginning 0) (match-end 0)
4436 (list 'mouse-face 'highlight
4437 'keymap org-mouse-map
4438 'help-echo "Radio target link"
4439 'org-linked-text t))
4440 (org-rear-nonsticky-at (match-end 0))
4441 t)))))
4443 (defun org-update-radio-target-regexp ()
4444 "Find all radio targets in this file and update the regular expression."
4445 (interactive)
4446 (when (memq 'radio org-activate-links)
4447 (setq org-target-link-regexp
4448 (org-make-target-link-regexp (org-all-targets 'radio)))
4449 (org-restart-font-lock)))
4451 (defun org-hide-wide-columns (limit)
4452 (let (s e)
4453 (setq s (text-property-any (point) (or limit (point-max))
4454 'org-cwidth t))
4455 (when s
4456 (setq e (next-single-property-change s 'org-cwidth))
4457 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4458 (goto-char e)
4459 t)))
4461 (defvar org-latex-and-specials-regexp nil
4462 "Regular expression for highlighting export special stuff.")
4463 (defvar org-match-substring-regexp)
4464 (defvar org-match-substring-with-braces-regexp)
4466 ;; This should be with the exporter code, but we also use if for font-locking
4467 (defconst org-export-html-special-string-regexps
4468 '(("\\\\-" . "&shy;")
4469 ("---\\([^-]\\)" . "&mdash;\\1")
4470 ("--\\([^-]\\)" . "&ndash;\\1")
4471 ("\\.\\.\\." . "&hellip;"))
4472 "Regular expressions for special string conversion.")
4475 (defun org-compute-latex-and-specials-regexp ()
4476 "Compute regular expression for stuff treated specially by exporters."
4477 (if (not org-highlight-latex-fragments-and-specials)
4478 (org-set-local 'org-latex-and-specials-regexp nil)
4479 (require 'org-exp)
4480 (let*
4481 ((matchers (plist-get org-format-latex-options :matchers))
4482 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4483 org-latex-regexps)))
4484 (options (org-combine-plists (org-default-export-plist)
4485 (org-infile-export-plist)))
4486 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4487 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4488 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4489 (org-export-html-expand (plist-get options :expand-quoted-html))
4490 (org-export-with-special-strings (plist-get options :special-strings))
4491 (re-sub
4492 (cond
4493 ((equal org-export-with-sub-superscripts '{})
4494 (list org-match-substring-with-braces-regexp))
4495 (org-export-with-sub-superscripts
4496 (list org-match-substring-regexp))
4497 (t nil)))
4498 (re-latex
4499 (if org-export-with-LaTeX-fragments
4500 (mapcar (lambda (x) (nth 1 x)) latexs)))
4501 (re-macros
4502 (if org-export-with-TeX-macros
4503 (list (concat "\\\\"
4504 (regexp-opt
4505 (append (mapcar 'car org-html-entities)
4506 (if (boundp 'org-latex-entities)
4507 (mapcar (lambda (x)
4508 (or (car-safe x) x))
4509 org-latex-entities)
4510 nil))
4511 'words))) ; FIXME
4513 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4514 (re-special (if org-export-with-special-strings
4515 (mapcar (lambda (x) (car x))
4516 org-export-html-special-string-regexps)))
4517 (re-rest
4518 (delq nil
4519 (list
4520 (if org-export-html-expand "@<[^>\n]+>")
4521 ))))
4522 (org-set-local
4523 'org-latex-and-specials-regexp
4524 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4525 re-rest) "\\|")))))
4527 (defun org-do-latex-and-special-faces (limit)
4528 "Run through the buffer and add overlays to links."
4529 (when org-latex-and-specials-regexp
4530 (let (rtn d)
4531 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4532 limit t))
4533 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4534 'face))
4535 '(org-code org-verbatim underline)))
4536 (progn
4537 (setq rtn t
4538 d (cond ((member (char-after (1+ (match-beginning 0)))
4539 '(?_ ?^)) 1)
4540 (t 0)))
4541 (font-lock-prepend-text-property
4542 (+ d (match-beginning 0)) (match-end 0)
4543 'face 'org-latex-and-export-specials)
4544 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4545 '(font-lock-multiline t)))))
4546 rtn)))
4548 (defun org-restart-font-lock ()
4549 "Restart font-lock-mode, to force refontification."
4550 (when (and (boundp 'font-lock-mode) font-lock-mode)
4551 (font-lock-mode -1)
4552 (font-lock-mode 1)))
4554 (defun org-all-targets (&optional radio)
4555 "Return a list of all targets in this file.
4556 With optional argument RADIO, only find radio targets."
4557 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4558 rtn)
4559 (save-excursion
4560 (goto-char (point-min))
4561 (while (re-search-forward re nil t)
4562 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4563 rtn)))
4565 (defun org-make-target-link-regexp (targets)
4566 "Make regular expression matching all strings in TARGETS.
4567 The regular expression finds the targets also if there is a line break
4568 between words."
4569 (and targets
4570 (concat
4571 "\\<\\("
4572 (mapconcat
4573 (lambda (x)
4574 (while (string-match " +" x)
4575 (setq x (replace-match "\\s-+" t t x)))
4577 targets
4578 "\\|")
4579 "\\)\\>")))
4581 (defun org-activate-tags (limit)
4582 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4583 (progn
4584 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4585 (add-text-properties (match-beginning 1) (match-end 1)
4586 (list 'mouse-face 'highlight
4587 'keymap org-mouse-map))
4588 (org-rear-nonsticky-at (match-end 1))
4589 t)))
4591 (defun org-outline-level ()
4592 (save-excursion
4593 (looking-at outline-regexp)
4594 (if (match-beginning 1)
4595 (+ (org-get-string-indentation (match-string 1)) 1000)
4596 (1- (- (match-end 0) (match-beginning 0))))))
4598 (defvar org-font-lock-keywords nil)
4600 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4601 "Regular expression matching a property line.")
4603 (defvar org-font-lock-hook nil
4604 "Functions to be called for special font lock stuff.")
4606 (defun org-font-lock-hook (limit)
4607 (run-hook-with-args 'org-font-lock-hook limit))
4609 (defun org-set-font-lock-defaults ()
4610 (let* ((em org-fontify-emphasized-text)
4611 (lk org-activate-links)
4612 (org-font-lock-extra-keywords
4613 (list
4614 ;; Call the hook
4615 '(org-font-lock-hook)
4616 ;; Headlines
4617 `(,(if org-fontify-whole-heading-line
4618 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
4619 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
4620 (1 (org-get-level-face 1))
4621 (2 (org-get-level-face 2))
4622 (3 (org-get-level-face 3)))
4623 ;; Table lines
4624 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4625 (1 'org-table t))
4626 ;; Table internals
4627 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4628 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4629 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4630 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
4631 ;; Drawers
4632 (list org-drawer-regexp '(0 'org-special-keyword t))
4633 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4634 ;; Properties
4635 (list org-property-re
4636 '(1 'org-special-keyword t)
4637 '(3 'org-property-value t))
4638 ;; Links
4639 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4640 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4641 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4642 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4643 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4644 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4645 (if (memq 'footnote lk) '(org-activate-footnote-links
4646 (2 'org-footnote t)))
4647 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4648 '(org-hide-wide-columns (0 nil append))
4649 ;; TODO lines
4650 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4651 '(1 (org-get-todo-face 1) t))
4652 ;; DONE
4653 (if org-fontify-done-headline
4654 (list (concat "^[*]+ +\\<\\("
4655 (mapconcat 'regexp-quote org-done-keywords "\\|")
4656 "\\)\\(.*\\)")
4657 '(2 'org-headline-done t))
4658 nil)
4659 ;; Priorities
4660 '(org-font-lock-add-priority-faces)
4661 ;; Tags
4662 '(org-font-lock-add-tag-faces)
4663 ;; Special keywords
4664 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4665 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4666 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4667 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4668 ;; Emphasis
4669 (if em
4670 (if (featurep 'xemacs)
4671 '(org-do-emphasis-faces (0 nil append))
4672 '(org-do-emphasis-faces)))
4673 ;; Checkboxes
4674 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4675 2 'org-checkbox prepend)
4676 (if org-provide-checkbox-statistics
4677 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4678 (0 (org-get-checkbox-statistics-face) t)))
4679 ;; Description list items
4680 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4681 2 'bold prepend)
4682 ;; ARCHIVEd headings
4683 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4684 '(1 'org-archived prepend))
4685 ;; Specials
4686 '(org-do-latex-and-special-faces)
4687 ;; Code
4688 '(org-activate-code (1 'org-code t))
4689 ;; COMMENT
4690 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4691 "\\|" org-quote-string "\\)\\>")
4692 '(1 'org-special-keyword t))
4693 '("^#.*" (0 'font-lock-comment-face t))
4694 ;; Blocks and meta lines
4695 '(org-fontify-meta-lines-and-blocks)
4697 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4698 ;; Now set the full font-lock-keywords
4699 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4700 (org-set-local 'font-lock-defaults
4701 '(org-font-lock-keywords t nil nil backward-paragraph))
4702 (kill-local-variable 'font-lock-keywords) nil))
4704 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
4705 "Fontify string S like in Org-mode"
4706 (with-temp-buffer
4707 (insert s)
4708 (let ((org-odd-levels-only odd-levels))
4709 (org-mode)
4710 (font-lock-fontify-buffer)
4711 (buffer-string))))
4713 (defvar org-m nil)
4714 (defvar org-l nil)
4715 (defvar org-f nil)
4716 (defun org-get-level-face (n)
4717 "Get the right face for match N in font-lock matching of headlines."
4718 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4719 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4720 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4721 (cond
4722 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4723 ((eq n 2) org-f)
4724 (t (if org-level-color-stars-only nil org-f))))
4726 (defun org-get-todo-face (kwd)
4727 "Get the right face for a TODO keyword KWD.
4728 If KWD is a number, get the corresponding match group."
4729 (if (numberp kwd) (setq kwd (match-string kwd)))
4730 (or (cdr (assoc kwd org-todo-keyword-faces))
4731 (and (member kwd org-done-keywords) 'org-done)
4732 'org-todo))
4734 (defun org-font-lock-add-tag-faces (limit)
4735 "Add the special tag faces."
4736 (when (and org-tag-faces org-tags-special-faces-re)
4737 (while (re-search-forward org-tags-special-faces-re limit t)
4738 (add-text-properties (match-beginning 1) (match-end 1)
4739 (list 'face (org-get-tag-face 1)
4740 'font-lock-fontified t))
4741 (backward-char 1))))
4743 (defun org-font-lock-add-priority-faces (limit)
4744 "Add the special priority faces."
4745 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4746 (add-text-properties
4747 (match-beginning 0) (match-end 0)
4748 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4749 org-priority-faces))
4750 'org-special-keyword)
4751 'font-lock-fontified t))))
4753 (defun org-get-tag-face (kwd)
4754 "Get the right face for a TODO keyword KWD.
4755 If KWD is a number, get the corresponding match group."
4756 (if (numberp kwd) (setq kwd (match-string kwd)))
4757 (or (cdr (assoc kwd org-tag-faces))
4758 'org-tag))
4760 (defun org-unfontify-region (beg end &optional maybe_loudly)
4761 "Remove fontification and activation overlays from links."
4762 (font-lock-default-unfontify-region beg end)
4763 (let* ((buffer-undo-list t)
4764 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4765 (inhibit-modification-hooks t)
4766 deactivate-mark buffer-file-name buffer-file-truename)
4767 (remove-text-properties beg end
4768 '(mouse-face t keymap t org-linked-text t
4769 invisible t intangible t
4770 line-prefix t wrap-prefix t
4771 org-no-flyspell t))))
4773 ;;;; Visibility cycling, including org-goto and indirect buffer
4775 ;;; Cycling
4777 (defvar org-cycle-global-status nil)
4778 (make-variable-buffer-local 'org-cycle-global-status)
4779 (defvar org-cycle-subtree-status nil)
4780 (make-variable-buffer-local 'org-cycle-subtree-status)
4782 ;;;###autoload
4784 (defvar org-inlinetask-min-level)
4786 (defun org-cycle (&optional arg)
4787 "TAB-action and visibility cycling for Org-mode.
4789 This is the command invoked in Org-mode by the TAB key. Its main purpose
4790 is outine visibility cycling, but it also invokes other actions
4791 in special contexts.
4793 - When this function is called with a prefix argument, rotate the entire
4794 buffer through 3 states (global cycling)
4795 1. OVERVIEW: Show only top-level headlines.
4796 2. CONTENTS: Show all headlines of all levels, but no body text.
4797 3. SHOW ALL: Show everything.
4798 When called with two `C-u C-u' prefixes, switch to the startup visibility,
4799 determined by the variable `org-startup-folded', and by any VISIBILITY
4800 properties in the buffer.
4801 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
4802 including any drawers.
4804 - When inside a table, re-align the table and move to the next field.
4806 - When point is at the beginning of a headline, rotate the subtree started
4807 by this line through 3 different states (local cycling)
4808 1. FOLDED: Only the main headline is shown.
4809 2. CHILDREN: The main headline and the direct children are shown.
4810 From this state, you can move to one of the children
4811 and zoom in further.
4812 3. SUBTREE: Show the entire subtree, including body text.
4813 If there is no subtree, switch directly from CHILDREN to FOLDED.
4815 - When there is a numeric prefix, go up to a heading with level ARG, do
4816 a `show-subtree' and return to the previous cursor position. If ARG
4817 is negative, go up that many levels.
4819 - When point is not at the beginning of a headline, execute the global
4820 binding for TAB, which is re-indenting the line. See the option
4821 `org-cycle-emulate-tab' for details.
4823 - Special case: if point is at the beginning of the buffer and there is
4824 no headline in line 1, this function will act as if called with prefix arg.
4825 But only if also the variable `org-cycle-global-at-bob' is t."
4826 (interactive "P")
4827 (org-load-modules-maybe)
4828 (unless (run-hook-with-args-until-success 'org-tab-first-hook)
4829 (let* ((limit-level
4830 (or org-cycle-max-level
4831 (and (boundp 'org-inlinetask-min-level)
4832 org-inlinetask-min-level
4833 (1- org-inlinetask-min-level))))
4834 (nstars (and limit-level
4835 (if org-odd-levels-only
4836 (and limit-level (1- (* limit-level 2)))
4837 limit-level)))
4838 (outline-regexp
4839 (cond
4840 ((not (org-mode-p)) outline-regexp)
4841 ((or (eq org-cycle-include-plain-lists 'integrate)
4842 (and org-cycle-include-plain-lists (org-at-item-p)))
4843 (concat "\\(?:\\*"
4844 (if nstars (format "\\{1,%d\\}" nstars) "+")
4845 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
4846 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
4847 (bob-special (and org-cycle-global-at-bob (bobp)
4848 (not (looking-at outline-regexp))))
4849 (org-cycle-hook
4850 (if bob-special
4851 (delq 'org-optimize-window-after-visibility-change
4852 (copy-sequence org-cycle-hook))
4853 org-cycle-hook))
4854 (pos (point)))
4856 (if (or bob-special (equal arg '(4)))
4857 ;; special case: use global cycling
4858 (setq arg t))
4860 (cond
4862 ((equal arg '(16))
4863 (org-set-startup-visibility)
4864 (message "Startup visibility, plus VISIBILITY properties"))
4866 ((equal arg '(64))
4867 (show-all)
4868 (message "Entire buffer visible, including drawers"))
4870 ((org-at-table-p 'any)
4871 ;; Enter the table or move to the next field in the table
4872 (or (org-table-recognize-table.el)
4873 (progn
4874 (if arg (org-table-edit-field t)
4875 (org-table-justify-field-maybe)
4876 (call-interactively 'org-table-next-field)))))
4878 ((run-hook-with-args-until-success
4879 'org-tab-after-check-for-table-hook))
4881 ((eq arg t) ;; Global cycling
4882 (org-cycle-internal-global))
4884 ((and org-drawers org-drawer-regexp
4885 (save-excursion
4886 (beginning-of-line 1)
4887 (looking-at org-drawer-regexp)))
4888 ;; Toggle block visibility
4889 (org-flag-drawer
4890 (not (get-char-property (match-end 0) 'invisible))))
4892 ((integerp arg)
4893 ;; Show-subtree, ARG levels up from here.
4894 (save-excursion
4895 (org-back-to-heading)
4896 (outline-up-heading (if (< arg 0) (- arg)
4897 (- (funcall outline-level) arg)))
4898 (org-show-subtree)))
4900 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4901 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4903 (org-cycle-internal-local))
4905 ;; TAB emulation and template completion
4906 (buffer-read-only (org-back-to-heading))
4908 ((run-hook-with-args-until-success
4909 'org-tab-after-check-for-cycling-hook))
4911 ((org-try-structure-completion))
4913 ((org-try-cdlatex-tab))
4915 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4916 (or (not (bolp))
4917 (not (looking-at outline-regexp))))
4918 (call-interactively (global-key-binding "\t")))
4920 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4921 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4922 (or (and (eq org-cycle-emulate-tab 'white)
4923 (= (match-end 0) (point-at-eol)))
4924 (and (eq org-cycle-emulate-tab 'whitestart)
4925 (>= (match-end 0) pos))))
4927 (eq org-cycle-emulate-tab t))
4928 (call-interactively (global-key-binding "\t")))
4930 (t (save-excursion
4931 (org-back-to-heading)
4932 (org-cycle)))))))
4934 (defun org-cycle-internal-global ()
4935 "Do the global cycling action."
4936 (cond
4937 ((and (eq last-command this-command)
4938 (eq org-cycle-global-status 'overview))
4939 ;; We just created the overview - now do table of contents
4940 ;; This can be slow in very large buffers, so indicate action
4941 (run-hook-with-args 'org-pre-cycle-hook 'contents)
4942 (message "CONTENTS...")
4943 (org-content)
4944 (message "CONTENTS...done")
4945 (setq org-cycle-global-status 'contents)
4946 (run-hook-with-args 'org-cycle-hook 'contents))
4948 ((and (eq last-command this-command)
4949 (eq org-cycle-global-status 'contents))
4950 ;; We just showed the table of contents - now show everything
4951 (run-hook-with-args 'org-pre-cycle-hook 'all)
4952 (show-all)
4953 (message "SHOW ALL")
4954 (setq org-cycle-global-status 'all)
4955 (run-hook-with-args 'org-cycle-hook 'all))
4958 ;; Default action: go to overview
4959 (run-hook-with-args 'org-pre-cycle-hook 'overview)
4960 (org-overview)
4961 (message "OVERVIEW")
4962 (setq org-cycle-global-status 'overview)
4963 (run-hook-with-args 'org-cycle-hook 'overview))))
4965 (defun org-cycle-internal-local ()
4966 "Do the local cycling action."
4967 (org-back-to-heading)
4968 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
4969 ;; First, some boundaries
4970 (save-excursion
4971 (org-back-to-heading)
4972 (setq level (funcall outline-level))
4973 (save-excursion
4974 (beginning-of-line 2)
4975 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
4976 ; XEmacs does not have `next-single-char-property-change'
4977 ; I'm not sure about Emacs 21.
4978 (while (and (not (eobp)) ;; this is like `next-line'
4979 (get-char-property (1- (point)) 'invisible))
4980 (beginning-of-line 2))
4981 (while (and (not (eobp)) ;; this is like `next-line'
4982 (get-char-property (1- (point)) 'invisible))
4983 (goto-char (next-single-char-property-change (point) 'invisible))
4984 ;;;??? (or (bolp) (beginning-of-line 2))))
4985 (and (eolp) (beginning-of-line 2))))
4986 (setq eol (point)))
4987 (outline-end-of-heading) (setq eoh (point))
4988 (save-excursion
4989 (outline-next-heading)
4990 (setq has-children (and (org-at-heading-p t)
4991 (> (funcall outline-level) level))))
4992 (org-end-of-subtree t)
4993 (unless (eobp)
4994 (skip-chars-forward " \t\n")
4995 (beginning-of-line 1) ; in case this is an item
4997 (setq eos (1- (point))))
4998 ;; Find out what to do next and set `this-command'
4999 (cond
5000 ((= eos eoh)
5001 ;; Nothing is hidden behind this heading
5002 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5003 (message "EMPTY ENTRY")
5004 (setq org-cycle-subtree-status nil)
5005 (save-excursion
5006 (goto-char eos)
5007 (outline-next-heading)
5008 (if (org-invisible-p) (org-flag-heading nil))))
5009 ((and (or (>= eol eos)
5010 (not (string-match "\\S-" (buffer-substring eol eos))))
5011 (or has-children
5012 (not (setq children-skipped
5013 org-cycle-skip-children-state-if-no-children))))
5014 ;; Entire subtree is hidden in one line: children view
5015 (run-hook-with-args 'org-pre-cycle-hook 'children)
5016 (org-show-entry)
5017 (show-children)
5018 (message "CHILDREN")
5019 (save-excursion
5020 (goto-char eos)
5021 (outline-next-heading)
5022 (if (org-invisible-p) (org-flag-heading nil)))
5023 (setq org-cycle-subtree-status 'children)
5024 (run-hook-with-args 'org-cycle-hook 'children))
5025 ((or children-skipped
5026 (and (eq last-command this-command)
5027 (eq org-cycle-subtree-status 'children)))
5028 ;; We just showed the children, or no children are there,
5029 ;; now show everything.
5030 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5031 (org-show-subtree)
5032 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5033 (setq org-cycle-subtree-status 'subtree)
5034 (run-hook-with-args 'org-cycle-hook 'subtree))
5036 ;; Default action: hide the subtree.
5037 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5038 (hide-subtree)
5039 (message "FOLDED")
5040 (setq org-cycle-subtree-status 'folded)
5041 (run-hook-with-args 'org-cycle-hook 'folded)))))
5043 ;;;###autoload
5044 (defun org-global-cycle (&optional arg)
5045 "Cycle the global visibility. For details see `org-cycle'.
5046 With C-u prefix arg, switch to startup visibility.
5047 With a numeric prefix, show all headlines up to that level."
5048 (interactive "P")
5049 (let ((org-cycle-include-plain-lists
5050 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5051 (cond
5052 ((integerp arg)
5053 (show-all)
5054 (hide-sublevels arg)
5055 (setq org-cycle-global-status 'contents))
5056 ((equal arg '(4))
5057 (org-set-startup-visibility)
5058 (message "Startup visibility, plus VISIBILITY properties."))
5060 (org-cycle '(4))))))
5062 (defun org-set-startup-visibility ()
5063 "Set the visibility required by startup options and properties."
5064 (cond
5065 ((eq org-startup-folded t)
5066 (org-cycle '(4)))
5067 ((eq org-startup-folded 'content)
5068 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5069 (org-cycle '(4)) (org-cycle '(4)))))
5070 (if org-hide-block-startup (org-hide-block-all))
5071 (org-set-visibility-according-to-property 'no-cleanup)
5072 (org-cycle-hide-archived-subtrees 'all)
5073 (org-cycle-hide-drawers 'all)
5074 (org-cycle-show-empty-lines 'all))
5076 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5077 "Switch subtree visibilities according to :VISIBILITY: property."
5078 (interactive)
5079 (let (org-show-entry-below state)
5080 (save-excursion
5081 (goto-char (point-min))
5082 (while (re-search-forward
5083 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5084 nil t)
5085 (setq state (match-string 1))
5086 (save-excursion
5087 (org-back-to-heading t)
5088 (hide-subtree)
5089 (org-reveal)
5090 (cond
5091 ((equal state '("fold" "folded"))
5092 (hide-subtree))
5093 ((equal state "children")
5094 (org-show-hidden-entry)
5095 (show-children))
5096 ((equal state "content")
5097 (save-excursion
5098 (save-restriction
5099 (org-narrow-to-subtree)
5100 (org-content))))
5101 ((member state '("all" "showall"))
5102 (show-subtree)))))
5103 (unless no-cleanup
5104 (org-cycle-hide-archived-subtrees 'all)
5105 (org-cycle-hide-drawers 'all)
5106 (org-cycle-show-empty-lines 'all)))))
5108 (defun org-overview ()
5109 "Switch to overview mode, showing only top-level headlines.
5110 Really, this shows all headlines with level equal or greater than the level
5111 of the first headline in the buffer. This is important, because if the
5112 first headline is not level one, then (hide-sublevels 1) gives confusing
5113 results."
5114 (interactive)
5115 (let ((level (save-excursion
5116 (goto-char (point-min))
5117 (if (re-search-forward (concat "^" outline-regexp) nil t)
5118 (progn
5119 (goto-char (match-beginning 0))
5120 (funcall outline-level))))))
5121 (and level (hide-sublevels level))))
5123 (defun org-content (&optional arg)
5124 "Show all headlines in the buffer, like a table of contents.
5125 With numerical argument N, show content up to level N."
5126 (interactive "P")
5127 (save-excursion
5128 ;; Visit all headings and show their offspring
5129 (and (integerp arg) (org-overview))
5130 (goto-char (point-max))
5131 (catch 'exit
5132 (while (and (progn (condition-case nil
5133 (outline-previous-visible-heading 1)
5134 (error (goto-char (point-min))))
5136 (looking-at outline-regexp))
5137 (if (integerp arg)
5138 (show-children (1- arg))
5139 (show-branches))
5140 (if (bobp) (throw 'exit nil))))))
5143 (defun org-optimize-window-after-visibility-change (state)
5144 "Adjust the window after a change in outline visibility.
5145 This function is the default value of the hook `org-cycle-hook'."
5146 (when (get-buffer-window (current-buffer))
5147 (cond
5148 ((eq state 'content) nil)
5149 ((eq state 'all) nil)
5150 ((eq state 'folded) nil)
5151 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5152 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5154 ;; FIXME: no longer in use
5155 (defun org-compact-display-after-subtree-move ()
5156 "Show a compacter version of the tree of the entry's parent."
5157 (save-excursion
5158 (if (org-up-heading-safe)
5159 (progn
5160 (hide-subtree)
5161 (show-entry)
5162 (show-children)
5163 (org-cycle-show-empty-lines 'children)
5164 (org-cycle-hide-drawers 'children))
5165 (org-overview))))
5167 (defun org-remove-empty-overlays-at (pos)
5168 "Remove outline overlays that do not contain non-white stuff."
5169 (mapc
5170 (lambda (o)
5171 (and (eq 'outline (org-overlay-get o 'invisible))
5172 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5173 (org-overlay-end o))))
5174 (org-delete-overlay o)))
5175 (org-overlays-at pos)))
5177 (defun org-clean-visibility-after-subtree-move ()
5178 "Fix visibility issues after moving a subtree."
5179 ;; First, find a reasonable region to look at:
5180 ;; Start two siblings above, end three below
5181 (let* ((beg (save-excursion
5182 (and (outline-get-last-sibling)
5183 (outline-get-last-sibling))
5184 (point)))
5185 (end (save-excursion
5186 (and (outline-get-next-sibling)
5187 (outline-get-next-sibling)
5188 (outline-get-next-sibling))
5189 (if (org-at-heading-p)
5190 (point-at-eol)
5191 (point))))
5192 (level (looking-at "\\*+"))
5193 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5194 (save-excursion
5195 (save-restriction
5196 (narrow-to-region beg end)
5197 (when re
5198 ;; Properly fold already folded siblings
5199 (goto-char (point-min))
5200 (while (re-search-forward re nil t)
5201 (if (save-excursion (goto-char (point-at-eol)) (org-invisible-p))
5202 (hide-entry))))
5203 (org-cycle-show-empty-lines 'overview)
5204 (org-cycle-hide-drawers 'overview)))))
5206 (defun org-cycle-show-empty-lines (state)
5207 "Show empty lines above all visible headlines.
5208 The region to be covered depends on STATE when called through
5209 `org-cycle-hook'. Lisp program can use t for STATE to get the
5210 entire buffer covered. Note that an empty line is only shown if there
5211 are at least `org-cycle-separator-lines' empty lines before the headline."
5212 (when (> org-cycle-separator-lines 0)
5213 (save-excursion
5214 (let* ((n org-cycle-separator-lines)
5215 (re (cond
5216 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5217 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5218 (t (let ((ns (number-to-string (- n 2))))
5219 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5220 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5221 beg end)
5222 (cond
5223 ((memq state '(overview contents t))
5224 (setq beg (point-min) end (point-max)))
5225 ((memq state '(children folded))
5226 (setq beg (point) end (progn (org-end-of-subtree t t)
5227 (beginning-of-line 2)
5228 (point)))))
5229 (when beg
5230 (goto-char beg)
5231 (while (re-search-forward re end t)
5232 (if (not (get-char-property (match-end 1) 'invisible))
5233 (outline-flag-region
5234 (match-beginning 1) (match-end 1) nil)))))))
5235 ;; Never hide empty lines at the end of the file.
5236 (save-excursion
5237 (goto-char (point-max))
5238 (outline-previous-heading)
5239 (outline-end-of-heading)
5240 (if (and (looking-at "[ \t\n]+")
5241 (= (match-end 0) (point-max)))
5242 (outline-flag-region (point) (match-end 0) nil))))
5244 (defun org-show-empty-lines-in-parent ()
5245 "Move to the parent and re-show empty lines before visible headlines."
5246 (save-excursion
5247 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5248 (org-cycle-show-empty-lines context))))
5250 (defun org-cycle-hide-drawers (state)
5251 "Re-hide all drawers after a visibility state change."
5252 (when (and (org-mode-p)
5253 (not (memq state '(overview folded contents))))
5254 (save-excursion
5255 (let* ((globalp (memq state '(contents all)))
5256 (beg (if globalp (point-min) (point)))
5257 (end (if globalp (point-max)
5258 (if (eq state 'children)
5259 (save-excursion (outline-next-heading) (point))
5260 (org-end-of-subtree t)))))
5261 (goto-char beg)
5262 (while (re-search-forward org-drawer-regexp end t)
5263 (org-flag-drawer t))))))
5265 (defun org-flag-drawer (flag)
5266 (save-excursion
5267 (beginning-of-line 1)
5268 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5269 (let ((b (match-end 0))
5270 (outline-regexp org-outline-regexp))
5271 (if (re-search-forward
5272 "^[ \t]*:END:"
5273 (save-excursion (outline-next-heading) (point)) t)
5274 (outline-flag-region b (point-at-eol) flag)
5275 (error ":END: line missing"))))))
5277 (defun org-subtree-end-visible-p ()
5278 "Is the end of the current subtree visible?"
5279 (pos-visible-in-window-p
5280 (save-excursion (org-end-of-subtree t) (point))))
5282 (defun org-first-headline-recenter (&optional N)
5283 "Move cursor to the first headline and recenter the headline.
5284 Optional argument N means, put the headline into the Nth line of the window."
5285 (goto-char (point-min))
5286 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5287 (beginning-of-line)
5288 (recenter (prefix-numeric-value N))))
5290 ;;; Folding of blocks
5292 (defconst org-block-regexp
5294 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5295 "Regular expression for hiding blocks.")
5297 (defvar org-hide-block-overlays nil
5298 "Overays hiding blocks.")
5299 (make-variable-buffer-local 'org-hide-block-overlays)
5301 (defun org-block-map (function &optional start end)
5302 "Call func at the head of all source blocks in the current
5303 buffer. Optional arguments START and END can be used to limit
5304 the range."
5305 (let ((start (or start (point-min)))
5306 (end (or end (point-max))))
5307 (save-excursion
5308 (goto-char start)
5309 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5310 (save-excursion
5311 (save-match-data
5312 (goto-char (match-beginning 0))
5313 (funcall function)))))))
5315 (defun org-hide-block-toggle-all ()
5316 "Toggle the visibility of all blocks in the current buffer."
5317 (org-block-map #'org-hide-block-toggle))
5319 (defun org-hide-block-all ()
5320 "Fold all blocks in the current buffer."
5321 (interactive)
5322 (org-show-block-all)
5323 (org-block-map #'org-hide-block-toggle-maybe))
5325 (defun org-show-block-all ()
5326 "Unfold all blocks in the current buffer."
5327 (mapc 'org-delete-overlay org-hide-block-overlays)
5328 (setq org-hide-block-overlays nil))
5330 (defun org-hide-block-toggle-maybe ()
5331 "Toggle visibility of block at point."
5332 (interactive)
5333 (let ((case-fold-search t))
5334 (if (save-excursion
5335 (beginning-of-line 1)
5336 (looking-at org-block-regexp))
5337 (progn (org-hide-block-toggle)
5338 t) ;; to signal that we took action
5339 nil))) ;; to signal that we did not
5341 (defun org-hide-block-toggle (&optional force)
5342 "Toggle the visibility of the current block."
5343 (interactive)
5344 (save-excursion
5345 (beginning-of-line)
5346 (if (re-search-forward org-block-regexp nil t)
5347 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5348 (end (match-end 0))
5349 ov) ;; end of entire body
5350 (if (memq t (mapcar (lambda (overlay)
5351 (eq (org-overlay-get overlay 'invisible)
5352 'org-hide-block))
5353 (org-overlays-at start)))
5354 (if (or (not force) (eq force 'off))
5355 (mapc (lambda (ov)
5356 (when (member ov org-hide-block-overlays)
5357 (setq org-hide-block-overlays
5358 (delq ov org-hide-block-overlays)))
5359 (when (eq (org-overlay-get ov 'invisible)
5360 'org-hide-block)
5361 (org-delete-overlay ov)))
5362 (org-overlays-at start)))
5363 (setq ov (org-make-overlay start end))
5364 (org-overlay-put ov 'invisible 'org-hide-block)
5365 (push ov org-hide-block-overlays)))
5366 (error "Not looking at a source block"))))
5368 ;; org-tab-after-check-for-cycling-hook
5369 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5370 ;; Remove overlays when changing major mode
5371 (add-hook 'org-mode-hook
5372 (lambda () (org-add-hook 'change-major-mode-hook
5373 'org-show-block-all 'append 'local)))
5375 ;;; Org-goto
5377 (defvar org-goto-window-configuration nil)
5378 (defvar org-goto-marker nil)
5379 (defvar org-goto-map
5380 (let ((map (make-sparse-keymap)))
5381 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5382 (while (setq cmd (pop cmds))
5383 (substitute-key-definition cmd cmd map global-map)))
5384 (suppress-keymap map)
5385 (org-defkey map "\C-m" 'org-goto-ret)
5386 (org-defkey map [(return)] 'org-goto-ret)
5387 (org-defkey map [(left)] 'org-goto-left)
5388 (org-defkey map [(right)] 'org-goto-right)
5389 (org-defkey map [(control ?g)] 'org-goto-quit)
5390 (org-defkey map "\C-i" 'org-cycle)
5391 (org-defkey map [(tab)] 'org-cycle)
5392 (org-defkey map [(down)] 'outline-next-visible-heading)
5393 (org-defkey map [(up)] 'outline-previous-visible-heading)
5394 (if org-goto-auto-isearch
5395 (if (fboundp 'define-key-after)
5396 (define-key-after map [t] 'org-goto-local-auto-isearch)
5397 nil)
5398 (org-defkey map "q" 'org-goto-quit)
5399 (org-defkey map "n" 'outline-next-visible-heading)
5400 (org-defkey map "p" 'outline-previous-visible-heading)
5401 (org-defkey map "f" 'outline-forward-same-level)
5402 (org-defkey map "b" 'outline-backward-same-level)
5403 (org-defkey map "u" 'outline-up-heading))
5404 (org-defkey map "/" 'org-occur)
5405 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5406 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5407 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5408 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5409 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5410 map))
5412 (defconst org-goto-help
5413 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5414 RET=jump to location [Q]uit and return to previous location
5415 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5417 (defvar org-goto-start-pos) ; dynamically scoped parameter
5419 ;; FIXME: Docstring doe not mention both interfaces
5420 (defun org-goto (&optional alternative-interface)
5421 "Look up a different location in the current file, keeping current visibility.
5423 When you want look-up or go to a different location in a document, the
5424 fastest way is often to fold the entire buffer and then dive into the tree.
5425 This method has the disadvantage, that the previous location will be folded,
5426 which may not be what you want.
5428 This command works around this by showing a copy of the current buffer
5429 in an indirect buffer, in overview mode. You can dive into the tree in
5430 that copy, use org-occur and incremental search to find a location.
5431 When pressing RET or `Q', the command returns to the original buffer in
5432 which the visibility is still unchanged. After RET is will also jump to
5433 the location selected in the indirect buffer and expose the
5434 the headline hierarchy above."
5435 (interactive "P")
5436 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5437 (org-refile-use-outline-path t)
5438 (org-refile-target-verify-function nil)
5439 (interface
5440 (if (not alternative-interface)
5441 org-goto-interface
5442 (if (eq org-goto-interface 'outline)
5443 'outline-path-completion
5444 'outline)))
5445 (org-goto-start-pos (point))
5446 (selected-point
5447 (if (eq interface 'outline)
5448 (car (org-get-location (current-buffer) org-goto-help))
5449 (nth 3 (org-refile-get-location "Goto: ")))))
5450 (if selected-point
5451 (progn
5452 (org-mark-ring-push org-goto-start-pos)
5453 (goto-char selected-point)
5454 (if (or (org-invisible-p) (org-invisible-p2))
5455 (org-show-context 'org-goto)))
5456 (message "Quit"))))
5458 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5459 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5460 (defvar org-goto-local-auto-isearch-map) ; defined below
5462 (defun org-get-location (buf help)
5463 "Let the user select a location in the Org-mode buffer BUF.
5464 This function uses a recursive edit. It returns the selected position
5465 or nil."
5466 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5467 (isearch-hide-immediately nil)
5468 (isearch-search-fun-function
5469 (lambda () 'org-goto-local-search-headings))
5470 (org-goto-selected-point org-goto-exit-command))
5471 (save-excursion
5472 (save-window-excursion
5473 (delete-other-windows)
5474 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5475 (switch-to-buffer
5476 (condition-case nil
5477 (make-indirect-buffer (current-buffer) "*org-goto*")
5478 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5479 (with-output-to-temp-buffer "*Help*"
5480 (princ help))
5481 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5482 (setq buffer-read-only nil)
5483 (let ((org-startup-truncated t)
5484 (org-startup-folded nil)
5485 (org-startup-align-all-tables nil))
5486 (org-mode)
5487 (org-overview))
5488 (setq buffer-read-only t)
5489 (if (and (boundp 'org-goto-start-pos)
5490 (integer-or-marker-p org-goto-start-pos))
5491 (let ((org-show-hierarchy-above t)
5492 (org-show-siblings t)
5493 (org-show-following-heading t))
5494 (goto-char org-goto-start-pos)
5495 (and (org-invisible-p) (org-show-context)))
5496 (goto-char (point-min)))
5497 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5498 (message "Select location and press RET")
5499 (use-local-map org-goto-map)
5500 (recursive-edit)
5502 (kill-buffer "*org-goto*")
5503 (cons org-goto-selected-point org-goto-exit-command)))
5505 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5506 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5507 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5508 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5510 (defun org-goto-local-search-headings (string bound noerror)
5511 "Search and make sure that any matches are in headlines."
5512 (catch 'return
5513 (while (if isearch-forward
5514 (search-forward string bound noerror)
5515 (search-backward string bound noerror))
5516 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5517 (and (member :headline context)
5518 (not (member :tags context))))
5519 (throw 'return (point))))))
5521 (defun org-goto-local-auto-isearch ()
5522 "Start isearch."
5523 (interactive)
5524 (goto-char (point-min))
5525 (let ((keys (this-command-keys)))
5526 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5527 (isearch-mode t)
5528 (isearch-process-search-char (string-to-char keys)))))
5530 (defun org-goto-ret (&optional arg)
5531 "Finish `org-goto' by going to the new location."
5532 (interactive "P")
5533 (setq org-goto-selected-point (point)
5534 org-goto-exit-command 'return)
5535 (throw 'exit nil))
5537 (defun org-goto-left ()
5538 "Finish `org-goto' by going to the new location."
5539 (interactive)
5540 (if (org-on-heading-p)
5541 (progn
5542 (beginning-of-line 1)
5543 (setq org-goto-selected-point (point)
5544 org-goto-exit-command 'left)
5545 (throw 'exit nil))
5546 (error "Not on a heading")))
5548 (defun org-goto-right ()
5549 "Finish `org-goto' by going to the new location."
5550 (interactive)
5551 (if (org-on-heading-p)
5552 (progn
5553 (setq org-goto-selected-point (point)
5554 org-goto-exit-command 'right)
5555 (throw 'exit nil))
5556 (error "Not on a heading")))
5558 (defun org-goto-quit ()
5559 "Finish `org-goto' without cursor motion."
5560 (interactive)
5561 (setq org-goto-selected-point nil)
5562 (setq org-goto-exit-command 'quit)
5563 (throw 'exit nil))
5565 ;;; Indirect buffer display of subtrees
5567 (defvar org-indirect-dedicated-frame nil
5568 "This is the frame being used for indirect tree display.")
5569 (defvar org-last-indirect-buffer nil)
5571 (defun org-tree-to-indirect-buffer (&optional arg)
5572 "Create indirect buffer and narrow it to current subtree.
5573 With numerical prefix ARG, go up to this level and then take that tree.
5574 If ARG is negative, go up that many levels.
5575 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5576 indirect buffer previously made with this command, to avoid proliferation of
5577 indirect buffers. However, when you call the command with a `C-u' prefix, or
5578 when `org-indirect-buffer-display' is `new-frame', the last buffer
5579 is kept so that you can work with several indirect buffers at the same time.
5580 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5581 requests that a new frame be made for the new buffer, so that the dedicated
5582 frame is not changed."
5583 (interactive "P")
5584 (let ((cbuf (current-buffer))
5585 (cwin (selected-window))
5586 (pos (point))
5587 beg end level heading ibuf)
5588 (save-excursion
5589 (org-back-to-heading t)
5590 (when (numberp arg)
5591 (setq level (org-outline-level))
5592 (if (< arg 0) (setq arg (+ level arg)))
5593 (while (> (setq level (org-outline-level)) arg)
5594 (outline-up-heading 1 t)))
5595 (setq beg (point)
5596 heading (org-get-heading))
5597 (org-end-of-subtree t) (setq end (point)))
5598 (if (and (buffer-live-p org-last-indirect-buffer)
5599 (not (eq org-indirect-buffer-display 'new-frame))
5600 (not arg))
5601 (kill-buffer org-last-indirect-buffer))
5602 (setq ibuf (org-get-indirect-buffer cbuf)
5603 org-last-indirect-buffer ibuf)
5604 (cond
5605 ((or (eq org-indirect-buffer-display 'new-frame)
5606 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5607 (select-frame (make-frame))
5608 (delete-other-windows)
5609 (switch-to-buffer ibuf)
5610 (org-set-frame-title heading))
5611 ((eq org-indirect-buffer-display 'dedicated-frame)
5612 (raise-frame
5613 (select-frame (or (and org-indirect-dedicated-frame
5614 (frame-live-p org-indirect-dedicated-frame)
5615 org-indirect-dedicated-frame)
5616 (setq org-indirect-dedicated-frame (make-frame)))))
5617 (delete-other-windows)
5618 (switch-to-buffer ibuf)
5619 (org-set-frame-title (concat "Indirect: " heading)))
5620 ((eq org-indirect-buffer-display 'current-window)
5621 (switch-to-buffer ibuf))
5622 ((eq org-indirect-buffer-display 'other-window)
5623 (pop-to-buffer ibuf))
5624 (t (error "Invalid value.")))
5625 (if (featurep 'xemacs)
5626 (save-excursion (org-mode) (turn-on-font-lock)))
5627 (narrow-to-region beg end)
5628 (show-all)
5629 (goto-char pos)
5630 (and (window-live-p cwin) (select-window cwin))))
5632 (defun org-get-indirect-buffer (&optional buffer)
5633 (setq buffer (or buffer (current-buffer)))
5634 (let ((n 1) (base (buffer-name buffer)) bname)
5635 (while (buffer-live-p
5636 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5637 (setq n (1+ n)))
5638 (condition-case nil
5639 (make-indirect-buffer buffer bname 'clone)
5640 (error (make-indirect-buffer buffer bname)))))
5642 (defun org-set-frame-title (title)
5643 "Set the title of the current frame to the string TITLE."
5644 ;; FIXME: how to name a single frame in XEmacs???
5645 (unless (featurep 'xemacs)
5646 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5648 ;;;; Structure editing
5650 ;;; Inserting headlines
5652 (defun org-previous-line-empty-p ()
5653 (save-excursion
5654 (and (not (bobp))
5655 (or (beginning-of-line 0) t)
5656 (save-match-data
5657 (looking-at "[ \t]*$")))))
5659 (defun org-insert-heading (&optional force-heading)
5660 "Insert a new heading or item with same depth at point.
5661 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5662 If point is at the beginning of a headline, insert a sibling before the
5663 current headline. If point is not at the beginning, do not split the line,
5664 but create the new headline after the current line."
5665 (interactive "P")
5666 (if (= (buffer-size) 0)
5667 (insert "\n* ")
5668 (when (or force-heading (not (org-insert-item)))
5669 (let* ((empty-line-p nil)
5670 (head (save-excursion
5671 (condition-case nil
5672 (progn
5673 (org-back-to-heading)
5674 (setq empty-line-p (org-previous-line-empty-p))
5675 (match-string 0))
5676 (error "*"))))
5677 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5678 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5679 pos hide-previous previous-pos)
5680 (cond
5681 ((and (org-on-heading-p) (bolp)
5682 (or (bobp)
5683 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5684 ;; insert before the current line
5685 (open-line (if blank 2 1)))
5686 ((and (bolp)
5687 (not org-insert-heading-respect-content)
5688 (or (bobp)
5689 (save-excursion
5690 (backward-char 1) (not (org-invisible-p)))))
5691 ;; insert right here
5692 nil)
5694 ;; somewhere in the line
5695 (save-excursion
5696 (setq previous-pos (point-at-bol))
5697 (end-of-line)
5698 (setq hide-previous (org-invisible-p)))
5699 (and org-insert-heading-respect-content (org-show-subtree))
5700 (let ((split
5701 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5702 (save-excursion
5703 (let ((p (point)))
5704 (goto-char (point-at-bol))
5705 (and (looking-at org-complex-heading-regexp)
5706 (> p (match-beginning 4)))))))
5707 tags pos)
5708 (cond
5709 (org-insert-heading-respect-content
5710 (org-end-of-subtree nil t)
5711 (or (bolp) (newline))
5712 (or (org-previous-line-empty-p)
5713 (and blank (newline)))
5714 (open-line 1))
5715 ((org-on-heading-p)
5716 (when hide-previous
5717 (show-children)
5718 (org-show-entry))
5719 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5720 (setq tags (and (match-end 2) (match-string 2)))
5721 (and (match-end 1)
5722 (delete-region (match-beginning 1) (match-end 1)))
5723 (setq pos (point-at-bol))
5724 (or split (end-of-line 1))
5725 (delete-horizontal-space)
5726 (newline (if blank 2 1))
5727 (when tags
5728 (save-excursion
5729 (goto-char pos)
5730 (end-of-line 1)
5731 (insert " " tags)
5732 (org-set-tags nil 'align))))
5734 (or split (end-of-line 1))
5735 (newline (if blank 2 1)))))))
5736 (insert head) (just-one-space)
5737 (setq pos (point))
5738 (end-of-line 1)
5739 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5740 (when (and org-insert-heading-respect-content hide-previous)
5741 (save-excursion
5742 (goto-char previous-pos)
5743 (hide-subtree)))
5744 (run-hooks 'org-insert-heading-hook)))))
5746 (defun org-get-heading (&optional no-tags)
5747 "Return the heading of the current entry, without the stars."
5748 (save-excursion
5749 (org-back-to-heading t)
5750 (if (looking-at
5751 (if no-tags
5752 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5753 "\\*+[ \t]+\\([^\r\n]*\\)"))
5754 (match-string 1) "")))
5756 (defun org-heading-components ()
5757 "Return the components of the current heading.
5758 This is a list with the following elements:
5759 - the level as an integer
5760 - the reduced level, different if `org-odd-levels-only' is set.
5761 - the TODO keyword, or nil
5762 - the priority character, like ?A, or nil if no priority is given
5763 - the headline text itself, or the tags string if no headline text
5764 - the tags string, or nil."
5765 (save-excursion
5766 (org-back-to-heading t)
5767 (if (looking-at org-complex-heading-regexp)
5768 (list (length (match-string 1))
5769 (org-reduced-level (length (match-string 1)))
5770 (org-match-string-no-properties 2)
5771 (and (match-end 3) (aref (match-string 3) 2))
5772 (org-match-string-no-properties 4)
5773 (org-match-string-no-properties 5)))))
5775 (defun org-get-entry ()
5776 "Get the entry text, after heading, entire subtree."
5777 (save-excursion
5778 (org-back-to-heading t)
5779 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
5781 (defun org-insert-heading-after-current ()
5782 "Insert a new heading with same level as current, after current subtree."
5783 (interactive)
5784 (org-back-to-heading)
5785 (org-insert-heading)
5786 (org-move-subtree-down)
5787 (end-of-line 1))
5789 (defun org-insert-heading-respect-content ()
5790 (interactive)
5791 (let ((org-insert-heading-respect-content t))
5792 (org-insert-heading t)))
5794 (defun org-insert-todo-heading-respect-content (&optional force-state)
5795 (interactive "P")
5796 (let ((org-insert-heading-respect-content t))
5797 (org-insert-todo-heading force-state t)))
5799 (defun org-insert-todo-heading (arg &optional force-heading)
5800 "Insert a new heading with the same level and TODO state as current heading.
5801 If the heading has no TODO state, or if the state is DONE, use the first
5802 state (TODO by default). Also with prefix arg, force first state."
5803 (interactive "P")
5804 (when (or force-heading (not (org-insert-item 'checkbox)))
5805 (org-insert-heading force-heading)
5806 (save-excursion
5807 (org-back-to-heading)
5808 (outline-previous-heading)
5809 (looking-at org-todo-line-regexp))
5810 (let*
5811 ((new-mark-x
5812 (if (or arg
5813 (not (match-beginning 2))
5814 (member (match-string 2) org-done-keywords))
5815 (car org-todo-keywords-1)
5816 (match-string 2)))
5817 (new-mark
5819 (run-hook-with-args-until-success
5820 'org-todo-get-default-hook new-mark-x nil)
5821 new-mark-x)))
5822 (beginning-of-line 1)
5823 (and (looking-at "\\*+ ") (goto-char (match-end 0))
5824 (if org-treat-insert-todo-heading-as-state-change
5825 (org-todo new-mark)
5826 (insert new-mark " "))))
5827 (when org-provide-todo-statistics
5828 (org-update-parent-todo-statistics))))
5830 (defun org-insert-subheading (arg)
5831 "Insert a new subheading and demote it.
5832 Works for outline headings and for plain lists alike."
5833 (interactive "P")
5834 (org-insert-heading arg)
5835 (cond
5836 ((org-on-heading-p) (org-do-demote))
5837 ((org-at-item-p) (org-indent-item 1))))
5839 (defun org-insert-todo-subheading (arg)
5840 "Insert a new subheading with TODO keyword or checkbox and demote it.
5841 Works for outline headings and for plain lists alike."
5842 (interactive "P")
5843 (org-insert-todo-heading arg)
5844 (cond
5845 ((org-on-heading-p) (org-do-demote))
5846 ((org-at-item-p) (org-indent-item 1))))
5848 ;;; Promotion and Demotion
5850 (defvar org-after-demote-entry-hook nil
5851 "Hook run after an entry has been demoted.
5852 The cursor will be at the beginning of the entry.
5853 When a subtree is being demoted, the hook will be called for each node.")
5855 (defvar org-after-promote-entry-hook nil
5856 "Hook run after an entry has been promoted.
5857 The cursor will be at the beginning of the entry.
5858 When a subtree is being promoted, the hook will be called for each node.")
5860 (defun org-promote-subtree ()
5861 "Promote the entire subtree.
5862 See also `org-promote'."
5863 (interactive)
5864 (save-excursion
5865 (org-map-tree 'org-promote))
5866 (org-fix-position-after-promote))
5868 (defun org-demote-subtree ()
5869 "Demote the entire subtree. See `org-demote'.
5870 See also `org-promote'."
5871 (interactive)
5872 (save-excursion
5873 (org-map-tree 'org-demote))
5874 (org-fix-position-after-promote))
5877 (defun org-do-promote ()
5878 "Promote the current heading higher up the tree.
5879 If the region is active in `transient-mark-mode', promote all headings
5880 in the region."
5881 (interactive)
5882 (save-excursion
5883 (if (org-region-active-p)
5884 (org-map-region 'org-promote (region-beginning) (region-end))
5885 (org-promote)))
5886 (org-fix-position-after-promote))
5888 (defun org-do-demote ()
5889 "Demote the current heading lower down the tree.
5890 If the region is active in `transient-mark-mode', demote all headings
5891 in the region."
5892 (interactive)
5893 (save-excursion
5894 (if (org-region-active-p)
5895 (org-map-region 'org-demote (region-beginning) (region-end))
5896 (org-demote)))
5897 (org-fix-position-after-promote))
5899 (defun org-fix-position-after-promote ()
5900 "Make sure that after pro/demotion cursor position is right."
5901 (let ((pos (point)))
5902 (when (save-excursion
5903 (beginning-of-line 1)
5904 (looking-at org-todo-line-regexp)
5905 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5906 (cond ((eobp) (insert " "))
5907 ((eolp) (insert " "))
5908 ((equal (char-after) ?\ ) (forward-char 1))))))
5910 (defun org-reduced-level (l)
5911 "Compute the effective level of a heading.
5912 This takes into account the setting of `org-odd-levels-only'."
5913 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5915 (defun org-get-valid-level (level &optional change)
5916 "Rectify a level change under the influence of `org-odd-levels-only'
5917 LEVEL is a current level, CHANGE is by how much the level should be
5918 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5919 even level numbers will become the next higher odd number."
5920 (if org-odd-levels-only
5921 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5922 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5923 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5924 (max 1 (+ level (or change 0)))))
5926 (if (boundp 'define-obsolete-function-alias)
5927 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5928 (define-obsolete-function-alias 'org-get-legal-level
5929 'org-get-valid-level)
5930 (define-obsolete-function-alias 'org-get-legal-level
5931 'org-get-valid-level "23.1")))
5933 (defun org-promote ()
5934 "Promote the current heading higher up the tree.
5935 If the region is active in `transient-mark-mode', promote all headings
5936 in the region."
5937 (org-back-to-heading t)
5938 (let* ((level (save-match-data (funcall outline-level)))
5939 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5940 (diff (abs (- level (length up-head) -1))))
5941 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5942 (replace-match up-head nil t)
5943 ;; Fixup tag positioning
5944 (and org-auto-align-tags (org-set-tags nil t))
5945 (if org-adapt-indentation (org-fixup-indentation (- diff)))
5946 (run-hooks 'org-after-promote-entry-hook)))
5948 (defun org-demote ()
5949 "Demote the current heading lower down the tree.
5950 If the region is active in `transient-mark-mode', demote all headings
5951 in the region."
5952 (org-back-to-heading t)
5953 (let* ((level (save-match-data (funcall outline-level)))
5954 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5955 (diff (abs (- level (length down-head) -1))))
5956 (replace-match down-head nil t)
5957 ;; Fixup tag positioning
5958 (and org-auto-align-tags (org-set-tags nil t))
5959 (if org-adapt-indentation (org-fixup-indentation diff))
5960 (run-hooks 'org-after-demote-entry-hook)))
5962 (defun org-map-tree (fun)
5963 "Call FUN for every heading underneath the current one."
5964 (org-back-to-heading)
5965 (let ((level (funcall outline-level)))
5966 (save-excursion
5967 (funcall fun)
5968 (while (and (progn
5969 (outline-next-heading)
5970 (> (funcall outline-level) level))
5971 (not (eobp)))
5972 (funcall fun)))))
5974 (defun org-map-region (fun beg end)
5975 "Call FUN for every heading between BEG and END."
5976 (let ((org-ignore-region t))
5977 (save-excursion
5978 (setq end (copy-marker end))
5979 (goto-char beg)
5980 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5981 (< (point) end))
5982 (funcall fun))
5983 (while (and (progn
5984 (outline-next-heading)
5985 (< (point) end))
5986 (not (eobp)))
5987 (funcall fun)))))
5989 (defun org-fixup-indentation (diff)
5990 "Change the indentation in the current entry by DIFF
5991 However, if any line in the current entry has no indentation, or if it
5992 would end up with no indentation after the change, nothing at all is done."
5993 (save-excursion
5994 (let ((end (save-excursion (outline-next-heading)
5995 (point-marker)))
5996 (prohibit (if (> diff 0)
5997 "^\\S-"
5998 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5999 col)
6000 (unless (save-excursion (end-of-line 1)
6001 (re-search-forward prohibit end t))
6002 (while (and (< (point) end)
6003 (re-search-forward "^[ \t]+" end t))
6004 (goto-char (match-end 0))
6005 (setq col (current-column))
6006 (if (< diff 0) (replace-match ""))
6007 (org-indent-to-column (+ diff col))))
6008 (move-marker end nil))))
6010 (defun org-convert-to-odd-levels ()
6011 "Convert an org-mode file with all levels allowed to one with odd levels.
6012 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6013 level 5 etc."
6014 (interactive)
6015 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6016 (let ((org-odd-levels-only nil) n)
6017 (save-excursion
6018 (goto-char (point-min))
6019 (while (re-search-forward "^\\*\\*+ " nil t)
6020 (setq n (- (length (match-string 0)) 2))
6021 (while (>= (setq n (1- n)) 0)
6022 (org-demote))
6023 (end-of-line 1))))))
6026 (defun org-convert-to-oddeven-levels ()
6027 "Convert an org-mode file with only odd levels to one with odd and even levels.
6028 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6029 section with an even level, conversion would destroy the structure of the file. An error
6030 is signaled in this case."
6031 (interactive)
6032 (goto-char (point-min))
6033 ;; First check if there are no even levels
6034 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6035 (org-show-context t)
6036 (error "Not all levels are odd in this file. Conversion not possible."))
6037 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6038 (let ((org-odd-levels-only nil) n)
6039 (save-excursion
6040 (goto-char (point-min))
6041 (while (re-search-forward "^\\*\\*+ " nil t)
6042 (setq n (/ (1- (length (match-string 0))) 2))
6043 (while (>= (setq n (1- n)) 0)
6044 (org-promote))
6045 (end-of-line 1))))))
6047 (defun org-tr-level (n)
6048 "Make N odd if required."
6049 (if org-odd-levels-only (1+ (/ n 2)) n))
6051 ;;; Vertical tree motion, cutting and pasting of subtrees
6053 (defun org-move-subtree-up (&optional arg)
6054 "Move the current subtree up past ARG headlines of the same level."
6055 (interactive "p")
6056 (org-move-subtree-down (- (prefix-numeric-value arg))))
6058 (defun org-move-subtree-down (&optional arg)
6059 "Move the current subtree down past ARG headlines of the same level."
6060 (interactive "p")
6061 (setq arg (prefix-numeric-value arg))
6062 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6063 'outline-get-last-sibling))
6064 (ins-point (make-marker))
6065 (cnt (abs arg))
6066 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6067 ;; Select the tree
6068 (org-back-to-heading)
6069 (setq beg0 (point))
6070 (save-excursion
6071 (setq ne-beg (org-back-over-empty-lines))
6072 (setq beg (point)))
6073 (save-match-data
6074 (save-excursion (outline-end-of-heading)
6075 (setq folded (org-invisible-p)))
6076 (outline-end-of-subtree))
6077 (outline-next-heading)
6078 (setq ne-end (org-back-over-empty-lines))
6079 (setq end (point))
6080 (goto-char beg0)
6081 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6082 ;; include less whitespace
6083 (save-excursion
6084 (goto-char beg)
6085 (forward-line (- ne-beg ne-end))
6086 (setq beg (point))))
6087 ;; Find insertion point, with error handling
6088 (while (> cnt 0)
6089 (or (and (funcall movfunc) (looking-at outline-regexp))
6090 (progn (goto-char beg0)
6091 (error "Cannot move past superior level or buffer limit")))
6092 (setq cnt (1- cnt)))
6093 (if (> arg 0)
6094 ;; Moving forward - still need to move over subtree
6095 (progn (org-end-of-subtree t t)
6096 (save-excursion
6097 (org-back-over-empty-lines)
6098 (or (bolp) (newline)))))
6099 (setq ne-ins (org-back-over-empty-lines))
6100 (move-marker ins-point (point))
6101 (setq txt (buffer-substring beg end))
6102 (org-save-markers-in-region beg end)
6103 (delete-region beg end)
6104 (org-remove-empty-overlays-at beg)
6105 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6106 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6107 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6108 (let ((bbb (point)))
6109 (insert-before-markers txt)
6110 (org-reinstall-markers-in-region bbb)
6111 (move-marker ins-point bbb))
6112 (or (bolp) (insert "\n"))
6113 (setq ins-end (point))
6114 (goto-char ins-point)
6115 (org-skip-whitespace)
6116 (when (and (< arg 0)
6117 (org-first-sibling-p)
6118 (> ne-ins ne-beg))
6119 ;; Move whitespace back to beginning
6120 (save-excursion
6121 (goto-char ins-end)
6122 (let ((kill-whole-line t))
6123 (kill-line (- ne-ins ne-beg)) (point)))
6124 (insert (make-string (- ne-ins ne-beg) ?\n)))
6125 (move-marker ins-point nil)
6126 (if folded
6127 (hide-subtree)
6128 (org-show-entry)
6129 (show-children)
6130 (org-cycle-hide-drawers 'children))
6131 (org-clean-visibility-after-subtree-move)))
6133 (defvar org-subtree-clip ""
6134 "Clipboard for cut and paste of subtrees.
6135 This is actually only a copy of the kill, because we use the normal kill
6136 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6138 (defvar org-subtree-clip-folded nil
6139 "Was the last copied subtree folded?
6140 This is used to fold the tree back after pasting.")
6142 (defun org-cut-subtree (&optional n)
6143 "Cut the current subtree into the clipboard.
6144 With prefix arg N, cut this many sequential subtrees.
6145 This is a short-hand for marking the subtree and then cutting it."
6146 (interactive "p")
6147 (org-copy-subtree n 'cut))
6149 (defun org-copy-subtree (&optional n cut force-store-markers)
6150 "Cut the current subtree into the clipboard.
6151 With prefix arg N, cut this many sequential subtrees.
6152 This is a short-hand for marking the subtree and then copying it.
6153 If CUT is non-nil, actually cut the subtree.
6154 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6155 of some markers in the region, even if CUT is non-nil. This is
6156 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6157 (interactive "p")
6158 (let (beg end folded (beg0 (point)))
6159 (if (interactive-p)
6160 (org-back-to-heading nil) ; take what looks like a subtree
6161 (org-back-to-heading t)) ; take what is really there
6162 (org-back-over-empty-lines)
6163 (setq beg (point))
6164 (skip-chars-forward " \t\r\n")
6165 (save-match-data
6166 (save-excursion (outline-end-of-heading)
6167 (setq folded (org-invisible-p)))
6168 (condition-case nil
6169 (org-forward-same-level (1- n) t)
6170 (error nil))
6171 (org-end-of-subtree t t))
6172 (org-back-over-empty-lines)
6173 (setq end (point))
6174 (goto-char beg0)
6175 (when (> end beg)
6176 (setq org-subtree-clip-folded folded)
6177 (when (or cut force-store-markers)
6178 (org-save-markers-in-region beg end))
6179 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6180 (setq org-subtree-clip (current-kill 0))
6181 (message "%s: Subtree(s) with %d characters"
6182 (if cut "Cut" "Copied")
6183 (length org-subtree-clip)))))
6185 (defun org-paste-subtree (&optional level tree for-yank)
6186 "Paste the clipboard as a subtree, with modification of headline level.
6187 The entire subtree is promoted or demoted in order to match a new headline
6188 level.
6190 If the cursor is at the beginning of a headline, the same level as
6191 that headline is used to paste the tree
6193 If not, the new level is derived from the *visible* headings
6194 before and after the insertion point, and taken to be the inferior headline
6195 level of the two. So if the previous visible heading is level 3 and the
6196 next is level 4 (or vice versa), level 4 will be used for insertion.
6197 This makes sure that the subtree remains an independent subtree and does
6198 not swallow low level entries.
6200 You can also force a different level, either by using a numeric prefix
6201 argument, or by inserting the heading marker by hand. For example, if the
6202 cursor is after \"*****\", then the tree will be shifted to level 5.
6204 If optional TREE is given, use this text instead of the kill ring.
6206 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6207 move back over whitespace before inserting, and move point to the end of
6208 the inserted text when done."
6209 (interactive "P")
6210 (setq tree (or tree (and kill-ring (current-kill 0))))
6211 (unless (org-kill-is-subtree-p tree)
6212 (error "%s"
6213 (substitute-command-keys
6214 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6215 (let* ((visp (not (org-invisible-p)))
6216 (txt tree)
6217 (^re (concat "^\\(" outline-regexp "\\)"))
6218 (re (concat "\\(" outline-regexp "\\)"))
6219 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6221 (old-level (if (string-match ^re txt)
6222 (- (match-end 0) (match-beginning 0) 1)
6223 -1))
6224 (force-level (cond (level (prefix-numeric-value level))
6225 ((and (looking-at "[ \t]*$")
6226 (string-match
6227 ^re_ (buffer-substring
6228 (point-at-bol) (point))))
6229 (- (match-end 1) (match-beginning 1)))
6230 ((and (bolp)
6231 (looking-at org-outline-regexp))
6232 (- (match-end 0) (point) 1))
6233 (t nil)))
6234 (previous-level (save-excursion
6235 (condition-case nil
6236 (progn
6237 (outline-previous-visible-heading 1)
6238 (if (looking-at re)
6239 (- (match-end 0) (match-beginning 0) 1)
6241 (error 1))))
6242 (next-level (save-excursion
6243 (condition-case nil
6244 (progn
6245 (or (looking-at outline-regexp)
6246 (outline-next-visible-heading 1))
6247 (if (looking-at re)
6248 (- (match-end 0) (match-beginning 0) 1)
6250 (error 1))))
6251 (new-level (or force-level (max previous-level next-level)))
6252 (shift (if (or (= old-level -1)
6253 (= new-level -1)
6254 (= old-level new-level))
6256 (- new-level old-level)))
6257 (delta (if (> shift 0) -1 1))
6258 (func (if (> shift 0) 'org-demote 'org-promote))
6259 (org-odd-levels-only nil)
6260 beg end newend)
6261 ;; Remove the forced level indicator
6262 (if force-level
6263 (delete-region (point-at-bol) (point)))
6264 ;; Paste
6265 (beginning-of-line 1)
6266 (unless for-yank (org-back-over-empty-lines))
6267 (setq beg (point))
6268 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6269 (insert-before-markers txt)
6270 (unless (string-match "\n\\'" txt) (insert "\n"))
6271 (setq newend (point))
6272 (org-reinstall-markers-in-region beg)
6273 (setq end (point))
6274 (goto-char beg)
6275 (skip-chars-forward " \t\n\r")
6276 (setq beg (point))
6277 (if (and (org-invisible-p) visp)
6278 (save-excursion (outline-show-heading)))
6279 ;; Shift if necessary
6280 (unless (= shift 0)
6281 (save-restriction
6282 (narrow-to-region beg end)
6283 (while (not (= shift 0))
6284 (org-map-region func (point-min) (point-max))
6285 (setq shift (+ delta shift)))
6286 (goto-char (point-min))
6287 (setq newend (point-max))))
6288 (when (or (interactive-p) for-yank)
6289 (message "Clipboard pasted as level %d subtree" new-level))
6290 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6291 kill-ring
6292 (eq org-subtree-clip (current-kill 0))
6293 org-subtree-clip-folded)
6294 ;; The tree was folded before it was killed/copied
6295 (hide-subtree))
6296 (and for-yank (goto-char newend))))
6298 (defun org-kill-is-subtree-p (&optional txt)
6299 "Check if the current kill is an outline subtree, or a set of trees.
6300 Returns nil if kill does not start with a headline, or if the first
6301 headline level is not the largest headline level in the tree.
6302 So this will actually accept several entries of equal levels as well,
6303 which is OK for `org-paste-subtree'.
6304 If optional TXT is given, check this string instead of the current kill."
6305 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6306 (start-level (and kill
6307 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6308 org-outline-regexp "\\)")
6309 kill)
6310 (- (match-end 2) (match-beginning 2) 1)))
6311 (re (concat "^" org-outline-regexp))
6312 (start (1+ (or (match-beginning 2) -1))))
6313 (if (not start-level)
6314 (progn
6315 nil) ;; does not even start with a heading
6316 (catch 'exit
6317 (while (setq start (string-match re kill (1+ start)))
6318 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6319 (throw 'exit nil)))
6320 t))))
6322 (defvar org-markers-to-move nil
6323 "Markers that should be moved with a cut-and-paste operation.
6324 Those markers are stored together with their positions relative to
6325 the start of the region.")
6327 (defun org-save-markers-in-region (beg end)
6328 "Check markers in region.
6329 If these markers are between BEG and END, record their position relative
6330 to BEG, so that after moving the block of text, we can put the markers back
6331 into place.
6332 This function gets called just before an entry or tree gets cut from the
6333 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6334 called immediately, to move the markers with the entries."
6335 (setq org-markers-to-move nil)
6336 (when (featurep 'org-clock)
6337 (org-clock-save-markers-for-cut-and-paste beg end))
6338 (when (featurep 'org-agenda)
6339 (org-agenda-save-markers-for-cut-and-paste beg end)))
6341 (defun org-check-and-save-marker (marker beg end)
6342 "Check if MARKER is between BEG and END.
6343 If yes, remember the marker and the distance to BEG."
6344 (when (and (marker-buffer marker)
6345 (equal (marker-buffer marker) (current-buffer)))
6346 (if (and (>= marker beg) (< marker end))
6347 (push (cons marker (- marker beg)) org-markers-to-move))))
6349 (defun org-reinstall-markers-in-region (beg)
6350 "Move all remembered markers to their position relative to BEG."
6351 (mapc (lambda (x)
6352 (move-marker (car x) (+ beg (cdr x))))
6353 org-markers-to-move)
6354 (setq org-markers-to-move nil))
6356 (defun org-narrow-to-subtree ()
6357 "Narrow buffer to the current subtree."
6358 (interactive)
6359 (save-excursion
6360 (save-match-data
6361 (narrow-to-region
6362 (progn (org-back-to-heading t) (point))
6363 (progn (org-end-of-subtree t) (point))))))
6365 (defun org-clone-subtree-with-time-shift (n &optional shift)
6366 "Clone the task (subtree) at point N times.
6367 The clones will be inserted as siblings.
6369 In interactive use, the user will be prompted for the number of clones
6370 to be produced, and for a time SHIFT, which may be a repeater as used
6371 in time stamps, for example `+3d'.
6373 When a valid repeater is given and the entry contains any time stamps,
6374 the clones will become a sequence in time, with time stamps in the
6375 subtree shifted for each clone produced. If SHIFT is nil or the
6376 empty string, time stamps will be left alone.
6378 If the original subtree did contain time stamps with a repeater,
6379 the following will happen:
6380 - the repeater will be removed in each clone
6381 - an additional clone will be produced, with the current, unshifted
6382 date(s) in the entry.
6383 - the original entry will be placed *after* all the clones, with
6384 repeater intact.
6385 - the start days in the repeater in the original entry will be shifted
6386 to past the last clone.
6387 I this way you can spell out a number of instances of a repeating task,
6388 and still retain the repeater to cover future instances of the task."
6389 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6390 (let (beg end template task
6391 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6392 (if (not (and (integerp n) (> n 0)))
6393 (error "Invalid number of replications %s" n))
6394 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6395 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6396 shift)))
6397 (error "Invalid shift specification %s" shift))
6398 (when doshift
6399 (setq shift-n (string-to-number (match-string 1 shift))
6400 shift-what (cdr (assoc (match-string 2 shift)
6401 '(("d" . day) ("w" . week)
6402 ("m" . month) ("y" . year))))))
6403 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6404 (setq nmin 1 nmax n)
6405 (org-back-to-heading t)
6406 (setq beg (point))
6407 (org-end-of-subtree t t)
6408 (setq end (point))
6409 (setq template (buffer-substring beg end))
6410 (when (and doshift
6411 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6412 (delete-region beg end)
6413 (setq end beg)
6414 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6415 (goto-char end)
6416 (loop for n from nmin to nmax do
6417 (if (not doshift)
6418 (setq task template)
6419 (with-temp-buffer
6420 (insert template)
6421 (org-mode)
6422 (goto-char (point-min))
6423 (while (re-search-forward org-ts-regexp-both nil t)
6424 (org-timestamp-change (* n shift-n) shift-what))
6425 (unless (= n n-no-remove)
6426 (goto-char (point-min))
6427 (while (re-search-forward org-ts-regexp nil t)
6428 (save-excursion
6429 (goto-char (match-beginning 0))
6430 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6431 (delete-region (match-beginning 1) (match-end 1))))))
6432 (setq task (buffer-string))))
6433 (insert task))
6434 (goto-char beg)))
6436 ;;; Outline Sorting
6438 (defun org-sort (with-case)
6439 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6440 Optional argument WITH-CASE means sort case-sensitively.
6441 With a double prefix argument, also remove duplicate entries."
6442 (interactive "P")
6443 (if (org-at-table-p)
6444 (org-call-with-arg 'org-table-sort-lines with-case)
6445 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6447 (defun org-sort-remove-invisible (s)
6448 (remove-text-properties 0 (length s) org-rm-props s)
6449 (while (string-match org-bracket-link-regexp s)
6450 (setq s (replace-match (if (match-end 2)
6451 (match-string 3 s)
6452 (match-string 1 s)) t t s)))
6455 (defvar org-priority-regexp) ; defined later in the file
6457 (defvar org-after-sorting-entries-or-items-hook nil
6458 "Hook that is run after a bunch of entries or items have been sorted.
6459 When children are sorted, the cursor is in the parent line when this
6460 hook gets called. When a region or a plain list is sorted, the cursor
6461 will be in the first entry of the sorted region/list.")
6463 (defun org-sort-entries-or-items
6464 (&optional with-case sorting-type getkey-func compare-func property)
6465 "Sort entries on a certain level of an outline tree, or plain list items.
6466 If there is an active region, the entries in the region are sorted.
6467 Else, if the cursor is before the first entry, sort the top-level items.
6468 Else, the children of the entry at point are sorted.
6469 If the cursor is at the first item in a plain list, the list items will be
6470 sorted.
6472 Sorting can be alphabetically, numerically, by date/time as given by
6473 a time stamp, by a property or by priority.
6475 The command prompts for the sorting type unless it has been given to the
6476 function through the SORTING-TYPE argument, which needs to a character,
6477 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6478 precise meaning of each character:
6480 n Numerically, by converting the beginning of the entry/item to a number.
6481 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6482 t By date/time, either the first active time stamp in the entry, or, if
6483 none exist, by the first inactive one.
6484 In items, only the first line will be chekced.
6485 s By the scheduled date/time.
6486 d By deadline date/time.
6487 c By creation time, which is assumed to be the first inactive time stamp
6488 at the beginning of a line.
6489 p By priority according to the cookie.
6490 r By the value of a property.
6492 Capital letters will reverse the sort order.
6494 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6495 called with point at the beginning of the record. It must return either
6496 a string or a number that should serve as the sorting key for that record.
6498 Comparing entries ignores case by default. However, with an optional argument
6499 WITH-CASE, the sorting considers case as well."
6500 (interactive "P")
6501 (let ((case-func (if with-case 'identity 'downcase))
6502 start beg end stars re re2
6503 txt what tmp plain-list-p)
6504 ;; Find beginning and end of region to sort
6505 (cond
6506 ((org-region-active-p)
6507 ;; we will sort the region
6508 (setq end (region-end)
6509 what "region")
6510 (goto-char (region-beginning))
6511 (if (not (org-on-heading-p)) (outline-next-heading))
6512 (setq start (point)))
6513 ((org-at-item-p)
6514 ;; we will sort this plain list
6515 (org-beginning-of-item-list) (setq start (point))
6516 (org-end-of-item-list) (setq end (point))
6517 (goto-char start)
6518 (setq plain-list-p t
6519 what "plain list"))
6520 ((or (org-on-heading-p)
6521 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6522 ;; we will sort the children of the current headline
6523 (org-back-to-heading)
6524 (setq start (point)
6525 end (progn (org-end-of-subtree t t)
6526 (org-back-over-empty-lines)
6527 (point))
6528 what "children")
6529 (goto-char start)
6530 (show-subtree)
6531 (outline-next-heading))
6533 ;; we will sort the top-level entries in this file
6534 (goto-char (point-min))
6535 (or (org-on-heading-p) (outline-next-heading))
6536 (setq start (point) end (point-max) what "top-level")
6537 (goto-char start)
6538 (show-all)))
6540 (setq beg (point))
6541 (if (>= beg end) (error "Nothing to sort"))
6543 (unless plain-list-p
6544 (looking-at "\\(\\*+\\)")
6545 (setq stars (match-string 1)
6546 re (concat "^" (regexp-quote stars) " +")
6547 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6548 txt (buffer-substring beg end))
6549 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6550 (if (and (not (equal stars "*")) (string-match re2 txt))
6551 (error "Region to sort contains a level above the first entry")))
6553 (unless sorting-type
6554 (message
6555 (if plain-list-p
6556 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6557 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
6558 [t]ime [s]cheduled [d]eadline [c]reated
6559 A/N/T/S/D/C/P/O/F means reversed:")
6560 what)
6561 (setq sorting-type (read-char-exclusive))
6563 (and (= (downcase sorting-type) ?f)
6564 (setq getkey-func
6565 (org-icompleting-read "Sort using function: "
6566 obarray 'fboundp t nil nil))
6567 (setq getkey-func (intern getkey-func)))
6569 (and (= (downcase sorting-type) ?r)
6570 (setq property
6571 (org-icompleting-read "Property: "
6572 (mapcar 'list (org-buffer-property-keys t))
6573 nil t))))
6575 (message "Sorting entries...")
6577 (save-restriction
6578 (narrow-to-region start end)
6580 (let ((dcst (downcase sorting-type))
6581 (case-fold-search nil)
6582 (now (current-time)))
6583 (sort-subr
6584 (/= dcst sorting-type)
6585 ;; This function moves to the beginning character of the "record" to
6586 ;; be sorted.
6587 (if plain-list-p
6588 (lambda nil
6589 (if (org-at-item-p) t (goto-char (point-max))))
6590 (lambda nil
6591 (if (re-search-forward re nil t)
6592 (goto-char (match-beginning 0))
6593 (goto-char (point-max)))))
6594 ;; This function moves to the last character of the "record" being
6595 ;; sorted.
6596 (if plain-list-p
6597 'org-end-of-item
6598 (lambda nil
6599 (save-match-data
6600 (condition-case nil
6601 (outline-forward-same-level 1)
6602 (error
6603 (goto-char (point-max)))))))
6605 ;; This function returns the value that gets sorted against.
6606 (if plain-list-p
6607 (lambda nil
6608 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6609 (cond
6610 ((= dcst ?n)
6611 (string-to-number (buffer-substring (match-end 0)
6612 (point-at-eol))))
6613 ((= dcst ?a)
6614 (buffer-substring (match-end 0) (point-at-eol)))
6615 ((= dcst ?t)
6616 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
6617 (re-search-forward org-ts-regexp-both
6618 (point-at-eol) t))
6619 (org-time-string-to-seconds (match-string 0))
6620 (time-to-seconds now)))
6621 ((= dcst ?f)
6622 (if getkey-func
6623 (progn
6624 (setq tmp (funcall getkey-func))
6625 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6626 tmp)
6627 (error "Invalid key function `%s'" getkey-func)))
6628 (t (error "Invalid sorting type `%c'" sorting-type)))))
6629 (lambda nil
6630 (cond
6631 ((= dcst ?n)
6632 (if (looking-at org-complex-heading-regexp)
6633 (string-to-number (match-string 4))
6634 nil))
6635 ((= dcst ?a)
6636 (if (looking-at org-complex-heading-regexp)
6637 (funcall case-func (match-string 4))
6638 nil))
6639 ((= dcst ?t)
6640 (let ((end (save-excursion (outline-next-heading) (point))))
6641 (if (or (re-search-forward org-ts-regexp end t)
6642 (re-search-forward org-ts-regexp-both end t))
6643 (org-time-string-to-seconds (match-string 0))
6644 (time-to-seconds now))))
6645 ((= dcst ?c)
6646 (let ((end (save-excursion (outline-next-heading) (point))))
6647 (if (re-search-forward
6648 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
6649 end t)
6650 (org-time-string-to-seconds (match-string 0))
6651 (time-to-seconds now))))
6652 ((= dcst ?s)
6653 (let ((end (save-excursion (outline-next-heading) (point))))
6654 (if (re-search-forward org-scheduled-time-regexp end t)
6655 (org-time-string-to-seconds (match-string 1))
6656 (time-to-seconds now))))
6657 ((= dcst ?d)
6658 (let ((end (save-excursion (outline-next-heading) (point))))
6659 (if (re-search-forward org-deadline-time-regexp end t)
6660 (org-time-string-to-seconds (match-string 1))
6661 (time-to-seconds now))))
6662 ((= dcst ?p)
6663 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6664 (string-to-char (match-string 2))
6665 org-default-priority))
6666 ((= dcst ?r)
6667 (or (org-entry-get nil property) ""))
6668 ((= dcst ?o)
6669 (if (looking-at org-complex-heading-regexp)
6670 (- 9999 (length (member (match-string 2)
6671 org-todo-keywords-1)))))
6672 ((= dcst ?f)
6673 (if getkey-func
6674 (progn
6675 (setq tmp (funcall getkey-func))
6676 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6677 tmp)
6678 (error "Invalid key function `%s'" getkey-func)))
6679 (t (error "Invalid sorting type `%c'" sorting-type)))))
6681 (cond
6682 ((= dcst ?a) 'string<)
6683 ((= dcst ?f) compare-func)
6684 ((member dcst '(?p ?t ?s ?d ?c)) '<)
6685 (t nil)))))
6686 (run-hooks 'org-after-sorting-entries-or-items-hook)
6687 (message "Sorting entries...done")))
6689 (defun org-do-sort (table what &optional with-case sorting-type)
6690 "Sort TABLE of WHAT according to SORTING-TYPE.
6691 The user will be prompted for the SORTING-TYPE if the call to this
6692 function does not specify it. WHAT is only for the prompt, to indicate
6693 what is being sorted. The sorting key will be extracted from
6694 the car of the elements of the table.
6695 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6696 (unless sorting-type
6697 (message
6698 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6699 what)
6700 (setq sorting-type (read-char-exclusive)))
6701 (let ((dcst (downcase sorting-type))
6702 extractfun comparefun)
6703 ;; Define the appropriate functions
6704 (cond
6705 ((= dcst ?n)
6706 (setq extractfun 'string-to-number
6707 comparefun (if (= dcst sorting-type) '< '>)))
6708 ((= dcst ?a)
6709 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6710 (lambda(x) (downcase (org-sort-remove-invisible x))))
6711 comparefun (if (= dcst sorting-type)
6712 'string<
6713 (lambda (a b) (and (not (string< a b))
6714 (not (string= a b)))))))
6715 ((= dcst ?t)
6716 (setq extractfun
6717 (lambda (x)
6718 (if (or (string-match org-ts-regexp x)
6719 (string-match org-ts-regexp-both x))
6720 (time-to-seconds
6721 (org-time-string-to-time (match-string 0 x)))
6723 comparefun (if (= dcst sorting-type) '< '>)))
6724 (t (error "Invalid sorting type `%c'" sorting-type)))
6726 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6727 table)
6728 (lambda (a b) (funcall comparefun (car a) (car b))))))
6731 ;;; The orgstruct minor mode
6733 ;; Define a minor mode which can be used in other modes in order to
6734 ;; integrate the org-mode structure editing commands.
6736 ;; This is really a hack, because the org-mode structure commands use
6737 ;; keys which normally belong to the major mode. Here is how it
6738 ;; works: The minor mode defines all the keys necessary to operate the
6739 ;; structure commands, but wraps the commands into a function which
6740 ;; tests if the cursor is currently at a headline or a plain list
6741 ;; item. If that is the case, the structure command is used,
6742 ;; temporarily setting many Org-mode variables like regular
6743 ;; expressions for filling etc. However, when any of those keys is
6744 ;; used at a different location, function uses `key-binding' to look
6745 ;; up if the key has an associated command in another currently active
6746 ;; keymap (minor modes, major mode, global), and executes that
6747 ;; command. There might be problems if any of the keys is otherwise
6748 ;; used as a prefix key.
6750 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6751 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6752 ;; addresses this by checking explicitly for both bindings.
6754 (defvar orgstruct-mode-map (make-sparse-keymap)
6755 "Keymap for the minor `orgstruct-mode'.")
6757 (defvar org-local-vars nil
6758 "List of local variables, for use by `orgstruct-mode'")
6760 ;;;###autoload
6761 (define-minor-mode orgstruct-mode
6762 "Toggle the minor more `orgstruct-mode'.
6763 This mode is for using Org-mode structure commands in other modes.
6764 The following key behave as if Org-mode was active, if the cursor
6765 is on a headline, or on a plain list item (both in the definition
6766 of Org-mode).
6768 M-up Move entry/item up
6769 M-down Move entry/item down
6770 M-left Promote
6771 M-right Demote
6772 M-S-up Move entry/item up
6773 M-S-down Move entry/item down
6774 M-S-left Promote subtree
6775 M-S-right Demote subtree
6776 M-q Fill paragraph and items like in Org-mode
6777 C-c ^ Sort entries
6778 C-c - Cycle list bullet
6779 TAB Cycle item visibility
6780 M-RET Insert new heading/item
6781 S-M-RET Insert new TODO heading / Checkbox item
6782 C-c C-c Set tags / toggle checkbox"
6783 nil " OrgStruct" nil
6784 (org-load-modules-maybe)
6785 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6787 ;;;###autoload
6788 (defun turn-on-orgstruct ()
6789 "Unconditionally turn on `orgstruct-mode'."
6790 (orgstruct-mode 1))
6792 (defun orgstruct++-mode (&optional arg)
6793 "Toggle `orgstruct-mode', the enhanced version of it.
6794 In addition to setting orgstruct-mode, this also exports all indentation
6795 and autofilling variables from org-mode into the buffer. It will also
6796 recognize item context in multiline items.
6797 Note that turning off orgstruct-mode will *not* remove the
6798 indentation/paragraph settings. This can only be done by refreshing the
6799 major mode, for example with \\[normal-mode]."
6800 (interactive "P")
6801 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6802 (if (< arg 1)
6803 (orgstruct-mode -1)
6804 (orgstruct-mode 1)
6805 (let (var val)
6806 (mapc
6807 (lambda (x)
6808 (when (string-match
6809 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6810 (symbol-name (car x)))
6811 (setq var (car x) val (nth 1 x))
6812 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6813 org-local-vars)
6814 (org-set-local 'orgstruct-is-++ t))))
6816 (defvar orgstruct-is-++ nil
6817 "Is orgstruct-mode in ++ version in the current-buffer?")
6818 (make-variable-buffer-local 'orgstruct-is-++)
6820 ;;;###autoload
6821 (defun turn-on-orgstruct++ ()
6822 "Unconditionally turn on `orgstruct++-mode'."
6823 (orgstruct++-mode 1))
6825 (defun orgstruct-error ()
6826 "Error when there is no default binding for a structure key."
6827 (interactive)
6828 (error "This key has no function outside structure elements"))
6830 (defun orgstruct-setup ()
6831 "Setup orgstruct keymaps."
6832 (let ((nfunc 0)
6833 (bindings
6834 (list
6835 '([(meta up)] org-metaup)
6836 '([(meta down)] org-metadown)
6837 '([(meta left)] org-metaleft)
6838 '([(meta right)] org-metaright)
6839 '([(meta shift up)] org-shiftmetaup)
6840 '([(meta shift down)] org-shiftmetadown)
6841 '([(meta shift left)] org-shiftmetaleft)
6842 '([(meta shift right)] org-shiftmetaright)
6843 '([?\e (up)] org-metaup)
6844 '([?\e (down)] org-metadown)
6845 '([?\e (left)] org-metaleft)
6846 '([?\e (right)] org-metaright)
6847 '([?\e (shift up)] org-shiftmetaup)
6848 '([?\e (shift down)] org-shiftmetadown)
6849 '([?\e (shift left)] org-shiftmetaleft)
6850 '([?\e (shift right)] org-shiftmetaright)
6851 '([(shift up)] org-shiftup)
6852 '([(shift down)] org-shiftdown)
6853 '([(shift left)] org-shiftleft)
6854 '([(shift right)] org-shiftright)
6855 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6856 '("\M-q" fill-paragraph)
6857 '("\C-c^" org-sort)
6858 '("\C-c-" org-cycle-list-bullet)))
6859 elt key fun cmd)
6860 (while (setq elt (pop bindings))
6861 (setq nfunc (1+ nfunc))
6862 (setq key (org-key (car elt))
6863 fun (nth 1 elt)
6864 cmd (orgstruct-make-binding fun nfunc key))
6865 (org-defkey orgstruct-mode-map key cmd))
6867 ;; Special treatment needed for TAB and RET
6868 (org-defkey orgstruct-mode-map [(tab)]
6869 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6870 (org-defkey orgstruct-mode-map "\C-i"
6871 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6873 (org-defkey orgstruct-mode-map "\M-\C-m"
6874 (orgstruct-make-binding 'org-insert-heading 105
6875 "\M-\C-m" [(meta return)]))
6876 (org-defkey orgstruct-mode-map [(meta return)]
6877 (orgstruct-make-binding 'org-insert-heading 106
6878 [(meta return)] "\M-\C-m"))
6880 (org-defkey orgstruct-mode-map [(shift meta return)]
6881 (orgstruct-make-binding 'org-insert-todo-heading 107
6882 [(meta return)] "\M-\C-m"))
6884 (org-defkey orgstruct-mode-map "\e\C-m"
6885 (orgstruct-make-binding 'org-insert-heading 108
6886 "\e\C-m" [?\e (return)]))
6887 (org-defkey orgstruct-mode-map [?\e (return)]
6888 (orgstruct-make-binding 'org-insert-heading 109
6889 [?\e (return)] "\e\C-m"))
6890 (org-defkey orgstruct-mode-map [?\e (shift return)]
6891 (orgstruct-make-binding 'org-insert-todo-heading 110
6892 [?\e (return)] "\e\C-m"))
6894 (unless org-local-vars
6895 (setq org-local-vars (org-get-local-variables)))
6899 (defun orgstruct-make-binding (fun n &rest keys)
6900 "Create a function for binding in the structure minor mode.
6901 FUN is the command to call inside a table. N is used to create a unique
6902 command name. KEYS are keys that should be checked in for a command
6903 to execute outside of tables."
6904 (eval
6905 (list 'defun
6906 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6907 '(arg)
6908 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6909 "Outside of structure, run the binding of `"
6910 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6911 "'.")
6912 '(interactive "p")
6913 (list 'if
6914 `(org-context-p 'headline 'item
6915 (and orgstruct-is-++
6916 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
6917 'item-body))
6918 (list 'org-run-like-in-org-mode (list 'quote fun))
6919 (list 'let '(orgstruct-mode)
6920 (list 'call-interactively
6921 (append '(or)
6922 (mapcar (lambda (k)
6923 (list 'key-binding k))
6924 keys)
6925 '('orgstruct-error))))))))
6927 (defun org-context-p (&rest contexts)
6928 "Check if local context is any of CONTEXTS.
6929 Possible values in the list of contexts are `table', `headline', and `item'."
6930 (let ((pos (point)))
6931 (goto-char (point-at-bol))
6932 (prog1 (or (and (memq 'table contexts)
6933 (looking-at "[ \t]*|"))
6934 (and (memq 'headline contexts)
6935 ;;????????? (looking-at "\\*+"))
6936 (looking-at outline-regexp))
6937 (and (memq 'item contexts)
6938 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
6939 (and (memq 'item-body contexts)
6940 (org-in-item-p)))
6941 (goto-char pos))))
6943 (defun org-get-local-variables ()
6944 "Return a list of all local variables in an org-mode buffer."
6945 (let (varlist)
6946 (with-current-buffer (get-buffer-create "*Org tmp*")
6947 (erase-buffer)
6948 (org-mode)
6949 (setq varlist (buffer-local-variables)))
6950 (kill-buffer "*Org tmp*")
6951 (delq nil
6952 (mapcar
6953 (lambda (x)
6954 (setq x
6955 (if (symbolp x)
6956 (list x)
6957 (list (car x) (list 'quote (cdr x)))))
6958 (if (string-match
6959 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6960 (symbol-name (car x)))
6961 x nil))
6962 varlist))))
6964 ;;;###autoload
6965 (defun org-run-like-in-org-mode (cmd)
6966 "Run a command, pretending that the current buffer is in Org-mode.
6967 This will temporarily bind local variables that are typically bound in
6968 Org-mode to the values they have in Org-mode, and then interactively
6969 call CMD."
6970 (org-load-modules-maybe)
6971 (unless org-local-vars
6972 (setq org-local-vars (org-get-local-variables)))
6973 (eval (list 'let org-local-vars
6974 (list 'call-interactively (list 'quote cmd)))))
6976 ;;;; Archiving
6978 (defun org-get-category (&optional pos)
6979 "Get the category applying to position POS."
6980 (get-text-property (or pos (point)) 'org-category))
6982 (defun org-refresh-category-properties ()
6983 "Refresh category text properties in the buffer."
6984 (let ((def-cat (cond
6985 ((null org-category)
6986 (if buffer-file-name
6987 (file-name-sans-extension
6988 (file-name-nondirectory buffer-file-name))
6989 "???"))
6990 ((symbolp org-category) (symbol-name org-category))
6991 (t org-category)))
6992 beg end cat pos optionp)
6993 (org-unmodified
6994 (save-excursion
6995 (save-restriction
6996 (widen)
6997 (goto-char (point-min))
6998 (put-text-property (point) (point-max) 'org-category def-cat)
6999 (while (re-search-forward
7000 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7001 (setq pos (match-end 0)
7002 optionp (equal (char-after (match-beginning 0)) ?#)
7003 cat (org-trim (match-string 2)))
7004 (if optionp
7005 (setq beg (point-at-bol) end (point-max))
7006 (org-back-to-heading t)
7007 (setq beg (point) end (org-end-of-subtree t t)))
7008 (put-text-property beg end 'org-category cat)
7009 (goto-char pos)))))))
7012 ;;;; Link Stuff
7014 ;;; Link abbreviations
7016 (defun org-link-expand-abbrev (link)
7017 "Apply replacements as defined in `org-link-abbrev-alist."
7018 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7019 (let* ((key (match-string 1 link))
7020 (as (or (assoc key org-link-abbrev-alist-local)
7021 (assoc key org-link-abbrev-alist)))
7022 (tag (and (match-end 2) (match-string 3 link)))
7023 rpl)
7024 (if (not as)
7025 link
7026 (setq rpl (cdr as))
7027 (cond
7028 ((symbolp rpl) (funcall rpl tag))
7029 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7030 ((string-match "%h" rpl)
7031 (replace-match (url-hexify-string (or tag "")) t t rpl))
7032 (t (concat rpl tag)))))
7033 link))
7035 ;;; Storing and inserting links
7037 (defvar org-insert-link-history nil
7038 "Minibuffer history for links inserted with `org-insert-link'.")
7040 (defvar org-stored-links nil
7041 "Contains the links stored with `org-store-link'.")
7043 (defvar org-store-link-plist nil
7044 "Plist with info about the most recently link created with `org-store-link'.")
7046 (defvar org-link-protocols nil
7047 "Link protocols added to Org-mode using `org-add-link-type'.")
7049 (defvar org-store-link-functions nil
7050 "List of functions that are called to create and store a link.
7051 Each function will be called in turn until one returns a non-nil
7052 value. Each function should check if it is responsible for creating
7053 this link (for example by looking at the major mode).
7054 If not, it must exit and return nil.
7055 If yes, it should return a non-nil value after a calling
7056 `org-store-link-props' with a list of properties and values.
7057 Special properties are:
7059 :type The link prefix. like \"http\". This must be given.
7060 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7061 This is obligatory as well.
7062 :description Optional default description for the second pair
7063 of brackets in an Org-mode link. The user can still change
7064 this when inserting this link into an Org-mode buffer.
7066 In addition to these, any additional properties can be specified
7067 and then used in remember templates.")
7069 (defun org-add-link-type (type &optional follow export)
7070 "Add TYPE to the list of `org-link-types'.
7071 Re-compute all regular expressions depending on `org-link-types'
7073 FOLLOW and EXPORT are two functions.
7075 FOLLOW should take the link path as the single argument and do whatever
7076 is necessary to follow the link, for example find a file or display
7077 a mail message.
7079 EXPORT should format the link path for export to one of the export formats.
7080 It should be a function accepting three arguments:
7082 path the path of the link, the text after the prefix (like \"http:\")
7083 desc the description of the link, if any, nil if there was no description
7084 format the export format, a symbol like `html' or `latex'.
7086 The function may use the FORMAT information to return different values
7087 depending on the format. The return value will be put literally into
7088 the exported file.
7089 Org-mode has a built-in default for exporting links. If you are happy with
7090 this default, there is no need to define an export function for the link
7091 type. For a simple example of an export function, see `org-bbdb.el'."
7092 (add-to-list 'org-link-types type t)
7093 (org-make-link-regexps)
7094 (if (assoc type org-link-protocols)
7095 (setcdr (assoc type org-link-protocols) (list follow export))
7096 (push (list type follow export) org-link-protocols)))
7098 ;;;###autoload
7099 (defun org-store-link (arg)
7100 "\\<org-mode-map>Store an org-link to the current location.
7101 This link is added to `org-stored-links' and can later be inserted
7102 into an org-buffer with \\[org-insert-link].
7104 For some link types, a prefix arg is interpreted:
7105 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7106 For file links, arg negates `org-context-in-file-links'."
7107 (interactive "P")
7108 (org-load-modules-maybe)
7109 (setq org-store-link-plist nil) ; reset
7110 (let ((outline-regexp (org-get-limited-outline-regexp))
7111 link cpltxt desc description search txt custom-id)
7112 (cond
7114 ((run-hook-with-args-until-success 'org-store-link-functions)
7115 (setq link (plist-get org-store-link-plist :link)
7116 desc (or (plist-get org-store-link-plist :description) link)))
7118 ((equal (buffer-name) "*Org Edit Src Example*")
7119 (let (label gc)
7120 (while (or (not label)
7121 (save-excursion
7122 (save-restriction
7123 (widen)
7124 (goto-char (point-min))
7125 (re-search-forward
7126 (regexp-quote (format org-coderef-label-format label))
7127 nil t))))
7128 (when label (message "Label exists already") (sit-for 2))
7129 (setq label (read-string "Code line label: " label)))
7130 (end-of-line 1)
7131 (setq link (format org-coderef-label-format label))
7132 (setq gc (- 79 (length link)))
7133 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7134 (insert link)
7135 (setq link (concat "(" label ")") desc nil)))
7137 ((eq major-mode 'calendar-mode)
7138 (let ((cd (calendar-cursor-to-date)))
7139 (setq link
7140 (format-time-string
7141 (car org-time-stamp-formats)
7142 (apply 'encode-time
7143 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7144 nil nil nil))))
7145 (org-store-link-props :type "calendar" :date cd)))
7147 ((eq major-mode 'w3-mode)
7148 (setq cpltxt (if (and (buffer-name)
7149 (not (string-match "Untitled" (buffer-name))))
7150 (buffer-name)
7151 (url-view-url t))
7152 link (org-make-link (url-view-url t)))
7153 (org-store-link-props :type "w3" :url (url-view-url t)))
7155 ((eq major-mode 'w3m-mode)
7156 (setq cpltxt (or w3m-current-title w3m-current-url)
7157 link (org-make-link w3m-current-url))
7158 (org-store-link-props :type "w3m" :url (url-view-url t)))
7160 ((setq search (run-hook-with-args-until-success
7161 'org-create-file-search-functions))
7162 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7163 "::" search))
7164 (setq cpltxt (or description link)))
7166 ((eq major-mode 'image-mode)
7167 (setq cpltxt (concat "file:"
7168 (abbreviate-file-name buffer-file-name))
7169 link (org-make-link cpltxt))
7170 (org-store-link-props :type "image" :file buffer-file-name))
7172 ((eq major-mode 'dired-mode)
7173 ;; link to the file in the current line
7174 (setq cpltxt (concat "file:"
7175 (abbreviate-file-name
7176 (expand-file-name
7177 (dired-get-filename nil t))))
7178 link (org-make-link cpltxt)))
7180 ((and buffer-file-name (org-mode-p))
7181 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7182 (cond
7183 ((org-in-regexp "<<\\(.*?\\)>>")
7184 (setq cpltxt
7185 (concat "file:"
7186 (abbreviate-file-name buffer-file-name)
7187 "::" (match-string 1))
7188 link (org-make-link cpltxt)))
7189 ((and (featurep 'org-id)
7190 (or (eq org-link-to-org-use-id t)
7191 (and (eq org-link-to-org-use-id 'create-if-interactive)
7192 (interactive-p))
7193 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7194 (interactive-p)
7195 (not custom-id))
7196 (and org-link-to-org-use-id
7197 (condition-case nil
7198 (org-entry-get nil "ID")
7199 (error nil)))))
7200 ;; We can make a link using the ID.
7201 (setq link (condition-case nil
7202 (prog1 (org-id-store-link)
7203 (setq desc (plist-get org-store-link-plist
7204 :description)))
7205 (error
7206 ;; probably before first headline, link to file only
7207 (concat "file:"
7208 (abbreviate-file-name buffer-file-name))))))
7210 ;; Just link to current headline
7211 (setq cpltxt (concat "file:"
7212 (abbreviate-file-name buffer-file-name)))
7213 ;; Add a context search string
7214 (when (org-xor org-context-in-file-links arg)
7215 (setq txt (cond
7216 ((org-on-heading-p) nil)
7217 ((org-region-active-p)
7218 (buffer-substring (region-beginning) (region-end)))
7219 (t nil)))
7220 (when (or (null txt) (string-match "\\S-" txt))
7221 (setq cpltxt
7222 (concat cpltxt "::"
7223 (condition-case nil
7224 (org-make-org-heading-search-string txt)
7225 (error "")))
7226 desc (or (nth 4 (org-heading-components)) "NONE"))))
7227 (if (string-match "::\\'" cpltxt)
7228 (setq cpltxt (substring cpltxt 0 -2)))
7229 (setq link (org-make-link cpltxt)))))
7231 ((buffer-file-name (buffer-base-buffer))
7232 ;; Just link to this file here.
7233 (setq cpltxt (concat "file:"
7234 (abbreviate-file-name
7235 (buffer-file-name (buffer-base-buffer)))))
7236 ;; Add a context string
7237 (when (org-xor org-context-in-file-links arg)
7238 (setq txt (if (org-region-active-p)
7239 (buffer-substring (region-beginning) (region-end))
7240 (buffer-substring (point-at-bol) (point-at-eol))))
7241 ;; Only use search option if there is some text.
7242 (when (string-match "\\S-" txt)
7243 (setq cpltxt
7244 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7245 desc "NONE")))
7246 (setq link (org-make-link cpltxt)))
7248 ((interactive-p)
7249 (error "Cannot link to a buffer which is not visiting a file"))
7251 (t (setq link nil)))
7253 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7254 (setq link (or link cpltxt)
7255 desc (or desc cpltxt))
7256 (if (equal desc "NONE") (setq desc nil))
7258 (if (and (or (interactive-p) executing-kbd-macro) link)
7259 (progn
7260 (setq org-stored-links
7261 (cons (list link desc) org-stored-links))
7262 (message "Stored: %s" (or desc link))
7263 (when custom-id
7264 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7265 "::#" custom-id))
7266 (setq org-stored-links
7267 (cons (list link desc) org-stored-links))))
7268 (and link (org-make-link-string link desc)))))
7270 (defun org-store-link-props (&rest plist)
7271 "Store link properties, extract names and addresses."
7272 (let (x adr)
7273 (when (setq x (plist-get plist :from))
7274 (setq adr (mail-extract-address-components x))
7275 (setq plist (plist-put plist :fromname (car adr)))
7276 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7277 (when (setq x (plist-get plist :to))
7278 (setq adr (mail-extract-address-components x))
7279 (setq plist (plist-put plist :toname (car adr)))
7280 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7281 (let ((from (plist-get plist :from))
7282 (to (plist-get plist :to)))
7283 (when (and from to org-from-is-user-regexp)
7284 (setq plist
7285 (plist-put plist :fromto
7286 (if (string-match org-from-is-user-regexp from)
7287 (concat "to %t")
7288 (concat "from %f"))))))
7289 (setq org-store-link-plist plist))
7291 (defun org-add-link-props (&rest plist)
7292 "Add these properties to the link property list."
7293 (let (key value)
7294 (while plist
7295 (setq key (pop plist) value (pop plist))
7296 (setq org-store-link-plist
7297 (plist-put org-store-link-plist key value)))))
7299 (defun org-email-link-description (&optional fmt)
7300 "Return the description part of an email link.
7301 This takes information from `org-store-link-plist' and formats it
7302 according to FMT (default from `org-email-link-description-format')."
7303 (setq fmt (or fmt org-email-link-description-format))
7304 (let* ((p org-store-link-plist)
7305 (to (plist-get p :toaddress))
7306 (from (plist-get p :fromaddress))
7307 (table
7308 (list
7309 (cons "%c" (plist-get p :fromto))
7310 (cons "%F" (plist-get p :from))
7311 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7312 (cons "%T" (plist-get p :to))
7313 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7314 (cons "%s" (plist-get p :subject))
7315 (cons "%m" (plist-get p :message-id)))))
7316 (when (string-match "%c" fmt)
7317 ;; Check if the user wrote this message
7318 (if (and org-from-is-user-regexp from to
7319 (save-match-data (string-match org-from-is-user-regexp from)))
7320 (setq fmt (replace-match "to %t" t t fmt))
7321 (setq fmt (replace-match "from %f" t t fmt))))
7322 (org-replace-escapes fmt table)))
7324 (defun org-make-org-heading-search-string (&optional string heading)
7325 "Make search string for STRING or current headline."
7326 (interactive)
7327 (let ((s (or string (org-get-heading))))
7328 (unless (and string (not heading))
7329 ;; We are using a headline, clean up garbage in there.
7330 (if (string-match org-todo-regexp s)
7331 (setq s (replace-match "" t t s)))
7332 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7333 (setq s (replace-match "" t t s)))
7334 (setq s (org-trim s))
7335 (if (string-match (concat "^\\(" org-quote-string "\\|"
7336 org-comment-string "\\)") s)
7337 (setq s (replace-match "" t t s)))
7338 (while (string-match org-ts-regexp s)
7339 (setq s (replace-match "" t t s))))
7340 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7341 (setq s (replace-match " " t t s)))
7342 (or string (setq s (concat "*" s))) ; Add * for headlines
7343 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7345 (defun org-make-link (&rest strings)
7346 "Concatenate STRINGS."
7347 (apply 'concat strings))
7349 (defun org-make-link-string (link &optional description)
7350 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7351 (unless (string-match "\\S-" link)
7352 (error "Empty link"))
7353 (when (stringp description)
7354 ;; Remove brackets from the description, they are fatal.
7355 (while (string-match "\\[" description)
7356 (setq description (replace-match "{" t t description)))
7357 (while (string-match "\\]" description)
7358 (setq description (replace-match "}" t t description))))
7359 (when (equal (org-link-escape link) description)
7360 ;; No description needed, it is identical
7361 (setq description nil))
7362 (when (and (not description)
7363 (not (equal link (org-link-escape link))))
7364 (setq description (org-extract-attributes link)))
7365 (concat "[[" (org-link-escape link) "]"
7366 (if description (concat "[" description "]") "")
7367 "]"))
7369 (defconst org-link-escape-chars
7370 '((?\ . "%20")
7371 (?\[ . "%5B")
7372 (?\] . "%5D")
7373 (?\340 . "%E0") ; `a
7374 (?\342 . "%E2") ; ^a
7375 (?\347 . "%E7") ; ,c
7376 (?\350 . "%E8") ; `e
7377 (?\351 . "%E9") ; 'e
7378 (?\352 . "%EA") ; ^e
7379 (?\356 . "%EE") ; ^i
7380 (?\364 . "%F4") ; ^o
7381 (?\371 . "%F9") ; `u
7382 (?\373 . "%FB") ; ^u
7383 (?\; . "%3B")
7384 (?? . "%3F")
7385 (?= . "%3D")
7386 (?+ . "%2B")
7388 "Association list of escapes for some characters problematic in links.
7389 This is the list that is used for internal purposes.")
7391 (defvar org-url-encoding-use-url-hexify nil)
7393 (defconst org-link-escape-chars-browser
7394 '((?\ . "%20")) ; 32 for the SPC char
7395 "Association list of escapes for some characters problematic in links.
7396 This is the list that is used before handing over to the browser.")
7398 (defun org-link-escape (text &optional table)
7399 "Escape characters in TEXT that are problematic for links."
7400 (if org-url-encoding-use-url-hexify
7401 (url-hexify-string text)
7402 (setq table (or table org-link-escape-chars))
7403 (when text
7404 (let ((re (mapconcat (lambda (x) (regexp-quote
7405 (char-to-string (car x))))
7406 table "\\|")))
7407 (while (string-match re text)
7408 (setq text
7409 (replace-match
7410 (cdr (assoc (string-to-char (match-string 0 text))
7411 table))
7412 t t text)))
7413 text))))
7415 (defun org-link-unescape (text &optional table)
7416 "Reverse the action of `org-link-escape'."
7417 (if org-url-encoding-use-url-hexify
7418 (url-unhex-string text)
7419 (setq table (or table org-link-escape-chars))
7420 (when text
7421 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7422 table "\\|")))
7423 (while (string-match re text)
7424 (setq text
7425 (replace-match
7426 (char-to-string (car (rassoc (match-string 0 text) table)))
7427 t t text)))
7428 text))))
7430 (defun org-xor (a b)
7431 "Exclusive or."
7432 (if a (not b) b))
7434 (defun org-fixup-message-id-for-http (s)
7435 "Replace special characters in a message id, so it can be used in an http query."
7436 (while (string-match "<" s)
7437 (setq s (replace-match "%3C" t t s)))
7438 (while (string-match ">" s)
7439 (setq s (replace-match "%3E" t t s)))
7440 (while (string-match "@" s)
7441 (setq s (replace-match "%40" t t s)))
7444 ;;;###autoload
7445 (defun org-insert-link-global ()
7446 "Insert a link like Org-mode does.
7447 This command can be called in any mode to insert a link in Org-mode syntax."
7448 (interactive)
7449 (org-load-modules-maybe)
7450 (org-run-like-in-org-mode 'org-insert-link))
7452 (defun org-insert-link (&optional complete-file link-location)
7453 "Insert a link. At the prompt, enter the link.
7455 Completion can be used to insert any of the link protocol prefixes like
7456 http or ftp in use.
7458 The history can be used to select a link previously stored with
7459 `org-store-link'. When the empty string is entered (i.e. if you just
7460 press RET at the prompt), the link defaults to the most recently
7461 stored link. As SPC triggers completion in the minibuffer, you need to
7462 use M-SPC or C-q SPC to force the insertion of a space character.
7464 You will also be prompted for a description, and if one is given, it will
7465 be displayed in the buffer instead of the link.
7467 If there is already a link at point, this command will allow you to edit link
7468 and description parts.
7470 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7471 be selected using completion. The path to the file will be relative to the
7472 current directory if the file is in the current directory or a subdirectory.
7473 Otherwise, the link will be the absolute path as completed in the minibuffer
7474 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7475 option `org-link-file-path-type'.
7477 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7478 the current directory or below.
7480 With three \\[universal-argument] prefixes, negate the meaning of
7481 `org-keep-stored-link-after-insertion'.
7483 If `org-make-link-description-function' is non-nil, this function will be
7484 called with the link target, and the result will be the default
7485 link description.
7487 If the LINK-LOCATION parameter is non-nil, this value will be
7488 used as the link location instead of reading one interactively."
7489 (interactive "P")
7490 (let* ((wcf (current-window-configuration))
7491 (region (if (org-region-active-p)
7492 (buffer-substring (region-beginning) (region-end))))
7493 (remove (and region (list (region-beginning) (region-end))))
7494 (desc region)
7495 tmphist ; byte-compile incorrectly complains about this
7496 (link link-location)
7497 entry file all-prefixes)
7498 (cond
7499 (link-location) ; specified by arg, just use it.
7500 ((org-in-regexp org-bracket-link-regexp 1)
7501 ;; We do have a link at point, and we are going to edit it.
7502 (setq remove (list (match-beginning 0) (match-end 0)))
7503 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7504 (setq link (read-string "Link: "
7505 (org-link-unescape
7506 (org-match-string-no-properties 1)))))
7507 ((or (org-in-regexp org-angle-link-re)
7508 (org-in-regexp org-plain-link-re))
7509 ;; Convert to bracket link
7510 (setq remove (list (match-beginning 0) (match-end 0))
7511 link (read-string "Link: "
7512 (org-remove-angle-brackets (match-string 0)))))
7513 ((member complete-file '((4) (16)))
7514 ;; Completing read for file names.
7515 (setq link (org-file-complete-link complete-file)))
7517 ;; Read link, with completion for stored links.
7518 (with-output-to-temp-buffer "*Org Links*"
7519 (princ "Insert a link.
7520 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
7521 (when org-stored-links
7522 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7523 (princ (mapconcat
7524 (lambda (x)
7525 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7526 (reverse org-stored-links) "\n"))))
7527 (let ((cw (selected-window)))
7528 (select-window (get-buffer-window "*Org Links*"))
7529 (setq truncate-lines t)
7530 (unless (pos-visible-in-window-p (point-max))
7531 (org-fit-window-to-buffer))
7532 (and (window-live-p cw) (select-window cw)))
7533 ;; Fake a link history, containing the stored links.
7534 (setq tmphist (append (mapcar 'car org-stored-links)
7535 org-insert-link-history))
7536 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
7537 (mapcar 'car org-link-abbrev-alist)
7538 org-link-types))
7539 (unwind-protect
7540 (progn
7541 (setq link
7542 (let ((org-completion-use-ido nil)
7543 (org-completion-use-iswitchb nil))
7544 (org-completing-read
7545 "Link: "
7546 (append
7547 (mapcar (lambda (x) (list (concat x ":")))
7548 all-prefixes)
7549 (mapcar 'car org-stored-links))
7550 nil nil nil
7551 'tmphist
7552 (car (car org-stored-links)))))
7553 (if (or (member link all-prefixes)
7554 (and (equal ":" (substring link -1))
7555 (member (substring link 0 -1) all-prefixes)
7556 (setq link (substring link 0 -1))))
7557 (setq link (org-link-try-special-completion link))))
7558 (set-window-configuration wcf)
7559 (kill-buffer "*Org Links*"))
7560 (setq entry (assoc link org-stored-links))
7561 (or entry (push link org-insert-link-history))
7562 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7563 (not org-keep-stored-link-after-insertion))
7564 (setq org-stored-links (delq (assoc link org-stored-links)
7565 org-stored-links)))
7566 (setq desc (or desc (nth 1 entry)))))
7568 (if (string-match org-plain-link-re link)
7569 ;; URL-like link, normalize the use of angular brackets.
7570 (setq link (org-make-link (org-remove-angle-brackets link))))
7572 ;; Check if we are linking to the current file with a search option
7573 ;; If yes, simplify the link by using only the search option.
7574 (when (and buffer-file-name
7575 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7576 (let* ((path (match-string 1 link))
7577 (case-fold-search nil)
7578 (search (match-string 2 link)))
7579 (save-match-data
7580 (if (equal (file-truename buffer-file-name) (file-truename path))
7581 ;; We are linking to this same file, with a search option
7582 (setq link search)))))
7584 ;; Check if we can/should use a relative path. If yes, simplify the link
7585 (when (string-match "^file:\\(.*\\)" link)
7586 (let* ((path (match-string 1 link))
7587 (origpath path)
7588 (case-fold-search nil))
7589 (cond
7590 ((or (eq org-link-file-path-type 'absolute)
7591 (equal complete-file '(16)))
7592 (setq path (abbreviate-file-name (expand-file-name path))))
7593 ((eq org-link-file-path-type 'noabbrev)
7594 (setq path (expand-file-name path)))
7595 ((eq org-link-file-path-type 'relative)
7596 (setq path (file-relative-name path)))
7598 (save-match-data
7599 (if (string-match (concat "^" (regexp-quote
7600 (file-name-as-directory
7601 (expand-file-name "."))))
7602 (expand-file-name path))
7603 ;; We are linking a file with relative path name.
7604 (setq path (substring (expand-file-name path)
7605 (match-end 0)))
7606 (setq path (abbreviate-file-name (expand-file-name path)))))))
7607 (setq link (concat "file:" path))
7608 (if (equal desc origpath)
7609 (setq desc path))))
7611 (if org-make-link-description-function
7612 (setq desc (funcall org-make-link-description-function link desc)))
7614 (setq desc (read-string "Description: " desc))
7615 (unless (string-match "\\S-" desc) (setq desc nil))
7616 (if remove (apply 'delete-region remove))
7617 (insert (org-make-link-string link desc))))
7619 (defun org-link-try-special-completion (type)
7620 "If there is completion support for link type TYPE, offer it."
7621 (let ((fun (intern (concat "org-" type "-complete-link"))))
7622 (if (functionp fun)
7623 (funcall fun)
7624 (read-string "Link (no completion support): " (concat type ":")))))
7626 (defun org-file-complete-link (&optional arg)
7627 "Create a file link using completion."
7628 (let (file link)
7629 (setq file (read-file-name "File: "))
7630 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7631 (pwd1 (file-name-as-directory (abbreviate-file-name
7632 (expand-file-name ".")))))
7633 (cond
7634 ((equal arg '(16))
7635 (setq link (org-make-link
7636 "file:"
7637 (abbreviate-file-name (expand-file-name file)))))
7638 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7639 (setq link (org-make-link "file:" (match-string 1 file))))
7640 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7641 (expand-file-name file))
7642 (setq link (org-make-link
7643 "file:" (match-string 1 (expand-file-name file)))))
7644 (t (setq link (org-make-link "file:" file)))))
7645 link))
7647 (defun org-completing-read (&rest args)
7648 "Completing-read with SPACE being a normal character."
7649 (let ((minibuffer-local-completion-map
7650 (copy-keymap minibuffer-local-completion-map)))
7651 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7652 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7653 (apply 'org-icompleting-read args)))
7655 (defun org-completing-read-no-i (&rest args)
7656 (let (org-completion-use-ido org-completion-use-iswitchb)
7657 (apply 'org-completing-read args)))
7659 (defun org-iswitchb-completing-read (prompt choices &rest args)
7660 "Use iswitch as a completing-read replacement to choose from choices.
7661 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
7662 from."
7663 (let ((iswitchb-make-buflist-hook
7664 (lambda ()
7665 (setq iswitchb-temp-buflist choices))))
7666 (iswitchb-read-buffer prompt)))
7668 (defun org-icompleting-read (&rest args)
7669 "Completing-read using `ido-mode' or `iswitchb' speedups if available"
7670 (if (and org-completion-use-ido
7671 (fboundp 'ido-completing-read)
7672 (boundp 'ido-mode) ido-mode
7673 (listp (second args)))
7674 (let ((ido-enter-matching-directory nil))
7675 (apply 'ido-completing-read (concat (car args))
7676 (if (consp (car (nth 1 args)))
7677 (mapcar (lambda (x) (car x)) (nth 1 args))
7678 (nth 1 args))
7679 (cddr args)))
7680 (if (and org-completion-use-iswitchb
7681 (boundp 'iswitchb-mode) iswitchb-mode
7682 (listp (second args)))
7683 (apply 'org-iswitchb-completing-read (concat (car args))
7684 (mapcar (lambda (x) (car x)) (nth 1 args))
7685 (cddr args))
7686 (apply 'completing-read args))))
7688 (defun org-extract-attributes (s)
7689 "Extract the attributes cookie from a string and set as text property."
7690 (let (a attr (start 0) key value)
7691 (save-match-data
7692 (when (string-match "{{\\([^}]+\\)}}$" s)
7693 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7694 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7695 (setq key (match-string 1 a) value (match-string 2 a)
7696 start (match-end 0)
7697 attr (plist-put attr (intern key) value))))
7698 (org-add-props s nil 'org-attr attr))
7701 (defun org-extract-attributes-from-string (tag)
7702 (let (key value attr)
7703 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
7704 (setq key (match-string 1 tag) value (match-string 2 tag)
7705 tag (replace-match "" t t tag)
7706 attr (plist-put attr (intern key) value)))
7707 (cons tag attr)))
7709 (defun org-attributes-to-string (plist)
7710 "Format a property list into an HTML attribute list."
7711 (let ((s "") key value)
7712 (while plist
7713 (setq key (pop plist) value (pop plist))
7714 (and value
7715 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7718 ;;; Opening/following a link
7720 (defvar org-link-search-failed nil)
7722 (defun org-next-link ()
7723 "Move forward to the next link.
7724 If the link is in hidden text, expose it."
7725 (interactive)
7726 (when (and org-link-search-failed (eq this-command last-command))
7727 (goto-char (point-min))
7728 (message "Link search wrapped back to beginning of buffer"))
7729 (setq org-link-search-failed nil)
7730 (let* ((pos (point))
7731 (ct (org-context))
7732 (a (assoc :link ct)))
7733 (if a (goto-char (nth 2 a)))
7734 (if (re-search-forward org-any-link-re nil t)
7735 (progn
7736 (goto-char (match-beginning 0))
7737 (if (org-invisible-p) (org-show-context)))
7738 (goto-char pos)
7739 (setq org-link-search-failed t)
7740 (error "No further link found"))))
7742 (defun org-previous-link ()
7743 "Move backward to the previous link.
7744 If the link is in hidden text, expose it."
7745 (interactive)
7746 (when (and org-link-search-failed (eq this-command last-command))
7747 (goto-char (point-max))
7748 (message "Link search wrapped back to end of buffer"))
7749 (setq org-link-search-failed nil)
7750 (let* ((pos (point))
7751 (ct (org-context))
7752 (a (assoc :link ct)))
7753 (if a (goto-char (nth 1 a)))
7754 (if (re-search-backward org-any-link-re nil t)
7755 (progn
7756 (goto-char (match-beginning 0))
7757 (if (org-invisible-p) (org-show-context)))
7758 (goto-char pos)
7759 (setq org-link-search-failed t)
7760 (error "No further link found"))))
7762 (defun org-translate-link (s)
7763 "Translate a link string if a translation function has been defined."
7764 (if (and org-link-translation-function
7765 (fboundp org-link-translation-function)
7766 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7767 (progn
7768 (setq s (funcall org-link-translation-function
7769 (match-string 1) (match-string 2)))
7770 (concat (car s) ":" (cdr s)))
7773 (defun org-translate-link-from-planner (type path)
7774 "Translate a link from Emacs Planner syntax so that Org can follow it.
7775 This is still an experimental function, your mileage may vary."
7776 (cond
7777 ((member type '("http" "https" "news" "ftp"))
7778 ;; standard Internet links are the same.
7779 nil)
7780 ((and (equal type "irc") (string-match "^//" path))
7781 ;; Planner has two / at the beginning of an irc link, we have 1.
7782 ;; We should have zero, actually....
7783 (setq path (substring path 1)))
7784 ((and (equal type "lisp") (string-match "^/" path))
7785 ;; Planner has a slash, we do not.
7786 (setq type "elisp" path (substring path 1)))
7787 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7788 ;; A typical message link. Planner has the id after the fina slash,
7789 ;; we separate it with a hash mark
7790 (setq path (concat (match-string 1 path) "#"
7791 (org-remove-angle-brackets (match-string 2 path)))))
7793 (cons type path))
7795 (defun org-find-file-at-mouse (ev)
7796 "Open file link or URL at mouse."
7797 (interactive "e")
7798 (mouse-set-point ev)
7799 (org-open-at-point 'in-emacs))
7801 (defun org-open-at-mouse (ev)
7802 "Open file link or URL at mouse."
7803 (interactive "e")
7804 (mouse-set-point ev)
7805 (if (eq major-mode 'org-agenda-mode)
7806 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7807 (org-open-at-point))
7809 (defvar org-window-config-before-follow-link nil
7810 "The window configuration before following a link.
7811 This is saved in case the need arises to restore it.")
7813 (defvar org-open-link-marker (make-marker)
7814 "Marker pointing to the location where `org-open-at-point; was called.")
7816 ;;;###autoload
7817 (defun org-open-at-point-global ()
7818 "Follow a link like Org-mode does.
7819 This command can be called in any mode to follow a link that has
7820 Org-mode syntax."
7821 (interactive)
7822 (org-run-like-in-org-mode 'org-open-at-point))
7824 ;;;###autoload
7825 (defun org-open-link-from-string (s &optional arg)
7826 "Open a link in the string S, as if it was in Org-mode."
7827 (interactive "sLink: \nP")
7828 (let ((reference-buffer (current-buffer)))
7829 (with-temp-buffer
7830 (let ((org-inhibit-startup t))
7831 (org-mode)
7832 (insert s)
7833 (goto-char (point-min))
7834 (org-open-at-point arg reference-buffer)))))
7836 (defun org-open-at-point (&optional in-emacs reference-buffer)
7837 "Open link at or after point.
7838 If there is no link at point, this function will search forward up to
7839 the end of the current line.
7840 Normally, files will be opened by an appropriate application. If the
7841 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7842 With a double prefix argument, try to open outside of Emacs, in the
7843 application the system uses for this file type."
7844 (interactive "P")
7845 (org-load-modules-maybe)
7846 (move-marker org-open-link-marker (point))
7847 (setq org-window-config-before-follow-link (current-window-configuration))
7848 (org-remove-occur-highlights nil nil t)
7849 (cond
7850 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7851 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7852 (org-footnote-action))
7854 (let (type path link line search (pos (point)))
7855 (catch 'match
7856 (save-excursion
7857 (skip-chars-forward "^]\n\r")
7858 (when (org-in-regexp org-bracket-link-regexp)
7859 (setq link (org-extract-attributes
7860 (org-link-unescape (org-match-string-no-properties 1))))
7861 (while (string-match " *\n *" link)
7862 (setq link (replace-match " " t t link)))
7863 (setq link (org-link-expand-abbrev link))
7864 (cond
7865 ((or (file-name-absolute-p link)
7866 (string-match "^\\.\\.?/" link))
7867 (setq type "file" path link))
7868 ((string-match org-link-re-with-space3 link)
7869 (setq type (match-string 1 link) path (match-string 2 link)))
7870 (t (setq type "thisfile" path link)))
7871 (throw 'match t)))
7873 (when (get-text-property (point) 'org-linked-text)
7874 (setq type "thisfile"
7875 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7876 (1+ (point)) (point))
7877 path (buffer-substring
7878 (previous-single-property-change pos 'org-linked-text)
7879 (next-single-property-change pos 'org-linked-text)))
7880 (throw 'match t))
7882 (save-excursion
7883 (when (or (org-in-regexp org-angle-link-re)
7884 (org-in-regexp org-plain-link-re))
7885 (setq type (match-string 1) path (match-string 2))
7886 (throw 'match t)))
7887 (save-excursion
7888 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7889 (setq type "tags"
7890 path (match-string 1))
7891 (while (string-match ":" path)
7892 (setq path (replace-match "+" t t path)))
7893 (throw 'match t)))
7894 (when (org-in-regexp "<\\([^><\n]+\\)>")
7895 (setq type "tree-match"
7896 path (match-string 1))
7897 (throw 'match t)))
7898 (unless path
7899 (error "No link found"))
7901 ;; switch back to reference buffer
7902 ;; needed when if called in a temporary buffer through
7903 ;; org-open-link-from-string
7904 (and reference-buffer (switch-to-buffer reference-buffer))
7906 ;; Remove any trailing spaces in path
7907 (if (string-match " +\\'" path)
7908 (setq path (replace-match "" t t path)))
7909 (if (and org-link-translation-function
7910 (fboundp org-link-translation-function))
7911 ;; Check if we need to translate the link
7912 (let ((tmp (funcall org-link-translation-function type path)))
7913 (setq type (car tmp) path (cdr tmp))))
7915 (cond
7917 ((assoc type org-link-protocols)
7918 (funcall (nth 1 (assoc type org-link-protocols)) path))
7920 ((equal type "mailto")
7921 (let ((cmd (car org-link-mailto-program))
7922 (args (cdr org-link-mailto-program)) args1
7923 (address path) (subject "") a)
7924 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7925 (setq address (match-string 1 path)
7926 subject (org-link-escape (match-string 2 path))))
7927 (while args
7928 (cond
7929 ((not (stringp (car args))) (push (pop args) args1))
7930 (t (setq a (pop args))
7931 (if (string-match "%a" a)
7932 (setq a (replace-match address t t a)))
7933 (if (string-match "%s" a)
7934 (setq a (replace-match subject t t a)))
7935 (push a args1))))
7936 (apply cmd (nreverse args1))))
7938 ((member type '("http" "https" "ftp" "news"))
7939 (browse-url (concat type ":" (org-link-escape
7940 path org-link-escape-chars-browser))))
7942 ((member type '("message"))
7943 (browse-url (concat type ":" path)))
7945 ((string= type "tags")
7946 (org-tags-view in-emacs path))
7947 ((string= type "thisfile")
7948 (if in-emacs
7949 (switch-to-buffer-other-window
7950 (org-get-buffer-for-internal-link (current-buffer)))
7951 (org-mark-ring-push))
7952 (let ((cmd `(org-link-search
7953 ,path
7954 ,(cond ((equal in-emacs '(4)) 'occur)
7955 ((equal in-emacs '(16)) 'org-occur)
7956 (t nil))
7957 ,pos)))
7958 (condition-case nil (eval cmd)
7959 (error (progn (widen) (eval cmd))))))
7961 ((string= type "tree-match")
7962 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7964 ((string= type "file")
7965 (if (string-match "::\\([0-9]+\\)\\'" path)
7966 (setq line (string-to-number (match-string 1 path))
7967 path (substring path 0 (match-beginning 0)))
7968 (if (string-match "::\\(.+\\)\\'" path)
7969 (setq search (match-string 1 path)
7970 path (substring path 0 (match-beginning 0)))))
7971 (if (string-match "[*?{]" (file-name-nondirectory path))
7972 (dired path)
7973 (org-open-file path in-emacs line search)))
7975 ((string= type "news")
7976 (require 'org-gnus)
7977 (org-gnus-follow-link path))
7979 ((string= type "shell")
7980 (let ((cmd path))
7981 (if (or (not org-confirm-shell-link-function)
7982 (funcall org-confirm-shell-link-function
7983 (format "Execute \"%s\" in shell? "
7984 (org-add-props cmd nil
7985 'face 'org-warning))))
7986 (progn
7987 (message "Executing %s" cmd)
7988 (shell-command cmd))
7989 (error "Abort"))))
7991 ((string= type "elisp")
7992 (let ((cmd path))
7993 (if (or (not org-confirm-elisp-link-function)
7994 (funcall org-confirm-elisp-link-function
7995 (format "Execute \"%s\" as elisp? "
7996 (org-add-props cmd nil
7997 'face 'org-warning))))
7998 (message "%s => %s" cmd
7999 (if (equal (string-to-char cmd) ?\()
8000 (eval (read cmd))
8001 (call-interactively (read cmd))))
8002 (error "Abort"))))
8005 (browse-url-at-point))))))
8006 (move-marker org-open-link-marker nil)
8007 (run-hook-with-args 'org-follow-link-hook))
8009 ;;;; Time estimates
8011 (defun org-get-effort (&optional pom)
8012 "Get the effort estimate for the current entry."
8013 (org-entry-get pom org-effort-property))
8015 ;;; File search
8017 (defvar org-create-file-search-functions nil
8018 "List of functions to construct the right search string for a file link.
8019 These functions are called in turn with point at the location to
8020 which the link should point.
8022 A function in the hook should first test if it would like to
8023 handle this file type, for example by checking the major-mode or
8024 the file extension. If it decides not to handle this file, it
8025 should just return nil to give other functions a chance. If it
8026 does handle the file, it must return the search string to be used
8027 when following the link. The search string will be part of the
8028 file link, given after a double colon, and `org-open-at-point'
8029 will automatically search for it. If special measures must be
8030 taken to make the search successful, another function should be
8031 added to the companion hook `org-execute-file-search-functions',
8032 which see.
8034 A function in this hook may also use `setq' to set the variable
8035 `description' to provide a suggestion for the descriptive text to
8036 be used for this link when it gets inserted into an Org-mode
8037 buffer with \\[org-insert-link].")
8039 (defvar org-execute-file-search-functions nil
8040 "List of functions to execute a file search triggered by a link.
8042 Functions added to this hook must accept a single argument, the
8043 search string that was part of the file link, the part after the
8044 double colon. The function must first check if it would like to
8045 handle this search, for example by checking the major-mode or the
8046 file extension. If it decides not to handle this search, it
8047 should just return nil to give other functions a chance. If it
8048 does handle the search, it must return a non-nil value to keep
8049 other functions from trying.
8051 Each function can access the current prefix argument through the
8052 variable `current-prefix-argument'. Note that a single prefix is
8053 used to force opening a link in Emacs, so it may be good to only
8054 use a numeric or double prefix to guide the search function.
8056 In case this is needed, a function in this hook can also restore
8057 the window configuration before `org-open-at-point' was called using:
8059 (set-window-configuration org-window-config-before-follow-link)")
8061 (defun org-link-search (s &optional type avoid-pos)
8062 "Search for a link search option.
8063 If S is surrounded by forward slashes, it is interpreted as a
8064 regular expression. In org-mode files, this will create an `org-occur'
8065 sparse tree. In ordinary files, `occur' will be used to list matches.
8066 If the current buffer is in `dired-mode', grep will be used to search
8067 in all files. If AVOID-POS is given, ignore matches near that position."
8068 (let ((case-fold-search t)
8069 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8070 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8071 (append '(("") (" ") ("\t") ("\n"))
8072 org-emphasis-alist)
8073 "\\|") "\\)"))
8074 (pos (point))
8075 (pre nil) (post nil)
8076 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8077 (cond
8078 ;; First check if there are any special
8079 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8080 ;; Now try the builtin stuff
8081 ((and (equal (string-to-char s0) ?#)
8082 (> (length s0) 1)
8083 (save-excursion
8084 (goto-char (point-min))
8085 (and
8086 (re-search-forward
8087 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8088 (setq type 'dedicated
8089 pos (match-beginning 0))))
8090 ;; There is an exact target for this
8091 (goto-char pos)
8092 (org-back-to-heading t)))
8093 ((save-excursion
8094 (goto-char (point-min))
8095 (and
8096 (re-search-forward
8097 (concat "<<" (regexp-quote s0) ">>") nil t)
8098 (setq type 'dedicated
8099 pos (match-beginning 0))))
8100 ;; There is an exact target for this
8101 (goto-char pos))
8102 ((and (string-match "^(\\(.*\\))$" s0)
8103 (save-excursion
8104 (goto-char (point-min))
8105 (and
8106 (re-search-forward
8107 (concat "[^[]" (regexp-quote
8108 (format org-coderef-label-format
8109 (match-string 1 s0))))
8110 nil t)
8111 (setq type 'dedicated
8112 pos (1+ (match-beginning 0))))))
8113 ;; There is a coderef target for this
8114 (goto-char pos))
8115 ((string-match "^/\\(.*\\)/$" s)
8116 ;; A regular expression
8117 (cond
8118 ((org-mode-p)
8119 (org-occur (match-string 1 s)))
8120 ;;((eq major-mode 'dired-mode)
8121 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8122 (t (org-do-occur (match-string 1 s)))))
8124 ;; A normal search strings
8125 (when (equal (string-to-char s) ?*)
8126 ;; Anchor on headlines, post may include tags.
8127 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8128 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8129 s (substring s 1)))
8130 (remove-text-properties
8131 0 (length s)
8132 '(face nil mouse-face nil keymap nil fontified nil) s)
8133 ;; Make a series of regular expressions to find a match
8134 (setq words (org-split-string s "[ \n\r\t]+")
8136 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8137 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8138 "\\)" markers)
8139 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8140 re2a (concat "[ \t\r\n]" re2a_)
8141 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8142 re4 (concat "[^a-zA-Z_]" re4_)
8144 re1 (concat pre re2 post)
8145 re3 (concat pre (if pre re4_ re4) post)
8146 re5 (concat pre ".*" re4)
8147 re2 (concat pre re2)
8148 re2a (concat pre (if pre re2a_ re2a))
8149 re4 (concat pre (if pre re4_ re4))
8150 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8151 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8152 re5 "\\)"
8154 (cond
8155 ((eq type 'org-occur) (org-occur reall))
8156 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8157 (t (goto-char (point-min))
8158 (setq type 'fuzzy)
8159 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8160 (org-search-not-self 1 re1 nil t)
8161 (org-search-not-self 1 re2 nil t)
8162 (org-search-not-self 1 re2a nil t)
8163 (org-search-not-self 1 re3 nil t)
8164 (org-search-not-self 1 re4 nil t)
8165 (org-search-not-self 1 re5 nil t)
8167 (goto-char (match-beginning 1))
8168 (goto-char pos)
8169 (error "No match")))))
8171 ;; Normal string-search
8172 (goto-char (point-min))
8173 (if (search-forward s nil t)
8174 (goto-char (match-beginning 0))
8175 (error "No match"))))
8176 (and (org-mode-p) (org-show-context 'link-search))
8177 type))
8179 (defun org-search-not-self (group &rest args)
8180 "Execute `re-search-forward', but only accept matches that do not
8181 enclose the position of `org-open-link-marker'."
8182 (let ((m org-open-link-marker))
8183 (catch 'exit
8184 (while (apply 're-search-forward args)
8185 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8186 (goto-char (match-end group))
8187 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8188 (> (match-beginning 0) (marker-position m))
8189 (< (match-end 0) (marker-position m)))
8190 (save-match-data
8191 (or (not (org-in-regexp
8192 org-bracket-link-analytic-regexp 1))
8193 (not (match-end 4)) ; no description
8194 (and (<= (match-beginning 4) (point))
8195 (>= (match-end 4) (point))))))
8196 (throw 'exit (point))))))))
8198 (defun org-get-buffer-for-internal-link (buffer)
8199 "Return a buffer to be used for displaying the link target of internal links."
8200 (cond
8201 ((not org-display-internal-link-with-indirect-buffer)
8202 buffer)
8203 ((string-match "(Clone)$" (buffer-name buffer))
8204 (message "Buffer is already a clone, not making another one")
8205 ;; we also do not modify visibility in this case
8206 buffer)
8207 (t ; make a new indirect buffer for displaying the link
8208 (let* ((bn (buffer-name buffer))
8209 (ibn (concat bn "(Clone)"))
8210 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8211 (with-current-buffer ib (org-overview))
8212 ib))))
8214 (defun org-do-occur (regexp &optional cleanup)
8215 "Call the Emacs command `occur'.
8216 If CLEANUP is non-nil, remove the printout of the regular expression
8217 in the *Occur* buffer. This is useful if the regex is long and not useful
8218 to read."
8219 (occur regexp)
8220 (when cleanup
8221 (let ((cwin (selected-window)) win beg end)
8222 (when (setq win (get-buffer-window "*Occur*"))
8223 (select-window win))
8224 (goto-char (point-min))
8225 (when (re-search-forward "match[a-z]+" nil t)
8226 (setq beg (match-end 0))
8227 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8228 (setq end (1- (match-beginning 0)))))
8229 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8230 (goto-char (point-min))
8231 (select-window cwin))))
8233 ;;; The mark ring for links jumps
8235 (defvar org-mark-ring nil
8236 "Mark ring for positions before jumps in Org-mode.")
8237 (defvar org-mark-ring-last-goto nil
8238 "Last position in the mark ring used to go back.")
8239 ;; Fill and close the ring
8240 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8241 (loop for i from 1 to org-mark-ring-length do
8242 (push (make-marker) org-mark-ring))
8243 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8244 org-mark-ring)
8246 (defun org-mark-ring-push (&optional pos buffer)
8247 "Put the current position or POS into the mark ring and rotate it."
8248 (interactive)
8249 (setq pos (or pos (point)))
8250 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8251 (move-marker (car org-mark-ring)
8252 (or pos (point))
8253 (or buffer (current-buffer)))
8254 (message "%s"
8255 (substitute-command-keys
8256 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8258 (defun org-mark-ring-goto (&optional n)
8259 "Jump to the previous position in the mark ring.
8260 With prefix arg N, jump back that many stored positions. When
8261 called several times in succession, walk through the entire ring.
8262 Org-mode commands jumping to a different position in the current file,
8263 or to another Org-mode file, automatically push the old position
8264 onto the ring."
8265 (interactive "p")
8266 (let (p m)
8267 (if (eq last-command this-command)
8268 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8269 (setq p org-mark-ring))
8270 (setq org-mark-ring-last-goto p)
8271 (setq m (car p))
8272 (switch-to-buffer (marker-buffer m))
8273 (goto-char m)
8274 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8276 (defun org-remove-angle-brackets (s)
8277 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8278 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8280 (defun org-add-angle-brackets (s)
8281 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8282 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8284 (defun org-remove-double-quotes (s)
8285 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8286 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8289 ;;; Following specific links
8291 (defun org-follow-timestamp-link ()
8292 (cond
8293 ((org-at-date-range-p t)
8294 (let ((org-agenda-start-on-weekday)
8295 (t1 (match-string 1))
8296 (t2 (match-string 2)))
8297 (setq t1 (time-to-days (org-time-string-to-time t1))
8298 t2 (time-to-days (org-time-string-to-time t2)))
8299 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8300 ((org-at-timestamp-p t)
8301 (org-agenda-list nil (time-to-days (org-time-string-to-time
8302 (substring (match-string 1) 0 10)))
8304 (t (error "This should not happen"))))
8307 ;;; Following file links
8308 (defvar org-wait nil)
8309 (defun org-open-file (path &optional in-emacs line search)
8310 "Open the file at PATH.
8311 First, this expands any special file name abbreviations. Then the
8312 configuration variable `org-file-apps' is checked if it contains an
8313 entry for this file type, and if yes, the corresponding command is launched.
8315 If no application is found, Emacs simply visits the file.
8317 With optional prefix argument IN-EMACS, Emacs will visit the file.
8318 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8319 and o use an external application to visit the file.
8321 Optional LINE specifies a line to go to, optional SEARCH a string to
8322 search for. If LINE or SEARCH is given, the file will always be
8323 opened in Emacs.
8324 If the file does not exist, an error is thrown."
8325 (setq in-emacs (or in-emacs line search))
8326 (let* ((file (if (equal path "")
8327 buffer-file-name
8328 (substitute-in-file-name (expand-file-name path))))
8329 (apps (append org-file-apps (org-default-apps)))
8330 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8331 (dirp (if remp nil (file-directory-p file)))
8332 (file (if (and dirp org-open-directory-means-index-dot-org)
8333 (concat (file-name-as-directory file) "index.org")
8334 file))
8335 (a-m-a-p (assq 'auto-mode apps))
8336 (dfile (downcase file))
8337 (old-buffer (current-buffer))
8338 (old-pos (point))
8339 (old-mode major-mode)
8340 ext cmd)
8341 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8342 (setq ext (match-string 1 dfile))
8343 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8344 (setq ext (match-string 1 dfile))))
8345 (cond
8346 ((equal in-emacs '(16))
8347 (setq cmd (cdr (assoc 'system apps))))
8348 (in-emacs (setq cmd 'emacs))
8350 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8351 (and dirp (cdr (assoc 'directory apps)))
8352 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8353 'string-match)
8354 (cdr (assoc ext apps))
8355 (cdr (assoc t apps))))))
8356 (when (eq cmd 'system)
8357 (setq cmd (cdr (assoc 'system apps))))
8358 (when (eq cmd 'default)
8359 (setq cmd (cdr (assoc t apps))))
8360 (when (eq cmd 'mailcap)
8361 (require 'mailcap)
8362 (mailcap-parse-mailcaps)
8363 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8364 (command (mailcap-mime-info mime-type)))
8365 (if (stringp command)
8366 (setq cmd command)
8367 (setq cmd 'emacs))))
8368 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8369 (not (file-exists-p file))
8370 (not org-open-non-existing-files))
8371 (error "No such file: %s" file))
8372 (cond
8373 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8374 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8375 (while (string-match "['\"]%s['\"]" cmd)
8376 (setq cmd (replace-match "%s" t t cmd)))
8377 (while (string-match "%s" cmd)
8378 (setq cmd (replace-match
8379 (save-match-data
8380 (shell-quote-argument
8381 (convert-standard-filename file)))
8382 t t cmd)))
8383 (save-window-excursion
8384 (start-process-shell-command cmd nil cmd)
8385 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8387 ((or (stringp cmd)
8388 (eq cmd 'emacs))
8389 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8390 (widen)
8391 (if line (goto-line line)
8392 (if search (org-link-search search))))
8393 ((consp cmd)
8394 (let ((file (convert-standard-filename file)))
8395 (eval cmd)))
8396 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8397 (and (org-mode-p) (eq old-mode 'org-mode)
8398 (or (not (equal old-buffer (current-buffer)))
8399 (not (equal old-pos (point))))
8400 (org-mark-ring-push old-pos old-buffer))))
8402 (defun org-default-apps ()
8403 "Return the default applications for this operating system."
8404 (cond
8405 ((eq system-type 'darwin)
8406 org-file-apps-defaults-macosx)
8407 ((eq system-type 'windows-nt)
8408 org-file-apps-defaults-windowsnt)
8409 (t org-file-apps-defaults-gnu)))
8411 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8412 "Convert extensions to regular expressions in the cars of LIST.
8413 Also, weed out any non-string entries, because the return value is used
8414 only for regexp matching.
8415 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8416 point to the symbol `emacs', indicating that the file should
8417 be opened in Emacs."
8418 (append
8419 (delq nil
8420 (mapcar (lambda (x)
8421 (if (not (stringp (car x)))
8423 (if (string-match "\\W" (car x))
8425 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8426 list))
8427 (if add-auto-mode
8428 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8430 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8431 (defun org-file-remote-p (file)
8432 "Test whether FILE specifies a location on a remote system.
8433 Return non-nil if the location is indeed remote.
8435 For example, the filename \"/user@host:/foo\" specifies a location
8436 on the system \"/user@host:\"."
8437 (cond ((fboundp 'file-remote-p)
8438 (file-remote-p file))
8439 ((fboundp 'tramp-handle-file-remote-p)
8440 (tramp-handle-file-remote-p file))
8441 ((and (boundp 'ange-ftp-name-format)
8442 (string-match (car ange-ftp-name-format) file))
8444 (t nil)))
8447 ;;;; Refiling
8449 (defun org-get-org-file ()
8450 "Read a filename, with default directory `org-directory'."
8451 (let ((default (or org-default-notes-file remember-data-file)))
8452 (read-file-name (format "File name [%s]: " default)
8453 (file-name-as-directory org-directory)
8454 default)))
8456 (defun org-notes-order-reversed-p ()
8457 "Check if the current file should receive notes in reversed order."
8458 (cond
8459 ((not org-reverse-note-order) nil)
8460 ((eq t org-reverse-note-order) t)
8461 ((not (listp org-reverse-note-order)) nil)
8462 (t (catch 'exit
8463 (let ((all org-reverse-note-order)
8464 entry)
8465 (while (setq entry (pop all))
8466 (if (string-match (car entry) buffer-file-name)
8467 (throw 'exit (cdr entry))))
8468 nil)))))
8470 (defvar org-refile-target-table nil
8471 "The list of refile targets, created by `org-refile'.")
8473 (defvar org-agenda-new-buffers nil
8474 "Buffers created to visit agenda files.")
8476 (defun org-get-refile-targets (&optional default-buffer)
8477 "Produce a table with refile targets."
8478 (let ((case-fold-search nil)
8479 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
8480 (entries (or org-refile-targets '((nil . (:level . 1)))))
8481 targets txt re files f desc descre fast-path-p level pos0)
8482 (message "Getting targets...")
8483 (with-current-buffer (or default-buffer (current-buffer))
8484 (while (setq entry (pop entries))
8485 (setq files (car entry) desc (cdr entry))
8486 (setq fast-path-p nil)
8487 (cond
8488 ((null files) (setq files (list (current-buffer))))
8489 ((eq files 'org-agenda-files)
8490 (setq files (org-agenda-files 'unrestricted)))
8491 ((and (symbolp files) (fboundp files))
8492 (setq files (funcall files)))
8493 ((and (symbolp files) (boundp files))
8494 (setq files (symbol-value files))))
8495 (if (stringp files) (setq files (list files)))
8496 (cond
8497 ((eq (car desc) :tag)
8498 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8499 ((eq (car desc) :todo)
8500 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8501 ((eq (car desc) :regexp)
8502 (setq descre (cdr desc)))
8503 ((eq (car desc) :level)
8504 (setq descre (concat "^\\*\\{" (number-to-string
8505 (if org-odd-levels-only
8506 (1- (* 2 (cdr desc)))
8507 (cdr desc)))
8508 "\\}[ \t]")))
8509 ((eq (car desc) :maxlevel)
8510 (setq fast-path-p t)
8511 (setq descre (concat "^\\*\\{1," (number-to-string
8512 (if org-odd-levels-only
8513 (1- (* 2 (cdr desc)))
8514 (cdr desc)))
8515 "\\}[ \t]")))
8516 (t (error "Bad refiling target description %s" desc)))
8517 (while (setq f (pop files))
8518 (save-excursion
8519 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
8520 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8521 (setq f (expand-file-name f))
8522 (if (eq org-refile-use-outline-path 'file)
8523 (push (list (file-name-nondirectory f) f nil nil) targets))
8524 (save-excursion
8525 (save-restriction
8526 (widen)
8527 (goto-char (point-min))
8528 (while (re-search-forward descre nil t)
8529 (goto-char (setq pos0 (point-at-bol)))
8530 (catch 'next
8531 (when org-refile-target-verify-function
8532 (save-match-data
8533 (or (funcall org-refile-target-verify-function)
8534 (throw 'next t))))
8535 (when (looking-at org-complex-heading-regexp)
8536 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8537 txt (org-link-display-format (match-string 4))
8538 re (concat "^" (regexp-quote
8539 (buffer-substring (match-beginning 1)
8540 (match-end 4)))))
8541 (if (match-end 5) (setq re (concat re "[ \t]+"
8542 (regexp-quote
8543 (match-string 5)))))
8544 (setq re (concat re "[ \t]*$"))
8545 (when org-refile-use-outline-path
8546 (setq txt (mapconcat 'org-protect-slash
8547 (append
8548 (if (eq org-refile-use-outline-path 'file)
8549 (list (file-name-nondirectory
8550 (buffer-file-name (buffer-base-buffer))))
8551 (if (eq org-refile-use-outline-path 'full-file-path)
8552 (list (buffer-file-name (buffer-base-buffer)))))
8553 (org-get-outline-path fast-path-p level txt)
8554 (list txt))
8555 "/")))
8556 (push (list txt f re (point)) targets)))
8557 (when (= (point) pos0)
8558 ;; verification function has not moved point
8559 (goto-char (point-at-eol))))))))))
8560 (message "Getting targets...done")
8561 (nreverse targets)))
8563 (defun org-protect-slash (s)
8564 (while (string-match "/" s)
8565 (setq s (replace-match "\\" t t s)))
8568 (defvar org-olpa (make-vector 20 nil))
8570 (defun org-get-outline-path (&optional fastp level heading)
8571 "Return the outline path to the current entry, as a list."
8572 (if fastp
8573 (progn
8574 (if (> level 19)
8575 (error "Outline path failure, more than 19 levels."))
8576 (loop for i from level upto 19 do
8577 (aset org-olpa i nil))
8578 (prog1
8579 (delq nil (append org-olpa nil))
8580 (aset org-olpa level heading)))
8581 (let (rtn)
8582 (save-excursion
8583 (while (org-up-heading-safe)
8584 (when (looking-at org-complex-heading-regexp)
8585 (push (org-match-string-no-properties 4) rtn)))
8586 rtn))))
8588 (defvar org-refile-history nil
8589 "History for refiling operations.")
8591 (defvar org-after-refile-insert-hook nil
8592 "Hook run after `org-refile' has inserted its stuff at the new location.
8593 Note that this is still *before* the stuff will be removed from
8594 the *old* location.")
8596 (defun org-refile (&optional goto default-buffer rfloc)
8597 "Move the entry at point to another heading.
8598 The list of target headings is compiled using the information in
8599 `org-refile-targets', which see. This list is created before each use
8600 and will therefore always be up-to-date.
8602 At the target location, the entry is filed as a subitem of the target heading.
8603 Depending on `org-reverse-note-order', the new subitem will either be the
8604 first or the last subitem.
8606 If there is an active region, all entries in that region will be moved.
8607 However, the region must fulfil the requirement that the first heading
8608 is the first one sets the top-level of the moved text - at most siblings
8609 below it are allowed.
8611 With prefix arg GOTO, the command will only visit the target location,
8612 not actually move anything.
8613 With a double prefix `C-u C-u', go to the location where the last refiling
8614 operation has put the subtree.
8616 RFLOC can be a refile location obtained in a different way.
8618 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
8619 (interactive "P")
8620 (let* ((cbuf (current-buffer))
8621 (regionp (org-region-active-p))
8622 (region-start (and regionp (region-beginning)))
8623 (region-end (and regionp (region-end)))
8624 (region-length (and regionp (- region-end region-start)))
8625 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8626 pos it nbuf file re level reversed)
8627 (when regionp
8628 (goto-char region-start)
8629 (or (bolp) (goto-char (point-at-bol)))
8630 (setq region-start (point))
8631 (unless (org-kill-is-subtree-p
8632 (buffer-substring region-start region-end))
8633 (error "The region is not a (sequence of) subtree(s)")))
8634 (if (equal goto '(16))
8635 (org-refile-goto-last-stored)
8636 (when (setq it (or rfloc
8637 (save-excursion
8638 (org-refile-get-location
8639 (if goto "Goto: " "Refile to: ") default-buffer
8640 org-refile-allow-creating-parent-nodes))))
8641 (setq file (nth 1 it)
8642 re (nth 2 it)
8643 pos (nth 3 it))
8644 (if (and (not goto)
8646 (equal (buffer-file-name) file)
8647 (if regionp
8648 (and (>= pos region-start)
8649 (<= pos region-end))
8650 (and (>= pos (point))
8651 (< pos (save-excursion
8652 (org-end-of-subtree t t))))))
8653 (error "Cannot refile to position inside the tree or region"))
8655 (setq nbuf (or (find-buffer-visiting file)
8656 (find-file-noselect file)))
8657 (if goto
8658 (progn
8659 (switch-to-buffer nbuf)
8660 (goto-char pos)
8661 (org-show-context 'org-goto))
8662 (if regionp
8663 (progn
8664 (org-kill-new (buffer-substring region-start region-end))
8665 (org-save-markers-in-region region-start region-end))
8666 (org-copy-subtree 1 nil t))
8667 (save-excursion
8668 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8669 (find-file-noselect file))))
8670 (setq reversed (org-notes-order-reversed-p))
8671 (save-excursion
8672 (save-restriction
8673 (widen)
8674 (if pos
8675 (progn
8676 (goto-char pos)
8677 (looking-at outline-regexp)
8678 (setq level (org-get-valid-level (funcall outline-level) 1))
8679 (goto-char
8680 (if reversed
8681 (or (outline-next-heading) (point-max))
8682 (or (save-excursion (outline-get-next-sibling))
8683 (org-end-of-subtree t t)
8684 (point-max)))))
8685 (setq level 1)
8686 (if (not reversed)
8687 (goto-char (point-max))
8688 (goto-char (point-min))
8689 (or (outline-next-heading) (goto-char (point-max)))))
8690 (if (not (bolp)) (newline))
8691 (bookmark-set "org-refile-last-stored")
8692 (org-paste-subtree level)
8693 (if (fboundp 'deactivate-mark) (deactivate-mark))
8694 (run-hooks 'org-after-refile-insert-hook))))
8695 (if regionp
8696 (delete-region (point) (+ (point) region-length))
8697 (org-cut-subtree))
8698 (when (featurep 'org-inlinetask)
8699 (org-inlinetask-remove-END-maybe))
8700 (setq org-markers-to-move nil)
8701 (message "Refiled to \"%s\"" (car it))))))
8702 (org-reveal))
8704 (defun org-refile-goto-last-stored ()
8705 "Go to the location where the last refile was stored."
8706 (interactive)
8707 (bookmark-jump "org-refile-last-stored")
8708 (message "This is the location of the last refile"))
8710 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
8711 "Prompt the user for a refile location, using PROMPT."
8712 (let ((org-refile-targets org-refile-targets)
8713 (org-refile-use-outline-path org-refile-use-outline-path))
8714 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8715 (unless org-refile-target-table
8716 (error "No refile targets"))
8717 (let* ((cbuf (current-buffer))
8718 (partial-completion-mode nil)
8719 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8720 (cfunc (if (and org-refile-use-outline-path
8721 org-outline-path-complete-in-steps)
8722 'org-olpath-completing-read
8723 'org-icompleting-read))
8724 (extra (if org-refile-use-outline-path "/" ""))
8725 (filename (and cfn (expand-file-name cfn)))
8726 (tbl (mapcar
8727 (lambda (x)
8728 (if (and (not (member org-refile-use-outline-path
8729 '(file full-file-path)))
8730 (not (equal filename (nth 1 x))))
8731 (cons (concat (car x) extra " ("
8732 (file-name-nondirectory (nth 1 x)) ")")
8733 (cdr x))
8734 (cons (concat (car x) extra) (cdr x))))
8735 org-refile-target-table))
8736 (completion-ignore-case t)
8737 pa answ parent-target child parent old-hist)
8738 (setq old-hist org-refile-history)
8739 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
8740 nil 'org-refile-history))
8741 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
8742 (if pa
8743 (progn
8744 (when (or (not org-refile-history)
8745 (not (eq old-hist org-refile-history))
8746 (not (equal (car pa) (car org-refile-history))))
8747 (setq org-refile-history
8748 (cons (car pa) (if (assoc (car org-refile-history) tbl)
8749 org-refile-history
8750 (cdr org-refile-history))))
8751 (if (equal (car org-refile-history) (nth 1 org-refile-history))
8752 (pop org-refile-history)))
8754 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
8755 (setq parent (match-string 1 answ)
8756 child (match-string 2 answ))
8757 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
8758 (when (and parent-target
8759 (or (eq new-nodes t)
8760 (and (eq new-nodes 'confirm)
8761 (y-or-n-p (format "Create new node \"%s\"? " child)))))
8762 (org-refile-new-child parent-target child))))))
8764 (defun org-refile-new-child (parent-target child)
8765 "Use refile target PARENT-TARGET to add new CHILD below it."
8766 (unless parent-target
8767 (error "Cannot find parent for new node"))
8768 (let ((file (nth 1 parent-target))
8769 (pos (nth 3 parent-target))
8770 level)
8771 (with-current-buffer (or (find-buffer-visiting file)
8772 (find-file-noselect file))
8773 (save-excursion
8774 (save-restriction
8775 (widen)
8776 (if pos
8777 (goto-char pos)
8778 (goto-char (point-max))
8779 (if (not (bolp)) (newline)))
8780 (when (looking-at outline-regexp)
8781 (setq level (funcall outline-level))
8782 (org-end-of-subtree t t))
8783 (org-back-over-empty-lines)
8784 (insert "\n" (make-string
8785 (if pos (org-get-valid-level level 1) 1) ?*)
8786 " " child "\n")
8787 (beginning-of-line 0)
8788 (list (concat (car parent-target) "/" child) file "" (point)))))))
8790 (defun org-olpath-completing-read (prompt collection &rest args)
8791 "Read an outline path like a file name."
8792 (let ((thetable collection)
8793 (org-completion-use-ido nil) ; does not work with ido.
8794 (org-completion-use-iswitchb nil)) ; or iswitchb
8795 (apply
8796 'org-icompleting-read prompt
8797 (lambda (string predicate &optional flag)
8798 (let (rtn r f (l (length string)))
8799 (cond
8800 ((eq flag nil)
8801 ;; try completion
8802 (try-completion string thetable))
8803 ((eq flag t)
8804 ;; all-completions
8805 (setq rtn (all-completions string thetable predicate))
8806 (mapcar
8807 (lambda (x)
8808 (setq r (substring x l))
8809 (if (string-match " ([^)]*)$" x)
8810 (setq f (match-string 0 x))
8811 (setq f ""))
8812 (if (string-match "/" r)
8813 (concat string (substring r 0 (match-end 0)) f)
8815 rtn))
8816 ((eq flag 'lambda)
8817 ;; exact match?
8818 (assoc string thetable)))
8820 args)))
8822 ;;;; Dynamic blocks
8824 (defun org-find-dblock (name)
8825 "Find the first dynamic block with name NAME in the buffer.
8826 If not found, stay at current position and return nil."
8827 (let (pos)
8828 (save-excursion
8829 (goto-char (point-min))
8830 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8831 nil t)
8832 (match-beginning 0))))
8833 (if pos (goto-char pos))
8834 pos))
8836 (defconst org-dblock-start-re
8837 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8838 "Matches the startline of a dynamic block, with parameters.")
8840 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8841 "Matches the end of a dynamic block.")
8843 (defun org-create-dblock (plist)
8844 "Create a dynamic block section, with parameters taken from PLIST.
8845 PLIST must contain a :name entry which is used as name of the block."
8846 (unless (bolp) (newline))
8847 (let ((name (plist-get plist :name)))
8848 (insert "#+BEGIN: " name)
8849 (while plist
8850 (if (eq (car plist) :name)
8851 (setq plist (cddr plist))
8852 (insert " " (prin1-to-string (pop plist)))))
8853 (insert "\n\n#+END:\n")
8854 (beginning-of-line -2)))
8856 (defun org-prepare-dblock ()
8857 "Prepare dynamic block for refresh.
8858 This empties the block, puts the cursor at the insert position and returns
8859 the property list including an extra property :name with the block name."
8860 (unless (looking-at org-dblock-start-re)
8861 (error "Not at a dynamic block"))
8862 (let* ((begdel (1+ (match-end 0)))
8863 (name (org-no-properties (match-string 1)))
8864 (params (append (list :name name)
8865 (read (concat "(" (match-string 3) ")")))))
8866 (unless (re-search-forward org-dblock-end-re nil t)
8867 (error "Dynamic block not terminated"))
8868 (setq params
8869 (append params
8870 (list :content (buffer-substring
8871 begdel (match-beginning 0)))))
8872 (delete-region begdel (match-beginning 0))
8873 (goto-char begdel)
8874 (open-line 1)
8875 params))
8877 (defun org-map-dblocks (&optional command)
8878 "Apply COMMAND to all dynamic blocks in the current buffer.
8879 If COMMAND is not given, use `org-update-dblock'."
8880 (let ((cmd (or command 'org-update-dblock))
8881 pos)
8882 (save-excursion
8883 (goto-char (point-min))
8884 (while (re-search-forward org-dblock-start-re nil t)
8885 (goto-char (setq pos (match-beginning 0)))
8886 (condition-case nil
8887 (funcall cmd)
8888 (error (message "Error during update of dynamic block")))
8889 (goto-char pos)
8890 (unless (re-search-forward org-dblock-end-re nil t)
8891 (error "Dynamic block not terminated"))))))
8893 (defun org-dblock-update (&optional arg)
8894 "User command for updating dynamic blocks.
8895 Update the dynamic block at point. With prefix ARG, update all dynamic
8896 blocks in the buffer."
8897 (interactive "P")
8898 (if arg
8899 (org-update-all-dblocks)
8900 (or (looking-at org-dblock-start-re)
8901 (org-beginning-of-dblock))
8902 (org-update-dblock)))
8904 (defun org-update-dblock ()
8905 "Update the dynamic block at point
8906 This means to empty the block, parse for parameters and then call
8907 the correct writing function."
8908 (save-window-excursion
8909 (let* ((pos (point))
8910 (line (org-current-line))
8911 (params (org-prepare-dblock))
8912 (name (plist-get params :name))
8913 (cmd (intern (concat "org-dblock-write:" name))))
8914 (message "Updating dynamic block `%s' at line %d..." name line)
8915 (funcall cmd params)
8916 (message "Updating dynamic block `%s' at line %d...done" name line)
8917 (goto-char pos))))
8919 (defun org-beginning-of-dblock ()
8920 "Find the beginning of the dynamic block at point.
8921 Error if there is no such block at point."
8922 (let ((pos (point))
8923 beg)
8924 (end-of-line 1)
8925 (if (and (re-search-backward org-dblock-start-re nil t)
8926 (setq beg (match-beginning 0))
8927 (re-search-forward org-dblock-end-re nil t)
8928 (> (match-end 0) pos))
8929 (goto-char beg)
8930 (goto-char pos)
8931 (error "Not in a dynamic block"))))
8933 (defun org-update-all-dblocks ()
8934 "Update all dynamic blocks in the buffer.
8935 This function can be used in a hook."
8936 (when (org-mode-p)
8937 (org-map-dblocks 'org-update-dblock)))
8940 ;;;; Completion
8942 (defconst org-additional-option-like-keywords
8943 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
8944 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
8945 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:" "ATTR_LaTeX"
8946 "BEGIN:" "END:"
8947 "ORGTBL" "TBLFM:" "TBLNAME:"
8948 "BEGIN_EXAMPLE" "END_EXAMPLE"
8949 "BEGIN_QUOTE" "END_QUOTE"
8950 "BEGIN_VERSE" "END_VERSE"
8951 "BEGIN_CENTER" "END_CENTER"
8952 "BEGIN_SRC" "END_SRC"
8953 "CATEGORY" "COLUMNS"
8954 "CAPTION" "LABEL"
8955 "BIND"))
8957 (defcustom org-structure-template-alist
8959 ("s" "#+begin_src ?\n\n#+end_src"
8960 "<src lang=\"?\">\n\n</src>")
8961 ("e" "#+begin_example\n?\n#+end_example"
8962 "<example>\n?\n</example>")
8963 ("q" "#+begin_quote\n?\n#+end_quote"
8964 "<quote>\n?\n</quote>")
8965 ("v" "#+begin_verse\n?\n#+end_verse"
8966 "<verse>\n?\n/verse>")
8967 ("c" "#+begin_center\n?\n#+end_center"
8968 "<center>\n?\n/center>")
8969 ("l" "#+begin_latex\n?\n#+end_latex"
8970 "<literal style=\"latex\">\n?\n</literal>")
8971 ("L" "#+latex: "
8972 "<literal style=\"latex\">?</literal>")
8973 ("h" "#+begin_html\n?\n#+end_html"
8974 "<literal style=\"html\">\n?\n</literal>")
8975 ("H" "#+html: "
8976 "<literal style=\"html\">?</literal>")
8977 ("a" "#+begin_ascii\n?\n#+end_ascii")
8978 ("A" "#+ascii: ")
8979 ("i" "#+include %file ?"
8980 "<include file=%file markup=\"?\">")
8982 "Structure completion elements.
8983 This is a list of abbreviation keys and values. The value gets inserted
8984 it you type @samp{.} followed by the key and then the completion key,
8985 usually `M-TAB'. %file will be replaced by a file name after prompting
8986 for the file using completion.
8987 There are two templates for each key, the first uses the original Org syntax,
8988 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8989 the default when the /org-mtags.el/ module has been loaded. See also the
8990 variable `org-mtags-prefer-muse-templates'.
8991 This is an experimental feature, it is undecided if it is going to stay in."
8992 :group 'org-completion
8993 :type '(repeat
8994 (string :tag "Key")
8995 (string :tag "Template")
8996 (string :tag "Muse Template")))
8998 (defun org-try-structure-completion ()
8999 "Try to complete a structure template before point.
9000 This looks for strings like \"<e\" on an otherwise empty line and
9001 expands them."
9002 (let ((l (buffer-substring (point-at-bol) (point)))
9004 (when (and (looking-at "[ \t]*$")
9005 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9006 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9007 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9008 (match-beginning 1)) a)
9009 t)))
9011 (defun org-complete-expand-structure-template (start cell)
9012 "Expand a structure template."
9013 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
9014 (rpl (nth (if musep 2 1) cell))
9015 (ind ""))
9016 (delete-region start (point))
9017 (when (string-match "\\`#\\+" rpl)
9018 (cond
9019 ((bolp))
9020 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
9021 (setq ind (buffer-substring (point-at-bol) (point))))
9022 (t (newline))))
9023 (setq start (point))
9024 (if (string-match "%file" rpl)
9025 (setq rpl (replace-match
9026 (concat
9027 "\""
9028 (save-match-data
9029 (abbreviate-file-name (read-file-name "Include file: ")))
9030 "\"")
9031 t t rpl)))
9032 (setq rpl (mapconcat 'identity (split-string rpl "\n")
9033 (concat "\n" ind)))
9034 (insert rpl)
9035 (if (re-search-backward "\\?" start t) (delete-char 1))))
9038 (defun org-complete (&optional arg)
9039 "Perform completion on word at point.
9040 At the beginning of a headline, this completes TODO keywords as given in
9041 `org-todo-keywords'.
9042 If the current word is preceded by a backslash, completes the TeX symbols
9043 that are supported for HTML support.
9044 If the current word is preceded by \"#+\", completes special words for
9045 setting file options.
9046 In the line after \"#+STARTUP:, complete valid keywords.\"
9047 At all other locations, this simply calls the value of
9048 `org-completion-fallback-command'."
9049 (interactive "P")
9050 (org-without-partial-completion
9051 (catch 'exit
9052 (let* ((a nil)
9053 (end (point))
9054 (beg1 (save-excursion
9055 (skip-chars-backward (org-re "[:alnum:]_@"))
9056 (point)))
9057 (beg (save-excursion
9058 (skip-chars-backward "a-zA-Z0-9_:$")
9059 (point)))
9060 (confirm (lambda (x) (stringp (car x))))
9061 (searchhead (equal (char-before beg) ?*))
9062 (struct
9063 (when (and (member (char-before beg1) '(?. ?<))
9064 (setq a (assoc (buffer-substring beg1 (point))
9065 org-structure-template-alist)))
9066 (org-complete-expand-structure-template (1- beg1) a)
9067 (throw 'exit t)))
9068 (tag (and (equal (char-before beg1) ?:)
9069 (equal (char-after (point-at-bol)) ?*)))
9070 (prop (and (equal (char-before beg1) ?:)
9071 (not (equal (char-after (point-at-bol)) ?*))))
9072 (texp (equal (char-before beg) ?\\))
9073 (link (equal (char-before beg) ?\[))
9074 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9075 beg)
9076 "#+"))
9077 (startup (string-match "^#\\+STARTUP:.*"
9078 (buffer-substring (point-at-bol) (point))))
9079 (completion-ignore-case opt)
9080 (type nil)
9081 (tbl nil)
9082 (table (cond
9083 (opt
9084 (setq type :opt)
9085 (require 'org-exp)
9086 (append
9087 (delq nil
9088 (mapcar
9089 (lambda (x)
9090 (if (string-match
9091 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9092 (cons (match-string 2 x)
9093 (match-string 1 x))))
9094 (org-split-string (org-get-current-options) "\n")))
9095 (mapcar 'list org-additional-option-like-keywords)))
9096 (startup
9097 (setq type :startup)
9098 org-startup-options)
9099 (link (append org-link-abbrev-alist-local
9100 org-link-abbrev-alist))
9101 (texp
9102 (setq type :tex)
9103 org-html-entities)
9104 ((string-match "\\`\\*+[ \t]+\\'"
9105 (buffer-substring (point-at-bol) beg))
9106 (setq type :todo)
9107 (mapcar 'list org-todo-keywords-1))
9108 (searchhead
9109 (setq type :searchhead)
9110 (save-excursion
9111 (goto-char (point-min))
9112 (while (re-search-forward org-todo-line-regexp nil t)
9113 (push (list
9114 (org-make-org-heading-search-string
9115 (match-string 3) t))
9116 tbl)))
9117 tbl)
9118 (tag (setq type :tag beg beg1)
9119 (or org-tag-alist (org-get-buffer-tags)))
9120 (prop (setq type :prop beg beg1)
9121 (mapcar 'list (org-buffer-property-keys nil t t)))
9122 (t (progn
9123 (call-interactively org-completion-fallback-command)
9124 (throw 'exit nil)))))
9125 (pattern (buffer-substring-no-properties beg end))
9126 (completion (try-completion pattern table confirm)))
9127 (cond ((eq completion t)
9128 (if (not (assoc (upcase pattern) table))
9129 (message "Already complete")
9130 (if (and (equal type :opt)
9131 (not (member (car (assoc (upcase pattern) table))
9132 org-additional-option-like-keywords)))
9133 (insert (substring (cdr (assoc (upcase pattern) table))
9134 (length pattern)))
9135 (if (memq type '(:tag :prop)) (insert ":")))))
9136 ((null completion)
9137 (message "Can't find completion for \"%s\"" pattern)
9138 (ding))
9139 ((not (string= pattern completion))
9140 (delete-region beg end)
9141 (if (string-match " +$" completion)
9142 (setq completion (replace-match "" t t completion)))
9143 (insert completion)
9144 (if (get-buffer-window "*Completions*")
9145 (delete-window (get-buffer-window "*Completions*")))
9146 (if (assoc completion table)
9147 (if (eq type :todo) (insert " ")
9148 (if (memq type '(:tag :prop)) (insert ":"))))
9149 (if (and (equal type :opt) (assoc completion table))
9150 (message "%s" (substitute-command-keys
9151 "Press \\[org-complete] again to insert example settings"))))
9153 (message "Making completion list...")
9154 (let ((list (sort (all-completions pattern table confirm)
9155 'string<)))
9156 (with-output-to-temp-buffer "*Completions*"
9157 (condition-case nil
9158 ;; Protection needed for XEmacs and emacs 21
9159 (display-completion-list list pattern)
9160 (error (display-completion-list list)))))
9161 (message "Making completion list...%s" "done")))))))
9163 ;;;; TODO, DEADLINE, Comments
9165 (defun org-toggle-comment ()
9166 "Change the COMMENT state of an entry."
9167 (interactive)
9168 (save-excursion
9169 (org-back-to-heading)
9170 (let (case-fold-search)
9171 (if (looking-at (concat outline-regexp
9172 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9173 (replace-match "" t t nil 1)
9174 (if (looking-at outline-regexp)
9175 (progn
9176 (goto-char (match-end 0))
9177 (insert org-comment-string " ")))))))
9179 (defvar org-last-todo-state-is-todo nil
9180 "This is non-nil when the last TODO state change led to a TODO state.
9181 If the last change removed the TODO tag or switched to DONE, then
9182 this is nil.")
9184 (defvar org-setting-tags nil) ; dynamically skipped
9186 (defun org-parse-local-options (string var)
9187 "Parse STRING for startup setting relevant for variable VAR."
9188 (let ((rtn (symbol-value var))
9189 e opts)
9190 (save-match-data
9191 (if (or (not string) (not (string-match "\\S-" string)))
9193 (setq opts (delq nil (mapcar (lambda (x)
9194 (setq e (assoc x org-startup-options))
9195 (if (eq (nth 1 e) var) e nil))
9196 (org-split-string string "[ \t]+"))))
9197 (if (not opts)
9199 (setq rtn nil)
9200 (while (setq e (pop opts))
9201 (if (not (nth 3 e))
9202 (setq rtn (nth 2 e))
9203 (if (not (listp rtn)) (setq rtn nil))
9204 (push (nth 2 e) rtn)))
9205 rtn)))))
9207 (defvar org-todo-setup-filter-hook nil
9208 "Hook for functions that pre-filter todo specs.
9210 Each function takes a todo spec and returns either `nil' or the spec
9211 transformed into canonical form." )
9213 (defvar org-todo-get-default-hook nil
9214 "Hook for functions that get a default item for todo.
9216 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9217 `nil' or a string to be used for the todo mark." )
9219 (defvar org-agenda-headline-snapshot-before-repeat)
9221 (defun org-todo (&optional arg)
9222 "Change the TODO state of an item.
9223 The state of an item is given by a keyword at the start of the heading,
9224 like
9225 *** TODO Write paper
9226 *** DONE Call mom
9228 The different keywords are specified in the variable `org-todo-keywords'.
9229 By default the available states are \"TODO\" and \"DONE\".
9230 So for this example: when the item starts with TODO, it is changed to DONE.
9231 When it starts with DONE, the DONE is removed. And when neither TODO nor
9232 DONE are present, add TODO at the beginning of the heading.
9234 With C-u prefix arg, use completion to determine the new state.
9235 With numeric prefix arg, switch to that state.
9236 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9237 With a tripple C-u prefix, circumvent any state blocking.
9239 For calling through lisp, arg is also interpreted in the following way:
9240 'none -> empty state
9241 \"\"(empty string) -> switch to empty state
9242 'done -> switch to DONE
9243 'nextset -> switch to the next set of keywords
9244 'previousset -> switch to the previous set of keywords
9245 \"WAITING\" -> switch to the specified keyword, but only if it
9246 really is a member of `org-todo-keywords'."
9247 (interactive "P")
9248 (if (equal arg '(16)) (setq arg 'nextset))
9249 (let ((org-blocker-hook org-blocker-hook)
9250 (case-fold-search nil))
9251 (when (equal arg '(64))
9252 (setq arg nil org-blocker-hook nil))
9253 (when (and org-blocker-hook
9254 (or org-inhibit-blocking
9255 (org-entry-get nil "NOBLOCKING")))
9256 (setq org-blocker-hook nil))
9257 (save-excursion
9258 (catch 'exit
9259 (org-back-to-heading)
9260 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9261 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9262 (looking-at " *"))
9263 (let* ((match-data (match-data))
9264 (startpos (point-at-bol))
9265 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9266 (org-log-done org-log-done)
9267 (org-log-repeat org-log-repeat)
9268 (org-todo-log-states org-todo-log-states)
9269 (this (match-string 1))
9270 (hl-pos (match-beginning 0))
9271 (head (org-get-todo-sequence-head this))
9272 (ass (assoc head org-todo-kwd-alist))
9273 (interpret (nth 1 ass))
9274 (done-word (nth 3 ass))
9275 (final-done-word (nth 4 ass))
9276 (last-state (or this ""))
9277 (completion-ignore-case t)
9278 (member (member this org-todo-keywords-1))
9279 (tail (cdr member))
9280 (state (cond
9281 ((and org-todo-key-trigger
9282 (or (and (equal arg '(4))
9283 (eq org-use-fast-todo-selection 'prefix))
9284 (and (not arg) org-use-fast-todo-selection
9285 (not (eq org-use-fast-todo-selection
9286 'prefix)))))
9287 ;; Use fast selection
9288 (org-fast-todo-selection))
9289 ((and (equal arg '(4))
9290 (or (not org-use-fast-todo-selection)
9291 (not org-todo-key-trigger)))
9292 ;; Read a state with completion
9293 (org-icompleting-read
9294 "State: " (mapcar (lambda(x) (list x))
9295 org-todo-keywords-1)
9296 nil t))
9297 ((eq arg 'right)
9298 (if this
9299 (if tail (car tail) nil)
9300 (car org-todo-keywords-1)))
9301 ((eq arg 'left)
9302 (if (equal member org-todo-keywords-1)
9304 (if this
9305 (nth (- (length org-todo-keywords-1)
9306 (length tail) 2)
9307 org-todo-keywords-1)
9308 (org-last org-todo-keywords-1))))
9309 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9310 (setq arg nil))) ; hack to fall back to cycling
9311 (arg
9312 ;; user or caller requests a specific state
9313 (cond
9314 ((equal arg "") nil)
9315 ((eq arg 'none) nil)
9316 ((eq arg 'done) (or done-word (car org-done-keywords)))
9317 ((eq arg 'nextset)
9318 (or (car (cdr (member head org-todo-heads)))
9319 (car org-todo-heads)))
9320 ((eq arg 'previousset)
9321 (let ((org-todo-heads (reverse org-todo-heads)))
9322 (or (car (cdr (member head org-todo-heads)))
9323 (car org-todo-heads))))
9324 ((car (member arg org-todo-keywords-1)))
9325 ((nth (1- (prefix-numeric-value arg))
9326 org-todo-keywords-1))))
9327 ((null member) (or head (car org-todo-keywords-1)))
9328 ((equal this final-done-word) nil) ;; -> make empty
9329 ((null tail) nil) ;; -> first entry
9330 ((memq interpret '(type priority))
9331 (if (eq this-command last-command)
9332 (car tail)
9333 (if (> (length tail) 0)
9334 (or done-word (car org-done-keywords))
9335 nil)))
9337 (car tail))))
9338 (state (or
9339 (run-hook-with-args-until-success
9340 'org-todo-get-default-hook state last-state)
9341 state))
9342 (next (if state (concat " " state " ") " "))
9343 (change-plist (list :type 'todo-state-change :from this :to state
9344 :position startpos))
9345 dolog now-done-p)
9346 (when org-blocker-hook
9347 (setq org-last-todo-state-is-todo
9348 (not (member this org-done-keywords)))
9349 (unless (save-excursion
9350 (save-match-data
9351 (run-hook-with-args-until-failure
9352 'org-blocker-hook change-plist)))
9353 (if (interactive-p)
9354 (error "TODO state change from %s to %s blocked" this state)
9355 ;; fail silently
9356 (message "TODO state change from %s to %s blocked" this state)
9357 (throw 'exit nil))))
9358 (store-match-data match-data)
9359 (replace-match next t t)
9360 (unless (pos-visible-in-window-p hl-pos)
9361 (message "TODO state changed to %s" (org-trim next)))
9362 (unless head
9363 (setq head (org-get-todo-sequence-head state)
9364 ass (assoc head org-todo-kwd-alist)
9365 interpret (nth 1 ass)
9366 done-word (nth 3 ass)
9367 final-done-word (nth 4 ass)))
9368 (when (memq arg '(nextset previousset))
9369 (message "Keyword-Set %d/%d: %s"
9370 (- (length org-todo-sets) -1
9371 (length (memq (assoc state org-todo-sets) org-todo-sets)))
9372 (length org-todo-sets)
9373 (mapconcat 'identity (assoc state org-todo-sets) " ")))
9374 (setq org-last-todo-state-is-todo
9375 (not (member state org-done-keywords)))
9376 (setq now-done-p (and (member state org-done-keywords)
9377 (not (member this org-done-keywords))))
9378 (and logging (org-local-logging logging))
9379 (when (and (or org-todo-log-states org-log-done)
9380 (not (eq org-inhibit-logging t))
9381 (not (memq arg '(nextset previousset))))
9382 ;; we need to look at recording a time and note
9383 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
9384 (nth 2 (assoc this org-todo-log-states))))
9385 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
9386 (setq dolog 'time))
9387 (when (and state
9388 (member state org-not-done-keywords)
9389 (not (member this org-not-done-keywords)))
9390 ;; This is now a todo state and was not one before
9391 ;; If there was a CLOSED time stamp, get rid of it.
9392 (org-add-planning-info nil nil 'closed))
9393 (when (and now-done-p org-log-done)
9394 ;; It is now done, and it was not done before
9395 (org-add-planning-info 'closed (org-current-time))
9396 (if (and (not dolog) (eq 'note org-log-done))
9397 (org-add-log-setup 'done state this 'findpos 'note)))
9398 (when (and state dolog)
9399 ;; This is a non-nil state, and we need to log it
9400 (org-add-log-setup 'state state this 'findpos dolog)))
9401 ;; Fixup tag positioning
9402 (org-todo-trigger-tag-changes state)
9403 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
9404 (when org-provide-todo-statistics
9405 (org-update-parent-todo-statistics))
9406 (run-hooks 'org-after-todo-state-change-hook)
9407 (if (and arg (not (member state org-done-keywords)))
9408 (setq head (org-get-todo-sequence-head state)))
9409 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9410 ;; Do we need to trigger a repeat?
9411 (when now-done-p
9412 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
9413 ;; This is for the agenda, take a snapshot of the headline.
9414 (save-match-data
9415 (setq org-agenda-headline-snapshot-before-repeat
9416 (org-get-heading))))
9417 (org-auto-repeat-maybe state))
9418 ;; Fixup cursor location if close to the keyword
9419 (if (and (outline-on-heading-p)
9420 (not (bolp))
9421 (save-excursion (beginning-of-line 1)
9422 (looking-at org-todo-line-regexp))
9423 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9424 (progn
9425 (goto-char (or (match-end 2) (match-end 1)))
9426 (and (looking-at " ") (just-one-space))))
9427 (when org-trigger-hook
9428 (save-excursion
9429 (run-hook-with-args 'org-trigger-hook change-plist))))))))
9431 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
9432 "Block turning an entry into a TODO, using the hierarchy.
9433 This checks whether the current task should be blocked from state
9434 changes. Such blocking occurs when:
9436 1. The task has children which are not all in a completed state.
9438 2. A task has a parent with the property :ORDERED:, and there
9439 are siblings prior to the current task with incomplete
9440 status.
9442 3. The parent of the task is blocked because it has siblings that should
9443 be done first, or is child of a block grandparent TODO entry."
9445 (catch 'dont-block
9446 ;; If this is not a todo state change, or if this entry is already DONE,
9447 ;; do not block
9448 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9449 (member (plist-get change-plist :from)
9450 (cons 'done org-done-keywords))
9451 (member (plist-get change-plist :to)
9452 (cons 'todo org-not-done-keywords)))
9453 (throw 'dont-block t))
9454 ;; If this task has children, and any are undone, it's blocked
9455 (save-excursion
9456 (org-back-to-heading t)
9457 (let ((this-level (funcall outline-level)))
9458 (outline-next-heading)
9459 (let ((child-level (funcall outline-level)))
9460 (while (and (not (eobp))
9461 (> child-level this-level))
9462 ;; this todo has children, check whether they are all
9463 ;; completed
9464 (if (and (not (org-entry-is-done-p))
9465 (org-entry-is-todo-p))
9466 (throw 'dont-block nil))
9467 (outline-next-heading)
9468 (setq child-level (funcall outline-level))))))
9469 ;; Otherwise, if the task's parent has the :ORDERED: property, and
9470 ;; any previous siblings are undone, it's blocked
9471 (save-excursion
9472 (org-back-to-heading t)
9473 (let* ((pos (point))
9474 (parent-pos (and (org-up-heading-safe) (point))))
9475 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9476 (when (and (org-entry-get (point) "ORDERED")
9477 (forward-line 1)
9478 (re-search-forward org-not-done-heading-regexp pos t))
9479 (throw 'dont-block nil)) ; block, there is an older sibling not done.
9480 ;; Search further up the hierarchy, to see if an anchestor is blocked
9481 (while t
9482 (goto-char parent-pos)
9483 (if (not (looking-at org-not-done-heading-regexp))
9484 (throw 'dont-block t)) ; do not block, parent is not a TODO
9485 (setq pos (point))
9486 (setq parent-pos (and (org-up-heading-safe) (point)))
9487 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9488 (when (and (org-entry-get (point) "ORDERED")
9489 (forward-line 1)
9490 (re-search-forward org-not-done-heading-regexp pos t))
9491 (throw 'dont-block nil))))))) ; block, older sibling not done.
9493 (defcustom org-track-ordered-property-with-tag nil
9494 "Should the ORDERED property also be shown as a tag?
9495 The ORDERED property decides if an entry should require subtasks to be
9496 completed in sequence. Since a property is not very visible, setting
9497 this option means that toggling the ORDERED property with the command
9498 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
9499 not relevant for the behavior, but it makes things more visible.
9501 Note that toggling the tag with tags commands will not change the property
9502 and therefore not influence behavior!
9504 This can be t, meaning the tag ORDERED should be used, It can also be a
9505 string to select a different tag for this task."
9506 :group 'org-todo
9507 :type '(choice
9508 (const :tag "No tracking" nil)
9509 (const :tag "Track with ORDERED tag" t)
9510 (string :tag "Use other tag")))
9512 (defun org-toggle-ordered-property ()
9513 "Toggle the ORDERED property of the current entry.
9514 For better visibility, you can track the value of this property with a tag.
9515 See variable `org-track-ordered-property-with-tag'."
9516 (interactive)
9517 (let* ((t1 org-track-ordered-property-with-tag)
9518 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
9519 (save-excursion
9520 (org-back-to-heading)
9521 (if (org-entry-get nil "ORDERED")
9522 (progn
9523 (org-delete-property "ORDERED")
9524 (and tag (org-toggle-tag tag 'off))
9525 (message "Subtasks can be completed in arbitrary order"))
9526 (org-entry-put nil "ORDERED" "t")
9527 (and tag (org-toggle-tag tag 'on))
9528 (message "Subtasks must be completed in sequence")))))
9530 (defvar org-blocked-by-checkboxes) ; dynamically scoped
9531 (defun org-block-todo-from-checkboxes (change-plist)
9532 "Block turning an entry into a TODO, using checkboxes.
9533 This checks whether the current task should be blocked from state
9534 changes because there are uncheckd boxes in this entry."
9535 (catch 'dont-block
9536 ;; If this is not a todo state change, or if this entry is already DONE,
9537 ;; do not block
9538 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9539 (member (plist-get change-plist :from)
9540 (cons 'done org-done-keywords))
9541 (member (plist-get change-plist :to)
9542 (cons 'todo org-not-done-keywords)))
9543 (throw 'dont-block t))
9544 ;; If this task has checkboxes that are not checked, it's blocked
9545 (save-excursion
9546 (org-back-to-heading t)
9547 (let ((beg (point)) end)
9548 (outline-next-heading)
9549 (setq end (point))
9550 (goto-char beg)
9551 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
9552 end t)
9553 (progn
9554 (if (boundp 'org-blocked-by-checkboxes)
9555 (setq org-blocked-by-checkboxes t))
9556 (throw 'dont-block nil)))))
9557 t)) ; do not block
9559 (defvar org-entry-property-inherited-from) ;; defined below
9560 (defun org-update-parent-todo-statistics ()
9561 "Update any statistics cookie in the parent of the current headline.
9562 When `org-hierarchical-todo-statistics' is nil, statistics will cover
9563 the entire subtree and this will travel up the hierarchy and update
9564 statistics everywhere."
9565 (interactive)
9566 (let* ((lim 0) prop
9567 (recursive (or (not org-hierarchical-todo-statistics)
9568 (string-match
9569 "\\<recursive\\>"
9570 (or (setq prop (org-entry-get
9571 nil "COOKIE_DATA" 'inherit)) ""))))
9572 (lim (or (and prop (marker-position
9573 org-entry-property-inherited-from))
9574 lim))
9575 (first t)
9576 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
9577 level ltoggle l1
9578 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
9579 (catch 'exit
9580 (save-excursion
9581 (beginning-of-line 1)
9582 (if (org-at-heading-p)
9583 (setq ltoggle (funcall outline-level))
9584 (error "This should not happen"))
9585 (while (and (setq level (org-up-heading-safe))
9586 (or recursive first)
9587 (>= (point) lim))
9588 (setq first nil)
9589 (unless (and level
9590 (not (string-match
9591 "\\<checkbox\\>"
9592 (downcase
9593 (or (org-entry-get
9594 nil "COOKIE_DATA")
9595 "")))))
9596 (throw 'exit nil))
9597 (while (re-search-forward box-re (point-at-eol) t)
9598 (setq cnt-all 0 cnt-done 0 cookie-present t)
9599 (setq is-percent (match-end 2))
9600 (save-match-data
9601 (unless (outline-next-heading) (throw 'exit nil))
9602 (while (and (looking-at org-complex-heading-regexp)
9603 (> (setq l1 (length (match-string 1))) level))
9604 (setq kwd (and (or recursive (= l1 ltoggle))
9605 (match-string 2)))
9606 (if (or (eq org-provide-todo-statistics 'all-headlines)
9607 (and (listp org-provide-todo-statistics)
9608 (or (member kwd org-provide-todo-statistics)
9609 (member kwd org-done-keywords))))
9610 (setq cnt-all (1+ cnt-all))
9611 (if (eq org-provide-todo-statistics t)
9612 (and kwd (setq cnt-all (1+ cnt-all)))))
9613 (and (member kwd org-done-keywords)
9614 (setq cnt-done (1+ cnt-done)))
9615 (outline-next-heading)))
9616 (replace-match
9617 (if is-percent
9618 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
9619 (format "[%d/%d]" cnt-done cnt-all)))))
9620 (when cookie-present
9621 (run-hook-with-args 'org-after-todo-statistics-hook
9622 cnt-done (- cnt-all cnt-done)))))
9623 (run-hooks 'org-todo-statistics-hook)))
9625 (defvar org-after-todo-statistics-hook nil
9626 "Hook that is called after a TODO statistics cookie has been updated.
9627 Each function is called with two arguments: the number of not-done entries
9628 and the number of done entries.
9630 For example, the following function, when added to this hook, will switch
9631 an entry to DONE when all children are done, and back to TODO when new
9632 entries are set to a TODO status. Note that this hook is only called
9633 when there is a statistics cookie in the headline!
9635 (defun org-summary-todo (n-done n-not-done)
9636 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
9637 (let (org-log-done org-log-states) ; turn off logging
9638 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
9641 (defvar org-todo-statistics-hook nil
9642 "Hook that is run whenever Org thinks TODO statistics should be updated.
9643 This hook runs even if there is no statisics cookie present, in which case
9644 `org-after-todo-statistics-hook' would not run.")
9646 (defun org-todo-trigger-tag-changes (state)
9647 "Apply the changes defined in `org-todo-state-tags-triggers'."
9648 (let ((l org-todo-state-tags-triggers)
9649 changes)
9650 (when (or (not state) (equal state ""))
9651 (setq changes (append changes (cdr (assoc "" l)))))
9652 (when (and (stringp state) (> (length state) 0))
9653 (setq changes (append changes (cdr (assoc state l)))))
9654 (when (member state org-not-done-keywords)
9655 (setq changes (append changes (cdr (assoc 'todo l)))))
9656 (when (member state org-done-keywords)
9657 (setq changes (append changes (cdr (assoc 'done l)))))
9658 (dolist (c changes)
9659 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
9661 (defun org-local-logging (value)
9662 "Get logging settings from a property VALUE."
9663 (let* (words w a)
9664 ;; directly set the variables, they are already local.
9665 (setq org-log-done nil
9666 org-log-repeat nil
9667 org-todo-log-states nil)
9668 (setq words (org-split-string value))
9669 (while (setq w (pop words))
9670 (cond
9671 ((setq a (assoc w org-startup-options))
9672 (and (member (nth 1 a) '(org-log-done org-log-repeat))
9673 (set (nth 1 a) (nth 2 a))))
9674 ((setq a (org-extract-log-state-settings w))
9675 (and (member (car a) org-todo-keywords-1)
9676 (push a org-todo-log-states)))))))
9678 (defun org-get-todo-sequence-head (kwd)
9679 "Return the head of the TODO sequence to which KWD belongs.
9680 If KWD is not set, check if there is a text property remembering the
9681 right sequence."
9682 (let (p)
9683 (cond
9684 ((not kwd)
9685 (or (get-text-property (point-at-bol) 'org-todo-head)
9686 (progn
9687 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
9688 nil (point-at-eol)))
9689 (get-text-property p 'org-todo-head))))
9690 ((not (member kwd org-todo-keywords-1))
9691 (car org-todo-keywords-1))
9692 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
9694 (defun org-fast-todo-selection ()
9695 "Fast TODO keyword selection with single keys.
9696 Returns the new TODO keyword, or nil if no state change should occur."
9697 (let* ((fulltable org-todo-key-alist)
9698 (done-keywords org-done-keywords) ;; needed for the faces.
9699 (maxlen (apply 'max (mapcar
9700 (lambda (x)
9701 (if (stringp (car x)) (string-width (car x)) 0))
9702 fulltable)))
9703 (expert nil)
9704 (fwidth (+ maxlen 3 1 3))
9705 (ncol (/ (- (window-width) 4) fwidth))
9706 tg cnt e c tbl
9707 groups ingroup)
9708 (save-excursion
9709 (save-window-excursion
9710 (if expert
9711 (set-buffer (get-buffer-create " *Org todo*"))
9712 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
9713 (erase-buffer)
9714 (org-set-local 'org-done-keywords done-keywords)
9715 (setq tbl fulltable cnt 0)
9716 (while (setq e (pop tbl))
9717 (cond
9718 ((equal e '(:startgroup))
9719 (push '() groups) (setq ingroup t)
9720 (when (not (= cnt 0))
9721 (setq cnt 0)
9722 (insert "\n"))
9723 (insert "{ "))
9724 ((equal e '(:endgroup))
9725 (setq ingroup nil cnt 0)
9726 (insert "}\n"))
9727 ((equal e '(:newline))
9728 (when (not (= cnt 0))
9729 (setq cnt 0)
9730 (insert "\n")
9731 (setq e (car tbl))
9732 (while (equal (car tbl) '(:newline))
9733 (insert "\n")
9734 (setq tbl (cdr tbl)))))
9736 (setq tg (car e) c (cdr e))
9737 (if ingroup (push tg (car groups)))
9738 (setq tg (org-add-props tg nil 'face
9739 (org-get-todo-face tg)))
9740 (if (and (= cnt 0) (not ingroup)) (insert " "))
9741 (insert "[" c "] " tg (make-string
9742 (- fwidth 4 (length tg)) ?\ ))
9743 (when (= (setq cnt (1+ cnt)) ncol)
9744 (insert "\n")
9745 (if ingroup (insert " "))
9746 (setq cnt 0)))))
9747 (insert "\n")
9748 (goto-char (point-min))
9749 (if (not expert) (org-fit-window-to-buffer))
9750 (message "[a-z..]:Set [SPC]:clear")
9751 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9752 (cond
9753 ((or (= c ?\C-g)
9754 (and (= c ?q) (not (rassoc c fulltable))))
9755 (setq quit-flag t))
9756 ((= c ?\ ) nil)
9757 ((setq e (rassoc c fulltable) tg (car e))
9759 (t (setq quit-flag t)))))))
9761 (defun org-entry-is-todo-p ()
9762 (member (org-get-todo-state) org-not-done-keywords))
9764 (defun org-entry-is-done-p ()
9765 (member (org-get-todo-state) org-done-keywords))
9767 (defun org-get-todo-state ()
9768 (save-excursion
9769 (org-back-to-heading t)
9770 (and (looking-at org-todo-line-regexp)
9771 (match-end 2)
9772 (match-string 2))))
9774 (defun org-at-date-range-p (&optional inactive-ok)
9775 "Is the cursor inside a date range?"
9776 (interactive)
9777 (save-excursion
9778 (catch 'exit
9779 (let ((pos (point)))
9780 (skip-chars-backward "^[<\r\n")
9781 (skip-chars-backward "<[")
9782 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9783 (>= (match-end 0) pos)
9784 (throw 'exit t))
9785 (skip-chars-backward "^<[\r\n")
9786 (skip-chars-backward "<[")
9787 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9788 (>= (match-end 0) pos)
9789 (throw 'exit t)))
9790 nil)))
9792 (defun org-get-repeat ()
9793 "Check if there is a deadline/schedule with repeater in this entry."
9794 (save-match-data
9795 (save-excursion
9796 (org-back-to-heading t)
9797 (if (re-search-forward
9798 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9799 (match-string 1)))))
9801 (defvar org-last-changed-timestamp)
9802 (defvar org-last-inserted-timestamp)
9803 (defvar org-log-post-message)
9804 (defvar org-log-note-purpose)
9805 (defvar org-log-note-how)
9806 (defvar org-log-note-extra)
9807 (defun org-auto-repeat-maybe (done-word)
9808 "Check if the current headline contains a repeated deadline/schedule.
9809 If yes, set TODO state back to what it was and change the base date
9810 of repeating deadline/scheduled time stamps to new date.
9811 This function is run automatically after each state change to a DONE state."
9812 ;; last-state is dynamically scoped into this function
9813 (let* ((repeat (org-get-repeat))
9814 (aa (assoc last-state org-todo-kwd-alist))
9815 (interpret (nth 1 aa))
9816 (head (nth 2 aa))
9817 (whata '(("d" . day) ("m" . month) ("y" . year)))
9818 (msg "Entry repeats: ")
9819 (org-log-done nil)
9820 (org-todo-log-states nil)
9821 (nshiftmax 10) (nshift 0)
9822 re type n what ts time)
9823 (when repeat
9824 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9825 (org-todo (if (eq interpret 'type) last-state head))
9826 (org-entry-put nil "LAST_REPEAT" (format-time-string
9827 (org-time-stamp-format t t)))
9828 (when org-log-repeat
9829 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9830 (memq 'org-add-log-note post-command-hook))
9831 ;; OK, we are already setup for some record
9832 (if (eq org-log-repeat 'note)
9833 ;; make sure we take a note, not only a time stamp
9834 (setq org-log-note-how 'note))
9835 ;; Set up for taking a record
9836 (org-add-log-setup 'state (or done-word (car org-done-keywords))
9837 last-state
9838 'findpos org-log-repeat)))
9839 (org-back-to-heading t)
9840 (org-add-planning-info nil nil 'closed)
9841 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9842 org-deadline-time-regexp "\\)\\|\\("
9843 org-ts-regexp "\\)"))
9844 (while (re-search-forward
9845 re (save-excursion (outline-next-heading) (point)) t)
9846 (setq type (if (match-end 1) org-scheduled-string
9847 (if (match-end 3) org-deadline-string "Plain:"))
9848 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
9849 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
9850 (setq n (string-to-number (match-string 2 ts))
9851 what (match-string 3 ts))
9852 (if (equal what "w") (setq n (* n 7) what "d"))
9853 ;; Preparation, see if we need to modify the start date for the change
9854 (when (match-end 1)
9855 (setq time (save-match-data (org-time-string-to-time ts)))
9856 (cond
9857 ((equal (match-string 1 ts) ".")
9858 ;; Shift starting date to today
9859 (org-timestamp-change
9860 (- (time-to-days (current-time)) (time-to-days time))
9861 'day))
9862 ((equal (match-string 1 ts) "+")
9863 (while (or (= nshift 0)
9864 (<= (time-to-days time) (time-to-days (current-time))))
9865 (when (= (incf nshift) nshiftmax)
9866 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
9867 (error "Abort")))
9868 (org-timestamp-change n (cdr (assoc what whata)))
9869 (org-at-timestamp-p t)
9870 (setq ts (match-string 1))
9871 (setq time (save-match-data (org-time-string-to-time ts))))
9872 (org-timestamp-change (- n) (cdr (assoc what whata)))
9873 ;; rematch, so that we have everything in place for the real shift
9874 (org-at-timestamp-p t)
9875 (setq ts (match-string 1))
9876 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
9877 (org-timestamp-change n (cdr (assoc what whata)))
9878 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
9879 (setq org-log-post-message msg)
9880 (message "%s" msg))))
9882 (defun org-show-todo-tree (arg)
9883 "Make a compact tree which shows all headlines marked with TODO.
9884 The tree will show the lines where the regexp matches, and all higher
9885 headlines above the match.
9886 With a \\[universal-argument] prefix, prompt for a regexp to match.
9887 With a numeric prefix N, construct a sparse tree for the Nth element
9888 of `org-todo-keywords-1'."
9889 (interactive "P")
9890 (let ((case-fold-search nil)
9891 (kwd-re
9892 (cond ((null arg) org-not-done-regexp)
9893 ((equal arg '(4))
9894 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
9895 (mapcar 'list org-todo-keywords-1))))
9896 (concat "\\("
9897 (mapconcat 'identity (org-split-string kwd "|") "\\|")
9898 "\\)\\>")))
9899 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
9900 (regexp-quote (nth (1- (prefix-numeric-value arg))
9901 org-todo-keywords-1)))
9902 (t (error "Invalid prefix argument: %s" arg)))))
9903 (message "%d TODO entries found"
9904 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
9906 (defun org-deadline (&optional remove time)
9907 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
9908 With argument REMOVE, remove any deadline from the item.
9909 When TIME is set, it should be an internal time specification, and the
9910 scheduling will use the corresponding date."
9911 (interactive "P")
9912 (if remove
9913 (progn
9914 (org-remove-timestamp-with-keyword org-deadline-string)
9915 (message "Item no longer has a deadline."))
9916 (if (org-get-repeat)
9917 (error "Cannot change deadline on task with repeater, please do that by hand")
9918 (org-add-planning-info 'deadline time 'closed)
9919 (message "Deadline on %s" org-last-inserted-timestamp))))
9921 (defun org-schedule (&optional remove time)
9922 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
9923 With argument REMOVE, remove any scheduling date from the item.
9924 When TIME is set, it should be an internal time specification, and the
9925 scheduling will use the corresponding date."
9926 (interactive "P")
9927 (if remove
9928 (progn
9929 (org-remove-timestamp-with-keyword org-scheduled-string)
9930 (message "Item is no longer scheduled."))
9931 (if (org-get-repeat)
9932 (error "Cannot reschedule task with repeater, please do that by hand")
9933 (org-add-planning-info 'scheduled time 'closed)
9934 (message "Scheduled to %s" org-last-inserted-timestamp))))
9936 (defun org-get-scheduled-time (pom &optional inherit)
9937 "Get the scheduled time as a time tuple, of a format suitable
9938 for calling org-schedule with, or if there is no scheduling,
9939 returns nil."
9940 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
9941 (when time
9942 (apply 'encode-time (org-parse-time-string time)))))
9944 (defun org-get-deadline-time (pom &optional inherit)
9945 "Get the deadine as a time tuple, of a format suitable for
9946 calling org-deadlin with, or if there is no scheduling, returns
9947 nil."
9948 (let ((time (org-entry-get pom "DEADLINE" inherit)))
9949 (when time
9950 (apply 'encode-time (org-parse-time-string time)))))
9952 (defun org-remove-timestamp-with-keyword (keyword)
9953 "Remove all time stamps with KEYWORD in the current entry."
9954 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
9955 beg)
9956 (save-excursion
9957 (org-back-to-heading t)
9958 (setq beg (point))
9959 (org-end-of-subtree t t)
9960 (while (re-search-backward re beg t)
9961 (replace-match "")
9962 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9963 (equal (char-before) ?\ ))
9964 (backward-delete-char 1)
9965 (if (string-match "^[ \t]*$" (buffer-substring
9966 (point-at-bol) (point-at-eol)))
9967 (delete-region (point-at-bol)
9968 (min (point-max) (1+ (point-at-eol))))))))))
9970 (defun org-add-planning-info (what &optional time &rest remove)
9971 "Insert new timestamp with keyword in the line directly after the headline.
9972 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9973 If non is given, the user is prompted for a date.
9974 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9975 be removed."
9976 (interactive)
9977 (let (org-time-was-given org-end-time-was-given ts
9978 end default-time default-input)
9980 (catch 'exit
9981 (when (and (not time) (memq what '(scheduled deadline)))
9982 ;; Try to get a default date/time from existing timestamp
9983 (save-excursion
9984 (org-back-to-heading t)
9985 (setq end (save-excursion (outline-next-heading) (point)))
9986 (when (re-search-forward (if (eq what 'scheduled)
9987 org-scheduled-time-regexp
9988 org-deadline-time-regexp)
9989 end t)
9990 (setq ts (match-string 1)
9991 default-time
9992 (apply 'encode-time (org-parse-time-string ts))
9993 default-input (and ts (org-get-compact-tod ts))))))
9994 (when what
9995 ;; If necessary, get the time from the user
9996 (setq time (or time (org-read-date nil 'to-time nil nil
9997 default-time default-input))))
9999 (when (and org-insert-labeled-timestamps-at-point
10000 (member what '(scheduled deadline)))
10001 (insert
10002 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
10003 (org-insert-time-stamp time org-time-was-given
10004 nil nil nil (list org-end-time-was-given))
10005 (setq what nil))
10006 (save-excursion
10007 (save-restriction
10008 (let (col list elt ts buffer-invisibility-spec)
10009 (org-back-to-heading t)
10010 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
10011 (goto-char (match-end 1))
10012 (setq col (current-column))
10013 (goto-char (match-end 0))
10014 (if (eobp) (insert "\n") (forward-char 1))
10015 (when (and (not what)
10016 (not (looking-at
10017 (concat "[ \t]*"
10018 org-keyword-time-not-clock-regexp))))
10019 ;; Nothing to add, nothing to remove...... :-)
10020 (throw 'exit nil))
10021 (if (and (not (looking-at outline-regexp))
10022 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
10023 "[^\r\n]*"))
10024 (not (equal (match-string 1) org-clock-string)))
10025 (narrow-to-region (match-beginning 0) (match-end 0))
10026 (insert-before-markers "\n")
10027 (backward-char 1)
10028 (narrow-to-region (point) (point))
10029 (and org-adapt-indentation (org-indent-to-column col)))
10030 ;; Check if we have to remove something.
10031 (setq list (cons what remove))
10032 (while list
10033 (setq elt (pop list))
10034 (goto-char (point-min))
10035 (when (or (and (eq elt 'scheduled)
10036 (re-search-forward org-scheduled-time-regexp nil t))
10037 (and (eq elt 'deadline)
10038 (re-search-forward org-deadline-time-regexp nil t))
10039 (and (eq elt 'closed)
10040 (re-search-forward org-closed-time-regexp nil t)))
10041 (replace-match "")
10042 (if (looking-at "--+<[^>]+>") (replace-match ""))
10043 (if (looking-at " +") (replace-match ""))))
10044 (goto-char (point-max))
10045 (when what
10046 (insert
10047 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
10048 (cond ((eq what 'scheduled) org-scheduled-string)
10049 ((eq what 'deadline) org-deadline-string)
10050 ((eq what 'closed) org-closed-string))
10051 " ")
10052 (setq ts (org-insert-time-stamp
10053 time
10054 (or org-time-was-given
10055 (and (eq what 'closed) org-log-done-with-time))
10056 (eq what 'closed)
10057 nil nil (list org-end-time-was-given)))
10058 (end-of-line 1))
10059 (goto-char (point-min))
10060 (widen)
10061 (if (and (looking-at "[ \t]+\n")
10062 (equal (char-before) ?\n))
10063 (delete-region (1- (point)) (point-at-eol)))
10064 ts))))))
10066 (defvar org-log-note-marker (make-marker))
10067 (defvar org-log-note-purpose nil)
10068 (defvar org-log-note-state nil)
10069 (defvar org-log-note-previous-state nil)
10070 (defvar org-log-note-how nil)
10071 (defvar org-log-note-extra nil)
10072 (defvar org-log-note-window-configuration nil)
10073 (defvar org-log-note-return-to (make-marker))
10074 (defvar org-log-post-message nil
10075 "Message to be displayed after a log note has been stored.
10076 The auto-repeater uses this.")
10078 (defun org-add-note ()
10079 "Add a note to the current entry.
10080 This is done in the same way as adding a state change note."
10081 (interactive)
10082 (org-add-log-setup 'note nil nil 'findpos nil))
10084 (defvar org-property-end-re)
10085 (defun org-add-log-setup (&optional purpose state prev-state
10086 findpos how &optional extra)
10087 "Set up the post command hook to take a note.
10088 If this is about to TODO state change, the new state is expected in STATE.
10089 When FINDPOS is non-nil, find the correct position for the note in
10090 the current entry. If not, assume that it can be inserted at point.
10091 HOW is an indicator what kind of note should be created.
10092 EXTRA is additional text that will be inserted into the notes buffer."
10093 (let* ((org-log-into-drawer (org-log-into-drawer))
10094 (drawer (cond ((stringp org-log-into-drawer)
10095 org-log-into-drawer)
10096 (org-log-into-drawer "LOGBOOK")
10097 (t nil))))
10098 (save-restriction
10099 (save-excursion
10100 (when findpos
10101 (org-back-to-heading t)
10102 (narrow-to-region (point) (save-excursion
10103 (outline-next-heading) (point)))
10104 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
10105 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
10106 "[^\r\n]*\\)?"))
10107 (goto-char (match-end 0))
10108 (cond
10109 (drawer
10110 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
10111 nil t)
10112 (progn
10113 (goto-char (match-end 0))
10114 (or org-log-states-order-reversed
10115 (and (re-search-forward org-property-end-re nil t)
10116 (goto-char (1- (match-beginning 0))))))
10117 (insert "\n:" drawer ":\n:END:")
10118 (beginning-of-line 0)
10119 (org-indent-line-function)
10120 (beginning-of-line 2)
10121 (org-indent-line-function)
10122 (end-of-line 0)))
10123 ((and org-log-state-notes-insert-after-drawers
10124 (save-excursion
10125 (forward-line) (looking-at org-drawer-regexp)))
10126 (forward-line)
10127 (while (looking-at org-drawer-regexp)
10128 (goto-char (match-end 0))
10129 (re-search-forward org-property-end-re (point-max) t)
10130 (forward-line))
10131 (forward-line -1)))
10132 (unless org-log-states-order-reversed
10133 (and (= (char-after) ?\n) (forward-char 1))
10134 (org-skip-over-state-notes)
10135 (skip-chars-backward " \t\n\r")))
10136 (move-marker org-log-note-marker (point))
10137 (setq org-log-note-purpose purpose
10138 org-log-note-state state
10139 org-log-note-previous-state prev-state
10140 org-log-note-how how
10141 org-log-note-extra extra)
10142 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
10144 (defun org-skip-over-state-notes ()
10145 "Skip past the list of State notes in an entry."
10146 (if (looking-at "\n[ \t]*- State") (forward-char 1))
10147 (while (looking-at "[ \t]*- State")
10148 (condition-case nil
10149 (org-next-item)
10150 (error (org-end-of-item)))))
10152 (defun org-add-log-note (&optional purpose)
10153 "Pop up a window for taking a note, and add this note later at point."
10154 (remove-hook 'post-command-hook 'org-add-log-note)
10155 (setq org-log-note-window-configuration (current-window-configuration))
10156 (delete-other-windows)
10157 (move-marker org-log-note-return-to (point))
10158 (switch-to-buffer (marker-buffer org-log-note-marker))
10159 (goto-char org-log-note-marker)
10160 (org-switch-to-buffer-other-window "*Org Note*")
10161 (erase-buffer)
10162 (if (memq org-log-note-how '(time state))
10163 (let (current-prefix-arg) (org-store-log-note))
10164 (let ((org-inhibit-startup t)) (org-mode))
10165 (insert (format "# Insert note for %s.
10166 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10167 (cond
10168 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10169 ((eq org-log-note-purpose 'done) "closed todo item")
10170 ((eq org-log-note-purpose 'state)
10171 (format "state change from \"%s\" to \"%s\""
10172 (or org-log-note-previous-state "")
10173 (or org-log-note-state "")))
10174 ((eq org-log-note-purpose 'note)
10175 "this entry")
10176 (t (error "This should not happen")))))
10177 (if org-log-note-extra (insert org-log-note-extra))
10178 (org-set-local 'org-finish-function 'org-store-log-note)))
10180 (defvar org-note-abort nil) ; dynamically scoped
10181 (defun org-store-log-note ()
10182 "Finish taking a log note, and insert it to where it belongs."
10183 (let ((txt (buffer-string))
10184 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10185 lines ind)
10186 (kill-buffer (current-buffer))
10187 (while (string-match "\\`#.*\n[ \t\n]*" txt)
10188 (setq txt (replace-match "" t t txt)))
10189 (if (string-match "\\s-+\\'" txt)
10190 (setq txt (replace-match "" t t txt)))
10191 (setq lines (org-split-string txt "\n"))
10192 (when (and note (string-match "\\S-" note))
10193 (setq note
10194 (org-replace-escapes
10195 note
10196 (list (cons "%u" (user-login-name))
10197 (cons "%U" user-full-name)
10198 (cons "%t" (format-time-string
10199 (org-time-stamp-format 'long 'inactive)
10200 (current-time)))
10201 (cons "%s" (if org-log-note-state
10202 (concat "\"" org-log-note-state "\"")
10203 ""))
10204 (cons "%S" (if org-log-note-previous-state
10205 (concat "\"" org-log-note-previous-state "\"")
10206 "\"\"")))))
10207 (if lines (setq note (concat note " \\\\")))
10208 (push note lines))
10209 (when (or current-prefix-arg org-note-abort)
10210 (when org-log-into-drawer
10211 (org-remove-empty-drawer-at
10212 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
10213 org-log-note-marker))
10214 (setq lines nil))
10215 (when lines
10216 (save-excursion
10217 (set-buffer (marker-buffer org-log-note-marker))
10218 (save-excursion
10219 (goto-char org-log-note-marker)
10220 (move-marker org-log-note-marker nil)
10221 (end-of-line 1)
10222 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
10223 (insert "- " (pop lines))
10224 (org-indent-line-function)
10225 (beginning-of-line 1)
10226 (looking-at "[ \t]*")
10227 (setq ind (concat (match-string 0) " "))
10228 (end-of-line 1)
10229 (while lines (insert "\n" ind (pop lines)))
10230 (message "Note stored")
10231 (org-back-to-heading t)
10232 (org-cycle-hide-drawers 'children)))))
10233 (set-window-configuration org-log-note-window-configuration)
10234 (with-current-buffer (marker-buffer org-log-note-return-to)
10235 (goto-char org-log-note-return-to))
10236 (move-marker org-log-note-return-to nil)
10237 (and org-log-post-message (message "%s" org-log-post-message)))
10239 (defun org-remove-empty-drawer-at (drawer pos)
10240 "Remove an emptyr DARWER drawer at position POS.
10241 POS may also be a marker."
10242 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
10243 (save-excursion
10244 (save-restriction
10245 (widen)
10246 (goto-char pos)
10247 (if (org-in-regexp
10248 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
10249 (replace-match ""))))))
10251 (defun org-sparse-tree (&optional arg)
10252 "Create a sparse tree, prompt for the details.
10253 This command can create sparse trees. You first need to select the type
10254 of match used to create the tree:
10256 t Show entries with a specific TODO keyword.
10257 m Show entries selected by a tags/property match.
10258 p Enter a property name and its value (both with completion on existing
10259 names/values) and show entries with that property.
10260 r Show entries matching a regular expression.
10261 d Show deadlines due within `org-deadline-warning-days'.
10262 b Show deadlines and scheduled items before a date.
10263 a Show deadlines and scheduled items after a date."
10264 (interactive "P")
10265 (let (ans kwd value)
10266 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
10267 (setq ans (read-char-exclusive))
10268 (cond
10269 ((equal ans ?d)
10270 (call-interactively 'org-check-deadlines))
10271 ((equal ans ?b)
10272 (call-interactively 'org-check-before-date))
10273 ((equal ans ?a)
10274 (call-interactively 'org-check-after-date))
10275 ((equal ans ?t)
10276 (org-show-todo-tree '(4)))
10277 ((member ans '(?T ?m))
10278 (call-interactively 'org-match-sparse-tree))
10279 ((member ans '(?p ?P))
10280 (setq kwd (org-icompleting-read "Property: "
10281 (mapcar 'list (org-buffer-property-keys))))
10282 (setq value (org-icompleting-read "Value: "
10283 (mapcar 'list (org-property-values kwd))))
10284 (unless (string-match "\\`{.*}\\'" value)
10285 (setq value (concat "\"" value "\"")))
10286 (org-match-sparse-tree arg (concat kwd "=" value)))
10287 ((member ans '(?r ?R ?/))
10288 (call-interactively 'org-occur))
10289 (t (error "No such sparse tree command \"%c\"" ans)))))
10291 (defvar org-occur-highlights nil
10292 "List of overlays used for occur matches.")
10293 (make-variable-buffer-local 'org-occur-highlights)
10294 (defvar org-occur-parameters nil
10295 "Parameters of the active org-occur calls.
10296 This is a list, each call to org-occur pushes as cons cell,
10297 containing the regular expression and the callback, onto the list.
10298 The list can contain several entries if `org-occur' has been called
10299 several time with the KEEP-PREVIOUS argument. Otherwise, this list
10300 will only contain one set of parameters. When the highlights are
10301 removed (for example with `C-c C-c', or with the next edit (depending
10302 on `org-remove-highlights-with-change'), this variable is emptied
10303 as well.")
10304 (make-variable-buffer-local 'org-occur-parameters)
10306 (defun org-occur (regexp &optional keep-previous callback)
10307 "Make a compact tree which shows all matches of REGEXP.
10308 The tree will show the lines where the regexp matches, and all higher
10309 headlines above the match. It will also show the heading after the match,
10310 to make sure editing the matching entry is easy.
10311 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
10312 call to `org-occur' will be kept, to allow stacking of calls to this
10313 command.
10314 If CALLBACK is non-nil, it is a function which is called to confirm
10315 that the match should indeed be shown."
10316 (interactive "sRegexp: \nP")
10317 (when (equal regexp "")
10318 (error "Regexp cannot be empty"))
10319 (unless keep-previous
10320 (org-remove-occur-highlights nil nil t))
10321 (push (cons regexp callback) org-occur-parameters)
10322 (let ((cnt 0))
10323 (save-excursion
10324 (goto-char (point-min))
10325 (if (or (not keep-previous) ; do not want to keep
10326 (not org-occur-highlights)) ; no previous matches
10327 ;; hide everything
10328 (org-overview))
10329 (while (re-search-forward regexp nil t)
10330 (when (or (not callback)
10331 (save-match-data (funcall callback)))
10332 (setq cnt (1+ cnt))
10333 (when org-highlight-sparse-tree-matches
10334 (org-highlight-new-match (match-beginning 0) (match-end 0)))
10335 (org-show-context 'occur-tree))))
10336 (when org-remove-highlights-with-change
10337 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10338 nil 'local))
10339 (unless org-sparse-tree-open-archived-trees
10340 (org-hide-archived-subtrees (point-min) (point-max)))
10341 (run-hooks 'org-occur-hook)
10342 (if (interactive-p)
10343 (message "%d match(es) for regexp %s" cnt regexp))
10344 cnt))
10346 (defun org-show-context (&optional key)
10347 "Make sure point and context and visible.
10348 How much context is shown depends upon the variables
10349 `org-show-hierarchy-above', `org-show-following-heading'. and
10350 `org-show-siblings'."
10351 (let ((heading-p (org-on-heading-p t))
10352 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
10353 (following-p (org-get-alist-option org-show-following-heading key))
10354 (entry-p (org-get-alist-option org-show-entry-below key))
10355 (siblings-p (org-get-alist-option org-show-siblings key)))
10356 (catch 'exit
10357 ;; Show heading or entry text
10358 (if (and heading-p (not entry-p))
10359 (org-flag-heading nil) ; only show the heading
10360 (and (or entry-p (org-invisible-p) (org-invisible-p2))
10361 (org-show-hidden-entry))) ; show entire entry
10362 (when following-p
10363 ;; Show next sibling, or heading below text
10364 (save-excursion
10365 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10366 (org-flag-heading nil))))
10367 (when siblings-p (org-show-siblings))
10368 (when hierarchy-p
10369 ;; show all higher headings, possibly with siblings
10370 (save-excursion
10371 (while (and (condition-case nil
10372 (progn (org-up-heading-all 1) t)
10373 (error nil))
10374 (not (bobp)))
10375 (org-flag-heading nil)
10376 (when siblings-p (org-show-siblings))))))))
10378 (defun org-reveal (&optional siblings)
10379 "Show current entry, hierarchy above it, and the following headline.
10380 This can be used to show a consistent set of context around locations
10381 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10382 not t for the search context.
10384 With optional argument SIBLINGS, on each level of the hierarchy all
10385 siblings are shown. This repairs the tree structure to what it would
10386 look like when opened with hierarchical calls to `org-cycle'."
10387 (interactive "P")
10388 (let ((org-show-hierarchy-above t)
10389 (org-show-following-heading t)
10390 (org-show-siblings (if siblings t org-show-siblings)))
10391 (org-show-context nil)))
10393 (defun org-highlight-new-match (beg end)
10394 "Highlight from BEG to END and mark the highlight is an occur headline."
10395 (let ((ov (org-make-overlay beg end)))
10396 (org-overlay-put ov 'face 'secondary-selection)
10397 (push ov org-occur-highlights)))
10399 (defun org-remove-occur-highlights (&optional beg end noremove)
10400 "Remove the occur highlights from the buffer.
10401 BEG and END are ignored. If NOREMOVE is nil, remove this function
10402 from the `before-change-functions' in the current buffer."
10403 (interactive)
10404 (unless org-inhibit-highlight-removal
10405 (mapc 'org-delete-overlay org-occur-highlights)
10406 (setq org-occur-highlights nil)
10407 (setq org-occur-parameters nil)
10408 (unless noremove
10409 (remove-hook 'before-change-functions
10410 'org-remove-occur-highlights 'local))))
10412 ;;;; Priorities
10414 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
10415 "Regular expression matching the priority indicator.")
10417 (defvar org-remove-priority-next-time nil)
10419 (defun org-priority-up ()
10420 "Increase the priority of the current item."
10421 (interactive)
10422 (org-priority 'up))
10424 (defun org-priority-down ()
10425 "Decrease the priority of the current item."
10426 (interactive)
10427 (org-priority 'down))
10429 (defun org-priority (&optional action)
10430 "Change the priority of an item by ARG.
10431 ACTION can be `set', `up', `down', or a character."
10432 (interactive)
10433 (unless org-enable-priority-commands
10434 (error "Priority commands are disabled"))
10435 (setq action (or action 'set))
10436 (let (current new news have remove)
10437 (save-excursion
10438 (org-back-to-heading t)
10439 (if (looking-at org-priority-regexp)
10440 (setq current (string-to-char (match-string 2))
10441 have t)
10442 (setq current org-default-priority))
10443 (cond
10444 ((or (eq action 'set)
10445 (if (featurep 'xemacs) (characterp action) (integerp action)))
10446 (if (not (eq action 'set))
10447 (setq new action)
10448 (message "Priority %c-%c, SPC to remove: "
10449 org-highest-priority org-lowest-priority)
10450 (setq new (read-char-exclusive)))
10451 (if (and (= (upcase org-highest-priority) org-highest-priority)
10452 (= (upcase org-lowest-priority) org-lowest-priority))
10453 (setq new (upcase new)))
10454 (cond ((equal new ?\ ) (setq remove t))
10455 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
10456 (error "Priority must be between `%c' and `%c'"
10457 org-highest-priority org-lowest-priority))))
10458 ((eq action 'up)
10459 (if (and (not have) (eq last-command this-command))
10460 (setq new org-lowest-priority)
10461 (setq new (if (and org-priority-start-cycle-with-default (not have))
10462 org-default-priority (1- current)))))
10463 ((eq action 'down)
10464 (if (and (not have) (eq last-command this-command))
10465 (setq new org-highest-priority)
10466 (setq new (if (and org-priority-start-cycle-with-default (not have))
10467 org-default-priority (1+ current)))))
10468 (t (error "Invalid action")))
10469 (if (or (< (upcase new) org-highest-priority)
10470 (> (upcase new) org-lowest-priority))
10471 (setq remove t))
10472 (setq news (format "%c" new))
10473 (if have
10474 (if remove
10475 (replace-match "" t t nil 1)
10476 (replace-match news t t nil 2))
10477 (if remove
10478 (error "No priority cookie found in line")
10479 (let ((case-fold-search nil))
10480 (looking-at org-todo-line-regexp))
10481 (if (match-end 2)
10482 (progn
10483 (goto-char (match-end 2))
10484 (insert " [#" news "]"))
10485 (goto-char (match-beginning 3))
10486 (insert "[#" news "] "))))
10487 (org-preserve-lc (org-set-tags nil 'align)))
10488 (if remove
10489 (message "Priority removed")
10490 (message "Priority of current item set to %s" news))))
10492 (defun org-get-priority (s)
10493 "Find priority cookie and return priority."
10494 (save-match-data
10495 (if (not (string-match org-priority-regexp s))
10496 (* 1000 (- org-lowest-priority org-default-priority))
10497 (* 1000 (- org-lowest-priority
10498 (string-to-char (match-string 2 s)))))))
10500 ;;;; Tags
10502 (defvar org-agenda-archives-mode)
10503 (defvar org-map-continue-from nil
10504 "Position from where mapping should continue.
10505 Can be set byt the action argument to `org-scan-tag's and `org-map-entries'.")
10507 (defvar org-scanner-tags nil
10508 "The current tag list while the tags scanner is running.")
10509 (defvar org-trust-scanner-tags nil
10510 "Should `org-get-tags-at' use the tags fro the scanner.
10511 This is for internal dynamical scoping only.
10512 When this is non-nil, the function `org-get-tags-at' will return the value
10513 of `org-scanner-tags' instead of building the list by itself. This
10514 can lead to large speed-ups when the tags scanner is used in a file with
10515 many entries, and when the list of tags is retrieved, for example to
10516 obtain a list of properties. Building the tags list for each entry in such
10517 a file becomes an N^2 operation - but with this variable set, it scales
10518 as N.")
10520 (defun org-scan-tags (action matcher &optional todo-only)
10521 "Scan headline tags with inheritance and produce output ACTION.
10523 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
10524 or `agenda' to produce an entry list for an agenda view. It can also be
10525 a Lisp form or a function that should be called at each matched headline, in
10526 this case the return value is a list of all return values from these calls.
10528 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
10529 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
10530 only lines with a TODO keyword are included in the output."
10531 (require 'org-agenda)
10532 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
10533 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
10534 (org-re
10535 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
10536 (props (list 'face 'default
10537 'done-face 'org-agenda-done
10538 'undone-face 'default
10539 'mouse-face 'highlight
10540 'org-not-done-regexp org-not-done-regexp
10541 'org-todo-regexp org-todo-regexp
10542 'keymap org-agenda-keymap
10543 'help-echo
10544 (format "mouse-2 or RET jump to org file %s"
10545 (abbreviate-file-name
10546 (or (buffer-file-name (buffer-base-buffer))
10547 (buffer-name (buffer-base-buffer)))))))
10548 (case-fold-search nil)
10549 (org-map-continue-from nil)
10550 lspos tags tags-list
10551 (tags-alist (list (cons 0 org-file-tags)))
10552 (llast 0) rtn rtn1 level category i txt
10553 todo marker entry priority)
10554 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
10555 (setq action (list 'lambda nil action)))
10556 (save-excursion
10557 (goto-char (point-min))
10558 (when (eq action 'sparse-tree)
10559 (org-overview)
10560 (org-remove-occur-highlights))
10561 (while (re-search-forward re nil t)
10562 (catch :skip
10563 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
10564 tags (if (match-end 4) (org-match-string-no-properties 4)))
10565 (goto-char (setq lspos (match-beginning 0)))
10566 (setq level (org-reduced-level (funcall outline-level))
10567 category (org-get-category))
10568 (setq i llast llast level)
10569 ;; remove tag lists from same and sublevels
10570 (while (>= i level)
10571 (when (setq entry (assoc i tags-alist))
10572 (setq tags-alist (delete entry tags-alist)))
10573 (setq i (1- i)))
10574 ;; add the next tags
10575 (when tags
10576 (setq tags (org-split-string tags ":")
10577 tags-alist
10578 (cons (cons level tags) tags-alist)))
10579 ;; compile tags for current headline
10580 (setq tags-list
10581 (if org-use-tag-inheritance
10582 (apply 'append (mapcar 'cdr (reverse tags-alist)))
10583 tags)
10584 org-scanner-tags tags-list)
10585 (when org-use-tag-inheritance
10586 (setcdr (car tags-alist)
10587 (mapcar (lambda (x)
10588 (setq x (copy-sequence x))
10589 (org-add-prop-inherited x))
10590 (cdar tags-alist))))
10591 (when (and tags org-use-tag-inheritance
10592 (or (not (eq t org-use-tag-inheritance))
10593 org-tags-exclude-from-inheritance))
10594 ;; selective inheritance, remove uninherited ones
10595 (setcdr (car tags-alist)
10596 (org-remove-uniherited-tags (cdar tags-alist))))
10597 (when (and (or (not todo-only)
10598 (and (member todo org-not-done-keywords)
10599 (or (not org-agenda-tags-todo-honor-ignore-options)
10600 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
10601 (let ((case-fold-search t)) (eval matcher))
10603 (not (member org-archive-tag tags-list))
10604 ;; we have an archive tag, should we use this anyway?
10605 (or (not org-agenda-skip-archived-trees)
10606 (and (eq action 'agenda) org-agenda-archives-mode))))
10607 (unless (eq action 'sparse-tree) (org-agenda-skip))
10609 ;; select this headline
10611 (cond
10612 ((eq action 'sparse-tree)
10613 (and org-highlight-sparse-tree-matches
10614 (org-get-heading) (match-end 0)
10615 (org-highlight-new-match
10616 (match-beginning 0) (match-beginning 1)))
10617 (org-show-context 'tags-tree))
10618 ((eq action 'agenda)
10619 (setq txt (org-format-agenda-item
10621 (concat
10622 (if (eq org-tags-match-list-sublevels 'indented)
10623 (make-string (1- level) ?.) "")
10624 (org-get-heading))
10625 category
10626 tags-list
10628 priority (org-get-priority txt))
10629 (goto-char lspos)
10630 (setq marker (org-agenda-new-marker))
10631 (org-add-props txt props
10632 'org-marker marker 'org-hd-marker marker 'org-category category
10633 'todo-state todo
10634 'priority priority 'type "tagsmatch")
10635 (push txt rtn))
10636 ((functionp action)
10637 (setq org-map-continue-from nil)
10638 (save-excursion
10639 (setq rtn1 (funcall action))
10640 (push rtn1 rtn)))
10641 (t (error "Invalid action")))
10643 ;; if we are to skip sublevels, jump to end of subtree
10644 (unless org-tags-match-list-sublevels
10645 (org-end-of-subtree t)
10646 (backward-char 1))))
10647 ;; Get the correct position from where to continue
10648 (if org-map-continue-from
10649 (goto-char org-map-continue-from)
10650 (and (= (point) lspos) (end-of-line 1)))))
10651 (when (and (eq action 'sparse-tree)
10652 (not org-sparse-tree-open-archived-trees))
10653 (org-hide-archived-subtrees (point-min) (point-max)))
10654 (nreverse rtn)))
10656 (defun org-remove-uniherited-tags (tags)
10657 "Remove all tags that are not inherited from the list TAGS."
10658 (cond
10659 ((eq org-use-tag-inheritance t)
10660 (if org-tags-exclude-from-inheritance
10661 (org-delete-all org-tags-exclude-from-inheritance tags)
10662 tags))
10663 ((not org-use-tag-inheritance) nil)
10664 ((stringp org-use-tag-inheritance)
10665 (delq nil (mapcar
10666 (lambda (x)
10667 (if (and (string-match org-use-tag-inheritance x)
10668 (not (member x org-tags-exclude-from-inheritance)))
10669 x nil))
10670 tags)))
10671 ((listp org-use-tag-inheritance)
10672 (delq nil (mapcar
10673 (lambda (x)
10674 (if (member x org-use-tag-inheritance) x nil))
10675 tags)))))
10677 (defvar todo-only) ;; dynamically scoped
10679 (defun org-match-sparse-tree (&optional todo-only match)
10680 "Create a sparse tree according to tags string MATCH.
10681 MATCH can contain positive and negative selection of tags, like
10682 \"+WORK+URGENT-WITHBOSS\".
10683 If optional argument TODO-ONLY is non-nil, only select lines that are
10684 also TODO lines."
10685 (interactive "P")
10686 (org-prepare-agenda-buffers (list (current-buffer)))
10687 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
10689 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
10691 (defvar org-cached-props nil)
10692 (defun org-cached-entry-get (pom property)
10693 (if (or (eq t org-use-property-inheritance)
10694 (and (stringp org-use-property-inheritance)
10695 (string-match org-use-property-inheritance property))
10696 (and (listp org-use-property-inheritance)
10697 (member property org-use-property-inheritance)))
10698 ;; Caching is not possible, check it directly
10699 (org-entry-get pom property 'inherit)
10700 ;; Get all properties, so that we can do complicated checks easily
10701 (cdr (assoc property (or org-cached-props
10702 (setq org-cached-props
10703 (org-entry-properties pom)))))))
10705 (defun org-global-tags-completion-table (&optional files)
10706 "Return the list of all tags in all agenda buffer/files."
10707 (save-excursion
10708 (org-uniquify
10709 (delq nil
10710 (apply 'append
10711 (mapcar
10712 (lambda (file)
10713 (set-buffer (find-file-noselect file))
10714 (append (org-get-buffer-tags)
10715 (mapcar (lambda (x) (if (stringp (car-safe x))
10716 (list (car-safe x)) nil))
10717 org-tag-alist)))
10718 (if (and files (car files))
10719 files
10720 (org-agenda-files))))))))
10722 (defun org-make-tags-matcher (match)
10723 "Create the TAGS//TODO matcher form for the selection string MATCH."
10724 ;; todo-only is scoped dynamically into this function, and the function
10725 ;; may change it if the matcher asks for it.
10726 (unless match
10727 ;; Get a new match request, with completion
10728 (let ((org-last-tags-completion-table
10729 (org-global-tags-completion-table)))
10730 (setq match (org-completing-read-no-i
10731 "Match: " 'org-tags-completion-function nil nil nil
10732 'org-tags-history))))
10734 ;; Parse the string and create a lisp form
10735 (let ((match0 match)
10736 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
10737 minus tag mm
10738 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
10739 orterms term orlist re-p str-p level-p level-op time-p
10740 prop-p pn pv po cat-p gv rest)
10741 (if (string-match "/+" match)
10742 ;; match contains also a todo-matching request
10743 (progn
10744 (setq tagsmatch (substring match 0 (match-beginning 0))
10745 todomatch (substring match (match-end 0)))
10746 (if (string-match "^!" todomatch)
10747 (setq todo-only t todomatch (substring todomatch 1)))
10748 (if (string-match "^\\s-*$" todomatch)
10749 (setq todomatch nil)))
10750 ;; only matching tags
10751 (setq tagsmatch match todomatch nil))
10753 ;; Make the tags matcher
10754 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10755 (setq tagsmatcher t)
10756 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10757 (while (setq term (pop orterms))
10758 (while (and (equal (substring term -1) "\\") orterms)
10759 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10760 (while (string-match re term)
10761 (setq rest (substring term (match-end 0))
10762 minus (and (match-end 1)
10763 (equal (match-string 1 term) "-"))
10764 tag (match-string 2 term)
10765 re-p (equal (string-to-char tag) ?{)
10766 level-p (match-end 4)
10767 prop-p (match-end 5)
10768 mm (cond
10769 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10770 (level-p
10771 (setq level-op (org-op-to-function (match-string 3 term)))
10772 `(,level-op level ,(string-to-number
10773 (match-string 4 term))))
10774 (prop-p
10775 (setq pn (match-string 5 term)
10776 po (match-string 6 term)
10777 pv (match-string 7 term)
10778 cat-p (equal pn "CATEGORY")
10779 re-p (equal (string-to-char pv) ?{)
10780 str-p (equal (string-to-char pv) ?\")
10781 time-p (save-match-data
10782 (string-match "^\"[[<].*[]>]\"$" pv))
10783 pv (if (or re-p str-p) (substring pv 1 -1) pv))
10784 (if time-p (setq pv (org-matcher-time pv)))
10785 (setq po (org-op-to-function po (if time-p 'time str-p)))
10786 (cond
10787 ((equal pn "CATEGORY")
10788 (setq gv '(get-text-property (point) 'org-category)))
10789 ((equal pn "TODO")
10790 (setq gv 'todo))
10792 (setq gv `(org-cached-entry-get nil ,pn))))
10793 (if re-p
10794 (if (eq po 'org<>)
10795 `(not (string-match ,pv (or ,gv "")))
10796 `(string-match ,pv (or ,gv "")))
10797 (if str-p
10798 `(,po (or ,gv "") ,pv)
10799 `(,po (string-to-number (or ,gv ""))
10800 ,(string-to-number pv) ))))
10801 (t `(member ,tag tags-list)))
10802 mm (if minus (list 'not mm) mm)
10803 term rest)
10804 (push mm tagsmatcher))
10805 (push (if (> (length tagsmatcher) 1)
10806 (cons 'and tagsmatcher)
10807 (car tagsmatcher))
10808 orlist)
10809 (setq tagsmatcher nil))
10810 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
10811 (setq tagsmatcher
10812 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
10813 ;; Make the todo matcher
10814 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10815 (setq todomatcher t)
10816 (setq orterms (org-split-string todomatch "|") orlist nil)
10817 (while (setq term (pop orterms))
10818 (while (string-match re term)
10819 (setq minus (and (match-end 1)
10820 (equal (match-string 1 term) "-"))
10821 kwd (match-string 2 term)
10822 re-p (equal (string-to-char kwd) ?{)
10823 term (substring term (match-end 0))
10824 mm (if re-p
10825 `(string-match ,(substring kwd 1 -1) todo)
10826 (list 'equal 'todo kwd))
10827 mm (if minus (list 'not mm) mm))
10828 (push mm todomatcher))
10829 (push (if (> (length todomatcher) 1)
10830 (cons 'and todomatcher)
10831 (car todomatcher))
10832 orlist)
10833 (setq todomatcher nil))
10834 (setq todomatcher (if (> (length orlist) 1)
10835 (cons 'or orlist) (car orlist))))
10837 ;; Return the string and lisp forms of the matcher
10838 (setq matcher (if todomatcher
10839 (list 'and tagsmatcher todomatcher)
10840 tagsmatcher))
10841 (cons match0 matcher)))
10843 (defun org-op-to-function (op &optional stringp)
10844 "Turn an operator into the appropriate function."
10845 (setq op
10846 (cond
10847 ((equal op "<" ) '(< string< org-time<))
10848 ((equal op ">" ) '(> org-string> org-time>))
10849 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
10850 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
10851 ((member op '("=" "==")) '(= string= org-time=))
10852 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
10853 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
10855 (defun org<> (a b) (not (= a b)))
10856 (defun org-string<= (a b) (or (string= a b) (string< a b)))
10857 (defun org-string>= (a b) (not (string< a b)))
10858 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
10859 (defun org-string<> (a b) (not (string= a b)))
10860 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
10861 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
10862 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
10863 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
10864 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
10865 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
10866 (defun org-2ft (s)
10867 "Convert S to a floating point time.
10868 If S is already a number, just return it. If it is a string, parse
10869 it as a time string and apply `float-time' to it. If S is nil, just return 0."
10870 (cond
10871 ((numberp s) s)
10872 ((stringp s)
10873 (condition-case nil
10874 (float-time (apply 'encode-time (org-parse-time-string s)))
10875 (error 0.)))
10876 (t 0.)))
10878 (defun org-time-today ()
10879 "Time in seconds today at 0:00.
10880 Returns the float number of seconds since the beginning of the
10881 epoch to the beginning of today (00:00)."
10882 (float-time (apply 'encode-time
10883 (append '(0 0 0) (nthcdr 3 (decode-time))))))
10885 (defun org-matcher-time (s)
10886 "Interpret a time comparison value."
10887 (save-match-data
10888 (cond
10889 ((string= s "<now>") (float-time))
10890 ((string= s "<today>") (org-time-today))
10891 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
10892 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
10893 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
10894 (+ (org-time-today)
10895 (* (string-to-number (match-string 1 s))
10896 (cdr (assoc (match-string 2 s)
10897 '(("d" . 86400.0) ("w" . 604800.0)
10898 ("m" . 2678400.0) ("y" . 31557600.0)))))))
10899 (t (org-2ft s)))))
10901 (defun org-match-any-p (re list)
10902 "Does re match any element of list?"
10903 (setq list (mapcar (lambda (x) (string-match re x)) list))
10904 (delq nil list))
10906 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
10907 (defvar org-tags-overlay (org-make-overlay 1 1))
10908 (org-detach-overlay org-tags-overlay)
10910 (defun org-get-local-tags-at (&optional pos)
10911 "Get a list of tags defined in the current headline."
10912 (org-get-tags-at pos 'local))
10914 (defun org-get-local-tags ()
10915 "Get a list of tags defined in the current headline."
10916 (org-get-tags-at nil 'local))
10918 (defun org-get-tags-at (&optional pos local)
10919 "Get a list of all headline tags applicable at POS.
10920 POS defaults to point. If tags are inherited, the list contains
10921 the targets in the same sequence as the headlines appear, i.e.
10922 the tags of the current headline come last.
10923 When LOCAL is non-nil, only return tags from the current headline,
10924 ignore inherited ones."
10925 (interactive)
10926 (if (and org-trust-scanner-tags
10927 (or (not pos) (equal pos (point)))
10928 (not local))
10929 org-scanner-tags
10930 (let (tags ltags lastpos parent)
10931 (save-excursion
10932 (save-restriction
10933 (widen)
10934 (goto-char (or pos (point)))
10935 (save-match-data
10936 (catch 'done
10937 (condition-case nil
10938 (progn
10939 (org-back-to-heading t)
10940 (while (not (equal lastpos (point)))
10941 (setq lastpos (point))
10942 (when (looking-at
10943 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
10944 (setq ltags (org-split-string
10945 (org-match-string-no-properties 1) ":"))
10946 (when parent
10947 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
10948 (setq tags (append
10949 (if parent
10950 (org-remove-uniherited-tags ltags)
10951 ltags)
10952 tags)))
10953 (or org-use-tag-inheritance (throw 'done t))
10954 (if local (throw 'done t))
10955 (or (org-up-heading-safe) (error nil))
10956 (setq parent t)))
10957 (error nil)))))
10958 (append (org-remove-uniherited-tags org-file-tags) tags)))))
10960 (defun org-add-prop-inherited (s)
10961 (add-text-properties 0 (length s) '(inherited t) s)
10964 (defun org-toggle-tag (tag &optional onoff)
10965 "Toggle the tag TAG for the current line.
10966 If ONOFF is `on' or `off', don't toggle but set to this state."
10967 (let (res current)
10968 (save-excursion
10969 (org-back-to-heading t)
10970 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
10971 (point-at-eol) t)
10972 (progn
10973 (setq current (match-string 1))
10974 (replace-match ""))
10975 (setq current ""))
10976 (setq current (nreverse (org-split-string current ":")))
10977 (cond
10978 ((eq onoff 'on)
10979 (setq res t)
10980 (or (member tag current) (push tag current)))
10981 ((eq onoff 'off)
10982 (or (not (member tag current)) (setq current (delete tag current))))
10983 (t (if (member tag current)
10984 (setq current (delete tag current))
10985 (setq res t)
10986 (push tag current))))
10987 (end-of-line 1)
10988 (if current
10989 (progn
10990 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
10991 (org-set-tags nil t))
10992 (delete-horizontal-space))
10993 (run-hooks 'org-after-tags-change-hook))
10994 res))
10996 (defun org-align-tags-here (to-col)
10997 ;; Assumes that this is a headline
10998 (let ((pos (point)) (col (current-column)) ncol tags-l p)
10999 (beginning-of-line 1)
11000 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11001 (< pos (match-beginning 2)))
11002 (progn
11003 (setq tags-l (- (match-end 2) (match-beginning 2)))
11004 (goto-char (match-beginning 1))
11005 (insert " ")
11006 (delete-region (point) (1+ (match-beginning 2)))
11007 (setq ncol (max (1+ (current-column))
11008 (1+ col)
11009 (if (> to-col 0)
11010 to-col
11011 (- (abs to-col) tags-l))))
11012 (setq p (point))
11013 (insert (make-string (- ncol (current-column)) ?\ ))
11014 (setq ncol (current-column))
11015 (when indent-tabs-mode (tabify p (point-at-eol)))
11016 (org-move-to-column (min ncol col) t))
11017 (goto-char pos))))
11019 (defun org-set-tags-command (&optional arg just-align)
11020 "Call the set-tags command for the current entry."
11021 (interactive "P")
11022 (if (org-on-heading-p)
11023 (org-set-tags arg just-align)
11024 (save-excursion
11025 (org-back-to-heading t)
11026 (org-set-tags arg just-align))))
11028 (defun org-set-tags (&optional arg just-align)
11029 "Set the tags for the current headline.
11030 With prefix ARG, realign all tags in headings in the current buffer."
11031 (interactive "P")
11032 (let* ((re (concat "^" outline-regexp))
11033 (current (org-get-tags-string))
11034 (col (current-column))
11035 (org-setting-tags t)
11036 table current-tags inherited-tags ; computed below when needed
11037 tags p0 c0 c1 rpl)
11038 (if arg
11039 (save-excursion
11040 (goto-char (point-min))
11041 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
11042 (while (re-search-forward re nil t)
11043 (org-set-tags nil t)
11044 (end-of-line 1)))
11045 (message "All tags realigned to column %d" org-tags-column))
11046 (if just-align
11047 (setq tags current)
11048 ;; Get a new set of tags from the user
11049 (save-excursion
11050 (setq table (append org-tag-persistent-alist
11051 (or org-tag-alist (org-get-buffer-tags)))
11052 org-last-tags-completion-table table
11053 current-tags (org-split-string current ":")
11054 inherited-tags (nreverse
11055 (nthcdr (length current-tags)
11056 (nreverse (org-get-tags-at))))
11057 tags
11058 (if (or (eq t org-use-fast-tag-selection)
11059 (and org-use-fast-tag-selection
11060 (delq nil (mapcar 'cdr table))))
11061 (org-fast-tag-selection
11062 current-tags inherited-tags table
11063 (if org-fast-tag-selection-include-todo org-todo-key-alist))
11064 (let ((org-add-colon-after-tag-completion t))
11065 (org-trim
11066 (org-without-partial-completion
11067 (org-icompleting-read "Tags: " 'org-tags-completion-function
11068 nil nil current 'org-tags-history)))))))
11069 (while (string-match "[-+&]+" tags)
11070 ;; No boolean logic, just a list
11071 (setq tags (replace-match ":" t t tags))))
11073 (if org-tags-sort-function
11074 (setq tags (mapconcat 'identity
11075 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
11076 org-tags-sort-function) ":")))
11078 (if (string-match "\\`[\t ]*\\'" tags)
11079 (setq tags "")
11080 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
11081 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
11083 ;; Insert new tags at the correct column
11084 (beginning-of-line 1)
11085 (cond
11086 ((and (equal current "") (equal tags "")))
11087 ((re-search-forward
11088 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
11089 (point-at-eol) t)
11090 (if (equal tags "")
11091 (setq rpl "")
11092 (goto-char (match-beginning 0))
11093 (setq c0 (current-column) p0 (point)
11094 c1 (max (1+ c0) (if (> org-tags-column 0)
11095 org-tags-column
11096 (- (- org-tags-column) (length tags))))
11097 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
11098 (replace-match rpl t t)
11099 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
11100 tags)
11101 (t (error "Tags alignment failed")))
11102 (org-move-to-column col)
11103 (unless just-align
11104 (run-hooks 'org-after-tags-change-hook)))))
11106 (defun org-change-tag-in-region (beg end tag off)
11107 "Add or remove TAG for each entry in the region.
11108 This works in the agenda, and also in an org-mode buffer."
11109 (interactive
11110 (list (region-beginning) (region-end)
11111 (let ((org-last-tags-completion-table
11112 (if (org-mode-p)
11113 (org-get-buffer-tags)
11114 (org-global-tags-completion-table))))
11115 (org-icompleting-read
11116 "Tag: " 'org-tags-completion-function nil nil nil
11117 'org-tags-history))
11118 (progn
11119 (message "[s]et or [r]emove? ")
11120 (equal (read-char-exclusive) ?r))))
11121 (if (fboundp 'deactivate-mark) (deactivate-mark))
11122 (let ((agendap (equal major-mode 'org-agenda-mode))
11123 l1 l2 m buf pos newhead (cnt 0))
11124 (goto-char end)
11125 (setq l2 (1- (org-current-line)))
11126 (goto-char beg)
11127 (setq l1 (org-current-line))
11128 (loop for l from l1 to l2 do
11129 (goto-line l)
11130 (setq m (get-text-property (point) 'org-hd-marker))
11131 (when (or (and (org-mode-p) (org-on-heading-p))
11132 (and agendap m))
11133 (setq buf (if agendap (marker-buffer m) (current-buffer))
11134 pos (if agendap m (point)))
11135 (with-current-buffer buf
11136 (save-excursion
11137 (save-restriction
11138 (goto-char pos)
11139 (setq cnt (1+ cnt))
11140 (org-toggle-tag tag (if off 'off 'on))
11141 (setq newhead (org-get-heading)))))
11142 (and agendap (org-agenda-change-all-lines newhead m))))
11143 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
11145 (defun org-tags-completion-function (string predicate &optional flag)
11146 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
11147 (confirm (lambda (x) (stringp (car x)))))
11148 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
11149 (setq s1 (match-string 1 string)
11150 s2 (match-string 2 string))
11151 (setq s1 "" s2 string))
11152 (cond
11153 ((eq flag nil)
11154 ;; try completion
11155 (setq rtn (try-completion s2 ctable confirm))
11156 (if (stringp rtn)
11157 (setq rtn
11158 (concat s1 s2 (substring rtn (length s2))
11159 (if (and org-add-colon-after-tag-completion
11160 (assoc rtn ctable))
11161 ":" ""))))
11162 rtn)
11163 ((eq flag t)
11164 ;; all-completions
11165 (all-completions s2 ctable confirm)
11167 ((eq flag 'lambda)
11168 ;; exact match?
11169 (assoc s2 ctable)))
11172 (defun org-fast-tag-insert (kwd tags face &optional end)
11173 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
11174 (insert (format "%-12s" (concat kwd ":"))
11175 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
11176 (or end "")))
11178 (defun org-fast-tag-show-exit (flag)
11179 (save-excursion
11180 (goto-line 3)
11181 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
11182 (replace-match ""))
11183 (when flag
11184 (end-of-line 1)
11185 (org-move-to-column (- (window-width) 19) t)
11186 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
11188 (defun org-set-current-tags-overlay (current prefix)
11189 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
11190 (if (featurep 'xemacs)
11191 (org-overlay-display org-tags-overlay (concat prefix s)
11192 'secondary-selection)
11193 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
11194 (org-overlay-display org-tags-overlay (concat prefix s)))))
11196 (defun org-fast-tag-selection (current inherited table &optional todo-table)
11197 "Fast tag selection with single keys.
11198 CURRENT is the current list of tags in the headline, INHERITED is the
11199 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
11200 possibly with grouping information. TODO-TABLE is a similar table with
11201 TODO keywords, should these have keys assigned to them.
11202 If the keys are nil, a-z are automatically assigned.
11203 Returns the new tags string, or nil to not change the current settings."
11204 (let* ((fulltable (append table todo-table))
11205 (maxlen (apply 'max (mapcar
11206 (lambda (x)
11207 (if (stringp (car x)) (string-width (car x)) 0))
11208 fulltable)))
11209 (buf (current-buffer))
11210 (expert (eq org-fast-tag-selection-single-key 'expert))
11211 (buffer-tags nil)
11212 (fwidth (+ maxlen 3 1 3))
11213 (ncol (/ (- (window-width) 4) fwidth))
11214 (i-face 'org-done)
11215 (c-face 'org-todo)
11216 tg cnt e c char c1 c2 ntable tbl rtn
11217 ov-start ov-end ov-prefix
11218 (exit-after-next org-fast-tag-selection-single-key)
11219 (done-keywords org-done-keywords)
11220 groups ingroup)
11221 (save-excursion
11222 (beginning-of-line 1)
11223 (if (looking-at
11224 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11225 (setq ov-start (match-beginning 1)
11226 ov-end (match-end 1)
11227 ov-prefix "")
11228 (setq ov-start (1- (point-at-eol))
11229 ov-end (1+ ov-start))
11230 (skip-chars-forward "^\n\r")
11231 (setq ov-prefix
11232 (concat
11233 (buffer-substring (1- (point)) (point))
11234 (if (> (current-column) org-tags-column)
11236 (make-string (- org-tags-column (current-column)) ?\ ))))))
11237 (org-move-overlay org-tags-overlay ov-start ov-end)
11238 (save-window-excursion
11239 (if expert
11240 (set-buffer (get-buffer-create " *Org tags*"))
11241 (delete-other-windows)
11242 (split-window-vertically)
11243 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
11244 (erase-buffer)
11245 (org-set-local 'org-done-keywords done-keywords)
11246 (org-fast-tag-insert "Inherited" inherited i-face "\n")
11247 (org-fast-tag-insert "Current" current c-face "\n\n")
11248 (org-fast-tag-show-exit exit-after-next)
11249 (org-set-current-tags-overlay current ov-prefix)
11250 (setq tbl fulltable char ?a cnt 0)
11251 (while (setq e (pop tbl))
11252 (cond
11253 ((equal e '(:startgroup))
11254 (push '() groups) (setq ingroup t)
11255 (when (not (= cnt 0))
11256 (setq cnt 0)
11257 (insert "\n"))
11258 (insert "{ "))
11259 ((equal e '(:endgroup))
11260 (setq ingroup nil cnt 0)
11261 (insert "}\n"))
11262 ((equal e '(:newline))
11263 (when (not (= cnt 0))
11264 (setq cnt 0)
11265 (insert "\n")
11266 (setq e (car tbl))
11267 (while (equal (car tbl) '(:newline))
11268 (insert "\n")
11269 (setq tbl (cdr tbl)))))
11271 (setq tg (copy-sequence (car e)) c2 nil)
11272 (if (cdr e)
11273 (setq c (cdr e))
11274 ;; automatically assign a character.
11275 (setq c1 (string-to-char
11276 (downcase (substring
11277 tg (if (= (string-to-char tg) ?@) 1 0)))))
11278 (if (or (rassoc c1 ntable) (rassoc c1 table))
11279 (while (or (rassoc char ntable) (rassoc char table))
11280 (setq char (1+ char)))
11281 (setq c2 c1))
11282 (setq c (or c2 char)))
11283 (if ingroup (push tg (car groups)))
11284 (setq tg (org-add-props tg nil 'face
11285 (cond
11286 ((not (assoc tg table))
11287 (org-get-todo-face tg))
11288 ((member tg current) c-face)
11289 ((member tg inherited) i-face)
11290 (t nil))))
11291 (if (and (= cnt 0) (not ingroup)) (insert " "))
11292 (insert "[" c "] " tg (make-string
11293 (- fwidth 4 (length tg)) ?\ ))
11294 (push (cons tg c) ntable)
11295 (when (= (setq cnt (1+ cnt)) ncol)
11296 (insert "\n")
11297 (if ingroup (insert " "))
11298 (setq cnt 0)))))
11299 (setq ntable (nreverse ntable))
11300 (insert "\n")
11301 (goto-char (point-min))
11302 (if (not expert) (org-fit-window-to-buffer))
11303 (setq rtn
11304 (catch 'exit
11305 (while t
11306 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
11307 (if groups " [!] no groups" " [!]groups")
11308 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
11309 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11310 (cond
11311 ((= c ?\r) (throw 'exit t))
11312 ((= c ?!)
11313 (setq groups (not groups))
11314 (goto-char (point-min))
11315 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
11316 ((= c ?\C-c)
11317 (if (not expert)
11318 (org-fast-tag-show-exit
11319 (setq exit-after-next (not exit-after-next)))
11320 (setq expert nil)
11321 (delete-other-windows)
11322 (split-window-vertically)
11323 (org-switch-to-buffer-other-window " *Org tags*")
11324 (org-fit-window-to-buffer)))
11325 ((or (= c ?\C-g)
11326 (and (= c ?q) (not (rassoc c ntable))))
11327 (org-detach-overlay org-tags-overlay)
11328 (setq quit-flag t))
11329 ((= c ?\ )
11330 (setq current nil)
11331 (if exit-after-next (setq exit-after-next 'now)))
11332 ((= c ?\t)
11333 (condition-case nil
11334 (setq tg (org-icompleting-read
11335 "Tag: "
11336 (or buffer-tags
11337 (with-current-buffer buf
11338 (org-get-buffer-tags)))))
11339 (quit (setq tg "")))
11340 (when (string-match "\\S-" tg)
11341 (add-to-list 'buffer-tags (list tg))
11342 (if (member tg current)
11343 (setq current (delete tg current))
11344 (push tg current)))
11345 (if exit-after-next (setq exit-after-next 'now)))
11346 ((setq e (rassoc c todo-table) tg (car e))
11347 (with-current-buffer buf
11348 (save-excursion (org-todo tg)))
11349 (if exit-after-next (setq exit-after-next 'now)))
11350 ((setq e (rassoc c ntable) tg (car e))
11351 (if (member tg current)
11352 (setq current (delete tg current))
11353 (loop for g in groups do
11354 (if (member tg g)
11355 (mapc (lambda (x)
11356 (setq current (delete x current)))
11357 g)))
11358 (push tg current))
11359 (if exit-after-next (setq exit-after-next 'now))))
11361 ;; Create a sorted list
11362 (setq current
11363 (sort current
11364 (lambda (a b)
11365 (assoc b (cdr (memq (assoc a ntable) ntable))))))
11366 (if (eq exit-after-next 'now) (throw 'exit t))
11367 (goto-char (point-min))
11368 (beginning-of-line 2)
11369 (delete-region (point) (point-at-eol))
11370 (org-fast-tag-insert "Current" current c-face)
11371 (org-set-current-tags-overlay current ov-prefix)
11372 (while (re-search-forward
11373 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
11374 (setq tg (match-string 1))
11375 (add-text-properties
11376 (match-beginning 1) (match-end 1)
11377 (list 'face
11378 (cond
11379 ((member tg current) c-face)
11380 ((member tg inherited) i-face)
11381 (t (get-text-property (match-beginning 1) 'face))))))
11382 (goto-char (point-min)))))
11383 (org-detach-overlay org-tags-overlay)
11384 (if rtn
11385 (mapconcat 'identity current ":")
11386 nil))))
11388 (defun org-get-tags-string ()
11389 "Get the TAGS string in the current headline."
11390 (unless (org-on-heading-p t)
11391 (error "Not on a heading"))
11392 (save-excursion
11393 (beginning-of-line 1)
11394 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11395 (org-match-string-no-properties 1)
11396 "")))
11398 (defun org-get-tags ()
11399 "Get the list of tags specified in the current headline."
11400 (org-split-string (org-get-tags-string) ":"))
11402 (defun org-get-buffer-tags ()
11403 "Get a table of all tags used in the buffer, for completion."
11404 (let (tags)
11405 (save-excursion
11406 (goto-char (point-min))
11407 (while (re-search-forward
11408 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
11409 (when (equal (char-after (point-at-bol 0)) ?*)
11410 (mapc (lambda (x) (add-to-list 'tags x))
11411 (org-split-string (org-match-string-no-properties 1) ":")))))
11412 (mapcar 'list tags)))
11414 ;;;; The mapping API
11416 ;;;###autoload
11417 (defun org-map-entries (func &optional match scope &rest skip)
11418 "Call FUNC at each headline selected by MATCH in SCOPE.
11420 FUNC is a function or a lisp form. The function will be called without
11421 arguments, with the cursor positioned at the beginning of the headline.
11422 The return values of all calls to the function will be collected and
11423 returned as a list.
11425 The call to FUNC will be wrapped into a save-excursion form, so FUNC
11426 does not need to preserve point. After evaluation, the cursor will be
11427 moved to the end of the line (presumably of the headline of the
11428 processed entry) and search continues from there. Under some
11429 circumstances, this may not produce the wanted results. For example,
11430 if you have removed (e.g. archived) the current (sub)tree it could
11431 mean that the next entry will be skipped entirely. In such cases, you
11432 can specify the position from where search should continue by making
11433 FUNC set the variable `org-map-continue-from' to the desired buffer
11434 position.
11436 MATCH is a tags/property/todo match as it is used in the agenda tags view.
11437 Only headlines that are matched by this query will be considered during
11438 the iteration. When MATCH is nil or t, all headlines will be
11439 visited by the iteration.
11441 SCOPE determines the scope of this command. It can be any of:
11443 nil The current buffer, respecting the restriction if any
11444 tree The subtree started with the entry at point
11445 file The current buffer, without restriction
11446 file-with-archives
11447 The current buffer, and any archives associated with it
11448 agenda All agenda files
11449 agenda-with-archives
11450 All agenda files with any archive files associated with them
11451 \(file1 file2 ...)
11452 If this is a list, all files in the list will be scanned
11454 The remaining args are treated as settings for the skipping facilities of
11455 the scanner. The following items can be given here:
11457 archive skip trees with the archive tag.
11458 comment skip trees with the COMMENT keyword
11459 function or Emacs Lisp form:
11460 will be used as value for `org-agenda-skip-function', so whenever
11461 the the function returns t, FUNC will not be called for that
11462 entry and search will continue from the point where the
11463 function leaves it.
11465 If your function needs to retrieve the tags including inherited tags
11466 at the *current* entry, you can use the value of the variable
11467 `org-scanner-tags' which will be much faster than getting the value
11468 with `org-get-tags-at'. If your function gets properties with
11469 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
11470 to t around the call to `org-entry-properties' to get the same speedup.
11471 Note that if your function moves around to retrieve tags and properties at
11472 a *different* entry, you cannot use these techniques."
11473 (let* ((org-agenda-archives-mode nil) ; just to make sure
11474 (org-agenda-skip-archived-trees (memq 'archive skip))
11475 (org-agenda-skip-comment-trees (memq 'comment skip))
11476 (org-agenda-skip-function
11477 (car (org-delete-all '(comment archive) skip)))
11478 (org-tags-match-list-sublevels t)
11479 matcher file res
11480 org-todo-keywords-for-agenda
11481 org-done-keywords-for-agenda
11482 org-todo-keyword-alist-for-agenda
11483 org-tag-alist-for-agenda)
11485 (cond
11486 ((eq match t) (setq matcher t))
11487 ((eq match nil) (setq matcher t))
11488 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
11490 (save-excursion
11491 (save-restriction
11492 (when (eq scope 'tree)
11493 (org-back-to-heading t)
11494 (org-narrow-to-subtree)
11495 (setq scope nil))
11497 (if (not scope)
11498 (progn
11499 (org-prepare-agenda-buffers
11500 (list (buffer-file-name (current-buffer))))
11501 (setq res (org-scan-tags func matcher)))
11502 ;; Get the right scope
11503 (cond
11504 ((and scope (listp scope) (symbolp (car scope)))
11505 (setq scope (eval scope)))
11506 ((eq scope 'agenda)
11507 (setq scope (org-agenda-files t)))
11508 ((eq scope 'agenda-with-archives)
11509 (setq scope (org-agenda-files t))
11510 (setq scope (org-add-archive-files scope)))
11511 ((eq scope 'file)
11512 (setq scope (list (buffer-file-name))))
11513 ((eq scope 'file-with-archives)
11514 (setq scope (org-add-archive-files (list (buffer-file-name))))))
11515 (org-prepare-agenda-buffers scope)
11516 (while (setq file (pop scope))
11517 (with-current-buffer (org-find-base-buffer-visiting file)
11518 (save-excursion
11519 (save-restriction
11520 (widen)
11521 (goto-char (point-min))
11522 (setq res (append res (org-scan-tags func matcher))))))))))
11523 res))
11525 ;;;; Properties
11527 ;;; Setting and retrieving properties
11529 (defconst org-special-properties
11530 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
11531 "TIMESTAMP" "TIMESTAMP_IA")
11532 "The special properties valid in Org-mode.
11534 These are properties that are not defined in the property drawer,
11535 but in some other way.")
11537 (defconst org-default-properties
11538 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
11539 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
11540 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
11541 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
11542 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
11543 "CLOCK_MODELINE_TOTAL")
11544 "Some properties that are used by Org-mode for various purposes.
11545 Being in this list makes sure that they are offered for completion.")
11547 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
11548 "Regular expression matching the first line of a property drawer.")
11550 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
11551 "Regular expression matching the first line of a property drawer.")
11553 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
11554 "Regular expression matching the first line of a property drawer.")
11556 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
11557 "Regular expression matching the first line of a property drawer.")
11559 (defconst org-property-drawer-re
11560 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
11561 org-property-end-re "\\)\n?")
11562 "Matches an entire property drawer.")
11564 (defconst org-clock-drawer-re
11565 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
11566 org-property-end-re "\\)\n?")
11567 "Matches an entire clock drawer.")
11569 (defun org-property-action ()
11570 "Do an action on properties."
11571 (interactive)
11572 (let (c)
11573 (org-at-property-p)
11574 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
11575 (setq c (read-char-exclusive))
11576 (cond
11577 ((equal c ?s)
11578 (call-interactively 'org-set-property))
11579 ((equal c ?d)
11580 (call-interactively 'org-delete-property))
11581 ((equal c ?D)
11582 (call-interactively 'org-delete-property-globally))
11583 ((equal c ?c)
11584 (call-interactively 'org-compute-property-at-point))
11585 (t (error "No such property action %c" c)))))
11587 (defun org-at-property-p ()
11588 "Is the cursor in a property line?"
11589 ;; FIXME: Does not check if we are actually in the drawer.
11590 ;; FIXME: also returns true on any drawers.....
11591 ;; This is used by C-c C-c for property action.
11592 (save-excursion
11593 (beginning-of-line 1)
11594 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
11596 (defun org-get-property-block (&optional beg end force)
11597 "Return the (beg . end) range of the body of the property drawer.
11598 BEG and END can be beginning and end of subtree, if not given
11599 they will be found.
11600 If the drawer does not exist and FORCE is non-nil, create the drawer."
11601 (catch 'exit
11602 (save-excursion
11603 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
11604 (end (or end (progn (outline-next-heading) (point)))))
11605 (goto-char beg)
11606 (if (re-search-forward org-property-start-re end t)
11607 (setq beg (1+ (match-end 0)))
11608 (if force
11609 (save-excursion
11610 (org-insert-property-drawer)
11611 (setq end (progn (outline-next-heading) (point))))
11612 (throw 'exit nil))
11613 (goto-char beg)
11614 (if (re-search-forward org-property-start-re end t)
11615 (setq beg (1+ (match-end 0)))))
11616 (if (re-search-forward org-property-end-re end t)
11617 (setq end (match-beginning 0))
11618 (or force (throw 'exit nil))
11619 (goto-char beg)
11620 (setq end beg)
11621 (org-indent-line-function)
11622 (insert ":END:\n"))
11623 (cons beg end)))))
11625 (defun org-entry-properties (&optional pom which)
11626 "Get all properties of the entry at point-or-marker POM.
11627 This includes the TODO keyword, the tags, time strings for deadline,
11628 scheduled, and clocking, and any additional properties defined in the
11629 entry. The return value is an alist, keys may occur multiple times
11630 if the property key was used several times.
11631 POM may also be nil, in which case the current entry is used.
11632 If WHICH is nil or `all', get all properties. If WHICH is
11633 `special' or `standard', only get that subclass."
11634 (setq which (or which 'all))
11635 (org-with-point-at pom
11636 (let ((clockstr (substring org-clock-string 0 -1))
11637 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
11638 beg end range props sum-props key value string clocksum)
11639 (save-excursion
11640 (when (condition-case nil
11641 (and (org-mode-p) (org-back-to-heading t))
11642 (error nil))
11643 (setq beg (point))
11644 (setq sum-props (get-text-property (point) 'org-summaries))
11645 (setq clocksum (get-text-property (point) :org-clock-minutes))
11646 (outline-next-heading)
11647 (setq end (point))
11648 (when (memq which '(all special))
11649 ;; Get the special properties, like TODO and tags
11650 (goto-char beg)
11651 (when (and (looking-at org-todo-line-regexp) (match-end 2))
11652 (push (cons "TODO" (org-match-string-no-properties 2)) props))
11653 (when (looking-at org-priority-regexp)
11654 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
11655 (when (and (setq value (org-get-tags-string))
11656 (string-match "\\S-" value))
11657 (push (cons "TAGS" value) props))
11658 (when (setq value (org-get-tags-at))
11659 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
11660 props))
11661 (while (re-search-forward org-maybe-keyword-time-regexp end t)
11662 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
11663 string (if (equal key clockstr)
11664 (org-no-properties
11665 (org-trim
11666 (buffer-substring
11667 (match-beginning 3) (goto-char (point-at-eol)))))
11668 (substring (org-match-string-no-properties 3) 1 -1)))
11669 (unless key
11670 (if (= (char-after (match-beginning 3)) ?\[)
11671 (setq key "TIMESTAMP_IA")
11672 (setq key "TIMESTAMP")))
11673 (when (or (equal key clockstr) (not (assoc key props)))
11674 (push (cons key string) props)))
11678 (when (memq which '(all standard))
11679 ;; Get the standard properties, like :PROP: ...
11680 (setq range (org-get-property-block beg end))
11681 (when range
11682 (goto-char (car range))
11683 (while (re-search-forward
11684 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
11685 (cdr range) t)
11686 (setq key (org-match-string-no-properties 1)
11687 value (org-trim (or (org-match-string-no-properties 2) "")))
11688 (unless (member key excluded)
11689 (push (cons key (or value "")) props)))))
11690 (if clocksum
11691 (push (cons "CLOCKSUM"
11692 (org-columns-number-to-string (/ (float clocksum) 60.)
11693 'add_times))
11694 props))
11695 (unless (assoc "CATEGORY" props)
11696 (setq value (or (org-get-category)
11697 (progn (org-refresh-category-properties)
11698 (org-get-category))))
11699 (push (cons "CATEGORY" value) props))
11700 (append sum-props (nreverse props)))))))
11702 (defun org-entry-get (pom property &optional inherit)
11703 "Get value of PROPERTY for entry at point-or-marker POM.
11704 If INHERIT is non-nil and the entry does not have the property,
11705 then also check higher levels of the hierarchy.
11706 If INHERIT is the symbol `selective', use inheritance only if the setting
11707 in `org-use-property-inheritance' selects PROPERTY for inheritance.
11708 If the property is present but empty, the return value is the empty string.
11709 If the property is not present at all, nil is returned."
11710 (org-with-point-at pom
11711 (if (and inherit (if (eq inherit 'selective)
11712 (org-property-inherit-p property)
11714 (org-entry-get-with-inheritance property)
11715 (if (member property org-special-properties)
11716 ;; We need a special property. Use brute force, get all properties.
11717 (cdr (assoc property (org-entry-properties nil 'special)))
11718 (let ((range (org-get-property-block)))
11719 (if (and range
11720 (goto-char (car range))
11721 (re-search-forward
11722 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
11723 (cdr range) t))
11724 ;; Found the property, return it.
11725 (if (match-end 1)
11726 (org-match-string-no-properties 1)
11727 "")))))))
11729 (defun org-property-or-variable-value (var &optional inherit)
11730 "Check if there is a property fixing the value of VAR.
11731 If yes, return this value. If not, return the current value of the variable."
11732 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
11733 (if (and prop (stringp prop) (string-match "\\S-" prop))
11734 (read prop)
11735 (symbol-value var))))
11737 (defun org-entry-delete (pom property)
11738 "Delete the property PROPERTY from entry at point-or-marker POM."
11739 (org-with-point-at pom
11740 (if (member property org-special-properties)
11741 nil ; cannot delete these properties.
11742 (let ((range (org-get-property-block)))
11743 (if (and range
11744 (goto-char (car range))
11745 (re-search-forward
11746 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
11747 (cdr range) t))
11748 (progn
11749 (delete-region (match-beginning 0) (1+ (point-at-eol)))
11751 nil)))))
11753 ;; Multi-values properties are properties that contain multiple values
11754 ;; These values are assumed to be single words, separated by whitespace.
11755 (defun org-entry-add-to-multivalued-property (pom property value)
11756 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
11757 (let* ((old (org-entry-get pom property))
11758 (values (and old (org-split-string old "[ \t]"))))
11759 (setq value (org-entry-protect-space value))
11760 (unless (member value values)
11761 (setq values (cons value values))
11762 (org-entry-put pom property
11763 (mapconcat 'identity values " ")))))
11765 (defun org-entry-remove-from-multivalued-property (pom property value)
11766 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
11767 (let* ((old (org-entry-get pom property))
11768 (values (and old (org-split-string old "[ \t]"))))
11769 (setq value (org-entry-protect-space value))
11770 (when (member value values)
11771 (setq values (delete value values))
11772 (org-entry-put pom property
11773 (mapconcat 'identity values " ")))))
11775 (defun org-entry-member-in-multivalued-property (pom property value)
11776 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
11777 (let* ((old (org-entry-get pom property))
11778 (values (and old (org-split-string old "[ \t]"))))
11779 (setq value (org-entry-protect-space value))
11780 (member value values)))
11782 (defun org-entry-get-multivalued-property (pom property)
11783 "Return a list of values in a multivalued property."
11784 (let* ((value (org-entry-get pom property))
11785 (values (and value (org-split-string value "[ \t]"))))
11786 (mapcar 'org-entry-restore-space values)))
11788 (defun org-entry-put-multivalued-property (pom property &rest values)
11789 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
11790 VALUES should be a list of strings. Spaces will be protected."
11791 (org-entry-put pom property
11792 (mapconcat 'org-entry-protect-space values " "))
11793 (let* ((value (org-entry-get pom property))
11794 (values (and value (org-split-string value "[ \t]"))))
11795 (mapcar 'org-entry-restore-space values)))
11797 (defun org-entry-protect-space (s)
11798 "Protect spaces and newline in string S."
11799 (while (string-match " " s)
11800 (setq s (replace-match "%20" t t s)))
11801 (while (string-match "\n" s)
11802 (setq s (replace-match "%0A" t t s)))
11805 (defun org-entry-restore-space (s)
11806 "Restore spaces and newline in string S."
11807 (while (string-match "%20" s)
11808 (setq s (replace-match " " t t s)))
11809 (while (string-match "%0A" s)
11810 (setq s (replace-match "\n" t t s)))
11813 (defvar org-entry-property-inherited-from (make-marker)
11814 "Marker pointing to the entry from where a property was inherited.
11815 Each call to `org-entry-get-with-inheritance' will set this marker to the
11816 location of the entry where the inheritance search matched. If there was
11817 no match, the marker will point nowhere.
11818 Note that also `org-entry-get' calls this function, if the INHERIT flag
11819 is set.")
11821 (defun org-entry-get-with-inheritance (property)
11822 "Get entry property, and search higher levels if not present."
11823 (move-marker org-entry-property-inherited-from nil)
11824 (let (tmp)
11825 (save-excursion
11826 (save-restriction
11827 (widen)
11828 (catch 'ex
11829 (while t
11830 (when (setq tmp (org-entry-get nil property))
11831 (org-back-to-heading t)
11832 (move-marker org-entry-property-inherited-from (point))
11833 (throw 'ex tmp))
11834 (or (org-up-heading-safe) (throw 'ex nil)))))
11835 (or tmp
11836 (cdr (assoc property org-file-properties))
11837 (cdr (assoc property org-global-properties))
11838 (cdr (assoc property org-global-properties-fixed))))))
11840 (defun org-entry-put (pom property value)
11841 "Set PROPERTY to VALUE for entry at point-or-marker POM."
11842 (org-with-point-at pom
11843 (org-back-to-heading t)
11844 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
11845 range)
11846 (cond
11847 ((equal property "TODO")
11848 (when (and (stringp value) (string-match "\\S-" value)
11849 (not (member value org-todo-keywords-1)))
11850 (error "\"%s\" is not a valid TODO state" value))
11851 (if (or (not value)
11852 (not (string-match "\\S-" value)))
11853 (setq value 'none))
11854 (org-todo value)
11855 (org-set-tags nil 'align))
11856 ((equal property "PRIORITY")
11857 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
11858 (string-to-char value) ?\ ))
11859 (org-set-tags nil 'align))
11860 ((equal property "SCHEDULED")
11861 (if (re-search-forward org-scheduled-time-regexp end t)
11862 (cond
11863 ((eq value 'earlier) (org-timestamp-change -1 'day))
11864 ((eq value 'later) (org-timestamp-change 1 'day))
11865 (t (call-interactively 'org-schedule)))
11866 (call-interactively 'org-schedule)))
11867 ((equal property "DEADLINE")
11868 (if (re-search-forward org-deadline-time-regexp end t)
11869 (cond
11870 ((eq value 'earlier) (org-timestamp-change -1 'day))
11871 ((eq value 'later) (org-timestamp-change 1 'day))
11872 (t (call-interactively 'org-deadline)))
11873 (call-interactively 'org-deadline)))
11874 ((member property org-special-properties)
11875 (error "The %s property can not yet be set with `org-entry-put'"
11876 property))
11877 (t ; a non-special property
11878 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
11879 (setq range (org-get-property-block beg end 'force))
11880 (goto-char (car range))
11881 (if (re-search-forward
11882 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
11883 (progn
11884 (delete-region (match-beginning 1) (match-end 1))
11885 (goto-char (match-beginning 1)))
11886 (goto-char (cdr range))
11887 (insert "\n")
11888 (backward-char 1)
11889 (org-indent-line-function)
11890 (insert ":" property ":"))
11891 (and value (insert " " value))
11892 (org-indent-line-function)))))))
11894 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
11895 "Get all property keys in the current buffer.
11896 With INCLUDE-SPECIALS, also list the special properties that reflect things
11897 like tags and TODO state.
11898 With INCLUDE-DEFAULTS, also include properties that has special meaning
11899 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
11900 With INCLUDE-COLUMNS, also include property names given in COLUMN
11901 formats in the current buffer."
11902 (let (rtn range cfmt s p)
11903 (save-excursion
11904 (save-restriction
11905 (widen)
11906 (goto-char (point-min))
11907 (while (re-search-forward org-property-start-re nil t)
11908 (setq range (org-get-property-block))
11909 (goto-char (car range))
11910 (while (re-search-forward
11911 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
11912 (cdr range) t)
11913 (add-to-list 'rtn (org-match-string-no-properties 1)))
11914 (outline-next-heading))))
11916 (when include-specials
11917 (setq rtn (append org-special-properties rtn)))
11919 (when include-defaults
11920 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
11921 (add-to-list 'rtn org-effort-property))
11923 (when include-columns
11924 (save-excursion
11925 (save-restriction
11926 (widen)
11927 (goto-char (point-min))
11928 (while (re-search-forward
11929 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
11930 nil t)
11931 (setq cfmt (match-string 2) s 0)
11932 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
11933 cfmt s)
11934 (setq s (match-end 0)
11935 p (match-string 1 cfmt))
11936 (unless (or (equal p "ITEM")
11937 (member p org-special-properties))
11938 (add-to-list 'rtn (match-string 1 cfmt))))))))
11940 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
11942 (defun org-property-values (key)
11943 "Return a list of all values of property KEY."
11944 (save-excursion
11945 (save-restriction
11946 (widen)
11947 (goto-char (point-min))
11948 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
11949 values)
11950 (while (re-search-forward re nil t)
11951 (add-to-list 'values (org-trim (match-string 1))))
11952 (delete "" values)))))
11954 (defun org-insert-property-drawer ()
11955 "Insert a property drawer into the current entry."
11956 (interactive)
11957 (org-back-to-heading t)
11958 (looking-at outline-regexp)
11959 (let ((indent (if org-adapt-indentation
11960 (- (match-end 0)(match-beginning 0))
11962 (beg (point))
11963 (re (concat "^[ \t]*" org-keyword-time-regexp))
11964 end hiddenp)
11965 (outline-next-heading)
11966 (setq end (point))
11967 (goto-char beg)
11968 (while (re-search-forward re end t))
11969 (setq hiddenp (org-invisible-p))
11970 (end-of-line 1)
11971 (and (equal (char-after) ?\n) (forward-char 1))
11972 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
11973 (if (member (match-string 1) '("CLOCK:" ":END:"))
11974 ;; just skip this line
11975 (beginning-of-line 2)
11976 ;; Drawer start, find the end
11977 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
11978 (beginning-of-line 1)))
11979 (org-skip-over-state-notes)
11980 (skip-chars-backward " \t\n\r")
11981 (if (eq (char-before) ?*) (forward-char 1))
11982 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
11983 (beginning-of-line 0)
11984 (org-indent-to-column indent)
11985 (beginning-of-line 2)
11986 (org-indent-to-column indent)
11987 (beginning-of-line 0)
11988 (if hiddenp
11989 (save-excursion
11990 (org-back-to-heading t)
11991 (hide-entry))
11992 (org-flag-drawer t))))
11994 (defun org-set-property (property value)
11995 "In the current entry, set PROPERTY to VALUE.
11996 When called interactively, this will prompt for a property name, offering
11997 completion on existing and default properties. And then it will prompt
11998 for a value, offering completion either on allowed values (via an inherited
11999 xxx_ALL property) or on existing values in other instances of this property
12000 in the current file."
12001 (interactive
12002 (let* ((completion-ignore-case t)
12003 (keys (org-buffer-property-keys nil t t))
12004 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
12005 (prop (if (member prop0 keys)
12006 prop0
12007 (or (cdr (assoc (downcase prop0)
12008 (mapcar (lambda (x) (cons (downcase x) x))
12009 keys)))
12010 prop0)))
12011 (cur (org-entry-get nil prop))
12012 (allowed (org-property-get-allowed-values nil prop 'table))
12013 (existing (mapcar 'list (org-property-values prop)))
12014 (val (if allowed
12015 (org-completing-read "Value: " allowed nil 'req-match)
12016 (let (org-completion-use-ido org-completion-use-iswitchb)
12017 (org-completing-read
12018 (concat "Value" (if (and cur (string-match "\\S-" cur))
12019 (concat "[" cur "]") "")
12020 ": ")
12021 existing nil nil "" nil cur)))))
12022 (list prop (if (equal val "") cur val))))
12023 (unless (equal (org-entry-get nil property) value)
12024 (org-entry-put nil property value)))
12026 (defun org-delete-property (property)
12027 "In the current entry, delete PROPERTY."
12028 (interactive
12029 (let* ((completion-ignore-case t)
12030 (prop (org-icompleting-read
12031 "Property: " (org-entry-properties nil 'standard))))
12032 (list prop)))
12033 (message "Property %s %s" property
12034 (if (org-entry-delete nil property)
12035 "deleted"
12036 "was not present in the entry")))
12038 (defun org-delete-property-globally (property)
12039 "Remove PROPERTY globally, from all entries."
12040 (interactive
12041 (let* ((completion-ignore-case t)
12042 (prop (org-icompleting-read
12043 "Globally remove property: "
12044 (mapcar 'list (org-buffer-property-keys)))))
12045 (list prop)))
12046 (save-excursion
12047 (save-restriction
12048 (widen)
12049 (goto-char (point-min))
12050 (let ((cnt 0))
12051 (while (re-search-forward
12052 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
12053 nil t)
12054 (setq cnt (1+ cnt))
12055 (replace-match ""))
12056 (message "Property \"%s\" removed from %d entries" property cnt)))))
12058 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
12060 (defun org-compute-property-at-point ()
12061 "Compute the property at point.
12062 This looks for an enclosing column format, extracts the operator and
12063 then applies it to the property in the column format's scope."
12064 (interactive)
12065 (unless (org-at-property-p)
12066 (error "Not at a property"))
12067 (let ((prop (org-match-string-no-properties 2)))
12068 (org-columns-get-format-and-top-level)
12069 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
12070 (error "No operator defined for property %s" prop))
12071 (org-columns-compute prop)))
12073 (defun org-property-get-allowed-values (pom property &optional table)
12074 "Get allowed values for the property PROPERTY.
12075 When TABLE is non-nil, return an alist that can directly be used for
12076 completion."
12077 (let (vals)
12078 (cond
12079 ((equal property "TODO")
12080 (setq vals (org-with-point-at pom
12081 (append org-todo-keywords-1 '("")))))
12082 ((equal property "PRIORITY")
12083 (let ((n org-lowest-priority))
12084 (while (>= n org-highest-priority)
12085 (push (char-to-string n) vals)
12086 (setq n (1- n)))))
12087 ((member property org-special-properties))
12089 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
12091 (when (and vals (string-match "\\S-" vals))
12092 (setq vals (car (read-from-string (concat "(" vals ")"))))
12093 (setq vals (mapcar (lambda (x)
12094 (cond ((stringp x) x)
12095 ((numberp x) (number-to-string x))
12096 ((symbolp x) (symbol-name x))
12097 (t "???")))
12098 vals)))))
12099 (if table (mapcar 'list vals) vals)))
12101 (defun org-property-previous-allowed-value (&optional previous)
12102 "Switch to the next allowed value for this property."
12103 (interactive)
12104 (org-property-next-allowed-value t))
12106 (defun org-property-next-allowed-value (&optional previous)
12107 "Switch to the next allowed value for this property."
12108 (interactive)
12109 (unless (org-at-property-p)
12110 (error "Not at a property"))
12111 (let* ((key (match-string 2))
12112 (value (match-string 3))
12113 (allowed (or (org-property-get-allowed-values (point) key)
12114 (and (member value '("[ ]" "[-]" "[X]"))
12115 '("[ ]" "[X]"))))
12116 nval)
12117 (unless allowed
12118 (error "Allowed values for this property have not been defined"))
12119 (if previous (setq allowed (reverse allowed)))
12120 (if (member value allowed)
12121 (setq nval (car (cdr (member value allowed)))))
12122 (setq nval (or nval (car allowed)))
12123 (if (equal nval value)
12124 (error "Only one allowed value for this property"))
12125 (org-at-property-p)
12126 (replace-match (concat " :" key ": " nval) t t)
12127 (org-indent-line-function)
12128 (beginning-of-line 1)
12129 (skip-chars-forward " \t")))
12131 (defun org-find-entry-with-id (ident)
12132 "Locate the entry that contains the ID property with exact value IDENT.
12133 IDENT can be a string, a symbol or a number, this function will search for
12134 the string representation of it.
12135 Return the position where this entry starts, or nil if there is no such entry."
12136 (interactive "sID: ")
12137 (let ((id (cond
12138 ((stringp ident) ident)
12139 ((symbol-name ident) (symbol-name ident))
12140 ((numberp ident) (number-to-string ident))
12141 (t (error "IDENT %s must be a string, symbol or number" ident))))
12142 (case-fold-search nil))
12143 (save-excursion
12144 (save-restriction
12145 (widen)
12146 (goto-char (point-min))
12147 (when (re-search-forward
12148 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
12149 nil t)
12150 (org-back-to-heading t)
12151 (point))))))
12153 ;;;; Timestamps
12155 (defvar org-last-changed-timestamp nil)
12156 (defvar org-last-inserted-timestamp nil
12157 "The last time stamp inserted with `org-insert-time-stamp'.")
12158 (defvar org-time-was-given) ; dynamically scoped parameter
12159 (defvar org-end-time-was-given) ; dynamically scoped parameter
12160 (defvar org-ts-what) ; dynamically scoped parameter
12162 (defun org-time-stamp (arg &optional inactive)
12163 "Prompt for a date/time and insert a time stamp.
12164 If the user specifies a time like HH:MM, or if this command is called
12165 with a prefix argument, the time stamp will contain date and time.
12166 Otherwise, only the date will be included. All parts of a date not
12167 specified by the user will be filled in from the current date/time.
12168 So if you press just return without typing anything, the time stamp
12169 will represent the current date/time. If there is already a timestamp
12170 at the cursor, it will be modified."
12171 (interactive "P")
12172 (let* ((ts nil)
12173 (default-time
12174 ;; Default time is either today, or, when entering a range,
12175 ;; the range start.
12176 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
12177 (save-excursion
12178 (re-search-backward
12179 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
12180 (- (point) 20) t)))
12181 (apply 'encode-time (org-parse-time-string (match-string 1)))
12182 (current-time)))
12183 (default-input (and ts (org-get-compact-tod ts)))
12184 org-time-was-given org-end-time-was-given time)
12185 (cond
12186 ((and (org-at-timestamp-p t)
12187 (memq last-command '(org-time-stamp org-time-stamp-inactive))
12188 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
12189 (insert "--")
12190 (setq time (let ((this-command this-command))
12191 (org-read-date arg 'totime nil nil
12192 default-time default-input)))
12193 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
12194 ((org-at-timestamp-p t)
12195 (setq time (let ((this-command this-command))
12196 (org-read-date arg 'totime nil nil default-time default-input)))
12197 (when (org-at-timestamp-p t) ; just to get the match data
12198 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
12199 (replace-match "")
12200 (setq org-last-changed-timestamp
12201 (org-insert-time-stamp
12202 time (or org-time-was-given arg)
12203 inactive nil nil (list org-end-time-was-given))))
12204 (message "Timestamp updated"))
12206 (setq time (let ((this-command this-command))
12207 (org-read-date arg 'totime nil nil default-time default-input)))
12208 (org-insert-time-stamp time (or org-time-was-given arg) inactive
12209 nil nil (list org-end-time-was-given))))))
12211 ;; FIXME: can we use this for something else, like computing time differences?
12212 (defun org-get-compact-tod (s)
12213 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
12214 (let* ((t1 (match-string 1 s))
12215 (h1 (string-to-number (match-string 2 s)))
12216 (m1 (string-to-number (match-string 3 s)))
12217 (t2 (and (match-end 4) (match-string 5 s)))
12218 (h2 (and t2 (string-to-number (match-string 6 s))))
12219 (m2 (and t2 (string-to-number (match-string 7 s))))
12220 dh dm)
12221 (if (not t2)
12223 (setq dh (- h2 h1) dm (- m2 m1))
12224 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
12225 (concat t1 "+" (number-to-string dh)
12226 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
12228 (defun org-time-stamp-inactive (&optional arg)
12229 "Insert an inactive time stamp.
12230 An inactive time stamp is enclosed in square brackets instead of angle
12231 brackets. It is inactive in the sense that it does not trigger agenda entries,
12232 does not link to the calendar and cannot be changed with the S-cursor keys.
12233 So these are more for recording a certain time/date."
12234 (interactive "P")
12235 (org-time-stamp arg 'inactive))
12237 (defvar org-date-ovl (org-make-overlay 1 1))
12238 (org-overlay-put org-date-ovl 'face 'org-warning)
12239 (org-detach-overlay org-date-ovl)
12241 (defvar org-ans1) ; dynamically scoped parameter
12242 (defvar org-ans2) ; dynamically scoped parameter
12244 (defvar org-plain-time-of-day-regexp) ; defined below
12246 (defvar org-overriding-default-time nil) ; dynamically scoped
12247 (defvar org-read-date-overlay nil)
12248 (defvar org-dcst nil) ; dynamically scoped
12249 (defvar org-read-date-history nil)
12250 (defvar org-read-date-final-answer nil)
12252 (defun org-read-date (&optional with-time to-time from-string prompt
12253 default-time default-input)
12254 "Read a date, possibly a time, and make things smooth for the user.
12255 The prompt will suggest to enter an ISO date, but you can also enter anything
12256 which will at least partially be understood by `parse-time-string'.
12257 Unrecognized parts of the date will default to the current day, month, year,
12258 hour and minute. If this command is called to replace a timestamp at point,
12259 of to enter the second timestamp of a range, the default time is taken from the
12260 existing stamp. For example,
12261 3-2-5 --> 2003-02-05
12262 feb 15 --> currentyear-02-15
12263 sep 12 9 --> 2009-09-12
12264 12:45 --> today 12:45
12265 22 sept 0:34 --> currentyear-09-22 0:34
12266 12 --> currentyear-currentmonth-12
12267 Fri --> nearest Friday (today or later)
12268 etc.
12270 Furthermore you can specify a relative date by giving, as the *first* thing
12271 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
12272 change in days weeks, months, years.
12273 With a single plus or minus, the date is relative to today. With a double
12274 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
12275 +4d --> four days from today
12276 +4 --> same as above
12277 +2w --> two weeks from today
12278 ++5 --> five days from default date
12280 The function understands only English month and weekday abbreviations,
12281 but this can be configured with the variables `parse-time-months' and
12282 `parse-time-weekdays'.
12284 While prompting, a calendar is popped up - you can also select the
12285 date with the mouse (button 1). The calendar shows a period of three
12286 months. To scroll it to other months, use the keys `>' and `<'.
12287 If you don't like the calendar, turn it off with
12288 \(setq org-read-date-popup-calendar nil)
12290 With optional argument TO-TIME, the date will immediately be converted
12291 to an internal time.
12292 With an optional argument WITH-TIME, the prompt will suggest to also
12293 insert a time. Note that when WITH-TIME is not set, you can still
12294 enter a time, and this function will inform the calling routine about
12295 this change. The calling routine may then choose to change the format
12296 used to insert the time stamp into the buffer to include the time.
12297 With optional argument FROM-STRING, read from this string instead from
12298 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
12299 the time/date that is used for everything that is not specified by the
12300 user."
12301 (require 'parse-time)
12302 (let* ((org-time-stamp-rounding-minutes
12303 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
12304 (org-dcst org-display-custom-times)
12305 (ct (org-current-time))
12306 (def (or org-overriding-default-time default-time ct))
12307 (defdecode (decode-time def))
12308 (dummy (progn
12309 (when (< (nth 2 defdecode) org-extend-today-until)
12310 (setcar (nthcdr 2 defdecode) -1)
12311 (setcar (nthcdr 1 defdecode) 59)
12312 (setq def (apply 'encode-time defdecode)
12313 defdecode (decode-time def)))))
12314 (calendar-frame-setup nil)
12315 (calendar-move-hook nil)
12316 (calendar-view-diary-initially-flag nil)
12317 (view-diary-entries-initially nil)
12318 (calendar-view-holidays-initially-flag nil)
12319 (view-calendar-holidays-initially nil)
12320 (timestr (format-time-string
12321 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
12322 (prompt (concat (if prompt (concat prompt " ") "")
12323 (format "Date+time [%s]: " timestr)))
12324 ans (org-ans0 "") org-ans1 org-ans2 final)
12326 (cond
12327 (from-string (setq ans from-string))
12328 (org-read-date-popup-calendar
12329 (save-excursion
12330 (save-window-excursion
12331 (calendar)
12332 (calendar-forward-day (- (time-to-days def)
12333 (calendar-absolute-from-gregorian
12334 (calendar-current-date))))
12335 (org-eval-in-calendar nil t)
12336 (let* ((old-map (current-local-map))
12337 (map (copy-keymap calendar-mode-map))
12338 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12339 (org-defkey map (kbd "RET") 'org-calendar-select)
12340 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
12341 'org-calendar-select-mouse)
12342 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
12343 'org-calendar-select-mouse)
12344 (org-defkey minibuffer-local-map [(meta shift left)]
12345 (lambda () (interactive)
12346 (org-eval-in-calendar '(calendar-backward-month 1))))
12347 (org-defkey minibuffer-local-map [(meta shift right)]
12348 (lambda () (interactive)
12349 (org-eval-in-calendar '(calendar-forward-month 1))))
12350 (org-defkey minibuffer-local-map [(meta shift up)]
12351 (lambda () (interactive)
12352 (org-eval-in-calendar '(calendar-backward-year 1))))
12353 (org-defkey minibuffer-local-map [(meta shift down)]
12354 (lambda () (interactive)
12355 (org-eval-in-calendar '(calendar-forward-year 1))))
12356 (org-defkey minibuffer-local-map [?\e (shift left)]
12357 (lambda () (interactive)
12358 (org-eval-in-calendar '(calendar-backward-month 1))))
12359 (org-defkey minibuffer-local-map [?\e (shift right)]
12360 (lambda () (interactive)
12361 (org-eval-in-calendar '(calendar-forward-month 1))))
12362 (org-defkey minibuffer-local-map [?\e (shift up)]
12363 (lambda () (interactive)
12364 (org-eval-in-calendar '(calendar-backward-year 1))))
12365 (org-defkey minibuffer-local-map [?\e (shift down)]
12366 (lambda () (interactive)
12367 (org-eval-in-calendar '(calendar-forward-year 1))))
12368 (org-defkey minibuffer-local-map [(shift up)]
12369 (lambda () (interactive)
12370 (org-eval-in-calendar '(calendar-backward-week 1))))
12371 (org-defkey minibuffer-local-map [(shift down)]
12372 (lambda () (interactive)
12373 (org-eval-in-calendar '(calendar-forward-week 1))))
12374 (org-defkey minibuffer-local-map [(shift left)]
12375 (lambda () (interactive)
12376 (org-eval-in-calendar '(calendar-backward-day 1))))
12377 (org-defkey minibuffer-local-map [(shift right)]
12378 (lambda () (interactive)
12379 (org-eval-in-calendar '(calendar-forward-day 1))))
12380 (org-defkey minibuffer-local-map ">"
12381 (lambda () (interactive)
12382 (org-eval-in-calendar '(scroll-calendar-left 1))))
12383 (org-defkey minibuffer-local-map "<"
12384 (lambda () (interactive)
12385 (org-eval-in-calendar '(scroll-calendar-right 1))))
12386 (run-hooks 'org-read-date-minibuffer-setup-hook)
12387 (unwind-protect
12388 (progn
12389 (use-local-map map)
12390 (add-hook 'post-command-hook 'org-read-date-display)
12391 (setq org-ans0 (read-string prompt default-input
12392 'org-read-date-history nil))
12393 ;; org-ans0: from prompt
12394 ;; org-ans1: from mouse click
12395 ;; org-ans2: from calendar motion
12396 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
12397 (remove-hook 'post-command-hook 'org-read-date-display)
12398 (use-local-map old-map)
12399 (when org-read-date-overlay
12400 (org-delete-overlay org-read-date-overlay)
12401 (setq org-read-date-overlay nil)))))))
12403 (t ; Naked prompt only
12404 (unwind-protect
12405 (setq ans (read-string prompt default-input
12406 'org-read-date-history timestr))
12407 (when org-read-date-overlay
12408 (org-delete-overlay org-read-date-overlay)
12409 (setq org-read-date-overlay nil)))))
12411 (setq final (org-read-date-analyze ans def defdecode))
12412 (setq org-read-date-final-answer ans)
12414 (if to-time
12415 (apply 'encode-time final)
12416 (if (and (boundp 'org-time-was-given) org-time-was-given)
12417 (format "%04d-%02d-%02d %02d:%02d"
12418 (nth 5 final) (nth 4 final) (nth 3 final)
12419 (nth 2 final) (nth 1 final))
12420 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
12422 (defvar def)
12423 (defvar defdecode)
12424 (defvar with-time)
12425 (defun org-read-date-display ()
12426 "Display the current date prompt interpretation in the minibuffer."
12427 (when org-read-date-display-live
12428 (when org-read-date-overlay
12429 (org-delete-overlay org-read-date-overlay))
12430 (let ((p (point)))
12431 (end-of-line 1)
12432 (while (not (equal (buffer-substring
12433 (max (point-min) (- (point) 4)) (point))
12434 " "))
12435 (insert " "))
12436 (goto-char p))
12437 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
12438 " " (or org-ans1 org-ans2)))
12439 (org-end-time-was-given nil)
12440 (f (org-read-date-analyze ans def defdecode))
12441 (fmts (if org-dcst
12442 org-time-stamp-custom-formats
12443 org-time-stamp-formats))
12444 (fmt (if (or with-time
12445 (and (boundp 'org-time-was-given) org-time-was-given))
12446 (cdr fmts)
12447 (car fmts)))
12448 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
12449 (when (and org-end-time-was-given
12450 (string-match org-plain-time-of-day-regexp txt))
12451 (setq txt (concat (substring txt 0 (match-end 0)) "-"
12452 org-end-time-was-given
12453 (substring txt (match-end 0)))))
12454 (setq org-read-date-overlay
12455 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
12456 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
12458 (defun org-read-date-analyze (ans def defdecode)
12459 "Analyse the combined answer of the date prompt."
12460 ;; FIXME: cleanup and comment
12461 (let (delta deltan deltaw deltadef year month day
12462 hour minute second wday pm h2 m2 tl wday1
12463 iso-year iso-weekday iso-week iso-year iso-date)
12465 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
12466 (setq ans "+0"))
12468 (when (setq delta (org-read-date-get-relative ans (current-time) def))
12469 (setq ans (replace-match "" t t ans)
12470 deltan (car delta)
12471 deltaw (nth 1 delta)
12472 deltadef (nth 2 delta)))
12474 ;; Check if there is an iso week date in there
12475 ;; If yes, sore the info and postpone interpreting it until the rest
12476 ;; of the parsing is done
12477 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
12478 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
12479 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
12480 iso-week (string-to-number (match-string 2 ans)))
12481 (setq ans (replace-match "" t t ans)))
12483 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
12484 (when (string-match
12485 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
12486 (setq year (if (match-end 2)
12487 (string-to-number (match-string 2 ans))
12488 (string-to-number (format-time-string "%Y")))
12489 month (string-to-number (match-string 3 ans))
12490 day (string-to-number (match-string 4 ans)))
12491 (if (< year 100) (setq year (+ 2000 year)))
12492 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
12493 t nil ans)))
12494 ;; Help matching am/pm times, because `parse-time-string' does not do that.
12495 ;; If there is a time with am/pm, and *no* time without it, we convert
12496 ;; so that matching will be successful.
12497 (loop for i from 1 to 2 do ; twice, for end time as well
12498 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
12499 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
12500 (setq hour (string-to-number (match-string 1 ans))
12501 minute (if (match-end 3)
12502 (string-to-number (match-string 3 ans))
12504 pm (equal ?p
12505 (string-to-char (downcase (match-string 4 ans)))))
12506 (if (and (= hour 12) (not pm))
12507 (setq hour 0)
12508 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
12509 (setq ans (replace-match (format "%02d:%02d" hour minute)
12510 t t ans))))
12512 ;; Check if a time range is given as a duration
12513 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
12514 (setq hour (string-to-number (match-string 1 ans))
12515 h2 (+ hour (string-to-number (match-string 3 ans)))
12516 minute (string-to-number (match-string 2 ans))
12517 m2 (+ minute (if (match-end 5) (string-to-number
12518 (match-string 5 ans))0)))
12519 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
12520 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
12521 t t ans)))
12523 ;; Check if there is a time range
12524 (when (boundp 'org-end-time-was-given)
12525 (setq org-time-was-given nil)
12526 (when (and (string-match org-plain-time-of-day-regexp ans)
12527 (match-end 8))
12528 (setq org-end-time-was-given (match-string 8 ans))
12529 (setq ans (concat (substring ans 0 (match-beginning 7))
12530 (substring ans (match-end 7))))))
12532 (setq tl (parse-time-string ans)
12533 day (or (nth 3 tl) (nth 3 defdecode))
12534 month (or (nth 4 tl)
12535 (if (and org-read-date-prefer-future
12536 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
12537 (1+ (nth 4 defdecode))
12538 (nth 4 defdecode)))
12539 year (or (nth 5 tl)
12540 (if (and org-read-date-prefer-future
12541 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
12542 (1+ (nth 5 defdecode))
12543 (nth 5 defdecode)))
12544 hour (or (nth 2 tl) (nth 2 defdecode))
12545 minute (or (nth 1 tl) (nth 1 defdecode))
12546 second (or (nth 0 tl) 0)
12547 wday (nth 6 tl))
12549 ;; Special date definitions below
12550 (cond
12551 (iso-week
12552 ;; There was an iso week
12553 (setq year (or iso-year year)
12554 day (or iso-weekday wday 1)
12555 wday nil ; to make sure that the trigger below does not match
12556 iso-date (calendar-gregorian-from-absolute
12557 (calendar-absolute-from-iso
12558 (list iso-week day year))))
12559 ; FIXME: Should we also push ISO weeks into the future?
12560 ; (when (and org-read-date-prefer-future
12561 ; (not iso-year)
12562 ; (< (calendar-absolute-from-gregorian iso-date)
12563 ; (time-to-days (current-time))))
12564 ; (setq year (1+ year)
12565 ; iso-date (calendar-gregorian-from-absolute
12566 ; (calendar-absolute-from-iso
12567 ; (list iso-week day year)))))
12568 (setq month (car iso-date)
12569 year (nth 2 iso-date)
12570 day (nth 1 iso-date)))
12571 (deltan
12572 (unless deltadef
12573 (let ((now (decode-time (current-time))))
12574 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
12575 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
12576 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
12577 ((equal deltaw "m") (setq month (+ month deltan)))
12578 ((equal deltaw "y") (setq year (+ year deltan)))))
12579 ((and wday (not (nth 3 tl)))
12580 ;; Weekday was given, but no day, so pick that day in the week
12581 ;; on or after the derived date.
12582 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
12583 (unless (equal wday wday1)
12584 (setq day (+ day (% (- wday wday1 -7) 7))))))
12585 (if (and (boundp 'org-time-was-given)
12586 (nth 2 tl))
12587 (setq org-time-was-given t))
12588 (if (< year 100) (setq year (+ 2000 year)))
12589 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
12590 (list second minute hour day month year)))
12592 (defvar parse-time-weekdays)
12594 (defun org-read-date-get-relative (s today default)
12595 "Check string S for special relative date string.
12596 TODAY and DEFAULT are internal times, for today and for a default.
12597 Return shift list (N what def-flag)
12598 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
12599 N is the number of WHATs to shift.
12600 DEF-FLAG is t when a double ++ or -- indicates shift relative to
12601 the DEFAULT date rather than TODAY."
12602 (when (and
12603 (string-match
12604 (concat
12605 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
12606 "\\([0-9]+\\)?"
12607 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
12608 "\\([ \t]\\|$\\)") s)
12609 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
12610 (let* ((dir (if (> (match-end 1) (match-beginning 1))
12611 (string-to-char (substring (match-string 1 s) -1))
12612 ?+))
12613 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
12614 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
12615 (what (if (match-end 3) (match-string 3 s) "d"))
12616 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
12617 (date (if rel default today))
12618 (wday (nth 6 (decode-time date)))
12619 delta)
12620 (if wday1
12621 (progn
12622 (setq delta (mod (+ 7 (- wday1 wday)) 7))
12623 (if (= dir ?-) (setq delta (- delta 7)))
12624 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
12625 (list delta "d" rel))
12626 (list (* n (if (= dir ?-) -1 1)) what rel)))))
12628 (defun org-eval-in-calendar (form &optional keepdate)
12629 "Eval FORM in the calendar window and return to current window.
12630 Also, store the cursor date in variable org-ans2."
12631 (let ((sf (selected-frame))
12632 (sw (selected-window)))
12633 (select-window (get-buffer-window "*Calendar*" t))
12634 (eval form)
12635 (when (and (not keepdate) (calendar-cursor-to-date))
12636 (let* ((date (calendar-cursor-to-date))
12637 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12638 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
12639 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
12640 (select-window sw)
12641 (select-frame-set-input-focus sf)))
12643 (defun org-calendar-select ()
12644 "Return to `org-read-date' with the date currently selected.
12645 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12646 (interactive)
12647 (when (calendar-cursor-to-date)
12648 (let* ((date (calendar-cursor-to-date))
12649 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12650 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12651 (if (active-minibuffer-window) (exit-minibuffer))))
12653 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
12654 "Insert a date stamp for the date given by the internal TIME.
12655 WITH-HM means, use the stamp format that includes the time of the day.
12656 INACTIVE means use square brackets instead of angular ones, so that the
12657 stamp will not contribute to the agenda.
12658 PRE and POST are optional strings to be inserted before and after the
12659 stamp.
12660 The command returns the inserted time stamp."
12661 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
12662 stamp)
12663 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
12664 (insert-before-markers (or pre ""))
12665 (insert-before-markers (setq stamp (format-time-string fmt time)))
12666 (when (listp extra)
12667 (setq extra (car extra))
12668 (if (and (stringp extra)
12669 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
12670 (setq extra (format "-%02d:%02d"
12671 (string-to-number (match-string 1 extra))
12672 (string-to-number (match-string 2 extra))))
12673 (setq extra nil)))
12674 (when extra
12675 (backward-char 1)
12676 (insert-before-markers extra)
12677 (forward-char 1))
12678 (insert-before-markers (or post ""))
12679 (setq org-last-inserted-timestamp stamp)))
12681 (defun org-toggle-time-stamp-overlays ()
12682 "Toggle the use of custom time stamp formats."
12683 (interactive)
12684 (setq org-display-custom-times (not org-display-custom-times))
12685 (unless org-display-custom-times
12686 (let ((p (point-min)) (bmp (buffer-modified-p)))
12687 (while (setq p (next-single-property-change p 'display))
12688 (if (and (get-text-property p 'display)
12689 (eq (get-text-property p 'face) 'org-date))
12690 (remove-text-properties
12691 p (setq p (next-single-property-change p 'display))
12692 '(display t))))
12693 (set-buffer-modified-p bmp)))
12694 (if (featurep 'xemacs)
12695 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12696 (org-restart-font-lock)
12697 (setq org-table-may-need-update t)
12698 (if org-display-custom-times
12699 (message "Time stamps are overlayed with custom format")
12700 (message "Time stamp overlays removed")))
12702 (defun org-display-custom-time (beg end)
12703 "Overlay modified time stamp format over timestamp between BEG and END."
12704 (let* ((ts (buffer-substring beg end))
12705 t1 w1 with-hm tf time str w2 (off 0))
12706 (save-match-data
12707 (setq t1 (org-parse-time-string ts t))
12708 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
12709 (setq off (- (match-end 0) (match-beginning 0)))))
12710 (setq end (- end off))
12711 (setq w1 (- end beg)
12712 with-hm (and (nth 1 t1) (nth 2 t1))
12713 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
12714 time (org-fix-decoded-time t1)
12715 str (org-add-props
12716 (format-time-string
12717 (substring tf 1 -1) (apply 'encode-time time))
12718 nil 'mouse-face 'highlight)
12719 w2 (length str))
12720 (if (not (= w2 w1))
12721 (add-text-properties (1+ beg) (+ 2 beg)
12722 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12723 (if (featurep 'xemacs)
12724 (progn
12725 (put-text-property beg end 'invisible t)
12726 (put-text-property beg end 'end-glyph (make-glyph str)))
12727 (put-text-property beg end 'display str))))
12729 (defun org-translate-time (string)
12730 "Translate all timestamps in STRING to custom format.
12731 But do this only if the variable `org-display-custom-times' is set."
12732 (when org-display-custom-times
12733 (save-match-data
12734 (let* ((start 0)
12735 (re org-ts-regexp-both)
12736 t1 with-hm inactive tf time str beg end)
12737 (while (setq start (string-match re string start))
12738 (setq beg (match-beginning 0)
12739 end (match-end 0)
12740 t1 (save-match-data
12741 (org-parse-time-string (substring string beg end) t))
12742 with-hm (and (nth 1 t1) (nth 2 t1))
12743 inactive (equal (substring string beg (1+ beg)) "[")
12744 tf (funcall (if with-hm 'cdr 'car)
12745 org-time-stamp-custom-formats)
12746 time (org-fix-decoded-time t1)
12747 str (format-time-string
12748 (concat
12749 (if inactive "[" "<") (substring tf 1 -1)
12750 (if inactive "]" ">"))
12751 (apply 'encode-time time))
12752 string (replace-match str t t string)
12753 start (+ start (length str)))))))
12754 string)
12756 (defun org-fix-decoded-time (time)
12757 "Set 0 instead of nil for the first 6 elements of time.
12758 Don't touch the rest."
12759 (let ((n 0))
12760 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12762 (defun org-days-to-time (timestamp-string)
12763 "Difference between TIMESTAMP-STRING and now in days."
12764 (- (time-to-days (org-time-string-to-time timestamp-string))
12765 (time-to-days (current-time))))
12767 (defun org-deadline-close (timestamp-string &optional ndays)
12768 "Is the time in TIMESTAMP-STRING close to the current date?"
12769 (setq ndays (or ndays (org-get-wdays timestamp-string)))
12770 (and (< (org-days-to-time timestamp-string) ndays)
12771 (not (org-entry-is-done-p))))
12773 (defun org-get-wdays (ts)
12774 "Get the deadline lead time appropriate for timestring TS."
12775 (cond
12776 ((<= org-deadline-warning-days 0)
12777 ;; 0 or negative, enforce this value no matter what
12778 (- org-deadline-warning-days))
12779 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
12780 ;; lead time is specified.
12781 (floor (* (string-to-number (match-string 1 ts))
12782 (cdr (assoc (match-string 2 ts)
12783 '(("d" . 1) ("w" . 7)
12784 ("m" . 30.4) ("y" . 365.25)))))))
12785 ;; go for the default.
12786 (t org-deadline-warning-days)))
12788 (defun org-calendar-select-mouse (ev)
12789 "Return to `org-read-date' with the date currently selected.
12790 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12791 (interactive "e")
12792 (mouse-set-point ev)
12793 (when (calendar-cursor-to-date)
12794 (let* ((date (calendar-cursor-to-date))
12795 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12796 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12797 (if (active-minibuffer-window) (exit-minibuffer))))
12799 (defun org-check-deadlines (ndays)
12800 "Check if there are any deadlines due or past due.
12801 A deadline is considered due if it happens within `org-deadline-warning-days'
12802 days from today's date. If the deadline appears in an entry marked DONE,
12803 it is not shown. The prefix arg NDAYS can be used to test that many
12804 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12805 (interactive "P")
12806 (let* ((org-warn-days
12807 (cond
12808 ((equal ndays '(4)) 100000)
12809 (ndays (prefix-numeric-value ndays))
12810 (t (abs org-deadline-warning-days))))
12811 (case-fold-search nil)
12812 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12813 (callback
12814 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12816 (message "%d deadlines past-due or due within %d days"
12817 (org-occur regexp nil callback)
12818 org-warn-days)))
12820 (defun org-check-before-date (date)
12821 "Check if there are deadlines or scheduled entries before DATE."
12822 (interactive (list (org-read-date)))
12823 (let ((case-fold-search nil)
12824 (regexp (concat "\\<\\(" org-deadline-string
12825 "\\|" org-scheduled-string
12826 "\\) *<\\([^>]+\\)>"))
12827 (callback
12828 (lambda () (time-less-p
12829 (org-time-string-to-time (match-string 2))
12830 (org-time-string-to-time date)))))
12831 (message "%d entries before %s"
12832 (org-occur regexp nil callback) date)))
12834 (defun org-check-after-date (date)
12835 "Check if there are deadlines or scheduled entries after DATE."
12836 (interactive (list (org-read-date)))
12837 (let ((case-fold-search nil)
12838 (regexp (concat "\\<\\(" org-deadline-string
12839 "\\|" org-scheduled-string
12840 "\\) *<\\([^>]+\\)>"))
12841 (callback
12842 (lambda () (not
12843 (time-less-p
12844 (org-time-string-to-time (match-string 2))
12845 (org-time-string-to-time date))))))
12846 (message "%d entries after %s"
12847 (org-occur regexp nil callback) date)))
12849 (defun org-evaluate-time-range (&optional to-buffer)
12850 "Evaluate a time range by computing the difference between start and end.
12851 Normally the result is just printed in the echo area, but with prefix arg
12852 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12853 If the time range is actually in a table, the result is inserted into the
12854 next column.
12855 For time difference computation, a year is assumed to be exactly 365
12856 days in order to avoid rounding problems."
12857 (interactive "P")
12859 (org-clock-update-time-maybe)
12860 (save-excursion
12861 (unless (org-at-date-range-p t)
12862 (goto-char (point-at-bol))
12863 (re-search-forward org-tr-regexp-both (point-at-eol) t))
12864 (if (not (org-at-date-range-p t))
12865 (error "Not at a time-stamp range, and none found in current line")))
12866 (let* ((ts1 (match-string 1))
12867 (ts2 (match-string 2))
12868 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12869 (match-end (match-end 0))
12870 (time1 (org-time-string-to-time ts1))
12871 (time2 (org-time-string-to-time ts2))
12872 (t1 (time-to-seconds time1))
12873 (t2 (time-to-seconds time2))
12874 (diff (abs (- t2 t1)))
12875 (negative (< (- t2 t1) 0))
12876 ;; (ys (floor (* 365 24 60 60)))
12877 (ds (* 24 60 60))
12878 (hs (* 60 60))
12879 (fy "%dy %dd %02d:%02d")
12880 (fy1 "%dy %dd")
12881 (fd "%dd %02d:%02d")
12882 (fd1 "%dd")
12883 (fh "%02d:%02d")
12884 y d h m align)
12885 (if havetime
12886 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12888 d (floor (/ diff ds)) diff (mod diff ds)
12889 h (floor (/ diff hs)) diff (mod diff hs)
12890 m (floor (/ diff 60)))
12891 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12893 d (floor (+ (/ diff ds) 0.5))
12894 h 0 m 0))
12895 (if (not to-buffer)
12896 (message "%s" (org-make-tdiff-string y d h m))
12897 (if (org-at-table-p)
12898 (progn
12899 (goto-char match-end)
12900 (setq align t)
12901 (and (looking-at " *|") (goto-char (match-end 0))))
12902 (goto-char match-end))
12903 (if (looking-at
12904 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12905 (replace-match ""))
12906 (if negative (insert " -"))
12907 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12908 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12909 (insert " " (format fh h m))))
12910 (if align (org-table-align))
12911 (message "Time difference inserted")))))
12913 (defun org-make-tdiff-string (y d h m)
12914 (let ((fmt "")
12915 (l nil))
12916 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12917 l (push y l)))
12918 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12919 l (push d l)))
12920 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12921 l (push h l)))
12922 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12923 l (push m l)))
12924 (apply 'format fmt (nreverse l))))
12926 (defun org-time-string-to-time (s)
12927 (apply 'encode-time (org-parse-time-string s)))
12928 (defun org-time-string-to-seconds (s)
12929 (time-to-seconds (org-time-string-to-time s)))
12931 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
12932 "Convert a time stamp to an absolute day number.
12933 If there is a specifyer for a cyclic time stamp, get the closest date to
12934 DAYNR.
12935 PREFER and SHOW-ALL are passed through to `org-closest-date'.
12936 the variable date is bound by the calendar when this is called."
12937 (cond
12938 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
12939 (if (org-diary-sexp-entry (match-string 1 s) "" date)
12940 daynr
12941 (+ daynr 1000)))
12942 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
12943 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
12944 (time-to-days (current-time))) (match-string 0 s)
12945 prefer show-all))
12946 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
12948 (defun org-days-to-iso-week (days)
12949 "Return the iso week number."
12950 (require 'cal-iso)
12951 (car (calendar-iso-from-absolute days)))
12953 (defun org-small-year-to-year (year)
12954 "Convert 2-digit years into 4-digit years.
12955 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
12956 The year 2000 cannot be abbreviated. Any year larger than 99
12957 is returned unchanged."
12958 (if (< year 38)
12959 (setq year (+ 2000 year))
12960 (if (< year 100)
12961 (setq year (+ 1900 year))))
12962 year)
12964 (defun org-time-from-absolute (d)
12965 "Return the time corresponding to date D.
12966 D may be an absolute day number, or a calendar-type list (month day year)."
12967 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
12968 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
12970 (defun org-calendar-holiday ()
12971 "List of holidays, for Diary display in Org-mode."
12972 (require 'holidays)
12973 (let ((hl (funcall
12974 (if (fboundp 'calendar-check-holidays)
12975 'calendar-check-holidays 'check-calendar-holidays) date)))
12976 (if hl (mapconcat 'identity hl "; "))))
12978 (defun org-diary-sexp-entry (sexp entry date)
12979 "Process a SEXP diary ENTRY for DATE."
12980 (require 'diary-lib)
12981 (let ((result (if calendar-debug-sexp
12982 (let ((stack-trace-on-error t))
12983 (eval (car (read-from-string sexp))))
12984 (condition-case nil
12985 (eval (car (read-from-string sexp)))
12986 (error
12987 (beep)
12988 (message "Bad sexp at line %d in %s: %s"
12989 (org-current-line)
12990 (buffer-file-name) sexp)
12991 (sleep-for 2))))))
12992 (cond ((stringp result) result)
12993 ((and (consp result)
12994 (stringp (cdr result))) (cdr result))
12995 (result entry)
12996 (t nil))))
12998 (defun org-diary-to-ical-string (frombuf)
12999 "Get iCalendar entries from diary entries in buffer FROMBUF.
13000 This uses the icalendar.el library."
13001 (let* ((tmpdir (if (featurep 'xemacs)
13002 (temp-directory)
13003 temporary-file-directory))
13004 (tmpfile (make-temp-name
13005 (expand-file-name "orgics" tmpdir)))
13006 buf rtn b e)
13007 (save-excursion
13008 (set-buffer frombuf)
13009 (icalendar-export-region (point-min) (point-max) tmpfile)
13010 (setq buf (find-buffer-visiting tmpfile))
13011 (set-buffer buf)
13012 (goto-char (point-min))
13013 (if (re-search-forward "^BEGIN:VEVENT" nil t)
13014 (setq b (match-beginning 0)))
13015 (goto-char (point-max))
13016 (if (re-search-backward "^END:VEVENT" nil t)
13017 (setq e (match-end 0)))
13018 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
13019 (kill-buffer buf)
13020 (delete-file tmpfile)
13021 rtn))
13023 (defun org-closest-date (start current change prefer show-all)
13024 "Find the date closest to CURRENT that is consistent with START and CHANGE.
13025 When PREFER is `past' return a date that is either CURRENT or past.
13026 When PREFER is `future', return a date that is either CURRENT or future.
13027 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
13028 ;; Make the proper lists from the dates
13029 (catch 'exit
13030 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
13031 dn dw sday cday n1 n2 n0
13032 d m y y1 y2 date1 date2 nmonths nm ny m2)
13034 (setq start (org-date-to-gregorian start)
13035 current (org-date-to-gregorian
13036 (if show-all
13037 current
13038 (time-to-days (current-time))))
13039 sday (calendar-absolute-from-gregorian start)
13040 cday (calendar-absolute-from-gregorian current))
13042 (if (<= cday sday) (throw 'exit sday))
13044 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
13045 (setq dn (string-to-number (match-string 1 change))
13046 dw (cdr (assoc (match-string 2 change) a1)))
13047 (error "Invalid change specifyer: %s" change))
13048 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
13049 (cond
13050 ((eq dw 'day)
13051 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
13052 n2 (+ n1 dn)))
13053 ((eq dw 'year)
13054 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
13055 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
13056 (setq date1 (list m d y1)
13057 n1 (calendar-absolute-from-gregorian date1)
13058 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
13059 n2 (calendar-absolute-from-gregorian date2)))
13060 ((eq dw 'month)
13061 ;; approx number of month between the two dates
13062 (setq nmonths (floor (/ (- cday sday) 30.436875)))
13063 ;; How often does dn fit in there?
13064 (setq d (nth 1 start) m (car start) y (nth 2 start)
13065 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
13066 m (+ m nm)
13067 ny (floor (/ m 12))
13068 y (+ y ny)
13069 m (- m (* ny 12)))
13070 (while (> m 12) (setq m (- m 12) y (1+ y)))
13071 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
13072 (setq m2 (+ m dn) y2 y)
13073 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13074 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
13075 (while (<= n2 cday)
13076 (setq n1 n2 m m2 y y2)
13077 (setq m2 (+ m dn) y2 y)
13078 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13079 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
13080 ;; Make sure n1 is the earlier date
13081 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
13082 (if show-all
13083 (cond
13084 ((eq prefer 'past) n1)
13085 ((eq prefer 'future) (if (= cday n1) n1 n2))
13086 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
13087 (cond
13088 ((eq prefer 'past) n1)
13089 ((eq prefer 'future) (if (= cday n1) n1 n2))
13090 (t (if (= cday n1) n1 n2)))))))
13092 (defun org-date-to-gregorian (date)
13093 "Turn any specification of DATE into a gregorian date for the calendar."
13094 (cond ((integerp date) (calendar-gregorian-from-absolute date))
13095 ((and (listp date) (= (length date) 3)) date)
13096 ((stringp date)
13097 (setq date (org-parse-time-string date))
13098 (list (nth 4 date) (nth 3 date) (nth 5 date)))
13099 ((listp date)
13100 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
13102 (defun org-parse-time-string (s &optional nodefault)
13103 "Parse the standard Org-mode time string.
13104 This should be a lot faster than the normal `parse-time-string'.
13105 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
13106 hour and minute fields will be nil if not given."
13107 (if (string-match org-ts-regexp0 s)
13108 (list 0
13109 (if (or (match-beginning 8) (not nodefault))
13110 (string-to-number (or (match-string 8 s) "0")))
13111 (if (or (match-beginning 7) (not nodefault))
13112 (string-to-number (or (match-string 7 s) "0")))
13113 (string-to-number (match-string 4 s))
13114 (string-to-number (match-string 3 s))
13115 (string-to-number (match-string 2 s))
13116 nil nil nil)
13117 (make-list 9 0)))
13119 (defun org-timestamp-up (&optional arg)
13120 "Increase the date item at the cursor by one.
13121 If the cursor is on the year, change the year. If it is on the month or
13122 the day, change that.
13123 With prefix ARG, change by that many units."
13124 (interactive "p")
13125 (org-timestamp-change (prefix-numeric-value arg)))
13127 (defun org-timestamp-down (&optional arg)
13128 "Decrease the date item at the cursor by one.
13129 If the cursor is on the year, change the year. If it is on the month or
13130 the day, change that.
13131 With prefix ARG, change by that many units."
13132 (interactive "p")
13133 (org-timestamp-change (- (prefix-numeric-value arg))))
13135 (defun org-timestamp-up-day (&optional arg)
13136 "Increase the date in the time stamp by one day.
13137 With prefix ARG, change that many days."
13138 (interactive "p")
13139 (if (and (not (org-at-timestamp-p t))
13140 (org-on-heading-p))
13141 (org-todo 'up)
13142 (org-timestamp-change (prefix-numeric-value arg) 'day)))
13144 (defun org-timestamp-down-day (&optional arg)
13145 "Decrease the date in the time stamp by one day.
13146 With prefix ARG, change that many days."
13147 (interactive "p")
13148 (if (and (not (org-at-timestamp-p t))
13149 (org-on-heading-p))
13150 (org-todo 'down)
13151 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
13153 (defun org-at-timestamp-p (&optional inactive-ok)
13154 "Determine if the cursor is in or at a timestamp."
13155 (interactive)
13156 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
13157 (pos (point))
13158 (ans (or (looking-at tsr)
13159 (save-excursion
13160 (skip-chars-backward "^[<\n\r\t")
13161 (if (> (point) (point-min)) (backward-char 1))
13162 (and (looking-at tsr)
13163 (> (- (match-end 0) pos) -1))))))
13164 (and ans
13165 (boundp 'org-ts-what)
13166 (setq org-ts-what
13167 (cond
13168 ((= pos (match-beginning 0)) 'bracket)
13169 ((= pos (1- (match-end 0))) 'bracket)
13170 ((org-pos-in-match-range pos 2) 'year)
13171 ((org-pos-in-match-range pos 3) 'month)
13172 ((org-pos-in-match-range pos 7) 'hour)
13173 ((org-pos-in-match-range pos 8) 'minute)
13174 ((or (org-pos-in-match-range pos 4)
13175 (org-pos-in-match-range pos 5)) 'day)
13176 ((and (> pos (or (match-end 8) (match-end 5)))
13177 (< pos (match-end 0)))
13178 (- pos (or (match-end 8) (match-end 5))))
13179 (t 'day))))
13180 ans))
13182 (defun org-toggle-timestamp-type ()
13183 "Toggle the type (<active> or [inactive]) of a time stamp."
13184 (interactive)
13185 (when (org-at-timestamp-p t)
13186 (let ((beg (match-beginning 0)) (end (match-end 0))
13187 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
13188 (save-excursion
13189 (goto-char beg)
13190 (while (re-search-forward "[][<>]" end t)
13191 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
13192 t t)))
13193 (message "Timestamp is now %sactive"
13194 (if (equal (char-after beg) ?<) "" "in")))))
13196 (defun org-timestamp-change (n &optional what)
13197 "Change the date in the time stamp at point.
13198 The date will be changed by N times WHAT. WHAT can be `day', `month',
13199 `year', `minute', `second'. If WHAT is not given, the cursor position
13200 in the timestamp determines what will be changed."
13201 (let ((pos (point))
13202 with-hm inactive
13203 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
13204 org-ts-what
13205 extra rem
13206 ts time time0)
13207 (if (not (org-at-timestamp-p t))
13208 (error "Not at a timestamp"))
13209 (if (and (not what) (eq org-ts-what 'bracket))
13210 (org-toggle-timestamp-type)
13211 (if (and (not what) (not (eq org-ts-what 'day))
13212 org-display-custom-times
13213 (get-text-property (point) 'display)
13214 (not (get-text-property (1- (point)) 'display)))
13215 (setq org-ts-what 'day))
13216 (setq org-ts-what (or what org-ts-what)
13217 inactive (= (char-after (match-beginning 0)) ?\[)
13218 ts (match-string 0))
13219 (replace-match "")
13220 (if (string-match
13221 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
13223 (setq extra (match-string 1 ts)))
13224 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
13225 (setq with-hm t))
13226 (setq time0 (org-parse-time-string ts))
13227 (when (and (eq org-ts-what 'minute)
13228 (eq current-prefix-arg nil))
13229 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
13230 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
13231 (setcar (cdr time0) (+ (nth 1 time0)
13232 (if (> n 0) (- rem) (- dm rem))))))
13233 (setq time
13234 (encode-time (or (car time0) 0)
13235 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
13236 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
13237 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
13238 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
13239 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
13240 (nthcdr 6 time0)))
13241 (when (and (member org-ts-what '(hour minute))
13242 extra
13243 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
13244 (setq extra (org-modify-ts-extra
13245 extra
13246 (if (eq org-ts-what 'hour) 2 5)
13247 n dm)))
13248 (when (integerp org-ts-what)
13249 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
13250 (if (eq what 'calendar)
13251 (let ((cal-date (org-get-date-from-calendar)))
13252 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
13253 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
13254 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
13255 (setcar time0 (or (car time0) 0))
13256 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
13257 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
13258 (setq time (apply 'encode-time time0))))
13259 (setq org-last-changed-timestamp
13260 (org-insert-time-stamp time with-hm inactive nil nil extra))
13261 (org-clock-update-time-maybe)
13262 (goto-char pos)
13263 ;; Try to recenter the calendar window, if any
13264 (if (and org-calendar-follow-timestamp-change
13265 (get-buffer-window "*Calendar*" t)
13266 (memq org-ts-what '(day month year)))
13267 (org-recenter-calendar (time-to-days time))))))
13269 (defun org-modify-ts-extra (s pos n dm)
13270 "Change the different parts of the lead-time and repeat fields in timestamp."
13271 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
13272 ng h m new rem)
13273 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
13274 (cond
13275 ((or (org-pos-in-match-range pos 2)
13276 (org-pos-in-match-range pos 3))
13277 (setq m (string-to-number (match-string 3 s))
13278 h (string-to-number (match-string 2 s)))
13279 (if (org-pos-in-match-range pos 2)
13280 (setq h (+ h n))
13281 (setq n (* dm (org-no-warnings (signum n))))
13282 (when (not (= 0 (setq rem (% m dm))))
13283 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
13284 (setq m (+ m n)))
13285 (if (< m 0) (setq m (+ m 60) h (1- h)))
13286 (if (> m 59) (setq m (- m 60) h (1+ h)))
13287 (setq h (min 24 (max 0 h)))
13288 (setq ng 1 new (format "-%02d:%02d" h m)))
13289 ((org-pos-in-match-range pos 6)
13290 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
13291 ((org-pos-in-match-range pos 5)
13292 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
13294 ((org-pos-in-match-range pos 9)
13295 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
13296 ((org-pos-in-match-range pos 8)
13297 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
13299 (when ng
13300 (setq s (concat
13301 (substring s 0 (match-beginning ng))
13303 (substring s (match-end ng))))))
13306 (defun org-recenter-calendar (date)
13307 "If the calendar is visible, recenter it to DATE."
13308 (let* ((win (selected-window))
13309 (cwin (get-buffer-window "*Calendar*" t))
13310 (calendar-move-hook nil))
13311 (when cwin
13312 (select-window cwin)
13313 (calendar-goto-date (if (listp date) date
13314 (calendar-gregorian-from-absolute date)))
13315 (select-window win))))
13317 (defun org-goto-calendar (&optional arg)
13318 "Go to the Emacs calendar at the current date.
13319 If there is a time stamp in the current line, go to that date.
13320 A prefix ARG can be used to force the current date."
13321 (interactive "P")
13322 (let ((tsr org-ts-regexp) diff
13323 (calendar-move-hook nil)
13324 (calendar-view-holidays-initially-flag nil)
13325 (view-calendar-holidays-initially nil)
13326 (calendar-view-diary-initially-flag nil)
13327 (view-diary-entries-initially nil))
13328 (if (or (org-at-timestamp-p)
13329 (save-excursion
13330 (beginning-of-line 1)
13331 (looking-at (concat ".*" tsr))))
13332 (let ((d1 (time-to-days (current-time)))
13333 (d2 (time-to-days
13334 (org-time-string-to-time (match-string 1)))))
13335 (setq diff (- d2 d1))))
13336 (calendar)
13337 (calendar-goto-today)
13338 (if (and diff (not arg)) (calendar-forward-day diff))))
13340 (defun org-get-date-from-calendar ()
13341 "Return a list (month day year) of date at point in calendar."
13342 (with-current-buffer "*Calendar*"
13343 (save-match-data
13344 (calendar-cursor-to-date))))
13346 (defun org-date-from-calendar ()
13347 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
13348 If there is already a time stamp at the cursor position, update it."
13349 (interactive)
13350 (if (org-at-timestamp-p t)
13351 (org-timestamp-change 0 'calendar)
13352 (let ((cal-date (org-get-date-from-calendar)))
13353 (org-insert-time-stamp
13354 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
13356 (defun org-minutes-to-hh:mm-string (m)
13357 "Compute H:MM from a number of minutes."
13358 (let ((h (/ m 60)))
13359 (setq m (- m (* 60 h)))
13360 (format org-time-clocksum-format h m)))
13362 (defun org-hh:mm-string-to-minutes (s)
13363 "Convert a string H:MM to a number of minutes.
13364 If the string is just a number, interprete it as minutes.
13365 In fact, the first hh:mm or number in the string will be taken,
13366 there can be extra stuff in the string.
13367 If no number is found, the return value is 0."
13368 (cond
13369 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
13370 (+ (* (string-to-number (match-string 1 s)) 60)
13371 (string-to-number (match-string 2 s))))
13372 ((string-match "\\([0-9]+\\)" s)
13373 (string-to-number (match-string 1 s)))
13374 (t 0)))
13376 ;;;; Files
13378 (defun org-save-all-org-buffers ()
13379 "Save all Org-mode buffers without user confirmation."
13380 (interactive)
13381 (message "Saving all Org-mode buffers...")
13382 (save-some-buffers t 'org-mode-p)
13383 (when (featurep 'org-id) (org-id-locations-save))
13384 (message "Saving all Org-mode buffers... done"))
13386 (defun org-revert-all-org-buffers ()
13387 "Revert all Org-mode buffers.
13388 Prompt for confirmation when there are unsaved changes.
13389 Be sure you know what you are doing before letting this function
13390 overwrite your changes.
13392 This function is useful in a setup where one tracks org files
13393 with a version control system, to revert on one machine after pulling
13394 changes from another. I believe the procedure must be like this:
13396 1. M-x org-save-all-org-buffers
13397 2. Pull changes from the other machine, resolve conflicts
13398 3. M-x org-revert-all-org-buffers"
13399 (interactive)
13400 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
13401 (error "Abort"))
13402 (save-excursion
13403 (save-window-excursion
13404 (mapc
13405 (lambda (b)
13406 (when (and (with-current-buffer b (org-mode-p))
13407 (with-current-buffer b buffer-file-name))
13408 (switch-to-buffer b)
13409 (revert-buffer t 'no-confirm)))
13410 (buffer-list))
13411 (when (and (featurep 'org-id) org-id-track-globally)
13412 (org-id-locations-load)))))
13414 ;;;; Agenda files
13416 ;;;###autoload
13417 (defun org-iswitchb (&optional arg)
13418 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
13419 With a prefix argument, restrict available to files.
13420 With two prefix arguments, restrict available buffers to agenda files.
13422 Due to some yet unresolved reason, the global function
13423 `iswitchb-mode' needs to be active for this function to work."
13424 (interactive "P")
13425 (require 'iswitchb)
13426 (let ((enabled iswitchb-mode) blist)
13427 (or enabled (iswitchb-mode 1))
13428 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13429 ((equal arg '(16)) (org-buffer-list 'agenda))
13430 (t (org-buffer-list))))
13431 (unwind-protect
13432 (let ((iswitchb-make-buflist-hook
13433 (lambda ()
13434 (setq iswitchb-temp-buflist
13435 (mapcar 'buffer-name blist)))))
13436 (switch-to-buffer
13437 (iswitchb-read-buffer
13438 "Switch-to: " nil t)))
13439 (or enabled (iswitchb-mode -1)))))
13441 ;;;###autoload
13442 (defun org-iswitchb (&optional arg)
13443 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
13444 With a prefix argument, restrict available to files.
13445 With two prefix arguments, restrict available buffers to agenda files."
13446 (interactive "P")
13447 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13448 ((equal arg '(16)) (org-buffer-list 'agenda))
13449 (t (org-buffer-list)))))
13450 (switch-to-buffer
13451 (org-icompleting-read "Org buffer: "
13452 (mapcar 'list (mapcar 'buffer-name blist))
13453 nil t))))
13455 ;;;###autoload
13456 (defalias 'org-ido-switchb 'org-iswitchb)
13458 (defun org-buffer-list (&optional predicate exclude-tmp)
13459 "Return a list of Org buffers.
13460 PREDICATE can be `export', `files' or `agenda'.
13462 export restrict the list to Export buffers.
13463 files restrict the list to buffers visiting Org files.
13464 agenda restrict the list to buffers visiting agenda files.
13466 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
13467 (let* ((bfn nil)
13468 (agenda-files (and (eq predicate 'agenda)
13469 (mapcar 'file-truename (org-agenda-files t))))
13470 (filter
13471 (cond
13472 ((eq predicate 'files)
13473 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
13474 ((eq predicate 'export)
13475 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
13476 ((eq predicate 'agenda)
13477 (lambda (b)
13478 (with-current-buffer b
13479 (and (eq major-mode 'org-mode)
13480 (setq bfn (buffer-file-name b))
13481 (member (file-truename bfn) agenda-files)))))
13482 (t (lambda (b) (with-current-buffer b
13483 (or (eq major-mode 'org-mode)
13484 (string-match "\*Org .*Export"
13485 (buffer-name b)))))))))
13486 (delq nil
13487 (mapcar
13488 (lambda(b)
13489 (if (and (funcall filter b)
13490 (or (not exclude-tmp)
13491 (not (string-match "tmp" (buffer-name b)))))
13493 nil))
13494 (buffer-list)))))
13496 (defun org-agenda-files (&optional unrestricted archives)
13497 "Get the list of agenda files.
13498 Optional UNRESTRICTED means return the full list even if a restriction
13499 is currently in place.
13500 When ARCHIVES is t, include all archive files hat are really being
13501 used by the agenda files. If ARCHIVE is `ifmode', do this only if
13502 `org-agenda-archives-mode' is t."
13503 (let ((files
13504 (cond
13505 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
13506 ((stringp org-agenda-files) (org-read-agenda-file-list))
13507 ((listp org-agenda-files) org-agenda-files)
13508 (t (error "Invalid value of `org-agenda-files'")))))
13509 (setq files (apply 'append
13510 (mapcar (lambda (f)
13511 (if (file-directory-p f)
13512 (directory-files
13513 f t org-agenda-file-regexp)
13514 (list f)))
13515 files)))
13516 (when org-agenda-skip-unavailable-files
13517 (setq files (delq nil
13518 (mapcar (function
13519 (lambda (file)
13520 (and (file-readable-p file) file)))
13521 files))))
13522 (when (or (eq archives t)
13523 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
13524 (setq files (org-add-archive-files files)))
13525 files))
13527 (defun org-edit-agenda-file-list ()
13528 "Edit the list of agenda files.
13529 Depending on setup, this either uses customize to edit the variable
13530 `org-agenda-files', or it visits the file that is holding the list. In the
13531 latter case, the buffer is set up in a way that saving it automatically kills
13532 the buffer and restores the previous window configuration."
13533 (interactive)
13534 (if (stringp org-agenda-files)
13535 (let ((cw (current-window-configuration)))
13536 (find-file org-agenda-files)
13537 (org-set-local 'org-window-configuration cw)
13538 (org-add-hook 'after-save-hook
13539 (lambda ()
13540 (set-window-configuration
13541 (prog1 org-window-configuration
13542 (kill-buffer (current-buffer))))
13543 (org-install-agenda-files-menu)
13544 (message "New agenda file list installed"))
13545 nil 'local)
13546 (message "%s" (substitute-command-keys
13547 "Edit list and finish with \\[save-buffer]")))
13548 (customize-variable 'org-agenda-files)))
13550 (defun org-store-new-agenda-file-list (list)
13551 "Set new value for the agenda file list and save it correctly."
13552 (if (stringp org-agenda-files)
13553 (let ((f org-agenda-files) b)
13554 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
13555 (with-temp-file f
13556 (insert (mapconcat 'identity list "\n") "\n")))
13557 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
13558 (setq org-agenda-files list)
13559 (customize-save-variable 'org-agenda-files org-agenda-files))))
13561 (defun org-read-agenda-file-list ()
13562 "Read the list of agenda files from a file."
13563 (when (file-directory-p org-agenda-files)
13564 (error "`org-agenda-files' cannot be a single directory"))
13565 (when (stringp org-agenda-files)
13566 (with-temp-buffer
13567 (insert-file-contents org-agenda-files)
13568 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
13571 ;;;###autoload
13572 (defun org-cycle-agenda-files ()
13573 "Cycle through the files in `org-agenda-files'.
13574 If the current buffer visits an agenda file, find the next one in the list.
13575 If the current buffer does not, find the first agenda file."
13576 (interactive)
13577 (let* ((fs (org-agenda-files t))
13578 (files (append fs (list (car fs))))
13579 (tcf (if buffer-file-name (file-truename buffer-file-name)))
13580 file)
13581 (unless files (error "No agenda files"))
13582 (catch 'exit
13583 (while (setq file (pop files))
13584 (if (equal (file-truename file) tcf)
13585 (when (car files)
13586 (find-file (car files))
13587 (throw 'exit t))))
13588 (find-file (car fs)))
13589 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
13591 (defun org-agenda-file-to-front (&optional to-end)
13592 "Move/add the current file to the top of the agenda file list.
13593 If the file is not present in the list, it is added to the front. If it is
13594 present, it is moved there. With optional argument TO-END, add/move to the
13595 end of the list."
13596 (interactive "P")
13597 (let ((org-agenda-skip-unavailable-files nil)
13598 (file-alist (mapcar (lambda (x)
13599 (cons (file-truename x) x))
13600 (org-agenda-files t)))
13601 (ctf (file-truename buffer-file-name))
13602 x had)
13603 (setq x (assoc ctf file-alist) had x)
13605 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
13606 (if to-end
13607 (setq file-alist (append (delq x file-alist) (list x)))
13608 (setq file-alist (cons x (delq x file-alist))))
13609 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
13610 (org-install-agenda-files-menu)
13611 (message "File %s to %s of agenda file list"
13612 (if had "moved" "added") (if to-end "end" "front"))))
13614 (defun org-remove-file (&optional file)
13615 "Remove current file from the list of files in variable `org-agenda-files'.
13616 These are the files which are being checked for agenda entries.
13617 Optional argument FILE means, use this file instead of the current."
13618 (interactive)
13619 (let* ((org-agenda-skip-unavailable-files nil)
13620 (file (or file buffer-file-name))
13621 (true-file (file-truename file))
13622 (afile (abbreviate-file-name file))
13623 (files (delq nil (mapcar
13624 (lambda (x)
13625 (if (equal true-file
13626 (file-truename x))
13627 nil x))
13628 (org-agenda-files t)))))
13629 (if (not (= (length files) (length (org-agenda-files t))))
13630 (progn
13631 (org-store-new-agenda-file-list files)
13632 (org-install-agenda-files-menu)
13633 (message "Removed file: %s" afile))
13634 (message "File was not in list: %s (not removed)" afile))))
13636 (defun org-file-menu-entry (file)
13637 (vector file (list 'find-file file) t))
13639 (defun org-check-agenda-file (file)
13640 "Make sure FILE exists. If not, ask user what to do."
13641 (when (not (file-exists-p file))
13642 (message "non-existent file %s. [R]emove from list or [A]bort?"
13643 (abbreviate-file-name file))
13644 (let ((r (downcase (read-char-exclusive))))
13645 (cond
13646 ((equal r ?r)
13647 (org-remove-file file)
13648 (throw 'nextfile t))
13649 (t (error "Abort"))))))
13651 (defun org-get-agenda-file-buffer (file)
13652 "Get a buffer visiting FILE. If the buffer needs to be created, add
13653 it to the list of buffers which might be released later."
13654 (let ((buf (org-find-base-buffer-visiting file)))
13655 (if buf
13656 buf ; just return it
13657 ;; Make a new buffer and remember it
13658 (setq buf (find-file-noselect file))
13659 (if buf (push buf org-agenda-new-buffers))
13660 buf)))
13662 (defun org-release-buffers (blist)
13663 "Release all buffers in list, asking the user for confirmation when needed.
13664 When a buffer is unmodified, it is just killed. When modified, it is saved
13665 \(if the user agrees) and then killed."
13666 (let (buf file)
13667 (while (setq buf (pop blist))
13668 (setq file (buffer-file-name buf))
13669 (when (and (buffer-modified-p buf)
13670 file
13671 (y-or-n-p (format "Save file %s? " file)))
13672 (with-current-buffer buf (save-buffer)))
13673 (kill-buffer buf))))
13675 (defun org-prepare-agenda-buffers (files)
13676 "Create buffers for all agenda files, protect archived trees and comments."
13677 (interactive)
13678 (let ((pa '(:org-archived t))
13679 (pc '(:org-comment t))
13680 (pall '(:org-archived t :org-comment t))
13681 (inhibit-read-only t)
13682 (rea (concat ":" org-archive-tag ":"))
13683 bmp file re)
13684 (save-excursion
13685 (save-restriction
13686 (while (setq file (pop files))
13687 (catch 'nextfile
13688 (if (bufferp file)
13689 (set-buffer file)
13690 (org-check-agenda-file file)
13691 (set-buffer (org-get-agenda-file-buffer file)))
13692 (widen)
13693 (setq bmp (buffer-modified-p))
13694 (org-refresh-category-properties)
13695 (setq org-todo-keywords-for-agenda
13696 (append org-todo-keywords-for-agenda org-todo-keywords-1))
13697 (setq org-done-keywords-for-agenda
13698 (append org-done-keywords-for-agenda org-done-keywords))
13699 (setq org-todo-keyword-alist-for-agenda
13700 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
13701 (setq org-tag-alist-for-agenda
13702 (append org-tag-alist-for-agenda org-tag-alist))
13704 (save-excursion
13705 (remove-text-properties (point-min) (point-max) pall)
13706 (when org-agenda-skip-archived-trees
13707 (goto-char (point-min))
13708 (while (re-search-forward rea nil t)
13709 (if (org-on-heading-p t)
13710 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
13711 (goto-char (point-min))
13712 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
13713 (while (re-search-forward re nil t)
13714 (add-text-properties
13715 (match-beginning 0) (org-end-of-subtree t) pc)))
13716 (set-buffer-modified-p bmp)))))
13717 (setq org-todo-keyword-alist-for-agenda
13718 (org-uniquify org-todo-keyword-alist-for-agenda)
13719 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
13721 ;;;; Embedded LaTeX
13723 (defvar org-cdlatex-mode-map (make-sparse-keymap)
13724 "Keymap for the minor `org-cdlatex-mode'.")
13726 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
13727 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
13728 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
13729 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
13730 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
13732 (defvar org-cdlatex-texmathp-advice-is-done nil
13733 "Flag remembering if we have applied the advice to texmathp already.")
13735 (define-minor-mode org-cdlatex-mode
13736 "Toggle the minor `org-cdlatex-mode'.
13737 This mode supports entering LaTeX environment and math in LaTeX fragments
13738 in Org-mode.
13739 \\{org-cdlatex-mode-map}"
13740 nil " OCDL" nil
13741 (when org-cdlatex-mode (require 'cdlatex))
13742 (unless org-cdlatex-texmathp-advice-is-done
13743 (setq org-cdlatex-texmathp-advice-is-done t)
13744 (defadvice texmathp (around org-math-always-on activate)
13745 "Always return t in org-mode buffers.
13746 This is because we want to insert math symbols without dollars even outside
13747 the LaTeX math segments. If Orgmode thinks that point is actually inside
13748 an embedded LaTeX fragment, let texmathp do its job.
13749 \\[org-cdlatex-mode-map]"
13750 (interactive)
13751 (let (p)
13752 (cond
13753 ((not (org-mode-p)) ad-do-it)
13754 ((eq this-command 'cdlatex-math-symbol)
13755 (setq ad-return-value t
13756 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
13758 (let ((p (org-inside-LaTeX-fragment-p)))
13759 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
13760 (setq ad-return-value t
13761 texmathp-why '("Org-mode embedded math" . 0))
13762 (if p ad-do-it)))))))))
13764 (defun turn-on-org-cdlatex ()
13765 "Unconditionally turn on `org-cdlatex-mode'."
13766 (org-cdlatex-mode 1))
13768 (defun org-inside-LaTeX-fragment-p ()
13769 "Test if point is inside a LaTeX fragment.
13770 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
13771 sequence appearing also before point.
13772 Even though the matchers for math are configurable, this function assumes
13773 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
13774 delimiters are skipped when they have been removed by customization.
13775 The return value is nil, or a cons cell with the delimiter and
13776 and the position of this delimiter.
13778 This function does a reasonably good job, but can locally be fooled by
13779 for example currency specifications. For example it will assume being in
13780 inline math after \"$22.34\". The LaTeX fragment formatter will only format
13781 fragments that are properly closed, but during editing, we have to live
13782 with the uncertainty caused by missing closing delimiters. This function
13783 looks only before point, not after."
13784 (catch 'exit
13785 (let ((pos (point))
13786 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
13787 (lim (progn
13788 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
13789 (point)))
13790 dd-on str (start 0) m re)
13791 (goto-char pos)
13792 (when dodollar
13793 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
13794 re (nth 1 (assoc "$" org-latex-regexps)))
13795 (while (string-match re str start)
13796 (cond
13797 ((= (match-end 0) (length str))
13798 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
13799 ((= (match-end 0) (- (length str) 5))
13800 (throw 'exit nil))
13801 (t (setq start (match-end 0))))))
13802 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
13803 (goto-char pos)
13804 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
13805 (and (match-beginning 2) (throw 'exit nil))
13806 ;; count $$
13807 (while (re-search-backward "\\$\\$" lim t)
13808 (setq dd-on (not dd-on)))
13809 (goto-char pos)
13810 (if dd-on (cons "$$" m))))))
13813 (defun org-try-cdlatex-tab ()
13814 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
13815 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
13816 - inside a LaTeX fragment, or
13817 - after the first word in a line, where an abbreviation expansion could
13818 insert a LaTeX environment."
13819 (when org-cdlatex-mode
13820 (cond
13821 ((save-excursion
13822 (skip-chars-backward "a-zA-Z0-9*")
13823 (skip-chars-backward " \t")
13824 (bolp))
13825 (cdlatex-tab) t)
13826 ((org-inside-LaTeX-fragment-p)
13827 (cdlatex-tab) t)
13828 (t nil))))
13830 (defun org-cdlatex-underscore-caret (&optional arg)
13831 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
13832 Revert to the normal definition outside of these fragments."
13833 (interactive "P")
13834 (if (org-inside-LaTeX-fragment-p)
13835 (call-interactively 'cdlatex-sub-superscript)
13836 (let (org-cdlatex-mode)
13837 (call-interactively (key-binding (vector last-input-event))))))
13839 (defun org-cdlatex-math-modify (&optional arg)
13840 "Execute `cdlatex-math-modify' in LaTeX fragments.
13841 Revert to the normal definition outside of these fragments."
13842 (interactive "P")
13843 (if (org-inside-LaTeX-fragment-p)
13844 (call-interactively 'cdlatex-math-modify)
13845 (let (org-cdlatex-mode)
13846 (call-interactively (key-binding (vector last-input-event))))))
13848 (defvar org-latex-fragment-image-overlays nil
13849 "List of overlays carrying the images of latex fragments.")
13850 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
13852 (defun org-remove-latex-fragment-image-overlays ()
13853 "Remove all overlays with LaTeX fragment images in current buffer."
13854 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
13855 (setq org-latex-fragment-image-overlays nil))
13857 (defun org-preview-latex-fragment (&optional subtree)
13858 "Preview the LaTeX fragment at point, or all locally or globally.
13859 If the cursor is in a LaTeX fragment, create the image and overlay
13860 it over the source code. If there is no fragment at point, display
13861 all fragments in the current text, from one headline to the next. With
13862 prefix SUBTREE, display all fragments in the current subtree. With a
13863 double prefix `C-u C-u', or when the cursor is before the first headline,
13864 display all fragments in the buffer.
13865 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
13866 (interactive "P")
13867 (org-remove-latex-fragment-image-overlays)
13868 (save-excursion
13869 (save-restriction
13870 (let (beg end at msg)
13871 (cond
13872 ((or (equal subtree '(16))
13873 (not (save-excursion
13874 (re-search-backward (concat "^" outline-regexp) nil t))))
13875 (setq beg (point-min) end (point-max)
13876 msg "Creating images for buffer...%s"))
13877 ((equal subtree '(4))
13878 (org-back-to-heading)
13879 (setq beg (point) end (org-end-of-subtree t)
13880 msg "Creating images for subtree...%s"))
13882 (if (setq at (org-inside-LaTeX-fragment-p))
13883 (goto-char (max (point-min) (- (cdr at) 2)))
13884 (org-back-to-heading))
13885 (setq beg (point) end (progn (outline-next-heading) (point))
13886 msg (if at "Creating image...%s"
13887 "Creating images for entry...%s"))))
13888 (message msg "")
13889 (narrow-to-region beg end)
13890 (goto-char beg)
13891 (org-format-latex
13892 (concat "ltxpng/" (file-name-sans-extension
13893 (file-name-nondirectory
13894 buffer-file-name)))
13895 default-directory 'overlays msg at 'forbuffer)
13896 (message msg "done. Use `C-c C-c' to remove images.")))))
13898 (defvar org-latex-regexps
13899 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
13900 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
13901 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
13902 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13903 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13904 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
13905 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
13906 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
13907 "Regular expressions for matching embedded LaTeX.")
13909 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
13910 "Replace LaTeX fragments with links to an image, and produce images."
13911 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
13912 (let* ((prefixnodir (file-name-nondirectory prefix))
13913 (absprefix (expand-file-name prefix dir))
13914 (todir (file-name-directory absprefix))
13915 (opt org-format-latex-options)
13916 (matchers (plist-get opt :matchers))
13917 (re-list org-latex-regexps)
13918 (cnt 0) txt link beg end re e checkdir
13919 executables-checked
13920 m n block linkfile movefile ov)
13921 ;; Check if there are old images files with this prefix, and remove them
13922 (when (file-directory-p todir)
13923 (mapc 'delete-file
13924 (directory-files
13925 todir 'full
13926 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
13927 ;; Check the different regular expressions
13928 (while (setq e (pop re-list))
13929 (setq m (car e) re (nth 1 e) n (nth 2 e)
13930 block (if (nth 3 e) "\n\n" ""))
13931 (when (member m matchers)
13932 (goto-char (point-min))
13933 (while (re-search-forward re nil t)
13934 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
13935 (not (get-text-property (match-beginning n)
13936 'org-protected))
13937 (or (not overlays)
13938 (not (eq (get-char-property (match-beginning n)
13939 'org-overlay-type)
13940 'org-latex-overlay))))
13941 (setq txt (match-string n)
13942 beg (match-beginning n) end (match-end n)
13943 cnt (1+ cnt)
13944 linkfile (format "%s_%04d.png" prefix cnt)
13945 movefile (format "%s_%04d.png" absprefix cnt)
13946 link (concat block "[[file:" linkfile "]]" block))
13947 (if msg (message msg cnt))
13948 (goto-char beg)
13949 (unless checkdir ; make sure the directory exists
13950 (setq checkdir t)
13951 (or (file-directory-p todir) (make-directory todir)))
13953 (unless executables-checked
13954 (org-check-external-command
13955 "latex" "needed to convert LaTeX fragments to images")
13956 (org-check-external-command
13957 "dvipng" "needed to convert LaTeX fragments to images")
13958 (setq executables-checked t))
13960 (org-create-formula-image
13961 txt movefile opt forbuffer)
13962 (if overlays
13963 (progn
13964 (mapc (lambda (o)
13965 (if (eq (org-overlay-get o 'org-overlay-type)
13966 'org-latex-overlay)
13967 (org-delete-overlay o)))
13968 (org-overlays-in beg end))
13969 (setq ov (org-make-overlay beg end))
13970 (org-overlay-put ov 'org-overlay-type 'org-latex-overlay)
13971 (if (featurep 'xemacs)
13972 (progn
13973 (org-overlay-put ov 'invisible t)
13974 (org-overlay-put
13975 ov 'end-glyph
13976 (make-glyph (vector 'png :file movefile))))
13977 (org-overlay-put
13978 ov 'display
13979 (list 'image :type 'png :file movefile :ascent 'center)))
13980 (push ov org-latex-fragment-image-overlays)
13981 (goto-char end))
13982 (delete-region beg end)
13983 (insert link))))))))
13985 ;; This function borrows from Ganesh Swami's latex2png.el
13986 (defun org-create-formula-image (string tofile options buffer)
13987 (require 'org-latex)
13988 (let* ((tmpdir (if (featurep 'xemacs)
13989 (temp-directory)
13990 temporary-file-directory))
13991 (texfilebase (make-temp-name
13992 (expand-file-name "orgtex" tmpdir)))
13993 (texfile (concat texfilebase ".tex"))
13994 (dvifile (concat texfilebase ".dvi"))
13995 (pngfile (concat texfilebase ".png"))
13996 (fnh (if (featurep 'xemacs)
13997 (font-height (get-face-font 'default))
13998 (face-attribute 'default :height nil)))
13999 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
14000 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
14001 (fg (or (plist-get options (if buffer :foreground :html-foreground))
14002 "Black"))
14003 (bg (or (plist-get options (if buffer :background :html-background))
14004 "Transparent")))
14005 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
14006 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
14007 (with-temp-file texfile
14008 (insert org-format-latex-header
14009 (if org-export-latex-packages-alist
14010 (concat "\n"
14011 (mapconcat (lambda(p)
14012 (if (equal "" (car p))
14013 (format "\\usepackage{%s}" (cadr p))
14014 (format "\\usepackage[%s]{%s}"
14015 (car p) (cadr p))))
14016 org-export-latex-packages-alist "\n"))
14018 "\n\\begin{document}\n" string "\n\\end{document}\n"))
14019 (debug)
14020 (let ((dir default-directory))
14021 (condition-case nil
14022 (progn
14023 (cd tmpdir)
14024 (call-process "latex" nil nil nil texfile))
14025 (error nil))
14026 (cd dir))
14027 (if (not (file-exists-p dvifile))
14028 (progn (message "Failed to create dvi file from %s" texfile) nil)
14029 (condition-case nil
14030 (call-process "dvipng" nil nil nil
14031 "-fg" fg "-bg" bg
14032 "-D" dpi
14033 ;;"-x" scale "-y" scale
14034 "-T" "tight"
14035 "-o" pngfile
14036 dvifile)
14037 (error nil))
14038 (if (not (file-exists-p pngfile))
14039 (progn (message "Failed to create png file from %s" texfile) nil)
14040 ;; Use the requested file name and clean up
14041 (copy-file pngfile tofile 'replace)
14042 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
14043 (delete-file (concat texfilebase e)))
14044 pngfile))))
14046 (defun org-dvipng-color (attr)
14047 "Return an rgb color specification for dvipng."
14048 (apply 'format "rgb %s %s %s"
14049 (mapcar 'org-normalize-color
14050 (color-values (face-attribute 'default attr nil)))))
14052 (defun org-normalize-color (value)
14053 "Return string to be used as color value for an RGB component."
14054 (format "%g" (/ value 65535.0)))
14056 ;;;; Key bindings
14058 ;; Make `C-c C-x' a prefix key
14059 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
14061 ;; TAB key with modifiers
14062 (org-defkey org-mode-map "\C-i" 'org-cycle)
14063 (org-defkey org-mode-map [(tab)] 'org-cycle)
14064 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
14065 (org-defkey org-mode-map [(meta tab)] 'org-complete)
14066 (org-defkey org-mode-map "\M-\t" 'org-complete)
14067 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
14068 ;; The following line is necessary under Suse GNU/Linux
14069 (unless (featurep 'xemacs)
14070 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
14071 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
14072 (define-key org-mode-map [backtab] 'org-shifttab)
14074 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
14075 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
14076 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
14078 ;; Cursor keys with modifiers
14079 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
14080 (org-defkey org-mode-map [(meta right)] 'org-metaright)
14081 (org-defkey org-mode-map [(meta up)] 'org-metaup)
14082 (org-defkey org-mode-map [(meta down)] 'org-metadown)
14084 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
14085 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
14086 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
14087 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
14089 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
14090 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
14091 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
14092 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
14094 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
14095 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
14097 ;;; Extra keys for tty access.
14098 ;; We only set them when really needed because otherwise the
14099 ;; menus don't show the simple keys
14101 (when (or org-use-extra-keys
14102 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
14103 (not window-system))
14104 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
14105 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
14106 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
14107 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
14108 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
14109 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
14110 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
14111 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
14112 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
14113 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
14114 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
14115 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
14116 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
14117 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
14118 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
14119 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
14120 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
14121 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
14122 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
14123 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
14124 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
14125 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
14126 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
14127 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
14128 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
14129 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
14130 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
14131 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
14133 ;; All the other keys
14135 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
14136 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
14137 (if (boundp 'narrow-map)
14138 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
14139 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
14140 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
14141 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
14142 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
14143 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
14144 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
14145 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
14146 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
14147 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
14148 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
14149 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
14150 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
14151 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
14152 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
14153 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
14154 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
14155 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
14156 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
14157 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
14158 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
14159 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
14160 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
14161 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
14162 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
14163 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
14164 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
14165 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
14166 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
14167 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
14168 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
14169 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
14170 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
14171 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
14172 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
14173 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
14174 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
14175 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
14176 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
14177 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
14178 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
14179 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
14180 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
14181 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14182 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
14183 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
14184 (org-defkey org-mode-map "\C-c^" 'org-sort)
14185 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
14186 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
14187 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
14188 (org-defkey org-mode-map "\C-m" 'org-return)
14189 (org-defkey org-mode-map "\C-j" 'org-return-indent)
14190 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
14191 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
14192 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
14193 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
14194 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
14195 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
14196 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
14197 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
14198 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
14199 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
14200 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
14201 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
14202 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
14203 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
14204 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
14205 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
14206 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
14207 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
14209 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
14210 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
14211 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
14212 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
14214 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
14215 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
14216 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
14217 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
14218 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
14219 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
14220 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
14221 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
14222 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
14223 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
14224 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
14225 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
14226 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
14227 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
14229 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
14230 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
14231 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
14232 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
14234 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
14236 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
14238 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
14239 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
14241 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
14244 (when (featurep 'xemacs)
14245 (org-defkey org-mode-map 'button3 'popup-mode-menu))
14248 (defvar org-self-insert-command-undo-counter 0)
14250 (defvar org-table-auto-blank-field) ; defined in org-table.el
14251 (defun org-self-insert-command (N)
14252 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
14253 If the cursor is in a table looking at whitespace, the whitespace is
14254 overwritten, and the table is not marked as requiring realignment."
14255 (interactive "p")
14256 (if (and
14257 (org-table-p)
14258 (progn
14259 ;; check if we blank the field, and if that triggers align
14260 (and (featurep 'org-table) org-table-auto-blank-field
14261 (member last-command
14262 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
14263 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
14264 ;; got extra space, this field does not determine column width
14265 (let (org-table-may-need-update) (org-table-blank-field))
14266 ;; no extra space, this field may determine column width
14267 (org-table-blank-field)))
14269 (eq N 1)
14270 (looking-at "[^|\n]* |"))
14271 (let (org-table-may-need-update)
14272 (goto-char (1- (match-end 0)))
14273 (delete-backward-char 1)
14274 (goto-char (match-beginning 0))
14275 (self-insert-command N))
14276 (setq org-table-may-need-update t)
14277 (self-insert-command N)
14278 (org-fix-tags-on-the-fly)
14279 (if org-self-insert-cluster-for-undo
14280 (if (not (eq last-command 'org-self-insert-command))
14281 (setq org-self-insert-command-undo-counter 1)
14282 (if (>= org-self-insert-command-undo-counter 20)
14283 (setq org-self-insert-command-undo-counter 1)
14284 (and (> org-self-insert-command-undo-counter 0)
14285 buffer-undo-list
14286 (not (cadr buffer-undo-list)) ; remove nil entry
14287 (setcdr buffer-undo-list (cddr buffer-undo-list)))
14288 (setq org-self-insert-command-undo-counter
14289 (1+ org-self-insert-command-undo-counter)))))))
14291 (defun org-fix-tags-on-the-fly ()
14292 (when (and (equal (char-after (point-at-bol)) ?*)
14293 (org-on-heading-p))
14294 (org-align-tags-here org-tags-column)))
14296 (defun org-delete-backward-char (N)
14297 "Like `delete-backward-char', insert whitespace at field end in tables.
14298 When deleting backwards, in tables this function will insert whitespace in
14299 front of the next \"|\" separator, to keep the table aligned. The table will
14300 still be marked for re-alignment if the field did fill the entire column,
14301 because, in this case the deletion might narrow the column."
14302 (interactive "p")
14303 (if (and (org-table-p)
14304 (eq N 1)
14305 (string-match "|" (buffer-substring (point-at-bol) (point)))
14306 (looking-at ".*?|"))
14307 (let ((pos (point))
14308 (noalign (looking-at "[^|\n\r]* |"))
14309 (c org-table-may-need-update))
14310 (backward-delete-char N)
14311 (skip-chars-forward "^|")
14312 (insert " ")
14313 (goto-char (1- pos))
14314 ;; noalign: if there were two spaces at the end, this field
14315 ;; does not determine the width of the column.
14316 (if noalign (setq org-table-may-need-update c)))
14317 (backward-delete-char N)
14318 (org-fix-tags-on-the-fly)))
14320 (defun org-delete-char (N)
14321 "Like `delete-char', but insert whitespace at field end in tables.
14322 When deleting characters, in tables this function will insert whitespace in
14323 front of the next \"|\" separator, to keep the table aligned. The table will
14324 still be marked for re-alignment if the field did fill the entire column,
14325 because, in this case the deletion might narrow the column."
14326 (interactive "p")
14327 (if (and (org-table-p)
14328 (not (bolp))
14329 (not (= (char-after) ?|))
14330 (eq N 1))
14331 (if (looking-at ".*?|")
14332 (let ((pos (point))
14333 (noalign (looking-at "[^|\n\r]* |"))
14334 (c org-table-may-need-update))
14335 (replace-match (concat
14336 (substring (match-string 0) 1 -1)
14337 " |"))
14338 (goto-char pos)
14339 ;; noalign: if there were two spaces at the end, this field
14340 ;; does not determine the width of the column.
14341 (if noalign (setq org-table-may-need-update c)))
14342 (delete-char N))
14343 (delete-char N)
14344 (org-fix-tags-on-the-fly)))
14346 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
14347 (put 'org-self-insert-command 'delete-selection t)
14348 (put 'orgtbl-self-insert-command 'delete-selection t)
14349 (put 'org-delete-char 'delete-selection 'supersede)
14350 (put 'org-delete-backward-char 'delete-selection 'supersede)
14351 (put 'org-yank 'delete-selection 'yank)
14353 ;; Make `flyspell-mode' delay after some commands
14354 (put 'org-self-insert-command 'flyspell-delayed t)
14355 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
14356 (put 'org-delete-char 'flyspell-delayed t)
14357 (put 'org-delete-backward-char 'flyspell-delayed t)
14359 ;; Make pabbrev-mode expand after org-mode commands
14360 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
14361 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
14363 ;; How to do this: Measure non-white length of current string
14364 ;; If equal to column width, we should realign.
14366 (defun org-remap (map &rest commands)
14367 "In MAP, remap the functions given in COMMANDS.
14368 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
14369 (let (new old)
14370 (while commands
14371 (setq old (pop commands) new (pop commands))
14372 (if (fboundp 'command-remapping)
14373 (org-defkey map (vector 'remap old) new)
14374 (substitute-key-definition old new map global-map)))))
14376 (when (eq org-enable-table-editor 'optimized)
14377 ;; If the user wants maximum table support, we need to hijack
14378 ;; some standard editing functions
14379 (org-remap org-mode-map
14380 'self-insert-command 'org-self-insert-command
14381 'delete-char 'org-delete-char
14382 'delete-backward-char 'org-delete-backward-char)
14383 (org-defkey org-mode-map "|" 'org-force-self-insert))
14385 (defvar org-ctrl-c-ctrl-c-hook nil
14386 "Hook for functions attaching themselves to `C-c C-c'.
14387 This can be used to add additional functionality to the C-c C-c key which
14388 executes context-dependent commands.
14389 Each function will be called with no arguments. The function must check
14390 if the context is appropriate for it to act. If yes, it should do its
14391 thing and then return a non-nil value. If the context is wrong,
14392 just do nothing and return nil.")
14394 (defvar org-tab-first-hook nil
14395 "Hook for functions to attach themselves to TAB.
14396 See `org-ctrl-c-ctrl-c-hook' for more information.
14397 This hook runs as the first action when TAB is pressed, even before
14398 `org-cycle' messes around with the `outline-regexp' to cater for
14399 inline tasks and plain list item folding.
14400 If any function in this hook returns t, not other actions like table
14401 field motion visibility cycling will be done.")
14403 (defvar org-tab-after-check-for-table-hook nil
14404 "Hook for functions to attach themselves to TAB.
14405 See `org-ctrl-c-ctrl-c-hook' for more information.
14406 This hook runs after it has been established that the cursor is not in a
14407 table, but before checking if the cursor is in a headline or if global cycling
14408 should be done.
14409 If any function in this hook returns t, not other actions like visibility
14410 cycling will be done.")
14412 (defvar org-tab-after-check-for-cycling-hook nil
14413 "Hook for functions to attach themselves to TAB.
14414 See `org-ctrl-c-ctrl-c-hook' for more information.
14415 This hook runs after it has been established that not table field motion and
14416 not visibility should be done because of current context. This is probably
14417 the place where a package like yasnippets can hook in.")
14419 (defvar org-metaleft-hook nil
14420 "Hook for functions attaching themselves to `M-left'.
14421 See `org-ctrl-c-ctrl-c-hook' for more information.")
14422 (defvar org-metaright-hook nil
14423 "Hook for functions attaching themselves to `M-right'.
14424 See `org-ctrl-c-ctrl-c-hook' for more information.")
14425 (defvar org-metaup-hook nil
14426 "Hook for functions attaching themselves to `M-up'.
14427 See `org-ctrl-c-ctrl-c-hook' for more information.")
14428 (defvar org-metadown-hook nil
14429 "Hook for functions attaching themselves to `M-down'.
14430 See `org-ctrl-c-ctrl-c-hook' for more information.")
14431 (defvar org-shiftmetaleft-hook nil
14432 "Hook for functions attaching themselves to `M-S-left'.
14433 See `org-ctrl-c-ctrl-c-hook' for more information.")
14434 (defvar org-shiftmetaright-hook nil
14435 "Hook for functions attaching themselves to `M-S-right'.
14436 See `org-ctrl-c-ctrl-c-hook' for more information.")
14437 (defvar org-shiftmetaup-hook nil
14438 "Hook for functions attaching themselves to `M-S-up'.
14439 See `org-ctrl-c-ctrl-c-hook' for more information.")
14440 (defvar org-shiftmetadown-hook nil
14441 "Hook for functions attaching themselves to `M-S-down'.
14442 See `org-ctrl-c-ctrl-c-hook' for more information.")
14443 (defvar org-metareturn-hook nil
14444 "Hook for functions attaching themselves to `M-RET'.
14445 See `org-ctrl-c-ctrl-c-hook' for more information.")
14447 (defun org-modifier-cursor-error ()
14448 "Throw an error, a modified cursor command was applied in wrong context."
14449 (error "This command is active in special context like tables, headlines or items"))
14451 (defun org-shiftselect-error ()
14452 "Throw an error because Shift-Cursor command was applied in wrong context."
14453 (if (and (boundp 'shift-select-mode) shift-select-mode)
14454 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
14455 (error "This command works only in special context like headlines or timestamps.")))
14457 (defun org-call-for-shift-select (cmd)
14458 (let ((this-command-keys-shift-translated t))
14459 (call-interactively cmd)))
14461 (defun org-shifttab (&optional arg)
14462 "Global visibility cycling or move to previous table field.
14463 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
14464 on context.
14465 See the individual commands for more information."
14466 (interactive "P")
14467 (cond
14468 ((org-at-table-p) (call-interactively 'org-table-previous-field))
14469 ((integerp arg)
14470 (message "Content view to level: %d" arg)
14471 (org-content (prefix-numeric-value arg))
14472 (setq org-cycle-global-status 'overview))
14473 (t (call-interactively 'org-global-cycle))))
14475 (defun org-shiftmetaleft ()
14476 "Promote subtree or delete table column.
14477 Calls `org-promote-subtree', `org-outdent-item',
14478 or `org-table-delete-column', depending on context.
14479 See the individual commands for more information."
14480 (interactive)
14481 (cond
14482 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
14483 ((org-at-table-p) (call-interactively 'org-table-delete-column))
14484 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
14485 ((org-at-item-p) (call-interactively 'org-outdent-item))
14486 (t (org-modifier-cursor-error))))
14488 (defun org-shiftmetaright ()
14489 "Demote subtree or insert table column.
14490 Calls `org-demote-subtree', `org-indent-item',
14491 or `org-table-insert-column', depending on context.
14492 See the individual commands for more information."
14493 (interactive)
14494 (cond
14495 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
14496 ((org-at-table-p) (call-interactively 'org-table-insert-column))
14497 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
14498 ((org-at-item-p) (call-interactively 'org-indent-item))
14499 (t (org-modifier-cursor-error))))
14501 (defun org-shiftmetaup (&optional arg)
14502 "Move subtree up or kill table row.
14503 Calls `org-move-subtree-up' or `org-table-kill-row' or
14504 `org-move-item-up' depending on context. See the individual commands
14505 for more information."
14506 (interactive "P")
14507 (cond
14508 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
14509 ((org-at-table-p) (call-interactively 'org-table-kill-row))
14510 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14511 ((org-at-item-p) (call-interactively 'org-move-item-up))
14512 (t (org-modifier-cursor-error))))
14514 (defun org-shiftmetadown (&optional arg)
14515 "Move subtree down or insert table row.
14516 Calls `org-move-subtree-down' or `org-table-insert-row' or
14517 `org-move-item-down', depending on context. See the individual
14518 commands for more information."
14519 (interactive "P")
14520 (cond
14521 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
14522 ((org-at-table-p) (call-interactively 'org-table-insert-row))
14523 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14524 ((org-at-item-p) (call-interactively 'org-move-item-down))
14525 (t (org-modifier-cursor-error))))
14527 (defun org-metaleft (&optional arg)
14528 "Promote heading or move table column to left.
14529 Calls `org-do-promote' or `org-table-move-column', depending on context.
14530 With no specific context, calls the Emacs default `backward-word'.
14531 See the individual commands for more information."
14532 (interactive "P")
14533 (cond
14534 ((run-hook-with-args-until-success 'org-metaleft-hook))
14535 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
14536 ((or (org-on-heading-p)
14537 (and (org-region-active-p)
14538 (save-excursion
14539 (goto-char (region-beginning))
14540 (org-on-heading-p))))
14541 (call-interactively 'org-do-promote))
14542 ((or (org-at-item-p)
14543 (and (org-region-active-p)
14544 (save-excursion
14545 (goto-char (region-beginning))
14546 (org-at-item-p))))
14547 (call-interactively 'org-outdent-item))
14548 (t (call-interactively 'backward-word))))
14550 (defun org-metaright (&optional arg)
14551 "Demote subtree or move table column to right.
14552 Calls `org-do-demote' or `org-table-move-column', depending on context.
14553 With no specific context, calls the Emacs default `forward-word'.
14554 See the individual commands for more information."
14555 (interactive "P")
14556 (cond
14557 ((run-hook-with-args-until-success 'org-metaright-hook))
14558 ((org-at-table-p) (call-interactively 'org-table-move-column))
14559 ((or (org-on-heading-p)
14560 (and (org-region-active-p)
14561 (save-excursion
14562 (goto-char (region-beginning))
14563 (org-on-heading-p))))
14564 (call-interactively 'org-do-demote))
14565 ((or (org-at-item-p)
14566 (and (org-region-active-p)
14567 (save-excursion
14568 (goto-char (region-beginning))
14569 (org-at-item-p))))
14570 (call-interactively 'org-indent-item))
14571 (t (call-interactively 'forward-word))))
14573 (defun org-metaup (&optional arg)
14574 "Move subtree up or move table row up.
14575 Calls `org-move-subtree-up' or `org-table-move-row' or
14576 `org-move-item-up', depending on context. See the individual commands
14577 for more information."
14578 (interactive "P")
14579 (cond
14580 ((run-hook-with-args-until-success 'org-metaup-hook))
14581 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
14582 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14583 ((org-at-item-p) (call-interactively 'org-move-item-up))
14584 (t (transpose-lines 1) (beginning-of-line -1))))
14586 (defun org-metadown (&optional arg)
14587 "Move subtree down or move table row down.
14588 Calls `org-move-subtree-down' or `org-table-move-row' or
14589 `org-move-item-down', depending on context. See the individual
14590 commands for more information."
14591 (interactive "P")
14592 (cond
14593 ((run-hook-with-args-until-success 'org-metadown-hook))
14594 ((org-at-table-p) (call-interactively 'org-table-move-row))
14595 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14596 ((org-at-item-p) (call-interactively 'org-move-item-down))
14597 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
14599 (defun org-shiftup (&optional arg)
14600 "Increase item in timestamp or increase priority of current headline.
14601 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
14602 depending on context. See the individual commands for more information."
14603 (interactive "P")
14604 (cond
14605 ((and org-support-shift-select (org-region-active-p))
14606 (org-call-for-shift-select 'previous-line))
14607 ((org-at-timestamp-p t)
14608 (call-interactively (if org-edit-timestamp-down-means-later
14609 'org-timestamp-down 'org-timestamp-up)))
14610 ((and (not (eq org-support-shift-select 'always))
14611 org-enable-priority-commands
14612 (org-on-heading-p))
14613 (call-interactively 'org-priority-up))
14614 ((and (not org-support-shift-select) (org-at-item-p))
14615 (call-interactively 'org-previous-item))
14616 ((org-clocktable-try-shift 'up arg))
14617 (org-support-shift-select
14618 (org-call-for-shift-select 'previous-line))
14619 (t (org-shiftselect-error))))
14621 (defun org-shiftdown (&optional arg)
14622 "Decrease item in timestamp or decrease priority of current headline.
14623 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
14624 depending on context. See the individual commands for more information."
14625 (interactive "P")
14626 (cond
14627 ((and org-support-shift-select (org-region-active-p))
14628 (org-call-for-shift-select 'next-line))
14629 ((org-at-timestamp-p t)
14630 (call-interactively (if org-edit-timestamp-down-means-later
14631 'org-timestamp-up 'org-timestamp-down)))
14632 ((and (not (eq org-support-shift-select 'always))
14633 org-enable-priority-commands
14634 (org-on-heading-p))
14635 (call-interactively 'org-priority-down))
14636 ((and (not org-support-shift-select) (org-at-item-p))
14637 (call-interactively 'org-next-item))
14638 ((org-clocktable-try-shift 'down arg))
14639 (org-support-shift-select
14640 (org-call-for-shift-select 'next-line))
14641 (t (org-shiftselect-error))))
14643 (defun org-shiftright (&optional arg)
14644 "Cycle the thing at point or in the current line, depending on context.
14645 Depending on context, this does one of the following:
14647 - switch a timestamp at point one day into the future
14648 - on a headline, switch to the next TODO keyword.
14649 - on an item, switch entire list to the next bullet type
14650 - on a property line, switch to the next allowed value
14651 - on a clocktable definition line, move time block into the future"
14652 (interactive "P")
14653 (cond
14654 ((and org-support-shift-select (org-region-active-p))
14655 (org-call-for-shift-select 'forward-char))
14656 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
14657 ((and (not (eq org-support-shift-select 'always))
14658 (org-on-heading-p))
14659 (let ((org-inhibit-logging
14660 (not org-treat-S-cursor-todo-selection-as-state-change))
14661 (org-inhibit-blocking
14662 (not org-treat-S-cursor-todo-selection-as-state-change)))
14663 (org-call-with-arg 'org-todo 'right)))
14664 ((or (and org-support-shift-select
14665 (not (eq org-support-shift-select 'always))
14666 (org-at-item-bullet-p))
14667 (and (not org-support-shift-select) (org-at-item-p)))
14668 (org-call-with-arg 'org-cycle-list-bullet nil))
14669 ((and (not (eq org-support-shift-select 'always))
14670 (org-at-property-p))
14671 (call-interactively 'org-property-next-allowed-value))
14672 ((org-clocktable-try-shift 'right arg))
14673 (org-support-shift-select
14674 (org-call-for-shift-select 'forward-char))
14675 (t (org-shiftselect-error))))
14677 (defun org-shiftleft (&optional arg)
14678 "Cycle the thing at point or in the current line, depending on context.
14679 Depending on context, this does one of the following:
14681 - switch a timestamp at point one day into the past
14682 - on a headline, switch to the previous TODO keyword.
14683 - on an item, switch entire list to the previous bullet type
14684 - on a property line, switch to the previous allowed value
14685 - on a clocktable definition line, move time block into the past"
14686 (interactive "P")
14687 (cond
14688 ((and org-support-shift-select (org-region-active-p))
14689 (org-call-for-shift-select 'backward-char))
14690 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
14691 ((and (not (eq org-support-shift-select 'always))
14692 (org-on-heading-p))
14693 (let ((org-inhibit-logging
14694 (not org-treat-S-cursor-todo-selection-as-state-change))
14695 (org-inhibit-blocking
14696 (not org-treat-S-cursor-todo-selection-as-state-change)))
14697 (org-call-with-arg 'org-todo 'left)))
14698 ((or (and org-support-shift-select
14699 (not (eq org-support-shift-select 'always))
14700 (org-at-item-bullet-p))
14701 (and (not org-support-shift-select) (org-at-item-p)))
14702 (org-call-with-arg 'org-cycle-list-bullet 'previous))
14703 ((and (not (eq org-support-shift-select 'always))
14704 (org-at-property-p))
14705 (call-interactively 'org-property-previous-allowed-value))
14706 ((org-clocktable-try-shift 'left arg))
14707 (org-support-shift-select
14708 (org-call-for-shift-select 'backward-char))
14709 (t (org-shiftselect-error))))
14711 (defun org-shiftcontrolright ()
14712 "Switch to next TODO set."
14713 (interactive)
14714 (cond
14715 ((and org-support-shift-select (org-region-active-p))
14716 (org-call-for-shift-select 'forward-word))
14717 ((and (not (eq org-support-shift-select 'always))
14718 (org-on-heading-p))
14719 (org-call-with-arg 'org-todo 'nextset))
14720 (org-support-shift-select
14721 (org-call-for-shift-select 'forward-word))
14722 (t (org-shiftselect-error))))
14724 (defun org-shiftcontrolleft ()
14725 "Switch to previous TODO set."
14726 (interactive)
14727 (cond
14728 ((and org-support-shift-select (org-region-active-p))
14729 (org-call-for-shift-select 'backward-word))
14730 ((and (not (eq org-support-shift-select 'always))
14731 (org-on-heading-p))
14732 (org-call-with-arg 'org-todo 'previousset))
14733 (org-support-shift-select
14734 (org-call-for-shift-select 'backward-word))
14735 (t (org-shiftselect-error))))
14737 (defun org-ctrl-c-ret ()
14738 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
14739 (interactive)
14740 (cond
14741 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
14742 (t (call-interactively 'org-insert-heading))))
14744 (defun org-copy-special ()
14745 "Copy region in table or copy current subtree.
14746 Calls `org-table-copy' or `org-copy-subtree', depending on context.
14747 See the individual commands for more information."
14748 (interactive)
14749 (call-interactively
14750 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
14752 (defun org-cut-special ()
14753 "Cut region in table or cut current subtree.
14754 Calls `org-table-copy' or `org-cut-subtree', depending on context.
14755 See the individual commands for more information."
14756 (interactive)
14757 (call-interactively
14758 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
14760 (defun org-paste-special (arg)
14761 "Paste rectangular region into table, or past subtree relative to level.
14762 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
14763 See the individual commands for more information."
14764 (interactive "P")
14765 (if (org-at-table-p)
14766 (org-table-paste-rectangle)
14767 (org-paste-subtree arg)))
14769 (defun org-edit-special ()
14770 "Call a special editor for the stuff at point.
14771 When at a table, call the formula editor with `org-table-edit-formulas'.
14772 When at the first line of an src example, call `org-edit-src-code'.
14773 When in an #+include line, visit the include file. Otherwise call
14774 `ffap' to visit the file at point."
14775 (interactive)
14776 (cond
14777 ((org-at-table-p)
14778 (call-interactively 'org-table-edit-formulas))
14779 ((save-excursion
14780 (beginning-of-line 1)
14781 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
14782 (find-file (org-trim (match-string 1))))
14783 ((org-edit-src-code))
14784 ((org-edit-fixed-width-region))
14785 (t (call-interactively 'ffap))))
14788 (defun org-ctrl-c-ctrl-c (&optional arg)
14789 "Set tags in headline, or update according to changed information at point.
14791 This command does many different things, depending on context:
14793 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
14794 this is what we do.
14796 - If the cursor is in a headline, prompt for tags and insert them
14797 into the current line, aligned to `org-tags-column'. When called
14798 with prefix arg, realign all tags in the current buffer.
14800 - If the cursor is in one of the special #+KEYWORD lines, this
14801 triggers scanning the buffer for these lines and updating the
14802 information.
14804 - If the cursor is inside a table, realign the table. This command
14805 works even if the automatic table editor has been turned off.
14807 - If the cursor is on a #+TBLFM line, re-apply the formulas to
14808 the entire table.
14810 - If the cursor is at a footnote reference or definition, jump to
14811 the corresponding definition or references, respectively.
14813 - If the cursor is a the beginning of a dynamic block, update it.
14815 - If the cursor is inside a table created by the table.el package,
14816 activate that table.
14818 - If the current buffer is a remember buffer, close note and file
14819 it. A prefix argument of 1 files to the default location
14820 without further interaction. A prefix argument of 2 files to
14821 the currently clocking task.
14823 - If the cursor is on a <<<target>>>, update radio targets and corresponding
14824 links in this buffer.
14826 - If the cursor is on a numbered item in a plain list, renumber the
14827 ordered list.
14829 - If the cursor is on a checkbox, toggle it."
14830 (interactive "P")
14831 (let ((org-enable-table-editor t))
14832 (cond
14833 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
14834 org-occur-highlights
14835 org-latex-fragment-image-overlays)
14836 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
14837 (org-remove-occur-highlights)
14838 (org-remove-latex-fragment-image-overlays)
14839 (message "Temporary highlights/overlays removed from current buffer"))
14840 ((and (local-variable-p 'org-finish-function (current-buffer))
14841 (fboundp org-finish-function))
14842 (funcall org-finish-function))
14843 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
14844 ((org-at-property-p)
14845 (call-interactively 'org-property-action))
14846 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
14847 ((org-on-heading-p) (call-interactively 'org-set-tags))
14848 ((org-at-table.el-p)
14849 (require 'table)
14850 (beginning-of-line 1)
14851 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
14852 (call-interactively 'table-recognize-table))
14853 ((org-at-table-p)
14854 (org-table-maybe-eval-formula)
14855 (if arg
14856 (call-interactively 'org-table-recalculate)
14857 (org-table-maybe-recalculate-line))
14858 (call-interactively 'org-table-align))
14859 ((or (org-footnote-at-reference-p)
14860 (org-footnote-at-definition-p))
14861 (call-interactively 'org-footnote-action))
14862 ((org-at-item-checkbox-p)
14863 (call-interactively 'org-toggle-checkbox))
14864 ((org-at-item-p)
14865 (if arg
14866 (call-interactively 'org-toggle-checkbox)
14867 (call-interactively 'org-maybe-renumber-ordered-list)))
14868 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
14869 ;; Dynamic block
14870 (beginning-of-line 1)
14871 (save-excursion (org-update-dblock)))
14872 ((save-excursion
14873 (beginning-of-line 1)
14874 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
14875 (cond
14876 ((equal (match-string 1) "TBLFM")
14877 ;; Recalculate the table before this line
14878 (save-excursion
14879 (beginning-of-line 1)
14880 (skip-chars-backward " \r\n\t")
14881 (if (org-at-table-p)
14882 (org-call-with-arg 'org-table-recalculate t))))
14884 ; (org-set-regexps-and-options)
14885 ; (org-restart-font-lock)
14886 (let ((org-inhibit-startup t)) (org-mode-restart))
14887 (message "Local setup has been refreshed"))))
14888 ((org-clock-update-time-maybe))
14889 (t (error "C-c C-c can do nothing useful at this location.")))))
14891 (defun org-mode-restart ()
14892 "Restart Org-mode, to scan again for special lines.
14893 Also updates the keyword regular expressions."
14894 (interactive)
14895 (org-mode)
14896 (message "Org-mode restarted"))
14898 (defun org-kill-note-or-show-branches ()
14899 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
14900 (interactive)
14901 (if (not org-finish-function)
14902 (call-interactively 'show-branches)
14903 (let ((org-note-abort t))
14904 (funcall org-finish-function))))
14906 (defun org-return (&optional indent)
14907 "Goto next table row or insert a newline.
14908 Calls `org-table-next-row' or `newline', depending on context.
14909 See the individual commands for more information."
14910 (interactive)
14911 (cond
14912 ((bobp) (if indent (newline-and-indent) (newline)))
14913 ((org-at-table-p)
14914 (org-table-justify-field-maybe)
14915 (call-interactively 'org-table-next-row))
14916 ((and org-return-follows-link
14917 (eq (get-text-property (point) 'face) 'org-link))
14918 (call-interactively 'org-open-at-point))
14919 ((and (org-at-heading-p)
14920 (looking-at
14921 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
14922 (org-show-entry)
14923 (end-of-line 1)
14924 (newline))
14925 (t (if indent (newline-and-indent) (newline)))))
14927 (defun org-return-indent ()
14928 "Goto next table row or insert a newline and indent.
14929 Calls `org-table-next-row' or `newline-and-indent', depending on
14930 context. See the individual commands for more information."
14931 (interactive)
14932 (org-return t))
14934 (defun org-ctrl-c-star ()
14935 "Compute table, or change heading status of lines.
14936 Calls `org-table-recalculate' or `org-toggle-heading',
14937 depending on context."
14938 (interactive)
14939 (cond
14940 ((org-at-table-p)
14941 (call-interactively 'org-table-recalculate))
14943 ;; Convert all lines in region to list items
14944 (call-interactively 'org-toggle-heading))))
14946 (defun org-ctrl-c-minus ()
14947 "Insert separator line in table or modify bullet status of line.
14948 Also turns a plain line or a region of lines into list items.
14949 Calls `org-table-insert-hline', `org-toggle-item', or
14950 `org-cycle-list-bullet', depending on context."
14951 (interactive)
14952 (cond
14953 ((org-at-table-p)
14954 (call-interactively 'org-table-insert-hline))
14955 ((org-region-active-p)
14956 (call-interactively 'org-toggle-item))
14957 ((org-in-item-p)
14958 (call-interactively 'org-cycle-list-bullet))
14960 (call-interactively 'org-toggle-item))))
14962 (defun org-toggle-item ()
14963 "Convert headings or normal lines to items, items to normal lines.
14964 If there is no active region, only the current line is considered.
14966 If the first line in the region is a headline, convert all headlines to items.
14968 If the first line in the region is an item, convert all items to normal lines.
14970 If the first line is normal text, add an item bullet to each line."
14971 (interactive)
14972 (let (l2 l beg end)
14973 (if (org-region-active-p)
14974 (setq beg (region-beginning) end (region-end))
14975 (setq beg (point-at-bol)
14976 end (min (1+ (point-at-eol)) (point-max))))
14977 (save-excursion
14978 (goto-char end)
14979 (setq l2 (org-current-line))
14980 (goto-char beg)
14981 (beginning-of-line 1)
14982 (setq l (1- (org-current-line)))
14983 (if (org-at-item-p)
14984 ;; We already have items, de-itemize
14985 (while (< (setq l (1+ l)) l2)
14986 (when (org-at-item-p)
14987 (goto-char (match-beginning 2))
14988 (delete-region (match-beginning 2) (match-end 2))
14989 (and (looking-at "[ \t]+") (replace-match "")))
14990 (beginning-of-line 2))
14991 (if (org-on-heading-p)
14992 ;; Headings, convert to items
14993 (while (< (setq l (1+ l)) l2)
14994 (if (looking-at org-outline-regexp)
14995 (replace-match "- " t t))
14996 (beginning-of-line 2))
14997 ;; normal lines, turn them into items
14998 (while (< (setq l (1+ l)) l2)
14999 (unless (org-at-item-p)
15000 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15001 (replace-match "\\1- \\2")))
15002 (beginning-of-line 2)))))))
15004 (defun org-toggle-heading (&optional nstars)
15005 "Convert headings to normal text, or items or text to headings.
15006 If there is no active region, only the current line is considered.
15008 If the first line is a heading, remove the stars from all headlines
15009 in the region.
15011 If the first line is a plain list item, turn all plain list items
15012 into headings.
15014 If the first line is a normal line, turn each and every line in the
15015 region into a heading.
15017 When converting a line into a heading, the number of stars is chosen
15018 such that the lines become children of the current entry. However,
15019 when a prefix argument is given, its value determines the number of
15020 stars to add."
15021 (interactive "P")
15022 (let (l2 l itemp beg end)
15023 (if (org-region-active-p)
15024 (setq beg (region-beginning) end (region-end))
15025 (setq beg (point-at-bol)
15026 end (min (1+ (point-at-eol)) (point-max))))
15027 (save-excursion
15028 (goto-char end)
15029 (setq l2 (org-current-line))
15030 (goto-char beg)
15031 (beginning-of-line 1)
15032 (setq l (1- (org-current-line)))
15033 (if (org-on-heading-p)
15034 ;; We already have headlines, de-star them
15035 (while (< (setq l (1+ l)) l2)
15036 (when (org-on-heading-p t)
15037 (and (looking-at outline-regexp) (replace-match "")))
15038 (beginning-of-line 2))
15039 (setq itemp (org-at-item-p))
15040 (let* ((stars
15041 (if nstars
15042 (make-string (prefix-numeric-value current-prefix-arg)
15044 (save-excursion
15045 (if (re-search-backward org-complex-heading-regexp nil t)
15046 (match-string 1) ""))))
15047 (add-stars (cond (nstars "")
15048 ((equal stars "") "*")
15049 (org-odd-levels-only "**")
15050 (t "*")))
15051 (rpl (concat stars add-stars " ")))
15052 (while (< (setq l (1+ l)) l2)
15053 (if itemp
15054 (and (org-at-item-p) (replace-match rpl t t))
15055 (unless (org-on-heading-p)
15056 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15057 (replace-match (concat rpl (match-string 2))))))
15058 (beginning-of-line 2)))))))
15060 (defun org-meta-return (&optional arg)
15061 "Insert a new heading or wrap a region in a table.
15062 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
15063 See the individual commands for more information."
15064 (interactive "P")
15065 (cond
15066 ((run-hook-with-args-until-success 'org-metareturn-hook))
15067 ((org-at-table-p)
15068 (call-interactively 'org-table-wrap-region))
15069 (t (call-interactively 'org-insert-heading))))
15071 ;;; Menu entries
15073 ;; Define the Org-mode menus
15074 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
15075 '("Tbl"
15076 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
15077 ["Next Field" org-cycle (org-at-table-p)]
15078 ["Previous Field" org-shifttab (org-at-table-p)]
15079 ["Next Row" org-return (org-at-table-p)]
15080 "--"
15081 ["Blank Field" org-table-blank-field (org-at-table-p)]
15082 ["Edit Field" org-table-edit-field (org-at-table-p)]
15083 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
15084 "--"
15085 ("Column"
15086 ["Move Column Left" org-metaleft (org-at-table-p)]
15087 ["Move Column Right" org-metaright (org-at-table-p)]
15088 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
15089 ["Insert Column" org-shiftmetaright (org-at-table-p)])
15090 ("Row"
15091 ["Move Row Up" org-metaup (org-at-table-p)]
15092 ["Move Row Down" org-metadown (org-at-table-p)]
15093 ["Delete Row" org-shiftmetaup (org-at-table-p)]
15094 ["Insert Row" org-shiftmetadown (org-at-table-p)]
15095 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
15096 "--"
15097 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
15098 ("Rectangle"
15099 ["Copy Rectangle" org-copy-special (org-at-table-p)]
15100 ["Cut Rectangle" org-cut-special (org-at-table-p)]
15101 ["Paste Rectangle" org-paste-special (org-at-table-p)]
15102 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
15103 "--"
15104 ("Calculate"
15105 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
15106 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
15107 ["Edit Formulas" org-edit-special (org-at-table-p)]
15108 "--"
15109 ["Recalculate line" org-table-recalculate (org-at-table-p)]
15110 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
15111 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
15112 "--"
15113 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
15114 "--"
15115 ["Sum Column/Rectangle" org-table-sum
15116 (or (org-at-table-p) (org-region-active-p))]
15117 ["Which Column?" org-table-current-column (org-at-table-p)])
15118 ["Debug Formulas"
15119 org-table-toggle-formula-debugger
15120 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
15121 ["Show Col/Row Numbers"
15122 org-table-toggle-coordinate-overlays
15123 :style toggle
15124 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
15125 "--"
15126 ["Create" org-table-create (and (not (org-at-table-p))
15127 org-enable-table-editor)]
15128 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
15129 ["Import from File" org-table-import (not (org-at-table-p))]
15130 ["Export to File" org-table-export (org-at-table-p)]
15131 "--"
15132 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
15134 (easy-menu-define org-org-menu org-mode-map "Org menu"
15135 '("Org"
15136 ("Show/Hide"
15137 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
15138 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
15139 ["Sparse Tree..." org-sparse-tree t]
15140 ["Reveal Context" org-reveal t]
15141 ["Show All" show-all t]
15142 "--"
15143 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
15144 "--"
15145 ["New Heading" org-insert-heading t]
15146 ("Navigate Headings"
15147 ["Up" outline-up-heading t]
15148 ["Next" outline-next-visible-heading t]
15149 ["Previous" outline-previous-visible-heading t]
15150 ["Next Same Level" outline-forward-same-level t]
15151 ["Previous Same Level" outline-backward-same-level t]
15152 "--"
15153 ["Jump" org-goto t])
15154 ("Edit Structure"
15155 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
15156 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
15157 "--"
15158 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
15159 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
15160 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
15161 "--"
15162 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
15163 "--"
15164 ["Promote Heading" org-metaleft (not (org-at-table-p))]
15165 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
15166 ["Demote Heading" org-metaright (not (org-at-table-p))]
15167 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
15168 "--"
15169 ["Sort Region/Children" org-sort (not (org-at-table-p))]
15170 "--"
15171 ["Convert to odd levels" org-convert-to-odd-levels t]
15172 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
15173 ("Editing"
15174 ["Emphasis..." org-emphasize t]
15175 ["Edit Source Example" org-edit-special t]
15176 "--"
15177 ["Footnote new/jump" org-footnote-action t]
15178 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
15179 ("Archive"
15180 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
15181 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
15182 ; :active t :keys "C-u C-c C-x C-a"]
15183 ["Sparse trees open ARCHIVE trees"
15184 (setq org-sparse-tree-open-archived-trees
15185 (not org-sparse-tree-open-archived-trees))
15186 :style toggle :selected org-sparse-tree-open-archived-trees]
15187 ["Cycling opens ARCHIVE trees"
15188 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
15189 :style toggle :selected org-cycle-open-archived-trees]
15190 "--"
15191 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
15192 ["Move Subtree to Archive" org-advertized-archive-subtree t]
15193 ; ["Check and Move Children" (org-archive-subtree '(4))
15194 ; :active t :keys "C-u C-c C-x C-s"]
15196 "--"
15197 ("Hyperlinks"
15198 ["Store Link (Global)" org-store-link t]
15199 ["Find existing link to here" org-occur-link-in-agenda-files t]
15200 ["Insert Link" org-insert-link t]
15201 ["Follow Link" org-open-at-point t]
15202 "--"
15203 ["Next link" org-next-link t]
15204 ["Previous link" org-previous-link t]
15205 "--"
15206 ["Descriptive Links"
15207 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
15208 :style radio
15209 :selected (member '(org-link) buffer-invisibility-spec)]
15210 ["Literal Links"
15211 (progn
15212 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
15213 :style radio
15214 :selected (not (member '(org-link) buffer-invisibility-spec))])
15215 "--"
15216 ("TODO Lists"
15217 ["TODO/DONE/-" org-todo t]
15218 ("Select keyword"
15219 ["Next keyword" org-shiftright (org-on-heading-p)]
15220 ["Previous keyword" org-shiftleft (org-on-heading-p)]
15221 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
15222 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
15223 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
15224 ["Show TODO Tree" org-show-todo-tree t]
15225 ["Global TODO list" org-todo-list t]
15226 "--"
15227 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
15228 :selected org-enforce-todo-dependencies :style toggle :active t]
15229 "Settings for tree at point"
15230 ["Do Children sequentially" org-toggle-ordered-property :style radio
15231 :selected (ignore-errors (org-entry-get nil "ORDERED"))
15232 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15233 ["Do Children parallel" org-toggle-ordered-property :style radio
15234 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
15235 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15236 "--"
15237 ["Set Priority" org-priority t]
15238 ["Priority Up" org-shiftup t]
15239 ["Priority Down" org-shiftdown t]
15240 "--"
15241 ["Get news from all feeds" org-feed-update-all t]
15242 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
15243 ["Customize feeds" (customize-variable 'org-feed-alist) t])
15244 ("TAGS and Properties"
15245 ["Set Tags" org-set-tags-command t]
15246 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
15247 "--"
15248 ["Set property" org-set-property t]
15249 ["Column view of properties" org-columns t]
15250 ["Insert Column View DBlock" org-insert-columns-dblock t])
15251 ("Dates and Scheduling"
15252 ["Timestamp" org-time-stamp t]
15253 ["Timestamp (inactive)" org-time-stamp-inactive t]
15254 ("Change Date"
15255 ["1 Day Later" org-shiftright t]
15256 ["1 Day Earlier" org-shiftleft t]
15257 ["1 ... Later" org-shiftup t]
15258 ["1 ... Earlier" org-shiftdown t])
15259 ["Compute Time Range" org-evaluate-time-range t]
15260 ["Schedule Item" org-schedule t]
15261 ["Deadline" org-deadline t]
15262 "--"
15263 ["Custom time format" org-toggle-time-stamp-overlays
15264 :style radio :selected org-display-custom-times]
15265 "--"
15266 ["Goto Calendar" org-goto-calendar t]
15267 ["Date from Calendar" org-date-from-calendar t]
15268 "--"
15269 ["Start/Restart Timer" org-timer-start t]
15270 ["Pause/Continue Timer" org-timer-pause-or-continue t]
15271 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
15272 ["Insert Timer String" org-timer t]
15273 ["Insert Timer Item" org-timer-item t])
15274 ("Logging work"
15275 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
15276 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
15277 ["Clock out" org-clock-out t]
15278 ["Clock cancel" org-clock-cancel t]
15279 "--"
15280 ["Mark as default task" org-clock-mark-default-task t]
15281 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
15282 ["Goto running clock" org-clock-goto t]
15283 "--"
15284 ["Display times" org-clock-display t]
15285 ["Create clock table" org-clock-report t]
15286 "--"
15287 ["Record DONE time"
15288 (progn (setq org-log-done (not org-log-done))
15289 (message "Switching to %s will %s record a timestamp"
15290 (car org-done-keywords)
15291 (if org-log-done "automatically" "not")))
15292 :style toggle :selected org-log-done])
15293 "--"
15294 ["Agenda Command..." org-agenda t]
15295 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
15296 ("File List for Agenda")
15297 ("Special views current file"
15298 ["TODO Tree" org-show-todo-tree t]
15299 ["Check Deadlines" org-check-deadlines t]
15300 ["Timeline" org-timeline t]
15301 ["Tags/Property tree" org-match-sparse-tree t])
15302 "--"
15303 ["Export/Publish..." org-export t]
15304 ("LaTeX"
15305 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
15306 :selected org-cdlatex-mode]
15307 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
15308 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
15309 ["Modify math symbol" org-cdlatex-math-modify
15310 (org-inside-LaTeX-fragment-p)]
15311 ["Insert citation" org-reftex-citation t]
15312 "--"
15313 ["Export LaTeX fragments as images"
15314 (if (featurep 'org-exp)
15315 (setq org-export-with-LaTeX-fragments
15316 (not org-export-with-LaTeX-fragments))
15317 (require 'org-exp))
15318 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
15319 org-export-with-LaTeX-fragments)])
15320 "--"
15321 ("Documentation"
15322 ["Show Version" org-version t]
15323 ["Info Documentation" org-info t])
15324 ("Customize"
15325 ["Browse Org Group" org-customize t]
15326 "--"
15327 ["Expand This Menu" org-create-customize-menu
15328 (fboundp 'customize-menu-create)])
15329 "--"
15330 ("Refresh/Reload"
15331 ["Refresh setup current buffer" org-mode-restart t]
15332 ["Reload Org (after update)" org-reload t]
15333 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
15336 (defun org-info (&optional node)
15337 "Read documentation for Org-mode in the info system.
15338 With optional NODE, go directly to that node."
15339 (interactive)
15340 (info (format "(org)%s" (or node ""))))
15342 (defun org-install-agenda-files-menu ()
15343 (let ((bl (buffer-list)))
15344 (save-excursion
15345 (while bl
15346 (set-buffer (pop bl))
15347 (if (org-mode-p) (setq bl nil)))
15348 (when (org-mode-p)
15349 (easy-menu-change
15350 '("Org") "File List for Agenda"
15351 (append
15352 (list
15353 ["Edit File List" (org-edit-agenda-file-list) t]
15354 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
15355 ["Remove Current File from List" org-remove-file t]
15356 ["Cycle through agenda files" org-cycle-agenda-files t]
15357 ["Occur in all agenda files" org-occur-in-agenda-files t]
15358 "--")
15359 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
15361 ;;;; Documentation
15363 ;;;###autoload
15364 (defun org-require-autoloaded-modules ()
15365 (interactive)
15366 (mapc 'require
15367 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
15368 org-docbook org-exp org-html org-icalendar
15369 org-id org-latex
15370 org-publish org-remember org-table
15371 org-timer org-xoxo)))
15373 ;;;###autoload
15374 (defun org-reload (&optional uncompiled)
15375 "Reload all org lisp files.
15376 With prefix arg UNCOMPILED, load the uncompiled versions."
15377 (interactive "P")
15378 (require 'find-func)
15379 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
15380 (dir-org (file-name-directory (org-find-library-name "org")))
15381 (dir-org-contrib (ignore-errors
15382 (file-name-directory
15383 (org-find-library-name "org-contribdir"))))
15384 (files
15385 (append (directory-files dir-org t file-re)
15386 (and dir-org-contrib
15387 (directory-files dir-org-contrib t file-re))))
15388 (remove-re (concat (if (featurep 'xemacs)
15389 "org-colview" "org-colview-xemacs")
15390 "\\'")))
15391 (setq files (mapcar 'file-name-sans-extension files))
15392 (setq files (mapcar
15393 (lambda (x) (if (string-match remove-re x) nil x))
15394 files))
15395 (setq files (delq nil files))
15396 (mapc
15397 (lambda (f)
15398 (when (featurep (intern (file-name-nondirectory f)))
15399 (if (and (not uncompiled)
15400 (file-exists-p (concat f ".elc")))
15401 (load (concat f ".elc") nil nil t)
15402 (load (concat f ".el") nil nil t))))
15403 files))
15404 (org-version))
15406 ;;;###autoload
15407 (defun org-customize ()
15408 "Call the customize function with org as argument."
15409 (interactive)
15410 (org-load-modules-maybe)
15411 (org-require-autoloaded-modules)
15412 (customize-browse 'org))
15414 (defun org-create-customize-menu ()
15415 "Create a full customization menu for Org-mode, insert it into the menu."
15416 (interactive)
15417 (org-load-modules-maybe)
15418 (org-require-autoloaded-modules)
15419 (if (fboundp 'customize-menu-create)
15420 (progn
15421 (easy-menu-change
15422 '("Org") "Customize"
15423 `(["Browse Org group" org-customize t]
15424 "--"
15425 ,(customize-menu-create 'org)
15426 ["Set" Custom-set t]
15427 ["Save" Custom-save t]
15428 ["Reset to Current" Custom-reset-current t]
15429 ["Reset to Saved" Custom-reset-saved t]
15430 ["Reset to Standard Settings" Custom-reset-standard t]))
15431 (message "\"Org\"-menu now contains full customization menu"))
15432 (error "Cannot expand menu (outdated version of cus-edit.el)")))
15434 ;;;; Miscellaneous stuff
15436 ;;; Generally useful functions
15438 (defun org-find-text-property-in-string (prop s)
15439 "Return the first non-nil value of property PROP in string S."
15440 (or (get-text-property 0 prop s)
15441 (get-text-property (or (next-single-property-change 0 prop s) 0)
15442 prop s)))
15444 (defun org-display-warning (message) ;; Copied from Emacs-Muse
15445 "Display the given MESSAGE as a warning."
15446 (if (fboundp 'display-warning)
15447 (display-warning 'org message
15448 (if (featurep 'xemacs)
15449 'warning
15450 :warning))
15451 (let ((buf (get-buffer-create "*Org warnings*")))
15452 (with-current-buffer buf
15453 (goto-char (point-max))
15454 (insert "Warning (Org): " message)
15455 (unless (bolp)
15456 (newline)))
15457 (display-buffer buf)
15458 (sit-for 0))))
15460 (defun org-goto-marker-or-bmk (marker &optional bookmark)
15461 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
15462 (if (and marker (marker-buffer marker)
15463 (buffer-live-p (marker-buffer marker)))
15464 (progn
15465 (switch-to-buffer (marker-buffer marker))
15466 (if (or (> marker (point-max)) (< marker (point-min)))
15467 (widen))
15468 (goto-char marker)
15469 (org-show-context 'org-goto))
15470 (if bookmark
15471 (bookmark-jump bookmark)
15472 (error "Cannot find location"))))
15474 (defun org-quote-csv-field (s)
15475 "Quote field for inclusion in CSV material."
15476 (if (string-match "[\",]" s)
15477 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
15480 (defun org-plist-delete (plist property)
15481 "Delete PROPERTY from PLIST.
15482 This is in contrast to merely setting it to 0."
15483 (let (p)
15484 (while plist
15485 (if (not (eq property (car plist)))
15486 (setq p (plist-put p (car plist) (nth 1 plist))))
15487 (setq plist (cddr plist)))
15490 (defun org-force-self-insert (N)
15491 "Needed to enforce self-insert under remapping."
15492 (interactive "p")
15493 (self-insert-command N))
15495 (defun org-string-width (s)
15496 "Compute width of string, ignoring invisible characters.
15497 This ignores character with invisibility property `org-link', and also
15498 characters with property `org-cwidth', because these will become invisible
15499 upon the next fontification round."
15500 (let (b l)
15501 (when (or (eq t buffer-invisibility-spec)
15502 (assq 'org-link buffer-invisibility-spec))
15503 (while (setq b (text-property-any 0 (length s)
15504 'invisible 'org-link s))
15505 (setq s (concat (substring s 0 b)
15506 (substring s (or (next-single-property-change
15507 b 'invisible s) (length s)))))))
15508 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
15509 (setq s (concat (substring s 0 b)
15510 (substring s (or (next-single-property-change
15511 b 'org-cwidth s) (length s))))))
15512 (setq l (string-width s) b -1)
15513 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
15514 (setq l (- l (get-text-property b 'org-dwidth-n s))))
15517 (defun org-get-indentation (&optional line)
15518 "Get the indentation of the current line, interpreting tabs.
15519 When LINE is given, assume it represents a line and compute its indentation."
15520 (if line
15521 (if (string-match "^ *" (org-remove-tabs line))
15522 (match-end 0))
15523 (save-excursion
15524 (beginning-of-line 1)
15525 (skip-chars-forward " \t")
15526 (current-column))))
15528 (defun org-remove-tabs (s &optional width)
15529 "Replace tabulators in S with spaces.
15530 Assumes that s is a single line, starting in column 0."
15531 (setq width (or width tab-width))
15532 (while (string-match "\t" s)
15533 (setq s (replace-match
15534 (make-string
15535 (- (* width (/ (+ (match-beginning 0) width) width))
15536 (match-beginning 0)) ?\ )
15537 t t s)))
15540 (defun org-fix-indentation (line ind)
15541 "Fix indentation in LINE.
15542 IND is a cons cell with target and minimum indentation.
15543 If the current indentation in LINE is smaller than the minimum,
15544 leave it alone. If it is larger than ind, set it to the target."
15545 (let* ((l (org-remove-tabs line))
15546 (i (org-get-indentation l))
15547 (i1 (car ind)) (i2 (cdr ind)))
15548 (if (>= i i2) (setq l (substring line i2)))
15549 (if (> i1 0)
15550 (concat (make-string i1 ?\ ) l)
15551 l)))
15553 (defun org-remove-indentation (code &optional n)
15554 "Remove the maximum common indentation from the lines in CODE.
15555 N may optionally be the number of spaces to remove."
15556 (with-temp-buffer
15557 (insert code)
15558 (org-do-remove-indentation n)
15559 (buffer-string)))
15561 (defun org-do-remove-indentation (&optional n)
15562 "Remove the maximum common indentation from the buffer."
15563 (untabify (point-min) (point-max))
15564 (let ((min 10000) re)
15565 (if n
15566 (setq min n)
15567 (goto-char (point-min))
15568 (while (re-search-forward "^ *[^ \n]" nil t)
15569 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
15570 (unless (or (= min 0) (= min 10000))
15571 (setq re (format "^ \\{%d\\}" min))
15572 (goto-char (point-min))
15573 (while (re-search-forward re nil t)
15574 (replace-match "")
15575 (end-of-line 1))
15576 min)))
15578 (defun org-base-buffer (buffer)
15579 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
15580 (if (not buffer)
15581 buffer
15582 (or (buffer-base-buffer buffer)
15583 buffer)))
15585 (defun org-trim (s)
15586 "Remove whitespace at beginning and end of string."
15587 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
15588 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
15591 (defun org-wrap (string &optional width lines)
15592 "Wrap string to either a number of lines, or a width in characters.
15593 If WIDTH is non-nil, the string is wrapped to that width, however many lines
15594 that costs. If there is a word longer than WIDTH, the text is actually
15595 wrapped to the length of that word.
15596 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
15597 many lines, whatever width that takes.
15598 The return value is a list of lines, without newlines at the end."
15599 (let* ((words (org-split-string string "[ \t\n]+"))
15600 (maxword (apply 'max (mapcar 'org-string-width words)))
15601 w ll)
15602 (cond (width
15603 (org-do-wrap words (max maxword width)))
15604 (lines
15605 (setq w maxword)
15606 (setq ll (org-do-wrap words maxword))
15607 (if (<= (length ll) lines)
15609 (setq ll words)
15610 (while (> (length ll) lines)
15611 (setq w (1+ w))
15612 (setq ll (org-do-wrap words w)))
15613 ll))
15614 (t (error "Cannot wrap this")))))
15616 (defun org-do-wrap (words width)
15617 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
15618 (let (lines line)
15619 (while words
15620 (setq line (pop words))
15621 (while (and words (< (+ (length line) (length (car words))) width))
15622 (setq line (concat line " " (pop words))))
15623 (setq lines (push line lines)))
15624 (nreverse lines)))
15626 (defun org-split-string (string &optional separators)
15627 "Splits STRING into substrings at SEPARATORS.
15628 No empty strings are returned if there are matches at the beginning
15629 and end of string."
15630 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
15631 (start 0)
15632 notfirst
15633 (list nil))
15634 (while (and (string-match rexp string
15635 (if (and notfirst
15636 (= start (match-beginning 0))
15637 (< start (length string)))
15638 (1+ start) start))
15639 (< (match-beginning 0) (length string)))
15640 (setq notfirst t)
15641 (or (eq (match-beginning 0) 0)
15642 (and (eq (match-beginning 0) (match-end 0))
15643 (eq (match-beginning 0) start))
15644 (setq list
15645 (cons (substring string start (match-beginning 0))
15646 list)))
15647 (setq start (match-end 0)))
15648 (or (eq start (length string))
15649 (setq list
15650 (cons (substring string start)
15651 list)))
15652 (nreverse list)))
15654 (defun org-quote-vert (s)
15655 "Replace \"|\" with \"\\vert\"."
15656 (while (string-match "|" s)
15657 (setq s (replace-match "\\vert" t t s)))
15660 (defun org-uuidgen-p (s)
15661 "Is S an ID created by UUIDGEN?"
15662 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
15664 (defun org-context ()
15665 "Return a list of contexts of the current cursor position.
15666 If several contexts apply, all are returned.
15667 Each context entry is a list with a symbol naming the context, and
15668 two positions indicating start and end of the context. Possible
15669 contexts are:
15671 :headline anywhere in a headline
15672 :headline-stars on the leading stars in a headline
15673 :todo-keyword on a TODO keyword (including DONE) in a headline
15674 :tags on the TAGS in a headline
15675 :priority on the priority cookie in a headline
15676 :item on the first line of a plain list item
15677 :item-bullet on the bullet/number of a plain list item
15678 :checkbox on the checkbox in a plain list item
15679 :table in an org-mode table
15680 :table-special on a special filed in a table
15681 :table-table in a table.el table
15682 :link on a hyperlink
15683 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
15684 :target on a <<target>>
15685 :radio-target on a <<<radio-target>>>
15686 :latex-fragment on a LaTeX fragment
15687 :latex-preview on a LaTeX fragment with overlayed preview image
15689 This function expects the position to be visible because it uses font-lock
15690 faces as a help to recognize the following contexts: :table-special, :link,
15691 and :keyword."
15692 (let* ((f (get-text-property (point) 'face))
15693 (faces (if (listp f) f (list f)))
15694 (p (point)) clist o)
15695 ;; First the large context
15696 (cond
15697 ((org-on-heading-p t)
15698 (push (list :headline (point-at-bol) (point-at-eol)) clist)
15699 (when (progn
15700 (beginning-of-line 1)
15701 (looking-at org-todo-line-tags-regexp))
15702 (push (org-point-in-group p 1 :headline-stars) clist)
15703 (push (org-point-in-group p 2 :todo-keyword) clist)
15704 (push (org-point-in-group p 4 :tags) clist))
15705 (goto-char p)
15706 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
15707 (if (looking-at "\\[#[A-Z0-9]\\]")
15708 (push (org-point-in-group p 0 :priority) clist)))
15710 ((org-at-item-p)
15711 (push (org-point-in-group p 2 :item-bullet) clist)
15712 (push (list :item (point-at-bol)
15713 (save-excursion (org-end-of-item) (point)))
15714 clist)
15715 (and (org-at-item-checkbox-p)
15716 (push (org-point-in-group p 0 :checkbox) clist)))
15718 ((org-at-table-p)
15719 (push (list :table (org-table-begin) (org-table-end)) clist)
15720 (if (memq 'org-formula faces)
15721 (push (list :table-special
15722 (previous-single-property-change p 'face)
15723 (next-single-property-change p 'face)) clist)))
15724 ((org-at-table-p 'any)
15725 (push (list :table-table) clist)))
15726 (goto-char p)
15728 ;; Now the small context
15729 (cond
15730 ((org-at-timestamp-p)
15731 (push (org-point-in-group p 0 :timestamp) clist))
15732 ((memq 'org-link faces)
15733 (push (list :link
15734 (previous-single-property-change p 'face)
15735 (next-single-property-change p 'face)) clist))
15736 ((memq 'org-special-keyword faces)
15737 (push (list :keyword
15738 (previous-single-property-change p 'face)
15739 (next-single-property-change p 'face)) clist))
15740 ((org-on-target-p)
15741 (push (org-point-in-group p 0 :target) clist)
15742 (goto-char (1- (match-beginning 0)))
15743 (if (looking-at org-radio-target-regexp)
15744 (push (org-point-in-group p 0 :radio-target) clist))
15745 (goto-char p))
15746 ((setq o (car (delq nil
15747 (mapcar
15748 (lambda (x)
15749 (if (memq x org-latex-fragment-image-overlays) x))
15750 (org-overlays-at (point))))))
15751 (push (list :latex-fragment
15752 (org-overlay-start o) (org-overlay-end o)) clist)
15753 (push (list :latex-preview
15754 (org-overlay-start o) (org-overlay-end o)) clist))
15755 ((org-inside-LaTeX-fragment-p)
15756 ;; FIXME: positions wrong.
15757 (push (list :latex-fragment (point) (point)) clist)))
15759 (setq clist (nreverse (delq nil clist)))
15760 clist))
15762 ;; FIXME: Compare with at-regexp-p Do we need both?
15763 (defun org-in-regexp (re &optional nlines visually)
15764 "Check if point is inside a match of regexp.
15765 Normally only the current line is checked, but you can include NLINES extra
15766 lines both before and after point into the search.
15767 If VISUALLY is set, require that the cursor is not after the match but
15768 really on, so that the block visually is on the match."
15769 (catch 'exit
15770 (let ((pos (point))
15771 (eol (point-at-eol (+ 1 (or nlines 0))))
15772 (inc (if visually 1 0)))
15773 (save-excursion
15774 (beginning-of-line (- 1 (or nlines 0)))
15775 (while (re-search-forward re eol t)
15776 (if (and (<= (match-beginning 0) pos)
15777 (>= (+ inc (match-end 0)) pos))
15778 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
15780 (defun org-at-regexp-p (regexp)
15781 "Is point inside a match of REGEXP in the current line?"
15782 (catch 'exit
15783 (save-excursion
15784 (let ((pos (point)) (end (point-at-eol)))
15785 (beginning-of-line 1)
15786 (while (re-search-forward regexp end t)
15787 (if (and (<= (match-beginning 0) pos)
15788 (>= (match-end 0) pos))
15789 (throw 'exit t)))
15790 nil))))
15792 (defun org-occur-in-agenda-files (regexp &optional nlines)
15793 "Call `multi-occur' with buffers for all agenda files."
15794 (interactive "sOrg-files matching: \np")
15795 (let* ((files (org-agenda-files))
15796 (tnames (mapcar 'file-truename files))
15797 (extra org-agenda-text-search-extra-files)
15799 (when (eq (car extra) 'agenda-archives)
15800 (setq extra (cdr extra))
15801 (setq files (org-add-archive-files files)))
15802 (while (setq f (pop extra))
15803 (unless (member (file-truename f) tnames)
15804 (add-to-list 'files f 'append)
15805 (add-to-list 'tnames (file-truename f) 'append)))
15806 (multi-occur
15807 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
15808 regexp)))
15810 (if (boundp 'occur-mode-find-occurrence-hook)
15811 ;; Emacs 23
15812 (add-hook 'occur-mode-find-occurrence-hook
15813 (lambda ()
15814 (when (org-mode-p)
15815 (org-reveal))))
15816 ;; Emacs 22
15817 (defadvice occur-mode-goto-occurrence
15818 (after org-occur-reveal activate)
15819 (and (org-mode-p) (org-reveal)))
15820 (defadvice occur-mode-goto-occurrence-other-window
15821 (after org-occur-reveal activate)
15822 (and (org-mode-p) (org-reveal)))
15823 (defadvice occur-mode-display-occurrence
15824 (after org-occur-reveal activate)
15825 (when (org-mode-p)
15826 (let ((pos (occur-mode-find-occurrence)))
15827 (with-current-buffer (marker-buffer pos)
15828 (save-excursion
15829 (goto-char pos)
15830 (org-reveal)))))))
15832 (defun org-occur-link-in-agenda-files ()
15833 "Create a link and search for it in the agendas.
15834 The link is not stored in `org-stored-links', it is just created
15835 for the search purpose."
15836 (interactive)
15837 (let ((link (condition-case nil
15838 (org-store-link nil)
15839 (error "Unable to create a link to here"))))
15840 (org-occur-in-agenda-files (regexp-quote link))))
15842 (defun org-uniquify (list)
15843 "Remove duplicate elements from LIST."
15844 (let (res)
15845 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
15846 res))
15848 (defun org-delete-all (elts list)
15849 "Remove all elements in ELTS from LIST."
15850 (while elts
15851 (setq list (delete (pop elts) list)))
15852 list)
15854 (defun org-back-over-empty-lines ()
15855 "Move backwards over whitespace, to the beginning of the first empty line.
15856 Returns the number of empty lines passed."
15857 (let ((pos (point)))
15858 (skip-chars-backward " \t\n\r")
15859 (beginning-of-line 2)
15860 (goto-char (min (point) pos))
15861 (count-lines (point) pos)))
15863 (defun org-skip-whitespace ()
15864 (skip-chars-forward " \t\n\r"))
15866 (defun org-point-in-group (point group &optional context)
15867 "Check if POINT is in match-group GROUP.
15868 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
15869 match. If the match group does ot exist or point is not inside it,
15870 return nil."
15871 (and (match-beginning group)
15872 (>= point (match-beginning group))
15873 (<= point (match-end group))
15874 (if context
15875 (list context (match-beginning group) (match-end group))
15876 t)))
15878 (defun org-switch-to-buffer-other-window (&rest args)
15879 "Switch to buffer in a second window on the current frame.
15880 In particular, do not allow pop-up frames."
15881 (let (pop-up-frames special-display-buffer-names special-display-regexps
15882 special-display-function)
15883 (apply 'switch-to-buffer-other-window args)))
15885 (defun org-combine-plists (&rest plists)
15886 "Create a single property list from all plists in PLISTS.
15887 The process starts by copying the first list, and then setting properties
15888 from the other lists. Settings in the last list are the most significant
15889 ones and overrule settings in the other lists."
15890 (let ((rtn (copy-sequence (pop plists)))
15891 p v ls)
15892 (while plists
15893 (setq ls (pop plists))
15894 (while ls
15895 (setq p (pop ls) v (pop ls))
15896 (setq rtn (plist-put rtn p v))))
15897 rtn))
15899 (defun org-move-line-down (arg)
15900 "Move the current line down. With prefix argument, move it past ARG lines."
15901 (interactive "p")
15902 (let ((col (current-column))
15903 beg end pos)
15904 (beginning-of-line 1) (setq beg (point))
15905 (beginning-of-line 2) (setq end (point))
15906 (beginning-of-line (+ 1 arg))
15907 (setq pos (move-marker (make-marker) (point)))
15908 (insert (delete-and-extract-region beg end))
15909 (goto-char pos)
15910 (org-move-to-column col)))
15912 (defun org-move-line-up (arg)
15913 "Move the current line up. With prefix argument, move it past ARG lines."
15914 (interactive "p")
15915 (let ((col (current-column))
15916 beg end pos)
15917 (beginning-of-line 1) (setq beg (point))
15918 (beginning-of-line 2) (setq end (point))
15919 (beginning-of-line (- arg))
15920 (setq pos (move-marker (make-marker) (point)))
15921 (insert (delete-and-extract-region beg end))
15922 (goto-char pos)
15923 (org-move-to-column col)))
15925 (defun org-replace-escapes (string table)
15926 "Replace %-escapes in STRING with values in TABLE.
15927 TABLE is an association list with keys like \"%a\" and string values.
15928 The sequences in STRING may contain normal field width and padding information,
15929 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
15930 so values can contain further %-escapes if they are define later in TABLE."
15931 (let ((case-fold-search nil)
15932 e re rpl)
15933 (while (setq e (pop table))
15934 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
15935 (while (string-match re string)
15936 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
15937 (cdr e)))
15938 (setq string (replace-match rpl t t string))))
15939 string))
15942 (defun org-sublist (list start end)
15943 "Return a section of LIST, from START to END.
15944 Counting starts at 1."
15945 (let (rtn (c start))
15946 (setq list (nthcdr (1- start) list))
15947 (while (and list (<= c end))
15948 (push (pop list) rtn)
15949 (setq c (1+ c)))
15950 (nreverse rtn)))
15952 (defun org-find-base-buffer-visiting (file)
15953 "Like `find-buffer-visiting' but always return the base buffer and
15954 not an indirect buffer."
15955 (let ((buf (or (get-file-buffer file)
15956 (find-buffer-visiting file))))
15957 (if buf
15958 (or (buffer-base-buffer buf) buf)
15959 nil)))
15961 (defun org-image-file-name-regexp (&optional extensions)
15962 "Return regexp matching the file names of images.
15963 If EXTENSIONS is given, only match these."
15964 (if (and (not extensions) (fboundp 'image-file-name-regexp))
15965 (image-file-name-regexp)
15966 (let ((image-file-name-extensions
15967 (or extensions
15968 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
15969 "xbm" "xpm" "pbm" "pgm" "ppm"))))
15970 (concat "\\."
15971 (regexp-opt (nconc (mapcar 'upcase
15972 image-file-name-extensions)
15973 image-file-name-extensions)
15975 "\\'"))))
15977 (defun org-file-image-p (file &optional extensions)
15978 "Return non-nil if FILE is an image."
15979 (save-match-data
15980 (string-match (org-image-file-name-regexp extensions) file)))
15982 (defun org-get-cursor-date ()
15983 "Return the date at cursor in as a time.
15984 This works in the calendar and in the agenda, anywhere else it just
15985 returns the current time."
15986 (let (date day defd)
15987 (cond
15988 ((eq major-mode 'calendar-mode)
15989 (setq date (calendar-cursor-to-date)
15990 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15991 ((eq major-mode 'org-agenda-mode)
15992 (setq day (get-text-property (point) 'day))
15993 (if day
15994 (setq date (calendar-gregorian-from-absolute day)
15995 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
15996 (nth 2 date))))))
15997 (or defd (current-time))))
15999 (defvar org-agenda-action-marker (make-marker)
16000 "Marker pointing to the entry for the next agenda action.")
16002 (defun org-mark-entry-for-agenda-action ()
16003 "Mark the current entry as target of an agenda action.
16004 Agenda actions are actions executed from the agenda with the key `k',
16005 which make use of the date at the cursor."
16006 (interactive)
16007 (move-marker org-agenda-action-marker
16008 (save-excursion (org-back-to-heading t) (point))
16009 (current-buffer))
16010 (message
16011 "Entry marked for action; press `k' at desired date in agenda or calendar"))
16013 ;;; Paragraph filling stuff.
16014 ;; We want this to be just right, so use the full arsenal.
16016 (defun org-indent-line-function ()
16017 "Indent line like previous, but further if previous was headline or item."
16018 (interactive)
16019 (let* ((pos (point))
16020 (itemp (org-at-item-p))
16021 (case-fold-search t)
16022 (org-drawer-regexp (or org-drawer-regexp "\000"))
16023 column bpos bcol tpos tcol bullet btype bullet-type)
16024 ;; Find the previous relevant line
16025 (beginning-of-line 1)
16026 (cond
16027 ((looking-at "#") (setq column 0))
16028 ((looking-at "\\*+ ") (setq column 0))
16029 ((and (looking-at "[ \t]*:END:")
16030 (save-excursion (re-search-backward org-drawer-regexp nil t)))
16031 (save-excursion
16032 (goto-char (1- (match-beginning 1)))
16033 (setq column (current-column))))
16034 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
16035 (save-excursion
16036 (re-search-backward
16037 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
16038 (setq column (org-get-indentation (match-string 0))))
16040 (beginning-of-line 0)
16041 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
16042 (not (looking-at "[ \t]*:END:"))
16043 (not (looking-at org-drawer-regexp)))
16044 (beginning-of-line 0))
16045 (cond
16046 ((looking-at "\\*+[ \t]+")
16047 (if (not org-adapt-indentation)
16048 (setq column 0)
16049 (goto-char (match-end 0))
16050 (setq column (current-column))))
16051 ((looking-at org-drawer-regexp)
16052 (goto-char (1- (match-beginning 1)))
16053 (setq column (current-column)))
16054 ((looking-at "\\([ \t]*\\):END:")
16055 (goto-char (match-end 1))
16056 (setq column (current-column)))
16057 ((org-in-item-p)
16058 (org-beginning-of-item)
16059 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
16060 (setq bpos (match-beginning 1) tpos (match-end 0)
16061 bcol (progn (goto-char bpos) (current-column))
16062 tcol (progn (goto-char tpos) (current-column))
16063 bullet (match-string 1)
16064 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
16065 (if (> tcol (+ bcol org-description-max-indent))
16066 (setq tcol (+ bcol 5)))
16067 (if (not itemp)
16068 (setq column tcol)
16069 (goto-char pos)
16070 (beginning-of-line 1)
16071 (if (looking-at "\\S-")
16072 (progn
16073 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
16074 (setq bullet (match-string 1)
16075 btype (if (string-match "[0-9]" bullet) "n" bullet))
16076 (setq column (if (equal btype bullet-type) bcol tcol)))
16077 (setq column (org-get-indentation)))))
16078 (t (setq column (org-get-indentation))))))
16079 (goto-char pos)
16080 (if (<= (current-column) (current-indentation))
16081 (org-indent-line-to column)
16082 (save-excursion (org-indent-line-to column)))
16083 (setq column (current-column))
16084 (beginning-of-line 1)
16085 (if (looking-at
16086 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
16087 (replace-match (concat "\\1" (format org-property-format
16088 (match-string 2) (match-string 3)))
16089 t nil))
16090 (org-move-to-column column)))
16092 (defun org-set-autofill-regexps ()
16093 (interactive)
16094 ;; In the paragraph separator we include headlines, because filling
16095 ;; text in a line directly attached to a headline would otherwise
16096 ;; fill the headline as well.
16097 (org-set-local 'comment-start-skip "^#+[ \t]*")
16098 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
16099 ;; The paragraph starter includes hand-formatted lists.
16100 (org-set-local
16101 'paragraph-start
16102 (concat
16103 "\f" "\\|"
16104 "[ ]*$" "\\|"
16105 "\\*+ " "\\|"
16106 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
16107 "[ \t]*[:|]" "\\|"
16108 "\\$\\$" "\\|"
16109 "\\\\\\(begin\\|end\\|[][]\\)"))
16110 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
16111 ;; But only if the user has not turned off tables or fixed-width regions
16112 (org-set-local
16113 'auto-fill-inhibit-regexp
16114 (concat "\\*+ \\|#\\+"
16115 "\\|[ \t]*" org-keyword-time-regexp
16116 (if (or org-enable-table-editor org-enable-fixed-width-editor)
16117 (concat
16118 "\\|[ \t]*["
16119 (if org-enable-table-editor "|" "")
16120 (if org-enable-fixed-width-editor ":" "")
16121 "]"))))
16122 ;; We use our own fill-paragraph function, to make sure that tables
16123 ;; and fixed-width regions are not wrapped. That function will pass
16124 ;; through to `fill-paragraph' when appropriate.
16125 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
16126 ; Adaptive filling: To get full control, first make sure that
16127 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
16128 (org-set-local 'adaptive-fill-regexp "\000")
16129 (org-set-local 'adaptive-fill-function
16130 'org-adaptive-fill-function)
16131 (org-set-local
16132 'align-mode-rules-list
16133 '((org-in-buffer-settings
16134 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
16135 (modes . '(org-mode))))))
16137 (defun org-fill-paragraph (&optional justify)
16138 "Re-align a table, pass through to fill-paragraph if no table."
16139 (let ((table-p (org-at-table-p))
16140 (table.el-p (org-at-table.el-p)))
16141 (cond ((and (equal (char-after (point-at-bol)) ?*)
16142 (save-excursion (goto-char (point-at-bol))
16143 (looking-at outline-regexp)))
16144 t) ; skip headlines
16145 (table.el-p t) ; skip table.el tables
16146 (table-p (org-table-align) t) ; align org-mode tables
16147 (t nil)))) ; call paragraph-fill
16149 ;; For reference, this is the default value of adaptive-fill-regexp
16150 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
16152 (defun org-adaptive-fill-function ()
16153 "Return a fill prefix for org-mode files.
16154 In particular, this makes sure hanging paragraphs for hand-formatted lists
16155 work correctly."
16156 (cond ((looking-at "#[ \t]+")
16157 (match-string 0))
16158 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
16159 (save-excursion
16160 (if (> (match-end 1) (+ (match-beginning 1)
16161 org-description-max-indent))
16162 (goto-char (+ (match-beginning 1) 5))
16163 (goto-char (match-end 0)))
16164 (make-string (current-column) ?\ )))
16165 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
16166 (save-excursion
16167 (goto-char (match-end 0))
16168 (make-string (current-column) ?\ )))
16169 (t nil)))
16171 ;;; Other stuff.
16173 (defun org-toggle-fixed-width-section (arg)
16174 "Toggle the fixed-width export.
16175 If there is no active region, the QUOTE keyword at the current headline is
16176 inserted or removed. When present, it causes the text between this headline
16177 and the next to be exported as fixed-width text, and unmodified.
16178 If there is an active region, this command adds or removes a colon as the
16179 first character of this line. If the first character of a line is a colon,
16180 this line is also exported in fixed-width font."
16181 (interactive "P")
16182 (let* ((cc 0)
16183 (regionp (org-region-active-p))
16184 (beg (if regionp (region-beginning) (point)))
16185 (end (if regionp (region-end)))
16186 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
16187 (case-fold-search nil)
16188 (re "[ \t]*\\(: \\)")
16189 off)
16190 (if regionp
16191 (save-excursion
16192 (goto-char beg)
16193 (setq cc (current-column))
16194 (beginning-of-line 1)
16195 (setq off (looking-at re))
16196 (while (> nlines 0)
16197 (setq nlines (1- nlines))
16198 (beginning-of-line 1)
16199 (cond
16200 (arg
16201 (org-move-to-column cc t)
16202 (insert ": \n")
16203 (forward-line -1))
16204 ((and off (looking-at re))
16205 (replace-match "" t t nil 1))
16206 ((not off) (org-move-to-column cc t) (insert ": ")))
16207 (forward-line 1)))
16208 (save-excursion
16209 (org-back-to-heading)
16210 (if (looking-at (concat outline-regexp
16211 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
16212 (replace-match "" t t nil 1)
16213 (if (looking-at outline-regexp)
16214 (progn
16215 (goto-char (match-end 0))
16216 (insert org-quote-string " "))))))))
16218 (defun org-reftex-citation ()
16219 "Use reftex-citation to insert a citation into the buffer.
16220 This looks for a line like
16222 #+BIBLIOGRAPHY: foo plain option:-d
16224 and derives from it that foo.bib is the bbliography file relevant
16225 for this document. It then installs the necessary environment for RefTeX
16226 to work in this buffer and calls `reftex-citation' to insert a citation
16227 into the buffer.
16229 Export of such citations to both LaTeX and HTML is handled by the contributed
16230 package org-exp-bibtex by Taru Karttunen."
16231 (interactive)
16232 (let ((reftex-docstruct-symbol 'rds)
16233 (reftex-cite-format "\\cite{%l}")
16234 rds bib)
16235 (save-excursion
16236 (save-restriction
16237 (widen)
16238 (let ((case-fold-search t)
16239 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
16240 (if (not (save-excursion
16241 (or (re-search-forward re nil t)
16242 (re-search-backward re nil t))))
16243 (error "No bibliography defined in file")
16244 (setq bib (concat (match-string 1) ".bib")
16245 rds (list (list 'bib bib)))))))
16246 (call-interactively 'reftex-citation)))
16248 ;;;; Functions extending outline functionality
16250 (defun org-beginning-of-line (&optional arg)
16251 "Go to the beginning of the current line. If that is invisible, continue
16252 to a visible line beginning. This makes the function of C-a more intuitive.
16253 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16254 first attempt, and only move to after the tags when the cursor is already
16255 beyond the end of the headline."
16256 (interactive "P")
16257 (let ((pos (point))
16258 (special (if (consp org-special-ctrl-a/e)
16259 (car org-special-ctrl-a/e)
16260 org-special-ctrl-a/e))
16261 refpos)
16262 (if (org-bound-and-true-p line-move-visual)
16263 (beginning-of-visual-line 1)
16264 (beginning-of-line 1))
16265 (if (and arg (fboundp 'move-beginning-of-line))
16266 (call-interactively 'move-beginning-of-line)
16267 (if (bobp)
16269 (backward-char 1)
16270 (if (org-invisible-p)
16271 (while (and (not (bobp)) (org-invisible-p))
16272 (backward-char 1)
16273 (beginning-of-line 1))
16274 (forward-char 1))))
16275 (when special
16276 (cond
16277 ((and (looking-at org-complex-heading-regexp)
16278 (= (char-after (match-end 1)) ?\ ))
16279 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
16280 (point-at-eol)))
16281 (goto-char
16282 (if (eq special t)
16283 (cond ((> pos refpos) refpos)
16284 ((= pos (point)) refpos)
16285 (t (point)))
16286 (cond ((> pos (point)) (point))
16287 ((not (eq last-command this-command)) (point))
16288 (t refpos)))))
16289 ((org-at-item-p)
16290 (goto-char
16291 (if (eq special t)
16292 (cond ((> pos (match-end 4)) (match-end 4))
16293 ((= pos (point)) (match-end 4))
16294 (t (point)))
16295 (cond ((> pos (point)) (point))
16296 ((not (eq last-command this-command)) (point))
16297 (t (match-end 4))))))))
16298 (org-no-warnings
16299 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16301 (defun org-end-of-line (&optional arg)
16302 "Go to the end of the line.
16303 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16304 first attempt, and only move to after the tags when the cursor is already
16305 beyond the end of the headline."
16306 (interactive "P")
16307 (let ((special (if (consp org-special-ctrl-a/e)
16308 (cdr org-special-ctrl-a/e)
16309 org-special-ctrl-a/e)))
16310 (if (or (not special)
16311 (not (org-on-heading-p))
16312 arg)
16313 (call-interactively
16314 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
16315 ((fboundp 'move-end-of-line) 'move-end-of-line)
16316 (t 'end-of-line)))
16317 (let ((pos (point)))
16318 (beginning-of-line 1)
16319 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
16320 (if (eq special t)
16321 (if (or (< pos (match-beginning 1))
16322 (= pos (match-end 0)))
16323 (goto-char (match-beginning 1))
16324 (goto-char (match-end 0)))
16325 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
16326 (goto-char (match-end 0))
16327 (goto-char (match-beginning 1))))
16328 (call-interactively (if (fboundp 'move-end-of-line)
16329 'move-end-of-line
16330 'end-of-line)))))
16331 (org-no-warnings
16332 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16334 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
16335 (define-key org-mode-map "\C-e" 'org-end-of-line)
16337 (defun org-backward-sentence (&optional arg)
16338 "Go to beginning of sentence, or beginning of table field.
16339 This will call `backward-sentence' or `org-table-beginning-of-field',
16340 depending on context."
16341 (interactive "P")
16342 (cond
16343 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
16344 (t (call-interactively 'backward-sentence))))
16346 (defun org-forward-sentence (&optional arg)
16347 "Go to end of sentence, or end of table field.
16348 This will call `forward-sentence' or `org-table-end-of-field',
16349 depending on context."
16350 (interactive "P")
16351 (cond
16352 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
16353 (t (call-interactively 'forward-sentence))))
16355 (define-key org-mode-map "\M-a" 'org-backward-sentence)
16356 (define-key org-mode-map "\M-e" 'org-forward-sentence)
16358 (defun org-kill-line (&optional arg)
16359 "Kill line, to tags or end of line."
16360 (interactive "P")
16361 (cond
16362 ((or (not org-special-ctrl-k)
16363 (bolp)
16364 (not (org-on-heading-p)))
16365 (call-interactively 'kill-line))
16366 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
16367 (kill-region (point) (match-beginning 1))
16368 (org-set-tags nil t))
16369 (t (kill-region (point) (point-at-eol)))))
16371 (define-key org-mode-map "\C-k" 'org-kill-line)
16373 (defun org-yank (&optional arg)
16374 "Yank. If the kill is a subtree, treat it specially.
16375 This command will look at the current kill and check if is a single
16376 subtree, or a series of subtrees[1]. If it passes the test, and if the
16377 cursor is at the beginning of a line or after the stars of a currently
16378 empty headline, then the yank is handled specially. How exactly depends
16379 on the value of the following variables, both set by default.
16381 org-yank-folded-subtrees
16382 When set, the subtree(s) will be folded after insertion, but only
16383 if doing so would now swallow text after the yanked text.
16385 org-yank-adjusted-subtrees
16386 When set, the subtree will be promoted or demoted in order to
16387 fit into the local outline tree structure, which means that the level
16388 will be adjusted so that it becomes the smaller one of the two
16389 *visible* surrounding headings.
16391 Any prefix to this command will cause `yank' to be called directly with
16392 no special treatment. In particular, a simple `C-u' prefix will just
16393 plainly yank the text as it is.
16395 \[1] The test checks if the first non-white line is a heading
16396 and if there are no other headings with fewer stars."
16397 (interactive "P")
16398 (org-yank-generic 'yank arg))
16400 (defun org-yank-generic (command arg)
16401 "Perform some yank-like command.
16403 This function implements the behavior described in the `org-yank'
16404 documentation. However, it has been generalized to work for any
16405 interactive command with similar behavior."
16407 ;; pretend to be command COMMAND
16408 (setq this-command command)
16410 (if arg
16411 (call-interactively command)
16413 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
16414 (and (org-kill-is-subtree-p)
16415 (or (bolp)
16416 (and (looking-at "[ \t]*$")
16417 (string-match
16418 "\\`\\*+\\'"
16419 (buffer-substring (point-at-bol) (point)))))))
16420 swallowp)
16421 (cond
16422 ((and subtreep org-yank-folded-subtrees)
16423 (let ((beg (point))
16424 end)
16425 (if (and subtreep org-yank-adjusted-subtrees)
16426 (org-paste-subtree nil nil 'for-yank)
16427 (call-interactively command))
16429 (setq end (point))
16430 (goto-char beg)
16431 (when (and (bolp) subtreep
16432 (not (setq swallowp
16433 (org-yank-folding-would-swallow-text beg end))))
16434 (or (looking-at outline-regexp)
16435 (re-search-forward (concat "^" outline-regexp) end t))
16436 (while (and (< (point) end) (looking-at outline-regexp))
16437 (hide-subtree)
16438 (org-cycle-show-empty-lines 'folded)
16439 (condition-case nil
16440 (outline-forward-same-level 1)
16441 (error (goto-char end)))))
16442 (when swallowp
16443 (message
16444 "Inserted text not folded because that would swallow text"))
16446 (goto-char end)
16447 (skip-chars-forward " \t\n\r")
16448 (beginning-of-line 1)
16449 (push-mark beg 'nomsg)))
16450 ((and subtreep org-yank-adjusted-subtrees)
16451 (let ((beg (point-at-bol)))
16452 (org-paste-subtree nil nil 'for-yank)
16453 (push-mark beg 'nomsg)))
16455 (call-interactively command))))))
16457 (defun org-yank-folding-would-swallow-text (beg end)
16458 "Would hide-subtree at BEG swallow any text after END?"
16459 (let (level)
16460 (save-excursion
16461 (goto-char beg)
16462 (when (or (looking-at outline-regexp)
16463 (re-search-forward (concat "^" outline-regexp) end t))
16464 (setq level (org-outline-level)))
16465 (goto-char end)
16466 (skip-chars-forward " \t\r\n\v\f")
16467 (if (or (eobp)
16468 (and (bolp) (looking-at org-outline-regexp)
16469 (<= (org-outline-level) level)))
16470 nil ; Nothing would be swallowed
16471 t)))) ; something would swallow
16473 (define-key org-mode-map "\C-y" 'org-yank)
16475 (defun org-invisible-p ()
16476 "Check if point is at a character currently not visible."
16477 ;; Early versions of noutline don't have `outline-invisible-p'.
16478 (if (fboundp 'outline-invisible-p)
16479 (outline-invisible-p)
16480 (get-char-property (point) 'invisible)))
16482 (defun org-invisible-p2 ()
16483 "Check if point is at a character currently not visible."
16484 (save-excursion
16485 (if (and (eolp) (not (bobp))) (backward-char 1))
16486 ;; Early versions of noutline don't have `outline-invisible-p'.
16487 (if (fboundp 'outline-invisible-p)
16488 (outline-invisible-p)
16489 (get-char-property (point) 'invisible))))
16491 (defun org-back-to-heading (&optional invisible-ok)
16492 "Call `outline-back-to-heading', but provide a better error message."
16493 (condition-case nil
16494 (outline-back-to-heading invisible-ok)
16495 (error (error "Before first headline at position %d in buffer %s"
16496 (point) (current-buffer)))))
16498 (defun org-before-first-heading-p ()
16499 "Before first heading?"
16500 (save-excursion
16501 (null (re-search-backward "^\\*+ " nil t))))
16503 (defalias 'org-on-heading-p 'outline-on-heading-p)
16504 (defalias 'org-at-heading-p 'outline-on-heading-p)
16505 (defun org-at-heading-or-item-p ()
16506 (or (org-on-heading-p) (org-at-item-p)))
16508 (defun org-on-target-p ()
16509 (or (org-in-regexp org-radio-target-regexp)
16510 (org-in-regexp org-target-regexp)))
16512 (defun org-up-heading-all (arg)
16513 "Move to the heading line of which the present line is a subheading.
16514 This function considers both visible and invisible heading lines.
16515 With argument, move up ARG levels."
16516 (if (fboundp 'outline-up-heading-all)
16517 (outline-up-heading-all arg) ; emacs 21 version of outline.el
16518 (outline-up-heading arg t))) ; emacs 22 version of outline.el
16520 (defun org-up-heading-safe ()
16521 "Move to the heading line of which the present line is a subheading.
16522 This version will not throw an error. It will return the level of the
16523 headline found, or nil if no higher level is found.
16525 Also, this function will be a lot faster than `outline-up-heading',
16526 because it relies on stars being the outline starters. This can really
16527 make a significant difference in outlines with very many siblings."
16528 (let (start-level re)
16529 (org-back-to-heading t)
16530 (setq start-level (funcall outline-level))
16531 (if (equal start-level 1)
16533 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
16534 (if (re-search-backward re nil t)
16535 (funcall outline-level)))))
16537 (defun org-first-sibling-p ()
16538 "Is this heading the first child of its parents?"
16539 (interactive)
16540 (let ((re (concat "^" outline-regexp))
16541 level l)
16542 (unless (org-at-heading-p t)
16543 (error "Not at a heading"))
16544 (setq level (funcall outline-level))
16545 (save-excursion
16546 (if (not (re-search-backward re nil t))
16548 (setq l (funcall outline-level))
16549 (< l level)))))
16551 (defun org-goto-sibling (&optional previous)
16552 "Goto the next sibling, even if it is invisible.
16553 When PREVIOUS is set, go to the previous sibling instead. Returns t
16554 when a sibling was found. When none is found, return nil and don't
16555 move point."
16556 (let ((fun (if previous 're-search-backward 're-search-forward))
16557 (pos (point))
16558 (re (concat "^" outline-regexp))
16559 level l)
16560 (when (condition-case nil (org-back-to-heading t) (error nil))
16561 (setq level (funcall outline-level))
16562 (catch 'exit
16563 (or previous (forward-char 1))
16564 (while (funcall fun re nil t)
16565 (setq l (funcall outline-level))
16566 (when (< l level) (goto-char pos) (throw 'exit nil))
16567 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
16568 (goto-char pos)
16569 nil))))
16571 (defun org-show-siblings ()
16572 "Show all siblings of the current headline."
16573 (save-excursion
16574 (while (org-goto-sibling) (org-flag-heading nil)))
16575 (save-excursion
16576 (while (org-goto-sibling 'previous)
16577 (org-flag-heading nil))))
16579 (defun org-show-hidden-entry ()
16580 "Show an entry where even the heading is hidden."
16581 (save-excursion
16582 (org-show-entry)))
16584 (defun org-flag-heading (flag &optional entry)
16585 "Flag the current heading. FLAG non-nil means make invisible.
16586 When ENTRY is non-nil, show the entire entry."
16587 (save-excursion
16588 (org-back-to-heading t)
16589 ;; Check if we should show the entire entry
16590 (if entry
16591 (progn
16592 (org-show-entry)
16593 (save-excursion
16594 (and (outline-next-heading)
16595 (org-flag-heading nil))))
16596 (outline-flag-region (max (point-min) (1- (point)))
16597 (save-excursion (outline-end-of-heading) (point))
16598 flag))))
16600 (defun org-get-next-sibling ()
16601 "Move to next heading of the same level, and return point.
16602 If there is no such heading, return nil.
16603 This is like outline-next-sibling, but invisible headings are ok."
16604 (let ((level (funcall outline-level)))
16605 (outline-next-heading)
16606 (while (and (not (eobp)) (> (funcall outline-level) level))
16607 (outline-next-heading))
16608 (if (or (eobp) (< (funcall outline-level) level))
16610 (point))))
16612 (defun org-end-of-subtree (&optional invisible-OK to-heading)
16613 ;; This contains an exact copy of the original function, but it uses
16614 ;; `org-back-to-heading', to make it work also in invisible
16615 ;; trees. And is uses an invisible-OK argument.
16616 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
16617 ;; Furthermore, when used inside Org, finding the end of a large subtree
16618 ;; with many children and grandchildren etc, this can be much faster
16619 ;; than the outline version.
16620 (org-back-to-heading invisible-OK)
16621 (let ((first t)
16622 (level (funcall outline-level)))
16623 (if (and (org-mode-p) (< level 1000))
16624 ;; A true heading (not a plain list item), in Org-mode
16625 ;; This means we can easily find the end by looking
16626 ;; only for the right number of stars. Using a regexp to do
16627 ;; this is so much faster than using a Lisp loop.
16628 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
16629 (forward-char 1)
16630 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
16631 ;; something else, do it the slow way
16632 (while (and (not (eobp))
16633 (or first (> (funcall outline-level) level)))
16634 (setq first nil)
16635 (outline-next-heading)))
16636 (unless to-heading
16637 (if (memq (preceding-char) '(?\n ?\^M))
16638 (progn
16639 ;; Go to end of line before heading
16640 (forward-char -1)
16641 (if (memq (preceding-char) '(?\n ?\^M))
16642 ;; leave blank line before heading
16643 (forward-char -1))))))
16644 (point))
16646 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
16647 "Use Org version in org-mode, for dramatic speed-up."
16648 (if (eq major-mode 'org-mode)
16649 (progn
16650 (org-end-of-subtree nil t)
16651 (backward-char 1))
16652 ad-do-it))
16654 (defun org-forward-same-level (arg &optional invisible-ok)
16655 "Move forward to the arg'th subheading at same level as this one.
16656 Stop at the first and last subheadings of a superior heading."
16657 (interactive "p")
16658 (org-back-to-heading invisible-ok)
16659 (org-on-heading-p)
16660 (let* ((level (- (match-end 0) (match-beginning 0) 1))
16661 (re (format "^\\*\\{1,%d\\} " level))
16663 (forward-char 1)
16664 (while (> arg 0)
16665 (while (and (re-search-forward re nil 'move)
16666 (setq l (- (match-end 0) (match-beginning 0) 1))
16667 (= l level)
16668 (not invisible-ok)
16669 (org-invisible-p))
16670 (if (< l level) (setq arg 1)))
16671 (setq arg (1- arg)))
16672 (beginning-of-line 1)))
16674 (defun org-backward-same-level (arg &optional invisible-ok)
16675 "Move backward to the arg'th subheading at same level as this one.
16676 Stop at the first and last subheadings of a superior heading."
16677 (interactive "p")
16678 (org-back-to-heading)
16679 (org-on-heading-p)
16680 (let* ((level (- (match-end 0) (match-beginning 0) 1))
16681 (re (format "^\\*\\{1,%d\\} " level))
16683 (while (> arg 0)
16684 (while (and (re-search-backward re nil 'move)
16685 (setq l (- (match-end 0) (match-beginning 0) 1))
16686 (= l level)
16687 (not invisible-ok)
16688 (org-invisible-p))
16689 (if (< l level) (setq arg 1)))
16690 (setq arg (1- arg)))))
16692 (defun org-show-subtree ()
16693 "Show everything after this heading at deeper levels."
16694 (outline-flag-region
16695 (point)
16696 (save-excursion
16697 (outline-end-of-subtree) (outline-next-heading) (point))
16698 nil))
16700 (defun org-show-entry ()
16701 "Show the body directly following this heading.
16702 Show the heading too, if it is currently invisible."
16703 (interactive)
16704 (save-excursion
16705 (condition-case nil
16706 (progn
16707 (org-back-to-heading t)
16708 (outline-flag-region
16709 (max (point-min) (1- (point)))
16710 (save-excursion
16711 (if (re-search-forward
16712 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
16713 (match-beginning 1)
16714 (point-max)))
16715 nil)
16716 (org-cycle-hide-drawers 'children))
16717 (error nil))))
16719 (defun org-make-options-regexp (kwds &optional extra)
16720 "Make a regular expression for keyword lines."
16721 (concat
16723 "#?[ \t]*\\+\\("
16724 (mapconcat 'regexp-quote kwds "\\|")
16725 (if extra (concat "\\|" extra))
16726 "\\):[ \t]*"
16727 "\\(.*\\)"))
16729 ;; Make isearch reveal the necessary context
16730 (defun org-isearch-end ()
16731 "Reveal context after isearch exits."
16732 (when isearch-success ; only if search was successful
16733 (if (featurep 'xemacs)
16734 ;; Under XEmacs, the hook is run in the correct place,
16735 ;; we directly show the context.
16736 (org-show-context 'isearch)
16737 ;; In Emacs the hook runs *before* restoring the overlays.
16738 ;; So we have to use a one-time post-command-hook to do this.
16739 ;; (Emacs 22 has a special variable, see function `org-mode')
16740 (unless (and (boundp 'isearch-mode-end-hook-quit)
16741 isearch-mode-end-hook-quit)
16742 ;; Only when the isearch was not quitted.
16743 (org-add-hook 'post-command-hook 'org-isearch-post-command
16744 'append 'local)))))
16746 (defun org-isearch-post-command ()
16747 "Remove self from hook, and show context."
16748 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
16749 (org-show-context 'isearch))
16752 ;;;; Integration with and fixes for other packages
16754 ;;; Imenu support
16756 (defvar org-imenu-markers nil
16757 "All markers currently used by Imenu.")
16758 (make-variable-buffer-local 'org-imenu-markers)
16760 (defun org-imenu-new-marker (&optional pos)
16761 "Return a new marker for use by Imenu, and remember the marker."
16762 (let ((m (make-marker)))
16763 (move-marker m (or pos (point)))
16764 (push m org-imenu-markers)
16767 (defun org-imenu-get-tree ()
16768 "Produce the index for Imenu."
16769 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
16770 (setq org-imenu-markers nil)
16771 (let* ((n org-imenu-depth)
16772 (re (concat "^" outline-regexp))
16773 (subs (make-vector (1+ n) nil))
16774 (last-level 0)
16775 m level head)
16776 (save-excursion
16777 (save-restriction
16778 (widen)
16779 (goto-char (point-max))
16780 (while (re-search-backward re nil t)
16781 (setq level (org-reduced-level (funcall outline-level)))
16782 (when (<= level n)
16783 (looking-at org-complex-heading-regexp)
16784 (setq head (org-link-display-format
16785 (org-match-string-no-properties 4))
16786 m (org-imenu-new-marker))
16787 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
16788 (if (>= level last-level)
16789 (push (cons head m) (aref subs level))
16790 (push (cons head (aref subs (1+ level))) (aref subs level))
16791 (loop for i from (1+ level) to n do (aset subs i nil)))
16792 (setq last-level level)))))
16793 (aref subs 1)))
16795 (eval-after-load "imenu"
16796 '(progn
16797 (add-hook 'imenu-after-jump-hook
16798 (lambda ()
16799 (if (eq major-mode 'org-mode)
16800 (org-show-context 'org-goto))))))
16802 (defun org-link-display-format (link)
16803 "Replace a link with either the description, or the link target
16804 if no description is present"
16805 (save-match-data
16806 (if (string-match org-bracket-link-analytic-regexp link)
16807 (replace-match (or (match-string 5 link)
16808 (concat (match-string 1 link)
16809 (match-string 3 link)))
16810 nil nil link)
16811 link)))
16813 ;; Speedbar support
16815 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
16816 "Overlay marking the agenda restriction line in speedbar.")
16817 (org-overlay-put org-speedbar-restriction-lock-overlay
16818 'face 'org-agenda-restriction-lock)
16819 (org-overlay-put org-speedbar-restriction-lock-overlay
16820 'help-echo "Agendas are currently limited to this item.")
16821 (org-detach-overlay org-speedbar-restriction-lock-overlay)
16823 (defun org-speedbar-set-agenda-restriction ()
16824 "Restrict future agenda commands to the location at point in speedbar.
16825 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
16826 (interactive)
16827 (require 'org-agenda)
16828 (let (p m tp np dir txt)
16829 (cond
16830 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16831 'org-imenu t))
16832 (setq m (get-text-property p 'org-imenu-marker))
16833 (save-excursion
16834 (save-restriction
16835 (set-buffer (marker-buffer m))
16836 (goto-char m)
16837 (org-agenda-set-restriction-lock 'subtree))))
16838 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16839 'speedbar-function 'speedbar-find-file))
16840 (setq tp (previous-single-property-change
16841 (1+ p) 'speedbar-function)
16842 np (next-single-property-change
16843 tp 'speedbar-function)
16844 dir (speedbar-line-directory)
16845 txt (buffer-substring-no-properties (or tp (point-min))
16846 (or np (point-max))))
16847 (save-excursion
16848 (save-restriction
16849 (set-buffer (find-file-noselect
16850 (let ((default-directory dir))
16851 (expand-file-name txt))))
16852 (unless (org-mode-p)
16853 (error "Cannot restrict to non-Org-mode file"))
16854 (org-agenda-set-restriction-lock 'file))))
16855 (t (error "Don't know how to restrict Org-mode's agenda")))
16856 (org-move-overlay org-speedbar-restriction-lock-overlay
16857 (point-at-bol) (point-at-eol))
16858 (setq current-prefix-arg nil)
16859 (org-agenda-maybe-redo)))
16861 (eval-after-load "speedbar"
16862 '(progn
16863 (speedbar-add-supported-extension ".org")
16864 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
16865 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
16866 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
16867 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16868 (add-hook 'speedbar-visiting-tag-hook
16869 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
16872 ;;; Fixes and Hacks for problems with other packages
16874 ;; Make flyspell not check words in links, to not mess up our keymap
16875 (defun org-mode-flyspell-verify ()
16876 "Don't let flyspell put overlays at active buttons."
16877 (and (not (get-text-property (point) 'keymap))
16878 (not (get-text-property (point) 'org-no-flyspell))))
16880 (defun org-remove-flyspell-overlays-in (beg end)
16881 "Remove flyspell overlays in region."
16882 (and (org-bound-and-true-p flyspell-mode)
16883 (fboundp 'flyspell-delete-region-overlays)
16884 (flyspell-delete-region-overlays beg end))
16885 (add-text-properties beg end '(org-no-flyspell t)))
16887 ;; Make `bookmark-jump' show the jump location if it was hidden.
16888 (eval-after-load "bookmark"
16889 '(if (boundp 'bookmark-after-jump-hook)
16890 ;; We can use the hook
16891 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
16892 ;; Hook not available, use advice
16893 (defadvice bookmark-jump (after org-make-visible activate)
16894 "Make the position visible."
16895 (org-bookmark-jump-unhide))))
16897 ;; Make sure saveplace show the location if it was hidden
16898 (eval-after-load "saveplace"
16899 '(defadvice save-place-find-file-hook (after org-make-visible activate)
16900 "Make the position visible."
16901 (org-bookmark-jump-unhide)))
16903 (defun org-bookmark-jump-unhide ()
16904 "Unhide the current position, to show the bookmark location."
16905 (and (org-mode-p)
16906 (or (org-invisible-p)
16907 (save-excursion (goto-char (max (point-min) (1- (point))))
16908 (org-invisible-p)))
16909 (org-show-context 'bookmark-jump)))
16911 ;; Make session.el ignore our circular variable
16912 (eval-after-load "session"
16913 '(add-to-list 'session-globals-exclude 'org-mark-ring))
16915 ;;;; Experimental code
16917 (defun org-closed-in-range ()
16918 "Sparse tree of items closed in a certain time range.
16919 Still experimental, may disappear in the future."
16920 (interactive)
16921 ;; Get the time interval from the user.
16922 (let* ((time1 (time-to-seconds
16923 (org-read-date nil 'to-time nil "Starting date: ")))
16924 (time2 (time-to-seconds
16925 (org-read-date nil 'to-time nil "End date:")))
16926 ;; callback function
16927 (callback (lambda ()
16928 (let ((time
16929 (time-to-seconds
16930 (apply 'encode-time
16931 (org-parse-time-string
16932 (match-string 1))))))
16933 ;; check if time in interval
16934 (and (>= time time1) (<= time time2))))))
16935 ;; make tree, check each match with the callback
16936 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
16938 ;;;; Finish up
16940 (provide 'org)
16942 (run-hooks 'org-load-hook)
16944 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
16946 ;;; org.el ends here