Speed-up multiple calls to `org-diary'.
[org-mode.git] / lisp / org.el
blobe30c49a7b9af52e5cb58d06c4be76aa4fbb950c5
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.34trans
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.34trans"
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* ((origin default-directory)
106 (version org-version)
107 (git-version)
108 (dir (concat (file-name-directory (locate-library "org")) "../" )))
109 (when (and (file-exists-p (expand-file-name ".git" dir))
110 (executable-find "git"))
111 (unwind-protect
112 (progn
113 (cd dir)
114 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
115 (with-current-buffer "*Shell Command Output*"
116 (goto-char (point-min))
117 (setq git-version (buffer-substring (point) (point-at-eol))))
118 (subst-char-in-string ?- ?. git-version t)
119 (when (string-match "\\S-"
120 (shell-command-to-string
121 "git diff-index --name-only HEAD --"))
122 (setq git-version (concat git-version ".dirty")))
123 (setq version (concat version " (" git-version ")"))))
124 (cd origin)))
125 (setq version (format "Org-mode version %s" version))
126 (if here (insert version))
127 (message version)))
129 ;;; Compatibility constants
131 ;;; The custom variables
133 (defgroup org nil
134 "Outline-based notes management and organizer."
135 :tag "Org"
136 :group 'outlines
137 :group 'calendar)
139 (defcustom org-mode-hook nil
140 "Mode hook for Org-mode, run after the mode was turned on."
141 :group 'org
142 :type 'hook)
144 (defcustom org-load-hook nil
145 "Hook that is run after org.el has been loaded."
146 :group 'org
147 :type 'hook)
149 (defvar org-modules) ; defined below
150 (defvar org-modules-loaded nil
151 "Have the modules been loaded already?")
153 (defun org-load-modules-maybe (&optional force)
154 "Load all extensions listed in `org-modules'."
155 (when (or force (not org-modules-loaded))
156 (mapc (lambda (ext)
157 (condition-case nil (require ext)
158 (error (message "Problems while trying to load feature `%s'" ext))))
159 org-modules)
160 (setq org-modules-loaded t)))
162 (defun org-set-modules (var value)
163 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
164 (set var value)
165 (when (featurep 'org)
166 (org-load-modules-maybe 'force)))
168 (when (org-bound-and-true-p org-modules)
169 (let ((a (member 'org-infojs org-modules)))
170 (and a (setcar a 'org-jsinfo))))
172 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
173 "Modules that should always be loaded together with org.el.
174 If a description starts with <C>, the file is not part of Emacs
175 and loading it will require that you have downloaded and properly installed
176 the org-mode distribution.
178 You can also use this system to load external packages (i.e. neither Org
179 core modules, nor modules from the CONTRIB directory). Just add symbols
180 to the end of the list. If the package is called org-xyz.el, then you need
181 to add the symbol `xyz', and the package must have a call to
183 (provide 'org-xyz)"
184 :group 'org
185 :set 'org-set-modules
186 :type
187 '(set :greedy t
188 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
189 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
190 (const :tag " crypt: Encryption of subtrees" org-crypt)
191 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
192 (const :tag " docview: Links to doc-view buffers" org-docview)
193 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
194 (const :tag " id: Global IDs for identifying entries" org-id)
195 (const :tag " info: Links to Info nodes" org-info)
196 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
197 (const :tag " habit: Track your consistency with habits" org-habit)
198 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
199 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
200 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
201 (const :tag " mew Links to Mew folders/messages" org-mew)
202 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
203 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
204 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
205 (const :tag " vm: Links to VM folders/messages" org-vm)
206 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
207 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
208 (const :tag " mouse: Additional mouse support" org-mouse)
210 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
211 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
212 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
213 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
214 (const :tag "C collector: Collect properties into tables" org-collector)
215 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
216 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
217 (const :tag "C eval: Include command output as text" org-eval)
218 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
219 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
220 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
221 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
222 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
224 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
226 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
227 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
228 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
229 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
230 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
231 (const :tag "C mtags: Support for muse-like tags" org-mtags)
232 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
233 (const :tag "C R: Computation using the R language" org-R)
234 (const :tag "C registry: A registry for Org-mode links" org-registry)
235 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
236 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
237 (const :tag "C secretary: Team management with org-mode" org-secretary)
238 (const :tag "C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
239 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
240 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
241 (const :tag "C track: Keep up with Org-mode development" org-track)
242 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
244 (defcustom org-support-shift-select nil
245 "Non-nil means make shift-cursor commands select text when possible.
247 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
248 selecting a region, or enlarge thusly regions started in this way.
249 In Org-mode, in special contexts, these same keys are used for other
250 purposes, important enough to compete with shift selection. Org tries
251 to balance these needs by supporting `shift-select-mode' outside these
252 special contexts, under control of this variable.
254 The default of this variable is nil, to avoid confusing behavior. Shifted
255 cursor keys will then execute Org commands in the following contexts:
256 - on a headline, changing TODO state (left/right) and priority (up/down)
257 - on a time stamp, changing the time
258 - in a plain list item, changing the bullet type
259 - in a property definition line, switching between allowed values
260 - in the BEGIN line of a clock table (changing the time block).
261 Outside these contexts, the commands will throw an error.
263 When this variable is t and the cursor is not in a special context,
264 Org-mode will support shift-selection for making and enlarging regions.
265 To make this more effective, the bullet cycling will no longer happen
266 anywhere in an item line, but only if the cursor is exactly on the bullet.
268 If you set this variable to the symbol `always', then the keys
269 will not be special in headlines, property lines, and item lines, to make
270 shift selection work there as well. If this is what you want, you can
271 use the following alternative commands: `C-c C-t' and `C-c ,' to
272 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
273 TODO sets, `C-c -' to cycle item bullet types, and properties can be
274 edited by hand or in column view.
276 However, when the cursor is on a timestamp, shift-cursor commands
277 will still edit the time stamp - this is just too good to give up.
279 XEmacs user should have this variable set to nil, because shift-select-mode
280 is Emacs 23 only."
281 :group 'org
282 :type '(choice
283 (const :tag "Never" nil)
284 (const :tag "When outside special context" t)
285 (const :tag "Everywhere except timestamps" always)))
287 (defgroup org-startup nil
288 "Options concerning startup of Org-mode."
289 :tag "Org Startup"
290 :group 'org)
292 (defcustom org-startup-folded t
293 "Non-nil means entering Org-mode will switch to OVERVIEW.
294 This can also be configured on a per-file basis by adding one of
295 the following lines anywhere in the buffer:
297 #+STARTUP: fold (or `overview', this is equivalent)
298 #+STARTUP: nofold (or `showall', this is equivalent)
299 #+STARTUP: content
300 #+STARTUP: showeverything"
301 :group 'org-startup
302 :type '(choice
303 (const :tag "nofold: show all" nil)
304 (const :tag "fold: overview" t)
305 (const :tag "content: all headlines" content)
306 (const :tag "show everything, even drawers" showeverything)))
308 (defcustom org-startup-truncated t
309 "Non-nil means entering Org-mode will set `truncate-lines'.
310 This is useful since some lines containing links can be very long and
311 uninteresting. Also tables look terrible when wrapped."
312 :group 'org-startup
313 :type 'boolean)
315 (defcustom org-startup-indented nil
316 "Non-nil means turn on `org-indent-mode' on startup.
317 This can also be configured on a per-file basis by adding one of
318 the following lines anywhere in the buffer:
320 #+STARTUP: indent
321 #+STARTUP: noindent"
322 :group 'org-structure
323 :type '(choice
324 (const :tag "Not" nil)
325 (const :tag "Globally (slow on startup in large files)" t)))
327 (defcustom org-startup-with-beamer-mode nil
328 "Non-nil means turn on `org-beamer-mode' on startup.
329 This can also be configured on a per-file basis by adding one of
330 the following lines anywhere in the buffer:
332 #+STARTUP: beamer"
333 :group 'org-startup
334 :type 'boolean)
336 (defcustom org-startup-align-all-tables nil
337 "Non-nil means align all tables when visiting a file.
338 This is useful when the column width in tables is forced with <N> cookies
339 in table fields. Such tables will look correct only after the first re-align.
340 This can also be configured on a per-file basis by adding one of
341 the following lines anywhere in the buffer:
342 #+STARTUP: align
343 #+STARTUP: noalign"
344 :group 'org-startup
345 :type 'boolean)
347 (defcustom org-insert-mode-line-in-empty-file nil
348 "Non-nil means insert the first line setting Org-mode in empty files.
349 When the function `org-mode' is called interactively in an empty file, this
350 normally means that the file name does not automatically trigger Org-mode.
351 To ensure that the file will always be in Org-mode in the future, a
352 line enforcing Org-mode will be inserted into the buffer, if this option
353 has been set."
354 :group 'org-startup
355 :type 'boolean)
357 (defcustom org-replace-disputed-keys nil
358 "Non-nil means use alternative key bindings for some keys.
359 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
360 These keys are also used by other packages like shift-selection-mode'
361 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
362 If you want to use Org-mode together with one of these other modes,
363 or more generally if you would like to move some Org-mode commands to
364 other keys, set this variable and configure the keys with the variable
365 `org-disputed-keys'.
367 This option is only relevant at load-time of Org-mode, and must be set
368 *before* org.el is loaded. Changing it requires a restart of Emacs to
369 become effective."
370 :group 'org-startup
371 :type 'boolean)
373 (defcustom org-use-extra-keys nil
374 "Non-nil means use extra key sequence definitions for certain
375 commands. This happens automatically if you run XEmacs or if
376 window-system is nil. This variable lets you do the same
377 manually. You must set it before loading org.
379 Example: on Carbon Emacs 22 running graphically, with an external
380 keyboard on a Powerbook, the default way of setting M-left might
381 not work for either Alt or ESC. Setting this variable will make
382 it work for ESC."
383 :group 'org-startup
384 :type 'boolean)
386 (if (fboundp 'defvaralias)
387 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
389 (defcustom org-disputed-keys
390 '(([(shift up)] . [(meta p)])
391 ([(shift down)] . [(meta n)])
392 ([(shift left)] . [(meta -)])
393 ([(shift right)] . [(meta +)])
394 ([(control shift right)] . [(meta shift +)])
395 ([(control shift left)] . [(meta shift -)]))
396 "Keys for which Org-mode and other modes compete.
397 This is an alist, cars are the default keys, second element specifies
398 the alternative to use when `org-replace-disputed-keys' is t.
400 Keys can be specified in any syntax supported by `define-key'.
401 The value of this option takes effect only at Org-mode's startup,
402 therefore you'll have to restart Emacs to apply it after changing."
403 :group 'org-startup
404 :type 'alist)
406 (defun org-key (key)
407 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
408 Or return the original if not disputed."
409 (if org-replace-disputed-keys
410 (let* ((nkey (key-description key))
411 (x (org-find-if (lambda (x)
412 (equal (key-description (car x)) nkey))
413 org-disputed-keys)))
414 (if x (cdr x) key))
415 key))
417 (defun org-find-if (predicate seq)
418 (catch 'exit
419 (while seq
420 (if (funcall predicate (car seq))
421 (throw 'exit (car seq))
422 (pop seq)))))
424 (defun org-defkey (keymap key def)
425 "Define a key, possibly translated, as returned by `org-key'."
426 (define-key keymap (org-key key) def))
428 (defcustom org-ellipsis nil
429 "The ellipsis to use in the Org-mode outline.
430 When nil, just use the standard three dots. When a string, use that instead,
431 When a face, use the standard 3 dots, but with the specified face.
432 The change affects only Org-mode (which will then use its own display table).
433 Changing this requires executing `M-x org-mode' in a buffer to become
434 effective."
435 :group 'org-startup
436 :type '(choice (const :tag "Default" nil)
437 (face :tag "Face" :value org-warning)
438 (string :tag "String" :value "...#")))
440 (defvar org-display-table nil
441 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
443 (defgroup org-keywords nil
444 "Keywords in Org-mode."
445 :tag "Org Keywords"
446 :group 'org)
448 (defcustom org-deadline-string "DEADLINE:"
449 "String to mark deadline entries.
450 A deadline is this string, followed by a time stamp. Should be a word,
451 terminated by a colon. You can insert a schedule keyword and
452 a timestamp with \\[org-deadline].
453 Changes become only effective after restarting Emacs."
454 :group 'org-keywords
455 :type 'string)
457 (defcustom org-scheduled-string "SCHEDULED:"
458 "String to mark scheduled TODO entries.
459 A schedule is this string, followed by a time stamp. Should be a word,
460 terminated by a colon. You can insert a schedule keyword and
461 a timestamp with \\[org-schedule].
462 Changes become only effective after restarting Emacs."
463 :group 'org-keywords
464 :type 'string)
466 (defcustom org-closed-string "CLOSED:"
467 "String used as the prefix for timestamps logging closing a TODO entry."
468 :group 'org-keywords
469 :type 'string)
471 (defcustom org-clock-string "CLOCK:"
472 "String used as prefix for timestamps clocking work hours on an item."
473 :group 'org-keywords
474 :type 'string)
476 (defcustom org-comment-string "COMMENT"
477 "Entries starting with this keyword will never be exported.
478 An entry can be toggled between COMMENT and normal with
479 \\[org-toggle-comment].
480 Changes become only effective after restarting Emacs."
481 :group 'org-keywords
482 :type 'string)
484 (defcustom org-quote-string "QUOTE"
485 "Entries starting with this keyword will be exported in fixed-width font.
486 Quoting applies only to the text in the entry following the headline, and does
487 not extend beyond the next headline, even if that is lower level.
488 An entry can be toggled between QUOTE and normal with
489 \\[org-toggle-fixed-width-section]."
490 :group 'org-keywords
491 :type 'string)
493 (defconst org-repeat-re
494 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
495 "Regular expression for specifying repeated events.
496 After a match, group 1 contains the repeat expression.")
498 (defgroup org-structure nil
499 "Options concerning the general structure of Org-mode files."
500 :tag "Org Structure"
501 :group 'org)
503 (defgroup org-reveal-location nil
504 "Options about how to make context of a location visible."
505 :tag "Org Reveal Location"
506 :group 'org-structure)
508 (defconst org-context-choice
509 '(choice
510 (const :tag "Always" t)
511 (const :tag "Never" nil)
512 (repeat :greedy t :tag "Individual contexts"
513 (cons
514 (choice :tag "Context"
515 (const agenda)
516 (const org-goto)
517 (const occur-tree)
518 (const tags-tree)
519 (const link-search)
520 (const mark-goto)
521 (const bookmark-jump)
522 (const isearch)
523 (const default))
524 (boolean))))
525 "Contexts for the reveal options.")
527 (defcustom org-show-hierarchy-above '((default . t))
528 "Non-nil means show full hierarchy when revealing a location.
529 Org-mode often shows locations in an org-mode file which might have
530 been invisible before. When this is set, the hierarchy of headings
531 above the exposed location is shown.
532 Turning this off for example for sparse trees makes them very compact.
533 Instead of t, this can also be an alist specifying this option for different
534 contexts. Valid contexts are
535 agenda when exposing an entry from the agenda
536 org-goto when using the command `org-goto' on key C-c C-j
537 occur-tree when using the command `org-occur' on key C-c /
538 tags-tree when constructing a sparse tree based on tags matches
539 link-search when exposing search matches associated with a link
540 mark-goto when exposing the jump goal of a mark
541 bookmark-jump when exposing a bookmark location
542 isearch when exiting from an incremental search
543 default default for all contexts not set explicitly"
544 :group 'org-reveal-location
545 :type org-context-choice)
547 (defcustom org-show-following-heading '((default . nil))
548 "Non-nil means show following heading when revealing a location.
549 Org-mode often shows locations in an org-mode file which might have
550 been invisible before. When this is set, the heading following the
551 match is shown.
552 Turning this off for example for sparse trees makes them very compact,
553 but makes it harder to edit the location of the match. In such a case,
554 use the command \\[org-reveal] to show more context.
555 Instead of t, this can also be an alist specifying this option for different
556 contexts. See `org-show-hierarchy-above' for valid contexts."
557 :group 'org-reveal-location
558 :type org-context-choice)
560 (defcustom org-show-siblings '((default . nil) (isearch t))
561 "Non-nil means show all sibling heading when revealing a location.
562 Org-mode often shows locations in an org-mode file which might have
563 been invisible before. When this is set, the sibling of the current entry
564 heading are all made visible. If `org-show-hierarchy-above' is t,
565 the same happens on each level of the hierarchy above the current entry.
567 By default this is on for the isearch context, off for all other contexts.
568 Turning this off for example for sparse trees makes them very compact,
569 but makes it harder to edit the location of the match. In such a case,
570 use the command \\[org-reveal] to show more context.
571 Instead of t, this can also be an alist specifying this option for different
572 contexts. See `org-show-hierarchy-above' for valid contexts."
573 :group 'org-reveal-location
574 :type org-context-choice)
576 (defcustom org-show-entry-below '((default . nil))
577 "Non-nil means show the entry below a headline when revealing a location.
578 Org-mode often shows locations in an org-mode file which might have
579 been invisible before. When this is set, the text below the headline that is
580 exposed is also shown.
582 By default this is off for all contexts.
583 Instead of t, this can also be an alist specifying this option for different
584 contexts. See `org-show-hierarchy-above' for valid contexts."
585 :group 'org-reveal-location
586 :type org-context-choice)
588 (defcustom org-indirect-buffer-display 'other-window
589 "How should indirect tree buffers be displayed?
590 This applies to indirect buffers created with the commands
591 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
592 Valid values are:
593 current-window Display in the current window
594 other-window Just display in another window.
595 dedicated-frame Create one new frame, and re-use it each time.
596 new-frame Make a new frame each time. Note that in this case
597 previously-made indirect buffers are kept, and you need to
598 kill these buffers yourself."
599 :group 'org-structure
600 :group 'org-agenda-windows
601 :type '(choice
602 (const :tag "In current window" current-window)
603 (const :tag "In current frame, other window" other-window)
604 (const :tag "Each time a new frame" new-frame)
605 (const :tag "One dedicated frame" dedicated-frame)))
607 (defcustom org-use-speed-commands nil
608 "Non-nil means activate single letter commands at beginning of a headline.
609 This may also be a function to test for appropriate locations where speed
610 commands should be active."
611 :group 'org-structure
612 :type '(choice
613 (const :tag "Never" nil)
614 (const :tag "At beginning of headline stars" t)
615 (function)))
617 (defcustom org-speed-commands-user nil
618 "Alist of additional speed commands.
619 This list will be checked before `org-speed-commands-default'
620 when the variable `org-use-speed-commands' is non-nil
621 and when the cursor is at the beginning of a headline.
622 The car if each entry is a string with a single letter, which must
623 be assigned to `self-insert-command' in the global map.
624 The cdr is either a command to be called interactively, a function
625 to be called, or a form to be evaluated.
626 An entry that is just a list with a single string will be interpreted
627 as a descriptive headline that will be added when listing the speed
628 copmmands in the Help buffer using the `?' speed command."
629 :group 'org-structure
630 :type '(repeat :value ("k" . ignore)
631 (choice :value ("k" . ignore)
632 (list :tag "Descriptive Headline" (string :tag "Headline"))
633 (cons :tag "Letter and Command"
634 (string :tag "Command letter")
635 (choice
636 (function)
637 (sexp))))))
639 (defgroup org-cycle nil
640 "Options concerning visibility cycling in Org-mode."
641 :tag "Org Cycle"
642 :group 'org-structure)
644 (defcustom org-cycle-skip-children-state-if-no-children t
645 "Non-nil means skip CHILDREN state in entries that don't have any."
646 :group 'org-cycle
647 :type 'boolean)
649 (defcustom org-cycle-max-level nil
650 "Maximum level which should still be subject to visibility cycling.
651 Levels higher than this will, for cycling, be treated as text, not a headline.
652 When `org-odd-levels-only' is set, a value of N in this variable actually
653 means 2N-1 stars as the limiting headline.
654 When nil, cycle all levels.
655 Note that the limiting level of cycling is also influenced by
656 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
657 `org-inlinetask-min-level' is, cycling will be limited to levels one less
658 than its value."
659 :group 'org-cycle
660 :type '(choice
661 (const :tag "No limit" nil)
662 (integer :tag "Maximum level")))
664 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
665 "Names of drawers. Drawers are not opened by cycling on the headline above.
666 Drawers only open with a TAB on the drawer line itself. A drawer looks like
667 this:
668 :DRAWERNAME:
669 .....
670 :END:
671 The drawer \"PROPERTIES\" is special for capturing properties through
672 the property API.
674 Drawers can be defined on the per-file basis with a line like:
676 #+DRAWERS: HIDDEN STATE PROPERTIES"
677 :group 'org-structure
678 :group 'org-cycle
679 :type '(repeat (string :tag "Drawer Name")))
681 (defcustom org-hide-block-startup nil
682 "Non-nil means entering Org-mode will fold all blocks.
683 This can also be set in on a per-file basis with
685 #+STARTUP: hideblocks
686 #+STARTUP: showblocks"
687 :group 'org-startup
688 :group 'org-cycle
689 :type 'boolean)
691 (defcustom org-cycle-global-at-bob nil
692 "Cycle globally if cursor is at beginning of buffer and not at a headline.
693 This makes it possible to do global cycling without having to use S-TAB or
694 C-u TAB. For this special case to work, the first line of the buffer
695 must not be a headline - it may be empty or some other text. When used in
696 this way, `org-cycle-hook' is disables temporarily, to make sure the
697 cursor stays at the beginning of the buffer.
698 When this option is nil, don't do anything special at the beginning
699 of the buffer."
700 :group 'org-cycle
701 :type 'boolean)
703 (defcustom org-cycle-level-after-item/entry-creation t
704 "Non-nil means cycle entry level or item indentation in new empty entries.
706 When the cursor is at the end of an empty headline, i.e with only stars
707 and maybe a TODO keyword, TAB will then switch the entry to become a child,
708 and then all possible anchestor states, before returning to the original state.
709 This makes data entry extremely fast: M-RET to create a new headline,
710 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
712 When the cursor is at the end of an empty plain list item, one TAB will
713 make it a subitem, two or more tabs will back up to make this an item
714 higher up in the item hierarchy."
715 :group 'org-cycle
716 :type 'boolean)
718 (defcustom org-cycle-emulate-tab t
719 "Where should `org-cycle' emulate TAB.
720 nil Never
721 white Only in completely white lines
722 whitestart Only at the beginning of lines, before the first non-white char
723 t Everywhere except in headlines
724 exc-hl-bol Everywhere except at the start of a headline
725 If TAB is used in a place where it does not emulate TAB, the current subtree
726 visibility is cycled."
727 :group 'org-cycle
728 :type '(choice (const :tag "Never" nil)
729 (const :tag "Only in completely white lines" white)
730 (const :tag "Before first char in a line" whitestart)
731 (const :tag "Everywhere except in headlines" t)
732 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
735 (defcustom org-cycle-separator-lines 2
736 "Number of empty lines needed to keep an empty line between collapsed trees.
737 If you leave an empty line between the end of a subtree and the following
738 headline, this empty line is hidden when the subtree is folded.
739 Org-mode will leave (exactly) one empty line visible if the number of
740 empty lines is equal or larger to the number given in this variable.
741 So the default 2 means at least 2 empty lines after the end of a subtree
742 are needed to produce free space between a collapsed subtree and the
743 following headline.
745 If the number is negative, and the number of empty lines is at least -N,
746 all empty lines are shown.
748 Special case: when 0, never leave empty lines in collapsed view."
749 :group 'org-cycle
750 :type 'integer)
751 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
753 (defcustom org-pre-cycle-hook nil
754 "Hook that is run before visibility cycling is happening.
755 The function(s) in this hook must accept a single argument which indicates
756 the new state that will be set right after running this hook. The
757 argument is a symbol. Before a global state change, it can have the values
758 `overview', `content', or `all'. Before a local state change, it can have
759 the values `folded', `children', or `subtree'."
760 :group 'org-cycle
761 :type 'hook)
763 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
764 org-cycle-hide-drawers
765 org-cycle-show-empty-lines
766 org-optimize-window-after-visibility-change)
767 "Hook that is run after `org-cycle' has changed the buffer visibility.
768 The function(s) in this hook must accept a single argument which indicates
769 the new state that was set by the most recent `org-cycle' command. The
770 argument is a symbol. After a global state change, it can have the values
771 `overview', `content', or `all'. After a local state change, it can have
772 the values `folded', `children', or `subtree'."
773 :group 'org-cycle
774 :type 'hook)
776 (defgroup org-edit-structure nil
777 "Options concerning structure editing in Org-mode."
778 :tag "Org Edit Structure"
779 :group 'org-structure)
781 (defcustom org-odd-levels-only nil
782 "Non-nil means skip even levels and only use odd levels for the outline.
783 This has the effect that two stars are being added/taken away in
784 promotion/demotion commands. It also influences how levels are
785 handled by the exporters.
786 Changing it requires restart of `font-lock-mode' to become effective
787 for fontification also in regions already fontified.
788 You may also set this on a per-file basis by adding one of the following
789 lines to the buffer:
791 #+STARTUP: odd
792 #+STARTUP: oddeven"
793 :group 'org-edit-structure
794 :group 'org-font-lock
795 :type 'boolean)
797 (defcustom org-adapt-indentation t
798 "Non-nil means adapt indentation to outline node level.
800 When this variable is set, Org assumes that you write outlines by
801 indenting text in each node to align with the headline (after the stars).
802 The following issues are influenced by this variable:
804 - When this is set and the *entire* text in an entry is indented, the
805 indentation is increased by one space in a demotion command, and
806 decreased by one in a promotion command. If any line in the entry
807 body starts with text at column 0, indentation is not changed at all.
809 - Property drawers and planning information is inserted indented when
810 this variable s set. When nil, they will not be indented.
812 - TAB indents a line relative to context. The lines below a headline
813 will be indented when this variable is set.
815 Note that this is all about true indentation, by adding and removing
816 space characters. See also `org-indent.el' which does level-dependent
817 indentation in a virtual way, i.e. at display time in Emacs."
818 :group 'org-edit-structure
819 :type 'boolean)
821 (defcustom org-special-ctrl-a/e nil
822 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
824 When t, `C-a' will bring back the cursor to the beginning of the
825 headline text, i.e. after the stars and after a possible TODO keyword.
826 In an item, this will be the position after the bullet.
827 When the cursor is already at that position, another `C-a' will bring
828 it to the beginning of the line.
830 `C-e' will jump to the end of the headline, ignoring the presence of tags
831 in the headline. A second `C-e' will then jump to the true end of the
832 line, after any tags. This also means that, when this variable is
833 non-nil, `C-e' also will never jump beyond the end of the heading of a
834 folded section, i.e. not after the ellipses.
836 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
837 going to the true line boundary first. Only a directly following, identical
838 keypress will bring the cursor to the special positions.
840 This may also be a cons cell where the behavior for `C-a' and `C-e' is
841 set separately."
842 :group 'org-edit-structure
843 :type '(choice
844 (const :tag "off" nil)
845 (const :tag "on: after stars/bullet and before tags first" t)
846 (const :tag "reversed: true line boundary first" reversed)
847 (cons :tag "Set C-a and C-e separately"
848 (choice :tag "Special C-a"
849 (const :tag "off" nil)
850 (const :tag "on: after stars/bullet first" t)
851 (const :tag "reversed: before stars/bullet first" reversed))
852 (choice :tag "Special C-e"
853 (const :tag "off" nil)
854 (const :tag "on: before tags first" t)
855 (const :tag "reversed: after tags first" reversed)))))
856 (if (fboundp 'defvaralias)
857 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
859 (defcustom org-special-ctrl-k nil
860 "Non-nil means `C-k' will behave specially in headlines.
861 When nil, `C-k' will call the default `kill-line' command.
862 When t, the following will happen while the cursor is in the headline:
864 - When the cursor is at the beginning of a headline, kill the entire
865 line and possible the folded subtree below the line.
866 - When in the middle of the headline text, kill the headline up to the tags.
867 - When after the headline text, kill the tags."
868 :group 'org-edit-structure
869 :type 'boolean)
871 (defcustom org-yank-folded-subtrees t
872 "Non-nil means when yanking subtrees, fold them.
873 If the kill is a single subtree, or a sequence of subtrees, i.e. if
874 it starts with a heading and all other headings in it are either children
875 or siblings, then fold all the subtrees. However, do this only if no
876 text after the yank would be swallowed into a folded tree by this action."
877 :group 'org-edit-structure
878 :type 'boolean)
880 (defcustom org-yank-adjusted-subtrees nil
881 "Non-nil means when yanking subtrees, adjust the level.
882 With this setting, `org-paste-subtree' is used to insert the subtree, see
883 this function for details."
884 :group 'org-edit-structure
885 :type 'boolean)
887 (defcustom org-M-RET-may-split-line '((default . t))
888 "Non-nil means M-RET will split the line at the cursor position.
889 When nil, it will go to the end of the line before making a
890 new line.
891 You may also set this option in a different way for different
892 contexts. Valid contexts are:
894 headline when creating a new headline
895 item when creating a new item
896 table in a table field
897 default the value to be used for all contexts not explicitly
898 customized"
899 :group 'org-structure
900 :group 'org-table
901 :type '(choice
902 (const :tag "Always" t)
903 (const :tag "Never" nil)
904 (repeat :greedy t :tag "Individual contexts"
905 (cons
906 (choice :tag "Context"
907 (const headline)
908 (const item)
909 (const table)
910 (const default))
911 (boolean)))))
914 (defcustom org-insert-heading-respect-content nil
915 "Non-nil means insert new headings after the current subtree.
916 When nil, the new heading is created directly after the current line.
917 The commands \\[org-insert-heading-respect-content] and
918 \\[org-insert-todo-heading-respect-content] turn this variable on
919 for the duration of the command."
920 :group 'org-structure
921 :type 'boolean)
923 (defcustom org-blank-before-new-entry '((heading . auto)
924 (plain-list-item . auto))
925 "Should `org-insert-heading' leave a blank line before new heading/item?
926 The value is an alist, with `heading' and `plain-list-item' as car,
927 and a boolean flag as cdr. For plain lists, if the variable
928 `org-empty-line-terminates-plain-lists' is set, the setting here
929 is ignored and no empty line is inserted, to keep the list in tact."
930 :group 'org-edit-structure
931 :type '(list
932 (cons (const heading)
933 (choice (const :tag "Never" nil)
934 (const :tag "Always" t)
935 (const :tag "Auto" auto)))
936 (cons (const plain-list-item)
937 (choice (const :tag "Never" nil)
938 (const :tag "Always" t)
939 (const :tag "Auto" auto)))))
941 (defcustom org-insert-heading-hook nil
942 "Hook being run after inserting a new heading."
943 :group 'org-edit-structure
944 :type 'hook)
946 (defcustom org-enable-fixed-width-editor t
947 "Non-nil means lines starting with \":\" are treated as fixed-width.
948 This currently only means they are never auto-wrapped.
949 When nil, such lines will be treated like ordinary lines.
950 See also the QUOTE keyword."
951 :group 'org-edit-structure
952 :type 'boolean)
955 (defcustom org-goto-auto-isearch t
956 "Non-nil means typing characters in org-goto starts incremental search."
957 :group 'org-edit-structure
958 :type 'boolean)
960 (defgroup org-sparse-trees nil
961 "Options concerning sparse trees in Org-mode."
962 :tag "Org Sparse Trees"
963 :group 'org-structure)
965 (defcustom org-highlight-sparse-tree-matches t
966 "Non-nil means highlight all matches that define a sparse tree.
967 The highlights will automatically disappear the next time the buffer is
968 changed by an edit command."
969 :group 'org-sparse-trees
970 :type 'boolean)
972 (defcustom org-remove-highlights-with-change t
973 "Non-nil means any change to the buffer will remove temporary highlights.
974 Such highlights are created by `org-occur' and `org-clock-display'.
975 When nil, `C-c C-c needs to be used to get rid of the highlights.
976 The highlights created by `org-preview-latex-fragment' always need
977 `C-c C-c' to be removed."
978 :group 'org-sparse-trees
979 :group 'org-time
980 :type 'boolean)
983 (defcustom org-occur-hook '(org-first-headline-recenter)
984 "Hook that is run after `org-occur' has constructed a sparse tree.
985 This can be used to recenter the window to show as much of the structure
986 as possible."
987 :group 'org-sparse-trees
988 :type 'hook)
990 (defgroup org-imenu-and-speedbar nil
991 "Options concerning imenu and speedbar in Org-mode."
992 :tag "Org Imenu and Speedbar"
993 :group 'org-structure)
995 (defcustom org-imenu-depth 2
996 "The maximum level for Imenu access to Org-mode headlines.
997 This also applied for speedbar access."
998 :group 'org-imenu-and-speedbar
999 :type 'integer)
1001 (defgroup org-table nil
1002 "Options concerning tables in Org-mode."
1003 :tag "Org Table"
1004 :group 'org)
1006 (defcustom org-enable-table-editor 'optimized
1007 "Non-nil means lines starting with \"|\" are handled by the table editor.
1008 When nil, such lines will be treated like ordinary lines.
1010 When equal to the symbol `optimized', the table editor will be optimized to
1011 do the following:
1012 - Automatic overwrite mode in front of whitespace in table fields.
1013 This makes the structure of the table stay in tact as long as the edited
1014 field does not exceed the column width.
1015 - Minimize the number of realigns. Normally, the table is aligned each time
1016 TAB or RET are pressed to move to another field. With optimization this
1017 happens only if changes to a field might have changed the column width.
1018 Optimization requires replacing the functions `self-insert-command',
1019 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1020 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1021 very good at guessing when a re-align will be necessary, but you can always
1022 force one with \\[org-ctrl-c-ctrl-c].
1024 If you would like to use the optimized version in Org-mode, but the
1025 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1027 This variable can be used to turn on and off the table editor during a session,
1028 but in order to toggle optimization, a restart is required.
1030 See also the variable `org-table-auto-blank-field'."
1031 :group 'org-table
1032 :type '(choice
1033 (const :tag "off" nil)
1034 (const :tag "on" t)
1035 (const :tag "on, optimized" optimized)))
1037 (defcustom org-self-insert-cluster-for-undo t
1038 "Non-nil means cluster self-insert commands for undo when possible.
1039 If this is set, then, like in the Emacs command loop, 20 consecutive
1040 characters will be undone together.
1041 This is configurable, because there is some impact on typing performance."
1042 :group 'org-table
1043 :type 'boolean)
1045 (defcustom org-table-tab-recognizes-table.el t
1046 "Non-nil means TAB will automatically notice a table.el table.
1047 When it sees such a table, it moves point into it and - if necessary -
1048 calls `table-recognize-table'."
1049 :group 'org-table-editing
1050 :type 'boolean)
1052 (defgroup org-link nil
1053 "Options concerning links in Org-mode."
1054 :tag "Org Link"
1055 :group 'org)
1057 (defvar org-link-abbrev-alist-local nil
1058 "Buffer-local version of `org-link-abbrev-alist', which see.
1059 The value of this is taken from the #+LINK lines.")
1060 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1062 (defcustom org-link-abbrev-alist nil
1063 "Alist of link abbreviations.
1064 The car of each element is a string, to be replaced at the start of a link.
1065 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1066 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1068 [[linkkey:tag][description]]
1070 The 'linkkey' must be a word word, starting with a letter, followed
1071 by letters, numbers, '-' or '_'.
1073 If REPLACE is a string, the tag will simply be appended to create the link.
1074 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1075 the placeholder \"%h\" will cause a url-encoded version of the tag to
1076 be inserted at that point (see the function `url-hexify-string').
1078 REPLACE may also be a function that will be called with the tag as the
1079 only argument to create the link, which should be returned as a string.
1081 See the manual for examples."
1082 :group 'org-link
1083 :type '(repeat
1084 (cons
1085 (string :tag "Protocol")
1086 (choice
1087 (string :tag "Format")
1088 (function)))))
1090 (defcustom org-descriptive-links t
1091 "Non-nil means hide link part and only show description of bracket links.
1092 Bracket links are like [[link][description]]. This variable sets the initial
1093 state in new org-mode buffers. The setting can then be toggled on a
1094 per-buffer basis from the Org->Hyperlinks menu."
1095 :group 'org-link
1096 :type 'boolean)
1098 (defcustom org-link-file-path-type 'adaptive
1099 "How the path name in file links should be stored.
1100 Valid values are:
1102 relative Relative to the current directory, i.e. the directory of the file
1103 into which the link is being inserted.
1104 absolute Absolute path, if possible with ~ for home directory.
1105 noabbrev Absolute path, no abbreviation of home directory.
1106 adaptive Use relative path for files in the current directory and sub-
1107 directories of it. For other files, use an absolute path."
1108 :group 'org-link
1109 :type '(choice
1110 (const relative)
1111 (const absolute)
1112 (const noabbrev)
1113 (const adaptive)))
1115 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1116 "Types of links that should be activated in Org-mode files.
1117 This is a list of symbols, each leading to the activation of a certain link
1118 type. In principle, it does not hurt to turn on most link types - there may
1119 be a small gain when turning off unused link types. The types are:
1121 bracket The recommended [[link][description]] or [[link]] links with hiding.
1122 angular Links in angular brackets that may contain whitespace like
1123 <bbdb:Carsten Dominik>.
1124 plain Plain links in normal text, no whitespace, like http://google.com.
1125 radio Text that is matched by a radio target, see manual for details.
1126 tag Tag settings in a headline (link to tag search).
1127 date Time stamps (link to calendar).
1128 footnote Footnote labels.
1130 Changing this variable requires a restart of Emacs to become effective."
1131 :group 'org-link
1132 :type '(set :greedy t
1133 (const :tag "Double bracket links (new style)" bracket)
1134 (const :tag "Angular bracket links (old style)" angular)
1135 (const :tag "Plain text links" plain)
1136 (const :tag "Radio target matches" radio)
1137 (const :tag "Tags" tag)
1138 (const :tag "Timestamps" date)
1139 (const :tag "Footnotes" footnote)))
1141 (defcustom org-make-link-description-function nil
1142 "Function to use to generate link descriptions from links. If
1143 nil the link location will be used. This function must take two
1144 parameters; the first is the link and the second the description
1145 org-insert-link has generated, and should return the description
1146 to use."
1147 :group 'org-link
1148 :type 'function)
1150 (defgroup org-link-store nil
1151 "Options concerning storing links in Org-mode."
1152 :tag "Org Store Link"
1153 :group 'org-link)
1155 (defcustom org-email-link-description-format "Email %c: %.30s"
1156 "Format of the description part of a link to an email or usenet message.
1157 The following %-escapes will be replaced by corresponding information:
1159 %F full \"From\" field
1160 %f name, taken from \"From\" field, address if no name
1161 %T full \"To\" field
1162 %t first name in \"To\" field, address if no name
1163 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1164 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1165 %s subject
1166 %m message-id.
1168 You may use normal field width specification between the % and the letter.
1169 This is for example useful to limit the length of the subject.
1171 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1172 :group 'org-link-store
1173 :type 'string)
1175 (defcustom org-from-is-user-regexp
1176 (let (r1 r2)
1177 (when (and user-mail-address (not (string= user-mail-address "")))
1178 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1179 (when (and user-full-name (not (string= user-full-name "")))
1180 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1181 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1182 "Regexp matched against the \"From:\" header of an email or usenet message.
1183 It should match if the message is from the user him/herself."
1184 :group 'org-link-store
1185 :type 'regexp)
1187 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1188 "Non-nil means storing a link to an Org file will use entry IDs.
1190 Note that before this variable is even considered, org-id must be loaded,
1191 so please customize `org-modules' and turn it on.
1193 The variable can have the following values:
1195 t Create an ID if needed to make a link to the current entry.
1197 create-if-interactive
1198 If `org-store-link' is called directly (interactively, as a user
1199 command), do create an ID to support the link. But when doing the
1200 job for remember, only use the ID if it already exists. The
1201 purpose of this setting is to avoid proliferation of unwanted
1202 IDs, just because you happen to be in an Org file when you
1203 call `org-remember' that automatically and preemptively
1204 creates a link. If you do want to get an ID link in a remember
1205 template to an entry not having an ID, create it first by
1206 explicitly creating a link to it, using `C-c C-l' first.
1208 create-if-interactive-and-no-custom-id
1209 Like create-if-interactive, but do not create an ID if there is
1210 a CUSTOM_ID property defined in the entry. This is the default.
1212 use-existing
1213 Use existing ID, do not create one.
1215 nil Never use an ID to make a link, instead link using a text search for
1216 the headline text."
1217 :group 'org-link-store
1218 :type '(choice
1219 (const :tag "Create ID to make link" t)
1220 (const :tag "Create if storing link interactively"
1221 create-if-interactive)
1222 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1223 create-if-interactive-and-no-custom-id)
1224 (const :tag "Only use existing" use-existing)
1225 (const :tag "Do not use ID to create link" nil)))
1227 (defcustom org-context-in-file-links t
1228 "Non-nil means file links from `org-store-link' contain context.
1229 A search string will be added to the file name with :: as separator and
1230 used to find the context when the link is activated by the command
1231 `org-open-at-point'.
1232 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1233 negates this setting for the duration of the command."
1234 :group 'org-link-store
1235 :type 'boolean)
1237 (defcustom org-keep-stored-link-after-insertion nil
1238 "Non-nil means keep link in list for entire session.
1240 The command `org-store-link' adds a link pointing to the current
1241 location to an internal list. These links accumulate during a session.
1242 The command `org-insert-link' can be used to insert links into any
1243 Org-mode file (offering completion for all stored links). When this
1244 option is nil, every link which has been inserted once using \\[org-insert-link]
1245 will be removed from the list, to make completing the unused links
1246 more efficient."
1247 :group 'org-link-store
1248 :type 'boolean)
1250 (defgroup org-link-follow nil
1251 "Options concerning following links in Org-mode."
1252 :tag "Org Follow Link"
1253 :group 'org-link)
1255 (defcustom org-link-translation-function nil
1256 "Function to translate links with different syntax to Org syntax.
1257 This can be used to translate links created for example by the Planner
1258 or emacs-wiki packages to Org syntax.
1259 The function must accept two parameters, a TYPE containing the link
1260 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1261 which is everything after the link protocol. It should return a cons
1262 with possibly modified values of type and path.
1263 Org contains a function for this, so if you set this variable to
1264 `org-translate-link-from-planner', you should be able follow many
1265 links created by planner."
1266 :group 'org-link-follow
1267 :type 'function)
1269 (defcustom org-follow-link-hook nil
1270 "Hook that is run after a link has been followed."
1271 :group 'org-link-follow
1272 :type 'hook)
1274 (defcustom org-tab-follows-link nil
1275 "Non-nil means on links TAB will follow the link.
1276 Needs to be set before org.el is loaded.
1277 This really should not be used, it does not make sense, and the
1278 implementation is bad."
1279 :group 'org-link-follow
1280 :type 'boolean)
1282 (defcustom org-return-follows-link nil
1283 "Non-nil means on links RET will follow the link.
1284 Needs to be set before org.el is loaded."
1285 :group 'org-link-follow
1286 :type 'boolean)
1288 (defcustom org-mouse-1-follows-link
1289 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1290 "Non-nil means mouse-1 on a link will follow the link.
1291 A longer mouse click will still set point. Does not work on XEmacs.
1292 Needs to be set before org.el is loaded."
1293 :group 'org-link-follow
1294 :type 'boolean)
1296 (defcustom org-mark-ring-length 4
1297 "Number of different positions to be recorded in the ring
1298 Changing this requires a restart of Emacs to work correctly."
1299 :group 'org-link-follow
1300 :type 'integer)
1302 (defcustom org-link-frame-setup
1303 '((vm . vm-visit-folder-other-frame)
1304 (gnus . gnus-other-frame)
1305 (file . find-file-other-window))
1306 "Setup the frame configuration for following links.
1307 When following a link with Emacs, it may often be useful to display
1308 this link in another window or frame. This variable can be used to
1309 set this up for the different types of links.
1310 For VM, use any of
1311 `vm-visit-folder'
1312 `vm-visit-folder-other-frame'
1313 For Gnus, use any of
1314 `gnus'
1315 `gnus-other-frame'
1316 `org-gnus-no-new-news'
1317 For FILE, use any of
1318 `find-file'
1319 `find-file-other-window'
1320 `find-file-other-frame'
1321 For the calendar, use the variable `calendar-setup'.
1322 For BBDB, it is currently only possible to display the matches in
1323 another window."
1324 :group 'org-link-follow
1325 :type '(list
1326 (cons (const vm)
1327 (choice
1328 (const vm-visit-folder)
1329 (const vm-visit-folder-other-window)
1330 (const vm-visit-folder-other-frame)))
1331 (cons (const gnus)
1332 (choice
1333 (const gnus)
1334 (const gnus-other-frame)
1335 (const org-gnus-no-new-news)))
1336 (cons (const file)
1337 (choice
1338 (const find-file)
1339 (const find-file-other-window)
1340 (const find-file-other-frame)))))
1342 (defcustom org-display-internal-link-with-indirect-buffer nil
1343 "Non-nil means use indirect buffer to display infile links.
1344 Activating internal links (from one location in a file to another location
1345 in the same file) normally just jumps to the location. When the link is
1346 activated with a C-u prefix (or with mouse-3), the link is displayed in
1347 another window. When this option is set, the other window actually displays
1348 an indirect buffer clone of the current buffer, to avoid any visibility
1349 changes to the current buffer."
1350 :group 'org-link-follow
1351 :type 'boolean)
1353 (defcustom org-open-non-existing-files nil
1354 "Non-nil means `org-open-file' will open non-existing files.
1355 When nil, an error will be generated.
1356 This variable applies only to external applications because they
1357 might choke on non-existing files. If the link is to a file that
1358 will be opened in Emacs, the variable is ignored."
1359 :group 'org-link-follow
1360 :type 'boolean)
1362 (defcustom org-open-directory-means-index-dot-org nil
1363 "Non-nil means a link to a directory really means to index.org.
1364 When nil, following a directory link will run dired or open a finder/explorer
1365 window on that directory."
1366 :group 'org-link-follow
1367 :type 'boolean)
1369 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1370 "Function and arguments to call for following mailto links.
1371 This is a list with the first element being a lisp function, and the
1372 remaining elements being arguments to the function. In string arguments,
1373 %a will be replaced by the address, and %s will be replaced by the subject
1374 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1375 :group 'org-link-follow
1376 :type '(choice
1377 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1378 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1379 (const :tag "message-mail" (message-mail "%a" "%s"))
1380 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1382 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1383 "Non-nil means ask for confirmation before executing shell links.
1384 Shell links can be dangerous: just think about a link
1386 [[shell:rm -rf ~/*][Google Search]]
1388 This link would show up in your Org-mode document as \"Google Search\",
1389 but really it would remove your entire home directory.
1390 Therefore we advise against setting this variable to nil.
1391 Just change it to `y-or-n-p' if you want to confirm with a
1392 single keystroke rather than having to type \"yes\"."
1393 :group 'org-link-follow
1394 :type '(choice
1395 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1396 (const :tag "with y-or-n (faster)" y-or-n-p)
1397 (const :tag "no confirmation (dangerous)" nil)))
1399 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1400 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1401 Elisp links can be dangerous: just think about a link
1403 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1405 This link would show up in your Org-mode document as \"Google Search\",
1406 but really it would remove your entire home directory.
1407 Therefore we advise against setting this variable to nil.
1408 Just change it to `y-or-n-p' if you want to confirm with a
1409 single keystroke rather than having to type \"yes\"."
1410 :group 'org-link-follow
1411 :type '(choice
1412 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1413 (const :tag "with y-or-n (faster)" y-or-n-p)
1414 (const :tag "no confirmation (dangerous)" nil)))
1416 (defconst org-file-apps-defaults-gnu
1417 '((remote . emacs)
1418 (system . mailcap)
1419 (t . mailcap))
1420 "Default file applications on a UNIX or GNU/Linux system.
1421 See `org-file-apps'.")
1423 (defconst org-file-apps-defaults-macosx
1424 '((remote . emacs)
1425 (t . "open %s")
1426 (system . "open %s")
1427 ("ps.gz" . "gv %s")
1428 ("eps.gz" . "gv %s")
1429 ("dvi" . "xdvi %s")
1430 ("fig" . "xfig %s"))
1431 "Default file applications on a MacOS X system.
1432 The system \"open\" is known as a default, but we use X11 applications
1433 for some files for which the OS does not have a good default.
1434 See `org-file-apps'.")
1436 (defconst org-file-apps-defaults-windowsnt
1437 (list
1438 '(remote . emacs)
1439 (cons t
1440 (list (if (featurep 'xemacs)
1441 'mswindows-shell-execute
1442 'w32-shell-execute)
1443 "open" 'file))
1444 (cons 'system
1445 (list (if (featurep 'xemacs)
1446 'mswindows-shell-execute
1447 'w32-shell-execute)
1448 "open" 'file)))
1449 "Default file applications on a Windows NT system.
1450 The system \"open\" is used for most files.
1451 See `org-file-apps'.")
1453 (defcustom org-file-apps
1455 (auto-mode . emacs)
1456 ("\\.mm\\'" . default)
1457 ("\\.x?html?\\'" . default)
1458 ("\\.pdf\\'" . default)
1460 "External applications for opening `file:path' items in a document.
1461 Org-mode uses system defaults for different file types, but
1462 you can use this variable to set the application for a given file
1463 extension. The entries in this list are cons cells where the car identifies
1464 files and the cdr the corresponding command. Possible values for the
1465 file identifier are
1466 \"regex\" Regular expression matched against the file: link. For
1467 backward compatibility, this can also be a string with only
1468 alphanumeric characters, which is then interpreted as an
1469 extension.
1470 `directory' Matches a directory
1471 `remote' Matches a remote file, accessible through tramp or efs.
1472 Remote files most likely should be visited through Emacs
1473 because external applications cannot handle such paths.
1474 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1475 so all files Emacs knows how to handle. Using this with
1476 command `emacs' will open most files in Emacs. Beware that this
1477 will also open html files inside Emacs, unless you add
1478 (\"html\" . default) to the list as well.
1479 t Default for files not matched by any of the other options.
1480 `system' The system command to open files, like `open' on Windows
1481 and Mac OS X, and mailcap under GNU/Linux. This is the command
1482 that will be selected if you call `C-c C-o' with a double
1483 `C-u C-u' prefix.
1485 Possible values for the command are:
1486 `emacs' The file will be visited by the current Emacs process.
1487 `default' Use the default application for this file type, which is the
1488 association for t in the list, most likely in the system-specific
1489 part.
1490 This can be used to overrule an unwanted setting in the
1491 system-specific variable.
1492 `system' Use the system command for opening files, like \"open\".
1493 This command is specified by the entry whose car is `system'.
1494 Most likely, the system-specific version of this variable
1495 does define this command, but you can overrule/replace it
1496 here.
1497 string A command to be executed by a shell; %s will be replaced
1498 by the path to the file. If the file identifier is a regex,
1499 %n will be replaced by the match of the nth match group.
1500 sexp A Lisp form which will be evaluated. The file path will
1501 be available in the Lisp variable `file', the link itself
1502 in the Lisp variable `link'. If the file identifier is a regex,
1503 the original match data will be restored, so subexpression
1504 matches are accessible using (match-string n link).
1505 For more examples, see the system specific constants
1506 `org-file-apps-defaults-macosx'
1507 `org-file-apps-defaults-windowsnt'
1508 `org-file-apps-defaults-gnu'."
1509 :group 'org-link-follow
1510 :type '(repeat
1511 (cons (choice :value ""
1512 (string :tag "Extension")
1513 (const :tag "System command to open files" system)
1514 (const :tag "Default for unrecognized files" t)
1515 (const :tag "Remote file" remote)
1516 (const :tag "Links to a directory" directory)
1517 (const :tag "Any files that have Emacs modes"
1518 auto-mode))
1519 (choice :value ""
1520 (const :tag "Visit with Emacs" emacs)
1521 (const :tag "Use default" default)
1522 (const :tag "Use the system command" system)
1523 (string :tag "Command")
1524 (sexp :tag "Lisp form")))))
1526 (defgroup org-refile nil
1527 "Options concerning refiling entries in Org-mode."
1528 :tag "Org Refile"
1529 :group 'org)
1531 (defcustom org-directory "~/org"
1532 "Directory with org files.
1533 This is just a default location to look for Org files. There is no need
1534 at all to put your files into this directory. It is only used in the
1535 following situations:
1537 1. When a remember template specifies a target file that is not an
1538 absolute path. The path will then be interpreted relative to
1539 `org-directory'
1540 2. When a remember note is filed away in an interactive way (when exiting the
1541 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1542 with `org-directory' as the default path."
1543 :group 'org-refile
1544 :group 'org-remember
1545 :type 'directory)
1547 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1548 "Default target for storing notes.
1549 Used by the hooks for remember.el. This can be a string, or nil to mean
1550 the value of `remember-data-file'.
1551 You can set this on a per-template basis with the variable
1552 `org-remember-templates'."
1553 :group 'org-refile
1554 :group 'org-remember
1555 :type '(choice
1556 (const :tag "Default from remember-data-file" nil)
1557 file))
1559 (defcustom org-goto-interface 'outline
1560 "The default interface to be used for `org-goto'.
1561 Allowed values are:
1562 outline The interface shows an outline of the relevant file
1563 and the correct heading is found by moving through
1564 the outline or by searching with incremental search.
1565 outline-path-completion Headlines in the current buffer are offered via
1566 completion. This is the interface also used by
1567 the refile command."
1568 :group 'org-refile
1569 :type '(choice
1570 (const :tag "Outline" outline)
1571 (const :tag "Outline-path-completion" outline-path-completion)))
1573 (defcustom org-goto-max-level 5
1574 "Maximum level to be considered when running org-goto with refile interface."
1575 :group 'org-refile
1576 :type 'integer)
1578 (defcustom org-reverse-note-order nil
1579 "Non-nil means store new notes at the beginning of a file or entry.
1580 When nil, new notes will be filed to the end of a file or entry.
1581 This can also be a list with cons cells of regular expressions that
1582 are matched against file names, and values."
1583 :group 'org-remember
1584 :group 'org-refile
1585 :type '(choice
1586 (const :tag "Reverse always" t)
1587 (const :tag "Reverse never" nil)
1588 (repeat :tag "By file name regexp"
1589 (cons regexp boolean))))
1591 (defcustom org-log-refile nil
1592 "Information to record when a task is refiled.
1594 Possible values are:
1596 nil Don't add anything
1597 time Add a time stamp to the task
1598 note Prompt for a note and add it with template `org-log-note-headings'
1600 This option can also be set with on a per-file-basis with
1602 #+STARTUP: nologrefile
1603 #+STARTUP: logrefile
1604 #+STARTUP: lognoterefile
1606 You can have local logging settings for a subtree by setting the LOGGING
1607 property to one or more of these keywords.
1609 When bulk-refiling from the agenda, the value `note' is forbidden and
1610 will temporarily be changed to `time'."
1611 :group 'org-refile
1612 :group 'org-progress
1613 :type '(choice
1614 (const :tag "No logging" nil)
1615 (const :tag "Record timestamp" time)
1616 (const :tag "Record timestamp with note." note)))
1618 (defcustom org-refile-targets nil
1619 "Targets for refiling entries with \\[org-refile].
1620 This is list of cons cells. Each cell contains:
1621 - a specification of the files to be considered, either a list of files,
1622 or a symbol whose function or variable value will be used to retrieve
1623 a file name or a list of file names. If you use `org-agenda-files' for
1624 that, all agenda files will be scanned for targets. Nil means consider
1625 headings in the current buffer.
1626 - A specification of how to find candidate refile targets. This may be
1627 any of:
1628 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1629 This tag has to be present in all target headlines, inheritance will
1630 not be considered.
1631 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1632 todo keyword.
1633 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1634 headlines that are refiling targets.
1635 - a cons cell (:level . N). Any headline of level N is considered a target.
1636 Note that, when `org-odd-levels-only' is set, level corresponds to
1637 order in hierarchy, not to the number of stars.
1638 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1639 Note that, when `org-odd-levels-only' is set, level corresponds to
1640 order in hierarchy, not to the number of stars.
1642 You can set the variable `org-refile-target-verify-function' to a function
1643 to verify each headline found by the simple critery above.
1645 When this variable is nil, all top-level headlines in the current buffer
1646 are used, equivalent to the value `((nil . (:level . 1))'."
1647 :group 'org-refile
1648 :type '(repeat
1649 (cons
1650 (choice :value org-agenda-files
1651 (const :tag "All agenda files" org-agenda-files)
1652 (const :tag "Current buffer" nil)
1653 (function) (variable) (file))
1654 (choice :tag "Identify target headline by"
1655 (cons :tag "Specific tag" (const :value :tag) (string))
1656 (cons :tag "TODO keyword" (const :value :todo) (string))
1657 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1658 (cons :tag "Level number" (const :value :level) (integer))
1659 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1661 (defcustom org-refile-target-verify-function nil
1662 "Function to verify if the headline at point should be a refile target.
1663 The function will be called without arguments, with point at the
1664 beginning of the headline. It should return t and leave point
1665 where it is if the headline is a valid target for refiling.
1667 If the target should not be selected, the function must return nil.
1668 In addition to this, it may move point to a place from where the search
1669 should be continued. For example, the function may decide that the entire
1670 subtree of the current entry should be excluded and move point to the end
1671 of the subtree."
1672 :group 'org-refile
1673 :type 'function)
1675 (defcustom org-refile-use-outline-path nil
1676 "Non-nil means provide refile targets as paths.
1677 So a level 3 headline will be available as level1/level2/level3.
1679 When the value is `file', also include the file name (without directory)
1680 into the path. In this case, you can also stop the completion after
1681 the file name, to get entries inserted as top level in the file.
1683 When `full-file-path', include the full file path."
1684 :group 'org-refile
1685 :type '(choice
1686 (const :tag "Not" nil)
1687 (const :tag "Yes" t)
1688 (const :tag "Start with file name" file)
1689 (const :tag "Start with full file path" full-file-path)))
1691 (defcustom org-outline-path-complete-in-steps t
1692 "Non-nil means complete the outline path in hierarchical steps.
1693 When Org-mode uses the refile interface to select an outline path
1694 \(see variable `org-refile-use-outline-path'), the completion of
1695 the path can be done is a single go, or if can be done in steps down
1696 the headline hierarchy. Going in steps is probably the best if you
1697 do not use a special completion package like `ido' or `icicles'.
1698 However, when using these packages, going in one step can be very
1699 fast, while still showing the whole path to the entry."
1700 :group 'org-refile
1701 :type 'boolean)
1703 (defcustom org-refile-allow-creating-parent-nodes nil
1704 "Non-nil means allow to create new nodes as refile targets.
1705 New nodes are then created by adding \"/new node name\" to the completion
1706 of an existing node. When the value of this variable is `confirm',
1707 new node creation must be confirmed by the user (recommended)
1708 When nil, the completion must match an existing entry.
1710 Note that, if the new heading is not seen by the criteria
1711 listed in `org-refile-targets', multiple instances of the same
1712 heading would be created by trying again to file under the new
1713 heading."
1714 :group 'org-refile
1715 :type '(choice
1716 (const :tag "Never" nil)
1717 (const :tag "Always" t)
1718 (const :tag "Prompt for confirmation" confirm)))
1720 (defgroup org-todo nil
1721 "Options concerning TODO items in Org-mode."
1722 :tag "Org TODO"
1723 :group 'org)
1725 (defgroup org-progress nil
1726 "Options concerning Progress logging in Org-mode."
1727 :tag "Org Progress"
1728 :group 'org-time)
1730 (defvar org-todo-interpretation-widgets
1732 (:tag "Sequence (cycling hits every state)" sequence)
1733 (:tag "Type (cycling directly to DONE)" type))
1734 "The available interpretation symbols for customizing
1735 `org-todo-keywords'.
1736 Interested libraries should add to this list.")
1738 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1739 "List of TODO entry keyword sequences and their interpretation.
1740 \\<org-mode-map>This is a list of sequences.
1742 Each sequence starts with a symbol, either `sequence' or `type',
1743 indicating if the keywords should be interpreted as a sequence of
1744 action steps, or as different types of TODO items. The first
1745 keywords are states requiring action - these states will select a headline
1746 for inclusion into the global TODO list Org-mode produces. If one of
1747 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1748 signify that no further action is necessary. If \"|\" is not found,
1749 the last keyword is treated as the only DONE state of the sequence.
1751 The command \\[org-todo] cycles an entry through these states, and one
1752 additional state where no keyword is present. For details about this
1753 cycling, see the manual.
1755 TODO keywords and interpretation can also be set on a per-file basis with
1756 the special #+SEQ_TODO and #+TYP_TODO lines.
1758 Each keyword can optionally specify a character for fast state selection
1759 \(in combination with the variable `org-use-fast-todo-selection')
1760 and specifiers for state change logging, using the same syntax
1761 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1762 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1763 indicates to record a time stamp each time this state is selected.
1765 Each keyword may also specify if a timestamp or a note should be
1766 recorded when entering or leaving the state, by adding additional
1767 characters in the parenthesis after the keyword. This looks like this:
1768 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1769 record only the time of the state change. With X and Y being either
1770 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1771 Y when leaving the state if and only if the *target* state does not
1772 define X. You may omit any of the fast-selection key or X or /Y,
1773 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1775 For backward compatibility, this variable may also be just a list
1776 of keywords - in this case the interpretation (sequence or type) will be
1777 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1778 :group 'org-todo
1779 :group 'org-keywords
1780 :type '(choice
1781 (repeat :tag "Old syntax, just keywords"
1782 (string :tag "Keyword"))
1783 (repeat :tag "New syntax"
1784 (cons
1785 (choice
1786 :tag "Interpretation"
1787 ;;Quick and dirty way to see
1788 ;;`org-todo-interpretations'. This takes the
1789 ;;place of item arguments
1790 :convert-widget
1791 (lambda (widget)
1792 (widget-put widget
1793 :args (mapcar
1794 #'(lambda (x)
1795 (widget-convert
1796 (cons 'const x)))
1797 org-todo-interpretation-widgets))
1798 widget))
1799 (repeat
1800 (string :tag "Keyword"))))))
1802 (defvar org-todo-keywords-1 nil
1803 "All TODO and DONE keywords active in a buffer.")
1804 (make-variable-buffer-local 'org-todo-keywords-1)
1805 (defvar org-todo-keywords-for-agenda nil)
1806 (defvar org-done-keywords-for-agenda nil)
1807 (defvar org-drawers-for-agenda nil)
1808 (defvar org-todo-keyword-alist-for-agenda nil)
1809 (defvar org-tag-alist-for-agenda nil)
1810 (defvar org-agenda-contributing-files nil)
1811 (defvar org-not-done-keywords nil)
1812 (make-variable-buffer-local 'org-not-done-keywords)
1813 (defvar org-done-keywords nil)
1814 (make-variable-buffer-local 'org-done-keywords)
1815 (defvar org-todo-heads nil)
1816 (make-variable-buffer-local 'org-todo-heads)
1817 (defvar org-todo-sets nil)
1818 (make-variable-buffer-local 'org-todo-sets)
1819 (defvar org-todo-log-states nil)
1820 (make-variable-buffer-local 'org-todo-log-states)
1821 (defvar org-todo-kwd-alist nil)
1822 (make-variable-buffer-local 'org-todo-kwd-alist)
1823 (defvar org-todo-key-alist nil)
1824 (make-variable-buffer-local 'org-todo-key-alist)
1825 (defvar org-todo-key-trigger nil)
1826 (make-variable-buffer-local 'org-todo-key-trigger)
1828 (defcustom org-todo-interpretation 'sequence
1829 "Controls how TODO keywords are interpreted.
1830 This variable is in principle obsolete and is only used for
1831 backward compatibility, if the interpretation of todo keywords is
1832 not given already in `org-todo-keywords'. See that variable for
1833 more information."
1834 :group 'org-todo
1835 :group 'org-keywords
1836 :type '(choice (const sequence)
1837 (const type)))
1839 (defcustom org-use-fast-todo-selection t
1840 "Non-nil means use the fast todo selection scheme with C-c C-t.
1841 This variable describes if and under what circumstances the cycling
1842 mechanism for TODO keywords will be replaced by a single-key, direct
1843 selection scheme.
1845 When nil, fast selection is never used.
1847 When the symbol `prefix', it will be used when `org-todo' is called with
1848 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1849 in an agenda buffer.
1851 When t, fast selection is used by default. In this case, the prefix
1852 argument forces cycling instead.
1854 In all cases, the special interface is only used if access keys have actually
1855 been assigned by the user, i.e. if keywords in the configuration are followed
1856 by a letter in parenthesis, like TODO(t)."
1857 :group 'org-todo
1858 :type '(choice
1859 (const :tag "Never" nil)
1860 (const :tag "By default" t)
1861 (const :tag "Only with C-u C-c C-t" prefix)))
1863 (defcustom org-provide-todo-statistics t
1864 "Non-nil means update todo statistics after insert and toggle.
1865 ALL-HEADLINES means update todo statistics by including headlines
1866 with no TODO keyword as well, counting them as not done.
1867 A list of TODO keywords means the same, but skip keywords that are
1868 not in this list.
1870 When this is set, todo statistics is updated in the parent of the
1871 current entry each time a todo state is changed."
1872 :group 'org-todo
1873 :type '(choice
1874 (const :tag "Yes, only for TODO entries" t)
1875 (const :tag "Yes, including all entries" 'all-headlines)
1876 (repeat :tag "Yes, for TODOs in this list"
1877 (string :tag "TODO keyword"))
1878 (other :tag "No TODO statistics" nil)))
1880 (defcustom org-hierarchical-todo-statistics t
1881 "Non-nil means TODO statistics covers just direct children.
1882 When nil, all entries in the subtree are considered.
1883 This has only an effect if `org-provide-todo-statistics' is set.
1884 To set this to nil for only a single subtree, use a COOKIE_DATA
1885 property and include the word \"recursive\" into the value."
1886 :group 'org-todo
1887 :type 'boolean)
1889 (defcustom org-after-todo-state-change-hook nil
1890 "Hook which is run after the state of a TODO item was changed.
1891 The new state (a string with a TODO keyword, or nil) is available in the
1892 Lisp variable `state'."
1893 :group 'org-todo
1894 :type 'hook)
1896 (defvar org-blocker-hook nil
1897 "Hook for functions that are allowed to block a state change.
1899 Each function gets as its single argument a property list, see
1900 `org-trigger-hook' for more information about this list.
1902 If any of the functions in this hook returns nil, the state change
1903 is blocked.")
1905 (defvar org-trigger-hook nil
1906 "Hook for functions that are triggered by a state change.
1908 Each function gets as its single argument a property list with at least
1909 the following elements:
1911 (:type type-of-change :position pos-at-entry-start
1912 :from old-state :to new-state)
1914 Depending on the type, more properties may be present.
1916 This mechanism is currently implemented for:
1918 TODO state changes
1919 ------------------
1920 :type todo-state-change
1921 :from previous state (keyword as a string), or nil, or a symbol
1922 'todo' or 'done', to indicate the general type of state.
1923 :to new state, like in :from")
1925 (defcustom org-enforce-todo-dependencies nil
1926 "Non-nil means undone TODO entries will block switching the parent to DONE.
1927 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1928 be blocked if any prior sibling is not yet done.
1929 Finally, if the parent is blocked because of ordered siblings of its own,
1930 the child will also be blocked.
1931 This variable needs to be set before org.el is loaded, and you need to
1932 restart Emacs after a change to make the change effective. The only way
1933 to change is while Emacs is running is through the customize interface."
1934 :set (lambda (var val)
1935 (set var val)
1936 (if val
1937 (add-hook 'org-blocker-hook
1938 'org-block-todo-from-children-or-siblings-or-parent)
1939 (remove-hook 'org-blocker-hook
1940 'org-block-todo-from-children-or-siblings-or-parent)))
1941 :group 'org-todo
1942 :type 'boolean)
1944 (defcustom org-enforce-todo-checkbox-dependencies nil
1945 "Non-nil means unchecked boxes will block switching the parent to DONE.
1946 When this is nil, checkboxes have no influence on switching TODO states.
1947 When non-nil, you first need to check off all check boxes before the TODO
1948 entry can be switched to DONE.
1949 This variable needs to be set before org.el is loaded, and you need to
1950 restart Emacs after a change to make the change effective. The only way
1951 to change is while Emacs is running is through the customize interface."
1952 :set (lambda (var val)
1953 (set var val)
1954 (if val
1955 (add-hook 'org-blocker-hook
1956 'org-block-todo-from-checkboxes)
1957 (remove-hook 'org-blocker-hook
1958 'org-block-todo-from-checkboxes)))
1959 :group 'org-todo
1960 :type 'boolean)
1962 (defcustom org-treat-insert-todo-heading-as-state-change nil
1963 "Non-nil means inserting a TODO heading is treated as state change.
1964 So when the command \\[org-insert-todo-heading] is used, state change
1965 logging will apply if appropriate. When nil, the new TODO item will
1966 be inserted directly, and no logging will take place."
1967 :group 'org-todo
1968 :type 'boolean)
1970 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1971 "Non-nil means switching TODO states with S-cursor counts as state change.
1972 This is the default behavior. However, setting this to nil allows a
1973 convenient way to select a TODO state and bypass any logging associated
1974 with that."
1975 :group 'org-todo
1976 :type 'boolean)
1978 (defcustom org-todo-state-tags-triggers nil
1979 "Tag changes that should be triggered by TODO state changes.
1980 This is a list. Each entry is
1982 (state-change (tag . flag) .......)
1984 State-change can be a string with a state, and empty string to indicate the
1985 state that has no TODO keyword, or it can be one of the symbols `todo'
1986 or `done', meaning any not-done or done state, respectively."
1987 :group 'org-todo
1988 :group 'org-tags
1989 :type '(repeat
1990 (cons (choice :tag "When changing to"
1991 (const :tag "Not-done state" todo)
1992 (const :tag "Done state" done)
1993 (string :tag "State"))
1994 (repeat
1995 (cons :tag "Tag action"
1996 (string :tag "Tag")
1997 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1999 (defcustom org-log-done nil
2000 "Information to record when a task moves to the DONE state.
2002 Possible values are:
2004 nil Don't add anything, just change the keyword
2005 time Add a time stamp to the task
2006 note Prompt for a note and add it with template `org-log-note-headings'
2008 This option can also be set with on a per-file-basis with
2010 #+STARTUP: nologdone
2011 #+STARTUP: logdone
2012 #+STARTUP: lognotedone
2014 You can have local logging settings for a subtree by setting the LOGGING
2015 property to one or more of these keywords."
2016 :group 'org-todo
2017 :group 'org-progress
2018 :type '(choice
2019 (const :tag "No logging" nil)
2020 (const :tag "Record CLOSED timestamp" time)
2021 (const :tag "Record CLOSED timestamp with note." note)))
2023 ;; Normalize old uses of org-log-done.
2024 (cond
2025 ((eq org-log-done t) (setq org-log-done 'time))
2026 ((and (listp org-log-done) (memq 'done org-log-done))
2027 (setq org-log-done 'note)))
2029 (defcustom org-log-reschedule nil
2030 "Information to record when the scheduling date of a tasks is modified.
2032 Possible values are:
2034 nil Don't add anything, just change the date
2035 time Add a time stamp to the task
2036 note Prompt for a note and add it with template `org-log-note-headings'
2038 This option can also be set with on a per-file-basis with
2040 #+STARTUP: nologreschedule
2041 #+STARTUP: logreschedule
2042 #+STARTUP: lognotereschedule"
2043 :group 'org-todo
2044 :group 'org-progress
2045 :type '(choice
2046 (const :tag "No logging" nil)
2047 (const :tag "Record timestamp" time)
2048 (const :tag "Record timestamp with note." note)))
2050 (defcustom org-log-redeadline nil
2051 "Information to record when the deadline date of a tasks is modified.
2053 Possible values are:
2055 nil Don't add anything, just change the date
2056 time Add a time stamp to the task
2057 note Prompt for a note and add it with template `org-log-note-headings'
2059 This option can also be set with on a per-file-basis with
2061 #+STARTUP: nologredeadline
2062 #+STARTUP: logredeadline
2063 #+STARTUP: lognoteredeadline
2065 You can have local logging settings for a subtree by setting the LOGGING
2066 property to one or more of these keywords."
2067 :group 'org-todo
2068 :group 'org-progress
2069 :type '(choice
2070 (const :tag "No logging" nil)
2071 (const :tag "Record timestamp" time)
2072 (const :tag "Record timestamp with note." note)))
2074 (defcustom org-log-note-clock-out nil
2075 "Non-nil means record a note when clocking out of an item.
2076 This can also be configured on a per-file basis by adding one of
2077 the following lines anywhere in the buffer:
2079 #+STARTUP: lognoteclock-out
2080 #+STARTUP: nolognoteclock-out"
2081 :group 'org-todo
2082 :group 'org-progress
2083 :type 'boolean)
2085 (defcustom org-log-done-with-time t
2086 "Non-nil means the CLOSED time stamp will contain date and time.
2087 When nil, only the date will be recorded."
2088 :group 'org-progress
2089 :type 'boolean)
2091 (defcustom org-log-note-headings
2092 '((done . "CLOSING NOTE %t")
2093 (state . "State %-12s from %-12S %t")
2094 (note . "Note taken on %t")
2095 (reschedule . "Rescheduled from %S on %t")
2096 (delschedule . "Not scheduled, was %S on %t")
2097 (redeadline . "New deadline from %S on %t")
2098 (deldeadline . "Removed deadline, was %S on %t")
2099 (refile . "Refiled on %t")
2100 (clock-out . ""))
2101 "Headings for notes added to entries.
2102 The value is an alist, with the car being a symbol indicating the note
2103 context, and the cdr is the heading to be used. The heading may also be the
2104 empty string.
2105 %t in the heading will be replaced by a time stamp.
2106 %s will be replaced by the new TODO state, in double quotes.
2107 %S will be replaced by the old TODO state, in double quotes.
2108 %u will be replaced by the user name.
2109 %U will be replaced by the full user name.
2111 In fact, it is not a good idea to change the `state' entry, because
2112 agenda log mode depends on the format of these entries."
2113 :group 'org-todo
2114 :group 'org-progress
2115 :type '(list :greedy t
2116 (cons (const :tag "Heading when closing an item" done) string)
2117 (cons (const :tag
2118 "Heading when changing todo state (todo sequence only)"
2119 state) string)
2120 (cons (const :tag "Heading when just taking a note" note) string)
2121 (cons (const :tag "Heading when clocking out" clock-out) string)
2122 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2123 (cons (const :tag "Heading when rescheduling" reschedule) string)
2124 (cons (const :tag "Heading when changing deadline" redeadline) string)
2125 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2126 (cons (const :tag "Heading when refiling" refile) string)))
2128 (unless (assq 'note org-log-note-headings)
2129 (push '(note . "%t") org-log-note-headings))
2131 (defcustom org-log-into-drawer nil
2132 "Non-nil means insert state change notes and time stamps into a drawer.
2133 When nil, state changes notes will be inserted after the headline and
2134 any scheduling and clock lines, but not inside a drawer.
2136 The value of this variable should be the name of the drawer to use.
2137 LOGBOOK is proposed at the default drawer for this purpose, you can
2138 also set this to a string to define the drawer of your choice.
2140 A value of t is also allowed, representing \"LOGBOOK\".
2142 If this variable is set, `org-log-state-notes-insert-after-drawers'
2143 will be ignored.
2145 You can set the property LOG_INTO_DRAWER to overrule this setting for
2146 a subtree."
2147 :group 'org-todo
2148 :group 'org-progress
2149 :type '(choice
2150 (const :tag "Not into a drawer" nil)
2151 (const :tag "LOGBOOK" t)
2152 (string :tag "Other")))
2154 (if (fboundp 'defvaralias)
2155 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2157 (defun org-log-into-drawer ()
2158 "Return the value of `org-log-into-drawer', but let properties overrule.
2159 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2160 used instead of the default value."
2161 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
2162 (cond
2163 ((or (not p) (equal p "nil")) org-log-into-drawer)
2164 ((equal p "t") "LOGBOOK")
2165 (t p))))
2167 (defcustom org-log-state-notes-insert-after-drawers nil
2168 "Non-nil means insert state change notes after any drawers in entry.
2169 Only the drawers that *immediately* follow the headline and the
2170 deadline/scheduled line are skipped.
2171 When nil, insert notes right after the heading and perhaps the line
2172 with deadline/scheduling if present.
2174 This variable will have no effect if `org-log-into-drawer' is
2175 set."
2176 :group 'org-todo
2177 :group 'org-progress
2178 :type 'boolean)
2180 (defcustom org-log-states-order-reversed t
2181 "Non-nil means the latest state note will be directly after heading.
2182 When nil, the state change notes will be ordered according to time."
2183 :group 'org-todo
2184 :group 'org-progress
2185 :type 'boolean)
2187 (defcustom org-log-repeat 'time
2188 "Non-nil means record moving through the DONE state when triggering repeat.
2189 An auto-repeating task is immediately switched back to TODO when
2190 marked DONE. If you are not logging state changes (by adding \"@\"
2191 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2192 record a closing note, there will be no record of the task moving
2193 through DONE. This variable forces taking a note anyway.
2195 nil Don't force a record
2196 time Record a time stamp
2197 note Record a note
2199 This option can also be set with on a per-file-basis with
2201 #+STARTUP: logrepeat
2202 #+STARTUP: lognoterepeat
2203 #+STARTUP: nologrepeat
2205 You can have local logging settings for a subtree by setting the LOGGING
2206 property to one or more of these keywords."
2207 :group 'org-todo
2208 :group 'org-progress
2209 :type '(choice
2210 (const :tag "Don't force a record" nil)
2211 (const :tag "Force recording the DONE state" time)
2212 (const :tag "Force recording a note with the DONE state" note)))
2215 (defgroup org-priorities nil
2216 "Priorities in Org-mode."
2217 :tag "Org Priorities"
2218 :group 'org-todo)
2220 (defcustom org-enable-priority-commands t
2221 "Non-nil means priority commands are active.
2222 When nil, these commands will be disabled, so that you never accidentally
2223 set a priority."
2224 :group 'org-priorities
2225 :type 'boolean)
2227 (defcustom org-highest-priority ?A
2228 "The highest priority of TODO items. A character like ?A, ?B etc.
2229 Must have a smaller ASCII number than `org-lowest-priority'."
2230 :group 'org-priorities
2231 :type 'character)
2233 (defcustom org-lowest-priority ?C
2234 "The lowest priority of TODO items. A character like ?A, ?B etc.
2235 Must have a larger ASCII number than `org-highest-priority'."
2236 :group 'org-priorities
2237 :type 'character)
2239 (defcustom org-default-priority ?B
2240 "The default priority of TODO items.
2241 This is the priority an item get if no explicit priority is given."
2242 :group 'org-priorities
2243 :type 'character)
2245 (defcustom org-priority-start-cycle-with-default t
2246 "Non-nil means start with default priority when starting to cycle.
2247 When this is nil, the first step in the cycle will be (depending on the
2248 command used) one higher or lower that the default priority."
2249 :group 'org-priorities
2250 :type 'boolean)
2252 (defgroup org-time nil
2253 "Options concerning time stamps and deadlines in Org-mode."
2254 :tag "Org Time"
2255 :group 'org)
2257 (defcustom org-insert-labeled-timestamps-at-point nil
2258 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2259 When nil, these labeled time stamps are forces into the second line of an
2260 entry, just after the headline. When scheduling from the global TODO list,
2261 the time stamp will always be forced into the second line."
2262 :group 'org-time
2263 :type 'boolean)
2265 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2266 "Formats for `format-time-string' which are used for time stamps.
2267 It is not recommended to change this constant.")
2269 (defcustom org-time-stamp-rounding-minutes '(0 5)
2270 "Number of minutes to round time stamps to.
2271 These are two values, the first applies when first creating a time stamp.
2272 The second applies when changing it with the commands `S-up' and `S-down'.
2273 When changing the time stamp, this means that it will change in steps
2274 of N minutes, as given by the second value.
2276 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2277 numbers should be factors of 60, so for example 5, 10, 15.
2279 When this is larger than 1, you can still force an exact time-stamp by using
2280 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2281 and by using a prefix arg to `S-up/down' to specify the exact number
2282 of minutes to shift."
2283 :group 'org-time
2284 :get '(lambda (var) ; Make sure all entries have 5 elements
2285 (if (integerp (default-value var))
2286 (list (default-value var) 5)
2287 (default-value var)))
2288 :type '(list
2289 (integer :tag "when inserting times")
2290 (integer :tag "when modifying times")))
2292 ;; Normalize old customizations of this variable.
2293 (when (integerp org-time-stamp-rounding-minutes)
2294 (setq org-time-stamp-rounding-minutes
2295 (list org-time-stamp-rounding-minutes
2296 org-time-stamp-rounding-minutes)))
2298 (defcustom org-display-custom-times nil
2299 "Non-nil means overlay custom formats over all time stamps.
2300 The formats are defined through the variable `org-time-stamp-custom-formats'.
2301 To turn this on on a per-file basis, insert anywhere in the file:
2302 #+STARTUP: customtime"
2303 :group 'org-time
2304 :set 'set-default
2305 :type 'sexp)
2306 (make-variable-buffer-local 'org-display-custom-times)
2308 (defcustom org-time-stamp-custom-formats
2309 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2310 "Custom formats for time stamps. See `format-time-string' for the syntax.
2311 These are overlayed over the default ISO format if the variable
2312 `org-display-custom-times' is set. Time like %H:%M should be at the
2313 end of the second format. The custom formats are also honored by export
2314 commands, if custom time display is turned on at the time of export."
2315 :group 'org-time
2316 :type 'sexp)
2318 (defun org-time-stamp-format (&optional long inactive)
2319 "Get the right format for a time string."
2320 (let ((f (if long (cdr org-time-stamp-formats)
2321 (car org-time-stamp-formats))))
2322 (if inactive
2323 (concat "[" (substring f 1 -1) "]")
2324 f)))
2326 (defcustom org-time-clocksum-format "%d:%02d"
2327 "The format string used when creating CLOCKSUM lines, or when
2328 org-mode generates a time duration."
2329 :group 'org-time
2330 :type 'string)
2332 (defcustom org-time-clocksum-use-fractional nil
2333 "If non-nil, \\[org-clock-display] uses fractional times.
2334 org-mode generates a time duration."
2335 :group 'org-time
2336 :type 'boolean)
2338 (defcustom org-time-clocksum-fractional-format "%.2f"
2339 "The format string used when creating CLOCKSUM lines, or when
2340 org-mode generates a time duration."
2341 :group 'org-time
2342 :type 'string)
2344 (defcustom org-deadline-warning-days 14
2345 "No. of days before expiration during which a deadline becomes active.
2346 This variable governs the display in sparse trees and in the agenda.
2347 When 0 or negative, it means use this number (the absolute value of it)
2348 even if a deadline has a different individual lead time specified.
2350 Custom commands can set this variable in the options section."
2351 :group 'org-time
2352 :group 'org-agenda-daily/weekly
2353 :type 'integer)
2355 (defcustom org-read-date-prefer-future t
2356 "Non-nil means assume future for incomplete date input from user.
2357 This affects the following situations:
2358 1. The user gives a month but not a year.
2359 For example, if it is april and you enter \"feb 2\", this will be read
2360 as feb 2, *next* year. \"May 5\", however, will be this year.
2361 2. The user gives a day, but no month.
2362 For example, if today is the 15th, and you enter \"3\", Org-mode will
2363 read this as the third of *next* month. However, if you enter \"17\",
2364 it will be considered as *this* month.
2366 If you set this variable to the symbol `time', then also the following
2367 will work:
2369 3. If the user gives a time, but no day. If the time is before now,
2370 to will be interpreted as tomorrow.
2372 Currently none of this works for ISO week specifications.
2374 When this option is nil, the current day, month and year will always be
2375 used as defaults."
2376 :group 'org-time
2377 :type '(choice
2378 (const :tag "Never" nil)
2379 (const :tag "Check month and day" t)
2380 (const :tag "Check month, day, and time" time)))
2382 (defcustom org-read-date-display-live t
2383 "Non-nil means display current interpretation of date prompt live.
2384 This display will be in an overlay, in the minibuffer."
2385 :group 'org-time
2386 :type 'boolean)
2388 (defcustom org-read-date-popup-calendar t
2389 "Non-nil means pop up a calendar when prompting for a date.
2390 In the calendar, the date can be selected with mouse-1. However, the
2391 minibuffer will also be active, and you can simply enter the date as well.
2392 When nil, only the minibuffer will be available."
2393 :group 'org-time
2394 :type 'boolean)
2395 (if (fboundp 'defvaralias)
2396 (defvaralias 'org-popup-calendar-for-date-prompt
2397 'org-read-date-popup-calendar))
2399 (defcustom org-read-date-minibuffer-setup-hook nil
2400 "Hook to be used to set up keys for the date/time interface.
2401 Add key definitions to `minibuffer-local-map', which will be a temporary
2402 copy."
2403 :group 'org-time
2404 :type 'hook)
2406 (defcustom org-extend-today-until 0
2407 "The hour when your day really ends. Must be an integer.
2408 This has influence for the following applications:
2409 - When switching the agenda to \"today\". It it is still earlier than
2410 the time given here, the day recognized as TODAY is actually yesterday.
2411 - When a date is read from the user and it is still before the time given
2412 here, the current date and time will be assumed to be yesterday, 23:59.
2413 Also, timestamps inserted in remember templates follow this rule.
2415 IMPORTANT: This is a feature whose implementation is and likely will
2416 remain incomplete. Really, it is only here because past midnight seems to
2417 be the favorite working time of John Wiegley :-)"
2418 :group 'org-time
2419 :type 'integer)
2421 (defcustom org-edit-timestamp-down-means-later nil
2422 "Non-nil means S-down will increase the time in a time stamp.
2423 When nil, S-up will increase."
2424 :group 'org-time
2425 :type 'boolean)
2427 (defcustom org-calendar-follow-timestamp-change t
2428 "Non-nil means make the calendar window follow timestamp changes.
2429 When a timestamp is modified and the calendar window is visible, it will be
2430 moved to the new date."
2431 :group 'org-time
2432 :type 'boolean)
2434 (defgroup org-tags nil
2435 "Options concerning tags in Org-mode."
2436 :tag "Org Tags"
2437 :group 'org)
2439 (defcustom org-tag-alist nil
2440 "List of tags allowed in Org-mode files.
2441 When this list is nil, Org-mode will base TAG input on what is already in the
2442 buffer.
2443 The value of this variable is an alist, the car of each entry must be a
2444 keyword as a string, the cdr may be a character that is used to select
2445 that tag through the fast-tag-selection interface.
2446 See the manual for details."
2447 :group 'org-tags
2448 :type '(repeat
2449 (choice
2450 (cons (string :tag "Tag name")
2451 (character :tag "Access char"))
2452 (list :tag "Start radio group"
2453 (const :startgroup)
2454 (option (string :tag "Group description")))
2455 (list :tag "End radio group"
2456 (const :endgroup)
2457 (option (string :tag "Group description")))
2458 (const :tag "New line" (:newline)))))
2460 (defcustom org-tag-persistent-alist nil
2461 "List of tags that will always appear in all Org-mode files.
2462 This is in addition to any in buffer settings or customizations
2463 of `org-tag-alist'.
2464 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2465 The value of this variable is an alist, the car of each entry must be a
2466 keyword as a string, the cdr may be a character that is used to select
2467 that tag through the fast-tag-selection interface.
2468 See the manual for details.
2469 To disable these tags on a per-file basis, insert anywhere in the file:
2470 #+STARTUP: noptag"
2471 :group 'org-tags
2472 :type '(repeat
2473 (choice
2474 (cons (string :tag "Tag name")
2475 (character :tag "Access char"))
2476 (const :tag "Start radio group" (:startgroup))
2477 (const :tag "End radio group" (:endgroup))
2478 (const :tag "New line" (:newline)))))
2480 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2481 "If non-nil, always offer completion for all tags of all agenda files.
2482 Instead of customizing this variable directly, you might want to
2483 set it locally for remember buffers, because there no list of
2484 tags in that file can be created dynamically (there are none).
2486 (add-hook 'org-remember-mode-hook
2487 (lambda ()
2488 (set (make-local-variable
2489 'org-complete-tags-always-offer-all-agenda-tags)
2490 t)))"
2491 :group 'org-tags
2492 :type 'boolean)
2494 (defvar org-file-tags nil
2495 "List of tags that can be inherited by all entries in the file.
2496 The tags will be inherited if the variable `org-use-tag-inheritance'
2497 says they should be.
2498 This variable is populated from #+FILETAGS lines.")
2500 (defcustom org-use-fast-tag-selection 'auto
2501 "Non-nil means use fast tag selection scheme.
2502 This is a special interface to select and deselect tags with single keys.
2503 When nil, fast selection is never used.
2504 When the symbol `auto', fast selection is used if and only if selection
2505 characters for tags have been configured, either through the variable
2506 `org-tag-alist' or through a #+TAGS line in the buffer.
2507 When t, fast selection is always used and selection keys are assigned
2508 automatically if necessary."
2509 :group 'org-tags
2510 :type '(choice
2511 (const :tag "Always" t)
2512 (const :tag "Never" nil)
2513 (const :tag "When selection characters are configured" 'auto)))
2515 (defcustom org-fast-tag-selection-single-key nil
2516 "Non-nil means fast tag selection exits after first change.
2517 When nil, you have to press RET to exit it.
2518 During fast tag selection, you can toggle this flag with `C-c'.
2519 This variable can also have the value `expert'. In this case, the window
2520 displaying the tags menu is not even shown, until you press C-c again."
2521 :group 'org-tags
2522 :type '(choice
2523 (const :tag "No" nil)
2524 (const :tag "Yes" t)
2525 (const :tag "Expert" expert)))
2527 (defvar org-fast-tag-selection-include-todo nil
2528 "Non-nil means fast tags selection interface will also offer TODO states.
2529 This is an undocumented feature, you should not rely on it.")
2531 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2532 "The column to which tags should be indented in a headline.
2533 If this number is positive, it specifies the column. If it is negative,
2534 it means that the tags should be flushright to that column. For example,
2535 -80 works well for a normal 80 character screen."
2536 :group 'org-tags
2537 :type 'integer)
2539 (defcustom org-auto-align-tags t
2540 "Non-nil means realign tags after pro/demotion of TODO state change.
2541 These operations change the length of a headline and therefore shift
2542 the tags around. With this options turned on, after each such operation
2543 the tags are again aligned to `org-tags-column'."
2544 :group 'org-tags
2545 :type 'boolean)
2547 (defcustom org-use-tag-inheritance t
2548 "Non-nil means tags in levels apply also for sublevels.
2549 When nil, only the tags directly given in a specific line apply there.
2550 This may also be a list of tags that should be inherited, or a regexp that
2551 matches tags that should be inherited. Additional control is possible
2552 with the variable `org-tags-exclude-from-inheritance' which gives an
2553 explicit list of tags to be excluded from inheritance., even if the value of
2554 `org-use-tag-inheritance' would select it for inheritance.
2556 If this option is t, a match early-on in a tree can lead to a large
2557 number of matches in the subtree when constructing the agenda or creating
2558 a sparse tree. If you only want to see the first match in a tree during
2559 a search, check out the variable `org-tags-match-list-sublevels'."
2560 :group 'org-tags
2561 :type '(choice
2562 (const :tag "Not" nil)
2563 (const :tag "Always" t)
2564 (repeat :tag "Specific tags" (string :tag "Tag"))
2565 (regexp :tag "Tags matched by regexp")))
2567 (defcustom org-tags-exclude-from-inheritance nil
2568 "List of tags that should never be inherited.
2569 This is a way to exclude a few tags from inheritance. For way to do
2570 the opposite, to actively allow inheritance for selected tags,
2571 see the variable `org-use-tag-inheritance'."
2572 :group 'org-tags
2573 :type '(repeat (string :tag "Tag")))
2575 (defun org-tag-inherit-p (tag)
2576 "Check if TAG is one that should be inherited."
2577 (cond
2578 ((member tag org-tags-exclude-from-inheritance) nil)
2579 ((eq org-use-tag-inheritance t) t)
2580 ((not org-use-tag-inheritance) nil)
2581 ((stringp org-use-tag-inheritance)
2582 (string-match org-use-tag-inheritance tag))
2583 ((listp org-use-tag-inheritance)
2584 (member tag org-use-tag-inheritance))
2585 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2587 (defcustom org-tags-match-list-sublevels t
2588 "Non-nil means list also sublevels of headlines matching a search.
2589 This variable applies to tags/property searches, and also to stuck
2590 projects because this search is based on a tags match as well.
2592 When set to the symbol `indented', sublevels are indented with
2593 leading dots.
2595 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2596 the sublevels of a headline matching a tag search often also match
2597 the same search. Listing all of them can create very long lists.
2598 Setting this variable to nil causes subtrees of a match to be skipped.
2600 This variable is semi-obsolete and probably should always be true. It
2601 is better to limit inheritance to certain tags using the variables
2602 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2603 :group 'org-tags
2604 :type '(choice
2605 (const :tag "No, don't list them" nil)
2606 (const :tag "Yes, do list them" t)
2607 (const :tag "List them, indented with leading dots" indented)))
2609 (defcustom org-tags-sort-function nil
2610 "When set, tags are sorted using this function as a comparator"
2611 :group 'org-tags
2612 :type '(choice
2613 (const :tag "No sorting" nil)
2614 (const :tag "Alphabetical" string<)
2615 (const :tag "Reverse alphabetical" string>)
2616 (function :tag "Custom function" nil)))
2618 (defvar org-tags-history nil
2619 "History of minibuffer reads for tags.")
2620 (defvar org-last-tags-completion-table nil
2621 "The last used completion table for tags.")
2622 (defvar org-after-tags-change-hook nil
2623 "Hook that is run after the tags in a line have changed.")
2625 (defgroup org-properties nil
2626 "Options concerning properties in Org-mode."
2627 :tag "Org Properties"
2628 :group 'org)
2630 (defcustom org-property-format "%-10s %s"
2631 "How property key/value pairs should be formatted by `indent-line'.
2632 When `indent-line' hits a property definition, it will format the line
2633 according to this format, mainly to make sure that the values are
2634 lined-up with respect to each other."
2635 :group 'org-properties
2636 :type 'string)
2638 (defcustom org-use-property-inheritance nil
2639 "Non-nil means properties apply also for sublevels.
2641 This setting is chiefly used during property searches. Turning it on can
2642 cause significant overhead when doing a search, which is why it is not
2643 on by default.
2645 When nil, only the properties directly given in the current entry count.
2646 When t, every property is inherited. The value may also be a list of
2647 properties that should have inheritance, or a regular expression matching
2648 properties that should be inherited.
2650 However, note that some special properties use inheritance under special
2651 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2652 and the properties ending in \"_ALL\" when they are used as descriptor
2653 for valid values of a property.
2655 Note for programmers:
2656 When querying an entry with `org-entry-get', you can control if inheritance
2657 should be used. By default, `org-entry-get' looks only at the local
2658 properties. You can request inheritance by setting the inherit argument
2659 to t (to force inheritance) or to `selective' (to respect the setting
2660 in this variable)."
2661 :group 'org-properties
2662 :type '(choice
2663 (const :tag "Not" nil)
2664 (const :tag "Always" t)
2665 (repeat :tag "Specific properties" (string :tag "Property"))
2666 (regexp :tag "Properties matched by regexp")))
2668 (defun org-property-inherit-p (property)
2669 "Check if PROPERTY is one that should be inherited."
2670 (cond
2671 ((eq org-use-property-inheritance t) t)
2672 ((not org-use-property-inheritance) nil)
2673 ((stringp org-use-property-inheritance)
2674 (string-match org-use-property-inheritance property))
2675 ((listp org-use-property-inheritance)
2676 (member property org-use-property-inheritance))
2677 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2679 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2680 "The default column format, if no other format has been defined.
2681 This variable can be set on the per-file basis by inserting a line
2683 #+COLUMNS: %25ITEM ....."
2684 :group 'org-properties
2685 :type 'string)
2687 (defcustom org-columns-ellipses ".."
2688 "The ellipses to be used when a field in column view is truncated.
2689 When this is the empty string, as many characters as possible are shown,
2690 but then there will be no visual indication that the field has been truncated.
2691 When this is a string of length N, the last N characters of a truncated
2692 field are replaced by this string. If the column is narrower than the
2693 ellipses string, only part of the ellipses string will be shown."
2694 :group 'org-properties
2695 :type 'string)
2697 (defcustom org-columns-modify-value-for-display-function nil
2698 "Function that modifies values for display in column view.
2699 For example, it can be used to cut out a certain part from a time stamp.
2700 The function must take 2 arguments:
2702 column-title The title of the column (*not* the property name)
2703 value The value that should be modified.
2705 The function should return the value that should be displayed,
2706 or nil if the normal value should be used."
2707 :group 'org-properties
2708 :type 'function)
2710 (defcustom org-effort-property "Effort"
2711 "The property that is being used to keep track of effort estimates.
2712 Effort estimates given in this property need to have the format H:MM."
2713 :group 'org-properties
2714 :group 'org-progress
2715 :type '(string :tag "Property"))
2717 (defconst org-global-properties-fixed
2718 '(("VISIBILITY_ALL" . "folded children content all")
2719 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2720 "List of property/value pairs that can be inherited by any entry.
2722 These are fixed values, for the preset properties. The user variable
2723 that can be used to add to this list is `org-global-properties'.
2725 The entries in this list are cons cells where the car is a property
2726 name and cdr is a string with the value. If the value represents
2727 multiple items like an \"_ALL\" property, separate the items by
2728 spaces.")
2730 (defcustom org-global-properties nil
2731 "List of property/value pairs that can be inherited by any entry.
2733 This list will be combined with the constant `org-global-properties-fixed'.
2735 The entries in this list are cons cells where the car is a property
2736 name and cdr is a string with the value.
2738 You can set buffer-local values for the same purpose in the variable
2739 `org-file-properties' this by adding lines like
2741 #+PROPERTY: NAME VALUE"
2742 :group 'org-properties
2743 :type '(repeat
2744 (cons (string :tag "Property")
2745 (string :tag "Value"))))
2747 (defvar org-file-properties nil
2748 "List of property/value pairs that can be inherited by any entry.
2749 Valid for the current buffer.
2750 This variable is populated from #+PROPERTY lines.")
2751 (make-variable-buffer-local 'org-file-properties)
2753 (defgroup org-agenda nil
2754 "Options concerning agenda views in Org-mode."
2755 :tag "Org Agenda"
2756 :group 'org)
2758 (defvar org-category nil
2759 "Variable used by org files to set a category for agenda display.
2760 Such files should use a file variable to set it, for example
2762 # -*- mode: org; org-category: \"ELisp\"
2764 or contain a special line
2766 #+CATEGORY: ELisp
2768 If the file does not specify a category, then file's base name
2769 is used instead.")
2770 (make-variable-buffer-local 'org-category)
2771 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2773 (defcustom org-agenda-files nil
2774 "The files to be used for agenda display.
2775 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2776 \\[org-remove-file]. You can also use customize to edit the list.
2778 If an entry is a directory, all files in that directory that are matched by
2779 `org-agenda-file-regexp' will be part of the file list.
2781 If the value of the variable is not a list but a single file name, then
2782 the list of agenda files is actually stored and maintained in that file, one
2783 agenda file per line. In this file paths can be given relative to
2784 `org-directory'. Tilde expansion and environment variable substitution
2785 are also made."
2786 :group 'org-agenda
2787 :type '(choice
2788 (repeat :tag "List of files and directories" file)
2789 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2791 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2792 "Regular expression to match files for `org-agenda-files'.
2793 If any element in the list in that variable contains a directory instead
2794 of a normal file, all files in that directory that are matched by this
2795 regular expression will be included."
2796 :group 'org-agenda
2797 :type 'regexp)
2799 (defcustom org-agenda-text-search-extra-files nil
2800 "List of extra files to be searched by text search commands.
2801 These files will be search in addition to the agenda files by the
2802 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2803 Note that these files will only be searched for text search commands,
2804 not for the other agenda views like todo lists, tag searches or the weekly
2805 agenda. This variable is intended to list notes and possibly archive files
2806 that should also be searched by these two commands.
2807 In fact, if the first element in the list is the symbol `agenda-archives',
2808 than all archive files of all agenda files will be added to the search
2809 scope."
2810 :group 'org-agenda
2811 :type '(set :greedy t
2812 (const :tag "Agenda Archives" agenda-archives)
2813 (repeat :inline t (file))))
2815 (if (fboundp 'defvaralias)
2816 (defvaralias 'org-agenda-multi-occur-extra-files
2817 'org-agenda-text-search-extra-files))
2819 (defcustom org-agenda-skip-unavailable-files nil
2820 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2821 A nil value means to remove them, after a query, from the list."
2822 :group 'org-agenda
2823 :type 'boolean)
2825 (defcustom org-calendar-to-agenda-key [?c]
2826 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2827 The command `org-calendar-goto-agenda' will be bound to this key. The
2828 default is the character `c' because then `c' can be used to switch back and
2829 forth between agenda and calendar."
2830 :group 'org-agenda
2831 :type 'sexp)
2833 (defcustom org-calendar-agenda-action-key [?k]
2834 "The key to be installed in `calendar-mode-map' for agenda-action.
2835 The command `org-agenda-action' will be bound to this key. The
2836 default is the character `k' because we use the same key in the agenda."
2837 :group 'org-agenda
2838 :type 'sexp)
2840 (defcustom org-calendar-insert-diary-entry-key [?i]
2841 "The key to be installed in `calendar-mode-map' for adding diary entries.
2842 This option is irrelevant until `org-agenda-diary-file' has been configured
2843 to point to an Org-mode file. When that is the case, the command
2844 `org-agenda-diary-entry' will be bound to the key given here, by default
2845 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
2846 if you want to continue doing this, you need to change this to a different
2847 key."
2848 :group 'org-agenda
2849 :type 'sexp)
2851 (defcustom org-agenda-diary-file 'diary-file
2852 "File to which to add new entries with the `i' key in agenda and calendar.
2853 When this is the symbol `diary-file', the functionality in the Emacs
2854 calendar will be used to add entries to the `diary-file'. But when this
2855 points to a file, `org-agenda-diary-entry' will be used instead."
2856 :group 'org-agenda
2857 :type '(choice
2858 (const :tag "The standard Emacs diary file" diary-file)
2859 (file :tag "Special Org file diary entries")))
2861 (eval-after-load "calendar"
2862 '(progn
2863 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2864 'org-calendar-goto-agenda)
2865 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2866 'org-agenda-action)
2867 (add-hook 'calendar-mode-hook
2868 (lambda ()
2869 (unless (eq org-agenda-diary-file 'diary-file)
2870 (define-key calendar-mode-map
2871 org-calendar-insert-diary-entry-key
2872 'org-agenda-diary-entry))))))
2874 (defgroup org-latex nil
2875 "Options for embedding LaTeX code into Org-mode."
2876 :tag "Org LaTeX"
2877 :group 'org)
2879 (defcustom org-format-latex-options
2880 '(:foreground default :background default :scale 1.0
2881 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2882 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2883 "Options for creating images from LaTeX fragments.
2884 This is a property list with the following properties:
2885 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2886 `default' means use the foreground of the default face.
2887 :background the background color, or \"Transparent\".
2888 `default' means use the background of the default face.
2889 :scale a scaling factor for the size of the images.
2890 :html-foreground, :html-background, :html-scale
2891 the same numbers for HTML export.
2892 :matchers a list indicating which matchers should be used to
2893 find LaTeX fragments. Valid members of this list are:
2894 \"begin\" find environments
2895 \"$1\" find single characters surrounded by $.$
2896 \"$\" find math expressions surrounded by $...$
2897 \"$$\" find math expressions surrounded by $$....$$
2898 \"\\(\" find math expressions surrounded by \\(...\\)
2899 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2900 :group 'org-latex
2901 :type 'plist)
2903 (defcustom org-format-latex-signal-error t
2904 "Non-nil means signal an error when image creation of LaTeX snippets fails.
2905 When nil, just push out a message."
2906 :group 'org-latex
2907 :type 'boolean)
2909 (defcustom org-format-latex-header "\\documentclass{article}
2910 \\usepackage{amssymb}
2911 \\usepackage[usenames]{color}
2912 \\usepackage{amsmath}
2913 \\usepackage{latexsym}
2914 \\usepackage[mathscr]{eucal}
2915 \\pagestyle{empty} % do not remove
2916 % The settings below are copied from fullpage.sty
2917 \\setlength{\\textwidth}{\\paperwidth}
2918 \\addtolength{\\textwidth}{-3cm}
2919 \\setlength{\\oddsidemargin}{1.5cm}
2920 \\addtolength{\\oddsidemargin}{-2.54cm}
2921 \\setlength{\\evensidemargin}{\\oddsidemargin}
2922 \\setlength{\\textheight}{\\paperheight}
2923 \\addtolength{\\textheight}{-\\headheight}
2924 \\addtolength{\\textheight}{-\\headsep}
2925 \\addtolength{\\textheight}{-\\footskip}
2926 \\addtolength{\\textheight}{-3cm}
2927 \\setlength{\\topmargin}{1.5cm}
2928 \\addtolength{\\topmargin}{-2.54cm}"
2929 "The document header used for processing LaTeX fragments.
2930 It is imperative that this header make sure that no page number
2931 appears on the page."
2932 :group 'org-latex
2933 :type 'string)
2935 (defvar org-format-latex-header-extra nil)
2937 ;; The following variable is defined here because is it also used
2938 ;; when formatting latex fragments. Originally it was part of the
2939 ;; LaTeX exporter, which is why the name includes "export".
2940 (defcustom org-export-latex-packages-alist nil
2941 "Alist of packages to be inserted in the header.
2942 Each cell is of the format \( \"option\" . \"package\" \)."
2943 :group 'org-export-latex
2944 :type '(repeat
2945 (list
2946 (string :tag "option")
2947 (string :tag "package"))))
2949 (defgroup org-font-lock nil
2950 "Font-lock settings for highlighting in Org-mode."
2951 :tag "Org Font Lock"
2952 :group 'org)
2954 (defcustom org-level-color-stars-only nil
2955 "Non-nil means fontify only the stars in each headline.
2956 When nil, the entire headline is fontified.
2957 Changing it requires restart of `font-lock-mode' to become effective
2958 also in regions already fontified."
2959 :group 'org-font-lock
2960 :type 'boolean)
2962 (defcustom org-hide-leading-stars nil
2963 "Non-nil means hide the first N-1 stars in a headline.
2964 This works by using the face `org-hide' for these stars. This
2965 face is white for a light background, and black for a dark
2966 background. You may have to customize the face `org-hide' to
2967 make this work.
2968 Changing it requires restart of `font-lock-mode' to become effective
2969 also in regions already fontified.
2970 You may also set this on a per-file basis by adding one of the following
2971 lines to the buffer:
2973 #+STARTUP: hidestars
2974 #+STARTUP: showstars"
2975 :group 'org-font-lock
2976 :type 'boolean)
2978 (defcustom org-hidden-keywords nil
2979 "List of keywords that should be hidden when typed in the org buffer.
2980 For example, add #+TITLE to this list in order to make the
2981 document title appear in the buffer without the initial #+TITLE:
2982 keyword."
2983 :group 'org-font-lock
2984 :type '(set (const :tag "#+AUTHOR" author)
2985 (const :tag "#+DATE" date)
2986 (const :tag "#+EMAIL" email)
2987 (const :tag "#+TITLE" title)))
2989 (defcustom org-fontify-done-headline nil
2990 "Non-nil means change the face of a headline if it is marked DONE.
2991 Normally, only the TODO/DONE keyword indicates the state of a headline.
2992 When this is non-nil, the headline after the keyword is set to the
2993 `org-headline-done' as an additional indication."
2994 :group 'org-font-lock
2995 :type 'boolean)
2997 (defcustom org-fontify-emphasized-text t
2998 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2999 Changing this variable requires a restart of Emacs to take effect."
3000 :group 'org-font-lock
3001 :type 'boolean)
3003 (defcustom org-fontify-whole-heading-line nil
3004 "Non-nil means fontify the whole line for headings.
3005 This is useful when setting a background color for the
3006 org-level-* faces."
3007 :group 'org-font-lock
3008 :type 'boolean)
3010 (defcustom org-highlight-latex-fragments-and-specials nil
3011 "Non-nil means fontify what is treated specially by the exporters."
3012 :group 'org-font-lock
3013 :type 'boolean)
3015 (defcustom org-hide-emphasis-markers nil
3016 "Non-nil mean font-lock should hide the emphasis marker characters."
3017 :group 'org-font-lock
3018 :type 'boolean)
3020 (defvar org-emph-re nil
3021 "Regular expression for matching emphasis.")
3022 (defvar org-verbatim-re nil
3023 "Regular expression for matching verbatim text.")
3024 (defvar org-emphasis-regexp-components) ; defined just below
3025 (defvar org-emphasis-alist) ; defined just below
3026 (defun org-set-emph-re (var val)
3027 "Set variable and compute the emphasis regular expression."
3028 (set var val)
3029 (when (and (boundp 'org-emphasis-alist)
3030 (boundp 'org-emphasis-regexp-components)
3031 org-emphasis-alist org-emphasis-regexp-components)
3032 (let* ((e org-emphasis-regexp-components)
3033 (pre (car e))
3034 (post (nth 1 e))
3035 (border (nth 2 e))
3036 (body (nth 3 e))
3037 (nl (nth 4 e))
3038 (body1 (concat body "*?"))
3039 (markers (mapconcat 'car org-emphasis-alist ""))
3040 (vmarkers (mapconcat
3041 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3042 org-emphasis-alist "")))
3043 ;; make sure special characters appear at the right position in the class
3044 (if (string-match "\\^" markers)
3045 (setq markers (concat (replace-match "" t t markers) "^")))
3046 (if (string-match "-" markers)
3047 (setq markers (concat (replace-match "" t t markers) "-")))
3048 (if (string-match "\\^" vmarkers)
3049 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3050 (if (string-match "-" vmarkers)
3051 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3052 (if (> nl 0)
3053 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3054 (int-to-string nl) "\\}")))
3055 ;; Make the regexp
3056 (setq org-emph-re
3057 (concat "\\([" pre "]\\|^\\)"
3058 "\\("
3059 "\\([" markers "]\\)"
3060 "\\("
3061 "[^" border "]\\|"
3062 "[^" border "]"
3063 body1
3064 "[^" border "]"
3065 "\\)"
3066 "\\3\\)"
3067 "\\([" post "]\\|$\\)"))
3068 (setq org-verbatim-re
3069 (concat "\\([" pre "]\\|^\\)"
3070 "\\("
3071 "\\([" vmarkers "]\\)"
3072 "\\("
3073 "[^" border "]\\|"
3074 "[^" border "]"
3075 body1
3076 "[^" border "]"
3077 "\\)"
3078 "\\3\\)"
3079 "\\([" post "]\\|$\\)")))))
3081 (defcustom org-emphasis-regexp-components
3082 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3083 "Components used to build the regular expression for emphasis.
3084 This is a list with 6 entries. Terminology: In an emphasis string
3085 like \" *strong word* \", we call the initial space PREMATCH, the final
3086 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3087 and \"trong wor\" is the body. The different components in this variable
3088 specify what is allowed/forbidden in each part:
3090 pre Chars allowed as prematch. Beginning of line will be allowed too.
3091 post Chars allowed as postmatch. End of line will be allowed too.
3092 border The chars *forbidden* as border characters.
3093 body-regexp A regexp like \".\" to match a body character. Don't use
3094 non-shy groups here, and don't allow newline here.
3095 newline The maximum number of newlines allowed in an emphasis exp.
3097 Use customize to modify this, or restart Emacs after changing it."
3098 :group 'org-font-lock
3099 :set 'org-set-emph-re
3100 :type '(list
3101 (sexp :tag "Allowed chars in pre ")
3102 (sexp :tag "Allowed chars in post ")
3103 (sexp :tag "Forbidden chars in border ")
3104 (sexp :tag "Regexp for body ")
3105 (integer :tag "number of newlines allowed")
3106 (option (boolean :tag "Please ignore this button"))))
3108 (defcustom org-emphasis-alist
3109 `(("*" bold "<b>" "</b>")
3110 ("/" italic "<i>" "</i>")
3111 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3112 ("=" org-code "<code>" "</code>" verbatim)
3113 ("~" org-verbatim "<code>" "</code>" verbatim)
3114 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3115 "<del>" "</del>")
3117 "Special syntax for emphasized text.
3118 Text starting and ending with a special character will be emphasized, for
3119 example *bold*, _underlined_ and /italic/. This variable sets the marker
3120 characters, the face to be used by font-lock for highlighting in Org-mode
3121 Emacs buffers, and the HTML tags to be used for this.
3122 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3123 Use customize to modify this, or restart Emacs after changing it."
3124 :group 'org-font-lock
3125 :set 'org-set-emph-re
3126 :type '(repeat
3127 (list
3128 (string :tag "Marker character")
3129 (choice
3130 (face :tag "Font-lock-face")
3131 (plist :tag "Face property list"))
3132 (string :tag "HTML start tag")
3133 (string :tag "HTML end tag")
3134 (option (const verbatim)))))
3136 (defvar org-protecting-blocks
3137 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3138 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3139 This is needed for font-lock setup.")
3141 ;;; Miscellaneous options
3143 (defgroup org-completion nil
3144 "Completion in Org-mode."
3145 :tag "Org Completion"
3146 :group 'org)
3148 (defcustom org-completion-use-ido nil
3149 "Non-nil means use ido completion wherever possible.
3150 Note that `ido-mode' must be active for this variable to be relevant.
3151 If you decide to turn this variable on, you might well want to turn off
3152 `org-outline-path-complete-in-steps'.
3153 See also `org-completion-use-iswitchb'."
3154 :group 'org-completion
3155 :type 'boolean)
3157 (defcustom org-completion-use-iswitchb nil
3158 "Non-nil means use iswitchb completion wherever possible.
3159 Note that `iswitchb-mode' must be active for this variable to be relevant.
3160 If you decide to turn this variable on, you might well want to turn off
3161 `org-outline-path-complete-in-steps'.
3162 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3163 :group 'org-completion
3164 :type 'boolean)
3166 (defcustom org-completion-fallback-command 'hippie-expand
3167 "The expansion command called by \\[org-complete] in normal context.
3168 Normal means no org-mode-specific context."
3169 :group 'org-completion
3170 :type 'function)
3172 ;;; Functions and variables from their packages
3173 ;; Declared here to avoid compiler warnings
3175 ;; XEmacs only
3176 (defvar outline-mode-menu-heading)
3177 (defvar outline-mode-menu-show)
3178 (defvar outline-mode-menu-hide)
3179 (defvar zmacs-regions) ; XEmacs regions
3181 ;; Emacs only
3182 (defvar mark-active)
3184 ;; Various packages
3185 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3186 (declare-function calendar-forward-day "cal-move" (arg))
3187 (declare-function calendar-goto-date "cal-move" (date))
3188 (declare-function calendar-goto-today "cal-move" ())
3189 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3190 (defvar calc-embedded-close-formula)
3191 (defvar calc-embedded-open-formula)
3192 (declare-function cdlatex-tab "ext:cdlatex" ())
3193 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3194 (defvar font-lock-unfontify-region-function)
3195 (declare-function iswitchb-read-buffer "iswitchb"
3196 (prompt &optional default require-match start matches-set))
3197 (defvar iswitchb-temp-buflist)
3198 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3199 (defvar org-agenda-tags-todo-honor-ignore-options)
3200 (declare-function org-agenda-skip "org-agenda" ())
3201 (declare-function
3202 org-format-agenda-item "org-agenda"
3203 (extra txt &optional category tags dotime noprefix remove-re habitp))
3204 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3205 (declare-function org-agenda-change-all-lines "org-agenda"
3206 (newhead hdmarker &optional fixface just-this))
3207 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3208 (declare-function org-agenda-maybe-redo "org-agenda" ())
3209 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3210 (beg end))
3211 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3212 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3213 "org-agenda" (&optional end))
3214 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3215 (declare-function org-indent-mode "org-indent" (&optional arg))
3216 (declare-function parse-time-string "parse-time" (string))
3217 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3218 (defvar remember-data-file)
3219 (defvar texmathp-why)
3220 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3221 (declare-function table--at-cell-p "table" (position &optional object at-column))
3223 (defvar w3m-current-url)
3224 (defvar w3m-current-title)
3226 (defvar org-latex-regexps)
3228 ;;; Autoload and prepare some org modules
3230 ;; Some table stuff that needs to be defined here, because it is used
3231 ;; by the functions setting up org-mode or checking for table context.
3233 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3234 "Detects an org-type or table-type table.")
3235 (defconst org-table-line-regexp "^[ \t]*|"
3236 "Detects an org-type table line.")
3237 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3238 "Detects an org-type table line.")
3239 (defconst org-table-hline-regexp "^[ \t]*|-"
3240 "Detects an org-type table hline.")
3241 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3242 "Detects a table-type table hline.")
3243 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3244 "Searching from within a table (any type) this finds the first line
3245 outside the table.")
3247 ;; Autoload the functions in org-table.el that are needed by functions here.
3249 (eval-and-compile
3250 (org-autoload "org-table"
3251 '(org-table-align org-table-begin org-table-blank-field
3252 org-table-convert org-table-convert-region org-table-copy-down
3253 org-table-copy-region org-table-create
3254 org-table-create-or-convert-from-region
3255 org-table-create-with-table.el org-table-current-dline
3256 org-table-cut-region org-table-delete-column org-table-edit-field
3257 org-table-edit-formulas org-table-end org-table-eval-formula
3258 org-table-export org-table-field-info
3259 org-table-get-stored-formulas org-table-goto-column
3260 org-table-hline-and-move org-table-import org-table-insert-column
3261 org-table-insert-hline org-table-insert-row org-table-iterate
3262 org-table-justify-field-maybe org-table-kill-row
3263 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3264 org-table-move-column org-table-move-column-left
3265 org-table-move-column-right org-table-move-row
3266 org-table-move-row-down org-table-move-row-up
3267 org-table-next-field org-table-next-row org-table-paste-rectangle
3268 org-table-previous-field org-table-recalculate
3269 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3270 org-table-toggle-coordinate-overlays
3271 org-table-toggle-formula-debugger org-table-wrap-region
3272 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
3274 (defun org-at-table-p (&optional table-type)
3275 "Return t if the cursor is inside an org-type table.
3276 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3277 (if org-enable-table-editor
3278 (save-excursion
3279 (beginning-of-line 1)
3280 (looking-at (if table-type org-table-any-line-regexp
3281 org-table-line-regexp)))
3282 nil))
3283 (defsubst org-table-p () (org-at-table-p))
3285 (defun org-at-table.el-p ()
3286 "Return t if and only if we are at a table.el table."
3287 (and (org-at-table-p 'any)
3288 (save-excursion
3289 (goto-char (org-table-begin 'any))
3290 (looking-at org-table1-hline-regexp))))
3291 (defun org-table-recognize-table.el ()
3292 "If there is a table.el table nearby, recognize it and move into it."
3293 (if org-table-tab-recognizes-table.el
3294 (if (org-at-table.el-p)
3295 (progn
3296 (beginning-of-line 1)
3297 (if (looking-at org-table-dataline-regexp)
3299 (if (looking-at org-table1-hline-regexp)
3300 (progn
3301 (beginning-of-line 2)
3302 (if (looking-at org-table-any-border-regexp)
3303 (beginning-of-line -1)))))
3304 (if (re-search-forward "|" (org-table-end t) t)
3305 (progn
3306 (require 'table)
3307 (if (table--at-cell-p (point))
3309 (message "recognizing table.el table...")
3310 (table-recognize-table)
3311 (message "recognizing table.el table...done")))
3312 (error "This should not happen..."))
3314 nil)
3315 nil))
3317 (defun org-at-table-hline-p ()
3318 "Return t if the cursor is inside a hline in a table."
3319 (if org-enable-table-editor
3320 (save-excursion
3321 (beginning-of-line 1)
3322 (looking-at org-table-hline-regexp))
3323 nil))
3325 (defvar org-table-clean-did-remove-column nil)
3327 (defun org-table-map-tables (function)
3328 "Apply FUNCTION to the start of all tables in the buffer."
3329 (save-excursion
3330 (save-restriction
3331 (widen)
3332 (goto-char (point-min))
3333 (while (re-search-forward org-table-any-line-regexp nil t)
3334 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
3335 (beginning-of-line 1)
3336 (when (looking-at org-table-line-regexp)
3337 (save-excursion (funcall function))
3338 (or (looking-at org-table-line-regexp)
3339 (forward-char 1)))
3340 (re-search-forward org-table-any-border-regexp nil 1))))
3341 (message "Mapping tables: done"))
3343 ;; Declare and autoload functions from org-exp.el & Co
3345 (declare-function org-default-export-plist "org-exp")
3346 (declare-function org-infile-export-plist "org-exp")
3347 (declare-function org-get-current-options "org-exp")
3348 (eval-and-compile
3349 (org-autoload "org-exp"
3350 '(org-export org-export-visible
3351 org-insert-export-options-template
3352 org-table-clean-before-export))
3353 (org-autoload "org-ascii"
3354 '(org-export-as-ascii org-export-ascii-preprocess
3355 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3356 org-export-region-as-ascii))
3357 (org-autoload "org-latex"
3358 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3359 org-replace-region-by-latex org-export-region-as-latex
3360 org-export-as-latex org-export-as-pdf
3361 org-export-as-pdf-and-open))
3362 (org-autoload "org-html"
3363 '(org-export-as-html-and-open
3364 org-export-as-html-batch org-export-as-html-to-buffer
3365 org-replace-region-by-html org-export-region-as-html
3366 org-export-as-html))
3367 (org-autoload "org-docbook"
3368 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3369 org-replace-region-by-docbook org-export-region-as-docbook
3370 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3371 org-export-as-docbook))
3372 (org-autoload "org-icalendar"
3373 '(org-export-icalendar-this-file
3374 org-export-icalendar-all-agenda-files
3375 org-export-icalendar-combine-agenda-files))
3376 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3377 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3379 ;; Declare and autoload functions from org-agenda.el
3381 (eval-and-compile
3382 (org-autoload "org-agenda"
3383 '(org-agenda org-agenda-list org-search-view
3384 org-todo-list org-tags-view org-agenda-list-stuck-projects
3385 org-diary org-agenda-to-appt
3386 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3388 ;; Autoload org-remember
3390 (eval-and-compile
3391 (org-autoload "org-remember"
3392 '(org-remember-insinuate org-remember-annotation
3393 org-remember-apply-template org-remember org-remember-handler)))
3395 ;; Autoload org-clock.el
3398 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3399 (beg end))
3400 (declare-function org-clock-update-mode-line "org-clock" ())
3401 (declare-function org-resolve-clocks "org-clock"
3402 (&optional also-non-dangling-p prompt last-valid))
3403 (defvar org-clock-start-time)
3404 (defvar org-clock-marker (make-marker)
3405 "Marker recording the last clock-in.")
3406 (defvar org-clock-hd-marker (make-marker)
3407 "Marker recording the last clock-in, but the headline position.")
3408 (defvar org-clock-heading ""
3409 "The heading of the current clock entry.")
3410 (defun org-clock-is-active ()
3411 "Return non-nil if clock is currently running.
3412 The return value is actually the clock marker."
3413 (marker-buffer org-clock-marker))
3415 (eval-and-compile
3416 (org-autoload
3417 "org-clock"
3418 '(org-clock-in org-clock-out org-clock-cancel
3419 org-clock-goto org-clock-sum org-clock-display
3420 org-clock-remove-overlays org-clock-report
3421 org-clocktable-shift org-dblock-write:clocktable
3422 org-get-clocktable org-resolve-clocks)))
3424 (defun org-clock-update-time-maybe ()
3425 "If this is a CLOCK line, update it and return t.
3426 Otherwise, return nil."
3427 (interactive)
3428 (save-excursion
3429 (beginning-of-line 1)
3430 (skip-chars-forward " \t")
3431 (when (looking-at org-clock-string)
3432 (let ((re (concat "[ \t]*" org-clock-string
3433 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3434 "\\([ \t]*=>.*\\)?\\)?"))
3435 ts te h m s neg)
3436 (cond
3437 ((not (looking-at re))
3438 nil)
3439 ((not (match-end 2))
3440 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3441 (> org-clock-marker (point))
3442 (<= org-clock-marker (point-at-eol)))
3443 ;; The clock is running here
3444 (setq org-clock-start-time
3445 (apply 'encode-time
3446 (org-parse-time-string (match-string 1))))
3447 (org-clock-update-mode-line)))
3449 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3450 (end-of-line 1)
3451 (setq ts (match-string 1)
3452 te (match-string 3))
3453 (setq s (- (org-float-time
3454 (apply 'encode-time (org-parse-time-string te)))
3455 (org-float-time
3456 (apply 'encode-time (org-parse-time-string ts))))
3457 neg (< s 0)
3458 s (abs s)
3459 h (floor (/ s 3600))
3460 s (- s (* 3600 h))
3461 m (floor (/ s 60))
3462 s (- s (* 60 s)))
3463 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3464 t))))))
3466 (defun org-check-running-clock ()
3467 "Check if the current buffer contains the running clock.
3468 If yes, offer to stop it and to save the buffer with the changes."
3469 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3470 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3471 (buffer-name))))
3472 (org-clock-out)
3473 (when (y-or-n-p "Save changed buffer?")
3474 (save-buffer))))
3476 (defun org-clocktable-try-shift (dir n)
3477 "Check if this line starts a clock table, if yes, shift the time block."
3478 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3479 (org-clocktable-shift dir n)))
3481 ;; Autoload org-timer.el
3483 (eval-and-compile
3484 (org-autoload
3485 "org-timer"
3486 '(org-timer-start org-timer org-timer-item
3487 org-timer-change-times-in-region
3488 org-timer-set-timer
3489 org-timer-reset-timers
3490 org-timer-show-remaining-time)))
3492 ;; Autoload org-feed.el
3494 (eval-and-compile
3495 (org-autoload
3496 "org-feed"
3497 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3500 ;; Autoload org-indent.el
3502 ;; Define the variable already here, to make sure we have it.
3503 (defvar org-indent-mode nil
3504 "Non-nil if Org-Indent mode is enabled.
3505 Use the command `org-indent-mode' to change this variable.")
3507 (eval-and-compile
3508 (org-autoload
3509 "org-indent"
3510 '(org-indent-mode)))
3512 ;; Autoload org-mobile.el
3514 (eval-and-compile
3515 (org-autoload
3516 "org-mobile"
3517 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3519 ;; Autoload archiving code
3520 ;; The stuff that is needed for cycling and tags has to be defined here.
3522 (defgroup org-archive nil
3523 "Options concerning archiving in Org-mode."
3524 :tag "Org Archive"
3525 :group 'org-structure)
3527 (defcustom org-archive-location "%s_archive::"
3528 "The location where subtrees should be archived.
3530 The value of this variable is a string, consisting of two parts,
3531 separated by a double-colon. The first part is a filename and
3532 the second part is a headline.
3534 When the filename is omitted, archiving happens in the same file.
3535 %s in the filename will be replaced by the current file
3536 name (without the directory part). Archiving to a different file
3537 is useful to keep archived entries from contributing to the
3538 Org-mode Agenda.
3540 The archived entries will be filed as subtrees of the specified
3541 headline. When the headline is omitted, the subtrees are simply
3542 filed away at the end of the file, as top-level entries. Also in
3543 the heading you can use %s to represent the file name, this can be
3544 useful when using the same archive for a number of different files.
3546 Here are a few examples:
3547 \"%s_archive::\"
3548 If the current file is Projects.org, archive in file
3549 Projects.org_archive, as top-level trees. This is the default.
3551 \"::* Archived Tasks\"
3552 Archive in the current file, under the top-level headline
3553 \"* Archived Tasks\".
3555 \"~/org/archive.org::\"
3556 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3558 \"~/org/archive.org::From %s\"
3559 Archive in file ~/org/archive.org (absolute path), under headlines
3560 \"From FILENAME\" where file name is the current file name.
3562 \"basement::** Finished Tasks\"
3563 Archive in file ./basement (relative path), as level 3 trees
3564 below the level 2 heading \"** Finished Tasks\".
3566 You may set this option on a per-file basis by adding to the buffer a
3567 line like
3569 #+ARCHIVE: basement::** Finished Tasks
3571 You may also define it locally for a subtree by setting an ARCHIVE property
3572 in the entry. If such a property is found in an entry, or anywhere up
3573 the hierarchy, it will be used."
3574 :group 'org-archive
3575 :type 'string)
3577 (defcustom org-archive-tag "ARCHIVE"
3578 "The tag that marks a subtree as archived.
3579 An archived subtree does not open during visibility cycling, and does
3580 not contribute to the agenda listings.
3581 After changing this, font-lock must be restarted in the relevant buffers to
3582 get the proper fontification."
3583 :group 'org-archive
3584 :group 'org-keywords
3585 :type 'string)
3587 (defcustom org-agenda-skip-archived-trees t
3588 "Non-nil means the agenda will skip any items located in archived trees.
3589 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3590 variable is no longer recommended, you should leave it at the value t.
3591 Instead, use the key `v' to cycle the archives-mode in the agenda."
3592 :group 'org-archive
3593 :group 'org-agenda-skip
3594 :type 'boolean)
3596 (defcustom org-columns-skip-archived-trees t
3597 "Non-nil means ignore archived trees when creating column view."
3598 :group 'org-archive
3599 :group 'org-properties
3600 :type 'boolean)
3602 (defcustom org-cycle-open-archived-trees nil
3603 "Non-nil means `org-cycle' will open archived trees.
3604 An archived tree is a tree marked with the tag ARCHIVE.
3605 When nil, archived trees will stay folded. You can still open them with
3606 normal outline commands like `show-all', but not with the cycling commands."
3607 :group 'org-archive
3608 :group 'org-cycle
3609 :type 'boolean)
3611 (defcustom org-sparse-tree-open-archived-trees nil
3612 "Non-nil means sparse tree construction shows matches in archived trees.
3613 When nil, matches in these trees are highlighted, but the trees are kept in
3614 collapsed state."
3615 :group 'org-archive
3616 :group 'org-sparse-trees
3617 :type 'boolean)
3619 (defun org-cycle-hide-archived-subtrees (state)
3620 "Re-hide all archived subtrees after a visibility state change."
3621 (when (and (not org-cycle-open-archived-trees)
3622 (not (memq state '(overview folded))))
3623 (save-excursion
3624 (let* ((globalp (memq state '(contents all)))
3625 (beg (if globalp (point-min) (point)))
3626 (end (if globalp (point-max) (org-end-of-subtree t))))
3627 (org-hide-archived-subtrees beg end)
3628 (goto-char beg)
3629 (if (looking-at (concat ".*:" org-archive-tag ":"))
3630 (message "%s" (substitute-command-keys
3631 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3633 (defun org-force-cycle-archived ()
3634 "Cycle subtree even if it is archived."
3635 (interactive)
3636 (setq this-command 'org-cycle)
3637 (let ((org-cycle-open-archived-trees t))
3638 (call-interactively 'org-cycle)))
3640 (defun org-hide-archived-subtrees (beg end)
3641 "Re-hide all archived subtrees after a visibility state change."
3642 (save-excursion
3643 (let* ((re (concat ":" org-archive-tag ":")))
3644 (goto-char beg)
3645 (while (re-search-forward re end t)
3646 (when (org-on-heading-p)
3647 (org-flag-subtree t)
3648 (org-end-of-subtree t))))))
3650 (defun org-flag-subtree (flag)
3651 (save-excursion
3652 (org-back-to-heading t)
3653 (outline-end-of-heading)
3654 (outline-flag-region (point)
3655 (progn (org-end-of-subtree t) (point))
3656 flag)))
3658 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3660 (eval-and-compile
3661 (org-autoload "org-archive"
3662 '(org-add-archive-files org-archive-subtree
3663 org-archive-to-archive-sibling org-toggle-archive-tag
3664 org-archive-subtree-default
3665 org-archive-subtree-default-with-confirmation)))
3667 ;; Autoload Column View Code
3669 (declare-function org-columns-number-to-string "org-colview")
3670 (declare-function org-columns-get-format-and-top-level "org-colview")
3671 (declare-function org-columns-compute "org-colview")
3673 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3674 '(org-columns-number-to-string org-columns-get-format-and-top-level
3675 org-columns-compute org-agenda-columns org-columns-remove-overlays
3676 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3678 ;; Autoload ID code
3680 (declare-function org-id-store-link "org-id")
3681 (declare-function org-id-locations-load "org-id")
3682 (declare-function org-id-locations-save "org-id")
3683 (defvar org-id-track-globally)
3684 (org-autoload "org-id"
3685 '(org-id-get-create org-id-new org-id-copy org-id-get
3686 org-id-get-with-outline-path-completion
3687 org-id-get-with-outline-drilling
3688 org-id-goto org-id-find org-id-store-link))
3690 ;; Autoload Plotting Code
3692 (org-autoload "org-plot"
3693 '(org-plot/gnuplot))
3695 ;;; Variables for pre-computed regular expressions, all buffer local
3697 (defvar org-drawer-regexp nil
3698 "Matches first line of a hidden block.")
3699 (make-variable-buffer-local 'org-drawer-regexp)
3700 (defvar org-todo-regexp nil
3701 "Matches any of the TODO state keywords.")
3702 (make-variable-buffer-local 'org-todo-regexp)
3703 (defvar org-not-done-regexp nil
3704 "Matches any of the TODO state keywords except the last one.")
3705 (make-variable-buffer-local 'org-not-done-regexp)
3706 (defvar org-not-done-heading-regexp nil
3707 "Matches a TODO headline that is not done.")
3708 (make-variable-buffer-local 'org-not-done-regexp)
3709 (defvar org-todo-line-regexp nil
3710 "Matches a headline and puts TODO state into group 2 if present.")
3711 (make-variable-buffer-local 'org-todo-line-regexp)
3712 (defvar org-complex-heading-regexp nil
3713 "Matches a headline and puts everything into groups:
3714 group 1: the stars
3715 group 2: The todo keyword, maybe
3716 group 3: Priority cookie
3717 group 4: True headline
3718 group 5: Tags")
3719 (make-variable-buffer-local 'org-complex-heading-regexp)
3720 (defvar org-complex-heading-regexp-format nil)
3721 (make-variable-buffer-local 'org-complex-heading-regexp-format)
3722 (defvar org-todo-line-tags-regexp nil
3723 "Matches a headline and puts TODO state into group 2 if present.
3724 Also put tags into group 4 if tags are present.")
3725 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3726 (defvar org-nl-done-regexp nil
3727 "Matches newline followed by a headline with the DONE keyword.")
3728 (make-variable-buffer-local 'org-nl-done-regexp)
3729 (defvar org-looking-at-done-regexp nil
3730 "Matches the DONE keyword a point.")
3731 (make-variable-buffer-local 'org-looking-at-done-regexp)
3732 (defvar org-ds-keyword-length 12
3733 "Maximum length of the Deadline and SCHEDULED keywords.")
3734 (make-variable-buffer-local 'org-ds-keyword-length)
3735 (defvar org-deadline-regexp nil
3736 "Matches the DEADLINE keyword.")
3737 (make-variable-buffer-local 'org-deadline-regexp)
3738 (defvar org-deadline-time-regexp nil
3739 "Matches the DEADLINE keyword together with a time stamp.")
3740 (make-variable-buffer-local 'org-deadline-time-regexp)
3741 (defvar org-deadline-line-regexp nil
3742 "Matches the DEADLINE keyword and the rest of the line.")
3743 (make-variable-buffer-local 'org-deadline-line-regexp)
3744 (defvar org-scheduled-regexp nil
3745 "Matches the SCHEDULED keyword.")
3746 (make-variable-buffer-local 'org-scheduled-regexp)
3747 (defvar org-scheduled-time-regexp nil
3748 "Matches the SCHEDULED keyword together with a time stamp.")
3749 (make-variable-buffer-local 'org-scheduled-time-regexp)
3750 (defvar org-closed-time-regexp nil
3751 "Matches the CLOSED keyword together with a time stamp.")
3752 (make-variable-buffer-local 'org-closed-time-regexp)
3754 (defvar org-keyword-time-regexp nil
3755 "Matches any of the 4 keywords, together with the time stamp.")
3756 (make-variable-buffer-local 'org-keyword-time-regexp)
3757 (defvar org-keyword-time-not-clock-regexp nil
3758 "Matches any of the 3 keywords, together with the time stamp.")
3759 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3760 (defvar org-maybe-keyword-time-regexp nil
3761 "Matches a timestamp, possibly preceeded by a keyword.")
3762 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3763 (defvar org-planning-or-clock-line-re nil
3764 "Matches a line with planning or clock info.")
3765 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3766 (defvar org-all-time-keywords nil
3767 "List of time keywords.")
3768 (make-variable-buffer-local 'org-all-time-keywords)
3770 (defconst org-plain-time-of-day-regexp
3771 (concat
3772 "\\(\\<[012]?[0-9]"
3773 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3774 "\\(--?"
3775 "\\(\\<[012]?[0-9]"
3776 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3777 "\\)?")
3778 "Regular expression to match a plain time or time range.
3779 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3780 groups carry important information:
3781 0 the full match
3782 1 the first time, range or not
3783 8 the second time, if it is a range.")
3785 (defconst org-plain-time-extension-regexp
3786 (concat
3787 "\\(\\<[012]?[0-9]"
3788 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3789 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3790 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3791 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3792 groups carry important information:
3793 0 the full match
3794 7 hours of duration
3795 9 minutes of duration")
3797 (defconst org-stamp-time-of-day-regexp
3798 (concat
3799 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3800 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3801 "\\(--?"
3802 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3803 "Regular expression to match a timestamp time or time range.
3804 After a match, the following groups carry important information:
3805 0 the full match
3806 1 date plus weekday, for back referencing to make sure both times are on the same day
3807 2 the first time, range or not
3808 4 the second time, if it is a range.")
3810 (defconst org-startup-options
3811 '(("fold" org-startup-folded t)
3812 ("overview" org-startup-folded t)
3813 ("nofold" org-startup-folded nil)
3814 ("showall" org-startup-folded nil)
3815 ("showeverything" org-startup-folded showeverything)
3816 ("content" org-startup-folded content)
3817 ("indent" org-startup-indented t)
3818 ("noindent" org-startup-indented nil)
3819 ("hidestars" org-hide-leading-stars t)
3820 ("showstars" org-hide-leading-stars nil)
3821 ("odd" org-odd-levels-only t)
3822 ("oddeven" org-odd-levels-only nil)
3823 ("align" org-startup-align-all-tables t)
3824 ("noalign" org-startup-align-all-tables nil)
3825 ("customtime" org-display-custom-times t)
3826 ("logdone" org-log-done time)
3827 ("lognotedone" org-log-done note)
3828 ("nologdone" org-log-done nil)
3829 ("lognoteclock-out" org-log-note-clock-out t)
3830 ("nolognoteclock-out" org-log-note-clock-out nil)
3831 ("logrepeat" org-log-repeat state)
3832 ("lognoterepeat" org-log-repeat note)
3833 ("nologrepeat" org-log-repeat nil)
3834 ("logreschedule" org-log-reschedule time)
3835 ("lognotereschedule" org-log-reschedule note)
3836 ("nologreschedule" org-log-reschedule nil)
3837 ("logredeadline" org-log-redeadline time)
3838 ("lognoteredeadline" org-log-redeadline note)
3839 ("nologredeadline" org-log-redeadline nil)
3840 ("logrefile" org-log-refile time)
3841 ("lognoterefile" org-log-refile note)
3842 ("nologrefile" org-log-refile nil)
3843 ("fninline" org-footnote-define-inline t)
3844 ("nofninline" org-footnote-define-inline nil)
3845 ("fnlocal" org-footnote-section nil)
3846 ("fnauto" org-footnote-auto-label t)
3847 ("fnprompt" org-footnote-auto-label nil)
3848 ("fnconfirm" org-footnote-auto-label confirm)
3849 ("fnplain" org-footnote-auto-label plain)
3850 ("fnadjust" org-footnote-auto-adjust t)
3851 ("nofnadjust" org-footnote-auto-adjust nil)
3852 ("constcgs" constants-unit-system cgs)
3853 ("constSI" constants-unit-system SI)
3854 ("noptag" org-tag-persistent-alist nil)
3855 ("hideblocks" org-hide-block-startup t)
3856 ("nohideblocks" org-hide-block-startup nil)
3857 ("beamer" org-startup-with-beamer-mode t))
3858 "Variable associated with STARTUP options for org-mode.
3859 Each element is a list of three items: The startup options as written
3860 in the #+STARTUP line, the corresponding variable, and the value to
3861 set this variable to if the option is found. An optional forth element PUSH
3862 means to push this value onto the list in the variable.")
3864 (defun org-set-regexps-and-options ()
3865 "Precompute regular expressions for current buffer."
3866 (when (org-mode-p)
3867 (org-set-local 'org-todo-kwd-alist nil)
3868 (org-set-local 'org-todo-key-alist nil)
3869 (org-set-local 'org-todo-key-trigger nil)
3870 (org-set-local 'org-todo-keywords-1 nil)
3871 (org-set-local 'org-done-keywords nil)
3872 (org-set-local 'org-todo-heads nil)
3873 (org-set-local 'org-todo-sets nil)
3874 (org-set-local 'org-todo-log-states nil)
3875 (org-set-local 'org-file-properties nil)
3876 (org-set-local 'org-file-tags nil)
3877 (let ((re (org-make-options-regexp
3878 '("CATEGORY" "TODO" "COLUMNS"
3879 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3880 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS")
3881 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3882 (splitre "[ \t]+")
3883 kwds kws0 kwsa key log value cat arch tags const links hw dws
3884 tail sep kws1 prio props ftags drawers beamer-p
3885 ext-setup-or-nil setup-contents (start 0))
3886 (save-excursion
3887 (save-restriction
3888 (widen)
3889 (goto-char (point-min))
3890 (while (or (and ext-setup-or-nil
3891 (string-match re ext-setup-or-nil start)
3892 (setq start (match-end 0)))
3893 (and (setq ext-setup-or-nil nil start 0)
3894 (re-search-forward re nil t)))
3895 (setq key (upcase (match-string 1 ext-setup-or-nil))
3896 value (org-match-string-no-properties 2 ext-setup-or-nil))
3897 (cond
3898 ((equal key "CATEGORY")
3899 (if (string-match "[ \t]+$" value)
3900 (setq value (replace-match "" t t value)))
3901 (setq cat value))
3902 ((member key '("SEQ_TODO" "TODO"))
3903 (push (cons 'sequence (org-split-string value splitre)) kwds))
3904 ((equal key "TYP_TODO")
3905 (push (cons 'type (org-split-string value splitre)) kwds))
3906 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3907 ;; general TODO-like setup
3908 (push (cons (intern (downcase (match-string 1 key)))
3909 (org-split-string value splitre)) kwds))
3910 ((equal key "TAGS")
3911 (setq tags (append tags (if tags '("\\n") nil)
3912 (org-split-string value splitre))))
3913 ((equal key "COLUMNS")
3914 (org-set-local 'org-columns-default-format value))
3915 ((equal key "LINK")
3916 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3917 (push (cons (match-string 1 value)
3918 (org-trim (match-string 2 value)))
3919 links)))
3920 ((equal key "PRIORITIES")
3921 (setq prio (org-split-string value " +")))
3922 ((equal key "PROPERTY")
3923 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3924 (push (cons (match-string 1 value) (match-string 2 value))
3925 props)))
3926 ((equal key "FILETAGS")
3927 (when (string-match "\\S-" value)
3928 (setq ftags
3929 (append
3930 ftags
3931 (apply 'append
3932 (mapcar (lambda (x) (org-split-string x ":"))
3933 (org-split-string value)))))))
3934 ((equal key "DRAWERS")
3935 (setq drawers (org-split-string value splitre)))
3936 ((equal key "CONSTANTS")
3937 (setq const (append const (org-split-string value splitre))))
3938 ((equal key "STARTUP")
3939 (let ((opts (org-split-string value splitre))
3940 l var val)
3941 (while (setq l (pop opts))
3942 (when (setq l (assoc l org-startup-options))
3943 (setq var (nth 1 l) val (nth 2 l))
3944 (if (not (nth 3 l))
3945 (set (make-local-variable var) val)
3946 (if (not (listp (symbol-value var)))
3947 (set (make-local-variable var) nil))
3948 (set (make-local-variable var) (symbol-value var))
3949 (add-to-list var val))))))
3950 ((equal key "ARCHIVE")
3951 (string-match " *$" value)
3952 (setq arch (replace-match "" t t value))
3953 (remove-text-properties 0 (length arch)
3954 '(face t fontified t) arch))
3955 ((equal key "LATEX_CLASS")
3956 (setq beamer-p (equal value "beamer")))
3957 ((equal key "SETUPFILE")
3958 (setq setup-contents (org-file-contents
3959 (expand-file-name
3960 (org-remove-double-quotes value))
3961 'noerror))
3962 (if (not ext-setup-or-nil)
3963 (setq ext-setup-or-nil setup-contents start 0)
3964 (setq ext-setup-or-nil
3965 (concat (substring ext-setup-or-nil 0 start)
3966 "\n" setup-contents "\n"
3967 (substring ext-setup-or-nil start)))))
3968 ))))
3969 (when cat
3970 (org-set-local 'org-category (intern cat))
3971 (push (cons "CATEGORY" cat) props))
3972 (when prio
3973 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3974 (setq prio (mapcar 'string-to-char prio))
3975 (org-set-local 'org-highest-priority (nth 0 prio))
3976 (org-set-local 'org-lowest-priority (nth 1 prio))
3977 (org-set-local 'org-default-priority (nth 2 prio)))
3978 (and props (org-set-local 'org-file-properties (nreverse props)))
3979 (and ftags (org-set-local 'org-file-tags
3980 (mapcar 'org-add-prop-inherited ftags)))
3981 (and drawers (org-set-local 'org-drawers drawers))
3982 (and arch (org-set-local 'org-archive-location arch))
3983 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3984 ;; Process the TODO keywords
3985 (unless kwds
3986 ;; Use the global values as if they had been given locally.
3987 (setq kwds (default-value 'org-todo-keywords))
3988 (if (stringp (car kwds))
3989 (setq kwds (list (cons org-todo-interpretation
3990 (default-value 'org-todo-keywords)))))
3991 (setq kwds (reverse kwds)))
3992 (setq kwds (nreverse kwds))
3993 (let (inter kws kw)
3994 (while (setq kws (pop kwds))
3995 (let ((kws (or
3996 (run-hook-with-args-until-success
3997 'org-todo-setup-filter-hook kws)
3998 kws)))
3999 (setq inter (pop kws) sep (member "|" kws)
4000 kws0 (delete "|" (copy-sequence kws))
4001 kwsa nil
4002 kws1 (mapcar
4003 (lambda (x)
4004 ;; 1 2
4005 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4006 (progn
4007 (setq kw (match-string 1 x)
4008 key (and (match-end 2) (match-string 2 x))
4009 log (org-extract-log-state-settings x))
4010 (push (cons kw (and key (string-to-char key))) kwsa)
4011 (and log (push log org-todo-log-states))
4013 (error "Invalid TODO keyword %s" x)))
4014 kws0)
4015 kwsa (if kwsa (append '((:startgroup))
4016 (nreverse kwsa)
4017 '((:endgroup))))
4018 hw (car kws1)
4019 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4020 tail (list inter hw (car dws) (org-last dws))))
4021 (add-to-list 'org-todo-heads hw 'append)
4022 (push kws1 org-todo-sets)
4023 (setq org-done-keywords (append org-done-keywords dws nil))
4024 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4025 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4026 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4027 (setq org-todo-sets (nreverse org-todo-sets)
4028 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4029 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4030 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4031 ;; Process the constants
4032 (when const
4033 (let (e cst)
4034 (while (setq e (pop const))
4035 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4036 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4037 (setq org-table-formula-constants-local cst)))
4039 ;; Process the tags.
4040 (when tags
4041 (let (e tgs)
4042 (while (setq e (pop tags))
4043 (cond
4044 ((equal e "{") (push '(:startgroup) tgs))
4045 ((equal e "}") (push '(:endgroup) tgs))
4046 ((equal e "\\n") (push '(:newline) tgs))
4047 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4048 (push (cons (match-string 1 e)
4049 (string-to-char (match-string 2 e)))
4050 tgs))
4051 (t (push (list e) tgs))))
4052 (org-set-local 'org-tag-alist nil)
4053 (while (setq e (pop tgs))
4054 (or (and (stringp (car e))
4055 (assoc (car e) org-tag-alist))
4056 (push e org-tag-alist)))))
4058 ;; Compute the regular expressions and other local variables
4059 (if (not org-done-keywords)
4060 (setq org-done-keywords (and org-todo-keywords-1
4061 (list (org-last org-todo-keywords-1)))))
4062 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4063 (length org-scheduled-string)
4064 (length org-clock-string)
4065 (length org-closed-string)))
4066 org-drawer-regexp
4067 (concat "^[ \t]*:\\("
4068 (mapconcat 'regexp-quote org-drawers "\\|")
4069 "\\):[ \t]*$")
4070 org-not-done-keywords
4071 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4072 org-todo-regexp
4073 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4074 "\\|") "\\)\\>")
4075 org-not-done-regexp
4076 (concat "\\<\\("
4077 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4078 "\\)\\>")
4079 org-not-done-heading-regexp
4080 (concat "^\\(\\*+\\)[ \t]+\\("
4081 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4082 "\\)\\>")
4083 org-todo-line-regexp
4084 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4085 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4086 "\\)\\>\\)?[ \t]*\\(.*\\)")
4087 org-complex-heading-regexp
4088 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4089 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4090 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4091 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4092 org-complex-heading-regexp-format
4093 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4094 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4095 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(%s\\)"
4096 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4097 org-nl-done-regexp
4098 (concat "\n\\*+[ \t]+"
4099 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4100 "\\)" "\\>")
4101 org-todo-line-tags-regexp
4102 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4103 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4104 (org-re
4105 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4106 org-looking-at-done-regexp
4107 (concat "^" "\\(?:"
4108 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4109 "\\>")
4110 org-deadline-regexp (concat "\\<" org-deadline-string)
4111 org-deadline-time-regexp
4112 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4113 org-deadline-line-regexp
4114 (concat "\\<\\(" org-deadline-string "\\).*")
4115 org-scheduled-regexp
4116 (concat "\\<" org-scheduled-string)
4117 org-scheduled-time-regexp
4118 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4119 org-closed-time-regexp
4120 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4121 org-keyword-time-regexp
4122 (concat "\\<\\(" org-scheduled-string
4123 "\\|" org-deadline-string
4124 "\\|" org-closed-string
4125 "\\|" org-clock-string "\\)"
4126 " *[[<]\\([^]>]+\\)[]>]")
4127 org-keyword-time-not-clock-regexp
4128 (concat "\\<\\(" org-scheduled-string
4129 "\\|" org-deadline-string
4130 "\\|" org-closed-string
4131 "\\)"
4132 " *[[<]\\([^]>]+\\)[]>]")
4133 org-maybe-keyword-time-regexp
4134 (concat "\\(\\<\\(" org-scheduled-string
4135 "\\|" org-deadline-string
4136 "\\|" org-closed-string
4137 "\\|" org-clock-string "\\)\\)?"
4138 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4139 org-planning-or-clock-line-re
4140 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4141 "\\|" org-deadline-string
4142 "\\|" org-closed-string "\\|" org-clock-string
4143 "\\)\\>\\)")
4144 org-all-time-keywords
4145 (mapcar (lambda (w) (substring w 0 -1))
4146 (list org-scheduled-string org-deadline-string
4147 org-clock-string org-closed-string))
4149 (org-compute-latex-and-specials-regexp)
4150 (org-set-font-lock-defaults))))
4152 (defun org-file-contents (file &optional noerror)
4153 "Return the contents of FILE, as a string."
4154 (if (or (not file)
4155 (not (file-readable-p file)))
4156 (if noerror
4157 (progn
4158 (message "Cannot read file %s" file)
4159 (ding) (sit-for 2)
4161 (error "Cannot read file %s" file))
4162 (with-temp-buffer
4163 (insert-file-contents file)
4164 (buffer-string))))
4166 (defun org-extract-log-state-settings (x)
4167 "Extract the log state setting from a TODO keyword string.
4168 This will extract info from a string like \"WAIT(w@/!)\"."
4169 (let (kw key log1 log2)
4170 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4171 (setq kw (match-string 1 x)
4172 key (and (match-end 2) (match-string 2 x))
4173 log1 (and (match-end 3) (match-string 3 x))
4174 log2 (and (match-end 4) (match-string 4 x)))
4175 (and (or log1 log2)
4176 (list kw
4177 (and log1 (if (equal log1 "!") 'time 'note))
4178 (and log2 (if (equal log2 "!") 'time 'note)))))))
4180 (defun org-remove-keyword-keys (list)
4181 "Remove a pair of parenthesis at the end of each string in LIST."
4182 (mapcar (lambda (x)
4183 (if (string-match "(.*)$" x)
4184 (substring x 0 (match-beginning 0))
4186 list))
4188 (defun org-assign-fast-keys (alist)
4189 "Assign fast keys to a keyword-key alist.
4190 Respect keys that are already there."
4191 (let (new e (alt ?0))
4192 (while (setq e (pop alist))
4193 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4194 (cdr e)) ;; Key already assigned.
4195 (push e new)
4196 (let ((clist (string-to-list (downcase (car e))))
4197 (used (append new alist)))
4198 (when (= (car clist) ?@)
4199 (pop clist))
4200 (while (and clist (rassoc (car clist) used))
4201 (pop clist))
4202 (unless clist
4203 (while (rassoc alt used)
4204 (incf alt)))
4205 (push (cons (car e) (or (car clist) alt)) new))))
4206 (nreverse new)))
4208 ;;; Some variables used in various places
4210 (defvar org-window-configuration nil
4211 "Used in various places to store a window configuration.")
4212 (defvar org-selected-window nil
4213 "Used in various places to store a window configuration.")
4214 (defvar org-finish-function nil
4215 "Function to be called when `C-c C-c' is used.
4216 This is for getting out of special buffers like remember.")
4219 ;; FIXME: Occasionally check by commenting these, to make sure
4220 ;; no other functions uses these, forgetting to let-bind them.
4221 (defvar entry)
4222 (defvar last-state)
4223 (defvar date)
4225 ;; Defined somewhere in this file, but used before definition.
4226 (defvar org-html-entities)
4227 (defvar org-struct-menu)
4228 (defvar org-org-menu)
4229 (defvar org-tbl-menu)
4231 ;;;; Define the Org-mode
4233 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4234 (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."))
4237 ;; We use a before-change function to check if a table might need
4238 ;; an update.
4239 (defvar org-table-may-need-update t
4240 "Indicates that a table might need an update.
4241 This variable is set by `org-before-change-function'.
4242 `org-table-align' sets it back to nil.")
4243 (defun org-before-change-function (beg end)
4244 "Every change indicates that a table might need an update."
4245 (setq org-table-may-need-update t))
4246 (defvar org-mode-map)
4247 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4248 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4249 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4250 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4251 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4252 (defvar org-table-buffer-is-an nil)
4253 (defconst org-outline-regexp "\\*+ ")
4255 ;;;###autoload
4256 (define-derived-mode org-mode outline-mode "Org"
4257 "Outline-based notes management and organizer, alias
4258 \"Carsten's outline-mode for keeping track of everything.\"
4260 Org-mode develops organizational tasks around a NOTES file which
4261 contains information about projects as plain text. Org-mode is
4262 implemented on top of outline-mode, which is ideal to keep the content
4263 of large files well structured. It supports ToDo items, deadlines and
4264 time stamps, which magically appear in the diary listing of the Emacs
4265 calendar. Tables are easily created with a built-in table editor.
4266 Plain text URL-like links connect to websites, emails (VM), Usenet
4267 messages (Gnus), BBDB entries, and any files related to the project.
4268 For printing and sharing of notes, an Org-mode file (or a part of it)
4269 can be exported as a structured ASCII or HTML file.
4271 The following commands are available:
4273 \\{org-mode-map}"
4275 ;; Get rid of Outline menus, they are not needed
4276 ;; Need to do this here because define-derived-mode sets up
4277 ;; the keymap so late. Still, it is a waste to call this each time
4278 ;; we switch another buffer into org-mode.
4279 (if (featurep 'xemacs)
4280 (when (boundp 'outline-mode-menu-heading)
4281 ;; Assume this is Greg's port, it used easymenu
4282 (easy-menu-remove outline-mode-menu-heading)
4283 (easy-menu-remove outline-mode-menu-show)
4284 (easy-menu-remove outline-mode-menu-hide))
4285 (define-key org-mode-map [menu-bar headings] 'undefined)
4286 (define-key org-mode-map [menu-bar hide] 'undefined)
4287 (define-key org-mode-map [menu-bar show] 'undefined))
4289 (org-load-modules-maybe)
4290 (easy-menu-add org-org-menu)
4291 (easy-menu-add org-tbl-menu)
4292 (org-install-agenda-files-menu)
4293 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4294 (org-add-to-invisibility-spec '(org-cwidth))
4295 (org-add-to-invisibility-spec '(org-hide-block . t))
4296 (when (featurep 'xemacs)
4297 (org-set-local 'line-move-ignore-invisible t))
4298 (org-set-local 'outline-regexp org-outline-regexp)
4299 (org-set-local 'outline-level 'org-outline-level)
4300 (when (and org-ellipsis
4301 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4302 (fboundp 'make-glyph-code))
4303 (unless org-display-table
4304 (setq org-display-table (make-display-table)))
4305 (set-display-table-slot
4306 org-display-table 4
4307 (vconcat (mapcar
4308 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4309 org-ellipsis)))
4310 (if (stringp org-ellipsis) org-ellipsis "..."))))
4311 (setq buffer-display-table org-display-table))
4312 (org-set-regexps-and-options)
4313 (when (and org-tag-faces (not org-tags-special-faces-re))
4314 ;; tag faces set outside customize.... force initialization.
4315 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4316 ;; Calc embedded
4317 (org-set-local 'calc-embedded-open-mode "# ")
4318 (modify-syntax-entry ?# "<")
4319 (modify-syntax-entry ?@ "w")
4320 (if org-startup-truncated (setq truncate-lines t))
4321 (org-set-local 'font-lock-unfontify-region-function
4322 'org-unfontify-region)
4323 ;; Activate before-change-function
4324 (org-set-local 'org-table-may-need-update t)
4325 (org-add-hook 'before-change-functions 'org-before-change-function nil
4326 'local)
4327 ;; Check for running clock before killing a buffer
4328 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4329 ;; Paragraphs and auto-filling
4330 (org-set-autofill-regexps)
4331 (setq indent-line-function 'org-indent-line-function)
4332 (org-update-radio-target-regexp)
4333 ;; Make sure dependence stuff works reliably, even for users who set it
4334 ;; too late :-(
4335 (if org-enforce-todo-dependencies
4336 (add-hook 'org-blocker-hook
4337 'org-block-todo-from-children-or-siblings-or-parent)
4338 (remove-hook 'org-blocker-hook
4339 'org-block-todo-from-children-or-siblings-or-parent))
4340 (if org-enforce-todo-checkbox-dependencies
4341 (add-hook 'org-blocker-hook
4342 'org-block-todo-from-checkboxes)
4343 (remove-hook 'org-blocker-hook
4344 'org-block-todo-from-checkboxes))
4346 ;; Comment characters
4347 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4348 (org-set-local 'comment-padding " ")
4350 ;; Align options lines
4351 (org-set-local
4352 'align-mode-rules-list
4353 '((org-in-buffer-settings
4354 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4355 (modes . '(org-mode)))))
4357 ;; Imenu
4358 (org-set-local 'imenu-create-index-function
4359 'org-imenu-get-tree)
4361 ;; Make isearch reveal context
4362 (if (or (featurep 'xemacs)
4363 (not (boundp 'outline-isearch-open-invisible-function)))
4364 ;; Emacs 21 and XEmacs make use of the hook
4365 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4366 ;; Emacs 22 deals with this through a special variable
4367 (org-set-local 'outline-isearch-open-invisible-function
4368 (lambda (&rest ignore) (org-show-context 'isearch))))
4370 ;; Turn on org-beamer-mode?
4371 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4373 ;; If empty file that did not turn on org-mode automatically, make it to.
4374 (if (and org-insert-mode-line-in-empty-file
4375 (interactive-p)
4376 (= (point-min) (point-max)))
4377 (insert "# -*- mode: org -*-\n\n"))
4378 (unless org-inhibit-startup
4379 (when org-startup-align-all-tables
4380 (let ((bmp (buffer-modified-p)))
4381 (org-table-map-tables 'org-table-align)
4382 (set-buffer-modified-p bmp)))
4383 (when org-startup-indented
4384 (require 'org-indent)
4385 (org-indent-mode 1))
4386 (unless org-inhibit-startup-visibility-stuff
4387 (org-set-startup-visibility))))
4389 (when (fboundp 'abbrev-table-put)
4390 (abbrev-table-put org-mode-abbrev-table
4391 :parents (list text-mode-abbrev-table)))
4393 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4395 (defun org-current-time ()
4396 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4397 (if (> (car org-time-stamp-rounding-minutes) 1)
4398 (let ((r (car org-time-stamp-rounding-minutes))
4399 (time (decode-time)))
4400 (apply 'encode-time
4401 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4402 (nthcdr 2 time))))
4403 (current-time)))
4405 ;;;; Font-Lock stuff, including the activators
4407 (defvar org-mouse-map (make-sparse-keymap))
4408 (org-defkey org-mouse-map
4409 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4410 (org-defkey org-mouse-map
4411 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4412 (when org-mouse-1-follows-link
4413 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4414 (when org-tab-follows-link
4415 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4416 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4418 (require 'font-lock)
4420 (defconst org-non-link-chars "]\t\n\r<>")
4421 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4422 "shell" "elisp"))
4423 (defvar org-link-types-re nil
4424 "Matches a link that has a url-like prefix like \"http:\"")
4425 (defvar org-link-re-with-space nil
4426 "Matches a link with spaces, optional angular brackets around it.")
4427 (defvar org-link-re-with-space2 nil
4428 "Matches a link with spaces, optional angular brackets around it.")
4429 (defvar org-link-re-with-space3 nil
4430 "Matches a link with spaces, only for internal part in bracket links.")
4431 (defvar org-angle-link-re nil
4432 "Matches link with angular brackets, spaces are allowed.")
4433 (defvar org-plain-link-re nil
4434 "Matches plain link, without spaces.")
4435 (defvar org-bracket-link-regexp nil
4436 "Matches a link in double brackets.")
4437 (defvar org-bracket-link-analytic-regexp nil
4438 "Regular expression used to analyze links.
4439 Here is what the match groups contain after a match:
4440 1: http:
4441 2: http
4442 3: path
4443 4: [desc]
4444 5: desc")
4445 (defvar org-bracket-link-analytic-regexp++ nil
4446 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4447 (defvar org-any-link-re nil
4448 "Regular expression matching any link.")
4450 (defun org-make-link-regexps ()
4451 "Update the link regular expressions.
4452 This should be called after the variable `org-link-types' has changed."
4453 (setq org-link-types-re
4454 (concat
4455 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
4456 org-link-re-with-space
4457 (concat
4458 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4459 "\\([^" org-non-link-chars " ]"
4460 "[^" org-non-link-chars "]*"
4461 "[^" org-non-link-chars " ]\\)>?")
4462 org-link-re-with-space2
4463 (concat
4464 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4465 "\\([^" org-non-link-chars " ]"
4466 "[^\t\n\r]*"
4467 "[^" org-non-link-chars " ]\\)>?")
4468 org-link-re-with-space3
4469 (concat
4470 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4471 "\\([^" org-non-link-chars " ]"
4472 "[^\t\n\r]*\\)")
4473 org-angle-link-re
4474 (concat
4475 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4476 "\\([^" org-non-link-chars " ]"
4477 "[^" org-non-link-chars "]*"
4478 "\\)>")
4479 org-plain-link-re
4480 (concat
4481 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4482 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
4483 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4484 org-bracket-link-regexp
4485 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4486 org-bracket-link-analytic-regexp
4487 (concat
4488 "\\[\\["
4489 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
4490 "\\([^]]+\\)"
4491 "\\]"
4492 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4493 "\\]")
4494 org-bracket-link-analytic-regexp++
4495 (concat
4496 "\\[\\["
4497 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4498 "\\([^]]+\\)"
4499 "\\]"
4500 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4501 "\\]")
4502 org-any-link-re
4503 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4504 org-angle-link-re "\\)\\|\\("
4505 org-plain-link-re "\\)")))
4507 (org-make-link-regexps)
4509 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4510 "Regular expression for fast time stamp matching.")
4511 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4512 "Regular expression for fast time stamp matching.")
4513 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4514 "Regular expression matching time strings for analysis.
4515 This one does not require the space after the date, so it can be used
4516 on a string that terminates immediately after the date.")
4517 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4518 "Regular expression matching time strings for analysis.")
4519 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4520 "Regular expression matching time stamps, with groups.")
4521 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4522 "Regular expression matching time stamps (also [..]), with groups.")
4523 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4524 "Regular expression matching a time stamp range.")
4525 (defconst org-tr-regexp-both
4526 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4527 "Regular expression matching a time stamp range.")
4528 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4529 org-ts-regexp "\\)?")
4530 "Regular expression matching a time stamp or time stamp range.")
4531 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4532 org-ts-regexp-both "\\)?")
4533 "Regular expression matching a time stamp or time stamp range.
4534 The time stamps may be either active or inactive.")
4536 (defvar org-emph-face nil)
4538 (defun org-do-emphasis-faces (limit)
4539 "Run through the buffer and add overlays to links."
4540 (let (rtn a)
4541 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4542 (if (not (= (char-after (match-beginning 3))
4543 (char-after (match-beginning 4))))
4544 (progn
4545 (setq rtn t)
4546 (setq a (assoc (match-string 3) org-emphasis-alist))
4547 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4548 'face
4549 (nth 1 a))
4550 (and (nth 4 a)
4551 (org-remove-flyspell-overlays-in
4552 (match-beginning 0) (match-end 0)))
4553 (add-text-properties (match-beginning 2) (match-end 2)
4554 '(font-lock-multiline t))
4555 (when org-hide-emphasis-markers
4556 (add-text-properties (match-end 4) (match-beginning 5)
4557 '(invisible org-link))
4558 (add-text-properties (match-beginning 3) (match-end 3)
4559 '(invisible org-link)))))
4560 (backward-char 1))
4561 rtn))
4563 (defun org-emphasize (&optional char)
4564 "Insert or change an emphasis, i.e. a font like bold or italic.
4565 If there is an active region, change that region to a new emphasis.
4566 If there is no region, just insert the marker characters and position
4567 the cursor between them.
4568 CHAR should be either the marker character, or the first character of the
4569 HTML tag associated with that emphasis. If CHAR is a space, the means
4570 to remove the emphasis of the selected region.
4571 If char is not given (for example in an interactive call) it
4572 will be prompted for."
4573 (interactive)
4574 (let ((eal org-emphasis-alist) e det
4575 (erc org-emphasis-regexp-components)
4576 (prompt "")
4577 (string "") beg end move tag c s)
4578 (if (org-region-active-p)
4579 (setq beg (region-beginning) end (region-end)
4580 string (buffer-substring beg end))
4581 (setq move t))
4583 (while (setq e (pop eal))
4584 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4585 c (aref tag 0))
4586 (push (cons c (string-to-char (car e))) det)
4587 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4588 (substring tag 1)))))
4589 (setq det (nreverse det))
4590 (unless char
4591 (message "%s" (concat "Emphasis marker or tag:" prompt))
4592 (setq char (read-char-exclusive)))
4593 (setq char (or (cdr (assoc char det)) char))
4594 (if (equal char ?\ )
4595 (setq s "" move nil)
4596 (unless (assoc (char-to-string char) org-emphasis-alist)
4597 (error "No such emphasis marker: \"%c\"" char))
4598 (setq s (char-to-string char)))
4599 (while (and (> (length string) 1)
4600 (equal (substring string 0 1) (substring string -1))
4601 (assoc (substring string 0 1) org-emphasis-alist))
4602 (setq string (substring string 1 -1)))
4603 (setq string (concat s string s))
4604 (if beg (delete-region beg end))
4605 (unless (or (bolp)
4606 (string-match (concat "[" (nth 0 erc) "\n]")
4607 (char-to-string (char-before (point)))))
4608 (insert " "))
4609 (unless (or (eobp)
4610 (string-match (concat "[" (nth 1 erc) "\n]")
4611 (char-to-string (char-after (point)))))
4612 (insert " ") (backward-char 1))
4613 (insert string)
4614 (and move (backward-char 1))))
4616 (defconst org-nonsticky-props
4617 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4619 (defsubst org-rear-nonsticky-at (pos)
4620 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4622 (defun org-activate-plain-links (limit)
4623 "Run through the buffer and add overlays to links."
4624 (catch 'exit
4625 (let (f)
4626 (if (re-search-forward org-plain-link-re limit t)
4627 (progn
4628 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4629 (setq f (get-text-property (match-beginning 0) 'face))
4630 (if (or (eq f 'org-tag)
4631 (and (listp f) (memq 'org-tag f)))
4633 (add-text-properties (match-beginning 0) (match-end 0)
4634 (list 'mouse-face 'highlight
4635 'face 'org-link
4636 'keymap org-mouse-map))
4637 (org-rear-nonsticky-at (match-end 0)))
4638 t)))))
4640 (defun org-activate-code (limit)
4641 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4642 (progn
4643 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4644 (remove-text-properties (match-beginning 0) (match-end 0)
4645 '(display t invisible t intangible t))
4646 t)))
4648 (defun org-fontify-meta-lines-and-blocks (limit)
4649 "Fontify #+ lines and blocks, in the correct ways."
4650 (let ((case-fold-search t))
4651 (if (re-search-forward
4652 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4653 limit t)
4654 (let ((beg (match-beginning 0))
4655 (beg1 (line-beginning-position 2))
4656 (dc1 (downcase (match-string 2)))
4657 (dc3 (downcase (match-string 3)))
4658 end end1 quoting block-type)
4659 (cond
4660 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4661 ;; a single line of backend-specific content
4662 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4663 (remove-text-properties (match-beginning 0) (match-end 0)
4664 '(display t invisible t intangible t))
4665 (add-text-properties (match-beginning 1) (match-end 3)
4666 '(font-lock-fontified t face org-meta-line))
4667 (add-text-properties (match-beginning 6) (match-end 6)
4668 '(font-lock-fontified t face org-block))
4670 ((and (match-end 4) (equal dc3 "begin"))
4671 ;; Truely a block
4672 (setq block-type (downcase (match-string 5))
4673 quoting (member block-type org-protecting-blocks))
4674 (when (re-search-forward
4675 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4676 nil t) ;; on purpose, we look further than LIMIT
4677 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4678 (when quoting
4679 (remove-text-properties beg end
4680 '(display t invisible t intangible t)))
4681 (add-text-properties
4682 beg end
4683 '(font-lock-fontified t font-lock-multiline t))
4684 (add-text-properties beg beg1 '(face org-meta-line))
4685 (add-text-properties end1 end '(face org-meta-line))
4686 (cond
4687 (quoting
4688 (add-text-properties beg1 end1 '(face org-block)))
4689 ((not org-fontify-quote-and-verse-blocks))
4690 ((string= block-type "quote")
4691 (add-text-properties beg1 end1 '(face org-quote)))
4692 ((string= block-type "verse")
4693 (add-text-properties beg1 end1 '(face org-verse))))
4695 ((member dc1 '("title:" "author:" "email:" "date:"))
4696 (add-text-properties
4697 beg (match-end 3)
4698 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
4699 '(font-lock-fontified t invisible t)
4700 '(font-lock-fontified t face org-document-info-keyword)))
4701 (add-text-properties
4702 (match-beginning 6) (match-end 6)
4703 (if (string-equal dc1 "title:")
4704 '(font-lock-fontified t face org-document-title)
4705 '(font-lock-fontified t face org-document-info))))
4706 ((not (member (char-after beg) '(?\ ?\t)))
4707 ;; just any other in-buffer setting, but not indented
4708 (add-text-properties
4709 beg (match-end 0)
4710 '(font-lock-fontified t face org-meta-line))
4712 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
4713 "orgtbl:" "tblfm:" "tblname:"))
4714 (and (match-end 4) (equal dc3 "attr")))
4715 (add-text-properties
4716 beg (match-end 0)
4717 '(font-lock-fontified t face org-meta-line))
4719 ((member dc3 '(" " ""))
4720 (add-text-properties
4721 beg (match-end 0)
4722 '(font-lock-fontified t face font-lock-comment-face)))
4723 (t nil))))))
4725 (defun org-activate-angle-links (limit)
4726 "Run through the buffer and add overlays to links."
4727 (if (re-search-forward org-angle-link-re limit t)
4728 (progn
4729 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4730 (add-text-properties (match-beginning 0) (match-end 0)
4731 (list 'mouse-face 'highlight
4732 'keymap org-mouse-map))
4733 (org-rear-nonsticky-at (match-end 0))
4734 t)))
4736 (defun org-activate-footnote-links (limit)
4737 "Run through the buffer and add overlays to links."
4738 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4739 limit t)
4740 (progn
4741 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4742 (add-text-properties (match-beginning 2) (match-end 2)
4743 (list 'mouse-face 'highlight
4744 'keymap org-mouse-map
4745 'help-echo
4746 (if (= (point-at-bol) (match-beginning 2))
4747 "Footnote definition"
4748 "Footnote reference")
4750 (org-rear-nonsticky-at (match-end 2))
4751 t)))
4753 (defun org-activate-bracket-links (limit)
4754 "Run through the buffer and add overlays to bracketed links."
4755 (if (re-search-forward org-bracket-link-regexp limit t)
4756 (let* ((help (concat "LINK: "
4757 (org-match-string-no-properties 1)))
4758 ;; FIXME: above we should remove the escapes.
4759 ;; but that requires another match, protecting match data,
4760 ;; a lot of overhead for font-lock.
4761 (ip (org-maybe-intangible
4762 (list 'invisible 'org-link
4763 'keymap org-mouse-map 'mouse-face 'highlight
4764 'font-lock-multiline t 'help-echo help)))
4765 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4766 'font-lock-multiline t 'help-echo help)))
4767 ;; We need to remove the invisible property here. Table narrowing
4768 ;; may have made some of this invisible.
4769 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4770 (remove-text-properties (match-beginning 0) (match-end 0)
4771 '(invisible nil))
4772 (if (match-end 3)
4773 (progn
4774 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4775 (org-rear-nonsticky-at (match-beginning 3))
4776 (add-text-properties (match-beginning 3) (match-end 3) vp)
4777 (org-rear-nonsticky-at (match-end 3))
4778 (add-text-properties (match-end 3) (match-end 0) ip)
4779 (org-rear-nonsticky-at (match-end 0)))
4780 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4781 (org-rear-nonsticky-at (match-beginning 1))
4782 (add-text-properties (match-beginning 1) (match-end 1) vp)
4783 (org-rear-nonsticky-at (match-end 1))
4784 (add-text-properties (match-end 1) (match-end 0) ip)
4785 (org-rear-nonsticky-at (match-end 0)))
4786 t)))
4788 (defun org-activate-dates (limit)
4789 "Run through the buffer and add overlays to dates."
4790 (if (re-search-forward org-tsr-regexp-both limit t)
4791 (progn
4792 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4793 (add-text-properties (match-beginning 0) (match-end 0)
4794 (list 'mouse-face 'highlight
4795 'keymap org-mouse-map))
4796 (org-rear-nonsticky-at (match-end 0))
4797 (when org-display-custom-times
4798 (if (match-end 3)
4799 (org-display-custom-time (match-beginning 3) (match-end 3)))
4800 (org-display-custom-time (match-beginning 1) (match-end 1)))
4801 t)))
4803 (defvar org-target-link-regexp nil
4804 "Regular expression matching radio targets in plain text.")
4805 (make-variable-buffer-local 'org-target-link-regexp)
4806 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4807 "Regular expression matching a link target.")
4808 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4809 "Regular expression matching a radio target.")
4810 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4811 "Regular expression matching any target.")
4813 (defun org-activate-target-links (limit)
4814 "Run through the buffer and add overlays to target matches."
4815 (when org-target-link-regexp
4816 (let ((case-fold-search t))
4817 (if (re-search-forward org-target-link-regexp limit t)
4818 (progn
4819 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4820 (add-text-properties (match-beginning 0) (match-end 0)
4821 (list 'mouse-face 'highlight
4822 'keymap org-mouse-map
4823 'help-echo "Radio target link"
4824 'org-linked-text t))
4825 (org-rear-nonsticky-at (match-end 0))
4826 t)))))
4828 (defun org-update-radio-target-regexp ()
4829 "Find all radio targets in this file and update the regular expression."
4830 (interactive)
4831 (when (memq 'radio org-activate-links)
4832 (setq org-target-link-regexp
4833 (org-make-target-link-regexp (org-all-targets 'radio)))
4834 (org-restart-font-lock)))
4836 (defun org-hide-wide-columns (limit)
4837 (let (s e)
4838 (setq s (text-property-any (point) (or limit (point-max))
4839 'org-cwidth t))
4840 (when s
4841 (setq e (next-single-property-change s 'org-cwidth))
4842 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4843 (goto-char e)
4844 t)))
4846 (defvar org-latex-and-specials-regexp nil
4847 "Regular expression for highlighting export special stuff.")
4848 (defvar org-match-substring-regexp)
4849 (defvar org-match-substring-with-braces-regexp)
4851 ;; This should be with the exporter code, but we also use if for font-locking
4852 (defconst org-export-html-special-string-regexps
4853 '(("\\\\-" . "&shy;")
4854 ("---\\([^-]\\)" . "&mdash;\\1")
4855 ("--\\([^-]\\)" . "&ndash;\\1")
4856 ("\\.\\.\\." . "&hellip;"))
4857 "Regular expressions for special string conversion.")
4860 (defun org-compute-latex-and-specials-regexp ()
4861 "Compute regular expression for stuff treated specially by exporters."
4862 (if (not org-highlight-latex-fragments-and-specials)
4863 (org-set-local 'org-latex-and-specials-regexp nil)
4864 (require 'org-exp)
4865 (let*
4866 ((matchers (plist-get org-format-latex-options :matchers))
4867 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4868 org-latex-regexps)))
4869 (org-export-allow-BIND nil)
4870 (options (org-combine-plists (org-default-export-plist)
4871 (org-infile-export-plist)))
4872 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4873 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4874 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4875 (org-export-html-expand (plist-get options :expand-quoted-html))
4876 (org-export-with-special-strings (plist-get options :special-strings))
4877 (re-sub
4878 (cond
4879 ((equal org-export-with-sub-superscripts '{})
4880 (list org-match-substring-with-braces-regexp))
4881 (org-export-with-sub-superscripts
4882 (list org-match-substring-regexp))
4883 (t nil)))
4884 (re-latex
4885 (if org-export-with-LaTeX-fragments
4886 (mapcar (lambda (x) (nth 1 x)) latexs)))
4887 (re-macros
4888 (if org-export-with-TeX-macros
4889 (list (concat "\\\\"
4890 (regexp-opt
4891 (append (mapcar 'car org-html-entities)
4892 (if (boundp 'org-latex-entities)
4893 (mapcar (lambda (x)
4894 (or (car-safe x) x))
4895 org-latex-entities)
4896 nil))
4897 'words))) ; FIXME
4899 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4900 (re-special (if org-export-with-special-strings
4901 (mapcar (lambda (x) (car x))
4902 org-export-html-special-string-regexps)))
4903 (re-rest
4904 (delq nil
4905 (list
4906 (if org-export-html-expand "@<[^>\n]+>")
4907 ))))
4908 (org-set-local
4909 'org-latex-and-specials-regexp
4910 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4911 re-rest) "\\|")))))
4913 (defun org-do-latex-and-special-faces (limit)
4914 "Run through the buffer and add overlays to links."
4915 (when org-latex-and-specials-regexp
4916 (let (rtn d)
4917 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4918 limit t))
4919 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4920 'face))
4921 '(org-code org-verbatim underline)))
4922 (progn
4923 (setq rtn t
4924 d (cond ((member (char-after (1+ (match-beginning 0)))
4925 '(?_ ?^)) 1)
4926 (t 0)))
4927 (font-lock-prepend-text-property
4928 (+ d (match-beginning 0)) (match-end 0)
4929 'face 'org-latex-and-export-specials)
4930 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4931 '(font-lock-multiline t)))))
4932 rtn)))
4934 (defun org-restart-font-lock ()
4935 "Restart font-lock-mode, to force refontification."
4936 (when (and (boundp 'font-lock-mode) font-lock-mode)
4937 (font-lock-mode -1)
4938 (font-lock-mode 1)))
4940 (defun org-all-targets (&optional radio)
4941 "Return a list of all targets in this file.
4942 With optional argument RADIO, only find radio targets."
4943 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4944 rtn)
4945 (save-excursion
4946 (goto-char (point-min))
4947 (while (re-search-forward re nil t)
4948 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4949 rtn)))
4951 (defun org-make-target-link-regexp (targets)
4952 "Make regular expression matching all strings in TARGETS.
4953 The regular expression finds the targets also if there is a line break
4954 between words."
4955 (and targets
4956 (concat
4957 "\\<\\("
4958 (mapconcat
4959 (lambda (x)
4960 (while (string-match " +" x)
4961 (setq x (replace-match "\\s-+" t t x)))
4963 targets
4964 "\\|")
4965 "\\)\\>")))
4967 (defun org-activate-tags (limit)
4968 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4969 (progn
4970 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
4971 (add-text-properties (match-beginning 1) (match-end 1)
4972 (list 'mouse-face 'highlight
4973 'keymap org-mouse-map))
4974 (org-rear-nonsticky-at (match-end 1))
4975 t)))
4977 (defun org-outline-level ()
4978 "Compute the outline level of the heading at point.
4979 This function assumes that the cursor is at the beginning of a line matched
4980 by outline-regexp. Otherwise it returns garbage.
4981 If this is called at a normal headline, the level is the number of stars.
4982 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
4983 For plain list items, if they are matched by `outline-regexp', this returns
4984 1000 plus the line indentation."
4985 (save-excursion
4986 (looking-at outline-regexp)
4987 (if (match-beginning 1)
4988 (+ (org-get-string-indentation (match-string 1)) 1000)
4989 (1- (- (match-end 0) (match-beginning 0))))))
4991 (defvar org-font-lock-keywords nil)
4993 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4994 "Regular expression matching a property line.")
4996 (defvar org-font-lock-hook nil
4997 "Functions to be called for special font lock stuff.")
4999 (defun org-font-lock-hook (limit)
5000 (run-hook-with-args 'org-font-lock-hook limit))
5002 (defun org-set-font-lock-defaults ()
5003 (let* ((em org-fontify-emphasized-text)
5004 (lk org-activate-links)
5005 (org-font-lock-extra-keywords
5006 (list
5007 ;; Call the hook
5008 '(org-font-lock-hook)
5009 ;; Headlines
5010 `(,(if org-fontify-whole-heading-line
5011 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5012 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5013 (1 (org-get-level-face 1))
5014 (2 (org-get-level-face 2))
5015 (3 (org-get-level-face 3)))
5016 ;; Table lines
5017 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5018 (1 'org-table t))
5019 ;; Table internals
5020 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5021 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5022 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5023 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
5024 ;; Drawers
5025 (list org-drawer-regexp '(0 'org-special-keyword t))
5026 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5027 ;; Properties
5028 (list org-property-re
5029 '(1 'org-special-keyword t)
5030 '(3 'org-property-value t))
5031 ;; Links
5032 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5033 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5034 (if (memq 'plain lk) '(org-activate-plain-links))
5035 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5036 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5037 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5038 (if (memq 'footnote lk) '(org-activate-footnote-links
5039 (2 'org-footnote t)))
5040 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5041 '(org-hide-wide-columns (0 nil append))
5042 ;; TODO lines
5043 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
5044 '(1 (org-get-todo-face 1) t))
5045 ;; DONE
5046 (if org-fontify-done-headline
5047 (list (concat "^[*]+ +\\<\\("
5048 (mapconcat 'regexp-quote org-done-keywords "\\|")
5049 "\\)\\(.*\\)")
5050 '(2 'org-headline-done t))
5051 nil)
5052 ;; Priorities
5053 '(org-font-lock-add-priority-faces)
5054 ;; Tags
5055 '(org-font-lock-add-tag-faces)
5056 ;; Special keywords
5057 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5058 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5059 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5060 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5061 ;; Emphasis
5062 (if em
5063 (if (featurep 'xemacs)
5064 '(org-do-emphasis-faces (0 nil append))
5065 '(org-do-emphasis-faces)))
5066 ;; Checkboxes
5067 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5068 2 'org-checkbox prepend)
5069 (if org-provide-checkbox-statistics
5070 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5071 (0 (org-get-checkbox-statistics-face) t)))
5072 ;; Description list items
5073 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
5074 2 'bold prepend)
5075 ;; ARCHIVEd headings
5076 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5077 '(1 'org-archived prepend))
5078 ;; Specials
5079 '(org-do-latex-and-special-faces)
5080 ;; Code
5081 '(org-activate-code (1 'org-code t))
5082 ;; COMMENT
5083 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5084 "\\|" org-quote-string "\\)\\>")
5085 '(1 'org-special-keyword t))
5086 '("^#.*" (0 'font-lock-comment-face t))
5087 ;; Blocks and meta lines
5088 '(org-fontify-meta-lines-and-blocks)
5090 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5091 ;; Now set the full font-lock-keywords
5092 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5093 (org-set-local 'font-lock-defaults
5094 '(org-font-lock-keywords t nil nil backward-paragraph))
5095 (kill-local-variable 'font-lock-keywords) nil))
5097 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5098 "Fontify string S like in Org-mode"
5099 (with-temp-buffer
5100 (insert s)
5101 (let ((org-odd-levels-only odd-levels))
5102 (org-mode)
5103 (font-lock-fontify-buffer)
5104 (buffer-string))))
5106 (defvar org-m nil)
5107 (defvar org-l nil)
5108 (defvar org-f nil)
5109 (defun org-get-level-face (n)
5110 "Get the right face for match N in font-lock matching of headlines."
5111 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5112 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5113 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5114 (cond
5115 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5116 ((eq n 2) org-f)
5117 (t (if org-level-color-stars-only nil org-f))))
5119 (defun org-get-todo-face (kwd)
5120 "Get the right face for a TODO keyword KWD.
5121 If KWD is a number, get the corresponding match group."
5122 (if (numberp kwd) (setq kwd (match-string kwd)))
5123 (or (org-face-from-face-or-color
5124 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5125 (and (member kwd org-done-keywords) 'org-done)
5126 'org-todo))
5128 (defun org-face-from-face-or-color (context inherit face-or-color)
5129 "Create a face list that inherits INHERIT, but sets the foreground color.
5130 When FACE-OR-COLOR is not a string, just return it."
5131 (if (stringp face-or-color)
5132 (list :inherit inherit
5133 (cdr (assoc context org-faces-easy-properties))
5134 face-or-color)
5135 face-or-color))
5137 (defun org-font-lock-add-tag-faces (limit)
5138 "Add the special tag faces."
5139 (when (and org-tag-faces org-tags-special-faces-re)
5140 (while (re-search-forward org-tags-special-faces-re limit t)
5141 (add-text-properties (match-beginning 1) (match-end 1)
5142 (list 'face (org-get-tag-face 1)
5143 'font-lock-fontified t))
5144 (backward-char 1))))
5146 (defun org-font-lock-add-priority-faces (limit)
5147 "Add the special priority faces."
5148 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5149 (add-text-properties
5150 (match-beginning 0) (match-end 0)
5151 (list 'face (or (org-face-from-face-or-color
5152 'priority 'org-special-keyword
5153 (cdr (assoc (char-after (match-beginning 1))
5154 org-priority-faces)))
5155 'org-special-keyword)
5156 'font-lock-fontified t))))
5158 (defun org-get-tag-face (kwd)
5159 "Get the right face for a TODO keyword KWD.
5160 If KWD is a number, get the corresponding match group."
5161 (if (numberp kwd) (setq kwd (match-string kwd)))
5162 (or (org-face-from-face-or-color
5163 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5164 'org-tag))
5166 (defun org-unfontify-region (beg end &optional maybe_loudly)
5167 "Remove fontification and activation overlays from links."
5168 (font-lock-default-unfontify-region beg end)
5169 (let* ((buffer-undo-list t)
5170 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5171 (inhibit-modification-hooks t)
5172 deactivate-mark buffer-file-name buffer-file-truename)
5173 (remove-text-properties
5174 beg end
5175 (if org-indent-mode
5176 ;; also remove line-prefix and wrap-prefix properties
5177 '(mouse-face t keymap t org-linked-text t
5178 invisible t intangible t
5179 line-prefix t wrap-prefix t
5180 org-no-flyspell t)
5181 '(mouse-face t keymap t org-linked-text t
5182 invisible t intangible t
5183 org-no-flyspell t)))))
5185 ;;;; Visibility cycling, including org-goto and indirect buffer
5187 ;;; Cycling
5189 (defvar org-cycle-global-status nil)
5190 (make-variable-buffer-local 'org-cycle-global-status)
5191 (defvar org-cycle-subtree-status nil)
5192 (make-variable-buffer-local 'org-cycle-subtree-status)
5194 ;;;###autoload
5196 (defvar org-inlinetask-min-level)
5198 (defun org-cycle (&optional arg)
5199 "TAB-action and visibility cycling for Org-mode.
5201 This is the command invoked in Org-mode by the TAB key. Its main purpose
5202 is outline visibility cycling, but it also invokes other actions
5203 in special contexts.
5205 - When this function is called with a prefix argument, rotate the entire
5206 buffer through 3 states (global cycling)
5207 1. OVERVIEW: Show only top-level headlines.
5208 2. CONTENTS: Show all headlines of all levels, but no body text.
5209 3. SHOW ALL: Show everything.
5210 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5211 determined by the variable `org-startup-folded', and by any VISIBILITY
5212 properties in the buffer.
5213 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5214 including any drawers.
5216 - When inside a table, re-align the table and move to the next field.
5218 - When point is at the beginning of a headline, rotate the subtree started
5219 by this line through 3 different states (local cycling)
5220 1. FOLDED: Only the main headline is shown.
5221 2. CHILDREN: The main headline and the direct children are shown.
5222 From this state, you can move to one of the children
5223 and zoom in further.
5224 3. SUBTREE: Show the entire subtree, including body text.
5225 If there is no subtree, switch directly from CHILDREN to FOLDED.
5227 - When point is at the beginning of an empty headline and the variable
5228 `org-cycle-level-after-item/entry-creation' is set, cycle the level
5229 of the headline by demoting and promoting it to likely levels. This
5230 speeds up creation document structure by presing TAB once or several
5231 times right after creating a new headline.
5233 - When there is a numeric prefix, go up to a heading with level ARG, do
5234 a `show-subtree' and return to the previous cursor position. If ARG
5235 is negative, go up that many levels.
5237 - When point is not at the beginning of a headline, execute the global
5238 binding for TAB, which is re-indenting the line. See the option
5239 `org-cycle-emulate-tab' for details.
5241 - Special case: if point is at the beginning of the buffer and there is
5242 no headline in line 1, this function will act as if called with prefix arg.
5243 But only if also the variable `org-cycle-global-at-bob' is t."
5244 (interactive "P")
5245 (org-load-modules-maybe)
5246 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5247 (and org-cycle-level-after-item/entry-creation
5248 (or (org-cycle-level)
5249 (org-cycle-item-indentation))))
5250 (let* ((limit-level
5251 (or org-cycle-max-level
5252 (and (boundp 'org-inlinetask-min-level)
5253 org-inlinetask-min-level
5254 (1- org-inlinetask-min-level))))
5255 (nstars (and limit-level
5256 (if org-odd-levels-only
5257 (and limit-level (1- (* limit-level 2)))
5258 limit-level)))
5259 (outline-regexp
5260 (cond
5261 ((not (org-mode-p)) outline-regexp)
5262 ((or (eq org-cycle-include-plain-lists 'integrate)
5263 (and org-cycle-include-plain-lists (org-at-item-p)))
5264 (concat "\\(?:\\*"
5265 (if nstars (format "\\{1,%d\\}" nstars) "+")
5266 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5267 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
5268 (bob-special (and org-cycle-global-at-bob (bobp)
5269 (not (looking-at outline-regexp))))
5270 (org-cycle-hook
5271 (if bob-special
5272 (delq 'org-optimize-window-after-visibility-change
5273 (copy-sequence org-cycle-hook))
5274 org-cycle-hook))
5275 (pos (point)))
5277 (if (or bob-special (equal arg '(4)))
5278 ;; special case: use global cycling
5279 (setq arg t))
5281 (cond
5283 ((equal arg '(16))
5284 (org-set-startup-visibility)
5285 (message "Startup visibility, plus VISIBILITY properties"))
5287 ((equal arg '(64))
5288 (show-all)
5289 (message "Entire buffer visible, including drawers"))
5291 ((org-at-table-p 'any)
5292 ;; Enter the table or move to the next field in the table
5293 (if (org-at-table.el-p)
5294 (message "Use C-c ' to edit table.el tables")
5295 (if arg (org-table-edit-field t)
5296 (org-table-justify-field-maybe)
5297 (call-interactively 'org-table-next-field))))
5299 ((run-hook-with-args-until-success
5300 'org-tab-after-check-for-table-hook))
5302 ((eq arg t) ;; Global cycling
5303 (org-cycle-internal-global))
5305 ((and org-drawers org-drawer-regexp
5306 (save-excursion
5307 (beginning-of-line 1)
5308 (looking-at org-drawer-regexp)))
5309 ;; Toggle block visibility
5310 (org-flag-drawer
5311 (not (get-char-property (match-end 0) 'invisible))))
5313 ((integerp arg)
5314 ;; Show-subtree, ARG levels up from here.
5315 (save-excursion
5316 (org-back-to-heading)
5317 (outline-up-heading (if (< arg 0) (- arg)
5318 (- (funcall outline-level) arg)))
5319 (org-show-subtree)))
5321 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5322 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5324 (org-cycle-internal-local))
5326 ;; TAB emulation and template completion
5327 (buffer-read-only (org-back-to-heading))
5329 ((run-hook-with-args-until-success
5330 'org-tab-after-check-for-cycling-hook))
5332 ((org-try-structure-completion))
5334 ((org-try-cdlatex-tab))
5336 ((run-hook-with-args-until-success
5337 'org-tab-before-tab-emulation-hook))
5339 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5340 (or (not (bolp))
5341 (not (looking-at outline-regexp))))
5342 (call-interactively (global-key-binding "\t")))
5344 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5345 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5346 (or (and (eq org-cycle-emulate-tab 'white)
5347 (= (match-end 0) (point-at-eol)))
5348 (and (eq org-cycle-emulate-tab 'whitestart)
5349 (>= (match-end 0) pos))))
5351 (eq org-cycle-emulate-tab t))
5352 (call-interactively (global-key-binding "\t")))
5354 (t (save-excursion
5355 (org-back-to-heading)
5356 (org-cycle)))))))
5358 (defun org-cycle-internal-global ()
5359 "Do the global cycling action."
5360 (cond
5361 ((and (eq last-command this-command)
5362 (eq org-cycle-global-status 'overview))
5363 ;; We just created the overview - now do table of contents
5364 ;; This can be slow in very large buffers, so indicate action
5365 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5366 (message "CONTENTS...")
5367 (org-content)
5368 (message "CONTENTS...done")
5369 (setq org-cycle-global-status 'contents)
5370 (run-hook-with-args 'org-cycle-hook 'contents))
5372 ((and (eq last-command this-command)
5373 (eq org-cycle-global-status 'contents))
5374 ;; We just showed the table of contents - now show everything
5375 (run-hook-with-args 'org-pre-cycle-hook 'all)
5376 (show-all)
5377 (message "SHOW ALL")
5378 (setq org-cycle-global-status 'all)
5379 (run-hook-with-args 'org-cycle-hook 'all))
5382 ;; Default action: go to overview
5383 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5384 (org-overview)
5385 (message "OVERVIEW")
5386 (setq org-cycle-global-status 'overview)
5387 (run-hook-with-args 'org-cycle-hook 'overview))))
5389 (defun org-cycle-internal-local ()
5390 "Do the local cycling action."
5391 (org-back-to-heading)
5392 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5393 ;; First, some boundaries
5394 (save-excursion
5395 (org-back-to-heading)
5396 (setq level (funcall outline-level))
5397 (save-excursion
5398 (beginning-of-line 2)
5399 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5400 ; XEmacs does not have `next-single-char-property-change'
5401 ; I'm not sure about Emacs 21.
5402 (while (and (not (eobp)) ;; this is like `next-line'
5403 (get-char-property (1- (point)) 'invisible))
5404 (beginning-of-line 2))
5405 (while (and (not (eobp)) ;; this is like `next-line'
5406 (get-char-property (1- (point)) 'invisible))
5407 (goto-char (next-single-char-property-change (point) 'invisible))
5408 ;;;??? (or (bolp) (beginning-of-line 2))))
5409 (and (eolp) (beginning-of-line 2))))
5410 (setq eol (point)))
5411 (outline-end-of-heading) (setq eoh (point))
5412 (save-excursion
5413 (outline-next-heading)
5414 (setq has-children (and (org-at-heading-p t)
5415 (> (funcall outline-level) level))))
5416 (org-end-of-subtree t)
5417 (unless (eobp)
5418 (skip-chars-forward " \t\n")
5419 (beginning-of-line 1) ; in case this is an item
5421 (setq eos (if (eobp) (point) (1- (point)))))
5422 ;; Find out what to do next and set `this-command'
5423 (cond
5424 ((= eos eoh)
5425 ;; Nothing is hidden behind this heading
5426 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5427 (message "EMPTY ENTRY")
5428 (setq org-cycle-subtree-status nil)
5429 (save-excursion
5430 (goto-char eos)
5431 (outline-next-heading)
5432 (if (org-invisible-p) (org-flag-heading nil))))
5433 ((and (or (>= eol eos)
5434 (not (string-match "\\S-" (buffer-substring eol eos))))
5435 (or has-children
5436 (not (setq children-skipped
5437 org-cycle-skip-children-state-if-no-children))))
5438 ;; Entire subtree is hidden in one line: children view
5439 (run-hook-with-args 'org-pre-cycle-hook 'children)
5440 (org-show-entry)
5441 (show-children)
5442 (message "CHILDREN")
5443 (save-excursion
5444 (goto-char eos)
5445 (outline-next-heading)
5446 (if (org-invisible-p) (org-flag-heading nil)))
5447 (setq org-cycle-subtree-status 'children)
5448 (run-hook-with-args 'org-cycle-hook 'children))
5449 ((or children-skipped
5450 (and (eq last-command this-command)
5451 (eq org-cycle-subtree-status 'children)))
5452 ;; We just showed the children, or no children are there,
5453 ;; now show everything.
5454 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5455 (org-show-subtree)
5456 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5457 (setq org-cycle-subtree-status 'subtree)
5458 (run-hook-with-args 'org-cycle-hook 'subtree))
5460 ;; Default action: hide the subtree.
5461 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5462 (hide-subtree)
5463 (message "FOLDED")
5464 (setq org-cycle-subtree-status 'folded)
5465 (run-hook-with-args 'org-cycle-hook 'folded)))))
5467 ;;;###autoload
5468 (defun org-global-cycle (&optional arg)
5469 "Cycle the global visibility. For details see `org-cycle'.
5470 With C-u prefix arg, switch to startup visibility.
5471 With a numeric prefix, show all headlines up to that level."
5472 (interactive "P")
5473 (let ((org-cycle-include-plain-lists
5474 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5475 (cond
5476 ((integerp arg)
5477 (show-all)
5478 (hide-sublevels arg)
5479 (setq org-cycle-global-status 'contents))
5480 ((equal arg '(4))
5481 (org-set-startup-visibility)
5482 (message "Startup visibility, plus VISIBILITY properties."))
5484 (org-cycle '(4))))))
5486 (defun org-set-startup-visibility ()
5487 "Set the visibility required by startup options and properties."
5488 (cond
5489 ((eq org-startup-folded t)
5490 (org-cycle '(4)))
5491 ((eq org-startup-folded 'content)
5492 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5493 (org-cycle '(4)) (org-cycle '(4)))))
5494 (unless (eq org-startup-folded 'showeverything)
5495 (if org-hide-block-startup (org-hide-block-all))
5496 (org-set-visibility-according-to-property 'no-cleanup)
5497 (org-cycle-hide-archived-subtrees 'all)
5498 (org-cycle-hide-drawers 'all)
5499 (org-cycle-show-empty-lines 'all)))
5501 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5502 "Switch subtree visibilities according to :VISIBILITY: property."
5503 (interactive)
5504 (let (org-show-entry-below state)
5505 (save-excursion
5506 (goto-char (point-min))
5507 (while (re-search-forward
5508 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5509 nil t)
5510 (setq state (match-string 1))
5511 (save-excursion
5512 (org-back-to-heading t)
5513 (hide-subtree)
5514 (org-reveal)
5515 (cond
5516 ((equal state '("fold" "folded"))
5517 (hide-subtree))
5518 ((equal state "children")
5519 (org-show-hidden-entry)
5520 (show-children))
5521 ((equal state "content")
5522 (save-excursion
5523 (save-restriction
5524 (org-narrow-to-subtree)
5525 (org-content))))
5526 ((member state '("all" "showall"))
5527 (show-subtree)))))
5528 (unless no-cleanup
5529 (org-cycle-hide-archived-subtrees 'all)
5530 (org-cycle-hide-drawers 'all)
5531 (org-cycle-show-empty-lines 'all)))))
5533 (defun org-overview ()
5534 "Switch to overview mode, showing only top-level headlines.
5535 Really, this shows all headlines with level equal or greater than the level
5536 of the first headline in the buffer. This is important, because if the
5537 first headline is not level one, then (hide-sublevels 1) gives confusing
5538 results."
5539 (interactive)
5540 (let ((level (save-excursion
5541 (goto-char (point-min))
5542 (if (re-search-forward (concat "^" outline-regexp) nil t)
5543 (progn
5544 (goto-char (match-beginning 0))
5545 (funcall outline-level))))))
5546 (and level (hide-sublevels level))))
5548 (defun org-content (&optional arg)
5549 "Show all headlines in the buffer, like a table of contents.
5550 With numerical argument N, show content up to level N."
5551 (interactive "P")
5552 (save-excursion
5553 ;; Visit all headings and show their offspring
5554 (and (integerp arg) (org-overview))
5555 (goto-char (point-max))
5556 (catch 'exit
5557 (while (and (progn (condition-case nil
5558 (outline-previous-visible-heading 1)
5559 (error (goto-char (point-min))))
5561 (looking-at outline-regexp))
5562 (if (integerp arg)
5563 (show-children (1- arg))
5564 (show-branches))
5565 (if (bobp) (throw 'exit nil))))))
5568 (defun org-optimize-window-after-visibility-change (state)
5569 "Adjust the window after a change in outline visibility.
5570 This function is the default value of the hook `org-cycle-hook'."
5571 (when (get-buffer-window (current-buffer))
5572 (cond
5573 ((eq state 'content) nil)
5574 ((eq state 'all) nil)
5575 ((eq state 'folded) nil)
5576 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5577 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5579 (defun org-remove-empty-overlays-at (pos)
5580 "Remove outline overlays that do not contain non-white stuff."
5581 (mapc
5582 (lambda (o)
5583 (and (eq 'outline (org-overlay-get o 'invisible))
5584 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5585 (org-overlay-end o))))
5586 (org-delete-overlay o)))
5587 (org-overlays-at pos)))
5589 (defun org-clean-visibility-after-subtree-move ()
5590 "Fix visibility issues after moving a subtree."
5591 ;; First, find a reasonable region to look at:
5592 ;; Start two siblings above, end three below
5593 (let* ((beg (save-excursion
5594 (and (org-get-last-sibling)
5595 (org-get-last-sibling))
5596 (point)))
5597 (end (save-excursion
5598 (and (org-get-next-sibling)
5599 (org-get-next-sibling)
5600 (org-get-next-sibling))
5601 (if (org-at-heading-p)
5602 (point-at-eol)
5603 (point))))
5604 (level (looking-at "\\*+"))
5605 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5606 (save-excursion
5607 (save-restriction
5608 (narrow-to-region beg end)
5609 (when re
5610 ;; Properly fold already folded siblings
5611 (goto-char (point-min))
5612 (while (re-search-forward re nil t)
5613 (if (and (not (org-invisible-p))
5614 (save-excursion
5615 (goto-char (point-at-eol)) (org-invisible-p)))
5616 (hide-entry))))
5617 (org-cycle-show-empty-lines 'overview)
5618 (org-cycle-hide-drawers 'overview)))))
5620 (defun org-cycle-show-empty-lines (state)
5621 "Show empty lines above all visible headlines.
5622 The region to be covered depends on STATE when called through
5623 `org-cycle-hook'. Lisp program can use t for STATE to get the
5624 entire buffer covered. Note that an empty line is only shown if there
5625 are at least `org-cycle-separator-lines' empty lines before the headline."
5626 (when (not (= org-cycle-separator-lines 0))
5627 (save-excursion
5628 (let* ((n (abs org-cycle-separator-lines))
5629 (re (cond
5630 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5631 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5632 (t (let ((ns (number-to-string (- n 2))))
5633 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5634 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5635 beg end b e)
5636 (cond
5637 ((memq state '(overview contents t))
5638 (setq beg (point-min) end (point-max)))
5639 ((memq state '(children folded))
5640 (setq beg (point) end (progn (org-end-of-subtree t t)
5641 (beginning-of-line 2)
5642 (point)))))
5643 (when beg
5644 (goto-char beg)
5645 (while (re-search-forward re end t)
5646 (unless (get-char-property (match-end 1) 'invisible)
5647 (setq e (match-end 1))
5648 (if (< org-cycle-separator-lines 0)
5649 (setq b (save-excursion
5650 (goto-char (match-beginning 0))
5651 (org-back-over-empty-lines)
5652 (if (save-excursion
5653 (goto-char (max (point-min) (1- (point))))
5654 (org-on-heading-p))
5655 (1- (point))
5656 (point))))
5657 (setq b (match-beginning 1)))
5658 (outline-flag-region b e nil)))))))
5659 ;; Never hide empty lines at the end of the file.
5660 (save-excursion
5661 (goto-char (point-max))
5662 (outline-previous-heading)
5663 (outline-end-of-heading)
5664 (if (and (looking-at "[ \t\n]+")
5665 (= (match-end 0) (point-max)))
5666 (outline-flag-region (point) (match-end 0) nil))))
5668 (defun org-show-empty-lines-in-parent ()
5669 "Move to the parent and re-show empty lines before visible headlines."
5670 (save-excursion
5671 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5672 (org-cycle-show-empty-lines context))))
5674 (defun org-files-list ()
5675 "Return `org-agenda-files' list, plus all open org-mode files.
5676 This is useful for operations that need to scan all of a user's
5677 open and agenda-wise Org files."
5678 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
5679 (dolist (buf (buffer-list))
5680 (with-current-buffer buf
5681 (if (and (eq major-mode 'org-mode) (buffer-file-name))
5682 (let ((file (expand-file-name (buffer-file-name))))
5683 (unless (member file files)
5684 (push file files))))))
5685 files))
5687 (defsubst org-entry-beginning-position ()
5688 "Return the beginning position of the current entry."
5689 (save-excursion (outline-back-to-heading t) (point)))
5691 (defsubst org-entry-end-position ()
5692 "Return the end position of the current entry."
5693 (save-excursion (outline-next-heading) (point)))
5695 (defun org-cycle-hide-drawers (state)
5696 "Re-hide all drawers after a visibility state change."
5697 (when (and (org-mode-p)
5698 (not (memq state '(overview folded contents))))
5699 (save-excursion
5700 (let* ((globalp (memq state '(contents all)))
5701 (beg (if globalp (point-min) (point)))
5702 (end (if globalp (point-max)
5703 (if (eq state 'children)
5704 (save-excursion (outline-next-heading) (point))
5705 (org-end-of-subtree t)))))
5706 (goto-char beg)
5707 (while (re-search-forward org-drawer-regexp end t)
5708 (org-flag-drawer t))))))
5710 (defun org-flag-drawer (flag)
5711 (save-excursion
5712 (beginning-of-line 1)
5713 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5714 (let ((b (match-end 0))
5715 (outline-regexp org-outline-regexp))
5716 (if (re-search-forward
5717 "^[ \t]*:END:"
5718 (save-excursion (outline-next-heading) (point)) t)
5719 (outline-flag-region b (point-at-eol) flag)
5720 (error ":END: line missing at position %s" b))))))
5722 (defun org-subtree-end-visible-p ()
5723 "Is the end of the current subtree visible?"
5724 (pos-visible-in-window-p
5725 (save-excursion (org-end-of-subtree t) (point))))
5727 (defun org-first-headline-recenter (&optional N)
5728 "Move cursor to the first headline and recenter the headline.
5729 Optional argument N means put the headline into the Nth line of the window."
5730 (goto-char (point-min))
5731 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5732 (beginning-of-line)
5733 (recenter (prefix-numeric-value N))))
5735 ;;; Saving and restoring visibility
5737 (defun org-outline-overlay-data (&optional use-markers)
5738 "Return a list of the locations of all outline overlays.
5739 The are overlays with the `invisible' property value `outline'.
5740 The return valus is a list of cons cells, with start and stop
5741 positions for each overlay.
5742 If USE-MARKERS is set, return the positions as markers."
5743 (let (beg end)
5744 (save-excursion
5745 (save-restriction
5746 (widen)
5747 (delq nil
5748 (mapcar (lambda (o)
5749 (when (eq (org-overlay-get o 'invisible) 'outline)
5750 (setq beg (org-overlay-start o)
5751 end (org-overlay-end o))
5752 (and beg end (> end beg)
5753 (if use-markers
5754 (cons (move-marker (make-marker) beg)
5755 (move-marker (make-marker) end))
5756 (cons beg end)))))
5757 (org-overlays-in (point-min) (point-max))))))))
5759 (defun org-set-outline-overlay-data (data)
5760 "Create visibility overlays for all positions in DATA.
5761 DATA should have been made by `org-outline-overlay-data'."
5762 (let (o)
5763 (save-excursion
5764 (save-restriction
5765 (widen)
5766 (show-all)
5767 (mapc (lambda (c)
5768 (setq o (org-make-overlay (car c) (cdr c)))
5769 (org-overlay-put o 'invisible 'outline))
5770 data)))))
5772 (defmacro org-save-outline-visibility (use-markers &rest body)
5773 "Save and restore outline visibility around BODY.
5774 If USE-MARKERS is non-nil, use markers for the positions.
5775 This means that the buffer may change while running BODY,
5776 but it also means that the buffer should stay alive
5777 during the operation, because otherwise all these markers will
5778 point nowhere."
5779 `(let ((data (org-outline-overlay-data ,use-markers)))
5780 (unwind-protect
5781 (progn
5782 ,@body
5783 (org-set-outline-overlay-data data))
5784 (when ,use-markers
5785 (mapc (lambda (c)
5786 (and (markerp (car c)) (move-marker (car c) nil))
5787 (and (markerp (cdr c)) (move-marker (cdr c) nil)))
5788 data)))))
5791 ;;; Folding of blocks
5793 (defconst org-block-regexp
5795 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5796 "Regular expression for hiding blocks.")
5798 (defvar org-hide-block-overlays nil
5799 "Overlays hiding blocks.")
5800 (make-variable-buffer-local 'org-hide-block-overlays)
5802 (defun org-block-map (function &optional start end)
5803 "Call func at the head of all source blocks in the current
5804 buffer. Optional arguments START and END can be used to limit
5805 the range."
5806 (let ((start (or start (point-min)))
5807 (end (or end (point-max))))
5808 (save-excursion
5809 (goto-char start)
5810 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5811 (save-excursion
5812 (save-match-data
5813 (goto-char (match-beginning 0))
5814 (funcall function)))))))
5816 (defun org-hide-block-toggle-all ()
5817 "Toggle the visibility of all blocks in the current buffer."
5818 (org-block-map #'org-hide-block-toggle))
5820 (defun org-hide-block-all ()
5821 "Fold all blocks in the current buffer."
5822 (interactive)
5823 (org-show-block-all)
5824 (org-block-map #'org-hide-block-toggle-maybe))
5826 (defun org-show-block-all ()
5827 "Unfold all blocks in the current buffer."
5828 (mapc 'org-delete-overlay org-hide-block-overlays)
5829 (setq org-hide-block-overlays nil))
5831 (defun org-hide-block-toggle-maybe ()
5832 "Toggle visibility of block at point."
5833 (interactive)
5834 (let ((case-fold-search t))
5835 (if (save-excursion
5836 (beginning-of-line 1)
5837 (looking-at org-block-regexp))
5838 (progn (org-hide-block-toggle)
5839 t) ;; to signal that we took action
5840 nil))) ;; to signal that we did not
5842 (defun org-hide-block-toggle (&optional force)
5843 "Toggle the visibility of the current block."
5844 (interactive)
5845 (save-excursion
5846 (beginning-of-line)
5847 (if (re-search-forward org-block-regexp nil t)
5848 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5849 (end (match-end 0)) ;; end of entire body
5851 (if (memq t (mapcar (lambda (overlay)
5852 (eq (org-overlay-get overlay 'invisible)
5853 'org-hide-block))
5854 (org-overlays-at start)))
5855 (if (or (not force) (eq force 'off))
5856 (mapc (lambda (ov)
5857 (when (member ov org-hide-block-overlays)
5858 (setq org-hide-block-overlays
5859 (delq ov org-hide-block-overlays)))
5860 (when (eq (org-overlay-get ov 'invisible)
5861 'org-hide-block)
5862 (org-delete-overlay ov)))
5863 (org-overlays-at start)))
5864 (setq ov (org-make-overlay start end))
5865 (org-overlay-put ov 'invisible 'org-hide-block)
5866 ;; make the block accessible to isearch
5867 (org-overlay-put
5868 ov 'isearch-open-invisible
5869 (lambda (ov)
5870 (when (member ov org-hide-block-overlays)
5871 (setq org-hide-block-overlays
5872 (delq ov org-hide-block-overlays)))
5873 (when (eq (org-overlay-get ov 'invisible)
5874 'org-hide-block)
5875 (org-delete-overlay ov))))
5876 (push ov org-hide-block-overlays)))
5877 (error "Not looking at a source block"))))
5879 ;; org-tab-after-check-for-cycling-hook
5880 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5881 ;; Remove overlays when changing major mode
5882 (add-hook 'org-mode-hook
5883 (lambda () (org-add-hook 'change-major-mode-hook
5884 'org-show-block-all 'append 'local)))
5886 ;;; Org-goto
5888 (defvar org-goto-window-configuration nil)
5889 (defvar org-goto-marker nil)
5890 (defvar org-goto-map
5891 (let ((map (make-sparse-keymap)))
5892 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5893 (while (setq cmd (pop cmds))
5894 (substitute-key-definition cmd cmd map global-map)))
5895 (suppress-keymap map)
5896 (org-defkey map "\C-m" 'org-goto-ret)
5897 (org-defkey map [(return)] 'org-goto-ret)
5898 (org-defkey map [(left)] 'org-goto-left)
5899 (org-defkey map [(right)] 'org-goto-right)
5900 (org-defkey map [(control ?g)] 'org-goto-quit)
5901 (org-defkey map "\C-i" 'org-cycle)
5902 (org-defkey map [(tab)] 'org-cycle)
5903 (org-defkey map [(down)] 'outline-next-visible-heading)
5904 (org-defkey map [(up)] 'outline-previous-visible-heading)
5905 (if org-goto-auto-isearch
5906 (if (fboundp 'define-key-after)
5907 (define-key-after map [t] 'org-goto-local-auto-isearch)
5908 nil)
5909 (org-defkey map "q" 'org-goto-quit)
5910 (org-defkey map "n" 'outline-next-visible-heading)
5911 (org-defkey map "p" 'outline-previous-visible-heading)
5912 (org-defkey map "f" 'outline-forward-same-level)
5913 (org-defkey map "b" 'outline-backward-same-level)
5914 (org-defkey map "u" 'outline-up-heading))
5915 (org-defkey map "/" 'org-occur)
5916 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5917 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5918 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5919 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5920 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5921 map))
5923 (defconst org-goto-help
5924 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5925 RET=jump to location [Q]uit and return to previous location
5926 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5928 (defvar org-goto-start-pos) ; dynamically scoped parameter
5930 ;; FIXME: Docstring does not mention both interfaces
5931 (defun org-goto (&optional alternative-interface)
5932 "Look up a different location in the current file, keeping current visibility.
5934 When you want look-up or go to a different location in a document, the
5935 fastest way is often to fold the entire buffer and then dive into the tree.
5936 This method has the disadvantage, that the previous location will be folded,
5937 which may not be what you want.
5939 This command works around this by showing a copy of the current buffer
5940 in an indirect buffer, in overview mode. You can dive into the tree in
5941 that copy, use org-occur and incremental search to find a location.
5942 When pressing RET or `Q', the command returns to the original buffer in
5943 which the visibility is still unchanged. After RET is will also jump to
5944 the location selected in the indirect buffer and expose the
5945 the headline hierarchy above."
5946 (interactive "P")
5947 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5948 (org-refile-use-outline-path t)
5949 (org-refile-target-verify-function nil)
5950 (interface
5951 (if (not alternative-interface)
5952 org-goto-interface
5953 (if (eq org-goto-interface 'outline)
5954 'outline-path-completion
5955 'outline)))
5956 (org-goto-start-pos (point))
5957 (selected-point
5958 (if (eq interface 'outline)
5959 (car (org-get-location (current-buffer) org-goto-help))
5960 (nth 3 (org-refile-get-location "Goto: ")))))
5961 (if selected-point
5962 (progn
5963 (org-mark-ring-push org-goto-start-pos)
5964 (goto-char selected-point)
5965 (if (or (org-invisible-p) (org-invisible-p2))
5966 (org-show-context 'org-goto)))
5967 (message "Quit"))))
5969 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5970 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5971 (defvar org-goto-local-auto-isearch-map) ; defined below
5973 (defun org-get-location (buf help)
5974 "Let the user select a location in the Org-mode buffer BUF.
5975 This function uses a recursive edit. It returns the selected position
5976 or nil."
5977 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5978 (isearch-hide-immediately nil)
5979 (isearch-search-fun-function
5980 (lambda () 'org-goto-local-search-headings))
5981 (org-goto-selected-point org-goto-exit-command)
5982 (pop-up-frames nil)
5983 (special-display-buffer-names nil)
5984 (special-display-regexps nil)
5985 (special-display-function nil))
5986 (save-excursion
5987 (save-window-excursion
5988 (delete-other-windows)
5989 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5990 (switch-to-buffer
5991 (condition-case nil
5992 (make-indirect-buffer (current-buffer) "*org-goto*")
5993 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5994 (with-output-to-temp-buffer "*Help*"
5995 (princ help))
5996 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5997 (setq buffer-read-only nil)
5998 (let ((org-startup-truncated t)
5999 (org-startup-folded nil)
6000 (org-startup-align-all-tables nil))
6001 (org-mode)
6002 (org-overview))
6003 (setq buffer-read-only t)
6004 (if (and (boundp 'org-goto-start-pos)
6005 (integer-or-marker-p org-goto-start-pos))
6006 (let ((org-show-hierarchy-above t)
6007 (org-show-siblings t)
6008 (org-show-following-heading t))
6009 (goto-char org-goto-start-pos)
6010 (and (org-invisible-p) (org-show-context)))
6011 (goto-char (point-min)))
6012 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6013 (message "Select location and press RET")
6014 (use-local-map org-goto-map)
6015 (recursive-edit)
6017 (kill-buffer "*org-goto*")
6018 (cons org-goto-selected-point org-goto-exit-command)))
6020 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6021 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6022 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6023 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6025 (defun org-goto-local-search-headings (string bound noerror)
6026 "Search and make sure that any matches are in headlines."
6027 (catch 'return
6028 (while (if isearch-forward
6029 (search-forward string bound noerror)
6030 (search-backward string bound noerror))
6031 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6032 (and (member :headline context)
6033 (not (member :tags context))))
6034 (throw 'return (point))))))
6036 (defun org-goto-local-auto-isearch ()
6037 "Start isearch."
6038 (interactive)
6039 (goto-char (point-min))
6040 (let ((keys (this-command-keys)))
6041 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6042 (isearch-mode t)
6043 (isearch-process-search-char (string-to-char keys)))))
6045 (defun org-goto-ret (&optional arg)
6046 "Finish `org-goto' by going to the new location."
6047 (interactive "P")
6048 (setq org-goto-selected-point (point)
6049 org-goto-exit-command 'return)
6050 (throw 'exit nil))
6052 (defun org-goto-left ()
6053 "Finish `org-goto' by going to the new location."
6054 (interactive)
6055 (if (org-on-heading-p)
6056 (progn
6057 (beginning-of-line 1)
6058 (setq org-goto-selected-point (point)
6059 org-goto-exit-command 'left)
6060 (throw 'exit nil))
6061 (error "Not on a heading")))
6063 (defun org-goto-right ()
6064 "Finish `org-goto' by going to the new location."
6065 (interactive)
6066 (if (org-on-heading-p)
6067 (progn
6068 (setq org-goto-selected-point (point)
6069 org-goto-exit-command 'right)
6070 (throw 'exit nil))
6071 (error "Not on a heading")))
6073 (defun org-goto-quit ()
6074 "Finish `org-goto' without cursor motion."
6075 (interactive)
6076 (setq org-goto-selected-point nil)
6077 (setq org-goto-exit-command 'quit)
6078 (throw 'exit nil))
6080 ;;; Indirect buffer display of subtrees
6082 (defvar org-indirect-dedicated-frame nil
6083 "This is the frame being used for indirect tree display.")
6084 (defvar org-last-indirect-buffer nil)
6086 (defun org-tree-to-indirect-buffer (&optional arg)
6087 "Create indirect buffer and narrow it to current subtree.
6088 With numerical prefix ARG, go up to this level and then take that tree.
6089 If ARG is negative, go up that many levels.
6090 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6091 indirect buffer previously made with this command, to avoid proliferation of
6092 indirect buffers. However, when you call the command with a `C-u' prefix, or
6093 when `org-indirect-buffer-display' is `new-frame', the last buffer
6094 is kept so that you can work with several indirect buffers at the same time.
6095 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6096 requests that a new frame be made for the new buffer, so that the dedicated
6097 frame is not changed."
6098 (interactive "P")
6099 (let ((cbuf (current-buffer))
6100 (cwin (selected-window))
6101 (pos (point))
6102 beg end level heading ibuf)
6103 (save-excursion
6104 (org-back-to-heading t)
6105 (when (numberp arg)
6106 (setq level (org-outline-level))
6107 (if (< arg 0) (setq arg (+ level arg)))
6108 (while (> (setq level (org-outline-level)) arg)
6109 (outline-up-heading 1 t)))
6110 (setq beg (point)
6111 heading (org-get-heading))
6112 (org-end-of-subtree t t)
6113 (if (org-on-heading-p) (backward-char 1))
6114 (setq end (point)))
6115 (if (and (buffer-live-p org-last-indirect-buffer)
6116 (not (eq org-indirect-buffer-display 'new-frame))
6117 (not arg))
6118 (kill-buffer org-last-indirect-buffer))
6119 (setq ibuf (org-get-indirect-buffer cbuf)
6120 org-last-indirect-buffer ibuf)
6121 (cond
6122 ((or (eq org-indirect-buffer-display 'new-frame)
6123 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6124 (select-frame (make-frame))
6125 (delete-other-windows)
6126 (switch-to-buffer ibuf)
6127 (org-set-frame-title heading))
6128 ((eq org-indirect-buffer-display 'dedicated-frame)
6129 (raise-frame
6130 (select-frame (or (and org-indirect-dedicated-frame
6131 (frame-live-p org-indirect-dedicated-frame)
6132 org-indirect-dedicated-frame)
6133 (setq org-indirect-dedicated-frame (make-frame)))))
6134 (delete-other-windows)
6135 (switch-to-buffer ibuf)
6136 (org-set-frame-title (concat "Indirect: " heading)))
6137 ((eq org-indirect-buffer-display 'current-window)
6138 (switch-to-buffer ibuf))
6139 ((eq org-indirect-buffer-display 'other-window)
6140 (pop-to-buffer ibuf))
6141 (t (error "Invalid value")))
6142 (if (featurep 'xemacs)
6143 (save-excursion (org-mode) (turn-on-font-lock)))
6144 (narrow-to-region beg end)
6145 (show-all)
6146 (goto-char pos)
6147 (and (window-live-p cwin) (select-window cwin))))
6149 (defun org-get-indirect-buffer (&optional buffer)
6150 (setq buffer (or buffer (current-buffer)))
6151 (let ((n 1) (base (buffer-name buffer)) bname)
6152 (while (buffer-live-p
6153 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6154 (setq n (1+ n)))
6155 (condition-case nil
6156 (make-indirect-buffer buffer bname 'clone)
6157 (error (make-indirect-buffer buffer bname)))))
6159 (defun org-set-frame-title (title)
6160 "Set the title of the current frame to the string TITLE."
6161 ;; FIXME: how to name a single frame in XEmacs???
6162 (unless (featurep 'xemacs)
6163 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6165 ;;;; Structure editing
6167 ;;; Inserting headlines
6169 (defun org-previous-line-empty-p ()
6170 (save-excursion
6171 (and (not (bobp))
6172 (or (beginning-of-line 0) t)
6173 (save-match-data
6174 (looking-at "[ \t]*$")))))
6176 (defun org-insert-heading (&optional force-heading invisible-ok)
6177 "Insert a new heading or item with same depth at point.
6178 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6179 If point is at the beginning of a headline, insert a sibling before the
6180 current headline. If point is not at the beginning, do not split the line,
6181 but create the new headline after the current line.
6182 When INVISIBLE-OK is set, stop at invisible headlines when going back.
6183 This is important for non-interactive uses of the command."
6184 (interactive "P")
6185 (if (or (= (buffer-size) 0)
6186 (and (not (save-excursion (and (ignore-errors (org-back-to-heading invisible-ok))
6187 (org-on-heading-p))))
6188 (not (org-in-item-p))))
6189 (insert "\n* ")
6190 (when (or force-heading (not (org-insert-item)))
6191 (let* ((empty-line-p nil)
6192 (head (save-excursion
6193 (condition-case nil
6194 (progn
6195 (org-back-to-heading invisible-ok)
6196 (setq empty-line-p (org-previous-line-empty-p))
6197 (match-string 0))
6198 (error "*"))))
6199 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6200 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6201 pos hide-previous previous-pos)
6202 (cond
6203 ((and (org-on-heading-p) (bolp)
6204 (or (bobp)
6205 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6206 ;; insert before the current line
6207 (open-line (if blank 2 1)))
6208 ((and (bolp)
6209 (not org-insert-heading-respect-content)
6210 (or (bobp)
6211 (save-excursion
6212 (backward-char 1) (not (org-invisible-p)))))
6213 ;; insert right here
6214 nil)
6216 ;; somewhere in the line
6217 (save-excursion
6218 (setq previous-pos (point-at-bol))
6219 (end-of-line)
6220 (setq hide-previous (org-invisible-p)))
6221 (and org-insert-heading-respect-content (org-show-subtree))
6222 (let ((split
6223 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6224 (save-excursion
6225 (let ((p (point)))
6226 (goto-char (point-at-bol))
6227 (and (looking-at org-complex-heading-regexp)
6228 (> p (match-beginning 4)))))))
6229 tags pos)
6230 (cond
6231 (org-insert-heading-respect-content
6232 (org-end-of-subtree nil t)
6233 (or (bolp) (newline))
6234 (or (org-previous-line-empty-p)
6235 (and blank (newline)))
6236 (open-line 1))
6237 ((org-on-heading-p)
6238 (when hide-previous
6239 (show-children)
6240 (org-show-entry))
6241 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6242 (setq tags (and (match-end 2) (match-string 2)))
6243 (and (match-end 1)
6244 (delete-region (match-beginning 1) (match-end 1)))
6245 (setq pos (point-at-bol))
6246 (or split (end-of-line 1))
6247 (delete-horizontal-space)
6248 (if (string-match "\\`\\*+\\'"
6249 (buffer-substring (point-at-bol) (point)))
6250 (insert " "))
6251 (newline (if blank 2 1))
6252 (when tags
6253 (save-excursion
6254 (goto-char pos)
6255 (end-of-line 1)
6256 (insert " " tags)
6257 (org-set-tags nil 'align))))
6259 (or split (end-of-line 1))
6260 (newline (if blank 2 1)))))))
6261 (insert head) (just-one-space)
6262 (setq pos (point))
6263 (end-of-line 1)
6264 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6265 (when (and org-insert-heading-respect-content hide-previous)
6266 (save-excursion
6267 (goto-char previous-pos)
6268 (hide-subtree)))
6269 (run-hooks 'org-insert-heading-hook)))))
6271 (defun org-get-heading (&optional no-tags)
6272 "Return the heading of the current entry, without the stars."
6273 (save-excursion
6274 (org-back-to-heading t)
6275 (if (looking-at
6276 (if no-tags
6277 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
6278 "\\*+[ \t]+\\([^\r\n]*\\)"))
6279 (match-string 1) "")))
6281 (defun org-heading-components ()
6282 "Return the components of the current heading.
6283 This is a list with the following elements:
6284 - the level as an integer
6285 - the reduced level, different if `org-odd-levels-only' is set.
6286 - the TODO keyword, or nil
6287 - the priority character, like ?A, or nil if no priority is given
6288 - the headline text itself, or the tags string if no headline text
6289 - the tags string, or nil."
6290 (save-excursion
6291 (org-back-to-heading t)
6292 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
6293 (list (length (match-string 1))
6294 (org-reduced-level (length (match-string 1)))
6295 (org-match-string-no-properties 2)
6296 (and (match-end 3) (aref (match-string 3) 2))
6297 (org-match-string-no-properties 4)
6298 (org-match-string-no-properties 5)))))
6300 (defun org-get-entry ()
6301 "Get the entry text, after heading, entire subtree."
6302 (save-excursion
6303 (org-back-to-heading t)
6304 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6306 (defun org-insert-heading-after-current ()
6307 "Insert a new heading with same level as current, after current subtree."
6308 (interactive)
6309 (org-back-to-heading)
6310 (org-insert-heading)
6311 (org-move-subtree-down)
6312 (end-of-line 1))
6314 (defun org-insert-heading-respect-content ()
6315 (interactive)
6316 (let ((org-insert-heading-respect-content t))
6317 (org-insert-heading t)))
6319 (defun org-insert-todo-heading-respect-content (&optional force-state)
6320 (interactive "P")
6321 (let ((org-insert-heading-respect-content t))
6322 (org-insert-todo-heading force-state t)))
6324 (defun org-insert-todo-heading (arg &optional force-heading)
6325 "Insert a new heading with the same level and TODO state as current heading.
6326 If the heading has no TODO state, or if the state is DONE, use the first
6327 state (TODO by default). Also with prefix arg, force first state."
6328 (interactive "P")
6329 (when (or force-heading (not (org-insert-item 'checkbox)))
6330 (org-insert-heading force-heading)
6331 (save-excursion
6332 (org-back-to-heading)
6333 (outline-previous-heading)
6334 (looking-at org-todo-line-regexp))
6335 (let*
6336 ((new-mark-x
6337 (if (or arg
6338 (not (match-beginning 2))
6339 (member (match-string 2) org-done-keywords))
6340 (car org-todo-keywords-1)
6341 (match-string 2)))
6342 (new-mark
6344 (run-hook-with-args-until-success
6345 'org-todo-get-default-hook new-mark-x nil)
6346 new-mark-x)))
6347 (beginning-of-line 1)
6348 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6349 (if org-treat-insert-todo-heading-as-state-change
6350 (org-todo new-mark)
6351 (insert new-mark " "))))
6352 (when org-provide-todo-statistics
6353 (org-update-parent-todo-statistics))))
6355 (defun org-insert-subheading (arg)
6356 "Insert a new subheading and demote it.
6357 Works for outline headings and for plain lists alike."
6358 (interactive "P")
6359 (org-insert-heading arg)
6360 (cond
6361 ((org-on-heading-p) (org-do-demote))
6362 ((org-at-item-p) (org-indent-item 1))))
6364 (defun org-insert-todo-subheading (arg)
6365 "Insert a new subheading with TODO keyword or checkbox and demote it.
6366 Works for outline headings and for plain lists alike."
6367 (interactive "P")
6368 (org-insert-todo-heading arg)
6369 (cond
6370 ((org-on-heading-p) (org-do-demote))
6371 ((org-at-item-p) (org-indent-item 1))))
6373 ;;; Promotion and Demotion
6375 (defvar org-after-demote-entry-hook nil
6376 "Hook run after an entry has been demoted.
6377 The cursor will be at the beginning of the entry.
6378 When a subtree is being demoted, the hook will be called for each node.")
6380 (defvar org-after-promote-entry-hook nil
6381 "Hook run after an entry has been promoted.
6382 The cursor will be at the beginning of the entry.
6383 When a subtree is being promoted, the hook will be called for each node.")
6385 (defun org-promote-subtree ()
6386 "Promote the entire subtree.
6387 See also `org-promote'."
6388 (interactive)
6389 (save-excursion
6390 (org-map-tree 'org-promote))
6391 (org-fix-position-after-promote))
6393 (defun org-demote-subtree ()
6394 "Demote the entire subtree. See `org-demote'.
6395 See also `org-promote'."
6396 (interactive)
6397 (save-excursion
6398 (org-map-tree 'org-demote))
6399 (org-fix-position-after-promote))
6402 (defun org-do-promote ()
6403 "Promote the current heading higher up the tree.
6404 If the region is active in `transient-mark-mode', promote all headings
6405 in the region."
6406 (interactive)
6407 (save-excursion
6408 (if (org-region-active-p)
6409 (org-map-region 'org-promote (region-beginning) (region-end))
6410 (org-promote)))
6411 (org-fix-position-after-promote))
6413 (defun org-do-demote ()
6414 "Demote the current heading lower down the tree.
6415 If the region is active in `transient-mark-mode', demote all headings
6416 in the region."
6417 (interactive)
6418 (save-excursion
6419 (if (org-region-active-p)
6420 (org-map-region 'org-demote (region-beginning) (region-end))
6421 (org-demote)))
6422 (org-fix-position-after-promote))
6424 (defun org-fix-position-after-promote ()
6425 "Make sure that after pro/demotion cursor position is right."
6426 (let ((pos (point)))
6427 (when (save-excursion
6428 (beginning-of-line 1)
6429 (looking-at org-todo-line-regexp)
6430 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6431 (cond ((eobp) (insert " "))
6432 ((eolp) (insert " "))
6433 ((equal (char-after) ?\ ) (forward-char 1))))))
6435 (defun org-current-level ()
6436 "Return the level of the current entry, or nil if before the first headline.
6437 The level is the number of stars at the beginning of the headline."
6438 (save-excursion
6439 (condition-case nil
6440 (progn
6441 (org-back-to-heading t)
6442 (funcall outline-level))
6443 (error nil))))
6445 (defun org-get-previous-line-level ()
6446 "Return the outline depth of the last headline before the current line.
6447 Returns 0 for the first headline in the buffer, and nil if before the
6448 first headline."
6449 (let ((current-level (org-current-level))
6450 (prev-level (when (> (line-number-at-pos) 1)
6451 (save-excursion
6452 (beginning-of-line 0)
6453 (org-current-level)))))
6454 (cond ((null current-level) nil) ; Before first headline
6455 ((null prev-level) 0) ; At first headline
6456 (prev-level))))
6458 (defun org-reduced-level (l)
6459 "Compute the effective level of a heading.
6460 This takes into account the setting of `org-odd-levels-only'."
6461 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6463 (defun org-level-increment ()
6464 "Return the number of stars that will be added or removed at a
6465 time to headlines when structure editing, based on the value of
6466 `org-odd-levels-only'."
6467 (if org-odd-levels-only 2 1))
6469 (defun org-get-valid-level (level &optional change)
6470 "Rectify a level change under the influence of `org-odd-levels-only'
6471 LEVEL is a current level, CHANGE is by how much the level should be
6472 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6473 even level numbers will become the next higher odd number."
6474 (if org-odd-levels-only
6475 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6476 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6477 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6478 (max 1 (+ level (or change 0)))))
6480 (if (boundp 'define-obsolete-function-alias)
6481 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6482 (define-obsolete-function-alias 'org-get-legal-level
6483 'org-get-valid-level)
6484 (define-obsolete-function-alias 'org-get-legal-level
6485 'org-get-valid-level "23.1")))
6487 (defun org-promote ()
6488 "Promote the current heading higher up the tree.
6489 If the region is active in `transient-mark-mode', promote all headings
6490 in the region."
6491 (org-back-to-heading t)
6492 (let* ((level (save-match-data (funcall outline-level)))
6493 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6494 (diff (abs (- level (length up-head) -1))))
6495 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6496 (replace-match up-head nil t)
6497 ;; Fixup tag positioning
6498 (and org-auto-align-tags (org-set-tags nil t))
6499 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6500 (run-hooks 'org-after-promote-entry-hook)))
6502 (defun org-demote ()
6503 "Demote the current heading lower down the tree.
6504 If the region is active in `transient-mark-mode', demote all headings
6505 in the region."
6506 (org-back-to-heading t)
6507 (let* ((level (save-match-data (funcall outline-level)))
6508 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6509 (diff (abs (- level (length down-head) -1))))
6510 (replace-match down-head nil t)
6511 ;; Fixup tag positioning
6512 (and org-auto-align-tags (org-set-tags nil t))
6513 (if org-adapt-indentation (org-fixup-indentation diff))
6514 (run-hooks 'org-after-demote-entry-hook)))
6516 (defun org-cycle-level ()
6517 "Cycle the level of an empty headline through possible states.
6518 This goes first to child, then to parent, level, then up the hierarchy.
6519 After top level, it switches back to sibling level."
6520 (interactive)
6521 (let ((org-adapt-indentation nil))
6522 (when (org-point-at-end-of-empty-headline)
6523 (setq this-command 'org-cycle-level) ; Only needed for caching
6524 (let ((cur-level (org-current-level))
6525 (prev-level (org-get-previous-line-level)))
6526 (cond
6527 ;; If first headline in file, promote to top-level.
6528 ((= prev-level 0)
6529 (loop repeat (/ (- cur-level 1) (org-level-increment))
6530 do (org-do-promote)))
6531 ;; If same level as prev, demote one.
6532 ((= prev-level cur-level)
6533 (org-do-demote))
6534 ;; If parent is top-level, promote to top level if not already.
6535 ((= prev-level 1)
6536 (loop repeat (/ (- cur-level 1) (org-level-increment))
6537 do (org-do-promote)))
6538 ;; If top-level, return to prev-level.
6539 ((= cur-level 1)
6540 (loop repeat (/ (- prev-level 1) (org-level-increment))
6541 do (org-do-demote)))
6542 ;; If less than prev-level, promote one.
6543 ((< cur-level prev-level)
6544 (org-do-promote))
6545 ;; If deeper than prev-level, promote until higher than
6546 ;; prev-level.
6547 ((> cur-level prev-level)
6548 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
6549 do (org-do-promote))))
6550 t))))
6552 (defun org-map-tree (fun)
6553 "Call FUN for every heading underneath the current one."
6554 (org-back-to-heading)
6555 (let ((level (funcall outline-level)))
6556 (save-excursion
6557 (funcall fun)
6558 (while (and (progn
6559 (outline-next-heading)
6560 (> (funcall outline-level) level))
6561 (not (eobp)))
6562 (funcall fun)))))
6564 (defun org-map-region (fun beg end)
6565 "Call FUN for every heading between BEG and END."
6566 (let ((org-ignore-region t))
6567 (save-excursion
6568 (setq end (copy-marker end))
6569 (goto-char beg)
6570 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6571 (< (point) end))
6572 (funcall fun))
6573 (while (and (progn
6574 (outline-next-heading)
6575 (< (point) end))
6576 (not (eobp)))
6577 (funcall fun)))))
6579 (defun org-fixup-indentation (diff)
6580 "Change the indentation in the current entry by DIFF
6581 However, if any line in the current entry has no indentation, or if it
6582 would end up with no indentation after the change, nothing at all is done."
6583 (save-excursion
6584 (let ((end (save-excursion (outline-next-heading)
6585 (point-marker)))
6586 (prohibit (if (> diff 0)
6587 "^\\S-"
6588 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6589 col)
6590 (unless (save-excursion (end-of-line 1)
6591 (re-search-forward prohibit end t))
6592 (while (and (< (point) end)
6593 (re-search-forward "^[ \t]+" end t))
6594 (goto-char (match-end 0))
6595 (setq col (current-column))
6596 (if (< diff 0) (replace-match ""))
6597 (org-indent-to-column (+ diff col))))
6598 (move-marker end nil))))
6600 (defun org-convert-to-odd-levels ()
6601 "Convert an org-mode file with all levels allowed to one with odd levels.
6602 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6603 level 5 etc."
6604 (interactive)
6605 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6606 (let ((outline-regexp org-outline-regexp)
6607 (outline-level 'org-outline-level)
6608 (org-odd-levels-only nil) n)
6609 (save-excursion
6610 (goto-char (point-min))
6611 (while (re-search-forward "^\\*\\*+ " nil t)
6612 (setq n (- (length (match-string 0)) 2))
6613 (while (>= (setq n (1- n)) 0)
6614 (org-demote))
6615 (end-of-line 1))))))
6617 (defun org-convert-to-oddeven-levels ()
6618 "Convert an org-mode file with only odd levels to one with odd and even levels.
6619 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6620 section with an even level, conversion would destroy the structure of the file. An error
6621 is signaled in this case."
6622 (interactive)
6623 (goto-char (point-min))
6624 ;; First check if there are no even levels
6625 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6626 (org-show-context t)
6627 (error "Not all levels are odd in this file. Conversion not possible"))
6628 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6629 (let ((outline-regexp org-outline-regexp)
6630 (outline-level 'org-outline-level)
6631 (org-odd-levels-only nil) n)
6632 (save-excursion
6633 (goto-char (point-min))
6634 (while (re-search-forward "^\\*\\*+ " nil t)
6635 (setq n (/ (1- (length (match-string 0))) 2))
6636 (while (>= (setq n (1- n)) 0)
6637 (org-promote))
6638 (end-of-line 1))))))
6640 (defun org-tr-level (n)
6641 "Make N odd if required."
6642 (if org-odd-levels-only (1+ (/ n 2)) n))
6644 ;;; Vertical tree motion, cutting and pasting of subtrees
6646 (defun org-move-subtree-up (&optional arg)
6647 "Move the current subtree up past ARG headlines of the same level."
6648 (interactive "p")
6649 (org-move-subtree-down (- (prefix-numeric-value arg))))
6651 (defun org-move-subtree-down (&optional arg)
6652 "Move the current subtree down past ARG headlines of the same level."
6653 (interactive "p")
6654 (setq arg (prefix-numeric-value arg))
6655 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
6656 'org-get-last-sibling))
6657 (ins-point (make-marker))
6658 (cnt (abs arg))
6659 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6660 ;; Select the tree
6661 (org-back-to-heading)
6662 (setq beg0 (point))
6663 (save-excursion
6664 (setq ne-beg (org-back-over-empty-lines))
6665 (setq beg (point)))
6666 (save-match-data
6667 (save-excursion (outline-end-of-heading)
6668 (setq folded (org-invisible-p)))
6669 (outline-end-of-subtree))
6670 (outline-next-heading)
6671 (setq ne-end (org-back-over-empty-lines))
6672 (setq end (point))
6673 (goto-char beg0)
6674 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6675 ;; include less whitespace
6676 (save-excursion
6677 (goto-char beg)
6678 (forward-line (- ne-beg ne-end))
6679 (setq beg (point))))
6680 ;; Find insertion point, with error handling
6681 (while (> cnt 0)
6682 (or (and (funcall movfunc) (looking-at outline-regexp))
6683 (progn (goto-char beg0)
6684 (error "Cannot move past superior level or buffer limit")))
6685 (setq cnt (1- cnt)))
6686 (if (> arg 0)
6687 ;; Moving forward - still need to move over subtree
6688 (progn (org-end-of-subtree t t)
6689 (save-excursion
6690 (org-back-over-empty-lines)
6691 (or (bolp) (newline)))))
6692 (setq ne-ins (org-back-over-empty-lines))
6693 (move-marker ins-point (point))
6694 (setq txt (buffer-substring beg end))
6695 (org-save-markers-in-region beg end)
6696 (delete-region beg end)
6697 (org-remove-empty-overlays-at beg)
6698 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6699 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6700 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6701 (let ((bbb (point)))
6702 (insert-before-markers txt)
6703 (org-reinstall-markers-in-region bbb)
6704 (move-marker ins-point bbb))
6705 (or (bolp) (insert "\n"))
6706 (setq ins-end (point))
6707 (goto-char ins-point)
6708 (org-skip-whitespace)
6709 (when (and (< arg 0)
6710 (org-first-sibling-p)
6711 (> ne-ins ne-beg))
6712 ;; Move whitespace back to beginning
6713 (save-excursion
6714 (goto-char ins-end)
6715 (let ((kill-whole-line t))
6716 (kill-line (- ne-ins ne-beg)) (point)))
6717 (insert (make-string (- ne-ins ne-beg) ?\n)))
6718 (move-marker ins-point nil)
6719 (if folded
6720 (hide-subtree)
6721 (org-show-entry)
6722 (show-children)
6723 (org-cycle-hide-drawers 'children))
6724 (org-clean-visibility-after-subtree-move)))
6726 (defvar org-subtree-clip ""
6727 "Clipboard for cut and paste of subtrees.
6728 This is actually only a copy of the kill, because we use the normal kill
6729 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6731 (defvar org-subtree-clip-folded nil
6732 "Was the last copied subtree folded?
6733 This is used to fold the tree back after pasting.")
6735 (defun org-cut-subtree (&optional n)
6736 "Cut the current subtree into the clipboard.
6737 With prefix arg N, cut this many sequential subtrees.
6738 This is a short-hand for marking the subtree and then cutting it."
6739 (interactive "p")
6740 (org-copy-subtree n 'cut))
6742 (defun org-copy-subtree (&optional n cut force-store-markers)
6743 "Cut the current subtree into the clipboard.
6744 With prefix arg N, cut this many sequential subtrees.
6745 This is a short-hand for marking the subtree and then copying it.
6746 If CUT is non-nil, actually cut the subtree.
6747 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6748 of some markers in the region, even if CUT is non-nil. This is
6749 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6750 (interactive "p")
6751 (let (beg end folded (beg0 (point)))
6752 (if (interactive-p)
6753 (org-back-to-heading nil) ; take what looks like a subtree
6754 (org-back-to-heading t)) ; take what is really there
6755 (org-back-over-empty-lines)
6756 (setq beg (point))
6757 (skip-chars-forward " \t\r\n")
6758 (save-match-data
6759 (save-excursion (outline-end-of-heading)
6760 (setq folded (org-invisible-p)))
6761 (condition-case nil
6762 (org-forward-same-level (1- n) t)
6763 (error nil))
6764 (org-end-of-subtree t t))
6765 (org-back-over-empty-lines)
6766 (setq end (point))
6767 (goto-char beg0)
6768 (when (> end beg)
6769 (setq org-subtree-clip-folded folded)
6770 (when (or cut force-store-markers)
6771 (org-save-markers-in-region beg end))
6772 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6773 (setq org-subtree-clip (current-kill 0))
6774 (message "%s: Subtree(s) with %d characters"
6775 (if cut "Cut" "Copied")
6776 (length org-subtree-clip)))))
6778 (defun org-paste-subtree (&optional level tree for-yank)
6779 "Paste the clipboard as a subtree, with modification of headline level.
6780 The entire subtree is promoted or demoted in order to match a new headline
6781 level.
6783 If the cursor is at the beginning of a headline, the same level as
6784 that headline is used to paste the tree
6786 If not, the new level is derived from the *visible* headings
6787 before and after the insertion point, and taken to be the inferior headline
6788 level of the two. So if the previous visible heading is level 3 and the
6789 next is level 4 (or vice versa), level 4 will be used for insertion.
6790 This makes sure that the subtree remains an independent subtree and does
6791 not swallow low level entries.
6793 You can also force a different level, either by using a numeric prefix
6794 argument, or by inserting the heading marker by hand. For example, if the
6795 cursor is after \"*****\", then the tree will be shifted to level 5.
6797 If optional TREE is given, use this text instead of the kill ring.
6799 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6800 move back over whitespace before inserting, and move point to the end of
6801 the inserted text when done."
6802 (interactive "P")
6803 (setq tree (or tree (and kill-ring (current-kill 0))))
6804 (unless (org-kill-is-subtree-p tree)
6805 (error "%s"
6806 (substitute-command-keys
6807 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6808 (let* ((visp (not (org-invisible-p)))
6809 (txt tree)
6810 (^re (concat "^\\(" outline-regexp "\\)"))
6811 (re (concat "\\(" outline-regexp "\\)"))
6812 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6814 (old-level (if (string-match ^re txt)
6815 (- (match-end 0) (match-beginning 0) 1)
6816 -1))
6817 (force-level (cond (level (prefix-numeric-value level))
6818 ((and (looking-at "[ \t]*$")
6819 (string-match
6820 ^re_ (buffer-substring
6821 (point-at-bol) (point))))
6822 (- (match-end 1) (match-beginning 1)))
6823 ((and (bolp)
6824 (looking-at org-outline-regexp))
6825 (- (match-end 0) (point) 1))
6826 (t nil)))
6827 (previous-level (save-excursion
6828 (condition-case nil
6829 (progn
6830 (outline-previous-visible-heading 1)
6831 (if (looking-at re)
6832 (- (match-end 0) (match-beginning 0) 1)
6834 (error 1))))
6835 (next-level (save-excursion
6836 (condition-case nil
6837 (progn
6838 (or (looking-at outline-regexp)
6839 (outline-next-visible-heading 1))
6840 (if (looking-at re)
6841 (- (match-end 0) (match-beginning 0) 1)
6843 (error 1))))
6844 (new-level (or force-level (max previous-level next-level)))
6845 (shift (if (or (= old-level -1)
6846 (= new-level -1)
6847 (= old-level new-level))
6849 (- new-level old-level)))
6850 (delta (if (> shift 0) -1 1))
6851 (func (if (> shift 0) 'org-demote 'org-promote))
6852 (org-odd-levels-only nil)
6853 beg end newend)
6854 ;; Remove the forced level indicator
6855 (if force-level
6856 (delete-region (point-at-bol) (point)))
6857 ;; Paste
6858 (beginning-of-line 1)
6859 (unless for-yank (org-back-over-empty-lines))
6860 (setq beg (point))
6861 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6862 (insert-before-markers txt)
6863 (unless (string-match "\n\\'" txt) (insert "\n"))
6864 (setq newend (point))
6865 (org-reinstall-markers-in-region beg)
6866 (setq end (point))
6867 (goto-char beg)
6868 (skip-chars-forward " \t\n\r")
6869 (setq beg (point))
6870 (if (and (org-invisible-p) visp)
6871 (save-excursion (outline-show-heading)))
6872 ;; Shift if necessary
6873 (unless (= shift 0)
6874 (save-restriction
6875 (narrow-to-region beg end)
6876 (while (not (= shift 0))
6877 (org-map-region func (point-min) (point-max))
6878 (setq shift (+ delta shift)))
6879 (goto-char (point-min))
6880 (setq newend (point-max))))
6881 (when (or (interactive-p) for-yank)
6882 (message "Clipboard pasted as level %d subtree" new-level))
6883 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6884 kill-ring
6885 (eq org-subtree-clip (current-kill 0))
6886 org-subtree-clip-folded)
6887 ;; The tree was folded before it was killed/copied
6888 (hide-subtree))
6889 (and for-yank (goto-char newend))))
6891 (defun org-kill-is-subtree-p (&optional txt)
6892 "Check if the current kill is an outline subtree, or a set of trees.
6893 Returns nil if kill does not start with a headline, or if the first
6894 headline level is not the largest headline level in the tree.
6895 So this will actually accept several entries of equal levels as well,
6896 which is OK for `org-paste-subtree'.
6897 If optional TXT is given, check this string instead of the current kill."
6898 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6899 (start-level (and kill
6900 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6901 org-outline-regexp "\\)")
6902 kill)
6903 (- (match-end 2) (match-beginning 2) 1)))
6904 (re (concat "^" org-outline-regexp))
6905 (start (1+ (or (match-beginning 2) -1))))
6906 (if (not start-level)
6907 (progn
6908 nil) ;; does not even start with a heading
6909 (catch 'exit
6910 (while (setq start (string-match re kill (1+ start)))
6911 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6912 (throw 'exit nil)))
6913 t))))
6915 (defvar org-markers-to-move nil
6916 "Markers that should be moved with a cut-and-paste operation.
6917 Those markers are stored together with their positions relative to
6918 the start of the region.")
6920 (defun org-save-markers-in-region (beg end)
6921 "Check markers in region.
6922 If these markers are between BEG and END, record their position relative
6923 to BEG, so that after moving the block of text, we can put the markers back
6924 into place.
6925 This function gets called just before an entry or tree gets cut from the
6926 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6927 called immediately, to move the markers with the entries."
6928 (setq org-markers-to-move nil)
6929 (when (featurep 'org-clock)
6930 (org-clock-save-markers-for-cut-and-paste beg end))
6931 (when (featurep 'org-agenda)
6932 (org-agenda-save-markers-for-cut-and-paste beg end)))
6934 (defun org-check-and-save-marker (marker beg end)
6935 "Check if MARKER is between BEG and END.
6936 If yes, remember the marker and the distance to BEG."
6937 (when (and (marker-buffer marker)
6938 (equal (marker-buffer marker) (current-buffer)))
6939 (if (and (>= marker beg) (< marker end))
6940 (push (cons marker (- marker beg)) org-markers-to-move))))
6942 (defun org-reinstall-markers-in-region (beg)
6943 "Move all remembered markers to their position relative to BEG."
6944 (mapc (lambda (x)
6945 (move-marker (car x) (+ beg (cdr x))))
6946 org-markers-to-move)
6947 (setq org-markers-to-move nil))
6949 (defun org-narrow-to-subtree ()
6950 "Narrow buffer to the current subtree."
6951 (interactive)
6952 (save-excursion
6953 (save-match-data
6954 (narrow-to-region
6955 (progn (org-back-to-heading t) (point))
6956 (progn (org-end-of-subtree t t)
6957 (if (org-on-heading-p) (backward-char 1))
6958 (point))))))
6960 (defun org-clone-subtree-with-time-shift (n &optional shift)
6961 "Clone the task (subtree) at point N times.
6962 The clones will be inserted as siblings.
6964 In interactive use, the user will be prompted for the number of clones
6965 to be produced, and for a time SHIFT, which may be a repeater as used
6966 in time stamps, for example `+3d'.
6968 When a valid repeater is given and the entry contains any time stamps,
6969 the clones will become a sequence in time, with time stamps in the
6970 subtree shifted for each clone produced. If SHIFT is nil or the
6971 empty string, time stamps will be left alone.
6973 If the original subtree did contain time stamps with a repeater,
6974 the following will happen:
6975 - the repeater will be removed in each clone
6976 - an additional clone will be produced, with the current, unshifted
6977 date(s) in the entry.
6978 - the original entry will be placed *after* all the clones, with
6979 repeater intact.
6980 - the start days in the repeater in the original entry will be shifted
6981 to past the last clone.
6982 I this way you can spell out a number of instances of a repeating task,
6983 and still retain the repeater to cover future instances of the task."
6984 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6985 (let (beg end template task
6986 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6987 (if (not (and (integerp n) (> n 0)))
6988 (error "Invalid number of replications %s" n))
6989 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6990 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6991 shift)))
6992 (error "Invalid shift specification %s" shift))
6993 (when doshift
6994 (setq shift-n (string-to-number (match-string 1 shift))
6995 shift-what (cdr (assoc (match-string 2 shift)
6996 '(("d" . day) ("w" . week)
6997 ("m" . month) ("y" . year))))))
6998 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6999 (setq nmin 1 nmax n)
7000 (org-back-to-heading t)
7001 (setq beg (point))
7002 (org-end-of-subtree t t)
7003 (or (bolp) (insert "\n"))
7004 (setq end (point))
7005 (setq template (buffer-substring beg end))
7006 (when (and doshift
7007 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7008 (delete-region beg end)
7009 (setq end beg)
7010 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7011 (goto-char end)
7012 (loop for n from nmin to nmax do
7013 (if (not doshift)
7014 (setq task template)
7015 (with-temp-buffer
7016 (insert template)
7017 (org-mode)
7018 (goto-char (point-min))
7019 (while (re-search-forward org-ts-regexp-both nil t)
7020 (org-timestamp-change (* n shift-n) shift-what))
7021 (unless (= n n-no-remove)
7022 (goto-char (point-min))
7023 (while (re-search-forward org-ts-regexp nil t)
7024 (save-excursion
7025 (goto-char (match-beginning 0))
7026 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7027 (delete-region (match-beginning 1) (match-end 1))))))
7028 (setq task (buffer-string))))
7029 (insert task))
7030 (goto-char beg)))
7032 ;;; Outline Sorting
7034 (defun org-sort (with-case)
7035 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
7036 Optional argument WITH-CASE means sort case-sensitively.
7037 With a double prefix argument, also remove duplicate entries."
7038 (interactive "P")
7039 (if (org-at-table-p)
7040 (org-call-with-arg 'org-table-sort-lines with-case)
7041 (org-call-with-arg 'org-sort-entries-or-items with-case)))
7043 (defun org-sort-remove-invisible (s)
7044 (remove-text-properties 0 (length s) org-rm-props s)
7045 (while (string-match org-bracket-link-regexp s)
7046 (setq s (replace-match (if (match-end 2)
7047 (match-string 3 s)
7048 (match-string 1 s)) t t s)))
7051 (defvar org-priority-regexp) ; defined later in the file
7053 (defvar org-after-sorting-entries-or-items-hook nil
7054 "Hook that is run after a bunch of entries or items have been sorted.
7055 When children are sorted, the cursor is in the parent line when this
7056 hook gets called. When a region or a plain list is sorted, the cursor
7057 will be in the first entry of the sorted region/list.")
7059 (defun org-sort-entries-or-items
7060 (&optional with-case sorting-type getkey-func compare-func property)
7061 "Sort entries on a certain level of an outline tree, or plain list items.
7062 If there is an active region, the entries in the region are sorted.
7063 Else, if the cursor is before the first entry, sort the top-level items.
7064 Else, the children of the entry at point are sorted.
7065 If the cursor is at the first item in a plain list, the list items will be
7066 sorted.
7068 Sorting can be alphabetically, numerically, by date/time as given by
7069 a time stamp, by a property or by priority.
7071 The command prompts for the sorting type unless it has been given to the
7072 function through the SORTING-TYPE argument, which needs to a character,
7073 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7074 precise meaning of each character:
7076 n Numerically, by converting the beginning of the entry/item to a number.
7077 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7078 t By date/time, either the first active time stamp in the entry, or, if
7079 none exist, by the first inactive one.
7080 In items, only the first line will be checked.
7081 s By the scheduled date/time.
7082 d By deadline date/time.
7083 c By creation time, which is assumed to be the first inactive time stamp
7084 at the beginning of a line.
7085 p By priority according to the cookie.
7086 r By the value of a property.
7088 Capital letters will reverse the sort order.
7090 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
7091 called with point at the beginning of the record. It must return either
7092 a string or a number that should serve as the sorting key for that record.
7094 Comparing entries ignores case by default. However, with an optional argument
7095 WITH-CASE, the sorting considers case as well."
7096 (interactive "P")
7097 (let ((case-func (if with-case 'identity 'downcase))
7098 start beg end stars re re2
7099 txt what tmp plain-list-p)
7100 ;; Find beginning and end of region to sort
7101 (cond
7102 ((org-region-active-p)
7103 ;; we will sort the region
7104 (setq end (region-end)
7105 what "region")
7106 (goto-char (region-beginning))
7107 (if (not (org-on-heading-p)) (outline-next-heading))
7108 (setq start (point)))
7109 ((org-at-item-p)
7110 ;; we will sort this plain list
7111 (org-beginning-of-item-list) (setq start (point))
7112 (org-end-of-item-list)
7113 (or (bolp) (insert "\n"))
7114 (setq end (point))
7115 (goto-char start)
7116 (setq plain-list-p t
7117 what "plain list"))
7118 ((or (org-on-heading-p)
7119 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
7120 ;; we will sort the children of the current headline
7121 (org-back-to-heading)
7122 (setq start (point)
7123 end (progn (org-end-of-subtree t t)
7124 (or (bolp) (insert "\n"))
7125 (org-back-over-empty-lines)
7126 (point))
7127 what "children")
7128 (goto-char start)
7129 (show-subtree)
7130 (outline-next-heading))
7132 ;; we will sort the top-level entries in this file
7133 (goto-char (point-min))
7134 (or (org-on-heading-p) (outline-next-heading))
7135 (setq start (point))
7136 (goto-char (point-max))
7137 (beginning-of-line 1)
7138 (when (looking-at ".*?\\S-")
7139 ;; File ends in a non-white line
7140 (end-of-line 1)
7141 (insert "\n"))
7142 (setq end (point-max))
7143 (setq what "top-level")
7144 (goto-char start)
7145 (show-all)))
7147 (setq beg (point))
7148 (if (>= beg end) (error "Nothing to sort"))
7150 (unless plain-list-p
7151 (looking-at "\\(\\*+\\)")
7152 (setq stars (match-string 1)
7153 re (concat "^" (regexp-quote stars) " +")
7154 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
7155 txt (buffer-substring beg end))
7156 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7157 (if (and (not (equal stars "*")) (string-match re2 txt))
7158 (error "Region to sort contains a level above the first entry")))
7160 (unless sorting-type
7161 (message
7162 (if plain-list-p
7163 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
7164 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7165 [t]ime [s]cheduled [d]eadline [c]reated
7166 A/N/T/S/D/C/P/O/F means reversed:")
7167 what)
7168 (setq sorting-type (read-char-exclusive))
7170 (and (= (downcase sorting-type) ?f)
7171 (setq getkey-func
7172 (org-icompleting-read "Sort using function: "
7173 obarray 'fboundp t nil nil))
7174 (setq getkey-func (intern getkey-func)))
7176 (and (= (downcase sorting-type) ?r)
7177 (setq property
7178 (org-icompleting-read "Property: "
7179 (mapcar 'list (org-buffer-property-keys t))
7180 nil t))))
7182 (message "Sorting entries...")
7184 (save-restriction
7185 (narrow-to-region start end)
7187 (let ((dcst (downcase sorting-type))
7188 (case-fold-search nil)
7189 (now (current-time)))
7190 (sort-subr
7191 (/= dcst sorting-type)
7192 ;; This function moves to the beginning character of the "record" to
7193 ;; be sorted.
7194 (if plain-list-p
7195 (lambda nil
7196 (if (org-at-item-p) t (goto-char (point-max))))
7197 (lambda nil
7198 (if (re-search-forward re nil t)
7199 (goto-char (match-beginning 0))
7200 (goto-char (point-max)))))
7201 ;; This function moves to the last character of the "record" being
7202 ;; sorted.
7203 (if plain-list-p
7204 'org-end-of-item
7205 (lambda nil
7206 (save-match-data
7207 (condition-case nil
7208 (outline-forward-same-level 1)
7209 (error
7210 (goto-char (point-max)))))))
7212 ;; This function returns the value that gets sorted against.
7213 (if plain-list-p
7214 (lambda nil
7215 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7216 (cond
7217 ((= dcst ?n)
7218 (string-to-number (buffer-substring (match-end 0)
7219 (point-at-eol))))
7220 ((= dcst ?a)
7221 (buffer-substring (match-end 0) (point-at-eol)))
7222 ((= dcst ?t)
7223 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
7224 (re-search-forward org-ts-regexp-both
7225 (point-at-eol) t))
7226 (org-time-string-to-seconds (match-string 0))
7227 (org-float-time now)))
7228 ((= dcst ?f)
7229 (if getkey-func
7230 (progn
7231 (setq tmp (funcall getkey-func))
7232 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7233 tmp)
7234 (error "Invalid key function `%s'" getkey-func)))
7235 (t (error "Invalid sorting type `%c'" sorting-type)))))
7236 (lambda nil
7237 (cond
7238 ((= dcst ?n)
7239 (if (looking-at org-complex-heading-regexp)
7240 (string-to-number (match-string 4))
7241 nil))
7242 ((= dcst ?a)
7243 (if (looking-at org-complex-heading-regexp)
7244 (funcall case-func (match-string 4))
7245 nil))
7246 ((= dcst ?t)
7247 (let ((end (save-excursion (outline-next-heading) (point))))
7248 (if (or (re-search-forward org-ts-regexp end t)
7249 (re-search-forward org-ts-regexp-both end t))
7250 (org-time-string-to-seconds (match-string 0))
7251 (org-float-time now))))
7252 ((= dcst ?c)
7253 (let ((end (save-excursion (outline-next-heading) (point))))
7254 (if (re-search-forward
7255 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7256 end t)
7257 (org-time-string-to-seconds (match-string 0))
7258 (org-float-time now))))
7259 ((= dcst ?s)
7260 (let ((end (save-excursion (outline-next-heading) (point))))
7261 (if (re-search-forward org-scheduled-time-regexp end t)
7262 (org-time-string-to-seconds (match-string 1))
7263 (org-float-time now))))
7264 ((= dcst ?d)
7265 (let ((end (save-excursion (outline-next-heading) (point))))
7266 (if (re-search-forward org-deadline-time-regexp end t)
7267 (org-time-string-to-seconds (match-string 1))
7268 (org-float-time now))))
7269 ((= dcst ?p)
7270 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7271 (string-to-char (match-string 2))
7272 org-default-priority))
7273 ((= dcst ?r)
7274 (or (org-entry-get nil property) ""))
7275 ((= dcst ?o)
7276 (if (looking-at org-complex-heading-regexp)
7277 (- 9999 (length (member (match-string 2)
7278 org-todo-keywords-1)))))
7279 ((= dcst ?f)
7280 (if getkey-func
7281 (progn
7282 (setq tmp (funcall getkey-func))
7283 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7284 tmp)
7285 (error "Invalid key function `%s'" getkey-func)))
7286 (t (error "Invalid sorting type `%c'" sorting-type)))))
7288 (cond
7289 ((= dcst ?a) 'string<)
7290 ((= dcst ?f) compare-func)
7291 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7292 (t nil)))))
7293 (run-hooks 'org-after-sorting-entries-or-items-hook)
7294 (message "Sorting entries...done")))
7296 (defun org-do-sort (table what &optional with-case sorting-type)
7297 "Sort TABLE of WHAT according to SORTING-TYPE.
7298 The user will be prompted for the SORTING-TYPE if the call to this
7299 function does not specify it. WHAT is only for the prompt, to indicate
7300 what is being sorted. The sorting key will be extracted from
7301 the car of the elements of the table.
7302 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7303 (unless sorting-type
7304 (message
7305 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7306 what)
7307 (setq sorting-type (read-char-exclusive)))
7308 (let ((dcst (downcase sorting-type))
7309 extractfun comparefun)
7310 ;; Define the appropriate functions
7311 (cond
7312 ((= dcst ?n)
7313 (setq extractfun 'string-to-number
7314 comparefun (if (= dcst sorting-type) '< '>)))
7315 ((= dcst ?a)
7316 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7317 (lambda(x) (downcase (org-sort-remove-invisible x))))
7318 comparefun (if (= dcst sorting-type)
7319 'string<
7320 (lambda (a b) (and (not (string< a b))
7321 (not (string= a b)))))))
7322 ((= dcst ?t)
7323 (setq extractfun
7324 (lambda (x)
7325 (if (or (string-match org-ts-regexp x)
7326 (string-match org-ts-regexp-both x))
7327 (org-float-time
7328 (org-time-string-to-time (match-string 0 x)))
7330 comparefun (if (= dcst sorting-type) '< '>)))
7331 (t (error "Invalid sorting type `%c'" sorting-type)))
7333 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7334 table)
7335 (lambda (a b) (funcall comparefun (car a) (car b))))))
7338 ;;; The orgstruct minor mode
7340 ;; Define a minor mode which can be used in other modes in order to
7341 ;; integrate the org-mode structure editing commands.
7343 ;; This is really a hack, because the org-mode structure commands use
7344 ;; keys which normally belong to the major mode. Here is how it
7345 ;; works: The minor mode defines all the keys necessary to operate the
7346 ;; structure commands, but wraps the commands into a function which
7347 ;; tests if the cursor is currently at a headline or a plain list
7348 ;; item. If that is the case, the structure command is used,
7349 ;; temporarily setting many Org-mode variables like regular
7350 ;; expressions for filling etc. However, when any of those keys is
7351 ;; used at a different location, function uses `key-binding' to look
7352 ;; up if the key has an associated command in another currently active
7353 ;; keymap (minor modes, major mode, global), and executes that
7354 ;; command. There might be problems if any of the keys is otherwise
7355 ;; used as a prefix key.
7357 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7358 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7359 ;; addresses this by checking explicitly for both bindings.
7361 (defvar orgstruct-mode-map (make-sparse-keymap)
7362 "Keymap for the minor `orgstruct-mode'.")
7364 (defvar org-local-vars nil
7365 "List of local variables, for use by `orgstruct-mode'")
7367 ;;;###autoload
7368 (define-minor-mode orgstruct-mode
7369 "Toggle the minor more `orgstruct-mode'.
7370 This mode is for using Org-mode structure commands in other modes.
7371 The following key behave as if Org-mode was active, if the cursor
7372 is on a headline, or on a plain list item (both in the definition
7373 of Org-mode).
7375 M-up Move entry/item up
7376 M-down Move entry/item down
7377 M-left Promote
7378 M-right Demote
7379 M-S-up Move entry/item up
7380 M-S-down Move entry/item down
7381 M-S-left Promote subtree
7382 M-S-right Demote subtree
7383 M-q Fill paragraph and items like in Org-mode
7384 C-c ^ Sort entries
7385 C-c - Cycle list bullet
7386 TAB Cycle item visibility
7387 M-RET Insert new heading/item
7388 S-M-RET Insert new TODO heading / Checkbox item
7389 C-c C-c Set tags / toggle checkbox"
7390 nil " OrgStruct" nil
7391 (org-load-modules-maybe)
7392 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7394 ;;;###autoload
7395 (defun turn-on-orgstruct ()
7396 "Unconditionally turn on `orgstruct-mode'."
7397 (orgstruct-mode 1))
7399 (defun orgstruct++-mode (&optional arg)
7400 "Toggle `orgstruct-mode', the enhanced version of it.
7401 In addition to setting orgstruct-mode, this also exports all indentation
7402 and autofilling variables from org-mode into the buffer. It will also
7403 recognize item context in multiline items.
7404 Note that turning off orgstruct-mode will *not* remove the
7405 indentation/paragraph settings. This can only be done by refreshing the
7406 major mode, for example with \\[normal-mode]."
7407 (interactive "P")
7408 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7409 (if (< arg 1)
7410 (orgstruct-mode -1)
7411 (orgstruct-mode 1)
7412 (let (var val)
7413 (mapc
7414 (lambda (x)
7415 (when (string-match
7416 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7417 (symbol-name (car x)))
7418 (setq var (car x) val (nth 1 x))
7419 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7420 org-local-vars)
7421 (org-set-local 'orgstruct-is-++ t))))
7423 (defvar orgstruct-is-++ nil
7424 "Is orgstruct-mode in ++ version in the current-buffer?")
7425 (make-variable-buffer-local 'orgstruct-is-++)
7427 ;;;###autoload
7428 (defun turn-on-orgstruct++ ()
7429 "Unconditionally turn on `orgstruct++-mode'."
7430 (orgstruct++-mode 1))
7432 (defun orgstruct-error ()
7433 "Error when there is no default binding for a structure key."
7434 (interactive)
7435 (error "This key has no function outside structure elements"))
7437 (defun orgstruct-setup ()
7438 "Setup orgstruct keymaps."
7439 (let ((nfunc 0)
7440 (bindings
7441 (list
7442 '([(meta up)] org-metaup)
7443 '([(meta down)] org-metadown)
7444 '([(meta left)] org-metaleft)
7445 '([(meta right)] org-metaright)
7446 '([(meta shift up)] org-shiftmetaup)
7447 '([(meta shift down)] org-shiftmetadown)
7448 '([(meta shift left)] org-shiftmetaleft)
7449 '([(meta shift right)] org-shiftmetaright)
7450 '([?\e (up)] org-metaup)
7451 '([?\e (down)] org-metadown)
7452 '([?\e (left)] org-metaleft)
7453 '([?\e (right)] org-metaright)
7454 '([?\e (shift up)] org-shiftmetaup)
7455 '([?\e (shift down)] org-shiftmetadown)
7456 '([?\e (shift left)] org-shiftmetaleft)
7457 '([?\e (shift right)] org-shiftmetaright)
7458 '([(shift up)] org-shiftup)
7459 '([(shift down)] org-shiftdown)
7460 '([(shift left)] org-shiftleft)
7461 '([(shift right)] org-shiftright)
7462 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7463 '("\M-q" fill-paragraph)
7464 '("\C-c^" org-sort)
7465 '("\C-c-" org-cycle-list-bullet)))
7466 elt key fun cmd)
7467 (while (setq elt (pop bindings))
7468 (setq nfunc (1+ nfunc))
7469 (setq key (org-key (car elt))
7470 fun (nth 1 elt)
7471 cmd (orgstruct-make-binding fun nfunc key))
7472 (org-defkey orgstruct-mode-map key cmd))
7474 ;; Special treatment needed for TAB and RET
7475 (org-defkey orgstruct-mode-map [(tab)]
7476 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7477 (org-defkey orgstruct-mode-map "\C-i"
7478 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7480 (org-defkey orgstruct-mode-map "\M-\C-m"
7481 (orgstruct-make-binding 'org-insert-heading 105
7482 "\M-\C-m" [(meta return)]))
7483 (org-defkey orgstruct-mode-map [(meta return)]
7484 (orgstruct-make-binding 'org-insert-heading 106
7485 [(meta return)] "\M-\C-m"))
7487 (org-defkey orgstruct-mode-map [(shift meta return)]
7488 (orgstruct-make-binding 'org-insert-todo-heading 107
7489 [(meta return)] "\M-\C-m"))
7491 (org-defkey orgstruct-mode-map "\e\C-m"
7492 (orgstruct-make-binding 'org-insert-heading 108
7493 "\e\C-m" [?\e (return)]))
7494 (org-defkey orgstruct-mode-map [?\e (return)]
7495 (orgstruct-make-binding 'org-insert-heading 109
7496 [?\e (return)] "\e\C-m"))
7497 (org-defkey orgstruct-mode-map [?\e (shift return)]
7498 (orgstruct-make-binding 'org-insert-todo-heading 110
7499 [?\e (return)] "\e\C-m"))
7501 (unless org-local-vars
7502 (setq org-local-vars (org-get-local-variables)))
7506 (defun orgstruct-make-binding (fun n &rest keys)
7507 "Create a function for binding in the structure minor mode.
7508 FUN is the command to call inside a table. N is used to create a unique
7509 command name. KEYS are keys that should be checked in for a command
7510 to execute outside of tables."
7511 (eval
7512 (list 'defun
7513 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7514 '(arg)
7515 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7516 "Outside of structure, run the binding of `"
7517 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7518 "'.")
7519 '(interactive "p")
7520 (list 'if
7521 `(org-context-p 'headline 'item
7522 (and orgstruct-is-++
7523 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7524 'item-body))
7525 (list 'org-run-like-in-org-mode (list 'quote fun))
7526 (list 'let '(orgstruct-mode)
7527 (list 'call-interactively
7528 (append '(or)
7529 (mapcar (lambda (k)
7530 (list 'key-binding k))
7531 keys)
7532 '('orgstruct-error))))))))
7534 (defun org-context-p (&rest contexts)
7535 "Check if local context is any of CONTEXTS.
7536 Possible values in the list of contexts are `table', `headline', and `item'."
7537 (let ((pos (point)))
7538 (goto-char (point-at-bol))
7539 (prog1 (or (and (memq 'table contexts)
7540 (looking-at "[ \t]*|"))
7541 (and (memq 'headline contexts)
7542 ;;????????? (looking-at "\\*+"))
7543 (looking-at outline-regexp))
7544 (and (memq 'item contexts)
7545 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7546 (and (memq 'item-body contexts)
7547 (org-in-item-p)))
7548 (goto-char pos))))
7550 (defun org-get-local-variables ()
7551 "Return a list of all local variables in an org-mode buffer."
7552 (let (varlist)
7553 (with-current-buffer (get-buffer-create "*Org tmp*")
7554 (erase-buffer)
7555 (org-mode)
7556 (setq varlist (buffer-local-variables)))
7557 (kill-buffer "*Org tmp*")
7558 (delq nil
7559 (mapcar
7560 (lambda (x)
7561 (setq x
7562 (if (symbolp x)
7563 (list x)
7564 (list (car x) (list 'quote (cdr x)))))
7565 (if (string-match
7566 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7567 (symbol-name (car x)))
7568 x nil))
7569 varlist))))
7571 ;;;###autoload
7572 (defun org-run-like-in-org-mode (cmd)
7573 "Run a command, pretending that the current buffer is in Org-mode.
7574 This will temporarily bind local variables that are typically bound in
7575 Org-mode to the values they have in Org-mode, and then interactively
7576 call CMD."
7577 (org-load-modules-maybe)
7578 (unless org-local-vars
7579 (setq org-local-vars (org-get-local-variables)))
7580 (eval (list 'let org-local-vars
7581 (list 'call-interactively (list 'quote cmd)))))
7583 ;;;; Archiving
7585 (defun org-get-category (&optional pos)
7586 "Get the category applying to position POS."
7587 (get-text-property (or pos (point)) 'org-category))
7589 (defun org-refresh-category-properties ()
7590 "Refresh category text properties in the buffer."
7591 (let ((def-cat (cond
7592 ((null org-category)
7593 (if buffer-file-name
7594 (file-name-sans-extension
7595 (file-name-nondirectory buffer-file-name))
7596 "???"))
7597 ((symbolp org-category) (symbol-name org-category))
7598 (t org-category)))
7599 beg end cat pos optionp)
7600 (org-unmodified
7601 (save-excursion
7602 (save-restriction
7603 (widen)
7604 (goto-char (point-min))
7605 (put-text-property (point) (point-max) 'org-category def-cat)
7606 (while (re-search-forward
7607 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7608 (setq pos (match-end 0)
7609 optionp (equal (char-after (match-beginning 0)) ?#)
7610 cat (org-trim (match-string 2)))
7611 (if optionp
7612 (setq beg (point-at-bol) end (point-max))
7613 (org-back-to-heading t)
7614 (setq beg (point) end (org-end-of-subtree t t)))
7615 (put-text-property beg end 'org-category cat)
7616 (goto-char pos)))))))
7619 ;;;; Link Stuff
7621 ;;; Link abbreviations
7623 (defun org-link-expand-abbrev (link)
7624 "Apply replacements as defined in `org-link-abbrev-alist."
7625 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7626 (let* ((key (match-string 1 link))
7627 (as (or (assoc key org-link-abbrev-alist-local)
7628 (assoc key org-link-abbrev-alist)))
7629 (tag (and (match-end 2) (match-string 3 link)))
7630 rpl)
7631 (if (not as)
7632 link
7633 (setq rpl (cdr as))
7634 (cond
7635 ((symbolp rpl) (funcall rpl tag))
7636 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7637 ((string-match "%h" rpl)
7638 (replace-match (url-hexify-string (or tag "")) t t rpl))
7639 (t (concat rpl tag)))))
7640 link))
7642 ;;; Storing and inserting links
7644 (defvar org-insert-link-history nil
7645 "Minibuffer history for links inserted with `org-insert-link'.")
7647 (defvar org-stored-links nil
7648 "Contains the links stored with `org-store-link'.")
7650 (defvar org-store-link-plist nil
7651 "Plist with info about the most recently link created with `org-store-link'.")
7653 (defvar org-link-protocols nil
7654 "Link protocols added to Org-mode using `org-add-link-type'.")
7656 (defvar org-store-link-functions nil
7657 "List of functions that are called to create and store a link.
7658 Each function will be called in turn until one returns a non-nil
7659 value. Each function should check if it is responsible for creating
7660 this link (for example by looking at the major mode).
7661 If not, it must exit and return nil.
7662 If yes, it should return a non-nil value after a calling
7663 `org-store-link-props' with a list of properties and values.
7664 Special properties are:
7666 :type The link prefix. like \"http\". This must be given.
7667 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7668 This is obligatory as well.
7669 :description Optional default description for the second pair
7670 of brackets in an Org-mode link. The user can still change
7671 this when inserting this link into an Org-mode buffer.
7673 In addition to these, any additional properties can be specified
7674 and then used in remember templates.")
7676 (defun org-add-link-type (type &optional follow export)
7677 "Add TYPE to the list of `org-link-types'.
7678 Re-compute all regular expressions depending on `org-link-types'
7680 FOLLOW and EXPORT are two functions.
7682 FOLLOW should take the link path as the single argument and do whatever
7683 is necessary to follow the link, for example find a file or display
7684 a mail message.
7686 EXPORT should format the link path for export to one of the export formats.
7687 It should be a function accepting three arguments:
7689 path the path of the link, the text after the prefix (like \"http:\")
7690 desc the description of the link, if any, nil if there was no description
7691 format the export format, a symbol like `html' or `latex'.
7693 The function may use the FORMAT information to return different values
7694 depending on the format. The return value will be put literally into
7695 the exported file.
7696 Org-mode has a built-in default for exporting links. If you are happy with
7697 this default, there is no need to define an export function for the link
7698 type. For a simple example of an export function, see `org-bbdb.el'."
7699 (add-to-list 'org-link-types type t)
7700 (org-make-link-regexps)
7701 (if (assoc type org-link-protocols)
7702 (setcdr (assoc type org-link-protocols) (list follow export))
7703 (push (list type follow export) org-link-protocols)))
7705 (defvar org-agenda-buffer-name)
7707 ;;;###autoload
7708 (defun org-store-link (arg)
7709 "\\<org-mode-map>Store an org-link to the current location.
7710 This link is added to `org-stored-links' and can later be inserted
7711 into an org-buffer with \\[org-insert-link].
7713 For some link types, a prefix arg is interpreted:
7714 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7715 For file links, arg negates `org-context-in-file-links'."
7716 (interactive "P")
7717 (org-load-modules-maybe)
7718 (setq org-store-link-plist nil) ; reset
7719 (let ((outline-regexp (org-get-limited-outline-regexp))
7720 link cpltxt desc description search txt custom-id)
7721 (cond
7723 ((run-hook-with-args-until-success 'org-store-link-functions)
7724 (setq link (plist-get org-store-link-plist :link)
7725 desc (or (plist-get org-store-link-plist :description) link)))
7727 ((equal (buffer-name) "*Org Edit Src Example*")
7728 (let (label gc)
7729 (while (or (not label)
7730 (save-excursion
7731 (save-restriction
7732 (widen)
7733 (goto-char (point-min))
7734 (re-search-forward
7735 (regexp-quote (format org-coderef-label-format label))
7736 nil t))))
7737 (when label (message "Label exists already") (sit-for 2))
7738 (setq label (read-string "Code line label: " label)))
7739 (end-of-line 1)
7740 (setq link (format org-coderef-label-format label))
7741 (setq gc (- 79 (length link)))
7742 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7743 (insert link)
7744 (setq link (concat "(" label ")") desc nil)))
7746 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
7747 ;; We are in the agenda, link to referenced location
7748 (let ((m (or (get-text-property (point) 'org-hd-marker)
7749 (get-text-property (point) 'org-marker))))
7750 (when m
7751 (org-with-point-at m
7752 (call-interactively 'org-store-link)))))
7754 ((eq major-mode 'calendar-mode)
7755 (let ((cd (calendar-cursor-to-date)))
7756 (setq link
7757 (format-time-string
7758 (car org-time-stamp-formats)
7759 (apply 'encode-time
7760 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7761 nil nil nil))))
7762 (org-store-link-props :type "calendar" :date cd)))
7764 ((eq major-mode 'w3-mode)
7765 (setq cpltxt (if (and (buffer-name)
7766 (not (string-match "Untitled" (buffer-name))))
7767 (buffer-name)
7768 (url-view-url t))
7769 link (org-make-link (url-view-url t)))
7770 (org-store-link-props :type "w3" :url (url-view-url t)))
7772 ((eq major-mode 'w3m-mode)
7773 (setq cpltxt (or w3m-current-title w3m-current-url)
7774 link (org-make-link w3m-current-url))
7775 (org-store-link-props :type "w3m" :url (url-view-url t)))
7777 ((setq search (run-hook-with-args-until-success
7778 'org-create-file-search-functions))
7779 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7780 "::" search))
7781 (setq cpltxt (or description link)))
7783 ((eq major-mode 'image-mode)
7784 (setq cpltxt (concat "file:"
7785 (abbreviate-file-name buffer-file-name))
7786 link (org-make-link cpltxt))
7787 (org-store-link-props :type "image" :file buffer-file-name))
7789 ((eq major-mode 'dired-mode)
7790 ;; link to the file in the current line
7791 (let ((file (dired-get-filename nil t)))
7792 (setq file (if file
7793 (abbreviate-file-name
7794 (expand-file-name (dired-get-filename nil t)))
7795 ;; otherwise, no file so use current directory.
7796 default-directory))
7797 (setq cpltxt (concat "file:" file)
7798 link (org-make-link cpltxt))))
7800 ((and buffer-file-name (org-mode-p))
7801 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7802 (cond
7803 ((org-in-regexp "<<\\(.*?\\)>>")
7804 (setq cpltxt
7805 (concat "file:"
7806 (abbreviate-file-name buffer-file-name)
7807 "::" (match-string 1))
7808 link (org-make-link cpltxt)))
7809 ((and (featurep 'org-id)
7810 (or (eq org-link-to-org-use-id t)
7811 (and (eq org-link-to-org-use-id 'create-if-interactive)
7812 (interactive-p))
7813 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7814 (interactive-p)
7815 (not custom-id))
7816 (and org-link-to-org-use-id
7817 (condition-case nil
7818 (org-entry-get nil "ID")
7819 (error nil)))))
7820 ;; We can make a link using the ID.
7821 (setq link (condition-case nil
7822 (prog1 (org-id-store-link)
7823 (setq desc (plist-get org-store-link-plist
7824 :description)))
7825 (error
7826 ;; probably before first headline, link to file only
7827 (concat "file:"
7828 (abbreviate-file-name buffer-file-name))))))
7830 ;; Just link to current headline
7831 (setq cpltxt (concat "file:"
7832 (abbreviate-file-name buffer-file-name)))
7833 ;; Add a context search string
7834 (when (org-xor org-context-in-file-links arg)
7835 (setq txt (cond
7836 ((org-on-heading-p) nil)
7837 ((org-region-active-p)
7838 (buffer-substring (region-beginning) (region-end)))
7839 (t nil)))
7840 (when (or (null txt) (string-match "\\S-" txt))
7841 (setq cpltxt
7842 (concat cpltxt "::"
7843 (condition-case nil
7844 (org-make-org-heading-search-string txt)
7845 (error "")))
7846 desc (or (nth 4 (ignore-errors
7847 (org-heading-components))) "NONE"))))
7848 (if (string-match "::\\'" cpltxt)
7849 (setq cpltxt (substring cpltxt 0 -2)))
7850 (setq link (org-make-link cpltxt)))))
7852 ((buffer-file-name (buffer-base-buffer))
7853 ;; Just link to this file here.
7854 (setq cpltxt (concat "file:"
7855 (abbreviate-file-name
7856 (buffer-file-name (buffer-base-buffer)))))
7857 ;; Add a context string
7858 (when (org-xor org-context-in-file-links arg)
7859 (setq txt (if (org-region-active-p)
7860 (buffer-substring (region-beginning) (region-end))
7861 (buffer-substring (point-at-bol) (point-at-eol))))
7862 ;; Only use search option if there is some text.
7863 (when (string-match "\\S-" txt)
7864 (setq cpltxt
7865 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7866 desc "NONE")))
7867 (setq link (org-make-link cpltxt)))
7869 ((interactive-p)
7870 (error "Cannot link to a buffer which is not visiting a file"))
7872 (t (setq link nil)))
7874 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7875 (setq link (or link cpltxt)
7876 desc (or desc cpltxt))
7877 (if (equal desc "NONE") (setq desc nil))
7879 (if (and (or (interactive-p) executing-kbd-macro) link)
7880 (progn
7881 (setq org-stored-links
7882 (cons (list link desc) org-stored-links))
7883 (message "Stored: %s" (or desc link))
7884 (when custom-id
7885 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7886 "::#" custom-id))
7887 (setq org-stored-links
7888 (cons (list link desc) org-stored-links))))
7889 (and link (org-make-link-string link desc)))))
7891 (defun org-store-link-props (&rest plist)
7892 "Store link properties, extract names and addresses."
7893 (let (x adr)
7894 (when (setq x (plist-get plist :from))
7895 (setq adr (mail-extract-address-components x))
7896 (setq plist (plist-put plist :fromname (car adr)))
7897 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7898 (when (setq x (plist-get plist :to))
7899 (setq adr (mail-extract-address-components x))
7900 (setq plist (plist-put plist :toname (car adr)))
7901 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7902 (let ((from (plist-get plist :from))
7903 (to (plist-get plist :to)))
7904 (when (and from to org-from-is-user-regexp)
7905 (setq plist
7906 (plist-put plist :fromto
7907 (if (string-match org-from-is-user-regexp from)
7908 (concat "to %t")
7909 (concat "from %f"))))))
7910 (setq org-store-link-plist plist))
7912 (defun org-add-link-props (&rest plist)
7913 "Add these properties to the link property list."
7914 (let (key value)
7915 (while plist
7916 (setq key (pop plist) value (pop plist))
7917 (setq org-store-link-plist
7918 (plist-put org-store-link-plist key value)))))
7920 (defun org-email-link-description (&optional fmt)
7921 "Return the description part of an email link.
7922 This takes information from `org-store-link-plist' and formats it
7923 according to FMT (default from `org-email-link-description-format')."
7924 (setq fmt (or fmt org-email-link-description-format))
7925 (let* ((p org-store-link-plist)
7926 (to (plist-get p :toaddress))
7927 (from (plist-get p :fromaddress))
7928 (table
7929 (list
7930 (cons "%c" (plist-get p :fromto))
7931 (cons "%F" (plist-get p :from))
7932 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7933 (cons "%T" (plist-get p :to))
7934 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7935 (cons "%s" (plist-get p :subject))
7936 (cons "%m" (plist-get p :message-id)))))
7937 (when (string-match "%c" fmt)
7938 ;; Check if the user wrote this message
7939 (if (and org-from-is-user-regexp from to
7940 (save-match-data (string-match org-from-is-user-regexp from)))
7941 (setq fmt (replace-match "to %t" t t fmt))
7942 (setq fmt (replace-match "from %f" t t fmt))))
7943 (org-replace-escapes fmt table)))
7945 (defun org-make-org-heading-search-string (&optional string heading)
7946 "Make search string for STRING or current headline."
7947 (interactive)
7948 (let ((s (or string (org-get-heading))))
7949 (unless (and string (not heading))
7950 ;; We are using a headline, clean up garbage in there.
7951 (if (string-match org-todo-regexp s)
7952 (setq s (replace-match "" t t s)))
7953 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7954 (setq s (replace-match "" t t s)))
7955 (setq s (org-trim s))
7956 (if (string-match (concat "^\\(" org-quote-string "\\|"
7957 org-comment-string "\\)") s)
7958 (setq s (replace-match "" t t s)))
7959 (while (string-match org-ts-regexp s)
7960 (setq s (replace-match "" t t s))))
7961 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7962 (setq s (replace-match " " t t s)))
7963 (or string (setq s (concat "*" s))) ; Add * for headlines
7964 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7966 (defun org-make-link (&rest strings)
7967 "Concatenate STRINGS."
7968 (apply 'concat strings))
7970 (defun org-make-link-string (link &optional description)
7971 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7972 (unless (string-match "\\S-" link)
7973 (error "Empty link"))
7974 (when (and description
7975 (stringp description)
7976 (not (string-match "\\S-" description)))
7977 (setq description nil))
7978 (when (stringp description)
7979 ;; Remove brackets from the description, they are fatal.
7980 (while (string-match "\\[" description)
7981 (setq description (replace-match "{" t t description)))
7982 (while (string-match "\\]" description)
7983 (setq description (replace-match "}" t t description))))
7984 (when (equal (org-link-escape link) description)
7985 ;; No description needed, it is identical
7986 (setq description nil))
7987 (when (and (not description)
7988 (not (equal link (org-link-escape link))))
7989 (setq description (org-extract-attributes link)))
7990 (concat "[[" (org-link-escape link) "]"
7991 (if description (concat "[" description "]") "")
7992 "]"))
7994 (defconst org-link-escape-chars
7995 '((?\ . "%20")
7996 (?\[ . "%5B")
7997 (?\] . "%5D")
7998 (?\340 . "%E0") ; `a
7999 (?\342 . "%E2") ; ^a
8000 (?\347 . "%E7") ; ,c
8001 (?\350 . "%E8") ; `e
8002 (?\351 . "%E9") ; 'e
8003 (?\352 . "%EA") ; ^e
8004 (?\356 . "%EE") ; ^i
8005 (?\364 . "%F4") ; ^o
8006 (?\371 . "%F9") ; `u
8007 (?\373 . "%FB") ; ^u
8008 (?\; . "%3B")
8009 ;; (?? . "%3F")
8010 (?= . "%3D")
8011 (?+ . "%2B")
8013 "Association list of escapes for some characters problematic in links.
8014 This is the list that is used for internal purposes.")
8016 (defvar org-url-encoding-use-url-hexify nil)
8018 (defconst org-link-escape-chars-browser
8019 '((?\ . "%20")) ; 32 for the SPC char
8020 "Association list of escapes for some characters problematic in links.
8021 This is the list that is used before handing over to the browser.")
8023 (defun org-link-escape (text &optional table)
8024 "Escape characters in TEXT that are problematic for links."
8025 (if (and org-url-encoding-use-url-hexify (not table))
8026 (url-hexify-string text)
8027 (setq table (or table org-link-escape-chars))
8028 (when text
8029 (let ((re (mapconcat (lambda (x) (regexp-quote
8030 (char-to-string (car x))))
8031 table "\\|")))
8032 (while (string-match re text)
8033 (setq text
8034 (replace-match
8035 (cdr (assoc (string-to-char (match-string 0 text))
8036 table))
8037 t t text)))
8038 text))))
8040 (defun org-link-unescape (text &optional table)
8041 "Reverse the action of `org-link-escape'."
8042 (if (and org-url-encoding-use-url-hexify (not table))
8043 (url-unhex-string text)
8044 (setq table (or table org-link-escape-chars))
8045 (when text
8046 (let ((case-fold-search t)
8047 (re (mapconcat (lambda (x) (regexp-quote (downcase (cdr x))))
8048 table "\\|")))
8049 (while (string-match re text)
8050 (setq text
8051 (replace-match
8052 (char-to-string (car (rassoc (upcase (match-string 0 text))
8053 table)))
8054 t t text)))
8055 text))))
8057 (defun org-xor (a b)
8058 "Exclusive or."
8059 (if a (not b) b))
8061 (defun org-fixup-message-id-for-http (s)
8062 "Replace special characters in a message id, so it can be used in an http query."
8063 (while (string-match "<" s)
8064 (setq s (replace-match "%3C" t t s)))
8065 (while (string-match ">" s)
8066 (setq s (replace-match "%3E" t t s)))
8067 (while (string-match "@" s)
8068 (setq s (replace-match "%40" t t s)))
8071 ;;;###autoload
8072 (defun org-insert-link-global ()
8073 "Insert a link like Org-mode does.
8074 This command can be called in any mode to insert a link in Org-mode syntax."
8075 (interactive)
8076 (org-load-modules-maybe)
8077 (org-run-like-in-org-mode 'org-insert-link))
8079 (defun org-insert-link (&optional complete-file link-location)
8080 "Insert a link. At the prompt, enter the link.
8082 Completion can be used to insert any of the link protocol prefixes like
8083 http or ftp in use.
8085 The history can be used to select a link previously stored with
8086 `org-store-link'. When the empty string is entered (i.e. if you just
8087 press RET at the prompt), the link defaults to the most recently
8088 stored link. As SPC triggers completion in the minibuffer, you need to
8089 use M-SPC or C-q SPC to force the insertion of a space character.
8091 You will also be prompted for a description, and if one is given, it will
8092 be displayed in the buffer instead of the link.
8094 If there is already a link at point, this command will allow you to edit link
8095 and description parts.
8097 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
8098 be selected using completion. The path to the file will be relative to the
8099 current directory if the file is in the current directory or a subdirectory.
8100 Otherwise, the link will be the absolute path as completed in the minibuffer
8101 \(i.e. normally ~/path/to/file). You can configure this behavior using the
8102 option `org-link-file-path-type'.
8104 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
8105 the current directory or below.
8107 With three \\[universal-argument] prefixes, negate the meaning of
8108 `org-keep-stored-link-after-insertion'.
8110 If `org-make-link-description-function' is non-nil, this function will be
8111 called with the link target, and the result will be the default
8112 link description.
8114 If the LINK-LOCATION parameter is non-nil, this value will be
8115 used as the link location instead of reading one interactively."
8116 (interactive "P")
8117 (let* ((wcf (current-window-configuration))
8118 (region (if (org-region-active-p)
8119 (buffer-substring (region-beginning) (region-end))))
8120 (remove (and region (list (region-beginning) (region-end))))
8121 (desc region)
8122 tmphist ; byte-compile incorrectly complains about this
8123 (link link-location)
8124 entry file all-prefixes)
8125 (cond
8126 (link-location) ; specified by arg, just use it.
8127 ((org-in-regexp org-bracket-link-regexp 1)
8128 ;; We do have a link at point, and we are going to edit it.
8129 (setq remove (list (match-beginning 0) (match-end 0)))
8130 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8131 (setq link (read-string "Link: "
8132 (org-link-unescape
8133 (org-match-string-no-properties 1)))))
8134 ((or (org-in-regexp org-angle-link-re)
8135 (org-in-regexp org-plain-link-re))
8136 ;; Convert to bracket link
8137 (setq remove (list (match-beginning 0) (match-end 0))
8138 link (read-string "Link: "
8139 (org-remove-angle-brackets (match-string 0)))))
8140 ((member complete-file '((4) (16)))
8141 ;; Completing read for file names.
8142 (setq link (org-file-complete-link complete-file)))
8144 ;; Read link, with completion for stored links.
8145 (with-output-to-temp-buffer "*Org Links*"
8146 (princ "Insert a link.
8147 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
8148 (when org-stored-links
8149 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8150 (princ (mapconcat
8151 (lambda (x)
8152 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8153 (reverse org-stored-links) "\n"))))
8154 (let ((cw (selected-window)))
8155 (select-window (get-buffer-window "*Org Links*"))
8156 (setq truncate-lines t)
8157 (unless (pos-visible-in-window-p (point-max))
8158 (org-fit-window-to-buffer))
8159 (and (window-live-p cw) (select-window cw)))
8160 ;; Fake a link history, containing the stored links.
8161 (setq tmphist (append (mapcar 'car org-stored-links)
8162 org-insert-link-history))
8163 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8164 (mapcar 'car org-link-abbrev-alist)
8165 org-link-types))
8166 (unwind-protect
8167 (progn
8168 (setq link
8169 (let ((org-completion-use-ido nil)
8170 (org-completion-use-iswitchb nil))
8171 (org-completing-read
8172 "Link: "
8173 (append
8174 (mapcar (lambda (x) (list (concat x ":")))
8175 all-prefixes)
8176 (mapcar 'car org-stored-links))
8177 nil nil nil
8178 'tmphist
8179 (car (car org-stored-links)))))
8180 (if (not (string-match "\\S-" link))
8181 (error "No link selected"))
8182 (if (or (member link all-prefixes)
8183 (and (equal ":" (substring link -1))
8184 (member (substring link 0 -1) all-prefixes)
8185 (setq link (substring link 0 -1))))
8186 (setq link (org-link-try-special-completion link))))
8187 (set-window-configuration wcf)
8188 (kill-buffer "*Org Links*"))
8189 (setq entry (assoc link org-stored-links))
8190 (or entry (push link org-insert-link-history))
8191 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8192 (not org-keep-stored-link-after-insertion))
8193 (setq org-stored-links (delq (assoc link org-stored-links)
8194 org-stored-links)))
8195 (setq desc (or desc (nth 1 entry)))))
8197 (if (string-match org-plain-link-re link)
8198 ;; URL-like link, normalize the use of angular brackets.
8199 (setq link (org-make-link (org-remove-angle-brackets link))))
8201 ;; Check if we are linking to the current file with a search option
8202 ;; If yes, simplify the link by using only the search option.
8203 (when (and buffer-file-name
8204 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
8205 (let* ((path (match-string 1 link))
8206 (case-fold-search nil)
8207 (search (match-string 2 link)))
8208 (save-match-data
8209 (if (equal (file-truename buffer-file-name) (file-truename path))
8210 ;; We are linking to this same file, with a search option
8211 (setq link search)))))
8213 ;; Check if we can/should use a relative path. If yes, simplify the link
8214 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8215 (let* ((type (match-string 1 link))
8216 (path (match-string 2 link))
8217 (origpath path)
8218 (case-fold-search nil))
8219 (cond
8220 ((or (eq org-link-file-path-type 'absolute)
8221 (equal complete-file '(16)))
8222 (setq path (abbreviate-file-name (expand-file-name path))))
8223 ((eq org-link-file-path-type 'noabbrev)
8224 (setq path (expand-file-name path)))
8225 ((eq org-link-file-path-type 'relative)
8226 (setq path (file-relative-name path)))
8228 (save-match-data
8229 (if (string-match (concat "^" (regexp-quote
8230 (file-name-as-directory
8231 (expand-file-name "."))))
8232 (expand-file-name path))
8233 ;; We are linking a file with relative path name.
8234 (setq path (substring (expand-file-name path)
8235 (match-end 0)))
8236 (setq path (abbreviate-file-name (expand-file-name path)))))))
8237 (setq link (concat type path))
8238 (if (equal desc origpath)
8239 (setq desc path))))
8241 (if org-make-link-description-function
8242 (setq desc (funcall org-make-link-description-function link desc)))
8244 (setq desc (read-string "Description: " desc))
8245 (unless (string-match "\\S-" desc) (setq desc nil))
8246 (if remove (apply 'delete-region remove))
8247 (insert (org-make-link-string link desc))))
8249 (defun org-link-try-special-completion (type)
8250 "If there is completion support for link type TYPE, offer it."
8251 (let ((fun (intern (concat "org-" type "-complete-link"))))
8252 (if (functionp fun)
8253 (funcall fun)
8254 (read-string "Link (no completion support): " (concat type ":")))))
8256 (defun org-file-complete-link (&optional arg)
8257 "Create a file link using completion."
8258 (let (file link)
8259 (setq file (read-file-name "File: "))
8260 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8261 (pwd1 (file-name-as-directory (abbreviate-file-name
8262 (expand-file-name ".")))))
8263 (cond
8264 ((equal arg '(16))
8265 (setq link (org-make-link
8266 "file:"
8267 (abbreviate-file-name (expand-file-name file)))))
8268 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8269 (setq link (org-make-link "file:" (match-string 1 file))))
8270 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8271 (expand-file-name file))
8272 (setq link (org-make-link
8273 "file:" (match-string 1 (expand-file-name file)))))
8274 (t (setq link (org-make-link "file:" file)))))
8275 link))
8277 (defun org-completing-read (&rest args)
8278 "Completing-read with SPACE being a normal character."
8279 (let ((minibuffer-local-completion-map
8280 (copy-keymap minibuffer-local-completion-map)))
8281 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
8282 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
8283 (apply 'org-icompleting-read args)))
8285 (defun org-completing-read-no-i (&rest args)
8286 (let (org-completion-use-ido org-completion-use-iswitchb)
8287 (apply 'org-completing-read args)))
8289 (defun org-iswitchb-completing-read (prompt choices &rest args)
8290 "Use iswitch as a completing-read replacement to choose from choices.
8291 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
8292 from."
8293 (let* ((iswitchb-use-virtual-buffers nil)
8294 (iswitchb-make-buflist-hook
8295 (lambda ()
8296 (setq iswitchb-temp-buflist choices))))
8297 (iswitchb-read-buffer prompt)))
8299 (defun org-icompleting-read (&rest args)
8300 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
8301 (org-without-partial-completion
8302 (if (and org-completion-use-ido
8303 (fboundp 'ido-completing-read)
8304 (boundp 'ido-mode) ido-mode
8305 (listp (second args)))
8306 (let ((ido-enter-matching-directory nil))
8307 (apply 'ido-completing-read (concat (car args))
8308 (if (consp (car (nth 1 args)))
8309 (mapcar (lambda (x) (car x)) (nth 1 args))
8310 (nth 1 args))
8311 (cddr args)))
8312 (if (and org-completion-use-iswitchb
8313 (boundp 'iswitchb-mode) iswitchb-mode
8314 (listp (second args)))
8315 (apply 'org-iswitchb-completing-read (concat (car args))
8316 (if (consp (car (nth 1 args)))
8317 (mapcar (lambda (x) (car x)) (nth 1 args))
8318 (nth 1 args))
8319 (cddr args))
8320 (apply 'completing-read args)))))
8322 (defun org-extract-attributes (s)
8323 "Extract the attributes cookie from a string and set as text property."
8324 (let (a attr (start 0) key value)
8325 (save-match-data
8326 (when (string-match "{{\\([^}]+\\)}}$" s)
8327 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
8328 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
8329 (setq key (match-string 1 a) value (match-string 2 a)
8330 start (match-end 0)
8331 attr (plist-put attr (intern key) value))))
8332 (org-add-props s nil 'org-attr attr))
8335 (defun org-extract-attributes-from-string (tag)
8336 (let (key value attr)
8337 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
8338 (setq key (match-string 1 tag) value (match-string 2 tag)
8339 tag (replace-match "" t t tag)
8340 attr (plist-put attr (intern key) value)))
8341 (cons tag attr)))
8343 (defun org-attributes-to-string (plist)
8344 "Format a property list into an HTML attribute list."
8345 (let ((s "") key value)
8346 (while plist
8347 (setq key (pop plist) value (pop plist))
8348 (and value
8349 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8352 ;;; Opening/following a link
8354 (defvar org-link-search-failed nil)
8356 (defvar org-open-link-functions nil
8357 "Hook for functions finding a plain text link.
8358 These functions must take a single argument, the link content.
8359 They will be called for links that look like [[link text][description]]
8360 when LINK TEXT does not have a protocol like \"http:\" and does not look
8361 like a filename (e.g. \"./blue.png\").
8363 These functions will be called *before* Org attempts to resolve the
8364 link by doing text searches in the current buffer - so if you want a
8365 link \"[[target]]\" to still find \"<<target>>\", your function should
8366 handle this as a special case.
8368 When the function does handle the link, it must return a non-nil value.
8369 If it decides that it is not responsible for this link, it must return
8370 nil to indicate that that Org-mode can continue with other options
8371 like exact and fuzzy text search.")
8373 (defun org-next-link ()
8374 "Move forward to the next link.
8375 If the link is in hidden text, expose it."
8376 (interactive)
8377 (when (and org-link-search-failed (eq this-command last-command))
8378 (goto-char (point-min))
8379 (message "Link search wrapped back to beginning of buffer"))
8380 (setq org-link-search-failed nil)
8381 (let* ((pos (point))
8382 (ct (org-context))
8383 (a (assoc :link ct)))
8384 (if a (goto-char (nth 2 a)))
8385 (if (re-search-forward org-any-link-re nil t)
8386 (progn
8387 (goto-char (match-beginning 0))
8388 (if (org-invisible-p) (org-show-context)))
8389 (goto-char pos)
8390 (setq org-link-search-failed t)
8391 (error "No further link found"))))
8393 (defun org-previous-link ()
8394 "Move backward to the previous link.
8395 If the link is in hidden text, expose it."
8396 (interactive)
8397 (when (and org-link-search-failed (eq this-command last-command))
8398 (goto-char (point-max))
8399 (message "Link search wrapped back to end of buffer"))
8400 (setq org-link-search-failed nil)
8401 (let* ((pos (point))
8402 (ct (org-context))
8403 (a (assoc :link ct)))
8404 (if a (goto-char (nth 1 a)))
8405 (if (re-search-backward org-any-link-re nil t)
8406 (progn
8407 (goto-char (match-beginning 0))
8408 (if (org-invisible-p) (org-show-context)))
8409 (goto-char pos)
8410 (setq org-link-search-failed t)
8411 (error "No further link found"))))
8413 (defun org-translate-link (s)
8414 "Translate a link string if a translation function has been defined."
8415 (if (and org-link-translation-function
8416 (fboundp org-link-translation-function)
8417 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8418 (progn
8419 (setq s (funcall org-link-translation-function
8420 (match-string 1) (match-string 2)))
8421 (concat (car s) ":" (cdr s)))
8424 (defun org-translate-link-from-planner (type path)
8425 "Translate a link from Emacs Planner syntax so that Org can follow it.
8426 This is still an experimental function, your mileage may vary."
8427 (cond
8428 ((member type '("http" "https" "news" "ftp"))
8429 ;; standard Internet links are the same.
8430 nil)
8431 ((and (equal type "irc") (string-match "^//" path))
8432 ;; Planner has two / at the beginning of an irc link, we have 1.
8433 ;; We should have zero, actually....
8434 (setq path (substring path 1)))
8435 ((and (equal type "lisp") (string-match "^/" path))
8436 ;; Planner has a slash, we do not.
8437 (setq type "elisp" path (substring path 1)))
8438 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8439 ;; A typical message link. Planner has the id after the final slash,
8440 ;; we separate it with a hash mark
8441 (setq path (concat (match-string 1 path) "#"
8442 (org-remove-angle-brackets (match-string 2 path)))))
8444 (cons type path))
8446 (defun org-find-file-at-mouse (ev)
8447 "Open file link or URL at mouse."
8448 (interactive "e")
8449 (mouse-set-point ev)
8450 (org-open-at-point 'in-emacs))
8452 (defun org-open-at-mouse (ev)
8453 "Open file link or URL at mouse."
8454 (interactive "e")
8455 (mouse-set-point ev)
8456 (if (eq major-mode 'org-agenda-mode)
8457 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8458 (org-open-at-point))
8460 (defvar org-window-config-before-follow-link nil
8461 "The window configuration before following a link.
8462 This is saved in case the need arises to restore it.")
8464 (defvar org-open-link-marker (make-marker)
8465 "Marker pointing to the location where `org-open-at-point; was called.")
8467 ;;;###autoload
8468 (defun org-open-at-point-global ()
8469 "Follow a link like Org-mode does.
8470 This command can be called in any mode to follow a link that has
8471 Org-mode syntax."
8472 (interactive)
8473 (org-run-like-in-org-mode 'org-open-at-point))
8475 ;;;###autoload
8476 (defun org-open-link-from-string (s &optional arg reference-buffer)
8477 "Open a link in the string S, as if it was in Org-mode."
8478 (interactive "sLink: \nP")
8479 (let ((reference-buffer (or reference-buffer (current-buffer))))
8480 (with-temp-buffer
8481 (let ((org-inhibit-startup t))
8482 (org-mode)
8483 (insert s)
8484 (goto-char (point-min))
8485 (when reference-buffer
8486 (setq org-link-abbrev-alist-local
8487 (with-current-buffer reference-buffer
8488 org-link-abbrev-alist-local)))
8489 (org-open-at-point arg reference-buffer)))))
8491 (defun org-open-at-point (&optional in-emacs reference-buffer)
8492 "Open link at or after point.
8493 If there is no link at point, this function will search forward up to
8494 the end of the current line.
8495 Normally, files will be opened by an appropriate application. If the
8496 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8497 With a double prefix argument, try to open outside of Emacs, in the
8498 application the system uses for this file type."
8499 (interactive "P")
8500 (org-load-modules-maybe)
8501 (move-marker org-open-link-marker (point))
8502 (setq org-window-config-before-follow-link (current-window-configuration))
8503 (org-remove-occur-highlights nil nil t)
8504 (cond
8505 ((and (org-on-heading-p)
8506 (not (org-in-regexp
8507 (concat org-plain-link-re "\\|"
8508 org-bracket-link-regexp "\\|"
8509 org-angle-link-re "\\|"
8510 "[ \t]:[^ \t\n]+:[ \t]*$")))
8511 (not (get-text-property (point) 'org-linked-text)))
8512 (or (org-offer-links-in-entry in-emacs)
8513 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8514 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8515 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8516 (org-footnote-action))
8518 (let (type path link line search (pos (point)))
8519 (catch 'match
8520 (save-excursion
8521 (skip-chars-forward "^]\n\r")
8522 (when (org-in-regexp org-bracket-link-regexp 1)
8523 (setq link (org-extract-attributes
8524 (org-link-unescape (org-match-string-no-properties 1))))
8525 (while (string-match " *\n *" link)
8526 (setq link (replace-match " " t t link)))
8527 (setq link (org-link-expand-abbrev link))
8528 (cond
8529 ((or (file-name-absolute-p link)
8530 (string-match "^\\.\\.?/" link))
8531 (setq type "file" path link))
8532 ((string-match org-link-re-with-space3 link)
8533 (setq type (match-string 1 link) path (match-string 2 link)))
8534 (t (setq type "thisfile" path link)))
8535 (throw 'match t)))
8537 (when (get-text-property (point) 'org-linked-text)
8538 (setq type "thisfile"
8539 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8540 (1+ (point)) (point))
8541 path (buffer-substring
8542 (previous-single-property-change pos 'org-linked-text)
8543 (next-single-property-change pos 'org-linked-text)))
8544 (throw 'match t))
8546 (save-excursion
8547 (when (or (org-in-regexp org-angle-link-re)
8548 (org-in-regexp org-plain-link-re))
8549 (setq type (match-string 1) path (match-string 2))
8550 (throw 'match t)))
8551 (save-excursion
8552 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
8553 (setq type "tags"
8554 path (match-string 1))
8555 (while (string-match ":" path)
8556 (setq path (replace-match "+" t t path)))
8557 (throw 'match t)))
8558 (when (org-in-regexp "<\\([^><\n]+\\)>")
8559 (setq type "tree-match"
8560 path (match-string 1))
8561 (throw 'match t)))
8562 (unless path
8563 (error "No link found"))
8565 ;; switch back to reference buffer
8566 ;; needed when if called in a temporary buffer through
8567 ;; org-open-link-from-string
8568 (with-current-buffer (or reference-buffer (current-buffer))
8570 ;; Remove any trailing spaces in path
8571 (if (string-match " +\\'" path)
8572 (setq path (replace-match "" t t path)))
8573 (if (and org-link-translation-function
8574 (fboundp org-link-translation-function))
8575 ;; Check if we need to translate the link
8576 (let ((tmp (funcall org-link-translation-function type path)))
8577 (setq type (car tmp) path (cdr tmp))))
8579 (cond
8581 ((assoc type org-link-protocols)
8582 (funcall (nth 1 (assoc type org-link-protocols)) path))
8584 ((equal type "mailto")
8585 (let ((cmd (car org-link-mailto-program))
8586 (args (cdr org-link-mailto-program)) args1
8587 (address path) (subject "") a)
8588 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8589 (setq address (match-string 1 path)
8590 subject (org-link-escape (match-string 2 path))))
8591 (while args
8592 (cond
8593 ((not (stringp (car args))) (push (pop args) args1))
8594 (t (setq a (pop args))
8595 (if (string-match "%a" a)
8596 (setq a (replace-match address t t a)))
8597 (if (string-match "%s" a)
8598 (setq a (replace-match subject t t a)))
8599 (push a args1))))
8600 (apply cmd (nreverse args1))))
8602 ((member type '("http" "https" "ftp" "news"))
8603 (browse-url (concat type ":" (org-link-escape
8604 path org-link-escape-chars-browser))))
8606 ((member type '("message"))
8607 (browse-url (concat type ":" path)))
8609 ((string= type "tags")
8610 (org-tags-view in-emacs path))
8612 ((string= type "tree-match")
8613 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8615 ((string= type "file")
8616 (if (string-match "::\\([0-9]+\\)\\'" path)
8617 (setq line (string-to-number (match-string 1 path))
8618 path (substring path 0 (match-beginning 0)))
8619 (if (string-match "::\\(.+\\)\\'" path)
8620 (setq search (match-string 1 path)
8621 path (substring path 0 (match-beginning 0)))))
8622 (if (string-match "[*?{]" (file-name-nondirectory path))
8623 (dired path)
8624 (org-open-file path in-emacs line search)))
8626 ((string= type "news")
8627 (require 'org-gnus)
8628 (org-gnus-follow-link path))
8630 ((string= type "shell")
8631 (let ((cmd path))
8632 (if (or (not org-confirm-shell-link-function)
8633 (funcall org-confirm-shell-link-function
8634 (format "Execute \"%s\" in shell? "
8635 (org-add-props cmd nil
8636 'face 'org-warning))))
8637 (progn
8638 (message "Executing %s" cmd)
8639 (shell-command cmd))
8640 (error "Abort"))))
8642 ((string= type "elisp")
8643 (let ((cmd path))
8644 (if (or (not org-confirm-elisp-link-function)
8645 (funcall org-confirm-elisp-link-function
8646 (format "Execute \"%s\" as elisp? "
8647 (org-add-props cmd nil
8648 'face 'org-warning))))
8649 (message "%s => %s" cmd
8650 (if (equal (string-to-char cmd) ?\()
8651 (eval (read cmd))
8652 (call-interactively (read cmd))))
8653 (error "Abort"))))
8655 ((and (string= type "thisfile")
8656 (run-hook-with-args-until-success
8657 'org-open-link-functions path)))
8659 ((string= type "thisfile")
8660 (if in-emacs
8661 (switch-to-buffer-other-window
8662 (org-get-buffer-for-internal-link (current-buffer)))
8663 (org-mark-ring-push))
8664 (let ((cmd `(org-link-search
8665 ,path
8666 ,(cond ((equal in-emacs '(4)) 'occur)
8667 ((equal in-emacs '(16)) 'org-occur)
8668 (t nil))
8669 ,pos)))
8670 (condition-case nil (eval cmd)
8671 (error (progn (widen) (eval cmd))))))
8674 (browse-url-at-point)))))))
8675 (move-marker org-open-link-marker nil)
8676 (run-hook-with-args 'org-follow-link-hook))
8678 (defun org-offer-links-in-entry (&optional nth zero)
8679 "Offer links in the current entry and follow the selected link.
8680 If there is only one link, follow it immediately as well.
8681 If NTH is an integer, immediately pick the NTH link found.
8682 If ZERO is a string, check also this string for a link, and if
8683 there is one, offer it as link number zero."
8684 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
8685 "\\(" org-angle-link-re "\\)\\|"
8686 "\\(" org-plain-link-re "\\)"))
8687 (cnt ?0)
8688 (in-emacs (if (integerp nth) nil nth))
8689 have-zero end links link c)
8690 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
8691 (push (match-string 0 zero) links)
8692 (setq cnt (1- cnt) have-zero t))
8693 (save-excursion
8694 (org-back-to-heading t)
8695 (setq end (save-excursion (outline-next-heading) (point)))
8696 (while (re-search-forward re end t)
8697 (push (match-string 0) links))
8698 (setq links (org-uniquify (reverse links))))
8700 (cond
8701 ((null links)
8702 (message "No links"))
8703 ((equal (length links) 1)
8704 (setq link (list (car links))))
8705 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8706 (setq link (nth (if have-zero nth (1- nth)) links)))
8707 (t ; we have to select a link
8708 (save-excursion
8709 (save-window-excursion
8710 (delete-other-windows)
8711 (with-output-to-temp-buffer "*Select Link*"
8712 (mapc (lambda (l)
8713 (if (not (string-match org-bracket-link-regexp l))
8714 (princ (format "[%c] %s\n" (incf cnt)
8715 (org-remove-angle-brackets l)))
8716 (if (match-end 3)
8717 (princ (format "[%c] %s (%s)\n" (incf cnt)
8718 (match-string 3 l) (match-string 1 l)))
8719 (princ (format "[%c] %s\n" (incf cnt)
8720 (match-string 1 l))))))
8721 links))
8722 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8723 (message "Select link to open, RET to open all:")
8724 (setq c (read-char-exclusive))
8725 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8726 (when (equal c ?q) (error "Abort"))
8727 (if (equal c ?\C-m)
8728 (setq link links)
8729 (setq nth (- c ?0))
8730 (if have-zero (setq nth (1+ nth)))
8731 (unless (and (integerp nth) (>= (length links) nth))
8732 (error "Invalid link selection"))
8733 (setq link (list (nth (1- nth) links))))))
8734 (if link
8735 (let ((buf (current-buffer)))
8736 (dolist (l link)
8737 (org-open-link-from-string l in-emacs buf))
8739 nil)))
8741 ;; Add special file links that specify the way of opening
8743 (org-add-link-type "file+sys" 'org-open-file-with-system)
8744 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
8745 (defun org-open-file-with-system (path)
8746 "Open file at PATH using the system way of opeing it."
8747 (org-open-file path 'system))
8748 (defun org-open-file-with-emacs (path)
8749 "Open file at PATH in emacs."
8750 (org-open-file path 'emacs))
8751 (defun org-remove-file-link-modifiers ()
8752 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
8753 (goto-char (point-min))
8754 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
8755 (org-if-unprotected
8756 (replace-match "file:" t t))))
8757 (eval-after-load "org-exp"
8758 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
8759 'org-remove-file-link-modifiers))
8761 ;;;; Time estimates
8763 (defun org-get-effort (&optional pom)
8764 "Get the effort estimate for the current entry."
8765 (org-entry-get pom org-effort-property))
8767 ;;; File search
8769 (defvar org-create-file-search-functions nil
8770 "List of functions to construct the right search string for a file link.
8771 These functions are called in turn with point at the location to
8772 which the link should point.
8774 A function in the hook should first test if it would like to
8775 handle this file type, for example by checking the major-mode or
8776 the file extension. If it decides not to handle this file, it
8777 should just return nil to give other functions a chance. If it
8778 does handle the file, it must return the search string to be used
8779 when following the link. The search string will be part of the
8780 file link, given after a double colon, and `org-open-at-point'
8781 will automatically search for it. If special measures must be
8782 taken to make the search successful, another function should be
8783 added to the companion hook `org-execute-file-search-functions',
8784 which see.
8786 A function in this hook may also use `setq' to set the variable
8787 `description' to provide a suggestion for the descriptive text to
8788 be used for this link when it gets inserted into an Org-mode
8789 buffer with \\[org-insert-link].")
8791 (defvar org-execute-file-search-functions nil
8792 "List of functions to execute a file search triggered by a link.
8794 Functions added to this hook must accept a single argument, the
8795 search string that was part of the file link, the part after the
8796 double colon. The function must first check if it would like to
8797 handle this search, for example by checking the major-mode or the
8798 file extension. If it decides not to handle this search, it
8799 should just return nil to give other functions a chance. If it
8800 does handle the search, it must return a non-nil value to keep
8801 other functions from trying.
8803 Each function can access the current prefix argument through the
8804 variable `current-prefix-argument'. Note that a single prefix is
8805 used to force opening a link in Emacs, so it may be good to only
8806 use a numeric or double prefix to guide the search function.
8808 In case this is needed, a function in this hook can also restore
8809 the window configuration before `org-open-at-point' was called using:
8811 (set-window-configuration org-window-config-before-follow-link)")
8813 (defun org-link-search (s &optional type avoid-pos)
8814 "Search for a link search option.
8815 If S is surrounded by forward slashes, it is interpreted as a
8816 regular expression. In org-mode files, this will create an `org-occur'
8817 sparse tree. In ordinary files, `occur' will be used to list matches.
8818 If the current buffer is in `dired-mode', grep will be used to search
8819 in all files. If AVOID-POS is given, ignore matches near that position."
8820 (let ((case-fold-search t)
8821 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8822 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8823 (append '(("") (" ") ("\t") ("\n"))
8824 org-emphasis-alist)
8825 "\\|") "\\)"))
8826 (pos (point))
8827 (pre nil) (post nil)
8828 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8829 (cond
8830 ;; First check if there are any special
8831 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8832 ;; Now try the builtin stuff
8833 ((and (equal (string-to-char s0) ?#)
8834 (> (length s0) 1)
8835 (save-excursion
8836 (goto-char (point-min))
8837 (and
8838 (re-search-forward
8839 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8840 (setq type 'dedicated
8841 pos (match-beginning 0))))
8842 ;; There is an exact target for this
8843 (goto-char pos)
8844 (org-back-to-heading t)))
8845 ((save-excursion
8846 (goto-char (point-min))
8847 (and
8848 (re-search-forward
8849 (concat "<<" (regexp-quote s0) ">>") nil t)
8850 (setq type 'dedicated
8851 pos (match-beginning 0))))
8852 ;; There is an exact target for this
8853 (goto-char pos))
8854 ((and (string-match "^(\\(.*\\))$" s0)
8855 (save-excursion
8856 (goto-char (point-min))
8857 (and
8858 (re-search-forward
8859 (concat "[^[]" (regexp-quote
8860 (format org-coderef-label-format
8861 (match-string 1 s0))))
8862 nil t)
8863 (setq type 'dedicated
8864 pos (1+ (match-beginning 0))))))
8865 ;; There is a coderef target for this
8866 (goto-char pos))
8867 ((string-match "^/\\(.*\\)/$" s)
8868 ;; A regular expression
8869 (cond
8870 ((org-mode-p)
8871 (org-occur (match-string 1 s)))
8872 ;;((eq major-mode 'dired-mode)
8873 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8874 (t (org-do-occur (match-string 1 s)))))
8876 ;; A normal search strings
8877 (when (equal (string-to-char s) ?*)
8878 ;; Anchor on headlines, post may include tags.
8879 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8880 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8881 s (substring s 1)))
8882 (remove-text-properties
8883 0 (length s)
8884 '(face nil mouse-face nil keymap nil fontified nil) s)
8885 ;; Make a series of regular expressions to find a match
8886 (setq words (org-split-string s "[ \n\r\t]+")
8888 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8889 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8890 "\\)" markers)
8891 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8892 re2a (concat "[ \t\r\n]" re2a_)
8893 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8894 re4 (concat "[^a-zA-Z_]" re4_)
8896 re1 (concat pre re2 post)
8897 re3 (concat pre (if pre re4_ re4) post)
8898 re5 (concat pre ".*" re4)
8899 re2 (concat pre re2)
8900 re2a (concat pre (if pre re2a_ re2a))
8901 re4 (concat pre (if pre re4_ re4))
8902 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8903 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8904 re5 "\\)"
8906 (cond
8907 ((eq type 'org-occur) (org-occur reall))
8908 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8909 (t (goto-char (point-min))
8910 (setq type 'fuzzy)
8911 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8912 (org-search-not-self 1 re1 nil t)
8913 (org-search-not-self 1 re2 nil t)
8914 (org-search-not-self 1 re2a nil t)
8915 (org-search-not-self 1 re3 nil t)
8916 (org-search-not-self 1 re4 nil t)
8917 (org-search-not-self 1 re5 nil t)
8919 (goto-char (match-beginning 1))
8920 (goto-char pos)
8921 (error "No match")))))
8923 ;; Normal string-search
8924 (goto-char (point-min))
8925 (if (search-forward s nil t)
8926 (goto-char (match-beginning 0))
8927 (error "No match"))))
8928 (and (org-mode-p) (org-show-context 'link-search))
8929 type))
8931 (defun org-search-not-self (group &rest args)
8932 "Execute `re-search-forward', but only accept matches that do not
8933 enclose the position of `org-open-link-marker'."
8934 (let ((m org-open-link-marker))
8935 (catch 'exit
8936 (while (apply 're-search-forward args)
8937 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8938 (goto-char (match-end group))
8939 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8940 (> (match-beginning 0) (marker-position m))
8941 (< (match-end 0) (marker-position m)))
8942 (save-match-data
8943 (or (not (org-in-regexp
8944 org-bracket-link-analytic-regexp 1))
8945 (not (match-end 4)) ; no description
8946 (and (<= (match-beginning 4) (point))
8947 (>= (match-end 4) (point))))))
8948 (throw 'exit (point))))))))
8950 (defun org-get-buffer-for-internal-link (buffer)
8951 "Return a buffer to be used for displaying the link target of internal links."
8952 (cond
8953 ((not org-display-internal-link-with-indirect-buffer)
8954 buffer)
8955 ((string-match "(Clone)$" (buffer-name buffer))
8956 (message "Buffer is already a clone, not making another one")
8957 ;; we also do not modify visibility in this case
8958 buffer)
8959 (t ; make a new indirect buffer for displaying the link
8960 (let* ((bn (buffer-name buffer))
8961 (ibn (concat bn "(Clone)"))
8962 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8963 (with-current-buffer ib (org-overview))
8964 ib))))
8966 (defun org-do-occur (regexp &optional cleanup)
8967 "Call the Emacs command `occur'.
8968 If CLEANUP is non-nil, remove the printout of the regular expression
8969 in the *Occur* buffer. This is useful if the regex is long and not useful
8970 to read."
8971 (occur regexp)
8972 (when cleanup
8973 (let ((cwin (selected-window)) win beg end)
8974 (when (setq win (get-buffer-window "*Occur*"))
8975 (select-window win))
8976 (goto-char (point-min))
8977 (when (re-search-forward "match[a-z]+" nil t)
8978 (setq beg (match-end 0))
8979 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8980 (setq end (1- (match-beginning 0)))))
8981 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8982 (goto-char (point-min))
8983 (select-window cwin))))
8985 ;;; The mark ring for links jumps
8987 (defvar org-mark-ring nil
8988 "Mark ring for positions before jumps in Org-mode.")
8989 (defvar org-mark-ring-last-goto nil
8990 "Last position in the mark ring used to go back.")
8991 ;; Fill and close the ring
8992 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8993 (loop for i from 1 to org-mark-ring-length do
8994 (push (make-marker) org-mark-ring))
8995 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8996 org-mark-ring)
8998 (defun org-mark-ring-push (&optional pos buffer)
8999 "Put the current position or POS into the mark ring and rotate it."
9000 (interactive)
9001 (setq pos (or pos (point)))
9002 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9003 (move-marker (car org-mark-ring)
9004 (or pos (point))
9005 (or buffer (current-buffer)))
9006 (message "%s"
9007 (substitute-command-keys
9008 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9010 (defun org-mark-ring-goto (&optional n)
9011 "Jump to the previous position in the mark ring.
9012 With prefix arg N, jump back that many stored positions. When
9013 called several times in succession, walk through the entire ring.
9014 Org-mode commands jumping to a different position in the current file,
9015 or to another Org-mode file, automatically push the old position
9016 onto the ring."
9017 (interactive "p")
9018 (let (p m)
9019 (if (eq last-command this-command)
9020 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9021 (setq p org-mark-ring))
9022 (setq org-mark-ring-last-goto p)
9023 (setq m (car p))
9024 (switch-to-buffer (marker-buffer m))
9025 (goto-char m)
9026 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9028 (defun org-remove-angle-brackets (s)
9029 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9030 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9032 (defun org-add-angle-brackets (s)
9033 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9034 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9036 (defun org-remove-double-quotes (s)
9037 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
9038 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
9041 ;;; Following specific links
9043 (defun org-follow-timestamp-link ()
9044 (cond
9045 ((org-at-date-range-p t)
9046 (let ((org-agenda-start-on-weekday)
9047 (t1 (match-string 1))
9048 (t2 (match-string 2)))
9049 (setq t1 (time-to-days (org-time-string-to-time t1))
9050 t2 (time-to-days (org-time-string-to-time t2)))
9051 (org-agenda-list nil t1 (1+ (- t2 t1)))))
9052 ((org-at-timestamp-p t)
9053 (org-agenda-list nil (time-to-days (org-time-string-to-time
9054 (substring (match-string 1) 0 10)))
9056 (t (error "This should not happen"))))
9059 ;;; Following file links
9060 (defvar org-wait nil)
9061 (defun org-open-file (path &optional in-emacs line search)
9062 "Open the file at PATH.
9063 First, this expands any special file name abbreviations. Then the
9064 configuration variable `org-file-apps' is checked if it contains an
9065 entry for this file type, and if yes, the corresponding command is launched.
9067 If no application is found, Emacs simply visits the file.
9069 With optional prefix argument IN-EMACS, Emacs will visit the file.
9070 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
9071 and to use an external application to visit the file.
9073 Optional LINE specifies a line to go to, optional SEARCH a string to
9074 search for. If LINE or SEARCH is given, but IN-EMACS is nil, it will
9075 be assumed that org-open-file was called to open a file: link, and the
9076 original link to match against org-file-apps will be reconstructed
9077 from PATH and whichever of LINE or SEARCH is given.
9079 If the file does not exist, an error is thrown."
9080 (let* ((file (if (equal path "")
9081 buffer-file-name
9082 (substitute-in-file-name (expand-file-name path))))
9083 (apps (append org-file-apps (org-default-apps)))
9084 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9085 (dirp (if remp nil (file-directory-p file)))
9086 (file (if (and dirp org-open-directory-means-index-dot-org)
9087 (concat (file-name-as-directory file) "index.org")
9088 file))
9089 (a-m-a-p (assq 'auto-mode apps))
9090 (dfile (downcase file))
9091 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
9092 (link (cond ((and (eq line nil)
9093 (eq search nil))
9094 file)
9095 (line
9096 (concat file "::" (number-to-string line)))
9097 (search
9098 (concat file "::" search))))
9099 (dlink (downcase link))
9100 (old-buffer (current-buffer))
9101 (old-pos (point))
9102 (old-mode major-mode)
9103 ext cmd link-match-data)
9104 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9105 (setq ext (match-string 1 dfile))
9106 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9107 (setq ext (match-string 1 dfile))))
9108 (cond
9109 ((member in-emacs '((16) system))
9110 (setq cmd (cdr (assoc 'system apps))))
9111 (in-emacs (setq cmd 'emacs))
9113 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9114 (and dirp (cdr (assoc 'directory apps)))
9115 ;; if we find a match in org-file-apps, store the match
9116 ;; data for later
9117 (let ((match (assoc-default dlink (org-apps-regexp-alist
9118 apps a-m-a-p)
9119 'string-match)))
9120 (if match
9121 (progn (setq link-match-data (match-data))
9122 match)
9123 nil))
9124 (cdr (assoc ext apps))
9125 (cdr (assoc t apps))))))
9126 (when (eq cmd 'system)
9127 (setq cmd (cdr (assoc 'system apps))))
9128 (when (eq cmd 'default)
9129 (setq cmd (cdr (assoc t apps))))
9130 (when (eq cmd 'mailcap)
9131 (require 'mailcap)
9132 (mailcap-parse-mailcaps)
9133 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9134 (command (mailcap-mime-info mime-type)))
9135 (if (stringp command)
9136 (setq cmd command)
9137 (setq cmd 'emacs))))
9138 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
9139 (not (file-exists-p file))
9140 (not org-open-non-existing-files))
9141 (error "No such file: %s" file))
9142 (cond
9143 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9144 ;; Remove quotes around the file name - we'll use shell-quote-argument.
9145 (while (string-match "['\"]%s['\"]" cmd)
9146 (setq cmd (replace-match "%s" t t cmd)))
9147 (while (string-match "%s" cmd)
9148 (setq cmd (replace-match
9149 (save-match-data
9150 (shell-quote-argument
9151 (convert-standard-filename file)))
9152 t t cmd)))
9153 ;; Replace "%1", "%2" etc. in command with group matches from regex
9154 (save-match-data
9155 (let ((match-index 1)
9156 (number-of-groups (- (/ (length link-match-data) 2) 1)))
9157 (set-match-data link-match-data)
9158 (while (<= match-index number-of-groups)
9159 (let ((regex (concat "%" (number-to-string match-index)))
9160 (replace-with (match-string match-index dlink)))
9161 (while (string-match regex cmd)
9162 (setq cmd (replace-match replace-with t t cmd))))
9163 (setq match-index (+ match-index 1)))))
9165 (save-window-excursion
9166 (start-process-shell-command cmd nil cmd)
9167 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
9169 ((or (stringp cmd)
9170 (eq cmd 'emacs))
9171 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9172 (widen)
9173 (if line (org-goto-line line)
9174 (if search (org-link-search search))))
9175 ((consp cmd)
9176 (let ((file (convert-standard-filename file)))
9177 (save-match-data
9178 (set-match-data link-match-data)
9179 (eval cmd))))
9180 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9181 (and (org-mode-p) (eq old-mode 'org-mode)
9182 (or (not (equal old-buffer (current-buffer)))
9183 (not (equal old-pos (point))))
9184 (org-mark-ring-push old-pos old-buffer))))
9186 (defun org-default-apps ()
9187 "Return the default applications for this operating system."
9188 (cond
9189 ((eq system-type 'darwin)
9190 org-file-apps-defaults-macosx)
9191 ((eq system-type 'windows-nt)
9192 org-file-apps-defaults-windowsnt)
9193 (t org-file-apps-defaults-gnu)))
9195 (defun org-apps-regexp-alist (list &optional add-auto-mode)
9196 "Convert extensions to regular expressions in the cars of LIST.
9197 Also, weed out any non-string entries, because the return value is used
9198 only for regexp matching.
9199 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
9200 point to the symbol `emacs', indicating that the file should
9201 be opened in Emacs."
9202 (append
9203 (delq nil
9204 (mapcar (lambda (x)
9205 (if (not (stringp (car x)))
9207 (if (string-match "\\W" (car x))
9209 (cons (concat "\\." (car x) "\\(::.*\\)?\\'")
9210 (cdr x)))))
9211 list))
9212 (if add-auto-mode
9213 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
9215 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
9216 (defun org-file-remote-p (file)
9217 "Test whether FILE specifies a location on a remote system.
9218 Return non-nil if the location is indeed remote.
9220 For example, the filename \"/user@host:/foo\" specifies a location
9221 on the system \"/user@host:\"."
9222 (cond ((fboundp 'file-remote-p)
9223 (file-remote-p file))
9224 ((fboundp 'tramp-handle-file-remote-p)
9225 (tramp-handle-file-remote-p file))
9226 ((and (boundp 'ange-ftp-name-format)
9227 (string-match (car ange-ftp-name-format) file))
9229 (t nil)))
9232 ;;;; Refiling
9234 (defun org-get-org-file ()
9235 "Read a filename, with default directory `org-directory'."
9236 (let ((default (or org-default-notes-file remember-data-file)))
9237 (read-file-name (format "File name [%s]: " default)
9238 (file-name-as-directory org-directory)
9239 default)))
9241 (defun org-notes-order-reversed-p ()
9242 "Check if the current file should receive notes in reversed order."
9243 (cond
9244 ((not org-reverse-note-order) nil)
9245 ((eq t org-reverse-note-order) t)
9246 ((not (listp org-reverse-note-order)) nil)
9247 (t (catch 'exit
9248 (let ((all org-reverse-note-order)
9249 entry)
9250 (while (setq entry (pop all))
9251 (if (string-match (car entry) buffer-file-name)
9252 (throw 'exit (cdr entry))))
9253 nil)))))
9255 (defvar org-refile-target-table nil
9256 "The list of refile targets, created by `org-refile'.")
9258 (defvar org-agenda-new-buffers nil
9259 "Buffers created to visit agenda files.")
9261 (defun org-get-refile-targets (&optional default-buffer)
9262 "Produce a table with refile targets."
9263 (let ((case-fold-search nil)
9264 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
9265 (entries (or org-refile-targets '((nil . (:level . 1)))))
9266 targets txt re files f desc descre fast-path-p level pos0)
9267 (message "Getting targets...")
9268 (with-current-buffer (or default-buffer (current-buffer))
9269 (while (setq entry (pop entries))
9270 (setq files (car entry) desc (cdr entry))
9271 (setq fast-path-p nil)
9272 (cond
9273 ((null files) (setq files (list (current-buffer))))
9274 ((eq files 'org-agenda-files)
9275 (setq files (org-agenda-files 'unrestricted)))
9276 ((and (symbolp files) (fboundp files))
9277 (setq files (funcall files)))
9278 ((and (symbolp files) (boundp files))
9279 (setq files (symbol-value files))))
9280 (if (stringp files) (setq files (list files)))
9281 (cond
9282 ((eq (car desc) :tag)
9283 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
9284 ((eq (car desc) :todo)
9285 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
9286 ((eq (car desc) :regexp)
9287 (setq descre (cdr desc)))
9288 ((eq (car desc) :level)
9289 (setq descre (concat "^\\*\\{" (number-to-string
9290 (if org-odd-levels-only
9291 (1- (* 2 (cdr desc)))
9292 (cdr desc)))
9293 "\\}[ \t]")))
9294 ((eq (car desc) :maxlevel)
9295 (setq fast-path-p t)
9296 (setq descre (concat "^\\*\\{1," (number-to-string
9297 (if org-odd-levels-only
9298 (1- (* 2 (cdr desc)))
9299 (cdr desc)))
9300 "\\}[ \t]")))
9301 (t (error "Bad refiling target description %s" desc)))
9302 (while (setq f (pop files))
9303 (with-current-buffer
9304 (if (bufferp f) f (org-get-agenda-file-buffer f))
9305 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
9306 (setq f (and f (expand-file-name f)))
9307 (if (eq org-refile-use-outline-path 'file)
9308 (push (list (file-name-nondirectory f) f nil nil) targets))
9309 (save-excursion
9310 (save-restriction
9311 (widen)
9312 (goto-char (point-min))
9313 (while (re-search-forward descre nil t)
9314 (goto-char (setq pos0 (point-at-bol)))
9315 (catch 'next
9316 (when org-refile-target-verify-function
9317 (save-match-data
9318 (or (funcall org-refile-target-verify-function)
9319 (throw 'next t))))
9320 (when (looking-at org-complex-heading-regexp)
9321 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
9322 txt (org-link-display-format (match-string 4))
9323 re (concat "^" (regexp-quote
9324 (buffer-substring (match-beginning 1)
9325 (match-end 4)))))
9326 (if (match-end 5) (setq re (concat re "[ \t]+"
9327 (regexp-quote
9328 (match-string 5)))))
9329 (setq re (concat re "[ \t]*$"))
9330 (when org-refile-use-outline-path
9331 (setq txt (mapconcat 'org-protect-slash
9332 (append
9333 (if (eq org-refile-use-outline-path 'file)
9334 (list (file-name-nondirectory
9335 (buffer-file-name (buffer-base-buffer))))
9336 (if (eq org-refile-use-outline-path 'full-file-path)
9337 (list (buffer-file-name (buffer-base-buffer)))))
9338 (org-get-outline-path fast-path-p level txt)
9339 (list txt))
9340 "/")))
9341 (push (list txt f re (point)) targets)))
9342 (when (= (point) pos0)
9343 ;; verification function has not moved point
9344 (goto-char (point-at-eol))))))))))
9345 (message "Getting targets...done")
9346 (nreverse targets)))
9348 (defun org-protect-slash (s)
9349 (while (string-match "/" s)
9350 (setq s (replace-match "\\" t t s)))
9353 (defvar org-olpa (make-vector 20 nil))
9355 (defun org-get-outline-path (&optional fastp level heading)
9356 "Return the outline path to the current entry, as a list.
9357 The parameters FASTP, LEVEL, and HEADING are for use be a scanner
9358 routine which makes outline path derivations for an entire file,
9359 avoiding backtracing."
9360 (if fastp
9361 (progn
9362 (if (> level 19)
9363 (error "Outline path failure, more than 19 levels."))
9364 (loop for i from level upto 19 do
9365 (aset org-olpa i nil))
9366 (prog1
9367 (delq nil (append org-olpa nil))
9368 (aset org-olpa level heading)))
9369 (let (rtn case-fold-search)
9370 (save-excursion
9371 (save-restriction
9372 (widen)
9373 (while (org-up-heading-safe)
9374 (when (looking-at org-complex-heading-regexp)
9375 (push (org-match-string-no-properties 4) rtn)))
9376 rtn)))))
9378 (defun org-format-outline-path (path &optional width prefix)
9379 "Format the outlie path PATH for display.
9380 Width is the maximum number of characters that is available.
9381 Prefix is a prefix to be included in the returned string,
9382 such as the file name."
9383 (setq width (or width 79))
9384 (if prefix (setq width (- width (length prefix))))
9385 (if (not path)
9386 (or prefix "")
9387 (let* ((nsteps (length path))
9388 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
9389 (maxwidth (if (<= total-width width)
9390 10000 ;; everything fits
9391 ;; we need to shorten the level headings
9392 (/ (- width nsteps) nsteps)))
9393 (org-odd-levels-only nil)
9394 (n 0)
9395 (total (1+ (length prefix))))
9396 (setq maxwidth (max maxwidth 10))
9397 (concat prefix
9398 (mapconcat
9399 (lambda (h)
9400 (setq n (1+ n))
9401 (if (and (= n nsteps) (< maxwidth 10000))
9402 (setq maxwidth (- total-width total)))
9403 (if (< (length h) maxwidth)
9404 (progn (setq total (+ total (length h) 1)) h)
9405 (setq h (substring h 0 (- maxwidth 2))
9406 total (+ total maxwidth 1))
9407 (if (string-match "[ \t]+\\'" h)
9408 (setq h (substring h 0 (match-beginning 0))))
9409 (setq h (concat h "..")))
9410 (org-add-props h nil 'face
9411 (nth (% (1- n) org-n-level-faces)
9412 org-level-faces))
9414 path "/")))))
9416 (defun org-display-outline-path (&optional file current)
9417 "Display the current outline path in the echo area."
9418 (interactive "P")
9419 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
9420 (case-fold-search nil)
9421 (path (and (org-mode-p) (org-get-outline-path))))
9422 (if current (setq path (append path
9423 (save-excursion
9424 (org-back-to-heading t)
9425 (if (looking-at org-complex-heading-regexp)
9426 (list (match-string 4)))))))
9427 (message "%s"
9428 (org-format-outline-path
9429 path
9430 (1- (frame-width))
9431 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
9433 (defvar org-refile-history nil
9434 "History for refiling operations.")
9436 (defvar org-after-refile-insert-hook nil
9437 "Hook run after `org-refile' has inserted its stuff at the new location.
9438 Note that this is still *before* the stuff will be removed from
9439 the *old* location.")
9441 (defun org-refile (&optional goto default-buffer rfloc)
9442 "Move the entry at point to another heading.
9443 The list of target headings is compiled using the information in
9444 `org-refile-targets', which see. This list is created before each use
9445 and will therefore always be up-to-date.
9447 At the target location, the entry is filed as a subitem of the target heading.
9448 Depending on `org-reverse-note-order', the new subitem will either be the
9449 first or the last subitem.
9451 If there is an active region, all entries in that region will be moved.
9452 However, the region must fulfil the requirement that the first heading
9453 is the first one sets the top-level of the moved text - at most siblings
9454 below it are allowed.
9456 With prefix arg GOTO, the command will only visit the target location,
9457 not actually move anything.
9458 With a double prefix `C-u C-u', go to the location where the last refiling
9459 operation has put the subtree.
9460 With a prefix argument of `2', refile to the running clock.
9462 RFLOC can be a refile location obtained in a different way.
9464 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
9465 (interactive "P")
9466 (let* ((cbuf (current-buffer))
9467 (regionp (org-region-active-p))
9468 (region-start (and regionp (region-beginning)))
9469 (region-end (and regionp (region-end)))
9470 (region-length (and regionp (- region-end region-start)))
9471 (filename (buffer-file-name (buffer-base-buffer cbuf)))
9472 pos it nbuf file re level reversed)
9473 (setq last-command nil)
9474 (when regionp
9475 (goto-char region-start)
9476 (or (bolp) (goto-char (point-at-bol)))
9477 (setq region-start (point))
9478 (unless (org-kill-is-subtree-p
9479 (buffer-substring region-start region-end))
9480 (error "The region is not a (sequence of) subtree(s)")))
9481 (if (equal goto '(16))
9482 (org-refile-goto-last-stored)
9483 (when (or
9484 (and (equal goto 2)
9485 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
9486 (prog1
9487 (setq it (list (or org-clock-heading "running clock")
9488 (buffer-file-name
9489 (marker-buffer org-clock-hd-marker))
9491 (marker-position org-clock-hd-marker)))
9492 (setq goto nil)))
9493 (setq it (or rfloc
9494 (save-excursion
9495 (org-refile-get-location
9496 (if goto "Goto: " "Refile to: ") default-buffer
9497 org-refile-allow-creating-parent-nodes)))))
9498 (setq file (nth 1 it)
9499 re (nth 2 it)
9500 pos (nth 3 it))
9501 (if (and (not goto)
9503 (equal (buffer-file-name) file)
9504 (if regionp
9505 (and (>= pos region-start)
9506 (<= pos region-end))
9507 (and (>= pos (point))
9508 (< pos (save-excursion
9509 (org-end-of-subtree t t))))))
9510 (error "Cannot refile to position inside the tree or region"))
9512 (setq nbuf (or (find-buffer-visiting file)
9513 (find-file-noselect file)))
9514 (if goto
9515 (progn
9516 (switch-to-buffer nbuf)
9517 (goto-char pos)
9518 (org-show-context 'org-goto))
9519 (if regionp
9520 (progn
9521 (org-kill-new (buffer-substring region-start region-end))
9522 (org-save-markers-in-region region-start region-end))
9523 (org-copy-subtree 1 nil t))
9524 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
9525 (find-file-noselect file)))
9526 (setq reversed (org-notes-order-reversed-p))
9527 (save-excursion
9528 (save-restriction
9529 (widen)
9530 (if pos
9531 (progn
9532 (goto-char pos)
9533 (looking-at outline-regexp)
9534 (setq level (org-get-valid-level (funcall outline-level) 1))
9535 (goto-char
9536 (if reversed
9537 (or (outline-next-heading) (point-max))
9538 (or (save-excursion (org-get-next-sibling))
9539 (org-end-of-subtree t t)
9540 (point-max)))))
9541 (setq level 1)
9542 (if (not reversed)
9543 (goto-char (point-max))
9544 (goto-char (point-min))
9545 (or (outline-next-heading) (goto-char (point-max)))))
9546 (if (not (bolp)) (newline))
9547 (org-paste-subtree level)
9548 (when org-log-refile
9549 (org-add-log-setup 'refile nil nil 'findpos
9550 org-log-refile)
9551 (unless (eq org-log-refile 'note)
9552 (save-excursion (org-add-log-note))))
9553 (and org-auto-align-tags (org-set-tags nil t))
9554 (bookmark-set "org-refile-last-stored")
9555 (if (fboundp 'deactivate-mark) (deactivate-mark))
9556 (run-hooks 'org-after-refile-insert-hook))))
9557 (if regionp
9558 (delete-region (point) (+ (point) region-length))
9559 (org-cut-subtree))
9560 (when (featurep 'org-inlinetask)
9561 (org-inlinetask-remove-END-maybe))
9562 (setq org-markers-to-move nil)
9563 (message "Refiled to \"%s\"" (car it))))))
9564 (org-reveal))
9566 (defun org-refile-goto-last-stored ()
9567 "Go to the location where the last refile was stored."
9568 (interactive)
9569 (bookmark-jump "org-refile-last-stored")
9570 (message "This is the location of the last refile"))
9572 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
9573 "Prompt the user for a refile location, using PROMPT."
9574 (let ((org-refile-targets org-refile-targets)
9575 (org-refile-use-outline-path org-refile-use-outline-path))
9576 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
9577 (unless org-refile-target-table
9578 (error "No refile targets"))
9579 (let* ((cbuf (current-buffer))
9580 (partial-completion-mode nil)
9581 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
9582 (cfunc (if (and org-refile-use-outline-path
9583 org-outline-path-complete-in-steps)
9584 'org-olpath-completing-read
9585 'org-icompleting-read))
9586 (extra (if org-refile-use-outline-path "/" ""))
9587 (filename (and cfn (expand-file-name cfn)))
9588 (tbl (mapcar
9589 (lambda (x)
9590 (if (and (not (member org-refile-use-outline-path
9591 '(file full-file-path)))
9592 (not (equal filename (nth 1 x))))
9593 (cons (concat (car x) extra " ("
9594 (file-name-nondirectory (nth 1 x)) ")")
9595 (cdr x))
9596 (cons (concat (car x) extra) (cdr x))))
9597 org-refile-target-table))
9598 (completion-ignore-case t)
9599 pa answ parent-target child parent old-hist)
9600 (setq old-hist org-refile-history)
9601 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
9602 nil 'org-refile-history))
9603 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
9604 (if pa
9605 (progn
9606 (when (or (not org-refile-history)
9607 (not (eq old-hist org-refile-history))
9608 (not (equal (car pa) (car org-refile-history))))
9609 (setq org-refile-history
9610 (cons (car pa) (if (assoc (car org-refile-history) tbl)
9611 org-refile-history
9612 (cdr org-refile-history))))
9613 (if (equal (car org-refile-history) (nth 1 org-refile-history))
9614 (pop org-refile-history)))
9616 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
9617 (progn
9618 (setq parent (match-string 1 answ)
9619 child (match-string 2 answ))
9620 (setq parent-target (or (assoc parent tbl)
9621 (assoc (concat parent "/") tbl)))
9622 (when (and parent-target
9623 (or (eq new-nodes t)
9624 (and (eq new-nodes 'confirm)
9625 (y-or-n-p (format "Create new node \"%s\"? "
9626 child)))))
9627 (org-refile-new-child parent-target child)))
9628 (error "Invalid target location")))))
9630 (defun org-refile-new-child (parent-target child)
9631 "Use refile target PARENT-TARGET to add new CHILD below it."
9632 (unless parent-target
9633 (error "Cannot find parent for new node"))
9634 (let ((file (nth 1 parent-target))
9635 (pos (nth 3 parent-target))
9636 level)
9637 (with-current-buffer (or (find-buffer-visiting file)
9638 (find-file-noselect file))
9639 (save-excursion
9640 (save-restriction
9641 (widen)
9642 (if pos
9643 (goto-char pos)
9644 (goto-char (point-max))
9645 (if (not (bolp)) (newline)))
9646 (when (looking-at outline-regexp)
9647 (setq level (funcall outline-level))
9648 (org-end-of-subtree t t))
9649 (org-back-over-empty-lines)
9650 (insert "\n" (make-string
9651 (if pos (org-get-valid-level level 1) 1) ?*)
9652 " " child "\n")
9653 (beginning-of-line 0)
9654 (list (concat (car parent-target) "/" child) file "" (point)))))))
9656 (defun org-olpath-completing-read (prompt collection &rest args)
9657 "Read an outline path like a file name."
9658 (let ((thetable collection)
9659 (org-completion-use-ido nil) ; does not work with ido.
9660 (org-completion-use-iswitchb nil)) ; or iswitchb
9661 (apply
9662 'org-icompleting-read prompt
9663 (lambda (string predicate &optional flag)
9664 (let (rtn r f (l (length string)))
9665 (cond
9666 ((eq flag nil)
9667 ;; try completion
9668 (try-completion string thetable))
9669 ((eq flag t)
9670 ;; all-completions
9671 (setq rtn (all-completions string thetable predicate))
9672 (mapcar
9673 (lambda (x)
9674 (setq r (substring x l))
9675 (if (string-match " ([^)]*)$" x)
9676 (setq f (match-string 0 x))
9677 (setq f ""))
9678 (if (string-match "/" r)
9679 (concat string (substring r 0 (match-end 0)) f)
9681 rtn))
9682 ((eq flag 'lambda)
9683 ;; exact match?
9684 (assoc string thetable)))
9686 args)))
9688 ;;;; Dynamic blocks
9690 (defun org-find-dblock (name)
9691 "Find the first dynamic block with name NAME in the buffer.
9692 If not found, stay at current position and return nil."
9693 (let (pos)
9694 (save-excursion
9695 (goto-char (point-min))
9696 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
9697 nil t)
9698 (match-beginning 0))))
9699 (if pos (goto-char pos))
9700 pos))
9702 (defconst org-dblock-start-re
9703 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
9704 "Matches the start line of a dynamic block, with parameters.")
9706 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
9707 "Matches the end of a dynamic block.")
9709 (defun org-create-dblock (plist)
9710 "Create a dynamic block section, with parameters taken from PLIST.
9711 PLIST must contain a :name entry which is used as name of the block."
9712 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
9713 (end-of-line 1)
9714 (newline))
9715 (let ((col (current-column))
9716 (name (plist-get plist :name)))
9717 (insert "#+BEGIN: " name)
9718 (while plist
9719 (if (eq (car plist) :name)
9720 (setq plist (cddr plist))
9721 (insert " " (prin1-to-string (pop plist)))))
9722 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
9723 (beginning-of-line -2)))
9725 (defun org-prepare-dblock ()
9726 "Prepare dynamic block for refresh.
9727 This empties the block, puts the cursor at the insert position and returns
9728 the property list including an extra property :name with the block name."
9729 (unless (looking-at org-dblock-start-re)
9730 (error "Not at a dynamic block"))
9731 (let* ((begdel (1+ (match-end 0)))
9732 (name (org-no-properties (match-string 1)))
9733 (params (append (list :name name)
9734 (read (concat "(" (match-string 3) ")")))))
9735 (save-excursion
9736 (beginning-of-line 1)
9737 (skip-chars-forward " \t")
9738 (setq params (plist-put params :indentation-column (current-column))))
9739 (unless (re-search-forward org-dblock-end-re nil t)
9740 (error "Dynamic block not terminated"))
9741 (setq params
9742 (append params
9743 (list :content (buffer-substring
9744 begdel (match-beginning 0)))))
9745 (delete-region begdel (match-beginning 0))
9746 (goto-char begdel)
9747 (open-line 1)
9748 params))
9750 (defun org-map-dblocks (&optional command)
9751 "Apply COMMAND to all dynamic blocks in the current buffer.
9752 If COMMAND is not given, use `org-update-dblock'."
9753 (let ((cmd (or command 'org-update-dblock)))
9754 (save-excursion
9755 (goto-char (point-min))
9756 (while (re-search-forward org-dblock-start-re nil t)
9757 (goto-char (match-beginning 0))
9758 (save-excursion
9759 (condition-case nil
9760 (funcall cmd)
9761 (error (message "Error during update of dynamic block"))))
9762 (unless (re-search-forward org-dblock-end-re nil t)
9763 (error "Dynamic block not terminated"))))))
9765 (defun org-dblock-update (&optional arg)
9766 "User command for updating dynamic blocks.
9767 Update the dynamic block at point. With prefix ARG, update all dynamic
9768 blocks in the buffer."
9769 (interactive "P")
9770 (if arg
9771 (org-update-all-dblocks)
9772 (or (looking-at org-dblock-start-re)
9773 (org-beginning-of-dblock))
9774 (org-update-dblock)))
9776 (defun org-update-dblock ()
9777 "Update the dynamic block at point
9778 This means to empty the block, parse for parameters and then call
9779 the correct writing function."
9780 (save-window-excursion
9781 (let* ((pos (point))
9782 (line (org-current-line))
9783 (params (org-prepare-dblock))
9784 (name (plist-get params :name))
9785 (indent (plist-get params :indentation-column))
9786 (cmd (intern (concat "org-dblock-write:" name))))
9787 (message "Updating dynamic block `%s' at line %d..." name line)
9788 (funcall cmd params)
9789 (message "Updating dynamic block `%s' at line %d...done" name line)
9790 (goto-char pos)
9791 (when (and indent (> indent 0))
9792 (setq indent (make-string indent ?\ ))
9793 (save-excursion
9794 (org-beginning-of-dblock)
9795 (forward-line 1)
9796 (while (not (looking-at org-dblock-end-re))
9797 (insert indent)
9798 (beginning-of-line 2))
9799 (when (looking-at org-dblock-end-re)
9800 (and (looking-at "[ \t]+")
9801 (replace-match ""))
9802 (insert indent)))))))
9804 (defun org-beginning-of-dblock ()
9805 "Find the beginning of the dynamic block at point.
9806 Error if there is no such block at point."
9807 (let ((pos (point))
9808 beg)
9809 (end-of-line 1)
9810 (if (and (re-search-backward org-dblock-start-re nil t)
9811 (setq beg (match-beginning 0))
9812 (re-search-forward org-dblock-end-re nil t)
9813 (> (match-end 0) pos))
9814 (goto-char beg)
9815 (goto-char pos)
9816 (error "Not in a dynamic block"))))
9818 (defun org-update-all-dblocks ()
9819 "Update all dynamic blocks in the buffer.
9820 This function can be used in a hook."
9821 (when (org-mode-p)
9822 (org-map-dblocks 'org-update-dblock)))
9825 ;;;; Completion
9827 (defconst org-additional-option-like-keywords
9828 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
9829 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
9830 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
9831 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX"
9832 "BEGIN:" "END:"
9833 "ORGTBL" "TBLFM:" "TBLNAME:"
9834 "BEGIN_EXAMPLE" "END_EXAMPLE"
9835 "BEGIN_QUOTE" "END_QUOTE"
9836 "BEGIN_VERSE" "END_VERSE"
9837 "BEGIN_CENTER" "END_CENTER"
9838 "BEGIN_SRC" "END_SRC"
9839 "CATEGORY" "COLUMNS"
9840 "CAPTION" "LABEL"
9841 "SETUPFILE"
9842 "BIND"
9843 "MACRO"))
9845 (defcustom org-structure-template-alist
9847 ("s" "#+begin_src ?\n\n#+end_src"
9848 "<src lang=\"?\">\n\n</src>")
9849 ("e" "#+begin_example\n?\n#+end_example"
9850 "<example>\n?\n</example>")
9851 ("q" "#+begin_quote\n?\n#+end_quote"
9852 "<quote>\n?\n</quote>")
9853 ("v" "#+begin_verse\n?\n#+end_verse"
9854 "<verse>\n?\n/verse>")
9855 ("c" "#+begin_center\n?\n#+end_center"
9856 "<center>\n?\n/center>")
9857 ("l" "#+begin_latex\n?\n#+end_latex"
9858 "<literal style=\"latex\">\n?\n</literal>")
9859 ("L" "#+latex: "
9860 "<literal style=\"latex\">?</literal>")
9861 ("h" "#+begin_html\n?\n#+end_html"
9862 "<literal style=\"html\">\n?\n</literal>")
9863 ("H" "#+html: "
9864 "<literal style=\"html\">?</literal>")
9865 ("a" "#+begin_ascii\n?\n#+end_ascii")
9866 ("A" "#+ascii: ")
9867 ("i" "#+include %file ?"
9868 "<include file=%file markup=\"?\">")
9870 "Structure completion elements.
9871 This is a list of abbreviation keys and values. The value gets inserted
9872 it you type @samp{.} followed by the key and then the completion key,
9873 usually `M-TAB'. %file will be replaced by a file name after prompting
9874 for the file using completion.
9875 There are two templates for each key, the first uses the original Org syntax,
9876 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
9877 the default when the /org-mtags.el/ module has been loaded. See also the
9878 variable `org-mtags-prefer-muse-templates'.
9879 This is an experimental feature, it is undecided if it is going to stay in."
9880 :group 'org-completion
9881 :type '(repeat
9882 (string :tag "Key")
9883 (string :tag "Template")
9884 (string :tag "Muse Template")))
9886 (defun org-try-structure-completion ()
9887 "Try to complete a structure template before point.
9888 This looks for strings like \"<e\" on an otherwise empty line and
9889 expands them."
9890 (let ((l (buffer-substring (point-at-bol) (point)))
9892 (when (and (looking-at "[ \t]*$")
9893 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9894 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9895 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9896 (match-beginning 1)) a)
9897 t)))
9899 (defun org-complete-expand-structure-template (start cell)
9900 "Expand a structure template."
9901 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
9902 (rpl (nth (if musep 2 1) cell))
9903 (ind ""))
9904 (delete-region start (point))
9905 (when (string-match "\\`#\\+" rpl)
9906 (cond
9907 ((bolp))
9908 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
9909 (setq ind (buffer-substring (point-at-bol) (point))))
9910 (t (newline))))
9911 (setq start (point))
9912 (if (string-match "%file" rpl)
9913 (setq rpl (replace-match
9914 (concat
9915 "\""
9916 (save-match-data
9917 (abbreviate-file-name (read-file-name "Include file: ")))
9918 "\"")
9919 t t rpl)))
9920 (setq rpl (mapconcat 'identity (split-string rpl "\n")
9921 (concat "\n" ind)))
9922 (insert rpl)
9923 (if (re-search-backward "\\?" start t) (delete-char 1))))
9926 (defun org-complete (&optional arg)
9927 "Perform completion on word at point.
9928 At the beginning of a headline, this completes TODO keywords as given in
9929 `org-todo-keywords'.
9930 If the current word is preceded by a backslash, completes the TeX symbols
9931 that are supported for HTML support.
9932 If the current word is preceded by \"#+\", completes special words for
9933 setting file options.
9934 In the line after \"#+STARTUP:, complete valid keywords.\"
9935 At all other locations, this simply calls the value of
9936 `org-completion-fallback-command'."
9937 (interactive "P")
9938 (org-without-partial-completion
9939 (catch 'exit
9940 (let* ((a nil)
9941 (end (point))
9942 (beg1 (save-excursion
9943 (skip-chars-backward (org-re "[:alnum:]_@"))
9944 (point)))
9945 (beg (save-excursion
9946 (skip-chars-backward "a-zA-Z0-9_:$")
9947 (point)))
9948 (confirm (lambda (x) (stringp (car x))))
9949 (searchhead (equal (char-before beg) ?*))
9950 (struct
9951 (when (and (member (char-before beg1) '(?. ?<))
9952 (setq a (assoc (buffer-substring beg1 (point))
9953 org-structure-template-alist)))
9954 (org-complete-expand-structure-template (1- beg1) a)
9955 (throw 'exit t)))
9956 (tag (and (equal (char-before beg1) ?:)
9957 (equal (char-after (point-at-bol)) ?*)))
9958 (prop (and (equal (char-before beg1) ?:)
9959 (not (equal (char-after (point-at-bol)) ?*))))
9960 (texp (equal (char-before beg) ?\\))
9961 (link (equal (char-before beg) ?\[))
9962 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9963 beg)
9964 "#+"))
9965 (startup (string-match "^#\\+STARTUP:.*"
9966 (buffer-substring (point-at-bol) (point))))
9967 (completion-ignore-case opt)
9968 (type nil)
9969 (tbl nil)
9970 (table (cond
9971 (opt
9972 (setq type :opt)
9973 (require 'org-exp)
9974 (append
9975 (delq nil
9976 (mapcar
9977 (lambda (x)
9978 (if (string-match
9979 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9980 (cons (match-string 2 x)
9981 (match-string 1 x))))
9982 (org-split-string (org-get-current-options) "\n")))
9983 (mapcar 'list org-additional-option-like-keywords)))
9984 (startup
9985 (setq type :startup)
9986 org-startup-options)
9987 (link (append org-link-abbrev-alist-local
9988 org-link-abbrev-alist))
9989 (texp
9990 (setq type :tex)
9991 org-html-entities)
9992 ((string-match "\\`\\*+[ \t]+\\'"
9993 (buffer-substring (point-at-bol) beg))
9994 (setq type :todo)
9995 (mapcar 'list org-todo-keywords-1))
9996 (searchhead
9997 (setq type :searchhead)
9998 (save-excursion
9999 (goto-char (point-min))
10000 (while (re-search-forward org-todo-line-regexp nil t)
10001 (push (list
10002 (org-make-org-heading-search-string
10003 (match-string 3) t))
10004 tbl)))
10005 tbl)
10006 (tag (setq type :tag beg beg1)
10007 (or org-tag-alist (org-get-buffer-tags)))
10008 (prop (setq type :prop beg beg1)
10009 (mapcar 'list (org-buffer-property-keys nil t t)))
10010 (t (progn
10011 (call-interactively org-completion-fallback-command)
10012 (throw 'exit nil)))))
10013 (pattern (buffer-substring-no-properties beg end))
10014 (completion (try-completion pattern table confirm)))
10015 (cond ((eq completion t)
10016 (if (not (assoc (upcase pattern) table))
10017 (message "Already complete")
10018 (if (and (equal type :opt)
10019 (not (member (car (assoc (upcase pattern) table))
10020 org-additional-option-like-keywords)))
10021 (insert (substring (cdr (assoc (upcase pattern) table))
10022 (length pattern)))
10023 (if (memq type '(:tag :prop)) (insert ":")))))
10024 ((null completion)
10025 (message "Can't find completion for \"%s\"" pattern)
10026 (ding))
10027 ((not (string= pattern completion))
10028 (delete-region beg end)
10029 (if (string-match " +$" completion)
10030 (setq completion (replace-match "" t t completion)))
10031 (insert completion)
10032 (if (get-buffer-window "*Completions*")
10033 (delete-window (get-buffer-window "*Completions*")))
10034 (if (assoc completion table)
10035 (if (eq type :todo) (insert " ")
10036 (if (memq type '(:tag :prop)) (insert ":"))))
10037 (if (and (equal type :opt) (assoc completion table))
10038 (message "%s" (substitute-command-keys
10039 "Press \\[org-complete] again to insert example settings"))))
10041 (message "Making completion list...")
10042 (let ((list (sort (all-completions pattern table confirm)
10043 'string<)))
10044 (with-output-to-temp-buffer "*Completions*"
10045 (condition-case nil
10046 ;; Protection needed for XEmacs and emacs 21
10047 (display-completion-list list pattern)
10048 (error (display-completion-list list)))))
10049 (message "Making completion list...%s" "done")))))))
10051 ;;;; TODO, DEADLINE, Comments
10053 (defun org-toggle-comment ()
10054 "Change the COMMENT state of an entry."
10055 (interactive)
10056 (save-excursion
10057 (org-back-to-heading)
10058 (let (case-fold-search)
10059 (if (looking-at (concat outline-regexp
10060 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
10061 (replace-match "" t t nil 1)
10062 (if (looking-at outline-regexp)
10063 (progn
10064 (goto-char (match-end 0))
10065 (insert org-comment-string " ")))))))
10067 (defvar org-last-todo-state-is-todo nil
10068 "This is non-nil when the last TODO state change led to a TODO state.
10069 If the last change removed the TODO tag or switched to DONE, then
10070 this is nil.")
10072 (defvar org-setting-tags nil) ; dynamically skipped
10074 (defun org-parse-local-options (string var)
10075 "Parse STRING for startup setting relevant for variable VAR."
10076 (let ((rtn (symbol-value var))
10077 e opts)
10078 (save-match-data
10079 (if (or (not string) (not (string-match "\\S-" string)))
10081 (setq opts (delq nil (mapcar (lambda (x)
10082 (setq e (assoc x org-startup-options))
10083 (if (eq (nth 1 e) var) e nil))
10084 (org-split-string string "[ \t]+"))))
10085 (if (not opts)
10087 (setq rtn nil)
10088 (while (setq e (pop opts))
10089 (if (not (nth 3 e))
10090 (setq rtn (nth 2 e))
10091 (if (not (listp rtn)) (setq rtn nil))
10092 (push (nth 2 e) rtn)))
10093 rtn)))))
10095 (defvar org-todo-setup-filter-hook nil
10096 "Hook for functions that pre-filter todo specs.
10098 Each function takes a todo spec and returns either `nil' or the spec
10099 transformed into canonical form." )
10101 (defvar org-todo-get-default-hook nil
10102 "Hook for functions that get a default item for todo.
10104 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
10105 `nil' or a string to be used for the todo mark." )
10107 (defvar org-agenda-headline-snapshot-before-repeat)
10109 (defun org-todo (&optional arg)
10110 "Change the TODO state of an item.
10111 The state of an item is given by a keyword at the start of the heading,
10112 like
10113 *** TODO Write paper
10114 *** DONE Call mom
10116 The different keywords are specified in the variable `org-todo-keywords'.
10117 By default the available states are \"TODO\" and \"DONE\".
10118 So for this example: when the item starts with TODO, it is changed to DONE.
10119 When it starts with DONE, the DONE is removed. And when neither TODO nor
10120 DONE are present, add TODO at the beginning of the heading.
10122 With C-u prefix arg, use completion to determine the new state.
10123 With numeric prefix arg, switch to that state.
10124 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
10125 With a triple C-u prefix, circumvent any state blocking.
10127 For calling through lisp, arg is also interpreted in the following way:
10128 'none -> empty state
10129 \"\"(empty string) -> switch to empty state
10130 'done -> switch to DONE
10131 'nextset -> switch to the next set of keywords
10132 'previousset -> switch to the previous set of keywords
10133 \"WAITING\" -> switch to the specified keyword, but only if it
10134 really is a member of `org-todo-keywords'."
10135 (interactive "P")
10136 (if (equal arg '(16)) (setq arg 'nextset))
10137 (let ((org-blocker-hook org-blocker-hook)
10138 (case-fold-search nil))
10139 (when (equal arg '(64))
10140 (setq arg nil org-blocker-hook nil))
10141 (when (and org-blocker-hook
10142 (or org-inhibit-blocking
10143 (org-entry-get nil "NOBLOCKING")))
10144 (setq org-blocker-hook nil))
10145 (save-excursion
10146 (catch 'exit
10147 (org-back-to-heading t)
10148 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
10149 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
10150 (looking-at " *"))
10151 (let* ((match-data (match-data))
10152 (startpos (point-at-bol))
10153 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
10154 (org-log-done org-log-done)
10155 (org-log-repeat org-log-repeat)
10156 (org-todo-log-states org-todo-log-states)
10157 (this (match-string 1))
10158 (hl-pos (match-beginning 0))
10159 (head (org-get-todo-sequence-head this))
10160 (ass (assoc head org-todo-kwd-alist))
10161 (interpret (nth 1 ass))
10162 (done-word (nth 3 ass))
10163 (final-done-word (nth 4 ass))
10164 (last-state (or this ""))
10165 (completion-ignore-case t)
10166 (member (member this org-todo-keywords-1))
10167 (tail (cdr member))
10168 (state (cond
10169 ((and org-todo-key-trigger
10170 (or (and (equal arg '(4))
10171 (eq org-use-fast-todo-selection 'prefix))
10172 (and (not arg) org-use-fast-todo-selection
10173 (not (eq org-use-fast-todo-selection
10174 'prefix)))))
10175 ;; Use fast selection
10176 (org-fast-todo-selection))
10177 ((and (equal arg '(4))
10178 (or (not org-use-fast-todo-selection)
10179 (not org-todo-key-trigger)))
10180 ;; Read a state with completion
10181 (org-icompleting-read
10182 "State: " (mapcar (lambda(x) (list x))
10183 org-todo-keywords-1)
10184 nil t))
10185 ((eq arg 'right)
10186 (if this
10187 (if tail (car tail) nil)
10188 (car org-todo-keywords-1)))
10189 ((eq arg 'left)
10190 (if (equal member org-todo-keywords-1)
10192 (if this
10193 (nth (- (length org-todo-keywords-1)
10194 (length tail) 2)
10195 org-todo-keywords-1)
10196 (org-last org-todo-keywords-1))))
10197 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10198 (setq arg nil))) ; hack to fall back to cycling
10199 (arg
10200 ;; user or caller requests a specific state
10201 (cond
10202 ((equal arg "") nil)
10203 ((eq arg 'none) nil)
10204 ((eq arg 'done) (or done-word (car org-done-keywords)))
10205 ((eq arg 'nextset)
10206 (or (car (cdr (member head org-todo-heads)))
10207 (car org-todo-heads)))
10208 ((eq arg 'previousset)
10209 (let ((org-todo-heads (reverse org-todo-heads)))
10210 (or (car (cdr (member head org-todo-heads)))
10211 (car org-todo-heads))))
10212 ((car (member arg org-todo-keywords-1)))
10213 ((stringp arg)
10214 (error "State `%s' not valid in this file" arg))
10215 ((nth (1- (prefix-numeric-value arg))
10216 org-todo-keywords-1))))
10217 ((null member) (or head (car org-todo-keywords-1)))
10218 ((equal this final-done-word) nil) ;; -> make empty
10219 ((null tail) nil) ;; -> first entry
10220 ((memq interpret '(type priority))
10221 (if (eq this-command last-command)
10222 (car tail)
10223 (if (> (length tail) 0)
10224 (or done-word (car org-done-keywords))
10225 nil)))
10227 (car tail))))
10228 (state (or
10229 (run-hook-with-args-until-success
10230 'org-todo-get-default-hook state last-state)
10231 state))
10232 (next (if state (concat " " state " ") " "))
10233 (change-plist (list :type 'todo-state-change :from this :to state
10234 :position startpos))
10235 dolog now-done-p)
10236 (when org-blocker-hook
10237 (setq org-last-todo-state-is-todo
10238 (not (member this org-done-keywords)))
10239 (unless (save-excursion
10240 (save-match-data
10241 (run-hook-with-args-until-failure
10242 'org-blocker-hook change-plist)))
10243 (if (interactive-p)
10244 (error "TODO state change from %s to %s blocked" this state)
10245 ;; fail silently
10246 (message "TODO state change from %s to %s blocked" this state)
10247 (throw 'exit nil))))
10248 (store-match-data match-data)
10249 (replace-match next t t)
10250 (unless (pos-visible-in-window-p hl-pos)
10251 (message "TODO state changed to %s" (org-trim next)))
10252 (unless head
10253 (setq head (org-get-todo-sequence-head state)
10254 ass (assoc head org-todo-kwd-alist)
10255 interpret (nth 1 ass)
10256 done-word (nth 3 ass)
10257 final-done-word (nth 4 ass)))
10258 (when (memq arg '(nextset previousset))
10259 (message "Keyword-Set %d/%d: %s"
10260 (- (length org-todo-sets) -1
10261 (length (memq (assoc state org-todo-sets) org-todo-sets)))
10262 (length org-todo-sets)
10263 (mapconcat 'identity (assoc state org-todo-sets) " ")))
10264 (setq org-last-todo-state-is-todo
10265 (not (member state org-done-keywords)))
10266 (setq now-done-p (and (member state org-done-keywords)
10267 (not (member this org-done-keywords))))
10268 (and logging (org-local-logging logging))
10269 (when (and (or org-todo-log-states org-log-done)
10270 (not (eq org-inhibit-logging t))
10271 (not (memq arg '(nextset previousset))))
10272 ;; we need to look at recording a time and note
10273 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
10274 (nth 2 (assoc this org-todo-log-states))))
10275 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
10276 (setq dolog 'time))
10277 (when (and state
10278 (member state org-not-done-keywords)
10279 (not (member this org-not-done-keywords)))
10280 ;; This is now a todo state and was not one before
10281 ;; If there was a CLOSED time stamp, get rid of it.
10282 (org-add-planning-info nil nil 'closed))
10283 (when (and now-done-p org-log-done)
10284 ;; It is now done, and it was not done before
10285 (org-add-planning-info 'closed (org-current-time))
10286 (if (and (not dolog) (eq 'note org-log-done))
10287 (org-add-log-setup 'done state this 'findpos 'note)))
10288 (when (and state dolog)
10289 ;; This is a non-nil state, and we need to log it
10290 (org-add-log-setup 'state state this 'findpos dolog)))
10291 ;; Fixup tag positioning
10292 (org-todo-trigger-tag-changes state)
10293 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
10294 (when org-provide-todo-statistics
10295 (org-update-parent-todo-statistics))
10296 (run-hooks 'org-after-todo-state-change-hook)
10297 (if (and arg (not (member state org-done-keywords)))
10298 (setq head (org-get-todo-sequence-head state)))
10299 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
10300 ;; Do we need to trigger a repeat?
10301 (when now-done-p
10302 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
10303 ;; This is for the agenda, take a snapshot of the headline.
10304 (save-match-data
10305 (setq org-agenda-headline-snapshot-before-repeat
10306 (org-get-heading))))
10307 (org-auto-repeat-maybe state))
10308 ;; Fixup cursor location if close to the keyword
10309 (if (and (outline-on-heading-p)
10310 (not (bolp))
10311 (save-excursion (beginning-of-line 1)
10312 (looking-at org-todo-line-regexp))
10313 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
10314 (progn
10315 (goto-char (or (match-end 2) (match-end 1)))
10316 (and (looking-at " ") (just-one-space))))
10317 (when org-trigger-hook
10318 (save-excursion
10319 (run-hook-with-args 'org-trigger-hook change-plist))))))))
10321 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
10322 "Block turning an entry into a TODO, using the hierarchy.
10323 This checks whether the current task should be blocked from state
10324 changes. Such blocking occurs when:
10326 1. The task has children which are not all in a completed state.
10328 2. A task has a parent with the property :ORDERED:, and there
10329 are siblings prior to the current task with incomplete
10330 status.
10332 3. The parent of the task is blocked because it has siblings that should
10333 be done first, or is child of a block grandparent TODO entry."
10335 (if (not org-enforce-todo-dependencies)
10336 t ; if locally turned off don't block
10337 (catch 'dont-block
10338 ;; If this is not a todo state change, or if this entry is already DONE,
10339 ;; do not block
10340 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10341 (member (plist-get change-plist :from)
10342 (cons 'done org-done-keywords))
10343 (member (plist-get change-plist :to)
10344 (cons 'todo org-not-done-keywords))
10345 (not (plist-get change-plist :to)))
10346 (throw 'dont-block t))
10347 ;; If this task has children, and any are undone, it's blocked
10348 (save-excursion
10349 (org-back-to-heading t)
10350 (let ((this-level (funcall outline-level)))
10351 (outline-next-heading)
10352 (let ((child-level (funcall outline-level)))
10353 (while (and (not (eobp))
10354 (> child-level this-level))
10355 ;; this todo has children, check whether they are all
10356 ;; completed
10357 (if (and (not (org-entry-is-done-p))
10358 (org-entry-is-todo-p))
10359 (throw 'dont-block nil))
10360 (outline-next-heading)
10361 (setq child-level (funcall outline-level))))))
10362 ;; Otherwise, if the task's parent has the :ORDERED: property, and
10363 ;; any previous siblings are undone, it's blocked
10364 (save-excursion
10365 (org-back-to-heading t)
10366 (let* ((pos (point))
10367 (parent-pos (and (org-up-heading-safe) (point))))
10368 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10369 (when (and (org-entry-get (point) "ORDERED")
10370 (forward-line 1)
10371 (re-search-forward org-not-done-heading-regexp pos t))
10372 (throw 'dont-block nil)) ; block, there is an older sibling not done.
10373 ;; Search further up the hierarchy, to see if an anchestor is blocked
10374 (while t
10375 (goto-char parent-pos)
10376 (if (not (looking-at org-not-done-heading-regexp))
10377 (throw 'dont-block t)) ; do not block, parent is not a TODO
10378 (setq pos (point))
10379 (setq parent-pos (and (org-up-heading-safe) (point)))
10380 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10381 (when (and (org-entry-get (point) "ORDERED")
10382 (forward-line 1)
10383 (re-search-forward org-not-done-heading-regexp pos t))
10384 (throw 'dont-block nil)))))))) ; block, older sibling not done.
10386 (defcustom org-track-ordered-property-with-tag nil
10387 "Should the ORDERED property also be shown as a tag?
10388 The ORDERED property decides if an entry should require subtasks to be
10389 completed in sequence. Since a property is not very visible, setting
10390 this option means that toggling the ORDERED property with the command
10391 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
10392 not relevant for the behavior, but it makes things more visible.
10394 Note that toggling the tag with tags commands will not change the property
10395 and therefore not influence behavior!
10397 This can be t, meaning the tag ORDERED should be used, It can also be a
10398 string to select a different tag for this task."
10399 :group 'org-todo
10400 :type '(choice
10401 (const :tag "No tracking" nil)
10402 (const :tag "Track with ORDERED tag" t)
10403 (string :tag "Use other tag")))
10405 (defun org-toggle-ordered-property ()
10406 "Toggle the ORDERED property of the current entry.
10407 For better visibility, you can track the value of this property with a tag.
10408 See variable `org-track-ordered-property-with-tag'."
10409 (interactive)
10410 (let* ((t1 org-track-ordered-property-with-tag)
10411 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
10412 (save-excursion
10413 (org-back-to-heading)
10414 (if (org-entry-get nil "ORDERED")
10415 (progn
10416 (org-delete-property "ORDERED")
10417 (and tag (org-toggle-tag tag 'off))
10418 (message "Subtasks can be completed in arbitrary order"))
10419 (org-entry-put nil "ORDERED" "t")
10420 (and tag (org-toggle-tag tag 'on))
10421 (message "Subtasks must be completed in sequence")))))
10423 (defvar org-blocked-by-checkboxes) ; dynamically scoped
10424 (defun org-block-todo-from-checkboxes (change-plist)
10425 "Block turning an entry into a TODO, using checkboxes.
10426 This checks whether the current task should be blocked from state
10427 changes because there are unchecked boxes in this entry."
10428 (if (not org-enforce-todo-checkbox-dependencies)
10429 t ; if locally turned off don't block
10430 (catch 'dont-block
10431 ;; If this is not a todo state change, or if this entry is already DONE,
10432 ;; do not block
10433 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10434 (member (plist-get change-plist :from)
10435 (cons 'done org-done-keywords))
10436 (member (plist-get change-plist :to)
10437 (cons 'todo org-not-done-keywords))
10438 (not (plist-get change-plist :to)))
10439 (throw 'dont-block t))
10440 ;; If this task has checkboxes that are not checked, it's blocked
10441 (save-excursion
10442 (org-back-to-heading t)
10443 (let ((beg (point)) end)
10444 (outline-next-heading)
10445 (setq end (point))
10446 (goto-char beg)
10447 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
10448 end t)
10449 (progn
10450 (if (boundp 'org-blocked-by-checkboxes)
10451 (setq org-blocked-by-checkboxes t))
10452 (throw 'dont-block nil)))))
10453 t))) ; do not block
10455 (defun org-entry-blocked-p ()
10456 "Is the current entry blocked?"
10457 (if (org-entry-get nil "NOBLOCKING")
10458 nil ;; Never block this entry
10459 (not
10460 (run-hook-with-args-until-failure
10461 'org-blocker-hook
10462 (list :type 'todo-state-change
10463 :position (point)
10464 :from 'todo
10465 :to 'done)))))
10467 (defun org-update-statistics-cookies (all)
10468 "Update the statistics cookie, either from TODO or from checkboxes.
10469 This should be called with the cursor in a line with a statistics cookie."
10470 (interactive "P")
10471 (if all
10472 (progn
10473 (org-update-checkbox-count 'all)
10474 (org-map-entries 'org-update-parent-todo-statistics))
10475 (if (not (org-on-heading-p))
10476 (org-update-checkbox-count)
10477 (let ((pos (move-marker (make-marker) (point)))
10478 end l1 l2)
10479 (ignore-errors (org-back-to-heading t))
10480 (if (not (org-on-heading-p))
10481 (org-update-checkbox-count)
10482 (setq l1 (org-outline-level))
10483 (setq end (save-excursion
10484 (outline-next-heading)
10485 (if (org-on-heading-p) (setq l2 (org-outline-level)))
10486 (point)))
10487 (if (and (save-excursion
10488 (re-search-forward
10489 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
10490 (not (save-excursion (re-search-forward
10491 ":COOKIE_DATA:.*\\<todo\\>" end t))))
10492 (org-update-checkbox-count)
10493 (if (and l2 (> l2 l1))
10494 (progn
10495 (goto-char end)
10496 (org-update-parent-todo-statistics))
10497 (goto-char pos)
10498 (beginning-of-line 1)
10499 (while (re-search-forward
10500 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
10501 (point-at-eol) t)
10502 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
10503 (goto-char pos)
10504 (move-marker pos nil)))))
10506 (defvar org-entry-property-inherited-from) ;; defined below
10507 (defun org-update-parent-todo-statistics ()
10508 "Update any statistics cookie in the parent of the current headline.
10509 When `org-hierarchical-todo-statistics' is nil, statistics will cover
10510 the entire subtree and this will travel up the hierarchy and update
10511 statistics everywhere."
10512 (interactive)
10513 (let* ((lim 0) prop
10514 (recursive (or (not org-hierarchical-todo-statistics)
10515 (string-match
10516 "\\<recursive\\>"
10517 (or (setq prop (org-entry-get
10518 nil "COOKIE_DATA" 'inherit)) ""))))
10519 (lim (or (and prop (marker-position
10520 org-entry-property-inherited-from))
10521 lim))
10522 (first t)
10523 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
10524 level ltoggle l1 new ndel
10525 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
10526 (catch 'exit
10527 (save-excursion
10528 (beginning-of-line 1)
10529 (if (org-at-heading-p)
10530 (setq ltoggle (funcall outline-level))
10531 (error "This should not happen"))
10532 (while (and (setq level (org-up-heading-safe))
10533 (or recursive first)
10534 (>= (point) lim))
10535 (setq first nil cookie-present nil)
10536 (unless (and level
10537 (not (string-match
10538 "\\<checkbox\\>"
10539 (downcase
10540 (or (org-entry-get
10541 nil "COOKIE_DATA")
10542 "")))))
10543 (throw 'exit nil))
10544 (while (re-search-forward box-re (point-at-eol) t)
10545 (setq cnt-all 0 cnt-done 0 cookie-present t)
10546 (setq is-percent (match-end 2))
10547 (save-match-data
10548 (unless (outline-next-heading) (throw 'exit nil))
10549 (while (and (looking-at org-complex-heading-regexp)
10550 (> (setq l1 (length (match-string 1))) level))
10551 (setq kwd (and (or recursive (= l1 ltoggle))
10552 (match-string 2)))
10553 (if (or (eq org-provide-todo-statistics 'all-headlines)
10554 (and (listp org-provide-todo-statistics)
10555 (or (member kwd org-provide-todo-statistics)
10556 (member kwd org-done-keywords))))
10557 (setq cnt-all (1+ cnt-all))
10558 (if (eq org-provide-todo-statistics t)
10559 (and kwd (setq cnt-all (1+ cnt-all)))))
10560 (and (member kwd org-done-keywords)
10561 (setq cnt-done (1+ cnt-done)))
10562 (outline-next-heading)))
10563 (setq new
10564 (if is-percent
10565 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
10566 (format "[%d/%d]" cnt-done cnt-all))
10567 ndel (- (match-end 0) (match-beginning 0)))
10568 (goto-char (match-beginning 0))
10569 (insert new)
10570 (delete-region (point) (+ (point) ndel)))
10571 (when cookie-present
10572 (run-hook-with-args 'org-after-todo-statistics-hook
10573 cnt-done (- cnt-all cnt-done))))))
10574 (run-hooks 'org-todo-statistics-hook)))
10576 (defvar org-after-todo-statistics-hook nil
10577 "Hook that is called after a TODO statistics cookie has been updated.
10578 Each function is called with two arguments: the number of not-done entries
10579 and the number of done entries.
10581 For example, the following function, when added to this hook, will switch
10582 an entry to DONE when all children are done, and back to TODO when new
10583 entries are set to a TODO status. Note that this hook is only called
10584 when there is a statistics cookie in the headline!
10586 (defun org-summary-todo (n-done n-not-done)
10587 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
10588 (let (org-log-done org-log-states) ; turn off logging
10589 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
10592 (defvar org-todo-statistics-hook nil
10593 "Hook that is run whenever Org thinks TODO statistics should be updated.
10594 This hook runs even if there is no statistics cookie present, in which case
10595 `org-after-todo-statistics-hook' would not run.")
10597 (defun org-todo-trigger-tag-changes (state)
10598 "Apply the changes defined in `org-todo-state-tags-triggers'."
10599 (let ((l org-todo-state-tags-triggers)
10600 changes)
10601 (when (or (not state) (equal state ""))
10602 (setq changes (append changes (cdr (assoc "" l)))))
10603 (when (and (stringp state) (> (length state) 0))
10604 (setq changes (append changes (cdr (assoc state l)))))
10605 (when (member state org-not-done-keywords)
10606 (setq changes (append changes (cdr (assoc 'todo l)))))
10607 (when (member state org-done-keywords)
10608 (setq changes (append changes (cdr (assoc 'done l)))))
10609 (dolist (c changes)
10610 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
10612 (defun org-local-logging (value)
10613 "Get logging settings from a property VALUE."
10614 (let* (words w a)
10615 ;; directly set the variables, they are already local.
10616 (setq org-log-done nil
10617 org-log-repeat nil
10618 org-todo-log-states nil)
10619 (setq words (org-split-string value))
10620 (while (setq w (pop words))
10621 (cond
10622 ((setq a (assoc w org-startup-options))
10623 (and (member (nth 1 a) '(org-log-done org-log-repeat))
10624 (set (nth 1 a) (nth 2 a))))
10625 ((setq a (org-extract-log-state-settings w))
10626 (and (member (car a) org-todo-keywords-1)
10627 (push a org-todo-log-states)))))))
10629 (defun org-get-todo-sequence-head (kwd)
10630 "Return the head of the TODO sequence to which KWD belongs.
10631 If KWD is not set, check if there is a text property remembering the
10632 right sequence."
10633 (let (p)
10634 (cond
10635 ((not kwd)
10636 (or (get-text-property (point-at-bol) 'org-todo-head)
10637 (progn
10638 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
10639 nil (point-at-eol)))
10640 (get-text-property p 'org-todo-head))))
10641 ((not (member kwd org-todo-keywords-1))
10642 (car org-todo-keywords-1))
10643 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
10645 (defun org-fast-todo-selection ()
10646 "Fast TODO keyword selection with single keys.
10647 Returns the new TODO keyword, or nil if no state change should occur."
10648 (let* ((fulltable org-todo-key-alist)
10649 (done-keywords org-done-keywords) ;; needed for the faces.
10650 (maxlen (apply 'max (mapcar
10651 (lambda (x)
10652 (if (stringp (car x)) (string-width (car x)) 0))
10653 fulltable)))
10654 (expert nil)
10655 (fwidth (+ maxlen 3 1 3))
10656 (ncol (/ (- (window-width) 4) fwidth))
10657 tg cnt e c tbl
10658 groups ingroup)
10659 (save-excursion
10660 (save-window-excursion
10661 (if expert
10662 (set-buffer (get-buffer-create " *Org todo*"))
10663 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
10664 (erase-buffer)
10665 (org-set-local 'org-done-keywords done-keywords)
10666 (setq tbl fulltable cnt 0)
10667 (while (setq e (pop tbl))
10668 (cond
10669 ((equal e '(:startgroup))
10670 (push '() groups) (setq ingroup t)
10671 (when (not (= cnt 0))
10672 (setq cnt 0)
10673 (insert "\n"))
10674 (insert "{ "))
10675 ((equal e '(:endgroup))
10676 (setq ingroup nil cnt 0)
10677 (insert "}\n"))
10678 ((equal e '(:newline))
10679 (when (not (= cnt 0))
10680 (setq cnt 0)
10681 (insert "\n")
10682 (setq e (car tbl))
10683 (while (equal (car tbl) '(:newline))
10684 (insert "\n")
10685 (setq tbl (cdr tbl)))))
10687 (setq tg (car e) c (cdr e))
10688 (if ingroup (push tg (car groups)))
10689 (setq tg (org-add-props tg nil 'face
10690 (org-get-todo-face tg)))
10691 (if (and (= cnt 0) (not ingroup)) (insert " "))
10692 (insert "[" c "] " tg (make-string
10693 (- fwidth 4 (length tg)) ?\ ))
10694 (when (= (setq cnt (1+ cnt)) ncol)
10695 (insert "\n")
10696 (if ingroup (insert " "))
10697 (setq cnt 0)))))
10698 (insert "\n")
10699 (goto-char (point-min))
10700 (if (not expert) (org-fit-window-to-buffer))
10701 (message "[a-z..]:Set [SPC]:clear")
10702 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10703 (cond
10704 ((or (= c ?\C-g)
10705 (and (= c ?q) (not (rassoc c fulltable))))
10706 (setq quit-flag t))
10707 ((= c ?\ ) nil)
10708 ((setq e (rassoc c fulltable) tg (car e))
10710 (t (setq quit-flag t)))))))
10712 (defun org-entry-is-todo-p ()
10713 (member (org-get-todo-state) org-not-done-keywords))
10715 (defun org-entry-is-done-p ()
10716 (member (org-get-todo-state) org-done-keywords))
10718 (defun org-get-todo-state ()
10719 (save-excursion
10720 (org-back-to-heading t)
10721 (and (looking-at org-todo-line-regexp)
10722 (match-end 2)
10723 (match-string 2))))
10725 (defun org-at-date-range-p (&optional inactive-ok)
10726 "Is the cursor inside a date range?"
10727 (interactive)
10728 (save-excursion
10729 (catch 'exit
10730 (let ((pos (point)))
10731 (skip-chars-backward "^[<\r\n")
10732 (skip-chars-backward "<[")
10733 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10734 (>= (match-end 0) pos)
10735 (throw 'exit t))
10736 (skip-chars-backward "^<[\r\n")
10737 (skip-chars-backward "<[")
10738 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10739 (>= (match-end 0) pos)
10740 (throw 'exit t)))
10741 nil)))
10743 (defun org-get-repeat (&optional tagline)
10744 "Check if there is a deadline/schedule with repeater in this entry."
10745 (save-match-data
10746 (save-excursion
10747 (org-back-to-heading t)
10748 (and (re-search-forward (if tagline
10749 (concat tagline "\\s-*" org-repeat-re)
10750 org-repeat-re)
10751 (org-entry-end-position) t)
10752 (match-string-no-properties 1)))))
10754 (defvar org-last-changed-timestamp)
10755 (defvar org-last-inserted-timestamp)
10756 (defvar org-log-post-message)
10757 (defvar org-log-note-purpose)
10758 (defvar org-log-note-how)
10759 (defvar org-log-note-extra)
10760 (defun org-auto-repeat-maybe (done-word)
10761 "Check if the current headline contains a repeated deadline/schedule.
10762 If yes, set TODO state back to what it was and change the base date
10763 of repeating deadline/scheduled time stamps to new date.
10764 This function is run automatically after each state change to a DONE state."
10765 ;; last-state is dynamically scoped into this function
10766 (let* ((repeat (org-get-repeat))
10767 (aa (assoc last-state org-todo-kwd-alist))
10768 (interpret (nth 1 aa))
10769 (head (nth 2 aa))
10770 (whata '(("d" . day) ("m" . month) ("y" . year)))
10771 (msg "Entry repeats: ")
10772 (org-log-done nil)
10773 (org-todo-log-states nil)
10774 (nshiftmax 10) (nshift 0)
10775 re type n what ts time)
10776 (when repeat
10777 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
10778 (org-todo (if (eq interpret 'type) last-state head))
10779 (org-entry-put nil "LAST_REPEAT" (format-time-string
10780 (org-time-stamp-format t t)))
10781 (when org-log-repeat
10782 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
10783 (memq 'org-add-log-note post-command-hook))
10784 ;; OK, we are already setup for some record
10785 (if (eq org-log-repeat 'note)
10786 ;; make sure we take a note, not only a time stamp
10787 (setq org-log-note-how 'note))
10788 ;; Set up for taking a record
10789 (org-add-log-setup 'state (or done-word (car org-done-keywords))
10790 last-state
10791 'findpos org-log-repeat)))
10792 (org-back-to-heading t)
10793 (org-add-planning-info nil nil 'closed)
10794 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
10795 org-deadline-time-regexp "\\)\\|\\("
10796 org-ts-regexp "\\)"))
10797 (while (re-search-forward
10798 re (save-excursion (outline-next-heading) (point)) t)
10799 (setq type (if (match-end 1) org-scheduled-string
10800 (if (match-end 3) org-deadline-string "Plain:"))
10801 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
10802 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
10803 (setq n (string-to-number (match-string 2 ts))
10804 what (match-string 3 ts))
10805 (if (equal what "w") (setq n (* n 7) what "d"))
10806 ;; Preparation, see if we need to modify the start date for the change
10807 (when (match-end 1)
10808 (setq time (save-match-data (org-time-string-to-time ts)))
10809 (cond
10810 ((equal (match-string 1 ts) ".")
10811 ;; Shift starting date to today
10812 (org-timestamp-change
10813 (- (time-to-days (current-time)) (time-to-days time))
10814 'day))
10815 ((equal (match-string 1 ts) "+")
10816 (while (or (= nshift 0)
10817 (<= (time-to-days time) (time-to-days (current-time))))
10818 (when (= (incf nshift) nshiftmax)
10819 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
10820 (error "Abort")))
10821 (org-timestamp-change n (cdr (assoc what whata)))
10822 (org-at-timestamp-p t)
10823 (setq ts (match-string 1))
10824 (setq time (save-match-data (org-time-string-to-time ts))))
10825 (org-timestamp-change (- n) (cdr (assoc what whata)))
10826 ;; rematch, so that we have everything in place for the real shift
10827 (org-at-timestamp-p t)
10828 (setq ts (match-string 1))
10829 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
10830 (org-timestamp-change n (cdr (assoc what whata)))
10831 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
10832 (setq org-log-post-message msg)
10833 (message "%s" msg))))
10835 (defun org-show-todo-tree (arg)
10836 "Make a compact tree which shows all headlines marked with TODO.
10837 The tree will show the lines where the regexp matches, and all higher
10838 headlines above the match.
10839 With a \\[universal-argument] prefix, prompt for a regexp to match.
10840 With a numeric prefix N, construct a sparse tree for the Nth element
10841 of `org-todo-keywords-1'."
10842 (interactive "P")
10843 (let ((case-fold-search nil)
10844 (kwd-re
10845 (cond ((null arg) org-not-done-regexp)
10846 ((equal arg '(4))
10847 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
10848 (mapcar 'list org-todo-keywords-1))))
10849 (concat "\\("
10850 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10851 "\\)\\>")))
10852 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10853 (regexp-quote (nth (1- (prefix-numeric-value arg))
10854 org-todo-keywords-1)))
10855 (t (error "Invalid prefix argument: %s" arg)))))
10856 (message "%d TODO entries found"
10857 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
10859 (defun org-deadline (&optional remove time)
10860 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
10861 With argument REMOVE, remove any deadline from the item.
10862 When TIME is set, it should be an internal time specification, and the
10863 scheduling will use the corresponding date."
10864 (interactive "P")
10865 (let* ((old-date (org-entry-get nil "DEADLINE"))
10866 (repeater (and old-date
10867 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
10868 (match-string 1 old-date))))
10869 (if remove
10870 (progn
10871 (when (and old-date org-log-redeadline)
10872 (org-add-log-setup 'deldeadline nil old-date 'findpos
10873 org-log-redeadline))
10874 (org-remove-timestamp-with-keyword org-deadline-string)
10875 (message "Item no longer has a deadline."))
10876 (org-add-planning-info 'deadline time 'closed)
10877 (when (and old-date org-log-redeadline
10878 (not (equal old-date
10879 (substring org-last-inserted-timestamp 1 -1))))
10880 (org-add-log-setup 'redeadline nil old-date 'findpos
10881 org-log-redeadline))
10882 (when repeater
10883 (save-excursion
10884 (org-back-to-heading t)
10885 (when (re-search-forward (concat org-deadline-string " "
10886 org-last-inserted-timestamp)
10887 (save-excursion
10888 (outline-next-heading) (point)) t)
10889 (goto-char (1- (match-end 0)))
10890 (insert " " repeater)
10891 (setq org-last-inserted-timestamp
10892 (concat (substring org-last-inserted-timestamp 0 -1)
10893 " " repeater
10894 (substring org-last-inserted-timestamp -1))))))
10895 (message "Deadline on %s" org-last-inserted-timestamp))))
10897 (defun org-schedule (&optional remove time)
10898 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
10899 With argument REMOVE, remove any scheduling date from the item.
10900 When TIME is set, it should be an internal time specification, and the
10901 scheduling will use the corresponding date."
10902 (interactive "P")
10903 (let* ((old-date (org-entry-get nil "SCHEDULED"))
10904 (repeater (and old-date
10905 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
10906 (match-string 1 old-date))))
10907 (if remove
10908 (progn
10909 (when (and old-date org-log-reschedule)
10910 (org-add-log-setup 'delschedule nil old-date 'findpos
10911 org-log-reschedule))
10912 (org-remove-timestamp-with-keyword org-scheduled-string)
10913 (message "Item is no longer scheduled."))
10914 (org-add-planning-info 'scheduled time 'closed)
10915 (when (and old-date org-log-reschedule
10916 (not (equal old-date
10917 (substring org-last-inserted-timestamp 1 -1))))
10918 (org-add-log-setup 'reschedule nil old-date 'findpos
10919 org-log-reschedule))
10920 (when repeater
10921 (save-excursion
10922 (org-back-to-heading t)
10923 (when (re-search-forward (concat org-scheduled-string " "
10924 org-last-inserted-timestamp)
10925 (save-excursion
10926 (outline-next-heading) (point)) t)
10927 (goto-char (1- (match-end 0)))
10928 (insert " " repeater)
10929 (setq org-last-inserted-timestamp
10930 (concat (substring org-last-inserted-timestamp 0 -1)
10931 " " repeater
10932 (substring org-last-inserted-timestamp -1))))))
10933 (message "Scheduled to %s" org-last-inserted-timestamp))))
10935 (defun org-get-scheduled-time (pom &optional inherit)
10936 "Get the scheduled time as a time tuple, of a format suitable
10937 for calling org-schedule with, or if there is no scheduling,
10938 returns nil."
10939 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
10940 (when time
10941 (apply 'encode-time (org-parse-time-string time)))))
10943 (defun org-get-deadline-time (pom &optional inherit)
10944 "Get the deadine as a time tuple, of a format suitable for
10945 calling org-deadline with, or if there is no scheduling, returns
10946 nil."
10947 (let ((time (org-entry-get pom "DEADLINE" inherit)))
10948 (when time
10949 (apply 'encode-time (org-parse-time-string time)))))
10951 (defun org-remove-timestamp-with-keyword (keyword)
10952 "Remove all time stamps with KEYWORD in the current entry."
10953 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
10954 beg)
10955 (save-excursion
10956 (org-back-to-heading t)
10957 (setq beg (point))
10958 (outline-next-heading)
10959 (while (re-search-backward re beg t)
10960 (replace-match "")
10961 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
10962 (equal (char-before) ?\ ))
10963 (backward-delete-char 1)
10964 (if (string-match "^[ \t]*$" (buffer-substring
10965 (point-at-bol) (point-at-eol)))
10966 (delete-region (point-at-bol)
10967 (min (point-max) (1+ (point-at-eol))))))))))
10969 (defun org-add-planning-info (what &optional time &rest remove)
10970 "Insert new timestamp with keyword in the line directly after the headline.
10971 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
10972 If non is given, the user is prompted for a date.
10973 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
10974 be removed."
10975 (interactive)
10976 (let (org-time-was-given org-end-time-was-given ts
10977 end default-time default-input)
10979 (catch 'exit
10980 (when (and (not time) (memq what '(scheduled deadline)))
10981 ;; Try to get a default date/time from existing timestamp
10982 (save-excursion
10983 (org-back-to-heading t)
10984 (setq end (save-excursion (outline-next-heading) (point)))
10985 (when (re-search-forward (if (eq what 'scheduled)
10986 org-scheduled-time-regexp
10987 org-deadline-time-regexp)
10988 end t)
10989 (setq ts (match-string 1)
10990 default-time
10991 (apply 'encode-time (org-parse-time-string ts))
10992 default-input (and ts (org-get-compact-tod ts))))))
10993 (when what
10994 ;; If necessary, get the time from the user
10995 (setq time (or time (org-read-date nil 'to-time nil nil
10996 default-time default-input))))
10998 (when (and org-insert-labeled-timestamps-at-point
10999 (member what '(scheduled deadline)))
11000 (insert
11001 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11002 (org-insert-time-stamp time org-time-was-given
11003 nil nil nil (list org-end-time-was-given))
11004 (setq what nil))
11005 (save-excursion
11006 (save-restriction
11007 (let (col list elt ts buffer-invisibility-spec)
11008 (org-back-to-heading t)
11009 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
11010 (goto-char (match-end 1))
11011 (setq col (current-column))
11012 (goto-char (match-end 0))
11013 (if (eobp) (insert "\n") (forward-char 1))
11014 (when (and (not what)
11015 (not (looking-at
11016 (concat "[ \t]*"
11017 org-keyword-time-not-clock-regexp))))
11018 ;; Nothing to add, nothing to remove...... :-)
11019 (throw 'exit nil))
11020 (if (and (not (looking-at outline-regexp))
11021 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11022 "[^\r\n]*"))
11023 (not (equal (match-string 1) org-clock-string)))
11024 (narrow-to-region (match-beginning 0) (match-end 0))
11025 (insert-before-markers "\n")
11026 (backward-char 1)
11027 (narrow-to-region (point) (point))
11028 (and org-adapt-indentation (org-indent-to-column col)))
11029 ;; Check if we have to remove something.
11030 (setq list (cons what remove))
11031 (while list
11032 (setq elt (pop list))
11033 (goto-char (point-min))
11034 (when (or (and (eq elt 'scheduled)
11035 (re-search-forward org-scheduled-time-regexp nil t))
11036 (and (eq elt 'deadline)
11037 (re-search-forward org-deadline-time-regexp nil t))
11038 (and (eq elt 'closed)
11039 (re-search-forward org-closed-time-regexp nil t)))
11040 (replace-match "")
11041 (if (looking-at "--+<[^>]+>") (replace-match ""))
11042 (skip-chars-backward " ")
11043 (if (looking-at " +") (replace-match ""))))
11044 (goto-char (point-max))
11045 (and org-adapt-indentation (bolp) (org-indent-to-column col))
11046 (when what
11047 (insert
11048 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
11049 (cond ((eq what 'scheduled) org-scheduled-string)
11050 ((eq what 'deadline) org-deadline-string)
11051 ((eq what 'closed) org-closed-string))
11052 " ")
11053 (setq ts (org-insert-time-stamp
11054 time
11055 (or org-time-was-given
11056 (and (eq what 'closed) org-log-done-with-time))
11057 (eq what 'closed)
11058 nil nil (list org-end-time-was-given)))
11059 (end-of-line 1))
11060 (goto-char (point-min))
11061 (widen)
11062 (if (and (looking-at "[ \t]+\n")
11063 (equal (char-before) ?\n))
11064 (delete-region (1- (point)) (point-at-eol)))
11065 ts))))))
11067 (defvar org-log-note-marker (make-marker))
11068 (defvar org-log-note-purpose nil)
11069 (defvar org-log-note-state nil)
11070 (defvar org-log-note-previous-state nil)
11071 (defvar org-log-note-how nil)
11072 (defvar org-log-note-extra nil)
11073 (defvar org-log-note-window-configuration nil)
11074 (defvar org-log-note-return-to (make-marker))
11075 (defvar org-log-post-message nil
11076 "Message to be displayed after a log note has been stored.
11077 The auto-repeater uses this.")
11079 (defun org-add-note ()
11080 "Add a note to the current entry.
11081 This is done in the same way as adding a state change note."
11082 (interactive)
11083 (org-add-log-setup 'note nil nil 'findpos nil))
11085 (defvar org-property-end-re)
11086 (defun org-add-log-setup (&optional purpose state prev-state
11087 findpos how &optional extra)
11088 "Set up the post command hook to take a note.
11089 If this is about to TODO state change, the new state is expected in STATE.
11090 When FINDPOS is non-nil, find the correct position for the note in
11091 the current entry. If not, assume that it can be inserted at point.
11092 HOW is an indicator what kind of note should be created.
11093 EXTRA is additional text that will be inserted into the notes buffer."
11094 (let* ((org-log-into-drawer (org-log-into-drawer))
11095 (drawer (cond ((stringp org-log-into-drawer)
11096 org-log-into-drawer)
11097 (org-log-into-drawer "LOGBOOK")
11098 (t nil))))
11099 (save-restriction
11100 (save-excursion
11101 (when findpos
11102 (org-back-to-heading t)
11103 (narrow-to-region (point) (save-excursion
11104 (outline-next-heading) (point)))
11105 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
11106 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
11107 "[^\r\n]*\\)?"))
11108 (goto-char (match-end 0))
11109 (cond
11110 (drawer
11111 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
11112 nil t)
11113 (progn
11114 (goto-char (match-end 0))
11115 (or org-log-states-order-reversed
11116 (and (re-search-forward org-property-end-re nil t)
11117 (goto-char (1- (match-beginning 0))))))
11118 (insert "\n:" drawer ":\n:END:")
11119 (beginning-of-line 0)
11120 (org-indent-line-function)
11121 (beginning-of-line 2)
11122 (org-indent-line-function)
11123 (end-of-line 0)))
11124 ((and org-log-state-notes-insert-after-drawers
11125 (save-excursion
11126 (forward-line) (looking-at org-drawer-regexp)))
11127 (forward-line)
11128 (while (looking-at org-drawer-regexp)
11129 (goto-char (match-end 0))
11130 (re-search-forward org-property-end-re (point-max) t)
11131 (forward-line))
11132 (forward-line -1)))
11133 (unless org-log-states-order-reversed
11134 (and (= (char-after) ?\n) (forward-char 1))
11135 (org-skip-over-state-notes)
11136 (skip-chars-backward " \t\n\r")))
11137 (move-marker org-log-note-marker (point))
11138 (setq org-log-note-purpose purpose
11139 org-log-note-state state
11140 org-log-note-previous-state prev-state
11141 org-log-note-how how
11142 org-log-note-extra extra)
11143 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
11145 (defun org-skip-over-state-notes ()
11146 "Skip past the list of State notes in an entry."
11147 (if (looking-at "\n[ \t]*- State") (forward-char 1))
11148 (while (looking-at "[ \t]*- State")
11149 (condition-case nil
11150 (org-next-item)
11151 (error (org-end-of-item)))))
11153 (defun org-add-log-note (&optional purpose)
11154 "Pop up a window for taking a note, and add this note later at point."
11155 (remove-hook 'post-command-hook 'org-add-log-note)
11156 (setq org-log-note-window-configuration (current-window-configuration))
11157 (delete-other-windows)
11158 (move-marker org-log-note-return-to (point))
11159 (switch-to-buffer (marker-buffer org-log-note-marker))
11160 (goto-char org-log-note-marker)
11161 (org-switch-to-buffer-other-window "*Org Note*")
11162 (erase-buffer)
11163 (if (memq org-log-note-how '(time state))
11164 (let (current-prefix-arg) (org-store-log-note))
11165 (let ((org-inhibit-startup t)) (org-mode))
11166 (insert (format "# Insert note for %s.
11167 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
11168 (cond
11169 ((eq org-log-note-purpose 'clock-out) "stopped clock")
11170 ((eq org-log-note-purpose 'done) "closed todo item")
11171 ((eq org-log-note-purpose 'state)
11172 (format "state change from \"%s\" to \"%s\""
11173 (or org-log-note-previous-state "")
11174 (or org-log-note-state "")))
11175 ((eq org-log-note-purpose 'reschedule)
11176 "rescheduling")
11177 ((eq org-log-note-purpose 'delschedule)
11178 "no longer scheduled")
11179 ((eq org-log-note-purpose 'redeadline)
11180 "changing deadline")
11181 ((eq org-log-note-purpose 'deldeadline)
11182 "removing deadline")
11183 ((eq org-log-note-purpose 'refile)
11184 "refiling")
11185 ((eq org-log-note-purpose 'note)
11186 "this entry")
11187 (t (error "This should not happen")))))
11188 (if org-log-note-extra (insert org-log-note-extra))
11189 (org-set-local 'org-finish-function 'org-store-log-note)))
11191 (defvar org-note-abort nil) ; dynamically scoped
11192 (defun org-store-log-note ()
11193 "Finish taking a log note, and insert it to where it belongs."
11194 (let ((txt (buffer-string))
11195 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
11196 lines ind)
11197 (kill-buffer (current-buffer))
11198 (while (string-match "\\`#.*\n[ \t\n]*" txt)
11199 (setq txt (replace-match "" t t txt)))
11200 (if (string-match "\\s-+\\'" txt)
11201 (setq txt (replace-match "" t t txt)))
11202 (setq lines (org-split-string txt "\n"))
11203 (when (and note (string-match "\\S-" note))
11204 (setq note
11205 (org-replace-escapes
11206 note
11207 (list (cons "%u" (user-login-name))
11208 (cons "%U" user-full-name)
11209 (cons "%t" (format-time-string
11210 (org-time-stamp-format 'long 'inactive)
11211 (current-time)))
11212 (cons "%s" (if org-log-note-state
11213 (concat "\"" org-log-note-state "\"")
11214 ""))
11215 (cons "%S" (if org-log-note-previous-state
11216 (concat "\"" org-log-note-previous-state "\"")
11217 "\"\"")))))
11218 (if lines (setq note (concat note " \\\\")))
11219 (push note lines))
11220 (when (or current-prefix-arg org-note-abort)
11221 (when org-log-into-drawer
11222 (org-remove-empty-drawer-at
11223 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
11224 org-log-note-marker))
11225 (setq lines nil))
11226 (when lines
11227 (with-current-buffer (marker-buffer org-log-note-marker)
11228 (save-excursion
11229 (goto-char org-log-note-marker)
11230 (move-marker org-log-note-marker nil)
11231 (end-of-line 1)
11232 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
11233 (insert "- " (pop lines))
11234 (org-indent-line-function)
11235 (beginning-of-line 1)
11236 (looking-at "[ \t]*")
11237 (setq ind (concat (match-string 0) " "))
11238 (end-of-line 1)
11239 (while lines (insert "\n" ind (pop lines)))
11240 (message "Note stored")
11241 (org-back-to-heading t)
11242 (org-cycle-hide-drawers 'children)))))
11243 (set-window-configuration org-log-note-window-configuration)
11244 (with-current-buffer (marker-buffer org-log-note-return-to)
11245 (goto-char org-log-note-return-to))
11246 (move-marker org-log-note-return-to nil)
11247 (and org-log-post-message (message "%s" org-log-post-message)))
11249 (defun org-remove-empty-drawer-at (drawer pos)
11250 "Remove an empty drawer DRAWER at position POS.
11251 POS may also be a marker."
11252 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
11253 (save-excursion
11254 (save-restriction
11255 (widen)
11256 (goto-char pos)
11257 (if (org-in-regexp
11258 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
11259 (replace-match ""))))))
11261 (defun org-sparse-tree (&optional arg)
11262 "Create a sparse tree, prompt for the details.
11263 This command can create sparse trees. You first need to select the type
11264 of match used to create the tree:
11266 t Show entries with a specific TODO keyword.
11267 m Show entries selected by a tags/property match.
11268 p Enter a property name and its value (both with completion on existing
11269 names/values) and show entries with that property.
11270 / Show entries matching a regular expression (`r' can be used as well)
11271 d Show deadlines due within `org-deadline-warning-days'.
11272 b Show deadlines and scheduled items before a date.
11273 a Show deadlines and scheduled items after a date."
11274 (interactive "P")
11275 (let (ans kwd value)
11276 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
11277 (setq ans (read-char-exclusive))
11278 (cond
11279 ((equal ans ?d)
11280 (call-interactively 'org-check-deadlines))
11281 ((equal ans ?b)
11282 (call-interactively 'org-check-before-date))
11283 ((equal ans ?a)
11284 (call-interactively 'org-check-after-date))
11285 ((equal ans ?t)
11286 (org-show-todo-tree '(4)))
11287 ((member ans '(?T ?m))
11288 (call-interactively 'org-match-sparse-tree))
11289 ((member ans '(?p ?P))
11290 (setq kwd (org-icompleting-read "Property: "
11291 (mapcar 'list (org-buffer-property-keys))))
11292 (setq value (org-icompleting-read "Value: "
11293 (mapcar 'list (org-property-values kwd))))
11294 (unless (string-match "\\`{.*}\\'" value)
11295 (setq value (concat "\"" value "\"")))
11296 (org-match-sparse-tree arg (concat kwd "=" value)))
11297 ((member ans '(?r ?R ?/))
11298 (call-interactively 'org-occur))
11299 (t (error "No such sparse tree command \"%c\"" ans)))))
11301 (defvar org-occur-highlights nil
11302 "List of overlays used for occur matches.")
11303 (make-variable-buffer-local 'org-occur-highlights)
11304 (defvar org-occur-parameters nil
11305 "Parameters of the active org-occur calls.
11306 This is a list, each call to org-occur pushes as cons cell,
11307 containing the regular expression and the callback, onto the list.
11308 The list can contain several entries if `org-occur' has been called
11309 several time with the KEEP-PREVIOUS argument. Otherwise, this list
11310 will only contain one set of parameters. When the highlights are
11311 removed (for example with `C-c C-c', or with the next edit (depending
11312 on `org-remove-highlights-with-change'), this variable is emptied
11313 as well.")
11314 (make-variable-buffer-local 'org-occur-parameters)
11316 (defun org-occur (regexp &optional keep-previous callback)
11317 "Make a compact tree which shows all matches of REGEXP.
11318 The tree will show the lines where the regexp matches, and all higher
11319 headlines above the match. It will also show the heading after the match,
11320 to make sure editing the matching entry is easy.
11321 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
11322 call to `org-occur' will be kept, to allow stacking of calls to this
11323 command.
11324 If CALLBACK is non-nil, it is a function which is called to confirm
11325 that the match should indeed be shown."
11326 (interactive "sRegexp: \nP")
11327 (when (equal regexp "")
11328 (error "Regexp cannot be empty"))
11329 (unless keep-previous
11330 (org-remove-occur-highlights nil nil t))
11331 (push (cons regexp callback) org-occur-parameters)
11332 (let ((cnt 0))
11333 (save-excursion
11334 (goto-char (point-min))
11335 (if (or (not keep-previous) ; do not want to keep
11336 (not org-occur-highlights)) ; no previous matches
11337 ;; hide everything
11338 (org-overview))
11339 (while (re-search-forward regexp nil t)
11340 (when (or (not callback)
11341 (save-match-data (funcall callback)))
11342 (setq cnt (1+ cnt))
11343 (when org-highlight-sparse-tree-matches
11344 (org-highlight-new-match (match-beginning 0) (match-end 0)))
11345 (org-show-context 'occur-tree))))
11346 (when org-remove-highlights-with-change
11347 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
11348 nil 'local))
11349 (unless org-sparse-tree-open-archived-trees
11350 (org-hide-archived-subtrees (point-min) (point-max)))
11351 (run-hooks 'org-occur-hook)
11352 (if (interactive-p)
11353 (message "%d match(es) for regexp %s" cnt regexp))
11354 cnt))
11356 (defun org-show-context (&optional key)
11357 "Make sure point and context and visible.
11358 How much context is shown depends upon the variables
11359 `org-show-hierarchy-above', `org-show-following-heading'. and
11360 `org-show-siblings'."
11361 (let ((heading-p (org-on-heading-p t))
11362 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
11363 (following-p (org-get-alist-option org-show-following-heading key))
11364 (entry-p (org-get-alist-option org-show-entry-below key))
11365 (siblings-p (org-get-alist-option org-show-siblings key)))
11366 (catch 'exit
11367 ;; Show heading or entry text
11368 (if (and heading-p (not entry-p))
11369 (org-flag-heading nil) ; only show the heading
11370 (and (or entry-p (org-invisible-p) (org-invisible-p2))
11371 (org-show-hidden-entry))) ; show entire entry
11372 (when following-p
11373 ;; Show next sibling, or heading below text
11374 (save-excursion
11375 (and (if heading-p (org-goto-sibling) (outline-next-heading))
11376 (org-flag-heading nil))))
11377 (when siblings-p (org-show-siblings))
11378 (when hierarchy-p
11379 ;; show all higher headings, possibly with siblings
11380 (save-excursion
11381 (while (and (condition-case nil
11382 (progn (org-up-heading-all 1) t)
11383 (error nil))
11384 (not (bobp)))
11385 (org-flag-heading nil)
11386 (when siblings-p (org-show-siblings))))))))
11388 (defvar org-reveal-start-hook nil
11389 "Hook run before revealing a location.")
11391 (defun org-reveal (&optional siblings)
11392 "Show current entry, hierarchy above it, and the following headline.
11393 This can be used to show a consistent set of context around locations
11394 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
11395 not t for the search context.
11397 With optional argument SIBLINGS, on each level of the hierarchy all
11398 siblings are shown. This repairs the tree structure to what it would
11399 look like when opened with hierarchical calls to `org-cycle'.
11400 With double optional argument `C-u C-u', go to the parent and show the
11401 entire tree."
11402 (interactive "P")
11403 (run-hooks 'org-reveal-start-hook)
11404 (let ((org-show-hierarchy-above t)
11405 (org-show-following-heading t)
11406 (org-show-siblings (if siblings t org-show-siblings)))
11407 (org-show-context nil))
11408 (when (equal siblings '(16))
11409 (save-excursion
11410 (when (org-up-heading-safe)
11411 (org-show-subtree)
11412 (run-hook-with-args 'org-cycle-hook 'subtree)))))
11414 (defun org-highlight-new-match (beg end)
11415 "Highlight from BEG to END and mark the highlight is an occur headline."
11416 (let ((ov (org-make-overlay beg end)))
11417 (org-overlay-put ov 'face 'secondary-selection)
11418 (push ov org-occur-highlights)))
11420 (defun org-remove-occur-highlights (&optional beg end noremove)
11421 "Remove the occur highlights from the buffer.
11422 BEG and END are ignored. If NOREMOVE is nil, remove this function
11423 from the `before-change-functions' in the current buffer."
11424 (interactive)
11425 (unless org-inhibit-highlight-removal
11426 (mapc 'org-delete-overlay org-occur-highlights)
11427 (setq org-occur-highlights nil)
11428 (setq org-occur-parameters nil)
11429 (unless noremove
11430 (remove-hook 'before-change-functions
11431 'org-remove-occur-highlights 'local))))
11433 ;;;; Priorities
11435 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
11436 "Regular expression matching the priority indicator.")
11438 (defvar org-remove-priority-next-time nil)
11440 (defun org-priority-up ()
11441 "Increase the priority of the current item."
11442 (interactive)
11443 (org-priority 'up))
11445 (defun org-priority-down ()
11446 "Decrease the priority of the current item."
11447 (interactive)
11448 (org-priority 'down))
11450 (defun org-priority (&optional action)
11451 "Change the priority of an item by ARG.
11452 ACTION can be `set', `up', `down', or a character."
11453 (interactive)
11454 (unless org-enable-priority-commands
11455 (error "Priority commands are disabled"))
11456 (setq action (or action 'set))
11457 (let (current new news have remove)
11458 (save-excursion
11459 (org-back-to-heading t)
11460 (if (looking-at org-priority-regexp)
11461 (setq current (string-to-char (match-string 2))
11462 have t)
11463 (setq current org-default-priority))
11464 (cond
11465 ((eq action 'remove)
11466 (setq remove t new ?\ ))
11467 ((or (eq action 'set)
11468 (if (featurep 'xemacs) (characterp action) (integerp action)))
11469 (if (not (eq action 'set))
11470 (setq new action)
11471 (message "Priority %c-%c, SPC to remove: "
11472 org-highest-priority org-lowest-priority)
11473 (setq new (read-char-exclusive)))
11474 (if (and (= (upcase org-highest-priority) org-highest-priority)
11475 (= (upcase org-lowest-priority) org-lowest-priority))
11476 (setq new (upcase new)))
11477 (cond ((equal new ?\ ) (setq remove t))
11478 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
11479 (error "Priority must be between `%c' and `%c'"
11480 org-highest-priority org-lowest-priority))))
11481 ((eq action 'up)
11482 (if (and (not have) (eq last-command this-command))
11483 (setq new org-lowest-priority)
11484 (setq new (if (and org-priority-start-cycle-with-default (not have))
11485 org-default-priority (1- current)))))
11486 ((eq action 'down)
11487 (if (and (not have) (eq last-command this-command))
11488 (setq new org-highest-priority)
11489 (setq new (if (and org-priority-start-cycle-with-default (not have))
11490 org-default-priority (1+ current)))))
11491 (t (error "Invalid action")))
11492 (if (or (< (upcase new) org-highest-priority)
11493 (> (upcase new) org-lowest-priority))
11494 (setq remove t))
11495 (setq news (format "%c" new))
11496 (if have
11497 (if remove
11498 (replace-match "" t t nil 1)
11499 (replace-match news t t nil 2))
11500 (if remove
11501 (error "No priority cookie found in line")
11502 (let ((case-fold-search nil))
11503 (looking-at org-todo-line-regexp))
11504 (if (match-end 2)
11505 (progn
11506 (goto-char (match-end 2))
11507 (insert " [#" news "]"))
11508 (goto-char (match-beginning 3))
11509 (insert "[#" news "] "))))
11510 (org-preserve-lc (org-set-tags nil 'align)))
11511 (if remove
11512 (message "Priority removed")
11513 (message "Priority of current item set to %s" news))))
11515 (defun org-get-priority (s)
11516 "Find priority cookie and return priority."
11517 (save-match-data
11518 (if (not (string-match org-priority-regexp s))
11519 (* 1000 (- org-lowest-priority org-default-priority))
11520 (* 1000 (- org-lowest-priority
11521 (string-to-char (match-string 2 s)))))))
11523 ;;;; Tags
11525 (defvar org-agenda-archives-mode)
11526 (defvar org-map-continue-from nil
11527 "Position from where mapping should continue.
11528 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
11530 (defvar org-scanner-tags nil
11531 "The current tag list while the tags scanner is running.")
11532 (defvar org-trust-scanner-tags nil
11533 "Should `org-get-tags-at' use the tags fro the scanner.
11534 This is for internal dynamical scoping only.
11535 When this is non-nil, the function `org-get-tags-at' will return the value
11536 of `org-scanner-tags' instead of building the list by itself. This
11537 can lead to large speed-ups when the tags scanner is used in a file with
11538 many entries, and when the list of tags is retrieved, for example to
11539 obtain a list of properties. Building the tags list for each entry in such
11540 a file becomes an N^2 operation - but with this variable set, it scales
11541 as N.")
11543 (defun org-scan-tags (action matcher &optional todo-only)
11544 "Scan headline tags with inheritance and produce output ACTION.
11546 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
11547 or `agenda' to produce an entry list for an agenda view. It can also be
11548 a Lisp form or a function that should be called at each matched headline, in
11549 this case the return value is a list of all return values from these calls.
11551 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
11552 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
11553 only lines with a TODO keyword are included in the output."
11554 (require 'org-agenda)
11555 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
11556 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
11557 (org-re
11558 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
11559 (props (list 'face 'default
11560 'done-face 'org-agenda-done
11561 'undone-face 'default
11562 'mouse-face 'highlight
11563 'org-not-done-regexp org-not-done-regexp
11564 'org-todo-regexp org-todo-regexp
11565 'help-echo
11566 (format "mouse-2 or RET jump to org file %s"
11567 (abbreviate-file-name
11568 (or (buffer-file-name (buffer-base-buffer))
11569 (buffer-name (buffer-base-buffer)))))))
11570 (case-fold-search nil)
11571 (org-map-continue-from nil)
11572 lspos tags tags-list
11573 (tags-alist (list (cons 0 org-file-tags)))
11574 (llast 0) rtn rtn1 level category i txt
11575 todo marker entry priority)
11576 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
11577 (setq action (list 'lambda nil action)))
11578 (save-excursion
11579 (goto-char (point-min))
11580 (when (eq action 'sparse-tree)
11581 (org-overview)
11582 (org-remove-occur-highlights))
11583 (while (re-search-forward re nil t)
11584 (catch :skip
11585 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
11586 tags (if (match-end 4) (org-match-string-no-properties 4)))
11587 (goto-char (setq lspos (match-beginning 0)))
11588 (setq level (org-reduced-level (funcall outline-level))
11589 category (org-get-category))
11590 (setq i llast llast level)
11591 ;; remove tag lists from same and sublevels
11592 (while (>= i level)
11593 (when (setq entry (assoc i tags-alist))
11594 (setq tags-alist (delete entry tags-alist)))
11595 (setq i (1- i)))
11596 ;; add the next tags
11597 (when tags
11598 (setq tags (org-split-string tags ":")
11599 tags-alist
11600 (cons (cons level tags) tags-alist)))
11601 ;; compile tags for current headline
11602 (setq tags-list
11603 (if org-use-tag-inheritance
11604 (apply 'append (mapcar 'cdr (reverse tags-alist)))
11605 tags)
11606 org-scanner-tags tags-list)
11607 (when org-use-tag-inheritance
11608 (setcdr (car tags-alist)
11609 (mapcar (lambda (x)
11610 (setq x (copy-sequence x))
11611 (org-add-prop-inherited x))
11612 (cdar tags-alist))))
11613 (when (and tags org-use-tag-inheritance
11614 (or (not (eq t org-use-tag-inheritance))
11615 org-tags-exclude-from-inheritance))
11616 ;; selective inheritance, remove uninherited ones
11617 (setcdr (car tags-alist)
11618 (org-remove-uniherited-tags (cdar tags-alist))))
11619 (when (and (or (not todo-only)
11620 (and (member todo org-not-done-keywords)
11621 (or (not org-agenda-tags-todo-honor-ignore-options)
11622 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
11623 (let ((case-fold-search t)) (eval matcher))
11625 (not (member org-archive-tag tags-list))
11626 ;; we have an archive tag, should we use this anyway?
11627 (or (not org-agenda-skip-archived-trees)
11628 (and (eq action 'agenda) org-agenda-archives-mode))))
11629 (unless (eq action 'sparse-tree) (org-agenda-skip))
11631 ;; select this headline
11633 (cond
11634 ((eq action 'sparse-tree)
11635 (and org-highlight-sparse-tree-matches
11636 (org-get-heading) (match-end 0)
11637 (org-highlight-new-match
11638 (match-beginning 0) (match-beginning 1)))
11639 (org-show-context 'tags-tree))
11640 ((eq action 'agenda)
11641 (setq txt (org-format-agenda-item
11643 (concat
11644 (if (eq org-tags-match-list-sublevels 'indented)
11645 (make-string (1- level) ?.) "")
11646 (org-get-heading))
11647 category
11648 tags-list
11650 priority (org-get-priority txt))
11651 (goto-char lspos)
11652 (setq marker (org-agenda-new-marker))
11653 (org-add-props txt props
11654 'org-marker marker 'org-hd-marker marker 'org-category category
11655 'todo-state todo
11656 'priority priority 'type "tagsmatch")
11657 (push txt rtn))
11658 ((functionp action)
11659 (setq org-map-continue-from nil)
11660 (save-excursion
11661 (setq rtn1 (funcall action))
11662 (push rtn1 rtn)))
11663 (t (error "Invalid action")))
11665 ;; if we are to skip sublevels, jump to end of subtree
11666 (unless org-tags-match-list-sublevels
11667 (org-end-of-subtree t)
11668 (backward-char 1))))
11669 ;; Get the correct position from where to continue
11670 (if org-map-continue-from
11671 (goto-char org-map-continue-from)
11672 (and (= (point) lspos) (end-of-line 1)))))
11673 (when (and (eq action 'sparse-tree)
11674 (not org-sparse-tree-open-archived-trees))
11675 (org-hide-archived-subtrees (point-min) (point-max)))
11676 (nreverse rtn)))
11678 (defun org-remove-uniherited-tags (tags)
11679 "Remove all tags that are not inherited from the list TAGS."
11680 (cond
11681 ((eq org-use-tag-inheritance t)
11682 (if org-tags-exclude-from-inheritance
11683 (org-delete-all org-tags-exclude-from-inheritance tags)
11684 tags))
11685 ((not org-use-tag-inheritance) nil)
11686 ((stringp org-use-tag-inheritance)
11687 (delq nil (mapcar
11688 (lambda (x)
11689 (if (and (string-match org-use-tag-inheritance x)
11690 (not (member x org-tags-exclude-from-inheritance)))
11691 x nil))
11692 tags)))
11693 ((listp org-use-tag-inheritance)
11694 (delq nil (mapcar
11695 (lambda (x)
11696 (if (member x org-use-tag-inheritance) x nil))
11697 tags)))))
11699 (defvar todo-only) ;; dynamically scoped
11701 (defun org-match-sparse-tree (&optional todo-only match)
11702 "Create a sparse tree according to tags string MATCH.
11703 MATCH can contain positive and negative selection of tags, like
11704 \"+WORK+URGENT-WITHBOSS\".
11705 If optional argument TODO-ONLY is non-nil, only select lines that are
11706 also TODO lines."
11707 (interactive "P")
11708 (org-prepare-agenda-buffers (list (current-buffer)))
11709 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
11711 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
11713 (defvar org-cached-props nil)
11714 (defun org-cached-entry-get (pom property)
11715 (if (or (eq t org-use-property-inheritance)
11716 (and (stringp org-use-property-inheritance)
11717 (string-match org-use-property-inheritance property))
11718 (and (listp org-use-property-inheritance)
11719 (member property org-use-property-inheritance)))
11720 ;; Caching is not possible, check it directly
11721 (org-entry-get pom property 'inherit)
11722 ;; Get all properties, so that we can do complicated checks easily
11723 (cdr (assoc property (or org-cached-props
11724 (setq org-cached-props
11725 (org-entry-properties pom)))))))
11727 (defun org-global-tags-completion-table (&optional files)
11728 "Return the list of all tags in all agenda buffer/files."
11729 (save-excursion
11730 (org-uniquify
11731 (delq nil
11732 (apply 'append
11733 (mapcar
11734 (lambda (file)
11735 (set-buffer (find-file-noselect file))
11736 (append (org-get-buffer-tags)
11737 (mapcar (lambda (x) (if (stringp (car-safe x))
11738 (list (car-safe x)) nil))
11739 org-tag-alist)))
11740 (if (and files (car files))
11741 files
11742 (org-agenda-files))))))))
11744 (defun org-make-tags-matcher (match)
11745 "Create the TAGS//TODO matcher form for the selection string MATCH."
11746 ;; todo-only is scoped dynamically into this function, and the function
11747 ;; may change it if the matcher asks for it.
11748 (unless match
11749 ;; Get a new match request, with completion
11750 (let ((org-last-tags-completion-table
11751 (org-global-tags-completion-table)))
11752 (setq match (org-completing-read-no-i
11753 "Match: " 'org-tags-completion-function nil nil nil
11754 'org-tags-history))))
11756 ;; Parse the string and create a lisp form
11757 (let ((match0 match)
11758 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
11759 minus tag mm
11760 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
11761 orterms term orlist re-p str-p level-p level-op time-p
11762 prop-p pn pv po cat-p gv rest)
11763 (if (string-match "/+" match)
11764 ;; match contains also a todo-matching request
11765 (progn
11766 (setq tagsmatch (substring match 0 (match-beginning 0))
11767 todomatch (substring match (match-end 0)))
11768 (if (string-match "^!" todomatch)
11769 (setq todo-only t todomatch (substring todomatch 1)))
11770 (if (string-match "^\\s-*$" todomatch)
11771 (setq todomatch nil)))
11772 ;; only matching tags
11773 (setq tagsmatch match todomatch nil))
11775 ;; Make the tags matcher
11776 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
11777 (setq tagsmatcher t)
11778 (setq orterms (org-split-string tagsmatch "|") orlist nil)
11779 (while (setq term (pop orterms))
11780 (while (and (equal (substring term -1) "\\") orterms)
11781 (setq term (concat term "|" (pop orterms)))) ; repair bad split
11782 (while (string-match re term)
11783 (setq rest (substring term (match-end 0))
11784 minus (and (match-end 1)
11785 (equal (match-string 1 term) "-"))
11786 tag (match-string 2 term)
11787 re-p (equal (string-to-char tag) ?{)
11788 level-p (match-end 4)
11789 prop-p (match-end 5)
11790 mm (cond
11791 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
11792 (level-p
11793 (setq level-op (org-op-to-function (match-string 3 term)))
11794 `(,level-op level ,(string-to-number
11795 (match-string 4 term))))
11796 (prop-p
11797 (setq pn (match-string 5 term)
11798 po (match-string 6 term)
11799 pv (match-string 7 term)
11800 cat-p (equal pn "CATEGORY")
11801 re-p (equal (string-to-char pv) ?{)
11802 str-p (equal (string-to-char pv) ?\")
11803 time-p (save-match-data
11804 (string-match "^\"[[<].*[]>]\"$" pv))
11805 pv (if (or re-p str-p) (substring pv 1 -1) pv))
11806 (if time-p (setq pv (org-matcher-time pv)))
11807 (setq po (org-op-to-function po (if time-p 'time str-p)))
11808 (cond
11809 ((equal pn "CATEGORY")
11810 (setq gv '(get-text-property (point) 'org-category)))
11811 ((equal pn "TODO")
11812 (setq gv 'todo))
11814 (setq gv `(org-cached-entry-get nil ,pn))))
11815 (if re-p
11816 (if (eq po 'org<>)
11817 `(not (string-match ,pv (or ,gv "")))
11818 `(string-match ,pv (or ,gv "")))
11819 (if str-p
11820 `(,po (or ,gv "") ,pv)
11821 `(,po (string-to-number (or ,gv ""))
11822 ,(string-to-number pv) ))))
11823 (t `(member ,tag tags-list)))
11824 mm (if minus (list 'not mm) mm)
11825 term rest)
11826 (push mm tagsmatcher))
11827 (push (if (> (length tagsmatcher) 1)
11828 (cons 'and tagsmatcher)
11829 (car tagsmatcher))
11830 orlist)
11831 (setq tagsmatcher nil))
11832 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
11833 (setq tagsmatcher
11834 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
11835 ;; Make the todo matcher
11836 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11837 (setq todomatcher t)
11838 (setq orterms (org-split-string todomatch "|") orlist nil)
11839 (while (setq term (pop orterms))
11840 (while (string-match re term)
11841 (setq minus (and (match-end 1)
11842 (equal (match-string 1 term) "-"))
11843 kwd (match-string 2 term)
11844 re-p (equal (string-to-char kwd) ?{)
11845 term (substring term (match-end 0))
11846 mm (if re-p
11847 `(string-match ,(substring kwd 1 -1) todo)
11848 (list 'equal 'todo kwd))
11849 mm (if minus (list 'not mm) mm))
11850 (push mm todomatcher))
11851 (push (if (> (length todomatcher) 1)
11852 (cons 'and todomatcher)
11853 (car todomatcher))
11854 orlist)
11855 (setq todomatcher nil))
11856 (setq todomatcher (if (> (length orlist) 1)
11857 (cons 'or orlist) (car orlist))))
11859 ;; Return the string and lisp forms of the matcher
11860 (setq matcher (if todomatcher
11861 (list 'and tagsmatcher todomatcher)
11862 tagsmatcher))
11863 (cons match0 matcher)))
11865 (defun org-op-to-function (op &optional stringp)
11866 "Turn an operator into the appropriate function."
11867 (setq op
11868 (cond
11869 ((equal op "<" ) '(< string< org-time<))
11870 ((equal op ">" ) '(> org-string> org-time>))
11871 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
11872 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
11873 ((member op '("=" "==")) '(= string= org-time=))
11874 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
11875 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
11877 (defun org<> (a b) (not (= a b)))
11878 (defun org-string<= (a b) (or (string= a b) (string< a b)))
11879 (defun org-string>= (a b) (not (string< a b)))
11880 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
11881 (defun org-string<> (a b) (not (string= a b)))
11882 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
11883 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
11884 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
11885 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
11886 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
11887 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
11888 (defun org-2ft (s)
11889 "Convert S to a floating point time.
11890 If S is already a number, just return it. If it is a string, parse
11891 it as a time string and apply `float-time' to it. If S is nil, just return 0."
11892 (cond
11893 ((numberp s) s)
11894 ((stringp s)
11895 (condition-case nil
11896 (float-time (apply 'encode-time (org-parse-time-string s)))
11897 (error 0.)))
11898 (t 0.)))
11900 (defun org-time-today ()
11901 "Time in seconds today at 0:00.
11902 Returns the float number of seconds since the beginning of the
11903 epoch to the beginning of today (00:00)."
11904 (float-time (apply 'encode-time
11905 (append '(0 0 0) (nthcdr 3 (decode-time))))))
11907 (defun org-matcher-time (s)
11908 "Interpret a time comparison value."
11909 (save-match-data
11910 (cond
11911 ((string= s "<now>") (float-time))
11912 ((string= s "<today>") (org-time-today))
11913 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
11914 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
11915 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
11916 (+ (org-time-today)
11917 (* (string-to-number (match-string 1 s))
11918 (cdr (assoc (match-string 2 s)
11919 '(("d" . 86400.0) ("w" . 604800.0)
11920 ("m" . 2678400.0) ("y" . 31557600.0)))))))
11921 (t (org-2ft s)))))
11923 (defun org-match-any-p (re list)
11924 "Does re match any element of list?"
11925 (setq list (mapcar (lambda (x) (string-match re x)) list))
11926 (delq nil list))
11928 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
11929 (defvar org-tags-overlay (org-make-overlay 1 1))
11930 (org-detach-overlay org-tags-overlay)
11932 (defun org-get-local-tags-at (&optional pos)
11933 "Get a list of tags defined in the current headline."
11934 (org-get-tags-at pos 'local))
11936 (defun org-get-local-tags ()
11937 "Get a list of tags defined in the current headline."
11938 (org-get-tags-at nil 'local))
11940 (defun org-get-tags-at (&optional pos local)
11941 "Get a list of all headline tags applicable at POS.
11942 POS defaults to point. If tags are inherited, the list contains
11943 the targets in the same sequence as the headlines appear, i.e.
11944 the tags of the current headline come last.
11945 When LOCAL is non-nil, only return tags from the current headline,
11946 ignore inherited ones."
11947 (interactive)
11948 (if (and org-trust-scanner-tags
11949 (or (not pos) (equal pos (point)))
11950 (not local))
11951 org-scanner-tags
11952 (let (tags ltags lastpos parent)
11953 (save-excursion
11954 (save-restriction
11955 (widen)
11956 (goto-char (or pos (point)))
11957 (save-match-data
11958 (catch 'done
11959 (condition-case nil
11960 (progn
11961 (org-back-to-heading t)
11962 (while (not (equal lastpos (point)))
11963 (setq lastpos (point))
11964 (when (looking-at
11965 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
11966 (setq ltags (org-split-string
11967 (org-match-string-no-properties 1) ":"))
11968 (when parent
11969 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
11970 (setq tags (append
11971 (if parent
11972 (org-remove-uniherited-tags ltags)
11973 ltags)
11974 tags)))
11975 (or org-use-tag-inheritance (throw 'done t))
11976 (if local (throw 'done t))
11977 (or (org-up-heading-safe) (error nil))
11978 (setq parent t)))
11979 (error nil)))))
11980 (append (org-remove-uniherited-tags org-file-tags) tags)))))
11982 (defun org-add-prop-inherited (s)
11983 (add-text-properties 0 (length s) '(inherited t) s)
11986 (defun org-toggle-tag (tag &optional onoff)
11987 "Toggle the tag TAG for the current line.
11988 If ONOFF is `on' or `off', don't toggle but set to this state."
11989 (let (res current)
11990 (save-excursion
11991 (org-back-to-heading t)
11992 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
11993 (point-at-eol) t)
11994 (progn
11995 (setq current (match-string 1))
11996 (replace-match ""))
11997 (setq current ""))
11998 (setq current (nreverse (org-split-string current ":")))
11999 (cond
12000 ((eq onoff 'on)
12001 (setq res t)
12002 (or (member tag current) (push tag current)))
12003 ((eq onoff 'off)
12004 (or (not (member tag current)) (setq current (delete tag current))))
12005 (t (if (member tag current)
12006 (setq current (delete tag current))
12007 (setq res t)
12008 (push tag current))))
12009 (end-of-line 1)
12010 (if current
12011 (progn
12012 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
12013 (org-set-tags nil t))
12014 (delete-horizontal-space))
12015 (run-hooks 'org-after-tags-change-hook))
12016 res))
12018 (defun org-align-tags-here (to-col)
12019 ;; Assumes that this is a headline
12020 (let ((pos (point)) (col (current-column)) ncol tags-l p)
12021 (beginning-of-line 1)
12022 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12023 (< pos (match-beginning 2)))
12024 (progn
12025 (setq tags-l (- (match-end 2) (match-beginning 2)))
12026 (goto-char (match-beginning 1))
12027 (insert " ")
12028 (delete-region (point) (1+ (match-beginning 2)))
12029 (setq ncol (max (1+ (current-column))
12030 (1+ col)
12031 (if (> to-col 0)
12032 to-col
12033 (- (abs to-col) tags-l))))
12034 (setq p (point))
12035 (insert (make-string (- ncol (current-column)) ?\ ))
12036 (setq ncol (current-column))
12037 (when indent-tabs-mode (tabify p (point-at-eol)))
12038 (org-move-to-column (min ncol col) t))
12039 (goto-char pos))))
12041 (defun org-set-tags-command (&optional arg just-align)
12042 "Call the set-tags command for the current entry."
12043 (interactive "P")
12044 (if (org-on-heading-p)
12045 (org-set-tags arg just-align)
12046 (save-excursion
12047 (org-back-to-heading t)
12048 (org-set-tags arg just-align))))
12050 (defun org-set-tags-to (data)
12051 "Set the tags of the current entry to DATA, replacing the current tags.
12052 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
12053 If DATA is nil or the empty string, any tags will be removed."
12054 (interactive "sTags: ")
12055 (setq data
12056 (cond
12057 ((eq data nil) "")
12058 ((equal data "") "")
12059 ((stringp data)
12060 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
12061 ":"))
12062 ((listp data)
12063 (concat ":" (mapconcat 'identity data ":") ":"))
12064 (t nil)))
12065 (when data
12066 (save-excursion
12067 (org-back-to-heading t)
12068 (when (looking-at org-complex-heading-regexp)
12069 (if (match-end 5)
12070 (progn
12071 (goto-char (match-beginning 5))
12072 (insert data)
12073 (delete-region (point) (point-at-eol))
12074 (org-set-tags nil 'align))
12075 (goto-char (point-at-eol))
12076 (insert " " data)
12077 (org-set-tags nil 'align)))
12078 (beginning-of-line 1)
12079 (if (looking-at ".*?\\([ \t]+\\)$")
12080 (delete-region (match-beginning 1) (match-end 1))))))
12082 (defun org-set-tags (&optional arg just-align)
12083 "Set the tags for the current headline.
12084 With prefix ARG, realign all tags in headings in the current buffer."
12085 (interactive "P")
12086 (let* ((re (concat "^" outline-regexp))
12087 (current (org-get-tags-string))
12088 (col (current-column))
12089 (org-setting-tags t)
12090 table current-tags inherited-tags ; computed below when needed
12091 tags p0 c0 c1 rpl)
12092 (if arg
12093 (save-excursion
12094 (goto-char (point-min))
12095 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
12096 (while (re-search-forward re nil t)
12097 (org-set-tags nil t)
12098 (end-of-line 1)))
12099 (message "All tags realigned to column %d" org-tags-column))
12100 (if just-align
12101 (setq tags current)
12102 ;; Get a new set of tags from the user
12103 (save-excursion
12104 (setq table (append org-tag-persistent-alist
12105 (or org-tag-alist (org-get-buffer-tags))
12106 (and org-complete-tags-always-offer-all-agenda-tags
12107 (org-global-tags-completion-table (org-agenda-files))))
12108 org-last-tags-completion-table table
12109 current-tags (org-split-string current ":")
12110 inherited-tags (nreverse
12111 (nthcdr (length current-tags)
12112 (nreverse (org-get-tags-at))))
12113 tags
12114 (if (or (eq t org-use-fast-tag-selection)
12115 (and org-use-fast-tag-selection
12116 (delq nil (mapcar 'cdr table))))
12117 (org-fast-tag-selection
12118 current-tags inherited-tags table
12119 (if org-fast-tag-selection-include-todo org-todo-key-alist))
12120 (let ((org-add-colon-after-tag-completion t))
12121 (org-trim
12122 (org-without-partial-completion
12123 (org-icompleting-read "Tags: " 'org-tags-completion-function
12124 nil nil current 'org-tags-history)))))))
12125 (while (string-match "[-+&]+" tags)
12126 ;; No boolean logic, just a list
12127 (setq tags (replace-match ":" t t tags))))
12129 (if org-tags-sort-function
12130 (setq tags (mapconcat 'identity
12131 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
12132 org-tags-sort-function) ":")))
12134 (if (string-match "\\`[\t ]*\\'" tags)
12135 (setq tags "")
12136 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
12137 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
12139 ;; Insert new tags at the correct column
12140 (beginning-of-line 1)
12141 (cond
12142 ((and (equal current "") (equal tags "")))
12143 ((re-search-forward
12144 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
12145 (point-at-eol) t)
12146 (if (equal tags "")
12147 (setq rpl "")
12148 (goto-char (match-beginning 0))
12149 (setq c0 (current-column) p0 (if (equal (char-before) ?*)
12150 (1+ (point)) (point))
12151 c1 (max (1+ c0) (if (> org-tags-column 0)
12152 org-tags-column
12153 (- (- org-tags-column) (length tags))))
12154 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
12155 (replace-match rpl t t)
12156 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
12157 tags)
12158 (t (error "Tags alignment failed")))
12159 (org-move-to-column col)
12160 (unless just-align
12161 (run-hooks 'org-after-tags-change-hook)))))
12163 (defun org-change-tag-in-region (beg end tag off)
12164 "Add or remove TAG for each entry in the region.
12165 This works in the agenda, and also in an org-mode buffer."
12166 (interactive
12167 (list (region-beginning) (region-end)
12168 (let ((org-last-tags-completion-table
12169 (if (org-mode-p)
12170 (org-get-buffer-tags)
12171 (org-global-tags-completion-table))))
12172 (org-icompleting-read
12173 "Tag: " 'org-tags-completion-function nil nil nil
12174 'org-tags-history))
12175 (progn
12176 (message "[s]et or [r]emove? ")
12177 (equal (read-char-exclusive) ?r))))
12178 (if (fboundp 'deactivate-mark) (deactivate-mark))
12179 (let ((agendap (equal major-mode 'org-agenda-mode))
12180 l1 l2 m buf pos newhead (cnt 0))
12181 (goto-char end)
12182 (setq l2 (1- (org-current-line)))
12183 (goto-char beg)
12184 (setq l1 (org-current-line))
12185 (loop for l from l1 to l2 do
12186 (org-goto-line l)
12187 (setq m (get-text-property (point) 'org-hd-marker))
12188 (when (or (and (org-mode-p) (org-on-heading-p))
12189 (and agendap m))
12190 (setq buf (if agendap (marker-buffer m) (current-buffer))
12191 pos (if agendap m (point)))
12192 (with-current-buffer buf
12193 (save-excursion
12194 (save-restriction
12195 (goto-char pos)
12196 (setq cnt (1+ cnt))
12197 (org-toggle-tag tag (if off 'off 'on))
12198 (setq newhead (org-get-heading)))))
12199 (and agendap (org-agenda-change-all-lines newhead m))))
12200 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
12202 (defun org-tags-completion-function (string predicate &optional flag)
12203 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
12204 (confirm (lambda (x) (stringp (car x)))))
12205 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
12206 (setq s1 (match-string 1 string)
12207 s2 (match-string 2 string))
12208 (setq s1 "" s2 string))
12209 (cond
12210 ((eq flag nil)
12211 ;; try completion
12212 (setq rtn (try-completion s2 ctable confirm))
12213 (if (stringp rtn)
12214 (setq rtn
12215 (concat s1 s2 (substring rtn (length s2))
12216 (if (and org-add-colon-after-tag-completion
12217 (assoc rtn ctable))
12218 ":" ""))))
12219 rtn)
12220 ((eq flag t)
12221 ;; all-completions
12222 (all-completions s2 ctable confirm)
12224 ((eq flag 'lambda)
12225 ;; exact match?
12226 (assoc s2 ctable)))
12229 (defun org-fast-tag-insert (kwd tags face &optional end)
12230 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
12231 (insert (format "%-12s" (concat kwd ":"))
12232 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
12233 (or end "")))
12235 (defun org-fast-tag-show-exit (flag)
12236 (save-excursion
12237 (org-goto-line 3)
12238 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
12239 (replace-match ""))
12240 (when flag
12241 (end-of-line 1)
12242 (org-move-to-column (- (window-width) 19) t)
12243 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
12245 (defun org-set-current-tags-overlay (current prefix)
12246 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
12247 (if (featurep 'xemacs)
12248 (org-overlay-display org-tags-overlay (concat prefix s)
12249 'secondary-selection)
12250 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
12251 (org-overlay-display org-tags-overlay (concat prefix s)))))
12253 (defvar org-last-tag-selection-key nil)
12254 (defun org-fast-tag-selection (current inherited table &optional todo-table)
12255 "Fast tag selection with single keys.
12256 CURRENT is the current list of tags in the headline, INHERITED is the
12257 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
12258 possibly with grouping information. TODO-TABLE is a similar table with
12259 TODO keywords, should these have keys assigned to them.
12260 If the keys are nil, a-z are automatically assigned.
12261 Returns the new tags string, or nil to not change the current settings."
12262 (let* ((fulltable (append table todo-table))
12263 (maxlen (apply 'max (mapcar
12264 (lambda (x)
12265 (if (stringp (car x)) (string-width (car x)) 0))
12266 fulltable)))
12267 (buf (current-buffer))
12268 (expert (eq org-fast-tag-selection-single-key 'expert))
12269 (buffer-tags nil)
12270 (fwidth (+ maxlen 3 1 3))
12271 (ncol (/ (- (window-width) 4) fwidth))
12272 (i-face 'org-done)
12273 (c-face 'org-todo)
12274 tg cnt e c char c1 c2 ntable tbl rtn
12275 ov-start ov-end ov-prefix
12276 (exit-after-next org-fast-tag-selection-single-key)
12277 (done-keywords org-done-keywords)
12278 groups ingroup)
12279 (save-excursion
12280 (beginning-of-line 1)
12281 (if (looking-at
12282 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12283 (setq ov-start (match-beginning 1)
12284 ov-end (match-end 1)
12285 ov-prefix "")
12286 (setq ov-start (1- (point-at-eol))
12287 ov-end (1+ ov-start))
12288 (skip-chars-forward "^\n\r")
12289 (setq ov-prefix
12290 (concat
12291 (buffer-substring (1- (point)) (point))
12292 (if (> (current-column) org-tags-column)
12294 (make-string (- org-tags-column (current-column)) ?\ ))))))
12295 (org-move-overlay org-tags-overlay ov-start ov-end)
12296 (save-window-excursion
12297 (if expert
12298 (set-buffer (get-buffer-create " *Org tags*"))
12299 (delete-other-windows)
12300 (split-window-vertically)
12301 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
12302 (erase-buffer)
12303 (org-set-local 'org-done-keywords done-keywords)
12304 (org-fast-tag-insert "Inherited" inherited i-face "\n")
12305 (org-fast-tag-insert "Current" current c-face "\n\n")
12306 (org-fast-tag-show-exit exit-after-next)
12307 (org-set-current-tags-overlay current ov-prefix)
12308 (setq tbl fulltable char ?a cnt 0)
12309 (while (setq e (pop tbl))
12310 (cond
12311 ((equal (car e) :startgroup)
12312 (push '() groups) (setq ingroup t)
12313 (when (not (= cnt 0))
12314 (setq cnt 0)
12315 (insert "\n"))
12316 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
12317 ((equal (car e) :endgroup)
12318 (setq ingroup nil cnt 0)
12319 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
12320 ((equal e '(:newline))
12321 (when (not (= cnt 0))
12322 (setq cnt 0)
12323 (insert "\n")
12324 (setq e (car tbl))
12325 (while (equal (car tbl) '(:newline))
12326 (insert "\n")
12327 (setq tbl (cdr tbl)))))
12329 (setq tg (copy-sequence (car e)) c2 nil)
12330 (if (cdr e)
12331 (setq c (cdr e))
12332 ;; automatically assign a character.
12333 (setq c1 (string-to-char
12334 (downcase (substring
12335 tg (if (= (string-to-char tg) ?@) 1 0)))))
12336 (if (or (rassoc c1 ntable) (rassoc c1 table))
12337 (while (or (rassoc char ntable) (rassoc char table))
12338 (setq char (1+ char)))
12339 (setq c2 c1))
12340 (setq c (or c2 char)))
12341 (if ingroup (push tg (car groups)))
12342 (setq tg (org-add-props tg nil 'face
12343 (cond
12344 ((not (assoc tg table))
12345 (org-get-todo-face tg))
12346 ((member tg current) c-face)
12347 ((member tg inherited) i-face)
12348 (t nil))))
12349 (if (and (= cnt 0) (not ingroup)) (insert " "))
12350 (insert "[" c "] " tg (make-string
12351 (- fwidth 4 (length tg)) ?\ ))
12352 (push (cons tg c) ntable)
12353 (when (= (setq cnt (1+ cnt)) ncol)
12354 (insert "\n")
12355 (if ingroup (insert " "))
12356 (setq cnt 0)))))
12357 (setq ntable (nreverse ntable))
12358 (insert "\n")
12359 (goto-char (point-min))
12360 (if (not expert) (org-fit-window-to-buffer))
12361 (setq rtn
12362 (catch 'exit
12363 (while t
12364 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
12365 (if (not groups) "no " "")
12366 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
12367 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12368 (setq org-last-tag-selection-key c)
12369 (cond
12370 ((= c ?\r) (throw 'exit t))
12371 ((= c ?!)
12372 (setq groups (not groups))
12373 (goto-char (point-min))
12374 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
12375 ((= c ?\C-c)
12376 (if (not expert)
12377 (org-fast-tag-show-exit
12378 (setq exit-after-next (not exit-after-next)))
12379 (setq expert nil)
12380 (delete-other-windows)
12381 (split-window-vertically)
12382 (org-switch-to-buffer-other-window " *Org tags*")
12383 (org-fit-window-to-buffer)))
12384 ((or (= c ?\C-g)
12385 (and (= c ?q) (not (rassoc c ntable))))
12386 (org-detach-overlay org-tags-overlay)
12387 (setq quit-flag t))
12388 ((= c ?\ )
12389 (setq current nil)
12390 (if exit-after-next (setq exit-after-next 'now)))
12391 ((= c ?\t)
12392 (condition-case nil
12393 (setq tg (org-icompleting-read
12394 "Tag: "
12395 (or buffer-tags
12396 (with-current-buffer buf
12397 (org-get-buffer-tags)))))
12398 (quit (setq tg "")))
12399 (when (string-match "\\S-" tg)
12400 (add-to-list 'buffer-tags (list tg))
12401 (if (member tg current)
12402 (setq current (delete tg current))
12403 (push tg current)))
12404 (if exit-after-next (setq exit-after-next 'now)))
12405 ((setq e (rassoc c todo-table) tg (car e))
12406 (with-current-buffer buf
12407 (save-excursion (org-todo tg)))
12408 (if exit-after-next (setq exit-after-next 'now)))
12409 ((setq e (rassoc c ntable) tg (car e))
12410 (if (member tg current)
12411 (setq current (delete tg current))
12412 (loop for g in groups do
12413 (if (member tg g)
12414 (mapc (lambda (x)
12415 (setq current (delete x current)))
12416 g)))
12417 (push tg current))
12418 (if exit-after-next (setq exit-after-next 'now))))
12420 ;; Create a sorted list
12421 (setq current
12422 (sort current
12423 (lambda (a b)
12424 (assoc b (cdr (memq (assoc a ntable) ntable))))))
12425 (if (eq exit-after-next 'now) (throw 'exit t))
12426 (goto-char (point-min))
12427 (beginning-of-line 2)
12428 (delete-region (point) (point-at-eol))
12429 (org-fast-tag-insert "Current" current c-face)
12430 (org-set-current-tags-overlay current ov-prefix)
12431 (while (re-search-forward
12432 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
12433 (setq tg (match-string 1))
12434 (add-text-properties
12435 (match-beginning 1) (match-end 1)
12436 (list 'face
12437 (cond
12438 ((member tg current) c-face)
12439 ((member tg inherited) i-face)
12440 (t (get-text-property (match-beginning 1) 'face))))))
12441 (goto-char (point-min)))))
12442 (org-detach-overlay org-tags-overlay)
12443 (if rtn
12444 (mapconcat 'identity current ":")
12445 nil))))
12447 (defun org-get-tags-string ()
12448 "Get the TAGS string in the current headline."
12449 (unless (org-on-heading-p t)
12450 (error "Not on a heading"))
12451 (save-excursion
12452 (beginning-of-line 1)
12453 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12454 (org-match-string-no-properties 1)
12455 "")))
12457 (defun org-get-tags ()
12458 "Get the list of tags specified in the current headline."
12459 (org-split-string (org-get-tags-string) ":"))
12461 (defun org-get-buffer-tags ()
12462 "Get a table of all tags used in the buffer, for completion."
12463 (let (tags)
12464 (save-excursion
12465 (goto-char (point-min))
12466 (while (re-search-forward
12467 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
12468 (when (equal (char-after (point-at-bol 0)) ?*)
12469 (mapc (lambda (x) (add-to-list 'tags x))
12470 (org-split-string (org-match-string-no-properties 1) ":")))))
12471 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
12472 (mapcar 'list tags)))
12474 ;;;; The mapping API
12476 ;;;###autoload
12477 (defun org-map-entries (func &optional match scope &rest skip)
12478 "Call FUNC at each headline selected by MATCH in SCOPE.
12480 FUNC is a function or a lisp form. The function will be called without
12481 arguments, with the cursor positioned at the beginning of the headline.
12482 The return values of all calls to the function will be collected and
12483 returned as a list.
12485 The call to FUNC will be wrapped into a save-excursion form, so FUNC
12486 does not need to preserve point. After evaluation, the cursor will be
12487 moved to the end of the line (presumably of the headline of the
12488 processed entry) and search continues from there. Under some
12489 circumstances, this may not produce the wanted results. For example,
12490 if you have removed (e.g. archived) the current (sub)tree it could
12491 mean that the next entry will be skipped entirely. In such cases, you
12492 can specify the position from where search should continue by making
12493 FUNC set the variable `org-map-continue-from' to the desired buffer
12494 position.
12496 MATCH is a tags/property/todo match as it is used in the agenda tags view.
12497 Only headlines that are matched by this query will be considered during
12498 the iteration. When MATCH is nil or t, all headlines will be
12499 visited by the iteration.
12501 SCOPE determines the scope of this command. It can be any of:
12503 nil The current buffer, respecting the restriction if any
12504 tree The subtree started with the entry at point
12505 file The current buffer, without restriction
12506 file-with-archives
12507 The current buffer, and any archives associated with it
12508 agenda All agenda files
12509 agenda-with-archives
12510 All agenda files with any archive files associated with them
12511 \(file1 file2 ...)
12512 If this is a list, all files in the list will be scanned
12514 The remaining args are treated as settings for the skipping facilities of
12515 the scanner. The following items can be given here:
12517 archive skip trees with the archive tag.
12518 comment skip trees with the COMMENT keyword
12519 function or Emacs Lisp form:
12520 will be used as value for `org-agenda-skip-function', so whenever
12521 the function returns t, FUNC will not be called for that
12522 entry and search will continue from the point where the
12523 function leaves it.
12525 If your function needs to retrieve the tags including inherited tags
12526 at the *current* entry, you can use the value of the variable
12527 `org-scanner-tags' which will be much faster than getting the value
12528 with `org-get-tags-at'. If your function gets properties with
12529 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
12530 to t around the call to `org-entry-properties' to get the same speedup.
12531 Note that if your function moves around to retrieve tags and properties at
12532 a *different* entry, you cannot use these techniques."
12533 (let* ((org-agenda-archives-mode nil) ; just to make sure
12534 (org-agenda-skip-archived-trees (memq 'archive skip))
12535 (org-agenda-skip-comment-trees (memq 'comment skip))
12536 (org-agenda-skip-function
12537 (car (org-delete-all '(comment archive) skip)))
12538 (org-tags-match-list-sublevels t)
12539 matcher file res
12540 org-todo-keywords-for-agenda
12541 org-done-keywords-for-agenda
12542 org-todo-keyword-alist-for-agenda
12543 org-drawers-for-agenda
12544 org-tag-alist-for-agenda)
12546 (cond
12547 ((eq match t) (setq matcher t))
12548 ((eq match nil) (setq matcher t))
12549 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
12551 (save-excursion
12552 (save-restriction
12553 (when (eq scope 'tree)
12554 (org-back-to-heading t)
12555 (org-narrow-to-subtree)
12556 (setq scope nil))
12558 (if (not scope)
12559 (progn
12560 (org-prepare-agenda-buffers
12561 (list (buffer-file-name (current-buffer))))
12562 (setq res (org-scan-tags func matcher)))
12563 ;; Get the right scope
12564 (cond
12565 ((and scope (listp scope) (symbolp (car scope)))
12566 (setq scope (eval scope)))
12567 ((eq scope 'agenda)
12568 (setq scope (org-agenda-files t)))
12569 ((eq scope 'agenda-with-archives)
12570 (setq scope (org-agenda-files t))
12571 (setq scope (org-add-archive-files scope)))
12572 ((eq scope 'file)
12573 (setq scope (list (buffer-file-name))))
12574 ((eq scope 'file-with-archives)
12575 (setq scope (org-add-archive-files (list (buffer-file-name))))))
12576 (org-prepare-agenda-buffers scope)
12577 (while (setq file (pop scope))
12578 (with-current-buffer (org-find-base-buffer-visiting file)
12579 (save-excursion
12580 (save-restriction
12581 (widen)
12582 (goto-char (point-min))
12583 (setq res (append res (org-scan-tags func matcher))))))))))
12584 res))
12586 ;;;; Properties
12588 ;;; Setting and retrieving properties
12590 (defconst org-special-properties
12591 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
12592 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED")
12593 "The special properties valid in Org-mode.
12595 These are properties that are not defined in the property drawer,
12596 but in some other way.")
12598 (defconst org-default-properties
12599 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
12600 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
12601 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
12602 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
12603 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
12604 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
12605 "Some properties that are used by Org-mode for various purposes.
12606 Being in this list makes sure that they are offered for completion.")
12608 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
12609 "Regular expression matching the first line of a property drawer.")
12611 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
12612 "Regular expression matching the last line of a property drawer.")
12614 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
12615 "Regular expression matching the first line of a property drawer.")
12617 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
12618 "Regular expression matching the first line of a property drawer.")
12620 (defconst org-property-drawer-re
12621 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
12622 org-property-end-re "\\)\n?")
12623 "Matches an entire property drawer.")
12625 (defconst org-clock-drawer-re
12626 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
12627 org-property-end-re "\\)\n?")
12628 "Matches an entire clock drawer.")
12630 (defun org-property-action ()
12631 "Do an action on properties."
12632 (interactive)
12633 (let (c)
12634 (org-at-property-p)
12635 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
12636 (setq c (read-char-exclusive))
12637 (cond
12638 ((equal c ?s)
12639 (call-interactively 'org-set-property))
12640 ((equal c ?d)
12641 (call-interactively 'org-delete-property))
12642 ((equal c ?D)
12643 (call-interactively 'org-delete-property-globally))
12644 ((equal c ?c)
12645 (call-interactively 'org-compute-property-at-point))
12646 (t (error "No such property action %c" c)))))
12648 (defun org-set-effort (&optional value)
12649 "Set the effort property of the current entry.
12650 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
12651 allowed value."
12652 (interactive "P")
12653 (if (equal value 0) (setq value 10))
12654 (let* ((completion-ignore-case t)
12655 (prop org-effort-property)
12656 (cur (org-entry-get nil prop))
12657 (allowed (org-property-get-allowed-values nil prop 'table))
12658 (existing (mapcar 'list (org-property-values prop)))
12660 (val (cond
12661 ((stringp value) value)
12662 ((and allowed (integerp value))
12663 (or (car (nth (1- value) allowed))
12664 (car (org-last allowed))))
12665 (allowed
12666 (message "Select 1-9,0, [RET%s]: %s"
12667 (if cur (concat "=" cur) "")
12668 (mapconcat 'car allowed " "))
12669 (setq rpl (read-char-exclusive))
12670 (if (equal rpl ?\r)
12672 (setq rpl (- rpl ?0))
12673 (if (equal rpl 0) (setq rpl 10))
12674 (if (and (> rpl 0) (<= rpl (length allowed)))
12675 (car (nth (1- rpl) allowed))
12676 (org-completing-read "Effort: " allowed nil))))
12678 (let (org-completion-use-ido org-completion-use-iswitchb)
12679 (org-completing-read
12680 (concat "Effort " (if (and cur (string-match "\\S-" cur))
12681 (concat "[" cur "]") "")
12682 ": ")
12683 existing nil nil "" nil cur))))))
12684 (unless (equal (org-entry-get nil prop) val)
12685 (org-entry-put nil prop val))
12686 (message "%s is now %s" prop val)))
12688 (defun org-at-property-p ()
12689 "Is cursor inside a property drawer?"
12690 (save-excursion
12691 (beginning-of-line 1)
12692 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
12693 (let ((match (match-data)) ;; Keep match-data for use by calling
12694 (p (point)) ;; procedures.
12695 (range (unless (org-before-first-heading-p)
12696 (org-get-property-block))))
12697 (prog1 (and range (<= (car range) p) (< p (cdr range)))
12698 (set-match-data match))))))
12700 (defun org-get-property-block (&optional beg end force)
12701 "Return the (beg . end) range of the body of the property drawer.
12702 BEG and END can be beginning and end of subtree, if not given
12703 they will be found.
12704 If the drawer does not exist and FORCE is non-nil, create the drawer."
12705 (catch 'exit
12706 (save-excursion
12707 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
12708 (end (or end (progn (outline-next-heading) (point)))))
12709 (goto-char beg)
12710 (if (re-search-forward org-property-start-re end t)
12711 (setq beg (1+ (match-end 0)))
12712 (if force
12713 (save-excursion
12714 (org-insert-property-drawer)
12715 (setq end (progn (outline-next-heading) (point))))
12716 (throw 'exit nil))
12717 (goto-char beg)
12718 (if (re-search-forward org-property-start-re end t)
12719 (setq beg (1+ (match-end 0)))))
12720 (if (re-search-forward org-property-end-re end t)
12721 (setq end (match-beginning 0))
12722 (or force (throw 'exit nil))
12723 (goto-char beg)
12724 (setq end beg)
12725 (org-indent-line-function)
12726 (insert ":END:\n"))
12727 (cons beg end)))))
12729 (defun org-entry-properties (&optional pom which specific)
12730 "Get all properties of the entry at point-or-marker POM.
12731 This includes the TODO keyword, the tags, time strings for deadline,
12732 scheduled, and clocking, and any additional properties defined in the
12733 entry. The return value is an alist, keys may occur multiple times
12734 if the property key was used several times.
12735 POM may also be nil, in which case the current entry is used.
12736 If WHICH is nil or `all', get all properties. If WHICH is
12737 `special' or `standard', only get that subclass. If WHICH
12738 is a string only get exactly this property. Specific can be a string, the
12739 specific property we are interested in. Specifying it can speed
12740 things up because then unnecessary parsing is avoided."
12741 (setq which (or which 'all))
12742 (org-with-point-at pom
12743 (let ((clockstr (substring org-clock-string 0 -1))
12744 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
12745 (case-fold-search nil)
12746 beg end range props sum-props key value string clocksum)
12747 (save-excursion
12748 (when (condition-case nil
12749 (and (org-mode-p) (org-back-to-heading t))
12750 (error nil))
12751 (setq beg (point))
12752 (setq sum-props (get-text-property (point) 'org-summaries))
12753 (setq clocksum (get-text-property (point) :org-clock-minutes))
12754 (outline-next-heading)
12755 (setq end (point))
12756 (when (memq which '(all special))
12757 ;; Get the special properties, like TODO and tags
12758 (goto-char beg)
12759 (when (and (or (not specific) (string= specific "TODO"))
12760 (looking-at org-todo-line-regexp) (match-end 2))
12761 (push (cons "TODO" (org-match-string-no-properties 2)) props))
12762 (when (and (or (not specific) (string= specific "PRIORITY"))
12763 (looking-at org-priority-regexp))
12764 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
12765 (when (and (or (not specific) (string= specific "TAGS"))
12766 (setq value (org-get-tags-string))
12767 (string-match "\\S-" value))
12768 (push (cons "TAGS" value) props))
12769 (when (and (or (not specific) (string= specific "ALLTAGS"))
12770 (setq value (org-get-tags-at)))
12771 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
12772 ":"))
12773 props))
12774 (when (or (not specific) (string= specific "BLOCKED"))
12775 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
12776 (when (or (not specific)
12777 (member specific org-all-time-keywords)
12778 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
12779 (while (re-search-forward org-maybe-keyword-time-regexp end t)
12780 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
12781 string (if (equal key clockstr)
12782 (org-no-properties
12783 (org-trim
12784 (buffer-substring
12785 (match-beginning 3) (goto-char (point-at-eol)))))
12786 (substring (org-match-string-no-properties 3) 1 -1)))
12787 (unless key
12788 (if (= (char-after (match-beginning 3)) ?\[)
12789 (setq key "TIMESTAMP_IA")
12790 (setq key "TIMESTAMP")))
12791 (when (or (equal key clockstr) (not (assoc key props)))
12792 (push (cons key string) props))))
12796 (when (memq which '(all standard))
12797 ;; Get the standard properties, like :PROP: ...
12798 (setq range (org-get-property-block beg end))
12799 (when range
12800 (goto-char (car range))
12801 (while (re-search-forward
12802 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
12803 (cdr range) t)
12804 (setq key (org-match-string-no-properties 1)
12805 value (org-trim (or (org-match-string-no-properties 2) "")))
12806 (unless (member key excluded)
12807 (push (cons key (or value "")) props)))))
12808 (if clocksum
12809 (push (cons "CLOCKSUM"
12810 (org-columns-number-to-string (/ (float clocksum) 60.)
12811 'add_times))
12812 props))
12813 (unless (assoc "CATEGORY" props)
12814 (setq value (or (org-get-category)
12815 (progn (org-refresh-category-properties)
12816 (org-get-category))))
12817 (push (cons "CATEGORY" value) props))
12818 (append sum-props (nreverse props)))))))
12820 (defun org-entry-get (pom property &optional inherit)
12821 "Get value of PROPERTY for entry at point-or-marker POM.
12822 If INHERIT is non-nil and the entry does not have the property,
12823 then also check higher levels of the hierarchy.
12824 If INHERIT is the symbol `selective', use inheritance only if the setting
12825 in `org-use-property-inheritance' selects PROPERTY for inheritance.
12826 If the property is present but empty, the return value is the empty string.
12827 If the property is not present at all, nil is returned."
12828 (org-with-point-at pom
12829 (if (and inherit (if (eq inherit 'selective)
12830 (org-property-inherit-p property)
12832 (org-entry-get-with-inheritance property)
12833 (if (member property org-special-properties)
12834 ;; We need a special property. Use `org-entry-properties' to
12835 ;; retrieve it, but specify the wanted property
12836 (cdr (assoc property (org-entry-properties nil 'special property)))
12837 (let ((range (org-get-property-block)))
12838 (if (and range
12839 (goto-char (car range))
12840 (re-search-forward
12841 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
12842 (cdr range) t))
12843 ;; Found the property, return it.
12844 (if (match-end 1)
12845 (org-match-string-no-properties 1)
12846 "")))))))
12848 (defun org-property-or-variable-value (var &optional inherit)
12849 "Check if there is a property fixing the value of VAR.
12850 If yes, return this value. If not, return the current value of the variable."
12851 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
12852 (if (and prop (stringp prop) (string-match "\\S-" prop))
12853 (read prop)
12854 (symbol-value var))))
12856 (defun org-entry-delete (pom property)
12857 "Delete the property PROPERTY from entry at point-or-marker POM."
12858 (org-with-point-at pom
12859 (if (member property org-special-properties)
12860 nil ; cannot delete these properties.
12861 (let ((range (org-get-property-block)))
12862 (if (and range
12863 (goto-char (car range))
12864 (re-search-forward
12865 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
12866 (cdr range) t))
12867 (progn
12868 (delete-region (match-beginning 0) (1+ (point-at-eol)))
12870 nil)))))
12872 ;; Multi-values properties are properties that contain multiple values
12873 ;; These values are assumed to be single words, separated by whitespace.
12874 (defun org-entry-add-to-multivalued-property (pom property value)
12875 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
12876 (let* ((old (org-entry-get pom property))
12877 (values (and old (org-split-string old "[ \t]"))))
12878 (setq value (org-entry-protect-space value))
12879 (unless (member value values)
12880 (setq values (cons value values))
12881 (org-entry-put pom property
12882 (mapconcat 'identity values " ")))))
12884 (defun org-entry-remove-from-multivalued-property (pom property value)
12885 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
12886 (let* ((old (org-entry-get pom property))
12887 (values (and old (org-split-string old "[ \t]"))))
12888 (setq value (org-entry-protect-space value))
12889 (when (member value values)
12890 (setq values (delete value values))
12891 (org-entry-put pom property
12892 (mapconcat 'identity values " ")))))
12894 (defun org-entry-member-in-multivalued-property (pom property value)
12895 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
12896 (let* ((old (org-entry-get pom property))
12897 (values (and old (org-split-string old "[ \t]"))))
12898 (setq value (org-entry-protect-space value))
12899 (member value values)))
12901 (defun org-entry-get-multivalued-property (pom property)
12902 "Return a list of values in a multivalued property."
12903 (let* ((value (org-entry-get pom property))
12904 (values (and value (org-split-string value "[ \t]"))))
12905 (mapcar 'org-entry-restore-space values)))
12907 (defun org-entry-put-multivalued-property (pom property &rest values)
12908 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
12909 VALUES should be a list of strings. Spaces will be protected."
12910 (org-entry-put pom property
12911 (mapconcat 'org-entry-protect-space values " "))
12912 (let* ((value (org-entry-get pom property))
12913 (values (and value (org-split-string value "[ \t]"))))
12914 (mapcar 'org-entry-restore-space values)))
12916 (defun org-entry-protect-space (s)
12917 "Protect spaces and newline in string S."
12918 (while (string-match " " s)
12919 (setq s (replace-match "%20" t t s)))
12920 (while (string-match "\n" s)
12921 (setq s (replace-match "%0A" t t s)))
12924 (defun org-entry-restore-space (s)
12925 "Restore spaces and newline in string S."
12926 (while (string-match "%20" s)
12927 (setq s (replace-match " " t t s)))
12928 (while (string-match "%0A" s)
12929 (setq s (replace-match "\n" t t s)))
12932 (defvar org-entry-property-inherited-from (make-marker)
12933 "Marker pointing to the entry from where a property was inherited.
12934 Each call to `org-entry-get-with-inheritance' will set this marker to the
12935 location of the entry where the inheritance search matched. If there was
12936 no match, the marker will point nowhere.
12937 Note that also `org-entry-get' calls this function, if the INHERIT flag
12938 is set.")
12940 (defun org-entry-get-with-inheritance (property)
12941 "Get entry property, and search higher levels if not present."
12942 (move-marker org-entry-property-inherited-from nil)
12943 (let (tmp)
12944 (save-excursion
12945 (save-restriction
12946 (widen)
12947 (catch 'ex
12948 (while t
12949 (when (setq tmp (org-entry-get nil property))
12950 (org-back-to-heading t)
12951 (move-marker org-entry-property-inherited-from (point))
12952 (throw 'ex tmp))
12953 (or (org-up-heading-safe) (throw 'ex nil)))))
12954 (or tmp
12955 (cdr (assoc property org-file-properties))
12956 (cdr (assoc property org-global-properties))
12957 (cdr (assoc property org-global-properties-fixed))))))
12959 (defvar org-property-changed-functions nil
12960 "Hook called when the value of a property has changed.
12961 Each hook function should accept two arguments, the name of the property
12962 and the new value.")
12964 (defun org-entry-put (pom property value)
12965 "Set PROPERTY to VALUE for entry at point-or-marker POM."
12966 (org-with-point-at pom
12967 (org-back-to-heading t)
12968 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
12969 range)
12970 (cond
12971 ((equal property "TODO")
12972 (when (and (stringp value) (string-match "\\S-" value)
12973 (not (member value org-todo-keywords-1)))
12974 (error "\"%s\" is not a valid TODO state" value))
12975 (if (or (not value)
12976 (not (string-match "\\S-" value)))
12977 (setq value 'none))
12978 (org-todo value)
12979 (org-set-tags nil 'align))
12980 ((equal property "PRIORITY")
12981 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
12982 (string-to-char value) ?\ ))
12983 (org-set-tags nil 'align))
12984 ((equal property "SCHEDULED")
12985 (if (re-search-forward org-scheduled-time-regexp end t)
12986 (cond
12987 ((eq value 'earlier) (org-timestamp-change -1 'day))
12988 ((eq value 'later) (org-timestamp-change 1 'day))
12989 (t (call-interactively 'org-schedule)))
12990 (call-interactively 'org-schedule)))
12991 ((equal property "DEADLINE")
12992 (if (re-search-forward org-deadline-time-regexp end t)
12993 (cond
12994 ((eq value 'earlier) (org-timestamp-change -1 'day))
12995 ((eq value 'later) (org-timestamp-change 1 'day))
12996 (t (call-interactively 'org-deadline)))
12997 (call-interactively 'org-deadline)))
12998 ((member property org-special-properties)
12999 (error "The %s property can not yet be set with `org-entry-put'"
13000 property))
13001 (t ; a non-special property
13002 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
13003 (setq range (org-get-property-block beg end 'force))
13004 (goto-char (car range))
13005 (if (re-search-forward
13006 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
13007 (progn
13008 (delete-region (match-beginning 1) (match-end 1))
13009 (goto-char (match-beginning 1)))
13010 (goto-char (cdr range))
13011 (insert "\n")
13012 (backward-char 1)
13013 (org-indent-line-function)
13014 (insert ":" property ":"))
13015 (and value (insert " " value))
13016 (org-indent-line-function)))))
13017 (run-hook-with-args 'org-property-changed-functions property value)))
13019 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
13020 "Get all property keys in the current buffer.
13021 With INCLUDE-SPECIALS, also list the special properties that reflect things
13022 like tags and TODO state.
13023 With INCLUDE-DEFAULTS, also include properties that has special meaning
13024 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
13025 With INCLUDE-COLUMNS, also include property names given in COLUMN
13026 formats in the current buffer."
13027 (let (rtn range cfmt s p)
13028 (save-excursion
13029 (save-restriction
13030 (widen)
13031 (goto-char (point-min))
13032 (while (re-search-forward org-property-start-re nil t)
13033 (setq range (org-get-property-block))
13034 (goto-char (car range))
13035 (while (re-search-forward
13036 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
13037 (cdr range) t)
13038 (add-to-list 'rtn (org-match-string-no-properties 1)))
13039 (outline-next-heading))))
13041 (when include-specials
13042 (setq rtn (append org-special-properties rtn)))
13044 (when include-defaults
13045 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
13046 (add-to-list 'rtn org-effort-property))
13048 (when include-columns
13049 (save-excursion
13050 (save-restriction
13051 (widen)
13052 (goto-char (point-min))
13053 (while (re-search-forward
13054 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
13055 nil t)
13056 (setq cfmt (match-string 2) s 0)
13057 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
13058 cfmt s)
13059 (setq s (match-end 0)
13060 p (match-string 1 cfmt))
13061 (unless (or (equal p "ITEM")
13062 (member p org-special-properties))
13063 (add-to-list 'rtn (match-string 1 cfmt))))))))
13065 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
13067 (defun org-property-values (key)
13068 "Return a list of all values of property KEY."
13069 (save-excursion
13070 (save-restriction
13071 (widen)
13072 (goto-char (point-min))
13073 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
13074 values)
13075 (while (re-search-forward re nil t)
13076 (add-to-list 'values (org-trim (match-string 1))))
13077 (delete "" values)))))
13079 (defun org-insert-property-drawer ()
13080 "Insert a property drawer into the current entry."
13081 (interactive)
13082 (org-back-to-heading t)
13083 (looking-at outline-regexp)
13084 (let ((indent (if org-adapt-indentation
13085 (- (match-end 0)(match-beginning 0))
13087 (beg (point))
13088 (re (concat "^[ \t]*" org-keyword-time-regexp))
13089 end hiddenp)
13090 (outline-next-heading)
13091 (setq end (point))
13092 (goto-char beg)
13093 (while (re-search-forward re end t))
13094 (setq hiddenp (org-invisible-p))
13095 (end-of-line 1)
13096 (and (equal (char-after) ?\n) (forward-char 1))
13097 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
13098 (if (member (match-string 1) '("CLOCK:" ":END:"))
13099 ;; just skip this line
13100 (beginning-of-line 2)
13101 ;; Drawer start, find the end
13102 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
13103 (beginning-of-line 1)))
13104 (org-skip-over-state-notes)
13105 (skip-chars-backward " \t\n\r")
13106 (if (eq (char-before) ?*) (forward-char 1))
13107 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
13108 (beginning-of-line 0)
13109 (org-indent-to-column indent)
13110 (beginning-of-line 2)
13111 (org-indent-to-column indent)
13112 (beginning-of-line 0)
13113 (if hiddenp
13114 (save-excursion
13115 (org-back-to-heading t)
13116 (hide-entry))
13117 (org-flag-drawer t))))
13119 (defun org-set-property (property value)
13120 "In the current entry, set PROPERTY to VALUE.
13121 When called interactively, this will prompt for a property name, offering
13122 completion on existing and default properties. And then it will prompt
13123 for a value, offering completion either on allowed values (via an inherited
13124 xxx_ALL property) or on existing values in other instances of this property
13125 in the current file."
13126 (interactive
13127 (let* ((completion-ignore-case t)
13128 (keys (org-buffer-property-keys nil t t))
13129 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
13130 (prop (if (member prop0 keys)
13131 prop0
13132 (or (cdr (assoc (downcase prop0)
13133 (mapcar (lambda (x) (cons (downcase x) x))
13134 keys)))
13135 prop0)))
13136 (cur (org-entry-get nil prop))
13137 (prompt (concat prop " value"
13138 (if (and cur (string-match "\\S-" cur))
13139 (concat " [" cur "]") "") ": "))
13140 (allowed (org-property-get-allowed-values nil prop 'table))
13141 (existing (mapcar 'list (org-property-values prop)))
13142 (val (if allowed
13143 (org-completing-read prompt allowed nil
13144 (not (get-text-property 0 'org-unrestricted
13145 (caar allowed))))
13146 (let (org-completion-use-ido org-completion-use-iswitchb)
13147 (org-completing-read prompt existing nil nil "" nil cur)))))
13148 (list prop (if (equal val "") cur val))))
13149 (unless (equal (org-entry-get nil property) value)
13150 (org-entry-put nil property value)))
13152 (defun org-delete-property (property)
13153 "In the current entry, delete PROPERTY."
13154 (interactive
13155 (let* ((completion-ignore-case t)
13156 (prop (org-icompleting-read "Property: " (org-entry-properties nil 'standard))))
13157 (list prop)))
13158 (message "Property %s %s" property
13159 (if (org-entry-delete nil property)
13160 "deleted"
13161 "was not present in the entry")))
13163 (defun org-delete-property-globally (property)
13164 "Remove PROPERTY globally, from all entries."
13165 (interactive
13166 (let* ((completion-ignore-case t)
13167 (prop (org-icompleting-read
13168 "Globally remove property: "
13169 (mapcar 'list (org-buffer-property-keys)))))
13170 (list prop)))
13171 (save-excursion
13172 (save-restriction
13173 (widen)
13174 (goto-char (point-min))
13175 (let ((cnt 0))
13176 (while (re-search-forward
13177 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
13178 nil t)
13179 (setq cnt (1+ cnt))
13180 (replace-match ""))
13181 (message "Property \"%s\" removed from %d entries" property cnt)))))
13183 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
13185 (defun org-compute-property-at-point ()
13186 "Compute the property at point.
13187 This looks for an enclosing column format, extracts the operator and
13188 then applies it to the property in the column format's scope."
13189 (interactive)
13190 (unless (org-at-property-p)
13191 (error "Not at a property"))
13192 (let ((prop (org-match-string-no-properties 2)))
13193 (org-columns-get-format-and-top-level)
13194 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
13195 (error "No operator defined for property %s" prop))
13196 (org-columns-compute prop)))
13198 (defvar org-property-allowed-value-functions nil
13199 "Hook for functions supplying allowed values for a specific property.
13200 The functions must take a single argument, the name of the property, and
13201 return a flat list of allowed values. If \":ETC\" is one of
13202 the values, this means that these values are intended as defaults for
13203 completion, but that other values should be allowed too.
13204 The functions must return nil if they are not responsible for this
13205 property.")
13207 (defun org-property-get-allowed-values (pom property &optional table)
13208 "Get allowed values for the property PROPERTY.
13209 When TABLE is non-nil, return an alist that can directly be used for
13210 completion."
13211 (let (vals)
13212 (cond
13213 ((equal property "TODO")
13214 (setq vals (org-with-point-at pom
13215 (append org-todo-keywords-1 '("")))))
13216 ((equal property "PRIORITY")
13217 (let ((n org-lowest-priority))
13218 (while (>= n org-highest-priority)
13219 (push (char-to-string n) vals)
13220 (setq n (1- n)))))
13221 ((member property org-special-properties))
13222 ((setq vals (run-hook-with-args-until-success
13223 'org-property-allowed-value-functions property)))
13225 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
13226 (when (and vals (string-match "\\S-" vals))
13227 (setq vals (car (read-from-string (concat "(" vals ")"))))
13228 (setq vals (mapcar (lambda (x)
13229 (cond ((stringp x) x)
13230 ((numberp x) (number-to-string x))
13231 ((symbolp x) (symbol-name x))
13232 (t "???")))
13233 vals)))))
13234 (when (member ":ETC" vals)
13235 (setq vals (remove ":ETC" vals))
13236 (org-add-props (car vals) '(org-unrestricted t)))
13237 (if table (mapcar 'list vals) vals)))
13239 (defun org-property-previous-allowed-value (&optional previous)
13240 "Switch to the next allowed value for this property."
13241 (interactive)
13242 (org-property-next-allowed-value t))
13244 (defun org-property-next-allowed-value (&optional previous)
13245 "Switch to the next allowed value for this property."
13246 (interactive)
13247 (unless (org-at-property-p)
13248 (error "Not at a property"))
13249 (let* ((key (match-string 2))
13250 (value (match-string 3))
13251 (allowed (or (org-property-get-allowed-values (point) key)
13252 (and (member value '("[ ]" "[-]" "[X]"))
13253 '("[ ]" "[X]"))))
13254 nval)
13255 (unless allowed
13256 (error "Allowed values for this property have not been defined"))
13257 (if previous (setq allowed (reverse allowed)))
13258 (if (member value allowed)
13259 (setq nval (car (cdr (member value allowed)))))
13260 (setq nval (or nval (car allowed)))
13261 (if (equal nval value)
13262 (error "Only one allowed value for this property"))
13263 (org-at-property-p)
13264 (replace-match (concat " :" key ": " nval) t t)
13265 (org-indent-line-function)
13266 (beginning-of-line 1)
13267 (skip-chars-forward " \t")
13268 (run-hook-with-args 'org-property-changed-functions key nval)))
13270 (defun org-find-entry-with-id (ident)
13271 "Locate the entry that contains the ID property with exact value IDENT.
13272 IDENT can be a string, a symbol or a number, this function will search for
13273 the string representation of it.
13274 Return the position where this entry starts, or nil if there is no such entry."
13275 (interactive "sID: ")
13276 (let ((id (cond
13277 ((stringp ident) ident)
13278 ((symbol-name ident) (symbol-name ident))
13279 ((numberp ident) (number-to-string ident))
13280 (t (error "IDENT %s must be a string, symbol or number" ident))))
13281 (case-fold-search nil))
13282 (save-excursion
13283 (save-restriction
13284 (widen)
13285 (goto-char (point-min))
13286 (when (re-search-forward
13287 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
13288 nil t)
13289 (org-back-to-heading t)
13290 (point))))))
13292 ;;;; Timestamps
13294 (defvar org-last-changed-timestamp nil)
13295 (defvar org-last-inserted-timestamp nil
13296 "The last time stamp inserted with `org-insert-time-stamp'.")
13297 (defvar org-time-was-given) ; dynamically scoped parameter
13298 (defvar org-end-time-was-given) ; dynamically scoped parameter
13299 (defvar org-ts-what) ; dynamically scoped parameter
13301 (defun org-time-stamp (arg &optional inactive)
13302 "Prompt for a date/time and insert a time stamp.
13303 If the user specifies a time like HH:MM, or if this command is called
13304 with a prefix argument, the time stamp will contain date and time.
13305 Otherwise, only the date will be included. All parts of a date not
13306 specified by the user will be filled in from the current date/time.
13307 So if you press just return without typing anything, the time stamp
13308 will represent the current date/time. If there is already a timestamp
13309 at the cursor, it will be modified."
13310 (interactive "P")
13311 (let* ((ts nil)
13312 (default-time
13313 ;; Default time is either today, or, when entering a range,
13314 ;; the range start.
13315 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
13316 (save-excursion
13317 (re-search-backward
13318 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
13319 (- (point) 20) t)))
13320 (apply 'encode-time (org-parse-time-string (match-string 1)))
13321 (current-time)))
13322 (default-input (and ts (org-get-compact-tod ts)))
13323 org-time-was-given org-end-time-was-given time)
13324 (cond
13325 ((and (org-at-timestamp-p t)
13326 (memq last-command '(org-time-stamp org-time-stamp-inactive))
13327 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
13328 (insert "--")
13329 (setq time (let ((this-command this-command))
13330 (org-read-date arg 'totime nil nil
13331 default-time default-input)))
13332 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
13333 ((org-at-timestamp-p t)
13334 (setq time (let ((this-command this-command))
13335 (org-read-date arg 'totime nil nil default-time default-input)))
13336 (when (org-at-timestamp-p t) ; just to get the match data
13337 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
13338 (replace-match "")
13339 (setq org-last-changed-timestamp
13340 (org-insert-time-stamp
13341 time (or org-time-was-given arg)
13342 inactive nil nil (list org-end-time-was-given))))
13343 (message "Timestamp updated"))
13345 (setq time (let ((this-command this-command))
13346 (org-read-date arg 'totime nil nil default-time default-input)))
13347 (org-insert-time-stamp time (or org-time-was-given arg) inactive
13348 nil nil (list org-end-time-was-given))))))
13350 ;; FIXME: can we use this for something else, like computing time differences?
13351 (defun org-get-compact-tod (s)
13352 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
13353 (let* ((t1 (match-string 1 s))
13354 (h1 (string-to-number (match-string 2 s)))
13355 (m1 (string-to-number (match-string 3 s)))
13356 (t2 (and (match-end 4) (match-string 5 s)))
13357 (h2 (and t2 (string-to-number (match-string 6 s))))
13358 (m2 (and t2 (string-to-number (match-string 7 s))))
13359 dh dm)
13360 (if (not t2)
13362 (setq dh (- h2 h1) dm (- m2 m1))
13363 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
13364 (concat t1 "+" (number-to-string dh)
13365 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
13367 (defun org-time-stamp-inactive (&optional arg)
13368 "Insert an inactive time stamp.
13369 An inactive time stamp is enclosed in square brackets instead of angle
13370 brackets. It is inactive in the sense that it does not trigger agenda entries,
13371 does not link to the calendar and cannot be changed with the S-cursor keys.
13372 So these are more for recording a certain time/date."
13373 (interactive "P")
13374 (org-time-stamp arg 'inactive))
13376 (defvar org-date-ovl (org-make-overlay 1 1))
13377 (org-overlay-put org-date-ovl 'face 'org-warning)
13378 (org-detach-overlay org-date-ovl)
13380 (defvar org-ans1) ; dynamically scoped parameter
13381 (defvar org-ans2) ; dynamically scoped parameter
13383 (defvar org-plain-time-of-day-regexp) ; defined below
13385 (defvar org-overriding-default-time nil) ; dynamically scoped
13386 (defvar org-read-date-overlay nil)
13387 (defvar org-dcst nil) ; dynamically scoped
13388 (defvar org-read-date-history nil)
13389 (defvar org-read-date-final-answer nil)
13391 (defun org-read-date (&optional with-time to-time from-string prompt
13392 default-time default-input)
13393 "Read a date, possibly a time, and make things smooth for the user.
13394 The prompt will suggest to enter an ISO date, but you can also enter anything
13395 which will at least partially be understood by `parse-time-string'.
13396 Unrecognized parts of the date will default to the current day, month, year,
13397 hour and minute. If this command is called to replace a timestamp at point,
13398 of to enter the second timestamp of a range, the default time is taken from the
13399 existing stamp. For example,
13400 3-2-5 --> 2003-02-05
13401 feb 15 --> currentyear-02-15
13402 sep 12 9 --> 2009-09-12
13403 12:45 --> today 12:45
13404 22 sept 0:34 --> currentyear-09-22 0:34
13405 12 --> currentyear-currentmonth-12
13406 Fri --> nearest Friday (today or later)
13407 etc.
13409 Furthermore you can specify a relative date by giving, as the *first* thing
13410 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
13411 change in days weeks, months, years.
13412 With a single plus or minus, the date is relative to today. With a double
13413 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
13414 +4d --> four days from today
13415 +4 --> same as above
13416 +2w --> two weeks from today
13417 ++5 --> five days from default date
13419 The function understands only English month and weekday abbreviations,
13420 but this can be configured with the variables `parse-time-months' and
13421 `parse-time-weekdays'.
13423 While prompting, a calendar is popped up - you can also select the
13424 date with the mouse (button 1). The calendar shows a period of three
13425 months. To scroll it to other months, use the keys `>' and `<'.
13426 If you don't like the calendar, turn it off with
13427 \(setq org-read-date-popup-calendar nil)
13429 With optional argument TO-TIME, the date will immediately be converted
13430 to an internal time.
13431 With an optional argument WITH-TIME, the prompt will suggest to also
13432 insert a time. Note that when WITH-TIME is not set, you can still
13433 enter a time, and this function will inform the calling routine about
13434 this change. The calling routine may then choose to change the format
13435 used to insert the time stamp into the buffer to include the time.
13436 With optional argument FROM-STRING, read from this string instead from
13437 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
13438 the time/date that is used for everything that is not specified by the
13439 user."
13440 (require 'parse-time)
13441 (let* ((org-time-stamp-rounding-minutes
13442 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
13443 (org-dcst org-display-custom-times)
13444 (ct (org-current-time))
13445 (def (or org-overriding-default-time default-time ct))
13446 (defdecode (decode-time def))
13447 (dummy (progn
13448 (when (< (nth 2 defdecode) org-extend-today-until)
13449 (setcar (nthcdr 2 defdecode) -1)
13450 (setcar (nthcdr 1 defdecode) 59)
13451 (setq def (apply 'encode-time defdecode)
13452 defdecode (decode-time def)))))
13453 (calendar-frame-setup nil)
13454 (calendar-move-hook nil)
13455 (calendar-view-diary-initially-flag nil)
13456 (view-diary-entries-initially nil)
13457 (calendar-view-holidays-initially-flag nil)
13458 (view-calendar-holidays-initially nil)
13459 (timestr (format-time-string
13460 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
13461 (prompt (concat (if prompt (concat prompt " ") "")
13462 (format "Date+time [%s]: " timestr)))
13463 ans (org-ans0 "") org-ans1 org-ans2 final)
13465 (cond
13466 (from-string (setq ans from-string))
13467 (org-read-date-popup-calendar
13468 (save-excursion
13469 (save-window-excursion
13470 (calendar)
13471 (calendar-forward-day (- (time-to-days def)
13472 (calendar-absolute-from-gregorian
13473 (calendar-current-date))))
13474 (org-eval-in-calendar nil t)
13475 (let* ((old-map (current-local-map))
13476 (map (copy-keymap calendar-mode-map))
13477 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
13478 (org-defkey map (kbd "RET") 'org-calendar-select)
13479 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
13480 'org-calendar-select-mouse)
13481 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
13482 'org-calendar-select-mouse)
13483 (org-defkey minibuffer-local-map [(meta shift left)]
13484 (lambda () (interactive)
13485 (org-eval-in-calendar '(calendar-backward-month 1))))
13486 (org-defkey minibuffer-local-map [(meta shift right)]
13487 (lambda () (interactive)
13488 (org-eval-in-calendar '(calendar-forward-month 1))))
13489 (org-defkey minibuffer-local-map [(meta shift up)]
13490 (lambda () (interactive)
13491 (org-eval-in-calendar '(calendar-backward-year 1))))
13492 (org-defkey minibuffer-local-map [(meta shift down)]
13493 (lambda () (interactive)
13494 (org-eval-in-calendar '(calendar-forward-year 1))))
13495 (org-defkey minibuffer-local-map [?\e (shift left)]
13496 (lambda () (interactive)
13497 (org-eval-in-calendar '(calendar-backward-month 1))))
13498 (org-defkey minibuffer-local-map [?\e (shift right)]
13499 (lambda () (interactive)
13500 (org-eval-in-calendar '(calendar-forward-month 1))))
13501 (org-defkey minibuffer-local-map [?\e (shift up)]
13502 (lambda () (interactive)
13503 (org-eval-in-calendar '(calendar-backward-year 1))))
13504 (org-defkey minibuffer-local-map [?\e (shift down)]
13505 (lambda () (interactive)
13506 (org-eval-in-calendar '(calendar-forward-year 1))))
13507 (org-defkey minibuffer-local-map [(shift up)]
13508 (lambda () (interactive)
13509 (org-eval-in-calendar '(calendar-backward-week 1))))
13510 (org-defkey minibuffer-local-map [(shift down)]
13511 (lambda () (interactive)
13512 (org-eval-in-calendar '(calendar-forward-week 1))))
13513 (org-defkey minibuffer-local-map [(shift left)]
13514 (lambda () (interactive)
13515 (org-eval-in-calendar '(calendar-backward-day 1))))
13516 (org-defkey minibuffer-local-map [(shift right)]
13517 (lambda () (interactive)
13518 (org-eval-in-calendar '(calendar-forward-day 1))))
13519 (org-defkey minibuffer-local-map ">"
13520 (lambda () (interactive)
13521 (org-eval-in-calendar '(scroll-calendar-left 1))))
13522 (org-defkey minibuffer-local-map "<"
13523 (lambda () (interactive)
13524 (org-eval-in-calendar '(scroll-calendar-right 1))))
13525 (run-hooks 'org-read-date-minibuffer-setup-hook)
13526 (unwind-protect
13527 (progn
13528 (use-local-map map)
13529 (add-hook 'post-command-hook 'org-read-date-display)
13530 (setq org-ans0 (read-string prompt default-input
13531 'org-read-date-history nil))
13532 ;; org-ans0: from prompt
13533 ;; org-ans1: from mouse click
13534 ;; org-ans2: from calendar motion
13535 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
13536 (remove-hook 'post-command-hook 'org-read-date-display)
13537 (use-local-map old-map)
13538 (when org-read-date-overlay
13539 (org-delete-overlay org-read-date-overlay)
13540 (setq org-read-date-overlay nil)))))))
13542 (t ; Naked prompt only
13543 (unwind-protect
13544 (setq ans (read-string prompt default-input
13545 'org-read-date-history timestr))
13546 (when org-read-date-overlay
13547 (org-delete-overlay org-read-date-overlay)
13548 (setq org-read-date-overlay nil)))))
13550 (setq final (org-read-date-analyze ans def defdecode))
13551 (setq org-read-date-final-answer ans)
13553 (if to-time
13554 (apply 'encode-time final)
13555 (if (and (boundp 'org-time-was-given) org-time-was-given)
13556 (format "%04d-%02d-%02d %02d:%02d"
13557 (nth 5 final) (nth 4 final) (nth 3 final)
13558 (nth 2 final) (nth 1 final))
13559 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
13561 (defvar def)
13562 (defvar defdecode)
13563 (defvar with-time)
13564 (defvar org-read-date-analyze-futurep nil)
13565 (defun org-read-date-display ()
13566 "Display the current date prompt interpretation in the minibuffer."
13567 (when org-read-date-display-live
13568 (when org-read-date-overlay
13569 (org-delete-overlay org-read-date-overlay))
13570 (let ((p (point)))
13571 (end-of-line 1)
13572 (while (not (equal (buffer-substring
13573 (max (point-min) (- (point) 4)) (point))
13574 " "))
13575 (insert " "))
13576 (goto-char p))
13577 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
13578 " " (or org-ans1 org-ans2)))
13579 (org-end-time-was-given nil)
13580 (f (org-read-date-analyze ans def defdecode))
13581 (fmts (if org-dcst
13582 org-time-stamp-custom-formats
13583 org-time-stamp-formats))
13584 (fmt (if (or with-time
13585 (and (boundp 'org-time-was-given) org-time-was-given))
13586 (cdr fmts)
13587 (car fmts)))
13588 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
13589 (when (and org-end-time-was-given
13590 (string-match org-plain-time-of-day-regexp txt))
13591 (setq txt (concat (substring txt 0 (match-end 0)) "-"
13592 org-end-time-was-given
13593 (substring txt (match-end 0)))))
13594 (when org-read-date-analyze-futurep
13595 (setq txt (concat txt " (=>F)")))
13596 (setq org-read-date-overlay
13597 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
13598 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
13600 (defun org-read-date-analyze (ans def defdecode)
13601 "Analyse the combined answer of the date prompt."
13602 ;; FIXME: cleanup and comment
13603 (let ((nowdecode (decode-time (current-time)))
13604 delta deltan deltaw deltadef year month day
13605 hour minute second wday pm h2 m2 tl wday1
13606 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
13607 (setq org-read-date-analyze-futurep nil)
13608 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
13609 (setq ans "+0"))
13611 (when (setq delta (org-read-date-get-relative ans (current-time) def))
13612 (setq ans (replace-match "" t t ans)
13613 deltan (car delta)
13614 deltaw (nth 1 delta)
13615 deltadef (nth 2 delta)))
13617 ;; Check if there is an iso week date in there
13618 ;; If yes, store the info and postpone interpreting it until the rest
13619 ;; of the parsing is done
13620 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
13621 (setq iso-year (if (match-end 1)
13622 (org-small-year-to-year
13623 (string-to-number (match-string 1 ans))))
13624 iso-weekday (if (match-end 3)
13625 (string-to-number (match-string 3 ans)))
13626 iso-week (string-to-number (match-string 2 ans)))
13627 (setq ans (replace-match "" t t ans)))
13629 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
13630 (when (string-match
13631 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
13632 (setq year (if (match-end 2)
13633 (string-to-number (match-string 2 ans))
13634 (progn (setq kill-year t)
13635 (string-to-number (format-time-string "%Y"))))
13636 month (string-to-number (match-string 3 ans))
13637 day (string-to-number (match-string 4 ans)))
13638 (if (< year 100) (setq year (+ 2000 year)))
13639 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13640 t nil ans)))
13641 ;; Help matching american dates, like 5/30 or 5/30/7
13642 (when (string-match
13643 "^ *\\([0-3]?[0-9]\\)/\\([0-1]?[0-9]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
13644 (setq year (if (match-end 4)
13645 (string-to-number (match-string 4 ans))
13646 (progn (setq kill-year t)
13647 (string-to-number (format-time-string "%Y"))))
13648 month (string-to-number (match-string 1 ans))
13649 day (string-to-number (match-string 2 ans)))
13650 (if (< year 100) (setq year (+ 2000 year)))
13651 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13652 t nil ans)))
13653 ;; Help matching am/pm times, because `parse-time-string' does not do that.
13654 ;; If there is a time with am/pm, and *no* time without it, we convert
13655 ;; so that matching will be successful.
13656 (loop for i from 1 to 2 do ; twice, for end time as well
13657 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
13658 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
13659 (setq hour (string-to-number (match-string 1 ans))
13660 minute (if (match-end 3)
13661 (string-to-number (match-string 3 ans))
13663 pm (equal ?p
13664 (string-to-char (downcase (match-string 4 ans)))))
13665 (if (and (= hour 12) (not pm))
13666 (setq hour 0)
13667 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
13668 (setq ans (replace-match (format "%02d:%02d" hour minute)
13669 t t ans))))
13671 ;; Check if a time range is given as a duration
13672 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
13673 (setq hour (string-to-number (match-string 1 ans))
13674 h2 (+ hour (string-to-number (match-string 3 ans)))
13675 minute (string-to-number (match-string 2 ans))
13676 m2 (+ minute (if (match-end 5) (string-to-number
13677 (match-string 5 ans))0)))
13678 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
13679 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
13680 t t ans)))
13682 ;; Check if there is a time range
13683 (when (boundp 'org-end-time-was-given)
13684 (setq org-time-was-given nil)
13685 (when (and (string-match org-plain-time-of-day-regexp ans)
13686 (match-end 8))
13687 (setq org-end-time-was-given (match-string 8 ans))
13688 (setq ans (concat (substring ans 0 (match-beginning 7))
13689 (substring ans (match-end 7))))))
13691 (setq tl (parse-time-string ans)
13692 day (or (nth 3 tl) (nth 3 defdecode))
13693 month (or (nth 4 tl)
13694 (if (and org-read-date-prefer-future
13695 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
13696 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
13697 (nth 4 defdecode)))
13698 year (or (and (not kill-year) (nth 5 tl))
13699 (if (and org-read-date-prefer-future
13700 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
13701 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
13702 (nth 5 defdecode)))
13703 hour (or (nth 2 tl) (nth 2 defdecode))
13704 minute (or (nth 1 tl) (nth 1 defdecode))
13705 second (or (nth 0 tl) 0)
13706 wday (nth 6 tl))
13708 (when (and (eq org-read-date-prefer-future 'time)
13709 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
13710 (equal day (nth 3 nowdecode))
13711 (equal month (nth 4 nowdecode))
13712 (equal year (nth 5 nowdecode))
13713 (nth 2 tl)
13714 (or (< (nth 2 tl) (nth 2 nowdecode))
13715 (and (= (nth 2 tl) (nth 2 nowdecode))
13716 (nth 1 tl)
13717 (< (nth 1 tl) (nth 1 nowdecode)))))
13718 (setq day (1+ day)
13719 futurep t))
13721 ;; Special date definitions below
13722 (cond
13723 (iso-week
13724 ;; There was an iso week
13725 (require 'cal-iso)
13726 (setq futurep nil)
13727 (setq year (or iso-year year)
13728 day (or iso-weekday wday 1)
13729 wday nil ; to make sure that the trigger below does not match
13730 iso-date (calendar-gregorian-from-absolute
13731 (calendar-absolute-from-iso
13732 (list iso-week day year))))
13733 ; FIXME: Should we also push ISO weeks into the future?
13734 ; (when (and org-read-date-prefer-future
13735 ; (not iso-year)
13736 ; (< (calendar-absolute-from-gregorian iso-date)
13737 ; (time-to-days (current-time))))
13738 ; (setq year (1+ year)
13739 ; iso-date (calendar-gregorian-from-absolute
13740 ; (calendar-absolute-from-iso
13741 ; (list iso-week day year)))))
13742 (setq month (car iso-date)
13743 year (nth 2 iso-date)
13744 day (nth 1 iso-date)))
13745 (deltan
13746 (setq futurep nil)
13747 (unless deltadef
13748 (let ((now (decode-time (current-time))))
13749 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
13750 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
13751 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
13752 ((equal deltaw "m") (setq month (+ month deltan)))
13753 ((equal deltaw "y") (setq year (+ year deltan)))))
13754 ((and wday (not (nth 3 tl)))
13755 (setq futurep nil)
13756 ;; Weekday was given, but no day, so pick that day in the week
13757 ;; on or after the derived date.
13758 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
13759 (unless (equal wday wday1)
13760 (setq day (+ day (% (- wday wday1 -7) 7))))))
13761 (if (and (boundp 'org-time-was-given)
13762 (nth 2 tl))
13763 (setq org-time-was-given t))
13764 (if (< year 100) (setq year (+ 2000 year)))
13765 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
13766 (setq org-read-date-analyze-futurep futurep)
13767 (list second minute hour day month year)))
13769 (defvar parse-time-weekdays)
13771 (defun org-read-date-get-relative (s today default)
13772 "Check string S for special relative date string.
13773 TODAY and DEFAULT are internal times, for today and for a default.
13774 Return shift list (N what def-flag)
13775 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
13776 N is the number of WHATs to shift.
13777 DEF-FLAG is t when a double ++ or -- indicates shift relative to
13778 the DEFAULT date rather than TODAY."
13779 (when (and
13780 (string-match
13781 (concat
13782 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
13783 "\\([0-9]+\\)?"
13784 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
13785 "\\([ \t]\\|$\\)") s)
13786 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
13787 (let* ((dir (if (> (match-end 1) (match-beginning 1))
13788 (string-to-char (substring (match-string 1 s) -1))
13789 ?+))
13790 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
13791 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
13792 (what (if (match-end 3) (match-string 3 s) "d"))
13793 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
13794 (date (if rel default today))
13795 (wday (nth 6 (decode-time date)))
13796 delta)
13797 (if wday1
13798 (progn
13799 (setq delta (mod (+ 7 (- wday1 wday)) 7))
13800 (if (= dir ?-) (setq delta (- delta 7)))
13801 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
13802 (list delta "d" rel))
13803 (list (* n (if (= dir ?-) -1 1)) what rel)))))
13805 (defun org-order-calendar-date-args (arg1 arg2 arg3)
13806 "Turn a user-specified date into the internal representation.
13807 The internal representation needed by the calendar is (month day year).
13808 This is a wrapper to handle the brain-dead convention in calendar that
13809 user function argument order change dependent on argument order."
13810 (if (boundp 'calendar-date-style)
13811 (cond
13812 ((eq calendar-date-style 'american)
13813 (list arg1 arg2 arg3))
13814 ((eq calendar-date-style 'european)
13815 (list arg2 arg1 arg3))
13816 ((eq calendar-date-style 'iso)
13817 (list arg2 arg3 arg1)))
13818 (if (org-bound-and-true-p european-calendar-style)
13819 (list arg2 arg1 arg3)
13820 (list arg1 arg2 arg3))))
13822 (defun org-eval-in-calendar (form &optional keepdate)
13823 "Eval FORM in the calendar window and return to current window.
13824 Also, store the cursor date in variable org-ans2."
13825 (let ((sf (selected-frame))
13826 (sw (selected-window)))
13827 (select-window (get-buffer-window "*Calendar*" t))
13828 (eval form)
13829 (when (and (not keepdate) (calendar-cursor-to-date))
13830 (let* ((date (calendar-cursor-to-date))
13831 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13832 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
13833 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
13834 (select-window sw)
13835 (org-select-frame-set-input-focus sf)))
13837 (defun org-calendar-select ()
13838 "Return to `org-read-date' with the date currently selected.
13839 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13840 (interactive)
13841 (when (calendar-cursor-to-date)
13842 (let* ((date (calendar-cursor-to-date))
13843 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13844 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13845 (if (active-minibuffer-window) (exit-minibuffer))))
13847 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
13848 "Insert a date stamp for the date given by the internal TIME.
13849 WITH-HM means use the stamp format that includes the time of the day.
13850 INACTIVE means use square brackets instead of angular ones, so that the
13851 stamp will not contribute to the agenda.
13852 PRE and POST are optional strings to be inserted before and after the
13853 stamp.
13854 The command returns the inserted time stamp."
13855 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
13856 stamp)
13857 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
13858 (insert-before-markers (or pre ""))
13859 (insert-before-markers (setq stamp (format-time-string fmt time)))
13860 (when (listp extra)
13861 (setq extra (car extra))
13862 (if (and (stringp extra)
13863 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
13864 (setq extra (format "-%02d:%02d"
13865 (string-to-number (match-string 1 extra))
13866 (string-to-number (match-string 2 extra))))
13867 (setq extra nil)))
13868 (when extra
13869 (backward-char 1)
13870 (insert-before-markers extra)
13871 (forward-char 1))
13872 (insert-before-markers (or post ""))
13873 (setq org-last-inserted-timestamp stamp)))
13875 (defun org-toggle-time-stamp-overlays ()
13876 "Toggle the use of custom time stamp formats."
13877 (interactive)
13878 (setq org-display-custom-times (not org-display-custom-times))
13879 (unless org-display-custom-times
13880 (let ((p (point-min)) (bmp (buffer-modified-p)))
13881 (while (setq p (next-single-property-change p 'display))
13882 (if (and (get-text-property p 'display)
13883 (eq (get-text-property p 'face) 'org-date))
13884 (remove-text-properties
13885 p (setq p (next-single-property-change p 'display))
13886 '(display t))))
13887 (set-buffer-modified-p bmp)))
13888 (if (featurep 'xemacs)
13889 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
13890 (org-restart-font-lock)
13891 (setq org-table-may-need-update t)
13892 (if org-display-custom-times
13893 (message "Time stamps are overlayed with custom format")
13894 (message "Time stamp overlays removed")))
13896 (defun org-display-custom-time (beg end)
13897 "Overlay modified time stamp format over timestamp between BEG and END."
13898 (let* ((ts (buffer-substring beg end))
13899 t1 w1 with-hm tf time str w2 (off 0))
13900 (save-match-data
13901 (setq t1 (org-parse-time-string ts t))
13902 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
13903 (setq off (- (match-end 0) (match-beginning 0)))))
13904 (setq end (- end off))
13905 (setq w1 (- end beg)
13906 with-hm (and (nth 1 t1) (nth 2 t1))
13907 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
13908 time (org-fix-decoded-time t1)
13909 str (org-add-props
13910 (format-time-string
13911 (substring tf 1 -1) (apply 'encode-time time))
13912 nil 'mouse-face 'highlight)
13913 w2 (length str))
13914 (if (not (= w2 w1))
13915 (add-text-properties (1+ beg) (+ 2 beg)
13916 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
13917 (if (featurep 'xemacs)
13918 (progn
13919 (put-text-property beg end 'invisible t)
13920 (put-text-property beg end 'end-glyph (make-glyph str)))
13921 (put-text-property beg end 'display str))))
13923 (defun org-translate-time (string)
13924 "Translate all timestamps in STRING to custom format.
13925 But do this only if the variable `org-display-custom-times' is set."
13926 (when org-display-custom-times
13927 (save-match-data
13928 (let* ((start 0)
13929 (re org-ts-regexp-both)
13930 t1 with-hm inactive tf time str beg end)
13931 (while (setq start (string-match re string start))
13932 (setq beg (match-beginning 0)
13933 end (match-end 0)
13934 t1 (save-match-data
13935 (org-parse-time-string (substring string beg end) t))
13936 with-hm (and (nth 1 t1) (nth 2 t1))
13937 inactive (equal (substring string beg (1+ beg)) "[")
13938 tf (funcall (if with-hm 'cdr 'car)
13939 org-time-stamp-custom-formats)
13940 time (org-fix-decoded-time t1)
13941 str (format-time-string
13942 (concat
13943 (if inactive "[" "<") (substring tf 1 -1)
13944 (if inactive "]" ">"))
13945 (apply 'encode-time time))
13946 string (replace-match str t t string)
13947 start (+ start (length str)))))))
13948 string)
13950 (defun org-fix-decoded-time (time)
13951 "Set 0 instead of nil for the first 6 elements of time.
13952 Don't touch the rest."
13953 (let ((n 0))
13954 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
13956 (defun org-days-to-time (timestamp-string)
13957 "Difference between TIMESTAMP-STRING and now in days."
13958 (- (time-to-days (org-time-string-to-time timestamp-string))
13959 (time-to-days (current-time))))
13961 (defun org-deadline-close (timestamp-string &optional ndays)
13962 "Is the time in TIMESTAMP-STRING close to the current date?"
13963 (setq ndays (or ndays (org-get-wdays timestamp-string)))
13964 (and (< (org-days-to-time timestamp-string) ndays)
13965 (not (org-entry-is-done-p))))
13967 (defun org-get-wdays (ts)
13968 "Get the deadline lead time appropriate for timestring TS."
13969 (cond
13970 ((<= org-deadline-warning-days 0)
13971 ;; 0 or negative, enforce this value no matter what
13972 (- org-deadline-warning-days))
13973 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
13974 ;; lead time is specified.
13975 (floor (* (string-to-number (match-string 1 ts))
13976 (cdr (assoc (match-string 2 ts)
13977 '(("d" . 1) ("w" . 7)
13978 ("m" . 30.4) ("y" . 365.25)))))))
13979 ;; go for the default.
13980 (t org-deadline-warning-days)))
13982 (defun org-calendar-select-mouse (ev)
13983 "Return to `org-read-date' with the date currently selected.
13984 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13985 (interactive "e")
13986 (mouse-set-point ev)
13987 (when (calendar-cursor-to-date)
13988 (let* ((date (calendar-cursor-to-date))
13989 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13990 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13991 (if (active-minibuffer-window) (exit-minibuffer))))
13993 (defun org-check-deadlines (ndays)
13994 "Check if there are any deadlines due or past due.
13995 A deadline is considered due if it happens within `org-deadline-warning-days'
13996 days from today's date. If the deadline appears in an entry marked DONE,
13997 it is not shown. The prefix arg NDAYS can be used to test that many
13998 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
13999 (interactive "P")
14000 (let* ((org-warn-days
14001 (cond
14002 ((equal ndays '(4)) 100000)
14003 (ndays (prefix-numeric-value ndays))
14004 (t (abs org-deadline-warning-days))))
14005 (case-fold-search nil)
14006 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
14007 (callback
14008 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
14010 (message "%d deadlines past-due or due within %d days"
14011 (org-occur regexp nil callback)
14012 org-warn-days)))
14014 (defun org-check-before-date (date)
14015 "Check if there are deadlines or scheduled entries before DATE."
14016 (interactive (list (org-read-date)))
14017 (let ((case-fold-search nil)
14018 (regexp (concat "\\<\\(" org-deadline-string
14019 "\\|" org-scheduled-string
14020 "\\) *<\\([^>]+\\)>"))
14021 (callback
14022 (lambda () (time-less-p
14023 (org-time-string-to-time (match-string 2))
14024 (org-time-string-to-time date)))))
14025 (message "%d entries before %s"
14026 (org-occur regexp nil callback) date)))
14028 (defun org-check-after-date (date)
14029 "Check if there are deadlines or scheduled entries after DATE."
14030 (interactive (list (org-read-date)))
14031 (let ((case-fold-search nil)
14032 (regexp (concat "\\<\\(" org-deadline-string
14033 "\\|" org-scheduled-string
14034 "\\) *<\\([^>]+\\)>"))
14035 (callback
14036 (lambda () (not
14037 (time-less-p
14038 (org-time-string-to-time (match-string 2))
14039 (org-time-string-to-time date))))))
14040 (message "%d entries after %s"
14041 (org-occur regexp nil callback) date)))
14043 (defun org-evaluate-time-range (&optional to-buffer)
14044 "Evaluate a time range by computing the difference between start and end.
14045 Normally the result is just printed in the echo area, but with prefix arg
14046 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
14047 If the time range is actually in a table, the result is inserted into the
14048 next column.
14049 For time difference computation, a year is assumed to be exactly 365
14050 days in order to avoid rounding problems."
14051 (interactive "P")
14053 (org-clock-update-time-maybe)
14054 (save-excursion
14055 (unless (org-at-date-range-p t)
14056 (goto-char (point-at-bol))
14057 (re-search-forward org-tr-regexp-both (point-at-eol) t))
14058 (if (not (org-at-date-range-p t))
14059 (error "Not at a time-stamp range, and none found in current line")))
14060 (let* ((ts1 (match-string 1))
14061 (ts2 (match-string 2))
14062 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
14063 (match-end (match-end 0))
14064 (time1 (org-time-string-to-time ts1))
14065 (time2 (org-time-string-to-time ts2))
14066 (t1 (org-float-time time1))
14067 (t2 (org-float-time time2))
14068 (diff (abs (- t2 t1)))
14069 (negative (< (- t2 t1) 0))
14070 ;; (ys (floor (* 365 24 60 60)))
14071 (ds (* 24 60 60))
14072 (hs (* 60 60))
14073 (fy "%dy %dd %02d:%02d")
14074 (fy1 "%dy %dd")
14075 (fd "%dd %02d:%02d")
14076 (fd1 "%dd")
14077 (fh "%02d:%02d")
14078 y d h m align)
14079 (if havetime
14080 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14082 d (floor (/ diff ds)) diff (mod diff ds)
14083 h (floor (/ diff hs)) diff (mod diff hs)
14084 m (floor (/ diff 60)))
14085 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14087 d (floor (+ (/ diff ds) 0.5))
14088 h 0 m 0))
14089 (if (not to-buffer)
14090 (message "%s" (org-make-tdiff-string y d h m))
14091 (if (org-at-table-p)
14092 (progn
14093 (goto-char match-end)
14094 (setq align t)
14095 (and (looking-at " *|") (goto-char (match-end 0))))
14096 (goto-char match-end))
14097 (if (looking-at
14098 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
14099 (replace-match ""))
14100 (if negative (insert " -"))
14101 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
14102 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
14103 (insert " " (format fh h m))))
14104 (if align (org-table-align))
14105 (message "Time difference inserted")))))
14107 (defun org-make-tdiff-string (y d h m)
14108 (let ((fmt "")
14109 (l nil))
14110 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
14111 l (push y l)))
14112 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
14113 l (push d l)))
14114 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
14115 l (push h l)))
14116 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
14117 l (push m l)))
14118 (apply 'format fmt (nreverse l))))
14120 (defun org-time-string-to-time (s)
14121 (apply 'encode-time (org-parse-time-string s)))
14122 (defun org-time-string-to-seconds (s)
14123 (org-float-time (org-time-string-to-time s)))
14125 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
14126 "Convert a time stamp to an absolute day number.
14127 If there is a specifyer for a cyclic time stamp, get the closest date to
14128 DAYNR.
14129 PREFER and SHOW-ALL are passed through to `org-closest-date'.
14130 the variable date is bound by the calendar when this is called."
14131 (cond
14132 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
14133 (if (org-diary-sexp-entry (match-string 1 s) "" date)
14134 daynr
14135 (+ daynr 1000)))
14136 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
14137 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
14138 (time-to-days (current-time))) (match-string 0 s)
14139 prefer show-all))
14140 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
14142 (defun org-days-to-iso-week (days)
14143 "Return the iso week number."
14144 (require 'cal-iso)
14145 (car (calendar-iso-from-absolute days)))
14147 (defun org-small-year-to-year (year)
14148 "Convert 2-digit years into 4-digit years.
14149 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
14150 The year 2000 cannot be abbreviated. Any year larger than 99
14151 is returned unchanged."
14152 (if (< year 38)
14153 (setq year (+ 2000 year))
14154 (if (< year 100)
14155 (setq year (+ 1900 year))))
14156 year)
14158 (defun org-time-from-absolute (d)
14159 "Return the time corresponding to date D.
14160 D may be an absolute day number, or a calendar-type list (month day year)."
14161 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
14162 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
14164 (defun org-calendar-holiday ()
14165 "List of holidays, for Diary display in Org-mode."
14166 (require 'holidays)
14167 (let ((hl (funcall
14168 (if (fboundp 'calendar-check-holidays)
14169 'calendar-check-holidays 'check-calendar-holidays) date)))
14170 (if hl (mapconcat 'identity hl "; "))))
14172 (defun org-diary-sexp-entry (sexp entry date)
14173 "Process a SEXP diary ENTRY for DATE."
14174 (require 'diary-lib)
14175 (let ((result (if calendar-debug-sexp
14176 (let ((stack-trace-on-error t))
14177 (eval (car (read-from-string sexp))))
14178 (condition-case nil
14179 (eval (car (read-from-string sexp)))
14180 (error
14181 (beep)
14182 (message "Bad sexp at line %d in %s: %s"
14183 (org-current-line)
14184 (buffer-file-name) sexp)
14185 (sleep-for 2))))))
14186 (cond ((stringp result) result)
14187 ((and (consp result)
14188 (stringp (cdr result))) (cdr result))
14189 (result entry)
14190 (t nil))))
14192 (defun org-diary-to-ical-string (frombuf)
14193 "Get iCalendar entries from diary entries in buffer FROMBUF.
14194 This uses the icalendar.el library."
14195 (let* ((tmpdir (if (featurep 'xemacs)
14196 (temp-directory)
14197 temporary-file-directory))
14198 (tmpfile (make-temp-name
14199 (expand-file-name "orgics" tmpdir)))
14200 buf rtn b e)
14201 (with-current-buffer frombuf
14202 (icalendar-export-region (point-min) (point-max) tmpfile)
14203 (setq buf (find-buffer-visiting tmpfile))
14204 (set-buffer buf)
14205 (goto-char (point-min))
14206 (if (re-search-forward "^BEGIN:VEVENT" nil t)
14207 (setq b (match-beginning 0)))
14208 (goto-char (point-max))
14209 (if (re-search-backward "^END:VEVENT" nil t)
14210 (setq e (match-end 0)))
14211 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
14212 (kill-buffer buf)
14213 (delete-file tmpfile)
14214 rtn))
14216 (defun org-closest-date (start current change prefer show-all)
14217 "Find the date closest to CURRENT that is consistent with START and CHANGE.
14218 When PREFER is `past' return a date that is either CURRENT or past.
14219 When PREFER is `future', return a date that is either CURRENT or future.
14220 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
14221 ;; Make the proper lists from the dates
14222 (catch 'exit
14223 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
14224 dn dw sday cday n1 n2 n0
14225 d m y y1 y2 date1 date2 nmonths nm ny m2)
14227 (setq start (org-date-to-gregorian start)
14228 current (org-date-to-gregorian
14229 (if show-all
14230 current
14231 (time-to-days (current-time))))
14232 sday (calendar-absolute-from-gregorian start)
14233 cday (calendar-absolute-from-gregorian current))
14235 (if (<= cday sday) (throw 'exit sday))
14237 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
14238 (setq dn (string-to-number (match-string 1 change))
14239 dw (cdr (assoc (match-string 2 change) a1)))
14240 (error "Invalid change specifyer: %s" change))
14241 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
14242 (cond
14243 ((eq dw 'day)
14244 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
14245 n2 (+ n1 dn)))
14246 ((eq dw 'year)
14247 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
14248 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
14249 (setq date1 (list m d y1)
14250 n1 (calendar-absolute-from-gregorian date1)
14251 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
14252 n2 (calendar-absolute-from-gregorian date2)))
14253 ((eq dw 'month)
14254 ;; approx number of month between the two dates
14255 (setq nmonths (floor (/ (- cday sday) 30.436875)))
14256 ;; How often does dn fit in there?
14257 (setq d (nth 1 start) m (car start) y (nth 2 start)
14258 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
14259 m (+ m nm)
14260 ny (floor (/ m 12))
14261 y (+ y ny)
14262 m (- m (* ny 12)))
14263 (while (> m 12) (setq m (- m 12) y (1+ y)))
14264 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
14265 (setq m2 (+ m dn) y2 y)
14266 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14267 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
14268 (while (<= n2 cday)
14269 (setq n1 n2 m m2 y y2)
14270 (setq m2 (+ m dn) y2 y)
14271 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14272 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
14273 ;; Make sure n1 is the earlier date
14274 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
14275 (if show-all
14276 (cond
14277 ((eq prefer 'past) (if (= cday n2) n2 n1))
14278 ((eq prefer 'future) (if (= cday n1) n1 n2))
14279 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
14280 (cond
14281 ((eq prefer 'past) (if (= cday n2) n2 n1))
14282 ((eq prefer 'future) (if (= cday n1) n1 n2))
14283 (t (if (= cday n1) n1 n2)))))))
14285 (defun org-date-to-gregorian (date)
14286 "Turn any specification of DATE into a gregorian date for the calendar."
14287 (cond ((integerp date) (calendar-gregorian-from-absolute date))
14288 ((and (listp date) (= (length date) 3)) date)
14289 ((stringp date)
14290 (setq date (org-parse-time-string date))
14291 (list (nth 4 date) (nth 3 date) (nth 5 date)))
14292 ((listp date)
14293 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
14295 (defun org-parse-time-string (s &optional nodefault)
14296 "Parse the standard Org-mode time string.
14297 This should be a lot faster than the normal `parse-time-string'.
14298 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
14299 hour and minute fields will be nil if not given."
14300 (if (string-match org-ts-regexp0 s)
14301 (list 0
14302 (if (or (match-beginning 8) (not nodefault))
14303 (string-to-number (or (match-string 8 s) "0")))
14304 (if (or (match-beginning 7) (not nodefault))
14305 (string-to-number (or (match-string 7 s) "0")))
14306 (string-to-number (match-string 4 s))
14307 (string-to-number (match-string 3 s))
14308 (string-to-number (match-string 2 s))
14309 nil nil nil)
14310 (error "Not a standard Org-mode time string: %s" s)))
14312 (defun org-timestamp-up (&optional arg)
14313 "Increase the date item at the cursor by one.
14314 If the cursor is on the year, change the year. If it is on the month or
14315 the day, change that.
14316 With prefix ARG, change by that many units."
14317 (interactive "p")
14318 (org-timestamp-change (prefix-numeric-value arg)))
14320 (defun org-timestamp-down (&optional arg)
14321 "Decrease the date item at the cursor by one.
14322 If the cursor is on the year, change the year. If it is on the month or
14323 the day, change that.
14324 With prefix ARG, change by that many units."
14325 (interactive "p")
14326 (org-timestamp-change (- (prefix-numeric-value arg))))
14328 (defun org-timestamp-up-day (&optional arg)
14329 "Increase the date in the time stamp by one day.
14330 With prefix ARG, change that many days."
14331 (interactive "p")
14332 (if (and (not (org-at-timestamp-p t))
14333 (org-on-heading-p))
14334 (org-todo 'up)
14335 (org-timestamp-change (prefix-numeric-value arg) 'day)))
14337 (defun org-timestamp-down-day (&optional arg)
14338 "Decrease the date in the time stamp by one day.
14339 With prefix ARG, change that many days."
14340 (interactive "p")
14341 (if (and (not (org-at-timestamp-p t))
14342 (org-on-heading-p))
14343 (org-todo 'down)
14344 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
14346 (defun org-at-timestamp-p (&optional inactive-ok)
14347 "Determine if the cursor is in or at a timestamp."
14348 (interactive)
14349 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
14350 (pos (point))
14351 (ans (or (looking-at tsr)
14352 (save-excursion
14353 (skip-chars-backward "^[<\n\r\t")
14354 (if (> (point) (point-min)) (backward-char 1))
14355 (and (looking-at tsr)
14356 (> (- (match-end 0) pos) -1))))))
14357 (and ans
14358 (boundp 'org-ts-what)
14359 (setq org-ts-what
14360 (cond
14361 ((= pos (match-beginning 0)) 'bracket)
14362 ((= pos (1- (match-end 0))) 'bracket)
14363 ((org-pos-in-match-range pos 2) 'year)
14364 ((org-pos-in-match-range pos 3) 'month)
14365 ((org-pos-in-match-range pos 7) 'hour)
14366 ((org-pos-in-match-range pos 8) 'minute)
14367 ((or (org-pos-in-match-range pos 4)
14368 (org-pos-in-match-range pos 5)) 'day)
14369 ((and (> pos (or (match-end 8) (match-end 5)))
14370 (< pos (match-end 0)))
14371 (- pos (or (match-end 8) (match-end 5))))
14372 (t 'day))))
14373 ans))
14375 (defun org-toggle-timestamp-type ()
14376 "Toggle the type (<active> or [inactive]) of a time stamp."
14377 (interactive)
14378 (when (org-at-timestamp-p t)
14379 (let ((beg (match-beginning 0)) (end (match-end 0))
14380 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
14381 (save-excursion
14382 (goto-char beg)
14383 (while (re-search-forward "[][<>]" end t)
14384 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
14385 t t)))
14386 (message "Timestamp is now %sactive"
14387 (if (equal (char-after beg) ?<) "" "in")))))
14389 (defun org-timestamp-change (n &optional what)
14390 "Change the date in the time stamp at point.
14391 The date will be changed by N times WHAT. WHAT can be `day', `month',
14392 `year', `minute', `second'. If WHAT is not given, the cursor position
14393 in the timestamp determines what will be changed."
14394 (let ((pos (point))
14395 with-hm inactive
14396 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
14397 org-ts-what
14398 extra rem
14399 ts time time0)
14400 (if (not (org-at-timestamp-p t))
14401 (error "Not at a timestamp"))
14402 (if (and (not what) (eq org-ts-what 'bracket))
14403 (org-toggle-timestamp-type)
14404 (if (and (not what) (not (eq org-ts-what 'day))
14405 org-display-custom-times
14406 (get-text-property (point) 'display)
14407 (not (get-text-property (1- (point)) 'display)))
14408 (setq org-ts-what 'day))
14409 (setq org-ts-what (or what org-ts-what)
14410 inactive (= (char-after (match-beginning 0)) ?\[)
14411 ts (match-string 0))
14412 (replace-match "")
14413 (if (string-match
14414 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
14416 (setq extra (match-string 1 ts)))
14417 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
14418 (setq with-hm t))
14419 (setq time0 (org-parse-time-string ts))
14420 (when (and (eq org-ts-what 'minute)
14421 (eq current-prefix-arg nil))
14422 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
14423 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
14424 (setcar (cdr time0) (+ (nth 1 time0)
14425 (if (> n 0) (- rem) (- dm rem))))))
14426 (setq time
14427 (encode-time (or (car time0) 0)
14428 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
14429 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
14430 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
14431 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
14432 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
14433 (nthcdr 6 time0)))
14434 (when (and (member org-ts-what '(hour minute))
14435 extra
14436 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
14437 (setq extra (org-modify-ts-extra
14438 extra
14439 (if (eq org-ts-what 'hour) 2 5)
14440 n dm)))
14441 (when (integerp org-ts-what)
14442 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
14443 (if (eq what 'calendar)
14444 (let ((cal-date (org-get-date-from-calendar)))
14445 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
14446 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
14447 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
14448 (setcar time0 (or (car time0) 0))
14449 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
14450 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
14451 (setq time (apply 'encode-time time0))))
14452 (setq org-last-changed-timestamp
14453 (org-insert-time-stamp time with-hm inactive nil nil extra))
14454 (org-clock-update-time-maybe)
14455 (goto-char pos)
14456 ;; Try to recenter the calendar window, if any
14457 (if (and org-calendar-follow-timestamp-change
14458 (get-buffer-window "*Calendar*" t)
14459 (memq org-ts-what '(day month year)))
14460 (org-recenter-calendar (time-to-days time))))))
14462 (defun org-modify-ts-extra (s pos n dm)
14463 "Change the different parts of the lead-time and repeat fields in timestamp."
14464 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
14465 ng h m new rem)
14466 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
14467 (cond
14468 ((or (org-pos-in-match-range pos 2)
14469 (org-pos-in-match-range pos 3))
14470 (setq m (string-to-number (match-string 3 s))
14471 h (string-to-number (match-string 2 s)))
14472 (if (org-pos-in-match-range pos 2)
14473 (setq h (+ h n))
14474 (setq n (* dm (org-no-warnings (signum n))))
14475 (when (not (= 0 (setq rem (% m dm))))
14476 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
14477 (setq m (+ m n)))
14478 (if (< m 0) (setq m (+ m 60) h (1- h)))
14479 (if (> m 59) (setq m (- m 60) h (1+ h)))
14480 (setq h (min 24 (max 0 h)))
14481 (setq ng 1 new (format "-%02d:%02d" h m)))
14482 ((org-pos-in-match-range pos 6)
14483 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
14484 ((org-pos-in-match-range pos 5)
14485 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
14487 ((org-pos-in-match-range pos 9)
14488 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
14489 ((org-pos-in-match-range pos 8)
14490 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
14492 (when ng
14493 (setq s (concat
14494 (substring s 0 (match-beginning ng))
14496 (substring s (match-end ng))))))
14499 (defun org-recenter-calendar (date)
14500 "If the calendar is visible, recenter it to DATE."
14501 (let* ((win (selected-window))
14502 (cwin (get-buffer-window "*Calendar*" t))
14503 (calendar-move-hook nil))
14504 (when cwin
14505 (select-window cwin)
14506 (calendar-goto-date (if (listp date) date
14507 (calendar-gregorian-from-absolute date)))
14508 (select-window win))))
14510 (defun org-goto-calendar (&optional arg)
14511 "Go to the Emacs calendar at the current date.
14512 If there is a time stamp in the current line, go to that date.
14513 A prefix ARG can be used to force the current date."
14514 (interactive "P")
14515 (let ((tsr org-ts-regexp) diff
14516 (calendar-move-hook nil)
14517 (calendar-view-holidays-initially-flag nil)
14518 (view-calendar-holidays-initially nil)
14519 (calendar-view-diary-initially-flag nil)
14520 (view-diary-entries-initially nil))
14521 (if (or (org-at-timestamp-p)
14522 (save-excursion
14523 (beginning-of-line 1)
14524 (looking-at (concat ".*" tsr))))
14525 (let ((d1 (time-to-days (current-time)))
14526 (d2 (time-to-days
14527 (org-time-string-to-time (match-string 1)))))
14528 (setq diff (- d2 d1))))
14529 (calendar)
14530 (calendar-goto-today)
14531 (if (and diff (not arg)) (calendar-forward-day diff))))
14533 (defun org-get-date-from-calendar ()
14534 "Return a list (month day year) of date at point in calendar."
14535 (with-current-buffer "*Calendar*"
14536 (save-match-data
14537 (calendar-cursor-to-date))))
14539 (defun org-date-from-calendar ()
14540 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
14541 If there is already a time stamp at the cursor position, update it."
14542 (interactive)
14543 (if (org-at-timestamp-p t)
14544 (org-timestamp-change 0 'calendar)
14545 (let ((cal-date (org-get-date-from-calendar)))
14546 (org-insert-time-stamp
14547 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
14549 (defun org-minutes-to-hh:mm-string (m)
14550 "Compute H:MM from a number of minutes."
14551 (let ((h (/ m 60)))
14552 (setq m (- m (* 60 h)))
14553 (format org-time-clocksum-format h m)))
14555 (defun org-hh:mm-string-to-minutes (s)
14556 "Convert a string H:MM to a number of minutes.
14557 If the string is just a number, interpret it as minutes.
14558 In fact, the first hh:mm or number in the string will be taken,
14559 there can be extra stuff in the string.
14560 If no number is found, the return value is 0."
14561 (cond
14562 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
14563 (+ (* (string-to-number (match-string 1 s)) 60)
14564 (string-to-number (match-string 2 s))))
14565 ((string-match "\\([0-9]+\\)" s)
14566 (string-to-number (match-string 1 s)))
14567 (t 0)))
14569 ;;;; Files
14571 (defun org-save-all-org-buffers ()
14572 "Save all Org-mode buffers without user confirmation."
14573 (interactive)
14574 (message "Saving all Org-mode buffers...")
14575 (save-some-buffers t 'org-mode-p)
14576 (when (featurep 'org-id) (org-id-locations-save))
14577 (message "Saving all Org-mode buffers... done"))
14579 (defun org-revert-all-org-buffers ()
14580 "Revert all Org-mode buffers.
14581 Prompt for confirmation when there are unsaved changes.
14582 Be sure you know what you are doing before letting this function
14583 overwrite your changes.
14585 This function is useful in a setup where one tracks org files
14586 with a version control system, to revert on one machine after pulling
14587 changes from another. I believe the procedure must be like this:
14589 1. M-x org-save-all-org-buffers
14590 2. Pull changes from the other machine, resolve conflicts
14591 3. M-x org-revert-all-org-buffers"
14592 (interactive)
14593 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
14594 (error "Abort"))
14595 (save-excursion
14596 (save-window-excursion
14597 (mapc
14598 (lambda (b)
14599 (when (and (with-current-buffer b (org-mode-p))
14600 (with-current-buffer b buffer-file-name))
14601 (switch-to-buffer b)
14602 (revert-buffer t 'no-confirm)))
14603 (buffer-list))
14604 (when (and (featurep 'org-id) org-id-track-globally)
14605 (org-id-locations-load)))))
14607 ;;;; Agenda files
14609 ;;;###autoload
14610 (defun org-iswitchb (&optional arg)
14611 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
14612 With a prefix argument, restrict available to files.
14613 With two prefix arguments, restrict available buffers to agenda files."
14614 (interactive "P")
14615 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
14616 ((equal arg '(16)) (org-buffer-list 'agenda))
14617 (t (org-buffer-list)))))
14618 (switch-to-buffer
14619 (org-icompleting-read "Org buffer: "
14620 (mapcar 'list (mapcar 'buffer-name blist))
14621 nil t))))
14623 ;;;###autoload
14624 (defalias 'org-ido-switchb 'org-iswitchb)
14626 (defun org-buffer-list (&optional predicate exclude-tmp)
14627 "Return a list of Org buffers.
14628 PREDICATE can be `export', `files' or `agenda'.
14630 export restrict the list to Export buffers.
14631 files restrict the list to buffers visiting Org files.
14632 agenda restrict the list to buffers visiting agenda files.
14634 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
14635 (let* ((bfn nil)
14636 (agenda-files (and (eq predicate 'agenda)
14637 (mapcar 'file-truename (org-agenda-files t))))
14638 (filter
14639 (cond
14640 ((eq predicate 'files)
14641 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
14642 ((eq predicate 'export)
14643 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
14644 ((eq predicate 'agenda)
14645 (lambda (b)
14646 (with-current-buffer b
14647 (and (eq major-mode 'org-mode)
14648 (setq bfn (buffer-file-name b))
14649 (member (file-truename bfn) agenda-files)))))
14650 (t (lambda (b) (with-current-buffer b
14651 (or (eq major-mode 'org-mode)
14652 (string-match "\*Org .*Export"
14653 (buffer-name b)))))))))
14654 (delq nil
14655 (mapcar
14656 (lambda(b)
14657 (if (and (funcall filter b)
14658 (or (not exclude-tmp)
14659 (not (string-match "tmp" (buffer-name b)))))
14661 nil))
14662 (buffer-list)))))
14664 (defun org-agenda-files (&optional unrestricted archives)
14665 "Get the list of agenda files.
14666 Optional UNRESTRICTED means return the full list even if a restriction
14667 is currently in place.
14668 When ARCHIVES is t, include all archive files that are really being
14669 used by the agenda files. If ARCHIVE is `ifmode', do this only if
14670 `org-agenda-archives-mode' is t."
14671 (let ((files
14672 (cond
14673 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
14674 ((stringp org-agenda-files) (org-read-agenda-file-list))
14675 ((listp org-agenda-files) org-agenda-files)
14676 (t (error "Invalid value of `org-agenda-files'")))))
14677 (setq files (apply 'append
14678 (mapcar (lambda (f)
14679 (if (file-directory-p f)
14680 (directory-files
14681 f t org-agenda-file-regexp)
14682 (list f)))
14683 files)))
14684 (when org-agenda-skip-unavailable-files
14685 (setq files (delq nil
14686 (mapcar (function
14687 (lambda (file)
14688 (and (file-readable-p file) file)))
14689 files))))
14690 (when (or (eq archives t)
14691 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
14692 (setq files (org-add-archive-files files)))
14693 files))
14695 (defun org-edit-agenda-file-list ()
14696 "Edit the list of agenda files.
14697 Depending on setup, this either uses customize to edit the variable
14698 `org-agenda-files', or it visits the file that is holding the list. In the
14699 latter case, the buffer is set up in a way that saving it automatically kills
14700 the buffer and restores the previous window configuration."
14701 (interactive)
14702 (if (stringp org-agenda-files)
14703 (let ((cw (current-window-configuration)))
14704 (find-file org-agenda-files)
14705 (org-set-local 'org-window-configuration cw)
14706 (org-add-hook 'after-save-hook
14707 (lambda ()
14708 (set-window-configuration
14709 (prog1 org-window-configuration
14710 (kill-buffer (current-buffer))))
14711 (org-install-agenda-files-menu)
14712 (message "New agenda file list installed"))
14713 nil 'local)
14714 (message "%s" (substitute-command-keys
14715 "Edit list and finish with \\[save-buffer]")))
14716 (customize-variable 'org-agenda-files)))
14718 (defun org-store-new-agenda-file-list (list)
14719 "Set new value for the agenda file list and save it correctly."
14720 (if (stringp org-agenda-files)
14721 (let ((fe (org-read-agenda-file-list t)) b u)
14722 (while (setq b (find-buffer-visiting org-agenda-files))
14723 (kill-buffer b))
14724 (with-temp-file org-agenda-files
14725 (insert
14726 (mapconcat
14727 (lambda (f) ;; Keep un-expanded entries.
14728 (if (setq u (assoc f fe))
14729 (cdr u)
14731 list "\n")
14732 "\n")))
14733 (let ((org-mode-hook nil) (org-inhibit-startup t)
14734 (org-insert-mode-line-in-empty-file nil))
14735 (setq org-agenda-files list)
14736 (customize-save-variable 'org-agenda-files org-agenda-files))))
14738 (defun org-read-agenda-file-list (&optional pair-with-expansion)
14739 "Read the list of agenda files from a file.
14740 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
14741 filenames, used by `org-store-new-agenda-file-list' to write back
14742 un-expanded file names."
14743 (when (file-directory-p org-agenda-files)
14744 (error "`org-agenda-files' cannot be a single directory"))
14745 (when (stringp org-agenda-files)
14746 (with-temp-buffer
14747 (insert-file-contents org-agenda-files)
14748 (mapcar
14749 (lambda (f)
14750 (let ((e (expand-file-name (substitute-in-file-name f)
14751 org-directory)))
14752 (if pair-with-expansion
14753 (cons e f)
14754 e)))
14755 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
14757 ;;;###autoload
14758 (defun org-cycle-agenda-files ()
14759 "Cycle through the files in `org-agenda-files'.
14760 If the current buffer visits an agenda file, find the next one in the list.
14761 If the current buffer does not, find the first agenda file."
14762 (interactive)
14763 (let* ((fs (org-agenda-files t))
14764 (files (append fs (list (car fs))))
14765 (tcf (if buffer-file-name (file-truename buffer-file-name)))
14766 file)
14767 (unless files (error "No agenda files"))
14768 (catch 'exit
14769 (while (setq file (pop files))
14770 (if (equal (file-truename file) tcf)
14771 (when (car files)
14772 (find-file (car files))
14773 (throw 'exit t))))
14774 (find-file (car fs)))
14775 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
14777 (defun org-agenda-file-to-front (&optional to-end)
14778 "Move/add the current file to the top of the agenda file list.
14779 If the file is not present in the list, it is added to the front. If it is
14780 present, it is moved there. With optional argument TO-END, add/move to the
14781 end of the list."
14782 (interactive "P")
14783 (let ((org-agenda-skip-unavailable-files nil)
14784 (file-alist (mapcar (lambda (x)
14785 (cons (file-truename x) x))
14786 (org-agenda-files t)))
14787 (ctf (file-truename buffer-file-name))
14788 x had)
14789 (setq x (assoc ctf file-alist) had x)
14791 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
14792 (if to-end
14793 (setq file-alist (append (delq x file-alist) (list x)))
14794 (setq file-alist (cons x (delq x file-alist))))
14795 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
14796 (org-install-agenda-files-menu)
14797 (message "File %s to %s of agenda file list"
14798 (if had "moved" "added") (if to-end "end" "front"))))
14800 (defun org-remove-file (&optional file)
14801 "Remove current file from the list of files in variable `org-agenda-files'.
14802 These are the files which are being checked for agenda entries.
14803 Optional argument FILE means use this file instead of the current."
14804 (interactive)
14805 (let* ((org-agenda-skip-unavailable-files nil)
14806 (file (or file buffer-file-name))
14807 (true-file (file-truename file))
14808 (afile (abbreviate-file-name file))
14809 (files (delq nil (mapcar
14810 (lambda (x)
14811 (if (equal true-file
14812 (file-truename x))
14813 nil x))
14814 (org-agenda-files t)))))
14815 (if (not (= (length files) (length (org-agenda-files t))))
14816 (progn
14817 (org-store-new-agenda-file-list files)
14818 (org-install-agenda-files-menu)
14819 (message "Removed file: %s" afile))
14820 (message "File was not in list: %s (not removed)" afile))))
14822 (defun org-file-menu-entry (file)
14823 (vector file (list 'find-file file) t))
14825 (defun org-check-agenda-file (file)
14826 "Make sure FILE exists. If not, ask user what to do."
14827 (when (not (file-exists-p file))
14828 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
14829 (abbreviate-file-name file))
14830 (let ((r (downcase (read-char-exclusive))))
14831 (cond
14832 ((equal r ?r)
14833 (org-remove-file file)
14834 (throw 'nextfile t))
14835 (t (error "Abort"))))))
14837 (defun org-get-agenda-file-buffer (file)
14838 "Get a buffer visiting FILE. If the buffer needs to be created, add
14839 it to the list of buffers which might be released later."
14840 (let ((buf (org-find-base-buffer-visiting file)))
14841 (if buf
14842 buf ; just return it
14843 ;; Make a new buffer and remember it
14844 (setq buf (find-file-noselect file))
14845 (if buf (push buf org-agenda-new-buffers))
14846 buf)))
14848 (defun org-release-buffers (blist)
14849 "Release all buffers in list, asking the user for confirmation when needed.
14850 When a buffer is unmodified, it is just killed. When modified, it is saved
14851 \(if the user agrees) and then killed."
14852 (let (buf file)
14853 (while (setq buf (pop blist))
14854 (setq file (buffer-file-name buf))
14855 (when (and (buffer-modified-p buf)
14856 file
14857 (y-or-n-p (format "Save file %s? " file)))
14858 (with-current-buffer buf (save-buffer)))
14859 (kill-buffer buf))))
14861 (defun org-prepare-agenda-buffers (files)
14862 "Create buffers for all agenda files, protect archived trees and comments."
14863 (interactive)
14864 (let ((pa '(:org-archived t))
14865 (pc '(:org-comment t))
14866 (pall '(:org-archived t :org-comment t))
14867 (inhibit-read-only t)
14868 (rea (concat ":" org-archive-tag ":"))
14869 bmp file re)
14870 (save-excursion
14871 (save-restriction
14872 (while (setq file (pop files))
14873 (catch 'nextfile
14874 (if (bufferp file)
14875 (set-buffer file)
14876 (org-check-agenda-file file)
14877 (set-buffer (org-get-agenda-file-buffer file)))
14878 (widen)
14879 (setq bmp (buffer-modified-p))
14880 (org-refresh-category-properties)
14881 (setq org-todo-keywords-for-agenda
14882 (append org-todo-keywords-for-agenda org-todo-keywords-1))
14883 (setq org-done-keywords-for-agenda
14884 (append org-done-keywords-for-agenda org-done-keywords))
14885 (setq org-todo-keyword-alist-for-agenda
14886 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
14887 (setq org-drawers-for-agenda
14888 (append org-drawers-for-agenda org-drawers))
14889 (setq org-tag-alist-for-agenda
14890 (append org-tag-alist-for-agenda org-tag-alist))
14892 (save-excursion
14893 (remove-text-properties (point-min) (point-max) pall)
14894 (when org-agenda-skip-archived-trees
14895 (goto-char (point-min))
14896 (while (re-search-forward rea nil t)
14897 (if (org-on-heading-p t)
14898 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
14899 (goto-char (point-min))
14900 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
14901 (while (re-search-forward re nil t)
14902 (add-text-properties
14903 (match-beginning 0) (org-end-of-subtree t) pc)))
14904 (set-buffer-modified-p bmp)))))
14905 (setq org-todo-keyword-alist-for-agenda
14906 (org-uniquify org-todo-keyword-alist-for-agenda)
14907 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
14909 ;;;; Embedded LaTeX
14911 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14912 "Keymap for the minor `org-cdlatex-mode'.")
14914 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14915 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14916 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14917 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14918 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14920 (defvar org-cdlatex-texmathp-advice-is-done nil
14921 "Flag remembering if we have applied the advice to texmathp already.")
14923 (define-minor-mode org-cdlatex-mode
14924 "Toggle the minor `org-cdlatex-mode'.
14925 This mode supports entering LaTeX environment and math in LaTeX fragments
14926 in Org-mode.
14927 \\{org-cdlatex-mode-map}"
14928 nil " OCDL" nil
14929 (when org-cdlatex-mode (require 'cdlatex))
14930 (unless org-cdlatex-texmathp-advice-is-done
14931 (setq org-cdlatex-texmathp-advice-is-done t)
14932 (defadvice texmathp (around org-math-always-on activate)
14933 "Always return t in org-mode buffers.
14934 This is because we want to insert math symbols without dollars even outside
14935 the LaTeX math segments. If Orgmode thinks that point is actually inside
14936 an embedded LaTeX fragment, let texmathp do its job.
14937 \\[org-cdlatex-mode-map]"
14938 (interactive)
14939 (let (p)
14940 (cond
14941 ((not (org-mode-p)) ad-do-it)
14942 ((eq this-command 'cdlatex-math-symbol)
14943 (setq ad-return-value t
14944 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
14946 (let ((p (org-inside-LaTeX-fragment-p)))
14947 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
14948 (setq ad-return-value t
14949 texmathp-why '("Org-mode embedded math" . 0))
14950 (if p ad-do-it)))))))))
14952 (defun turn-on-org-cdlatex ()
14953 "Unconditionally turn on `org-cdlatex-mode'."
14954 (org-cdlatex-mode 1))
14956 (defun org-inside-LaTeX-fragment-p ()
14957 "Test if point is inside a LaTeX fragment.
14958 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
14959 sequence appearing also before point.
14960 Even though the matchers for math are configurable, this function assumes
14961 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
14962 delimiters are skipped when they have been removed by customization.
14963 The return value is nil, or a cons cell with the delimiter and
14964 and the position of this delimiter.
14966 This function does a reasonably good job, but can locally be fooled by
14967 for example currency specifications. For example it will assume being in
14968 inline math after \"$22.34\". The LaTeX fragment formatter will only format
14969 fragments that are properly closed, but during editing, we have to live
14970 with the uncertainty caused by missing closing delimiters. This function
14971 looks only before point, not after."
14972 (catch 'exit
14973 (let ((pos (point))
14974 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
14975 (lim (progn
14976 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
14977 (point)))
14978 dd-on str (start 0) m re)
14979 (goto-char pos)
14980 (when dodollar
14981 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
14982 re (nth 1 (assoc "$" org-latex-regexps)))
14983 (while (string-match re str start)
14984 (cond
14985 ((= (match-end 0) (length str))
14986 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
14987 ((= (match-end 0) (- (length str) 5))
14988 (throw 'exit nil))
14989 (t (setq start (match-end 0))))))
14990 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
14991 (goto-char pos)
14992 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
14993 (and (match-beginning 2) (throw 'exit nil))
14994 ;; count $$
14995 (while (re-search-backward "\\$\\$" lim t)
14996 (setq dd-on (not dd-on)))
14997 (goto-char pos)
14998 (if dd-on (cons "$$" m))))))
15000 (defun org-inside-latex-macro-p ()
15001 "Is point inside a LaTeX macro or its arguments?"
15002 (save-match-data
15003 (org-in-regexp
15004 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
15006 (defun test ()
15007 (interactive)
15008 (message "%s" (org-inside-latex-macro-p)))
15010 (defun org-try-cdlatex-tab ()
15011 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
15012 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
15013 - inside a LaTeX fragment, or
15014 - after the first word in a line, where an abbreviation expansion could
15015 insert a LaTeX environment."
15016 (when org-cdlatex-mode
15017 (cond
15018 ((save-excursion
15019 (skip-chars-backward "a-zA-Z0-9*")
15020 (skip-chars-backward " \t")
15021 (bolp))
15022 (cdlatex-tab) t)
15023 ((org-inside-LaTeX-fragment-p)
15024 (cdlatex-tab) t)
15025 (t nil))))
15027 (defun org-cdlatex-underscore-caret (&optional arg)
15028 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
15029 Revert to the normal definition outside of these fragments."
15030 (interactive "P")
15031 (if (org-inside-LaTeX-fragment-p)
15032 (call-interactively 'cdlatex-sub-superscript)
15033 (let (org-cdlatex-mode)
15034 (call-interactively (key-binding (vector last-input-event))))))
15036 (defun org-cdlatex-math-modify (&optional arg)
15037 "Execute `cdlatex-math-modify' in LaTeX fragments.
15038 Revert to the normal definition outside of these fragments."
15039 (interactive "P")
15040 (if (org-inside-LaTeX-fragment-p)
15041 (call-interactively 'cdlatex-math-modify)
15042 (let (org-cdlatex-mode)
15043 (call-interactively (key-binding (vector last-input-event))))))
15045 (defvar org-latex-fragment-image-overlays nil
15046 "List of overlays carrying the images of latex fragments.")
15047 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
15049 (defun org-remove-latex-fragment-image-overlays ()
15050 "Remove all overlays with LaTeX fragment images in current buffer."
15051 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
15052 (setq org-latex-fragment-image-overlays nil))
15054 (defun org-preview-latex-fragment (&optional subtree)
15055 "Preview the LaTeX fragment at point, or all locally or globally.
15056 If the cursor is in a LaTeX fragment, create the image and overlay
15057 it over the source code. If there is no fragment at point, display
15058 all fragments in the current text, from one headline to the next. With
15059 prefix SUBTREE, display all fragments in the current subtree. With a
15060 double prefix `C-u C-u', or when the cursor is before the first headline,
15061 display all fragments in the buffer.
15062 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
15063 (interactive "P")
15064 (org-remove-latex-fragment-image-overlays)
15065 (save-excursion
15066 (save-restriction
15067 (let (beg end at msg)
15068 (cond
15069 ((or (equal subtree '(16))
15070 (not (save-excursion
15071 (re-search-backward (concat "^" outline-regexp) nil t))))
15072 (setq beg (point-min) end (point-max)
15073 msg "Creating images for buffer...%s"))
15074 ((equal subtree '(4))
15075 (org-back-to-heading)
15076 (setq beg (point) end (org-end-of-subtree t)
15077 msg "Creating images for subtree...%s"))
15079 (if (setq at (org-inside-LaTeX-fragment-p))
15080 (goto-char (max (point-min) (- (cdr at) 2)))
15081 (org-back-to-heading))
15082 (setq beg (point) end (progn (outline-next-heading) (point))
15083 msg (if at "Creating image...%s"
15084 "Creating images for entry...%s"))))
15085 (message msg "")
15086 (narrow-to-region beg end)
15087 (goto-char beg)
15088 (org-format-latex
15089 (concat "ltxpng/" (file-name-sans-extension
15090 (file-name-nondirectory
15091 buffer-file-name)))
15092 default-directory 'overlays msg at 'forbuffer)
15093 (message msg "done. Use `C-c C-c' to remove images.")))))
15095 (defvar org-latex-regexps
15096 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
15097 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
15098 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
15099 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15100 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15101 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
15102 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
15103 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
15104 "Regular expressions for matching embedded LaTeX.")
15106 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
15107 "Replace LaTeX fragments with links to an image, and produce images.
15108 Some of the options can be changed using the variable
15109 `org-format-latex-options'."
15110 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
15111 (let* ((prefixnodir (file-name-nondirectory prefix))
15112 (absprefix (expand-file-name prefix dir))
15113 (todir (file-name-directory absprefix))
15114 (opt org-format-latex-options)
15115 (matchers (plist-get opt :matchers))
15116 (re-list org-latex-regexps)
15117 (org-format-latex-header-extra
15118 (plist-get (org-infile-export-plist) :latex-header-extra))
15119 (cnt 0) txt hash link beg end re e checkdir
15120 executables-checked
15121 m n block linkfile movefile ov)
15122 ;; Check the different regular expressions
15123 (while (setq e (pop re-list))
15124 (setq m (car e) re (nth 1 e) n (nth 2 e)
15125 block (if (nth 3 e) "\n\n" ""))
15126 (when (member m matchers)
15127 (goto-char (point-min))
15128 (while (re-search-forward re nil t)
15129 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
15130 (not (get-text-property (match-beginning n)
15131 'org-protected))
15132 (or (not overlays)
15133 (not (eq (get-char-property (match-beginning n)
15134 'org-overlay-type)
15135 'org-latex-overlay))))
15136 (setq txt (match-string n)
15137 beg (match-beginning n) end (match-end n)
15138 cnt (1+ cnt))
15139 (let (print-length print-level) ; make sure full list is printed
15140 (setq hash (sha1 (prin1-to-string
15141 (list org-format-latex-header
15142 org-format-latex-header-extra
15143 org-export-latex-packages-alist
15144 org-format-latex-options
15145 forbuffer txt)))
15146 linkfile (format "%s_%s.png" prefix hash)
15147 movefile (format "%s_%s.png" absprefix hash)))
15148 (setq link (concat block "[[file:" linkfile "]]" block))
15149 (if msg (message msg cnt))
15150 (goto-char beg)
15151 (unless checkdir ; make sure the directory exists
15152 (setq checkdir t)
15153 (or (file-directory-p todir) (make-directory todir)))
15155 (unless executables-checked
15156 (org-check-external-command
15157 "latex" "needed to convert LaTeX fragments to images")
15158 (org-check-external-command
15159 "dvipng" "needed to convert LaTeX fragments to images")
15160 (setq executables-checked t))
15162 (unless (file-exists-p movefile)
15163 (org-create-formula-image
15164 txt movefile opt forbuffer))
15165 (if overlays
15166 (progn
15167 (mapc (lambda (o)
15168 (if (eq (org-overlay-get o 'org-overlay-type)
15169 'org-latex-overlay)
15170 (org-delete-overlay o)))
15171 (org-overlays-in beg end))
15172 (setq ov (org-make-overlay beg end))
15173 (org-overlay-put ov 'org-overlay-type 'org-latex-overlay)
15174 (if (featurep 'xemacs)
15175 (progn
15176 (org-overlay-put ov 'invisible t)
15177 (org-overlay-put
15178 ov 'end-glyph
15179 (make-glyph (vector 'png :file movefile))))
15180 (org-overlay-put
15181 ov 'display
15182 (list 'image :type 'png :file movefile :ascent 'center)))
15183 (push ov org-latex-fragment-image-overlays)
15184 (goto-char end))
15185 (delete-region beg end)
15186 (insert link))))))))
15188 ;; This function borrows from Ganesh Swami's latex2png.el
15189 (defun org-create-formula-image (string tofile options buffer)
15190 "This calls dvipng."
15191 (require 'org-latex)
15192 (let* ((tmpdir (if (featurep 'xemacs)
15193 (temp-directory)
15194 temporary-file-directory))
15195 (texfilebase (make-temp-name
15196 (expand-file-name "orgtex" tmpdir)))
15197 (texfile (concat texfilebase ".tex"))
15198 (dvifile (concat texfilebase ".dvi"))
15199 (pngfile (concat texfilebase ".png"))
15200 (fnh (if (featurep 'xemacs)
15201 (font-height (get-face-font 'default))
15202 (face-attribute 'default :height nil)))
15203 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
15204 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
15205 (fg (or (plist-get options (if buffer :foreground :html-foreground))
15206 "Black"))
15207 (bg (or (plist-get options (if buffer :background :html-background))
15208 "Transparent")))
15209 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
15210 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
15211 (with-temp-file texfile
15212 (insert org-format-latex-header
15213 (if org-export-latex-packages-alist
15214 (concat "\n"
15215 (mapconcat (lambda(p)
15216 (if (equal "" (car p))
15217 (format "\\usepackage{%s}" (cadr p))
15218 (format "\\usepackage[%s]{%s}"
15219 (car p) (cadr p))))
15220 org-export-latex-packages-alist "\n"))
15222 (if org-format-latex-header-extra
15223 (concat "\n" org-format-latex-header-extra)
15225 "\n\\begin{document}\n" string "\n\\end{document}\n"))
15226 (let ((dir default-directory))
15227 (condition-case nil
15228 (progn
15229 (cd tmpdir)
15230 (call-process "latex" nil nil nil texfile))
15231 (error nil))
15232 (cd dir))
15233 (if (not (file-exists-p dvifile))
15234 (progn (message "Failed to create dvi file from %s" texfile) nil)
15235 (condition-case nil
15236 (call-process "dvipng" nil nil nil
15237 "-fg" fg "-bg" bg
15238 "-D" dpi
15239 ;;"-x" scale "-y" scale
15240 "-T" "tight"
15241 "-o" pngfile
15242 dvifile)
15243 (error nil))
15244 (if (not (file-exists-p pngfile))
15245 (if org-format-latex-signal-error
15246 (error "Failed to create png file from %s" texfile)
15247 (message "Failed to create png file from %s" texfile)
15248 nil)
15249 ;; Use the requested file name and clean up
15250 (copy-file pngfile tofile 'replace)
15251 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
15252 (delete-file (concat texfilebase e)))
15253 pngfile))))
15255 (defun org-dvipng-color (attr)
15256 "Return an rgb color specification for dvipng."
15257 (apply 'format "rgb %s %s %s"
15258 (mapcar 'org-normalize-color
15259 (color-values (face-attribute 'default attr nil)))))
15261 (defun org-normalize-color (value)
15262 "Return string to be used as color value for an RGB component."
15263 (format "%g" (/ value 65535.0)))
15265 ;;;; Key bindings
15267 ;; Make `C-c C-x' a prefix key
15268 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
15270 ;; TAB key with modifiers
15271 (org-defkey org-mode-map "\C-i" 'org-cycle)
15272 (org-defkey org-mode-map [(tab)] 'org-cycle)
15273 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
15274 (org-defkey org-mode-map [(meta tab)] 'org-complete)
15275 (org-defkey org-mode-map "\M-\t" 'org-complete)
15276 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
15277 ;; The following line is necessary under Suse GNU/Linux
15278 (unless (featurep 'xemacs)
15279 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
15280 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
15281 (define-key org-mode-map [backtab] 'org-shifttab)
15283 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
15284 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
15285 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
15287 ;; Cursor keys with modifiers
15288 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
15289 (org-defkey org-mode-map [(meta right)] 'org-metaright)
15290 (org-defkey org-mode-map [(meta up)] 'org-metaup)
15291 (org-defkey org-mode-map [(meta down)] 'org-metadown)
15293 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
15294 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
15295 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
15296 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
15298 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
15299 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
15300 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
15301 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
15303 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
15304 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
15306 ;;; Extra keys for tty access.
15307 ;; We only set them when really needed because otherwise the
15308 ;; menus don't show the simple keys
15310 (when (or org-use-extra-keys
15311 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
15312 (not window-system))
15313 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
15314 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
15315 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
15316 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
15317 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
15318 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
15319 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
15320 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
15321 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
15322 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
15323 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
15324 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
15325 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
15326 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
15327 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
15328 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
15329 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
15330 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
15331 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
15332 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
15333 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
15334 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
15335 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
15336 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
15337 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
15338 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
15339 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
15340 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
15342 ;; All the other keys
15344 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
15345 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
15346 (if (boundp 'narrow-map)
15347 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
15348 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
15349 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
15350 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
15351 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
15352 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
15353 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
15354 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
15355 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
15356 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
15357 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
15358 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
15359 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
15360 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
15361 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
15362 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
15363 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
15364 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
15365 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
15366 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
15367 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
15368 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
15369 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
15370 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
15371 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
15372 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
15373 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
15374 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
15375 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
15376 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
15377 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
15378 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
15379 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
15380 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
15381 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
15382 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
15383 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
15384 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
15385 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
15386 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
15387 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
15388 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
15389 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
15390 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15391 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
15392 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
15393 (org-defkey org-mode-map "\C-c^" 'org-sort)
15394 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
15395 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
15396 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
15397 (org-defkey org-mode-map "\C-m" 'org-return)
15398 (org-defkey org-mode-map "\C-j" 'org-return-indent)
15399 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
15400 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
15401 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
15402 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
15403 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
15404 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
15405 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
15406 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
15407 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
15408 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
15409 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
15410 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
15411 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
15412 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
15413 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
15414 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
15415 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
15416 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
15417 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
15418 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
15420 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
15421 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
15422 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
15423 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
15425 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
15426 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
15427 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
15428 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
15429 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
15430 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
15431 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
15432 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
15433 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
15434 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
15435 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
15436 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
15437 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
15438 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
15439 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
15441 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
15442 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
15443 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
15444 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
15446 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
15448 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
15450 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
15451 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
15453 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
15456 (when (featurep 'xemacs)
15457 (org-defkey org-mode-map 'button3 'popup-mode-menu))
15460 (defconst org-speed-commands-default
15462 ("Outline Navigation")
15463 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
15464 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
15465 ("f" . (org-speed-move-safe 'org-forward-same-level))
15466 ("b" . (org-speed-move-safe 'org-backward-same-level))
15467 ("u" . (org-speed-move-safe 'outline-up-heading))
15468 ("j" . org-goto)
15469 ("g" . (org-refile t))
15470 ("Outline Visibility")
15471 ("c" . org-cycle)
15472 ("C" . org-shifttab)
15473 (" " . org-display-outline-path)
15474 ("Outline Structure Editing")
15475 ("U" . org-shiftmetaup)
15476 ("D" . org-shiftmetadown)
15477 ("r" . org-metaright)
15478 ("l" . org-metaleft)
15479 ("R" . org-shiftmetaright)
15480 ("L" . org-shiftmetaleft)
15481 ("i" . (progn (forward-char 1) (call-interactively
15482 'org-insert-heading-respect-content)))
15483 ("^" . org-sort)
15484 ("w" . org-refile)
15485 ("a" . org-archive-subtree-default-with-confirmation)
15486 ("." . outline-mark-subtree)
15487 ("Clock Commands")
15488 ("I" . org-clock-in)
15489 ("O" . org-clock-out)
15490 ("Meta Data Editing")
15491 ("t" . org-todo)
15492 ("0" . (org-priority ?\ ))
15493 ("1" . (org-priority ?A))
15494 ("2" . (org-priority ?B))
15495 ("3" . (org-priority ?C))
15496 (";" . org-set-tags-command)
15497 ("e" . org-set-effort)
15498 ("Agenda Views etc")
15499 ("v" . org-agenda)
15500 ("/" . org-sparse-tree)
15501 ("Misc")
15502 ("o" . org-open-at-point)
15503 ("?" . org-speed-command-help)
15505 "The default speed commands.")
15507 (defun org-print-speed-command (e)
15508 (if (> (length (car e)) 1)
15509 (progn
15510 (princ "\n")
15511 (princ (car e))
15512 (princ "\n")
15513 (princ (make-string (length (car e)) ?-))
15514 (princ "\n"))
15515 (princ (car e))
15516 (princ " ")
15517 (if (symbolp (cdr e))
15518 (princ (symbol-name (cdr e)))
15519 (prin1 (cdr e)))
15520 (princ "\n")))
15522 (defun org-speed-command-help ()
15523 "Show the available speed commands."
15524 (interactive)
15525 (if (not org-use-speed-commands)
15526 (error "Speed commands are not activated, customize `org-use-speed-commands'.")
15527 (with-output-to-temp-buffer "*Help*"
15528 (princ "User-defined Speed commands\n===========================\n")
15529 (mapc 'org-print-speed-command org-speed-commands-user)
15530 (princ "\n")
15531 (princ "Built-in Speed commands\n=======================\n")
15532 (mapc 'org-print-speed-command org-speed-commands-default))
15533 (with-current-buffer "*Help*"
15534 (setq truncate-lines t))))
15536 (defun org-speed-move-safe (cmd)
15537 "Execute CMD, but make sure that the cursor always ends up in a headline.
15538 If not, return to the original position and throw an error."
15539 (interactive)
15540 (let ((pos (point)))
15541 (call-interactively cmd)
15542 (unless (and (bolp) (org-on-heading-p))
15543 (goto-char pos)
15544 (error "Boundary reached while executing %s" cmd))))
15546 (defvar org-self-insert-command-undo-counter 0)
15548 (defvar org-table-auto-blank-field) ; defined in org-table.el
15549 (defvar org-speed-command nil)
15550 (defun org-self-insert-command (N)
15551 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
15552 If the cursor is in a table looking at whitespace, the whitespace is
15553 overwritten, and the table is not marked as requiring realignment."
15554 (interactive "p")
15555 (cond
15556 ((and org-use-speed-commands
15557 (or (and (bolp) (looking-at outline-regexp))
15558 (and (functionp org-use-speed-commands)
15559 (funcall org-use-speed-commands)))
15560 (setq
15561 org-speed-command
15562 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
15563 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
15564 (cond
15565 ((commandp org-speed-command)
15566 (setq this-command org-speed-command)
15567 (call-interactively org-speed-command))
15568 ((functionp org-speed-command)
15569 (funcall org-speed-command))
15570 ((and org-speed-command (listp org-speed-command))
15571 (eval org-speed-command))
15572 (t (let (org-use-speed-commands)
15573 (call-interactively 'org-self-insert-command)))))
15574 ((and
15575 (org-table-p)
15576 (progn
15577 ;; check if we blank the field, and if that triggers align
15578 (and (featurep 'org-table) org-table-auto-blank-field
15579 (member last-command
15580 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
15581 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
15582 ;; got extra space, this field does not determine column width
15583 (let (org-table-may-need-update) (org-table-blank-field))
15584 ;; no extra space, this field may determine column width
15585 (org-table-blank-field)))
15587 (eq N 1)
15588 (looking-at "[^|\n]* |"))
15589 (let (org-table-may-need-update)
15590 (goto-char (1- (match-end 0)))
15591 (delete-backward-char 1)
15592 (goto-char (match-beginning 0))
15593 (self-insert-command N)))
15595 (setq org-table-may-need-update t)
15596 (self-insert-command N)
15597 (org-fix-tags-on-the-fly)
15598 (if org-self-insert-cluster-for-undo
15599 (if (not (eq last-command 'org-self-insert-command))
15600 (setq org-self-insert-command-undo-counter 1)
15601 (if (>= org-self-insert-command-undo-counter 20)
15602 (setq org-self-insert-command-undo-counter 1)
15603 (and (> org-self-insert-command-undo-counter 0)
15604 buffer-undo-list
15605 (not (cadr buffer-undo-list)) ; remove nil entry
15606 (setcdr buffer-undo-list (cddr buffer-undo-list)))
15607 (setq org-self-insert-command-undo-counter
15608 (1+ org-self-insert-command-undo-counter))))))))
15610 (defun org-fix-tags-on-the-fly ()
15611 (when (and (equal (char-after (point-at-bol)) ?*)
15612 (org-on-heading-p))
15613 (org-align-tags-here org-tags-column)))
15615 (defun org-delete-backward-char (N)
15616 "Like `delete-backward-char', insert whitespace at field end in tables.
15617 When deleting backwards, in tables this function will insert whitespace in
15618 front of the next \"|\" separator, to keep the table aligned. The table will
15619 still be marked for re-alignment if the field did fill the entire column,
15620 because, in this case the deletion might narrow the column."
15621 (interactive "p")
15622 (if (and (org-table-p)
15623 (eq N 1)
15624 (string-match "|" (buffer-substring (point-at-bol) (point)))
15625 (looking-at ".*?|"))
15626 (let ((pos (point))
15627 (noalign (looking-at "[^|\n\r]* |"))
15628 (c org-table-may-need-update))
15629 (backward-delete-char N)
15630 (skip-chars-forward "^|")
15631 (insert " ")
15632 (goto-char (1- pos))
15633 ;; noalign: if there were two spaces at the end, this field
15634 ;; does not determine the width of the column.
15635 (if noalign (setq org-table-may-need-update c)))
15636 (backward-delete-char N)
15637 (org-fix-tags-on-the-fly)))
15639 (defun org-delete-char (N)
15640 "Like `delete-char', but insert whitespace at field end in tables.
15641 When deleting characters, in tables this function will insert whitespace in
15642 front of the next \"|\" separator, to keep the table aligned. The table will
15643 still be marked for re-alignment if the field did fill the entire column,
15644 because, in this case the deletion might narrow the column."
15645 (interactive "p")
15646 (if (and (org-table-p)
15647 (not (bolp))
15648 (not (= (char-after) ?|))
15649 (eq N 1))
15650 (if (looking-at ".*?|")
15651 (let ((pos (point))
15652 (noalign (looking-at "[^|\n\r]* |"))
15653 (c org-table-may-need-update))
15654 (replace-match (concat
15655 (substring (match-string 0) 1 -1)
15656 " |"))
15657 (goto-char pos)
15658 ;; noalign: if there were two spaces at the end, this field
15659 ;; does not determine the width of the column.
15660 (if noalign (setq org-table-may-need-update c)))
15661 (delete-char N))
15662 (delete-char N)
15663 (org-fix-tags-on-the-fly)))
15665 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
15666 (put 'org-self-insert-command 'delete-selection t)
15667 (put 'orgtbl-self-insert-command 'delete-selection t)
15668 (put 'org-delete-char 'delete-selection 'supersede)
15669 (put 'org-delete-backward-char 'delete-selection 'supersede)
15670 (put 'org-yank 'delete-selection 'yank)
15672 ;; Make `flyspell-mode' delay after some commands
15673 (put 'org-self-insert-command 'flyspell-delayed t)
15674 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
15675 (put 'org-delete-char 'flyspell-delayed t)
15676 (put 'org-delete-backward-char 'flyspell-delayed t)
15678 ;; Make pabbrev-mode expand after org-mode commands
15679 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
15680 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
15682 ;; How to do this: Measure non-white length of current string
15683 ;; If equal to column width, we should realign.
15685 (defun org-remap (map &rest commands)
15686 "In MAP, remap the functions given in COMMANDS.
15687 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
15688 (let (new old)
15689 (while commands
15690 (setq old (pop commands) new (pop commands))
15691 (if (fboundp 'command-remapping)
15692 (org-defkey map (vector 'remap old) new)
15693 (substitute-key-definition old new map global-map)))))
15695 (when (eq org-enable-table-editor 'optimized)
15696 ;; If the user wants maximum table support, we need to hijack
15697 ;; some standard editing functions
15698 (org-remap org-mode-map
15699 'self-insert-command 'org-self-insert-command
15700 'delete-char 'org-delete-char
15701 'delete-backward-char 'org-delete-backward-char)
15702 (org-defkey org-mode-map "|" 'org-force-self-insert))
15704 (defvar org-ctrl-c-ctrl-c-hook nil
15705 "Hook for functions attaching themselves to `C-c C-c'.
15706 This can be used to add additional functionality to the C-c C-c key which
15707 executes context-dependent commands.
15708 Each function will be called with no arguments. The function must check
15709 if the context is appropriate for it to act. If yes, it should do its
15710 thing and then return a non-nil value. If the context is wrong,
15711 just do nothing and return nil.")
15713 (defvar org-tab-first-hook nil
15714 "Hook for functions to attach themselves to TAB.
15715 See `org-ctrl-c-ctrl-c-hook' for more information.
15716 This hook runs as the first action when TAB is pressed, even before
15717 `org-cycle' messes around with the `outline-regexp' to cater for
15718 inline tasks and plain list item folding.
15719 If any function in this hook returns t, not other actions like table
15720 field motion visibility cycling will be done.")
15722 (defvar org-tab-after-check-for-table-hook nil
15723 "Hook for functions to attach themselves to TAB.
15724 See `org-ctrl-c-ctrl-c-hook' for more information.
15725 This hook runs after it has been established that the cursor is not in a
15726 table, but before checking if the cursor is in a headline or if global cycling
15727 should be done.
15728 If any function in this hook returns t, not other actions like visibility
15729 cycling will be done.")
15731 (defvar org-tab-after-check-for-cycling-hook nil
15732 "Hook for functions to attach themselves to TAB.
15733 See `org-ctrl-c-ctrl-c-hook' for more information.
15734 This hook runs after it has been established that not table field motion and
15735 not visibility should be done because of current context. This is probably
15736 the place where a package like yasnippets can hook in.")
15738 (defvar org-tab-before-tab-emulation-hook nil
15739 "Hook for functions to attach themselves to TAB.
15740 See `org-ctrl-c-ctrl-c-hook' for more information.
15741 This hook runs after every other options for TAB have been exhausted, but
15742 before indentation and \t insertion takes place.")
15744 (defvar org-metaleft-hook nil
15745 "Hook for functions attaching themselves to `M-left'.
15746 See `org-ctrl-c-ctrl-c-hook' for more information.")
15747 (defvar org-metaright-hook nil
15748 "Hook for functions attaching themselves to `M-right'.
15749 See `org-ctrl-c-ctrl-c-hook' for more information.")
15750 (defvar org-metaup-hook nil
15751 "Hook for functions attaching themselves to `M-up'.
15752 See `org-ctrl-c-ctrl-c-hook' for more information.")
15753 (defvar org-metadown-hook nil
15754 "Hook for functions attaching themselves to `M-down'.
15755 See `org-ctrl-c-ctrl-c-hook' for more information.")
15756 (defvar org-shiftmetaleft-hook nil
15757 "Hook for functions attaching themselves to `M-S-left'.
15758 See `org-ctrl-c-ctrl-c-hook' for more information.")
15759 (defvar org-shiftmetaright-hook nil
15760 "Hook for functions attaching themselves to `M-S-right'.
15761 See `org-ctrl-c-ctrl-c-hook' for more information.")
15762 (defvar org-shiftmetaup-hook nil
15763 "Hook for functions attaching themselves to `M-S-up'.
15764 See `org-ctrl-c-ctrl-c-hook' for more information.")
15765 (defvar org-shiftmetadown-hook nil
15766 "Hook for functions attaching themselves to `M-S-down'.
15767 See `org-ctrl-c-ctrl-c-hook' for more information.")
15768 (defvar org-metareturn-hook nil
15769 "Hook for functions attaching themselves to `M-RET'.
15770 See `org-ctrl-c-ctrl-c-hook' for more information.")
15772 (defun org-modifier-cursor-error ()
15773 "Throw an error, a modified cursor command was applied in wrong context."
15774 (error "This command is active in special context like tables, headlines or items"))
15776 (defun org-shiftselect-error ()
15777 "Throw an error because Shift-Cursor command was applied in wrong context."
15778 (if (and (boundp 'shift-select-mode) shift-select-mode)
15779 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
15780 (error "This command works only in special context like headlines or timestamps")))
15782 (defun org-call-for-shift-select (cmd)
15783 (let ((this-command-keys-shift-translated t))
15784 (call-interactively cmd)))
15786 (defun org-shifttab (&optional arg)
15787 "Global visibility cycling or move to previous table field.
15788 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15789 on context.
15790 See the individual commands for more information."
15791 (interactive "P")
15792 (cond
15793 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15794 ((integerp arg)
15795 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
15796 (message "Content view to level: %d" arg)
15797 (org-content (prefix-numeric-value arg2))
15798 (setq org-cycle-global-status 'overview)))
15799 (t (call-interactively 'org-global-cycle))))
15801 (defun org-shiftmetaleft ()
15802 "Promote subtree or delete table column.
15803 Calls `org-promote-subtree', `org-outdent-item',
15804 or `org-table-delete-column', depending on context.
15805 See the individual commands for more information."
15806 (interactive)
15807 (cond
15808 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
15809 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15810 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15811 ((org-at-item-p) (call-interactively 'org-outdent-item))
15812 (t (org-modifier-cursor-error))))
15814 (defun org-shiftmetaright ()
15815 "Demote subtree or insert table column.
15816 Calls `org-demote-subtree', `org-indent-item',
15817 or `org-table-insert-column', depending on context.
15818 See the individual commands for more information."
15819 (interactive)
15820 (cond
15821 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
15822 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15823 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15824 ((org-at-item-p) (call-interactively 'org-indent-item))
15825 (t (org-modifier-cursor-error))))
15827 (defun org-shiftmetaup (&optional arg)
15828 "Move subtree up or kill table row.
15829 Calls `org-move-subtree-up' or `org-table-kill-row' or
15830 `org-move-item-up' depending on context. See the individual commands
15831 for more information."
15832 (interactive "P")
15833 (cond
15834 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
15835 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15836 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15837 ((org-at-item-p) (call-interactively 'org-move-item-up))
15838 (t (org-modifier-cursor-error))))
15840 (defun org-shiftmetadown (&optional arg)
15841 "Move subtree down or insert table row.
15842 Calls `org-move-subtree-down' or `org-table-insert-row' or
15843 `org-move-item-down', depending on context. See the individual
15844 commands for more information."
15845 (interactive "P")
15846 (cond
15847 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
15848 ((org-at-table-p) (call-interactively 'org-table-insert-row))
15849 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15850 ((org-at-item-p) (call-interactively 'org-move-item-down))
15851 (t (org-modifier-cursor-error))))
15853 (defun org-metaleft (&optional arg)
15854 "Promote heading or move table column to left.
15855 Calls `org-do-promote' or `org-table-move-column', depending on context.
15856 With no specific context, calls the Emacs default `backward-word'.
15857 See the individual commands for more information."
15858 (interactive "P")
15859 (cond
15860 ((run-hook-with-args-until-success 'org-metaleft-hook))
15861 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
15862 ((or (org-on-heading-p)
15863 (and (org-region-active-p)
15864 (save-excursion
15865 (goto-char (region-beginning))
15866 (org-on-heading-p))))
15867 (call-interactively 'org-do-promote))
15868 ((or (org-at-item-p)
15869 (and (org-region-active-p)
15870 (save-excursion
15871 (goto-char (region-beginning))
15872 (org-at-item-p))))
15873 (call-interactively 'org-outdent-item))
15874 (t (call-interactively 'backward-word))))
15876 (defun org-metaright (&optional arg)
15877 "Demote subtree or move table column to right.
15878 Calls `org-do-demote' or `org-table-move-column', depending on context.
15879 With no specific context, calls the Emacs default `forward-word'.
15880 See the individual commands for more information."
15881 (interactive "P")
15882 (cond
15883 ((run-hook-with-args-until-success 'org-metaright-hook))
15884 ((org-at-table-p) (call-interactively 'org-table-move-column))
15885 ((or (org-on-heading-p)
15886 (and (org-region-active-p)
15887 (save-excursion
15888 (goto-char (region-beginning))
15889 (org-on-heading-p))))
15890 (call-interactively 'org-do-demote))
15891 ((or (org-at-item-p)
15892 (and (org-region-active-p)
15893 (save-excursion
15894 (goto-char (region-beginning))
15895 (org-at-item-p))))
15896 (call-interactively 'org-indent-item))
15897 (t (call-interactively 'forward-word))))
15899 (defun org-metaup (&optional arg)
15900 "Move subtree up or move table row up.
15901 Calls `org-move-subtree-up' or `org-table-move-row' or
15902 `org-move-item-up', depending on context. See the individual commands
15903 for more information."
15904 (interactive "P")
15905 (cond
15906 ((run-hook-with-args-until-success 'org-metaup-hook))
15907 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
15908 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15909 ((org-at-item-p) (call-interactively 'org-move-item-up))
15910 (t (transpose-lines 1) (beginning-of-line -1))))
15912 (defun org-metadown (&optional arg)
15913 "Move subtree down or move table row down.
15914 Calls `org-move-subtree-down' or `org-table-move-row' or
15915 `org-move-item-down', depending on context. See the individual
15916 commands for more information."
15917 (interactive "P")
15918 (cond
15919 ((run-hook-with-args-until-success 'org-metadown-hook))
15920 ((org-at-table-p) (call-interactively 'org-table-move-row))
15921 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15922 ((org-at-item-p) (call-interactively 'org-move-item-down))
15923 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
15925 (defun org-shiftup (&optional arg)
15926 "Increase item in timestamp or increase priority of current headline.
15927 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
15928 depending on context. See the individual commands for more information."
15929 (interactive "P")
15930 (cond
15931 ((and org-support-shift-select (org-region-active-p))
15932 (org-call-for-shift-select 'previous-line))
15933 ((org-at-timestamp-p t)
15934 (call-interactively (if org-edit-timestamp-down-means-later
15935 'org-timestamp-down 'org-timestamp-up)))
15936 ((and (not (eq org-support-shift-select 'always))
15937 org-enable-priority-commands
15938 (org-on-heading-p))
15939 (call-interactively 'org-priority-up))
15940 ((and (not org-support-shift-select) (org-at-item-p))
15941 (call-interactively 'org-previous-item))
15942 ((org-clocktable-try-shift 'up arg))
15943 (org-support-shift-select
15944 (org-call-for-shift-select 'previous-line))
15945 (t (org-shiftselect-error))))
15947 (defun org-shiftdown (&optional arg)
15948 "Decrease item in timestamp or decrease priority of current headline.
15949 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
15950 depending on context. See the individual commands for more information."
15951 (interactive "P")
15952 (cond
15953 ((and org-support-shift-select (org-region-active-p))
15954 (org-call-for-shift-select 'next-line))
15955 ((org-at-timestamp-p t)
15956 (call-interactively (if org-edit-timestamp-down-means-later
15957 'org-timestamp-up 'org-timestamp-down)))
15958 ((and (not (eq org-support-shift-select 'always))
15959 org-enable-priority-commands
15960 (org-on-heading-p))
15961 (call-interactively 'org-priority-down))
15962 ((and (not org-support-shift-select) (org-at-item-p))
15963 (call-interactively 'org-next-item))
15964 ((org-clocktable-try-shift 'down arg))
15965 (org-support-shift-select
15966 (org-call-for-shift-select 'next-line))
15967 (t (org-shiftselect-error))))
15969 (defun org-shiftright (&optional arg)
15970 "Cycle the thing at point or in the current line, depending on context.
15971 Depending on context, this does one of the following:
15973 - switch a timestamp at point one day into the future
15974 - on a headline, switch to the next TODO keyword.
15975 - on an item, switch entire list to the next bullet type
15976 - on a property line, switch to the next allowed value
15977 - on a clocktable definition line, move time block into the future"
15978 (interactive "P")
15979 (cond
15980 ((and org-support-shift-select (org-region-active-p))
15981 (org-call-for-shift-select 'forward-char))
15982 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
15983 ((and (not (eq org-support-shift-select 'always))
15984 (org-on-heading-p))
15985 (let ((org-inhibit-logging
15986 (not org-treat-S-cursor-todo-selection-as-state-change))
15987 (org-inhibit-blocking
15988 (not org-treat-S-cursor-todo-selection-as-state-change)))
15989 (org-call-with-arg 'org-todo 'right)))
15990 ((or (and org-support-shift-select
15991 (not (eq org-support-shift-select 'always))
15992 (org-at-item-bullet-p))
15993 (and (not org-support-shift-select) (org-at-item-p)))
15994 (org-call-with-arg 'org-cycle-list-bullet nil))
15995 ((and (not (eq org-support-shift-select 'always))
15996 (org-at-property-p))
15997 (call-interactively 'org-property-next-allowed-value))
15998 ((org-clocktable-try-shift 'right arg))
15999 (org-support-shift-select
16000 (org-call-for-shift-select 'forward-char))
16001 (t (org-shiftselect-error))))
16003 (defun org-shiftleft (&optional arg)
16004 "Cycle the thing at point or in the current line, depending on context.
16005 Depending on context, this does one of the following:
16007 - switch a timestamp at point one day into the past
16008 - on a headline, switch to the previous TODO keyword.
16009 - on an item, switch entire list to the previous bullet type
16010 - on a property line, switch to the previous allowed value
16011 - on a clocktable definition line, move time block into the past"
16012 (interactive "P")
16013 (cond
16014 ((and org-support-shift-select (org-region-active-p))
16015 (org-call-for-shift-select 'backward-char))
16016 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
16017 ((and (not (eq org-support-shift-select 'always))
16018 (org-on-heading-p))
16019 (let ((org-inhibit-logging
16020 (not org-treat-S-cursor-todo-selection-as-state-change))
16021 (org-inhibit-blocking
16022 (not org-treat-S-cursor-todo-selection-as-state-change)))
16023 (org-call-with-arg 'org-todo 'left)))
16024 ((or (and org-support-shift-select
16025 (not (eq org-support-shift-select 'always))
16026 (org-at-item-bullet-p))
16027 (and (not org-support-shift-select) (org-at-item-p)))
16028 (org-call-with-arg 'org-cycle-list-bullet 'previous))
16029 ((and (not (eq org-support-shift-select 'always))
16030 (org-at-property-p))
16031 (call-interactively 'org-property-previous-allowed-value))
16032 ((org-clocktable-try-shift 'left arg))
16033 (org-support-shift-select
16034 (org-call-for-shift-select 'backward-char))
16035 (t (org-shiftselect-error))))
16037 (defun org-shiftcontrolright ()
16038 "Switch to next TODO set."
16039 (interactive)
16040 (cond
16041 ((and org-support-shift-select (org-region-active-p))
16042 (org-call-for-shift-select 'forward-word))
16043 ((and (not (eq org-support-shift-select 'always))
16044 (org-on-heading-p))
16045 (org-call-with-arg 'org-todo 'nextset))
16046 (org-support-shift-select
16047 (org-call-for-shift-select 'forward-word))
16048 (t (org-shiftselect-error))))
16050 (defun org-shiftcontrolleft ()
16051 "Switch to previous TODO set."
16052 (interactive)
16053 (cond
16054 ((and org-support-shift-select (org-region-active-p))
16055 (org-call-for-shift-select 'backward-word))
16056 ((and (not (eq org-support-shift-select 'always))
16057 (org-on-heading-p))
16058 (org-call-with-arg 'org-todo 'previousset))
16059 (org-support-shift-select
16060 (org-call-for-shift-select 'backward-word))
16061 (t (org-shiftselect-error))))
16063 (defun org-ctrl-c-ret ()
16064 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
16065 (interactive)
16066 (cond
16067 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
16068 (t (call-interactively 'org-insert-heading))))
16070 (defun org-copy-special ()
16071 "Copy region in table or copy current subtree.
16072 Calls `org-table-copy' or `org-copy-subtree', depending on context.
16073 See the individual commands for more information."
16074 (interactive)
16075 (call-interactively
16076 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
16078 (defun org-cut-special ()
16079 "Cut region in table or cut current subtree.
16080 Calls `org-table-copy' or `org-cut-subtree', depending on context.
16081 See the individual commands for more information."
16082 (interactive)
16083 (call-interactively
16084 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
16086 (defun org-paste-special (arg)
16087 "Paste rectangular region into table, or past subtree relative to level.
16088 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
16089 See the individual commands for more information."
16090 (interactive "P")
16091 (if (org-at-table-p)
16092 (org-table-paste-rectangle)
16093 (org-paste-subtree arg)))
16095 (defun org-edit-special ()
16096 "Call a special editor for the stuff at point.
16097 When at a table, call the formula editor with `org-table-edit-formulas'.
16098 When at the first line of an src example, call `org-edit-src-code'.
16099 When in an #+include line, visit the include file. Otherwise call
16100 `ffap' to visit the file at point."
16101 (interactive)
16102 (cond
16103 ((org-at-table.el-p)
16104 (org-edit-src-code))
16105 ((org-at-table-p)
16106 (call-interactively 'org-table-edit-formulas))
16107 ((save-excursion
16108 (beginning-of-line 1)
16109 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
16110 (find-file (org-trim (match-string 1))))
16111 ((org-edit-src-code))
16112 ((org-edit-fixed-width-region))
16113 (t (call-interactively 'ffap))))
16116 (defun org-ctrl-c-ctrl-c (&optional arg)
16117 "Set tags in headline, or update according to changed information at point.
16119 This command does many different things, depending on context:
16121 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
16122 this is what we do.
16124 - If the cursor is on a statistics cookie, update it.
16126 - If the cursor is in a headline, prompt for tags and insert them
16127 into the current line, aligned to `org-tags-column'. When called
16128 with prefix arg, realign all tags in the current buffer.
16130 - If the cursor is in one of the special #+KEYWORD lines, this
16131 triggers scanning the buffer for these lines and updating the
16132 information.
16134 - If the cursor is inside a table, realign the table. This command
16135 works even if the automatic table editor has been turned off.
16137 - If the cursor is on a #+TBLFM line, re-apply the formulas to
16138 the entire table.
16140 - If the cursor is at a footnote reference or definition, jump to
16141 the corresponding definition or references, respectively.
16143 - If the cursor is a the beginning of a dynamic block, update it.
16145 - If the current buffer is a remember buffer, close note and file
16146 it. A prefix argument of 1 files to the default location
16147 without further interaction. A prefix argument of 2 files to
16148 the currently clocking task.
16150 - If the cursor is on a <<<target>>>, update radio targets and corresponding
16151 links in this buffer.
16153 - If the cursor is on a numbered item in a plain list, renumber the
16154 ordered list.
16156 - If the cursor is on a checkbox, toggle it."
16157 (interactive "P")
16158 (let ((org-enable-table-editor t))
16159 (cond
16160 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
16161 org-occur-highlights
16162 org-latex-fragment-image-overlays)
16163 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
16164 (org-remove-occur-highlights)
16165 (org-remove-latex-fragment-image-overlays)
16166 (message "Temporary highlights/overlays removed from current buffer"))
16167 ((and (local-variable-p 'org-finish-function (current-buffer))
16168 (fboundp org-finish-function))
16169 (funcall org-finish-function))
16170 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
16171 ((or (looking-at (org-re org-property-start-re))
16172 (org-at-property-p))
16173 (call-interactively 'org-property-action))
16174 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
16175 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
16176 (or (org-on-heading-p) (org-at-item-p)))
16177 (call-interactively 'org-update-statistics-cookies))
16178 ((org-on-heading-p) (call-interactively 'org-set-tags))
16179 ((org-at-table.el-p)
16180 (message "Use C-c ' to edit table.el tables"))
16181 ((org-at-table-p)
16182 (org-table-maybe-eval-formula)
16183 (if arg
16184 (call-interactively 'org-table-recalculate)
16185 (org-table-maybe-recalculate-line))
16186 (call-interactively 'org-table-align))
16187 ((or (org-footnote-at-reference-p)
16188 (org-footnote-at-definition-p))
16189 (call-interactively 'org-footnote-action))
16190 ((org-at-item-checkbox-p)
16191 (call-interactively 'org-toggle-checkbox))
16192 ((org-at-item-p)
16193 (if arg
16194 (call-interactively 'org-toggle-checkbox)
16195 (call-interactively 'org-maybe-renumber-ordered-list)))
16196 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
16197 ;; Dynamic block
16198 (beginning-of-line 1)
16199 (save-excursion (org-update-dblock)))
16200 ((save-excursion
16201 (beginning-of-line 1)
16202 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
16203 (cond
16204 ((equal (match-string 1) "TBLFM")
16205 ;; Recalculate the table before this line
16206 (save-excursion
16207 (beginning-of-line 1)
16208 (skip-chars-backward " \r\n\t")
16209 (if (org-at-table-p)
16210 (org-call-with-arg 'org-table-recalculate (or arg t)))))
16212 (let ((org-inhibit-startup-visibility-stuff t)
16213 (org-startup-align-all-tables nil))
16214 (org-save-outline-visibility 'use-markers (org-mode-restart)))
16215 (message "Local setup has been refreshed"))))
16216 ((org-clock-update-time-maybe))
16217 (t (error "C-c C-c can do nothing useful at this location")))))
16219 (defun org-mode-restart ()
16220 "Restart Org-mode, to scan again for special lines.
16221 Also updates the keyword regular expressions."
16222 (interactive)
16223 (org-mode)
16224 (message "Org-mode restarted"))
16226 (defun org-kill-note-or-show-branches ()
16227 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
16228 (interactive)
16229 (if (not org-finish-function)
16230 (call-interactively 'show-branches)
16231 (let ((org-note-abort t))
16232 (funcall org-finish-function))))
16234 (defun org-return (&optional indent)
16235 "Goto next table row or insert a newline.
16236 Calls `org-table-next-row' or `newline', depending on context.
16237 See the individual commands for more information."
16238 (interactive)
16239 (cond
16240 ((bobp) (if indent (newline-and-indent) (newline)))
16241 ((org-at-table-p)
16242 (org-table-justify-field-maybe)
16243 (call-interactively 'org-table-next-row))
16244 ((and org-return-follows-link
16245 (eq (get-text-property (point) 'face) 'org-link))
16246 (call-interactively 'org-open-at-point))
16247 ((and (org-at-heading-p)
16248 (looking-at
16249 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
16250 (org-show-entry)
16251 (end-of-line 1)
16252 (newline))
16253 (t (if indent (newline-and-indent) (newline)))))
16255 (defun org-return-indent ()
16256 "Goto next table row or insert a newline and indent.
16257 Calls `org-table-next-row' or `newline-and-indent', depending on
16258 context. See the individual commands for more information."
16259 (interactive)
16260 (org-return t))
16262 (defun org-ctrl-c-star ()
16263 "Compute table, or change heading status of lines.
16264 Calls `org-table-recalculate' or `org-toggle-heading',
16265 depending on context."
16266 (interactive)
16267 (cond
16268 ((org-at-table-p)
16269 (call-interactively 'org-table-recalculate))
16271 ;; Convert all lines in region to list items
16272 (call-interactively 'org-toggle-heading))))
16274 (defun org-ctrl-c-minus ()
16275 "Insert separator line in table or modify bullet status of line.
16276 Also turns a plain line or a region of lines into list items.
16277 Calls `org-table-insert-hline', `org-toggle-item', or
16278 `org-cycle-list-bullet', depending on context."
16279 (interactive)
16280 (cond
16281 ((org-at-table-p)
16282 (call-interactively 'org-table-insert-hline))
16283 ((org-region-active-p)
16284 (call-interactively 'org-toggle-item))
16285 ((org-in-item-p)
16286 (call-interactively 'org-cycle-list-bullet))
16288 (call-interactively 'org-toggle-item))))
16290 (defun org-toggle-item ()
16291 "Convert headings or normal lines to items, items to normal lines.
16292 If there is no active region, only the current line is considered.
16294 If the first line in the region is a headline, convert all headlines to items.
16296 If the first line in the region is an item, convert all items to normal lines.
16298 If the first line is normal text, add an item bullet to each line."
16299 (interactive)
16300 (let (l2 l beg end)
16301 (if (org-region-active-p)
16302 (setq beg (region-beginning) end (region-end))
16303 (setq beg (point-at-bol)
16304 end (min (1+ (point-at-eol)) (point-max))))
16305 (save-excursion
16306 (goto-char end)
16307 (setq l2 (org-current-line))
16308 (goto-char beg)
16309 (beginning-of-line 1)
16310 (setq l (1- (org-current-line)))
16311 (if (org-at-item-p)
16312 ;; We already have items, de-itemize
16313 (while (< (setq l (1+ l)) l2)
16314 (when (org-at-item-p)
16315 (goto-char (match-beginning 2))
16316 (delete-region (match-beginning 2) (match-end 2))
16317 (and (looking-at "[ \t]+") (replace-match "")))
16318 (beginning-of-line 2))
16319 (if (org-on-heading-p)
16320 ;; Headings, convert to items
16321 (while (< (setq l (1+ l)) l2)
16322 (if (looking-at org-outline-regexp)
16323 (replace-match "- " t t))
16324 (beginning-of-line 2))
16325 ;; normal lines, turn them into items
16326 (while (< (setq l (1+ l)) l2)
16327 (unless (org-at-item-p)
16328 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
16329 (replace-match "\\1- \\2")))
16330 (beginning-of-line 2)))))))
16332 (defun org-toggle-heading (&optional nstars)
16333 "Convert headings to normal text, or items or text to headings.
16334 If there is no active region, only the current line is considered.
16336 If the first line is a heading, remove the stars from all headlines
16337 in the region.
16339 If the first line is a plain list item, turn all plain list items
16340 into headings.
16342 If the first line is a normal line, turn each and every line in the
16343 region into a heading.
16345 When converting a line into a heading, the number of stars is chosen
16346 such that the lines become children of the current entry. However,
16347 when a prefix argument is given, its value determines the number of
16348 stars to add."
16349 (interactive "P")
16350 (let (l2 l itemp beg end)
16351 (if (org-region-active-p)
16352 (setq beg (region-beginning) end (region-end))
16353 (setq beg (point-at-bol)
16354 end (min (1+ (point-at-eol)) (point-max))))
16355 (save-excursion
16356 (goto-char end)
16357 (setq l2 (org-current-line))
16358 (goto-char beg)
16359 (beginning-of-line 1)
16360 (setq l (1- (org-current-line)))
16361 (if (org-on-heading-p)
16362 ;; We already have headlines, de-star them
16363 (while (< (setq l (1+ l)) l2)
16364 (when (org-on-heading-p t)
16365 (and (looking-at outline-regexp) (replace-match "")))
16366 (beginning-of-line 2))
16367 (setq itemp (org-at-item-p))
16368 (let* ((stars
16369 (if nstars
16370 (make-string (prefix-numeric-value current-prefix-arg)
16372 (save-excursion
16373 (if (re-search-backward org-complex-heading-regexp nil t)
16374 (match-string 1) ""))))
16375 (add-stars (cond (nstars "")
16376 ((equal stars "") "*")
16377 (org-odd-levels-only "**")
16378 (t "*")))
16379 (rpl (concat stars add-stars " ")))
16380 (while (< (setq l (1+ l)) l2)
16381 (if itemp
16382 (and (org-at-item-p) (replace-match rpl t t))
16383 (unless (org-on-heading-p)
16384 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
16385 (replace-match (concat rpl (match-string 2))))))
16386 (beginning-of-line 2)))))))
16388 (defun org-meta-return (&optional arg)
16389 "Insert a new heading or wrap a region in a table.
16390 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
16391 See the individual commands for more information."
16392 (interactive "P")
16393 (cond
16394 ((run-hook-with-args-until-success 'org-metareturn-hook))
16395 ((org-at-table-p)
16396 (call-interactively 'org-table-wrap-region))
16397 (t (call-interactively 'org-insert-heading))))
16399 ;;; Menu entries
16401 ;; Define the Org-mode menus
16402 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
16403 '("Tbl"
16404 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
16405 ["Next Field" org-cycle (org-at-table-p)]
16406 ["Previous Field" org-shifttab (org-at-table-p)]
16407 ["Next Row" org-return (org-at-table-p)]
16408 "--"
16409 ["Blank Field" org-table-blank-field (org-at-table-p)]
16410 ["Edit Field" org-table-edit-field (org-at-table-p)]
16411 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
16412 "--"
16413 ("Column"
16414 ["Move Column Left" org-metaleft (org-at-table-p)]
16415 ["Move Column Right" org-metaright (org-at-table-p)]
16416 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
16417 ["Insert Column" org-shiftmetaright (org-at-table-p)])
16418 ("Row"
16419 ["Move Row Up" org-metaup (org-at-table-p)]
16420 ["Move Row Down" org-metadown (org-at-table-p)]
16421 ["Delete Row" org-shiftmetaup (org-at-table-p)]
16422 ["Insert Row" org-shiftmetadown (org-at-table-p)]
16423 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
16424 "--"
16425 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
16426 ("Rectangle"
16427 ["Copy Rectangle" org-copy-special (org-at-table-p)]
16428 ["Cut Rectangle" org-cut-special (org-at-table-p)]
16429 ["Paste Rectangle" org-paste-special (org-at-table-p)]
16430 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
16431 "--"
16432 ("Calculate"
16433 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
16434 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
16435 ["Edit Formulas" org-edit-special (org-at-table-p)]
16436 "--"
16437 ["Recalculate line" org-table-recalculate (org-at-table-p)]
16438 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
16439 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
16440 "--"
16441 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
16442 "--"
16443 ["Sum Column/Rectangle" org-table-sum
16444 (or (org-at-table-p) (org-region-active-p))]
16445 ["Which Column?" org-table-current-column (org-at-table-p)])
16446 ["Debug Formulas"
16447 org-table-toggle-formula-debugger
16448 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
16449 ["Show Col/Row Numbers"
16450 org-table-toggle-coordinate-overlays
16451 :style toggle
16452 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
16453 "--"
16454 ["Create" org-table-create (and (not (org-at-table-p))
16455 org-enable-table-editor)]
16456 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
16457 ["Import from File" org-table-import (not (org-at-table-p))]
16458 ["Export to File" org-table-export (org-at-table-p)]
16459 "--"
16460 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
16462 (easy-menu-define org-org-menu org-mode-map "Org menu"
16463 '("Org"
16464 ("Show/Hide"
16465 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
16466 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
16467 ["Sparse Tree..." org-sparse-tree t]
16468 ["Reveal Context" org-reveal t]
16469 ["Show All" show-all t]
16470 "--"
16471 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
16472 "--"
16473 ["New Heading" org-insert-heading t]
16474 ("Navigate Headings"
16475 ["Up" outline-up-heading t]
16476 ["Next" outline-next-visible-heading t]
16477 ["Previous" outline-previous-visible-heading t]
16478 ["Next Same Level" outline-forward-same-level t]
16479 ["Previous Same Level" outline-backward-same-level t]
16480 "--"
16481 ["Jump" org-goto t])
16482 ("Edit Structure"
16483 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
16484 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
16485 "--"
16486 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
16487 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
16488 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
16489 "--"
16490 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
16491 "--"
16492 ["Promote Heading" org-metaleft (not (org-at-table-p))]
16493 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
16494 ["Demote Heading" org-metaright (not (org-at-table-p))]
16495 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
16496 "--"
16497 ["Sort Region/Children" org-sort (not (org-at-table-p))]
16498 "--"
16499 ["Convert to odd levels" org-convert-to-odd-levels t]
16500 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
16501 ("Editing"
16502 ["Emphasis..." org-emphasize t]
16503 ["Edit Source Example" org-edit-special t]
16504 "--"
16505 ["Footnote new/jump" org-footnote-action t]
16506 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
16507 ("Archive"
16508 ["Archive (default method)" org-archive-subtree-default t]
16509 "--"
16510 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
16511 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
16512 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
16514 "--"
16515 ("Hyperlinks"
16516 ["Store Link (Global)" org-store-link t]
16517 ["Find existing link to here" org-occur-link-in-agenda-files t]
16518 ["Insert Link" org-insert-link t]
16519 ["Follow Link" org-open-at-point t]
16520 "--"
16521 ["Next link" org-next-link t]
16522 ["Previous link" org-previous-link t]
16523 "--"
16524 ["Descriptive Links"
16525 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
16526 :style radio
16527 :selected (member '(org-link) buffer-invisibility-spec)]
16528 ["Literal Links"
16529 (progn
16530 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
16531 :style radio
16532 :selected (not (member '(org-link) buffer-invisibility-spec))])
16533 "--"
16534 ("TODO Lists"
16535 ["TODO/DONE/-" org-todo t]
16536 ("Select keyword"
16537 ["Next keyword" org-shiftright (org-on-heading-p)]
16538 ["Previous keyword" org-shiftleft (org-on-heading-p)]
16539 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
16540 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
16541 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
16542 ["Show TODO Tree" org-show-todo-tree t]
16543 ["Global TODO list" org-todo-list t]
16544 "--"
16545 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
16546 :selected org-enforce-todo-dependencies :style toggle :active t]
16547 "Settings for tree at point"
16548 ["Do Children sequentially" org-toggle-ordered-property :style radio
16549 :selected (ignore-errors (org-entry-get nil "ORDERED"))
16550 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16551 ["Do Children parallel" org-toggle-ordered-property :style radio
16552 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
16553 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16554 "--"
16555 ["Set Priority" org-priority t]
16556 ["Priority Up" org-shiftup t]
16557 ["Priority Down" org-shiftdown t]
16558 "--"
16559 ["Get news from all feeds" org-feed-update-all t]
16560 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
16561 ["Customize feeds" (customize-variable 'org-feed-alist) t])
16562 ("TAGS and Properties"
16563 ["Set Tags" org-set-tags-command t]
16564 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
16565 "--"
16566 ["Set property" org-set-property t]
16567 ["Column view of properties" org-columns t]
16568 ["Insert Column View DBlock" org-insert-columns-dblock t])
16569 ("Dates and Scheduling"
16570 ["Timestamp" org-time-stamp t]
16571 ["Timestamp (inactive)" org-time-stamp-inactive t]
16572 ("Change Date"
16573 ["1 Day Later" org-shiftright t]
16574 ["1 Day Earlier" org-shiftleft t]
16575 ["1 ... Later" org-shiftup t]
16576 ["1 ... Earlier" org-shiftdown t])
16577 ["Compute Time Range" org-evaluate-time-range t]
16578 ["Schedule Item" org-schedule t]
16579 ["Deadline" org-deadline t]
16580 "--"
16581 ["Custom time format" org-toggle-time-stamp-overlays
16582 :style radio :selected org-display-custom-times]
16583 "--"
16584 ["Goto Calendar" org-goto-calendar t]
16585 ["Date from Calendar" org-date-from-calendar t]
16586 "--"
16587 ["Start/Restart Timer" org-timer-start t]
16588 ["Pause/Continue Timer" org-timer-pause-or-continue t]
16589 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
16590 ["Insert Timer String" org-timer t]
16591 ["Insert Timer Item" org-timer-item t])
16592 ("Logging work"
16593 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
16594 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
16595 ["Clock out" org-clock-out t]
16596 ["Clock cancel" org-clock-cancel t]
16597 "--"
16598 ["Mark as default task" org-clock-mark-default-task t]
16599 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
16600 ["Goto running clock" org-clock-goto t]
16601 "--"
16602 ["Display times" org-clock-display t]
16603 ["Create clock table" org-clock-report t]
16604 "--"
16605 ["Record DONE time"
16606 (progn (setq org-log-done (not org-log-done))
16607 (message "Switching to %s will %s record a timestamp"
16608 (car org-done-keywords)
16609 (if org-log-done "automatically" "not")))
16610 :style toggle :selected org-log-done])
16611 "--"
16612 ["Agenda Command..." org-agenda t]
16613 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
16614 ("File List for Agenda")
16615 ("Special views current file"
16616 ["TODO Tree" org-show-todo-tree t]
16617 ["Check Deadlines" org-check-deadlines t]
16618 ["Timeline" org-timeline t]
16619 ["Tags/Property tree" org-match-sparse-tree t])
16620 "--"
16621 ["Export/Publish..." org-export t]
16622 ("LaTeX"
16623 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
16624 :selected org-cdlatex-mode]
16625 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
16626 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
16627 ["Modify math symbol" org-cdlatex-math-modify
16628 (org-inside-LaTeX-fragment-p)]
16629 ["Insert citation" org-reftex-citation t]
16630 "--"
16631 ["Export LaTeX fragments as images"
16632 (if (featurep 'org-exp)
16633 (setq org-export-with-LaTeX-fragments
16634 (not org-export-with-LaTeX-fragments))
16635 (require 'org-exp))
16636 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
16637 org-export-with-LaTeX-fragments)]
16638 "--"
16639 ["Template for BEAMER" org-beamer-settings-template t])
16640 "--"
16641 ("MobileOrg"
16642 ["Push Files and Views" org-mobile-push t]
16643 ["Get Captured and Flagged" org-mobile-pull t]
16644 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
16645 "--"
16646 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
16647 "--"
16648 ("Documentation"
16649 ["Show Version" org-version t]
16650 ["Info Documentation" org-info t])
16651 ("Customize"
16652 ["Browse Org Group" org-customize t]
16653 "--"
16654 ["Expand This Menu" org-create-customize-menu
16655 (fboundp 'customize-menu-create)])
16656 ["Send bug report" org-submit-bug-report t]
16657 "--"
16658 ("Refresh/Reload"
16659 ["Refresh setup current buffer" org-mode-restart t]
16660 ["Reload Org (after update)" org-reload t]
16661 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
16664 (defun org-info (&optional node)
16665 "Read documentation for Org-mode in the info system.
16666 With optional NODE, go directly to that node."
16667 (interactive)
16668 (info (format "(org)%s" (or node ""))))
16670 ;;;###autoload
16671 (defun org-submit-bug-report ()
16672 "Submit a bug report on Org-mode via mail.
16674 Don't hesitate to report any problems or inaccurate documentation.
16676 If you don't have setup sending mail from (X)Emacs, please copy the
16677 output buffer into your mail program, as it gives us important
16678 information about your Org-mode version and configuration."
16679 (interactive)
16680 (require 'reporter)
16681 (org-load-modules-maybe)
16682 (org-require-autoloaded-modules)
16683 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
16684 (reporter-submit-bug-report
16685 "emacs-orgmode@gnu.org"
16686 (org-version)
16687 (let (list)
16688 (save-window-excursion
16689 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
16690 (delete-other-windows)
16691 (erase-buffer)
16692 (insert "You are about to submit a bug report to the Org-mode mailing list.
16694 We would like to add your full Org-mode and Outline configuration to the
16695 bug report. This greatly simplifies the work of the maintainer and
16696 other experts on the mailing list.
16698 HOWEVER, some variables you have customized may contain private
16699 information. The names of customers, colleagues, or friends, might
16700 appear in the form of file names, tags, todo states, or search strings.
16701 If you answer yes to the prompt, you might want to check and remove
16702 such private information before sending the email.")
16703 (add-text-properties (point-min) (point-max) '(face org-warning))
16704 (when (yes-or-no-p "Include your Org-mode configuration ")
16705 (mapatoms
16706 (lambda (v)
16707 (and (boundp v)
16708 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
16709 (or (and (symbol-value v)
16710 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
16711 (and
16712 (get v 'custom-type) (get v 'standard-value)
16713 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
16714 (push v list)))))
16715 (kill-buffer (get-buffer "*Warn about privacy*"))
16716 list))
16717 nil nil
16718 "Remember to cover the basics, that is, what you expected to happen and
16719 what in fact did happen. You don't know how to make a good report? See
16721 http://orgmode.org/manual/Feedback.html#Feedback
16723 Your bug report will be posted to the Org-mode mailing list.
16724 ------------------------------------------------------------------------")
16725 (save-excursion
16726 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
16727 (replace-match "\\1Bug: \\3 [\\2]")))))
16730 (defun org-install-agenda-files-menu ()
16731 (let ((bl (buffer-list)))
16732 (save-excursion
16733 (while bl
16734 (set-buffer (pop bl))
16735 (if (org-mode-p) (setq bl nil)))
16736 (when (org-mode-p)
16737 (easy-menu-change
16738 '("Org") "File List for Agenda"
16739 (append
16740 (list
16741 ["Edit File List" (org-edit-agenda-file-list) t]
16742 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
16743 ["Remove Current File from List" org-remove-file t]
16744 ["Cycle through agenda files" org-cycle-agenda-files t]
16745 ["Occur in all agenda files" org-occur-in-agenda-files t]
16746 "--")
16747 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
16749 ;;;; Documentation
16751 ;;;###autoload
16752 (defun org-require-autoloaded-modules ()
16753 (interactive)
16754 (mapc 'require
16755 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
16756 org-docbook org-exp org-html org-icalendar
16757 org-id org-latex
16758 org-publish org-remember org-table
16759 org-timer org-xoxo)))
16761 ;;;###autoload
16762 (defun org-reload (&optional uncompiled)
16763 "Reload all org lisp files.
16764 With prefix arg UNCOMPILED, load the uncompiled versions."
16765 (interactive "P")
16766 (require 'find-func)
16767 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
16768 (dir-org (file-name-directory (org-find-library-name "org")))
16769 (dir-org-contrib (ignore-errors
16770 (file-name-directory
16771 (org-find-library-name "org-contribdir"))))
16772 (files
16773 (append (directory-files dir-org t file-re)
16774 (and dir-org-contrib
16775 (directory-files dir-org-contrib t file-re))))
16776 (remove-re (concat (if (featurep 'xemacs)
16777 "org-colview" "org-colview-xemacs")
16778 "\\'")))
16779 (setq files (mapcar 'file-name-sans-extension files))
16780 (setq files (mapcar
16781 (lambda (x) (if (string-match remove-re x) nil x))
16782 files))
16783 (setq files (delq nil files))
16784 (mapc
16785 (lambda (f)
16786 (when (featurep (intern (file-name-nondirectory f)))
16787 (if (and (not uncompiled)
16788 (file-exists-p (concat f ".elc")))
16789 (load (concat f ".elc") nil nil t)
16790 (load (concat f ".el") nil nil t))))
16791 files))
16792 (org-version))
16794 ;;;###autoload
16795 (defun org-customize ()
16796 "Call the customize function with org as argument."
16797 (interactive)
16798 (org-load-modules-maybe)
16799 (org-require-autoloaded-modules)
16800 (customize-browse 'org))
16802 (defun org-create-customize-menu ()
16803 "Create a full customization menu for Org-mode, insert it into the menu."
16804 (interactive)
16805 (org-load-modules-maybe)
16806 (org-require-autoloaded-modules)
16807 (if (fboundp 'customize-menu-create)
16808 (progn
16809 (easy-menu-change
16810 '("Org") "Customize"
16811 `(["Browse Org group" org-customize t]
16812 "--"
16813 ,(customize-menu-create 'org)
16814 ["Set" Custom-set t]
16815 ["Save" Custom-save t]
16816 ["Reset to Current" Custom-reset-current t]
16817 ["Reset to Saved" Custom-reset-saved t]
16818 ["Reset to Standard Settings" Custom-reset-standard t]))
16819 (message "\"Org\"-menu now contains full customization menu"))
16820 (error "Cannot expand menu (outdated version of cus-edit.el)")))
16822 ;;;; Miscellaneous stuff
16824 ;;; Generally useful functions
16826 (defun org-get-at-bol (property)
16827 "Get text property PROPERTY at beginning of line."
16828 (get-text-property (point-at-bol) property))
16830 (defun org-find-text-property-in-string (prop s)
16831 "Return the first non-nil value of property PROP in string S."
16832 (or (get-text-property 0 prop s)
16833 (get-text-property (or (next-single-property-change 0 prop s) 0)
16834 prop s)))
16836 (defun org-display-warning (message) ;; Copied from Emacs-Muse
16837 "Display the given MESSAGE as a warning."
16838 (if (fboundp 'display-warning)
16839 (display-warning 'org message
16840 (if (featurep 'xemacs)
16841 'warning
16842 :warning))
16843 (let ((buf (get-buffer-create "*Org warnings*")))
16844 (with-current-buffer buf
16845 (goto-char (point-max))
16846 (insert "Warning (Org): " message)
16847 (unless (bolp)
16848 (newline)))
16849 (display-buffer buf)
16850 (sit-for 0))))
16852 (defun org-in-commented-line ()
16853 "Is point in a line starting with `#'?"
16854 (equal (char-after (point-at-bol)) ?#))
16856 (defun org-in-verbatim-emphasis ()
16857 (save-match-data
16858 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
16860 (defun org-goto-marker-or-bmk (marker &optional bookmark)
16861 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
16862 (if (and marker (marker-buffer marker)
16863 (buffer-live-p (marker-buffer marker)))
16864 (progn
16865 (switch-to-buffer (marker-buffer marker))
16866 (if (or (> marker (point-max)) (< marker (point-min)))
16867 (widen))
16868 (goto-char marker)
16869 (org-show-context 'org-goto))
16870 (if bookmark
16871 (bookmark-jump bookmark)
16872 (error "Cannot find location"))))
16874 (defun org-quote-csv-field (s)
16875 "Quote field for inclusion in CSV material."
16876 (if (string-match "[\",]" s)
16877 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
16880 (defun org-plist-delete (plist property)
16881 "Delete PROPERTY from PLIST.
16882 This is in contrast to merely setting it to 0."
16883 (let (p)
16884 (while plist
16885 (if (not (eq property (car plist)))
16886 (setq p (plist-put p (car plist) (nth 1 plist))))
16887 (setq plist (cddr plist)))
16890 (defun org-force-self-insert (N)
16891 "Needed to enforce self-insert under remapping."
16892 (interactive "p")
16893 (self-insert-command N))
16895 (defun org-string-width (s)
16896 "Compute width of string, ignoring invisible characters.
16897 This ignores character with invisibility property `org-link', and also
16898 characters with property `org-cwidth', because these will become invisible
16899 upon the next fontification round."
16900 (let (b l)
16901 (when (or (eq t buffer-invisibility-spec)
16902 (assq 'org-link buffer-invisibility-spec))
16903 (while (setq b (text-property-any 0 (length s)
16904 'invisible 'org-link s))
16905 (setq s (concat (substring s 0 b)
16906 (substring s (or (next-single-property-change
16907 b 'invisible s) (length s)))))))
16908 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
16909 (setq s (concat (substring s 0 b)
16910 (substring s (or (next-single-property-change
16911 b 'org-cwidth s) (length s))))))
16912 (setq l (string-width s) b -1)
16913 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
16914 (setq l (- l (get-text-property b 'org-dwidth-n s))))
16917 (defun org-get-indentation (&optional line)
16918 "Get the indentation of the current line, interpreting tabs.
16919 When LINE is given, assume it represents a line and compute its indentation."
16920 (if line
16921 (if (string-match "^ *" (org-remove-tabs line))
16922 (match-end 0))
16923 (save-excursion
16924 (beginning-of-line 1)
16925 (skip-chars-forward " \t")
16926 (current-column))))
16928 (defun org-remove-tabs (s &optional width)
16929 "Replace tabulators in S with spaces.
16930 Assumes that s is a single line, starting in column 0."
16931 (setq width (or width tab-width))
16932 (while (string-match "\t" s)
16933 (setq s (replace-match
16934 (make-string
16935 (- (* width (/ (+ (match-beginning 0) width) width))
16936 (match-beginning 0)) ?\ )
16937 t t s)))
16940 (defun org-fix-indentation (line ind)
16941 "Fix indentation in LINE.
16942 IND is a cons cell with target and minimum indentation.
16943 If the current indentation in LINE is smaller than the minimum,
16944 leave it alone. If it is larger than ind, set it to the target."
16945 (let* ((l (org-remove-tabs line))
16946 (i (org-get-indentation l))
16947 (i1 (car ind)) (i2 (cdr ind)))
16948 (if (>= i i2) (setq l (substring line i2)))
16949 (if (> i1 0)
16950 (concat (make-string i1 ?\ ) l)
16951 l)))
16953 (defun org-remove-indentation (code &optional n)
16954 "Remove the maximum common indentation from the lines in CODE.
16955 N may optionally be the number of spaces to remove."
16956 (with-temp-buffer
16957 (insert code)
16958 (org-do-remove-indentation n)
16959 (buffer-string)))
16961 (defun org-do-remove-indentation (&optional n)
16962 "Remove the maximum common indentation from the buffer."
16963 (untabify (point-min) (point-max))
16964 (let ((min 10000) re)
16965 (if n
16966 (setq min n)
16967 (goto-char (point-min))
16968 (while (re-search-forward "^ *[^ \n]" nil t)
16969 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
16970 (unless (or (= min 0) (= min 10000))
16971 (setq re (format "^ \\{%d\\}" min))
16972 (goto-char (point-min))
16973 (while (re-search-forward re nil t)
16974 (replace-match "")
16975 (end-of-line 1))
16976 min)))
16978 (defun org-fill-template (template alist)
16979 "Find each %key of ALIST in TEMPLATE and replace it."
16980 (let ((case-fold-search nil)
16981 entry key value)
16982 (setq alist (sort (copy-sequence alist)
16983 (lambda (a b) (< (length (car a)) (length (car b))))))
16984 (while (setq entry (pop alist))
16985 (setq template
16986 (replace-regexp-in-string
16987 (concat "%" (regexp-quote (car entry)))
16988 (cdr entry) template t t)))
16989 template))
16991 (defun org-base-buffer (buffer)
16992 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
16993 (if (not buffer)
16994 buffer
16995 (or (buffer-base-buffer buffer)
16996 buffer)))
16998 (defun org-trim (s)
16999 "Remove whitespace at beginning and end of string."
17000 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
17001 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
17004 (defun org-wrap (string &optional width lines)
17005 "Wrap string to either a number of lines, or a width in characters.
17006 If WIDTH is non-nil, the string is wrapped to that width, however many lines
17007 that costs. If there is a word longer than WIDTH, the text is actually
17008 wrapped to the length of that word.
17009 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
17010 many lines, whatever width that takes.
17011 The return value is a list of lines, without newlines at the end."
17012 (let* ((words (org-split-string string "[ \t\n]+"))
17013 (maxword (apply 'max (mapcar 'org-string-width words)))
17014 w ll)
17015 (cond (width
17016 (org-do-wrap words (max maxword width)))
17017 (lines
17018 (setq w maxword)
17019 (setq ll (org-do-wrap words maxword))
17020 (if (<= (length ll) lines)
17022 (setq ll words)
17023 (while (> (length ll) lines)
17024 (setq w (1+ w))
17025 (setq ll (org-do-wrap words w)))
17026 ll))
17027 (t (error "Cannot wrap this")))))
17029 (defun org-do-wrap (words width)
17030 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
17031 (let (lines line)
17032 (while words
17033 (setq line (pop words))
17034 (while (and words (< (+ (length line) (length (car words))) width))
17035 (setq line (concat line " " (pop words))))
17036 (setq lines (push line lines)))
17037 (nreverse lines)))
17039 (defun org-split-string (string &optional separators)
17040 "Splits STRING into substrings at SEPARATORS.
17041 No empty strings are returned if there are matches at the beginning
17042 and end of string."
17043 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
17044 (start 0)
17045 notfirst
17046 (list nil))
17047 (while (and (string-match rexp string
17048 (if (and notfirst
17049 (= start (match-beginning 0))
17050 (< start (length string)))
17051 (1+ start) start))
17052 (< (match-beginning 0) (length string)))
17053 (setq notfirst t)
17054 (or (eq (match-beginning 0) 0)
17055 (and (eq (match-beginning 0) (match-end 0))
17056 (eq (match-beginning 0) start))
17057 (setq list
17058 (cons (substring string start (match-beginning 0))
17059 list)))
17060 (setq start (match-end 0)))
17061 (or (eq start (length string))
17062 (setq list
17063 (cons (substring string start)
17064 list)))
17065 (nreverse list)))
17067 (defun org-quote-vert (s)
17068 "Replace \"|\" with \"\\vert\"."
17069 (while (string-match "|" s)
17070 (setq s (replace-match "\\vert" t t s)))
17073 (defun org-uuidgen-p (s)
17074 "Is S an ID created by UUIDGEN?"
17075 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
17077 (defun org-context ()
17078 "Return a list of contexts of the current cursor position.
17079 If several contexts apply, all are returned.
17080 Each context entry is a list with a symbol naming the context, and
17081 two positions indicating start and end of the context. Possible
17082 contexts are:
17084 :headline anywhere in a headline
17085 :headline-stars on the leading stars in a headline
17086 :todo-keyword on a TODO keyword (including DONE) in a headline
17087 :tags on the TAGS in a headline
17088 :priority on the priority cookie in a headline
17089 :item on the first line of a plain list item
17090 :item-bullet on the bullet/number of a plain list item
17091 :checkbox on the checkbox in a plain list item
17092 :table in an org-mode table
17093 :table-special on a special filed in a table
17094 :table-table in a table.el table
17095 :link on a hyperlink
17096 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
17097 :target on a <<target>>
17098 :radio-target on a <<<radio-target>>>
17099 :latex-fragment on a LaTeX fragment
17100 :latex-preview on a LaTeX fragment with overlayed preview image
17102 This function expects the position to be visible because it uses font-lock
17103 faces as a help to recognize the following contexts: :table-special, :link,
17104 and :keyword."
17105 (let* ((f (get-text-property (point) 'face))
17106 (faces (if (listp f) f (list f)))
17107 (p (point)) clist o)
17108 ;; First the large context
17109 (cond
17110 ((org-on-heading-p t)
17111 (push (list :headline (point-at-bol) (point-at-eol)) clist)
17112 (when (progn
17113 (beginning-of-line 1)
17114 (looking-at org-todo-line-tags-regexp))
17115 (push (org-point-in-group p 1 :headline-stars) clist)
17116 (push (org-point-in-group p 2 :todo-keyword) clist)
17117 (push (org-point-in-group p 4 :tags) clist))
17118 (goto-char p)
17119 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
17120 (if (looking-at "\\[#[A-Z0-9]\\]")
17121 (push (org-point-in-group p 0 :priority) clist)))
17123 ((org-at-item-p)
17124 (push (org-point-in-group p 2 :item-bullet) clist)
17125 (push (list :item (point-at-bol)
17126 (save-excursion (org-end-of-item) (point)))
17127 clist)
17128 (and (org-at-item-checkbox-p)
17129 (push (org-point-in-group p 0 :checkbox) clist)))
17131 ((org-at-table-p)
17132 (push (list :table (org-table-begin) (org-table-end)) clist)
17133 (if (memq 'org-formula faces)
17134 (push (list :table-special
17135 (previous-single-property-change p 'face)
17136 (next-single-property-change p 'face)) clist)))
17137 ((org-at-table-p 'any)
17138 (push (list :table-table) clist)))
17139 (goto-char p)
17141 ;; Now the small context
17142 (cond
17143 ((org-at-timestamp-p)
17144 (push (org-point-in-group p 0 :timestamp) clist))
17145 ((memq 'org-link faces)
17146 (push (list :link
17147 (previous-single-property-change p 'face)
17148 (next-single-property-change p 'face)) clist))
17149 ((memq 'org-special-keyword faces)
17150 (push (list :keyword
17151 (previous-single-property-change p 'face)
17152 (next-single-property-change p 'face)) clist))
17153 ((org-on-target-p)
17154 (push (org-point-in-group p 0 :target) clist)
17155 (goto-char (1- (match-beginning 0)))
17156 (if (looking-at org-radio-target-regexp)
17157 (push (org-point-in-group p 0 :radio-target) clist))
17158 (goto-char p))
17159 ((setq o (car (delq nil
17160 (mapcar
17161 (lambda (x)
17162 (if (memq x org-latex-fragment-image-overlays) x))
17163 (org-overlays-at (point))))))
17164 (push (list :latex-fragment
17165 (org-overlay-start o) (org-overlay-end o)) clist)
17166 (push (list :latex-preview
17167 (org-overlay-start o) (org-overlay-end o)) clist))
17168 ((org-inside-LaTeX-fragment-p)
17169 ;; FIXME: positions wrong.
17170 (push (list :latex-fragment (point) (point)) clist)))
17172 (setq clist (nreverse (delq nil clist)))
17173 clist))
17175 ;; FIXME: Compare with at-regexp-p Do we need both?
17176 (defun org-in-regexp (re &optional nlines visually)
17177 "Check if point is inside a match of regexp.
17178 Normally only the current line is checked, but you can include NLINES extra
17179 lines both before and after point into the search.
17180 If VISUALLY is set, require that the cursor is not after the match but
17181 really on, so that the block visually is on the match."
17182 (catch 'exit
17183 (let ((pos (point))
17184 (eol (point-at-eol (+ 1 (or nlines 0))))
17185 (inc (if visually 1 0)))
17186 (save-excursion
17187 (beginning-of-line (- 1 (or nlines 0)))
17188 (while (re-search-forward re eol t)
17189 (if (and (<= (match-beginning 0) pos)
17190 (>= (+ inc (match-end 0)) pos))
17191 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
17193 (defun org-at-regexp-p (regexp)
17194 "Is point inside a match of REGEXP in the current line?"
17195 (catch 'exit
17196 (save-excursion
17197 (let ((pos (point)) (end (point-at-eol)))
17198 (beginning-of-line 1)
17199 (while (re-search-forward regexp end t)
17200 (if (and (<= (match-beginning 0) pos)
17201 (>= (match-end 0) pos))
17202 (throw 'exit t)))
17203 nil))))
17205 (defun org-in-regexps-block-p (start-re end-re)
17206 "Returns t if the current point is between matches of START-RE and END-RE.
17207 This will also return to if point is on one of the two matches."
17208 (interactive)
17209 (let ((p (point)))
17210 (save-excursion
17211 (and (or (org-at-regexp-p start-re)
17212 (re-search-backward start-re nil t))
17213 (re-search-forward end-re nil t)
17214 (>= (point) p)))))
17216 (defun org-occur-in-agenda-files (regexp &optional nlines)
17217 "Call `multi-occur' with buffers for all agenda files."
17218 (interactive "sOrg-files matching: \np")
17219 (let* ((files (org-agenda-files))
17220 (tnames (mapcar 'file-truename files))
17221 (extra org-agenda-text-search-extra-files)
17223 (when (eq (car extra) 'agenda-archives)
17224 (setq extra (cdr extra))
17225 (setq files (org-add-archive-files files)))
17226 (while (setq f (pop extra))
17227 (unless (member (file-truename f) tnames)
17228 (add-to-list 'files f 'append)
17229 (add-to-list 'tnames (file-truename f) 'append)))
17230 (multi-occur
17231 (mapcar (lambda (x)
17232 (with-current-buffer
17233 (or (get-file-buffer x) (find-file-noselect x))
17234 (widen)
17235 (current-buffer)))
17236 files)
17237 regexp)))
17239 (if (boundp 'occur-mode-find-occurrence-hook)
17240 ;; Emacs 23
17241 (add-hook 'occur-mode-find-occurrence-hook
17242 (lambda ()
17243 (when (org-mode-p)
17244 (org-reveal))))
17245 ;; Emacs 22
17246 (defadvice occur-mode-goto-occurrence
17247 (after org-occur-reveal activate)
17248 (and (org-mode-p) (org-reveal)))
17249 (defadvice occur-mode-goto-occurrence-other-window
17250 (after org-occur-reveal activate)
17251 (and (org-mode-p) (org-reveal)))
17252 (defadvice occur-mode-display-occurrence
17253 (after org-occur-reveal activate)
17254 (when (org-mode-p)
17255 (let ((pos (occur-mode-find-occurrence)))
17256 (with-current-buffer (marker-buffer pos)
17257 (save-excursion
17258 (goto-char pos)
17259 (org-reveal)))))))
17261 (defun org-occur-link-in-agenda-files ()
17262 "Create a link and search for it in the agendas.
17263 The link is not stored in `org-stored-links', it is just created
17264 for the search purpose."
17265 (interactive)
17266 (let ((link (condition-case nil
17267 (org-store-link nil)
17268 (error "Unable to create a link to here"))))
17269 (org-occur-in-agenda-files (regexp-quote link))))
17271 (defun org-uniquify (list)
17272 "Remove duplicate elements from LIST."
17273 (let (res)
17274 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
17275 res))
17277 (defun org-delete-all (elts list)
17278 "Remove all elements in ELTS from LIST."
17279 (while elts
17280 (setq list (delete (pop elts) list)))
17281 list)
17283 (defun org-back-over-empty-lines ()
17284 "Move backwards over whitespace, to the beginning of the first empty line.
17285 Returns the number of empty lines passed."
17286 (let ((pos (point)))
17287 (skip-chars-backward " \t\n\r")
17288 (beginning-of-line 2)
17289 (goto-char (min (point) pos))
17290 (count-lines (point) pos)))
17292 (defun org-skip-whitespace ()
17293 (skip-chars-forward " \t\n\r"))
17295 (defun org-point-in-group (point group &optional context)
17296 "Check if POINT is in match-group GROUP.
17297 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
17298 match. If the match group does ot exist or point is not inside it,
17299 return nil."
17300 (and (match-beginning group)
17301 (>= point (match-beginning group))
17302 (<= point (match-end group))
17303 (if context
17304 (list context (match-beginning group) (match-end group))
17305 t)))
17307 (defun org-switch-to-buffer-other-window (&rest args)
17308 "Switch to buffer in a second window on the current frame.
17309 In particular, do not allow pop-up frames."
17310 (let (pop-up-frames special-display-buffer-names special-display-regexps
17311 special-display-function)
17312 (apply 'switch-to-buffer-other-window args)))
17314 (defun org-combine-plists (&rest plists)
17315 "Create a single property list from all plists in PLISTS.
17316 The process starts by copying the first list, and then setting properties
17317 from the other lists. Settings in the last list are the most significant
17318 ones and overrule settings in the other lists."
17319 (let ((rtn (copy-sequence (pop plists)))
17320 p v ls)
17321 (while plists
17322 (setq ls (pop plists))
17323 (while ls
17324 (setq p (pop ls) v (pop ls))
17325 (setq rtn (plist-put rtn p v))))
17326 rtn))
17328 (defun org-move-line-down (arg)
17329 "Move the current line down. With prefix argument, move it past ARG lines."
17330 (interactive "p")
17331 (let ((col (current-column))
17332 beg end pos)
17333 (beginning-of-line 1) (setq beg (point))
17334 (beginning-of-line 2) (setq end (point))
17335 (beginning-of-line (+ 1 arg))
17336 (setq pos (move-marker (make-marker) (point)))
17337 (insert (delete-and-extract-region beg end))
17338 (goto-char pos)
17339 (org-move-to-column col)))
17341 (defun org-move-line-up (arg)
17342 "Move the current line up. With prefix argument, move it past ARG lines."
17343 (interactive "p")
17344 (let ((col (current-column))
17345 beg end pos)
17346 (beginning-of-line 1) (setq beg (point))
17347 (beginning-of-line 2) (setq end (point))
17348 (beginning-of-line (- arg))
17349 (setq pos (move-marker (make-marker) (point)))
17350 (insert (delete-and-extract-region beg end))
17351 (goto-char pos)
17352 (org-move-to-column col)))
17354 (defun org-replace-escapes (string table)
17355 "Replace %-escapes in STRING with values in TABLE.
17356 TABLE is an association list with keys like \"%a\" and string values.
17357 The sequences in STRING may contain normal field width and padding information,
17358 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
17359 so values can contain further %-escapes if they are define later in TABLE."
17360 (let ((case-fold-search nil)
17361 e re rpl)
17362 (while (setq e (pop table))
17363 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
17364 (while (string-match re string)
17365 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
17366 (cdr e)))
17367 (setq string (replace-match rpl t t string))))
17368 string))
17371 (defun org-sublist (list start end)
17372 "Return a section of LIST, from START to END.
17373 Counting starts at 1."
17374 (let (rtn (c start))
17375 (setq list (nthcdr (1- start) list))
17376 (while (and list (<= c end))
17377 (push (pop list) rtn)
17378 (setq c (1+ c)))
17379 (nreverse rtn)))
17381 (defun org-find-base-buffer-visiting (file)
17382 "Like `find-buffer-visiting' but always return the base buffer and
17383 not an indirect buffer."
17384 (let ((buf (or (get-file-buffer file)
17385 (find-buffer-visiting file))))
17386 (if buf
17387 (or (buffer-base-buffer buf) buf)
17388 nil)))
17390 (defun org-image-file-name-regexp (&optional extensions)
17391 "Return regexp matching the file names of images.
17392 If EXTENSIONS is given, only match these."
17393 (if (and (not extensions) (fboundp 'image-file-name-regexp))
17394 (image-file-name-regexp)
17395 (let ((image-file-name-extensions
17396 (or extensions
17397 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
17398 "xbm" "xpm" "pbm" "pgm" "ppm"))))
17399 (concat "\\."
17400 (regexp-opt (nconc (mapcar 'upcase
17401 image-file-name-extensions)
17402 image-file-name-extensions)
17404 "\\'"))))
17406 (defun org-file-image-p (file &optional extensions)
17407 "Return non-nil if FILE is an image."
17408 (save-match-data
17409 (string-match (org-image-file-name-regexp extensions) file)))
17411 (defun org-get-cursor-date ()
17412 "Return the date at cursor in as a time.
17413 This works in the calendar and in the agenda, anywhere else it just
17414 returns the current time."
17415 (let (date day defd)
17416 (cond
17417 ((eq major-mode 'calendar-mode)
17418 (setq date (calendar-cursor-to-date)
17419 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17420 ((eq major-mode 'org-agenda-mode)
17421 (setq day (get-text-property (point) 'day))
17422 (if day
17423 (setq date (calendar-gregorian-from-absolute day)
17424 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
17425 (nth 2 date))))))
17426 (or defd (current-time))))
17428 (defvar org-agenda-action-marker (make-marker)
17429 "Marker pointing to the entry for the next agenda action.")
17431 (defun org-mark-entry-for-agenda-action ()
17432 "Mark the current entry as target of an agenda action.
17433 Agenda actions are actions executed from the agenda with the key `k',
17434 which make use of the date at the cursor."
17435 (interactive)
17436 (move-marker org-agenda-action-marker
17437 (save-excursion (org-back-to-heading t) (point))
17438 (current-buffer))
17439 (message
17440 "Entry marked for action; press `k' at desired date in agenda or calendar"))
17442 ;;; Paragraph filling stuff.
17443 ;; We want this to be just right, so use the full arsenal.
17445 (defun org-indent-line-function ()
17446 "Indent line like previous, but further if previous was headline or item."
17447 (interactive)
17448 (let* ((pos (point))
17449 (itemp (org-at-item-p))
17450 (case-fold-search t)
17451 (org-drawer-regexp (or org-drawer-regexp "\000"))
17452 column bpos bcol tpos tcol bullet btype bullet-type)
17453 ;; Find the previous relevant line
17454 (beginning-of-line 1)
17455 (cond
17456 ((looking-at "#") (setq column 0))
17457 ((looking-at "\\*+ ") (setq column 0))
17458 ((and (looking-at "[ \t]*:END:")
17459 (save-excursion (re-search-backward org-drawer-regexp nil t)))
17460 (save-excursion
17461 (goto-char (1- (match-beginning 1)))
17462 (setq column (current-column))))
17463 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
17464 (save-excursion
17465 (re-search-backward
17466 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
17467 (setq column (org-get-indentation (match-string 0))))
17469 (beginning-of-line 0)
17470 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
17471 (not (looking-at "[ \t]*:END:"))
17472 (not (looking-at org-drawer-regexp)))
17473 (beginning-of-line 0))
17474 (cond
17475 ((looking-at "\\*+[ \t]+")
17476 (if (not org-adapt-indentation)
17477 (setq column 0)
17478 (goto-char (match-end 0))
17479 (setq column (current-column))))
17480 ((looking-at org-drawer-regexp)
17481 (goto-char (1- (match-beginning 1)))
17482 (setq column (current-column)))
17483 ((looking-at "\\([ \t]*\\):END:")
17484 (goto-char (match-end 1))
17485 (setq column (current-column)))
17486 ((org-in-item-p)
17487 (org-beginning-of-item)
17488 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
17489 (setq bpos (match-beginning 1) tpos (match-end 0)
17490 bcol (progn (goto-char bpos) (current-column))
17491 tcol (progn (goto-char tpos) (current-column))
17492 bullet (match-string 1)
17493 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
17494 (if (> tcol (+ bcol org-description-max-indent))
17495 (setq tcol (+ bcol 5)))
17496 (if (not itemp)
17497 (setq column tcol)
17498 (goto-char pos)
17499 (beginning-of-line 1)
17500 (if (looking-at "\\S-")
17501 (progn
17502 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
17503 (setq bullet (match-string 1)
17504 btype (if (string-match "[0-9]" bullet) "n" bullet))
17505 (setq column (if (equal btype bullet-type) bcol tcol)))
17506 (setq column (org-get-indentation)))))
17507 (t (setq column (org-get-indentation))))))
17508 (goto-char pos)
17509 (if (<= (current-column) (current-indentation))
17510 (org-indent-line-to column)
17511 (save-excursion (org-indent-line-to column)))
17512 (setq column (current-column))
17513 (beginning-of-line 1)
17514 (if (looking-at
17515 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
17516 (replace-match (concat (match-string 1)
17517 (format org-property-format
17518 (match-string 2) (match-string 3)))
17519 t t))
17520 (org-move-to-column column)))
17522 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
17523 "Variable to store copy of `adaptive-fill-regexp'.
17524 Since `adaptive-fill-regexp' is set to never match, we need to
17525 store a backup of its value before entering `org-mode' so that
17526 the functionality can be provided as a fall-back.")
17528 (defun org-set-autofill-regexps ()
17529 (interactive)
17530 ;; In the paragraph separator we include headlines, because filling
17531 ;; text in a line directly attached to a headline would otherwise
17532 ;; fill the headline as well.
17533 (org-set-local 'comment-start-skip "^#+[ \t]*")
17534 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
17535 ;; The paragraph starter includes hand-formatted lists.
17536 (org-set-local
17537 'paragraph-start
17538 (concat
17539 "\f" "\\|"
17540 "[ ]*$" "\\|"
17541 "\\*+ " "\\|"
17542 "[ \t]*#" "\\|"
17543 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
17544 "[ \t]*[:|]" "\\|"
17545 "\\$\\$" "\\|"
17546 "\\\\\\(begin\\|end\\|[][]\\)"))
17547 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
17548 ;; But only if the user has not turned off tables or fixed-width regions
17549 (org-set-local
17550 'auto-fill-inhibit-regexp
17551 (concat "\\*+ \\|#\\+"
17552 "\\|[ \t]*" org-keyword-time-regexp
17553 (if (or org-enable-table-editor org-enable-fixed-width-editor)
17554 (concat
17555 "\\|[ \t]*["
17556 (if org-enable-table-editor "|" "")
17557 (if org-enable-fixed-width-editor ":" "")
17558 "]"))))
17559 ;; We use our own fill-paragraph function, to make sure that tables
17560 ;; and fixed-width regions are not wrapped. That function will pass
17561 ;; through to `fill-paragraph' when appropriate.
17562 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
17563 ;; Adaptive filling: To get full control, first make sure that
17564 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
17565 (unless (local-variable-p 'adaptive-fill-regexp)
17566 (org-set-local 'org-adaptive-fill-regexp-backup
17567 adaptive-fill-regexp))
17568 (org-set-local 'adaptive-fill-regexp "\000")
17569 (org-set-local 'adaptive-fill-function
17570 'org-adaptive-fill-function)
17571 (org-set-local
17572 'align-mode-rules-list
17573 '((org-in-buffer-settings
17574 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
17575 (modes . '(org-mode))))))
17577 (defun org-fill-paragraph (&optional justify)
17578 "Re-align a table, pass through to fill-paragraph if no table."
17579 (let ((table-p (org-at-table-p))
17580 (table.el-p (org-at-table.el-p)))
17581 (cond ((and (equal (char-after (point-at-bol)) ?*)
17582 (save-excursion (goto-char (point-at-bol))
17583 (looking-at outline-regexp)))
17584 t) ; skip headlines
17585 (table.el-p t) ; skip table.el tables
17586 (table-p (org-table-align) t) ; align org-mode tables
17587 (t nil)))) ; call paragraph-fill
17589 ;; For reference, this is the default value of adaptive-fill-regexp
17590 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
17592 (defun org-adaptive-fill-function ()
17593 "Return a fill prefix for org-mode files.
17594 In particular, this makes sure hanging paragraphs for hand-formatted lists
17595 work correctly."
17596 (cond
17597 ;; Comment line
17598 ((looking-at "#[ \t]+")
17599 (match-string-no-properties 0))
17600 ;; Description list
17601 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
17602 (save-excursion
17603 (if (> (match-end 1) (+ (match-beginning 1)
17604 org-description-max-indent))
17605 (goto-char (+ (match-beginning 1) 5))
17606 (goto-char (match-end 0)))
17607 (make-string (current-column) ?\ )))
17608 ;; Ordered or unordered list
17609 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)")
17610 (save-excursion
17611 (goto-char (match-end 0))
17612 (make-string (current-column) ?\ )))
17613 ;; Other text
17614 ((looking-at org-adaptive-fill-regexp-backup)
17615 (match-string-no-properties 0))))
17617 ;;; Other stuff.
17619 (defun org-toggle-fixed-width-section (arg)
17620 "Toggle the fixed-width export.
17621 If there is no active region, the QUOTE keyword at the current headline is
17622 inserted or removed. When present, it causes the text between this headline
17623 and the next to be exported as fixed-width text, and unmodified.
17624 If there is an active region, this command adds or removes a colon as the
17625 first character of this line. If the first character of a line is a colon,
17626 this line is also exported in fixed-width font."
17627 (interactive "P")
17628 (let* ((cc 0)
17629 (regionp (org-region-active-p))
17630 (beg (if regionp (region-beginning) (point)))
17631 (end (if regionp (region-end)))
17632 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
17633 (case-fold-search nil)
17634 (re "[ \t]*\\(: \\)")
17635 off)
17636 (if regionp
17637 (save-excursion
17638 (goto-char beg)
17639 (setq cc (current-column))
17640 (beginning-of-line 1)
17641 (setq off (looking-at re))
17642 (while (> nlines 0)
17643 (setq nlines (1- nlines))
17644 (beginning-of-line 1)
17645 (cond
17646 (arg
17647 (org-move-to-column cc t)
17648 (insert ": \n")
17649 (forward-line -1))
17650 ((and off (looking-at re))
17651 (replace-match "" t t nil 1))
17652 ((not off) (org-move-to-column cc t) (insert ": ")))
17653 (forward-line 1)))
17654 (save-excursion
17655 (org-back-to-heading)
17656 (if (looking-at (concat outline-regexp
17657 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
17658 (replace-match "" t t nil 1)
17659 (if (looking-at outline-regexp)
17660 (progn
17661 (goto-char (match-end 0))
17662 (insert org-quote-string " "))))))))
17664 (defun org-reftex-citation ()
17665 "Use reftex-citation to insert a citation into the buffer.
17666 This looks for a line like
17668 #+BIBLIOGRAPHY: foo plain option:-d
17670 and derives from it that foo.bib is the bibliography file relevant
17671 for this document. It then installs the necessary environment for RefTeX
17672 to work in this buffer and calls `reftex-citation' to insert a citation
17673 into the buffer.
17675 Export of such citations to both LaTeX and HTML is handled by the contributed
17676 package org-exp-bibtex by Taru Karttunen."
17677 (interactive)
17678 (let ((reftex-docstruct-symbol 'rds)
17679 (reftex-cite-format "\\cite{%l}")
17680 rds bib)
17681 (save-excursion
17682 (save-restriction
17683 (widen)
17684 (let ((case-fold-search t)
17685 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
17686 (if (not (save-excursion
17687 (or (re-search-forward re nil t)
17688 (re-search-backward re nil t))))
17689 (error "No bibliography defined in file")
17690 (setq bib (concat (match-string 1) ".bib")
17691 rds (list (list 'bib bib)))))))
17692 (call-interactively 'reftex-citation)))
17694 ;;;; Functions extending outline functionality
17696 (defun org-beginning-of-line (&optional arg)
17697 "Go to the beginning of the current line. If that is invisible, continue
17698 to a visible line beginning. This makes the function of C-a more intuitive.
17699 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17700 first attempt, and only move to after the tags when the cursor is already
17701 beyond the end of the headline."
17702 (interactive "P")
17703 (let ((pos (point))
17704 (special (if (consp org-special-ctrl-a/e)
17705 (car org-special-ctrl-a/e)
17706 org-special-ctrl-a/e))
17707 refpos)
17708 (if (org-bound-and-true-p line-move-visual)
17709 (beginning-of-visual-line 1)
17710 (beginning-of-line 1))
17711 (if (and arg (fboundp 'move-beginning-of-line))
17712 (call-interactively 'move-beginning-of-line)
17713 (if (bobp)
17715 (backward-char 1)
17716 (if (org-invisible-p)
17717 (while (and (not (bobp)) (org-invisible-p))
17718 (backward-char 1)
17719 (beginning-of-line 1))
17720 (forward-char 1))))
17721 (when special
17722 (cond
17723 ((and (looking-at org-complex-heading-regexp)
17724 (= (char-after (match-end 1)) ?\ ))
17725 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
17726 (point-at-eol)))
17727 (goto-char
17728 (if (eq special t)
17729 (cond ((> pos refpos) refpos)
17730 ((= pos (point)) refpos)
17731 (t (point)))
17732 (cond ((> pos (point)) (point))
17733 ((not (eq last-command this-command)) (point))
17734 (t refpos)))))
17735 ((org-at-item-p)
17736 (goto-char
17737 (if (eq special t)
17738 (cond ((> pos (match-end 4)) (match-end 4))
17739 ((= pos (point)) (match-end 4))
17740 (t (point)))
17741 (cond ((> pos (point)) (point))
17742 ((not (eq last-command this-command)) (point))
17743 (t (match-end 4))))))))
17744 (org-no-warnings
17745 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17747 (defun org-end-of-line (&optional arg)
17748 "Go to the end of the line.
17749 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17750 first attempt, and only move to after the tags when the cursor is already
17751 beyond the end of the headline."
17752 (interactive "P")
17753 (let ((special (if (consp org-special-ctrl-a/e)
17754 (cdr org-special-ctrl-a/e)
17755 org-special-ctrl-a/e)))
17756 (if (or (not special)
17757 (not (org-on-heading-p))
17758 arg)
17759 (call-interactively
17760 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
17761 ((fboundp 'move-end-of-line) 'move-end-of-line)
17762 (t 'end-of-line)))
17763 (let ((pos (point)))
17764 (beginning-of-line 1)
17765 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
17766 (if (eq special t)
17767 (if (or (< pos (match-beginning 1))
17768 (= pos (match-end 0)))
17769 (goto-char (match-beginning 1))
17770 (goto-char (match-end 0)))
17771 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
17772 (goto-char (match-end 0))
17773 (goto-char (match-beginning 1))))
17774 (call-interactively (if (fboundp 'move-end-of-line)
17775 'move-end-of-line
17776 'end-of-line)))))
17777 (org-no-warnings
17778 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17780 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
17781 (define-key org-mode-map "\C-e" 'org-end-of-line)
17782 (define-key org-mode-map [home] 'org-beginning-of-line)
17783 (define-key org-mode-map [end] 'org-end-of-line)
17785 (defun org-backward-sentence (&optional arg)
17786 "Go to beginning of sentence, or beginning of table field.
17787 This will call `backward-sentence' or `org-table-beginning-of-field',
17788 depending on context."
17789 (interactive "P")
17790 (cond
17791 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
17792 (t (call-interactively 'backward-sentence))))
17794 (defun org-forward-sentence (&optional arg)
17795 "Go to end of sentence, or end of table field.
17796 This will call `forward-sentence' or `org-table-end-of-field',
17797 depending on context."
17798 (interactive "P")
17799 (cond
17800 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
17801 (t (call-interactively 'forward-sentence))))
17803 (define-key org-mode-map "\M-a" 'org-backward-sentence)
17804 (define-key org-mode-map "\M-e" 'org-forward-sentence)
17806 (defun org-kill-line (&optional arg)
17807 "Kill line, to tags or end of line."
17808 (interactive "P")
17809 (cond
17810 ((or (not org-special-ctrl-k)
17811 (bolp)
17812 (not (org-on-heading-p)))
17813 (call-interactively 'kill-line))
17814 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
17815 (kill-region (point) (match-beginning 1))
17816 (org-set-tags nil t))
17817 (t (kill-region (point) (point-at-eol)))))
17819 (define-key org-mode-map "\C-k" 'org-kill-line)
17821 (defun org-yank (&optional arg)
17822 "Yank. If the kill is a subtree, treat it specially.
17823 This command will look at the current kill and check if is a single
17824 subtree, or a series of subtrees[1]. If it passes the test, and if the
17825 cursor is at the beginning of a line or after the stars of a currently
17826 empty headline, then the yank is handled specially. How exactly depends
17827 on the value of the following variables, both set by default.
17829 org-yank-folded-subtrees
17830 When set, the subtree(s) will be folded after insertion, but only
17831 if doing so would now swallow text after the yanked text.
17833 org-yank-adjusted-subtrees
17834 When set, the subtree will be promoted or demoted in order to
17835 fit into the local outline tree structure, which means that the level
17836 will be adjusted so that it becomes the smaller one of the two
17837 *visible* surrounding headings.
17839 Any prefix to this command will cause `yank' to be called directly with
17840 no special treatment. In particular, a simple `C-u' prefix will just
17841 plainly yank the text as it is.
17843 \[1] The test checks if the first non-white line is a heading
17844 and if there are no other headings with fewer stars."
17845 (interactive "P")
17846 (org-yank-generic 'yank arg))
17848 (defun org-yank-generic (command arg)
17849 "Perform some yank-like command.
17851 This function implements the behavior described in the `org-yank'
17852 documentation. However, it has been generalized to work for any
17853 interactive command with similar behavior."
17855 ;; pretend to be command COMMAND
17856 (setq this-command command)
17858 (if arg
17859 (call-interactively command)
17861 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
17862 (and (org-kill-is-subtree-p)
17863 (or (bolp)
17864 (and (looking-at "[ \t]*$")
17865 (string-match
17866 "\\`\\*+\\'"
17867 (buffer-substring (point-at-bol) (point)))))))
17868 swallowp)
17869 (cond
17870 ((and subtreep org-yank-folded-subtrees)
17871 (let ((beg (point))
17872 end)
17873 (if (and subtreep org-yank-adjusted-subtrees)
17874 (org-paste-subtree nil nil 'for-yank)
17875 (call-interactively command))
17877 (setq end (point))
17878 (goto-char beg)
17879 (when (and (bolp) subtreep
17880 (not (setq swallowp
17881 (org-yank-folding-would-swallow-text beg end))))
17882 (or (looking-at outline-regexp)
17883 (re-search-forward (concat "^" outline-regexp) end t))
17884 (while (and (< (point) end) (looking-at outline-regexp))
17885 (hide-subtree)
17886 (org-cycle-show-empty-lines 'folded)
17887 (condition-case nil
17888 (outline-forward-same-level 1)
17889 (error (goto-char end)))))
17890 (when swallowp
17891 (message
17892 "Inserted text not folded because that would swallow text"))
17894 (goto-char end)
17895 (skip-chars-forward " \t\n\r")
17896 (beginning-of-line 1)
17897 (push-mark beg 'nomsg)))
17898 ((and subtreep org-yank-adjusted-subtrees)
17899 (let ((beg (point-at-bol)))
17900 (org-paste-subtree nil nil 'for-yank)
17901 (push-mark beg 'nomsg)))
17903 (call-interactively command))))))
17905 (defun org-yank-folding-would-swallow-text (beg end)
17906 "Would hide-subtree at BEG swallow any text after END?"
17907 (let (level)
17908 (save-excursion
17909 (goto-char beg)
17910 (when (or (looking-at outline-regexp)
17911 (re-search-forward (concat "^" outline-regexp) end t))
17912 (setq level (org-outline-level)))
17913 (goto-char end)
17914 (skip-chars-forward " \t\r\n\v\f")
17915 (if (or (eobp)
17916 (and (bolp) (looking-at org-outline-regexp)
17917 (<= (org-outline-level) level)))
17918 nil ; Nothing would be swallowed
17919 t)))) ; something would swallow
17921 (define-key org-mode-map "\C-y" 'org-yank)
17923 (defun org-invisible-p ()
17924 "Check if point is at a character currently not visible."
17925 ;; Early versions of noutline don't have `outline-invisible-p'.
17926 (if (fboundp 'outline-invisible-p)
17927 (outline-invisible-p)
17928 (get-char-property (point) 'invisible)))
17930 (defun org-invisible-p2 ()
17931 "Check if point is at a character currently not visible."
17932 (save-excursion
17933 (if (and (eolp) (not (bobp))) (backward-char 1))
17934 ;; Early versions of noutline don't have `outline-invisible-p'.
17935 (if (fboundp 'outline-invisible-p)
17936 (outline-invisible-p)
17937 (get-char-property (point) 'invisible))))
17939 (defun org-back-to-heading (&optional invisible-ok)
17940 "Call `outline-back-to-heading', but provide a better error message."
17941 (condition-case nil
17942 (outline-back-to-heading invisible-ok)
17943 (error (error "Before first headline at position %d in buffer %s"
17944 (point) (current-buffer)))))
17946 (defun org-before-first-heading-p ()
17947 "Before first heading?"
17948 (save-excursion
17949 (null (re-search-backward "^\\*+ " nil t))))
17951 (defun org-on-heading-p (&optional ignored)
17952 (outline-on-heading-p t))
17953 (defun org-at-heading-p (&optional ignored)
17954 (outline-on-heading-p t))
17956 (defun org-point-at-end-of-empty-headline ()
17957 "If point is at the end of an empty headline, return t, else nil.
17958 If the heading only contains a TODO keyword, it is still still considered
17959 empty."
17960 (and (looking-at "[ \t]*$")
17961 (save-excursion
17962 (beginning-of-line 1)
17963 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp
17964 "\\)?[ \t]*$")))))
17965 (defun org-at-heading-or-item-p ()
17966 (or (org-on-heading-p) (org-at-item-p)))
17968 (defun org-on-target-p ()
17969 (or (org-in-regexp org-radio-target-regexp)
17970 (org-in-regexp org-target-regexp)))
17972 (defun org-up-heading-all (arg)
17973 "Move to the heading line of which the present line is a subheading.
17974 This function considers both visible and invisible heading lines.
17975 With argument, move up ARG levels."
17976 (if (fboundp 'outline-up-heading-all)
17977 (outline-up-heading-all arg) ; emacs 21 version of outline.el
17978 (outline-up-heading arg t))) ; emacs 22 version of outline.el
17980 (defun org-up-heading-safe ()
17981 "Move to the heading line of which the present line is a subheading.
17982 This version will not throw an error. It will return the level of the
17983 headline found, or nil if no higher level is found.
17985 Also, this function will be a lot faster than `outline-up-heading',
17986 because it relies on stars being the outline starters. This can really
17987 make a significant difference in outlines with very many siblings."
17988 (let (start-level re)
17989 (org-back-to-heading t)
17990 (setq start-level (funcall outline-level))
17991 (if (equal start-level 1)
17993 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
17994 (if (re-search-backward re nil t)
17995 (funcall outline-level)))))
17997 (defun org-first-sibling-p ()
17998 "Is this heading the first child of its parents?"
17999 (interactive)
18000 (let ((re (concat "^" outline-regexp))
18001 level l)
18002 (unless (org-at-heading-p t)
18003 (error "Not at a heading"))
18004 (setq level (funcall outline-level))
18005 (save-excursion
18006 (if (not (re-search-backward re nil t))
18008 (setq l (funcall outline-level))
18009 (< l level)))))
18011 (defun org-goto-sibling (&optional previous)
18012 "Goto the next sibling, even if it is invisible.
18013 When PREVIOUS is set, go to the previous sibling instead. Returns t
18014 when a sibling was found. When none is found, return nil and don't
18015 move point."
18016 (let ((fun (if previous 're-search-backward 're-search-forward))
18017 (pos (point))
18018 (re (concat "^" outline-regexp))
18019 level l)
18020 (when (condition-case nil (org-back-to-heading t) (error nil))
18021 (setq level (funcall outline-level))
18022 (catch 'exit
18023 (or previous (forward-char 1))
18024 (while (funcall fun re nil t)
18025 (setq l (funcall outline-level))
18026 (when (< l level) (goto-char pos) (throw 'exit nil))
18027 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
18028 (goto-char pos)
18029 nil))))
18031 (defun org-show-siblings ()
18032 "Show all siblings of the current headline."
18033 (save-excursion
18034 (while (org-goto-sibling) (org-flag-heading nil)))
18035 (save-excursion
18036 (while (org-goto-sibling 'previous)
18037 (org-flag-heading nil))))
18039 (defun org-show-hidden-entry ()
18040 "Show an entry where even the heading is hidden."
18041 (save-excursion
18042 (org-show-entry)))
18044 (defun org-flag-heading (flag &optional entry)
18045 "Flag the current heading. FLAG non-nil means make invisible.
18046 When ENTRY is non-nil, show the entire entry."
18047 (save-excursion
18048 (org-back-to-heading t)
18049 ;; Check if we should show the entire entry
18050 (if entry
18051 (progn
18052 (org-show-entry)
18053 (save-excursion
18054 (and (outline-next-heading)
18055 (org-flag-heading nil))))
18056 (outline-flag-region (max (point-min) (1- (point)))
18057 (save-excursion (outline-end-of-heading) (point))
18058 flag))))
18060 (defun org-get-next-sibling ()
18061 "Move to next heading of the same level, and return point.
18062 If there is no such heading, return nil.
18063 This is like outline-next-sibling, but invisible headings are ok."
18064 (let ((level (funcall outline-level)))
18065 (outline-next-heading)
18066 (while (and (not (eobp)) (> (funcall outline-level) level))
18067 (outline-next-heading))
18068 (if (or (eobp) (< (funcall outline-level) level))
18070 (point))))
18072 (defun org-get-last-sibling ()
18073 "Move to previous heading of the same level, and return point.
18074 If there is no such heading, return nil."
18075 (let ((opoint (point))
18076 (level (funcall outline-level)))
18077 (outline-previous-heading)
18078 (when (and (/= (point) opoint) (outline-on-heading-p t))
18079 (while (and (> (funcall outline-level) level)
18080 (not (bobp)))
18081 (outline-previous-heading))
18082 (if (< (funcall outline-level) level)
18084 (point)))))
18086 (defun org-end-of-subtree (&optional invisible-OK to-heading)
18087 ;; This contains an exact copy of the original function, but it uses
18088 ;; `org-back-to-heading', to make it work also in invisible
18089 ;; trees. And is uses an invisible-OK argument.
18090 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
18091 ;; Furthermore, when used inside Org, finding the end of a large subtree
18092 ;; with many children and grandchildren etc, this can be much faster
18093 ;; than the outline version.
18094 (org-back-to-heading invisible-OK)
18095 (let ((first t)
18096 (level (funcall outline-level)))
18097 (if (and (org-mode-p) (< level 1000))
18098 ;; A true heading (not a plain list item), in Org-mode
18099 ;; This means we can easily find the end by looking
18100 ;; only for the right number of stars. Using a regexp to do
18101 ;; this is so much faster than using a Lisp loop.
18102 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
18103 (forward-char 1)
18104 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
18105 ;; something else, do it the slow way
18106 (while (and (not (eobp))
18107 (or first (> (funcall outline-level) level)))
18108 (setq first nil)
18109 (outline-next-heading)))
18110 (unless to-heading
18111 (if (memq (preceding-char) '(?\n ?\^M))
18112 (progn
18113 ;; Go to end of line before heading
18114 (forward-char -1)
18115 (if (memq (preceding-char) '(?\n ?\^M))
18116 ;; leave blank line before heading
18117 (forward-char -1))))))
18118 (point))
18120 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
18121 "Use Org version in org-mode, for dramatic speed-up."
18122 (if (eq major-mode 'org-mode)
18123 (progn
18124 (org-end-of-subtree nil t)
18125 (unless (eobp) (backward-char 1)))
18126 ad-do-it))
18128 (defun org-forward-same-level (arg &optional invisible-ok)
18129 "Move forward to the arg'th subheading at same level as this one.
18130 Stop at the first and last subheadings of a superior heading."
18131 (interactive "p")
18132 (org-back-to-heading invisible-ok)
18133 (org-on-heading-p)
18134 (let* ((level (- (match-end 0) (match-beginning 0) 1))
18135 (re (format "^\\*\\{1,%d\\} " level))
18137 (forward-char 1)
18138 (while (> arg 0)
18139 (while (and (re-search-forward re nil 'move)
18140 (setq l (- (match-end 0) (match-beginning 0) 1))
18141 (= l level)
18142 (not invisible-ok)
18143 (progn (backward-char 1) (org-invisible-p)))
18144 (if (< l level) (setq arg 1)))
18145 (setq arg (1- arg)))
18146 (beginning-of-line 1)))
18148 (defun org-backward-same-level (arg &optional invisible-ok)
18149 "Move backward to the arg'th subheading at same level as this one.
18150 Stop at the first and last subheadings of a superior heading."
18151 (interactive "p")
18152 (org-back-to-heading)
18153 (org-on-heading-p)
18154 (let* ((level (- (match-end 0) (match-beginning 0) 1))
18155 (re (format "^\\*\\{1,%d\\} " level))
18157 (while (> arg 0)
18158 (while (and (re-search-backward re nil 'move)
18159 (setq l (- (match-end 0) (match-beginning 0) 1))
18160 (= l level)
18161 (not invisible-ok)
18162 (org-invisible-p))
18163 (if (< l level) (setq arg 1)))
18164 (setq arg (1- arg)))))
18166 (defun org-show-subtree ()
18167 "Show everything after this heading at deeper levels."
18168 (outline-flag-region
18169 (point)
18170 (save-excursion
18171 (org-end-of-subtree t t))
18172 nil))
18174 (defun org-show-entry ()
18175 "Show the body directly following this heading.
18176 Show the heading too, if it is currently invisible."
18177 (interactive)
18178 (save-excursion
18179 (condition-case nil
18180 (progn
18181 (org-back-to-heading t)
18182 (outline-flag-region
18183 (max (point-min) (1- (point)))
18184 (save-excursion
18185 (if (re-search-forward
18186 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
18187 (match-beginning 1)
18188 (point-max)))
18189 nil)
18190 (org-cycle-hide-drawers 'children))
18191 (error nil))))
18193 (defun org-make-options-regexp (kwds &optional extra)
18194 "Make a regular expression for keyword lines."
18195 (concat
18197 "#?[ \t]*\\+\\("
18198 (mapconcat 'regexp-quote kwds "\\|")
18199 (if extra (concat "\\|" extra))
18200 "\\):[ \t]*"
18201 "\\(.*\\)"))
18203 ;; Make isearch reveal the necessary context
18204 (defun org-isearch-end ()
18205 "Reveal context after isearch exits."
18206 (when isearch-success ; only if search was successful
18207 (if (featurep 'xemacs)
18208 ;; Under XEmacs, the hook is run in the correct place,
18209 ;; we directly show the context.
18210 (org-show-context 'isearch)
18211 ;; In Emacs the hook runs *before* restoring the overlays.
18212 ;; So we have to use a one-time post-command-hook to do this.
18213 ;; (Emacs 22 has a special variable, see function `org-mode')
18214 (unless (and (boundp 'isearch-mode-end-hook-quit)
18215 isearch-mode-end-hook-quit)
18216 ;; Only when the isearch was not quitted.
18217 (org-add-hook 'post-command-hook 'org-isearch-post-command
18218 'append 'local)))))
18220 (defun org-isearch-post-command ()
18221 "Remove self from hook, and show context."
18222 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
18223 (org-show-context 'isearch))
18226 ;;;; Integration with and fixes for other packages
18228 ;;; Imenu support
18230 (defvar org-imenu-markers nil
18231 "All markers currently used by Imenu.")
18232 (make-variable-buffer-local 'org-imenu-markers)
18234 (defun org-imenu-new-marker (&optional pos)
18235 "Return a new marker for use by Imenu, and remember the marker."
18236 (let ((m (make-marker)))
18237 (move-marker m (or pos (point)))
18238 (push m org-imenu-markers)
18241 (defun org-imenu-get-tree ()
18242 "Produce the index for Imenu."
18243 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
18244 (setq org-imenu-markers nil)
18245 (let* ((n org-imenu-depth)
18246 (re (concat "^" outline-regexp))
18247 (subs (make-vector (1+ n) nil))
18248 (last-level 0)
18249 m level head)
18250 (save-excursion
18251 (save-restriction
18252 (widen)
18253 (goto-char (point-max))
18254 (while (re-search-backward re nil t)
18255 (setq level (org-reduced-level (funcall outline-level)))
18256 (when (<= level n)
18257 (looking-at org-complex-heading-regexp)
18258 (setq head (org-link-display-format
18259 (org-match-string-no-properties 4))
18260 m (org-imenu-new-marker))
18261 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
18262 (if (>= level last-level)
18263 (push (cons head m) (aref subs level))
18264 (push (cons head (aref subs (1+ level))) (aref subs level))
18265 (loop for i from (1+ level) to n do (aset subs i nil)))
18266 (setq last-level level)))))
18267 (aref subs 1)))
18269 (eval-after-load "imenu"
18270 '(progn
18271 (add-hook 'imenu-after-jump-hook
18272 (lambda ()
18273 (if (eq major-mode 'org-mode)
18274 (org-show-context 'org-goto))))))
18276 (defun org-link-display-format (link)
18277 "Replace a link with either the description, or the link target
18278 if no description is present"
18279 (save-match-data
18280 (if (string-match org-bracket-link-analytic-regexp link)
18281 (replace-match (if (match-end 5)
18282 (match-string 5 link)
18283 (concat (match-string 1 link)
18284 (match-string 3 link)))
18285 nil t link)
18286 link)))
18288 ;; Speedbar support
18290 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
18291 "Overlay marking the agenda restriction line in speedbar.")
18292 (org-overlay-put org-speedbar-restriction-lock-overlay
18293 'face 'org-agenda-restriction-lock)
18294 (org-overlay-put org-speedbar-restriction-lock-overlay
18295 'help-echo "Agendas are currently limited to this item.")
18296 (org-detach-overlay org-speedbar-restriction-lock-overlay)
18298 (defun org-speedbar-set-agenda-restriction ()
18299 "Restrict future agenda commands to the location at point in speedbar.
18300 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
18301 (interactive)
18302 (require 'org-agenda)
18303 (let (p m tp np dir txt)
18304 (cond
18305 ((setq p (text-property-any (point-at-bol) (point-at-eol)
18306 'org-imenu t))
18307 (setq m (get-text-property p 'org-imenu-marker))
18308 (with-current-buffer (marker-buffer m)
18309 (goto-char m)
18310 (org-agenda-set-restriction-lock 'subtree)))
18311 ((setq p (text-property-any (point-at-bol) (point-at-eol)
18312 'speedbar-function 'speedbar-find-file))
18313 (setq tp (previous-single-property-change
18314 (1+ p) 'speedbar-function)
18315 np (next-single-property-change
18316 tp 'speedbar-function)
18317 dir (speedbar-line-directory)
18318 txt (buffer-substring-no-properties (or tp (point-min))
18319 (or np (point-max))))
18320 (with-current-buffer (find-file-noselect
18321 (let ((default-directory dir))
18322 (expand-file-name txt)))
18323 (unless (org-mode-p)
18324 (error "Cannot restrict to non-Org-mode file"))
18325 (org-agenda-set-restriction-lock 'file)))
18326 (t (error "Don't know how to restrict Org-mode's agenda")))
18327 (org-move-overlay org-speedbar-restriction-lock-overlay
18328 (point-at-bol) (point-at-eol))
18329 (setq current-prefix-arg nil)
18330 (org-agenda-maybe-redo)))
18332 (eval-after-load "speedbar"
18333 '(progn
18334 (speedbar-add-supported-extension ".org")
18335 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
18336 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
18337 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
18338 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18339 (add-hook 'speedbar-visiting-tag-hook
18340 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
18343 ;;; Fixes and Hacks for problems with other packages
18345 ;; Make flyspell not check words in links, to not mess up our keymap
18346 (defun org-mode-flyspell-verify ()
18347 "Don't let flyspell put overlays at active buttons."
18348 (and (not (get-text-property (point) 'keymap))
18349 (not (get-text-property (point) 'org-no-flyspell))))
18351 (defun org-remove-flyspell-overlays-in (beg end)
18352 "Remove flyspell overlays in region."
18353 (and (org-bound-and-true-p flyspell-mode)
18354 (fboundp 'flyspell-delete-region-overlays)
18355 (flyspell-delete-region-overlays beg end))
18356 (add-text-properties beg end '(org-no-flyspell t)))
18358 ;; Make `bookmark-jump' shows the jump location if it was hidden.
18359 (eval-after-load "bookmark"
18360 '(if (boundp 'bookmark-after-jump-hook)
18361 ;; We can use the hook
18362 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
18363 ;; Hook not available, use advice
18364 (defadvice bookmark-jump (after org-make-visible activate)
18365 "Make the position visible."
18366 (org-bookmark-jump-unhide))))
18368 ;; Make sure saveplace shows the location if it was hidden
18369 (eval-after-load "saveplace"
18370 '(defadvice save-place-find-file-hook (after org-make-visible activate)
18371 "Make the position visible."
18372 (org-bookmark-jump-unhide)))
18374 ;; Make sure ecb shows the location if it was hidden
18375 (eval-after-load "ecb"
18376 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
18377 "Make hierarchy visible when jumping into location from ECB tree buffer."
18378 (if (eq major-mode 'org-mode)
18379 (org-show-context))))
18381 (defun org-bookmark-jump-unhide ()
18382 "Unhide the current position, to show the bookmark location."
18383 (and (org-mode-p)
18384 (or (org-invisible-p)
18385 (save-excursion (goto-char (max (point-min) (1- (point))))
18386 (org-invisible-p)))
18387 (org-show-context 'bookmark-jump)))
18389 ;; Make session.el ignore our circular variable
18390 (eval-after-load "session"
18391 '(add-to-list 'session-globals-exclude 'org-mark-ring))
18393 ;;;; Experimental code
18395 (defun org-closed-in-range ()
18396 "Sparse tree of items closed in a certain time range.
18397 Still experimental, may disappear in the future."
18398 (interactive)
18399 ;; Get the time interval from the user.
18400 (let* ((time1 (org-float-time
18401 (org-read-date nil 'to-time nil "Starting date: ")))
18402 (time2 (org-float-time
18403 (org-read-date nil 'to-time nil "End date:")))
18404 ;; callback function
18405 (callback (lambda ()
18406 (let ((time
18407 (org-float-time
18408 (apply 'encode-time
18409 (org-parse-time-string
18410 (match-string 1))))))
18411 ;; check if time in interval
18412 (and (>= time time1) (<= time time2))))))
18413 ;; make tree, check each match with the callback
18414 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
18416 ;;;; Finish up
18418 (provide 'org)
18420 (run-hooks 'org-load-hook)
18422 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
18424 ;;; org.el ends here