Fix problem when inserting a new headline
[org-mode.git] / lisp / org.el
blob84bec4c4868cb1c70b9be566f804723e5759918d
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-refile-targets nil
1592 "Targets for refiling entries with \\[org-refile].
1593 This is list of cons cells. Each cell contains:
1594 - a specification of the files to be considered, either a list of files,
1595 or a symbol whose function or variable value will be used to retrieve
1596 a file name or a list of file names. If you use `org-agenda-files' for
1597 that, all agenda files will be scanned for targets. Nil means consider
1598 headings in the current buffer.
1599 - A specification of how to find candidate refile targets. This may be
1600 any of:
1601 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1602 This tag has to be present in all target headlines, inheritance will
1603 not be considered.
1604 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1605 todo keyword.
1606 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1607 headlines that are refiling targets.
1608 - a cons cell (:level . N). Any headline of level N is considered a target.
1609 Note that, when `org-odd-levels-only' is set, level corresponds to
1610 order in hierarchy, not to the number of stars.
1611 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1612 Note that, when `org-odd-levels-only' is set, level corresponds to
1613 order in hierarchy, not to the number of stars.
1615 You can set the variable `org-refile-target-verify-function' to a function
1616 to verify each headline found by the simple critery above.
1618 When this variable is nil, all top-level headlines in the current buffer
1619 are used, equivalent to the value `((nil . (:level . 1))'."
1620 :group 'org-refile
1621 :type '(repeat
1622 (cons
1623 (choice :value org-agenda-files
1624 (const :tag "All agenda files" org-agenda-files)
1625 (const :tag "Current buffer" nil)
1626 (function) (variable) (file))
1627 (choice :tag "Identify target headline by"
1628 (cons :tag "Specific tag" (const :value :tag) (string))
1629 (cons :tag "TODO keyword" (const :value :todo) (string))
1630 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1631 (cons :tag "Level number" (const :value :level) (integer))
1632 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1634 (defcustom org-refile-target-verify-function nil
1635 "Function to verify if the headline at point should be a refile target.
1636 The function will be called without arguments, with point at the
1637 beginning of the headline. It should return t and leave point
1638 where it is if the headline is a valid target for refiling.
1640 If the target should not be selected, the function must return nil.
1641 In addition to this, it may move point to a place from where the search
1642 should be continued. For example, the function may decide that the entire
1643 subtree of the current entry should be excluded and move point to the end
1644 of the subtree."
1645 :group 'org-refile
1646 :type 'function)
1648 (defcustom org-refile-use-outline-path nil
1649 "Non-nil means provide refile targets as paths.
1650 So a level 3 headline will be available as level1/level2/level3.
1652 When the value is `file', also include the file name (without directory)
1653 into the path. In this case, you can also stop the completion after
1654 the file name, to get entries inserted as top level in the file.
1656 When `full-file-path', include the full file path."
1657 :group 'org-refile
1658 :type '(choice
1659 (const :tag "Not" nil)
1660 (const :tag "Yes" t)
1661 (const :tag "Start with file name" file)
1662 (const :tag "Start with full file path" full-file-path)))
1664 (defcustom org-outline-path-complete-in-steps t
1665 "Non-nil means complete the outline path in hierarchical steps.
1666 When Org-mode uses the refile interface to select an outline path
1667 \(see variable `org-refile-use-outline-path'), the completion of
1668 the path can be done is a single go, or if can be done in steps down
1669 the headline hierarchy. Going in steps is probably the best if you
1670 do not use a special completion package like `ido' or `icicles'.
1671 However, when using these packages, going in one step can be very
1672 fast, while still showing the whole path to the entry."
1673 :group 'org-refile
1674 :type 'boolean)
1676 (defcustom org-refile-allow-creating-parent-nodes nil
1677 "Non-nil means allow to create new nodes as refile targets.
1678 New nodes are then created by adding \"/new node name\" to the completion
1679 of an existing node. When the value of this variable is `confirm',
1680 new node creation must be confirmed by the user (recommended)
1681 When nil, the completion must match an existing entry.
1683 Note that, if the new heading is not seen by the criteria
1684 listed in `org-refile-targets', multiple instances of the same
1685 heading would be created by trying again to file under the new
1686 heading."
1687 :group 'org-refile
1688 :type '(choice
1689 (const :tag "Never" nil)
1690 (const :tag "Always" t)
1691 (const :tag "Prompt for confirmation" confirm)))
1693 (defgroup org-todo nil
1694 "Options concerning TODO items in Org-mode."
1695 :tag "Org TODO"
1696 :group 'org)
1698 (defgroup org-progress nil
1699 "Options concerning Progress logging in Org-mode."
1700 :tag "Org Progress"
1701 :group 'org-time)
1703 (defvar org-todo-interpretation-widgets
1705 (:tag "Sequence (cycling hits every state)" sequence)
1706 (:tag "Type (cycling directly to DONE)" type))
1707 "The available interpretation symbols for customizing
1708 `org-todo-keywords'.
1709 Interested libraries should add to this list.")
1711 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1712 "List of TODO entry keyword sequences and their interpretation.
1713 \\<org-mode-map>This is a list of sequences.
1715 Each sequence starts with a symbol, either `sequence' or `type',
1716 indicating if the keywords should be interpreted as a sequence of
1717 action steps, or as different types of TODO items. The first
1718 keywords are states requiring action - these states will select a headline
1719 for inclusion into the global TODO list Org-mode produces. If one of
1720 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1721 signify that no further action is necessary. If \"|\" is not found,
1722 the last keyword is treated as the only DONE state of the sequence.
1724 The command \\[org-todo] cycles an entry through these states, and one
1725 additional state where no keyword is present. For details about this
1726 cycling, see the manual.
1728 TODO keywords and interpretation can also be set on a per-file basis with
1729 the special #+SEQ_TODO and #+TYP_TODO lines.
1731 Each keyword can optionally specify a character for fast state selection
1732 \(in combination with the variable `org-use-fast-todo-selection')
1733 and specifiers for state change logging, using the same syntax
1734 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1735 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1736 indicates to record a time stamp each time this state is selected.
1738 Each keyword may also specify if a timestamp or a note should be
1739 recorded when entering or leaving the state, by adding additional
1740 characters in the parenthesis after the keyword. This looks like this:
1741 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1742 record only the time of the state change. With X and Y being either
1743 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1744 Y when leaving the state if and only if the *target* state does not
1745 define X. You may omit any of the fast-selection key or X or /Y,
1746 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1748 For backward compatibility, this variable may also be just a list
1749 of keywords - in this case the interpretation (sequence or type) will be
1750 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1751 :group 'org-todo
1752 :group 'org-keywords
1753 :type '(choice
1754 (repeat :tag "Old syntax, just keywords"
1755 (string :tag "Keyword"))
1756 (repeat :tag "New syntax"
1757 (cons
1758 (choice
1759 :tag "Interpretation"
1760 ;;Quick and dirty way to see
1761 ;;`org-todo-interpretations'. This takes the
1762 ;;place of item arguments
1763 :convert-widget
1764 (lambda (widget)
1765 (widget-put widget
1766 :args (mapcar
1767 #'(lambda (x)
1768 (widget-convert
1769 (cons 'const x)))
1770 org-todo-interpretation-widgets))
1771 widget))
1772 (repeat
1773 (string :tag "Keyword"))))))
1775 (defvar org-todo-keywords-1 nil
1776 "All TODO and DONE keywords active in a buffer.")
1777 (make-variable-buffer-local 'org-todo-keywords-1)
1778 (defvar org-todo-keywords-for-agenda nil)
1779 (defvar org-done-keywords-for-agenda nil)
1780 (defvar org-drawers-for-agenda nil)
1781 (defvar org-todo-keyword-alist-for-agenda nil)
1782 (defvar org-tag-alist-for-agenda nil)
1783 (defvar org-agenda-contributing-files nil)
1784 (defvar org-not-done-keywords nil)
1785 (make-variable-buffer-local 'org-not-done-keywords)
1786 (defvar org-done-keywords nil)
1787 (make-variable-buffer-local 'org-done-keywords)
1788 (defvar org-todo-heads nil)
1789 (make-variable-buffer-local 'org-todo-heads)
1790 (defvar org-todo-sets nil)
1791 (make-variable-buffer-local 'org-todo-sets)
1792 (defvar org-todo-log-states nil)
1793 (make-variable-buffer-local 'org-todo-log-states)
1794 (defvar org-todo-kwd-alist nil)
1795 (make-variable-buffer-local 'org-todo-kwd-alist)
1796 (defvar org-todo-key-alist nil)
1797 (make-variable-buffer-local 'org-todo-key-alist)
1798 (defvar org-todo-key-trigger nil)
1799 (make-variable-buffer-local 'org-todo-key-trigger)
1801 (defcustom org-todo-interpretation 'sequence
1802 "Controls how TODO keywords are interpreted.
1803 This variable is in principle obsolete and is only used for
1804 backward compatibility, if the interpretation of todo keywords is
1805 not given already in `org-todo-keywords'. See that variable for
1806 more information."
1807 :group 'org-todo
1808 :group 'org-keywords
1809 :type '(choice (const sequence)
1810 (const type)))
1812 (defcustom org-use-fast-todo-selection t
1813 "Non-nil means use the fast todo selection scheme with C-c C-t.
1814 This variable describes if and under what circumstances the cycling
1815 mechanism for TODO keywords will be replaced by a single-key, direct
1816 selection scheme.
1818 When nil, fast selection is never used.
1820 When the symbol `prefix', it will be used when `org-todo' is called with
1821 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1822 in an agenda buffer.
1824 When t, fast selection is used by default. In this case, the prefix
1825 argument forces cycling instead.
1827 In all cases, the special interface is only used if access keys have actually
1828 been assigned by the user, i.e. if keywords in the configuration are followed
1829 by a letter in parenthesis, like TODO(t)."
1830 :group 'org-todo
1831 :type '(choice
1832 (const :tag "Never" nil)
1833 (const :tag "By default" t)
1834 (const :tag "Only with C-u C-c C-t" prefix)))
1836 (defcustom org-provide-todo-statistics t
1837 "Non-nil means update todo statistics after insert and toggle.
1838 ALL-HEADLINES means update todo statistics by including headlines
1839 with no TODO keyword as well, counting them as not done.
1840 A list of TODO keywords means the same, but skip keywords that are
1841 not in this list.
1843 When this is set, todo statistics is updated in the parent of the
1844 current entry each time a todo state is changed."
1845 :group 'org-todo
1846 :type '(choice
1847 (const :tag "Yes, only for TODO entries" t)
1848 (const :tag "Yes, including all entries" 'all-headlines)
1849 (repeat :tag "Yes, for TODOs in this list"
1850 (string :tag "TODO keyword"))
1851 (other :tag "No TODO statistics" nil)))
1853 (defcustom org-hierarchical-todo-statistics t
1854 "Non-nil means TODO statistics covers just direct children.
1855 When nil, all entries in the subtree are considered.
1856 This has only an effect if `org-provide-todo-statistics' is set.
1857 To set this to nil for only a single subtree, use a COOKIE_DATA
1858 property and include the word \"recursive\" into the value."
1859 :group 'org-todo
1860 :type 'boolean)
1862 (defcustom org-after-todo-state-change-hook nil
1863 "Hook which is run after the state of a TODO item was changed.
1864 The new state (a string with a TODO keyword, or nil) is available in the
1865 Lisp variable `state'."
1866 :group 'org-todo
1867 :type 'hook)
1869 (defvar org-blocker-hook nil
1870 "Hook for functions that are allowed to block a state change.
1872 Each function gets as its single argument a property list, see
1873 `org-trigger-hook' for more information about this list.
1875 If any of the functions in this hook returns nil, the state change
1876 is blocked.")
1878 (defvar org-trigger-hook nil
1879 "Hook for functions that are triggered by a state change.
1881 Each function gets as its single argument a property list with at least
1882 the following elements:
1884 (:type type-of-change :position pos-at-entry-start
1885 :from old-state :to new-state)
1887 Depending on the type, more properties may be present.
1889 This mechanism is currently implemented for:
1891 TODO state changes
1892 ------------------
1893 :type todo-state-change
1894 :from previous state (keyword as a string), or nil, or a symbol
1895 'todo' or 'done', to indicate the general type of state.
1896 :to new state, like in :from")
1898 (defcustom org-enforce-todo-dependencies nil
1899 "Non-nil means undone TODO entries will block switching the parent to DONE.
1900 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1901 be blocked if any prior sibling is not yet done.
1902 Finally, if the parent is blocked because of ordered siblings of its own,
1903 the child will also be blocked.
1904 This variable needs to be set before org.el is loaded, and you need to
1905 restart Emacs after a change to make the change effective. The only way
1906 to change is while Emacs is running is through the customize interface."
1907 :set (lambda (var val)
1908 (set var val)
1909 (if val
1910 (add-hook 'org-blocker-hook
1911 'org-block-todo-from-children-or-siblings-or-parent)
1912 (remove-hook 'org-blocker-hook
1913 'org-block-todo-from-children-or-siblings-or-parent)))
1914 :group 'org-todo
1915 :type 'boolean)
1917 (defcustom org-enforce-todo-checkbox-dependencies nil
1918 "Non-nil means unchecked boxes will block switching the parent to DONE.
1919 When this is nil, checkboxes have no influence on switching TODO states.
1920 When non-nil, you first need to check off all check boxes before the TODO
1921 entry can be switched to DONE.
1922 This variable needs to be set before org.el is loaded, and you need to
1923 restart Emacs after a change to make the change effective. The only way
1924 to change is while Emacs is running is through the customize interface."
1925 :set (lambda (var val)
1926 (set var val)
1927 (if val
1928 (add-hook 'org-blocker-hook
1929 'org-block-todo-from-checkboxes)
1930 (remove-hook 'org-blocker-hook
1931 'org-block-todo-from-checkboxes)))
1932 :group 'org-todo
1933 :type 'boolean)
1935 (defcustom org-treat-insert-todo-heading-as-state-change nil
1936 "Non-nil means inserting a TODO heading is treated as state change.
1937 So when the command \\[org-insert-todo-heading] is used, state change
1938 logging will apply if appropriate. When nil, the new TODO item will
1939 be inserted directly, and no logging will take place."
1940 :group 'org-todo
1941 :type 'boolean)
1943 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1944 "Non-nil means switching TODO states with S-cursor counts as state change.
1945 This is the default behavior. However, setting this to nil allows a
1946 convenient way to select a TODO state and bypass any logging associated
1947 with that."
1948 :group 'org-todo
1949 :type 'boolean)
1951 (defcustom org-todo-state-tags-triggers nil
1952 "Tag changes that should be triggered by TODO state changes.
1953 This is a list. Each entry is
1955 (state-change (tag . flag) .......)
1957 State-change can be a string with a state, and empty string to indicate the
1958 state that has no TODO keyword, or it can be one of the symbols `todo'
1959 or `done', meaning any not-done or done state, respectively."
1960 :group 'org-todo
1961 :group 'org-tags
1962 :type '(repeat
1963 (cons (choice :tag "When changing to"
1964 (const :tag "Not-done state" todo)
1965 (const :tag "Done state" done)
1966 (string :tag "State"))
1967 (repeat
1968 (cons :tag "Tag action"
1969 (string :tag "Tag")
1970 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1972 (defcustom org-log-done nil
1973 "Information to record when a task moves to the DONE state.
1975 Possible values are:
1977 nil Don't add anything, just change the keyword
1978 time Add a time stamp to the task
1979 note Prompt for a note and add it with template `org-log-note-headings'
1981 This option can also be set with on a per-file-basis with
1983 #+STARTUP: nologdone
1984 #+STARTUP: logdone
1985 #+STARTUP: lognotedone
1987 You can have local logging settings for a subtree by setting the LOGGING
1988 property to one or more of these keywords."
1989 :group 'org-todo
1990 :group 'org-progress
1991 :type '(choice
1992 (const :tag "No logging" nil)
1993 (const :tag "Record CLOSED timestamp" time)
1994 (const :tag "Record CLOSED timestamp with note." note)))
1996 ;; Normalize old uses of org-log-done.
1997 (cond
1998 ((eq org-log-done t) (setq org-log-done 'time))
1999 ((and (listp org-log-done) (memq 'done org-log-done))
2000 (setq org-log-done 'note)))
2002 (defcustom org-log-reschedule nil
2003 "Information to record when the scheduling date of a tasks is modified.
2005 Possible values are:
2007 nil Don't add anything, just change the date
2008 time Add a time stamp to the task
2009 note Prompt for a note and add it with template `org-log-note-headings'
2011 This option can also be set with on a per-file-basis with
2013 #+STARTUP: nologreschedule
2014 #+STARTUP: logreschedule
2015 #+STARTUP: lognotereschedule"
2016 :group 'org-todo
2017 :group 'org-progress
2018 :type '(choice
2019 (const :tag "No logging" nil)
2020 (const :tag "Record timestamp" time)
2021 (const :tag "Record timestamp with note." note)))
2023 (defcustom org-log-redeadline nil
2024 "Information to record when the deadline date of a tasks is modified.
2026 Possible values are:
2028 nil Don't add anything, just change the date
2029 time Add a time stamp to the task
2030 note Prompt for a note and add it with template `org-log-note-headings'
2032 This option can also be set with on a per-file-basis with
2034 #+STARTUP: nologredeadline
2035 #+STARTUP: logredeadline
2036 #+STARTUP: lognoteredeadline
2038 You can have local logging settings for a subtree by setting the LOGGING
2039 property to one or more of these keywords."
2040 :group 'org-todo
2041 :group 'org-progress
2042 :type '(choice
2043 (const :tag "No logging" nil)
2044 (const :tag "Record timestamp" time)
2045 (const :tag "Record timestamp with note." note)))
2047 (defcustom org-log-note-clock-out nil
2048 "Non-nil means record a note when clocking out of an item.
2049 This can also be configured on a per-file basis by adding one of
2050 the following lines anywhere in the buffer:
2052 #+STARTUP: lognoteclock-out
2053 #+STARTUP: nolognoteclock-out"
2054 :group 'org-todo
2055 :group 'org-progress
2056 :type 'boolean)
2058 (defcustom org-log-done-with-time t
2059 "Non-nil means the CLOSED time stamp will contain date and time.
2060 When nil, only the date will be recorded."
2061 :group 'org-progress
2062 :type 'boolean)
2064 (defcustom org-log-note-headings
2065 '((done . "CLOSING NOTE %t")
2066 (state . "State %-12s from %-12S %t")
2067 (note . "Note taken on %t")
2068 (reschedule . "Rescheduled from %S on %t")
2069 (delschedule . "Not scheduled, was %S on %t")
2070 (redeadline . "New deadline from %S on %t")
2071 (deldeadline . "Removed deadline, was %S on %t")
2072 (clock-out . ""))
2073 "Headings for notes added to entries.
2074 The value is an alist, with the car being a symbol indicating the note
2075 context, and the cdr is the heading to be used. The heading may also be the
2076 empty string.
2077 %t in the heading will be replaced by a time stamp.
2078 %s will be replaced by the new TODO state, in double quotes.
2079 %S will be replaced by the old TODO state, in double quotes.
2080 %u will be replaced by the user name.
2081 %U will be replaced by the full user name.
2083 In fact, it is not a good idea to change the `state' entry, because
2084 agenda log mode depends on the format of these entries."
2085 :group 'org-todo
2086 :group 'org-progress
2087 :type '(list :greedy t
2088 (cons (const :tag "Heading when closing an item" done) string)
2089 (cons (const :tag
2090 "Heading when changing todo state (todo sequence only)"
2091 state) string)
2092 (cons (const :tag "Heading when just taking a note" note) string)
2093 (cons (const :tag "Heading when clocking out" clock-out) string)
2094 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2095 (cons (const :tag "Heading when rescheduling" reschedule) string)
2096 (cons (const :tag "Heading when changing deadline" redeadline) string
2097 (cons (const :tag "Heading when deleting a deadline" deldeadline) string))))
2099 (unless (assq 'note org-log-note-headings)
2100 (push '(note . "%t") org-log-note-headings))
2102 (defcustom org-log-into-drawer nil
2103 "Non-nil means insert state change notes and time stamps into a drawer.
2104 When nil, state changes notes will be inserted after the headline and
2105 any scheduling and clock lines, but not inside a drawer.
2107 The value of this variable should be the name of the drawer to use.
2108 LOGBOOK is proposed at the default drawer for this purpose, you can
2109 also set this to a string to define the drawer of your choice.
2111 A value of t is also allowed, representing \"LOGBOOK\".
2113 If this variable is set, `org-log-state-notes-insert-after-drawers'
2114 will be ignored.
2116 You can set the property LOG_INTO_DRAWER to overrule this setting for
2117 a subtree."
2118 :group 'org-todo
2119 :group 'org-progress
2120 :type '(choice
2121 (const :tag "Not into a drawer" nil)
2122 (const :tag "LOGBOOK" t)
2123 (string :tag "Other")))
2125 (if (fboundp 'defvaralias)
2126 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2128 (defun org-log-into-drawer ()
2129 "Return the value of `org-log-into-drawer', but let properties overrule.
2130 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2131 used instead of the default value."
2132 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
2133 (cond
2134 ((or (not p) (equal p "nil")) org-log-into-drawer)
2135 ((equal p "t") "LOGBOOK")
2136 (t p))))
2138 (defcustom org-log-state-notes-insert-after-drawers nil
2139 "Non-nil means insert state change notes after any drawers in entry.
2140 Only the drawers that *immediately* follow the headline and the
2141 deadline/scheduled line are skipped.
2142 When nil, insert notes right after the heading and perhaps the line
2143 with deadline/scheduling if present.
2145 This variable will have no effect if `org-log-into-drawer' is
2146 set."
2147 :group 'org-todo
2148 :group 'org-progress
2149 :type 'boolean)
2151 (defcustom org-log-states-order-reversed t
2152 "Non-nil means the latest state note will be directly after heading.
2153 When nil, the state change notes will be ordered according to time."
2154 :group 'org-todo
2155 :group 'org-progress
2156 :type 'boolean)
2158 (defcustom org-log-repeat 'time
2159 "Non-nil means record moving through the DONE state when triggering repeat.
2160 An auto-repeating task is immediately switched back to TODO when
2161 marked DONE. If you are not logging state changes (by adding \"@\"
2162 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2163 record a closing note, there will be no record of the task moving
2164 through DONE. This variable forces taking a note anyway.
2166 nil Don't force a record
2167 time Record a time stamp
2168 note Record a note
2170 This option can also be set with on a per-file-basis with
2172 #+STARTUP: logrepeat
2173 #+STARTUP: lognoterepeat
2174 #+STARTUP: nologrepeat
2176 You can have local logging settings for a subtree by setting the LOGGING
2177 property to one or more of these keywords."
2178 :group 'org-todo
2179 :group 'org-progress
2180 :type '(choice
2181 (const :tag "Don't force a record" nil)
2182 (const :tag "Force recording the DONE state" time)
2183 (const :tag "Force recording a note with the DONE state" note)))
2186 (defgroup org-priorities nil
2187 "Priorities in Org-mode."
2188 :tag "Org Priorities"
2189 :group 'org-todo)
2191 (defcustom org-enable-priority-commands t
2192 "Non-nil means priority commands are active.
2193 When nil, these commands will be disabled, so that you never accidentally
2194 set a priority."
2195 :group 'org-priorities
2196 :type 'boolean)
2198 (defcustom org-highest-priority ?A
2199 "The highest priority of TODO items. A character like ?A, ?B etc.
2200 Must have a smaller ASCII number than `org-lowest-priority'."
2201 :group 'org-priorities
2202 :type 'character)
2204 (defcustom org-lowest-priority ?C
2205 "The lowest priority of TODO items. A character like ?A, ?B etc.
2206 Must have a larger ASCII number than `org-highest-priority'."
2207 :group 'org-priorities
2208 :type 'character)
2210 (defcustom org-default-priority ?B
2211 "The default priority of TODO items.
2212 This is the priority an item get if no explicit priority is given."
2213 :group 'org-priorities
2214 :type 'character)
2216 (defcustom org-priority-start-cycle-with-default t
2217 "Non-nil means start with default priority when starting to cycle.
2218 When this is nil, the first step in the cycle will be (depending on the
2219 command used) one higher or lower that the default priority."
2220 :group 'org-priorities
2221 :type 'boolean)
2223 (defgroup org-time nil
2224 "Options concerning time stamps and deadlines in Org-mode."
2225 :tag "Org Time"
2226 :group 'org)
2228 (defcustom org-insert-labeled-timestamps-at-point nil
2229 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2230 When nil, these labeled time stamps are forces into the second line of an
2231 entry, just after the headline. When scheduling from the global TODO list,
2232 the time stamp will always be forced into the second line."
2233 :group 'org-time
2234 :type 'boolean)
2236 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2237 "Formats for `format-time-string' which are used for time stamps.
2238 It is not recommended to change this constant.")
2240 (defcustom org-time-stamp-rounding-minutes '(0 5)
2241 "Number of minutes to round time stamps to.
2242 These are two values, the first applies when first creating a time stamp.
2243 The second applies when changing it with the commands `S-up' and `S-down'.
2244 When changing the time stamp, this means that it will change in steps
2245 of N minutes, as given by the second value.
2247 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2248 numbers should be factors of 60, so for example 5, 10, 15.
2250 When this is larger than 1, you can still force an exact time-stamp by using
2251 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2252 and by using a prefix arg to `S-up/down' to specify the exact number
2253 of minutes to shift."
2254 :group 'org-time
2255 :get '(lambda (var) ; Make sure all entries have 5 elements
2256 (if (integerp (default-value var))
2257 (list (default-value var) 5)
2258 (default-value var)))
2259 :type '(list
2260 (integer :tag "when inserting times")
2261 (integer :tag "when modifying times")))
2263 ;; Normalize old customizations of this variable.
2264 (when (integerp org-time-stamp-rounding-minutes)
2265 (setq org-time-stamp-rounding-minutes
2266 (list org-time-stamp-rounding-minutes
2267 org-time-stamp-rounding-minutes)))
2269 (defcustom org-display-custom-times nil
2270 "Non-nil means overlay custom formats over all time stamps.
2271 The formats are defined through the variable `org-time-stamp-custom-formats'.
2272 To turn this on on a per-file basis, insert anywhere in the file:
2273 #+STARTUP: customtime"
2274 :group 'org-time
2275 :set 'set-default
2276 :type 'sexp)
2277 (make-variable-buffer-local 'org-display-custom-times)
2279 (defcustom org-time-stamp-custom-formats
2280 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2281 "Custom formats for time stamps. See `format-time-string' for the syntax.
2282 These are overlayed over the default ISO format if the variable
2283 `org-display-custom-times' is set. Time like %H:%M should be at the
2284 end of the second format. The custom formats are also honored by export
2285 commands, if custom time display is turned on at the time of export."
2286 :group 'org-time
2287 :type 'sexp)
2289 (defun org-time-stamp-format (&optional long inactive)
2290 "Get the right format for a time string."
2291 (let ((f (if long (cdr org-time-stamp-formats)
2292 (car org-time-stamp-formats))))
2293 (if inactive
2294 (concat "[" (substring f 1 -1) "]")
2295 f)))
2297 (defcustom org-time-clocksum-format "%d:%02d"
2298 "The format string used when creating CLOCKSUM lines, or when
2299 org-mode generates a time duration."
2300 :group 'org-time
2301 :type 'string)
2303 (defcustom org-time-clocksum-use-fractional nil
2304 "If non-nil, \\[org-clock-display] uses fractional times.
2305 org-mode generates a time duration."
2306 :group 'org-time
2307 :type 'boolean)
2309 (defcustom org-time-clocksum-fractional-format "%.2f"
2310 "The format string used when creating CLOCKSUM lines, or when
2311 org-mode generates a time duration."
2312 :group 'org-time
2313 :type 'string)
2315 (defcustom org-deadline-warning-days 14
2316 "No. of days before expiration during which a deadline becomes active.
2317 This variable governs the display in sparse trees and in the agenda.
2318 When 0 or negative, it means use this number (the absolute value of it)
2319 even if a deadline has a different individual lead time specified.
2321 Custom commands can set this variable in the options section."
2322 :group 'org-time
2323 :group 'org-agenda-daily/weekly
2324 :type 'integer)
2326 (defcustom org-read-date-prefer-future t
2327 "Non-nil means assume future for incomplete date input from user.
2328 This affects the following situations:
2329 1. The user gives a month but not a year.
2330 For example, if it is april and you enter \"feb 2\", this will be read
2331 as feb 2, *next* year. \"May 5\", however, will be this year.
2332 2. The user gives a day, but no month.
2333 For example, if today is the 15th, and you enter \"3\", Org-mode will
2334 read this as the third of *next* month. However, if you enter \"17\",
2335 it will be considered as *this* month.
2337 If you set this variable to the symbol `time', then also the following
2338 will work:
2340 3. If the user gives a time, but no day. If the time is before now,
2341 to will be interpreted as tomorrow.
2343 Currently none of this works for ISO week specifications.
2345 When this option is nil, the current day, month and year will always be
2346 used as defaults."
2347 :group 'org-time
2348 :type '(choice
2349 (const :tag "Never" nil)
2350 (const :tag "Check month and day" t)
2351 (const :tag "Check month, day, and time" time)))
2353 (defcustom org-read-date-display-live t
2354 "Non-nil means display current interpretation of date prompt live.
2355 This display will be in an overlay, in the minibuffer."
2356 :group 'org-time
2357 :type 'boolean)
2359 (defcustom org-read-date-popup-calendar t
2360 "Non-nil means pop up a calendar when prompting for a date.
2361 In the calendar, the date can be selected with mouse-1. However, the
2362 minibuffer will also be active, and you can simply enter the date as well.
2363 When nil, only the minibuffer will be available."
2364 :group 'org-time
2365 :type 'boolean)
2366 (if (fboundp 'defvaralias)
2367 (defvaralias 'org-popup-calendar-for-date-prompt
2368 'org-read-date-popup-calendar))
2370 (defcustom org-read-date-minibuffer-setup-hook nil
2371 "Hook to be used to set up keys for the date/time interface.
2372 Add key definitions to `minibuffer-local-map', which will be a temporary
2373 copy."
2374 :group 'org-time
2375 :type 'hook)
2377 (defcustom org-extend-today-until 0
2378 "The hour when your day really ends. Must be an integer.
2379 This has influence for the following applications:
2380 - When switching the agenda to \"today\". It it is still earlier than
2381 the time given here, the day recognized as TODAY is actually yesterday.
2382 - When a date is read from the user and it is still before the time given
2383 here, the current date and time will be assumed to be yesterday, 23:59.
2384 Also, timestamps inserted in remember templates follow this rule.
2386 IMPORTANT: This is a feature whose implementation is and likely will
2387 remain incomplete. Really, it is only here because past midnight seems to
2388 be the favorite working time of John Wiegley :-)"
2389 :group 'org-time
2390 :type 'integer)
2392 (defcustom org-edit-timestamp-down-means-later nil
2393 "Non-nil means S-down will increase the time in a time stamp.
2394 When nil, S-up will increase."
2395 :group 'org-time
2396 :type 'boolean)
2398 (defcustom org-calendar-follow-timestamp-change t
2399 "Non-nil means make the calendar window follow timestamp changes.
2400 When a timestamp is modified and the calendar window is visible, it will be
2401 moved to the new date."
2402 :group 'org-time
2403 :type 'boolean)
2405 (defgroup org-tags nil
2406 "Options concerning tags in Org-mode."
2407 :tag "Org Tags"
2408 :group 'org)
2410 (defcustom org-tag-alist nil
2411 "List of tags allowed in Org-mode files.
2412 When this list is nil, Org-mode will base TAG input on what is already in the
2413 buffer.
2414 The value of this variable is an alist, the car of each entry must be a
2415 keyword as a string, the cdr may be a character that is used to select
2416 that tag through the fast-tag-selection interface.
2417 See the manual for details."
2418 :group 'org-tags
2419 :type '(repeat
2420 (choice
2421 (cons (string :tag "Tag name")
2422 (character :tag "Access char"))
2423 (list :tag "Start radio group"
2424 (const :startgroup)
2425 (option (string :tag "Group description")))
2426 (list :tag "End radio group"
2427 (const :endgroup)
2428 (option (string :tag "Group description")))
2429 (const :tag "New line" (:newline)))))
2431 (defcustom org-tag-persistent-alist nil
2432 "List of tags that will always appear in all Org-mode files.
2433 This is in addition to any in buffer settings or customizations
2434 of `org-tag-alist'.
2435 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2436 The value of this variable is an alist, the car of each entry must be a
2437 keyword as a string, the cdr may be a character that is used to select
2438 that tag through the fast-tag-selection interface.
2439 See the manual for details.
2440 To disable these tags on a per-file basis, insert anywhere in the file:
2441 #+STARTUP: noptag"
2442 :group 'org-tags
2443 :type '(repeat
2444 (choice
2445 (cons (string :tag "Tag name")
2446 (character :tag "Access char"))
2447 (const :tag "Start radio group" (:startgroup))
2448 (const :tag "End radio group" (:endgroup))
2449 (const :tag "New line" (:newline)))))
2451 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2452 "If non-nil, always offer completion for all tags of all agenda files.
2453 Instead of customizing this variable directly, you might want to
2454 set it locally for remember buffers, because there no list of
2455 tags in that file can be created dynamically (there are none).
2457 (add-hook 'org-remember-mode-hook
2458 (lambda ()
2459 (set (make-local-variable
2460 'org-complete-tags-always-offer-all-agenda-tags)
2461 t)))"
2462 :group 'org-tags
2463 :type 'boolean)
2465 (defvar org-file-tags nil
2466 "List of tags that can be inherited by all entries in the file.
2467 The tags will be inherited if the variable `org-use-tag-inheritance'
2468 says they should be.
2469 This variable is populated from #+FILETAGS lines.")
2471 (defcustom org-use-fast-tag-selection 'auto
2472 "Non-nil means use fast tag selection scheme.
2473 This is a special interface to select and deselect tags with single keys.
2474 When nil, fast selection is never used.
2475 When the symbol `auto', fast selection is used if and only if selection
2476 characters for tags have been configured, either through the variable
2477 `org-tag-alist' or through a #+TAGS line in the buffer.
2478 When t, fast selection is always used and selection keys are assigned
2479 automatically if necessary."
2480 :group 'org-tags
2481 :type '(choice
2482 (const :tag "Always" t)
2483 (const :tag "Never" nil)
2484 (const :tag "When selection characters are configured" 'auto)))
2486 (defcustom org-fast-tag-selection-single-key nil
2487 "Non-nil means fast tag selection exits after first change.
2488 When nil, you have to press RET to exit it.
2489 During fast tag selection, you can toggle this flag with `C-c'.
2490 This variable can also have the value `expert'. In this case, the window
2491 displaying the tags menu is not even shown, until you press C-c again."
2492 :group 'org-tags
2493 :type '(choice
2494 (const :tag "No" nil)
2495 (const :tag "Yes" t)
2496 (const :tag "Expert" expert)))
2498 (defvar org-fast-tag-selection-include-todo nil
2499 "Non-nil means fast tags selection interface will also offer TODO states.
2500 This is an undocumented feature, you should not rely on it.")
2502 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2503 "The column to which tags should be indented in a headline.
2504 If this number is positive, it specifies the column. If it is negative,
2505 it means that the tags should be flushright to that column. For example,
2506 -80 works well for a normal 80 character screen."
2507 :group 'org-tags
2508 :type 'integer)
2510 (defcustom org-auto-align-tags t
2511 "Non-nil means realign tags after pro/demotion of TODO state change.
2512 These operations change the length of a headline and therefore shift
2513 the tags around. With this options turned on, after each such operation
2514 the tags are again aligned to `org-tags-column'."
2515 :group 'org-tags
2516 :type 'boolean)
2518 (defcustom org-use-tag-inheritance t
2519 "Non-nil means tags in levels apply also for sublevels.
2520 When nil, only the tags directly given in a specific line apply there.
2521 This may also be a list of tags that should be inherited, or a regexp that
2522 matches tags that should be inherited. Additional control is possible
2523 with the variable `org-tags-exclude-from-inheritance' which gives an
2524 explicit list of tags to be excluded from inheritance., even if the value of
2525 `org-use-tag-inheritance' would select it for inheritance.
2527 If this option is t, a match early-on in a tree can lead to a large
2528 number of matches in the subtree when constructing the agenda or creating
2529 a sparse tree. If you only want to see the first match in a tree during
2530 a search, check out the variable `org-tags-match-list-sublevels'."
2531 :group 'org-tags
2532 :type '(choice
2533 (const :tag "Not" nil)
2534 (const :tag "Always" t)
2535 (repeat :tag "Specific tags" (string :tag "Tag"))
2536 (regexp :tag "Tags matched by regexp")))
2538 (defcustom org-tags-exclude-from-inheritance nil
2539 "List of tags that should never be inherited.
2540 This is a way to exclude a few tags from inheritance. For way to do
2541 the opposite, to actively allow inheritance for selected tags,
2542 see the variable `org-use-tag-inheritance'."
2543 :group 'org-tags
2544 :type '(repeat (string :tag "Tag")))
2546 (defun org-tag-inherit-p (tag)
2547 "Check if TAG is one that should be inherited."
2548 (cond
2549 ((member tag org-tags-exclude-from-inheritance) nil)
2550 ((eq org-use-tag-inheritance t) t)
2551 ((not org-use-tag-inheritance) nil)
2552 ((stringp org-use-tag-inheritance)
2553 (string-match org-use-tag-inheritance tag))
2554 ((listp org-use-tag-inheritance)
2555 (member tag org-use-tag-inheritance))
2556 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2558 (defcustom org-tags-match-list-sublevels t
2559 "Non-nil means list also sublevels of headlines matching a search.
2560 This variable applies to tags/property searches, and also to stuck
2561 projects because this search is based on a tags match as well.
2563 When set to the symbol `indented', sublevels are indented with
2564 leading dots.
2566 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2567 the sublevels of a headline matching a tag search often also match
2568 the same search. Listing all of them can create very long lists.
2569 Setting this variable to nil causes subtrees of a match to be skipped.
2571 This variable is semi-obsolete and probably should always be true. It
2572 is better to limit inheritance to certain tags using the variables
2573 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2574 :group 'org-tags
2575 :type '(choice
2576 (const :tag "No, don't list them" nil)
2577 (const :tag "Yes, do list them" t)
2578 (const :tag "List them, indented with leading dots" indented)))
2580 (defcustom org-tags-sort-function nil
2581 "When set, tags are sorted using this function as a comparator"
2582 :group 'org-tags
2583 :type '(choice
2584 (const :tag "No sorting" nil)
2585 (const :tag "Alphabetical" string<)
2586 (const :tag "Reverse alphabetical" string>)
2587 (function :tag "Custom function" nil)))
2589 (defvar org-tags-history nil
2590 "History of minibuffer reads for tags.")
2591 (defvar org-last-tags-completion-table nil
2592 "The last used completion table for tags.")
2593 (defvar org-after-tags-change-hook nil
2594 "Hook that is run after the tags in a line have changed.")
2596 (defgroup org-properties nil
2597 "Options concerning properties in Org-mode."
2598 :tag "Org Properties"
2599 :group 'org)
2601 (defcustom org-property-format "%-10s %s"
2602 "How property key/value pairs should be formatted by `indent-line'.
2603 When `indent-line' hits a property definition, it will format the line
2604 according to this format, mainly to make sure that the values are
2605 lined-up with respect to each other."
2606 :group 'org-properties
2607 :type 'string)
2609 (defcustom org-use-property-inheritance nil
2610 "Non-nil means properties apply also for sublevels.
2612 This setting is chiefly used during property searches. Turning it on can
2613 cause significant overhead when doing a search, which is why it is not
2614 on by default.
2616 When nil, only the properties directly given in the current entry count.
2617 When t, every property is inherited. The value may also be a list of
2618 properties that should have inheritance, or a regular expression matching
2619 properties that should be inherited.
2621 However, note that some special properties use inheritance under special
2622 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2623 and the properties ending in \"_ALL\" when they are used as descriptor
2624 for valid values of a property.
2626 Note for programmers:
2627 When querying an entry with `org-entry-get', you can control if inheritance
2628 should be used. By default, `org-entry-get' looks only at the local
2629 properties. You can request inheritance by setting the inherit argument
2630 to t (to force inheritance) or to `selective' (to respect the setting
2631 in this variable)."
2632 :group 'org-properties
2633 :type '(choice
2634 (const :tag "Not" nil)
2635 (const :tag "Always" t)
2636 (repeat :tag "Specific properties" (string :tag "Property"))
2637 (regexp :tag "Properties matched by regexp")))
2639 (defun org-property-inherit-p (property)
2640 "Check if PROPERTY is one that should be inherited."
2641 (cond
2642 ((eq org-use-property-inheritance t) t)
2643 ((not org-use-property-inheritance) nil)
2644 ((stringp org-use-property-inheritance)
2645 (string-match org-use-property-inheritance property))
2646 ((listp org-use-property-inheritance)
2647 (member property org-use-property-inheritance))
2648 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2650 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2651 "The default column format, if no other format has been defined.
2652 This variable can be set on the per-file basis by inserting a line
2654 #+COLUMNS: %25ITEM ....."
2655 :group 'org-properties
2656 :type 'string)
2658 (defcustom org-columns-ellipses ".."
2659 "The ellipses to be used when a field in column view is truncated.
2660 When this is the empty string, as many characters as possible are shown,
2661 but then there will be no visual indication that the field has been truncated.
2662 When this is a string of length N, the last N characters of a truncated
2663 field are replaced by this string. If the column is narrower than the
2664 ellipses string, only part of the ellipses string will be shown."
2665 :group 'org-properties
2666 :type 'string)
2668 (defcustom org-columns-modify-value-for-display-function nil
2669 "Function that modifies values for display in column view.
2670 For example, it can be used to cut out a certain part from a time stamp.
2671 The function must take 2 arguments:
2673 column-title The title of the column (*not* the property name)
2674 value The value that should be modified.
2676 The function should return the value that should be displayed,
2677 or nil if the normal value should be used."
2678 :group 'org-properties
2679 :type 'function)
2681 (defcustom org-effort-property "Effort"
2682 "The property that is being used to keep track of effort estimates.
2683 Effort estimates given in this property need to have the format H:MM."
2684 :group 'org-properties
2685 :group 'org-progress
2686 :type '(string :tag "Property"))
2688 (defconst org-global-properties-fixed
2689 '(("VISIBILITY_ALL" . "folded children content all")
2690 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2691 "List of property/value pairs that can be inherited by any entry.
2693 These are fixed values, for the preset properties. The user variable
2694 that can be used to add to this list is `org-global-properties'.
2696 The entries in this list are cons cells where the car is a property
2697 name and cdr is a string with the value. If the value represents
2698 multiple items like an \"_ALL\" property, separate the items by
2699 spaces.")
2701 (defcustom org-global-properties nil
2702 "List of property/value pairs that can be inherited by any entry.
2704 This list will be combined with the constant `org-global-properties-fixed'.
2706 The entries in this list are cons cells where the car is a property
2707 name and cdr is a string with the value.
2709 You can set buffer-local values for the same purpose in the variable
2710 `org-file-properties' this by adding lines like
2712 #+PROPERTY: NAME VALUE"
2713 :group 'org-properties
2714 :type '(repeat
2715 (cons (string :tag "Property")
2716 (string :tag "Value"))))
2718 (defvar org-file-properties nil
2719 "List of property/value pairs that can be inherited by any entry.
2720 Valid for the current buffer.
2721 This variable is populated from #+PROPERTY lines.")
2722 (make-variable-buffer-local 'org-file-properties)
2724 (defgroup org-agenda nil
2725 "Options concerning agenda views in Org-mode."
2726 :tag "Org Agenda"
2727 :group 'org)
2729 (defvar org-category nil
2730 "Variable used by org files to set a category for agenda display.
2731 Such files should use a file variable to set it, for example
2733 # -*- mode: org; org-category: \"ELisp\"
2735 or contain a special line
2737 #+CATEGORY: ELisp
2739 If the file does not specify a category, then file's base name
2740 is used instead.")
2741 (make-variable-buffer-local 'org-category)
2742 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2744 (defcustom org-agenda-files nil
2745 "The files to be used for agenda display.
2746 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2747 \\[org-remove-file]. You can also use customize to edit the list.
2749 If an entry is a directory, all files in that directory that are matched by
2750 `org-agenda-file-regexp' will be part of the file list.
2752 If the value of the variable is not a list but a single file name, then
2753 the list of agenda files is actually stored and maintained in that file, one
2754 agenda file per line."
2755 :group 'org-agenda
2756 :type '(choice
2757 (repeat :tag "List of files and directories" file)
2758 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2760 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2761 "Regular expression to match files for `org-agenda-files'.
2762 If any element in the list in that variable contains a directory instead
2763 of a normal file, all files in that directory that are matched by this
2764 regular expression will be included."
2765 :group 'org-agenda
2766 :type 'regexp)
2768 (defcustom org-agenda-text-search-extra-files nil
2769 "List of extra files to be searched by text search commands.
2770 These files will be search in addition to the agenda files by the
2771 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2772 Note that these files will only be searched for text search commands,
2773 not for the other agenda views like todo lists, tag searches or the weekly
2774 agenda. This variable is intended to list notes and possibly archive files
2775 that should also be searched by these two commands.
2776 In fact, if the first element in the list is the symbol `agenda-archives',
2777 than all archive files of all agenda files will be added to the search
2778 scope."
2779 :group 'org-agenda
2780 :type '(set :greedy t
2781 (const :tag "Agenda Archives" agenda-archives)
2782 (repeat :inline t (file))))
2784 (if (fboundp 'defvaralias)
2785 (defvaralias 'org-agenda-multi-occur-extra-files
2786 'org-agenda-text-search-extra-files))
2788 (defcustom org-agenda-skip-unavailable-files nil
2789 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2790 A nil value means to remove them, after a query, from the list."
2791 :group 'org-agenda
2792 :type 'boolean)
2794 (defcustom org-calendar-to-agenda-key [?c]
2795 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2796 The command `org-calendar-goto-agenda' will be bound to this key. The
2797 default is the character `c' because then `c' can be used to switch back and
2798 forth between agenda and calendar."
2799 :group 'org-agenda
2800 :type 'sexp)
2802 (defcustom org-calendar-agenda-action-key [?k]
2803 "The key to be installed in `calendar-mode-map' for agenda-action.
2804 The command `org-agenda-action' will be bound to this key. The
2805 default is the character `k' because we use the same key in the agenda."
2806 :group 'org-agenda
2807 :type 'sexp)
2809 (defcustom org-calendar-insert-diary-entry-key [?i]
2810 "The key to be installed in `calendar-mode-map' for adding diary entries.
2811 This option is irrelevant until `org-agenda-diary-file' has been configured
2812 to point to an Org-mode file. When that is the case, the command
2813 `org-agenda-diary-entry' will be bound to the key given here, by default
2814 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
2815 if you want to continue doing this, you need to change this to a different
2816 key."
2817 :group 'org-agenda
2818 :type 'sexp)
2820 (defcustom org-agenda-diary-file 'diary-file
2821 "File to which to add new entries with the `i' key in agenda and calendar.
2822 When this is the symbol `diary-file', the functionality in the Emacs
2823 calendar will be used to add entries to the `diary-file'. But when this
2824 points to a file, `org-agenda-diary-entry' will be used instead."
2825 :group 'org-agenda
2826 :type '(choice
2827 (const :tag "The standard Emacs diary file" diary-file)
2828 (file :tag "Special Org file diary entries")))
2830 (eval-after-load "calendar"
2831 '(progn
2832 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2833 'org-calendar-goto-agenda)
2834 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2835 'org-agenda-action)
2836 (add-hook 'calendar-mode-hook
2837 (lambda ()
2838 (unless (eq org-agenda-diary-file 'diary-file)
2839 (define-key calendar-mode-map
2840 org-calendar-insert-diary-entry-key
2841 'org-agenda-diary-entry))))))
2843 (defgroup org-latex nil
2844 "Options for embedding LaTeX code into Org-mode."
2845 :tag "Org LaTeX"
2846 :group 'org)
2848 (defcustom org-format-latex-options
2849 '(:foreground default :background default :scale 1.0
2850 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2851 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2852 "Options for creating images from LaTeX fragments.
2853 This is a property list with the following properties:
2854 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2855 `default' means use the foreground of the default face.
2856 :background the background color, or \"Transparent\".
2857 `default' means use the background of the default face.
2858 :scale a scaling factor for the size of the images.
2859 :html-foreground, :html-background, :html-scale
2860 the same numbers for HTML export.
2861 :matchers a list indicating which matchers should be used to
2862 find LaTeX fragments. Valid members of this list are:
2863 \"begin\" find environments
2864 \"$1\" find single characters surrounded by $.$
2865 \"$\" find math expressions surrounded by $...$
2866 \"$$\" find math expressions surrounded by $$....$$
2867 \"\\(\" find math expressions surrounded by \\(...\\)
2868 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2869 :group 'org-latex
2870 :type 'plist)
2872 (defcustom org-format-latex-signal-error t
2873 "Non-nil means signal an error when image creation of LaTeX snippets fails.
2874 When nil, just push out a message."
2875 :group 'org-latex
2876 :type 'boolean)
2878 (defcustom org-format-latex-header "\\documentclass{article}
2879 \\usepackage{amssymb}
2880 \\usepackage[usenames]{color}
2881 \\usepackage{amsmath}
2882 \\usepackage{latexsym}
2883 \\usepackage[mathscr]{eucal}
2884 \\pagestyle{empty} % do not remove
2885 % The settings below are copied from fullpage.sty
2886 \\setlength{\\textwidth}{\\paperwidth}
2887 \\addtolength{\\textwidth}{-3cm}
2888 \\setlength{\\oddsidemargin}{1.5cm}
2889 \\addtolength{\\oddsidemargin}{-2.54cm}
2890 \\setlength{\\evensidemargin}{\\oddsidemargin}
2891 \\setlength{\\textheight}{\\paperheight}
2892 \\addtolength{\\textheight}{-\\headheight}
2893 \\addtolength{\\textheight}{-\\headsep}
2894 \\addtolength{\\textheight}{-\\footskip}
2895 \\addtolength{\\textheight}{-3cm}
2896 \\setlength{\\topmargin}{1.5cm}
2897 \\addtolength{\\topmargin}{-2.54cm}"
2898 "The document header used for processing LaTeX fragments.
2899 It is imperative that this header make sure that no page number
2900 appears on the page."
2901 :group 'org-latex
2902 :type 'string)
2904 (defvar org-format-latex-header-extra nil)
2906 ;; The following variable is defined here because is it also used
2907 ;; when formatting latex fragments. Originally it was part of the
2908 ;; LaTeX exporter, which is why the name includes "export".
2909 (defcustom org-export-latex-packages-alist nil
2910 "Alist of packages to be inserted in the header.
2911 Each cell is of the format \( \"option\" . \"package\" \)."
2912 :group 'org-export-latex
2913 :type '(repeat
2914 (list
2915 (string :tag "option")
2916 (string :tag "package"))))
2918 (defgroup org-font-lock nil
2919 "Font-lock settings for highlighting in Org-mode."
2920 :tag "Org Font Lock"
2921 :group 'org)
2923 (defcustom org-level-color-stars-only nil
2924 "Non-nil means fontify only the stars in each headline.
2925 When nil, the entire headline is fontified.
2926 Changing it requires restart of `font-lock-mode' to become effective
2927 also in regions already fontified."
2928 :group 'org-font-lock
2929 :type 'boolean)
2931 (defcustom org-hide-leading-stars nil
2932 "Non-nil means hide the first N-1 stars in a headline.
2933 This works by using the face `org-hide' for these stars. This
2934 face is white for a light background, and black for a dark
2935 background. You may have to customize the face `org-hide' to
2936 make this work.
2937 Changing it requires restart of `font-lock-mode' to become effective
2938 also in regions already fontified.
2939 You may also set this on a per-file basis by adding one of the following
2940 lines to the buffer:
2942 #+STARTUP: hidestars
2943 #+STARTUP: showstars"
2944 :group 'org-font-lock
2945 :type 'boolean)
2947 (defcustom org-fontify-done-headline nil
2948 "Non-nil means change the face of a headline if it is marked DONE.
2949 Normally, only the TODO/DONE keyword indicates the state of a headline.
2950 When this is non-nil, the headline after the keyword is set to the
2951 `org-headline-done' as an additional indication."
2952 :group 'org-font-lock
2953 :type 'boolean)
2955 (defcustom org-fontify-emphasized-text t
2956 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2957 Changing this variable requires a restart of Emacs to take effect."
2958 :group 'org-font-lock
2959 :type 'boolean)
2961 (defcustom org-fontify-whole-heading-line nil
2962 "Non-nil means fontify the whole line for headings.
2963 This is useful when setting a background color for the
2964 org-level-* faces."
2965 :group 'org-font-lock
2966 :type 'boolean)
2968 (defcustom org-highlight-latex-fragments-and-specials nil
2969 "Non-nil means fontify what is treated specially by the exporters."
2970 :group 'org-font-lock
2971 :type 'boolean)
2973 (defcustom org-hide-emphasis-markers nil
2974 "Non-nil mean font-lock should hide the emphasis marker characters."
2975 :group 'org-font-lock
2976 :type 'boolean)
2978 (defvar org-emph-re nil
2979 "Regular expression for matching emphasis.")
2980 (defvar org-verbatim-re nil
2981 "Regular expression for matching verbatim text.")
2982 (defvar org-emphasis-regexp-components) ; defined just below
2983 (defvar org-emphasis-alist) ; defined just below
2984 (defun org-set-emph-re (var val)
2985 "Set variable and compute the emphasis regular expression."
2986 (set var val)
2987 (when (and (boundp 'org-emphasis-alist)
2988 (boundp 'org-emphasis-regexp-components)
2989 org-emphasis-alist org-emphasis-regexp-components)
2990 (let* ((e org-emphasis-regexp-components)
2991 (pre (car e))
2992 (post (nth 1 e))
2993 (border (nth 2 e))
2994 (body (nth 3 e))
2995 (nl (nth 4 e))
2996 (body1 (concat body "*?"))
2997 (markers (mapconcat 'car org-emphasis-alist ""))
2998 (vmarkers (mapconcat
2999 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3000 org-emphasis-alist "")))
3001 ;; make sure special characters appear at the right position in the class
3002 (if (string-match "\\^" markers)
3003 (setq markers (concat (replace-match "" t t markers) "^")))
3004 (if (string-match "-" markers)
3005 (setq markers (concat (replace-match "" t t markers) "-")))
3006 (if (string-match "\\^" vmarkers)
3007 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3008 (if (string-match "-" vmarkers)
3009 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3010 (if (> nl 0)
3011 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3012 (int-to-string nl) "\\}")))
3013 ;; Make the regexp
3014 (setq org-emph-re
3015 (concat "\\([" pre "]\\|^\\)"
3016 "\\("
3017 "\\([" markers "]\\)"
3018 "\\("
3019 "[^" border "]\\|"
3020 "[^" border "]"
3021 body1
3022 "[^" border "]"
3023 "\\)"
3024 "\\3\\)"
3025 "\\([" post "]\\|$\\)"))
3026 (setq org-verbatim-re
3027 (concat "\\([" pre "]\\|^\\)"
3028 "\\("
3029 "\\([" vmarkers "]\\)"
3030 "\\("
3031 "[^" border "]\\|"
3032 "[^" border "]"
3033 body1
3034 "[^" border "]"
3035 "\\)"
3036 "\\3\\)"
3037 "\\([" post "]\\|$\\)")))))
3039 (defcustom org-emphasis-regexp-components
3040 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3041 "Components used to build the regular expression for emphasis.
3042 This is a list with 6 entries. Terminology: In an emphasis string
3043 like \" *strong word* \", we call the initial space PREMATCH, the final
3044 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3045 and \"trong wor\" is the body. The different components in this variable
3046 specify what is allowed/forbidden in each part:
3048 pre Chars allowed as prematch. Beginning of line will be allowed too.
3049 post Chars allowed as postmatch. End of line will be allowed too.
3050 border The chars *forbidden* as border characters.
3051 body-regexp A regexp like \".\" to match a body character. Don't use
3052 non-shy groups here, and don't allow newline here.
3053 newline The maximum number of newlines allowed in an emphasis exp.
3055 Use customize to modify this, or restart Emacs after changing it."
3056 :group 'org-font-lock
3057 :set 'org-set-emph-re
3058 :type '(list
3059 (sexp :tag "Allowed chars in pre ")
3060 (sexp :tag "Allowed chars in post ")
3061 (sexp :tag "Forbidden chars in border ")
3062 (sexp :tag "Regexp for body ")
3063 (integer :tag "number of newlines allowed")
3064 (option (boolean :tag "Please ignore this button"))))
3066 (defcustom org-emphasis-alist
3067 `(("*" bold "<b>" "</b>")
3068 ("/" italic "<i>" "</i>")
3069 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3070 ("=" org-code "<code>" "</code>" verbatim)
3071 ("~" org-verbatim "<code>" "</code>" verbatim)
3072 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3073 "<del>" "</del>")
3075 "Special syntax for emphasized text.
3076 Text starting and ending with a special character will be emphasized, for
3077 example *bold*, _underlined_ and /italic/. This variable sets the marker
3078 characters, the face to be used by font-lock for highlighting in Org-mode
3079 Emacs buffers, and the HTML tags to be used for this.
3080 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3081 Use customize to modify this, or restart Emacs after changing it."
3082 :group 'org-font-lock
3083 :set 'org-set-emph-re
3084 :type '(repeat
3085 (list
3086 (string :tag "Marker character")
3087 (choice
3088 (face :tag "Font-lock-face")
3089 (plist :tag "Face property list"))
3090 (string :tag "HTML start tag")
3091 (string :tag "HTML end tag")
3092 (option (const verbatim)))))
3094 (defvar org-protecting-blocks
3095 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3096 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3097 This is needed for font-lock setup.")
3099 ;;; Miscellaneous options
3101 (defgroup org-completion nil
3102 "Completion in Org-mode."
3103 :tag "Org Completion"
3104 :group 'org)
3106 (defcustom org-completion-use-ido nil
3107 "Non-nil means use ido completion wherever possible.
3108 Note that `ido-mode' must be active for this variable to be relevant.
3109 If you decide to turn this variable on, you might well want to turn off
3110 `org-outline-path-complete-in-steps'.
3111 See also `org-completion-use-iswitchb'."
3112 :group 'org-completion
3113 :type 'boolean)
3115 (defcustom org-completion-use-iswitchb nil
3116 "Non-nil means use iswitchb completion wherever possible.
3117 Note that `iswitchb-mode' must be active for this variable to be relevant.
3118 If you decide to turn this variable on, you might well want to turn off
3119 `org-outline-path-complete-in-steps'.
3120 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3121 :group 'org-completion
3122 :type 'boolean)
3124 (defcustom org-completion-fallback-command 'hippie-expand
3125 "The expansion command called by \\[org-complete] in normal context.
3126 Normal means no org-mode-specific context."
3127 :group 'org-completion
3128 :type 'function)
3130 ;;; Functions and variables from their packages
3131 ;; Declared here to avoid compiler warnings
3133 ;; XEmacs only
3134 (defvar outline-mode-menu-heading)
3135 (defvar outline-mode-menu-show)
3136 (defvar outline-mode-menu-hide)
3137 (defvar zmacs-regions) ; XEmacs regions
3139 ;; Emacs only
3140 (defvar mark-active)
3142 ;; Various packages
3143 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3144 (declare-function calendar-forward-day "cal-move" (arg))
3145 (declare-function calendar-goto-date "cal-move" (date))
3146 (declare-function calendar-goto-today "cal-move" ())
3147 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3148 (defvar calc-embedded-close-formula)
3149 (defvar calc-embedded-open-formula)
3150 (declare-function cdlatex-tab "ext:cdlatex" ())
3151 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3152 (defvar font-lock-unfontify-region-function)
3153 (declare-function iswitchb-read-buffer "iswitchb"
3154 (prompt &optional default require-match start matches-set))
3155 (defvar iswitchb-temp-buflist)
3156 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3157 (defvar org-agenda-tags-todo-honor-ignore-options)
3158 (declare-function org-agenda-skip "org-agenda" ())
3159 (declare-function
3160 org-format-agenda-item "org-agenda"
3161 (extra txt &optional category tags dotime noprefix remove-re habitp))
3162 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3163 (declare-function org-agenda-change-all-lines "org-agenda"
3164 (newhead hdmarker &optional fixface just-this))
3165 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3166 (declare-function org-agenda-maybe-redo "org-agenda" ())
3167 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3168 (beg end))
3169 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3170 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3171 "org-agenda" (&optional end))
3172 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3173 (declare-function org-indent-mode "org-indent" (&optional arg))
3174 (declare-function parse-time-string "parse-time" (string))
3175 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3176 (defvar remember-data-file)
3177 (defvar texmathp-why)
3178 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3179 (declare-function table--at-cell-p "table" (position &optional object at-column))
3181 (defvar w3m-current-url)
3182 (defvar w3m-current-title)
3184 (defvar org-latex-regexps)
3186 ;;; Autoload and prepare some org modules
3188 ;; Some table stuff that needs to be defined here, because it is used
3189 ;; by the functions setting up org-mode or checking for table context.
3191 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3192 "Detects an org-type or table-type table.")
3193 (defconst org-table-line-regexp "^[ \t]*|"
3194 "Detects an org-type table line.")
3195 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3196 "Detects an org-type table line.")
3197 (defconst org-table-hline-regexp "^[ \t]*|-"
3198 "Detects an org-type table hline.")
3199 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3200 "Detects a table-type table hline.")
3201 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3202 "Searching from within a table (any type) this finds the first line
3203 outside the table.")
3205 ;; Autoload the functions in org-table.el that are needed by functions here.
3207 (eval-and-compile
3208 (org-autoload "org-table"
3209 '(org-table-align org-table-begin org-table-blank-field
3210 org-table-convert org-table-convert-region org-table-copy-down
3211 org-table-copy-region org-table-create
3212 org-table-create-or-convert-from-region
3213 org-table-create-with-table.el org-table-current-dline
3214 org-table-cut-region org-table-delete-column org-table-edit-field
3215 org-table-edit-formulas org-table-end org-table-eval-formula
3216 org-table-export org-table-field-info
3217 org-table-get-stored-formulas org-table-goto-column
3218 org-table-hline-and-move org-table-import org-table-insert-column
3219 org-table-insert-hline org-table-insert-row org-table-iterate
3220 org-table-justify-field-maybe org-table-kill-row
3221 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3222 org-table-move-column org-table-move-column-left
3223 org-table-move-column-right org-table-move-row
3224 org-table-move-row-down org-table-move-row-up
3225 org-table-next-field org-table-next-row org-table-paste-rectangle
3226 org-table-previous-field org-table-recalculate
3227 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3228 org-table-toggle-coordinate-overlays
3229 org-table-toggle-formula-debugger org-table-wrap-region
3230 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
3232 (defun org-at-table-p (&optional table-type)
3233 "Return t if the cursor is inside an org-type table.
3234 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3235 (if org-enable-table-editor
3236 (save-excursion
3237 (beginning-of-line 1)
3238 (looking-at (if table-type org-table-any-line-regexp
3239 org-table-line-regexp)))
3240 nil))
3241 (defsubst org-table-p () (org-at-table-p))
3243 (defun org-at-table.el-p ()
3244 "Return t if and only if we are at a table.el table."
3245 (and (org-at-table-p 'any)
3246 (save-excursion
3247 (goto-char (org-table-begin 'any))
3248 (looking-at org-table1-hline-regexp))))
3249 (defun org-table-recognize-table.el ()
3250 "If there is a table.el table nearby, recognize it and move into it."
3251 (if org-table-tab-recognizes-table.el
3252 (if (org-at-table.el-p)
3253 (progn
3254 (beginning-of-line 1)
3255 (if (looking-at org-table-dataline-regexp)
3257 (if (looking-at org-table1-hline-regexp)
3258 (progn
3259 (beginning-of-line 2)
3260 (if (looking-at org-table-any-border-regexp)
3261 (beginning-of-line -1)))))
3262 (if (re-search-forward "|" (org-table-end t) t)
3263 (progn
3264 (require 'table)
3265 (if (table--at-cell-p (point))
3267 (message "recognizing table.el table...")
3268 (table-recognize-table)
3269 (message "recognizing table.el table...done")))
3270 (error "This should not happen..."))
3272 nil)
3273 nil))
3275 (defun org-at-table-hline-p ()
3276 "Return t if the cursor is inside a hline in a table."
3277 (if org-enable-table-editor
3278 (save-excursion
3279 (beginning-of-line 1)
3280 (looking-at org-table-hline-regexp))
3281 nil))
3283 (defvar org-table-clean-did-remove-column nil)
3285 (defun org-table-map-tables (function)
3286 "Apply FUNCTION to the start of all tables in the buffer."
3287 (save-excursion
3288 (save-restriction
3289 (widen)
3290 (goto-char (point-min))
3291 (while (re-search-forward org-table-any-line-regexp nil t)
3292 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
3293 (beginning-of-line 1)
3294 (when (looking-at org-table-line-regexp)
3295 (save-excursion (funcall function))
3296 (or (looking-at org-table-line-regexp)
3297 (forward-char 1)))
3298 (re-search-forward org-table-any-border-regexp nil 1))))
3299 (message "Mapping tables: done"))
3301 ;; Declare and autoload functions from org-exp.el & Co
3303 (declare-function org-default-export-plist "org-exp")
3304 (declare-function org-infile-export-plist "org-exp")
3305 (declare-function org-get-current-options "org-exp")
3306 (eval-and-compile
3307 (org-autoload "org-exp"
3308 '(org-export org-export-visible
3309 org-insert-export-options-template
3310 org-table-clean-before-export))
3311 (org-autoload "org-ascii"
3312 '(org-export-as-ascii org-export-ascii-preprocess
3313 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3314 org-export-region-as-ascii))
3315 (org-autoload "org-latex"
3316 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3317 org-replace-region-by-latex org-export-region-as-latex
3318 org-export-as-latex org-export-as-pdf
3319 org-export-as-pdf-and-open))
3320 (org-autoload "org-html"
3321 '(org-export-as-html-and-open
3322 org-export-as-html-batch org-export-as-html-to-buffer
3323 org-replace-region-by-html org-export-region-as-html
3324 org-export-as-html))
3325 (org-autoload "org-docbook"
3326 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3327 org-replace-region-by-docbook org-export-region-as-docbook
3328 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3329 org-export-as-docbook))
3330 (org-autoload "org-icalendar"
3331 '(org-export-icalendar-this-file
3332 org-export-icalendar-all-agenda-files
3333 org-export-icalendar-combine-agenda-files))
3334 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3335 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3337 ;; Declare and autoload functions from org-agenda.el
3339 (eval-and-compile
3340 (org-autoload "org-agenda"
3341 '(org-agenda org-agenda-list org-search-view
3342 org-todo-list org-tags-view org-agenda-list-stuck-projects
3343 org-diary org-agenda-to-appt
3344 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3346 ;; Autoload org-remember
3348 (eval-and-compile
3349 (org-autoload "org-remember"
3350 '(org-remember-insinuate org-remember-annotation
3351 org-remember-apply-template org-remember org-remember-handler)))
3353 ;; Autoload org-clock.el
3356 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3357 (beg end))
3358 (declare-function org-clock-update-mode-line "org-clock" ())
3359 (declare-function org-resolve-clocks "org-clock"
3360 (&optional also-non-dangling-p prompt last-valid))
3361 (defvar org-clock-start-time)
3362 (defvar org-clock-marker (make-marker)
3363 "Marker recording the last clock-in.")
3364 (defvar org-clock-hd-marker (make-marker)
3365 "Marker recording the last clock-in, but the headline position.")
3366 (defvar org-clock-heading ""
3367 "The heading of the current clock entry.")
3368 (defun org-clock-is-active ()
3369 "Return non-nil if clock is currently running.
3370 The return value is actually the clock marker."
3371 (marker-buffer org-clock-marker))
3373 (eval-and-compile
3374 (org-autoload
3375 "org-clock"
3376 '(org-clock-in org-clock-out org-clock-cancel
3377 org-clock-goto org-clock-sum org-clock-display
3378 org-clock-remove-overlays org-clock-report
3379 org-clocktable-shift org-dblock-write:clocktable
3380 org-get-clocktable org-resolve-clocks)))
3382 (defun org-clock-update-time-maybe ()
3383 "If this is a CLOCK line, update it and return t.
3384 Otherwise, return nil."
3385 (interactive)
3386 (save-excursion
3387 (beginning-of-line 1)
3388 (skip-chars-forward " \t")
3389 (when (looking-at org-clock-string)
3390 (let ((re (concat "[ \t]*" org-clock-string
3391 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3392 "\\([ \t]*=>.*\\)?\\)?"))
3393 ts te h m s neg)
3394 (cond
3395 ((not (looking-at re))
3396 nil)
3397 ((not (match-end 2))
3398 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3399 (> org-clock-marker (point))
3400 (<= org-clock-marker (point-at-eol)))
3401 ;; The clock is running here
3402 (setq org-clock-start-time
3403 (apply 'encode-time
3404 (org-parse-time-string (match-string 1))))
3405 (org-clock-update-mode-line)))
3407 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3408 (end-of-line 1)
3409 (setq ts (match-string 1)
3410 te (match-string 3))
3411 (setq s (- (org-float-time
3412 (apply 'encode-time (org-parse-time-string te)))
3413 (org-float-time
3414 (apply 'encode-time (org-parse-time-string ts))))
3415 neg (< s 0)
3416 s (abs s)
3417 h (floor (/ s 3600))
3418 s (- s (* 3600 h))
3419 m (floor (/ s 60))
3420 s (- s (* 60 s)))
3421 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3422 t))))))
3424 (defun org-check-running-clock ()
3425 "Check if the current buffer contains the running clock.
3426 If yes, offer to stop it and to save the buffer with the changes."
3427 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3428 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3429 (buffer-name))))
3430 (org-clock-out)
3431 (when (y-or-n-p "Save changed buffer?")
3432 (save-buffer))))
3434 (defun org-clocktable-try-shift (dir n)
3435 "Check if this line starts a clock table, if yes, shift the time block."
3436 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3437 (org-clocktable-shift dir n)))
3439 ;; Autoload org-timer.el
3441 (eval-and-compile
3442 (org-autoload
3443 "org-timer"
3444 '(org-timer-start org-timer org-timer-item
3445 org-timer-change-times-in-region
3446 org-timer-set-timer
3447 org-timer-reset-timers
3448 org-timer-show-remaining-time)))
3450 ;; Autoload org-feed.el
3452 (eval-and-compile
3453 (org-autoload
3454 "org-feed"
3455 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3458 ;; Autoload org-indent.el
3460 ;; Define the variable already here, to make sure we have it.
3461 (defvar org-indent-mode nil
3462 "Non-nil if Org-Indent mode is enabled.
3463 Use the command `org-indent-mode' to change this variable.")
3465 (eval-and-compile
3466 (org-autoload
3467 "org-indent"
3468 '(org-indent-mode)))
3470 ;; Autoload org-mobile.el
3472 (eval-and-compile
3473 (org-autoload
3474 "org-mobile"
3475 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3477 ;; Autoload archiving code
3478 ;; The stuff that is needed for cycling and tags has to be defined here.
3480 (defgroup org-archive nil
3481 "Options concerning archiving in Org-mode."
3482 :tag "Org Archive"
3483 :group 'org-structure)
3485 (defcustom org-archive-location "%s_archive::"
3486 "The location where subtrees should be archived.
3488 The value of this variable is a string, consisting of two parts,
3489 separated by a double-colon. The first part is a filename and
3490 the second part is a headline.
3492 When the filename is omitted, archiving happens in the same file.
3493 %s in the filename will be replaced by the current file
3494 name (without the directory part). Archiving to a different file
3495 is useful to keep archived entries from contributing to the
3496 Org-mode Agenda.
3498 The archived entries will be filed as subtrees of the specified
3499 headline. When the headline is omitted, the subtrees are simply
3500 filed away at the end of the file, as top-level entries. Also in
3501 the heading you can use %s to represent the file name, this can be
3502 useful when using the same archive for a number of different files.
3504 Here are a few examples:
3505 \"%s_archive::\"
3506 If the current file is Projects.org, archive in file
3507 Projects.org_archive, as top-level trees. This is the default.
3509 \"::* Archived Tasks\"
3510 Archive in the current file, under the top-level headline
3511 \"* Archived Tasks\".
3513 \"~/org/archive.org::\"
3514 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3516 \"~/org/archive.org::From %s\"
3517 Archive in file ~/org/archive.org (absolute path), under headlines
3518 \"From FILENAME\" where file name is the current file name.
3520 \"basement::** Finished Tasks\"
3521 Archive in file ./basement (relative path), as level 3 trees
3522 below the level 2 heading \"** Finished Tasks\".
3524 You may set this option on a per-file basis by adding to the buffer a
3525 line like
3527 #+ARCHIVE: basement::** Finished Tasks
3529 You may also define it locally for a subtree by setting an ARCHIVE property
3530 in the entry. If such a property is found in an entry, or anywhere up
3531 the hierarchy, it will be used."
3532 :group 'org-archive
3533 :type 'string)
3535 (defcustom org-archive-tag "ARCHIVE"
3536 "The tag that marks a subtree as archived.
3537 An archived subtree does not open during visibility cycling, and does
3538 not contribute to the agenda listings.
3539 After changing this, font-lock must be restarted in the relevant buffers to
3540 get the proper fontification."
3541 :group 'org-archive
3542 :group 'org-keywords
3543 :type 'string)
3545 (defcustom org-agenda-skip-archived-trees t
3546 "Non-nil means the agenda will skip any items located in archived trees.
3547 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3548 variable is no longer recommended, you should leave it at the value t.
3549 Instead, use the key `v' to cycle the archives-mode in the agenda."
3550 :group 'org-archive
3551 :group 'org-agenda-skip
3552 :type 'boolean)
3554 (defcustom org-columns-skip-archived-trees t
3555 "Non-nil means ignore archived trees when creating column view."
3556 :group 'org-archive
3557 :group 'org-properties
3558 :type 'boolean)
3560 (defcustom org-cycle-open-archived-trees nil
3561 "Non-nil means `org-cycle' will open archived trees.
3562 An archived tree is a tree marked with the tag ARCHIVE.
3563 When nil, archived trees will stay folded. You can still open them with
3564 normal outline commands like `show-all', but not with the cycling commands."
3565 :group 'org-archive
3566 :group 'org-cycle
3567 :type 'boolean)
3569 (defcustom org-sparse-tree-open-archived-trees nil
3570 "Non-nil means sparse tree construction shows matches in archived trees.
3571 When nil, matches in these trees are highlighted, but the trees are kept in
3572 collapsed state."
3573 :group 'org-archive
3574 :group 'org-sparse-trees
3575 :type 'boolean)
3577 (defun org-cycle-hide-archived-subtrees (state)
3578 "Re-hide all archived subtrees after a visibility state change."
3579 (when (and (not org-cycle-open-archived-trees)
3580 (not (memq state '(overview folded))))
3581 (save-excursion
3582 (let* ((globalp (memq state '(contents all)))
3583 (beg (if globalp (point-min) (point)))
3584 (end (if globalp (point-max) (org-end-of-subtree t))))
3585 (org-hide-archived-subtrees beg end)
3586 (goto-char beg)
3587 (if (looking-at (concat ".*:" org-archive-tag ":"))
3588 (message "%s" (substitute-command-keys
3589 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3591 (defun org-force-cycle-archived ()
3592 "Cycle subtree even if it is archived."
3593 (interactive)
3594 (setq this-command 'org-cycle)
3595 (let ((org-cycle-open-archived-trees t))
3596 (call-interactively 'org-cycle)))
3598 (defun org-hide-archived-subtrees (beg end)
3599 "Re-hide all archived subtrees after a visibility state change."
3600 (save-excursion
3601 (let* ((re (concat ":" org-archive-tag ":")))
3602 (goto-char beg)
3603 (while (re-search-forward re end t)
3604 (when (org-on-heading-p)
3605 (org-flag-subtree t)
3606 (org-end-of-subtree t))))))
3608 (defun org-flag-subtree (flag)
3609 (save-excursion
3610 (org-back-to-heading t)
3611 (outline-end-of-heading)
3612 (outline-flag-region (point)
3613 (progn (org-end-of-subtree t) (point))
3614 flag)))
3616 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3618 (eval-and-compile
3619 (org-autoload "org-archive"
3620 '(org-add-archive-files org-archive-subtree
3621 org-archive-to-archive-sibling org-toggle-archive-tag
3622 org-archive-subtree-default
3623 org-archive-subtree-default-with-confirmation)))
3625 ;; Autoload Column View Code
3627 (declare-function org-columns-number-to-string "org-colview")
3628 (declare-function org-columns-get-format-and-top-level "org-colview")
3629 (declare-function org-columns-compute "org-colview")
3631 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3632 '(org-columns-number-to-string org-columns-get-format-and-top-level
3633 org-columns-compute org-agenda-columns org-columns-remove-overlays
3634 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3636 ;; Autoload ID code
3638 (declare-function org-id-store-link "org-id")
3639 (declare-function org-id-locations-load "org-id")
3640 (declare-function org-id-locations-save "org-id")
3641 (defvar org-id-track-globally)
3642 (org-autoload "org-id"
3643 '(org-id-get-create org-id-new org-id-copy org-id-get
3644 org-id-get-with-outline-path-completion
3645 org-id-get-with-outline-drilling
3646 org-id-goto org-id-find org-id-store-link))
3648 ;; Autoload Plotting Code
3650 (org-autoload "org-plot"
3651 '(org-plot/gnuplot))
3653 ;;; Variables for pre-computed regular expressions, all buffer local
3655 (defvar org-drawer-regexp nil
3656 "Matches first line of a hidden block.")
3657 (make-variable-buffer-local 'org-drawer-regexp)
3658 (defvar org-todo-regexp nil
3659 "Matches any of the TODO state keywords.")
3660 (make-variable-buffer-local 'org-todo-regexp)
3661 (defvar org-not-done-regexp nil
3662 "Matches any of the TODO state keywords except the last one.")
3663 (make-variable-buffer-local 'org-not-done-regexp)
3664 (defvar org-not-done-heading-regexp nil
3665 "Matches a TODO headline that is not done.")
3666 (make-variable-buffer-local 'org-not-done-regexp)
3667 (defvar org-todo-line-regexp nil
3668 "Matches a headline and puts TODO state into group 2 if present.")
3669 (make-variable-buffer-local 'org-todo-line-regexp)
3670 (defvar org-complex-heading-regexp nil
3671 "Matches a headline and puts everything into groups:
3672 group 1: the stars
3673 group 2: The todo keyword, maybe
3674 group 3: Priority cookie
3675 group 4: True headline
3676 group 5: Tags")
3677 (make-variable-buffer-local 'org-complex-heading-regexp)
3678 (defvar org-complex-heading-regexp-format nil)
3679 (make-variable-buffer-local 'org-complex-heading-regexp-format)
3680 (defvar org-todo-line-tags-regexp nil
3681 "Matches a headline and puts TODO state into group 2 if present.
3682 Also put tags into group 4 if tags are present.")
3683 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3684 (defvar org-nl-done-regexp nil
3685 "Matches newline followed by a headline with the DONE keyword.")
3686 (make-variable-buffer-local 'org-nl-done-regexp)
3687 (defvar org-looking-at-done-regexp nil
3688 "Matches the DONE keyword a point.")
3689 (make-variable-buffer-local 'org-looking-at-done-regexp)
3690 (defvar org-ds-keyword-length 12
3691 "Maximum length of the Deadline and SCHEDULED keywords.")
3692 (make-variable-buffer-local 'org-ds-keyword-length)
3693 (defvar org-deadline-regexp nil
3694 "Matches the DEADLINE keyword.")
3695 (make-variable-buffer-local 'org-deadline-regexp)
3696 (defvar org-deadline-time-regexp nil
3697 "Matches the DEADLINE keyword together with a time stamp.")
3698 (make-variable-buffer-local 'org-deadline-time-regexp)
3699 (defvar org-deadline-line-regexp nil
3700 "Matches the DEADLINE keyword and the rest of the line.")
3701 (make-variable-buffer-local 'org-deadline-line-regexp)
3702 (defvar org-scheduled-regexp nil
3703 "Matches the SCHEDULED keyword.")
3704 (make-variable-buffer-local 'org-scheduled-regexp)
3705 (defvar org-scheduled-time-regexp nil
3706 "Matches the SCHEDULED keyword together with a time stamp.")
3707 (make-variable-buffer-local 'org-scheduled-time-regexp)
3708 (defvar org-closed-time-regexp nil
3709 "Matches the CLOSED keyword together with a time stamp.")
3710 (make-variable-buffer-local 'org-closed-time-regexp)
3712 (defvar org-keyword-time-regexp nil
3713 "Matches any of the 4 keywords, together with the time stamp.")
3714 (make-variable-buffer-local 'org-keyword-time-regexp)
3715 (defvar org-keyword-time-not-clock-regexp nil
3716 "Matches any of the 3 keywords, together with the time stamp.")
3717 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3718 (defvar org-maybe-keyword-time-regexp nil
3719 "Matches a timestamp, possibly preceeded by a keyword.")
3720 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3721 (defvar org-planning-or-clock-line-re nil
3722 "Matches a line with planning or clock info.")
3723 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3724 (defvar org-all-time-keywords nil
3725 "List of time keywords.")
3726 (make-variable-buffer-local 'org-all-time-keywords)
3728 (defconst org-plain-time-of-day-regexp
3729 (concat
3730 "\\(\\<[012]?[0-9]"
3731 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3732 "\\(--?"
3733 "\\(\\<[012]?[0-9]"
3734 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3735 "\\)?")
3736 "Regular expression to match a plain time or time range.
3737 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3738 groups carry important information:
3739 0 the full match
3740 1 the first time, range or not
3741 8 the second time, if it is a range.")
3743 (defconst org-plain-time-extension-regexp
3744 (concat
3745 "\\(\\<[012]?[0-9]"
3746 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3747 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3748 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3749 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3750 groups carry important information:
3751 0 the full match
3752 7 hours of duration
3753 9 minutes of duration")
3755 (defconst org-stamp-time-of-day-regexp
3756 (concat
3757 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3758 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3759 "\\(--?"
3760 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3761 "Regular expression to match a timestamp time or time range.
3762 After a match, the following groups carry important information:
3763 0 the full match
3764 1 date plus weekday, for back referencing to make sure both times are on the same day
3765 2 the first time, range or not
3766 4 the second time, if it is a range.")
3768 (defconst org-startup-options
3769 '(("fold" org-startup-folded t)
3770 ("overview" org-startup-folded t)
3771 ("nofold" org-startup-folded nil)
3772 ("showall" org-startup-folded nil)
3773 ("showeverything" org-startup-folded showeverything)
3774 ("content" org-startup-folded content)
3775 ("indent" org-startup-indented t)
3776 ("noindent" org-startup-indented nil)
3777 ("hidestars" org-hide-leading-stars t)
3778 ("showstars" org-hide-leading-stars nil)
3779 ("odd" org-odd-levels-only t)
3780 ("oddeven" org-odd-levels-only nil)
3781 ("align" org-startup-align-all-tables t)
3782 ("noalign" org-startup-align-all-tables nil)
3783 ("customtime" org-display-custom-times t)
3784 ("logdone" org-log-done time)
3785 ("lognotedone" org-log-done note)
3786 ("nologdone" org-log-done nil)
3787 ("lognoteclock-out" org-log-note-clock-out t)
3788 ("nolognoteclock-out" org-log-note-clock-out nil)
3789 ("logrepeat" org-log-repeat state)
3790 ("lognoterepeat" org-log-repeat note)
3791 ("nologrepeat" org-log-repeat nil)
3792 ("logreschedule" org-log-reschedule time)
3793 ("lognotereschedule" org-log-reschedule note)
3794 ("nologreschedule" org-log-reschedule nil)
3795 ("logredeadline" org-log-redeadline time)
3796 ("lognoteredeadline" org-log-redeadline note)
3797 ("nologredeadline" org-log-redeadline nil)
3798 ("fninline" org-footnote-define-inline t)
3799 ("nofninline" org-footnote-define-inline nil)
3800 ("fnlocal" org-footnote-section nil)
3801 ("fnauto" org-footnote-auto-label t)
3802 ("fnprompt" org-footnote-auto-label nil)
3803 ("fnconfirm" org-footnote-auto-label confirm)
3804 ("fnplain" org-footnote-auto-label plain)
3805 ("fnadjust" org-footnote-auto-adjust t)
3806 ("nofnadjust" org-footnote-auto-adjust nil)
3807 ("constcgs" constants-unit-system cgs)
3808 ("constSI" constants-unit-system SI)
3809 ("noptag" org-tag-persistent-alist nil)
3810 ("hideblocks" org-hide-block-startup t)
3811 ("nohideblocks" org-hide-block-startup nil)
3812 ("beamer" org-startup-with-beamer-mode t))
3813 "Variable associated with STARTUP options for org-mode.
3814 Each element is a list of three items: The startup options as written
3815 in the #+STARTUP line, the corresponding variable, and the value to
3816 set this variable to if the option is found. An optional forth element PUSH
3817 means to push this value onto the list in the variable.")
3819 (defun org-set-regexps-and-options ()
3820 "Precompute regular expressions for current buffer."
3821 (when (org-mode-p)
3822 (org-set-local 'org-todo-kwd-alist nil)
3823 (org-set-local 'org-todo-key-alist nil)
3824 (org-set-local 'org-todo-key-trigger nil)
3825 (org-set-local 'org-todo-keywords-1 nil)
3826 (org-set-local 'org-done-keywords nil)
3827 (org-set-local 'org-todo-heads nil)
3828 (org-set-local 'org-todo-sets nil)
3829 (org-set-local 'org-todo-log-states nil)
3830 (org-set-local 'org-file-properties nil)
3831 (org-set-local 'org-file-tags nil)
3832 (let ((re (org-make-options-regexp
3833 '("CATEGORY" "TODO" "COLUMNS"
3834 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3835 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS")
3836 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3837 (splitre "[ \t]+")
3838 kwds kws0 kwsa key log value cat arch tags const links hw dws
3839 tail sep kws1 prio props ftags drawers beamer-p
3840 ext-setup-or-nil setup-contents (start 0))
3841 (save-excursion
3842 (save-restriction
3843 (widen)
3844 (goto-char (point-min))
3845 (while (or (and ext-setup-or-nil
3846 (string-match re ext-setup-or-nil start)
3847 (setq start (match-end 0)))
3848 (and (setq ext-setup-or-nil nil start 0)
3849 (re-search-forward re nil t)))
3850 (setq key (upcase (match-string 1 ext-setup-or-nil))
3851 value (org-match-string-no-properties 2 ext-setup-or-nil))
3852 (cond
3853 ((equal key "CATEGORY")
3854 (if (string-match "[ \t]+$" value)
3855 (setq value (replace-match "" t t value)))
3856 (setq cat value))
3857 ((member key '("SEQ_TODO" "TODO"))
3858 (push (cons 'sequence (org-split-string value splitre)) kwds))
3859 ((equal key "TYP_TODO")
3860 (push (cons 'type (org-split-string value splitre)) kwds))
3861 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3862 ;; general TODO-like setup
3863 (push (cons (intern (downcase (match-string 1 key)))
3864 (org-split-string value splitre)) kwds))
3865 ((equal key "TAGS")
3866 (setq tags (append tags (if tags '("\\n") nil)
3867 (org-split-string value splitre))))
3868 ((equal key "COLUMNS")
3869 (org-set-local 'org-columns-default-format value))
3870 ((equal key "LINK")
3871 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3872 (push (cons (match-string 1 value)
3873 (org-trim (match-string 2 value)))
3874 links)))
3875 ((equal key "PRIORITIES")
3876 (setq prio (org-split-string value " +")))
3877 ((equal key "PROPERTY")
3878 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3879 (push (cons (match-string 1 value) (match-string 2 value))
3880 props)))
3881 ((equal key "FILETAGS")
3882 (when (string-match "\\S-" value)
3883 (setq ftags
3884 (append
3885 ftags
3886 (apply 'append
3887 (mapcar (lambda (x) (org-split-string x ":"))
3888 (org-split-string value)))))))
3889 ((equal key "DRAWERS")
3890 (setq drawers (org-split-string value splitre)))
3891 ((equal key "CONSTANTS")
3892 (setq const (append const (org-split-string value splitre))))
3893 ((equal key "STARTUP")
3894 (let ((opts (org-split-string value splitre))
3895 l var val)
3896 (while (setq l (pop opts))
3897 (when (setq l (assoc l org-startup-options))
3898 (setq var (nth 1 l) val (nth 2 l))
3899 (if (not (nth 3 l))
3900 (set (make-local-variable var) val)
3901 (if (not (listp (symbol-value var)))
3902 (set (make-local-variable var) nil))
3903 (set (make-local-variable var) (symbol-value var))
3904 (add-to-list var val))))))
3905 ((equal key "ARCHIVE")
3906 (string-match " *$" value)
3907 (setq arch (replace-match "" t t value))
3908 (remove-text-properties 0 (length arch)
3909 '(face t fontified t) arch))
3910 ((equal key "LATEX_CLASS")
3911 (setq beamer-p (equal value "beamer")))
3912 ((equal key "SETUPFILE")
3913 (setq setup-contents (org-file-contents
3914 (expand-file-name
3915 (org-remove-double-quotes value))
3916 'noerror))
3917 (if (not ext-setup-or-nil)
3918 (setq ext-setup-or-nil setup-contents start 0)
3919 (setq ext-setup-or-nil
3920 (concat (substring ext-setup-or-nil 0 start)
3921 "\n" setup-contents "\n"
3922 (substring ext-setup-or-nil start)))))
3923 ))))
3924 (when cat
3925 (org-set-local 'org-category (intern cat))
3926 (push (cons "CATEGORY" cat) props))
3927 (when prio
3928 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3929 (setq prio (mapcar 'string-to-char prio))
3930 (org-set-local 'org-highest-priority (nth 0 prio))
3931 (org-set-local 'org-lowest-priority (nth 1 prio))
3932 (org-set-local 'org-default-priority (nth 2 prio)))
3933 (and props (org-set-local 'org-file-properties (nreverse props)))
3934 (and ftags (org-set-local 'org-file-tags
3935 (mapcar 'org-add-prop-inherited ftags)))
3936 (and drawers (org-set-local 'org-drawers drawers))
3937 (and arch (org-set-local 'org-archive-location arch))
3938 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3939 ;; Process the TODO keywords
3940 (unless kwds
3941 ;; Use the global values as if they had been given locally.
3942 (setq kwds (default-value 'org-todo-keywords))
3943 (if (stringp (car kwds))
3944 (setq kwds (list (cons org-todo-interpretation
3945 (default-value 'org-todo-keywords)))))
3946 (setq kwds (reverse kwds)))
3947 (setq kwds (nreverse kwds))
3948 (let (inter kws kw)
3949 (while (setq kws (pop kwds))
3950 (let ((kws (or
3951 (run-hook-with-args-until-success
3952 'org-todo-setup-filter-hook kws)
3953 kws)))
3954 (setq inter (pop kws) sep (member "|" kws)
3955 kws0 (delete "|" (copy-sequence kws))
3956 kwsa nil
3957 kws1 (mapcar
3958 (lambda (x)
3959 ;; 1 2
3960 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3961 (progn
3962 (setq kw (match-string 1 x)
3963 key (and (match-end 2) (match-string 2 x))
3964 log (org-extract-log-state-settings x))
3965 (push (cons kw (and key (string-to-char key))) kwsa)
3966 (and log (push log org-todo-log-states))
3968 (error "Invalid TODO keyword %s" x)))
3969 kws0)
3970 kwsa (if kwsa (append '((:startgroup))
3971 (nreverse kwsa)
3972 '((:endgroup))))
3973 hw (car kws1)
3974 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3975 tail (list inter hw (car dws) (org-last dws))))
3976 (add-to-list 'org-todo-heads hw 'append)
3977 (push kws1 org-todo-sets)
3978 (setq org-done-keywords (append org-done-keywords dws nil))
3979 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3980 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3981 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3982 (setq org-todo-sets (nreverse org-todo-sets)
3983 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3984 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3985 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3986 ;; Process the constants
3987 (when const
3988 (let (e cst)
3989 (while (setq e (pop const))
3990 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3991 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3992 (setq org-table-formula-constants-local cst)))
3994 ;; Process the tags.
3995 (when tags
3996 (let (e tgs)
3997 (while (setq e (pop tags))
3998 (cond
3999 ((equal e "{") (push '(:startgroup) tgs))
4000 ((equal e "}") (push '(:endgroup) tgs))
4001 ((equal e "\\n") (push '(:newline) tgs))
4002 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4003 (push (cons (match-string 1 e)
4004 (string-to-char (match-string 2 e)))
4005 tgs))
4006 (t (push (list e) tgs))))
4007 (org-set-local 'org-tag-alist nil)
4008 (while (setq e (pop tgs))
4009 (or (and (stringp (car e))
4010 (assoc (car e) org-tag-alist))
4011 (push e org-tag-alist)))))
4013 ;; Compute the regular expressions and other local variables
4014 (if (not org-done-keywords)
4015 (setq org-done-keywords (and org-todo-keywords-1
4016 (list (org-last org-todo-keywords-1)))))
4017 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4018 (length org-scheduled-string)
4019 (length org-clock-string)
4020 (length org-closed-string)))
4021 org-drawer-regexp
4022 (concat "^[ \t]*:\\("
4023 (mapconcat 'regexp-quote org-drawers "\\|")
4024 "\\):[ \t]*$")
4025 org-not-done-keywords
4026 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4027 org-todo-regexp
4028 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4029 "\\|") "\\)\\>")
4030 org-not-done-regexp
4031 (concat "\\<\\("
4032 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4033 "\\)\\>")
4034 org-not-done-heading-regexp
4035 (concat "^\\(\\*+\\)[ \t]+\\("
4036 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4037 "\\)\\>")
4038 org-todo-line-regexp
4039 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4040 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4041 "\\)\\>\\)?[ \t]*\\(.*\\)")
4042 org-complex-heading-regexp
4043 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4044 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4045 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4046 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4047 org-complex-heading-regexp-format
4048 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4049 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4050 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(%s\\)"
4051 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4052 org-nl-done-regexp
4053 (concat "\n\\*+[ \t]+"
4054 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4055 "\\)" "\\>")
4056 org-todo-line-tags-regexp
4057 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4058 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4059 (org-re
4060 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4061 org-looking-at-done-regexp
4062 (concat "^" "\\(?:"
4063 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4064 "\\>")
4065 org-deadline-regexp (concat "\\<" org-deadline-string)
4066 org-deadline-time-regexp
4067 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4068 org-deadline-line-regexp
4069 (concat "\\<\\(" org-deadline-string "\\).*")
4070 org-scheduled-regexp
4071 (concat "\\<" org-scheduled-string)
4072 org-scheduled-time-regexp
4073 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4074 org-closed-time-regexp
4075 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4076 org-keyword-time-regexp
4077 (concat "\\<\\(" org-scheduled-string
4078 "\\|" org-deadline-string
4079 "\\|" org-closed-string
4080 "\\|" org-clock-string "\\)"
4081 " *[[<]\\([^]>]+\\)[]>]")
4082 org-keyword-time-not-clock-regexp
4083 (concat "\\<\\(" org-scheduled-string
4084 "\\|" org-deadline-string
4085 "\\|" org-closed-string
4086 "\\)"
4087 " *[[<]\\([^]>]+\\)[]>]")
4088 org-maybe-keyword-time-regexp
4089 (concat "\\(\\<\\(" org-scheduled-string
4090 "\\|" org-deadline-string
4091 "\\|" org-closed-string
4092 "\\|" org-clock-string "\\)\\)?"
4093 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4094 org-planning-or-clock-line-re
4095 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4096 "\\|" org-deadline-string
4097 "\\|" org-closed-string "\\|" org-clock-string
4098 "\\)\\>\\)")
4099 org-all-time-keywords
4100 (mapcar (lambda (w) (substring w 0 -1))
4101 (list org-scheduled-string org-deadline-string
4102 org-clock-string org-closed-string))
4104 (org-compute-latex-and-specials-regexp)
4105 (org-set-font-lock-defaults))))
4107 (defun org-file-contents (file &optional noerror)
4108 "Return the contents of FILE, as a string."
4109 (if (or (not file)
4110 (not (file-readable-p file)))
4111 (if noerror
4112 (progn
4113 (message "Cannot read file %s" file)
4114 (ding) (sit-for 2)
4116 (error "Cannot read file %s" file))
4117 (with-temp-buffer
4118 (insert-file-contents file)
4119 (buffer-string))))
4121 (defun org-extract-log-state-settings (x)
4122 "Extract the log state setting from a TODO keyword string.
4123 This will extract info from a string like \"WAIT(w@/!)\"."
4124 (let (kw key log1 log2)
4125 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4126 (setq kw (match-string 1 x)
4127 key (and (match-end 2) (match-string 2 x))
4128 log1 (and (match-end 3) (match-string 3 x))
4129 log2 (and (match-end 4) (match-string 4 x)))
4130 (and (or log1 log2)
4131 (list kw
4132 (and log1 (if (equal log1 "!") 'time 'note))
4133 (and log2 (if (equal log2 "!") 'time 'note)))))))
4135 (defun org-remove-keyword-keys (list)
4136 "Remove a pair of parenthesis at the end of each string in LIST."
4137 (mapcar (lambda (x)
4138 (if (string-match "(.*)$" x)
4139 (substring x 0 (match-beginning 0))
4141 list))
4143 (defun org-assign-fast-keys (alist)
4144 "Assign fast keys to a keyword-key alist.
4145 Respect keys that are already there."
4146 (let (new e (alt ?0))
4147 (while (setq e (pop alist))
4148 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4149 (cdr e)) ;; Key already assigned.
4150 (push e new)
4151 (let ((clist (string-to-list (downcase (car e))))
4152 (used (append new alist)))
4153 (when (= (car clist) ?@)
4154 (pop clist))
4155 (while (and clist (rassoc (car clist) used))
4156 (pop clist))
4157 (unless clist
4158 (while (rassoc alt used)
4159 (incf alt)))
4160 (push (cons (car e) (or (car clist) alt)) new))))
4161 (nreverse new)))
4163 ;;; Some variables used in various places
4165 (defvar org-window-configuration nil
4166 "Used in various places to store a window configuration.")
4167 (defvar org-selected-window nil
4168 "Used in various places to store a window configuration.")
4169 (defvar org-finish-function nil
4170 "Function to be called when `C-c C-c' is used.
4171 This is for getting out of special buffers like remember.")
4174 ;; FIXME: Occasionally check by commenting these, to make sure
4175 ;; no other functions uses these, forgetting to let-bind them.
4176 (defvar entry)
4177 (defvar last-state)
4178 (defvar date)
4180 ;; Defined somewhere in this file, but used before definition.
4181 (defvar org-html-entities)
4182 (defvar org-struct-menu)
4183 (defvar org-org-menu)
4184 (defvar org-tbl-menu)
4186 ;;;; Define the Org-mode
4188 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4189 (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."))
4192 ;; We use a before-change function to check if a table might need
4193 ;; an update.
4194 (defvar org-table-may-need-update t
4195 "Indicates that a table might need an update.
4196 This variable is set by `org-before-change-function'.
4197 `org-table-align' sets it back to nil.")
4198 (defun org-before-change-function (beg end)
4199 "Every change indicates that a table might need an update."
4200 (setq org-table-may-need-update t))
4201 (defvar org-mode-map)
4202 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4203 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4204 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4205 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4206 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4207 (defvar org-table-buffer-is-an nil)
4208 (defconst org-outline-regexp "\\*+ ")
4210 ;;;###autoload
4211 (define-derived-mode org-mode outline-mode "Org"
4212 "Outline-based notes management and organizer, alias
4213 \"Carsten's outline-mode for keeping track of everything.\"
4215 Org-mode develops organizational tasks around a NOTES file which
4216 contains information about projects as plain text. Org-mode is
4217 implemented on top of outline-mode, which is ideal to keep the content
4218 of large files well structured. It supports ToDo items, deadlines and
4219 time stamps, which magically appear in the diary listing of the Emacs
4220 calendar. Tables are easily created with a built-in table editor.
4221 Plain text URL-like links connect to websites, emails (VM), Usenet
4222 messages (Gnus), BBDB entries, and any files related to the project.
4223 For printing and sharing of notes, an Org-mode file (or a part of it)
4224 can be exported as a structured ASCII or HTML file.
4226 The following commands are available:
4228 \\{org-mode-map}"
4230 ;; Get rid of Outline menus, they are not needed
4231 ;; Need to do this here because define-derived-mode sets up
4232 ;; the keymap so late. Still, it is a waste to call this each time
4233 ;; we switch another buffer into org-mode.
4234 (if (featurep 'xemacs)
4235 (when (boundp 'outline-mode-menu-heading)
4236 ;; Assume this is Greg's port, it used easymenu
4237 (easy-menu-remove outline-mode-menu-heading)
4238 (easy-menu-remove outline-mode-menu-show)
4239 (easy-menu-remove outline-mode-menu-hide))
4240 (define-key org-mode-map [menu-bar headings] 'undefined)
4241 (define-key org-mode-map [menu-bar hide] 'undefined)
4242 (define-key org-mode-map [menu-bar show] 'undefined))
4244 (org-load-modules-maybe)
4245 (easy-menu-add org-org-menu)
4246 (easy-menu-add org-tbl-menu)
4247 (org-install-agenda-files-menu)
4248 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4249 (org-add-to-invisibility-spec '(org-cwidth))
4250 (org-add-to-invisibility-spec '(org-hide-block . t))
4251 (when (featurep 'xemacs)
4252 (org-set-local 'line-move-ignore-invisible t))
4253 (org-set-local 'outline-regexp org-outline-regexp)
4254 (org-set-local 'outline-level 'org-outline-level)
4255 (when (and org-ellipsis
4256 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4257 (fboundp 'make-glyph-code))
4258 (unless org-display-table
4259 (setq org-display-table (make-display-table)))
4260 (set-display-table-slot
4261 org-display-table 4
4262 (vconcat (mapcar
4263 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4264 org-ellipsis)))
4265 (if (stringp org-ellipsis) org-ellipsis "..."))))
4266 (setq buffer-display-table org-display-table))
4267 (org-set-regexps-and-options)
4268 (when (and org-tag-faces (not org-tags-special-faces-re))
4269 ;; tag faces set outside customize.... force initialization.
4270 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4271 ;; Calc embedded
4272 (org-set-local 'calc-embedded-open-mode "# ")
4273 (modify-syntax-entry ?# "<")
4274 (modify-syntax-entry ?@ "w")
4275 (if org-startup-truncated (setq truncate-lines t))
4276 (org-set-local 'font-lock-unfontify-region-function
4277 'org-unfontify-region)
4278 ;; Activate before-change-function
4279 (org-set-local 'org-table-may-need-update t)
4280 (org-add-hook 'before-change-functions 'org-before-change-function nil
4281 'local)
4282 ;; Check for running clock before killing a buffer
4283 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4284 ;; Paragraphs and auto-filling
4285 (org-set-autofill-regexps)
4286 (setq indent-line-function 'org-indent-line-function)
4287 (org-update-radio-target-regexp)
4288 ;; Make sure dependence stuff works reliably, even for users who set it
4289 ;; too late :-(
4290 (if org-enforce-todo-dependencies
4291 (add-hook 'org-blocker-hook
4292 'org-block-todo-from-children-or-siblings-or-parent)
4293 (remove-hook 'org-blocker-hook
4294 'org-block-todo-from-children-or-siblings-or-parent))
4295 (if org-enforce-todo-checkbox-dependencies
4296 (add-hook 'org-blocker-hook
4297 'org-block-todo-from-checkboxes)
4298 (remove-hook 'org-blocker-hook
4299 'org-block-todo-from-checkboxes))
4301 ;; Comment characters
4302 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4303 (org-set-local 'comment-padding " ")
4305 ;; Align options lines
4306 (org-set-local
4307 'align-mode-rules-list
4308 '((org-in-buffer-settings
4309 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4310 (modes . '(org-mode)))))
4312 ;; Imenu
4313 (org-set-local 'imenu-create-index-function
4314 'org-imenu-get-tree)
4316 ;; Make isearch reveal context
4317 (if (or (featurep 'xemacs)
4318 (not (boundp 'outline-isearch-open-invisible-function)))
4319 ;; Emacs 21 and XEmacs make use of the hook
4320 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4321 ;; Emacs 22 deals with this through a special variable
4322 (org-set-local 'outline-isearch-open-invisible-function
4323 (lambda (&rest ignore) (org-show-context 'isearch))))
4325 ;; Turn on org-beamer-mode?
4326 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4328 ;; If empty file that did not turn on org-mode automatically, make it to.
4329 (if (and org-insert-mode-line-in-empty-file
4330 (interactive-p)
4331 (= (point-min) (point-max)))
4332 (insert "# -*- mode: org -*-\n\n"))
4333 (unless org-inhibit-startup
4334 (when org-startup-align-all-tables
4335 (let ((bmp (buffer-modified-p)))
4336 (org-table-map-tables 'org-table-align)
4337 (set-buffer-modified-p bmp)))
4338 (when org-startup-indented
4339 (require 'org-indent)
4340 (org-indent-mode 1))
4341 (unless org-inhibit-startup-visibility-stuff
4342 (org-set-startup-visibility))))
4344 (when (fboundp 'abbrev-table-put)
4345 (abbrev-table-put org-mode-abbrev-table
4346 :parents (list text-mode-abbrev-table)))
4348 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4350 (defun org-current-time ()
4351 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4352 (if (> (car org-time-stamp-rounding-minutes) 1)
4353 (let ((r (car org-time-stamp-rounding-minutes))
4354 (time (decode-time)))
4355 (apply 'encode-time
4356 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4357 (nthcdr 2 time))))
4358 (current-time)))
4360 ;;;; Font-Lock stuff, including the activators
4362 (defvar org-mouse-map (make-sparse-keymap))
4363 (org-defkey org-mouse-map
4364 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4365 (org-defkey org-mouse-map
4366 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4367 (when org-mouse-1-follows-link
4368 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4369 (when org-tab-follows-link
4370 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4371 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4373 (require 'font-lock)
4375 (defconst org-non-link-chars "]\t\n\r<>")
4376 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4377 "shell" "elisp"))
4378 (defvar org-link-types-re nil
4379 "Matches a link that has a url-like prefix like \"http:\"")
4380 (defvar org-link-re-with-space nil
4381 "Matches a link with spaces, optional angular brackets around it.")
4382 (defvar org-link-re-with-space2 nil
4383 "Matches a link with spaces, optional angular brackets around it.")
4384 (defvar org-link-re-with-space3 nil
4385 "Matches a link with spaces, only for internal part in bracket links.")
4386 (defvar org-angle-link-re nil
4387 "Matches link with angular brackets, spaces are allowed.")
4388 (defvar org-plain-link-re nil
4389 "Matches plain link, without spaces.")
4390 (defvar org-bracket-link-regexp nil
4391 "Matches a link in double brackets.")
4392 (defvar org-bracket-link-analytic-regexp nil
4393 "Regular expression used to analyze links.
4394 Here is what the match groups contain after a match:
4395 1: http:
4396 2: http
4397 3: path
4398 4: [desc]
4399 5: desc")
4400 (defvar org-bracket-link-analytic-regexp++ nil
4401 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4402 (defvar org-any-link-re nil
4403 "Regular expression matching any link.")
4405 (defun org-make-link-regexps ()
4406 "Update the link regular expressions.
4407 This should be called after the variable `org-link-types' has changed."
4408 (setq org-link-types-re
4409 (concat
4410 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
4411 org-link-re-with-space
4412 (concat
4413 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4414 "\\([^" org-non-link-chars " ]"
4415 "[^" org-non-link-chars "]*"
4416 "[^" org-non-link-chars " ]\\)>?")
4417 org-link-re-with-space2
4418 (concat
4419 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4420 "\\([^" org-non-link-chars " ]"
4421 "[^\t\n\r]*"
4422 "[^" org-non-link-chars " ]\\)>?")
4423 org-link-re-with-space3
4424 (concat
4425 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4426 "\\([^" org-non-link-chars " ]"
4427 "[^\t\n\r]*\\)")
4428 org-angle-link-re
4429 (concat
4430 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4431 "\\([^" org-non-link-chars " ]"
4432 "[^" org-non-link-chars "]*"
4433 "\\)>")
4434 org-plain-link-re
4435 (concat
4436 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4437 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
4438 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4439 org-bracket-link-regexp
4440 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4441 org-bracket-link-analytic-regexp
4442 (concat
4443 "\\[\\["
4444 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
4445 "\\([^]]+\\)"
4446 "\\]"
4447 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4448 "\\]")
4449 org-bracket-link-analytic-regexp++
4450 (concat
4451 "\\[\\["
4452 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4453 "\\([^]]+\\)"
4454 "\\]"
4455 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4456 "\\]")
4457 org-any-link-re
4458 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4459 org-angle-link-re "\\)\\|\\("
4460 org-plain-link-re "\\)")))
4462 (org-make-link-regexps)
4464 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4465 "Regular expression for fast time stamp matching.")
4466 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4467 "Regular expression for fast time stamp matching.")
4468 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4469 "Regular expression matching time strings for analysis.
4470 This one does not require the space after the date, so it can be used
4471 on a string that terminates immediately after the date.")
4472 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4473 "Regular expression matching time strings for analysis.")
4474 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4475 "Regular expression matching time stamps, with groups.")
4476 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4477 "Regular expression matching time stamps (also [..]), with groups.")
4478 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4479 "Regular expression matching a time stamp range.")
4480 (defconst org-tr-regexp-both
4481 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4482 "Regular expression matching a time stamp range.")
4483 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4484 org-ts-regexp "\\)?")
4485 "Regular expression matching a time stamp or time stamp range.")
4486 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4487 org-ts-regexp-both "\\)?")
4488 "Regular expression matching a time stamp or time stamp range.
4489 The time stamps may be either active or inactive.")
4491 (defvar org-emph-face nil)
4493 (defun org-do-emphasis-faces (limit)
4494 "Run through the buffer and add overlays to links."
4495 (let (rtn a)
4496 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4497 (if (not (= (char-after (match-beginning 3))
4498 (char-after (match-beginning 4))))
4499 (progn
4500 (setq rtn t)
4501 (setq a (assoc (match-string 3) org-emphasis-alist))
4502 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4503 'face
4504 (nth 1 a))
4505 (and (nth 4 a)
4506 (org-remove-flyspell-overlays-in
4507 (match-beginning 0) (match-end 0)))
4508 (add-text-properties (match-beginning 2) (match-end 2)
4509 '(font-lock-multiline t))
4510 (when org-hide-emphasis-markers
4511 (add-text-properties (match-end 4) (match-beginning 5)
4512 '(invisible org-link))
4513 (add-text-properties (match-beginning 3) (match-end 3)
4514 '(invisible org-link)))))
4515 (backward-char 1))
4516 rtn))
4518 (defun org-emphasize (&optional char)
4519 "Insert or change an emphasis, i.e. a font like bold or italic.
4520 If there is an active region, change that region to a new emphasis.
4521 If there is no region, just insert the marker characters and position
4522 the cursor between them.
4523 CHAR should be either the marker character, or the first character of the
4524 HTML tag associated with that emphasis. If CHAR is a space, the means
4525 to remove the emphasis of the selected region.
4526 If char is not given (for example in an interactive call) it
4527 will be prompted for."
4528 (interactive)
4529 (let ((eal org-emphasis-alist) e det
4530 (erc org-emphasis-regexp-components)
4531 (prompt "")
4532 (string "") beg end move tag c s)
4533 (if (org-region-active-p)
4534 (setq beg (region-beginning) end (region-end)
4535 string (buffer-substring beg end))
4536 (setq move t))
4538 (while (setq e (pop eal))
4539 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4540 c (aref tag 0))
4541 (push (cons c (string-to-char (car e))) det)
4542 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4543 (substring tag 1)))))
4544 (setq det (nreverse det))
4545 (unless char
4546 (message "%s" (concat "Emphasis marker or tag:" prompt))
4547 (setq char (read-char-exclusive)))
4548 (setq char (or (cdr (assoc char det)) char))
4549 (if (equal char ?\ )
4550 (setq s "" move nil)
4551 (unless (assoc (char-to-string char) org-emphasis-alist)
4552 (error "No such emphasis marker: \"%c\"" char))
4553 (setq s (char-to-string char)))
4554 (while (and (> (length string) 1)
4555 (equal (substring string 0 1) (substring string -1))
4556 (assoc (substring string 0 1) org-emphasis-alist))
4557 (setq string (substring string 1 -1)))
4558 (setq string (concat s string s))
4559 (if beg (delete-region beg end))
4560 (unless (or (bolp)
4561 (string-match (concat "[" (nth 0 erc) "\n]")
4562 (char-to-string (char-before (point)))))
4563 (insert " "))
4564 (unless (or (eobp)
4565 (string-match (concat "[" (nth 1 erc) "\n]")
4566 (char-to-string (char-after (point)))))
4567 (insert " ") (backward-char 1))
4568 (insert string)
4569 (and move (backward-char 1))))
4571 (defconst org-nonsticky-props
4572 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4574 (defsubst org-rear-nonsticky-at (pos)
4575 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4577 (defun org-activate-plain-links (limit)
4578 "Run through the buffer and add overlays to links."
4579 (catch 'exit
4580 (let (f)
4581 (if (re-search-forward org-plain-link-re limit t)
4582 (progn
4583 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4584 (setq f (get-text-property (match-beginning 0) 'face))
4585 (if (or (eq f 'org-tag)
4586 (and (listp f) (memq 'org-tag f)))
4588 (add-text-properties (match-beginning 0) (match-end 0)
4589 (list 'mouse-face 'highlight
4590 'face 'org-link
4591 'keymap org-mouse-map))
4592 (org-rear-nonsticky-at (match-end 0)))
4593 t)))))
4595 (defun org-activate-code (limit)
4596 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4597 (progn
4598 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4599 (remove-text-properties (match-beginning 0) (match-end 0)
4600 '(display t invisible t intangible t))
4601 t)))
4603 (defun org-fontify-meta-lines-and-blocks (limit)
4604 "Fontify #+ lines and blocks, in the correct ways."
4605 (let ((case-fold-search t))
4606 (if (re-search-forward
4607 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4608 limit t)
4609 (let ((beg (match-beginning 0))
4610 (beg1 (line-beginning-position 2))
4611 (dc1 (downcase (match-string 2)))
4612 (dc3 (downcase (match-string 3)))
4613 end end1 quoting block-type)
4614 (cond
4615 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4616 ;; a single line of backend-specific content
4617 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4618 (remove-text-properties (match-beginning 0) (match-end 0)
4619 '(display t invisible t intangible t))
4620 (add-text-properties (match-beginning 1) (match-end 3)
4621 '(font-lock-fontified t face org-meta-line))
4622 (add-text-properties (match-beginning 6) (match-end 6)
4623 '(font-lock-fontified t face org-block))
4625 ((and (match-end 4) (equal dc3 "begin"))
4626 ;; Truely a block
4627 (setq block-type (downcase (match-string 5))
4628 quoting (member block-type org-protecting-blocks))
4629 (when (re-search-forward
4630 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4631 nil t) ;; on purpose, we look further than LIMIT
4632 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4633 (when quoting
4634 (remove-text-properties beg end
4635 '(display t invisible t intangible t)))
4636 (add-text-properties
4637 beg end
4638 '(font-lock-fontified t font-lock-multiline t))
4639 (add-text-properties beg beg1 '(face org-meta-line))
4640 (add-text-properties end1 end '(face org-meta-line))
4641 (cond
4642 (quoting
4643 (add-text-properties beg1 end1 '(face org-block)))
4644 ((not org-fontify-quote-and-verse-blocks))
4645 ((string= block-type "quote")
4646 (add-text-properties beg1 end1 '(face org-quote)))
4647 ((string= block-type "verse")
4648 (add-text-properties beg1 end1 '(face org-verse))))
4650 ((not (member (char-after beg) '(?\ ?\t)))
4651 ;; just any other in-buffer setting, but not indented
4652 (add-text-properties
4653 beg (match-end 0)
4654 '(font-lock-fontified t face org-meta-line))
4656 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
4657 "orgtbl:" "tblfm:" "tblname:"))
4658 (and (match-end 4) (equal dc3 "attr")))
4659 (add-text-properties
4660 beg (match-end 0)
4661 '(font-lock-fontified t face org-meta-line))
4663 ((member dc3 '(" " ""))
4664 (add-text-properties
4665 beg (match-end 0)
4666 '(font-lock-fontified t face font-lock-comment-face)))
4667 (t nil))))))
4669 (defun org-activate-angle-links (limit)
4670 "Run through the buffer and add overlays to links."
4671 (if (re-search-forward org-angle-link-re limit t)
4672 (progn
4673 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4674 (add-text-properties (match-beginning 0) (match-end 0)
4675 (list 'mouse-face 'highlight
4676 'keymap org-mouse-map))
4677 (org-rear-nonsticky-at (match-end 0))
4678 t)))
4680 (defun org-activate-footnote-links (limit)
4681 "Run through the buffer and add overlays to links."
4682 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4683 limit t)
4684 (progn
4685 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4686 (add-text-properties (match-beginning 2) (match-end 2)
4687 (list 'mouse-face 'highlight
4688 'keymap org-mouse-map
4689 'help-echo
4690 (if (= (point-at-bol) (match-beginning 2))
4691 "Footnote definition"
4692 "Footnote reference")
4694 (org-rear-nonsticky-at (match-end 2))
4695 t)))
4697 (defun org-activate-bracket-links (limit)
4698 "Run through the buffer and add overlays to bracketed links."
4699 (if (re-search-forward org-bracket-link-regexp limit t)
4700 (let* ((help (concat "LINK: "
4701 (org-match-string-no-properties 1)))
4702 ;; FIXME: above we should remove the escapes.
4703 ;; but that requires another match, protecting match data,
4704 ;; a lot of overhead for font-lock.
4705 (ip (org-maybe-intangible
4706 (list 'invisible 'org-link
4707 'keymap org-mouse-map 'mouse-face 'highlight
4708 'font-lock-multiline t 'help-echo help)))
4709 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4710 'font-lock-multiline t 'help-echo help)))
4711 ;; We need to remove the invisible property here. Table narrowing
4712 ;; may have made some of this invisible.
4713 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4714 (remove-text-properties (match-beginning 0) (match-end 0)
4715 '(invisible nil))
4716 (if (match-end 3)
4717 (progn
4718 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4719 (org-rear-nonsticky-at (match-beginning 3))
4720 (add-text-properties (match-beginning 3) (match-end 3) vp)
4721 (org-rear-nonsticky-at (match-end 3))
4722 (add-text-properties (match-end 3) (match-end 0) ip)
4723 (org-rear-nonsticky-at (match-end 0)))
4724 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4725 (org-rear-nonsticky-at (match-beginning 1))
4726 (add-text-properties (match-beginning 1) (match-end 1) vp)
4727 (org-rear-nonsticky-at (match-end 1))
4728 (add-text-properties (match-end 1) (match-end 0) ip)
4729 (org-rear-nonsticky-at (match-end 0)))
4730 t)))
4732 (defun org-activate-dates (limit)
4733 "Run through the buffer and add overlays to dates."
4734 (if (re-search-forward org-tsr-regexp-both limit t)
4735 (progn
4736 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4737 (add-text-properties (match-beginning 0) (match-end 0)
4738 (list 'mouse-face 'highlight
4739 'keymap org-mouse-map))
4740 (org-rear-nonsticky-at (match-end 0))
4741 (when org-display-custom-times
4742 (if (match-end 3)
4743 (org-display-custom-time (match-beginning 3) (match-end 3)))
4744 (org-display-custom-time (match-beginning 1) (match-end 1)))
4745 t)))
4747 (defvar org-target-link-regexp nil
4748 "Regular expression matching radio targets in plain text.")
4749 (make-variable-buffer-local 'org-target-link-regexp)
4750 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4751 "Regular expression matching a link target.")
4752 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4753 "Regular expression matching a radio target.")
4754 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4755 "Regular expression matching any target.")
4757 (defun org-activate-target-links (limit)
4758 "Run through the buffer and add overlays to target matches."
4759 (when org-target-link-regexp
4760 (let ((case-fold-search t))
4761 (if (re-search-forward org-target-link-regexp limit t)
4762 (progn
4763 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4764 (add-text-properties (match-beginning 0) (match-end 0)
4765 (list 'mouse-face 'highlight
4766 'keymap org-mouse-map
4767 'help-echo "Radio target link"
4768 'org-linked-text t))
4769 (org-rear-nonsticky-at (match-end 0))
4770 t)))))
4772 (defun org-update-radio-target-regexp ()
4773 "Find all radio targets in this file and update the regular expression."
4774 (interactive)
4775 (when (memq 'radio org-activate-links)
4776 (setq org-target-link-regexp
4777 (org-make-target-link-regexp (org-all-targets 'radio)))
4778 (org-restart-font-lock)))
4780 (defun org-hide-wide-columns (limit)
4781 (let (s e)
4782 (setq s (text-property-any (point) (or limit (point-max))
4783 'org-cwidth t))
4784 (when s
4785 (setq e (next-single-property-change s 'org-cwidth))
4786 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4787 (goto-char e)
4788 t)))
4790 (defvar org-latex-and-specials-regexp nil
4791 "Regular expression for highlighting export special stuff.")
4792 (defvar org-match-substring-regexp)
4793 (defvar org-match-substring-with-braces-regexp)
4795 ;; This should be with the exporter code, but we also use if for font-locking
4796 (defconst org-export-html-special-string-regexps
4797 '(("\\\\-" . "&shy;")
4798 ("---\\([^-]\\)" . "&mdash;\\1")
4799 ("--\\([^-]\\)" . "&ndash;\\1")
4800 ("\\.\\.\\." . "&hellip;"))
4801 "Regular expressions for special string conversion.")
4804 (defun org-compute-latex-and-specials-regexp ()
4805 "Compute regular expression for stuff treated specially by exporters."
4806 (if (not org-highlight-latex-fragments-and-specials)
4807 (org-set-local 'org-latex-and-specials-regexp nil)
4808 (require 'org-exp)
4809 (let*
4810 ((matchers (plist-get org-format-latex-options :matchers))
4811 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4812 org-latex-regexps)))
4813 (org-export-allow-BIND nil)
4814 (options (org-combine-plists (org-default-export-plist)
4815 (org-infile-export-plist)))
4816 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4817 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4818 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4819 (org-export-html-expand (plist-get options :expand-quoted-html))
4820 (org-export-with-special-strings (plist-get options :special-strings))
4821 (re-sub
4822 (cond
4823 ((equal org-export-with-sub-superscripts '{})
4824 (list org-match-substring-with-braces-regexp))
4825 (org-export-with-sub-superscripts
4826 (list org-match-substring-regexp))
4827 (t nil)))
4828 (re-latex
4829 (if org-export-with-LaTeX-fragments
4830 (mapcar (lambda (x) (nth 1 x)) latexs)))
4831 (re-macros
4832 (if org-export-with-TeX-macros
4833 (list (concat "\\\\"
4834 (regexp-opt
4835 (append (mapcar 'car org-html-entities)
4836 (if (boundp 'org-latex-entities)
4837 (mapcar (lambda (x)
4838 (or (car-safe x) x))
4839 org-latex-entities)
4840 nil))
4841 'words))) ; FIXME
4843 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4844 (re-special (if org-export-with-special-strings
4845 (mapcar (lambda (x) (car x))
4846 org-export-html-special-string-regexps)))
4847 (re-rest
4848 (delq nil
4849 (list
4850 (if org-export-html-expand "@<[^>\n]+>")
4851 ))))
4852 (org-set-local
4853 'org-latex-and-specials-regexp
4854 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4855 re-rest) "\\|")))))
4857 (defun org-do-latex-and-special-faces (limit)
4858 "Run through the buffer and add overlays to links."
4859 (when org-latex-and-specials-regexp
4860 (let (rtn d)
4861 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4862 limit t))
4863 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4864 'face))
4865 '(org-code org-verbatim underline)))
4866 (progn
4867 (setq rtn t
4868 d (cond ((member (char-after (1+ (match-beginning 0)))
4869 '(?_ ?^)) 1)
4870 (t 0)))
4871 (font-lock-prepend-text-property
4872 (+ d (match-beginning 0)) (match-end 0)
4873 'face 'org-latex-and-export-specials)
4874 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4875 '(font-lock-multiline t)))))
4876 rtn)))
4878 (defun org-restart-font-lock ()
4879 "Restart font-lock-mode, to force refontification."
4880 (when (and (boundp 'font-lock-mode) font-lock-mode)
4881 (font-lock-mode -1)
4882 (font-lock-mode 1)))
4884 (defun org-all-targets (&optional radio)
4885 "Return a list of all targets in this file.
4886 With optional argument RADIO, only find radio targets."
4887 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4888 rtn)
4889 (save-excursion
4890 (goto-char (point-min))
4891 (while (re-search-forward re nil t)
4892 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4893 rtn)))
4895 (defun org-make-target-link-regexp (targets)
4896 "Make regular expression matching all strings in TARGETS.
4897 The regular expression finds the targets also if there is a line break
4898 between words."
4899 (and targets
4900 (concat
4901 "\\<\\("
4902 (mapconcat
4903 (lambda (x)
4904 (while (string-match " +" x)
4905 (setq x (replace-match "\\s-+" t t x)))
4907 targets
4908 "\\|")
4909 "\\)\\>")))
4911 (defun org-activate-tags (limit)
4912 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4913 (progn
4914 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
4915 (add-text-properties (match-beginning 1) (match-end 1)
4916 (list 'mouse-face 'highlight
4917 'keymap org-mouse-map))
4918 (org-rear-nonsticky-at (match-end 1))
4919 t)))
4921 (defun org-outline-level ()
4922 "Compute the outline level of the heading at point.
4923 This function assumes that the cursor is at the beginning of a line matched
4924 by outline-regexp. Otherwise it returns garbage.
4925 If this is called at a normal headline, the level is the number of stars.
4926 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
4927 For plain list items, if they are matched by `outline-regexp', this returns
4928 1000 plus the line indentation."
4929 (save-excursion
4930 (looking-at outline-regexp)
4931 (if (match-beginning 1)
4932 (+ (org-get-string-indentation (match-string 1)) 1000)
4933 (1- (- (match-end 0) (match-beginning 0))))))
4935 (defvar org-font-lock-keywords nil)
4937 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4938 "Regular expression matching a property line.")
4940 (defvar org-font-lock-hook nil
4941 "Functions to be called for special font lock stuff.")
4943 (defun org-font-lock-hook (limit)
4944 (run-hook-with-args 'org-font-lock-hook limit))
4946 (defun org-set-font-lock-defaults ()
4947 (let* ((em org-fontify-emphasized-text)
4948 (lk org-activate-links)
4949 (org-font-lock-extra-keywords
4950 (list
4951 ;; Call the hook
4952 '(org-font-lock-hook)
4953 ;; Headlines
4954 `(,(if org-fontify-whole-heading-line
4955 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
4956 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
4957 (1 (org-get-level-face 1))
4958 (2 (org-get-level-face 2))
4959 (3 (org-get-level-face 3)))
4960 ;; Table lines
4961 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4962 (1 'org-table t))
4963 ;; Table internals
4964 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4965 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4966 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4967 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
4968 ;; Drawers
4969 (list org-drawer-regexp '(0 'org-special-keyword t))
4970 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4971 ;; Properties
4972 (list org-property-re
4973 '(1 'org-special-keyword t)
4974 '(3 'org-property-value t))
4975 ;; Links
4976 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4977 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4978 (if (memq 'plain lk) '(org-activate-plain-links))
4979 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4980 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4981 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4982 (if (memq 'footnote lk) '(org-activate-footnote-links
4983 (2 'org-footnote t)))
4984 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4985 '(org-hide-wide-columns (0 nil append))
4986 ;; TODO lines
4987 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4988 '(1 (org-get-todo-face 1) t))
4989 ;; DONE
4990 (if org-fontify-done-headline
4991 (list (concat "^[*]+ +\\<\\("
4992 (mapconcat 'regexp-quote org-done-keywords "\\|")
4993 "\\)\\(.*\\)")
4994 '(2 'org-headline-done t))
4995 nil)
4996 ;; Priorities
4997 '(org-font-lock-add-priority-faces)
4998 ;; Tags
4999 '(org-font-lock-add-tag-faces)
5000 ;; Special keywords
5001 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5002 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5003 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5004 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5005 ;; Emphasis
5006 (if em
5007 (if (featurep 'xemacs)
5008 '(org-do-emphasis-faces (0 nil append))
5009 '(org-do-emphasis-faces)))
5010 ;; Checkboxes
5011 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5012 2 'org-checkbox prepend)
5013 (if org-provide-checkbox-statistics
5014 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5015 (0 (org-get-checkbox-statistics-face) t)))
5016 ;; Description list items
5017 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
5018 2 'bold prepend)
5019 ;; ARCHIVEd headings
5020 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5021 '(1 'org-archived prepend))
5022 ;; Specials
5023 '(org-do-latex-and-special-faces)
5024 ;; Code
5025 '(org-activate-code (1 'org-code t))
5026 ;; COMMENT
5027 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5028 "\\|" org-quote-string "\\)\\>")
5029 '(1 'org-special-keyword t))
5030 '("^#.*" (0 'font-lock-comment-face t))
5031 ;; Blocks and meta lines
5032 '(org-fontify-meta-lines-and-blocks)
5034 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5035 ;; Now set the full font-lock-keywords
5036 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5037 (org-set-local 'font-lock-defaults
5038 '(org-font-lock-keywords t nil nil backward-paragraph))
5039 (kill-local-variable 'font-lock-keywords) nil))
5041 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5042 "Fontify string S like in Org-mode"
5043 (with-temp-buffer
5044 (insert s)
5045 (let ((org-odd-levels-only odd-levels))
5046 (org-mode)
5047 (font-lock-fontify-buffer)
5048 (buffer-string))))
5050 (defvar org-m nil)
5051 (defvar org-l nil)
5052 (defvar org-f nil)
5053 (defun org-get-level-face (n)
5054 "Get the right face for match N in font-lock matching of headlines."
5055 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5056 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5057 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5058 (cond
5059 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5060 ((eq n 2) org-f)
5061 (t (if org-level-color-stars-only nil org-f))))
5063 (defun org-get-todo-face (kwd)
5064 "Get the right face for a TODO keyword KWD.
5065 If KWD is a number, get the corresponding match group."
5066 (if (numberp kwd) (setq kwd (match-string kwd)))
5067 (or (org-face-from-face-or-color
5068 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5069 (and (member kwd org-done-keywords) 'org-done)
5070 'org-todo))
5072 (defun org-face-from-face-or-color (context inherit face-or-color)
5073 "Create a face list that inherits INHERIT, but sets the foreground color.
5074 When FACE-OR-COLOR is not a string, just return it."
5075 (if (stringp face-or-color)
5076 (list :inherit inherit
5077 (cdr (assoc context org-faces-easy-properties))
5078 face-or-color)
5079 face-or-color))
5081 (defun org-font-lock-add-tag-faces (limit)
5082 "Add the special tag faces."
5083 (when (and org-tag-faces org-tags-special-faces-re)
5084 (while (re-search-forward org-tags-special-faces-re limit t)
5085 (add-text-properties (match-beginning 1) (match-end 1)
5086 (list 'face (org-get-tag-face 1)
5087 'font-lock-fontified t))
5088 (backward-char 1))))
5090 (defun org-font-lock-add-priority-faces (limit)
5091 "Add the special priority faces."
5092 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5093 (add-text-properties
5094 (match-beginning 0) (match-end 0)
5095 (list 'face (or (org-face-from-face-or-color
5096 'priority 'org-special-keyword
5097 (cdr (assoc (char-after (match-beginning 1))
5098 org-priority-faces)))
5099 'org-special-keyword)
5100 'font-lock-fontified t))))
5102 (defun org-get-tag-face (kwd)
5103 "Get the right face for a TODO keyword KWD.
5104 If KWD is a number, get the corresponding match group."
5105 (if (numberp kwd) (setq kwd (match-string kwd)))
5106 (or (org-face-from-face-or-color
5107 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5108 'org-tag))
5110 (defun org-unfontify-region (beg end &optional maybe_loudly)
5111 "Remove fontification and activation overlays from links."
5112 (font-lock-default-unfontify-region beg end)
5113 (let* ((buffer-undo-list t)
5114 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5115 (inhibit-modification-hooks t)
5116 deactivate-mark buffer-file-name buffer-file-truename)
5117 (remove-text-properties
5118 beg end
5119 (if org-indent-mode
5120 ;; also remove line-prefix and wrap-prefix properties
5121 '(mouse-face t keymap t org-linked-text t
5122 invisible t intangible t
5123 line-prefix t wrap-prefix t
5124 org-no-flyspell t)
5125 '(mouse-face t keymap t org-linked-text t
5126 invisible t intangible t
5127 org-no-flyspell t)))))
5129 ;;;; Visibility cycling, including org-goto and indirect buffer
5131 ;;; Cycling
5133 (defvar org-cycle-global-status nil)
5134 (make-variable-buffer-local 'org-cycle-global-status)
5135 (defvar org-cycle-subtree-status nil)
5136 (make-variable-buffer-local 'org-cycle-subtree-status)
5138 ;;;###autoload
5140 (defvar org-inlinetask-min-level)
5142 (defun org-cycle (&optional arg)
5143 "TAB-action and visibility cycling for Org-mode.
5145 This is the command invoked in Org-mode by the TAB key. Its main purpose
5146 is outline visibility cycling, but it also invokes other actions
5147 in special contexts.
5149 - When this function is called with a prefix argument, rotate the entire
5150 buffer through 3 states (global cycling)
5151 1. OVERVIEW: Show only top-level headlines.
5152 2. CONTENTS: Show all headlines of all levels, but no body text.
5153 3. SHOW ALL: Show everything.
5154 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5155 determined by the variable `org-startup-folded', and by any VISIBILITY
5156 properties in the buffer.
5157 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5158 including any drawers.
5160 - When inside a table, re-align the table and move to the next field.
5162 - When point is at the beginning of a headline, rotate the subtree started
5163 by this line through 3 different states (local cycling)
5164 1. FOLDED: Only the main headline is shown.
5165 2. CHILDREN: The main headline and the direct children are shown.
5166 From this state, you can move to one of the children
5167 and zoom in further.
5168 3. SUBTREE: Show the entire subtree, including body text.
5169 If there is no subtree, switch directly from CHILDREN to FOLDED.
5171 - When point is at the beginning of an empty headline and the variable
5172 `org-cycle-level-after-item/entry-creation' is set, cycle the level
5173 of the headline by demoting and promoting it to likely levels. This
5174 speeds up creation document structure by presing TAB once or several
5175 times right after creating a new headline.
5177 - When there is a numeric prefix, go up to a heading with level ARG, do
5178 a `show-subtree' and return to the previous cursor position. If ARG
5179 is negative, go up that many levels.
5181 - When point is not at the beginning of a headline, execute the global
5182 binding for TAB, which is re-indenting the line. See the option
5183 `org-cycle-emulate-tab' for details.
5185 - Special case: if point is at the beginning of the buffer and there is
5186 no headline in line 1, this function will act as if called with prefix arg.
5187 But only if also the variable `org-cycle-global-at-bob' is t."
5188 (interactive "P")
5189 (org-load-modules-maybe)
5190 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5191 (and org-cycle-level-after-item/entry-creation
5192 (or (org-cycle-level)
5193 (org-cycle-item-indentation))))
5194 (let* ((limit-level
5195 (or org-cycle-max-level
5196 (and (boundp 'org-inlinetask-min-level)
5197 org-inlinetask-min-level
5198 (1- org-inlinetask-min-level))))
5199 (nstars (and limit-level
5200 (if org-odd-levels-only
5201 (and limit-level (1- (* limit-level 2)))
5202 limit-level)))
5203 (outline-regexp
5204 (cond
5205 ((not (org-mode-p)) outline-regexp)
5206 ((or (eq org-cycle-include-plain-lists 'integrate)
5207 (and org-cycle-include-plain-lists (org-at-item-p)))
5208 (concat "\\(?:\\*"
5209 (if nstars (format "\\{1,%d\\}" nstars) "+")
5210 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5211 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
5212 (bob-special (and org-cycle-global-at-bob (bobp)
5213 (not (looking-at outline-regexp))))
5214 (org-cycle-hook
5215 (if bob-special
5216 (delq 'org-optimize-window-after-visibility-change
5217 (copy-sequence org-cycle-hook))
5218 org-cycle-hook))
5219 (pos (point)))
5221 (if (or bob-special (equal arg '(4)))
5222 ;; special case: use global cycling
5223 (setq arg t))
5225 (cond
5227 ((equal arg '(16))
5228 (org-set-startup-visibility)
5229 (message "Startup visibility, plus VISIBILITY properties"))
5231 ((equal arg '(64))
5232 (show-all)
5233 (message "Entire buffer visible, including drawers"))
5235 ((org-at-table-p 'any)
5236 ;; Enter the table or move to the next field in the table
5237 (if (org-at-table.el-p)
5238 (message "Use C-c ' to edit table.el tables")
5239 (if arg (org-table-edit-field t)
5240 (org-table-justify-field-maybe)
5241 (call-interactively 'org-table-next-field))))
5243 ((run-hook-with-args-until-success
5244 'org-tab-after-check-for-table-hook))
5246 ((eq arg t) ;; Global cycling
5247 (org-cycle-internal-global))
5249 ((and org-drawers org-drawer-regexp
5250 (save-excursion
5251 (beginning-of-line 1)
5252 (looking-at org-drawer-regexp)))
5253 ;; Toggle block visibility
5254 (org-flag-drawer
5255 (not (get-char-property (match-end 0) 'invisible))))
5257 ((integerp arg)
5258 ;; Show-subtree, ARG levels up from here.
5259 (save-excursion
5260 (org-back-to-heading)
5261 (outline-up-heading (if (< arg 0) (- arg)
5262 (- (funcall outline-level) arg)))
5263 (org-show-subtree)))
5265 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5266 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5268 (org-cycle-internal-local))
5270 ;; TAB emulation and template completion
5271 (buffer-read-only (org-back-to-heading))
5273 ((run-hook-with-args-until-success
5274 'org-tab-after-check-for-cycling-hook))
5276 ((org-try-structure-completion))
5278 ((org-try-cdlatex-tab))
5280 ((run-hook-with-args-until-success
5281 'org-tab-before-tab-emulation-hook))
5283 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5284 (or (not (bolp))
5285 (not (looking-at outline-regexp))))
5286 (call-interactively (global-key-binding "\t")))
5288 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5289 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5290 (or (and (eq org-cycle-emulate-tab 'white)
5291 (= (match-end 0) (point-at-eol)))
5292 (and (eq org-cycle-emulate-tab 'whitestart)
5293 (>= (match-end 0) pos))))
5295 (eq org-cycle-emulate-tab t))
5296 (call-interactively (global-key-binding "\t")))
5298 (t (save-excursion
5299 (org-back-to-heading)
5300 (org-cycle)))))))
5302 (defun org-cycle-internal-global ()
5303 "Do the global cycling action."
5304 (cond
5305 ((and (eq last-command this-command)
5306 (eq org-cycle-global-status 'overview))
5307 ;; We just created the overview - now do table of contents
5308 ;; This can be slow in very large buffers, so indicate action
5309 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5310 (message "CONTENTS...")
5311 (org-content)
5312 (message "CONTENTS...done")
5313 (setq org-cycle-global-status 'contents)
5314 (run-hook-with-args 'org-cycle-hook 'contents))
5316 ((and (eq last-command this-command)
5317 (eq org-cycle-global-status 'contents))
5318 ;; We just showed the table of contents - now show everything
5319 (run-hook-with-args 'org-pre-cycle-hook 'all)
5320 (show-all)
5321 (message "SHOW ALL")
5322 (setq org-cycle-global-status 'all)
5323 (run-hook-with-args 'org-cycle-hook 'all))
5326 ;; Default action: go to overview
5327 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5328 (org-overview)
5329 (message "OVERVIEW")
5330 (setq org-cycle-global-status 'overview)
5331 (run-hook-with-args 'org-cycle-hook 'overview))))
5333 (defun org-cycle-internal-local ()
5334 "Do the local cycling action."
5335 (org-back-to-heading)
5336 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5337 ;; First, some boundaries
5338 (save-excursion
5339 (org-back-to-heading)
5340 (setq level (funcall outline-level))
5341 (save-excursion
5342 (beginning-of-line 2)
5343 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5344 ; XEmacs does not have `next-single-char-property-change'
5345 ; I'm not sure about Emacs 21.
5346 (while (and (not (eobp)) ;; this is like `next-line'
5347 (get-char-property (1- (point)) 'invisible))
5348 (beginning-of-line 2))
5349 (while (and (not (eobp)) ;; this is like `next-line'
5350 (get-char-property (1- (point)) 'invisible))
5351 (goto-char (next-single-char-property-change (point) 'invisible))
5352 ;;;??? (or (bolp) (beginning-of-line 2))))
5353 (and (eolp) (beginning-of-line 2))))
5354 (setq eol (point)))
5355 (outline-end-of-heading) (setq eoh (point))
5356 (save-excursion
5357 (outline-next-heading)
5358 (setq has-children (and (org-at-heading-p t)
5359 (> (funcall outline-level) level))))
5360 (org-end-of-subtree t)
5361 (unless (eobp)
5362 (skip-chars-forward " \t\n")
5363 (beginning-of-line 1) ; in case this is an item
5365 (setq eos (if (eobp) (point) (1- (point)))))
5366 ;; Find out what to do next and set `this-command'
5367 (cond
5368 ((= eos eoh)
5369 ;; Nothing is hidden behind this heading
5370 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5371 (message "EMPTY ENTRY")
5372 (setq org-cycle-subtree-status nil)
5373 (save-excursion
5374 (goto-char eos)
5375 (outline-next-heading)
5376 (if (org-invisible-p) (org-flag-heading nil))))
5377 ((and (or (>= eol eos)
5378 (not (string-match "\\S-" (buffer-substring eol eos))))
5379 (or has-children
5380 (not (setq children-skipped
5381 org-cycle-skip-children-state-if-no-children))))
5382 ;; Entire subtree is hidden in one line: children view
5383 (run-hook-with-args 'org-pre-cycle-hook 'children)
5384 (org-show-entry)
5385 (show-children)
5386 (message "CHILDREN")
5387 (save-excursion
5388 (goto-char eos)
5389 (outline-next-heading)
5390 (if (org-invisible-p) (org-flag-heading nil)))
5391 (setq org-cycle-subtree-status 'children)
5392 (run-hook-with-args 'org-cycle-hook 'children))
5393 ((or children-skipped
5394 (and (eq last-command this-command)
5395 (eq org-cycle-subtree-status 'children)))
5396 ;; We just showed the children, or no children are there,
5397 ;; now show everything.
5398 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5399 (org-show-subtree)
5400 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5401 (setq org-cycle-subtree-status 'subtree)
5402 (run-hook-with-args 'org-cycle-hook 'subtree))
5404 ;; Default action: hide the subtree.
5405 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5406 (hide-subtree)
5407 (message "FOLDED")
5408 (setq org-cycle-subtree-status 'folded)
5409 (run-hook-with-args 'org-cycle-hook 'folded)))))
5411 ;;;###autoload
5412 (defun org-global-cycle (&optional arg)
5413 "Cycle the global visibility. For details see `org-cycle'.
5414 With C-u prefix arg, switch to startup visibility.
5415 With a numeric prefix, show all headlines up to that level."
5416 (interactive "P")
5417 (let ((org-cycle-include-plain-lists
5418 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5419 (cond
5420 ((integerp arg)
5421 (show-all)
5422 (hide-sublevels arg)
5423 (setq org-cycle-global-status 'contents))
5424 ((equal arg '(4))
5425 (org-set-startup-visibility)
5426 (message "Startup visibility, plus VISIBILITY properties."))
5428 (org-cycle '(4))))))
5430 (defun org-set-startup-visibility ()
5431 "Set the visibility required by startup options and properties."
5432 (cond
5433 ((eq org-startup-folded t)
5434 (org-cycle '(4)))
5435 ((eq org-startup-folded 'content)
5436 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5437 (org-cycle '(4)) (org-cycle '(4)))))
5438 (unless (eq org-startup-folded 'showeverything)
5439 (if org-hide-block-startup (org-hide-block-all))
5440 (org-set-visibility-according-to-property 'no-cleanup)
5441 (org-cycle-hide-archived-subtrees 'all)
5442 (org-cycle-hide-drawers 'all)
5443 (org-cycle-show-empty-lines 'all)))
5445 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5446 "Switch subtree visibilities according to :VISIBILITY: property."
5447 (interactive)
5448 (let (org-show-entry-below state)
5449 (save-excursion
5450 (goto-char (point-min))
5451 (while (re-search-forward
5452 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5453 nil t)
5454 (setq state (match-string 1))
5455 (save-excursion
5456 (org-back-to-heading t)
5457 (hide-subtree)
5458 (org-reveal)
5459 (cond
5460 ((equal state '("fold" "folded"))
5461 (hide-subtree))
5462 ((equal state "children")
5463 (org-show-hidden-entry)
5464 (show-children))
5465 ((equal state "content")
5466 (save-excursion
5467 (save-restriction
5468 (org-narrow-to-subtree)
5469 (org-content))))
5470 ((member state '("all" "showall"))
5471 (show-subtree)))))
5472 (unless no-cleanup
5473 (org-cycle-hide-archived-subtrees 'all)
5474 (org-cycle-hide-drawers 'all)
5475 (org-cycle-show-empty-lines 'all)))))
5477 (defun org-overview ()
5478 "Switch to overview mode, showing only top-level headlines.
5479 Really, this shows all headlines with level equal or greater than the level
5480 of the first headline in the buffer. This is important, because if the
5481 first headline is not level one, then (hide-sublevels 1) gives confusing
5482 results."
5483 (interactive)
5484 (let ((level (save-excursion
5485 (goto-char (point-min))
5486 (if (re-search-forward (concat "^" outline-regexp) nil t)
5487 (progn
5488 (goto-char (match-beginning 0))
5489 (funcall outline-level))))))
5490 (and level (hide-sublevels level))))
5492 (defun org-content (&optional arg)
5493 "Show all headlines in the buffer, like a table of contents.
5494 With numerical argument N, show content up to level N."
5495 (interactive "P")
5496 (save-excursion
5497 ;; Visit all headings and show their offspring
5498 (and (integerp arg) (org-overview))
5499 (goto-char (point-max))
5500 (catch 'exit
5501 (while (and (progn (condition-case nil
5502 (outline-previous-visible-heading 1)
5503 (error (goto-char (point-min))))
5505 (looking-at outline-regexp))
5506 (if (integerp arg)
5507 (show-children (1- arg))
5508 (show-branches))
5509 (if (bobp) (throw 'exit nil))))))
5512 (defun org-optimize-window-after-visibility-change (state)
5513 "Adjust the window after a change in outline visibility.
5514 This function is the default value of the hook `org-cycle-hook'."
5515 (when (get-buffer-window (current-buffer))
5516 (cond
5517 ((eq state 'content) nil)
5518 ((eq state 'all) nil)
5519 ((eq state 'folded) nil)
5520 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5521 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5523 (defun org-remove-empty-overlays-at (pos)
5524 "Remove outline overlays that do not contain non-white stuff."
5525 (mapc
5526 (lambda (o)
5527 (and (eq 'outline (org-overlay-get o 'invisible))
5528 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5529 (org-overlay-end o))))
5530 (org-delete-overlay o)))
5531 (org-overlays-at pos)))
5533 (defun org-clean-visibility-after-subtree-move ()
5534 "Fix visibility issues after moving a subtree."
5535 ;; First, find a reasonable region to look at:
5536 ;; Start two siblings above, end three below
5537 (let* ((beg (save-excursion
5538 (and (org-get-last-sibling)
5539 (org-get-last-sibling))
5540 (point)))
5541 (end (save-excursion
5542 (and (org-get-next-sibling)
5543 (org-get-next-sibling)
5544 (org-get-next-sibling))
5545 (if (org-at-heading-p)
5546 (point-at-eol)
5547 (point))))
5548 (level (looking-at "\\*+"))
5549 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5550 (save-excursion
5551 (save-restriction
5552 (narrow-to-region beg end)
5553 (when re
5554 ;; Properly fold already folded siblings
5555 (goto-char (point-min))
5556 (while (re-search-forward re nil t)
5557 (if (and (not (org-invisible-p))
5558 (save-excursion
5559 (goto-char (point-at-eol)) (org-invisible-p)))
5560 (hide-entry))))
5561 (org-cycle-show-empty-lines 'overview)
5562 (org-cycle-hide-drawers 'overview)))))
5564 (defun org-cycle-show-empty-lines (state)
5565 "Show empty lines above all visible headlines.
5566 The region to be covered depends on STATE when called through
5567 `org-cycle-hook'. Lisp program can use t for STATE to get the
5568 entire buffer covered. Note that an empty line is only shown if there
5569 are at least `org-cycle-separator-lines' empty lines before the headline."
5570 (when (not (= org-cycle-separator-lines 0))
5571 (save-excursion
5572 (let* ((n (abs org-cycle-separator-lines))
5573 (re (cond
5574 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5575 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5576 (t (let ((ns (number-to-string (- n 2))))
5577 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5578 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5579 beg end b e)
5580 (cond
5581 ((memq state '(overview contents t))
5582 (setq beg (point-min) end (point-max)))
5583 ((memq state '(children folded))
5584 (setq beg (point) end (progn (org-end-of-subtree t t)
5585 (beginning-of-line 2)
5586 (point)))))
5587 (when beg
5588 (goto-char beg)
5589 (while (re-search-forward re end t)
5590 (unless (get-char-property (match-end 1) 'invisible)
5591 (setq e (match-end 1))
5592 (if (< org-cycle-separator-lines 0)
5593 (setq b (save-excursion
5594 (goto-char (match-beginning 0))
5595 (org-back-over-empty-lines)
5596 (if (save-excursion
5597 (goto-char (max (point-min) (1- (point))))
5598 (org-on-heading-p))
5599 (1- (point))
5600 (point))))
5601 (setq b (match-beginning 1)))
5602 (outline-flag-region b e nil)))))))
5603 ;; Never hide empty lines at the end of the file.
5604 (save-excursion
5605 (goto-char (point-max))
5606 (outline-previous-heading)
5607 (outline-end-of-heading)
5608 (if (and (looking-at "[ \t\n]+")
5609 (= (match-end 0) (point-max)))
5610 (outline-flag-region (point) (match-end 0) nil))))
5612 (defun org-show-empty-lines-in-parent ()
5613 "Move to the parent and re-show empty lines before visible headlines."
5614 (save-excursion
5615 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5616 (org-cycle-show-empty-lines context))))
5618 (defun org-files-list ()
5619 "Return `org-agenda-files' list, plus all open org-mode files.
5620 This is useful for operations that need to scan all of a user's
5621 open and agenda-wise Org files."
5622 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
5623 (dolist (buf (buffer-list))
5624 (with-current-buffer buf
5625 (if (and (eq major-mode 'org-mode) (buffer-file-name))
5626 (let ((file (expand-file-name (buffer-file-name))))
5627 (unless (member file files)
5628 (push file files))))))
5629 files))
5631 (defsubst org-entry-beginning-position ()
5632 "Return the beginning position of the current entry."
5633 (save-excursion (outline-back-to-heading t) (point)))
5635 (defsubst org-entry-end-position ()
5636 "Return the end position of the current entry."
5637 (save-excursion (outline-next-heading) (point)))
5639 (defun org-cycle-hide-drawers (state)
5640 "Re-hide all drawers after a visibility state change."
5641 (when (and (org-mode-p)
5642 (not (memq state '(overview folded contents))))
5643 (save-excursion
5644 (let* ((globalp (memq state '(contents all)))
5645 (beg (if globalp (point-min) (point)))
5646 (end (if globalp (point-max)
5647 (if (eq state 'children)
5648 (save-excursion (outline-next-heading) (point))
5649 (org-end-of-subtree t)))))
5650 (goto-char beg)
5651 (while (re-search-forward org-drawer-regexp end t)
5652 (org-flag-drawer t))))))
5654 (defun org-flag-drawer (flag)
5655 (save-excursion
5656 (beginning-of-line 1)
5657 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5658 (let ((b (match-end 0))
5659 (outline-regexp org-outline-regexp))
5660 (if (re-search-forward
5661 "^[ \t]*:END:"
5662 (save-excursion (outline-next-heading) (point)) t)
5663 (outline-flag-region b (point-at-eol) flag)
5664 (error ":END: line missing at position %s" b))))))
5666 (defun org-subtree-end-visible-p ()
5667 "Is the end of the current subtree visible?"
5668 (pos-visible-in-window-p
5669 (save-excursion (org-end-of-subtree t) (point))))
5671 (defun org-first-headline-recenter (&optional N)
5672 "Move cursor to the first headline and recenter the headline.
5673 Optional argument N means put the headline into the Nth line of the window."
5674 (goto-char (point-min))
5675 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5676 (beginning-of-line)
5677 (recenter (prefix-numeric-value N))))
5679 ;;; Saving and restoring visibility
5681 (defun org-outline-overlay-data (&optional use-markers)
5682 "Return a list of the locations of all outline overlays.
5683 The are overlays with the `invisible' property value `outline'.
5684 The return valus is a list of cons cells, with start and stop
5685 positions for each overlay.
5686 If USE-MARKERS is set, return the positions as markers."
5687 (let (beg end)
5688 (save-excursion
5689 (save-restriction
5690 (widen)
5691 (delq nil
5692 (mapcar (lambda (o)
5693 (when (eq (org-overlay-get o 'invisible) 'outline)
5694 (setq beg (org-overlay-start o)
5695 end (org-overlay-end o))
5696 (and beg end (> end beg)
5697 (if use-markers
5698 (cons (move-marker (make-marker) beg)
5699 (move-marker (make-marker) end))
5700 (cons beg end)))))
5701 (org-overlays-in (point-min) (point-max))))))))
5703 (defun org-set-outline-overlay-data (data)
5704 "Create visibility overlays for all positions in DATA.
5705 DATA should have been made by `org-outline-overlay-data'."
5706 (let (o)
5707 (save-excursion
5708 (save-restriction
5709 (widen)
5710 (show-all)
5711 (mapc (lambda (c)
5712 (setq o (org-make-overlay (car c) (cdr c)))
5713 (org-overlay-put o 'invisible 'outline))
5714 data)))))
5716 (defmacro org-save-outline-visibility (use-markers &rest body)
5717 "Save and restore outline visibility around BODY.
5718 If USE-MARKERS is non-nil, use markers for the positions.
5719 This means that the buffer may change while running BODY,
5720 but it also means that the buffer should stay alive
5721 during the operation, because otherwise all these markers will
5722 point nowhere."
5723 `(let ((data (org-outline-overlay-data ,use-markers)))
5724 (unwind-protect
5725 (progn
5726 ,@body
5727 (org-set-outline-overlay-data data))
5728 (when ,use-markers
5729 (mapc (lambda (c)
5730 (and (markerp (car c)) (move-marker (car c) nil))
5731 (and (markerp (cdr c)) (move-marker (cdr c) nil)))
5732 data)))))
5735 ;;; Folding of blocks
5737 (defconst org-block-regexp
5739 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5740 "Regular expression for hiding blocks.")
5742 (defvar org-hide-block-overlays nil
5743 "Overlays hiding blocks.")
5744 (make-variable-buffer-local 'org-hide-block-overlays)
5746 (defun org-block-map (function &optional start end)
5747 "Call func at the head of all source blocks in the current
5748 buffer. Optional arguments START and END can be used to limit
5749 the range."
5750 (let ((start (or start (point-min)))
5751 (end (or end (point-max))))
5752 (save-excursion
5753 (goto-char start)
5754 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5755 (save-excursion
5756 (save-match-data
5757 (goto-char (match-beginning 0))
5758 (funcall function)))))))
5760 (defun org-hide-block-toggle-all ()
5761 "Toggle the visibility of all blocks in the current buffer."
5762 (org-block-map #'org-hide-block-toggle))
5764 (defun org-hide-block-all ()
5765 "Fold all blocks in the current buffer."
5766 (interactive)
5767 (org-show-block-all)
5768 (org-block-map #'org-hide-block-toggle-maybe))
5770 (defun org-show-block-all ()
5771 "Unfold all blocks in the current buffer."
5772 (mapc 'org-delete-overlay org-hide-block-overlays)
5773 (setq org-hide-block-overlays nil))
5775 (defun org-hide-block-toggle-maybe ()
5776 "Toggle visibility of block at point."
5777 (interactive)
5778 (let ((case-fold-search t))
5779 (if (save-excursion
5780 (beginning-of-line 1)
5781 (looking-at org-block-regexp))
5782 (progn (org-hide-block-toggle)
5783 t) ;; to signal that we took action
5784 nil))) ;; to signal that we did not
5786 (defun org-hide-block-toggle (&optional force)
5787 "Toggle the visibility of the current block."
5788 (interactive)
5789 (save-excursion
5790 (beginning-of-line)
5791 (if (re-search-forward org-block-regexp nil t)
5792 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5793 (end (match-end 0)) ;; end of entire body
5795 (if (memq t (mapcar (lambda (overlay)
5796 (eq (org-overlay-get overlay 'invisible)
5797 'org-hide-block))
5798 (org-overlays-at start)))
5799 (if (or (not force) (eq force 'off))
5800 (mapc (lambda (ov)
5801 (when (member ov org-hide-block-overlays)
5802 (setq org-hide-block-overlays
5803 (delq ov org-hide-block-overlays)))
5804 (when (eq (org-overlay-get ov 'invisible)
5805 'org-hide-block)
5806 (org-delete-overlay ov)))
5807 (org-overlays-at start)))
5808 (setq ov (org-make-overlay start end))
5809 (org-overlay-put ov 'invisible 'org-hide-block)
5810 ;; make the block accessible to isearch
5811 (org-overlay-put
5812 ov 'isearch-open-invisible
5813 (lambda (ov)
5814 (when (member ov org-hide-block-overlays)
5815 (setq org-hide-block-overlays
5816 (delq ov org-hide-block-overlays)))
5817 (when (eq (org-overlay-get ov 'invisible)
5818 'org-hide-block)
5819 (org-delete-overlay ov))))
5820 (push ov org-hide-block-overlays)))
5821 (error "Not looking at a source block"))))
5823 ;; org-tab-after-check-for-cycling-hook
5824 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5825 ;; Remove overlays when changing major mode
5826 (add-hook 'org-mode-hook
5827 (lambda () (org-add-hook 'change-major-mode-hook
5828 'org-show-block-all 'append 'local)))
5830 ;;; Org-goto
5832 (defvar org-goto-window-configuration nil)
5833 (defvar org-goto-marker nil)
5834 (defvar org-goto-map
5835 (let ((map (make-sparse-keymap)))
5836 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5837 (while (setq cmd (pop cmds))
5838 (substitute-key-definition cmd cmd map global-map)))
5839 (suppress-keymap map)
5840 (org-defkey map "\C-m" 'org-goto-ret)
5841 (org-defkey map [(return)] 'org-goto-ret)
5842 (org-defkey map [(left)] 'org-goto-left)
5843 (org-defkey map [(right)] 'org-goto-right)
5844 (org-defkey map [(control ?g)] 'org-goto-quit)
5845 (org-defkey map "\C-i" 'org-cycle)
5846 (org-defkey map [(tab)] 'org-cycle)
5847 (org-defkey map [(down)] 'outline-next-visible-heading)
5848 (org-defkey map [(up)] 'outline-previous-visible-heading)
5849 (if org-goto-auto-isearch
5850 (if (fboundp 'define-key-after)
5851 (define-key-after map [t] 'org-goto-local-auto-isearch)
5852 nil)
5853 (org-defkey map "q" 'org-goto-quit)
5854 (org-defkey map "n" 'outline-next-visible-heading)
5855 (org-defkey map "p" 'outline-previous-visible-heading)
5856 (org-defkey map "f" 'outline-forward-same-level)
5857 (org-defkey map "b" 'outline-backward-same-level)
5858 (org-defkey map "u" 'outline-up-heading))
5859 (org-defkey map "/" 'org-occur)
5860 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5861 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5862 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5863 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5864 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5865 map))
5867 (defconst org-goto-help
5868 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5869 RET=jump to location [Q]uit and return to previous location
5870 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5872 (defvar org-goto-start-pos) ; dynamically scoped parameter
5874 ;; FIXME: Docstring does not mention both interfaces
5875 (defun org-goto (&optional alternative-interface)
5876 "Look up a different location in the current file, keeping current visibility.
5878 When you want look-up or go to a different location in a document, the
5879 fastest way is often to fold the entire buffer and then dive into the tree.
5880 This method has the disadvantage, that the previous location will be folded,
5881 which may not be what you want.
5883 This command works around this by showing a copy of the current buffer
5884 in an indirect buffer, in overview mode. You can dive into the tree in
5885 that copy, use org-occur and incremental search to find a location.
5886 When pressing RET or `Q', the command returns to the original buffer in
5887 which the visibility is still unchanged. After RET is will also jump to
5888 the location selected in the indirect buffer and expose the
5889 the headline hierarchy above."
5890 (interactive "P")
5891 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5892 (org-refile-use-outline-path t)
5893 (org-refile-target-verify-function nil)
5894 (interface
5895 (if (not alternative-interface)
5896 org-goto-interface
5897 (if (eq org-goto-interface 'outline)
5898 'outline-path-completion
5899 'outline)))
5900 (org-goto-start-pos (point))
5901 (selected-point
5902 (if (eq interface 'outline)
5903 (car (org-get-location (current-buffer) org-goto-help))
5904 (nth 3 (org-refile-get-location "Goto: ")))))
5905 (if selected-point
5906 (progn
5907 (org-mark-ring-push org-goto-start-pos)
5908 (goto-char selected-point)
5909 (if (or (org-invisible-p) (org-invisible-p2))
5910 (org-show-context 'org-goto)))
5911 (message "Quit"))))
5913 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5914 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5915 (defvar org-goto-local-auto-isearch-map) ; defined below
5917 (defun org-get-location (buf help)
5918 "Let the user select a location in the Org-mode buffer BUF.
5919 This function uses a recursive edit. It returns the selected position
5920 or nil."
5921 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5922 (isearch-hide-immediately nil)
5923 (isearch-search-fun-function
5924 (lambda () 'org-goto-local-search-headings))
5925 (org-goto-selected-point org-goto-exit-command)
5926 (pop-up-frames nil)
5927 (special-display-buffer-names nil)
5928 (special-display-regexps nil)
5929 (special-display-function nil))
5930 (save-excursion
5931 (save-window-excursion
5932 (delete-other-windows)
5933 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5934 (switch-to-buffer
5935 (condition-case nil
5936 (make-indirect-buffer (current-buffer) "*org-goto*")
5937 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5938 (with-output-to-temp-buffer "*Help*"
5939 (princ help))
5940 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5941 (setq buffer-read-only nil)
5942 (let ((org-startup-truncated t)
5943 (org-startup-folded nil)
5944 (org-startup-align-all-tables nil))
5945 (org-mode)
5946 (org-overview))
5947 (setq buffer-read-only t)
5948 (if (and (boundp 'org-goto-start-pos)
5949 (integer-or-marker-p org-goto-start-pos))
5950 (let ((org-show-hierarchy-above t)
5951 (org-show-siblings t)
5952 (org-show-following-heading t))
5953 (goto-char org-goto-start-pos)
5954 (and (org-invisible-p) (org-show-context)))
5955 (goto-char (point-min)))
5956 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5957 (message "Select location and press RET")
5958 (use-local-map org-goto-map)
5959 (recursive-edit)
5961 (kill-buffer "*org-goto*")
5962 (cons org-goto-selected-point org-goto-exit-command)))
5964 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5965 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5966 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5967 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5969 (defun org-goto-local-search-headings (string bound noerror)
5970 "Search and make sure that any matches are in headlines."
5971 (catch 'return
5972 (while (if isearch-forward
5973 (search-forward string bound noerror)
5974 (search-backward string bound noerror))
5975 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5976 (and (member :headline context)
5977 (not (member :tags context))))
5978 (throw 'return (point))))))
5980 (defun org-goto-local-auto-isearch ()
5981 "Start isearch."
5982 (interactive)
5983 (goto-char (point-min))
5984 (let ((keys (this-command-keys)))
5985 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5986 (isearch-mode t)
5987 (isearch-process-search-char (string-to-char keys)))))
5989 (defun org-goto-ret (&optional arg)
5990 "Finish `org-goto' by going to the new location."
5991 (interactive "P")
5992 (setq org-goto-selected-point (point)
5993 org-goto-exit-command 'return)
5994 (throw 'exit nil))
5996 (defun org-goto-left ()
5997 "Finish `org-goto' by going to the new location."
5998 (interactive)
5999 (if (org-on-heading-p)
6000 (progn
6001 (beginning-of-line 1)
6002 (setq org-goto-selected-point (point)
6003 org-goto-exit-command 'left)
6004 (throw 'exit nil))
6005 (error "Not on a heading")))
6007 (defun org-goto-right ()
6008 "Finish `org-goto' by going to the new location."
6009 (interactive)
6010 (if (org-on-heading-p)
6011 (progn
6012 (setq org-goto-selected-point (point)
6013 org-goto-exit-command 'right)
6014 (throw 'exit nil))
6015 (error "Not on a heading")))
6017 (defun org-goto-quit ()
6018 "Finish `org-goto' without cursor motion."
6019 (interactive)
6020 (setq org-goto-selected-point nil)
6021 (setq org-goto-exit-command 'quit)
6022 (throw 'exit nil))
6024 ;;; Indirect buffer display of subtrees
6026 (defvar org-indirect-dedicated-frame nil
6027 "This is the frame being used for indirect tree display.")
6028 (defvar org-last-indirect-buffer nil)
6030 (defun org-tree-to-indirect-buffer (&optional arg)
6031 "Create indirect buffer and narrow it to current subtree.
6032 With numerical prefix ARG, go up to this level and then take that tree.
6033 If ARG is negative, go up that many levels.
6034 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6035 indirect buffer previously made with this command, to avoid proliferation of
6036 indirect buffers. However, when you call the command with a `C-u' prefix, or
6037 when `org-indirect-buffer-display' is `new-frame', the last buffer
6038 is kept so that you can work with several indirect buffers at the same time.
6039 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6040 requests that a new frame be made for the new buffer, so that the dedicated
6041 frame is not changed."
6042 (interactive "P")
6043 (let ((cbuf (current-buffer))
6044 (cwin (selected-window))
6045 (pos (point))
6046 beg end level heading ibuf)
6047 (save-excursion
6048 (org-back-to-heading t)
6049 (when (numberp arg)
6050 (setq level (org-outline-level))
6051 (if (< arg 0) (setq arg (+ level arg)))
6052 (while (> (setq level (org-outline-level)) arg)
6053 (outline-up-heading 1 t)))
6054 (setq beg (point)
6055 heading (org-get-heading))
6056 (org-end-of-subtree t t)
6057 (if (org-on-heading-p) (backward-char 1))
6058 (setq end (point)))
6059 (if (and (buffer-live-p org-last-indirect-buffer)
6060 (not (eq org-indirect-buffer-display 'new-frame))
6061 (not arg))
6062 (kill-buffer org-last-indirect-buffer))
6063 (setq ibuf (org-get-indirect-buffer cbuf)
6064 org-last-indirect-buffer ibuf)
6065 (cond
6066 ((or (eq org-indirect-buffer-display 'new-frame)
6067 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6068 (select-frame (make-frame))
6069 (delete-other-windows)
6070 (switch-to-buffer ibuf)
6071 (org-set-frame-title heading))
6072 ((eq org-indirect-buffer-display 'dedicated-frame)
6073 (raise-frame
6074 (select-frame (or (and org-indirect-dedicated-frame
6075 (frame-live-p org-indirect-dedicated-frame)
6076 org-indirect-dedicated-frame)
6077 (setq org-indirect-dedicated-frame (make-frame)))))
6078 (delete-other-windows)
6079 (switch-to-buffer ibuf)
6080 (org-set-frame-title (concat "Indirect: " heading)))
6081 ((eq org-indirect-buffer-display 'current-window)
6082 (switch-to-buffer ibuf))
6083 ((eq org-indirect-buffer-display 'other-window)
6084 (pop-to-buffer ibuf))
6085 (t (error "Invalid value")))
6086 (if (featurep 'xemacs)
6087 (save-excursion (org-mode) (turn-on-font-lock)))
6088 (narrow-to-region beg end)
6089 (show-all)
6090 (goto-char pos)
6091 (and (window-live-p cwin) (select-window cwin))))
6093 (defun org-get-indirect-buffer (&optional buffer)
6094 (setq buffer (or buffer (current-buffer)))
6095 (let ((n 1) (base (buffer-name buffer)) bname)
6096 (while (buffer-live-p
6097 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6098 (setq n (1+ n)))
6099 (condition-case nil
6100 (make-indirect-buffer buffer bname 'clone)
6101 (error (make-indirect-buffer buffer bname)))))
6103 (defun org-set-frame-title (title)
6104 "Set the title of the current frame to the string TITLE."
6105 ;; FIXME: how to name a single frame in XEmacs???
6106 (unless (featurep 'xemacs)
6107 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6109 ;;;; Structure editing
6111 ;;; Inserting headlines
6113 (defun org-previous-line-empty-p ()
6114 (save-excursion
6115 (and (not (bobp))
6116 (or (beginning-of-line 0) t)
6117 (save-match-data
6118 (looking-at "[ \t]*$")))))
6120 (defun org-insert-heading (&optional force-heading invisible-ok)
6121 "Insert a new heading or item with same depth at point.
6122 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6123 If point is at the beginning of a headline, insert a sibling before the
6124 current headline. If point is not at the beginning, do not split the line,
6125 but create the new headline after the current line.
6126 When INVISIBLE-OK is set, stop at invisible headlines when going back.
6127 This is important for non-interactive uses of the command."
6128 (interactive "P")
6129 (if (or (= (buffer-size) 0)
6130 (and (not (save-excursion (and (ignore-errors (org-back-to-heading invisible-ok))
6131 (org-on-heading-p))))
6132 (not (org-in-item-p))))
6133 (insert "\n* ")
6134 (when (or force-heading (not (org-insert-item)))
6135 (let* ((empty-line-p nil)
6136 (head (save-excursion
6137 (condition-case nil
6138 (progn
6139 (org-back-to-heading invisible-ok)
6140 (setq empty-line-p (org-previous-line-empty-p))
6141 (match-string 0))
6142 (error "*"))))
6143 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6144 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6145 pos hide-previous previous-pos)
6146 (cond
6147 ((and (org-on-heading-p) (bolp)
6148 (or (bobp)
6149 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6150 ;; insert before the current line
6151 (open-line (if blank 2 1)))
6152 ((and (bolp)
6153 (not org-insert-heading-respect-content)
6154 (or (bobp)
6155 (save-excursion
6156 (backward-char 1) (not (org-invisible-p)))))
6157 ;; insert right here
6158 nil)
6160 ;; somewhere in the line
6161 (save-excursion
6162 (setq previous-pos (point-at-bol))
6163 (end-of-line)
6164 (setq hide-previous (org-invisible-p)))
6165 (and org-insert-heading-respect-content (org-show-subtree))
6166 (let ((split
6167 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6168 (save-excursion
6169 (let ((p (point)))
6170 (goto-char (point-at-bol))
6171 (and (looking-at org-complex-heading-regexp)
6172 (> p (match-beginning 4)))))))
6173 tags pos)
6174 (cond
6175 (org-insert-heading-respect-content
6176 (org-end-of-subtree nil t)
6177 (or (bolp) (newline))
6178 (or (org-previous-line-empty-p)
6179 (and blank (newline)))
6180 (open-line 1))
6181 ((org-on-heading-p)
6182 (when hide-previous
6183 (show-children)
6184 (org-show-entry))
6185 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6186 (setq tags (and (match-end 2) (match-string 2)))
6187 (and (match-end 1)
6188 (delete-region (match-beginning 1) (match-end 1)))
6189 (setq pos (point-at-bol))
6190 (or split (end-of-line 1))
6191 (delete-horizontal-space)
6192 (if (string-match "\\`\\*+\\'"
6193 (buffer-substring (point-at-bol) (point)))
6194 (insert " "))
6195 (newline (if blank 2 1))
6196 (when tags
6197 (save-excursion
6198 (goto-char pos)
6199 (end-of-line 1)
6200 (insert " " tags)
6201 (org-set-tags nil 'align))))
6203 (or split (end-of-line 1))
6204 (newline (if blank 2 1)))))))
6205 (insert head) (just-one-space)
6206 (setq pos (point))
6207 (end-of-line 1)
6208 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6209 (when (and org-insert-heading-respect-content hide-previous)
6210 (save-excursion
6211 (goto-char previous-pos)
6212 (hide-subtree)))
6213 (run-hooks 'org-insert-heading-hook)))))
6215 (defun org-get-heading (&optional no-tags)
6216 "Return the heading of the current entry, without the stars."
6217 (save-excursion
6218 (org-back-to-heading t)
6219 (if (looking-at
6220 (if no-tags
6221 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
6222 "\\*+[ \t]+\\([^\r\n]*\\)"))
6223 (match-string 1) "")))
6225 (defun org-heading-components ()
6226 "Return the components of the current heading.
6227 This is a list with the following elements:
6228 - the level as an integer
6229 - the reduced level, different if `org-odd-levels-only' is set.
6230 - the TODO keyword, or nil
6231 - the priority character, like ?A, or nil if no priority is given
6232 - the headline text itself, or the tags string if no headline text
6233 - the tags string, or nil."
6234 (save-excursion
6235 (org-back-to-heading t)
6236 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
6237 (list (length (match-string 1))
6238 (org-reduced-level (length (match-string 1)))
6239 (org-match-string-no-properties 2)
6240 (and (match-end 3) (aref (match-string 3) 2))
6241 (org-match-string-no-properties 4)
6242 (org-match-string-no-properties 5)))))
6244 (defun org-get-entry ()
6245 "Get the entry text, after heading, entire subtree."
6246 (save-excursion
6247 (org-back-to-heading t)
6248 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6250 (defun org-insert-heading-after-current ()
6251 "Insert a new heading with same level as current, after current subtree."
6252 (interactive)
6253 (org-back-to-heading)
6254 (org-insert-heading)
6255 (org-move-subtree-down)
6256 (end-of-line 1))
6258 (defun org-insert-heading-respect-content ()
6259 (interactive)
6260 (let ((org-insert-heading-respect-content t))
6261 (org-insert-heading t)))
6263 (defun org-insert-todo-heading-respect-content (&optional force-state)
6264 (interactive "P")
6265 (let ((org-insert-heading-respect-content t))
6266 (org-insert-todo-heading force-state t)))
6268 (defun org-insert-todo-heading (arg &optional force-heading)
6269 "Insert a new heading with the same level and TODO state as current heading.
6270 If the heading has no TODO state, or if the state is DONE, use the first
6271 state (TODO by default). Also with prefix arg, force first state."
6272 (interactive "P")
6273 (when (or force-heading (not (org-insert-item 'checkbox)))
6274 (org-insert-heading force-heading)
6275 (save-excursion
6276 (org-back-to-heading)
6277 (outline-previous-heading)
6278 (looking-at org-todo-line-regexp))
6279 (let*
6280 ((new-mark-x
6281 (if (or arg
6282 (not (match-beginning 2))
6283 (member (match-string 2) org-done-keywords))
6284 (car org-todo-keywords-1)
6285 (match-string 2)))
6286 (new-mark
6288 (run-hook-with-args-until-success
6289 'org-todo-get-default-hook new-mark-x nil)
6290 new-mark-x)))
6291 (beginning-of-line 1)
6292 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6293 (if org-treat-insert-todo-heading-as-state-change
6294 (org-todo new-mark)
6295 (insert new-mark " "))))
6296 (when org-provide-todo-statistics
6297 (org-update-parent-todo-statistics))))
6299 (defun org-insert-subheading (arg)
6300 "Insert a new subheading and demote it.
6301 Works for outline headings and for plain lists alike."
6302 (interactive "P")
6303 (org-insert-heading arg)
6304 (cond
6305 ((org-on-heading-p) (org-do-demote))
6306 ((org-at-item-p) (org-indent-item 1))))
6308 (defun org-insert-todo-subheading (arg)
6309 "Insert a new subheading with TODO keyword or checkbox and demote it.
6310 Works for outline headings and for plain lists alike."
6311 (interactive "P")
6312 (org-insert-todo-heading arg)
6313 (cond
6314 ((org-on-heading-p) (org-do-demote))
6315 ((org-at-item-p) (org-indent-item 1))))
6317 ;;; Promotion and Demotion
6319 (defvar org-after-demote-entry-hook nil
6320 "Hook run after an entry has been demoted.
6321 The cursor will be at the beginning of the entry.
6322 When a subtree is being demoted, the hook will be called for each node.")
6324 (defvar org-after-promote-entry-hook nil
6325 "Hook run after an entry has been promoted.
6326 The cursor will be at the beginning of the entry.
6327 When a subtree is being promoted, the hook will be called for each node.")
6329 (defun org-promote-subtree ()
6330 "Promote the entire subtree.
6331 See also `org-promote'."
6332 (interactive)
6333 (save-excursion
6334 (org-map-tree 'org-promote))
6335 (org-fix-position-after-promote))
6337 (defun org-demote-subtree ()
6338 "Demote the entire subtree. See `org-demote'.
6339 See also `org-promote'."
6340 (interactive)
6341 (save-excursion
6342 (org-map-tree 'org-demote))
6343 (org-fix-position-after-promote))
6346 (defun org-do-promote ()
6347 "Promote the current heading higher up the tree.
6348 If the region is active in `transient-mark-mode', promote all headings
6349 in the region."
6350 (interactive)
6351 (save-excursion
6352 (if (org-region-active-p)
6353 (org-map-region 'org-promote (region-beginning) (region-end))
6354 (org-promote)))
6355 (org-fix-position-after-promote))
6357 (defun org-do-demote ()
6358 "Demote the current heading lower down the tree.
6359 If the region is active in `transient-mark-mode', demote all headings
6360 in the region."
6361 (interactive)
6362 (save-excursion
6363 (if (org-region-active-p)
6364 (org-map-region 'org-demote (region-beginning) (region-end))
6365 (org-demote)))
6366 (org-fix-position-after-promote))
6368 (defun org-fix-position-after-promote ()
6369 "Make sure that after pro/demotion cursor position is right."
6370 (let ((pos (point)))
6371 (when (save-excursion
6372 (beginning-of-line 1)
6373 (looking-at org-todo-line-regexp)
6374 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6375 (cond ((eobp) (insert " "))
6376 ((eolp) (insert " "))
6377 ((equal (char-after) ?\ ) (forward-char 1))))))
6379 (defun org-current-level ()
6380 "Return the level of the current entry, or nil if before the first headline.
6381 The level is the number of stars at the beginning of the headline."
6382 (save-excursion
6383 (condition-case nil
6384 (progn
6385 (org-back-to-heading t)
6386 (funcall outline-level))
6387 (error nil))))
6389 (defun org-get-previous-line-level ()
6390 "Return the outline depth of the last headline before the current line.
6391 Returns 0 for the first headline in the buffer, and nil if before the
6392 first headline."
6393 (let ((current-level (org-current-level))
6394 (prev-level (when (> (line-number-at-pos) 1)
6395 (save-excursion
6396 (beginning-of-line 0)
6397 (org-current-level)))))
6398 (cond ((null current-level) nil) ; Before first headline
6399 ((null prev-level) 0) ; At first headline
6400 (prev-level))))
6402 (defun org-reduced-level (l)
6403 "Compute the effective level of a heading.
6404 This takes into account the setting of `org-odd-levels-only'."
6405 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6407 (defun org-level-increment ()
6408 "Return the number of stars that will be added or removed at a
6409 time to headlines when structure editing, based on the value of
6410 `org-odd-levels-only'."
6411 (if org-odd-levels-only 2 1))
6413 (defun org-get-valid-level (level &optional change)
6414 "Rectify a level change under the influence of `org-odd-levels-only'
6415 LEVEL is a current level, CHANGE is by how much the level should be
6416 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6417 even level numbers will become the next higher odd number."
6418 (if org-odd-levels-only
6419 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6420 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6421 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6422 (max 1 (+ level (or change 0)))))
6424 (if (boundp 'define-obsolete-function-alias)
6425 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6426 (define-obsolete-function-alias 'org-get-legal-level
6427 'org-get-valid-level)
6428 (define-obsolete-function-alias 'org-get-legal-level
6429 'org-get-valid-level "23.1")))
6431 (defun org-promote ()
6432 "Promote the current heading higher up the tree.
6433 If the region is active in `transient-mark-mode', promote all headings
6434 in the region."
6435 (org-back-to-heading t)
6436 (let* ((level (save-match-data (funcall outline-level)))
6437 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6438 (diff (abs (- level (length up-head) -1))))
6439 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6440 (replace-match up-head nil t)
6441 ;; Fixup tag positioning
6442 (and org-auto-align-tags (org-set-tags nil t))
6443 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6444 (run-hooks 'org-after-promote-entry-hook)))
6446 (defun org-demote ()
6447 "Demote the current heading lower down the tree.
6448 If the region is active in `transient-mark-mode', demote all headings
6449 in the region."
6450 (org-back-to-heading t)
6451 (let* ((level (save-match-data (funcall outline-level)))
6452 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6453 (diff (abs (- level (length down-head) -1))))
6454 (replace-match down-head nil t)
6455 ;; Fixup tag positioning
6456 (and org-auto-align-tags (org-set-tags nil t))
6457 (if org-adapt-indentation (org-fixup-indentation diff))
6458 (run-hooks 'org-after-demote-entry-hook)))
6460 (defun org-cycle-level ()
6461 "Cycle the level of an empty headline through possible states.
6462 This goes first to child, then to parent, level, then up the hierarchy.
6463 After top level, it switches back to sibling level."
6464 (interactive)
6465 (let ((org-adapt-indentation nil))
6466 (when (org-point-at-end-of-empty-headline)
6467 (setq this-command 'org-cycle-level) ; Only needed for caching
6468 (let ((cur-level (org-current-level))
6469 (prev-level (org-get-previous-line-level)))
6470 (cond
6471 ;; If first headline in file, promote to top-level.
6472 ((= prev-level 0)
6473 (loop repeat (/ (- cur-level 1) (org-level-increment))
6474 do (org-do-promote)))
6475 ;; If same level as prev, demote one.
6476 ((= prev-level cur-level)
6477 (org-do-demote))
6478 ;; If parent is top-level, promote to top level if not already.
6479 ((= prev-level 1)
6480 (loop repeat (/ (- cur-level 1) (org-level-increment))
6481 do (org-do-promote)))
6482 ;; If top-level, return to prev-level.
6483 ((= cur-level 1)
6484 (loop repeat (/ (- prev-level 1) (org-level-increment))
6485 do (org-do-demote)))
6486 ;; If less than prev-level, promote one.
6487 ((< cur-level prev-level)
6488 (org-do-promote))
6489 ;; If deeper than prev-level, promote until higher than
6490 ;; prev-level.
6491 ((> cur-level prev-level)
6492 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
6493 do (org-do-promote))))
6494 t))))
6496 (defun org-map-tree (fun)
6497 "Call FUN for every heading underneath the current one."
6498 (org-back-to-heading)
6499 (let ((level (funcall outline-level)))
6500 (save-excursion
6501 (funcall fun)
6502 (while (and (progn
6503 (outline-next-heading)
6504 (> (funcall outline-level) level))
6505 (not (eobp)))
6506 (funcall fun)))))
6508 (defun org-map-region (fun beg end)
6509 "Call FUN for every heading between BEG and END."
6510 (let ((org-ignore-region t))
6511 (save-excursion
6512 (setq end (copy-marker end))
6513 (goto-char beg)
6514 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6515 (< (point) end))
6516 (funcall fun))
6517 (while (and (progn
6518 (outline-next-heading)
6519 (< (point) end))
6520 (not (eobp)))
6521 (funcall fun)))))
6523 (defun org-fixup-indentation (diff)
6524 "Change the indentation in the current entry by DIFF
6525 However, if any line in the current entry has no indentation, or if it
6526 would end up with no indentation after the change, nothing at all is done."
6527 (save-excursion
6528 (let ((end (save-excursion (outline-next-heading)
6529 (point-marker)))
6530 (prohibit (if (> diff 0)
6531 "^\\S-"
6532 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6533 col)
6534 (unless (save-excursion (end-of-line 1)
6535 (re-search-forward prohibit end t))
6536 (while (and (< (point) end)
6537 (re-search-forward "^[ \t]+" end t))
6538 (goto-char (match-end 0))
6539 (setq col (current-column))
6540 (if (< diff 0) (replace-match ""))
6541 (org-indent-to-column (+ diff col))))
6542 (move-marker end nil))))
6544 (defun org-convert-to-odd-levels ()
6545 "Convert an org-mode file with all levels allowed to one with odd levels.
6546 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6547 level 5 etc."
6548 (interactive)
6549 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6550 (let ((outline-regexp org-outline-regexp)
6551 (outline-level 'org-outline-level)
6552 (org-odd-levels-only nil) n)
6553 (save-excursion
6554 (goto-char (point-min))
6555 (while (re-search-forward "^\\*\\*+ " nil t)
6556 (setq n (- (length (match-string 0)) 2))
6557 (while (>= (setq n (1- n)) 0)
6558 (org-demote))
6559 (end-of-line 1))))))
6561 (defun org-convert-to-oddeven-levels ()
6562 "Convert an org-mode file with only odd levels to one with odd and even levels.
6563 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6564 section with an even level, conversion would destroy the structure of the file. An error
6565 is signaled in this case."
6566 (interactive)
6567 (goto-char (point-min))
6568 ;; First check if there are no even levels
6569 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6570 (org-show-context t)
6571 (error "Not all levels are odd in this file. Conversion not possible"))
6572 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6573 (let ((outline-regexp org-outline-regexp)
6574 (outline-level 'org-outline-level)
6575 (org-odd-levels-only nil) n)
6576 (save-excursion
6577 (goto-char (point-min))
6578 (while (re-search-forward "^\\*\\*+ " nil t)
6579 (setq n (/ (1- (length (match-string 0))) 2))
6580 (while (>= (setq n (1- n)) 0)
6581 (org-promote))
6582 (end-of-line 1))))))
6584 (defun org-tr-level (n)
6585 "Make N odd if required."
6586 (if org-odd-levels-only (1+ (/ n 2)) n))
6588 ;;; Vertical tree motion, cutting and pasting of subtrees
6590 (defun org-move-subtree-up (&optional arg)
6591 "Move the current subtree up past ARG headlines of the same level."
6592 (interactive "p")
6593 (org-move-subtree-down (- (prefix-numeric-value arg))))
6595 (defun org-move-subtree-down (&optional arg)
6596 "Move the current subtree down past ARG headlines of the same level."
6597 (interactive "p")
6598 (setq arg (prefix-numeric-value arg))
6599 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
6600 'org-get-last-sibling))
6601 (ins-point (make-marker))
6602 (cnt (abs arg))
6603 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6604 ;; Select the tree
6605 (org-back-to-heading)
6606 (setq beg0 (point))
6607 (save-excursion
6608 (setq ne-beg (org-back-over-empty-lines))
6609 (setq beg (point)))
6610 (save-match-data
6611 (save-excursion (outline-end-of-heading)
6612 (setq folded (org-invisible-p)))
6613 (outline-end-of-subtree))
6614 (outline-next-heading)
6615 (setq ne-end (org-back-over-empty-lines))
6616 (setq end (point))
6617 (goto-char beg0)
6618 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6619 ;; include less whitespace
6620 (save-excursion
6621 (goto-char beg)
6622 (forward-line (- ne-beg ne-end))
6623 (setq beg (point))))
6624 ;; Find insertion point, with error handling
6625 (while (> cnt 0)
6626 (or (and (funcall movfunc) (looking-at outline-regexp))
6627 (progn (goto-char beg0)
6628 (error "Cannot move past superior level or buffer limit")))
6629 (setq cnt (1- cnt)))
6630 (if (> arg 0)
6631 ;; Moving forward - still need to move over subtree
6632 (progn (org-end-of-subtree t t)
6633 (save-excursion
6634 (org-back-over-empty-lines)
6635 (or (bolp) (newline)))))
6636 (setq ne-ins (org-back-over-empty-lines))
6637 (move-marker ins-point (point))
6638 (setq txt (buffer-substring beg end))
6639 (org-save-markers-in-region beg end)
6640 (delete-region beg end)
6641 (org-remove-empty-overlays-at beg)
6642 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6643 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6644 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6645 (let ((bbb (point)))
6646 (insert-before-markers txt)
6647 (org-reinstall-markers-in-region bbb)
6648 (move-marker ins-point bbb))
6649 (or (bolp) (insert "\n"))
6650 (setq ins-end (point))
6651 (goto-char ins-point)
6652 (org-skip-whitespace)
6653 (when (and (< arg 0)
6654 (org-first-sibling-p)
6655 (> ne-ins ne-beg))
6656 ;; Move whitespace back to beginning
6657 (save-excursion
6658 (goto-char ins-end)
6659 (let ((kill-whole-line t))
6660 (kill-line (- ne-ins ne-beg)) (point)))
6661 (insert (make-string (- ne-ins ne-beg) ?\n)))
6662 (move-marker ins-point nil)
6663 (if folded
6664 (hide-subtree)
6665 (org-show-entry)
6666 (show-children)
6667 (org-cycle-hide-drawers 'children))
6668 (org-clean-visibility-after-subtree-move)))
6670 (defvar org-subtree-clip ""
6671 "Clipboard for cut and paste of subtrees.
6672 This is actually only a copy of the kill, because we use the normal kill
6673 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6675 (defvar org-subtree-clip-folded nil
6676 "Was the last copied subtree folded?
6677 This is used to fold the tree back after pasting.")
6679 (defun org-cut-subtree (&optional n)
6680 "Cut the current subtree into the clipboard.
6681 With prefix arg N, cut this many sequential subtrees.
6682 This is a short-hand for marking the subtree and then cutting it."
6683 (interactive "p")
6684 (org-copy-subtree n 'cut))
6686 (defun org-copy-subtree (&optional n cut force-store-markers)
6687 "Cut the current subtree into the clipboard.
6688 With prefix arg N, cut this many sequential subtrees.
6689 This is a short-hand for marking the subtree and then copying it.
6690 If CUT is non-nil, actually cut the subtree.
6691 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6692 of some markers in the region, even if CUT is non-nil. This is
6693 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6694 (interactive "p")
6695 (let (beg end folded (beg0 (point)))
6696 (if (interactive-p)
6697 (org-back-to-heading nil) ; take what looks like a subtree
6698 (org-back-to-heading t)) ; take what is really there
6699 (org-back-over-empty-lines)
6700 (setq beg (point))
6701 (skip-chars-forward " \t\r\n")
6702 (save-match-data
6703 (save-excursion (outline-end-of-heading)
6704 (setq folded (org-invisible-p)))
6705 (condition-case nil
6706 (org-forward-same-level (1- n) t)
6707 (error nil))
6708 (org-end-of-subtree t t))
6709 (org-back-over-empty-lines)
6710 (setq end (point))
6711 (goto-char beg0)
6712 (when (> end beg)
6713 (setq org-subtree-clip-folded folded)
6714 (when (or cut force-store-markers)
6715 (org-save-markers-in-region beg end))
6716 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6717 (setq org-subtree-clip (current-kill 0))
6718 (message "%s: Subtree(s) with %d characters"
6719 (if cut "Cut" "Copied")
6720 (length org-subtree-clip)))))
6722 (defun org-paste-subtree (&optional level tree for-yank)
6723 "Paste the clipboard as a subtree, with modification of headline level.
6724 The entire subtree is promoted or demoted in order to match a new headline
6725 level.
6727 If the cursor is at the beginning of a headline, the same level as
6728 that headline is used to paste the tree
6730 If not, the new level is derived from the *visible* headings
6731 before and after the insertion point, and taken to be the inferior headline
6732 level of the two. So if the previous visible heading is level 3 and the
6733 next is level 4 (or vice versa), level 4 will be used for insertion.
6734 This makes sure that the subtree remains an independent subtree and does
6735 not swallow low level entries.
6737 You can also force a different level, either by using a numeric prefix
6738 argument, or by inserting the heading marker by hand. For example, if the
6739 cursor is after \"*****\", then the tree will be shifted to level 5.
6741 If optional TREE is given, use this text instead of the kill ring.
6743 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6744 move back over whitespace before inserting, and move point to the end of
6745 the inserted text when done."
6746 (interactive "P")
6747 (setq tree (or tree (and kill-ring (current-kill 0))))
6748 (unless (org-kill-is-subtree-p tree)
6749 (error "%s"
6750 (substitute-command-keys
6751 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6752 (let* ((visp (not (org-invisible-p)))
6753 (txt tree)
6754 (^re (concat "^\\(" outline-regexp "\\)"))
6755 (re (concat "\\(" outline-regexp "\\)"))
6756 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6758 (old-level (if (string-match ^re txt)
6759 (- (match-end 0) (match-beginning 0) 1)
6760 -1))
6761 (force-level (cond (level (prefix-numeric-value level))
6762 ((and (looking-at "[ \t]*$")
6763 (string-match
6764 ^re_ (buffer-substring
6765 (point-at-bol) (point))))
6766 (- (match-end 1) (match-beginning 1)))
6767 ((and (bolp)
6768 (looking-at org-outline-regexp))
6769 (- (match-end 0) (point) 1))
6770 (t nil)))
6771 (previous-level (save-excursion
6772 (condition-case nil
6773 (progn
6774 (outline-previous-visible-heading 1)
6775 (if (looking-at re)
6776 (- (match-end 0) (match-beginning 0) 1)
6778 (error 1))))
6779 (next-level (save-excursion
6780 (condition-case nil
6781 (progn
6782 (or (looking-at outline-regexp)
6783 (outline-next-visible-heading 1))
6784 (if (looking-at re)
6785 (- (match-end 0) (match-beginning 0) 1)
6787 (error 1))))
6788 (new-level (or force-level (max previous-level next-level)))
6789 (shift (if (or (= old-level -1)
6790 (= new-level -1)
6791 (= old-level new-level))
6793 (- new-level old-level)))
6794 (delta (if (> shift 0) -1 1))
6795 (func (if (> shift 0) 'org-demote 'org-promote))
6796 (org-odd-levels-only nil)
6797 beg end newend)
6798 ;; Remove the forced level indicator
6799 (if force-level
6800 (delete-region (point-at-bol) (point)))
6801 ;; Paste
6802 (beginning-of-line 1)
6803 (unless for-yank (org-back-over-empty-lines))
6804 (setq beg (point))
6805 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6806 (insert-before-markers txt)
6807 (unless (string-match "\n\\'" txt) (insert "\n"))
6808 (setq newend (point))
6809 (org-reinstall-markers-in-region beg)
6810 (setq end (point))
6811 (goto-char beg)
6812 (skip-chars-forward " \t\n\r")
6813 (setq beg (point))
6814 (if (and (org-invisible-p) visp)
6815 (save-excursion (outline-show-heading)))
6816 ;; Shift if necessary
6817 (unless (= shift 0)
6818 (save-restriction
6819 (narrow-to-region beg end)
6820 (while (not (= shift 0))
6821 (org-map-region func (point-min) (point-max))
6822 (setq shift (+ delta shift)))
6823 (goto-char (point-min))
6824 (setq newend (point-max))))
6825 (when (or (interactive-p) for-yank)
6826 (message "Clipboard pasted as level %d subtree" new-level))
6827 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6828 kill-ring
6829 (eq org-subtree-clip (current-kill 0))
6830 org-subtree-clip-folded)
6831 ;; The tree was folded before it was killed/copied
6832 (hide-subtree))
6833 (and for-yank (goto-char newend))))
6835 (defun org-kill-is-subtree-p (&optional txt)
6836 "Check if the current kill is an outline subtree, or a set of trees.
6837 Returns nil if kill does not start with a headline, or if the first
6838 headline level is not the largest headline level in the tree.
6839 So this will actually accept several entries of equal levels as well,
6840 which is OK for `org-paste-subtree'.
6841 If optional TXT is given, check this string instead of the current kill."
6842 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6843 (start-level (and kill
6844 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6845 org-outline-regexp "\\)")
6846 kill)
6847 (- (match-end 2) (match-beginning 2) 1)))
6848 (re (concat "^" org-outline-regexp))
6849 (start (1+ (or (match-beginning 2) -1))))
6850 (if (not start-level)
6851 (progn
6852 nil) ;; does not even start with a heading
6853 (catch 'exit
6854 (while (setq start (string-match re kill (1+ start)))
6855 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6856 (throw 'exit nil)))
6857 t))))
6859 (defvar org-markers-to-move nil
6860 "Markers that should be moved with a cut-and-paste operation.
6861 Those markers are stored together with their positions relative to
6862 the start of the region.")
6864 (defun org-save-markers-in-region (beg end)
6865 "Check markers in region.
6866 If these markers are between BEG and END, record their position relative
6867 to BEG, so that after moving the block of text, we can put the markers back
6868 into place.
6869 This function gets called just before an entry or tree gets cut from the
6870 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6871 called immediately, to move the markers with the entries."
6872 (setq org-markers-to-move nil)
6873 (when (featurep 'org-clock)
6874 (org-clock-save-markers-for-cut-and-paste beg end))
6875 (when (featurep 'org-agenda)
6876 (org-agenda-save-markers-for-cut-and-paste beg end)))
6878 (defun org-check-and-save-marker (marker beg end)
6879 "Check if MARKER is between BEG and END.
6880 If yes, remember the marker and the distance to BEG."
6881 (when (and (marker-buffer marker)
6882 (equal (marker-buffer marker) (current-buffer)))
6883 (if (and (>= marker beg) (< marker end))
6884 (push (cons marker (- marker beg)) org-markers-to-move))))
6886 (defun org-reinstall-markers-in-region (beg)
6887 "Move all remembered markers to their position relative to BEG."
6888 (mapc (lambda (x)
6889 (move-marker (car x) (+ beg (cdr x))))
6890 org-markers-to-move)
6891 (setq org-markers-to-move nil))
6893 (defun org-narrow-to-subtree ()
6894 "Narrow buffer to the current subtree."
6895 (interactive)
6896 (save-excursion
6897 (save-match-data
6898 (narrow-to-region
6899 (progn (org-back-to-heading t) (point))
6900 (progn (org-end-of-subtree t t)
6901 (if (org-on-heading-p) (backward-char 1))
6902 (point))))))
6904 (defun org-clone-subtree-with-time-shift (n &optional shift)
6905 "Clone the task (subtree) at point N times.
6906 The clones will be inserted as siblings.
6908 In interactive use, the user will be prompted for the number of clones
6909 to be produced, and for a time SHIFT, which may be a repeater as used
6910 in time stamps, for example `+3d'.
6912 When a valid repeater is given and the entry contains any time stamps,
6913 the clones will become a sequence in time, with time stamps in the
6914 subtree shifted for each clone produced. If SHIFT is nil or the
6915 empty string, time stamps will be left alone.
6917 If the original subtree did contain time stamps with a repeater,
6918 the following will happen:
6919 - the repeater will be removed in each clone
6920 - an additional clone will be produced, with the current, unshifted
6921 date(s) in the entry.
6922 - the original entry will be placed *after* all the clones, with
6923 repeater intact.
6924 - the start days in the repeater in the original entry will be shifted
6925 to past the last clone.
6926 I this way you can spell out a number of instances of a repeating task,
6927 and still retain the repeater to cover future instances of the task."
6928 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6929 (let (beg end template task
6930 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6931 (if (not (and (integerp n) (> n 0)))
6932 (error "Invalid number of replications %s" n))
6933 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6934 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6935 shift)))
6936 (error "Invalid shift specification %s" shift))
6937 (when doshift
6938 (setq shift-n (string-to-number (match-string 1 shift))
6939 shift-what (cdr (assoc (match-string 2 shift)
6940 '(("d" . day) ("w" . week)
6941 ("m" . month) ("y" . year))))))
6942 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6943 (setq nmin 1 nmax n)
6944 (org-back-to-heading t)
6945 (setq beg (point))
6946 (org-end-of-subtree t t)
6947 (or (bolp) (insert "\n"))
6948 (setq end (point))
6949 (setq template (buffer-substring beg end))
6950 (when (and doshift
6951 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6952 (delete-region beg end)
6953 (setq end beg)
6954 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6955 (goto-char end)
6956 (loop for n from nmin to nmax do
6957 (if (not doshift)
6958 (setq task template)
6959 (with-temp-buffer
6960 (insert template)
6961 (org-mode)
6962 (goto-char (point-min))
6963 (while (re-search-forward org-ts-regexp-both nil t)
6964 (org-timestamp-change (* n shift-n) shift-what))
6965 (unless (= n n-no-remove)
6966 (goto-char (point-min))
6967 (while (re-search-forward org-ts-regexp nil t)
6968 (save-excursion
6969 (goto-char (match-beginning 0))
6970 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6971 (delete-region (match-beginning 1) (match-end 1))))))
6972 (setq task (buffer-string))))
6973 (insert task))
6974 (goto-char beg)))
6976 ;;; Outline Sorting
6978 (defun org-sort (with-case)
6979 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6980 Optional argument WITH-CASE means sort case-sensitively.
6981 With a double prefix argument, also remove duplicate entries."
6982 (interactive "P")
6983 (if (org-at-table-p)
6984 (org-call-with-arg 'org-table-sort-lines with-case)
6985 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6987 (defun org-sort-remove-invisible (s)
6988 (remove-text-properties 0 (length s) org-rm-props s)
6989 (while (string-match org-bracket-link-regexp s)
6990 (setq s (replace-match (if (match-end 2)
6991 (match-string 3 s)
6992 (match-string 1 s)) t t s)))
6995 (defvar org-priority-regexp) ; defined later in the file
6997 (defvar org-after-sorting-entries-or-items-hook nil
6998 "Hook that is run after a bunch of entries or items have been sorted.
6999 When children are sorted, the cursor is in the parent line when this
7000 hook gets called. When a region or a plain list is sorted, the cursor
7001 will be in the first entry of the sorted region/list.")
7003 (defun org-sort-entries-or-items
7004 (&optional with-case sorting-type getkey-func compare-func property)
7005 "Sort entries on a certain level of an outline tree, or plain list items.
7006 If there is an active region, the entries in the region are sorted.
7007 Else, if the cursor is before the first entry, sort the top-level items.
7008 Else, the children of the entry at point are sorted.
7009 If the cursor is at the first item in a plain list, the list items will be
7010 sorted.
7012 Sorting can be alphabetically, numerically, by date/time as given by
7013 a time stamp, by a property or by priority.
7015 The command prompts for the sorting type unless it has been given to the
7016 function through the SORTING-TYPE argument, which needs to a character,
7017 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7018 precise meaning of each character:
7020 n Numerically, by converting the beginning of the entry/item to a number.
7021 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7022 t By date/time, either the first active time stamp in the entry, or, if
7023 none exist, by the first inactive one.
7024 In items, only the first line will be checked.
7025 s By the scheduled date/time.
7026 d By deadline date/time.
7027 c By creation time, which is assumed to be the first inactive time stamp
7028 at the beginning of a line.
7029 p By priority according to the cookie.
7030 r By the value of a property.
7032 Capital letters will reverse the sort order.
7034 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
7035 called with point at the beginning of the record. It must return either
7036 a string or a number that should serve as the sorting key for that record.
7038 Comparing entries ignores case by default. However, with an optional argument
7039 WITH-CASE, the sorting considers case as well."
7040 (interactive "P")
7041 (let ((case-func (if with-case 'identity 'downcase))
7042 start beg end stars re re2
7043 txt what tmp plain-list-p)
7044 ;; Find beginning and end of region to sort
7045 (cond
7046 ((org-region-active-p)
7047 ;; we will sort the region
7048 (setq end (region-end)
7049 what "region")
7050 (goto-char (region-beginning))
7051 (if (not (org-on-heading-p)) (outline-next-heading))
7052 (setq start (point)))
7053 ((org-at-item-p)
7054 ;; we will sort this plain list
7055 (org-beginning-of-item-list) (setq start (point))
7056 (org-end-of-item-list)
7057 (or (bolp) (insert "\n"))
7058 (setq end (point))
7059 (goto-char start)
7060 (setq plain-list-p t
7061 what "plain list"))
7062 ((or (org-on-heading-p)
7063 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
7064 ;; we will sort the children of the current headline
7065 (org-back-to-heading)
7066 (setq start (point)
7067 end (progn (org-end-of-subtree t t)
7068 (or (bolp) (insert "\n"))
7069 (org-back-over-empty-lines)
7070 (point))
7071 what "children")
7072 (goto-char start)
7073 (show-subtree)
7074 (outline-next-heading))
7076 ;; we will sort the top-level entries in this file
7077 (goto-char (point-min))
7078 (or (org-on-heading-p) (outline-next-heading))
7079 (setq start (point))
7080 (goto-char (point-max))
7081 (beginning-of-line 1)
7082 (when (looking-at ".*?\\S-")
7083 ;; File ends in a non-white line
7084 (end-of-line 1)
7085 (insert "\n"))
7086 (setq end (point-max))
7087 (setq what "top-level")
7088 (goto-char start)
7089 (show-all)))
7091 (setq beg (point))
7092 (if (>= beg end) (error "Nothing to sort"))
7094 (unless plain-list-p
7095 (looking-at "\\(\\*+\\)")
7096 (setq stars (match-string 1)
7097 re (concat "^" (regexp-quote stars) " +")
7098 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
7099 txt (buffer-substring beg end))
7100 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7101 (if (and (not (equal stars "*")) (string-match re2 txt))
7102 (error "Region to sort contains a level above the first entry")))
7104 (unless sorting-type
7105 (message
7106 (if plain-list-p
7107 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
7108 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7109 [t]ime [s]cheduled [d]eadline [c]reated
7110 A/N/T/S/D/C/P/O/F means reversed:")
7111 what)
7112 (setq sorting-type (read-char-exclusive))
7114 (and (= (downcase sorting-type) ?f)
7115 (setq getkey-func
7116 (org-icompleting-read "Sort using function: "
7117 obarray 'fboundp t nil nil))
7118 (setq getkey-func (intern getkey-func)))
7120 (and (= (downcase sorting-type) ?r)
7121 (setq property
7122 (org-icompleting-read "Property: "
7123 (mapcar 'list (org-buffer-property-keys t))
7124 nil t))))
7126 (message "Sorting entries...")
7128 (save-restriction
7129 (narrow-to-region start end)
7131 (let ((dcst (downcase sorting-type))
7132 (case-fold-search nil)
7133 (now (current-time)))
7134 (sort-subr
7135 (/= dcst sorting-type)
7136 ;; This function moves to the beginning character of the "record" to
7137 ;; be sorted.
7138 (if plain-list-p
7139 (lambda nil
7140 (if (org-at-item-p) t (goto-char (point-max))))
7141 (lambda nil
7142 (if (re-search-forward re nil t)
7143 (goto-char (match-beginning 0))
7144 (goto-char (point-max)))))
7145 ;; This function moves to the last character of the "record" being
7146 ;; sorted.
7147 (if plain-list-p
7148 'org-end-of-item
7149 (lambda nil
7150 (save-match-data
7151 (condition-case nil
7152 (outline-forward-same-level 1)
7153 (error
7154 (goto-char (point-max)))))))
7156 ;; This function returns the value that gets sorted against.
7157 (if plain-list-p
7158 (lambda nil
7159 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7160 (cond
7161 ((= dcst ?n)
7162 (string-to-number (buffer-substring (match-end 0)
7163 (point-at-eol))))
7164 ((= dcst ?a)
7165 (buffer-substring (match-end 0) (point-at-eol)))
7166 ((= dcst ?t)
7167 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
7168 (re-search-forward org-ts-regexp-both
7169 (point-at-eol) t))
7170 (org-time-string-to-seconds (match-string 0))
7171 (org-float-time now)))
7172 ((= dcst ?f)
7173 (if getkey-func
7174 (progn
7175 (setq tmp (funcall getkey-func))
7176 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7177 tmp)
7178 (error "Invalid key function `%s'" getkey-func)))
7179 (t (error "Invalid sorting type `%c'" sorting-type)))))
7180 (lambda nil
7181 (cond
7182 ((= dcst ?n)
7183 (if (looking-at org-complex-heading-regexp)
7184 (string-to-number (match-string 4))
7185 nil))
7186 ((= dcst ?a)
7187 (if (looking-at org-complex-heading-regexp)
7188 (funcall case-func (match-string 4))
7189 nil))
7190 ((= dcst ?t)
7191 (let ((end (save-excursion (outline-next-heading) (point))))
7192 (if (or (re-search-forward org-ts-regexp end t)
7193 (re-search-forward org-ts-regexp-both end t))
7194 (org-time-string-to-seconds (match-string 0))
7195 (org-float-time now))))
7196 ((= dcst ?c)
7197 (let ((end (save-excursion (outline-next-heading) (point))))
7198 (if (re-search-forward
7199 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7200 end t)
7201 (org-time-string-to-seconds (match-string 0))
7202 (org-float-time now))))
7203 ((= dcst ?s)
7204 (let ((end (save-excursion (outline-next-heading) (point))))
7205 (if (re-search-forward org-scheduled-time-regexp end t)
7206 (org-time-string-to-seconds (match-string 1))
7207 (org-float-time now))))
7208 ((= dcst ?d)
7209 (let ((end (save-excursion (outline-next-heading) (point))))
7210 (if (re-search-forward org-deadline-time-regexp end t)
7211 (org-time-string-to-seconds (match-string 1))
7212 (org-float-time now))))
7213 ((= dcst ?p)
7214 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7215 (string-to-char (match-string 2))
7216 org-default-priority))
7217 ((= dcst ?r)
7218 (or (org-entry-get nil property) ""))
7219 ((= dcst ?o)
7220 (if (looking-at org-complex-heading-regexp)
7221 (- 9999 (length (member (match-string 2)
7222 org-todo-keywords-1)))))
7223 ((= dcst ?f)
7224 (if getkey-func
7225 (progn
7226 (setq tmp (funcall getkey-func))
7227 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7228 tmp)
7229 (error "Invalid key function `%s'" getkey-func)))
7230 (t (error "Invalid sorting type `%c'" sorting-type)))))
7232 (cond
7233 ((= dcst ?a) 'string<)
7234 ((= dcst ?f) compare-func)
7235 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7236 (t nil)))))
7237 (run-hooks 'org-after-sorting-entries-or-items-hook)
7238 (message "Sorting entries...done")))
7240 (defun org-do-sort (table what &optional with-case sorting-type)
7241 "Sort TABLE of WHAT according to SORTING-TYPE.
7242 The user will be prompted for the SORTING-TYPE if the call to this
7243 function does not specify it. WHAT is only for the prompt, to indicate
7244 what is being sorted. The sorting key will be extracted from
7245 the car of the elements of the table.
7246 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7247 (unless sorting-type
7248 (message
7249 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7250 what)
7251 (setq sorting-type (read-char-exclusive)))
7252 (let ((dcst (downcase sorting-type))
7253 extractfun comparefun)
7254 ;; Define the appropriate functions
7255 (cond
7256 ((= dcst ?n)
7257 (setq extractfun 'string-to-number
7258 comparefun (if (= dcst sorting-type) '< '>)))
7259 ((= dcst ?a)
7260 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7261 (lambda(x) (downcase (org-sort-remove-invisible x))))
7262 comparefun (if (= dcst sorting-type)
7263 'string<
7264 (lambda (a b) (and (not (string< a b))
7265 (not (string= a b)))))))
7266 ((= dcst ?t)
7267 (setq extractfun
7268 (lambda (x)
7269 (if (or (string-match org-ts-regexp x)
7270 (string-match org-ts-regexp-both x))
7271 (org-float-time
7272 (org-time-string-to-time (match-string 0 x)))
7274 comparefun (if (= dcst sorting-type) '< '>)))
7275 (t (error "Invalid sorting type `%c'" sorting-type)))
7277 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7278 table)
7279 (lambda (a b) (funcall comparefun (car a) (car b))))))
7282 ;;; The orgstruct minor mode
7284 ;; Define a minor mode which can be used in other modes in order to
7285 ;; integrate the org-mode structure editing commands.
7287 ;; This is really a hack, because the org-mode structure commands use
7288 ;; keys which normally belong to the major mode. Here is how it
7289 ;; works: The minor mode defines all the keys necessary to operate the
7290 ;; structure commands, but wraps the commands into a function which
7291 ;; tests if the cursor is currently at a headline or a plain list
7292 ;; item. If that is the case, the structure command is used,
7293 ;; temporarily setting many Org-mode variables like regular
7294 ;; expressions for filling etc. However, when any of those keys is
7295 ;; used at a different location, function uses `key-binding' to look
7296 ;; up if the key has an associated command in another currently active
7297 ;; keymap (minor modes, major mode, global), and executes that
7298 ;; command. There might be problems if any of the keys is otherwise
7299 ;; used as a prefix key.
7301 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7302 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7303 ;; addresses this by checking explicitly for both bindings.
7305 (defvar orgstruct-mode-map (make-sparse-keymap)
7306 "Keymap for the minor `orgstruct-mode'.")
7308 (defvar org-local-vars nil
7309 "List of local variables, for use by `orgstruct-mode'")
7311 ;;;###autoload
7312 (define-minor-mode orgstruct-mode
7313 "Toggle the minor more `orgstruct-mode'.
7314 This mode is for using Org-mode structure commands in other modes.
7315 The following key behave as if Org-mode was active, if the cursor
7316 is on a headline, or on a plain list item (both in the definition
7317 of Org-mode).
7319 M-up Move entry/item up
7320 M-down Move entry/item down
7321 M-left Promote
7322 M-right Demote
7323 M-S-up Move entry/item up
7324 M-S-down Move entry/item down
7325 M-S-left Promote subtree
7326 M-S-right Demote subtree
7327 M-q Fill paragraph and items like in Org-mode
7328 C-c ^ Sort entries
7329 C-c - Cycle list bullet
7330 TAB Cycle item visibility
7331 M-RET Insert new heading/item
7332 S-M-RET Insert new TODO heading / Checkbox item
7333 C-c C-c Set tags / toggle checkbox"
7334 nil " OrgStruct" nil
7335 (org-load-modules-maybe)
7336 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7338 ;;;###autoload
7339 (defun turn-on-orgstruct ()
7340 "Unconditionally turn on `orgstruct-mode'."
7341 (orgstruct-mode 1))
7343 (defun orgstruct++-mode (&optional arg)
7344 "Toggle `orgstruct-mode', the enhanced version of it.
7345 In addition to setting orgstruct-mode, this also exports all indentation
7346 and autofilling variables from org-mode into the buffer. It will also
7347 recognize item context in multiline items.
7348 Note that turning off orgstruct-mode will *not* remove the
7349 indentation/paragraph settings. This can only be done by refreshing the
7350 major mode, for example with \\[normal-mode]."
7351 (interactive "P")
7352 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7353 (if (< arg 1)
7354 (orgstruct-mode -1)
7355 (orgstruct-mode 1)
7356 (let (var val)
7357 (mapc
7358 (lambda (x)
7359 (when (string-match
7360 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7361 (symbol-name (car x)))
7362 (setq var (car x) val (nth 1 x))
7363 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7364 org-local-vars)
7365 (org-set-local 'orgstruct-is-++ t))))
7367 (defvar orgstruct-is-++ nil
7368 "Is orgstruct-mode in ++ version in the current-buffer?")
7369 (make-variable-buffer-local 'orgstruct-is-++)
7371 ;;;###autoload
7372 (defun turn-on-orgstruct++ ()
7373 "Unconditionally turn on `orgstruct++-mode'."
7374 (orgstruct++-mode 1))
7376 (defun orgstruct-error ()
7377 "Error when there is no default binding for a structure key."
7378 (interactive)
7379 (error "This key has no function outside structure elements"))
7381 (defun orgstruct-setup ()
7382 "Setup orgstruct keymaps."
7383 (let ((nfunc 0)
7384 (bindings
7385 (list
7386 '([(meta up)] org-metaup)
7387 '([(meta down)] org-metadown)
7388 '([(meta left)] org-metaleft)
7389 '([(meta right)] org-metaright)
7390 '([(meta shift up)] org-shiftmetaup)
7391 '([(meta shift down)] org-shiftmetadown)
7392 '([(meta shift left)] org-shiftmetaleft)
7393 '([(meta shift right)] org-shiftmetaright)
7394 '([?\e (up)] org-metaup)
7395 '([?\e (down)] org-metadown)
7396 '([?\e (left)] org-metaleft)
7397 '([?\e (right)] org-metaright)
7398 '([?\e (shift up)] org-shiftmetaup)
7399 '([?\e (shift down)] org-shiftmetadown)
7400 '([?\e (shift left)] org-shiftmetaleft)
7401 '([?\e (shift right)] org-shiftmetaright)
7402 '([(shift up)] org-shiftup)
7403 '([(shift down)] org-shiftdown)
7404 '([(shift left)] org-shiftleft)
7405 '([(shift right)] org-shiftright)
7406 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7407 '("\M-q" fill-paragraph)
7408 '("\C-c^" org-sort)
7409 '("\C-c-" org-cycle-list-bullet)))
7410 elt key fun cmd)
7411 (while (setq elt (pop bindings))
7412 (setq nfunc (1+ nfunc))
7413 (setq key (org-key (car elt))
7414 fun (nth 1 elt)
7415 cmd (orgstruct-make-binding fun nfunc key))
7416 (org-defkey orgstruct-mode-map key cmd))
7418 ;; Special treatment needed for TAB and RET
7419 (org-defkey orgstruct-mode-map [(tab)]
7420 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7421 (org-defkey orgstruct-mode-map "\C-i"
7422 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7424 (org-defkey orgstruct-mode-map "\M-\C-m"
7425 (orgstruct-make-binding 'org-insert-heading 105
7426 "\M-\C-m" [(meta return)]))
7427 (org-defkey orgstruct-mode-map [(meta return)]
7428 (orgstruct-make-binding 'org-insert-heading 106
7429 [(meta return)] "\M-\C-m"))
7431 (org-defkey orgstruct-mode-map [(shift meta return)]
7432 (orgstruct-make-binding 'org-insert-todo-heading 107
7433 [(meta return)] "\M-\C-m"))
7435 (org-defkey orgstruct-mode-map "\e\C-m"
7436 (orgstruct-make-binding 'org-insert-heading 108
7437 "\e\C-m" [?\e (return)]))
7438 (org-defkey orgstruct-mode-map [?\e (return)]
7439 (orgstruct-make-binding 'org-insert-heading 109
7440 [?\e (return)] "\e\C-m"))
7441 (org-defkey orgstruct-mode-map [?\e (shift return)]
7442 (orgstruct-make-binding 'org-insert-todo-heading 110
7443 [?\e (return)] "\e\C-m"))
7445 (unless org-local-vars
7446 (setq org-local-vars (org-get-local-variables)))
7450 (defun orgstruct-make-binding (fun n &rest keys)
7451 "Create a function for binding in the structure minor mode.
7452 FUN is the command to call inside a table. N is used to create a unique
7453 command name. KEYS are keys that should be checked in for a command
7454 to execute outside of tables."
7455 (eval
7456 (list 'defun
7457 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7458 '(arg)
7459 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7460 "Outside of structure, run the binding of `"
7461 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7462 "'.")
7463 '(interactive "p")
7464 (list 'if
7465 `(org-context-p 'headline 'item
7466 (and orgstruct-is-++
7467 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7468 'item-body))
7469 (list 'org-run-like-in-org-mode (list 'quote fun))
7470 (list 'let '(orgstruct-mode)
7471 (list 'call-interactively
7472 (append '(or)
7473 (mapcar (lambda (k)
7474 (list 'key-binding k))
7475 keys)
7476 '('orgstruct-error))))))))
7478 (defun org-context-p (&rest contexts)
7479 "Check if local context is any of CONTEXTS.
7480 Possible values in the list of contexts are `table', `headline', and `item'."
7481 (let ((pos (point)))
7482 (goto-char (point-at-bol))
7483 (prog1 (or (and (memq 'table contexts)
7484 (looking-at "[ \t]*|"))
7485 (and (memq 'headline contexts)
7486 ;;????????? (looking-at "\\*+"))
7487 (looking-at outline-regexp))
7488 (and (memq 'item contexts)
7489 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7490 (and (memq 'item-body contexts)
7491 (org-in-item-p)))
7492 (goto-char pos))))
7494 (defun org-get-local-variables ()
7495 "Return a list of all local variables in an org-mode buffer."
7496 (let (varlist)
7497 (with-current-buffer (get-buffer-create "*Org tmp*")
7498 (erase-buffer)
7499 (org-mode)
7500 (setq varlist (buffer-local-variables)))
7501 (kill-buffer "*Org tmp*")
7502 (delq nil
7503 (mapcar
7504 (lambda (x)
7505 (setq x
7506 (if (symbolp x)
7507 (list x)
7508 (list (car x) (list 'quote (cdr x)))))
7509 (if (string-match
7510 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7511 (symbol-name (car x)))
7512 x nil))
7513 varlist))))
7515 ;;;###autoload
7516 (defun org-run-like-in-org-mode (cmd)
7517 "Run a command, pretending that the current buffer is in Org-mode.
7518 This will temporarily bind local variables that are typically bound in
7519 Org-mode to the values they have in Org-mode, and then interactively
7520 call CMD."
7521 (org-load-modules-maybe)
7522 (unless org-local-vars
7523 (setq org-local-vars (org-get-local-variables)))
7524 (eval (list 'let org-local-vars
7525 (list 'call-interactively (list 'quote cmd)))))
7527 ;;;; Archiving
7529 (defun org-get-category (&optional pos)
7530 "Get the category applying to position POS."
7531 (get-text-property (or pos (point)) 'org-category))
7533 (defun org-refresh-category-properties ()
7534 "Refresh category text properties in the buffer."
7535 (let ((def-cat (cond
7536 ((null org-category)
7537 (if buffer-file-name
7538 (file-name-sans-extension
7539 (file-name-nondirectory buffer-file-name))
7540 "???"))
7541 ((symbolp org-category) (symbol-name org-category))
7542 (t org-category)))
7543 beg end cat pos optionp)
7544 (org-unmodified
7545 (save-excursion
7546 (save-restriction
7547 (widen)
7548 (goto-char (point-min))
7549 (put-text-property (point) (point-max) 'org-category def-cat)
7550 (while (re-search-forward
7551 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7552 (setq pos (match-end 0)
7553 optionp (equal (char-after (match-beginning 0)) ?#)
7554 cat (org-trim (match-string 2)))
7555 (if optionp
7556 (setq beg (point-at-bol) end (point-max))
7557 (org-back-to-heading t)
7558 (setq beg (point) end (org-end-of-subtree t t)))
7559 (put-text-property beg end 'org-category cat)
7560 (goto-char pos)))))))
7563 ;;;; Link Stuff
7565 ;;; Link abbreviations
7567 (defun org-link-expand-abbrev (link)
7568 "Apply replacements as defined in `org-link-abbrev-alist."
7569 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7570 (let* ((key (match-string 1 link))
7571 (as (or (assoc key org-link-abbrev-alist-local)
7572 (assoc key org-link-abbrev-alist)))
7573 (tag (and (match-end 2) (match-string 3 link)))
7574 rpl)
7575 (if (not as)
7576 link
7577 (setq rpl (cdr as))
7578 (cond
7579 ((symbolp rpl) (funcall rpl tag))
7580 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7581 ((string-match "%h" rpl)
7582 (replace-match (url-hexify-string (or tag "")) t t rpl))
7583 (t (concat rpl tag)))))
7584 link))
7586 ;;; Storing and inserting links
7588 (defvar org-insert-link-history nil
7589 "Minibuffer history for links inserted with `org-insert-link'.")
7591 (defvar org-stored-links nil
7592 "Contains the links stored with `org-store-link'.")
7594 (defvar org-store-link-plist nil
7595 "Plist with info about the most recently link created with `org-store-link'.")
7597 (defvar org-link-protocols nil
7598 "Link protocols added to Org-mode using `org-add-link-type'.")
7600 (defvar org-store-link-functions nil
7601 "List of functions that are called to create and store a link.
7602 Each function will be called in turn until one returns a non-nil
7603 value. Each function should check if it is responsible for creating
7604 this link (for example by looking at the major mode).
7605 If not, it must exit and return nil.
7606 If yes, it should return a non-nil value after a calling
7607 `org-store-link-props' with a list of properties and values.
7608 Special properties are:
7610 :type The link prefix. like \"http\". This must be given.
7611 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7612 This is obligatory as well.
7613 :description Optional default description for the second pair
7614 of brackets in an Org-mode link. The user can still change
7615 this when inserting this link into an Org-mode buffer.
7617 In addition to these, any additional properties can be specified
7618 and then used in remember templates.")
7620 (defun org-add-link-type (type &optional follow export)
7621 "Add TYPE to the list of `org-link-types'.
7622 Re-compute all regular expressions depending on `org-link-types'
7624 FOLLOW and EXPORT are two functions.
7626 FOLLOW should take the link path as the single argument and do whatever
7627 is necessary to follow the link, for example find a file or display
7628 a mail message.
7630 EXPORT should format the link path for export to one of the export formats.
7631 It should be a function accepting three arguments:
7633 path the path of the link, the text after the prefix (like \"http:\")
7634 desc the description of the link, if any, nil if there was no description
7635 format the export format, a symbol like `html' or `latex'.
7637 The function may use the FORMAT information to return different values
7638 depending on the format. The return value will be put literally into
7639 the exported file.
7640 Org-mode has a built-in default for exporting links. If you are happy with
7641 this default, there is no need to define an export function for the link
7642 type. For a simple example of an export function, see `org-bbdb.el'."
7643 (add-to-list 'org-link-types type t)
7644 (org-make-link-regexps)
7645 (if (assoc type org-link-protocols)
7646 (setcdr (assoc type org-link-protocols) (list follow export))
7647 (push (list type follow export) org-link-protocols)))
7649 (defvar org-agenda-buffer-name)
7651 ;;;###autoload
7652 (defun org-store-link (arg)
7653 "\\<org-mode-map>Store an org-link to the current location.
7654 This link is added to `org-stored-links' and can later be inserted
7655 into an org-buffer with \\[org-insert-link].
7657 For some link types, a prefix arg is interpreted:
7658 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7659 For file links, arg negates `org-context-in-file-links'."
7660 (interactive "P")
7661 (org-load-modules-maybe)
7662 (setq org-store-link-plist nil) ; reset
7663 (let ((outline-regexp (org-get-limited-outline-regexp))
7664 link cpltxt desc description search txt custom-id)
7665 (cond
7667 ((run-hook-with-args-until-success 'org-store-link-functions)
7668 (setq link (plist-get org-store-link-plist :link)
7669 desc (or (plist-get org-store-link-plist :description) link)))
7671 ((equal (buffer-name) "*Org Edit Src Example*")
7672 (let (label gc)
7673 (while (or (not label)
7674 (save-excursion
7675 (save-restriction
7676 (widen)
7677 (goto-char (point-min))
7678 (re-search-forward
7679 (regexp-quote (format org-coderef-label-format label))
7680 nil t))))
7681 (when label (message "Label exists already") (sit-for 2))
7682 (setq label (read-string "Code line label: " label)))
7683 (end-of-line 1)
7684 (setq link (format org-coderef-label-format label))
7685 (setq gc (- 79 (length link)))
7686 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7687 (insert link)
7688 (setq link (concat "(" label ")") desc nil)))
7690 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
7691 ;; We are in the agenda, link to referenced location
7692 (let ((m (or (get-text-property (point) 'org-hd-marker)
7693 (get-text-property (point) 'org-marker))))
7694 (when m
7695 (org-with-point-at m
7696 (call-interactively 'org-store-link)))))
7698 ((eq major-mode 'calendar-mode)
7699 (let ((cd (calendar-cursor-to-date)))
7700 (setq link
7701 (format-time-string
7702 (car org-time-stamp-formats)
7703 (apply 'encode-time
7704 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7705 nil nil nil))))
7706 (org-store-link-props :type "calendar" :date cd)))
7708 ((eq major-mode 'w3-mode)
7709 (setq cpltxt (if (and (buffer-name)
7710 (not (string-match "Untitled" (buffer-name))))
7711 (buffer-name)
7712 (url-view-url t))
7713 link (org-make-link (url-view-url t)))
7714 (org-store-link-props :type "w3" :url (url-view-url t)))
7716 ((eq major-mode 'w3m-mode)
7717 (setq cpltxt (or w3m-current-title w3m-current-url)
7718 link (org-make-link w3m-current-url))
7719 (org-store-link-props :type "w3m" :url (url-view-url t)))
7721 ((setq search (run-hook-with-args-until-success
7722 'org-create-file-search-functions))
7723 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7724 "::" search))
7725 (setq cpltxt (or description link)))
7727 ((eq major-mode 'image-mode)
7728 (setq cpltxt (concat "file:"
7729 (abbreviate-file-name buffer-file-name))
7730 link (org-make-link cpltxt))
7731 (org-store-link-props :type "image" :file buffer-file-name))
7733 ((eq major-mode 'dired-mode)
7734 ;; link to the file in the current line
7735 (let ((file (dired-get-filename nil t)))
7736 (setq file (if file
7737 (abbreviate-file-name
7738 (expand-file-name (dired-get-filename nil t)))
7739 ;; otherwise, no file so use current directory.
7740 default-directory))
7741 (setq cpltxt (concat "file:" file)
7742 link (org-make-link cpltxt))))
7744 ((and buffer-file-name (org-mode-p))
7745 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7746 (cond
7747 ((org-in-regexp "<<\\(.*?\\)>>")
7748 (setq cpltxt
7749 (concat "file:"
7750 (abbreviate-file-name buffer-file-name)
7751 "::" (match-string 1))
7752 link (org-make-link cpltxt)))
7753 ((and (featurep 'org-id)
7754 (or (eq org-link-to-org-use-id t)
7755 (and (eq org-link-to-org-use-id 'create-if-interactive)
7756 (interactive-p))
7757 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7758 (interactive-p)
7759 (not custom-id))
7760 (and org-link-to-org-use-id
7761 (condition-case nil
7762 (org-entry-get nil "ID")
7763 (error nil)))))
7764 ;; We can make a link using the ID.
7765 (setq link (condition-case nil
7766 (prog1 (org-id-store-link)
7767 (setq desc (plist-get org-store-link-plist
7768 :description)))
7769 (error
7770 ;; probably before first headline, link to file only
7771 (concat "file:"
7772 (abbreviate-file-name buffer-file-name))))))
7774 ;; Just link to current headline
7775 (setq cpltxt (concat "file:"
7776 (abbreviate-file-name buffer-file-name)))
7777 ;; Add a context search string
7778 (when (org-xor org-context-in-file-links arg)
7779 (setq txt (cond
7780 ((org-on-heading-p) nil)
7781 ((org-region-active-p)
7782 (buffer-substring (region-beginning) (region-end)))
7783 (t nil)))
7784 (when (or (null txt) (string-match "\\S-" txt))
7785 (setq cpltxt
7786 (concat cpltxt "::"
7787 (condition-case nil
7788 (org-make-org-heading-search-string txt)
7789 (error "")))
7790 desc (or (nth 4 (ignore-errors
7791 (org-heading-components))) "NONE"))))
7792 (if (string-match "::\\'" cpltxt)
7793 (setq cpltxt (substring cpltxt 0 -2)))
7794 (setq link (org-make-link cpltxt)))))
7796 ((buffer-file-name (buffer-base-buffer))
7797 ;; Just link to this file here.
7798 (setq cpltxt (concat "file:"
7799 (abbreviate-file-name
7800 (buffer-file-name (buffer-base-buffer)))))
7801 ;; Add a context string
7802 (when (org-xor org-context-in-file-links arg)
7803 (setq txt (if (org-region-active-p)
7804 (buffer-substring (region-beginning) (region-end))
7805 (buffer-substring (point-at-bol) (point-at-eol))))
7806 ;; Only use search option if there is some text.
7807 (when (string-match "\\S-" txt)
7808 (setq cpltxt
7809 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7810 desc "NONE")))
7811 (setq link (org-make-link cpltxt)))
7813 ((interactive-p)
7814 (error "Cannot link to a buffer which is not visiting a file"))
7816 (t (setq link nil)))
7818 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7819 (setq link (or link cpltxt)
7820 desc (or desc cpltxt))
7821 (if (equal desc "NONE") (setq desc nil))
7823 (if (and (or (interactive-p) executing-kbd-macro) link)
7824 (progn
7825 (setq org-stored-links
7826 (cons (list link desc) org-stored-links))
7827 (message "Stored: %s" (or desc link))
7828 (when custom-id
7829 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7830 "::#" custom-id))
7831 (setq org-stored-links
7832 (cons (list link desc) org-stored-links))))
7833 (and link (org-make-link-string link desc)))))
7835 (defun org-store-link-props (&rest plist)
7836 "Store link properties, extract names and addresses."
7837 (let (x adr)
7838 (when (setq x (plist-get plist :from))
7839 (setq adr (mail-extract-address-components x))
7840 (setq plist (plist-put plist :fromname (car adr)))
7841 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7842 (when (setq x (plist-get plist :to))
7843 (setq adr (mail-extract-address-components x))
7844 (setq plist (plist-put plist :toname (car adr)))
7845 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7846 (let ((from (plist-get plist :from))
7847 (to (plist-get plist :to)))
7848 (when (and from to org-from-is-user-regexp)
7849 (setq plist
7850 (plist-put plist :fromto
7851 (if (string-match org-from-is-user-regexp from)
7852 (concat "to %t")
7853 (concat "from %f"))))))
7854 (setq org-store-link-plist plist))
7856 (defun org-add-link-props (&rest plist)
7857 "Add these properties to the link property list."
7858 (let (key value)
7859 (while plist
7860 (setq key (pop plist) value (pop plist))
7861 (setq org-store-link-plist
7862 (plist-put org-store-link-plist key value)))))
7864 (defun org-email-link-description (&optional fmt)
7865 "Return the description part of an email link.
7866 This takes information from `org-store-link-plist' and formats it
7867 according to FMT (default from `org-email-link-description-format')."
7868 (setq fmt (or fmt org-email-link-description-format))
7869 (let* ((p org-store-link-plist)
7870 (to (plist-get p :toaddress))
7871 (from (plist-get p :fromaddress))
7872 (table
7873 (list
7874 (cons "%c" (plist-get p :fromto))
7875 (cons "%F" (plist-get p :from))
7876 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7877 (cons "%T" (plist-get p :to))
7878 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7879 (cons "%s" (plist-get p :subject))
7880 (cons "%m" (plist-get p :message-id)))))
7881 (when (string-match "%c" fmt)
7882 ;; Check if the user wrote this message
7883 (if (and org-from-is-user-regexp from to
7884 (save-match-data (string-match org-from-is-user-regexp from)))
7885 (setq fmt (replace-match "to %t" t t fmt))
7886 (setq fmt (replace-match "from %f" t t fmt))))
7887 (org-replace-escapes fmt table)))
7889 (defun org-make-org-heading-search-string (&optional string heading)
7890 "Make search string for STRING or current headline."
7891 (interactive)
7892 (let ((s (or string (org-get-heading))))
7893 (unless (and string (not heading))
7894 ;; We are using a headline, clean up garbage in there.
7895 (if (string-match org-todo-regexp s)
7896 (setq s (replace-match "" t t s)))
7897 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7898 (setq s (replace-match "" t t s)))
7899 (setq s (org-trim s))
7900 (if (string-match (concat "^\\(" org-quote-string "\\|"
7901 org-comment-string "\\)") s)
7902 (setq s (replace-match "" t t s)))
7903 (while (string-match org-ts-regexp s)
7904 (setq s (replace-match "" t t s))))
7905 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7906 (setq s (replace-match " " t t s)))
7907 (or string (setq s (concat "*" s))) ; Add * for headlines
7908 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7910 (defun org-make-link (&rest strings)
7911 "Concatenate STRINGS."
7912 (apply 'concat strings))
7914 (defun org-make-link-string (link &optional description)
7915 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7916 (unless (string-match "\\S-" link)
7917 (error "Empty link"))
7918 (when (and description
7919 (stringp description)
7920 (not (string-match "\\S-" description)))
7921 (setq description nil))
7922 (when (stringp description)
7923 ;; Remove brackets from the description, they are fatal.
7924 (while (string-match "\\[" description)
7925 (setq description (replace-match "{" t t description)))
7926 (while (string-match "\\]" description)
7927 (setq description (replace-match "}" t t description))))
7928 (when (equal (org-link-escape link) description)
7929 ;; No description needed, it is identical
7930 (setq description nil))
7931 (when (and (not description)
7932 (not (equal link (org-link-escape link))))
7933 (setq description (org-extract-attributes link)))
7934 (concat "[[" (org-link-escape link) "]"
7935 (if description (concat "[" description "]") "")
7936 "]"))
7938 (defconst org-link-escape-chars
7939 '((?\ . "%20")
7940 (?\[ . "%5B")
7941 (?\] . "%5D")
7942 (?\340 . "%E0") ; `a
7943 (?\342 . "%E2") ; ^a
7944 (?\347 . "%E7") ; ,c
7945 (?\350 . "%E8") ; `e
7946 (?\351 . "%E9") ; 'e
7947 (?\352 . "%EA") ; ^e
7948 (?\356 . "%EE") ; ^i
7949 (?\364 . "%F4") ; ^o
7950 (?\371 . "%F9") ; `u
7951 (?\373 . "%FB") ; ^u
7952 (?\; . "%3B")
7953 ;; (?? . "%3F")
7954 (?= . "%3D")
7955 (?+ . "%2B")
7957 "Association list of escapes for some characters problematic in links.
7958 This is the list that is used for internal purposes.")
7960 (defvar org-url-encoding-use-url-hexify nil)
7962 (defconst org-link-escape-chars-browser
7963 '((?\ . "%20")) ; 32 for the SPC char
7964 "Association list of escapes for some characters problematic in links.
7965 This is the list that is used before handing over to the browser.")
7967 (defun org-link-escape (text &optional table)
7968 "Escape characters in TEXT that are problematic for links."
7969 (if (and org-url-encoding-use-url-hexify (not table))
7970 (url-hexify-string text)
7971 (setq table (or table org-link-escape-chars))
7972 (when text
7973 (let ((re (mapconcat (lambda (x) (regexp-quote
7974 (char-to-string (car x))))
7975 table "\\|")))
7976 (while (string-match re text)
7977 (setq text
7978 (replace-match
7979 (cdr (assoc (string-to-char (match-string 0 text))
7980 table))
7981 t t text)))
7982 text))))
7984 (defun org-link-unescape (text &optional table)
7985 "Reverse the action of `org-link-escape'."
7986 (if (and org-url-encoding-use-url-hexify (not table))
7987 (url-unhex-string text)
7988 (setq table (or table org-link-escape-chars))
7989 (when text
7990 (let ((case-fold-search t)
7991 (re (mapconcat (lambda (x) (regexp-quote (downcase (cdr x))))
7992 table "\\|")))
7993 (while (string-match re text)
7994 (setq text
7995 (replace-match
7996 (char-to-string (car (rassoc (upcase (match-string 0 text))
7997 table)))
7998 t t text)))
7999 text))))
8001 (defun org-xor (a b)
8002 "Exclusive or."
8003 (if a (not b) b))
8005 (defun org-fixup-message-id-for-http (s)
8006 "Replace special characters in a message id, so it can be used in an http query."
8007 (while (string-match "<" s)
8008 (setq s (replace-match "%3C" t t s)))
8009 (while (string-match ">" s)
8010 (setq s (replace-match "%3E" t t s)))
8011 (while (string-match "@" s)
8012 (setq s (replace-match "%40" t t s)))
8015 ;;;###autoload
8016 (defun org-insert-link-global ()
8017 "Insert a link like Org-mode does.
8018 This command can be called in any mode to insert a link in Org-mode syntax."
8019 (interactive)
8020 (org-load-modules-maybe)
8021 (org-run-like-in-org-mode 'org-insert-link))
8023 (defun org-insert-link (&optional complete-file link-location)
8024 "Insert a link. At the prompt, enter the link.
8026 Completion can be used to insert any of the link protocol prefixes like
8027 http or ftp in use.
8029 The history can be used to select a link previously stored with
8030 `org-store-link'. When the empty string is entered (i.e. if you just
8031 press RET at the prompt), the link defaults to the most recently
8032 stored link. As SPC triggers completion in the minibuffer, you need to
8033 use M-SPC or C-q SPC to force the insertion of a space character.
8035 You will also be prompted for a description, and if one is given, it will
8036 be displayed in the buffer instead of the link.
8038 If there is already a link at point, this command will allow you to edit link
8039 and description parts.
8041 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
8042 be selected using completion. The path to the file will be relative to the
8043 current directory if the file is in the current directory or a subdirectory.
8044 Otherwise, the link will be the absolute path as completed in the minibuffer
8045 \(i.e. normally ~/path/to/file). You can configure this behavior using the
8046 option `org-link-file-path-type'.
8048 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
8049 the current directory or below.
8051 With three \\[universal-argument] prefixes, negate the meaning of
8052 `org-keep-stored-link-after-insertion'.
8054 If `org-make-link-description-function' is non-nil, this function will be
8055 called with the link target, and the result will be the default
8056 link description.
8058 If the LINK-LOCATION parameter is non-nil, this value will be
8059 used as the link location instead of reading one interactively."
8060 (interactive "P")
8061 (let* ((wcf (current-window-configuration))
8062 (region (if (org-region-active-p)
8063 (buffer-substring (region-beginning) (region-end))))
8064 (remove (and region (list (region-beginning) (region-end))))
8065 (desc region)
8066 tmphist ; byte-compile incorrectly complains about this
8067 (link link-location)
8068 entry file all-prefixes)
8069 (cond
8070 (link-location) ; specified by arg, just use it.
8071 ((org-in-regexp org-bracket-link-regexp 1)
8072 ;; We do have a link at point, and we are going to edit it.
8073 (setq remove (list (match-beginning 0) (match-end 0)))
8074 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8075 (setq link (read-string "Link: "
8076 (org-link-unescape
8077 (org-match-string-no-properties 1)))))
8078 ((or (org-in-regexp org-angle-link-re)
8079 (org-in-regexp org-plain-link-re))
8080 ;; Convert to bracket link
8081 (setq remove (list (match-beginning 0) (match-end 0))
8082 link (read-string "Link: "
8083 (org-remove-angle-brackets (match-string 0)))))
8084 ((member complete-file '((4) (16)))
8085 ;; Completing read for file names.
8086 (setq link (org-file-complete-link complete-file)))
8088 ;; Read link, with completion for stored links.
8089 (with-output-to-temp-buffer "*Org Links*"
8090 (princ "Insert a link.
8091 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
8092 (when org-stored-links
8093 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8094 (princ (mapconcat
8095 (lambda (x)
8096 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8097 (reverse org-stored-links) "\n"))))
8098 (let ((cw (selected-window)))
8099 (select-window (get-buffer-window "*Org Links*"))
8100 (setq truncate-lines t)
8101 (unless (pos-visible-in-window-p (point-max))
8102 (org-fit-window-to-buffer))
8103 (and (window-live-p cw) (select-window cw)))
8104 ;; Fake a link history, containing the stored links.
8105 (setq tmphist (append (mapcar 'car org-stored-links)
8106 org-insert-link-history))
8107 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8108 (mapcar 'car org-link-abbrev-alist)
8109 org-link-types))
8110 (unwind-protect
8111 (progn
8112 (setq link
8113 (let ((org-completion-use-ido nil)
8114 (org-completion-use-iswitchb nil))
8115 (org-completing-read
8116 "Link: "
8117 (append
8118 (mapcar (lambda (x) (list (concat x ":")))
8119 all-prefixes)
8120 (mapcar 'car org-stored-links))
8121 nil nil nil
8122 'tmphist
8123 (car (car org-stored-links)))))
8124 (if (not (string-match "\\S-" link))
8125 (error "No link selected"))
8126 (if (or (member link all-prefixes)
8127 (and (equal ":" (substring link -1))
8128 (member (substring link 0 -1) all-prefixes)
8129 (setq link (substring link 0 -1))))
8130 (setq link (org-link-try-special-completion link))))
8131 (set-window-configuration wcf)
8132 (kill-buffer "*Org Links*"))
8133 (setq entry (assoc link org-stored-links))
8134 (or entry (push link org-insert-link-history))
8135 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8136 (not org-keep-stored-link-after-insertion))
8137 (setq org-stored-links (delq (assoc link org-stored-links)
8138 org-stored-links)))
8139 (setq desc (or desc (nth 1 entry)))))
8141 (if (string-match org-plain-link-re link)
8142 ;; URL-like link, normalize the use of angular brackets.
8143 (setq link (org-make-link (org-remove-angle-brackets link))))
8145 ;; Check if we are linking to the current file with a search option
8146 ;; If yes, simplify the link by using only the search option.
8147 (when (and buffer-file-name
8148 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
8149 (let* ((path (match-string 1 link))
8150 (case-fold-search nil)
8151 (search (match-string 2 link)))
8152 (save-match-data
8153 (if (equal (file-truename buffer-file-name) (file-truename path))
8154 ;; We are linking to this same file, with a search option
8155 (setq link search)))))
8157 ;; Check if we can/should use a relative path. If yes, simplify the link
8158 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8159 (let* ((type (match-string 1 link))
8160 (path (match-string 2 link))
8161 (origpath path)
8162 (case-fold-search nil))
8163 (cond
8164 ((or (eq org-link-file-path-type 'absolute)
8165 (equal complete-file '(16)))
8166 (setq path (abbreviate-file-name (expand-file-name path))))
8167 ((eq org-link-file-path-type 'noabbrev)
8168 (setq path (expand-file-name path)))
8169 ((eq org-link-file-path-type 'relative)
8170 (setq path (file-relative-name path)))
8172 (save-match-data
8173 (if (string-match (concat "^" (regexp-quote
8174 (file-name-as-directory
8175 (expand-file-name "."))))
8176 (expand-file-name path))
8177 ;; We are linking a file with relative path name.
8178 (setq path (substring (expand-file-name path)
8179 (match-end 0)))
8180 (setq path (abbreviate-file-name (expand-file-name path)))))))
8181 (setq link (concat type path))
8182 (if (equal desc origpath)
8183 (setq desc path))))
8185 (if org-make-link-description-function
8186 (setq desc (funcall org-make-link-description-function link desc)))
8188 (setq desc (read-string "Description: " desc))
8189 (unless (string-match "\\S-" desc) (setq desc nil))
8190 (if remove (apply 'delete-region remove))
8191 (insert (org-make-link-string link desc))))
8193 (defun org-link-try-special-completion (type)
8194 "If there is completion support for link type TYPE, offer it."
8195 (let ((fun (intern (concat "org-" type "-complete-link"))))
8196 (if (functionp fun)
8197 (funcall fun)
8198 (read-string "Link (no completion support): " (concat type ":")))))
8200 (defun org-file-complete-link (&optional arg)
8201 "Create a file link using completion."
8202 (let (file link)
8203 (setq file (read-file-name "File: "))
8204 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8205 (pwd1 (file-name-as-directory (abbreviate-file-name
8206 (expand-file-name ".")))))
8207 (cond
8208 ((equal arg '(16))
8209 (setq link (org-make-link
8210 "file:"
8211 (abbreviate-file-name (expand-file-name file)))))
8212 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8213 (setq link (org-make-link "file:" (match-string 1 file))))
8214 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8215 (expand-file-name file))
8216 (setq link (org-make-link
8217 "file:" (match-string 1 (expand-file-name file)))))
8218 (t (setq link (org-make-link "file:" file)))))
8219 link))
8221 (defun org-completing-read (&rest args)
8222 "Completing-read with SPACE being a normal character."
8223 (let ((minibuffer-local-completion-map
8224 (copy-keymap minibuffer-local-completion-map)))
8225 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
8226 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
8227 (apply 'org-icompleting-read args)))
8229 (defun org-completing-read-no-i (&rest args)
8230 (let (org-completion-use-ido org-completion-use-iswitchb)
8231 (apply 'org-completing-read args)))
8233 (defun org-iswitchb-completing-read (prompt choices &rest args)
8234 "Use iswitch as a completing-read replacement to choose from choices.
8235 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
8236 from."
8237 (let* ((iswitchb-use-virtual-buffers nil)
8238 (iswitchb-make-buflist-hook
8239 (lambda ()
8240 (setq iswitchb-temp-buflist choices))))
8241 (iswitchb-read-buffer prompt)))
8243 (defun org-icompleting-read (&rest args)
8244 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
8245 (org-without-partial-completion
8246 (if (and org-completion-use-ido
8247 (fboundp 'ido-completing-read)
8248 (boundp 'ido-mode) ido-mode
8249 (listp (second args)))
8250 (let ((ido-enter-matching-directory nil))
8251 (apply 'ido-completing-read (concat (car args))
8252 (if (consp (car (nth 1 args)))
8253 (mapcar (lambda (x) (car x)) (nth 1 args))
8254 (nth 1 args))
8255 (cddr args)))
8256 (if (and org-completion-use-iswitchb
8257 (boundp 'iswitchb-mode) iswitchb-mode
8258 (listp (second args)))
8259 (apply 'org-iswitchb-completing-read (concat (car args))
8260 (if (consp (car (nth 1 args)))
8261 (mapcar (lambda (x) (car x)) (nth 1 args))
8262 (nth 1 args))
8263 (cddr args))
8264 (apply 'completing-read args)))))
8266 (defun org-extract-attributes (s)
8267 "Extract the attributes cookie from a string and set as text property."
8268 (let (a attr (start 0) key value)
8269 (save-match-data
8270 (when (string-match "{{\\([^}]+\\)}}$" s)
8271 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
8272 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
8273 (setq key (match-string 1 a) value (match-string 2 a)
8274 start (match-end 0)
8275 attr (plist-put attr (intern key) value))))
8276 (org-add-props s nil 'org-attr attr))
8279 (defun org-extract-attributes-from-string (tag)
8280 (let (key value attr)
8281 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
8282 (setq key (match-string 1 tag) value (match-string 2 tag)
8283 tag (replace-match "" t t tag)
8284 attr (plist-put attr (intern key) value)))
8285 (cons tag attr)))
8287 (defun org-attributes-to-string (plist)
8288 "Format a property list into an HTML attribute list."
8289 (let ((s "") key value)
8290 (while plist
8291 (setq key (pop plist) value (pop plist))
8292 (and value
8293 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8296 ;;; Opening/following a link
8298 (defvar org-link-search-failed nil)
8300 (defvar org-open-link-functions nil
8301 "Hook for functions finding a plain text link.
8302 These functions must take a single argument, the link content.
8303 They will be called for links that look like [[link text][description]]
8304 when LINK TEXT does not have a protocol like \"http:\" and does not look
8305 like a filename (e.g. \"./blue.png\").
8307 These functions will be called *before* Org attempts to resolve the
8308 link by doing text searches in the current buffer - so if you want a
8309 link \"[[target]]\" to still find \"<<target>>\", your function should
8310 handle this as a special case.
8312 When the function does handle the link, it must return a non-nil value.
8313 If it decides that it is not responsible for this link, it must return
8314 nil to indicate that that Org-mode can continue with other options
8315 like exact and fuzzy text search.")
8317 (defun org-next-link ()
8318 "Move forward to the next link.
8319 If the link is in hidden text, expose it."
8320 (interactive)
8321 (when (and org-link-search-failed (eq this-command last-command))
8322 (goto-char (point-min))
8323 (message "Link search wrapped back to beginning of buffer"))
8324 (setq org-link-search-failed nil)
8325 (let* ((pos (point))
8326 (ct (org-context))
8327 (a (assoc :link ct)))
8328 (if a (goto-char (nth 2 a)))
8329 (if (re-search-forward org-any-link-re nil t)
8330 (progn
8331 (goto-char (match-beginning 0))
8332 (if (org-invisible-p) (org-show-context)))
8333 (goto-char pos)
8334 (setq org-link-search-failed t)
8335 (error "No further link found"))))
8337 (defun org-previous-link ()
8338 "Move backward to the previous link.
8339 If the link is in hidden text, expose it."
8340 (interactive)
8341 (when (and org-link-search-failed (eq this-command last-command))
8342 (goto-char (point-max))
8343 (message "Link search wrapped back to end of buffer"))
8344 (setq org-link-search-failed nil)
8345 (let* ((pos (point))
8346 (ct (org-context))
8347 (a (assoc :link ct)))
8348 (if a (goto-char (nth 1 a)))
8349 (if (re-search-backward org-any-link-re nil t)
8350 (progn
8351 (goto-char (match-beginning 0))
8352 (if (org-invisible-p) (org-show-context)))
8353 (goto-char pos)
8354 (setq org-link-search-failed t)
8355 (error "No further link found"))))
8357 (defun org-translate-link (s)
8358 "Translate a link string if a translation function has been defined."
8359 (if (and org-link-translation-function
8360 (fboundp org-link-translation-function)
8361 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8362 (progn
8363 (setq s (funcall org-link-translation-function
8364 (match-string 1) (match-string 2)))
8365 (concat (car s) ":" (cdr s)))
8368 (defun org-translate-link-from-planner (type path)
8369 "Translate a link from Emacs Planner syntax so that Org can follow it.
8370 This is still an experimental function, your mileage may vary."
8371 (cond
8372 ((member type '("http" "https" "news" "ftp"))
8373 ;; standard Internet links are the same.
8374 nil)
8375 ((and (equal type "irc") (string-match "^//" path))
8376 ;; Planner has two / at the beginning of an irc link, we have 1.
8377 ;; We should have zero, actually....
8378 (setq path (substring path 1)))
8379 ((and (equal type "lisp") (string-match "^/" path))
8380 ;; Planner has a slash, we do not.
8381 (setq type "elisp" path (substring path 1)))
8382 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8383 ;; A typical message link. Planner has the id after the final slash,
8384 ;; we separate it with a hash mark
8385 (setq path (concat (match-string 1 path) "#"
8386 (org-remove-angle-brackets (match-string 2 path)))))
8388 (cons type path))
8390 (defun org-find-file-at-mouse (ev)
8391 "Open file link or URL at mouse."
8392 (interactive "e")
8393 (mouse-set-point ev)
8394 (org-open-at-point 'in-emacs))
8396 (defun org-open-at-mouse (ev)
8397 "Open file link or URL at mouse."
8398 (interactive "e")
8399 (mouse-set-point ev)
8400 (if (eq major-mode 'org-agenda-mode)
8401 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8402 (org-open-at-point))
8404 (defvar org-window-config-before-follow-link nil
8405 "The window configuration before following a link.
8406 This is saved in case the need arises to restore it.")
8408 (defvar org-open-link-marker (make-marker)
8409 "Marker pointing to the location where `org-open-at-point; was called.")
8411 ;;;###autoload
8412 (defun org-open-at-point-global ()
8413 "Follow a link like Org-mode does.
8414 This command can be called in any mode to follow a link that has
8415 Org-mode syntax."
8416 (interactive)
8417 (org-run-like-in-org-mode 'org-open-at-point))
8419 ;;;###autoload
8420 (defun org-open-link-from-string (s &optional arg reference-buffer)
8421 "Open a link in the string S, as if it was in Org-mode."
8422 (interactive "sLink: \nP")
8423 (let ((reference-buffer (or reference-buffer (current-buffer))))
8424 (with-temp-buffer
8425 (let ((org-inhibit-startup t))
8426 (org-mode)
8427 (insert s)
8428 (goto-char (point-min))
8429 (when reference-buffer
8430 (setq org-link-abbrev-alist-local
8431 (with-current-buffer reference-buffer
8432 org-link-abbrev-alist-local)))
8433 (org-open-at-point arg reference-buffer)))))
8435 (defun org-open-at-point (&optional in-emacs reference-buffer)
8436 "Open link at or after point.
8437 If there is no link at point, this function will search forward up to
8438 the end of the current line.
8439 Normally, files will be opened by an appropriate application. If the
8440 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8441 With a double prefix argument, try to open outside of Emacs, in the
8442 application the system uses for this file type."
8443 (interactive "P")
8444 (org-load-modules-maybe)
8445 (move-marker org-open-link-marker (point))
8446 (setq org-window-config-before-follow-link (current-window-configuration))
8447 (org-remove-occur-highlights nil nil t)
8448 (cond
8449 ((and (org-on-heading-p)
8450 (not (org-in-regexp
8451 (concat org-plain-link-re "\\|"
8452 org-bracket-link-regexp "\\|"
8453 org-angle-link-re "\\|"
8454 "[ \t]:[^ \t\n]+:[ \t]*$")))
8455 (not (get-text-property (point) 'org-linked-text)))
8456 (or (org-offer-links-in-entry in-emacs)
8457 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8458 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8459 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8460 (org-footnote-action))
8462 (let (type path link line search (pos (point)))
8463 (catch 'match
8464 (save-excursion
8465 (skip-chars-forward "^]\n\r")
8466 (when (org-in-regexp org-bracket-link-regexp 1)
8467 (setq link (org-extract-attributes
8468 (org-link-unescape (org-match-string-no-properties 1))))
8469 (while (string-match " *\n *" link)
8470 (setq link (replace-match " " t t link)))
8471 (setq link (org-link-expand-abbrev link))
8472 (cond
8473 ((or (file-name-absolute-p link)
8474 (string-match "^\\.\\.?/" link))
8475 (setq type "file" path link))
8476 ((string-match org-link-re-with-space3 link)
8477 (setq type (match-string 1 link) path (match-string 2 link)))
8478 (t (setq type "thisfile" path link)))
8479 (throw 'match t)))
8481 (when (get-text-property (point) 'org-linked-text)
8482 (setq type "thisfile"
8483 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8484 (1+ (point)) (point))
8485 path (buffer-substring
8486 (previous-single-property-change pos 'org-linked-text)
8487 (next-single-property-change pos 'org-linked-text)))
8488 (throw 'match t))
8490 (save-excursion
8491 (when (or (org-in-regexp org-angle-link-re)
8492 (org-in-regexp org-plain-link-re))
8493 (setq type (match-string 1) path (match-string 2))
8494 (throw 'match t)))
8495 (save-excursion
8496 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
8497 (setq type "tags"
8498 path (match-string 1))
8499 (while (string-match ":" path)
8500 (setq path (replace-match "+" t t path)))
8501 (throw 'match t)))
8502 (when (org-in-regexp "<\\([^><\n]+\\)>")
8503 (setq type "tree-match"
8504 path (match-string 1))
8505 (throw 'match t)))
8506 (unless path
8507 (error "No link found"))
8509 ;; switch back to reference buffer
8510 ;; needed when if called in a temporary buffer through
8511 ;; org-open-link-from-string
8512 (with-current-buffer (or reference-buffer (current-buffer))
8514 ;; Remove any trailing spaces in path
8515 (if (string-match " +\\'" path)
8516 (setq path (replace-match "" t t path)))
8517 (if (and org-link-translation-function
8518 (fboundp org-link-translation-function))
8519 ;; Check if we need to translate the link
8520 (let ((tmp (funcall org-link-translation-function type path)))
8521 (setq type (car tmp) path (cdr tmp))))
8523 (cond
8525 ((assoc type org-link-protocols)
8526 (funcall (nth 1 (assoc type org-link-protocols)) path))
8528 ((equal type "mailto")
8529 (let ((cmd (car org-link-mailto-program))
8530 (args (cdr org-link-mailto-program)) args1
8531 (address path) (subject "") a)
8532 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8533 (setq address (match-string 1 path)
8534 subject (org-link-escape (match-string 2 path))))
8535 (while args
8536 (cond
8537 ((not (stringp (car args))) (push (pop args) args1))
8538 (t (setq a (pop args))
8539 (if (string-match "%a" a)
8540 (setq a (replace-match address t t a)))
8541 (if (string-match "%s" a)
8542 (setq a (replace-match subject t t a)))
8543 (push a args1))))
8544 (apply cmd (nreverse args1))))
8546 ((member type '("http" "https" "ftp" "news"))
8547 (browse-url (concat type ":" (org-link-escape
8548 path org-link-escape-chars-browser))))
8550 ((member type '("message"))
8551 (browse-url (concat type ":" path)))
8553 ((string= type "tags")
8554 (org-tags-view in-emacs path))
8556 ((string= type "tree-match")
8557 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8559 ((string= type "file")
8560 (if (string-match "::\\([0-9]+\\)\\'" path)
8561 (setq line (string-to-number (match-string 1 path))
8562 path (substring path 0 (match-beginning 0)))
8563 (if (string-match "::\\(.+\\)\\'" path)
8564 (setq search (match-string 1 path)
8565 path (substring path 0 (match-beginning 0)))))
8566 (if (string-match "[*?{]" (file-name-nondirectory path))
8567 (dired path)
8568 (org-open-file path in-emacs line search)))
8570 ((string= type "news")
8571 (require 'org-gnus)
8572 (org-gnus-follow-link path))
8574 ((string= type "shell")
8575 (let ((cmd path))
8576 (if (or (not org-confirm-shell-link-function)
8577 (funcall org-confirm-shell-link-function
8578 (format "Execute \"%s\" in shell? "
8579 (org-add-props cmd nil
8580 'face 'org-warning))))
8581 (progn
8582 (message "Executing %s" cmd)
8583 (shell-command cmd))
8584 (error "Abort"))))
8586 ((string= type "elisp")
8587 (let ((cmd path))
8588 (if (or (not org-confirm-elisp-link-function)
8589 (funcall org-confirm-elisp-link-function
8590 (format "Execute \"%s\" as elisp? "
8591 (org-add-props cmd nil
8592 'face 'org-warning))))
8593 (message "%s => %s" cmd
8594 (if (equal (string-to-char cmd) ?\()
8595 (eval (read cmd))
8596 (call-interactively (read cmd))))
8597 (error "Abort"))))
8599 ((and (string= type "thisfile")
8600 (run-hook-with-args-until-success
8601 'org-open-link-functions path)))
8603 ((string= type "thisfile")
8604 (if in-emacs
8605 (switch-to-buffer-other-window
8606 (org-get-buffer-for-internal-link (current-buffer)))
8607 (org-mark-ring-push))
8608 (let ((cmd `(org-link-search
8609 ,path
8610 ,(cond ((equal in-emacs '(4)) 'occur)
8611 ((equal in-emacs '(16)) 'org-occur)
8612 (t nil))
8613 ,pos)))
8614 (condition-case nil (eval cmd)
8615 (error (progn (widen) (eval cmd))))))
8618 (browse-url-at-point)))))))
8619 (move-marker org-open-link-marker nil)
8620 (run-hook-with-args 'org-follow-link-hook))
8622 (defun org-offer-links-in-entry (&optional nth zero)
8623 "Offer links in the current entry and follow the selected link.
8624 If there is only one link, follow it immediately as well.
8625 If NTH is an integer, immediately pick the NTH link found.
8626 If ZERO is a string, check also this string for a link, and if
8627 there is one, offer it as link number zero."
8628 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
8629 "\\(" org-angle-link-re "\\)\\|"
8630 "\\(" org-plain-link-re "\\)"))
8631 (cnt ?0)
8632 (in-emacs (if (integerp nth) nil nth))
8633 have-zero end links link c)
8634 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
8635 (push (match-string 0 zero) links)
8636 (setq cnt (1- cnt) have-zero t))
8637 (save-excursion
8638 (org-back-to-heading t)
8639 (setq end (save-excursion (outline-next-heading) (point)))
8640 (while (re-search-forward re end t)
8641 (push (match-string 0) links))
8642 (setq links (org-uniquify (reverse links))))
8644 (cond
8645 ((null links)
8646 (message "No links"))
8647 ((equal (length links) 1)
8648 (setq link (list (car links))))
8649 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8650 (setq link (nth (if have-zero nth (1- nth)) links)))
8651 (t ; we have to select a link
8652 (save-excursion
8653 (save-window-excursion
8654 (delete-other-windows)
8655 (with-output-to-temp-buffer "*Select Link*"
8656 (mapc (lambda (l)
8657 (if (not (string-match org-bracket-link-regexp l))
8658 (princ (format "[%c] %s\n" (incf cnt)
8659 (org-remove-angle-brackets l)))
8660 (if (match-end 3)
8661 (princ (format "[%c] %s (%s)\n" (incf cnt)
8662 (match-string 3 l) (match-string 1 l)))
8663 (princ (format "[%c] %s\n" (incf cnt)
8664 (match-string 1 l))))))
8665 links))
8666 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8667 (message "Select link to open, RET to open all:")
8668 (setq c (read-char-exclusive))
8669 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8670 (when (equal c ?q) (error "Abort"))
8671 (if (equal c ?\C-m)
8672 (setq link links)
8673 (setq nth (- c ?0))
8674 (if have-zero (setq nth (1+ nth)))
8675 (unless (and (integerp nth) (>= (length links) nth))
8676 (error "Invalid link selection"))
8677 (setq link (list (nth (1- nth) links))))))
8678 (if link
8679 (let ((buf (current-buffer)))
8680 (dolist (l link)
8681 (org-open-link-from-string l in-emacs buf))
8683 nil)))
8685 ;; Add special file links that specify the way of opening
8687 (org-add-link-type "file+sys" 'org-open-file-with-system)
8688 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
8689 (defun org-open-file-with-system (path)
8690 "Open file at PATH using the system way of opeing it."
8691 (org-open-file path 'system))
8692 (defun org-open-file-with-emacs (path)
8693 "Open file at PATH in emacs."
8694 (org-open-file path 'emacs))
8695 (defun org-remove-file-link-modifiers ()
8696 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
8697 (goto-char (point-min))
8698 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
8699 (org-if-unprotected
8700 (replace-match "file:" t t))))
8701 (eval-after-load "org-exp"
8702 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
8703 'org-remove-file-link-modifiers))
8705 ;;;; Time estimates
8707 (defun org-get-effort (&optional pom)
8708 "Get the effort estimate for the current entry."
8709 (org-entry-get pom org-effort-property))
8711 ;;; File search
8713 (defvar org-create-file-search-functions nil
8714 "List of functions to construct the right search string for a file link.
8715 These functions are called in turn with point at the location to
8716 which the link should point.
8718 A function in the hook should first test if it would like to
8719 handle this file type, for example by checking the major-mode or
8720 the file extension. If it decides not to handle this file, it
8721 should just return nil to give other functions a chance. If it
8722 does handle the file, it must return the search string to be used
8723 when following the link. The search string will be part of the
8724 file link, given after a double colon, and `org-open-at-point'
8725 will automatically search for it. If special measures must be
8726 taken to make the search successful, another function should be
8727 added to the companion hook `org-execute-file-search-functions',
8728 which see.
8730 A function in this hook may also use `setq' to set the variable
8731 `description' to provide a suggestion for the descriptive text to
8732 be used for this link when it gets inserted into an Org-mode
8733 buffer with \\[org-insert-link].")
8735 (defvar org-execute-file-search-functions nil
8736 "List of functions to execute a file search triggered by a link.
8738 Functions added to this hook must accept a single argument, the
8739 search string that was part of the file link, the part after the
8740 double colon. The function must first check if it would like to
8741 handle this search, for example by checking the major-mode or the
8742 file extension. If it decides not to handle this search, it
8743 should just return nil to give other functions a chance. If it
8744 does handle the search, it must return a non-nil value to keep
8745 other functions from trying.
8747 Each function can access the current prefix argument through the
8748 variable `current-prefix-argument'. Note that a single prefix is
8749 used to force opening a link in Emacs, so it may be good to only
8750 use a numeric or double prefix to guide the search function.
8752 In case this is needed, a function in this hook can also restore
8753 the window configuration before `org-open-at-point' was called using:
8755 (set-window-configuration org-window-config-before-follow-link)")
8757 (defun org-link-search (s &optional type avoid-pos)
8758 "Search for a link search option.
8759 If S is surrounded by forward slashes, it is interpreted as a
8760 regular expression. In org-mode files, this will create an `org-occur'
8761 sparse tree. In ordinary files, `occur' will be used to list matches.
8762 If the current buffer is in `dired-mode', grep will be used to search
8763 in all files. If AVOID-POS is given, ignore matches near that position."
8764 (let ((case-fold-search t)
8765 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8766 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8767 (append '(("") (" ") ("\t") ("\n"))
8768 org-emphasis-alist)
8769 "\\|") "\\)"))
8770 (pos (point))
8771 (pre nil) (post nil)
8772 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8773 (cond
8774 ;; First check if there are any special
8775 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8776 ;; Now try the builtin stuff
8777 ((and (equal (string-to-char s0) ?#)
8778 (> (length s0) 1)
8779 (save-excursion
8780 (goto-char (point-min))
8781 (and
8782 (re-search-forward
8783 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8784 (setq type 'dedicated
8785 pos (match-beginning 0))))
8786 ;; There is an exact target for this
8787 (goto-char pos)
8788 (org-back-to-heading t)))
8789 ((save-excursion
8790 (goto-char (point-min))
8791 (and
8792 (re-search-forward
8793 (concat "<<" (regexp-quote s0) ">>") nil t)
8794 (setq type 'dedicated
8795 pos (match-beginning 0))))
8796 ;; There is an exact target for this
8797 (goto-char pos))
8798 ((and (string-match "^(\\(.*\\))$" s0)
8799 (save-excursion
8800 (goto-char (point-min))
8801 (and
8802 (re-search-forward
8803 (concat "[^[]" (regexp-quote
8804 (format org-coderef-label-format
8805 (match-string 1 s0))))
8806 nil t)
8807 (setq type 'dedicated
8808 pos (1+ (match-beginning 0))))))
8809 ;; There is a coderef target for this
8810 (goto-char pos))
8811 ((string-match "^/\\(.*\\)/$" s)
8812 ;; A regular expression
8813 (cond
8814 ((org-mode-p)
8815 (org-occur (match-string 1 s)))
8816 ;;((eq major-mode 'dired-mode)
8817 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8818 (t (org-do-occur (match-string 1 s)))))
8820 ;; A normal search strings
8821 (when (equal (string-to-char s) ?*)
8822 ;; Anchor on headlines, post may include tags.
8823 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8824 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8825 s (substring s 1)))
8826 (remove-text-properties
8827 0 (length s)
8828 '(face nil mouse-face nil keymap nil fontified nil) s)
8829 ;; Make a series of regular expressions to find a match
8830 (setq words (org-split-string s "[ \n\r\t]+")
8832 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8833 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8834 "\\)" markers)
8835 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8836 re2a (concat "[ \t\r\n]" re2a_)
8837 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8838 re4 (concat "[^a-zA-Z_]" re4_)
8840 re1 (concat pre re2 post)
8841 re3 (concat pre (if pre re4_ re4) post)
8842 re5 (concat pre ".*" re4)
8843 re2 (concat pre re2)
8844 re2a (concat pre (if pre re2a_ re2a))
8845 re4 (concat pre (if pre re4_ re4))
8846 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8847 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8848 re5 "\\)"
8850 (cond
8851 ((eq type 'org-occur) (org-occur reall))
8852 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8853 (t (goto-char (point-min))
8854 (setq type 'fuzzy)
8855 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8856 (org-search-not-self 1 re1 nil t)
8857 (org-search-not-self 1 re2 nil t)
8858 (org-search-not-self 1 re2a nil t)
8859 (org-search-not-self 1 re3 nil t)
8860 (org-search-not-self 1 re4 nil t)
8861 (org-search-not-self 1 re5 nil t)
8863 (goto-char (match-beginning 1))
8864 (goto-char pos)
8865 (error "No match")))))
8867 ;; Normal string-search
8868 (goto-char (point-min))
8869 (if (search-forward s nil t)
8870 (goto-char (match-beginning 0))
8871 (error "No match"))))
8872 (and (org-mode-p) (org-show-context 'link-search))
8873 type))
8875 (defun org-search-not-self (group &rest args)
8876 "Execute `re-search-forward', but only accept matches that do not
8877 enclose the position of `org-open-link-marker'."
8878 (let ((m org-open-link-marker))
8879 (catch 'exit
8880 (while (apply 're-search-forward args)
8881 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8882 (goto-char (match-end group))
8883 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8884 (> (match-beginning 0) (marker-position m))
8885 (< (match-end 0) (marker-position m)))
8886 (save-match-data
8887 (or (not (org-in-regexp
8888 org-bracket-link-analytic-regexp 1))
8889 (not (match-end 4)) ; no description
8890 (and (<= (match-beginning 4) (point))
8891 (>= (match-end 4) (point))))))
8892 (throw 'exit (point))))))))
8894 (defun org-get-buffer-for-internal-link (buffer)
8895 "Return a buffer to be used for displaying the link target of internal links."
8896 (cond
8897 ((not org-display-internal-link-with-indirect-buffer)
8898 buffer)
8899 ((string-match "(Clone)$" (buffer-name buffer))
8900 (message "Buffer is already a clone, not making another one")
8901 ;; we also do not modify visibility in this case
8902 buffer)
8903 (t ; make a new indirect buffer for displaying the link
8904 (let* ((bn (buffer-name buffer))
8905 (ibn (concat bn "(Clone)"))
8906 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8907 (with-current-buffer ib (org-overview))
8908 ib))))
8910 (defun org-do-occur (regexp &optional cleanup)
8911 "Call the Emacs command `occur'.
8912 If CLEANUP is non-nil, remove the printout of the regular expression
8913 in the *Occur* buffer. This is useful if the regex is long and not useful
8914 to read."
8915 (occur regexp)
8916 (when cleanup
8917 (let ((cwin (selected-window)) win beg end)
8918 (when (setq win (get-buffer-window "*Occur*"))
8919 (select-window win))
8920 (goto-char (point-min))
8921 (when (re-search-forward "match[a-z]+" nil t)
8922 (setq beg (match-end 0))
8923 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8924 (setq end (1- (match-beginning 0)))))
8925 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8926 (goto-char (point-min))
8927 (select-window cwin))))
8929 ;;; The mark ring for links jumps
8931 (defvar org-mark-ring nil
8932 "Mark ring for positions before jumps in Org-mode.")
8933 (defvar org-mark-ring-last-goto nil
8934 "Last position in the mark ring used to go back.")
8935 ;; Fill and close the ring
8936 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8937 (loop for i from 1 to org-mark-ring-length do
8938 (push (make-marker) org-mark-ring))
8939 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8940 org-mark-ring)
8942 (defun org-mark-ring-push (&optional pos buffer)
8943 "Put the current position or POS into the mark ring and rotate it."
8944 (interactive)
8945 (setq pos (or pos (point)))
8946 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8947 (move-marker (car org-mark-ring)
8948 (or pos (point))
8949 (or buffer (current-buffer)))
8950 (message "%s"
8951 (substitute-command-keys
8952 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8954 (defun org-mark-ring-goto (&optional n)
8955 "Jump to the previous position in the mark ring.
8956 With prefix arg N, jump back that many stored positions. When
8957 called several times in succession, walk through the entire ring.
8958 Org-mode commands jumping to a different position in the current file,
8959 or to another Org-mode file, automatically push the old position
8960 onto the ring."
8961 (interactive "p")
8962 (let (p m)
8963 (if (eq last-command this-command)
8964 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8965 (setq p org-mark-ring))
8966 (setq org-mark-ring-last-goto p)
8967 (setq m (car p))
8968 (switch-to-buffer (marker-buffer m))
8969 (goto-char m)
8970 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8972 (defun org-remove-angle-brackets (s)
8973 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8974 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8976 (defun org-add-angle-brackets (s)
8977 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8978 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8980 (defun org-remove-double-quotes (s)
8981 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8982 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8985 ;;; Following specific links
8987 (defun org-follow-timestamp-link ()
8988 (cond
8989 ((org-at-date-range-p t)
8990 (let ((org-agenda-start-on-weekday)
8991 (t1 (match-string 1))
8992 (t2 (match-string 2)))
8993 (setq t1 (time-to-days (org-time-string-to-time t1))
8994 t2 (time-to-days (org-time-string-to-time t2)))
8995 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8996 ((org-at-timestamp-p t)
8997 (org-agenda-list nil (time-to-days (org-time-string-to-time
8998 (substring (match-string 1) 0 10)))
9000 (t (error "This should not happen"))))
9003 ;;; Following file links
9004 (defvar org-wait nil)
9005 (defun org-open-file (path &optional in-emacs line search)
9006 "Open the file at PATH.
9007 First, this expands any special file name abbreviations. Then the
9008 configuration variable `org-file-apps' is checked if it contains an
9009 entry for this file type, and if yes, the corresponding command is launched.
9011 If no application is found, Emacs simply visits the file.
9013 With optional prefix argument IN-EMACS, Emacs will visit the file.
9014 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
9015 and to use an external application to visit the file.
9017 Optional LINE specifies a line to go to, optional SEARCH a string to
9018 search for. If LINE or SEARCH is given, but IN-EMACS is nil, it will
9019 be assumed that org-open-file was called to open a file: link, and the
9020 original link to match against org-file-apps will be reconstructed
9021 from PATH and whichever of LINE or SEARCH is given.
9023 If the file does not exist, an error is thrown."
9024 (let* ((file (if (equal path "")
9025 buffer-file-name
9026 (substitute-in-file-name (expand-file-name path))))
9027 (apps (append org-file-apps (org-default-apps)))
9028 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9029 (dirp (if remp nil (file-directory-p file)))
9030 (file (if (and dirp org-open-directory-means-index-dot-org)
9031 (concat (file-name-as-directory file) "index.org")
9032 file))
9033 (a-m-a-p (assq 'auto-mode apps))
9034 (dfile (downcase file))
9035 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
9036 (link (cond ((and (eq line nil)
9037 (eq search nil))
9038 file)
9039 (line
9040 (concat file "::" (number-to-string line)))
9041 (search
9042 (concat file "::" search))))
9043 (dlink (downcase link))
9044 (old-buffer (current-buffer))
9045 (old-pos (point))
9046 (old-mode major-mode)
9047 ext cmd link-match-data)
9048 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9049 (setq ext (match-string 1 dfile))
9050 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9051 (setq ext (match-string 1 dfile))))
9052 (cond
9053 ((member in-emacs '((16) system))
9054 (setq cmd (cdr (assoc 'system apps))))
9055 (in-emacs (setq cmd 'emacs))
9057 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9058 (and dirp (cdr (assoc 'directory apps)))
9059 ;; if we find a match in org-file-apps, store the match
9060 ;; data for later
9061 (let ((match (assoc-default dlink (org-apps-regexp-alist
9062 apps a-m-a-p)
9063 'string-match)))
9064 (if match
9065 (progn (setq link-match-data (match-data))
9066 match)
9067 nil))
9068 (cdr (assoc ext apps))
9069 (cdr (assoc t apps))))))
9070 (when (eq cmd 'system)
9071 (setq cmd (cdr (assoc 'system apps))))
9072 (when (eq cmd 'default)
9073 (setq cmd (cdr (assoc t apps))))
9074 (when (eq cmd 'mailcap)
9075 (require 'mailcap)
9076 (mailcap-parse-mailcaps)
9077 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9078 (command (mailcap-mime-info mime-type)))
9079 (if (stringp command)
9080 (setq cmd command)
9081 (setq cmd 'emacs))))
9082 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
9083 (not (file-exists-p file))
9084 (not org-open-non-existing-files))
9085 (error "No such file: %s" file))
9086 (cond
9087 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9088 ;; Remove quotes around the file name - we'll use shell-quote-argument.
9089 (while (string-match "['\"]%s['\"]" cmd)
9090 (setq cmd (replace-match "%s" t t cmd)))
9091 (while (string-match "%s" cmd)
9092 (setq cmd (replace-match
9093 (save-match-data
9094 (shell-quote-argument
9095 (convert-standard-filename file)))
9096 t t cmd)))
9097 ;; Replace "%1", "%2" etc. in command with group matches from regex
9098 (save-match-data
9099 (let ((match-index 1)
9100 (number-of-groups (- (/ (length link-match-data) 2) 1)))
9101 (set-match-data link-match-data)
9102 (while (<= match-index number-of-groups)
9103 (let ((regex (concat "%" (number-to-string match-index)))
9104 (replace-with (match-string match-index dlink)))
9105 (while (string-match regex cmd)
9106 (setq cmd (replace-match replace-with t t cmd))))
9107 (setq match-index (+ match-index 1)))))
9109 (save-window-excursion
9110 (start-process-shell-command cmd nil cmd)
9111 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
9113 ((or (stringp cmd)
9114 (eq cmd 'emacs))
9115 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9116 (widen)
9117 (if line (org-goto-line line)
9118 (if search (org-link-search search))))
9119 ((consp cmd)
9120 (let ((file (convert-standard-filename file)))
9121 (save-match-data
9122 (set-match-data link-match-data)
9123 (eval cmd))))
9124 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9125 (and (org-mode-p) (eq old-mode 'org-mode)
9126 (or (not (equal old-buffer (current-buffer)))
9127 (not (equal old-pos (point))))
9128 (org-mark-ring-push old-pos old-buffer))))
9130 (defun org-default-apps ()
9131 "Return the default applications for this operating system."
9132 (cond
9133 ((eq system-type 'darwin)
9134 org-file-apps-defaults-macosx)
9135 ((eq system-type 'windows-nt)
9136 org-file-apps-defaults-windowsnt)
9137 (t org-file-apps-defaults-gnu)))
9139 (defun org-apps-regexp-alist (list &optional add-auto-mode)
9140 "Convert extensions to regular expressions in the cars of LIST.
9141 Also, weed out any non-string entries, because the return value is used
9142 only for regexp matching.
9143 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
9144 point to the symbol `emacs', indicating that the file should
9145 be opened in Emacs."
9146 (append
9147 (delq nil
9148 (mapcar (lambda (x)
9149 (if (not (stringp (car x)))
9151 (if (string-match "\\W" (car x))
9153 (cons (concat "\\." (car x) "\\(::.*\\)?\\'")
9154 (cdr x)))))
9155 list))
9156 (if add-auto-mode
9157 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
9159 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
9160 (defun org-file-remote-p (file)
9161 "Test whether FILE specifies a location on a remote system.
9162 Return non-nil if the location is indeed remote.
9164 For example, the filename \"/user@host:/foo\" specifies a location
9165 on the system \"/user@host:\"."
9166 (cond ((fboundp 'file-remote-p)
9167 (file-remote-p file))
9168 ((fboundp 'tramp-handle-file-remote-p)
9169 (tramp-handle-file-remote-p file))
9170 ((and (boundp 'ange-ftp-name-format)
9171 (string-match (car ange-ftp-name-format) file))
9173 (t nil)))
9176 ;;;; Refiling
9178 (defun org-get-org-file ()
9179 "Read a filename, with default directory `org-directory'."
9180 (let ((default (or org-default-notes-file remember-data-file)))
9181 (read-file-name (format "File name [%s]: " default)
9182 (file-name-as-directory org-directory)
9183 default)))
9185 (defun org-notes-order-reversed-p ()
9186 "Check if the current file should receive notes in reversed order."
9187 (cond
9188 ((not org-reverse-note-order) nil)
9189 ((eq t org-reverse-note-order) t)
9190 ((not (listp org-reverse-note-order)) nil)
9191 (t (catch 'exit
9192 (let ((all org-reverse-note-order)
9193 entry)
9194 (while (setq entry (pop all))
9195 (if (string-match (car entry) buffer-file-name)
9196 (throw 'exit (cdr entry))))
9197 nil)))))
9199 (defvar org-refile-target-table nil
9200 "The list of refile targets, created by `org-refile'.")
9202 (defvar org-agenda-new-buffers nil
9203 "Buffers created to visit agenda files.")
9205 (defun org-get-refile-targets (&optional default-buffer)
9206 "Produce a table with refile targets."
9207 (let ((case-fold-search nil)
9208 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
9209 (entries (or org-refile-targets '((nil . (:level . 1)))))
9210 targets txt re files f desc descre fast-path-p level pos0)
9211 (message "Getting targets...")
9212 (with-current-buffer (or default-buffer (current-buffer))
9213 (while (setq entry (pop entries))
9214 (setq files (car entry) desc (cdr entry))
9215 (setq fast-path-p nil)
9216 (cond
9217 ((null files) (setq files (list (current-buffer))))
9218 ((eq files 'org-agenda-files)
9219 (setq files (org-agenda-files 'unrestricted)))
9220 ((and (symbolp files) (fboundp files))
9221 (setq files (funcall files)))
9222 ((and (symbolp files) (boundp files))
9223 (setq files (symbol-value files))))
9224 (if (stringp files) (setq files (list files)))
9225 (cond
9226 ((eq (car desc) :tag)
9227 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
9228 ((eq (car desc) :todo)
9229 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
9230 ((eq (car desc) :regexp)
9231 (setq descre (cdr desc)))
9232 ((eq (car desc) :level)
9233 (setq descre (concat "^\\*\\{" (number-to-string
9234 (if org-odd-levels-only
9235 (1- (* 2 (cdr desc)))
9236 (cdr desc)))
9237 "\\}[ \t]")))
9238 ((eq (car desc) :maxlevel)
9239 (setq fast-path-p t)
9240 (setq descre (concat "^\\*\\{1," (number-to-string
9241 (if org-odd-levels-only
9242 (1- (* 2 (cdr desc)))
9243 (cdr desc)))
9244 "\\}[ \t]")))
9245 (t (error "Bad refiling target description %s" desc)))
9246 (while (setq f (pop files))
9247 (with-current-buffer
9248 (if (bufferp f) f (org-get-agenda-file-buffer f))
9249 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
9250 (setq f (and f (expand-file-name f)))
9251 (if (eq org-refile-use-outline-path 'file)
9252 (push (list (file-name-nondirectory f) f nil nil) targets))
9253 (save-excursion
9254 (save-restriction
9255 (widen)
9256 (goto-char (point-min))
9257 (while (re-search-forward descre nil t)
9258 (goto-char (setq pos0 (point-at-bol)))
9259 (catch 'next
9260 (when org-refile-target-verify-function
9261 (save-match-data
9262 (or (funcall org-refile-target-verify-function)
9263 (throw 'next t))))
9264 (when (looking-at org-complex-heading-regexp)
9265 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
9266 txt (org-link-display-format (match-string 4))
9267 re (concat "^" (regexp-quote
9268 (buffer-substring (match-beginning 1)
9269 (match-end 4)))))
9270 (if (match-end 5) (setq re (concat re "[ \t]+"
9271 (regexp-quote
9272 (match-string 5)))))
9273 (setq re (concat re "[ \t]*$"))
9274 (when org-refile-use-outline-path
9275 (setq txt (mapconcat 'org-protect-slash
9276 (append
9277 (if (eq org-refile-use-outline-path 'file)
9278 (list (file-name-nondirectory
9279 (buffer-file-name (buffer-base-buffer))))
9280 (if (eq org-refile-use-outline-path 'full-file-path)
9281 (list (buffer-file-name (buffer-base-buffer)))))
9282 (org-get-outline-path fast-path-p level txt)
9283 (list txt))
9284 "/")))
9285 (push (list txt f re (point)) targets)))
9286 (when (= (point) pos0)
9287 ;; verification function has not moved point
9288 (goto-char (point-at-eol))))))))))
9289 (message "Getting targets...done")
9290 (nreverse targets)))
9292 (defun org-protect-slash (s)
9293 (while (string-match "/" s)
9294 (setq s (replace-match "\\" t t s)))
9297 (defvar org-olpa (make-vector 20 nil))
9299 (defun org-get-outline-path (&optional fastp level heading)
9300 "Return the outline path to the current entry, as a list.
9301 The parameters FASTP, LEVEL, and HEADING are for use be a scanner
9302 routine which makes outline path derivations for an entire file,
9303 avoiding backtracing."
9304 (if fastp
9305 (progn
9306 (if (> level 19)
9307 (error "Outline path failure, more than 19 levels."))
9308 (loop for i from level upto 19 do
9309 (aset org-olpa i nil))
9310 (prog1
9311 (delq nil (append org-olpa nil))
9312 (aset org-olpa level heading)))
9313 (let (rtn case-fold-search)
9314 (save-excursion
9315 (save-restriction
9316 (widen)
9317 (while (org-up-heading-safe)
9318 (when (looking-at org-complex-heading-regexp)
9319 (push (org-match-string-no-properties 4) rtn)))
9320 rtn)))))
9322 (defun org-format-outline-path (path &optional width prefix)
9323 "Format the outlie path PATH for display.
9324 Width is the maximum number of characters that is available.
9325 Prefix is a prefix to be included in the returned string,
9326 such as the file name."
9327 (setq width (or width 79))
9328 (if prefix (setq width (- width (length prefix))))
9329 (if (not path)
9330 (or prefix "")
9331 (let* ((nsteps (length path))
9332 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
9333 (maxwidth (if (<= total-width width)
9334 10000 ;; everything fits
9335 ;; we need to shorten the level headings
9336 (/ (- width nsteps) nsteps)))
9337 (org-odd-levels-only nil)
9338 (n 0)
9339 (total (1+ (length prefix))))
9340 (setq maxwidth (max maxwidth 10))
9341 (concat prefix
9342 (mapconcat
9343 (lambda (h)
9344 (setq n (1+ n))
9345 (if (and (= n nsteps) (< maxwidth 10000))
9346 (setq maxwidth (- total-width total)))
9347 (if (< (length h) maxwidth)
9348 (progn (setq total (+ total (length h) 1)) h)
9349 (setq h (substring h 0 (- maxwidth 2))
9350 total (+ total maxwidth 1))
9351 (if (string-match "[ \t]+\\'" h)
9352 (setq h (substring h 0 (match-beginning 0))))
9353 (setq h (concat h "..")))
9354 (org-add-props h nil 'face
9355 (nth (% (1- n) org-n-level-faces)
9356 org-level-faces))
9358 path "/")))))
9360 (defun org-display-outline-path (&optional file current)
9361 "Display the current outline path in the echo area."
9362 (interactive "P")
9363 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
9364 (case-fold-search nil)
9365 (path (and (org-mode-p) (org-get-outline-path))))
9366 (if current (setq path (append path
9367 (save-excursion
9368 (org-back-to-heading t)
9369 (if (looking-at org-complex-heading-regexp)
9370 (list (match-string 4)))))))
9371 (message "%s"
9372 (org-format-outline-path
9373 path
9374 (1- (frame-width))
9375 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
9377 (defvar org-refile-history nil
9378 "History for refiling operations.")
9380 (defvar org-after-refile-insert-hook nil
9381 "Hook run after `org-refile' has inserted its stuff at the new location.
9382 Note that this is still *before* the stuff will be removed from
9383 the *old* location.")
9385 (defun org-refile (&optional goto default-buffer rfloc)
9386 "Move the entry at point to another heading.
9387 The list of target headings is compiled using the information in
9388 `org-refile-targets', which see. This list is created before each use
9389 and will therefore always be up-to-date.
9391 At the target location, the entry is filed as a subitem of the target heading.
9392 Depending on `org-reverse-note-order', the new subitem will either be the
9393 first or the last subitem.
9395 If there is an active region, all entries in that region will be moved.
9396 However, the region must fulfil the requirement that the first heading
9397 is the first one sets the top-level of the moved text - at most siblings
9398 below it are allowed.
9400 With prefix arg GOTO, the command will only visit the target location,
9401 not actually move anything.
9402 With a double prefix `C-u C-u', go to the location where the last refiling
9403 operation has put the subtree.
9404 With a prefix argument of `2', refile to the running clock.
9406 RFLOC can be a refile location obtained in a different way.
9408 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
9409 (interactive "P")
9410 (let* ((cbuf (current-buffer))
9411 (regionp (org-region-active-p))
9412 (region-start (and regionp (region-beginning)))
9413 (region-end (and regionp (region-end)))
9414 (region-length (and regionp (- region-end region-start)))
9415 (filename (buffer-file-name (buffer-base-buffer cbuf)))
9416 pos it nbuf file re level reversed)
9417 (setq last-command nil)
9418 (when regionp
9419 (goto-char region-start)
9420 (or (bolp) (goto-char (point-at-bol)))
9421 (setq region-start (point))
9422 (unless (org-kill-is-subtree-p
9423 (buffer-substring region-start region-end))
9424 (error "The region is not a (sequence of) subtree(s)")))
9425 (if (equal goto '(16))
9426 (org-refile-goto-last-stored)
9427 (when (or
9428 (and (equal goto 2)
9429 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
9430 (prog1
9431 (setq it (list (or org-clock-heading "running clock")
9432 (buffer-file-name
9433 (marker-buffer org-clock-hd-marker))
9435 (marker-position org-clock-hd-marker)))
9436 (setq goto nil)))
9437 (setq it (or rfloc
9438 (save-excursion
9439 (org-refile-get-location
9440 (if goto "Goto: " "Refile to: ") default-buffer
9441 org-refile-allow-creating-parent-nodes)))))
9442 (setq file (nth 1 it)
9443 re (nth 2 it)
9444 pos (nth 3 it))
9445 (if (and (not goto)
9447 (equal (buffer-file-name) file)
9448 (if regionp
9449 (and (>= pos region-start)
9450 (<= pos region-end))
9451 (and (>= pos (point))
9452 (< pos (save-excursion
9453 (org-end-of-subtree t t))))))
9454 (error "Cannot refile to position inside the tree or region"))
9456 (setq nbuf (or (find-buffer-visiting file)
9457 (find-file-noselect file)))
9458 (if goto
9459 (progn
9460 (switch-to-buffer nbuf)
9461 (goto-char pos)
9462 (org-show-context 'org-goto))
9463 (if regionp
9464 (progn
9465 (org-kill-new (buffer-substring region-start region-end))
9466 (org-save-markers-in-region region-start region-end))
9467 (org-copy-subtree 1 nil t))
9468 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
9469 (find-file-noselect file)))
9470 (setq reversed (org-notes-order-reversed-p))
9471 (save-excursion
9472 (save-restriction
9473 (widen)
9474 (if pos
9475 (progn
9476 (goto-char pos)
9477 (looking-at outline-regexp)
9478 (setq level (org-get-valid-level (funcall outline-level) 1))
9479 (goto-char
9480 (if reversed
9481 (or (outline-next-heading) (point-max))
9482 (or (save-excursion (org-get-next-sibling))
9483 (org-end-of-subtree t t)
9484 (point-max)))))
9485 (setq level 1)
9486 (if (not reversed)
9487 (goto-char (point-max))
9488 (goto-char (point-min))
9489 (or (outline-next-heading) (goto-char (point-max)))))
9490 (if (not (bolp)) (newline))
9491 (org-paste-subtree level)
9492 (and org-auto-align-tags (org-set-tags nil t))
9493 (bookmark-set "org-refile-last-stored")
9494 (if (fboundp 'deactivate-mark) (deactivate-mark))
9495 (run-hooks 'org-after-refile-insert-hook))))
9496 (if regionp
9497 (delete-region (point) (+ (point) region-length))
9498 (org-cut-subtree))
9499 (when (featurep 'org-inlinetask)
9500 (org-inlinetask-remove-END-maybe))
9501 (setq org-markers-to-move nil)
9502 (message "Refiled to \"%s\"" (car it))))))
9503 (org-reveal))
9505 (defun org-refile-goto-last-stored ()
9506 "Go to the location where the last refile was stored."
9507 (interactive)
9508 (bookmark-jump "org-refile-last-stored")
9509 (message "This is the location of the last refile"))
9511 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
9512 "Prompt the user for a refile location, using PROMPT."
9513 (let ((org-refile-targets org-refile-targets)
9514 (org-refile-use-outline-path org-refile-use-outline-path))
9515 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
9516 (unless org-refile-target-table
9517 (error "No refile targets"))
9518 (let* ((cbuf (current-buffer))
9519 (partial-completion-mode nil)
9520 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
9521 (cfunc (if (and org-refile-use-outline-path
9522 org-outline-path-complete-in-steps)
9523 'org-olpath-completing-read
9524 'org-icompleting-read))
9525 (extra (if org-refile-use-outline-path "/" ""))
9526 (filename (and cfn (expand-file-name cfn)))
9527 (tbl (mapcar
9528 (lambda (x)
9529 (if (and (not (member org-refile-use-outline-path
9530 '(file full-file-path)))
9531 (not (equal filename (nth 1 x))))
9532 (cons (concat (car x) extra " ("
9533 (file-name-nondirectory (nth 1 x)) ")")
9534 (cdr x))
9535 (cons (concat (car x) extra) (cdr x))))
9536 org-refile-target-table))
9537 (completion-ignore-case t)
9538 pa answ parent-target child parent old-hist)
9539 (setq old-hist org-refile-history)
9540 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
9541 nil 'org-refile-history))
9542 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
9543 (if pa
9544 (progn
9545 (when (or (not org-refile-history)
9546 (not (eq old-hist org-refile-history))
9547 (not (equal (car pa) (car org-refile-history))))
9548 (setq org-refile-history
9549 (cons (car pa) (if (assoc (car org-refile-history) tbl)
9550 org-refile-history
9551 (cdr org-refile-history))))
9552 (if (equal (car org-refile-history) (nth 1 org-refile-history))
9553 (pop org-refile-history)))
9555 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
9556 (progn
9557 (setq parent (match-string 1 answ)
9558 child (match-string 2 answ))
9559 (setq parent-target (or (assoc parent tbl)
9560 (assoc (concat parent "/") tbl)))
9561 (when (and parent-target
9562 (or (eq new-nodes t)
9563 (and (eq new-nodes 'confirm)
9564 (y-or-n-p (format "Create new node \"%s\"? "
9565 child)))))
9566 (org-refile-new-child parent-target child)))
9567 (error "Invalid target location")))))
9569 (defun org-refile-new-child (parent-target child)
9570 "Use refile target PARENT-TARGET to add new CHILD below it."
9571 (unless parent-target
9572 (error "Cannot find parent for new node"))
9573 (let ((file (nth 1 parent-target))
9574 (pos (nth 3 parent-target))
9575 level)
9576 (with-current-buffer (or (find-buffer-visiting file)
9577 (find-file-noselect file))
9578 (save-excursion
9579 (save-restriction
9580 (widen)
9581 (if pos
9582 (goto-char pos)
9583 (goto-char (point-max))
9584 (if (not (bolp)) (newline)))
9585 (when (looking-at outline-regexp)
9586 (setq level (funcall outline-level))
9587 (org-end-of-subtree t t))
9588 (org-back-over-empty-lines)
9589 (insert "\n" (make-string
9590 (if pos (org-get-valid-level level 1) 1) ?*)
9591 " " child "\n")
9592 (beginning-of-line 0)
9593 (list (concat (car parent-target) "/" child) file "" (point)))))))
9595 (defun org-olpath-completing-read (prompt collection &rest args)
9596 "Read an outline path like a file name."
9597 (let ((thetable collection)
9598 (org-completion-use-ido nil) ; does not work with ido.
9599 (org-completion-use-iswitchb nil)) ; or iswitchb
9600 (apply
9601 'org-icompleting-read prompt
9602 (lambda (string predicate &optional flag)
9603 (let (rtn r f (l (length string)))
9604 (cond
9605 ((eq flag nil)
9606 ;; try completion
9607 (try-completion string thetable))
9608 ((eq flag t)
9609 ;; all-completions
9610 (setq rtn (all-completions string thetable predicate))
9611 (mapcar
9612 (lambda (x)
9613 (setq r (substring x l))
9614 (if (string-match " ([^)]*)$" x)
9615 (setq f (match-string 0 x))
9616 (setq f ""))
9617 (if (string-match "/" r)
9618 (concat string (substring r 0 (match-end 0)) f)
9620 rtn))
9621 ((eq flag 'lambda)
9622 ;; exact match?
9623 (assoc string thetable)))
9625 args)))
9627 ;;;; Dynamic blocks
9629 (defun org-find-dblock (name)
9630 "Find the first dynamic block with name NAME in the buffer.
9631 If not found, stay at current position and return nil."
9632 (let (pos)
9633 (save-excursion
9634 (goto-char (point-min))
9635 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
9636 nil t)
9637 (match-beginning 0))))
9638 (if pos (goto-char pos))
9639 pos))
9641 (defconst org-dblock-start-re
9642 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
9643 "Matches the start line of a dynamic block, with parameters.")
9645 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
9646 "Matches the end of a dynamic block.")
9648 (defun org-create-dblock (plist)
9649 "Create a dynamic block section, with parameters taken from PLIST.
9650 PLIST must contain a :name entry which is used as name of the block."
9651 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
9652 (end-of-line 1)
9653 (newline))
9654 (let ((col (current-column))
9655 (name (plist-get plist :name)))
9656 (insert "#+BEGIN: " name)
9657 (while plist
9658 (if (eq (car plist) :name)
9659 (setq plist (cddr plist))
9660 (insert " " (prin1-to-string (pop plist)))))
9661 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
9662 (beginning-of-line -2)))
9664 (defun org-prepare-dblock ()
9665 "Prepare dynamic block for refresh.
9666 This empties the block, puts the cursor at the insert position and returns
9667 the property list including an extra property :name with the block name."
9668 (unless (looking-at org-dblock-start-re)
9669 (error "Not at a dynamic block"))
9670 (let* ((begdel (1+ (match-end 0)))
9671 (name (org-no-properties (match-string 1)))
9672 (params (append (list :name name)
9673 (read (concat "(" (match-string 3) ")")))))
9674 (save-excursion
9675 (beginning-of-line 1)
9676 (skip-chars-forward " \t")
9677 (setq params (plist-put params :indentation-column (current-column))))
9678 (unless (re-search-forward org-dblock-end-re nil t)
9679 (error "Dynamic block not terminated"))
9680 (setq params
9681 (append params
9682 (list :content (buffer-substring
9683 begdel (match-beginning 0)))))
9684 (delete-region begdel (match-beginning 0))
9685 (goto-char begdel)
9686 (open-line 1)
9687 params))
9689 (defun org-map-dblocks (&optional command)
9690 "Apply COMMAND to all dynamic blocks in the current buffer.
9691 If COMMAND is not given, use `org-update-dblock'."
9692 (let ((cmd (or command 'org-update-dblock))
9693 pos)
9694 (save-excursion
9695 (goto-char (point-min))
9696 (while (re-search-forward org-dblock-start-re nil t)
9697 (goto-char (setq pos (match-beginning 0)))
9698 (condition-case nil
9699 (funcall cmd)
9700 (error (message "Error during update of dynamic block")))
9701 (goto-char pos)
9702 (unless (re-search-forward org-dblock-end-re nil t)
9703 (error "Dynamic block not terminated"))))))
9705 (defun org-dblock-update (&optional arg)
9706 "User command for updating dynamic blocks.
9707 Update the dynamic block at point. With prefix ARG, update all dynamic
9708 blocks in the buffer."
9709 (interactive "P")
9710 (if arg
9711 (org-update-all-dblocks)
9712 (or (looking-at org-dblock-start-re)
9713 (org-beginning-of-dblock))
9714 (org-update-dblock)))
9716 (defun org-update-dblock ()
9717 "Update the dynamic block at point
9718 This means to empty the block, parse for parameters and then call
9719 the correct writing function."
9720 (save-window-excursion
9721 (let* ((pos (point))
9722 (line (org-current-line))
9723 (params (org-prepare-dblock))
9724 (name (plist-get params :name))
9725 (indent (plist-get params :indentation-column))
9726 (cmd (intern (concat "org-dblock-write:" name))))
9727 (message "Updating dynamic block `%s' at line %d..." name line)
9728 (funcall cmd params)
9729 (message "Updating dynamic block `%s' at line %d...done" name line)
9730 (goto-char pos)
9731 (when (and indent (> indent 0))
9732 (setq indent (make-string indent ?\ ))
9733 (save-excursion
9734 (org-beginning-of-dblock)
9735 (forward-line 1)
9736 (while (not (looking-at org-dblock-end-re))
9737 (insert indent)
9738 (beginning-of-line 2))
9739 (when (looking-at org-dblock-end-re)
9740 (and (looking-at "[ \t]+")
9741 (replace-match ""))
9742 (insert indent)))))))
9744 (defun org-beginning-of-dblock ()
9745 "Find the beginning of the dynamic block at point.
9746 Error if there is no such block at point."
9747 (let ((pos (point))
9748 beg)
9749 (end-of-line 1)
9750 (if (and (re-search-backward org-dblock-start-re nil t)
9751 (setq beg (match-beginning 0))
9752 (re-search-forward org-dblock-end-re nil t)
9753 (> (match-end 0) pos))
9754 (goto-char beg)
9755 (goto-char pos)
9756 (error "Not in a dynamic block"))))
9758 (defun org-update-all-dblocks ()
9759 "Update all dynamic blocks in the buffer.
9760 This function can be used in a hook."
9761 (when (org-mode-p)
9762 (org-map-dblocks 'org-update-dblock)))
9765 ;;;; Completion
9767 (defconst org-additional-option-like-keywords
9768 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
9769 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
9770 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
9771 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX"
9772 "BEGIN:" "END:"
9773 "ORGTBL" "TBLFM:" "TBLNAME:"
9774 "BEGIN_EXAMPLE" "END_EXAMPLE"
9775 "BEGIN_QUOTE" "END_QUOTE"
9776 "BEGIN_VERSE" "END_VERSE"
9777 "BEGIN_CENTER" "END_CENTER"
9778 "BEGIN_SRC" "END_SRC"
9779 "CATEGORY" "COLUMNS"
9780 "CAPTION" "LABEL"
9781 "SETUPFILE"
9782 "BIND"
9783 "MACRO"))
9785 (defcustom org-structure-template-alist
9787 ("s" "#+begin_src ?\n\n#+end_src"
9788 "<src lang=\"?\">\n\n</src>")
9789 ("e" "#+begin_example\n?\n#+end_example"
9790 "<example>\n?\n</example>")
9791 ("q" "#+begin_quote\n?\n#+end_quote"
9792 "<quote>\n?\n</quote>")
9793 ("v" "#+begin_verse\n?\n#+end_verse"
9794 "<verse>\n?\n/verse>")
9795 ("c" "#+begin_center\n?\n#+end_center"
9796 "<center>\n?\n/center>")
9797 ("l" "#+begin_latex\n?\n#+end_latex"
9798 "<literal style=\"latex\">\n?\n</literal>")
9799 ("L" "#+latex: "
9800 "<literal style=\"latex\">?</literal>")
9801 ("h" "#+begin_html\n?\n#+end_html"
9802 "<literal style=\"html\">\n?\n</literal>")
9803 ("H" "#+html: "
9804 "<literal style=\"html\">?</literal>")
9805 ("a" "#+begin_ascii\n?\n#+end_ascii")
9806 ("A" "#+ascii: ")
9807 ("i" "#+include %file ?"
9808 "<include file=%file markup=\"?\">")
9810 "Structure completion elements.
9811 This is a list of abbreviation keys and values. The value gets inserted
9812 it you type @samp{.} followed by the key and then the completion key,
9813 usually `M-TAB'. %file will be replaced by a file name after prompting
9814 for the file using completion.
9815 There are two templates for each key, the first uses the original Org syntax,
9816 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
9817 the default when the /org-mtags.el/ module has been loaded. See also the
9818 variable `org-mtags-prefer-muse-templates'.
9819 This is an experimental feature, it is undecided if it is going to stay in."
9820 :group 'org-completion
9821 :type '(repeat
9822 (string :tag "Key")
9823 (string :tag "Template")
9824 (string :tag "Muse Template")))
9826 (defun org-try-structure-completion ()
9827 "Try to complete a structure template before point.
9828 This looks for strings like \"<e\" on an otherwise empty line and
9829 expands them."
9830 (let ((l (buffer-substring (point-at-bol) (point)))
9832 (when (and (looking-at "[ \t]*$")
9833 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9834 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9835 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9836 (match-beginning 1)) a)
9837 t)))
9839 (defun org-complete-expand-structure-template (start cell)
9840 "Expand a structure template."
9841 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
9842 (rpl (nth (if musep 2 1) cell))
9843 (ind ""))
9844 (delete-region start (point))
9845 (when (string-match "\\`#\\+" rpl)
9846 (cond
9847 ((bolp))
9848 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
9849 (setq ind (buffer-substring (point-at-bol) (point))))
9850 (t (newline))))
9851 (setq start (point))
9852 (if (string-match "%file" rpl)
9853 (setq rpl (replace-match
9854 (concat
9855 "\""
9856 (save-match-data
9857 (abbreviate-file-name (read-file-name "Include file: ")))
9858 "\"")
9859 t t rpl)))
9860 (setq rpl (mapconcat 'identity (split-string rpl "\n")
9861 (concat "\n" ind)))
9862 (insert rpl)
9863 (if (re-search-backward "\\?" start t) (delete-char 1))))
9866 (defun org-complete (&optional arg)
9867 "Perform completion on word at point.
9868 At the beginning of a headline, this completes TODO keywords as given in
9869 `org-todo-keywords'.
9870 If the current word is preceded by a backslash, completes the TeX symbols
9871 that are supported for HTML support.
9872 If the current word is preceded by \"#+\", completes special words for
9873 setting file options.
9874 In the line after \"#+STARTUP:, complete valid keywords.\"
9875 At all other locations, this simply calls the value of
9876 `org-completion-fallback-command'."
9877 (interactive "P")
9878 (org-without-partial-completion
9879 (catch 'exit
9880 (let* ((a nil)
9881 (end (point))
9882 (beg1 (save-excursion
9883 (skip-chars-backward (org-re "[:alnum:]_@"))
9884 (point)))
9885 (beg (save-excursion
9886 (skip-chars-backward "a-zA-Z0-9_:$")
9887 (point)))
9888 (confirm (lambda (x) (stringp (car x))))
9889 (searchhead (equal (char-before beg) ?*))
9890 (struct
9891 (when (and (member (char-before beg1) '(?. ?<))
9892 (setq a (assoc (buffer-substring beg1 (point))
9893 org-structure-template-alist)))
9894 (org-complete-expand-structure-template (1- beg1) a)
9895 (throw 'exit t)))
9896 (tag (and (equal (char-before beg1) ?:)
9897 (equal (char-after (point-at-bol)) ?*)))
9898 (prop (and (equal (char-before beg1) ?:)
9899 (not (equal (char-after (point-at-bol)) ?*))))
9900 (texp (equal (char-before beg) ?\\))
9901 (link (equal (char-before beg) ?\[))
9902 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9903 beg)
9904 "#+"))
9905 (startup (string-match "^#\\+STARTUP:.*"
9906 (buffer-substring (point-at-bol) (point))))
9907 (completion-ignore-case opt)
9908 (type nil)
9909 (tbl nil)
9910 (table (cond
9911 (opt
9912 (setq type :opt)
9913 (require 'org-exp)
9914 (append
9915 (delq nil
9916 (mapcar
9917 (lambda (x)
9918 (if (string-match
9919 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9920 (cons (match-string 2 x)
9921 (match-string 1 x))))
9922 (org-split-string (org-get-current-options) "\n")))
9923 (mapcar 'list org-additional-option-like-keywords)))
9924 (startup
9925 (setq type :startup)
9926 org-startup-options)
9927 (link (append org-link-abbrev-alist-local
9928 org-link-abbrev-alist))
9929 (texp
9930 (setq type :tex)
9931 org-html-entities)
9932 ((string-match "\\`\\*+[ \t]+\\'"
9933 (buffer-substring (point-at-bol) beg))
9934 (setq type :todo)
9935 (mapcar 'list org-todo-keywords-1))
9936 (searchhead
9937 (setq type :searchhead)
9938 (save-excursion
9939 (goto-char (point-min))
9940 (while (re-search-forward org-todo-line-regexp nil t)
9941 (push (list
9942 (org-make-org-heading-search-string
9943 (match-string 3) t))
9944 tbl)))
9945 tbl)
9946 (tag (setq type :tag beg beg1)
9947 (or org-tag-alist (org-get-buffer-tags)))
9948 (prop (setq type :prop beg beg1)
9949 (mapcar 'list (org-buffer-property-keys nil t t)))
9950 (t (progn
9951 (call-interactively org-completion-fallback-command)
9952 (throw 'exit nil)))))
9953 (pattern (buffer-substring-no-properties beg end))
9954 (completion (try-completion pattern table confirm)))
9955 (cond ((eq completion t)
9956 (if (not (assoc (upcase pattern) table))
9957 (message "Already complete")
9958 (if (and (equal type :opt)
9959 (not (member (car (assoc (upcase pattern) table))
9960 org-additional-option-like-keywords)))
9961 (insert (substring (cdr (assoc (upcase pattern) table))
9962 (length pattern)))
9963 (if (memq type '(:tag :prop)) (insert ":")))))
9964 ((null completion)
9965 (message "Can't find completion for \"%s\"" pattern)
9966 (ding))
9967 ((not (string= pattern completion))
9968 (delete-region beg end)
9969 (if (string-match " +$" completion)
9970 (setq completion (replace-match "" t t completion)))
9971 (insert completion)
9972 (if (get-buffer-window "*Completions*")
9973 (delete-window (get-buffer-window "*Completions*")))
9974 (if (assoc completion table)
9975 (if (eq type :todo) (insert " ")
9976 (if (memq type '(:tag :prop)) (insert ":"))))
9977 (if (and (equal type :opt) (assoc completion table))
9978 (message "%s" (substitute-command-keys
9979 "Press \\[org-complete] again to insert example settings"))))
9981 (message "Making completion list...")
9982 (let ((list (sort (all-completions pattern table confirm)
9983 'string<)))
9984 (with-output-to-temp-buffer "*Completions*"
9985 (condition-case nil
9986 ;; Protection needed for XEmacs and emacs 21
9987 (display-completion-list list pattern)
9988 (error (display-completion-list list)))))
9989 (message "Making completion list...%s" "done")))))))
9991 ;;;; TODO, DEADLINE, Comments
9993 (defun org-toggle-comment ()
9994 "Change the COMMENT state of an entry."
9995 (interactive)
9996 (save-excursion
9997 (org-back-to-heading)
9998 (let (case-fold-search)
9999 (if (looking-at (concat outline-regexp
10000 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
10001 (replace-match "" t t nil 1)
10002 (if (looking-at outline-regexp)
10003 (progn
10004 (goto-char (match-end 0))
10005 (insert org-comment-string " ")))))))
10007 (defvar org-last-todo-state-is-todo nil
10008 "This is non-nil when the last TODO state change led to a TODO state.
10009 If the last change removed the TODO tag or switched to DONE, then
10010 this is nil.")
10012 (defvar org-setting-tags nil) ; dynamically skipped
10014 (defun org-parse-local-options (string var)
10015 "Parse STRING for startup setting relevant for variable VAR."
10016 (let ((rtn (symbol-value var))
10017 e opts)
10018 (save-match-data
10019 (if (or (not string) (not (string-match "\\S-" string)))
10021 (setq opts (delq nil (mapcar (lambda (x)
10022 (setq e (assoc x org-startup-options))
10023 (if (eq (nth 1 e) var) e nil))
10024 (org-split-string string "[ \t]+"))))
10025 (if (not opts)
10027 (setq rtn nil)
10028 (while (setq e (pop opts))
10029 (if (not (nth 3 e))
10030 (setq rtn (nth 2 e))
10031 (if (not (listp rtn)) (setq rtn nil))
10032 (push (nth 2 e) rtn)))
10033 rtn)))))
10035 (defvar org-todo-setup-filter-hook nil
10036 "Hook for functions that pre-filter todo specs.
10038 Each function takes a todo spec and returns either `nil' or the spec
10039 transformed into canonical form." )
10041 (defvar org-todo-get-default-hook nil
10042 "Hook for functions that get a default item for todo.
10044 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
10045 `nil' or a string to be used for the todo mark." )
10047 (defvar org-agenda-headline-snapshot-before-repeat)
10049 (defun org-todo (&optional arg)
10050 "Change the TODO state of an item.
10051 The state of an item is given by a keyword at the start of the heading,
10052 like
10053 *** TODO Write paper
10054 *** DONE Call mom
10056 The different keywords are specified in the variable `org-todo-keywords'.
10057 By default the available states are \"TODO\" and \"DONE\".
10058 So for this example: when the item starts with TODO, it is changed to DONE.
10059 When it starts with DONE, the DONE is removed. And when neither TODO nor
10060 DONE are present, add TODO at the beginning of the heading.
10062 With C-u prefix arg, use completion to determine the new state.
10063 With numeric prefix arg, switch to that state.
10064 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
10065 With a triple C-u prefix, circumvent any state blocking.
10067 For calling through lisp, arg is also interpreted in the following way:
10068 'none -> empty state
10069 \"\"(empty string) -> switch to empty state
10070 'done -> switch to DONE
10071 'nextset -> switch to the next set of keywords
10072 'previousset -> switch to the previous set of keywords
10073 \"WAITING\" -> switch to the specified keyword, but only if it
10074 really is a member of `org-todo-keywords'."
10075 (interactive "P")
10076 (if (equal arg '(16)) (setq arg 'nextset))
10077 (let ((org-blocker-hook org-blocker-hook)
10078 (case-fold-search nil))
10079 (when (equal arg '(64))
10080 (setq arg nil org-blocker-hook nil))
10081 (when (and org-blocker-hook
10082 (or org-inhibit-blocking
10083 (org-entry-get nil "NOBLOCKING")))
10084 (setq org-blocker-hook nil))
10085 (save-excursion
10086 (catch 'exit
10087 (org-back-to-heading t)
10088 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
10089 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
10090 (looking-at " *"))
10091 (let* ((match-data (match-data))
10092 (startpos (point-at-bol))
10093 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
10094 (org-log-done org-log-done)
10095 (org-log-repeat org-log-repeat)
10096 (org-todo-log-states org-todo-log-states)
10097 (this (match-string 1))
10098 (hl-pos (match-beginning 0))
10099 (head (org-get-todo-sequence-head this))
10100 (ass (assoc head org-todo-kwd-alist))
10101 (interpret (nth 1 ass))
10102 (done-word (nth 3 ass))
10103 (final-done-word (nth 4 ass))
10104 (last-state (or this ""))
10105 (completion-ignore-case t)
10106 (member (member this org-todo-keywords-1))
10107 (tail (cdr member))
10108 (state (cond
10109 ((and org-todo-key-trigger
10110 (or (and (equal arg '(4))
10111 (eq org-use-fast-todo-selection 'prefix))
10112 (and (not arg) org-use-fast-todo-selection
10113 (not (eq org-use-fast-todo-selection
10114 'prefix)))))
10115 ;; Use fast selection
10116 (org-fast-todo-selection))
10117 ((and (equal arg '(4))
10118 (or (not org-use-fast-todo-selection)
10119 (not org-todo-key-trigger)))
10120 ;; Read a state with completion
10121 (org-icompleting-read
10122 "State: " (mapcar (lambda(x) (list x))
10123 org-todo-keywords-1)
10124 nil t))
10125 ((eq arg 'right)
10126 (if this
10127 (if tail (car tail) nil)
10128 (car org-todo-keywords-1)))
10129 ((eq arg 'left)
10130 (if (equal member org-todo-keywords-1)
10132 (if this
10133 (nth (- (length org-todo-keywords-1)
10134 (length tail) 2)
10135 org-todo-keywords-1)
10136 (org-last org-todo-keywords-1))))
10137 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10138 (setq arg nil))) ; hack to fall back to cycling
10139 (arg
10140 ;; user or caller requests a specific state
10141 (cond
10142 ((equal arg "") nil)
10143 ((eq arg 'none) nil)
10144 ((eq arg 'done) (or done-word (car org-done-keywords)))
10145 ((eq arg 'nextset)
10146 (or (car (cdr (member head org-todo-heads)))
10147 (car org-todo-heads)))
10148 ((eq arg 'previousset)
10149 (let ((org-todo-heads (reverse org-todo-heads)))
10150 (or (car (cdr (member head org-todo-heads)))
10151 (car org-todo-heads))))
10152 ((car (member arg org-todo-keywords-1)))
10153 ((stringp arg)
10154 (error "State `%s' not valid in this file" arg))
10155 ((nth (1- (prefix-numeric-value arg))
10156 org-todo-keywords-1))))
10157 ((null member) (or head (car org-todo-keywords-1)))
10158 ((equal this final-done-word) nil) ;; -> make empty
10159 ((null tail) nil) ;; -> first entry
10160 ((memq interpret '(type priority))
10161 (if (eq this-command last-command)
10162 (car tail)
10163 (if (> (length tail) 0)
10164 (or done-word (car org-done-keywords))
10165 nil)))
10167 (car tail))))
10168 (state (or
10169 (run-hook-with-args-until-success
10170 'org-todo-get-default-hook state last-state)
10171 state))
10172 (next (if state (concat " " state " ") " "))
10173 (change-plist (list :type 'todo-state-change :from this :to state
10174 :position startpos))
10175 dolog now-done-p)
10176 (when org-blocker-hook
10177 (setq org-last-todo-state-is-todo
10178 (not (member this org-done-keywords)))
10179 (unless (save-excursion
10180 (save-match-data
10181 (run-hook-with-args-until-failure
10182 'org-blocker-hook change-plist)))
10183 (if (interactive-p)
10184 (error "TODO state change from %s to %s blocked" this state)
10185 ;; fail silently
10186 (message "TODO state change from %s to %s blocked" this state)
10187 (throw 'exit nil))))
10188 (store-match-data match-data)
10189 (replace-match next t t)
10190 (unless (pos-visible-in-window-p hl-pos)
10191 (message "TODO state changed to %s" (org-trim next)))
10192 (unless head
10193 (setq head (org-get-todo-sequence-head state)
10194 ass (assoc head org-todo-kwd-alist)
10195 interpret (nth 1 ass)
10196 done-word (nth 3 ass)
10197 final-done-word (nth 4 ass)))
10198 (when (memq arg '(nextset previousset))
10199 (message "Keyword-Set %d/%d: %s"
10200 (- (length org-todo-sets) -1
10201 (length (memq (assoc state org-todo-sets) org-todo-sets)))
10202 (length org-todo-sets)
10203 (mapconcat 'identity (assoc state org-todo-sets) " ")))
10204 (setq org-last-todo-state-is-todo
10205 (not (member state org-done-keywords)))
10206 (setq now-done-p (and (member state org-done-keywords)
10207 (not (member this org-done-keywords))))
10208 (and logging (org-local-logging logging))
10209 (when (and (or org-todo-log-states org-log-done)
10210 (not (eq org-inhibit-logging t))
10211 (not (memq arg '(nextset previousset))))
10212 ;; we need to look at recording a time and note
10213 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
10214 (nth 2 (assoc this org-todo-log-states))))
10215 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
10216 (setq dolog 'time))
10217 (when (and state
10218 (member state org-not-done-keywords)
10219 (not (member this org-not-done-keywords)))
10220 ;; This is now a todo state and was not one before
10221 ;; If there was a CLOSED time stamp, get rid of it.
10222 (org-add-planning-info nil nil 'closed))
10223 (when (and now-done-p org-log-done)
10224 ;; It is now done, and it was not done before
10225 (org-add-planning-info 'closed (org-current-time))
10226 (if (and (not dolog) (eq 'note org-log-done))
10227 (org-add-log-setup 'done state this 'findpos 'note)))
10228 (when (and state dolog)
10229 ;; This is a non-nil state, and we need to log it
10230 (org-add-log-setup 'state state this 'findpos dolog)))
10231 ;; Fixup tag positioning
10232 (org-todo-trigger-tag-changes state)
10233 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
10234 (when org-provide-todo-statistics
10235 (org-update-parent-todo-statistics))
10236 (run-hooks 'org-after-todo-state-change-hook)
10237 (if (and arg (not (member state org-done-keywords)))
10238 (setq head (org-get-todo-sequence-head state)))
10239 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
10240 ;; Do we need to trigger a repeat?
10241 (when now-done-p
10242 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
10243 ;; This is for the agenda, take a snapshot of the headline.
10244 (save-match-data
10245 (setq org-agenda-headline-snapshot-before-repeat
10246 (org-get-heading))))
10247 (org-auto-repeat-maybe state))
10248 ;; Fixup cursor location if close to the keyword
10249 (if (and (outline-on-heading-p)
10250 (not (bolp))
10251 (save-excursion (beginning-of-line 1)
10252 (looking-at org-todo-line-regexp))
10253 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
10254 (progn
10255 (goto-char (or (match-end 2) (match-end 1)))
10256 (and (looking-at " ") (just-one-space))))
10257 (when org-trigger-hook
10258 (save-excursion
10259 (run-hook-with-args 'org-trigger-hook change-plist))))))))
10261 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
10262 "Block turning an entry into a TODO, using the hierarchy.
10263 This checks whether the current task should be blocked from state
10264 changes. Such blocking occurs when:
10266 1. The task has children which are not all in a completed state.
10268 2. A task has a parent with the property :ORDERED:, and there
10269 are siblings prior to the current task with incomplete
10270 status.
10272 3. The parent of the task is blocked because it has siblings that should
10273 be done first, or is child of a block grandparent TODO entry."
10275 (if (not org-enforce-todo-dependencies)
10276 t ; if locally turned off don't block
10277 (catch 'dont-block
10278 ;; If this is not a todo state change, or if this entry is already DONE,
10279 ;; do not block
10280 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10281 (member (plist-get change-plist :from)
10282 (cons 'done org-done-keywords))
10283 (member (plist-get change-plist :to)
10284 (cons 'todo org-not-done-keywords))
10285 (not (plist-get change-plist :to)))
10286 (throw 'dont-block t))
10287 ;; If this task has children, and any are undone, it's blocked
10288 (save-excursion
10289 (org-back-to-heading t)
10290 (let ((this-level (funcall outline-level)))
10291 (outline-next-heading)
10292 (let ((child-level (funcall outline-level)))
10293 (while (and (not (eobp))
10294 (> child-level this-level))
10295 ;; this todo has children, check whether they are all
10296 ;; completed
10297 (if (and (not (org-entry-is-done-p))
10298 (org-entry-is-todo-p))
10299 (throw 'dont-block nil))
10300 (outline-next-heading)
10301 (setq child-level (funcall outline-level))))))
10302 ;; Otherwise, if the task's parent has the :ORDERED: property, and
10303 ;; any previous siblings are undone, it's blocked
10304 (save-excursion
10305 (org-back-to-heading t)
10306 (let* ((pos (point))
10307 (parent-pos (and (org-up-heading-safe) (point))))
10308 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10309 (when (and (org-entry-get (point) "ORDERED")
10310 (forward-line 1)
10311 (re-search-forward org-not-done-heading-regexp pos t))
10312 (throw 'dont-block nil)) ; block, there is an older sibling not done.
10313 ;; Search further up the hierarchy, to see if an anchestor is blocked
10314 (while t
10315 (goto-char parent-pos)
10316 (if (not (looking-at org-not-done-heading-regexp))
10317 (throw 'dont-block t)) ; do not block, parent is not a TODO
10318 (setq pos (point))
10319 (setq parent-pos (and (org-up-heading-safe) (point)))
10320 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10321 (when (and (org-entry-get (point) "ORDERED")
10322 (forward-line 1)
10323 (re-search-forward org-not-done-heading-regexp pos t))
10324 (throw 'dont-block nil)))))))) ; block, older sibling not done.
10326 (defcustom org-track-ordered-property-with-tag nil
10327 "Should the ORDERED property also be shown as a tag?
10328 The ORDERED property decides if an entry should require subtasks to be
10329 completed in sequence. Since a property is not very visible, setting
10330 this option means that toggling the ORDERED property with the command
10331 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
10332 not relevant for the behavior, but it makes things more visible.
10334 Note that toggling the tag with tags commands will not change the property
10335 and therefore not influence behavior!
10337 This can be t, meaning the tag ORDERED should be used, It can also be a
10338 string to select a different tag for this task."
10339 :group 'org-todo
10340 :type '(choice
10341 (const :tag "No tracking" nil)
10342 (const :tag "Track with ORDERED tag" t)
10343 (string :tag "Use other tag")))
10345 (defun org-toggle-ordered-property ()
10346 "Toggle the ORDERED property of the current entry.
10347 For better visibility, you can track the value of this property with a tag.
10348 See variable `org-track-ordered-property-with-tag'."
10349 (interactive)
10350 (let* ((t1 org-track-ordered-property-with-tag)
10351 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
10352 (save-excursion
10353 (org-back-to-heading)
10354 (if (org-entry-get nil "ORDERED")
10355 (progn
10356 (org-delete-property "ORDERED")
10357 (and tag (org-toggle-tag tag 'off))
10358 (message "Subtasks can be completed in arbitrary order"))
10359 (org-entry-put nil "ORDERED" "t")
10360 (and tag (org-toggle-tag tag 'on))
10361 (message "Subtasks must be completed in sequence")))))
10363 (defvar org-blocked-by-checkboxes) ; dynamically scoped
10364 (defun org-block-todo-from-checkboxes (change-plist)
10365 "Block turning an entry into a TODO, using checkboxes.
10366 This checks whether the current task should be blocked from state
10367 changes because there are unchecked boxes in this entry."
10368 (if (not org-enforce-todo-checkbox-dependencies)
10369 t ; if locally turned off don't block
10370 (catch 'dont-block
10371 ;; If this is not a todo state change, or if this entry is already DONE,
10372 ;; do not block
10373 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10374 (member (plist-get change-plist :from)
10375 (cons 'done org-done-keywords))
10376 (member (plist-get change-plist :to)
10377 (cons 'todo org-not-done-keywords))
10378 (not (plist-get change-plist :to)))
10379 (throw 'dont-block t))
10380 ;; If this task has checkboxes that are not checked, it's blocked
10381 (save-excursion
10382 (org-back-to-heading t)
10383 (let ((beg (point)) end)
10384 (outline-next-heading)
10385 (setq end (point))
10386 (goto-char beg)
10387 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
10388 end t)
10389 (progn
10390 (if (boundp 'org-blocked-by-checkboxes)
10391 (setq org-blocked-by-checkboxes t))
10392 (throw 'dont-block nil)))))
10393 t))) ; do not block
10395 (defun org-entry-blocked-p ()
10396 "Is the current entry blocked?"
10397 (if (org-entry-get nil "NOBLOCKING")
10398 nil ;; Never block this entry
10399 (not
10400 (run-hook-with-args-until-failure
10401 'org-blocker-hook
10402 (list :type 'todo-state-change
10403 :position (point)
10404 :from 'todo
10405 :to 'done)))))
10407 (defun org-update-statistics-cookies (all)
10408 "Update the statistics cookie, either from TODO or from checkboxes.
10409 This should be called with the cursor in a line with a statistics cookie."
10410 (interactive "P")
10411 (if all
10412 (progn
10413 (org-update-checkbox-count 'all)
10414 (org-map-entries 'org-update-parent-todo-statistics))
10415 (if (not (org-on-heading-p))
10416 (org-update-checkbox-count)
10417 (let ((pos (move-marker (make-marker) (point)))
10418 end l1 l2)
10419 (ignore-errors (org-back-to-heading t))
10420 (if (not (org-on-heading-p))
10421 (org-update-checkbox-count)
10422 (setq l1 (org-outline-level))
10423 (setq end (save-excursion
10424 (outline-next-heading)
10425 (if (org-on-heading-p) (setq l2 (org-outline-level)))
10426 (point)))
10427 (if (and (save-excursion
10428 (re-search-forward
10429 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
10430 (not (save-excursion (re-search-forward
10431 ":COOKIE_DATA:.*\\<todo\\>" end t))))
10432 (org-update-checkbox-count)
10433 (if (and l2 (> l2 l1))
10434 (progn
10435 (goto-char end)
10436 (org-update-parent-todo-statistics))
10437 (goto-char pos)
10438 (beginning-of-line 1)
10439 (while (re-search-forward
10440 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
10441 (point-at-eol) t)
10442 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
10443 (goto-char pos)
10444 (move-marker pos nil)))))
10446 (defvar org-entry-property-inherited-from) ;; defined below
10447 (defun org-update-parent-todo-statistics ()
10448 "Update any statistics cookie in the parent of the current headline.
10449 When `org-hierarchical-todo-statistics' is nil, statistics will cover
10450 the entire subtree and this will travel up the hierarchy and update
10451 statistics everywhere."
10452 (interactive)
10453 (let* ((lim 0) prop
10454 (recursive (or (not org-hierarchical-todo-statistics)
10455 (string-match
10456 "\\<recursive\\>"
10457 (or (setq prop (org-entry-get
10458 nil "COOKIE_DATA" 'inherit)) ""))))
10459 (lim (or (and prop (marker-position
10460 org-entry-property-inherited-from))
10461 lim))
10462 (first t)
10463 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
10464 level ltoggle l1 new ndel
10465 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
10466 (catch 'exit
10467 (save-excursion
10468 (beginning-of-line 1)
10469 (if (org-at-heading-p)
10470 (setq ltoggle (funcall outline-level))
10471 (error "This should not happen"))
10472 (while (and (setq level (org-up-heading-safe))
10473 (or recursive first)
10474 (>= (point) lim))
10475 (setq first nil cookie-present nil)
10476 (unless (and level
10477 (not (string-match
10478 "\\<checkbox\\>"
10479 (downcase
10480 (or (org-entry-get
10481 nil "COOKIE_DATA")
10482 "")))))
10483 (throw 'exit nil))
10484 (while (re-search-forward box-re (point-at-eol) t)
10485 (setq cnt-all 0 cnt-done 0 cookie-present t)
10486 (setq is-percent (match-end 2))
10487 (save-match-data
10488 (unless (outline-next-heading) (throw 'exit nil))
10489 (while (and (looking-at org-complex-heading-regexp)
10490 (> (setq l1 (length (match-string 1))) level))
10491 (setq kwd (and (or recursive (= l1 ltoggle))
10492 (match-string 2)))
10493 (if (or (eq org-provide-todo-statistics 'all-headlines)
10494 (and (listp org-provide-todo-statistics)
10495 (or (member kwd org-provide-todo-statistics)
10496 (member kwd org-done-keywords))))
10497 (setq cnt-all (1+ cnt-all))
10498 (if (eq org-provide-todo-statistics t)
10499 (and kwd (setq cnt-all (1+ cnt-all)))))
10500 (and (member kwd org-done-keywords)
10501 (setq cnt-done (1+ cnt-done)))
10502 (outline-next-heading)))
10503 (setq new
10504 (if is-percent
10505 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
10506 (format "[%d/%d]" cnt-done cnt-all))
10507 ndel (- (match-end 0) (match-beginning 0)))
10508 (goto-char (match-beginning 0))
10509 (insert new)
10510 (delete-region (point) (+ (point) ndel)))
10511 (when cookie-present
10512 (run-hook-with-args 'org-after-todo-statistics-hook
10513 cnt-done (- cnt-all cnt-done))))))
10514 (run-hooks 'org-todo-statistics-hook)))
10516 (defvar org-after-todo-statistics-hook nil
10517 "Hook that is called after a TODO statistics cookie has been updated.
10518 Each function is called with two arguments: the number of not-done entries
10519 and the number of done entries.
10521 For example, the following function, when added to this hook, will switch
10522 an entry to DONE when all children are done, and back to TODO when new
10523 entries are set to a TODO status. Note that this hook is only called
10524 when there is a statistics cookie in the headline!
10526 (defun org-summary-todo (n-done n-not-done)
10527 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
10528 (let (org-log-done org-log-states) ; turn off logging
10529 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
10532 (defvar org-todo-statistics-hook nil
10533 "Hook that is run whenever Org thinks TODO statistics should be updated.
10534 This hook runs even if there is no statistics cookie present, in which case
10535 `org-after-todo-statistics-hook' would not run.")
10537 (defun org-todo-trigger-tag-changes (state)
10538 "Apply the changes defined in `org-todo-state-tags-triggers'."
10539 (let ((l org-todo-state-tags-triggers)
10540 changes)
10541 (when (or (not state) (equal state ""))
10542 (setq changes (append changes (cdr (assoc "" l)))))
10543 (when (and (stringp state) (> (length state) 0))
10544 (setq changes (append changes (cdr (assoc state l)))))
10545 (when (member state org-not-done-keywords)
10546 (setq changes (append changes (cdr (assoc 'todo l)))))
10547 (when (member state org-done-keywords)
10548 (setq changes (append changes (cdr (assoc 'done l)))))
10549 (dolist (c changes)
10550 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
10552 (defun org-local-logging (value)
10553 "Get logging settings from a property VALUE."
10554 (let* (words w a)
10555 ;; directly set the variables, they are already local.
10556 (setq org-log-done nil
10557 org-log-repeat nil
10558 org-todo-log-states nil)
10559 (setq words (org-split-string value))
10560 (while (setq w (pop words))
10561 (cond
10562 ((setq a (assoc w org-startup-options))
10563 (and (member (nth 1 a) '(org-log-done org-log-repeat))
10564 (set (nth 1 a) (nth 2 a))))
10565 ((setq a (org-extract-log-state-settings w))
10566 (and (member (car a) org-todo-keywords-1)
10567 (push a org-todo-log-states)))))))
10569 (defun org-get-todo-sequence-head (kwd)
10570 "Return the head of the TODO sequence to which KWD belongs.
10571 If KWD is not set, check if there is a text property remembering the
10572 right sequence."
10573 (let (p)
10574 (cond
10575 ((not kwd)
10576 (or (get-text-property (point-at-bol) 'org-todo-head)
10577 (progn
10578 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
10579 nil (point-at-eol)))
10580 (get-text-property p 'org-todo-head))))
10581 ((not (member kwd org-todo-keywords-1))
10582 (car org-todo-keywords-1))
10583 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
10585 (defun org-fast-todo-selection ()
10586 "Fast TODO keyword selection with single keys.
10587 Returns the new TODO keyword, or nil if no state change should occur."
10588 (let* ((fulltable org-todo-key-alist)
10589 (done-keywords org-done-keywords) ;; needed for the faces.
10590 (maxlen (apply 'max (mapcar
10591 (lambda (x)
10592 (if (stringp (car x)) (string-width (car x)) 0))
10593 fulltable)))
10594 (expert nil)
10595 (fwidth (+ maxlen 3 1 3))
10596 (ncol (/ (- (window-width) 4) fwidth))
10597 tg cnt e c tbl
10598 groups ingroup)
10599 (save-excursion
10600 (save-window-excursion
10601 (if expert
10602 (set-buffer (get-buffer-create " *Org todo*"))
10603 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
10604 (erase-buffer)
10605 (org-set-local 'org-done-keywords done-keywords)
10606 (setq tbl fulltable cnt 0)
10607 (while (setq e (pop tbl))
10608 (cond
10609 ((equal e '(:startgroup))
10610 (push '() groups) (setq ingroup t)
10611 (when (not (= cnt 0))
10612 (setq cnt 0)
10613 (insert "\n"))
10614 (insert "{ "))
10615 ((equal e '(:endgroup))
10616 (setq ingroup nil cnt 0)
10617 (insert "}\n"))
10618 ((equal e '(:newline))
10619 (when (not (= cnt 0))
10620 (setq cnt 0)
10621 (insert "\n")
10622 (setq e (car tbl))
10623 (while (equal (car tbl) '(:newline))
10624 (insert "\n")
10625 (setq tbl (cdr tbl)))))
10627 (setq tg (car e) c (cdr e))
10628 (if ingroup (push tg (car groups)))
10629 (setq tg (org-add-props tg nil 'face
10630 (org-get-todo-face tg)))
10631 (if (and (= cnt 0) (not ingroup)) (insert " "))
10632 (insert "[" c "] " tg (make-string
10633 (- fwidth 4 (length tg)) ?\ ))
10634 (when (= (setq cnt (1+ cnt)) ncol)
10635 (insert "\n")
10636 (if ingroup (insert " "))
10637 (setq cnt 0)))))
10638 (insert "\n")
10639 (goto-char (point-min))
10640 (if (not expert) (org-fit-window-to-buffer))
10641 (message "[a-z..]:Set [SPC]:clear")
10642 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10643 (cond
10644 ((or (= c ?\C-g)
10645 (and (= c ?q) (not (rassoc c fulltable))))
10646 (setq quit-flag t))
10647 ((= c ?\ ) nil)
10648 ((setq e (rassoc c fulltable) tg (car e))
10650 (t (setq quit-flag t)))))))
10652 (defun org-entry-is-todo-p ()
10653 (member (org-get-todo-state) org-not-done-keywords))
10655 (defun org-entry-is-done-p ()
10656 (member (org-get-todo-state) org-done-keywords))
10658 (defun org-get-todo-state ()
10659 (save-excursion
10660 (org-back-to-heading t)
10661 (and (looking-at org-todo-line-regexp)
10662 (match-end 2)
10663 (match-string 2))))
10665 (defun org-at-date-range-p (&optional inactive-ok)
10666 "Is the cursor inside a date range?"
10667 (interactive)
10668 (save-excursion
10669 (catch 'exit
10670 (let ((pos (point)))
10671 (skip-chars-backward "^[<\r\n")
10672 (skip-chars-backward "<[")
10673 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10674 (>= (match-end 0) pos)
10675 (throw 'exit t))
10676 (skip-chars-backward "^<[\r\n")
10677 (skip-chars-backward "<[")
10678 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10679 (>= (match-end 0) pos)
10680 (throw 'exit t)))
10681 nil)))
10683 (defun org-get-repeat (&optional tagline)
10684 "Check if there is a deadline/schedule with repeater in this entry."
10685 (save-match-data
10686 (save-excursion
10687 (org-back-to-heading t)
10688 (and (re-search-forward (if tagline
10689 (concat tagline "\\s-*" org-repeat-re)
10690 org-repeat-re)
10691 (org-entry-end-position) t)
10692 (match-string-no-properties 1)))))
10694 (defvar org-last-changed-timestamp)
10695 (defvar org-last-inserted-timestamp)
10696 (defvar org-log-post-message)
10697 (defvar org-log-note-purpose)
10698 (defvar org-log-note-how)
10699 (defvar org-log-note-extra)
10700 (defun org-auto-repeat-maybe (done-word)
10701 "Check if the current headline contains a repeated deadline/schedule.
10702 If yes, set TODO state back to what it was and change the base date
10703 of repeating deadline/scheduled time stamps to new date.
10704 This function is run automatically after each state change to a DONE state."
10705 ;; last-state is dynamically scoped into this function
10706 (let* ((repeat (org-get-repeat))
10707 (aa (assoc last-state org-todo-kwd-alist))
10708 (interpret (nth 1 aa))
10709 (head (nth 2 aa))
10710 (whata '(("d" . day) ("m" . month) ("y" . year)))
10711 (msg "Entry repeats: ")
10712 (org-log-done nil)
10713 (org-todo-log-states nil)
10714 (nshiftmax 10) (nshift 0)
10715 re type n what ts time)
10716 (when repeat
10717 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
10718 (org-todo (if (eq interpret 'type) last-state head))
10719 (org-entry-put nil "LAST_REPEAT" (format-time-string
10720 (org-time-stamp-format t t)))
10721 (when org-log-repeat
10722 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
10723 (memq 'org-add-log-note post-command-hook))
10724 ;; OK, we are already setup for some record
10725 (if (eq org-log-repeat 'note)
10726 ;; make sure we take a note, not only a time stamp
10727 (setq org-log-note-how 'note))
10728 ;; Set up for taking a record
10729 (org-add-log-setup 'state (or done-word (car org-done-keywords))
10730 last-state
10731 'findpos org-log-repeat)))
10732 (org-back-to-heading t)
10733 (org-add-planning-info nil nil 'closed)
10734 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
10735 org-deadline-time-regexp "\\)\\|\\("
10736 org-ts-regexp "\\)"))
10737 (while (re-search-forward
10738 re (save-excursion (outline-next-heading) (point)) t)
10739 (setq type (if (match-end 1) org-scheduled-string
10740 (if (match-end 3) org-deadline-string "Plain:"))
10741 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
10742 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
10743 (setq n (string-to-number (match-string 2 ts))
10744 what (match-string 3 ts))
10745 (if (equal what "w") (setq n (* n 7) what "d"))
10746 ;; Preparation, see if we need to modify the start date for the change
10747 (when (match-end 1)
10748 (setq time (save-match-data (org-time-string-to-time ts)))
10749 (cond
10750 ((equal (match-string 1 ts) ".")
10751 ;; Shift starting date to today
10752 (org-timestamp-change
10753 (- (time-to-days (current-time)) (time-to-days time))
10754 'day))
10755 ((equal (match-string 1 ts) "+")
10756 (while (or (= nshift 0)
10757 (<= (time-to-days time) (time-to-days (current-time))))
10758 (when (= (incf nshift) nshiftmax)
10759 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
10760 (error "Abort")))
10761 (org-timestamp-change n (cdr (assoc what whata)))
10762 (org-at-timestamp-p t)
10763 (setq ts (match-string 1))
10764 (setq time (save-match-data (org-time-string-to-time ts))))
10765 (org-timestamp-change (- n) (cdr (assoc what whata)))
10766 ;; rematch, so that we have everything in place for the real shift
10767 (org-at-timestamp-p t)
10768 (setq ts (match-string 1))
10769 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
10770 (org-timestamp-change n (cdr (assoc what whata)))
10771 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
10772 (setq org-log-post-message msg)
10773 (message "%s" msg))))
10775 (defun org-show-todo-tree (arg)
10776 "Make a compact tree which shows all headlines marked with TODO.
10777 The tree will show the lines where the regexp matches, and all higher
10778 headlines above the match.
10779 With a \\[universal-argument] prefix, prompt for a regexp to match.
10780 With a numeric prefix N, construct a sparse tree for the Nth element
10781 of `org-todo-keywords-1'."
10782 (interactive "P")
10783 (let ((case-fold-search nil)
10784 (kwd-re
10785 (cond ((null arg) org-not-done-regexp)
10786 ((equal arg '(4))
10787 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
10788 (mapcar 'list org-todo-keywords-1))))
10789 (concat "\\("
10790 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10791 "\\)\\>")))
10792 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10793 (regexp-quote (nth (1- (prefix-numeric-value arg))
10794 org-todo-keywords-1)))
10795 (t (error "Invalid prefix argument: %s" arg)))))
10796 (message "%d TODO entries found"
10797 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
10799 (defun org-deadline (&optional remove time)
10800 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
10801 With argument REMOVE, remove any deadline from the item.
10802 When TIME is set, it should be an internal time specification, and the
10803 scheduling will use the corresponding date."
10804 (interactive "P")
10805 (let* ((old-date (org-entry-get nil "DEADLINE"))
10806 (repeater (and old-date
10807 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
10808 (match-string 1 old-date))))
10809 (if remove
10810 (progn
10811 (when (and old-date org-log-redeadline)
10812 (org-add-log-setup 'deldeadline nil old-date 'findpos
10813 org-log-redeadline))
10814 (org-remove-timestamp-with-keyword org-deadline-string)
10815 (message "Item no longer has a deadline."))
10816 (org-add-planning-info 'deadline time 'closed)
10817 (when (and old-date org-log-redeadline
10818 (not (equal old-date
10819 (substring org-last-inserted-timestamp 1 -1))))
10820 (org-add-log-setup 'redeadline nil old-date 'findpos
10821 org-log-redeadline))
10822 (when repeater
10823 (save-excursion
10824 (org-back-to-heading t)
10825 (when (re-search-forward (concat org-deadline-string " "
10826 org-last-inserted-timestamp)
10827 (save-excursion
10828 (outline-next-heading) (point)) t)
10829 (goto-char (1- (match-end 0)))
10830 (insert " " repeater)
10831 (setq org-last-inserted-timestamp
10832 (concat (substring org-last-inserted-timestamp 0 -1)
10833 " " repeater
10834 (substring org-last-inserted-timestamp -1))))))
10835 (message "Deadline on %s" org-last-inserted-timestamp))))
10837 (defun org-schedule (&optional remove time)
10838 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
10839 With argument REMOVE, remove any scheduling date from the item.
10840 When TIME is set, it should be an internal time specification, and the
10841 scheduling will use the corresponding date."
10842 (interactive "P")
10843 (let* ((old-date (org-entry-get nil "SCHEDULED"))
10844 (repeater (and old-date
10845 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
10846 (match-string 1 old-date))))
10847 (if remove
10848 (progn
10849 (when (and old-date org-log-reschedule)
10850 (org-add-log-setup 'delschedule nil old-date 'findpos
10851 org-log-reschedule))
10852 (org-remove-timestamp-with-keyword org-scheduled-string)
10853 (message "Item is no longer scheduled."))
10854 (org-add-planning-info 'scheduled time 'closed)
10855 (when (and old-date org-log-reschedule
10856 (not (equal old-date
10857 (substring org-last-inserted-timestamp 1 -1))))
10858 (org-add-log-setup 'reschedule nil old-date 'findpos
10859 org-log-reschedule))
10860 (when repeater
10861 (save-excursion
10862 (org-back-to-heading t)
10863 (when (re-search-forward (concat org-scheduled-string " "
10864 org-last-inserted-timestamp)
10865 (save-excursion
10866 (outline-next-heading) (point)) t)
10867 (goto-char (1- (match-end 0)))
10868 (insert " " repeater)
10869 (setq org-last-inserted-timestamp
10870 (concat (substring org-last-inserted-timestamp 0 -1)
10871 " " repeater
10872 (substring org-last-inserted-timestamp -1))))))
10873 (message "Scheduled to %s" org-last-inserted-timestamp))))
10875 (defun org-get-scheduled-time (pom &optional inherit)
10876 "Get the scheduled time as a time tuple, of a format suitable
10877 for calling org-schedule with, or if there is no scheduling,
10878 returns nil."
10879 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
10880 (when time
10881 (apply 'encode-time (org-parse-time-string time)))))
10883 (defun org-get-deadline-time (pom &optional inherit)
10884 "Get the deadine as a time tuple, of a format suitable for
10885 calling org-deadline with, or if there is no scheduling, returns
10886 nil."
10887 (let ((time (org-entry-get pom "DEADLINE" inherit)))
10888 (when time
10889 (apply 'encode-time (org-parse-time-string time)))))
10891 (defun org-remove-timestamp-with-keyword (keyword)
10892 "Remove all time stamps with KEYWORD in the current entry."
10893 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
10894 beg)
10895 (save-excursion
10896 (org-back-to-heading t)
10897 (setq beg (point))
10898 (outline-next-heading)
10899 (while (re-search-backward re beg t)
10900 (replace-match "")
10901 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
10902 (equal (char-before) ?\ ))
10903 (backward-delete-char 1)
10904 (if (string-match "^[ \t]*$" (buffer-substring
10905 (point-at-bol) (point-at-eol)))
10906 (delete-region (point-at-bol)
10907 (min (point-max) (1+ (point-at-eol))))))))))
10909 (defun org-add-planning-info (what &optional time &rest remove)
10910 "Insert new timestamp with keyword in the line directly after the headline.
10911 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
10912 If non is given, the user is prompted for a date.
10913 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
10914 be removed."
10915 (interactive)
10916 (let (org-time-was-given org-end-time-was-given ts
10917 end default-time default-input)
10919 (catch 'exit
10920 (when (and (not time) (memq what '(scheduled deadline)))
10921 ;; Try to get a default date/time from existing timestamp
10922 (save-excursion
10923 (org-back-to-heading t)
10924 (setq end (save-excursion (outline-next-heading) (point)))
10925 (when (re-search-forward (if (eq what 'scheduled)
10926 org-scheduled-time-regexp
10927 org-deadline-time-regexp)
10928 end t)
10929 (setq ts (match-string 1)
10930 default-time
10931 (apply 'encode-time (org-parse-time-string ts))
10932 default-input (and ts (org-get-compact-tod ts))))))
10933 (when what
10934 ;; If necessary, get the time from the user
10935 (setq time (or time (org-read-date nil 'to-time nil nil
10936 default-time default-input))))
10938 (when (and org-insert-labeled-timestamps-at-point
10939 (member what '(scheduled deadline)))
10940 (insert
10941 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
10942 (org-insert-time-stamp time org-time-was-given
10943 nil nil nil (list org-end-time-was-given))
10944 (setq what nil))
10945 (save-excursion
10946 (save-restriction
10947 (let (col list elt ts buffer-invisibility-spec)
10948 (org-back-to-heading t)
10949 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
10950 (goto-char (match-end 1))
10951 (setq col (current-column))
10952 (goto-char (match-end 0))
10953 (if (eobp) (insert "\n") (forward-char 1))
10954 (when (and (not what)
10955 (not (looking-at
10956 (concat "[ \t]*"
10957 org-keyword-time-not-clock-regexp))))
10958 ;; Nothing to add, nothing to remove...... :-)
10959 (throw 'exit nil))
10960 (if (and (not (looking-at outline-regexp))
10961 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
10962 "[^\r\n]*"))
10963 (not (equal (match-string 1) org-clock-string)))
10964 (narrow-to-region (match-beginning 0) (match-end 0))
10965 (insert-before-markers "\n")
10966 (backward-char 1)
10967 (narrow-to-region (point) (point))
10968 (and org-adapt-indentation (org-indent-to-column col)))
10969 ;; Check if we have to remove something.
10970 (setq list (cons what remove))
10971 (while list
10972 (setq elt (pop list))
10973 (goto-char (point-min))
10974 (when (or (and (eq elt 'scheduled)
10975 (re-search-forward org-scheduled-time-regexp nil t))
10976 (and (eq elt 'deadline)
10977 (re-search-forward org-deadline-time-regexp nil t))
10978 (and (eq elt 'closed)
10979 (re-search-forward org-closed-time-regexp nil t)))
10980 (replace-match "")
10981 (if (looking-at "--+<[^>]+>") (replace-match ""))
10982 (skip-chars-backward " ")
10983 (if (looking-at " +") (replace-match ""))))
10984 (goto-char (point-max))
10985 (and org-adapt-indentation (bolp) (org-indent-to-column col))
10986 (when what
10987 (insert
10988 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
10989 (cond ((eq what 'scheduled) org-scheduled-string)
10990 ((eq what 'deadline) org-deadline-string)
10991 ((eq what 'closed) org-closed-string))
10992 " ")
10993 (setq ts (org-insert-time-stamp
10994 time
10995 (or org-time-was-given
10996 (and (eq what 'closed) org-log-done-with-time))
10997 (eq what 'closed)
10998 nil nil (list org-end-time-was-given)))
10999 (end-of-line 1))
11000 (goto-char (point-min))
11001 (widen)
11002 (if (and (looking-at "[ \t]+\n")
11003 (equal (char-before) ?\n))
11004 (delete-region (1- (point)) (point-at-eol)))
11005 ts))))))
11007 (defvar org-log-note-marker (make-marker))
11008 (defvar org-log-note-purpose nil)
11009 (defvar org-log-note-state nil)
11010 (defvar org-log-note-previous-state nil)
11011 (defvar org-log-note-how nil)
11012 (defvar org-log-note-extra nil)
11013 (defvar org-log-note-window-configuration nil)
11014 (defvar org-log-note-return-to (make-marker))
11015 (defvar org-log-post-message nil
11016 "Message to be displayed after a log note has been stored.
11017 The auto-repeater uses this.")
11019 (defun org-add-note ()
11020 "Add a note to the current entry.
11021 This is done in the same way as adding a state change note."
11022 (interactive)
11023 (org-add-log-setup 'note nil nil 'findpos nil))
11025 (defvar org-property-end-re)
11026 (defun org-add-log-setup (&optional purpose state prev-state
11027 findpos how &optional extra)
11028 "Set up the post command hook to take a note.
11029 If this is about to TODO state change, the new state is expected in STATE.
11030 When FINDPOS is non-nil, find the correct position for the note in
11031 the current entry. If not, assume that it can be inserted at point.
11032 HOW is an indicator what kind of note should be created.
11033 EXTRA is additional text that will be inserted into the notes buffer."
11034 (let* ((org-log-into-drawer (org-log-into-drawer))
11035 (drawer (cond ((stringp org-log-into-drawer)
11036 org-log-into-drawer)
11037 (org-log-into-drawer "LOGBOOK")
11038 (t nil))))
11039 (save-restriction
11040 (save-excursion
11041 (when findpos
11042 (org-back-to-heading t)
11043 (narrow-to-region (point) (save-excursion
11044 (outline-next-heading) (point)))
11045 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
11046 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
11047 "[^\r\n]*\\)?"))
11048 (goto-char (match-end 0))
11049 (cond
11050 (drawer
11051 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
11052 nil t)
11053 (progn
11054 (goto-char (match-end 0))
11055 (or org-log-states-order-reversed
11056 (and (re-search-forward org-property-end-re nil t)
11057 (goto-char (1- (match-beginning 0))))))
11058 (insert "\n:" drawer ":\n:END:")
11059 (beginning-of-line 0)
11060 (org-indent-line-function)
11061 (beginning-of-line 2)
11062 (org-indent-line-function)
11063 (end-of-line 0)))
11064 ((and org-log-state-notes-insert-after-drawers
11065 (save-excursion
11066 (forward-line) (looking-at org-drawer-regexp)))
11067 (forward-line)
11068 (while (looking-at org-drawer-regexp)
11069 (goto-char (match-end 0))
11070 (re-search-forward org-property-end-re (point-max) t)
11071 (forward-line))
11072 (forward-line -1)))
11073 (unless org-log-states-order-reversed
11074 (and (= (char-after) ?\n) (forward-char 1))
11075 (org-skip-over-state-notes)
11076 (skip-chars-backward " \t\n\r")))
11077 (move-marker org-log-note-marker (point))
11078 (setq org-log-note-purpose purpose
11079 org-log-note-state state
11080 org-log-note-previous-state prev-state
11081 org-log-note-how how
11082 org-log-note-extra extra)
11083 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
11085 (defun org-skip-over-state-notes ()
11086 "Skip past the list of State notes in an entry."
11087 (if (looking-at "\n[ \t]*- State") (forward-char 1))
11088 (while (looking-at "[ \t]*- State")
11089 (condition-case nil
11090 (org-next-item)
11091 (error (org-end-of-item)))))
11093 (defun org-add-log-note (&optional purpose)
11094 "Pop up a window for taking a note, and add this note later at point."
11095 (remove-hook 'post-command-hook 'org-add-log-note)
11096 (setq org-log-note-window-configuration (current-window-configuration))
11097 (delete-other-windows)
11098 (move-marker org-log-note-return-to (point))
11099 (switch-to-buffer (marker-buffer org-log-note-marker))
11100 (goto-char org-log-note-marker)
11101 (org-switch-to-buffer-other-window "*Org Note*")
11102 (erase-buffer)
11103 (if (memq org-log-note-how '(time state))
11104 (let (current-prefix-arg) (org-store-log-note))
11105 (let ((org-inhibit-startup t)) (org-mode))
11106 (insert (format "# Insert note for %s.
11107 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
11108 (cond
11109 ((eq org-log-note-purpose 'clock-out) "stopped clock")
11110 ((eq org-log-note-purpose 'done) "closed todo item")
11111 ((eq org-log-note-purpose 'state)
11112 (format "state change from \"%s\" to \"%s\""
11113 (or org-log-note-previous-state "")
11114 (or org-log-note-state "")))
11115 ((eq org-log-note-purpose 'reschedule)
11116 "rescheduling")
11117 ((eq org-log-note-purpose 'delschedule)
11118 "no longer scheduled")
11119 ((eq org-log-note-purpose 'redeadline)
11120 "changing deadline")
11121 ((eq org-log-note-purpose 'deldeadline)
11122 "removing deadline")
11123 ((eq org-log-note-purpose 'note)
11124 "this entry")
11125 (t (error "This should not happen")))))
11126 (if org-log-note-extra (insert org-log-note-extra))
11127 (org-set-local 'org-finish-function 'org-store-log-note)))
11129 (defvar org-note-abort nil) ; dynamically scoped
11130 (defun org-store-log-note ()
11131 "Finish taking a log note, and insert it to where it belongs."
11132 (let ((txt (buffer-string))
11133 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
11134 lines ind)
11135 (kill-buffer (current-buffer))
11136 (while (string-match "\\`#.*\n[ \t\n]*" txt)
11137 (setq txt (replace-match "" t t txt)))
11138 (if (string-match "\\s-+\\'" txt)
11139 (setq txt (replace-match "" t t txt)))
11140 (setq lines (org-split-string txt "\n"))
11141 (when (and note (string-match "\\S-" note))
11142 (setq note
11143 (org-replace-escapes
11144 note
11145 (list (cons "%u" (user-login-name))
11146 (cons "%U" user-full-name)
11147 (cons "%t" (format-time-string
11148 (org-time-stamp-format 'long 'inactive)
11149 (current-time)))
11150 (cons "%s" (if org-log-note-state
11151 (concat "\"" org-log-note-state "\"")
11152 ""))
11153 (cons "%S" (if org-log-note-previous-state
11154 (concat "\"" org-log-note-previous-state "\"")
11155 "\"\"")))))
11156 (if lines (setq note (concat note " \\\\")))
11157 (push note lines))
11158 (when (or current-prefix-arg org-note-abort)
11159 (when org-log-into-drawer
11160 (org-remove-empty-drawer-at
11161 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
11162 org-log-note-marker))
11163 (setq lines nil))
11164 (when lines
11165 (with-current-buffer (marker-buffer org-log-note-marker)
11166 (save-excursion
11167 (goto-char org-log-note-marker)
11168 (move-marker org-log-note-marker nil)
11169 (end-of-line 1)
11170 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
11171 (insert "- " (pop lines))
11172 (org-indent-line-function)
11173 (beginning-of-line 1)
11174 (looking-at "[ \t]*")
11175 (setq ind (concat (match-string 0) " "))
11176 (end-of-line 1)
11177 (while lines (insert "\n" ind (pop lines)))
11178 (message "Note stored")
11179 (org-back-to-heading t)
11180 (org-cycle-hide-drawers 'children)))))
11181 (set-window-configuration org-log-note-window-configuration)
11182 (with-current-buffer (marker-buffer org-log-note-return-to)
11183 (goto-char org-log-note-return-to))
11184 (move-marker org-log-note-return-to nil)
11185 (and org-log-post-message (message "%s" org-log-post-message)))
11187 (defun org-remove-empty-drawer-at (drawer pos)
11188 "Remove an empty drawer DRAWER at position POS.
11189 POS may also be a marker."
11190 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
11191 (save-excursion
11192 (save-restriction
11193 (widen)
11194 (goto-char pos)
11195 (if (org-in-regexp
11196 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
11197 (replace-match ""))))))
11199 (defun org-sparse-tree (&optional arg)
11200 "Create a sparse tree, prompt for the details.
11201 This command can create sparse trees. You first need to select the type
11202 of match used to create the tree:
11204 t Show entries with a specific TODO keyword.
11205 m Show entries selected by a tags/property match.
11206 p Enter a property name and its value (both with completion on existing
11207 names/values) and show entries with that property.
11208 / Show entries matching a regular expression (`r' can be used as well)
11209 d Show deadlines due within `org-deadline-warning-days'.
11210 b Show deadlines and scheduled items before a date.
11211 a Show deadlines and scheduled items after a date."
11212 (interactive "P")
11213 (let (ans kwd value)
11214 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
11215 (setq ans (read-char-exclusive))
11216 (cond
11217 ((equal ans ?d)
11218 (call-interactively 'org-check-deadlines))
11219 ((equal ans ?b)
11220 (call-interactively 'org-check-before-date))
11221 ((equal ans ?a)
11222 (call-interactively 'org-check-after-date))
11223 ((equal ans ?t)
11224 (org-show-todo-tree '(4)))
11225 ((member ans '(?T ?m))
11226 (call-interactively 'org-match-sparse-tree))
11227 ((member ans '(?p ?P))
11228 (setq kwd (org-icompleting-read "Property: "
11229 (mapcar 'list (org-buffer-property-keys))))
11230 (setq value (org-icompleting-read "Value: "
11231 (mapcar 'list (org-property-values kwd))))
11232 (unless (string-match "\\`{.*}\\'" value)
11233 (setq value (concat "\"" value "\"")))
11234 (org-match-sparse-tree arg (concat kwd "=" value)))
11235 ((member ans '(?r ?R ?/))
11236 (call-interactively 'org-occur))
11237 (t (error "No such sparse tree command \"%c\"" ans)))))
11239 (defvar org-occur-highlights nil
11240 "List of overlays used for occur matches.")
11241 (make-variable-buffer-local 'org-occur-highlights)
11242 (defvar org-occur-parameters nil
11243 "Parameters of the active org-occur calls.
11244 This is a list, each call to org-occur pushes as cons cell,
11245 containing the regular expression and the callback, onto the list.
11246 The list can contain several entries if `org-occur' has been called
11247 several time with the KEEP-PREVIOUS argument. Otherwise, this list
11248 will only contain one set of parameters. When the highlights are
11249 removed (for example with `C-c C-c', or with the next edit (depending
11250 on `org-remove-highlights-with-change'), this variable is emptied
11251 as well.")
11252 (make-variable-buffer-local 'org-occur-parameters)
11254 (defun org-occur (regexp &optional keep-previous callback)
11255 "Make a compact tree which shows all matches of REGEXP.
11256 The tree will show the lines where the regexp matches, and all higher
11257 headlines above the match. It will also show the heading after the match,
11258 to make sure editing the matching entry is easy.
11259 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
11260 call to `org-occur' will be kept, to allow stacking of calls to this
11261 command.
11262 If CALLBACK is non-nil, it is a function which is called to confirm
11263 that the match should indeed be shown."
11264 (interactive "sRegexp: \nP")
11265 (when (equal regexp "")
11266 (error "Regexp cannot be empty"))
11267 (unless keep-previous
11268 (org-remove-occur-highlights nil nil t))
11269 (push (cons regexp callback) org-occur-parameters)
11270 (let ((cnt 0))
11271 (save-excursion
11272 (goto-char (point-min))
11273 (if (or (not keep-previous) ; do not want to keep
11274 (not org-occur-highlights)) ; no previous matches
11275 ;; hide everything
11276 (org-overview))
11277 (while (re-search-forward regexp nil t)
11278 (when (or (not callback)
11279 (save-match-data (funcall callback)))
11280 (setq cnt (1+ cnt))
11281 (when org-highlight-sparse-tree-matches
11282 (org-highlight-new-match (match-beginning 0) (match-end 0)))
11283 (org-show-context 'occur-tree))))
11284 (when org-remove-highlights-with-change
11285 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
11286 nil 'local))
11287 (unless org-sparse-tree-open-archived-trees
11288 (org-hide-archived-subtrees (point-min) (point-max)))
11289 (run-hooks 'org-occur-hook)
11290 (if (interactive-p)
11291 (message "%d match(es) for regexp %s" cnt regexp))
11292 cnt))
11294 (defun org-show-context (&optional key)
11295 "Make sure point and context and visible.
11296 How much context is shown depends upon the variables
11297 `org-show-hierarchy-above', `org-show-following-heading'. and
11298 `org-show-siblings'."
11299 (let ((heading-p (org-on-heading-p t))
11300 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
11301 (following-p (org-get-alist-option org-show-following-heading key))
11302 (entry-p (org-get-alist-option org-show-entry-below key))
11303 (siblings-p (org-get-alist-option org-show-siblings key)))
11304 (catch 'exit
11305 ;; Show heading or entry text
11306 (if (and heading-p (not entry-p))
11307 (org-flag-heading nil) ; only show the heading
11308 (and (or entry-p (org-invisible-p) (org-invisible-p2))
11309 (org-show-hidden-entry))) ; show entire entry
11310 (when following-p
11311 ;; Show next sibling, or heading below text
11312 (save-excursion
11313 (and (if heading-p (org-goto-sibling) (outline-next-heading))
11314 (org-flag-heading nil))))
11315 (when siblings-p (org-show-siblings))
11316 (when hierarchy-p
11317 ;; show all higher headings, possibly with siblings
11318 (save-excursion
11319 (while (and (condition-case nil
11320 (progn (org-up-heading-all 1) t)
11321 (error nil))
11322 (not (bobp)))
11323 (org-flag-heading nil)
11324 (when siblings-p (org-show-siblings))))))))
11326 (defvar org-reveal-start-hook nil
11327 "Hook run before revealing a location.")
11329 (defun org-reveal (&optional siblings)
11330 "Show current entry, hierarchy above it, and the following headline.
11331 This can be used to show a consistent set of context around locations
11332 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
11333 not t for the search context.
11335 With optional argument SIBLINGS, on each level of the hierarchy all
11336 siblings are shown. This repairs the tree structure to what it would
11337 look like when opened with hierarchical calls to `org-cycle'.
11338 With double optional argument `C-u C-u', go to the parent and show the
11339 entire tree."
11340 (interactive "P")
11341 (run-hooks 'org-reveal-start-hook)
11342 (let ((org-show-hierarchy-above t)
11343 (org-show-following-heading t)
11344 (org-show-siblings (if siblings t org-show-siblings)))
11345 (org-show-context nil))
11346 (when (equal siblings '(16))
11347 (save-excursion
11348 (when (org-up-heading-safe)
11349 (org-show-subtree)
11350 (run-hook-with-args 'org-cycle-hook 'subtree)))))
11352 (defun org-highlight-new-match (beg end)
11353 "Highlight from BEG to END and mark the highlight is an occur headline."
11354 (let ((ov (org-make-overlay beg end)))
11355 (org-overlay-put ov 'face 'secondary-selection)
11356 (push ov org-occur-highlights)))
11358 (defun org-remove-occur-highlights (&optional beg end noremove)
11359 "Remove the occur highlights from the buffer.
11360 BEG and END are ignored. If NOREMOVE is nil, remove this function
11361 from the `before-change-functions' in the current buffer."
11362 (interactive)
11363 (unless org-inhibit-highlight-removal
11364 (mapc 'org-delete-overlay org-occur-highlights)
11365 (setq org-occur-highlights nil)
11366 (setq org-occur-parameters nil)
11367 (unless noremove
11368 (remove-hook 'before-change-functions
11369 'org-remove-occur-highlights 'local))))
11371 ;;;; Priorities
11373 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
11374 "Regular expression matching the priority indicator.")
11376 (defvar org-remove-priority-next-time nil)
11378 (defun org-priority-up ()
11379 "Increase the priority of the current item."
11380 (interactive)
11381 (org-priority 'up))
11383 (defun org-priority-down ()
11384 "Decrease the priority of the current item."
11385 (interactive)
11386 (org-priority 'down))
11388 (defun org-priority (&optional action)
11389 "Change the priority of an item by ARG.
11390 ACTION can be `set', `up', `down', or a character."
11391 (interactive)
11392 (unless org-enable-priority-commands
11393 (error "Priority commands are disabled"))
11394 (setq action (or action 'set))
11395 (let (current new news have remove)
11396 (save-excursion
11397 (org-back-to-heading t)
11398 (if (looking-at org-priority-regexp)
11399 (setq current (string-to-char (match-string 2))
11400 have t)
11401 (setq current org-default-priority))
11402 (cond
11403 ((eq action 'remove)
11404 (setq remove t new ?\ ))
11405 ((or (eq action 'set)
11406 (if (featurep 'xemacs) (characterp action) (integerp action)))
11407 (if (not (eq action 'set))
11408 (setq new action)
11409 (message "Priority %c-%c, SPC to remove: "
11410 org-highest-priority org-lowest-priority)
11411 (setq new (read-char-exclusive)))
11412 (if (and (= (upcase org-highest-priority) org-highest-priority)
11413 (= (upcase org-lowest-priority) org-lowest-priority))
11414 (setq new (upcase new)))
11415 (cond ((equal new ?\ ) (setq remove t))
11416 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
11417 (error "Priority must be between `%c' and `%c'"
11418 org-highest-priority org-lowest-priority))))
11419 ((eq action 'up)
11420 (if (and (not have) (eq last-command this-command))
11421 (setq new org-lowest-priority)
11422 (setq new (if (and org-priority-start-cycle-with-default (not have))
11423 org-default-priority (1- current)))))
11424 ((eq action 'down)
11425 (if (and (not have) (eq last-command this-command))
11426 (setq new org-highest-priority)
11427 (setq new (if (and org-priority-start-cycle-with-default (not have))
11428 org-default-priority (1+ current)))))
11429 (t (error "Invalid action")))
11430 (if (or (< (upcase new) org-highest-priority)
11431 (> (upcase new) org-lowest-priority))
11432 (setq remove t))
11433 (setq news (format "%c" new))
11434 (if have
11435 (if remove
11436 (replace-match "" t t nil 1)
11437 (replace-match news t t nil 2))
11438 (if remove
11439 (error "No priority cookie found in line")
11440 (let ((case-fold-search nil))
11441 (looking-at org-todo-line-regexp))
11442 (if (match-end 2)
11443 (progn
11444 (goto-char (match-end 2))
11445 (insert " [#" news "]"))
11446 (goto-char (match-beginning 3))
11447 (insert "[#" news "] "))))
11448 (org-preserve-lc (org-set-tags nil 'align)))
11449 (if remove
11450 (message "Priority removed")
11451 (message "Priority of current item set to %s" news))))
11453 (defun org-get-priority (s)
11454 "Find priority cookie and return priority."
11455 (save-match-data
11456 (if (not (string-match org-priority-regexp s))
11457 (* 1000 (- org-lowest-priority org-default-priority))
11458 (* 1000 (- org-lowest-priority
11459 (string-to-char (match-string 2 s)))))))
11461 ;;;; Tags
11463 (defvar org-agenda-archives-mode)
11464 (defvar org-map-continue-from nil
11465 "Position from where mapping should continue.
11466 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
11468 (defvar org-scanner-tags nil
11469 "The current tag list while the tags scanner is running.")
11470 (defvar org-trust-scanner-tags nil
11471 "Should `org-get-tags-at' use the tags fro the scanner.
11472 This is for internal dynamical scoping only.
11473 When this is non-nil, the function `org-get-tags-at' will return the value
11474 of `org-scanner-tags' instead of building the list by itself. This
11475 can lead to large speed-ups when the tags scanner is used in a file with
11476 many entries, and when the list of tags is retrieved, for example to
11477 obtain a list of properties. Building the tags list for each entry in such
11478 a file becomes an N^2 operation - but with this variable set, it scales
11479 as N.")
11481 (defun org-scan-tags (action matcher &optional todo-only)
11482 "Scan headline tags with inheritance and produce output ACTION.
11484 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
11485 or `agenda' to produce an entry list for an agenda view. It can also be
11486 a Lisp form or a function that should be called at each matched headline, in
11487 this case the return value is a list of all return values from these calls.
11489 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
11490 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
11491 only lines with a TODO keyword are included in the output."
11492 (require 'org-agenda)
11493 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
11494 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
11495 (org-re
11496 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
11497 (props (list 'face 'default
11498 'done-face 'org-agenda-done
11499 'undone-face 'default
11500 'mouse-face 'highlight
11501 'org-not-done-regexp org-not-done-regexp
11502 'org-todo-regexp org-todo-regexp
11503 'help-echo
11504 (format "mouse-2 or RET jump to org file %s"
11505 (abbreviate-file-name
11506 (or (buffer-file-name (buffer-base-buffer))
11507 (buffer-name (buffer-base-buffer)))))))
11508 (case-fold-search nil)
11509 (org-map-continue-from nil)
11510 lspos tags tags-list
11511 (tags-alist (list (cons 0 org-file-tags)))
11512 (llast 0) rtn rtn1 level category i txt
11513 todo marker entry priority)
11514 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
11515 (setq action (list 'lambda nil action)))
11516 (save-excursion
11517 (goto-char (point-min))
11518 (when (eq action 'sparse-tree)
11519 (org-overview)
11520 (org-remove-occur-highlights))
11521 (while (re-search-forward re nil t)
11522 (catch :skip
11523 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
11524 tags (if (match-end 4) (org-match-string-no-properties 4)))
11525 (goto-char (setq lspos (match-beginning 0)))
11526 (setq level (org-reduced-level (funcall outline-level))
11527 category (org-get-category))
11528 (setq i llast llast level)
11529 ;; remove tag lists from same and sublevels
11530 (while (>= i level)
11531 (when (setq entry (assoc i tags-alist))
11532 (setq tags-alist (delete entry tags-alist)))
11533 (setq i (1- i)))
11534 ;; add the next tags
11535 (when tags
11536 (setq tags (org-split-string tags ":")
11537 tags-alist
11538 (cons (cons level tags) tags-alist)))
11539 ;; compile tags for current headline
11540 (setq tags-list
11541 (if org-use-tag-inheritance
11542 (apply 'append (mapcar 'cdr (reverse tags-alist)))
11543 tags)
11544 org-scanner-tags tags-list)
11545 (when org-use-tag-inheritance
11546 (setcdr (car tags-alist)
11547 (mapcar (lambda (x)
11548 (setq x (copy-sequence x))
11549 (org-add-prop-inherited x))
11550 (cdar tags-alist))))
11551 (when (and tags org-use-tag-inheritance
11552 (or (not (eq t org-use-tag-inheritance))
11553 org-tags-exclude-from-inheritance))
11554 ;; selective inheritance, remove uninherited ones
11555 (setcdr (car tags-alist)
11556 (org-remove-uniherited-tags (cdar tags-alist))))
11557 (when (and (or (not todo-only)
11558 (and (member todo org-not-done-keywords)
11559 (or (not org-agenda-tags-todo-honor-ignore-options)
11560 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
11561 (let ((case-fold-search t)) (eval matcher))
11563 (not (member org-archive-tag tags-list))
11564 ;; we have an archive tag, should we use this anyway?
11565 (or (not org-agenda-skip-archived-trees)
11566 (and (eq action 'agenda) org-agenda-archives-mode))))
11567 (unless (eq action 'sparse-tree) (org-agenda-skip))
11569 ;; select this headline
11571 (cond
11572 ((eq action 'sparse-tree)
11573 (and org-highlight-sparse-tree-matches
11574 (org-get-heading) (match-end 0)
11575 (org-highlight-new-match
11576 (match-beginning 0) (match-beginning 1)))
11577 (org-show-context 'tags-tree))
11578 ((eq action 'agenda)
11579 (setq txt (org-format-agenda-item
11581 (concat
11582 (if (eq org-tags-match-list-sublevels 'indented)
11583 (make-string (1- level) ?.) "")
11584 (org-get-heading))
11585 category
11586 tags-list
11588 priority (org-get-priority txt))
11589 (goto-char lspos)
11590 (setq marker (org-agenda-new-marker))
11591 (org-add-props txt props
11592 'org-marker marker 'org-hd-marker marker 'org-category category
11593 'todo-state todo
11594 'priority priority 'type "tagsmatch")
11595 (push txt rtn))
11596 ((functionp action)
11597 (setq org-map-continue-from nil)
11598 (save-excursion
11599 (setq rtn1 (funcall action))
11600 (push rtn1 rtn)))
11601 (t (error "Invalid action")))
11603 ;; if we are to skip sublevels, jump to end of subtree
11604 (unless org-tags-match-list-sublevels
11605 (org-end-of-subtree t)
11606 (backward-char 1))))
11607 ;; Get the correct position from where to continue
11608 (if org-map-continue-from
11609 (goto-char org-map-continue-from)
11610 (and (= (point) lspos) (end-of-line 1)))))
11611 (when (and (eq action 'sparse-tree)
11612 (not org-sparse-tree-open-archived-trees))
11613 (org-hide-archived-subtrees (point-min) (point-max)))
11614 (nreverse rtn)))
11616 (defun org-remove-uniherited-tags (tags)
11617 "Remove all tags that are not inherited from the list TAGS."
11618 (cond
11619 ((eq org-use-tag-inheritance t)
11620 (if org-tags-exclude-from-inheritance
11621 (org-delete-all org-tags-exclude-from-inheritance tags)
11622 tags))
11623 ((not org-use-tag-inheritance) nil)
11624 ((stringp org-use-tag-inheritance)
11625 (delq nil (mapcar
11626 (lambda (x)
11627 (if (and (string-match org-use-tag-inheritance x)
11628 (not (member x org-tags-exclude-from-inheritance)))
11629 x nil))
11630 tags)))
11631 ((listp org-use-tag-inheritance)
11632 (delq nil (mapcar
11633 (lambda (x)
11634 (if (member x org-use-tag-inheritance) x nil))
11635 tags)))))
11637 (defvar todo-only) ;; dynamically scoped
11639 (defun org-match-sparse-tree (&optional todo-only match)
11640 "Create a sparse tree according to tags string MATCH.
11641 MATCH can contain positive and negative selection of tags, like
11642 \"+WORK+URGENT-WITHBOSS\".
11643 If optional argument TODO-ONLY is non-nil, only select lines that are
11644 also TODO lines."
11645 (interactive "P")
11646 (org-prepare-agenda-buffers (list (current-buffer)))
11647 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
11649 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
11651 (defvar org-cached-props nil)
11652 (defun org-cached-entry-get (pom property)
11653 (if (or (eq t org-use-property-inheritance)
11654 (and (stringp org-use-property-inheritance)
11655 (string-match org-use-property-inheritance property))
11656 (and (listp org-use-property-inheritance)
11657 (member property org-use-property-inheritance)))
11658 ;; Caching is not possible, check it directly
11659 (org-entry-get pom property 'inherit)
11660 ;; Get all properties, so that we can do complicated checks easily
11661 (cdr (assoc property (or org-cached-props
11662 (setq org-cached-props
11663 (org-entry-properties pom)))))))
11665 (defun org-global-tags-completion-table (&optional files)
11666 "Return the list of all tags in all agenda buffer/files."
11667 (save-excursion
11668 (org-uniquify
11669 (delq nil
11670 (apply 'append
11671 (mapcar
11672 (lambda (file)
11673 (set-buffer (find-file-noselect file))
11674 (append (org-get-buffer-tags)
11675 (mapcar (lambda (x) (if (stringp (car-safe x))
11676 (list (car-safe x)) nil))
11677 org-tag-alist)))
11678 (if (and files (car files))
11679 files
11680 (org-agenda-files))))))))
11682 (defun org-make-tags-matcher (match)
11683 "Create the TAGS//TODO matcher form for the selection string MATCH."
11684 ;; todo-only is scoped dynamically into this function, and the function
11685 ;; may change it if the matcher asks for it.
11686 (unless match
11687 ;; Get a new match request, with completion
11688 (let ((org-last-tags-completion-table
11689 (org-global-tags-completion-table)))
11690 (setq match (org-completing-read-no-i
11691 "Match: " 'org-tags-completion-function nil nil nil
11692 'org-tags-history))))
11694 ;; Parse the string and create a lisp form
11695 (let ((match0 match)
11696 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
11697 minus tag mm
11698 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
11699 orterms term orlist re-p str-p level-p level-op time-p
11700 prop-p pn pv po cat-p gv rest)
11701 (if (string-match "/+" match)
11702 ;; match contains also a todo-matching request
11703 (progn
11704 (setq tagsmatch (substring match 0 (match-beginning 0))
11705 todomatch (substring match (match-end 0)))
11706 (if (string-match "^!" todomatch)
11707 (setq todo-only t todomatch (substring todomatch 1)))
11708 (if (string-match "^\\s-*$" todomatch)
11709 (setq todomatch nil)))
11710 ;; only matching tags
11711 (setq tagsmatch match todomatch nil))
11713 ;; Make the tags matcher
11714 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
11715 (setq tagsmatcher t)
11716 (setq orterms (org-split-string tagsmatch "|") orlist nil)
11717 (while (setq term (pop orterms))
11718 (while (and (equal (substring term -1) "\\") orterms)
11719 (setq term (concat term "|" (pop orterms)))) ; repair bad split
11720 (while (string-match re term)
11721 (setq rest (substring term (match-end 0))
11722 minus (and (match-end 1)
11723 (equal (match-string 1 term) "-"))
11724 tag (match-string 2 term)
11725 re-p (equal (string-to-char tag) ?{)
11726 level-p (match-end 4)
11727 prop-p (match-end 5)
11728 mm (cond
11729 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
11730 (level-p
11731 (setq level-op (org-op-to-function (match-string 3 term)))
11732 `(,level-op level ,(string-to-number
11733 (match-string 4 term))))
11734 (prop-p
11735 (setq pn (match-string 5 term)
11736 po (match-string 6 term)
11737 pv (match-string 7 term)
11738 cat-p (equal pn "CATEGORY")
11739 re-p (equal (string-to-char pv) ?{)
11740 str-p (equal (string-to-char pv) ?\")
11741 time-p (save-match-data
11742 (string-match "^\"[[<].*[]>]\"$" pv))
11743 pv (if (or re-p str-p) (substring pv 1 -1) pv))
11744 (if time-p (setq pv (org-matcher-time pv)))
11745 (setq po (org-op-to-function po (if time-p 'time str-p)))
11746 (cond
11747 ((equal pn "CATEGORY")
11748 (setq gv '(get-text-property (point) 'org-category)))
11749 ((equal pn "TODO")
11750 (setq gv 'todo))
11752 (setq gv `(org-cached-entry-get nil ,pn))))
11753 (if re-p
11754 (if (eq po 'org<>)
11755 `(not (string-match ,pv (or ,gv "")))
11756 `(string-match ,pv (or ,gv "")))
11757 (if str-p
11758 `(,po (or ,gv "") ,pv)
11759 `(,po (string-to-number (or ,gv ""))
11760 ,(string-to-number pv) ))))
11761 (t `(member ,tag tags-list)))
11762 mm (if minus (list 'not mm) mm)
11763 term rest)
11764 (push mm tagsmatcher))
11765 (push (if (> (length tagsmatcher) 1)
11766 (cons 'and tagsmatcher)
11767 (car tagsmatcher))
11768 orlist)
11769 (setq tagsmatcher nil))
11770 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
11771 (setq tagsmatcher
11772 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
11773 ;; Make the todo matcher
11774 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11775 (setq todomatcher t)
11776 (setq orterms (org-split-string todomatch "|") orlist nil)
11777 (while (setq term (pop orterms))
11778 (while (string-match re term)
11779 (setq minus (and (match-end 1)
11780 (equal (match-string 1 term) "-"))
11781 kwd (match-string 2 term)
11782 re-p (equal (string-to-char kwd) ?{)
11783 term (substring term (match-end 0))
11784 mm (if re-p
11785 `(string-match ,(substring kwd 1 -1) todo)
11786 (list 'equal 'todo kwd))
11787 mm (if minus (list 'not mm) mm))
11788 (push mm todomatcher))
11789 (push (if (> (length todomatcher) 1)
11790 (cons 'and todomatcher)
11791 (car todomatcher))
11792 orlist)
11793 (setq todomatcher nil))
11794 (setq todomatcher (if (> (length orlist) 1)
11795 (cons 'or orlist) (car orlist))))
11797 ;; Return the string and lisp forms of the matcher
11798 (setq matcher (if todomatcher
11799 (list 'and tagsmatcher todomatcher)
11800 tagsmatcher))
11801 (cons match0 matcher)))
11803 (defun org-op-to-function (op &optional stringp)
11804 "Turn an operator into the appropriate function."
11805 (setq op
11806 (cond
11807 ((equal op "<" ) '(< string< org-time<))
11808 ((equal op ">" ) '(> org-string> org-time>))
11809 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
11810 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
11811 ((member op '("=" "==")) '(= string= org-time=))
11812 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
11813 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
11815 (defun org<> (a b) (not (= a b)))
11816 (defun org-string<= (a b) (or (string= a b) (string< a b)))
11817 (defun org-string>= (a b) (not (string< a b)))
11818 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
11819 (defun org-string<> (a b) (not (string= a b)))
11820 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
11821 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
11822 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
11823 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
11824 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
11825 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
11826 (defun org-2ft (s)
11827 "Convert S to a floating point time.
11828 If S is already a number, just return it. If it is a string, parse
11829 it as a time string and apply `float-time' to it. If S is nil, just return 0."
11830 (cond
11831 ((numberp s) s)
11832 ((stringp s)
11833 (condition-case nil
11834 (float-time (apply 'encode-time (org-parse-time-string s)))
11835 (error 0.)))
11836 (t 0.)))
11838 (defun org-time-today ()
11839 "Time in seconds today at 0:00.
11840 Returns the float number of seconds since the beginning of the
11841 epoch to the beginning of today (00:00)."
11842 (float-time (apply 'encode-time
11843 (append '(0 0 0) (nthcdr 3 (decode-time))))))
11845 (defun org-matcher-time (s)
11846 "Interpret a time comparison value."
11847 (save-match-data
11848 (cond
11849 ((string= s "<now>") (float-time))
11850 ((string= s "<today>") (org-time-today))
11851 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
11852 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
11853 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
11854 (+ (org-time-today)
11855 (* (string-to-number (match-string 1 s))
11856 (cdr (assoc (match-string 2 s)
11857 '(("d" . 86400.0) ("w" . 604800.0)
11858 ("m" . 2678400.0) ("y" . 31557600.0)))))))
11859 (t (org-2ft s)))))
11861 (defun org-match-any-p (re list)
11862 "Does re match any element of list?"
11863 (setq list (mapcar (lambda (x) (string-match re x)) list))
11864 (delq nil list))
11866 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
11867 (defvar org-tags-overlay (org-make-overlay 1 1))
11868 (org-detach-overlay org-tags-overlay)
11870 (defun org-get-local-tags-at (&optional pos)
11871 "Get a list of tags defined in the current headline."
11872 (org-get-tags-at pos 'local))
11874 (defun org-get-local-tags ()
11875 "Get a list of tags defined in the current headline."
11876 (org-get-tags-at nil 'local))
11878 (defun org-get-tags-at (&optional pos local)
11879 "Get a list of all headline tags applicable at POS.
11880 POS defaults to point. If tags are inherited, the list contains
11881 the targets in the same sequence as the headlines appear, i.e.
11882 the tags of the current headline come last.
11883 When LOCAL is non-nil, only return tags from the current headline,
11884 ignore inherited ones."
11885 (interactive)
11886 (if (and org-trust-scanner-tags
11887 (or (not pos) (equal pos (point)))
11888 (not local))
11889 org-scanner-tags
11890 (let (tags ltags lastpos parent)
11891 (save-excursion
11892 (save-restriction
11893 (widen)
11894 (goto-char (or pos (point)))
11895 (save-match-data
11896 (catch 'done
11897 (condition-case nil
11898 (progn
11899 (org-back-to-heading t)
11900 (while (not (equal lastpos (point)))
11901 (setq lastpos (point))
11902 (when (looking-at
11903 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
11904 (setq ltags (org-split-string
11905 (org-match-string-no-properties 1) ":"))
11906 (when parent
11907 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
11908 (setq tags (append
11909 (if parent
11910 (org-remove-uniherited-tags ltags)
11911 ltags)
11912 tags)))
11913 (or org-use-tag-inheritance (throw 'done t))
11914 (if local (throw 'done t))
11915 (or (org-up-heading-safe) (error nil))
11916 (setq parent t)))
11917 (error nil)))))
11918 (append (org-remove-uniherited-tags org-file-tags) tags)))))
11920 (defun org-add-prop-inherited (s)
11921 (add-text-properties 0 (length s) '(inherited t) s)
11924 (defun org-toggle-tag (tag &optional onoff)
11925 "Toggle the tag TAG for the current line.
11926 If ONOFF is `on' or `off', don't toggle but set to this state."
11927 (let (res current)
11928 (save-excursion
11929 (org-back-to-heading t)
11930 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
11931 (point-at-eol) t)
11932 (progn
11933 (setq current (match-string 1))
11934 (replace-match ""))
11935 (setq current ""))
11936 (setq current (nreverse (org-split-string current ":")))
11937 (cond
11938 ((eq onoff 'on)
11939 (setq res t)
11940 (or (member tag current) (push tag current)))
11941 ((eq onoff 'off)
11942 (or (not (member tag current)) (setq current (delete tag current))))
11943 (t (if (member tag current)
11944 (setq current (delete tag current))
11945 (setq res t)
11946 (push tag current))))
11947 (end-of-line 1)
11948 (if current
11949 (progn
11950 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
11951 (org-set-tags nil t))
11952 (delete-horizontal-space))
11953 (run-hooks 'org-after-tags-change-hook))
11954 res))
11956 (defun org-align-tags-here (to-col)
11957 ;; Assumes that this is a headline
11958 (let ((pos (point)) (col (current-column)) ncol tags-l p)
11959 (beginning-of-line 1)
11960 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11961 (< pos (match-beginning 2)))
11962 (progn
11963 (setq tags-l (- (match-end 2) (match-beginning 2)))
11964 (goto-char (match-beginning 1))
11965 (insert " ")
11966 (delete-region (point) (1+ (match-beginning 2)))
11967 (setq ncol (max (1+ (current-column))
11968 (1+ col)
11969 (if (> to-col 0)
11970 to-col
11971 (- (abs to-col) tags-l))))
11972 (setq p (point))
11973 (insert (make-string (- ncol (current-column)) ?\ ))
11974 (setq ncol (current-column))
11975 (when indent-tabs-mode (tabify p (point-at-eol)))
11976 (org-move-to-column (min ncol col) t))
11977 (goto-char pos))))
11979 (defun org-set-tags-command (&optional arg just-align)
11980 "Call the set-tags command for the current entry."
11981 (interactive "P")
11982 (if (org-on-heading-p)
11983 (org-set-tags arg just-align)
11984 (save-excursion
11985 (org-back-to-heading t)
11986 (org-set-tags arg just-align))))
11988 (defun org-set-tags-to (data)
11989 "Set the tags of the current entry to DATA, replacing the current tags.
11990 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
11991 If DATA is nil or the empty string, any tags will be removed."
11992 (interactive "sTags: ")
11993 (setq data
11994 (cond
11995 ((eq data nil) "")
11996 ((equal data "") "")
11997 ((stringp data)
11998 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
11999 ":"))
12000 ((listp data)
12001 (concat ":" (mapconcat 'identity data ":") ":"))
12002 (t nil)))
12003 (when data
12004 (save-excursion
12005 (org-back-to-heading t)
12006 (when (looking-at org-complex-heading-regexp)
12007 (if (match-end 5)
12008 (progn
12009 (goto-char (match-beginning 5))
12010 (insert data)
12011 (delete-region (point) (point-at-eol))
12012 (org-set-tags nil 'align))
12013 (goto-char (point-at-eol))
12014 (insert " " data)
12015 (org-set-tags nil 'align)))
12016 (beginning-of-line 1)
12017 (if (looking-at ".*?\\([ \t]+\\)$")
12018 (delete-region (match-beginning 1) (match-end 1))))))
12020 (defun org-set-tags (&optional arg just-align)
12021 "Set the tags for the current headline.
12022 With prefix ARG, realign all tags in headings in the current buffer."
12023 (interactive "P")
12024 (let* ((re (concat "^" outline-regexp))
12025 (current (org-get-tags-string))
12026 (col (current-column))
12027 (org-setting-tags t)
12028 table current-tags inherited-tags ; computed below when needed
12029 tags p0 c0 c1 rpl)
12030 (if arg
12031 (save-excursion
12032 (goto-char (point-min))
12033 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
12034 (while (re-search-forward re nil t)
12035 (org-set-tags nil t)
12036 (end-of-line 1)))
12037 (message "All tags realigned to column %d" org-tags-column))
12038 (if just-align
12039 (setq tags current)
12040 ;; Get a new set of tags from the user
12041 (save-excursion
12042 (setq table (append org-tag-persistent-alist
12043 (or org-tag-alist (org-get-buffer-tags))
12044 (and org-complete-tags-always-offer-all-agenda-tags
12045 (org-global-tags-completion-table (org-agenda-files))))
12046 org-last-tags-completion-table table
12047 current-tags (org-split-string current ":")
12048 inherited-tags (nreverse
12049 (nthcdr (length current-tags)
12050 (nreverse (org-get-tags-at))))
12051 tags
12052 (if (or (eq t org-use-fast-tag-selection)
12053 (and org-use-fast-tag-selection
12054 (delq nil (mapcar 'cdr table))))
12055 (org-fast-tag-selection
12056 current-tags inherited-tags table
12057 (if org-fast-tag-selection-include-todo org-todo-key-alist))
12058 (let ((org-add-colon-after-tag-completion t))
12059 (org-trim
12060 (org-without-partial-completion
12061 (org-icompleting-read "Tags: " 'org-tags-completion-function
12062 nil nil current 'org-tags-history)))))))
12063 (while (string-match "[-+&]+" tags)
12064 ;; No boolean logic, just a list
12065 (setq tags (replace-match ":" t t tags))))
12067 (if org-tags-sort-function
12068 (setq tags (mapconcat 'identity
12069 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
12070 org-tags-sort-function) ":")))
12072 (if (string-match "\\`[\t ]*\\'" tags)
12073 (setq tags "")
12074 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
12075 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
12077 ;; Insert new tags at the correct column
12078 (beginning-of-line 1)
12079 (cond
12080 ((and (equal current "") (equal tags "")))
12081 ((re-search-forward
12082 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
12083 (point-at-eol) t)
12084 (if (equal tags "")
12085 (setq rpl "")
12086 (goto-char (match-beginning 0))
12087 (setq c0 (current-column) p0 (if (equal (char-before) ?*)
12088 (1+ (point)) (point))
12089 c1 (max (1+ c0) (if (> org-tags-column 0)
12090 org-tags-column
12091 (- (- org-tags-column) (length tags))))
12092 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
12093 (replace-match rpl t t)
12094 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
12095 tags)
12096 (t (error "Tags alignment failed")))
12097 (org-move-to-column col)
12098 (unless just-align
12099 (run-hooks 'org-after-tags-change-hook)))))
12101 (defun org-change-tag-in-region (beg end tag off)
12102 "Add or remove TAG for each entry in the region.
12103 This works in the agenda, and also in an org-mode buffer."
12104 (interactive
12105 (list (region-beginning) (region-end)
12106 (let ((org-last-tags-completion-table
12107 (if (org-mode-p)
12108 (org-get-buffer-tags)
12109 (org-global-tags-completion-table))))
12110 (org-icompleting-read
12111 "Tag: " 'org-tags-completion-function nil nil nil
12112 'org-tags-history))
12113 (progn
12114 (message "[s]et or [r]emove? ")
12115 (equal (read-char-exclusive) ?r))))
12116 (if (fboundp 'deactivate-mark) (deactivate-mark))
12117 (let ((agendap (equal major-mode 'org-agenda-mode))
12118 l1 l2 m buf pos newhead (cnt 0))
12119 (goto-char end)
12120 (setq l2 (1- (org-current-line)))
12121 (goto-char beg)
12122 (setq l1 (org-current-line))
12123 (loop for l from l1 to l2 do
12124 (org-goto-line l)
12125 (setq m (get-text-property (point) 'org-hd-marker))
12126 (when (or (and (org-mode-p) (org-on-heading-p))
12127 (and agendap m))
12128 (setq buf (if agendap (marker-buffer m) (current-buffer))
12129 pos (if agendap m (point)))
12130 (with-current-buffer buf
12131 (save-excursion
12132 (save-restriction
12133 (goto-char pos)
12134 (setq cnt (1+ cnt))
12135 (org-toggle-tag tag (if off 'off 'on))
12136 (setq newhead (org-get-heading)))))
12137 (and agendap (org-agenda-change-all-lines newhead m))))
12138 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
12140 (defun org-tags-completion-function (string predicate &optional flag)
12141 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
12142 (confirm (lambda (x) (stringp (car x)))))
12143 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
12144 (setq s1 (match-string 1 string)
12145 s2 (match-string 2 string))
12146 (setq s1 "" s2 string))
12147 (cond
12148 ((eq flag nil)
12149 ;; try completion
12150 (setq rtn (try-completion s2 ctable confirm))
12151 (if (stringp rtn)
12152 (setq rtn
12153 (concat s1 s2 (substring rtn (length s2))
12154 (if (and org-add-colon-after-tag-completion
12155 (assoc rtn ctable))
12156 ":" ""))))
12157 rtn)
12158 ((eq flag t)
12159 ;; all-completions
12160 (all-completions s2 ctable confirm)
12162 ((eq flag 'lambda)
12163 ;; exact match?
12164 (assoc s2 ctable)))
12167 (defun org-fast-tag-insert (kwd tags face &optional end)
12168 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
12169 (insert (format "%-12s" (concat kwd ":"))
12170 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
12171 (or end "")))
12173 (defun org-fast-tag-show-exit (flag)
12174 (save-excursion
12175 (org-goto-line 3)
12176 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
12177 (replace-match ""))
12178 (when flag
12179 (end-of-line 1)
12180 (org-move-to-column (- (window-width) 19) t)
12181 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
12183 (defun org-set-current-tags-overlay (current prefix)
12184 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
12185 (if (featurep 'xemacs)
12186 (org-overlay-display org-tags-overlay (concat prefix s)
12187 'secondary-selection)
12188 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
12189 (org-overlay-display org-tags-overlay (concat prefix s)))))
12191 (defvar org-last-tag-selection-key nil)
12192 (defun org-fast-tag-selection (current inherited table &optional todo-table)
12193 "Fast tag selection with single keys.
12194 CURRENT is the current list of tags in the headline, INHERITED is the
12195 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
12196 possibly with grouping information. TODO-TABLE is a similar table with
12197 TODO keywords, should these have keys assigned to them.
12198 If the keys are nil, a-z are automatically assigned.
12199 Returns the new tags string, or nil to not change the current settings."
12200 (let* ((fulltable (append table todo-table))
12201 (maxlen (apply 'max (mapcar
12202 (lambda (x)
12203 (if (stringp (car x)) (string-width (car x)) 0))
12204 fulltable)))
12205 (buf (current-buffer))
12206 (expert (eq org-fast-tag-selection-single-key 'expert))
12207 (buffer-tags nil)
12208 (fwidth (+ maxlen 3 1 3))
12209 (ncol (/ (- (window-width) 4) fwidth))
12210 (i-face 'org-done)
12211 (c-face 'org-todo)
12212 tg cnt e c char c1 c2 ntable tbl rtn
12213 ov-start ov-end ov-prefix
12214 (exit-after-next org-fast-tag-selection-single-key)
12215 (done-keywords org-done-keywords)
12216 groups ingroup)
12217 (save-excursion
12218 (beginning-of-line 1)
12219 (if (looking-at
12220 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12221 (setq ov-start (match-beginning 1)
12222 ov-end (match-end 1)
12223 ov-prefix "")
12224 (setq ov-start (1- (point-at-eol))
12225 ov-end (1+ ov-start))
12226 (skip-chars-forward "^\n\r")
12227 (setq ov-prefix
12228 (concat
12229 (buffer-substring (1- (point)) (point))
12230 (if (> (current-column) org-tags-column)
12232 (make-string (- org-tags-column (current-column)) ?\ ))))))
12233 (org-move-overlay org-tags-overlay ov-start ov-end)
12234 (save-window-excursion
12235 (if expert
12236 (set-buffer (get-buffer-create " *Org tags*"))
12237 (delete-other-windows)
12238 (split-window-vertically)
12239 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
12240 (erase-buffer)
12241 (org-set-local 'org-done-keywords done-keywords)
12242 (org-fast-tag-insert "Inherited" inherited i-face "\n")
12243 (org-fast-tag-insert "Current" current c-face "\n\n")
12244 (org-fast-tag-show-exit exit-after-next)
12245 (org-set-current-tags-overlay current ov-prefix)
12246 (setq tbl fulltable char ?a cnt 0)
12247 (while (setq e (pop tbl))
12248 (cond
12249 ((equal (car e) :startgroup)
12250 (push '() groups) (setq ingroup t)
12251 (when (not (= cnt 0))
12252 (setq cnt 0)
12253 (insert "\n"))
12254 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
12255 ((equal (car e) :endgroup)
12256 (setq ingroup nil cnt 0)
12257 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
12258 ((equal e '(:newline))
12259 (when (not (= cnt 0))
12260 (setq cnt 0)
12261 (insert "\n")
12262 (setq e (car tbl))
12263 (while (equal (car tbl) '(:newline))
12264 (insert "\n")
12265 (setq tbl (cdr tbl)))))
12267 (setq tg (copy-sequence (car e)) c2 nil)
12268 (if (cdr e)
12269 (setq c (cdr e))
12270 ;; automatically assign a character.
12271 (setq c1 (string-to-char
12272 (downcase (substring
12273 tg (if (= (string-to-char tg) ?@) 1 0)))))
12274 (if (or (rassoc c1 ntable) (rassoc c1 table))
12275 (while (or (rassoc char ntable) (rassoc char table))
12276 (setq char (1+ char)))
12277 (setq c2 c1))
12278 (setq c (or c2 char)))
12279 (if ingroup (push tg (car groups)))
12280 (setq tg (org-add-props tg nil 'face
12281 (cond
12282 ((not (assoc tg table))
12283 (org-get-todo-face tg))
12284 ((member tg current) c-face)
12285 ((member tg inherited) i-face)
12286 (t nil))))
12287 (if (and (= cnt 0) (not ingroup)) (insert " "))
12288 (insert "[" c "] " tg (make-string
12289 (- fwidth 4 (length tg)) ?\ ))
12290 (push (cons tg c) ntable)
12291 (when (= (setq cnt (1+ cnt)) ncol)
12292 (insert "\n")
12293 (if ingroup (insert " "))
12294 (setq cnt 0)))))
12295 (setq ntable (nreverse ntable))
12296 (insert "\n")
12297 (goto-char (point-min))
12298 (if (not expert) (org-fit-window-to-buffer))
12299 (setq rtn
12300 (catch 'exit
12301 (while t
12302 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
12303 (if (not groups) "no " "")
12304 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
12305 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12306 (setq org-last-tag-selection-key c)
12307 (cond
12308 ((= c ?\r) (throw 'exit t))
12309 ((= c ?!)
12310 (setq groups (not groups))
12311 (goto-char (point-min))
12312 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
12313 ((= c ?\C-c)
12314 (if (not expert)
12315 (org-fast-tag-show-exit
12316 (setq exit-after-next (not exit-after-next)))
12317 (setq expert nil)
12318 (delete-other-windows)
12319 (split-window-vertically)
12320 (org-switch-to-buffer-other-window " *Org tags*")
12321 (org-fit-window-to-buffer)))
12322 ((or (= c ?\C-g)
12323 (and (= c ?q) (not (rassoc c ntable))))
12324 (org-detach-overlay org-tags-overlay)
12325 (setq quit-flag t))
12326 ((= c ?\ )
12327 (setq current nil)
12328 (if exit-after-next (setq exit-after-next 'now)))
12329 ((= c ?\t)
12330 (condition-case nil
12331 (setq tg (org-icompleting-read
12332 "Tag: "
12333 (or buffer-tags
12334 (with-current-buffer buf
12335 (org-get-buffer-tags)))))
12336 (quit (setq tg "")))
12337 (when (string-match "\\S-" tg)
12338 (add-to-list 'buffer-tags (list tg))
12339 (if (member tg current)
12340 (setq current (delete tg current))
12341 (push tg current)))
12342 (if exit-after-next (setq exit-after-next 'now)))
12343 ((setq e (rassoc c todo-table) tg (car e))
12344 (with-current-buffer buf
12345 (save-excursion (org-todo tg)))
12346 (if exit-after-next (setq exit-after-next 'now)))
12347 ((setq e (rassoc c ntable) tg (car e))
12348 (if (member tg current)
12349 (setq current (delete tg current))
12350 (loop for g in groups do
12351 (if (member tg g)
12352 (mapc (lambda (x)
12353 (setq current (delete x current)))
12354 g)))
12355 (push tg current))
12356 (if exit-after-next (setq exit-after-next 'now))))
12358 ;; Create a sorted list
12359 (setq current
12360 (sort current
12361 (lambda (a b)
12362 (assoc b (cdr (memq (assoc a ntable) ntable))))))
12363 (if (eq exit-after-next 'now) (throw 'exit t))
12364 (goto-char (point-min))
12365 (beginning-of-line 2)
12366 (delete-region (point) (point-at-eol))
12367 (org-fast-tag-insert "Current" current c-face)
12368 (org-set-current-tags-overlay current ov-prefix)
12369 (while (re-search-forward
12370 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
12371 (setq tg (match-string 1))
12372 (add-text-properties
12373 (match-beginning 1) (match-end 1)
12374 (list 'face
12375 (cond
12376 ((member tg current) c-face)
12377 ((member tg inherited) i-face)
12378 (t (get-text-property (match-beginning 1) 'face))))))
12379 (goto-char (point-min)))))
12380 (org-detach-overlay org-tags-overlay)
12381 (if rtn
12382 (mapconcat 'identity current ":")
12383 nil))))
12385 (defun org-get-tags-string ()
12386 "Get the TAGS string in the current headline."
12387 (unless (org-on-heading-p t)
12388 (error "Not on a heading"))
12389 (save-excursion
12390 (beginning-of-line 1)
12391 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12392 (org-match-string-no-properties 1)
12393 "")))
12395 (defun org-get-tags ()
12396 "Get the list of tags specified in the current headline."
12397 (org-split-string (org-get-tags-string) ":"))
12399 (defun org-get-buffer-tags ()
12400 "Get a table of all tags used in the buffer, for completion."
12401 (let (tags)
12402 (save-excursion
12403 (goto-char (point-min))
12404 (while (re-search-forward
12405 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
12406 (when (equal (char-after (point-at-bol 0)) ?*)
12407 (mapc (lambda (x) (add-to-list 'tags x))
12408 (org-split-string (org-match-string-no-properties 1) ":")))))
12409 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
12410 (mapcar 'list tags)))
12412 ;;;; The mapping API
12414 ;;;###autoload
12415 (defun org-map-entries (func &optional match scope &rest skip)
12416 "Call FUNC at each headline selected by MATCH in SCOPE.
12418 FUNC is a function or a lisp form. The function will be called without
12419 arguments, with the cursor positioned at the beginning of the headline.
12420 The return values of all calls to the function will be collected and
12421 returned as a list.
12423 The call to FUNC will be wrapped into a save-excursion form, so FUNC
12424 does not need to preserve point. After evaluation, the cursor will be
12425 moved to the end of the line (presumably of the headline of the
12426 processed entry) and search continues from there. Under some
12427 circumstances, this may not produce the wanted results. For example,
12428 if you have removed (e.g. archived) the current (sub)tree it could
12429 mean that the next entry will be skipped entirely. In such cases, you
12430 can specify the position from where search should continue by making
12431 FUNC set the variable `org-map-continue-from' to the desired buffer
12432 position.
12434 MATCH is a tags/property/todo match as it is used in the agenda tags view.
12435 Only headlines that are matched by this query will be considered during
12436 the iteration. When MATCH is nil or t, all headlines will be
12437 visited by the iteration.
12439 SCOPE determines the scope of this command. It can be any of:
12441 nil The current buffer, respecting the restriction if any
12442 tree The subtree started with the entry at point
12443 file The current buffer, without restriction
12444 file-with-archives
12445 The current buffer, and any archives associated with it
12446 agenda All agenda files
12447 agenda-with-archives
12448 All agenda files with any archive files associated with them
12449 \(file1 file2 ...)
12450 If this is a list, all files in the list will be scanned
12452 The remaining args are treated as settings for the skipping facilities of
12453 the scanner. The following items can be given here:
12455 archive skip trees with the archive tag.
12456 comment skip trees with the COMMENT keyword
12457 function or Emacs Lisp form:
12458 will be used as value for `org-agenda-skip-function', so whenever
12459 the function returns t, FUNC will not be called for that
12460 entry and search will continue from the point where the
12461 function leaves it.
12463 If your function needs to retrieve the tags including inherited tags
12464 at the *current* entry, you can use the value of the variable
12465 `org-scanner-tags' which will be much faster than getting the value
12466 with `org-get-tags-at'. If your function gets properties with
12467 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
12468 to t around the call to `org-entry-properties' to get the same speedup.
12469 Note that if your function moves around to retrieve tags and properties at
12470 a *different* entry, you cannot use these techniques."
12471 (let* ((org-agenda-archives-mode nil) ; just to make sure
12472 (org-agenda-skip-archived-trees (memq 'archive skip))
12473 (org-agenda-skip-comment-trees (memq 'comment skip))
12474 (org-agenda-skip-function
12475 (car (org-delete-all '(comment archive) skip)))
12476 (org-tags-match-list-sublevels t)
12477 matcher file res
12478 org-todo-keywords-for-agenda
12479 org-done-keywords-for-agenda
12480 org-todo-keyword-alist-for-agenda
12481 org-drawers-for-agenda
12482 org-tag-alist-for-agenda)
12484 (cond
12485 ((eq match t) (setq matcher t))
12486 ((eq match nil) (setq matcher t))
12487 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
12489 (save-excursion
12490 (save-restriction
12491 (when (eq scope 'tree)
12492 (org-back-to-heading t)
12493 (org-narrow-to-subtree)
12494 (setq scope nil))
12496 (if (not scope)
12497 (progn
12498 (org-prepare-agenda-buffers
12499 (list (buffer-file-name (current-buffer))))
12500 (setq res (org-scan-tags func matcher)))
12501 ;; Get the right scope
12502 (cond
12503 ((and scope (listp scope) (symbolp (car scope)))
12504 (setq scope (eval scope)))
12505 ((eq scope 'agenda)
12506 (setq scope (org-agenda-files t)))
12507 ((eq scope 'agenda-with-archives)
12508 (setq scope (org-agenda-files t))
12509 (setq scope (org-add-archive-files scope)))
12510 ((eq scope 'file)
12511 (setq scope (list (buffer-file-name))))
12512 ((eq scope 'file-with-archives)
12513 (setq scope (org-add-archive-files (list (buffer-file-name))))))
12514 (org-prepare-agenda-buffers scope)
12515 (while (setq file (pop scope))
12516 (with-current-buffer (org-find-base-buffer-visiting file)
12517 (save-excursion
12518 (save-restriction
12519 (widen)
12520 (goto-char (point-min))
12521 (setq res (append res (org-scan-tags func matcher))))))))))
12522 res))
12524 ;;;; Properties
12526 ;;; Setting and retrieving properties
12528 (defconst org-special-properties
12529 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
12530 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED")
12531 "The special properties valid in Org-mode.
12533 These are properties that are not defined in the property drawer,
12534 but in some other way.")
12536 (defconst org-default-properties
12537 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
12538 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
12539 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
12540 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
12541 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
12542 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
12543 "Some properties that are used by Org-mode for various purposes.
12544 Being in this list makes sure that they are offered for completion.")
12546 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
12547 "Regular expression matching the first line of a property drawer.")
12549 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
12550 "Regular expression matching the last line of a property drawer.")
12552 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
12553 "Regular expression matching the first line of a property drawer.")
12555 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
12556 "Regular expression matching the first line of a property drawer.")
12558 (defconst org-property-drawer-re
12559 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
12560 org-property-end-re "\\)\n?")
12561 "Matches an entire property drawer.")
12563 (defconst org-clock-drawer-re
12564 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
12565 org-property-end-re "\\)\n?")
12566 "Matches an entire clock drawer.")
12568 (defun org-property-action ()
12569 "Do an action on properties."
12570 (interactive)
12571 (let (c)
12572 (org-at-property-p)
12573 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
12574 (setq c (read-char-exclusive))
12575 (cond
12576 ((equal c ?s)
12577 (call-interactively 'org-set-property))
12578 ((equal c ?d)
12579 (call-interactively 'org-delete-property))
12580 ((equal c ?D)
12581 (call-interactively 'org-delete-property-globally))
12582 ((equal c ?c)
12583 (call-interactively 'org-compute-property-at-point))
12584 (t (error "No such property action %c" c)))))
12586 (defun org-set-effort (&optional value)
12587 "Set the effort property of the current entry.
12588 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
12589 allowed value."
12590 (interactive "P")
12591 (if (equal value 0) (setq value 10))
12592 (let* ((completion-ignore-case t)
12593 (prop org-effort-property)
12594 (cur (org-entry-get nil prop))
12595 (allowed (org-property-get-allowed-values nil prop 'table))
12596 (existing (mapcar 'list (org-property-values prop)))
12598 (val (cond
12599 ((stringp value) value)
12600 ((and allowed (integerp value))
12601 (or (car (nth (1- value) allowed))
12602 (car (org-last allowed))))
12603 (allowed
12604 (message "Select 1-9,0, [RET%s]: %s"
12605 (if cur (concat "=" cur) "")
12606 (mapconcat 'car allowed " "))
12607 (setq rpl (read-char-exclusive))
12608 (if (equal rpl ?\r)
12610 (setq rpl (- rpl ?0))
12611 (if (equal rpl 0) (setq rpl 10))
12612 (if (and (> rpl 0) (<= rpl (length allowed)))
12613 (car (nth (1- rpl) allowed))
12614 (org-completing-read "Effort: " allowed nil))))
12616 (let (org-completion-use-ido org-completion-use-iswitchb)
12617 (org-completing-read
12618 (concat "Effort " (if (and cur (string-match "\\S-" cur))
12619 (concat "[" cur "]") "")
12620 ": ")
12621 existing nil nil "" nil cur))))))
12622 (unless (equal (org-entry-get nil prop) val)
12623 (org-entry-put nil prop val))
12624 (message "%s is now %s" prop val)))
12626 (defun org-at-property-p ()
12627 "Is cursor inside a property drawer?"
12628 (save-excursion
12629 (beginning-of-line 1)
12630 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
12631 (let ((match (match-data)) ;; Keep match-data for use by calling
12632 (p (point)) ;; procedures.
12633 (range (unless (org-before-first-heading-p)
12634 (org-get-property-block))))
12635 (prog1 (and range (<= (car range) p) (< p (cdr range)))
12636 (set-match-data match))))))
12638 (defun org-get-property-block (&optional beg end force)
12639 "Return the (beg . end) range of the body of the property drawer.
12640 BEG and END can be beginning and end of subtree, if not given
12641 they will be found.
12642 If the drawer does not exist and FORCE is non-nil, create the drawer."
12643 (catch 'exit
12644 (save-excursion
12645 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
12646 (end (or end (progn (outline-next-heading) (point)))))
12647 (goto-char beg)
12648 (if (re-search-forward org-property-start-re end t)
12649 (setq beg (1+ (match-end 0)))
12650 (if force
12651 (save-excursion
12652 (org-insert-property-drawer)
12653 (setq end (progn (outline-next-heading) (point))))
12654 (throw 'exit nil))
12655 (goto-char beg)
12656 (if (re-search-forward org-property-start-re end t)
12657 (setq beg (1+ (match-end 0)))))
12658 (if (re-search-forward org-property-end-re end t)
12659 (setq end (match-beginning 0))
12660 (or force (throw 'exit nil))
12661 (goto-char beg)
12662 (setq end beg)
12663 (org-indent-line-function)
12664 (insert ":END:\n"))
12665 (cons beg end)))))
12667 (defun org-entry-properties (&optional pom which specific)
12668 "Get all properties of the entry at point-or-marker POM.
12669 This includes the TODO keyword, the tags, time strings for deadline,
12670 scheduled, and clocking, and any additional properties defined in the
12671 entry. The return value is an alist, keys may occur multiple times
12672 if the property key was used several times.
12673 POM may also be nil, in which case the current entry is used.
12674 If WHICH is nil or `all', get all properties. If WHICH is
12675 `special' or `standard', only get that subclass. If WHICH
12676 is a string only get exactly this property. Specific can be a string, the
12677 specific property we are interested in. Specifying it can speed
12678 things up because then unnecessary parsing is avoided."
12679 (setq which (or which 'all))
12680 (org-with-point-at pom
12681 (let ((clockstr (substring org-clock-string 0 -1))
12682 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
12683 (case-fold-search nil)
12684 beg end range props sum-props key value string clocksum)
12685 (save-excursion
12686 (when (condition-case nil
12687 (and (org-mode-p) (org-back-to-heading t))
12688 (error nil))
12689 (setq beg (point))
12690 (setq sum-props (get-text-property (point) 'org-summaries))
12691 (setq clocksum (get-text-property (point) :org-clock-minutes))
12692 (outline-next-heading)
12693 (setq end (point))
12694 (when (memq which '(all special))
12695 ;; Get the special properties, like TODO and tags
12696 (goto-char beg)
12697 (when (and (or (not specific) (string= specific "TODO"))
12698 (looking-at org-todo-line-regexp) (match-end 2))
12699 (push (cons "TODO" (org-match-string-no-properties 2)) props))
12700 (when (and (or (not specific) (string= specific "PRIORITY"))
12701 (looking-at org-priority-regexp))
12702 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
12703 (when (and (or (not specific) (string= specific "TAGS"))
12704 (setq value (org-get-tags-string))
12705 (string-match "\\S-" value))
12706 (push (cons "TAGS" value) props))
12707 (when (and (or (not specific) (string= specific "ALLTAGS"))
12708 (setq value (org-get-tags-at)))
12709 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
12710 ":"))
12711 props))
12712 (when (or (not specific) (string= specific "BLOCKED"))
12713 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
12714 (when (or (not specific)
12715 (member specific org-all-time-keywords)
12716 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
12717 (while (re-search-forward org-maybe-keyword-time-regexp end t)
12718 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
12719 string (if (equal key clockstr)
12720 (org-no-properties
12721 (org-trim
12722 (buffer-substring
12723 (match-beginning 3) (goto-char (point-at-eol)))))
12724 (substring (org-match-string-no-properties 3) 1 -1)))
12725 (unless key
12726 (if (= (char-after (match-beginning 3)) ?\[)
12727 (setq key "TIMESTAMP_IA")
12728 (setq key "TIMESTAMP")))
12729 (when (or (equal key clockstr) (not (assoc key props)))
12730 (push (cons key string) props))))
12734 (when (memq which '(all standard))
12735 ;; Get the standard properties, like :PROP: ...
12736 (setq range (org-get-property-block beg end))
12737 (when range
12738 (goto-char (car range))
12739 (while (re-search-forward
12740 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
12741 (cdr range) t)
12742 (setq key (org-match-string-no-properties 1)
12743 value (org-trim (or (org-match-string-no-properties 2) "")))
12744 (unless (member key excluded)
12745 (push (cons key (or value "")) props)))))
12746 (if clocksum
12747 (push (cons "CLOCKSUM"
12748 (org-columns-number-to-string (/ (float clocksum) 60.)
12749 'add_times))
12750 props))
12751 (unless (assoc "CATEGORY" props)
12752 (setq value (or (org-get-category)
12753 (progn (org-refresh-category-properties)
12754 (org-get-category))))
12755 (push (cons "CATEGORY" value) props))
12756 (append sum-props (nreverse props)))))))
12758 (defun org-entry-get (pom property &optional inherit)
12759 "Get value of PROPERTY for entry at point-or-marker POM.
12760 If INHERIT is non-nil and the entry does not have the property,
12761 then also check higher levels of the hierarchy.
12762 If INHERIT is the symbol `selective', use inheritance only if the setting
12763 in `org-use-property-inheritance' selects PROPERTY for inheritance.
12764 If the property is present but empty, the return value is the empty string.
12765 If the property is not present at all, nil is returned."
12766 (org-with-point-at pom
12767 (if (and inherit (if (eq inherit 'selective)
12768 (org-property-inherit-p property)
12770 (org-entry-get-with-inheritance property)
12771 (if (member property org-special-properties)
12772 ;; We need a special property. Use `org-entry-properties' to
12773 ;; retrieve it, but specify the wanted property
12774 (cdr (assoc property (org-entry-properties nil 'special property)))
12775 (let ((range (org-get-property-block)))
12776 (if (and range
12777 (goto-char (car range))
12778 (re-search-forward
12779 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
12780 (cdr range) t))
12781 ;; Found the property, return it.
12782 (if (match-end 1)
12783 (org-match-string-no-properties 1)
12784 "")))))))
12786 (defun org-property-or-variable-value (var &optional inherit)
12787 "Check if there is a property fixing the value of VAR.
12788 If yes, return this value. If not, return the current value of the variable."
12789 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
12790 (if (and prop (stringp prop) (string-match "\\S-" prop))
12791 (read prop)
12792 (symbol-value var))))
12794 (defun org-entry-delete (pom property)
12795 "Delete the property PROPERTY from entry at point-or-marker POM."
12796 (org-with-point-at pom
12797 (if (member property org-special-properties)
12798 nil ; cannot delete these properties.
12799 (let ((range (org-get-property-block)))
12800 (if (and range
12801 (goto-char (car range))
12802 (re-search-forward
12803 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
12804 (cdr range) t))
12805 (progn
12806 (delete-region (match-beginning 0) (1+ (point-at-eol)))
12808 nil)))))
12810 ;; Multi-values properties are properties that contain multiple values
12811 ;; These values are assumed to be single words, separated by whitespace.
12812 (defun org-entry-add-to-multivalued-property (pom property value)
12813 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
12814 (let* ((old (org-entry-get pom property))
12815 (values (and old (org-split-string old "[ \t]"))))
12816 (setq value (org-entry-protect-space value))
12817 (unless (member value values)
12818 (setq values (cons value values))
12819 (org-entry-put pom property
12820 (mapconcat 'identity values " ")))))
12822 (defun org-entry-remove-from-multivalued-property (pom property value)
12823 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
12824 (let* ((old (org-entry-get pom property))
12825 (values (and old (org-split-string old "[ \t]"))))
12826 (setq value (org-entry-protect-space value))
12827 (when (member value values)
12828 (setq values (delete value values))
12829 (org-entry-put pom property
12830 (mapconcat 'identity values " ")))))
12832 (defun org-entry-member-in-multivalued-property (pom property value)
12833 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
12834 (let* ((old (org-entry-get pom property))
12835 (values (and old (org-split-string old "[ \t]"))))
12836 (setq value (org-entry-protect-space value))
12837 (member value values)))
12839 (defun org-entry-get-multivalued-property (pom property)
12840 "Return a list of values in a multivalued property."
12841 (let* ((value (org-entry-get pom property))
12842 (values (and value (org-split-string value "[ \t]"))))
12843 (mapcar 'org-entry-restore-space values)))
12845 (defun org-entry-put-multivalued-property (pom property &rest values)
12846 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
12847 VALUES should be a list of strings. Spaces will be protected."
12848 (org-entry-put pom property
12849 (mapconcat 'org-entry-protect-space values " "))
12850 (let* ((value (org-entry-get pom property))
12851 (values (and value (org-split-string value "[ \t]"))))
12852 (mapcar 'org-entry-restore-space values)))
12854 (defun org-entry-protect-space (s)
12855 "Protect spaces and newline in string S."
12856 (while (string-match " " s)
12857 (setq s (replace-match "%20" t t s)))
12858 (while (string-match "\n" s)
12859 (setq s (replace-match "%0A" t t s)))
12862 (defun org-entry-restore-space (s)
12863 "Restore spaces and newline in string S."
12864 (while (string-match "%20" s)
12865 (setq s (replace-match " " t t s)))
12866 (while (string-match "%0A" s)
12867 (setq s (replace-match "\n" t t s)))
12870 (defvar org-entry-property-inherited-from (make-marker)
12871 "Marker pointing to the entry from where a property was inherited.
12872 Each call to `org-entry-get-with-inheritance' will set this marker to the
12873 location of the entry where the inheritance search matched. If there was
12874 no match, the marker will point nowhere.
12875 Note that also `org-entry-get' calls this function, if the INHERIT flag
12876 is set.")
12878 (defun org-entry-get-with-inheritance (property)
12879 "Get entry property, and search higher levels if not present."
12880 (move-marker org-entry-property-inherited-from nil)
12881 (let (tmp)
12882 (save-excursion
12883 (save-restriction
12884 (widen)
12885 (catch 'ex
12886 (while t
12887 (when (setq tmp (org-entry-get nil property))
12888 (org-back-to-heading t)
12889 (move-marker org-entry-property-inherited-from (point))
12890 (throw 'ex tmp))
12891 (or (org-up-heading-safe) (throw 'ex nil)))))
12892 (or tmp
12893 (cdr (assoc property org-file-properties))
12894 (cdr (assoc property org-global-properties))
12895 (cdr (assoc property org-global-properties-fixed))))))
12897 (defvar org-property-changed-functions nil
12898 "Hook called when the value of a property has changed.
12899 Each hook function should accept two arguments, the name of the property
12900 and the new value.")
12902 (defun org-entry-put (pom property value)
12903 "Set PROPERTY to VALUE for entry at point-or-marker POM."
12904 (org-with-point-at pom
12905 (org-back-to-heading t)
12906 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
12907 range)
12908 (cond
12909 ((equal property "TODO")
12910 (when (and (stringp value) (string-match "\\S-" value)
12911 (not (member value org-todo-keywords-1)))
12912 (error "\"%s\" is not a valid TODO state" value))
12913 (if (or (not value)
12914 (not (string-match "\\S-" value)))
12915 (setq value 'none))
12916 (org-todo value)
12917 (org-set-tags nil 'align))
12918 ((equal property "PRIORITY")
12919 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
12920 (string-to-char value) ?\ ))
12921 (org-set-tags nil 'align))
12922 ((equal property "SCHEDULED")
12923 (if (re-search-forward org-scheduled-time-regexp end t)
12924 (cond
12925 ((eq value 'earlier) (org-timestamp-change -1 'day))
12926 ((eq value 'later) (org-timestamp-change 1 'day))
12927 (t (call-interactively 'org-schedule)))
12928 (call-interactively 'org-schedule)))
12929 ((equal property "DEADLINE")
12930 (if (re-search-forward org-deadline-time-regexp end t)
12931 (cond
12932 ((eq value 'earlier) (org-timestamp-change -1 'day))
12933 ((eq value 'later) (org-timestamp-change 1 'day))
12934 (t (call-interactively 'org-deadline)))
12935 (call-interactively 'org-deadline)))
12936 ((member property org-special-properties)
12937 (error "The %s property can not yet be set with `org-entry-put'"
12938 property))
12939 (t ; a non-special property
12940 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
12941 (setq range (org-get-property-block beg end 'force))
12942 (goto-char (car range))
12943 (if (re-search-forward
12944 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
12945 (progn
12946 (delete-region (match-beginning 1) (match-end 1))
12947 (goto-char (match-beginning 1)))
12948 (goto-char (cdr range))
12949 (insert "\n")
12950 (backward-char 1)
12951 (org-indent-line-function)
12952 (insert ":" property ":"))
12953 (and value (insert " " value))
12954 (org-indent-line-function)))))
12955 (run-hook-with-args 'org-property-changed-functions property value)))
12957 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
12958 "Get all property keys in the current buffer.
12959 With INCLUDE-SPECIALS, also list the special properties that reflect things
12960 like tags and TODO state.
12961 With INCLUDE-DEFAULTS, also include properties that has special meaning
12962 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
12963 With INCLUDE-COLUMNS, also include property names given in COLUMN
12964 formats in the current buffer."
12965 (let (rtn range cfmt s p)
12966 (save-excursion
12967 (save-restriction
12968 (widen)
12969 (goto-char (point-min))
12970 (while (re-search-forward org-property-start-re nil t)
12971 (setq range (org-get-property-block))
12972 (goto-char (car range))
12973 (while (re-search-forward
12974 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
12975 (cdr range) t)
12976 (add-to-list 'rtn (org-match-string-no-properties 1)))
12977 (outline-next-heading))))
12979 (when include-specials
12980 (setq rtn (append org-special-properties rtn)))
12982 (when include-defaults
12983 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
12984 (add-to-list 'rtn org-effort-property))
12986 (when include-columns
12987 (save-excursion
12988 (save-restriction
12989 (widen)
12990 (goto-char (point-min))
12991 (while (re-search-forward
12992 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
12993 nil t)
12994 (setq cfmt (match-string 2) s 0)
12995 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
12996 cfmt s)
12997 (setq s (match-end 0)
12998 p (match-string 1 cfmt))
12999 (unless (or (equal p "ITEM")
13000 (member p org-special-properties))
13001 (add-to-list 'rtn (match-string 1 cfmt))))))))
13003 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
13005 (defun org-property-values (key)
13006 "Return a list of all values of property KEY."
13007 (save-excursion
13008 (save-restriction
13009 (widen)
13010 (goto-char (point-min))
13011 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
13012 values)
13013 (while (re-search-forward re nil t)
13014 (add-to-list 'values (org-trim (match-string 1))))
13015 (delete "" values)))))
13017 (defun org-insert-property-drawer ()
13018 "Insert a property drawer into the current entry."
13019 (interactive)
13020 (org-back-to-heading t)
13021 (looking-at outline-regexp)
13022 (let ((indent (if org-adapt-indentation
13023 (- (match-end 0)(match-beginning 0))
13025 (beg (point))
13026 (re (concat "^[ \t]*" org-keyword-time-regexp))
13027 end hiddenp)
13028 (outline-next-heading)
13029 (setq end (point))
13030 (goto-char beg)
13031 (while (re-search-forward re end t))
13032 (setq hiddenp (org-invisible-p))
13033 (end-of-line 1)
13034 (and (equal (char-after) ?\n) (forward-char 1))
13035 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
13036 (if (member (match-string 1) '("CLOCK:" ":END:"))
13037 ;; just skip this line
13038 (beginning-of-line 2)
13039 ;; Drawer start, find the end
13040 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
13041 (beginning-of-line 1)))
13042 (org-skip-over-state-notes)
13043 (skip-chars-backward " \t\n\r")
13044 (if (eq (char-before) ?*) (forward-char 1))
13045 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
13046 (beginning-of-line 0)
13047 (org-indent-to-column indent)
13048 (beginning-of-line 2)
13049 (org-indent-to-column indent)
13050 (beginning-of-line 0)
13051 (if hiddenp
13052 (save-excursion
13053 (org-back-to-heading t)
13054 (hide-entry))
13055 (org-flag-drawer t))))
13057 (defun org-set-property (property value)
13058 "In the current entry, set PROPERTY to VALUE.
13059 When called interactively, this will prompt for a property name, offering
13060 completion on existing and default properties. And then it will prompt
13061 for a value, offering completion either on allowed values (via an inherited
13062 xxx_ALL property) or on existing values in other instances of this property
13063 in the current file."
13064 (interactive
13065 (let* ((completion-ignore-case t)
13066 (keys (org-buffer-property-keys nil t t))
13067 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
13068 (prop (if (member prop0 keys)
13069 prop0
13070 (or (cdr (assoc (downcase prop0)
13071 (mapcar (lambda (x) (cons (downcase x) x))
13072 keys)))
13073 prop0)))
13074 (cur (org-entry-get nil prop))
13075 (prompt (concat prop " value"
13076 (if (and cur (string-match "\\S-" cur))
13077 (concat " [" cur "]") "") ": "))
13078 (allowed (org-property-get-allowed-values nil prop 'table))
13079 (existing (mapcar 'list (org-property-values prop)))
13080 (val (if allowed
13081 (org-completing-read prompt allowed nil
13082 (not (get-text-property 0 'org-unrestricted
13083 (caar allowed))))
13084 (let (org-completion-use-ido org-completion-use-iswitchb)
13085 (org-completing-read prompt existing nil nil "" nil cur)))))
13086 (list prop (if (equal val "") cur val))))
13087 (unless (equal (org-entry-get nil property) value)
13088 (org-entry-put nil property value)))
13090 (defun org-delete-property (property)
13091 "In the current entry, delete PROPERTY."
13092 (interactive
13093 (let* ((completion-ignore-case t)
13094 (prop (org-icompleting-read "Property: " (org-entry-properties nil 'standard))))
13095 (list prop)))
13096 (message "Property %s %s" property
13097 (if (org-entry-delete nil property)
13098 "deleted"
13099 "was not present in the entry")))
13101 (defun org-delete-property-globally (property)
13102 "Remove PROPERTY globally, from all entries."
13103 (interactive
13104 (let* ((completion-ignore-case t)
13105 (prop (org-icompleting-read
13106 "Globally remove property: "
13107 (mapcar 'list (org-buffer-property-keys)))))
13108 (list prop)))
13109 (save-excursion
13110 (save-restriction
13111 (widen)
13112 (goto-char (point-min))
13113 (let ((cnt 0))
13114 (while (re-search-forward
13115 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
13116 nil t)
13117 (setq cnt (1+ cnt))
13118 (replace-match ""))
13119 (message "Property \"%s\" removed from %d entries" property cnt)))))
13121 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
13123 (defun org-compute-property-at-point ()
13124 "Compute the property at point.
13125 This looks for an enclosing column format, extracts the operator and
13126 then applies it to the property in the column format's scope."
13127 (interactive)
13128 (unless (org-at-property-p)
13129 (error "Not at a property"))
13130 (let ((prop (org-match-string-no-properties 2)))
13131 (org-columns-get-format-and-top-level)
13132 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
13133 (error "No operator defined for property %s" prop))
13134 (org-columns-compute prop)))
13136 (defvar org-property-allowed-value-functions nil
13137 "Hook for functions supplying allowed values for a specific property.
13138 The functions must take a single argument, the name of the property, and
13139 return a flat list of allowed values. If \":ETC\" is one of
13140 the values, this means that these values are intended as defaults for
13141 completion, but that other values should be allowed too.
13142 The functions must return nil if they are not responsible for this
13143 property.")
13145 (defun org-property-get-allowed-values (pom property &optional table)
13146 "Get allowed values for the property PROPERTY.
13147 When TABLE is non-nil, return an alist that can directly be used for
13148 completion."
13149 (let (vals)
13150 (cond
13151 ((equal property "TODO")
13152 (setq vals (org-with-point-at pom
13153 (append org-todo-keywords-1 '("")))))
13154 ((equal property "PRIORITY")
13155 (let ((n org-lowest-priority))
13156 (while (>= n org-highest-priority)
13157 (push (char-to-string n) vals)
13158 (setq n (1- n)))))
13159 ((member property org-special-properties))
13160 ((setq vals (run-hook-with-args-until-success
13161 'org-property-allowed-value-functions property)))
13163 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
13164 (when (and vals (string-match "\\S-" vals))
13165 (setq vals (car (read-from-string (concat "(" vals ")"))))
13166 (setq vals (mapcar (lambda (x)
13167 (cond ((stringp x) x)
13168 ((numberp x) (number-to-string x))
13169 ((symbolp x) (symbol-name x))
13170 (t "???")))
13171 vals)))))
13172 (when (member ":ETC" vals)
13173 (setq vals (remove ":ETC" vals))
13174 (org-add-props (car vals) '(org-unrestricted t)))
13175 (if table (mapcar 'list vals) vals)))
13177 (defun org-property-previous-allowed-value (&optional previous)
13178 "Switch to the next allowed value for this property."
13179 (interactive)
13180 (org-property-next-allowed-value t))
13182 (defun org-property-next-allowed-value (&optional previous)
13183 "Switch to the next allowed value for this property."
13184 (interactive)
13185 (unless (org-at-property-p)
13186 (error "Not at a property"))
13187 (let* ((key (match-string 2))
13188 (value (match-string 3))
13189 (allowed (or (org-property-get-allowed-values (point) key)
13190 (and (member value '("[ ]" "[-]" "[X]"))
13191 '("[ ]" "[X]"))))
13192 nval)
13193 (unless allowed
13194 (error "Allowed values for this property have not been defined"))
13195 (if previous (setq allowed (reverse allowed)))
13196 (if (member value allowed)
13197 (setq nval (car (cdr (member value allowed)))))
13198 (setq nval (or nval (car allowed)))
13199 (if (equal nval value)
13200 (error "Only one allowed value for this property"))
13201 (org-at-property-p)
13202 (replace-match (concat " :" key ": " nval) t t)
13203 (org-indent-line-function)
13204 (beginning-of-line 1)
13205 (skip-chars-forward " \t")
13206 (run-hook-with-args 'org-property-changed-functions key nval)))
13208 (defun org-find-entry-with-id (ident)
13209 "Locate the entry that contains the ID property with exact value IDENT.
13210 IDENT can be a string, a symbol or a number, this function will search for
13211 the string representation of it.
13212 Return the position where this entry starts, or nil if there is no such entry."
13213 (interactive "sID: ")
13214 (let ((id (cond
13215 ((stringp ident) ident)
13216 ((symbol-name ident) (symbol-name ident))
13217 ((numberp ident) (number-to-string ident))
13218 (t (error "IDENT %s must be a string, symbol or number" ident))))
13219 (case-fold-search nil))
13220 (save-excursion
13221 (save-restriction
13222 (widen)
13223 (goto-char (point-min))
13224 (when (re-search-forward
13225 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
13226 nil t)
13227 (org-back-to-heading t)
13228 (point))))))
13230 ;;;; Timestamps
13232 (defvar org-last-changed-timestamp nil)
13233 (defvar org-last-inserted-timestamp nil
13234 "The last time stamp inserted with `org-insert-time-stamp'.")
13235 (defvar org-time-was-given) ; dynamically scoped parameter
13236 (defvar org-end-time-was-given) ; dynamically scoped parameter
13237 (defvar org-ts-what) ; dynamically scoped parameter
13239 (defun org-time-stamp (arg &optional inactive)
13240 "Prompt for a date/time and insert a time stamp.
13241 If the user specifies a time like HH:MM, or if this command is called
13242 with a prefix argument, the time stamp will contain date and time.
13243 Otherwise, only the date will be included. All parts of a date not
13244 specified by the user will be filled in from the current date/time.
13245 So if you press just return without typing anything, the time stamp
13246 will represent the current date/time. If there is already a timestamp
13247 at the cursor, it will be modified."
13248 (interactive "P")
13249 (let* ((ts nil)
13250 (default-time
13251 ;; Default time is either today, or, when entering a range,
13252 ;; the range start.
13253 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
13254 (save-excursion
13255 (re-search-backward
13256 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
13257 (- (point) 20) t)))
13258 (apply 'encode-time (org-parse-time-string (match-string 1)))
13259 (current-time)))
13260 (default-input (and ts (org-get-compact-tod ts)))
13261 org-time-was-given org-end-time-was-given time)
13262 (cond
13263 ((and (org-at-timestamp-p t)
13264 (memq last-command '(org-time-stamp org-time-stamp-inactive))
13265 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
13266 (insert "--")
13267 (setq time (let ((this-command this-command))
13268 (org-read-date arg 'totime nil nil
13269 default-time default-input)))
13270 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
13271 ((org-at-timestamp-p t)
13272 (setq time (let ((this-command this-command))
13273 (org-read-date arg 'totime nil nil default-time default-input)))
13274 (when (org-at-timestamp-p t) ; just to get the match data
13275 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
13276 (replace-match "")
13277 (setq org-last-changed-timestamp
13278 (org-insert-time-stamp
13279 time (or org-time-was-given arg)
13280 inactive nil nil (list org-end-time-was-given))))
13281 (message "Timestamp updated"))
13283 (setq time (let ((this-command this-command))
13284 (org-read-date arg 'totime nil nil default-time default-input)))
13285 (org-insert-time-stamp time (or org-time-was-given arg) inactive
13286 nil nil (list org-end-time-was-given))))))
13288 ;; FIXME: can we use this for something else, like computing time differences?
13289 (defun org-get-compact-tod (s)
13290 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
13291 (let* ((t1 (match-string 1 s))
13292 (h1 (string-to-number (match-string 2 s)))
13293 (m1 (string-to-number (match-string 3 s)))
13294 (t2 (and (match-end 4) (match-string 5 s)))
13295 (h2 (and t2 (string-to-number (match-string 6 s))))
13296 (m2 (and t2 (string-to-number (match-string 7 s))))
13297 dh dm)
13298 (if (not t2)
13300 (setq dh (- h2 h1) dm (- m2 m1))
13301 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
13302 (concat t1 "+" (number-to-string dh)
13303 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
13305 (defun org-time-stamp-inactive (&optional arg)
13306 "Insert an inactive time stamp.
13307 An inactive time stamp is enclosed in square brackets instead of angle
13308 brackets. It is inactive in the sense that it does not trigger agenda entries,
13309 does not link to the calendar and cannot be changed with the S-cursor keys.
13310 So these are more for recording a certain time/date."
13311 (interactive "P")
13312 (org-time-stamp arg 'inactive))
13314 (defvar org-date-ovl (org-make-overlay 1 1))
13315 (org-overlay-put org-date-ovl 'face 'org-warning)
13316 (org-detach-overlay org-date-ovl)
13318 (defvar org-ans1) ; dynamically scoped parameter
13319 (defvar org-ans2) ; dynamically scoped parameter
13321 (defvar org-plain-time-of-day-regexp) ; defined below
13323 (defvar org-overriding-default-time nil) ; dynamically scoped
13324 (defvar org-read-date-overlay nil)
13325 (defvar org-dcst nil) ; dynamically scoped
13326 (defvar org-read-date-history nil)
13327 (defvar org-read-date-final-answer nil)
13329 (defun org-read-date (&optional with-time to-time from-string prompt
13330 default-time default-input)
13331 "Read a date, possibly a time, and make things smooth for the user.
13332 The prompt will suggest to enter an ISO date, but you can also enter anything
13333 which will at least partially be understood by `parse-time-string'.
13334 Unrecognized parts of the date will default to the current day, month, year,
13335 hour and minute. If this command is called to replace a timestamp at point,
13336 of to enter the second timestamp of a range, the default time is taken from the
13337 existing stamp. For example,
13338 3-2-5 --> 2003-02-05
13339 feb 15 --> currentyear-02-15
13340 sep 12 9 --> 2009-09-12
13341 12:45 --> today 12:45
13342 22 sept 0:34 --> currentyear-09-22 0:34
13343 12 --> currentyear-currentmonth-12
13344 Fri --> nearest Friday (today or later)
13345 etc.
13347 Furthermore you can specify a relative date by giving, as the *first* thing
13348 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
13349 change in days weeks, months, years.
13350 With a single plus or minus, the date is relative to today. With a double
13351 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
13352 +4d --> four days from today
13353 +4 --> same as above
13354 +2w --> two weeks from today
13355 ++5 --> five days from default date
13357 The function understands only English month and weekday abbreviations,
13358 but this can be configured with the variables `parse-time-months' and
13359 `parse-time-weekdays'.
13361 While prompting, a calendar is popped up - you can also select the
13362 date with the mouse (button 1). The calendar shows a period of three
13363 months. To scroll it to other months, use the keys `>' and `<'.
13364 If you don't like the calendar, turn it off with
13365 \(setq org-read-date-popup-calendar nil)
13367 With optional argument TO-TIME, the date will immediately be converted
13368 to an internal time.
13369 With an optional argument WITH-TIME, the prompt will suggest to also
13370 insert a time. Note that when WITH-TIME is not set, you can still
13371 enter a time, and this function will inform the calling routine about
13372 this change. The calling routine may then choose to change the format
13373 used to insert the time stamp into the buffer to include the time.
13374 With optional argument FROM-STRING, read from this string instead from
13375 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
13376 the time/date that is used for everything that is not specified by the
13377 user."
13378 (require 'parse-time)
13379 (let* ((org-time-stamp-rounding-minutes
13380 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
13381 (org-dcst org-display-custom-times)
13382 (ct (org-current-time))
13383 (def (or org-overriding-default-time default-time ct))
13384 (defdecode (decode-time def))
13385 (dummy (progn
13386 (when (< (nth 2 defdecode) org-extend-today-until)
13387 (setcar (nthcdr 2 defdecode) -1)
13388 (setcar (nthcdr 1 defdecode) 59)
13389 (setq def (apply 'encode-time defdecode)
13390 defdecode (decode-time def)))))
13391 (calendar-frame-setup nil)
13392 (calendar-move-hook nil)
13393 (calendar-view-diary-initially-flag nil)
13394 (view-diary-entries-initially nil)
13395 (calendar-view-holidays-initially-flag nil)
13396 (view-calendar-holidays-initially nil)
13397 (timestr (format-time-string
13398 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
13399 (prompt (concat (if prompt (concat prompt " ") "")
13400 (format "Date+time [%s]: " timestr)))
13401 ans (org-ans0 "") org-ans1 org-ans2 final)
13403 (cond
13404 (from-string (setq ans from-string))
13405 (org-read-date-popup-calendar
13406 (save-excursion
13407 (save-window-excursion
13408 (calendar)
13409 (calendar-forward-day (- (time-to-days def)
13410 (calendar-absolute-from-gregorian
13411 (calendar-current-date))))
13412 (org-eval-in-calendar nil t)
13413 (let* ((old-map (current-local-map))
13414 (map (copy-keymap calendar-mode-map))
13415 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
13416 (org-defkey map (kbd "RET") 'org-calendar-select)
13417 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
13418 'org-calendar-select-mouse)
13419 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
13420 'org-calendar-select-mouse)
13421 (org-defkey minibuffer-local-map [(meta shift left)]
13422 (lambda () (interactive)
13423 (org-eval-in-calendar '(calendar-backward-month 1))))
13424 (org-defkey minibuffer-local-map [(meta shift right)]
13425 (lambda () (interactive)
13426 (org-eval-in-calendar '(calendar-forward-month 1))))
13427 (org-defkey minibuffer-local-map [(meta shift up)]
13428 (lambda () (interactive)
13429 (org-eval-in-calendar '(calendar-backward-year 1))))
13430 (org-defkey minibuffer-local-map [(meta shift down)]
13431 (lambda () (interactive)
13432 (org-eval-in-calendar '(calendar-forward-year 1))))
13433 (org-defkey minibuffer-local-map [?\e (shift left)]
13434 (lambda () (interactive)
13435 (org-eval-in-calendar '(calendar-backward-month 1))))
13436 (org-defkey minibuffer-local-map [?\e (shift right)]
13437 (lambda () (interactive)
13438 (org-eval-in-calendar '(calendar-forward-month 1))))
13439 (org-defkey minibuffer-local-map [?\e (shift up)]
13440 (lambda () (interactive)
13441 (org-eval-in-calendar '(calendar-backward-year 1))))
13442 (org-defkey minibuffer-local-map [?\e (shift down)]
13443 (lambda () (interactive)
13444 (org-eval-in-calendar '(calendar-forward-year 1))))
13445 (org-defkey minibuffer-local-map [(shift up)]
13446 (lambda () (interactive)
13447 (org-eval-in-calendar '(calendar-backward-week 1))))
13448 (org-defkey minibuffer-local-map [(shift down)]
13449 (lambda () (interactive)
13450 (org-eval-in-calendar '(calendar-forward-week 1))))
13451 (org-defkey minibuffer-local-map [(shift left)]
13452 (lambda () (interactive)
13453 (org-eval-in-calendar '(calendar-backward-day 1))))
13454 (org-defkey minibuffer-local-map [(shift right)]
13455 (lambda () (interactive)
13456 (org-eval-in-calendar '(calendar-forward-day 1))))
13457 (org-defkey minibuffer-local-map ">"
13458 (lambda () (interactive)
13459 (org-eval-in-calendar '(scroll-calendar-left 1))))
13460 (org-defkey minibuffer-local-map "<"
13461 (lambda () (interactive)
13462 (org-eval-in-calendar '(scroll-calendar-right 1))))
13463 (run-hooks 'org-read-date-minibuffer-setup-hook)
13464 (unwind-protect
13465 (progn
13466 (use-local-map map)
13467 (add-hook 'post-command-hook 'org-read-date-display)
13468 (setq org-ans0 (read-string prompt default-input
13469 'org-read-date-history nil))
13470 ;; org-ans0: from prompt
13471 ;; org-ans1: from mouse click
13472 ;; org-ans2: from calendar motion
13473 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
13474 (remove-hook 'post-command-hook 'org-read-date-display)
13475 (use-local-map old-map)
13476 (when org-read-date-overlay
13477 (org-delete-overlay org-read-date-overlay)
13478 (setq org-read-date-overlay nil)))))))
13480 (t ; Naked prompt only
13481 (unwind-protect
13482 (setq ans (read-string prompt default-input
13483 'org-read-date-history timestr))
13484 (when org-read-date-overlay
13485 (org-delete-overlay org-read-date-overlay)
13486 (setq org-read-date-overlay nil)))))
13488 (setq final (org-read-date-analyze ans def defdecode))
13489 (setq org-read-date-final-answer ans)
13491 (if to-time
13492 (apply 'encode-time final)
13493 (if (and (boundp 'org-time-was-given) org-time-was-given)
13494 (format "%04d-%02d-%02d %02d:%02d"
13495 (nth 5 final) (nth 4 final) (nth 3 final)
13496 (nth 2 final) (nth 1 final))
13497 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
13499 (defvar def)
13500 (defvar defdecode)
13501 (defvar with-time)
13502 (defvar org-read-date-analyze-futurep nil)
13503 (defun org-read-date-display ()
13504 "Display the current date prompt interpretation in the minibuffer."
13505 (when org-read-date-display-live
13506 (when org-read-date-overlay
13507 (org-delete-overlay org-read-date-overlay))
13508 (let ((p (point)))
13509 (end-of-line 1)
13510 (while (not (equal (buffer-substring
13511 (max (point-min) (- (point) 4)) (point))
13512 " "))
13513 (insert " "))
13514 (goto-char p))
13515 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
13516 " " (or org-ans1 org-ans2)))
13517 (org-end-time-was-given nil)
13518 (f (org-read-date-analyze ans def defdecode))
13519 (fmts (if org-dcst
13520 org-time-stamp-custom-formats
13521 org-time-stamp-formats))
13522 (fmt (if (or with-time
13523 (and (boundp 'org-time-was-given) org-time-was-given))
13524 (cdr fmts)
13525 (car fmts)))
13526 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
13527 (when (and org-end-time-was-given
13528 (string-match org-plain-time-of-day-regexp txt))
13529 (setq txt (concat (substring txt 0 (match-end 0)) "-"
13530 org-end-time-was-given
13531 (substring txt (match-end 0)))))
13532 (when org-read-date-analyze-futurep
13533 (setq txt (concat txt " (=>F)")))
13534 (setq org-read-date-overlay
13535 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
13536 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
13538 (defun org-read-date-analyze (ans def defdecode)
13539 "Analyse the combined answer of the date prompt."
13540 ;; FIXME: cleanup and comment
13541 (let ((nowdecode (decode-time (current-time)))
13542 delta deltan deltaw deltadef year month day
13543 hour minute second wday pm h2 m2 tl wday1
13544 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
13545 (setq org-read-date-analyze-futurep nil)
13546 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
13547 (setq ans "+0"))
13549 (when (setq delta (org-read-date-get-relative ans (current-time) def))
13550 (setq ans (replace-match "" t t ans)
13551 deltan (car delta)
13552 deltaw (nth 1 delta)
13553 deltadef (nth 2 delta)))
13555 ;; Check if there is an iso week date in there
13556 ;; If yes, store the info and postpone interpreting it until the rest
13557 ;; of the parsing is done
13558 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
13559 (setq iso-year (if (match-end 1)
13560 (org-small-year-to-year
13561 (string-to-number (match-string 1 ans))))
13562 iso-weekday (if (match-end 3)
13563 (string-to-number (match-string 3 ans)))
13564 iso-week (string-to-number (match-string 2 ans)))
13565 (setq ans (replace-match "" t t ans)))
13567 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
13568 (when (string-match
13569 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
13570 (setq year (if (match-end 2)
13571 (string-to-number (match-string 2 ans))
13572 (progn (setq kill-year t)
13573 (string-to-number (format-time-string "%Y"))))
13574 month (string-to-number (match-string 3 ans))
13575 day (string-to-number (match-string 4 ans)))
13576 (if (< year 100) (setq year (+ 2000 year)))
13577 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13578 t nil ans)))
13579 ;; Help matching american dates, like 5/30 or 5/30/7
13580 (when (string-match
13581 "^ *\\([0-3]?[0-9]\\)/\\([0-1]?[0-9]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
13582 (setq year (if (match-end 4)
13583 (string-to-number (match-string 4 ans))
13584 (progn (setq kill-year t)
13585 (string-to-number (format-time-string "%Y"))))
13586 month (string-to-number (match-string 1 ans))
13587 day (string-to-number (match-string 2 ans)))
13588 (if (< year 100) (setq year (+ 2000 year)))
13589 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13590 t nil ans)))
13591 ;; Help matching am/pm times, because `parse-time-string' does not do that.
13592 ;; If there is a time with am/pm, and *no* time without it, we convert
13593 ;; so that matching will be successful.
13594 (loop for i from 1 to 2 do ; twice, for end time as well
13595 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
13596 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
13597 (setq hour (string-to-number (match-string 1 ans))
13598 minute (if (match-end 3)
13599 (string-to-number (match-string 3 ans))
13601 pm (equal ?p
13602 (string-to-char (downcase (match-string 4 ans)))))
13603 (if (and (= hour 12) (not pm))
13604 (setq hour 0)
13605 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
13606 (setq ans (replace-match (format "%02d:%02d" hour minute)
13607 t t ans))))
13609 ;; Check if a time range is given as a duration
13610 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
13611 (setq hour (string-to-number (match-string 1 ans))
13612 h2 (+ hour (string-to-number (match-string 3 ans)))
13613 minute (string-to-number (match-string 2 ans))
13614 m2 (+ minute (if (match-end 5) (string-to-number
13615 (match-string 5 ans))0)))
13616 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
13617 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
13618 t t ans)))
13620 ;; Check if there is a time range
13621 (when (boundp 'org-end-time-was-given)
13622 (setq org-time-was-given nil)
13623 (when (and (string-match org-plain-time-of-day-regexp ans)
13624 (match-end 8))
13625 (setq org-end-time-was-given (match-string 8 ans))
13626 (setq ans (concat (substring ans 0 (match-beginning 7))
13627 (substring ans (match-end 7))))))
13629 (setq tl (parse-time-string ans)
13630 day (or (nth 3 tl) (nth 3 defdecode))
13631 month (or (nth 4 tl)
13632 (if (and org-read-date-prefer-future
13633 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
13634 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
13635 (nth 4 defdecode)))
13636 year (or (and (not kill-year) (nth 5 tl))
13637 (if (and org-read-date-prefer-future
13638 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
13639 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
13640 (nth 5 defdecode)))
13641 hour (or (nth 2 tl) (nth 2 defdecode))
13642 minute (or (nth 1 tl) (nth 1 defdecode))
13643 second (or (nth 0 tl) 0)
13644 wday (nth 6 tl))
13646 (when (and (eq org-read-date-prefer-future 'time)
13647 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
13648 (equal day (nth 3 nowdecode))
13649 (equal month (nth 4 nowdecode))
13650 (equal year (nth 5 nowdecode))
13651 (nth 2 tl)
13652 (or (< (nth 2 tl) (nth 2 nowdecode))
13653 (and (= (nth 2 tl) (nth 2 nowdecode))
13654 (nth 1 tl)
13655 (< (nth 1 tl) (nth 1 nowdecode)))))
13656 (setq day (1+ day)
13657 futurep t))
13659 ;; Special date definitions below
13660 (cond
13661 (iso-week
13662 ;; There was an iso week
13663 (require 'cal-iso)
13664 (setq futurep nil)
13665 (setq year (or iso-year year)
13666 day (or iso-weekday wday 1)
13667 wday nil ; to make sure that the trigger below does not match
13668 iso-date (calendar-gregorian-from-absolute
13669 (calendar-absolute-from-iso
13670 (list iso-week day year))))
13671 ; FIXME: Should we also push ISO weeks into the future?
13672 ; (when (and org-read-date-prefer-future
13673 ; (not iso-year)
13674 ; (< (calendar-absolute-from-gregorian iso-date)
13675 ; (time-to-days (current-time))))
13676 ; (setq year (1+ year)
13677 ; iso-date (calendar-gregorian-from-absolute
13678 ; (calendar-absolute-from-iso
13679 ; (list iso-week day year)))))
13680 (setq month (car iso-date)
13681 year (nth 2 iso-date)
13682 day (nth 1 iso-date)))
13683 (deltan
13684 (setq futurep nil)
13685 (unless deltadef
13686 (let ((now (decode-time (current-time))))
13687 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
13688 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
13689 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
13690 ((equal deltaw "m") (setq month (+ month deltan)))
13691 ((equal deltaw "y") (setq year (+ year deltan)))))
13692 ((and wday (not (nth 3 tl)))
13693 (setq futurep nil)
13694 ;; Weekday was given, but no day, so pick that day in the week
13695 ;; on or after the derived date.
13696 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
13697 (unless (equal wday wday1)
13698 (setq day (+ day (% (- wday wday1 -7) 7))))))
13699 (if (and (boundp 'org-time-was-given)
13700 (nth 2 tl))
13701 (setq org-time-was-given t))
13702 (if (< year 100) (setq year (+ 2000 year)))
13703 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
13704 (setq org-read-date-analyze-futurep futurep)
13705 (list second minute hour day month year)))
13707 (defvar parse-time-weekdays)
13709 (defun org-read-date-get-relative (s today default)
13710 "Check string S for special relative date string.
13711 TODAY and DEFAULT are internal times, for today and for a default.
13712 Return shift list (N what def-flag)
13713 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
13714 N is the number of WHATs to shift.
13715 DEF-FLAG is t when a double ++ or -- indicates shift relative to
13716 the DEFAULT date rather than TODAY."
13717 (when (and
13718 (string-match
13719 (concat
13720 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
13721 "\\([0-9]+\\)?"
13722 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
13723 "\\([ \t]\\|$\\)") s)
13724 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
13725 (let* ((dir (if (> (match-end 1) (match-beginning 1))
13726 (string-to-char (substring (match-string 1 s) -1))
13727 ?+))
13728 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
13729 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
13730 (what (if (match-end 3) (match-string 3 s) "d"))
13731 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
13732 (date (if rel default today))
13733 (wday (nth 6 (decode-time date)))
13734 delta)
13735 (if wday1
13736 (progn
13737 (setq delta (mod (+ 7 (- wday1 wday)) 7))
13738 (if (= dir ?-) (setq delta (- delta 7)))
13739 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
13740 (list delta "d" rel))
13741 (list (* n (if (= dir ?-) -1 1)) what rel)))))
13743 (defun org-order-calendar-date-args (arg1 arg2 arg3)
13744 "Turn a user-specified date into the internal representation.
13745 The internal representation needed by the calendar is (month day year).
13746 This is a wrapper to handle the brain-dead convention in calendar that
13747 user function argument order change dependent on argument order."
13748 (if (boundp 'calendar-date-style)
13749 (cond
13750 ((eq calendar-date-style 'american)
13751 (list arg1 arg2 arg3))
13752 ((eq calendar-date-style 'european)
13753 (list arg2 arg1 arg3))
13754 ((eq calendar-date-style 'iso)
13755 (list arg2 arg3 arg1)))
13756 (if (org-bound-and-true-p european-calendar-style)
13757 (list arg2 arg1 arg3)
13758 (list arg1 arg2 arg3))))
13760 (defun org-eval-in-calendar (form &optional keepdate)
13761 "Eval FORM in the calendar window and return to current window.
13762 Also, store the cursor date in variable org-ans2."
13763 (let ((sf (selected-frame))
13764 (sw (selected-window)))
13765 (select-window (get-buffer-window "*Calendar*" t))
13766 (eval form)
13767 (when (and (not keepdate) (calendar-cursor-to-date))
13768 (let* ((date (calendar-cursor-to-date))
13769 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13770 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
13771 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
13772 (select-window sw)
13773 (org-select-frame-set-input-focus sf)))
13775 (defun org-calendar-select ()
13776 "Return to `org-read-date' with the date currently selected.
13777 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13778 (interactive)
13779 (when (calendar-cursor-to-date)
13780 (let* ((date (calendar-cursor-to-date))
13781 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13782 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13783 (if (active-minibuffer-window) (exit-minibuffer))))
13785 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
13786 "Insert a date stamp for the date given by the internal TIME.
13787 WITH-HM means use the stamp format that includes the time of the day.
13788 INACTIVE means use square brackets instead of angular ones, so that the
13789 stamp will not contribute to the agenda.
13790 PRE and POST are optional strings to be inserted before and after the
13791 stamp.
13792 The command returns the inserted time stamp."
13793 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
13794 stamp)
13795 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
13796 (insert-before-markers (or pre ""))
13797 (insert-before-markers (setq stamp (format-time-string fmt time)))
13798 (when (listp extra)
13799 (setq extra (car extra))
13800 (if (and (stringp extra)
13801 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
13802 (setq extra (format "-%02d:%02d"
13803 (string-to-number (match-string 1 extra))
13804 (string-to-number (match-string 2 extra))))
13805 (setq extra nil)))
13806 (when extra
13807 (backward-char 1)
13808 (insert-before-markers extra)
13809 (forward-char 1))
13810 (insert-before-markers (or post ""))
13811 (setq org-last-inserted-timestamp stamp)))
13813 (defun org-toggle-time-stamp-overlays ()
13814 "Toggle the use of custom time stamp formats."
13815 (interactive)
13816 (setq org-display-custom-times (not org-display-custom-times))
13817 (unless org-display-custom-times
13818 (let ((p (point-min)) (bmp (buffer-modified-p)))
13819 (while (setq p (next-single-property-change p 'display))
13820 (if (and (get-text-property p 'display)
13821 (eq (get-text-property p 'face) 'org-date))
13822 (remove-text-properties
13823 p (setq p (next-single-property-change p 'display))
13824 '(display t))))
13825 (set-buffer-modified-p bmp)))
13826 (if (featurep 'xemacs)
13827 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
13828 (org-restart-font-lock)
13829 (setq org-table-may-need-update t)
13830 (if org-display-custom-times
13831 (message "Time stamps are overlayed with custom format")
13832 (message "Time stamp overlays removed")))
13834 (defun org-display-custom-time (beg end)
13835 "Overlay modified time stamp format over timestamp between BEG and END."
13836 (let* ((ts (buffer-substring beg end))
13837 t1 w1 with-hm tf time str w2 (off 0))
13838 (save-match-data
13839 (setq t1 (org-parse-time-string ts t))
13840 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
13841 (setq off (- (match-end 0) (match-beginning 0)))))
13842 (setq end (- end off))
13843 (setq w1 (- end beg)
13844 with-hm (and (nth 1 t1) (nth 2 t1))
13845 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
13846 time (org-fix-decoded-time t1)
13847 str (org-add-props
13848 (format-time-string
13849 (substring tf 1 -1) (apply 'encode-time time))
13850 nil 'mouse-face 'highlight)
13851 w2 (length str))
13852 (if (not (= w2 w1))
13853 (add-text-properties (1+ beg) (+ 2 beg)
13854 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
13855 (if (featurep 'xemacs)
13856 (progn
13857 (put-text-property beg end 'invisible t)
13858 (put-text-property beg end 'end-glyph (make-glyph str)))
13859 (put-text-property beg end 'display str))))
13861 (defun org-translate-time (string)
13862 "Translate all timestamps in STRING to custom format.
13863 But do this only if the variable `org-display-custom-times' is set."
13864 (when org-display-custom-times
13865 (save-match-data
13866 (let* ((start 0)
13867 (re org-ts-regexp-both)
13868 t1 with-hm inactive tf time str beg end)
13869 (while (setq start (string-match re string start))
13870 (setq beg (match-beginning 0)
13871 end (match-end 0)
13872 t1 (save-match-data
13873 (org-parse-time-string (substring string beg end) t))
13874 with-hm (and (nth 1 t1) (nth 2 t1))
13875 inactive (equal (substring string beg (1+ beg)) "[")
13876 tf (funcall (if with-hm 'cdr 'car)
13877 org-time-stamp-custom-formats)
13878 time (org-fix-decoded-time t1)
13879 str (format-time-string
13880 (concat
13881 (if inactive "[" "<") (substring tf 1 -1)
13882 (if inactive "]" ">"))
13883 (apply 'encode-time time))
13884 string (replace-match str t t string)
13885 start (+ start (length str)))))))
13886 string)
13888 (defun org-fix-decoded-time (time)
13889 "Set 0 instead of nil for the first 6 elements of time.
13890 Don't touch the rest."
13891 (let ((n 0))
13892 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
13894 (defun org-days-to-time (timestamp-string)
13895 "Difference between TIMESTAMP-STRING and now in days."
13896 (- (time-to-days (org-time-string-to-time timestamp-string))
13897 (time-to-days (current-time))))
13899 (defun org-deadline-close (timestamp-string &optional ndays)
13900 "Is the time in TIMESTAMP-STRING close to the current date?"
13901 (setq ndays (or ndays (org-get-wdays timestamp-string)))
13902 (and (< (org-days-to-time timestamp-string) ndays)
13903 (not (org-entry-is-done-p))))
13905 (defun org-get-wdays (ts)
13906 "Get the deadline lead time appropriate for timestring TS."
13907 (cond
13908 ((<= org-deadline-warning-days 0)
13909 ;; 0 or negative, enforce this value no matter what
13910 (- org-deadline-warning-days))
13911 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
13912 ;; lead time is specified.
13913 (floor (* (string-to-number (match-string 1 ts))
13914 (cdr (assoc (match-string 2 ts)
13915 '(("d" . 1) ("w" . 7)
13916 ("m" . 30.4) ("y" . 365.25)))))))
13917 ;; go for the default.
13918 (t org-deadline-warning-days)))
13920 (defun org-calendar-select-mouse (ev)
13921 "Return to `org-read-date' with the date currently selected.
13922 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13923 (interactive "e")
13924 (mouse-set-point ev)
13925 (when (calendar-cursor-to-date)
13926 (let* ((date (calendar-cursor-to-date))
13927 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13928 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13929 (if (active-minibuffer-window) (exit-minibuffer))))
13931 (defun org-check-deadlines (ndays)
13932 "Check if there are any deadlines due or past due.
13933 A deadline is considered due if it happens within `org-deadline-warning-days'
13934 days from today's date. If the deadline appears in an entry marked DONE,
13935 it is not shown. The prefix arg NDAYS can be used to test that many
13936 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
13937 (interactive "P")
13938 (let* ((org-warn-days
13939 (cond
13940 ((equal ndays '(4)) 100000)
13941 (ndays (prefix-numeric-value ndays))
13942 (t (abs org-deadline-warning-days))))
13943 (case-fold-search nil)
13944 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
13945 (callback
13946 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
13948 (message "%d deadlines past-due or due within %d days"
13949 (org-occur regexp nil callback)
13950 org-warn-days)))
13952 (defun org-check-before-date (date)
13953 "Check if there are deadlines or scheduled entries before DATE."
13954 (interactive (list (org-read-date)))
13955 (let ((case-fold-search nil)
13956 (regexp (concat "\\<\\(" org-deadline-string
13957 "\\|" org-scheduled-string
13958 "\\) *<\\([^>]+\\)>"))
13959 (callback
13960 (lambda () (time-less-p
13961 (org-time-string-to-time (match-string 2))
13962 (org-time-string-to-time date)))))
13963 (message "%d entries before %s"
13964 (org-occur regexp nil callback) date)))
13966 (defun org-check-after-date (date)
13967 "Check if there are deadlines or scheduled entries after DATE."
13968 (interactive (list (org-read-date)))
13969 (let ((case-fold-search nil)
13970 (regexp (concat "\\<\\(" org-deadline-string
13971 "\\|" org-scheduled-string
13972 "\\) *<\\([^>]+\\)>"))
13973 (callback
13974 (lambda () (not
13975 (time-less-p
13976 (org-time-string-to-time (match-string 2))
13977 (org-time-string-to-time date))))))
13978 (message "%d entries after %s"
13979 (org-occur regexp nil callback) date)))
13981 (defun org-evaluate-time-range (&optional to-buffer)
13982 "Evaluate a time range by computing the difference between start and end.
13983 Normally the result is just printed in the echo area, but with prefix arg
13984 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
13985 If the time range is actually in a table, the result is inserted into the
13986 next column.
13987 For time difference computation, a year is assumed to be exactly 365
13988 days in order to avoid rounding problems."
13989 (interactive "P")
13991 (org-clock-update-time-maybe)
13992 (save-excursion
13993 (unless (org-at-date-range-p t)
13994 (goto-char (point-at-bol))
13995 (re-search-forward org-tr-regexp-both (point-at-eol) t))
13996 (if (not (org-at-date-range-p t))
13997 (error "Not at a time-stamp range, and none found in current line")))
13998 (let* ((ts1 (match-string 1))
13999 (ts2 (match-string 2))
14000 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
14001 (match-end (match-end 0))
14002 (time1 (org-time-string-to-time ts1))
14003 (time2 (org-time-string-to-time ts2))
14004 (t1 (org-float-time time1))
14005 (t2 (org-float-time time2))
14006 (diff (abs (- t2 t1)))
14007 (negative (< (- t2 t1) 0))
14008 ;; (ys (floor (* 365 24 60 60)))
14009 (ds (* 24 60 60))
14010 (hs (* 60 60))
14011 (fy "%dy %dd %02d:%02d")
14012 (fy1 "%dy %dd")
14013 (fd "%dd %02d:%02d")
14014 (fd1 "%dd")
14015 (fh "%02d:%02d")
14016 y d h m align)
14017 (if havetime
14018 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14020 d (floor (/ diff ds)) diff (mod diff ds)
14021 h (floor (/ diff hs)) diff (mod diff hs)
14022 m (floor (/ diff 60)))
14023 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14025 d (floor (+ (/ diff ds) 0.5))
14026 h 0 m 0))
14027 (if (not to-buffer)
14028 (message "%s" (org-make-tdiff-string y d h m))
14029 (if (org-at-table-p)
14030 (progn
14031 (goto-char match-end)
14032 (setq align t)
14033 (and (looking-at " *|") (goto-char (match-end 0))))
14034 (goto-char match-end))
14035 (if (looking-at
14036 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
14037 (replace-match ""))
14038 (if negative (insert " -"))
14039 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
14040 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
14041 (insert " " (format fh h m))))
14042 (if align (org-table-align))
14043 (message "Time difference inserted")))))
14045 (defun org-make-tdiff-string (y d h m)
14046 (let ((fmt "")
14047 (l nil))
14048 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
14049 l (push y l)))
14050 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
14051 l (push d l)))
14052 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
14053 l (push h l)))
14054 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
14055 l (push m l)))
14056 (apply 'format fmt (nreverse l))))
14058 (defun org-time-string-to-time (s)
14059 (apply 'encode-time (org-parse-time-string s)))
14060 (defun org-time-string-to-seconds (s)
14061 (org-float-time (org-time-string-to-time s)))
14063 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
14064 "Convert a time stamp to an absolute day number.
14065 If there is a specifyer for a cyclic time stamp, get the closest date to
14066 DAYNR.
14067 PREFER and SHOW-ALL are passed through to `org-closest-date'.
14068 the variable date is bound by the calendar when this is called."
14069 (cond
14070 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
14071 (if (org-diary-sexp-entry (match-string 1 s) "" date)
14072 daynr
14073 (+ daynr 1000)))
14074 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
14075 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
14076 (time-to-days (current-time))) (match-string 0 s)
14077 prefer show-all))
14078 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
14080 (defun org-days-to-iso-week (days)
14081 "Return the iso week number."
14082 (require 'cal-iso)
14083 (car (calendar-iso-from-absolute days)))
14085 (defun org-small-year-to-year (year)
14086 "Convert 2-digit years into 4-digit years.
14087 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
14088 The year 2000 cannot be abbreviated. Any year larger than 99
14089 is returned unchanged."
14090 (if (< year 38)
14091 (setq year (+ 2000 year))
14092 (if (< year 100)
14093 (setq year (+ 1900 year))))
14094 year)
14096 (defun org-time-from-absolute (d)
14097 "Return the time corresponding to date D.
14098 D may be an absolute day number, or a calendar-type list (month day year)."
14099 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
14100 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
14102 (defun org-calendar-holiday ()
14103 "List of holidays, for Diary display in Org-mode."
14104 (require 'holidays)
14105 (let ((hl (funcall
14106 (if (fboundp 'calendar-check-holidays)
14107 'calendar-check-holidays 'check-calendar-holidays) date)))
14108 (if hl (mapconcat 'identity hl "; "))))
14110 (defun org-diary-sexp-entry (sexp entry date)
14111 "Process a SEXP diary ENTRY for DATE."
14112 (require 'diary-lib)
14113 (let ((result (if calendar-debug-sexp
14114 (let ((stack-trace-on-error t))
14115 (eval (car (read-from-string sexp))))
14116 (condition-case nil
14117 (eval (car (read-from-string sexp)))
14118 (error
14119 (beep)
14120 (message "Bad sexp at line %d in %s: %s"
14121 (org-current-line)
14122 (buffer-file-name) sexp)
14123 (sleep-for 2))))))
14124 (cond ((stringp result) result)
14125 ((and (consp result)
14126 (stringp (cdr result))) (cdr result))
14127 (result entry)
14128 (t nil))))
14130 (defun org-diary-to-ical-string (frombuf)
14131 "Get iCalendar entries from diary entries in buffer FROMBUF.
14132 This uses the icalendar.el library."
14133 (let* ((tmpdir (if (featurep 'xemacs)
14134 (temp-directory)
14135 temporary-file-directory))
14136 (tmpfile (make-temp-name
14137 (expand-file-name "orgics" tmpdir)))
14138 buf rtn b e)
14139 (with-current-buffer frombuf
14140 (icalendar-export-region (point-min) (point-max) tmpfile)
14141 (setq buf (find-buffer-visiting tmpfile))
14142 (set-buffer buf)
14143 (goto-char (point-min))
14144 (if (re-search-forward "^BEGIN:VEVENT" nil t)
14145 (setq b (match-beginning 0)))
14146 (goto-char (point-max))
14147 (if (re-search-backward "^END:VEVENT" nil t)
14148 (setq e (match-end 0)))
14149 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
14150 (kill-buffer buf)
14151 (delete-file tmpfile)
14152 rtn))
14154 (defun org-closest-date (start current change prefer show-all)
14155 "Find the date closest to CURRENT that is consistent with START and CHANGE.
14156 When PREFER is `past' return a date that is either CURRENT or past.
14157 When PREFER is `future', return a date that is either CURRENT or future.
14158 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
14159 ;; Make the proper lists from the dates
14160 (catch 'exit
14161 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
14162 dn dw sday cday n1 n2 n0
14163 d m y y1 y2 date1 date2 nmonths nm ny m2)
14165 (setq start (org-date-to-gregorian start)
14166 current (org-date-to-gregorian
14167 (if show-all
14168 current
14169 (time-to-days (current-time))))
14170 sday (calendar-absolute-from-gregorian start)
14171 cday (calendar-absolute-from-gregorian current))
14173 (if (<= cday sday) (throw 'exit sday))
14175 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
14176 (setq dn (string-to-number (match-string 1 change))
14177 dw (cdr (assoc (match-string 2 change) a1)))
14178 (error "Invalid change specifyer: %s" change))
14179 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
14180 (cond
14181 ((eq dw 'day)
14182 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
14183 n2 (+ n1 dn)))
14184 ((eq dw 'year)
14185 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
14186 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
14187 (setq date1 (list m d y1)
14188 n1 (calendar-absolute-from-gregorian date1)
14189 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
14190 n2 (calendar-absolute-from-gregorian date2)))
14191 ((eq dw 'month)
14192 ;; approx number of month between the two dates
14193 (setq nmonths (floor (/ (- cday sday) 30.436875)))
14194 ;; How often does dn fit in there?
14195 (setq d (nth 1 start) m (car start) y (nth 2 start)
14196 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
14197 m (+ m nm)
14198 ny (floor (/ m 12))
14199 y (+ y ny)
14200 m (- m (* ny 12)))
14201 (while (> m 12) (setq m (- m 12) y (1+ y)))
14202 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
14203 (setq m2 (+ m dn) y2 y)
14204 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14205 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
14206 (while (<= n2 cday)
14207 (setq n1 n2 m m2 y y2)
14208 (setq m2 (+ m dn) y2 y)
14209 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14210 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
14211 ;; Make sure n1 is the earlier date
14212 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
14213 (if show-all
14214 (cond
14215 ((eq prefer 'past) (if (= cday n2) n2 n1))
14216 ((eq prefer 'future) (if (= cday n1) n1 n2))
14217 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
14218 (cond
14219 ((eq prefer 'past) (if (= cday n2) n2 n1))
14220 ((eq prefer 'future) (if (= cday n1) n1 n2))
14221 (t (if (= cday n1) n1 n2)))))))
14223 (defun org-date-to-gregorian (date)
14224 "Turn any specification of DATE into a gregorian date for the calendar."
14225 (cond ((integerp date) (calendar-gregorian-from-absolute date))
14226 ((and (listp date) (= (length date) 3)) date)
14227 ((stringp date)
14228 (setq date (org-parse-time-string date))
14229 (list (nth 4 date) (nth 3 date) (nth 5 date)))
14230 ((listp date)
14231 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
14233 (defun org-parse-time-string (s &optional nodefault)
14234 "Parse the standard Org-mode time string.
14235 This should be a lot faster than the normal `parse-time-string'.
14236 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
14237 hour and minute fields will be nil if not given."
14238 (if (string-match org-ts-regexp0 s)
14239 (list 0
14240 (if (or (match-beginning 8) (not nodefault))
14241 (string-to-number (or (match-string 8 s) "0")))
14242 (if (or (match-beginning 7) (not nodefault))
14243 (string-to-number (or (match-string 7 s) "0")))
14244 (string-to-number (match-string 4 s))
14245 (string-to-number (match-string 3 s))
14246 (string-to-number (match-string 2 s))
14247 nil nil nil)
14248 (error "Not a standard Org-mode time string: %s" s)))
14250 (defun org-timestamp-up (&optional arg)
14251 "Increase the date item at the cursor by one.
14252 If the cursor is on the year, change the year. If it is on the month or
14253 the day, change that.
14254 With prefix ARG, change by that many units."
14255 (interactive "p")
14256 (org-timestamp-change (prefix-numeric-value arg)))
14258 (defun org-timestamp-down (&optional arg)
14259 "Decrease the date item at the cursor by one.
14260 If the cursor is on the year, change the year. If it is on the month or
14261 the day, change that.
14262 With prefix ARG, change by that many units."
14263 (interactive "p")
14264 (org-timestamp-change (- (prefix-numeric-value arg))))
14266 (defun org-timestamp-up-day (&optional arg)
14267 "Increase the date in the time stamp by one day.
14268 With prefix ARG, change that many days."
14269 (interactive "p")
14270 (if (and (not (org-at-timestamp-p t))
14271 (org-on-heading-p))
14272 (org-todo 'up)
14273 (org-timestamp-change (prefix-numeric-value arg) 'day)))
14275 (defun org-timestamp-down-day (&optional arg)
14276 "Decrease the date in the time stamp by one day.
14277 With prefix ARG, change that many days."
14278 (interactive "p")
14279 (if (and (not (org-at-timestamp-p t))
14280 (org-on-heading-p))
14281 (org-todo 'down)
14282 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
14284 (defun org-at-timestamp-p (&optional inactive-ok)
14285 "Determine if the cursor is in or at a timestamp."
14286 (interactive)
14287 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
14288 (pos (point))
14289 (ans (or (looking-at tsr)
14290 (save-excursion
14291 (skip-chars-backward "^[<\n\r\t")
14292 (if (> (point) (point-min)) (backward-char 1))
14293 (and (looking-at tsr)
14294 (> (- (match-end 0) pos) -1))))))
14295 (and ans
14296 (boundp 'org-ts-what)
14297 (setq org-ts-what
14298 (cond
14299 ((= pos (match-beginning 0)) 'bracket)
14300 ((= pos (1- (match-end 0))) 'bracket)
14301 ((org-pos-in-match-range pos 2) 'year)
14302 ((org-pos-in-match-range pos 3) 'month)
14303 ((org-pos-in-match-range pos 7) 'hour)
14304 ((org-pos-in-match-range pos 8) 'minute)
14305 ((or (org-pos-in-match-range pos 4)
14306 (org-pos-in-match-range pos 5)) 'day)
14307 ((and (> pos (or (match-end 8) (match-end 5)))
14308 (< pos (match-end 0)))
14309 (- pos (or (match-end 8) (match-end 5))))
14310 (t 'day))))
14311 ans))
14313 (defun org-toggle-timestamp-type ()
14314 "Toggle the type (<active> or [inactive]) of a time stamp."
14315 (interactive)
14316 (when (org-at-timestamp-p t)
14317 (let ((beg (match-beginning 0)) (end (match-end 0))
14318 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
14319 (save-excursion
14320 (goto-char beg)
14321 (while (re-search-forward "[][<>]" end t)
14322 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
14323 t t)))
14324 (message "Timestamp is now %sactive"
14325 (if (equal (char-after beg) ?<) "" "in")))))
14327 (defun org-timestamp-change (n &optional what)
14328 "Change the date in the time stamp at point.
14329 The date will be changed by N times WHAT. WHAT can be `day', `month',
14330 `year', `minute', `second'. If WHAT is not given, the cursor position
14331 in the timestamp determines what will be changed."
14332 (let ((pos (point))
14333 with-hm inactive
14334 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
14335 org-ts-what
14336 extra rem
14337 ts time time0)
14338 (if (not (org-at-timestamp-p t))
14339 (error "Not at a timestamp"))
14340 (if (and (not what) (eq org-ts-what 'bracket))
14341 (org-toggle-timestamp-type)
14342 (if (and (not what) (not (eq org-ts-what 'day))
14343 org-display-custom-times
14344 (get-text-property (point) 'display)
14345 (not (get-text-property (1- (point)) 'display)))
14346 (setq org-ts-what 'day))
14347 (setq org-ts-what (or what org-ts-what)
14348 inactive (= (char-after (match-beginning 0)) ?\[)
14349 ts (match-string 0))
14350 (replace-match "")
14351 (if (string-match
14352 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
14354 (setq extra (match-string 1 ts)))
14355 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
14356 (setq with-hm t))
14357 (setq time0 (org-parse-time-string ts))
14358 (when (and (eq org-ts-what 'minute)
14359 (eq current-prefix-arg nil))
14360 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
14361 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
14362 (setcar (cdr time0) (+ (nth 1 time0)
14363 (if (> n 0) (- rem) (- dm rem))))))
14364 (setq time
14365 (encode-time (or (car time0) 0)
14366 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
14367 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
14368 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
14369 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
14370 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
14371 (nthcdr 6 time0)))
14372 (when (and (member org-ts-what '(hour minute))
14373 extra
14374 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
14375 (setq extra (org-modify-ts-extra
14376 extra
14377 (if (eq org-ts-what 'hour) 2 5)
14378 n dm)))
14379 (when (integerp org-ts-what)
14380 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
14381 (if (eq what 'calendar)
14382 (let ((cal-date (org-get-date-from-calendar)))
14383 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
14384 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
14385 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
14386 (setcar time0 (or (car time0) 0))
14387 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
14388 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
14389 (setq time (apply 'encode-time time0))))
14390 (setq org-last-changed-timestamp
14391 (org-insert-time-stamp time with-hm inactive nil nil extra))
14392 (org-clock-update-time-maybe)
14393 (goto-char pos)
14394 ;; Try to recenter the calendar window, if any
14395 (if (and org-calendar-follow-timestamp-change
14396 (get-buffer-window "*Calendar*" t)
14397 (memq org-ts-what '(day month year)))
14398 (org-recenter-calendar (time-to-days time))))))
14400 (defun org-modify-ts-extra (s pos n dm)
14401 "Change the different parts of the lead-time and repeat fields in timestamp."
14402 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
14403 ng h m new rem)
14404 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
14405 (cond
14406 ((or (org-pos-in-match-range pos 2)
14407 (org-pos-in-match-range pos 3))
14408 (setq m (string-to-number (match-string 3 s))
14409 h (string-to-number (match-string 2 s)))
14410 (if (org-pos-in-match-range pos 2)
14411 (setq h (+ h n))
14412 (setq n (* dm (org-no-warnings (signum n))))
14413 (when (not (= 0 (setq rem (% m dm))))
14414 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
14415 (setq m (+ m n)))
14416 (if (< m 0) (setq m (+ m 60) h (1- h)))
14417 (if (> m 59) (setq m (- m 60) h (1+ h)))
14418 (setq h (min 24 (max 0 h)))
14419 (setq ng 1 new (format "-%02d:%02d" h m)))
14420 ((org-pos-in-match-range pos 6)
14421 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
14422 ((org-pos-in-match-range pos 5)
14423 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
14425 ((org-pos-in-match-range pos 9)
14426 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
14427 ((org-pos-in-match-range pos 8)
14428 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
14430 (when ng
14431 (setq s (concat
14432 (substring s 0 (match-beginning ng))
14434 (substring s (match-end ng))))))
14437 (defun org-recenter-calendar (date)
14438 "If the calendar is visible, recenter it to DATE."
14439 (let* ((win (selected-window))
14440 (cwin (get-buffer-window "*Calendar*" t))
14441 (calendar-move-hook nil))
14442 (when cwin
14443 (select-window cwin)
14444 (calendar-goto-date (if (listp date) date
14445 (calendar-gregorian-from-absolute date)))
14446 (select-window win))))
14448 (defun org-goto-calendar (&optional arg)
14449 "Go to the Emacs calendar at the current date.
14450 If there is a time stamp in the current line, go to that date.
14451 A prefix ARG can be used to force the current date."
14452 (interactive "P")
14453 (let ((tsr org-ts-regexp) diff
14454 (calendar-move-hook nil)
14455 (calendar-view-holidays-initially-flag nil)
14456 (view-calendar-holidays-initially nil)
14457 (calendar-view-diary-initially-flag nil)
14458 (view-diary-entries-initially nil))
14459 (if (or (org-at-timestamp-p)
14460 (save-excursion
14461 (beginning-of-line 1)
14462 (looking-at (concat ".*" tsr))))
14463 (let ((d1 (time-to-days (current-time)))
14464 (d2 (time-to-days
14465 (org-time-string-to-time (match-string 1)))))
14466 (setq diff (- d2 d1))))
14467 (calendar)
14468 (calendar-goto-today)
14469 (if (and diff (not arg)) (calendar-forward-day diff))))
14471 (defun org-get-date-from-calendar ()
14472 "Return a list (month day year) of date at point in calendar."
14473 (with-current-buffer "*Calendar*"
14474 (save-match-data
14475 (calendar-cursor-to-date))))
14477 (defun org-date-from-calendar ()
14478 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
14479 If there is already a time stamp at the cursor position, update it."
14480 (interactive)
14481 (if (org-at-timestamp-p t)
14482 (org-timestamp-change 0 'calendar)
14483 (let ((cal-date (org-get-date-from-calendar)))
14484 (org-insert-time-stamp
14485 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
14487 (defun org-minutes-to-hh:mm-string (m)
14488 "Compute H:MM from a number of minutes."
14489 (let ((h (/ m 60)))
14490 (setq m (- m (* 60 h)))
14491 (format org-time-clocksum-format h m)))
14493 (defun org-hh:mm-string-to-minutes (s)
14494 "Convert a string H:MM to a number of minutes.
14495 If the string is just a number, interpret it as minutes.
14496 In fact, the first hh:mm or number in the string will be taken,
14497 there can be extra stuff in the string.
14498 If no number is found, the return value is 0."
14499 (cond
14500 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
14501 (+ (* (string-to-number (match-string 1 s)) 60)
14502 (string-to-number (match-string 2 s))))
14503 ((string-match "\\([0-9]+\\)" s)
14504 (string-to-number (match-string 1 s)))
14505 (t 0)))
14507 ;;;; Files
14509 (defun org-save-all-org-buffers ()
14510 "Save all Org-mode buffers without user confirmation."
14511 (interactive)
14512 (message "Saving all Org-mode buffers...")
14513 (save-some-buffers t 'org-mode-p)
14514 (when (featurep 'org-id) (org-id-locations-save))
14515 (message "Saving all Org-mode buffers... done"))
14517 (defun org-revert-all-org-buffers ()
14518 "Revert all Org-mode buffers.
14519 Prompt for confirmation when there are unsaved changes.
14520 Be sure you know what you are doing before letting this function
14521 overwrite your changes.
14523 This function is useful in a setup where one tracks org files
14524 with a version control system, to revert on one machine after pulling
14525 changes from another. I believe the procedure must be like this:
14527 1. M-x org-save-all-org-buffers
14528 2. Pull changes from the other machine, resolve conflicts
14529 3. M-x org-revert-all-org-buffers"
14530 (interactive)
14531 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
14532 (error "Abort"))
14533 (save-excursion
14534 (save-window-excursion
14535 (mapc
14536 (lambda (b)
14537 (when (and (with-current-buffer b (org-mode-p))
14538 (with-current-buffer b buffer-file-name))
14539 (switch-to-buffer b)
14540 (revert-buffer t 'no-confirm)))
14541 (buffer-list))
14542 (when (and (featurep 'org-id) org-id-track-globally)
14543 (org-id-locations-load)))))
14545 ;;;; Agenda files
14547 ;;;###autoload
14548 (defun org-iswitchb (&optional arg)
14549 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
14550 With a prefix argument, restrict available to files.
14551 With two prefix arguments, restrict available buffers to agenda files."
14552 (interactive "P")
14553 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
14554 ((equal arg '(16)) (org-buffer-list 'agenda))
14555 (t (org-buffer-list)))))
14556 (switch-to-buffer
14557 (org-icompleting-read "Org buffer: "
14558 (mapcar 'list (mapcar 'buffer-name blist))
14559 nil t))))
14561 ;;;###autoload
14562 (defalias 'org-ido-switchb 'org-iswitchb)
14564 (defun org-buffer-list (&optional predicate exclude-tmp)
14565 "Return a list of Org buffers.
14566 PREDICATE can be `export', `files' or `agenda'.
14568 export restrict the list to Export buffers.
14569 files restrict the list to buffers visiting Org files.
14570 agenda restrict the list to buffers visiting agenda files.
14572 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
14573 (let* ((bfn nil)
14574 (agenda-files (and (eq predicate 'agenda)
14575 (mapcar 'file-truename (org-agenda-files t))))
14576 (filter
14577 (cond
14578 ((eq predicate 'files)
14579 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
14580 ((eq predicate 'export)
14581 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
14582 ((eq predicate 'agenda)
14583 (lambda (b)
14584 (with-current-buffer b
14585 (and (eq major-mode 'org-mode)
14586 (setq bfn (buffer-file-name b))
14587 (member (file-truename bfn) agenda-files)))))
14588 (t (lambda (b) (with-current-buffer b
14589 (or (eq major-mode 'org-mode)
14590 (string-match "\*Org .*Export"
14591 (buffer-name b)))))))))
14592 (delq nil
14593 (mapcar
14594 (lambda(b)
14595 (if (and (funcall filter b)
14596 (or (not exclude-tmp)
14597 (not (string-match "tmp" (buffer-name b)))))
14599 nil))
14600 (buffer-list)))))
14602 (defun org-agenda-files (&optional unrestricted archives)
14603 "Get the list of agenda files.
14604 Optional UNRESTRICTED means return the full list even if a restriction
14605 is currently in place.
14606 When ARCHIVES is t, include all archive files hat are really being
14607 used by the agenda files. If ARCHIVE is `ifmode', do this only if
14608 `org-agenda-archives-mode' is t."
14609 (let ((files
14610 (cond
14611 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
14612 ((stringp org-agenda-files) (org-read-agenda-file-list))
14613 ((listp org-agenda-files) org-agenda-files)
14614 (t (error "Invalid value of `org-agenda-files'")))))
14615 (setq files (apply 'append
14616 (mapcar (lambda (f)
14617 (if (file-directory-p f)
14618 (directory-files
14619 f t org-agenda-file-regexp)
14620 (list f)))
14621 files)))
14622 (when org-agenda-skip-unavailable-files
14623 (setq files (delq nil
14624 (mapcar (function
14625 (lambda (file)
14626 (and (file-readable-p file) file)))
14627 files))))
14628 (when (or (eq archives t)
14629 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
14630 (setq files (org-add-archive-files files)))
14631 files))
14633 (defun org-edit-agenda-file-list ()
14634 "Edit the list of agenda files.
14635 Depending on setup, this either uses customize to edit the variable
14636 `org-agenda-files', or it visits the file that is holding the list. In the
14637 latter case, the buffer is set up in a way that saving it automatically kills
14638 the buffer and restores the previous window configuration."
14639 (interactive)
14640 (if (stringp org-agenda-files)
14641 (let ((cw (current-window-configuration)))
14642 (find-file org-agenda-files)
14643 (org-set-local 'org-window-configuration cw)
14644 (org-add-hook 'after-save-hook
14645 (lambda ()
14646 (set-window-configuration
14647 (prog1 org-window-configuration
14648 (kill-buffer (current-buffer))))
14649 (org-install-agenda-files-menu)
14650 (message "New agenda file list installed"))
14651 nil 'local)
14652 (message "%s" (substitute-command-keys
14653 "Edit list and finish with \\[save-buffer]")))
14654 (customize-variable 'org-agenda-files)))
14656 (defun org-store-new-agenda-file-list (list)
14657 "Set new value for the agenda file list and save it correctly."
14658 (if (stringp org-agenda-files)
14659 (let ((f org-agenda-files) b)
14660 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
14661 (with-temp-file f
14662 (insert (mapconcat 'identity list "\n") "\n")))
14663 (let ((org-mode-hook nil) (org-inhibit-startup t)
14664 (org-insert-mode-line-in-empty-file nil))
14665 (setq org-agenda-files list)
14666 (customize-save-variable 'org-agenda-files org-agenda-files))))
14668 (defun org-read-agenda-file-list ()
14669 "Read the list of agenda files from a file."
14670 (when (file-directory-p org-agenda-files)
14671 (error "`org-agenda-files' cannot be a single directory"))
14672 (when (stringp org-agenda-files)
14673 (with-temp-buffer
14674 (insert-file-contents org-agenda-files)
14675 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
14678 ;;;###autoload
14679 (defun org-cycle-agenda-files ()
14680 "Cycle through the files in `org-agenda-files'.
14681 If the current buffer visits an agenda file, find the next one in the list.
14682 If the current buffer does not, find the first agenda file."
14683 (interactive)
14684 (let* ((fs (org-agenda-files t))
14685 (files (append fs (list (car fs))))
14686 (tcf (if buffer-file-name (file-truename buffer-file-name)))
14687 file)
14688 (unless files (error "No agenda files"))
14689 (catch 'exit
14690 (while (setq file (pop files))
14691 (if (equal (file-truename file) tcf)
14692 (when (car files)
14693 (find-file (car files))
14694 (throw 'exit t))))
14695 (find-file (car fs)))
14696 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
14698 (defun org-agenda-file-to-front (&optional to-end)
14699 "Move/add the current file to the top of the agenda file list.
14700 If the file is not present in the list, it is added to the front. If it is
14701 present, it is moved there. With optional argument TO-END, add/move to the
14702 end of the list."
14703 (interactive "P")
14704 (let ((org-agenda-skip-unavailable-files nil)
14705 (file-alist (mapcar (lambda (x)
14706 (cons (file-truename x) x))
14707 (org-agenda-files t)))
14708 (ctf (file-truename buffer-file-name))
14709 x had)
14710 (setq x (assoc ctf file-alist) had x)
14712 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
14713 (if to-end
14714 (setq file-alist (append (delq x file-alist) (list x)))
14715 (setq file-alist (cons x (delq x file-alist))))
14716 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
14717 (org-install-agenda-files-menu)
14718 (message "File %s to %s of agenda file list"
14719 (if had "moved" "added") (if to-end "end" "front"))))
14721 (defun org-remove-file (&optional file)
14722 "Remove current file from the list of files in variable `org-agenda-files'.
14723 These are the files which are being checked for agenda entries.
14724 Optional argument FILE means use this file instead of the current."
14725 (interactive)
14726 (let* ((org-agenda-skip-unavailable-files nil)
14727 (file (or file buffer-file-name))
14728 (true-file (file-truename file))
14729 (afile (abbreviate-file-name file))
14730 (files (delq nil (mapcar
14731 (lambda (x)
14732 (if (equal true-file
14733 (file-truename x))
14734 nil x))
14735 (org-agenda-files t)))))
14736 (if (not (= (length files) (length (org-agenda-files t))))
14737 (progn
14738 (org-store-new-agenda-file-list files)
14739 (org-install-agenda-files-menu)
14740 (message "Removed file: %s" afile))
14741 (message "File was not in list: %s (not removed)" afile))))
14743 (defun org-file-menu-entry (file)
14744 (vector file (list 'find-file file) t))
14746 (defun org-check-agenda-file (file)
14747 "Make sure FILE exists. If not, ask user what to do."
14748 (when (not (file-exists-p file))
14749 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
14750 (abbreviate-file-name file))
14751 (let ((r (downcase (read-char-exclusive))))
14752 (cond
14753 ((equal r ?r)
14754 (org-remove-file file)
14755 (throw 'nextfile t))
14756 (t (error "Abort"))))))
14758 (defun org-get-agenda-file-buffer (file)
14759 "Get a buffer visiting FILE. If the buffer needs to be created, add
14760 it to the list of buffers which might be released later."
14761 (let ((buf (org-find-base-buffer-visiting file)))
14762 (if buf
14763 buf ; just return it
14764 ;; Make a new buffer and remember it
14765 (setq buf (find-file-noselect file))
14766 (if buf (push buf org-agenda-new-buffers))
14767 buf)))
14769 (defun org-release-buffers (blist)
14770 "Release all buffers in list, asking the user for confirmation when needed.
14771 When a buffer is unmodified, it is just killed. When modified, it is saved
14772 \(if the user agrees) and then killed."
14773 (let (buf file)
14774 (while (setq buf (pop blist))
14775 (setq file (buffer-file-name buf))
14776 (when (and (buffer-modified-p buf)
14777 file
14778 (y-or-n-p (format "Save file %s? " file)))
14779 (with-current-buffer buf (save-buffer)))
14780 (kill-buffer buf))))
14782 (defun org-prepare-agenda-buffers (files)
14783 "Create buffers for all agenda files, protect archived trees and comments."
14784 (interactive)
14785 (let ((pa '(:org-archived t))
14786 (pc '(:org-comment t))
14787 (pall '(:org-archived t :org-comment t))
14788 (inhibit-read-only t)
14789 (rea (concat ":" org-archive-tag ":"))
14790 bmp file re)
14791 (save-excursion
14792 (save-restriction
14793 (while (setq file (pop files))
14794 (catch 'nextfile
14795 (if (bufferp file)
14796 (set-buffer file)
14797 (org-check-agenda-file file)
14798 (set-buffer (org-get-agenda-file-buffer file)))
14799 (widen)
14800 (setq bmp (buffer-modified-p))
14801 (org-refresh-category-properties)
14802 (setq org-todo-keywords-for-agenda
14803 (append org-todo-keywords-for-agenda org-todo-keywords-1))
14804 (setq org-done-keywords-for-agenda
14805 (append org-done-keywords-for-agenda org-done-keywords))
14806 (setq org-todo-keyword-alist-for-agenda
14807 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
14808 (setq org-drawers-for-agenda
14809 (append org-drawers-for-agenda org-drawers))
14810 (setq org-tag-alist-for-agenda
14811 (append org-tag-alist-for-agenda org-tag-alist))
14813 (save-excursion
14814 (remove-text-properties (point-min) (point-max) pall)
14815 (when org-agenda-skip-archived-trees
14816 (goto-char (point-min))
14817 (while (re-search-forward rea nil t)
14818 (if (org-on-heading-p t)
14819 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
14820 (goto-char (point-min))
14821 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
14822 (while (re-search-forward re nil t)
14823 (add-text-properties
14824 (match-beginning 0) (org-end-of-subtree t) pc)))
14825 (set-buffer-modified-p bmp)))))
14826 (setq org-todo-keyword-alist-for-agenda
14827 (org-uniquify org-todo-keyword-alist-for-agenda)
14828 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
14830 ;;;; Embedded LaTeX
14832 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14833 "Keymap for the minor `org-cdlatex-mode'.")
14835 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14836 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14837 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14838 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14839 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14841 (defvar org-cdlatex-texmathp-advice-is-done nil
14842 "Flag remembering if we have applied the advice to texmathp already.")
14844 (define-minor-mode org-cdlatex-mode
14845 "Toggle the minor `org-cdlatex-mode'.
14846 This mode supports entering LaTeX environment and math in LaTeX fragments
14847 in Org-mode.
14848 \\{org-cdlatex-mode-map}"
14849 nil " OCDL" nil
14850 (when org-cdlatex-mode (require 'cdlatex))
14851 (unless org-cdlatex-texmathp-advice-is-done
14852 (setq org-cdlatex-texmathp-advice-is-done t)
14853 (defadvice texmathp (around org-math-always-on activate)
14854 "Always return t in org-mode buffers.
14855 This is because we want to insert math symbols without dollars even outside
14856 the LaTeX math segments. If Orgmode thinks that point is actually inside
14857 an embedded LaTeX fragment, let texmathp do its job.
14858 \\[org-cdlatex-mode-map]"
14859 (interactive)
14860 (let (p)
14861 (cond
14862 ((not (org-mode-p)) ad-do-it)
14863 ((eq this-command 'cdlatex-math-symbol)
14864 (setq ad-return-value t
14865 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
14867 (let ((p (org-inside-LaTeX-fragment-p)))
14868 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
14869 (setq ad-return-value t
14870 texmathp-why '("Org-mode embedded math" . 0))
14871 (if p ad-do-it)))))))))
14873 (defun turn-on-org-cdlatex ()
14874 "Unconditionally turn on `org-cdlatex-mode'."
14875 (org-cdlatex-mode 1))
14877 (defun org-inside-LaTeX-fragment-p ()
14878 "Test if point is inside a LaTeX fragment.
14879 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
14880 sequence appearing also before point.
14881 Even though the matchers for math are configurable, this function assumes
14882 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
14883 delimiters are skipped when they have been removed by customization.
14884 The return value is nil, or a cons cell with the delimiter and
14885 and the position of this delimiter.
14887 This function does a reasonably good job, but can locally be fooled by
14888 for example currency specifications. For example it will assume being in
14889 inline math after \"$22.34\". The LaTeX fragment formatter will only format
14890 fragments that are properly closed, but during editing, we have to live
14891 with the uncertainty caused by missing closing delimiters. This function
14892 looks only before point, not after."
14893 (catch 'exit
14894 (let ((pos (point))
14895 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
14896 (lim (progn
14897 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
14898 (point)))
14899 dd-on str (start 0) m re)
14900 (goto-char pos)
14901 (when dodollar
14902 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
14903 re (nth 1 (assoc "$" org-latex-regexps)))
14904 (while (string-match re str start)
14905 (cond
14906 ((= (match-end 0) (length str))
14907 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
14908 ((= (match-end 0) (- (length str) 5))
14909 (throw 'exit nil))
14910 (t (setq start (match-end 0))))))
14911 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
14912 (goto-char pos)
14913 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
14914 (and (match-beginning 2) (throw 'exit nil))
14915 ;; count $$
14916 (while (re-search-backward "\\$\\$" lim t)
14917 (setq dd-on (not dd-on)))
14918 (goto-char pos)
14919 (if dd-on (cons "$$" m))))))
14921 (defun org-inside-latex-macro-p ()
14922 "Is point inside a LaTeX macro or its arguments?"
14923 (save-match-data
14924 (org-in-regexp
14925 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
14927 (defun test ()
14928 (interactive)
14929 (message "%s" (org-inside-latex-macro-p)))
14931 (defun org-try-cdlatex-tab ()
14932 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
14933 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
14934 - inside a LaTeX fragment, or
14935 - after the first word in a line, where an abbreviation expansion could
14936 insert a LaTeX environment."
14937 (when org-cdlatex-mode
14938 (cond
14939 ((save-excursion
14940 (skip-chars-backward "a-zA-Z0-9*")
14941 (skip-chars-backward " \t")
14942 (bolp))
14943 (cdlatex-tab) t)
14944 ((org-inside-LaTeX-fragment-p)
14945 (cdlatex-tab) t)
14946 (t nil))))
14948 (defun org-cdlatex-underscore-caret (&optional arg)
14949 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
14950 Revert to the normal definition outside of these fragments."
14951 (interactive "P")
14952 (if (org-inside-LaTeX-fragment-p)
14953 (call-interactively 'cdlatex-sub-superscript)
14954 (let (org-cdlatex-mode)
14955 (call-interactively (key-binding (vector last-input-event))))))
14957 (defun org-cdlatex-math-modify (&optional arg)
14958 "Execute `cdlatex-math-modify' in LaTeX fragments.
14959 Revert to the normal definition outside of these fragments."
14960 (interactive "P")
14961 (if (org-inside-LaTeX-fragment-p)
14962 (call-interactively 'cdlatex-math-modify)
14963 (let (org-cdlatex-mode)
14964 (call-interactively (key-binding (vector last-input-event))))))
14966 (defvar org-latex-fragment-image-overlays nil
14967 "List of overlays carrying the images of latex fragments.")
14968 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
14970 (defun org-remove-latex-fragment-image-overlays ()
14971 "Remove all overlays with LaTeX fragment images in current buffer."
14972 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
14973 (setq org-latex-fragment-image-overlays nil))
14975 (defun org-preview-latex-fragment (&optional subtree)
14976 "Preview the LaTeX fragment at point, or all locally or globally.
14977 If the cursor is in a LaTeX fragment, create the image and overlay
14978 it over the source code. If there is no fragment at point, display
14979 all fragments in the current text, from one headline to the next. With
14980 prefix SUBTREE, display all fragments in the current subtree. With a
14981 double prefix `C-u C-u', or when the cursor is before the first headline,
14982 display all fragments in the buffer.
14983 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
14984 (interactive "P")
14985 (org-remove-latex-fragment-image-overlays)
14986 (save-excursion
14987 (save-restriction
14988 (let (beg end at msg)
14989 (cond
14990 ((or (equal subtree '(16))
14991 (not (save-excursion
14992 (re-search-backward (concat "^" outline-regexp) nil t))))
14993 (setq beg (point-min) end (point-max)
14994 msg "Creating images for buffer...%s"))
14995 ((equal subtree '(4))
14996 (org-back-to-heading)
14997 (setq beg (point) end (org-end-of-subtree t)
14998 msg "Creating images for subtree...%s"))
15000 (if (setq at (org-inside-LaTeX-fragment-p))
15001 (goto-char (max (point-min) (- (cdr at) 2)))
15002 (org-back-to-heading))
15003 (setq beg (point) end (progn (outline-next-heading) (point))
15004 msg (if at "Creating image...%s"
15005 "Creating images for entry...%s"))))
15006 (message msg "")
15007 (narrow-to-region beg end)
15008 (goto-char beg)
15009 (org-format-latex
15010 (concat "ltxpng/" (file-name-sans-extension
15011 (file-name-nondirectory
15012 buffer-file-name)))
15013 default-directory 'overlays msg at 'forbuffer)
15014 (message msg "done. Use `C-c C-c' to remove images.")))))
15016 (defvar org-latex-regexps
15017 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
15018 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
15019 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
15020 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15021 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15022 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
15023 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
15024 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
15025 "Regular expressions for matching embedded LaTeX.")
15027 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
15028 "Replace LaTeX fragments with links to an image, and produce images.
15029 Some of the options can be changed using the variable
15030 `org-format-latex-options'."
15031 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
15032 (let* ((prefixnodir (file-name-nondirectory prefix))
15033 (absprefix (expand-file-name prefix dir))
15034 (todir (file-name-directory absprefix))
15035 (opt org-format-latex-options)
15036 (matchers (plist-get opt :matchers))
15037 (re-list org-latex-regexps)
15038 (org-format-latex-header-extra
15039 (plist-get (org-infile-export-plist) :latex-header-extra))
15040 (cnt 0) txt hash link beg end re e checkdir
15041 executables-checked
15042 m n block linkfile movefile ov)
15043 ;; Check the different regular expressions
15044 (while (setq e (pop re-list))
15045 (setq m (car e) re (nth 1 e) n (nth 2 e)
15046 block (if (nth 3 e) "\n\n" ""))
15047 (when (member m matchers)
15048 (goto-char (point-min))
15049 (while (re-search-forward re nil t)
15050 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
15051 (not (get-text-property (match-beginning n)
15052 'org-protected))
15053 (or (not overlays)
15054 (not (eq (get-char-property (match-beginning n)
15055 'org-overlay-type)
15056 'org-latex-overlay))))
15057 (setq txt (match-string n)
15058 beg (match-beginning n) end (match-end n)
15059 cnt (1+ cnt))
15060 (let (print-length print-level) ; make sure full list is printed
15061 (setq hash (sha1 (prin1-to-string
15062 (list org-format-latex-header
15063 org-format-latex-header-extra
15064 org-export-latex-packages-alist
15065 org-format-latex-options
15066 forbuffer txt)))
15067 linkfile (format "%s_%s.png" prefix hash)
15068 movefile (format "%s_%s.png" absprefix hash)))
15069 (setq link (concat block "[[file:" linkfile "]]" block))
15070 (if msg (message msg cnt))
15071 (goto-char beg)
15072 (unless checkdir ; make sure the directory exists
15073 (setq checkdir t)
15074 (or (file-directory-p todir) (make-directory todir)))
15076 (unless executables-checked
15077 (org-check-external-command
15078 "latex" "needed to convert LaTeX fragments to images")
15079 (org-check-external-command
15080 "dvipng" "needed to convert LaTeX fragments to images")
15081 (setq executables-checked t))
15083 (unless (file-exists-p movefile)
15084 (org-create-formula-image
15085 txt movefile opt forbuffer))
15086 (if overlays
15087 (progn
15088 (mapc (lambda (o)
15089 (if (eq (org-overlay-get o 'org-overlay-type)
15090 'org-latex-overlay)
15091 (org-delete-overlay o)))
15092 (org-overlays-in beg end))
15093 (setq ov (org-make-overlay beg end))
15094 (org-overlay-put ov 'org-overlay-type 'org-latex-overlay)
15095 (if (featurep 'xemacs)
15096 (progn
15097 (org-overlay-put ov 'invisible t)
15098 (org-overlay-put
15099 ov 'end-glyph
15100 (make-glyph (vector 'png :file movefile))))
15101 (org-overlay-put
15102 ov 'display
15103 (list 'image :type 'png :file movefile :ascent 'center)))
15104 (push ov org-latex-fragment-image-overlays)
15105 (goto-char end))
15106 (delete-region beg end)
15107 (insert link))))))))
15109 ;; This function borrows from Ganesh Swami's latex2png.el
15110 (defun org-create-formula-image (string tofile options buffer)
15111 "This calls dvipng."
15112 (require 'org-latex)
15113 (let* ((tmpdir (if (featurep 'xemacs)
15114 (temp-directory)
15115 temporary-file-directory))
15116 (texfilebase (make-temp-name
15117 (expand-file-name "orgtex" tmpdir)))
15118 (texfile (concat texfilebase ".tex"))
15119 (dvifile (concat texfilebase ".dvi"))
15120 (pngfile (concat texfilebase ".png"))
15121 (fnh (if (featurep 'xemacs)
15122 (font-height (get-face-font 'default))
15123 (face-attribute 'default :height nil)))
15124 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
15125 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
15126 (fg (or (plist-get options (if buffer :foreground :html-foreground))
15127 "Black"))
15128 (bg (or (plist-get options (if buffer :background :html-background))
15129 "Transparent")))
15130 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
15131 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
15132 (with-temp-file texfile
15133 (insert org-format-latex-header
15134 (if org-export-latex-packages-alist
15135 (concat "\n"
15136 (mapconcat (lambda(p)
15137 (if (equal "" (car p))
15138 (format "\\usepackage{%s}" (cadr p))
15139 (format "\\usepackage[%s]{%s}"
15140 (car p) (cadr p))))
15141 org-export-latex-packages-alist "\n"))
15143 (if org-format-latex-header-extra
15144 (concat "\n" org-format-latex-header-extra)
15146 "\n\\begin{document}\n" string "\n\\end{document}\n"))
15147 (let ((dir default-directory))
15148 (condition-case nil
15149 (progn
15150 (cd tmpdir)
15151 (call-process "latex" nil nil nil texfile))
15152 (error nil))
15153 (cd dir))
15154 (if (not (file-exists-p dvifile))
15155 (progn (message "Failed to create dvi file from %s" texfile) nil)
15156 (condition-case nil
15157 (call-process "dvipng" nil nil nil
15158 "-fg" fg "-bg" bg
15159 "-D" dpi
15160 ;;"-x" scale "-y" scale
15161 "-T" "tight"
15162 "-o" pngfile
15163 dvifile)
15164 (error nil))
15165 (if (not (file-exists-p pngfile))
15166 (if org-format-latex-signal-error
15167 (error "Failed to create png file from %s" texfile)
15168 (message "Failed to create png file from %s" texfile)
15169 nil)
15170 ;; Use the requested file name and clean up
15171 (copy-file pngfile tofile 'replace)
15172 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
15173 (delete-file (concat texfilebase e)))
15174 pngfile))))
15176 (defun org-dvipng-color (attr)
15177 "Return an rgb color specification for dvipng."
15178 (apply 'format "rgb %s %s %s"
15179 (mapcar 'org-normalize-color
15180 (color-values (face-attribute 'default attr nil)))))
15182 (defun org-normalize-color (value)
15183 "Return string to be used as color value for an RGB component."
15184 (format "%g" (/ value 65535.0)))
15186 ;;;; Key bindings
15188 ;; Make `C-c C-x' a prefix key
15189 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
15191 ;; TAB key with modifiers
15192 (org-defkey org-mode-map "\C-i" 'org-cycle)
15193 (org-defkey org-mode-map [(tab)] 'org-cycle)
15194 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
15195 (org-defkey org-mode-map [(meta tab)] 'org-complete)
15196 (org-defkey org-mode-map "\M-\t" 'org-complete)
15197 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
15198 ;; The following line is necessary under Suse GNU/Linux
15199 (unless (featurep 'xemacs)
15200 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
15201 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
15202 (define-key org-mode-map [backtab] 'org-shifttab)
15204 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
15205 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
15206 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
15208 ;; Cursor keys with modifiers
15209 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
15210 (org-defkey org-mode-map [(meta right)] 'org-metaright)
15211 (org-defkey org-mode-map [(meta up)] 'org-metaup)
15212 (org-defkey org-mode-map [(meta down)] 'org-metadown)
15214 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
15215 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
15216 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
15217 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
15219 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
15220 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
15221 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
15222 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
15224 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
15225 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
15227 ;;; Extra keys for tty access.
15228 ;; We only set them when really needed because otherwise the
15229 ;; menus don't show the simple keys
15231 (when (or org-use-extra-keys
15232 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
15233 (not window-system))
15234 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
15235 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
15236 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
15237 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
15238 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
15239 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
15240 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
15241 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
15242 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
15243 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
15244 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
15245 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
15246 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
15247 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
15248 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
15249 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
15250 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
15251 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
15252 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
15253 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
15254 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
15255 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
15256 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
15257 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
15258 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
15259 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
15260 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
15261 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
15263 ;; All the other keys
15265 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
15266 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
15267 (if (boundp 'narrow-map)
15268 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
15269 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
15270 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
15271 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
15272 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
15273 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
15274 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
15275 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
15276 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
15277 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
15278 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
15279 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
15280 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
15281 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
15282 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
15283 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
15284 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
15285 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
15286 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
15287 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
15288 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
15289 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
15290 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
15291 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
15292 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
15293 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
15294 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
15295 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
15296 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
15297 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
15298 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
15299 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
15300 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
15301 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
15302 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
15303 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
15304 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
15305 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
15306 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
15307 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
15308 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
15309 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
15310 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
15311 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15312 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
15313 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
15314 (org-defkey org-mode-map "\C-c^" 'org-sort)
15315 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
15316 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
15317 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
15318 (org-defkey org-mode-map "\C-m" 'org-return)
15319 (org-defkey org-mode-map "\C-j" 'org-return-indent)
15320 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
15321 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
15322 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
15323 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
15324 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
15325 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
15326 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
15327 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
15328 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
15329 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
15330 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
15331 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
15332 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
15333 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
15334 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
15335 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
15336 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
15337 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
15338 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
15339 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
15341 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
15342 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
15343 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
15344 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
15346 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
15347 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
15348 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
15349 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
15350 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
15351 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
15352 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
15353 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
15354 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
15355 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
15356 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
15357 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
15358 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
15359 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
15360 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
15362 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
15363 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
15364 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
15365 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
15367 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
15369 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
15371 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
15372 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
15374 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
15377 (when (featurep 'xemacs)
15378 (org-defkey org-mode-map 'button3 'popup-mode-menu))
15381 (defconst org-speed-commands-default
15383 ("Outline Navigation")
15384 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
15385 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
15386 ("f" . (org-speed-move-safe 'org-forward-same-level))
15387 ("b" . (org-speed-move-safe 'org-backward-same-level))
15388 ("u" . (org-speed-move-safe 'outline-up-heading))
15389 ("j" . org-goto)
15390 ("g" . (org-refile t))
15391 ("Outline Visibility")
15392 ("c" . org-cycle)
15393 ("C" . org-shifttab)
15394 (" " . org-display-outline-path)
15395 ("Outline Structure Editing")
15396 ("U" . org-shiftmetaup)
15397 ("D" . org-shiftmetadown)
15398 ("r" . org-metaright)
15399 ("l" . org-metaleft)
15400 ("R" . org-shiftmetaright)
15401 ("L" . org-shiftmetaleft)
15402 ("i" . (progn (forward-char 1) (call-interactively
15403 'org-insert-heading-respect-content)))
15404 ("^" . org-sort)
15405 ("w" . org-refile)
15406 ("a" . org-archive-subtree-default-with-confirmation)
15407 ("." . outline-mark-subtree)
15408 ("Clock Commands")
15409 ("I" . org-clock-in)
15410 ("O" . org-clock-out)
15411 ("Meta Data Editing")
15412 ("t" . org-todo)
15413 ("0" . (org-priority ?\ ))
15414 ("1" . (org-priority ?A))
15415 ("2" . (org-priority ?B))
15416 ("3" . (org-priority ?C))
15417 (";" . org-set-tags-command)
15418 ("e" . org-set-effort)
15419 ("Agenda Views etc")
15420 ("v" . org-agenda)
15421 ("/" . org-sparse-tree)
15422 ("Misc")
15423 ("o" . org-open-at-point)
15424 ("?" . org-speed-command-help)
15426 "The default speed commands.")
15428 (defun org-print-speed-command (e)
15429 (if (> (length (car e)) 1)
15430 (progn
15431 (princ "\n")
15432 (princ (car e))
15433 (princ "\n")
15434 (princ (make-string (length (car e)) ?-))
15435 (princ "\n"))
15436 (princ (car e))
15437 (princ " ")
15438 (if (symbolp (cdr e))
15439 (princ (symbol-name (cdr e)))
15440 (prin1 (cdr e)))
15441 (princ "\n")))
15443 (defun org-speed-command-help ()
15444 "Show the available speed commands."
15445 (interactive)
15446 (if (not org-use-speed-commands)
15447 (error "Speed commands are not activated, customize `org-use-speed-commands'.")
15448 (with-output-to-temp-buffer "*Help*"
15449 (princ "User-defined Speed commands\n===========================\n")
15450 (mapc 'org-print-speed-command org-speed-commands-user)
15451 (princ "\n")
15452 (princ "Built-in Speed commands\n=======================\n")
15453 (mapc 'org-print-speed-command org-speed-commands-default))
15454 (with-current-buffer "*Help*"
15455 (setq truncate-lines t))))
15457 (defun org-speed-move-safe (cmd)
15458 "Execute CMD, but make sure that the cursor always ends up in a headline.
15459 If not, return to the original position and throw an error."
15460 (interactive)
15461 (let ((pos (point)))
15462 (call-interactively cmd)
15463 (unless (and (bolp) (org-on-heading-p))
15464 (goto-char pos)
15465 (error "Boundary reached while executing %s" cmd))))
15467 (defvar org-self-insert-command-undo-counter 0)
15469 (defvar org-table-auto-blank-field) ; defined in org-table.el
15470 (defvar org-speed-command nil)
15471 (defun org-self-insert-command (N)
15472 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
15473 If the cursor is in a table looking at whitespace, the whitespace is
15474 overwritten, and the table is not marked as requiring realignment."
15475 (interactive "p")
15476 (cond
15477 ((and org-use-speed-commands
15478 (or (and (bolp) (looking-at outline-regexp))
15479 (and (functionp org-use-speed-commands)
15480 (funcall org-use-speed-commands)))
15481 (setq
15482 org-speed-command
15483 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
15484 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
15485 (cond
15486 ((commandp org-speed-command)
15487 (setq this-command org-speed-command)
15488 (call-interactively org-speed-command))
15489 ((functionp org-speed-command)
15490 (funcall org-speed-command))
15491 ((and org-speed-command (listp org-speed-command))
15492 (eval org-speed-command))
15493 (t (let (org-use-speed-commands)
15494 (call-interactively 'org-self-insert-command)))))
15495 ((and
15496 (org-table-p)
15497 (progn
15498 ;; check if we blank the field, and if that triggers align
15499 (and (featurep 'org-table) org-table-auto-blank-field
15500 (member last-command
15501 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
15502 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
15503 ;; got extra space, this field does not determine column width
15504 (let (org-table-may-need-update) (org-table-blank-field))
15505 ;; no extra space, this field may determine column width
15506 (org-table-blank-field)))
15508 (eq N 1)
15509 (looking-at "[^|\n]* |"))
15510 (let (org-table-may-need-update)
15511 (goto-char (1- (match-end 0)))
15512 (delete-backward-char 1)
15513 (goto-char (match-beginning 0))
15514 (self-insert-command N)))
15516 (setq org-table-may-need-update t)
15517 (self-insert-command N)
15518 (org-fix-tags-on-the-fly)
15519 (if org-self-insert-cluster-for-undo
15520 (if (not (eq last-command 'org-self-insert-command))
15521 (setq org-self-insert-command-undo-counter 1)
15522 (if (>= org-self-insert-command-undo-counter 20)
15523 (setq org-self-insert-command-undo-counter 1)
15524 (and (> org-self-insert-command-undo-counter 0)
15525 buffer-undo-list
15526 (not (cadr buffer-undo-list)) ; remove nil entry
15527 (setcdr buffer-undo-list (cddr buffer-undo-list)))
15528 (setq org-self-insert-command-undo-counter
15529 (1+ org-self-insert-command-undo-counter))))))))
15531 (defun org-fix-tags-on-the-fly ()
15532 (when (and (equal (char-after (point-at-bol)) ?*)
15533 (org-on-heading-p))
15534 (org-align-tags-here org-tags-column)))
15536 (defun org-delete-backward-char (N)
15537 "Like `delete-backward-char', insert whitespace at field end in tables.
15538 When deleting backwards, in tables this function will insert whitespace in
15539 front of the next \"|\" separator, to keep the table aligned. The table will
15540 still be marked for re-alignment if the field did fill the entire column,
15541 because, in this case the deletion might narrow the column."
15542 (interactive "p")
15543 (if (and (org-table-p)
15544 (eq N 1)
15545 (string-match "|" (buffer-substring (point-at-bol) (point)))
15546 (looking-at ".*?|"))
15547 (let ((pos (point))
15548 (noalign (looking-at "[^|\n\r]* |"))
15549 (c org-table-may-need-update))
15550 (backward-delete-char N)
15551 (skip-chars-forward "^|")
15552 (insert " ")
15553 (goto-char (1- pos))
15554 ;; noalign: if there were two spaces at the end, this field
15555 ;; does not determine the width of the column.
15556 (if noalign (setq org-table-may-need-update c)))
15557 (backward-delete-char N)
15558 (org-fix-tags-on-the-fly)))
15560 (defun org-delete-char (N)
15561 "Like `delete-char', but insert whitespace at field end in tables.
15562 When deleting characters, in tables this function will insert whitespace in
15563 front of the next \"|\" separator, to keep the table aligned. The table will
15564 still be marked for re-alignment if the field did fill the entire column,
15565 because, in this case the deletion might narrow the column."
15566 (interactive "p")
15567 (if (and (org-table-p)
15568 (not (bolp))
15569 (not (= (char-after) ?|))
15570 (eq N 1))
15571 (if (looking-at ".*?|")
15572 (let ((pos (point))
15573 (noalign (looking-at "[^|\n\r]* |"))
15574 (c org-table-may-need-update))
15575 (replace-match (concat
15576 (substring (match-string 0) 1 -1)
15577 " |"))
15578 (goto-char pos)
15579 ;; noalign: if there were two spaces at the end, this field
15580 ;; does not determine the width of the column.
15581 (if noalign (setq org-table-may-need-update c)))
15582 (delete-char N))
15583 (delete-char N)
15584 (org-fix-tags-on-the-fly)))
15586 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
15587 (put 'org-self-insert-command 'delete-selection t)
15588 (put 'orgtbl-self-insert-command 'delete-selection t)
15589 (put 'org-delete-char 'delete-selection 'supersede)
15590 (put 'org-delete-backward-char 'delete-selection 'supersede)
15591 (put 'org-yank 'delete-selection 'yank)
15593 ;; Make `flyspell-mode' delay after some commands
15594 (put 'org-self-insert-command 'flyspell-delayed t)
15595 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
15596 (put 'org-delete-char 'flyspell-delayed t)
15597 (put 'org-delete-backward-char 'flyspell-delayed t)
15599 ;; Make pabbrev-mode expand after org-mode commands
15600 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
15601 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
15603 ;; How to do this: Measure non-white length of current string
15604 ;; If equal to column width, we should realign.
15606 (defun org-remap (map &rest commands)
15607 "In MAP, remap the functions given in COMMANDS.
15608 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
15609 (let (new old)
15610 (while commands
15611 (setq old (pop commands) new (pop commands))
15612 (if (fboundp 'command-remapping)
15613 (org-defkey map (vector 'remap old) new)
15614 (substitute-key-definition old new map global-map)))))
15616 (when (eq org-enable-table-editor 'optimized)
15617 ;; If the user wants maximum table support, we need to hijack
15618 ;; some standard editing functions
15619 (org-remap org-mode-map
15620 'self-insert-command 'org-self-insert-command
15621 'delete-char 'org-delete-char
15622 'delete-backward-char 'org-delete-backward-char)
15623 (org-defkey org-mode-map "|" 'org-force-self-insert))
15625 (defvar org-ctrl-c-ctrl-c-hook nil
15626 "Hook for functions attaching themselves to `C-c C-c'.
15627 This can be used to add additional functionality to the C-c C-c key which
15628 executes context-dependent commands.
15629 Each function will be called with no arguments. The function must check
15630 if the context is appropriate for it to act. If yes, it should do its
15631 thing and then return a non-nil value. If the context is wrong,
15632 just do nothing and return nil.")
15634 (defvar org-tab-first-hook nil
15635 "Hook for functions to attach themselves to TAB.
15636 See `org-ctrl-c-ctrl-c-hook' for more information.
15637 This hook runs as the first action when TAB is pressed, even before
15638 `org-cycle' messes around with the `outline-regexp' to cater for
15639 inline tasks and plain list item folding.
15640 If any function in this hook returns t, not other actions like table
15641 field motion visibility cycling will be done.")
15643 (defvar org-tab-after-check-for-table-hook nil
15644 "Hook for functions to attach themselves to TAB.
15645 See `org-ctrl-c-ctrl-c-hook' for more information.
15646 This hook runs after it has been established that the cursor is not in a
15647 table, but before checking if the cursor is in a headline or if global cycling
15648 should be done.
15649 If any function in this hook returns t, not other actions like visibility
15650 cycling will be done.")
15652 (defvar org-tab-after-check-for-cycling-hook nil
15653 "Hook for functions to attach themselves to TAB.
15654 See `org-ctrl-c-ctrl-c-hook' for more information.
15655 This hook runs after it has been established that not table field motion and
15656 not visibility should be done because of current context. This is probably
15657 the place where a package like yasnippets can hook in.")
15659 (defvar org-tab-before-tab-emulation-hook nil
15660 "Hook for functions to attach themselves to TAB.
15661 See `org-ctrl-c-ctrl-c-hook' for more information.
15662 This hook runs after every other options for TAB have been exhausted, but
15663 before indentation and \t insertion takes place.")
15665 (defvar org-metaleft-hook nil
15666 "Hook for functions attaching themselves to `M-left'.
15667 See `org-ctrl-c-ctrl-c-hook' for more information.")
15668 (defvar org-metaright-hook nil
15669 "Hook for functions attaching themselves to `M-right'.
15670 See `org-ctrl-c-ctrl-c-hook' for more information.")
15671 (defvar org-metaup-hook nil
15672 "Hook for functions attaching themselves to `M-up'.
15673 See `org-ctrl-c-ctrl-c-hook' for more information.")
15674 (defvar org-metadown-hook nil
15675 "Hook for functions attaching themselves to `M-down'.
15676 See `org-ctrl-c-ctrl-c-hook' for more information.")
15677 (defvar org-shiftmetaleft-hook nil
15678 "Hook for functions attaching themselves to `M-S-left'.
15679 See `org-ctrl-c-ctrl-c-hook' for more information.")
15680 (defvar org-shiftmetaright-hook nil
15681 "Hook for functions attaching themselves to `M-S-right'.
15682 See `org-ctrl-c-ctrl-c-hook' for more information.")
15683 (defvar org-shiftmetaup-hook nil
15684 "Hook for functions attaching themselves to `M-S-up'.
15685 See `org-ctrl-c-ctrl-c-hook' for more information.")
15686 (defvar org-shiftmetadown-hook nil
15687 "Hook for functions attaching themselves to `M-S-down'.
15688 See `org-ctrl-c-ctrl-c-hook' for more information.")
15689 (defvar org-metareturn-hook nil
15690 "Hook for functions attaching themselves to `M-RET'.
15691 See `org-ctrl-c-ctrl-c-hook' for more information.")
15693 (defun org-modifier-cursor-error ()
15694 "Throw an error, a modified cursor command was applied in wrong context."
15695 (error "This command is active in special context like tables, headlines or items"))
15697 (defun org-shiftselect-error ()
15698 "Throw an error because Shift-Cursor command was applied in wrong context."
15699 (if (and (boundp 'shift-select-mode) shift-select-mode)
15700 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
15701 (error "This command works only in special context like headlines or timestamps")))
15703 (defun org-call-for-shift-select (cmd)
15704 (let ((this-command-keys-shift-translated t))
15705 (call-interactively cmd)))
15707 (defun org-shifttab (&optional arg)
15708 "Global visibility cycling or move to previous table field.
15709 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15710 on context.
15711 See the individual commands for more information."
15712 (interactive "P")
15713 (cond
15714 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15715 ((integerp arg)
15716 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
15717 (message "Content view to level: %d" arg)
15718 (org-content (prefix-numeric-value arg2))
15719 (setq org-cycle-global-status 'overview)))
15720 (t (call-interactively 'org-global-cycle))))
15722 (defun org-shiftmetaleft ()
15723 "Promote subtree or delete table column.
15724 Calls `org-promote-subtree', `org-outdent-item',
15725 or `org-table-delete-column', depending on context.
15726 See the individual commands for more information."
15727 (interactive)
15728 (cond
15729 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
15730 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15731 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15732 ((org-at-item-p) (call-interactively 'org-outdent-item))
15733 (t (org-modifier-cursor-error))))
15735 (defun org-shiftmetaright ()
15736 "Demote subtree or insert table column.
15737 Calls `org-demote-subtree', `org-indent-item',
15738 or `org-table-insert-column', depending on context.
15739 See the individual commands for more information."
15740 (interactive)
15741 (cond
15742 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
15743 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15744 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15745 ((org-at-item-p) (call-interactively 'org-indent-item))
15746 (t (org-modifier-cursor-error))))
15748 (defun org-shiftmetaup (&optional arg)
15749 "Move subtree up or kill table row.
15750 Calls `org-move-subtree-up' or `org-table-kill-row' or
15751 `org-move-item-up' depending on context. See the individual commands
15752 for more information."
15753 (interactive "P")
15754 (cond
15755 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
15756 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15757 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15758 ((org-at-item-p) (call-interactively 'org-move-item-up))
15759 (t (org-modifier-cursor-error))))
15761 (defun org-shiftmetadown (&optional arg)
15762 "Move subtree down or insert table row.
15763 Calls `org-move-subtree-down' or `org-table-insert-row' or
15764 `org-move-item-down', depending on context. See the individual
15765 commands for more information."
15766 (interactive "P")
15767 (cond
15768 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
15769 ((org-at-table-p) (call-interactively 'org-table-insert-row))
15770 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15771 ((org-at-item-p) (call-interactively 'org-move-item-down))
15772 (t (org-modifier-cursor-error))))
15774 (defun org-metaleft (&optional arg)
15775 "Promote heading or move table column to left.
15776 Calls `org-do-promote' or `org-table-move-column', depending on context.
15777 With no specific context, calls the Emacs default `backward-word'.
15778 See the individual commands for more information."
15779 (interactive "P")
15780 (cond
15781 ((run-hook-with-args-until-success 'org-metaleft-hook))
15782 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
15783 ((or (org-on-heading-p)
15784 (and (org-region-active-p)
15785 (save-excursion
15786 (goto-char (region-beginning))
15787 (org-on-heading-p))))
15788 (call-interactively 'org-do-promote))
15789 ((or (org-at-item-p)
15790 (and (org-region-active-p)
15791 (save-excursion
15792 (goto-char (region-beginning))
15793 (org-at-item-p))))
15794 (call-interactively 'org-outdent-item))
15795 (t (call-interactively 'backward-word))))
15797 (defun org-metaright (&optional arg)
15798 "Demote subtree or move table column to right.
15799 Calls `org-do-demote' or `org-table-move-column', depending on context.
15800 With no specific context, calls the Emacs default `forward-word'.
15801 See the individual commands for more information."
15802 (interactive "P")
15803 (cond
15804 ((run-hook-with-args-until-success 'org-metaright-hook))
15805 ((org-at-table-p) (call-interactively 'org-table-move-column))
15806 ((or (org-on-heading-p)
15807 (and (org-region-active-p)
15808 (save-excursion
15809 (goto-char (region-beginning))
15810 (org-on-heading-p))))
15811 (call-interactively 'org-do-demote))
15812 ((or (org-at-item-p)
15813 (and (org-region-active-p)
15814 (save-excursion
15815 (goto-char (region-beginning))
15816 (org-at-item-p))))
15817 (call-interactively 'org-indent-item))
15818 (t (call-interactively 'forward-word))))
15820 (defun org-metaup (&optional arg)
15821 "Move subtree up or move table row up.
15822 Calls `org-move-subtree-up' or `org-table-move-row' or
15823 `org-move-item-up', depending on context. See the individual commands
15824 for more information."
15825 (interactive "P")
15826 (cond
15827 ((run-hook-with-args-until-success 'org-metaup-hook))
15828 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
15829 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15830 ((org-at-item-p) (call-interactively 'org-move-item-up))
15831 (t (transpose-lines 1) (beginning-of-line -1))))
15833 (defun org-metadown (&optional arg)
15834 "Move subtree down or move table row down.
15835 Calls `org-move-subtree-down' or `org-table-move-row' or
15836 `org-move-item-down', depending on context. See the individual
15837 commands for more information."
15838 (interactive "P")
15839 (cond
15840 ((run-hook-with-args-until-success 'org-metadown-hook))
15841 ((org-at-table-p) (call-interactively 'org-table-move-row))
15842 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15843 ((org-at-item-p) (call-interactively 'org-move-item-down))
15844 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
15846 (defun org-shiftup (&optional arg)
15847 "Increase item in timestamp or increase priority of current headline.
15848 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
15849 depending on context. See the individual commands for more information."
15850 (interactive "P")
15851 (cond
15852 ((and org-support-shift-select (org-region-active-p))
15853 (org-call-for-shift-select 'previous-line))
15854 ((org-at-timestamp-p t)
15855 (call-interactively (if org-edit-timestamp-down-means-later
15856 'org-timestamp-down 'org-timestamp-up)))
15857 ((and (not (eq org-support-shift-select 'always))
15858 org-enable-priority-commands
15859 (org-on-heading-p))
15860 (call-interactively 'org-priority-up))
15861 ((and (not org-support-shift-select) (org-at-item-p))
15862 (call-interactively 'org-previous-item))
15863 ((org-clocktable-try-shift 'up arg))
15864 (org-support-shift-select
15865 (org-call-for-shift-select 'previous-line))
15866 (t (org-shiftselect-error))))
15868 (defun org-shiftdown (&optional arg)
15869 "Decrease item in timestamp or decrease priority of current headline.
15870 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
15871 depending on context. See the individual commands for more information."
15872 (interactive "P")
15873 (cond
15874 ((and org-support-shift-select (org-region-active-p))
15875 (org-call-for-shift-select 'next-line))
15876 ((org-at-timestamp-p t)
15877 (call-interactively (if org-edit-timestamp-down-means-later
15878 'org-timestamp-up 'org-timestamp-down)))
15879 ((and (not (eq org-support-shift-select 'always))
15880 org-enable-priority-commands
15881 (org-on-heading-p))
15882 (call-interactively 'org-priority-down))
15883 ((and (not org-support-shift-select) (org-at-item-p))
15884 (call-interactively 'org-next-item))
15885 ((org-clocktable-try-shift 'down arg))
15886 (org-support-shift-select
15887 (org-call-for-shift-select 'next-line))
15888 (t (org-shiftselect-error))))
15890 (defun org-shiftright (&optional arg)
15891 "Cycle the thing at point or in the current line, depending on context.
15892 Depending on context, this does one of the following:
15894 - switch a timestamp at point one day into the future
15895 - on a headline, switch to the next TODO keyword.
15896 - on an item, switch entire list to the next bullet type
15897 - on a property line, switch to the next allowed value
15898 - on a clocktable definition line, move time block into the future"
15899 (interactive "P")
15900 (cond
15901 ((and org-support-shift-select (org-region-active-p))
15902 (org-call-for-shift-select 'forward-char))
15903 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
15904 ((and (not (eq org-support-shift-select 'always))
15905 (org-on-heading-p))
15906 (let ((org-inhibit-logging
15907 (not org-treat-S-cursor-todo-selection-as-state-change))
15908 (org-inhibit-blocking
15909 (not org-treat-S-cursor-todo-selection-as-state-change)))
15910 (org-call-with-arg 'org-todo 'right)))
15911 ((or (and org-support-shift-select
15912 (not (eq org-support-shift-select 'always))
15913 (org-at-item-bullet-p))
15914 (and (not org-support-shift-select) (org-at-item-p)))
15915 (org-call-with-arg 'org-cycle-list-bullet nil))
15916 ((and (not (eq org-support-shift-select 'always))
15917 (org-at-property-p))
15918 (call-interactively 'org-property-next-allowed-value))
15919 ((org-clocktable-try-shift 'right arg))
15920 (org-support-shift-select
15921 (org-call-for-shift-select 'forward-char))
15922 (t (org-shiftselect-error))))
15924 (defun org-shiftleft (&optional arg)
15925 "Cycle the thing at point or in the current line, depending on context.
15926 Depending on context, this does one of the following:
15928 - switch a timestamp at point one day into the past
15929 - on a headline, switch to the previous TODO keyword.
15930 - on an item, switch entire list to the previous bullet type
15931 - on a property line, switch to the previous allowed value
15932 - on a clocktable definition line, move time block into the past"
15933 (interactive "P")
15934 (cond
15935 ((and org-support-shift-select (org-region-active-p))
15936 (org-call-for-shift-select 'backward-char))
15937 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
15938 ((and (not (eq org-support-shift-select 'always))
15939 (org-on-heading-p))
15940 (let ((org-inhibit-logging
15941 (not org-treat-S-cursor-todo-selection-as-state-change))
15942 (org-inhibit-blocking
15943 (not org-treat-S-cursor-todo-selection-as-state-change)))
15944 (org-call-with-arg 'org-todo 'left)))
15945 ((or (and org-support-shift-select
15946 (not (eq org-support-shift-select 'always))
15947 (org-at-item-bullet-p))
15948 (and (not org-support-shift-select) (org-at-item-p)))
15949 (org-call-with-arg 'org-cycle-list-bullet 'previous))
15950 ((and (not (eq org-support-shift-select 'always))
15951 (org-at-property-p))
15952 (call-interactively 'org-property-previous-allowed-value))
15953 ((org-clocktable-try-shift 'left arg))
15954 (org-support-shift-select
15955 (org-call-for-shift-select 'backward-char))
15956 (t (org-shiftselect-error))))
15958 (defun org-shiftcontrolright ()
15959 "Switch to next TODO set."
15960 (interactive)
15961 (cond
15962 ((and org-support-shift-select (org-region-active-p))
15963 (org-call-for-shift-select 'forward-word))
15964 ((and (not (eq org-support-shift-select 'always))
15965 (org-on-heading-p))
15966 (org-call-with-arg 'org-todo 'nextset))
15967 (org-support-shift-select
15968 (org-call-for-shift-select 'forward-word))
15969 (t (org-shiftselect-error))))
15971 (defun org-shiftcontrolleft ()
15972 "Switch to previous TODO set."
15973 (interactive)
15974 (cond
15975 ((and org-support-shift-select (org-region-active-p))
15976 (org-call-for-shift-select 'backward-word))
15977 ((and (not (eq org-support-shift-select 'always))
15978 (org-on-heading-p))
15979 (org-call-with-arg 'org-todo 'previousset))
15980 (org-support-shift-select
15981 (org-call-for-shift-select 'backward-word))
15982 (t (org-shiftselect-error))))
15984 (defun org-ctrl-c-ret ()
15985 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
15986 (interactive)
15987 (cond
15988 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
15989 (t (call-interactively 'org-insert-heading))))
15991 (defun org-copy-special ()
15992 "Copy region in table or copy current subtree.
15993 Calls `org-table-copy' or `org-copy-subtree', depending on context.
15994 See the individual commands for more information."
15995 (interactive)
15996 (call-interactively
15997 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
15999 (defun org-cut-special ()
16000 "Cut region in table or cut current subtree.
16001 Calls `org-table-copy' or `org-cut-subtree', depending on context.
16002 See the individual commands for more information."
16003 (interactive)
16004 (call-interactively
16005 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
16007 (defun org-paste-special (arg)
16008 "Paste rectangular region into table, or past subtree relative to level.
16009 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
16010 See the individual commands for more information."
16011 (interactive "P")
16012 (if (org-at-table-p)
16013 (org-table-paste-rectangle)
16014 (org-paste-subtree arg)))
16016 (defun org-edit-special ()
16017 "Call a special editor for the stuff at point.
16018 When at a table, call the formula editor with `org-table-edit-formulas'.
16019 When at the first line of an src example, call `org-edit-src-code'.
16020 When in an #+include line, visit the include file. Otherwise call
16021 `ffap' to visit the file at point."
16022 (interactive)
16023 (cond
16024 ((org-at-table.el-p)
16025 (org-edit-src-code))
16026 ((org-at-table-p)
16027 (call-interactively 'org-table-edit-formulas))
16028 ((save-excursion
16029 (beginning-of-line 1)
16030 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
16031 (find-file (org-trim (match-string 1))))
16032 ((org-edit-src-code))
16033 ((org-edit-fixed-width-region))
16034 (t (call-interactively 'ffap))))
16037 (defun org-ctrl-c-ctrl-c (&optional arg)
16038 "Set tags in headline, or update according to changed information at point.
16040 This command does many different things, depending on context:
16042 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
16043 this is what we do.
16045 - If the cursor is on a statistics cookie, update it.
16047 - If the cursor is in a headline, prompt for tags and insert them
16048 into the current line, aligned to `org-tags-column'. When called
16049 with prefix arg, realign all tags in the current buffer.
16051 - If the cursor is in one of the special #+KEYWORD lines, this
16052 triggers scanning the buffer for these lines and updating the
16053 information.
16055 - If the cursor is inside a table, realign the table. This command
16056 works even if the automatic table editor has been turned off.
16058 - If the cursor is on a #+TBLFM line, re-apply the formulas to
16059 the entire table.
16061 - If the cursor is at a footnote reference or definition, jump to
16062 the corresponding definition or references, respectively.
16064 - If the cursor is a the beginning of a dynamic block, update it.
16066 - If the current buffer is a remember buffer, close note and file
16067 it. A prefix argument of 1 files to the default location
16068 without further interaction. A prefix argument of 2 files to
16069 the currently clocking task.
16071 - If the cursor is on a <<<target>>>, update radio targets and corresponding
16072 links in this buffer.
16074 - If the cursor is on a numbered item in a plain list, renumber the
16075 ordered list.
16077 - If the cursor is on a checkbox, toggle it."
16078 (interactive "P")
16079 (let ((org-enable-table-editor t))
16080 (cond
16081 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
16082 org-occur-highlights
16083 org-latex-fragment-image-overlays)
16084 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
16085 (org-remove-occur-highlights)
16086 (org-remove-latex-fragment-image-overlays)
16087 (message "Temporary highlights/overlays removed from current buffer"))
16088 ((and (local-variable-p 'org-finish-function (current-buffer))
16089 (fboundp org-finish-function))
16090 (funcall org-finish-function))
16091 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
16092 ((or (looking-at (org-re org-property-start-re))
16093 (org-at-property-p))
16094 (call-interactively 'org-property-action))
16095 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
16096 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
16097 (or (org-on-heading-p) (org-at-item-p)))
16098 (call-interactively 'org-update-statistics-cookies))
16099 ((org-on-heading-p) (call-interactively 'org-set-tags))
16100 ((org-at-table.el-p)
16101 (message "Use C-c ' to edit table.el tables"))
16102 ((org-at-table-p)
16103 (org-table-maybe-eval-formula)
16104 (if arg
16105 (call-interactively 'org-table-recalculate)
16106 (org-table-maybe-recalculate-line))
16107 (call-interactively 'org-table-align))
16108 ((or (org-footnote-at-reference-p)
16109 (org-footnote-at-definition-p))
16110 (call-interactively 'org-footnote-action))
16111 ((org-at-item-checkbox-p)
16112 (call-interactively 'org-toggle-checkbox))
16113 ((org-at-item-p)
16114 (if arg
16115 (call-interactively 'org-toggle-checkbox)
16116 (call-interactively 'org-maybe-renumber-ordered-list)))
16117 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
16118 ;; Dynamic block
16119 (beginning-of-line 1)
16120 (save-excursion (org-update-dblock)))
16121 ((save-excursion
16122 (beginning-of-line 1)
16123 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
16124 (cond
16125 ((equal (match-string 1) "TBLFM")
16126 ;; Recalculate the table before this line
16127 (save-excursion
16128 (beginning-of-line 1)
16129 (skip-chars-backward " \r\n\t")
16130 (if (org-at-table-p)
16131 (org-call-with-arg 'org-table-recalculate (or arg t)))))
16133 (let ((org-inhibit-startup-visibility-stuff t)
16134 (org-startup-align-all-tables nil))
16135 (org-save-outline-visibility 'use-markers (org-mode-restart)))
16136 (message "Local setup has been refreshed"))))
16137 ((org-clock-update-time-maybe))
16138 (t (error "C-c C-c can do nothing useful at this location")))))
16140 (defun org-mode-restart ()
16141 "Restart Org-mode, to scan again for special lines.
16142 Also updates the keyword regular expressions."
16143 (interactive)
16144 (org-mode)
16145 (message "Org-mode restarted"))
16147 (defun org-kill-note-or-show-branches ()
16148 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
16149 (interactive)
16150 (if (not org-finish-function)
16151 (call-interactively 'show-branches)
16152 (let ((org-note-abort t))
16153 (funcall org-finish-function))))
16155 (defun org-return (&optional indent)
16156 "Goto next table row or insert a newline.
16157 Calls `org-table-next-row' or `newline', depending on context.
16158 See the individual commands for more information."
16159 (interactive)
16160 (cond
16161 ((bobp) (if indent (newline-and-indent) (newline)))
16162 ((org-at-table-p)
16163 (org-table-justify-field-maybe)
16164 (call-interactively 'org-table-next-row))
16165 ((and org-return-follows-link
16166 (eq (get-text-property (point) 'face) 'org-link))
16167 (call-interactively 'org-open-at-point))
16168 ((and (org-at-heading-p)
16169 (looking-at
16170 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
16171 (org-show-entry)
16172 (end-of-line 1)
16173 (newline))
16174 (t (if indent (newline-and-indent) (newline)))))
16176 (defun org-return-indent ()
16177 "Goto next table row or insert a newline and indent.
16178 Calls `org-table-next-row' or `newline-and-indent', depending on
16179 context. See the individual commands for more information."
16180 (interactive)
16181 (org-return t))
16183 (defun org-ctrl-c-star ()
16184 "Compute table, or change heading status of lines.
16185 Calls `org-table-recalculate' or `org-toggle-heading',
16186 depending on context."
16187 (interactive)
16188 (cond
16189 ((org-at-table-p)
16190 (call-interactively 'org-table-recalculate))
16192 ;; Convert all lines in region to list items
16193 (call-interactively 'org-toggle-heading))))
16195 (defun org-ctrl-c-minus ()
16196 "Insert separator line in table or modify bullet status of line.
16197 Also turns a plain line or a region of lines into list items.
16198 Calls `org-table-insert-hline', `org-toggle-item', or
16199 `org-cycle-list-bullet', depending on context."
16200 (interactive)
16201 (cond
16202 ((org-at-table-p)
16203 (call-interactively 'org-table-insert-hline))
16204 ((org-region-active-p)
16205 (call-interactively 'org-toggle-item))
16206 ((org-in-item-p)
16207 (call-interactively 'org-cycle-list-bullet))
16209 (call-interactively 'org-toggle-item))))
16211 (defun org-toggle-item ()
16212 "Convert headings or normal lines to items, items to normal lines.
16213 If there is no active region, only the current line is considered.
16215 If the first line in the region is a headline, convert all headlines to items.
16217 If the first line in the region is an item, convert all items to normal lines.
16219 If the first line is normal text, add an item bullet to each line."
16220 (interactive)
16221 (let (l2 l beg end)
16222 (if (org-region-active-p)
16223 (setq beg (region-beginning) end (region-end))
16224 (setq beg (point-at-bol)
16225 end (min (1+ (point-at-eol)) (point-max))))
16226 (save-excursion
16227 (goto-char end)
16228 (setq l2 (org-current-line))
16229 (goto-char beg)
16230 (beginning-of-line 1)
16231 (setq l (1- (org-current-line)))
16232 (if (org-at-item-p)
16233 ;; We already have items, de-itemize
16234 (while (< (setq l (1+ l)) l2)
16235 (when (org-at-item-p)
16236 (goto-char (match-beginning 2))
16237 (delete-region (match-beginning 2) (match-end 2))
16238 (and (looking-at "[ \t]+") (replace-match "")))
16239 (beginning-of-line 2))
16240 (if (org-on-heading-p)
16241 ;; Headings, convert to items
16242 (while (< (setq l (1+ l)) l2)
16243 (if (looking-at org-outline-regexp)
16244 (replace-match "- " t t))
16245 (beginning-of-line 2))
16246 ;; normal lines, turn them into items
16247 (while (< (setq l (1+ l)) l2)
16248 (unless (org-at-item-p)
16249 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
16250 (replace-match "\\1- \\2")))
16251 (beginning-of-line 2)))))))
16253 (defun org-toggle-heading (&optional nstars)
16254 "Convert headings to normal text, or items or text to headings.
16255 If there is no active region, only the current line is considered.
16257 If the first line is a heading, remove the stars from all headlines
16258 in the region.
16260 If the first line is a plain list item, turn all plain list items
16261 into headings.
16263 If the first line is a normal line, turn each and every line in the
16264 region into a heading.
16266 When converting a line into a heading, the number of stars is chosen
16267 such that the lines become children of the current entry. However,
16268 when a prefix argument is given, its value determines the number of
16269 stars to add."
16270 (interactive "P")
16271 (let (l2 l itemp beg end)
16272 (if (org-region-active-p)
16273 (setq beg (region-beginning) end (region-end))
16274 (setq beg (point-at-bol)
16275 end (min (1+ (point-at-eol)) (point-max))))
16276 (save-excursion
16277 (goto-char end)
16278 (setq l2 (org-current-line))
16279 (goto-char beg)
16280 (beginning-of-line 1)
16281 (setq l (1- (org-current-line)))
16282 (if (org-on-heading-p)
16283 ;; We already have headlines, de-star them
16284 (while (< (setq l (1+ l)) l2)
16285 (when (org-on-heading-p t)
16286 (and (looking-at outline-regexp) (replace-match "")))
16287 (beginning-of-line 2))
16288 (setq itemp (org-at-item-p))
16289 (let* ((stars
16290 (if nstars
16291 (make-string (prefix-numeric-value current-prefix-arg)
16293 (save-excursion
16294 (if (re-search-backward org-complex-heading-regexp nil t)
16295 (match-string 1) ""))))
16296 (add-stars (cond (nstars "")
16297 ((equal stars "") "*")
16298 (org-odd-levels-only "**")
16299 (t "*")))
16300 (rpl (concat stars add-stars " ")))
16301 (while (< (setq l (1+ l)) l2)
16302 (if itemp
16303 (and (org-at-item-p) (replace-match rpl t t))
16304 (unless (org-on-heading-p)
16305 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
16306 (replace-match (concat rpl (match-string 2))))))
16307 (beginning-of-line 2)))))))
16309 (defun org-meta-return (&optional arg)
16310 "Insert a new heading or wrap a region in a table.
16311 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
16312 See the individual commands for more information."
16313 (interactive "P")
16314 (cond
16315 ((run-hook-with-args-until-success 'org-metareturn-hook))
16316 ((org-at-table-p)
16317 (call-interactively 'org-table-wrap-region))
16318 (t (call-interactively 'org-insert-heading))))
16320 ;;; Menu entries
16322 ;; Define the Org-mode menus
16323 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
16324 '("Tbl"
16325 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
16326 ["Next Field" org-cycle (org-at-table-p)]
16327 ["Previous Field" org-shifttab (org-at-table-p)]
16328 ["Next Row" org-return (org-at-table-p)]
16329 "--"
16330 ["Blank Field" org-table-blank-field (org-at-table-p)]
16331 ["Edit Field" org-table-edit-field (org-at-table-p)]
16332 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
16333 "--"
16334 ("Column"
16335 ["Move Column Left" org-metaleft (org-at-table-p)]
16336 ["Move Column Right" org-metaright (org-at-table-p)]
16337 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
16338 ["Insert Column" org-shiftmetaright (org-at-table-p)])
16339 ("Row"
16340 ["Move Row Up" org-metaup (org-at-table-p)]
16341 ["Move Row Down" org-metadown (org-at-table-p)]
16342 ["Delete Row" org-shiftmetaup (org-at-table-p)]
16343 ["Insert Row" org-shiftmetadown (org-at-table-p)]
16344 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
16345 "--"
16346 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
16347 ("Rectangle"
16348 ["Copy Rectangle" org-copy-special (org-at-table-p)]
16349 ["Cut Rectangle" org-cut-special (org-at-table-p)]
16350 ["Paste Rectangle" org-paste-special (org-at-table-p)]
16351 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
16352 "--"
16353 ("Calculate"
16354 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
16355 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
16356 ["Edit Formulas" org-edit-special (org-at-table-p)]
16357 "--"
16358 ["Recalculate line" org-table-recalculate (org-at-table-p)]
16359 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
16360 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
16361 "--"
16362 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
16363 "--"
16364 ["Sum Column/Rectangle" org-table-sum
16365 (or (org-at-table-p) (org-region-active-p))]
16366 ["Which Column?" org-table-current-column (org-at-table-p)])
16367 ["Debug Formulas"
16368 org-table-toggle-formula-debugger
16369 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
16370 ["Show Col/Row Numbers"
16371 org-table-toggle-coordinate-overlays
16372 :style toggle
16373 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
16374 "--"
16375 ["Create" org-table-create (and (not (org-at-table-p))
16376 org-enable-table-editor)]
16377 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
16378 ["Import from File" org-table-import (not (org-at-table-p))]
16379 ["Export to File" org-table-export (org-at-table-p)]
16380 "--"
16381 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
16383 (easy-menu-define org-org-menu org-mode-map "Org menu"
16384 '("Org"
16385 ("Show/Hide"
16386 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
16387 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
16388 ["Sparse Tree..." org-sparse-tree t]
16389 ["Reveal Context" org-reveal t]
16390 ["Show All" show-all t]
16391 "--"
16392 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
16393 "--"
16394 ["New Heading" org-insert-heading t]
16395 ("Navigate Headings"
16396 ["Up" outline-up-heading t]
16397 ["Next" outline-next-visible-heading t]
16398 ["Previous" outline-previous-visible-heading t]
16399 ["Next Same Level" outline-forward-same-level t]
16400 ["Previous Same Level" outline-backward-same-level t]
16401 "--"
16402 ["Jump" org-goto t])
16403 ("Edit Structure"
16404 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
16405 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
16406 "--"
16407 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
16408 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
16409 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
16410 "--"
16411 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
16412 "--"
16413 ["Promote Heading" org-metaleft (not (org-at-table-p))]
16414 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
16415 ["Demote Heading" org-metaright (not (org-at-table-p))]
16416 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
16417 "--"
16418 ["Sort Region/Children" org-sort (not (org-at-table-p))]
16419 "--"
16420 ["Convert to odd levels" org-convert-to-odd-levels t]
16421 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
16422 ("Editing"
16423 ["Emphasis..." org-emphasize t]
16424 ["Edit Source Example" org-edit-special t]
16425 "--"
16426 ["Footnote new/jump" org-footnote-action t]
16427 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
16428 ("Archive"
16429 ["Archive (default method)" org-archive-subtree-default t]
16430 "--"
16431 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
16432 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
16433 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
16435 "--"
16436 ("Hyperlinks"
16437 ["Store Link (Global)" org-store-link t]
16438 ["Find existing link to here" org-occur-link-in-agenda-files t]
16439 ["Insert Link" org-insert-link t]
16440 ["Follow Link" org-open-at-point t]
16441 "--"
16442 ["Next link" org-next-link t]
16443 ["Previous link" org-previous-link t]
16444 "--"
16445 ["Descriptive Links"
16446 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
16447 :style radio
16448 :selected (member '(org-link) buffer-invisibility-spec)]
16449 ["Literal Links"
16450 (progn
16451 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
16452 :style radio
16453 :selected (not (member '(org-link) buffer-invisibility-spec))])
16454 "--"
16455 ("TODO Lists"
16456 ["TODO/DONE/-" org-todo t]
16457 ("Select keyword"
16458 ["Next keyword" org-shiftright (org-on-heading-p)]
16459 ["Previous keyword" org-shiftleft (org-on-heading-p)]
16460 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
16461 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
16462 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
16463 ["Show TODO Tree" org-show-todo-tree t]
16464 ["Global TODO list" org-todo-list t]
16465 "--"
16466 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
16467 :selected org-enforce-todo-dependencies :style toggle :active t]
16468 "Settings for tree at point"
16469 ["Do Children sequentially" org-toggle-ordered-property :style radio
16470 :selected (ignore-errors (org-entry-get nil "ORDERED"))
16471 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16472 ["Do Children parallel" org-toggle-ordered-property :style radio
16473 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
16474 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16475 "--"
16476 ["Set Priority" org-priority t]
16477 ["Priority Up" org-shiftup t]
16478 ["Priority Down" org-shiftdown t]
16479 "--"
16480 ["Get news from all feeds" org-feed-update-all t]
16481 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
16482 ["Customize feeds" (customize-variable 'org-feed-alist) t])
16483 ("TAGS and Properties"
16484 ["Set Tags" org-set-tags-command t]
16485 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
16486 "--"
16487 ["Set property" org-set-property t]
16488 ["Column view of properties" org-columns t]
16489 ["Insert Column View DBlock" org-insert-columns-dblock t])
16490 ("Dates and Scheduling"
16491 ["Timestamp" org-time-stamp t]
16492 ["Timestamp (inactive)" org-time-stamp-inactive t]
16493 ("Change Date"
16494 ["1 Day Later" org-shiftright t]
16495 ["1 Day Earlier" org-shiftleft t]
16496 ["1 ... Later" org-shiftup t]
16497 ["1 ... Earlier" org-shiftdown t])
16498 ["Compute Time Range" org-evaluate-time-range t]
16499 ["Schedule Item" org-schedule t]
16500 ["Deadline" org-deadline t]
16501 "--"
16502 ["Custom time format" org-toggle-time-stamp-overlays
16503 :style radio :selected org-display-custom-times]
16504 "--"
16505 ["Goto Calendar" org-goto-calendar t]
16506 ["Date from Calendar" org-date-from-calendar t]
16507 "--"
16508 ["Start/Restart Timer" org-timer-start t]
16509 ["Pause/Continue Timer" org-timer-pause-or-continue t]
16510 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
16511 ["Insert Timer String" org-timer t]
16512 ["Insert Timer Item" org-timer-item t])
16513 ("Logging work"
16514 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
16515 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
16516 ["Clock out" org-clock-out t]
16517 ["Clock cancel" org-clock-cancel t]
16518 "--"
16519 ["Mark as default task" org-clock-mark-default-task t]
16520 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
16521 ["Goto running clock" org-clock-goto t]
16522 "--"
16523 ["Display times" org-clock-display t]
16524 ["Create clock table" org-clock-report t]
16525 "--"
16526 ["Record DONE time"
16527 (progn (setq org-log-done (not org-log-done))
16528 (message "Switching to %s will %s record a timestamp"
16529 (car org-done-keywords)
16530 (if org-log-done "automatically" "not")))
16531 :style toggle :selected org-log-done])
16532 "--"
16533 ["Agenda Command..." org-agenda t]
16534 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
16535 ("File List for Agenda")
16536 ("Special views current file"
16537 ["TODO Tree" org-show-todo-tree t]
16538 ["Check Deadlines" org-check-deadlines t]
16539 ["Timeline" org-timeline t]
16540 ["Tags/Property tree" org-match-sparse-tree t])
16541 "--"
16542 ["Export/Publish..." org-export t]
16543 ("LaTeX"
16544 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
16545 :selected org-cdlatex-mode]
16546 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
16547 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
16548 ["Modify math symbol" org-cdlatex-math-modify
16549 (org-inside-LaTeX-fragment-p)]
16550 ["Insert citation" org-reftex-citation t]
16551 "--"
16552 ["Export LaTeX fragments as images"
16553 (if (featurep 'org-exp)
16554 (setq org-export-with-LaTeX-fragments
16555 (not org-export-with-LaTeX-fragments))
16556 (require 'org-exp))
16557 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
16558 org-export-with-LaTeX-fragments)]
16559 "--"
16560 ["Template for BEAMER" org-beamer-settings-template t])
16561 "--"
16562 ("MobileOrg"
16563 ["Push Files and Views" org-mobile-push t]
16564 ["Get Captured and Flagged" org-mobile-pull t]
16565 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
16566 "--"
16567 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
16568 "--"
16569 ("Documentation"
16570 ["Show Version" org-version t]
16571 ["Info Documentation" org-info t])
16572 ("Customize"
16573 ["Browse Org Group" org-customize t]
16574 "--"
16575 ["Expand This Menu" org-create-customize-menu
16576 (fboundp 'customize-menu-create)])
16577 ["Send bug report" org-submit-bug-report t]
16578 "--"
16579 ("Refresh/Reload"
16580 ["Refresh setup current buffer" org-mode-restart t]
16581 ["Reload Org (after update)" org-reload t]
16582 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
16585 (defun org-info (&optional node)
16586 "Read documentation for Org-mode in the info system.
16587 With optional NODE, go directly to that node."
16588 (interactive)
16589 (info (format "(org)%s" (or node ""))))
16591 ;;;###autoload
16592 (defun org-submit-bug-report ()
16593 "Submit a bug report on Org-mode via mail.
16595 Don't hesitate to report any problems or inaccurate documentation.
16597 If you don't have setup sending mail from (X)Emacs, please copy the
16598 output buffer into your mail program, as it gives us important
16599 information about your Org-mode version and configuration."
16600 (interactive)
16601 (require 'reporter)
16602 (org-load-modules-maybe)
16603 (org-require-autoloaded-modules)
16604 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
16605 (reporter-submit-bug-report
16606 "emacs-orgmode@gnu.org"
16607 (org-version)
16608 (let (list)
16609 (save-window-excursion
16610 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
16611 (delete-other-windows)
16612 (erase-buffer)
16613 (insert "You are about to submit a bug report to the Org-mode mailing list.
16615 We would like to add your full Org-mode and Outline configuration to the
16616 bug report. This greatly simplifies the work of the maintainer and
16617 other experts on the mailing list.
16619 HOWEVER, some variables you have customized may contain private
16620 information. The names of customers, colleagues, or friends, might
16621 appear in the form of file names, tags, todo states, or search strings.
16622 If you answer yes to the prompt, you might want to check and remove
16623 such private information before sending the email.")
16624 (add-text-properties (point-min) (point-max) '(face org-warning))
16625 (when (yes-or-no-p "Include your Org-mode configuration ")
16626 (mapatoms
16627 (lambda (v)
16628 (and (boundp v)
16629 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
16630 (or (and (symbol-value v)
16631 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
16632 (and
16633 (get v 'custom-type) (get v 'standard-value)
16634 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
16635 (push v list)))))
16636 (kill-buffer (get-buffer "*Warn about privacy*"))
16637 list))
16638 nil nil
16639 "Remember to cover the basics, that is, what you expected to happen and
16640 what in fact did happen. You don't know how to make a good report? See
16642 http://orgmode.org/manual/Feedback.html#Feedback
16644 Your bug report will be posted to the Org-mode mailing list.
16645 ------------------------------------------------------------------------")
16646 (save-excursion
16647 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
16648 (replace-match "\\1Bug: \\3 [\\2]")))))
16651 (defun org-install-agenda-files-menu ()
16652 (let ((bl (buffer-list)))
16653 (save-excursion
16654 (while bl
16655 (set-buffer (pop bl))
16656 (if (org-mode-p) (setq bl nil)))
16657 (when (org-mode-p)
16658 (easy-menu-change
16659 '("Org") "File List for Agenda"
16660 (append
16661 (list
16662 ["Edit File List" (org-edit-agenda-file-list) t]
16663 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
16664 ["Remove Current File from List" org-remove-file t]
16665 ["Cycle through agenda files" org-cycle-agenda-files t]
16666 ["Occur in all agenda files" org-occur-in-agenda-files t]
16667 "--")
16668 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
16670 ;;;; Documentation
16672 ;;;###autoload
16673 (defun org-require-autoloaded-modules ()
16674 (interactive)
16675 (mapc 'require
16676 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
16677 org-docbook org-exp org-html org-icalendar
16678 org-id org-latex
16679 org-publish org-remember org-table
16680 org-timer org-xoxo)))
16682 ;;;###autoload
16683 (defun org-reload (&optional uncompiled)
16684 "Reload all org lisp files.
16685 With prefix arg UNCOMPILED, load the uncompiled versions."
16686 (interactive "P")
16687 (require 'find-func)
16688 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
16689 (dir-org (file-name-directory (org-find-library-name "org")))
16690 (dir-org-contrib (ignore-errors
16691 (file-name-directory
16692 (org-find-library-name "org-contribdir"))))
16693 (files
16694 (append (directory-files dir-org t file-re)
16695 (and dir-org-contrib
16696 (directory-files dir-org-contrib t file-re))))
16697 (remove-re (concat (if (featurep 'xemacs)
16698 "org-colview" "org-colview-xemacs")
16699 "\\'")))
16700 (setq files (mapcar 'file-name-sans-extension files))
16701 (setq files (mapcar
16702 (lambda (x) (if (string-match remove-re x) nil x))
16703 files))
16704 (setq files (delq nil files))
16705 (mapc
16706 (lambda (f)
16707 (when (featurep (intern (file-name-nondirectory f)))
16708 (if (and (not uncompiled)
16709 (file-exists-p (concat f ".elc")))
16710 (load (concat f ".elc") nil nil t)
16711 (load (concat f ".el") nil nil t))))
16712 files))
16713 (org-version))
16715 ;;;###autoload
16716 (defun org-customize ()
16717 "Call the customize function with org as argument."
16718 (interactive)
16719 (org-load-modules-maybe)
16720 (org-require-autoloaded-modules)
16721 (customize-browse 'org))
16723 (defun org-create-customize-menu ()
16724 "Create a full customization menu for Org-mode, insert it into the menu."
16725 (interactive)
16726 (org-load-modules-maybe)
16727 (org-require-autoloaded-modules)
16728 (if (fboundp 'customize-menu-create)
16729 (progn
16730 (easy-menu-change
16731 '("Org") "Customize"
16732 `(["Browse Org group" org-customize t]
16733 "--"
16734 ,(customize-menu-create 'org)
16735 ["Set" Custom-set t]
16736 ["Save" Custom-save t]
16737 ["Reset to Current" Custom-reset-current t]
16738 ["Reset to Saved" Custom-reset-saved t]
16739 ["Reset to Standard Settings" Custom-reset-standard t]))
16740 (message "\"Org\"-menu now contains full customization menu"))
16741 (error "Cannot expand menu (outdated version of cus-edit.el)")))
16743 ;;;; Miscellaneous stuff
16745 ;;; Generally useful functions
16747 (defun org-get-at-bol (property)
16748 "Get text property PROPERTY at beginning of line."
16749 (get-text-property (point-at-bol) property))
16751 (defun org-find-text-property-in-string (prop s)
16752 "Return the first non-nil value of property PROP in string S."
16753 (or (get-text-property 0 prop s)
16754 (get-text-property (or (next-single-property-change 0 prop s) 0)
16755 prop s)))
16757 (defun org-display-warning (message) ;; Copied from Emacs-Muse
16758 "Display the given MESSAGE as a warning."
16759 (if (fboundp 'display-warning)
16760 (display-warning 'org message
16761 (if (featurep 'xemacs)
16762 'warning
16763 :warning))
16764 (let ((buf (get-buffer-create "*Org warnings*")))
16765 (with-current-buffer buf
16766 (goto-char (point-max))
16767 (insert "Warning (Org): " message)
16768 (unless (bolp)
16769 (newline)))
16770 (display-buffer buf)
16771 (sit-for 0))))
16773 (defun org-in-commented-line ()
16774 "Is point in a line starting with `#'?"
16775 (equal (char-after (point-at-bol)) ?#))
16777 (defun org-in-verbatim-emphasis ()
16778 (save-match-data
16779 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
16781 (defun org-goto-marker-or-bmk (marker &optional bookmark)
16782 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
16783 (if (and marker (marker-buffer marker)
16784 (buffer-live-p (marker-buffer marker)))
16785 (progn
16786 (switch-to-buffer (marker-buffer marker))
16787 (if (or (> marker (point-max)) (< marker (point-min)))
16788 (widen))
16789 (goto-char marker)
16790 (org-show-context 'org-goto))
16791 (if bookmark
16792 (bookmark-jump bookmark)
16793 (error "Cannot find location"))))
16795 (defun org-quote-csv-field (s)
16796 "Quote field for inclusion in CSV material."
16797 (if (string-match "[\",]" s)
16798 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
16801 (defun org-plist-delete (plist property)
16802 "Delete PROPERTY from PLIST.
16803 This is in contrast to merely setting it to 0."
16804 (let (p)
16805 (while plist
16806 (if (not (eq property (car plist)))
16807 (setq p (plist-put p (car plist) (nth 1 plist))))
16808 (setq plist (cddr plist)))
16811 (defun org-force-self-insert (N)
16812 "Needed to enforce self-insert under remapping."
16813 (interactive "p")
16814 (self-insert-command N))
16816 (defun org-string-width (s)
16817 "Compute width of string, ignoring invisible characters.
16818 This ignores character with invisibility property `org-link', and also
16819 characters with property `org-cwidth', because these will become invisible
16820 upon the next fontification round."
16821 (let (b l)
16822 (when (or (eq t buffer-invisibility-spec)
16823 (assq 'org-link buffer-invisibility-spec))
16824 (while (setq b (text-property-any 0 (length s)
16825 'invisible 'org-link s))
16826 (setq s (concat (substring s 0 b)
16827 (substring s (or (next-single-property-change
16828 b 'invisible s) (length s)))))))
16829 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
16830 (setq s (concat (substring s 0 b)
16831 (substring s (or (next-single-property-change
16832 b 'org-cwidth s) (length s))))))
16833 (setq l (string-width s) b -1)
16834 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
16835 (setq l (- l (get-text-property b 'org-dwidth-n s))))
16838 (defun org-get-indentation (&optional line)
16839 "Get the indentation of the current line, interpreting tabs.
16840 When LINE is given, assume it represents a line and compute its indentation."
16841 (if line
16842 (if (string-match "^ *" (org-remove-tabs line))
16843 (match-end 0))
16844 (save-excursion
16845 (beginning-of-line 1)
16846 (skip-chars-forward " \t")
16847 (current-column))))
16849 (defun org-remove-tabs (s &optional width)
16850 "Replace tabulators in S with spaces.
16851 Assumes that s is a single line, starting in column 0."
16852 (setq width (or width tab-width))
16853 (while (string-match "\t" s)
16854 (setq s (replace-match
16855 (make-string
16856 (- (* width (/ (+ (match-beginning 0) width) width))
16857 (match-beginning 0)) ?\ )
16858 t t s)))
16861 (defun org-fix-indentation (line ind)
16862 "Fix indentation in LINE.
16863 IND is a cons cell with target and minimum indentation.
16864 If the current indentation in LINE is smaller than the minimum,
16865 leave it alone. If it is larger than ind, set it to the target."
16866 (let* ((l (org-remove-tabs line))
16867 (i (org-get-indentation l))
16868 (i1 (car ind)) (i2 (cdr ind)))
16869 (if (>= i i2) (setq l (substring line i2)))
16870 (if (> i1 0)
16871 (concat (make-string i1 ?\ ) l)
16872 l)))
16874 (defun org-remove-indentation (code &optional n)
16875 "Remove the maximum common indentation from the lines in CODE.
16876 N may optionally be the number of spaces to remove."
16877 (with-temp-buffer
16878 (insert code)
16879 (org-do-remove-indentation n)
16880 (buffer-string)))
16882 (defun org-do-remove-indentation (&optional n)
16883 "Remove the maximum common indentation from the buffer."
16884 (untabify (point-min) (point-max))
16885 (let ((min 10000) re)
16886 (if n
16887 (setq min n)
16888 (goto-char (point-min))
16889 (while (re-search-forward "^ *[^ \n]" nil t)
16890 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
16891 (unless (or (= min 0) (= min 10000))
16892 (setq re (format "^ \\{%d\\}" min))
16893 (goto-char (point-min))
16894 (while (re-search-forward re nil t)
16895 (replace-match "")
16896 (end-of-line 1))
16897 min)))
16899 (defun org-fill-template (template alist)
16900 "Find each %key of ALIST in TEMPLATE and replace it."
16901 (let ((case-fold-search nil)
16902 entry key value)
16903 (setq alist (sort (copy-sequence alist)
16904 (lambda (a b) (< (length (car a)) (length (car b))))))
16905 (while (setq entry (pop alist))
16906 (setq template
16907 (replace-regexp-in-string
16908 (concat "%" (regexp-quote (car entry)))
16909 (cdr entry) template t t)))
16910 template))
16912 (defun org-base-buffer (buffer)
16913 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
16914 (if (not buffer)
16915 buffer
16916 (or (buffer-base-buffer buffer)
16917 buffer)))
16919 (defun org-trim (s)
16920 "Remove whitespace at beginning and end of string."
16921 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
16922 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
16925 (defun org-wrap (string &optional width lines)
16926 "Wrap string to either a number of lines, or a width in characters.
16927 If WIDTH is non-nil, the string is wrapped to that width, however many lines
16928 that costs. If there is a word longer than WIDTH, the text is actually
16929 wrapped to the length of that word.
16930 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
16931 many lines, whatever width that takes.
16932 The return value is a list of lines, without newlines at the end."
16933 (let* ((words (org-split-string string "[ \t\n]+"))
16934 (maxword (apply 'max (mapcar 'org-string-width words)))
16935 w ll)
16936 (cond (width
16937 (org-do-wrap words (max maxword width)))
16938 (lines
16939 (setq w maxword)
16940 (setq ll (org-do-wrap words maxword))
16941 (if (<= (length ll) lines)
16943 (setq ll words)
16944 (while (> (length ll) lines)
16945 (setq w (1+ w))
16946 (setq ll (org-do-wrap words w)))
16947 ll))
16948 (t (error "Cannot wrap this")))))
16950 (defun org-do-wrap (words width)
16951 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
16952 (let (lines line)
16953 (while words
16954 (setq line (pop words))
16955 (while (and words (< (+ (length line) (length (car words))) width))
16956 (setq line (concat line " " (pop words))))
16957 (setq lines (push line lines)))
16958 (nreverse lines)))
16960 (defun org-split-string (string &optional separators)
16961 "Splits STRING into substrings at SEPARATORS.
16962 No empty strings are returned if there are matches at the beginning
16963 and end of string."
16964 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
16965 (start 0)
16966 notfirst
16967 (list nil))
16968 (while (and (string-match rexp string
16969 (if (and notfirst
16970 (= start (match-beginning 0))
16971 (< start (length string)))
16972 (1+ start) start))
16973 (< (match-beginning 0) (length string)))
16974 (setq notfirst t)
16975 (or (eq (match-beginning 0) 0)
16976 (and (eq (match-beginning 0) (match-end 0))
16977 (eq (match-beginning 0) start))
16978 (setq list
16979 (cons (substring string start (match-beginning 0))
16980 list)))
16981 (setq start (match-end 0)))
16982 (or (eq start (length string))
16983 (setq list
16984 (cons (substring string start)
16985 list)))
16986 (nreverse list)))
16988 (defun org-quote-vert (s)
16989 "Replace \"|\" with \"\\vert\"."
16990 (while (string-match "|" s)
16991 (setq s (replace-match "\\vert" t t s)))
16994 (defun org-uuidgen-p (s)
16995 "Is S an ID created by UUIDGEN?"
16996 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
16998 (defun org-context ()
16999 "Return a list of contexts of the current cursor position.
17000 If several contexts apply, all are returned.
17001 Each context entry is a list with a symbol naming the context, and
17002 two positions indicating start and end of the context. Possible
17003 contexts are:
17005 :headline anywhere in a headline
17006 :headline-stars on the leading stars in a headline
17007 :todo-keyword on a TODO keyword (including DONE) in a headline
17008 :tags on the TAGS in a headline
17009 :priority on the priority cookie in a headline
17010 :item on the first line of a plain list item
17011 :item-bullet on the bullet/number of a plain list item
17012 :checkbox on the checkbox in a plain list item
17013 :table in an org-mode table
17014 :table-special on a special filed in a table
17015 :table-table in a table.el table
17016 :link on a hyperlink
17017 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
17018 :target on a <<target>>
17019 :radio-target on a <<<radio-target>>>
17020 :latex-fragment on a LaTeX fragment
17021 :latex-preview on a LaTeX fragment with overlayed preview image
17023 This function expects the position to be visible because it uses font-lock
17024 faces as a help to recognize the following contexts: :table-special, :link,
17025 and :keyword."
17026 (let* ((f (get-text-property (point) 'face))
17027 (faces (if (listp f) f (list f)))
17028 (p (point)) clist o)
17029 ;; First the large context
17030 (cond
17031 ((org-on-heading-p t)
17032 (push (list :headline (point-at-bol) (point-at-eol)) clist)
17033 (when (progn
17034 (beginning-of-line 1)
17035 (looking-at org-todo-line-tags-regexp))
17036 (push (org-point-in-group p 1 :headline-stars) clist)
17037 (push (org-point-in-group p 2 :todo-keyword) clist)
17038 (push (org-point-in-group p 4 :tags) clist))
17039 (goto-char p)
17040 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
17041 (if (looking-at "\\[#[A-Z0-9]\\]")
17042 (push (org-point-in-group p 0 :priority) clist)))
17044 ((org-at-item-p)
17045 (push (org-point-in-group p 2 :item-bullet) clist)
17046 (push (list :item (point-at-bol)
17047 (save-excursion (org-end-of-item) (point)))
17048 clist)
17049 (and (org-at-item-checkbox-p)
17050 (push (org-point-in-group p 0 :checkbox) clist)))
17052 ((org-at-table-p)
17053 (push (list :table (org-table-begin) (org-table-end)) clist)
17054 (if (memq 'org-formula faces)
17055 (push (list :table-special
17056 (previous-single-property-change p 'face)
17057 (next-single-property-change p 'face)) clist)))
17058 ((org-at-table-p 'any)
17059 (push (list :table-table) clist)))
17060 (goto-char p)
17062 ;; Now the small context
17063 (cond
17064 ((org-at-timestamp-p)
17065 (push (org-point-in-group p 0 :timestamp) clist))
17066 ((memq 'org-link faces)
17067 (push (list :link
17068 (previous-single-property-change p 'face)
17069 (next-single-property-change p 'face)) clist))
17070 ((memq 'org-special-keyword faces)
17071 (push (list :keyword
17072 (previous-single-property-change p 'face)
17073 (next-single-property-change p 'face)) clist))
17074 ((org-on-target-p)
17075 (push (org-point-in-group p 0 :target) clist)
17076 (goto-char (1- (match-beginning 0)))
17077 (if (looking-at org-radio-target-regexp)
17078 (push (org-point-in-group p 0 :radio-target) clist))
17079 (goto-char p))
17080 ((setq o (car (delq nil
17081 (mapcar
17082 (lambda (x)
17083 (if (memq x org-latex-fragment-image-overlays) x))
17084 (org-overlays-at (point))))))
17085 (push (list :latex-fragment
17086 (org-overlay-start o) (org-overlay-end o)) clist)
17087 (push (list :latex-preview
17088 (org-overlay-start o) (org-overlay-end o)) clist))
17089 ((org-inside-LaTeX-fragment-p)
17090 ;; FIXME: positions wrong.
17091 (push (list :latex-fragment (point) (point)) clist)))
17093 (setq clist (nreverse (delq nil clist)))
17094 clist))
17096 ;; FIXME: Compare with at-regexp-p Do we need both?
17097 (defun org-in-regexp (re &optional nlines visually)
17098 "Check if point is inside a match of regexp.
17099 Normally only the current line is checked, but you can include NLINES extra
17100 lines both before and after point into the search.
17101 If VISUALLY is set, require that the cursor is not after the match but
17102 really on, so that the block visually is on the match."
17103 (catch 'exit
17104 (let ((pos (point))
17105 (eol (point-at-eol (+ 1 (or nlines 0))))
17106 (inc (if visually 1 0)))
17107 (save-excursion
17108 (beginning-of-line (- 1 (or nlines 0)))
17109 (while (re-search-forward re eol t)
17110 (if (and (<= (match-beginning 0) pos)
17111 (>= (+ inc (match-end 0)) pos))
17112 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
17114 (defun org-at-regexp-p (regexp)
17115 "Is point inside a match of REGEXP in the current line?"
17116 (catch 'exit
17117 (save-excursion
17118 (let ((pos (point)) (end (point-at-eol)))
17119 (beginning-of-line 1)
17120 (while (re-search-forward regexp end t)
17121 (if (and (<= (match-beginning 0) pos)
17122 (>= (match-end 0) pos))
17123 (throw 'exit t)))
17124 nil))))
17126 (defun org-in-regexps-block-p (start-re end-re)
17127 "Returns t if the current point is between matches of START-RE and END-RE.
17128 This will also return to if point is on one of the two matches."
17129 (interactive)
17130 (let ((p (point)))
17131 (save-excursion
17132 (and (or (org-at-regexp-p start-re)
17133 (re-search-backward start-re nil t))
17134 (re-search-forward end-re nil t)
17135 (>= (point) p)))))
17137 (defun org-occur-in-agenda-files (regexp &optional nlines)
17138 "Call `multi-occur' with buffers for all agenda files."
17139 (interactive "sOrg-files matching: \np")
17140 (let* ((files (org-agenda-files))
17141 (tnames (mapcar 'file-truename files))
17142 (extra org-agenda-text-search-extra-files)
17144 (when (eq (car extra) 'agenda-archives)
17145 (setq extra (cdr extra))
17146 (setq files (org-add-archive-files files)))
17147 (while (setq f (pop extra))
17148 (unless (member (file-truename f) tnames)
17149 (add-to-list 'files f 'append)
17150 (add-to-list 'tnames (file-truename f) 'append)))
17151 (multi-occur
17152 (mapcar (lambda (x)
17153 (with-current-buffer
17154 (or (get-file-buffer x) (find-file-noselect x))
17155 (widen)
17156 (current-buffer)))
17157 files)
17158 regexp)))
17160 (if (boundp 'occur-mode-find-occurrence-hook)
17161 ;; Emacs 23
17162 (add-hook 'occur-mode-find-occurrence-hook
17163 (lambda ()
17164 (when (org-mode-p)
17165 (org-reveal))))
17166 ;; Emacs 22
17167 (defadvice occur-mode-goto-occurrence
17168 (after org-occur-reveal activate)
17169 (and (org-mode-p) (org-reveal)))
17170 (defadvice occur-mode-goto-occurrence-other-window
17171 (after org-occur-reveal activate)
17172 (and (org-mode-p) (org-reveal)))
17173 (defadvice occur-mode-display-occurrence
17174 (after org-occur-reveal activate)
17175 (when (org-mode-p)
17176 (let ((pos (occur-mode-find-occurrence)))
17177 (with-current-buffer (marker-buffer pos)
17178 (save-excursion
17179 (goto-char pos)
17180 (org-reveal)))))))
17182 (defun org-occur-link-in-agenda-files ()
17183 "Create a link and search for it in the agendas.
17184 The link is not stored in `org-stored-links', it is just created
17185 for the search purpose."
17186 (interactive)
17187 (let ((link (condition-case nil
17188 (org-store-link nil)
17189 (error "Unable to create a link to here"))))
17190 (org-occur-in-agenda-files (regexp-quote link))))
17192 (defun org-uniquify (list)
17193 "Remove duplicate elements from LIST."
17194 (let (res)
17195 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
17196 res))
17198 (defun org-delete-all (elts list)
17199 "Remove all elements in ELTS from LIST."
17200 (while elts
17201 (setq list (delete (pop elts) list)))
17202 list)
17204 (defun org-back-over-empty-lines ()
17205 "Move backwards over whitespace, to the beginning of the first empty line.
17206 Returns the number of empty lines passed."
17207 (let ((pos (point)))
17208 (skip-chars-backward " \t\n\r")
17209 (beginning-of-line 2)
17210 (goto-char (min (point) pos))
17211 (count-lines (point) pos)))
17213 (defun org-skip-whitespace ()
17214 (skip-chars-forward " \t\n\r"))
17216 (defun org-point-in-group (point group &optional context)
17217 "Check if POINT is in match-group GROUP.
17218 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
17219 match. If the match group does ot exist or point is not inside it,
17220 return nil."
17221 (and (match-beginning group)
17222 (>= point (match-beginning group))
17223 (<= point (match-end group))
17224 (if context
17225 (list context (match-beginning group) (match-end group))
17226 t)))
17228 (defun org-switch-to-buffer-other-window (&rest args)
17229 "Switch to buffer in a second window on the current frame.
17230 In particular, do not allow pop-up frames."
17231 (let (pop-up-frames special-display-buffer-names special-display-regexps
17232 special-display-function)
17233 (apply 'switch-to-buffer-other-window args)))
17235 (defun org-combine-plists (&rest plists)
17236 "Create a single property list from all plists in PLISTS.
17237 The process starts by copying the first list, and then setting properties
17238 from the other lists. Settings in the last list are the most significant
17239 ones and overrule settings in the other lists."
17240 (let ((rtn (copy-sequence (pop plists)))
17241 p v ls)
17242 (while plists
17243 (setq ls (pop plists))
17244 (while ls
17245 (setq p (pop ls) v (pop ls))
17246 (setq rtn (plist-put rtn p v))))
17247 rtn))
17249 (defun org-move-line-down (arg)
17250 "Move the current line down. With prefix argument, move it past ARG lines."
17251 (interactive "p")
17252 (let ((col (current-column))
17253 beg end pos)
17254 (beginning-of-line 1) (setq beg (point))
17255 (beginning-of-line 2) (setq end (point))
17256 (beginning-of-line (+ 1 arg))
17257 (setq pos (move-marker (make-marker) (point)))
17258 (insert (delete-and-extract-region beg end))
17259 (goto-char pos)
17260 (org-move-to-column col)))
17262 (defun org-move-line-up (arg)
17263 "Move the current line up. With prefix argument, move it past ARG lines."
17264 (interactive "p")
17265 (let ((col (current-column))
17266 beg end pos)
17267 (beginning-of-line 1) (setq beg (point))
17268 (beginning-of-line 2) (setq end (point))
17269 (beginning-of-line (- arg))
17270 (setq pos (move-marker (make-marker) (point)))
17271 (insert (delete-and-extract-region beg end))
17272 (goto-char pos)
17273 (org-move-to-column col)))
17275 (defun org-replace-escapes (string table)
17276 "Replace %-escapes in STRING with values in TABLE.
17277 TABLE is an association list with keys like \"%a\" and string values.
17278 The sequences in STRING may contain normal field width and padding information,
17279 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
17280 so values can contain further %-escapes if they are define later in TABLE."
17281 (let ((case-fold-search nil)
17282 e re rpl)
17283 (while (setq e (pop table))
17284 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
17285 (while (string-match re string)
17286 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
17287 (cdr e)))
17288 (setq string (replace-match rpl t t string))))
17289 string))
17292 (defun org-sublist (list start end)
17293 "Return a section of LIST, from START to END.
17294 Counting starts at 1."
17295 (let (rtn (c start))
17296 (setq list (nthcdr (1- start) list))
17297 (while (and list (<= c end))
17298 (push (pop list) rtn)
17299 (setq c (1+ c)))
17300 (nreverse rtn)))
17302 (defun org-find-base-buffer-visiting (file)
17303 "Like `find-buffer-visiting' but always return the base buffer and
17304 not an indirect buffer."
17305 (let ((buf (or (get-file-buffer file)
17306 (find-buffer-visiting file))))
17307 (if buf
17308 (or (buffer-base-buffer buf) buf)
17309 nil)))
17311 (defun org-image-file-name-regexp (&optional extensions)
17312 "Return regexp matching the file names of images.
17313 If EXTENSIONS is given, only match these."
17314 (if (and (not extensions) (fboundp 'image-file-name-regexp))
17315 (image-file-name-regexp)
17316 (let ((image-file-name-extensions
17317 (or extensions
17318 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
17319 "xbm" "xpm" "pbm" "pgm" "ppm"))))
17320 (concat "\\."
17321 (regexp-opt (nconc (mapcar 'upcase
17322 image-file-name-extensions)
17323 image-file-name-extensions)
17325 "\\'"))))
17327 (defun org-file-image-p (file &optional extensions)
17328 "Return non-nil if FILE is an image."
17329 (save-match-data
17330 (string-match (org-image-file-name-regexp extensions) file)))
17332 (defun org-get-cursor-date ()
17333 "Return the date at cursor in as a time.
17334 This works in the calendar and in the agenda, anywhere else it just
17335 returns the current time."
17336 (let (date day defd)
17337 (cond
17338 ((eq major-mode 'calendar-mode)
17339 (setq date (calendar-cursor-to-date)
17340 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17341 ((eq major-mode 'org-agenda-mode)
17342 (setq day (get-text-property (point) 'day))
17343 (if day
17344 (setq date (calendar-gregorian-from-absolute day)
17345 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
17346 (nth 2 date))))))
17347 (or defd (current-time))))
17349 (defvar org-agenda-action-marker (make-marker)
17350 "Marker pointing to the entry for the next agenda action.")
17352 (defun org-mark-entry-for-agenda-action ()
17353 "Mark the current entry as target of an agenda action.
17354 Agenda actions are actions executed from the agenda with the key `k',
17355 which make use of the date at the cursor."
17356 (interactive)
17357 (move-marker org-agenda-action-marker
17358 (save-excursion (org-back-to-heading t) (point))
17359 (current-buffer))
17360 (message
17361 "Entry marked for action; press `k' at desired date in agenda or calendar"))
17363 ;;; Paragraph filling stuff.
17364 ;; We want this to be just right, so use the full arsenal.
17366 (defun org-indent-line-function ()
17367 "Indent line like previous, but further if previous was headline or item."
17368 (interactive)
17369 (let* ((pos (point))
17370 (itemp (org-at-item-p))
17371 (case-fold-search t)
17372 (org-drawer-regexp (or org-drawer-regexp "\000"))
17373 column bpos bcol tpos tcol bullet btype bullet-type)
17374 ;; Find the previous relevant line
17375 (beginning-of-line 1)
17376 (cond
17377 ((looking-at "#") (setq column 0))
17378 ((looking-at "\\*+ ") (setq column 0))
17379 ((and (looking-at "[ \t]*:END:")
17380 (save-excursion (re-search-backward org-drawer-regexp nil t)))
17381 (save-excursion
17382 (goto-char (1- (match-beginning 1)))
17383 (setq column (current-column))))
17384 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
17385 (save-excursion
17386 (re-search-backward
17387 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
17388 (setq column (org-get-indentation (match-string 0))))
17390 (beginning-of-line 0)
17391 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
17392 (not (looking-at "[ \t]*:END:"))
17393 (not (looking-at org-drawer-regexp)))
17394 (beginning-of-line 0))
17395 (cond
17396 ((looking-at "\\*+[ \t]+")
17397 (if (not org-adapt-indentation)
17398 (setq column 0)
17399 (goto-char (match-end 0))
17400 (setq column (current-column))))
17401 ((looking-at org-drawer-regexp)
17402 (goto-char (1- (match-beginning 1)))
17403 (setq column (current-column)))
17404 ((looking-at "\\([ \t]*\\):END:")
17405 (goto-char (match-end 1))
17406 (setq column (current-column)))
17407 ((org-in-item-p)
17408 (org-beginning-of-item)
17409 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
17410 (setq bpos (match-beginning 1) tpos (match-end 0)
17411 bcol (progn (goto-char bpos) (current-column))
17412 tcol (progn (goto-char tpos) (current-column))
17413 bullet (match-string 1)
17414 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
17415 (if (> tcol (+ bcol org-description-max-indent))
17416 (setq tcol (+ bcol 5)))
17417 (if (not itemp)
17418 (setq column tcol)
17419 (goto-char pos)
17420 (beginning-of-line 1)
17421 (if (looking-at "\\S-")
17422 (progn
17423 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
17424 (setq bullet (match-string 1)
17425 btype (if (string-match "[0-9]" bullet) "n" bullet))
17426 (setq column (if (equal btype bullet-type) bcol tcol)))
17427 (setq column (org-get-indentation)))))
17428 (t (setq column (org-get-indentation))))))
17429 (goto-char pos)
17430 (if (<= (current-column) (current-indentation))
17431 (org-indent-line-to column)
17432 (save-excursion (org-indent-line-to column)))
17433 (setq column (current-column))
17434 (beginning-of-line 1)
17435 (if (looking-at
17436 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
17437 (replace-match (concat (match-string 1)
17438 (format org-property-format
17439 (match-string 2) (match-string 3)))
17440 t t))
17441 (org-move-to-column column)))
17443 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
17444 "Variable to store copy of `adaptive-fill-regexp'.
17445 Since `adaptive-fill-regexp' is set to never match, we need to
17446 store a backup of its value before entering `org-mode' so that
17447 the functionality can be provided as a fall-back.")
17449 (defun org-set-autofill-regexps ()
17450 (interactive)
17451 ;; In the paragraph separator we include headlines, because filling
17452 ;; text in a line directly attached to a headline would otherwise
17453 ;; fill the headline as well.
17454 (org-set-local 'comment-start-skip "^#+[ \t]*")
17455 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
17456 ;; The paragraph starter includes hand-formatted lists.
17457 (org-set-local
17458 'paragraph-start
17459 (concat
17460 "\f" "\\|"
17461 "[ ]*$" "\\|"
17462 "\\*+ " "\\|"
17463 "[ \t]*#" "\\|"
17464 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
17465 "[ \t]*[:|]" "\\|"
17466 "\\$\\$" "\\|"
17467 "\\\\\\(begin\\|end\\|[][]\\)"))
17468 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
17469 ;; But only if the user has not turned off tables or fixed-width regions
17470 (org-set-local
17471 'auto-fill-inhibit-regexp
17472 (concat "\\*+ \\|#\\+"
17473 "\\|[ \t]*" org-keyword-time-regexp
17474 (if (or org-enable-table-editor org-enable-fixed-width-editor)
17475 (concat
17476 "\\|[ \t]*["
17477 (if org-enable-table-editor "|" "")
17478 (if org-enable-fixed-width-editor ":" "")
17479 "]"))))
17480 ;; We use our own fill-paragraph function, to make sure that tables
17481 ;; and fixed-width regions are not wrapped. That function will pass
17482 ;; through to `fill-paragraph' when appropriate.
17483 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
17484 ;; Adaptive filling: To get full control, first make sure that
17485 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
17486 (unless (local-variable-p 'adaptive-fill-regexp)
17487 (org-set-local 'org-adaptive-fill-regexp-backup
17488 adaptive-fill-regexp))
17489 (org-set-local 'adaptive-fill-regexp "\000")
17490 (org-set-local 'adaptive-fill-function
17491 'org-adaptive-fill-function)
17492 (org-set-local
17493 'align-mode-rules-list
17494 '((org-in-buffer-settings
17495 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
17496 (modes . '(org-mode))))))
17498 (defun org-fill-paragraph (&optional justify)
17499 "Re-align a table, pass through to fill-paragraph if no table."
17500 (let ((table-p (org-at-table-p))
17501 (table.el-p (org-at-table.el-p)))
17502 (cond ((and (equal (char-after (point-at-bol)) ?*)
17503 (save-excursion (goto-char (point-at-bol))
17504 (looking-at outline-regexp)))
17505 t) ; skip headlines
17506 (table.el-p t) ; skip table.el tables
17507 (table-p (org-table-align) t) ; align org-mode tables
17508 (t nil)))) ; call paragraph-fill
17510 ;; For reference, this is the default value of adaptive-fill-regexp
17511 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
17513 (defun org-adaptive-fill-function ()
17514 "Return a fill prefix for org-mode files.
17515 In particular, this makes sure hanging paragraphs for hand-formatted lists
17516 work correctly."
17517 (cond
17518 ;; Comment line
17519 ((looking-at "#[ \t]+")
17520 (match-string-no-properties 0))
17521 ;; Description list
17522 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
17523 (save-excursion
17524 (if (> (match-end 1) (+ (match-beginning 1)
17525 org-description-max-indent))
17526 (goto-char (+ (match-beginning 1) 5))
17527 (goto-char (match-end 0)))
17528 (make-string (current-column) ?\ )))
17529 ;; Ordered or unordered list
17530 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)")
17531 (save-excursion
17532 (goto-char (match-end 0))
17533 (make-string (current-column) ?\ )))
17534 ;; Other text
17535 ((looking-at org-adaptive-fill-regexp-backup)
17536 (match-string-no-properties 0))))
17538 ;;; Other stuff.
17540 (defun org-toggle-fixed-width-section (arg)
17541 "Toggle the fixed-width export.
17542 If there is no active region, the QUOTE keyword at the current headline is
17543 inserted or removed. When present, it causes the text between this headline
17544 and the next to be exported as fixed-width text, and unmodified.
17545 If there is an active region, this command adds or removes a colon as the
17546 first character of this line. If the first character of a line is a colon,
17547 this line is also exported in fixed-width font."
17548 (interactive "P")
17549 (let* ((cc 0)
17550 (regionp (org-region-active-p))
17551 (beg (if regionp (region-beginning) (point)))
17552 (end (if regionp (region-end)))
17553 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
17554 (case-fold-search nil)
17555 (re "[ \t]*\\(: \\)")
17556 off)
17557 (if regionp
17558 (save-excursion
17559 (goto-char beg)
17560 (setq cc (current-column))
17561 (beginning-of-line 1)
17562 (setq off (looking-at re))
17563 (while (> nlines 0)
17564 (setq nlines (1- nlines))
17565 (beginning-of-line 1)
17566 (cond
17567 (arg
17568 (org-move-to-column cc t)
17569 (insert ": \n")
17570 (forward-line -1))
17571 ((and off (looking-at re))
17572 (replace-match "" t t nil 1))
17573 ((not off) (org-move-to-column cc t) (insert ": ")))
17574 (forward-line 1)))
17575 (save-excursion
17576 (org-back-to-heading)
17577 (if (looking-at (concat outline-regexp
17578 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
17579 (replace-match "" t t nil 1)
17580 (if (looking-at outline-regexp)
17581 (progn
17582 (goto-char (match-end 0))
17583 (insert org-quote-string " "))))))))
17585 (defun org-reftex-citation ()
17586 "Use reftex-citation to insert a citation into the buffer.
17587 This looks for a line like
17589 #+BIBLIOGRAPHY: foo plain option:-d
17591 and derives from it that foo.bib is the bibliography file relevant
17592 for this document. It then installs the necessary environment for RefTeX
17593 to work in this buffer and calls `reftex-citation' to insert a citation
17594 into the buffer.
17596 Export of such citations to both LaTeX and HTML is handled by the contributed
17597 package org-exp-bibtex by Taru Karttunen."
17598 (interactive)
17599 (let ((reftex-docstruct-symbol 'rds)
17600 (reftex-cite-format "\\cite{%l}")
17601 rds bib)
17602 (save-excursion
17603 (save-restriction
17604 (widen)
17605 (let ((case-fold-search t)
17606 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
17607 (if (not (save-excursion
17608 (or (re-search-forward re nil t)
17609 (re-search-backward re nil t))))
17610 (error "No bibliography defined in file")
17611 (setq bib (concat (match-string 1) ".bib")
17612 rds (list (list 'bib bib)))))))
17613 (call-interactively 'reftex-citation)))
17615 ;;;; Functions extending outline functionality
17617 (defun org-beginning-of-line (&optional arg)
17618 "Go to the beginning of the current line. If that is invisible, continue
17619 to a visible line beginning. This makes the function of C-a more intuitive.
17620 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17621 first attempt, and only move to after the tags when the cursor is already
17622 beyond the end of the headline."
17623 (interactive "P")
17624 (let ((pos (point))
17625 (special (if (consp org-special-ctrl-a/e)
17626 (car org-special-ctrl-a/e)
17627 org-special-ctrl-a/e))
17628 refpos)
17629 (if (org-bound-and-true-p line-move-visual)
17630 (beginning-of-visual-line 1)
17631 (beginning-of-line 1))
17632 (if (and arg (fboundp 'move-beginning-of-line))
17633 (call-interactively 'move-beginning-of-line)
17634 (if (bobp)
17636 (backward-char 1)
17637 (if (org-invisible-p)
17638 (while (and (not (bobp)) (org-invisible-p))
17639 (backward-char 1)
17640 (beginning-of-line 1))
17641 (forward-char 1))))
17642 (when special
17643 (cond
17644 ((and (looking-at org-complex-heading-regexp)
17645 (= (char-after (match-end 1)) ?\ ))
17646 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
17647 (point-at-eol)))
17648 (goto-char
17649 (if (eq special t)
17650 (cond ((> pos refpos) refpos)
17651 ((= pos (point)) refpos)
17652 (t (point)))
17653 (cond ((> pos (point)) (point))
17654 ((not (eq last-command this-command)) (point))
17655 (t refpos)))))
17656 ((org-at-item-p)
17657 (goto-char
17658 (if (eq special t)
17659 (cond ((> pos (match-end 4)) (match-end 4))
17660 ((= pos (point)) (match-end 4))
17661 (t (point)))
17662 (cond ((> pos (point)) (point))
17663 ((not (eq last-command this-command)) (point))
17664 (t (match-end 4))))))))
17665 (org-no-warnings
17666 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17668 (defun org-end-of-line (&optional arg)
17669 "Go to the end of the line.
17670 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17671 first attempt, and only move to after the tags when the cursor is already
17672 beyond the end of the headline."
17673 (interactive "P")
17674 (let ((special (if (consp org-special-ctrl-a/e)
17675 (cdr org-special-ctrl-a/e)
17676 org-special-ctrl-a/e)))
17677 (if (or (not special)
17678 (not (org-on-heading-p))
17679 arg)
17680 (call-interactively
17681 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
17682 ((fboundp 'move-end-of-line) 'move-end-of-line)
17683 (t 'end-of-line)))
17684 (let ((pos (point)))
17685 (beginning-of-line 1)
17686 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
17687 (if (eq special t)
17688 (if (or (< pos (match-beginning 1))
17689 (= pos (match-end 0)))
17690 (goto-char (match-beginning 1))
17691 (goto-char (match-end 0)))
17692 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
17693 (goto-char (match-end 0))
17694 (goto-char (match-beginning 1))))
17695 (call-interactively (if (fboundp 'move-end-of-line)
17696 'move-end-of-line
17697 'end-of-line)))))
17698 (org-no-warnings
17699 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17701 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
17702 (define-key org-mode-map "\C-e" 'org-end-of-line)
17703 (define-key org-mode-map [home] 'org-beginning-of-line)
17704 (define-key org-mode-map [end] 'org-end-of-line)
17706 (defun org-backward-sentence (&optional arg)
17707 "Go to beginning of sentence, or beginning of table field.
17708 This will call `backward-sentence' or `org-table-beginning-of-field',
17709 depending on context."
17710 (interactive "P")
17711 (cond
17712 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
17713 (t (call-interactively 'backward-sentence))))
17715 (defun org-forward-sentence (&optional arg)
17716 "Go to end of sentence, or end of table field.
17717 This will call `forward-sentence' or `org-table-end-of-field',
17718 depending on context."
17719 (interactive "P")
17720 (cond
17721 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
17722 (t (call-interactively 'forward-sentence))))
17724 (define-key org-mode-map "\M-a" 'org-backward-sentence)
17725 (define-key org-mode-map "\M-e" 'org-forward-sentence)
17727 (defun org-kill-line (&optional arg)
17728 "Kill line, to tags or end of line."
17729 (interactive "P")
17730 (cond
17731 ((or (not org-special-ctrl-k)
17732 (bolp)
17733 (not (org-on-heading-p)))
17734 (call-interactively 'kill-line))
17735 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
17736 (kill-region (point) (match-beginning 1))
17737 (org-set-tags nil t))
17738 (t (kill-region (point) (point-at-eol)))))
17740 (define-key org-mode-map "\C-k" 'org-kill-line)
17742 (defun org-yank (&optional arg)
17743 "Yank. If the kill is a subtree, treat it specially.
17744 This command will look at the current kill and check if is a single
17745 subtree, or a series of subtrees[1]. If it passes the test, and if the
17746 cursor is at the beginning of a line or after the stars of a currently
17747 empty headline, then the yank is handled specially. How exactly depends
17748 on the value of the following variables, both set by default.
17750 org-yank-folded-subtrees
17751 When set, the subtree(s) will be folded after insertion, but only
17752 if doing so would now swallow text after the yanked text.
17754 org-yank-adjusted-subtrees
17755 When set, the subtree will be promoted or demoted in order to
17756 fit into the local outline tree structure, which means that the level
17757 will be adjusted so that it becomes the smaller one of the two
17758 *visible* surrounding headings.
17760 Any prefix to this command will cause `yank' to be called directly with
17761 no special treatment. In particular, a simple `C-u' prefix will just
17762 plainly yank the text as it is.
17764 \[1] The test checks if the first non-white line is a heading
17765 and if there are no other headings with fewer stars."
17766 (interactive "P")
17767 (org-yank-generic 'yank arg))
17769 (defun org-yank-generic (command arg)
17770 "Perform some yank-like command.
17772 This function implements the behavior described in the `org-yank'
17773 documentation. However, it has been generalized to work for any
17774 interactive command with similar behavior."
17776 ;; pretend to be command COMMAND
17777 (setq this-command command)
17779 (if arg
17780 (call-interactively command)
17782 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
17783 (and (org-kill-is-subtree-p)
17784 (or (bolp)
17785 (and (looking-at "[ \t]*$")
17786 (string-match
17787 "\\`\\*+\\'"
17788 (buffer-substring (point-at-bol) (point)))))))
17789 swallowp)
17790 (cond
17791 ((and subtreep org-yank-folded-subtrees)
17792 (let ((beg (point))
17793 end)
17794 (if (and subtreep org-yank-adjusted-subtrees)
17795 (org-paste-subtree nil nil 'for-yank)
17796 (call-interactively command))
17798 (setq end (point))
17799 (goto-char beg)
17800 (when (and (bolp) subtreep
17801 (not (setq swallowp
17802 (org-yank-folding-would-swallow-text beg end))))
17803 (or (looking-at outline-regexp)
17804 (re-search-forward (concat "^" outline-regexp) end t))
17805 (while (and (< (point) end) (looking-at outline-regexp))
17806 (hide-subtree)
17807 (org-cycle-show-empty-lines 'folded)
17808 (condition-case nil
17809 (outline-forward-same-level 1)
17810 (error (goto-char end)))))
17811 (when swallowp
17812 (message
17813 "Inserted text not folded because that would swallow text"))
17815 (goto-char end)
17816 (skip-chars-forward " \t\n\r")
17817 (beginning-of-line 1)
17818 (push-mark beg 'nomsg)))
17819 ((and subtreep org-yank-adjusted-subtrees)
17820 (let ((beg (point-at-bol)))
17821 (org-paste-subtree nil nil 'for-yank)
17822 (push-mark beg 'nomsg)))
17824 (call-interactively command))))))
17826 (defun org-yank-folding-would-swallow-text (beg end)
17827 "Would hide-subtree at BEG swallow any text after END?"
17828 (let (level)
17829 (save-excursion
17830 (goto-char beg)
17831 (when (or (looking-at outline-regexp)
17832 (re-search-forward (concat "^" outline-regexp) end t))
17833 (setq level (org-outline-level)))
17834 (goto-char end)
17835 (skip-chars-forward " \t\r\n\v\f")
17836 (if (or (eobp)
17837 (and (bolp) (looking-at org-outline-regexp)
17838 (<= (org-outline-level) level)))
17839 nil ; Nothing would be swallowed
17840 t)))) ; something would swallow
17842 (define-key org-mode-map "\C-y" 'org-yank)
17844 (defun org-invisible-p ()
17845 "Check if point is at a character currently not visible."
17846 ;; Early versions of noutline don't have `outline-invisible-p'.
17847 (if (fboundp 'outline-invisible-p)
17848 (outline-invisible-p)
17849 (get-char-property (point) 'invisible)))
17851 (defun org-invisible-p2 ()
17852 "Check if point is at a character currently not visible."
17853 (save-excursion
17854 (if (and (eolp) (not (bobp))) (backward-char 1))
17855 ;; Early versions of noutline don't have `outline-invisible-p'.
17856 (if (fboundp 'outline-invisible-p)
17857 (outline-invisible-p)
17858 (get-char-property (point) 'invisible))))
17860 (defun org-back-to-heading (&optional invisible-ok)
17861 "Call `outline-back-to-heading', but provide a better error message."
17862 (condition-case nil
17863 (outline-back-to-heading invisible-ok)
17864 (error (error "Before first headline at position %d in buffer %s"
17865 (point) (current-buffer)))))
17867 (defun org-before-first-heading-p ()
17868 "Before first heading?"
17869 (save-excursion
17870 (null (re-search-backward "^\\*+ " nil t))))
17872 (defun org-on-heading-p (&optional ignored)
17873 (outline-on-heading-p t))
17874 (defun org-at-heading-p (&optional ignored)
17875 (outline-on-heading-p t))
17877 (defun org-point-at-end-of-empty-headline ()
17878 "If point is at the end of an empty headline, return t, else nil.
17879 If the heading only contains a TODO keyword, it is still still considered
17880 empty."
17881 (and (looking-at "[ \t]*$")
17882 (save-excursion
17883 (beginning-of-line 1)
17884 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp
17885 "\\)?[ \t]*$")))))
17886 (defun org-at-heading-or-item-p ()
17887 (or (org-on-heading-p) (org-at-item-p)))
17889 (defun org-on-target-p ()
17890 (or (org-in-regexp org-radio-target-regexp)
17891 (org-in-regexp org-target-regexp)))
17893 (defun org-up-heading-all (arg)
17894 "Move to the heading line of which the present line is a subheading.
17895 This function considers both visible and invisible heading lines.
17896 With argument, move up ARG levels."
17897 (if (fboundp 'outline-up-heading-all)
17898 (outline-up-heading-all arg) ; emacs 21 version of outline.el
17899 (outline-up-heading arg t))) ; emacs 22 version of outline.el
17901 (defun org-up-heading-safe ()
17902 "Move to the heading line of which the present line is a subheading.
17903 This version will not throw an error. It will return the level of the
17904 headline found, or nil if no higher level is found.
17906 Also, this function will be a lot faster than `outline-up-heading',
17907 because it relies on stars being the outline starters. This can really
17908 make a significant difference in outlines with very many siblings."
17909 (let (start-level re)
17910 (org-back-to-heading t)
17911 (setq start-level (funcall outline-level))
17912 (if (equal start-level 1)
17914 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
17915 (if (re-search-backward re nil t)
17916 (funcall outline-level)))))
17918 (defun org-first-sibling-p ()
17919 "Is this heading the first child of its parents?"
17920 (interactive)
17921 (let ((re (concat "^" outline-regexp))
17922 level l)
17923 (unless (org-at-heading-p t)
17924 (error "Not at a heading"))
17925 (setq level (funcall outline-level))
17926 (save-excursion
17927 (if (not (re-search-backward re nil t))
17929 (setq l (funcall outline-level))
17930 (< l level)))))
17932 (defun org-goto-sibling (&optional previous)
17933 "Goto the next sibling, even if it is invisible.
17934 When PREVIOUS is set, go to the previous sibling instead. Returns t
17935 when a sibling was found. When none is found, return nil and don't
17936 move point."
17937 (let ((fun (if previous 're-search-backward 're-search-forward))
17938 (pos (point))
17939 (re (concat "^" outline-regexp))
17940 level l)
17941 (when (condition-case nil (org-back-to-heading t) (error nil))
17942 (setq level (funcall outline-level))
17943 (catch 'exit
17944 (or previous (forward-char 1))
17945 (while (funcall fun re nil t)
17946 (setq l (funcall outline-level))
17947 (when (< l level) (goto-char pos) (throw 'exit nil))
17948 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
17949 (goto-char pos)
17950 nil))))
17952 (defun org-show-siblings ()
17953 "Show all siblings of the current headline."
17954 (save-excursion
17955 (while (org-goto-sibling) (org-flag-heading nil)))
17956 (save-excursion
17957 (while (org-goto-sibling 'previous)
17958 (org-flag-heading nil))))
17960 (defun org-show-hidden-entry ()
17961 "Show an entry where even the heading is hidden."
17962 (save-excursion
17963 (org-show-entry)))
17965 (defun org-flag-heading (flag &optional entry)
17966 "Flag the current heading. FLAG non-nil means make invisible.
17967 When ENTRY is non-nil, show the entire entry."
17968 (save-excursion
17969 (org-back-to-heading t)
17970 ;; Check if we should show the entire entry
17971 (if entry
17972 (progn
17973 (org-show-entry)
17974 (save-excursion
17975 (and (outline-next-heading)
17976 (org-flag-heading nil))))
17977 (outline-flag-region (max (point-min) (1- (point)))
17978 (save-excursion (outline-end-of-heading) (point))
17979 flag))))
17981 (defun org-get-next-sibling ()
17982 "Move to next heading of the same level, and return point.
17983 If there is no such heading, return nil.
17984 This is like outline-next-sibling, but invisible headings are ok."
17985 (let ((level (funcall outline-level)))
17986 (outline-next-heading)
17987 (while (and (not (eobp)) (> (funcall outline-level) level))
17988 (outline-next-heading))
17989 (if (or (eobp) (< (funcall outline-level) level))
17991 (point))))
17993 (defun org-get-last-sibling ()
17994 "Move to previous heading of the same level, and return point.
17995 If there is no such heading, return nil."
17996 (let ((opoint (point))
17997 (level (funcall outline-level)))
17998 (outline-previous-heading)
17999 (when (and (/= (point) opoint) (outline-on-heading-p t))
18000 (while (and (> (funcall outline-level) level)
18001 (not (bobp)))
18002 (outline-previous-heading))
18003 (if (< (funcall outline-level) level)
18005 (point)))))
18007 (defun org-end-of-subtree (&optional invisible-OK to-heading)
18008 ;; This contains an exact copy of the original function, but it uses
18009 ;; `org-back-to-heading', to make it work also in invisible
18010 ;; trees. And is uses an invisible-OK argument.
18011 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
18012 ;; Furthermore, when used inside Org, finding the end of a large subtree
18013 ;; with many children and grandchildren etc, this can be much faster
18014 ;; than the outline version.
18015 (org-back-to-heading invisible-OK)
18016 (let ((first t)
18017 (level (funcall outline-level)))
18018 (if (and (org-mode-p) (< level 1000))
18019 ;; A true heading (not a plain list item), in Org-mode
18020 ;; This means we can easily find the end by looking
18021 ;; only for the right number of stars. Using a regexp to do
18022 ;; this is so much faster than using a Lisp loop.
18023 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
18024 (forward-char 1)
18025 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
18026 ;; something else, do it the slow way
18027 (while (and (not (eobp))
18028 (or first (> (funcall outline-level) level)))
18029 (setq first nil)
18030 (outline-next-heading)))
18031 (unless to-heading
18032 (if (memq (preceding-char) '(?\n ?\^M))
18033 (progn
18034 ;; Go to end of line before heading
18035 (forward-char -1)
18036 (if (memq (preceding-char) '(?\n ?\^M))
18037 ;; leave blank line before heading
18038 (forward-char -1))))))
18039 (point))
18041 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
18042 "Use Org version in org-mode, for dramatic speed-up."
18043 (if (eq major-mode 'org-mode)
18044 (progn
18045 (org-end-of-subtree nil t)
18046 (unless (eobp) (backward-char 1)))
18047 ad-do-it))
18049 (defun org-forward-same-level (arg &optional invisible-ok)
18050 "Move forward to the arg'th subheading at same level as this one.
18051 Stop at the first and last subheadings of a superior heading."
18052 (interactive "p")
18053 (org-back-to-heading invisible-ok)
18054 (org-on-heading-p)
18055 (let* ((level (- (match-end 0) (match-beginning 0) 1))
18056 (re (format "^\\*\\{1,%d\\} " level))
18058 (forward-char 1)
18059 (while (> arg 0)
18060 (while (and (re-search-forward re nil 'move)
18061 (setq l (- (match-end 0) (match-beginning 0) 1))
18062 (= l level)
18063 (not invisible-ok)
18064 (progn (backward-char 1) (org-invisible-p)))
18065 (if (< l level) (setq arg 1)))
18066 (setq arg (1- arg)))
18067 (beginning-of-line 1)))
18069 (defun org-backward-same-level (arg &optional invisible-ok)
18070 "Move backward to the arg'th subheading at same level as this one.
18071 Stop at the first and last subheadings of a superior heading."
18072 (interactive "p")
18073 (org-back-to-heading)
18074 (org-on-heading-p)
18075 (let* ((level (- (match-end 0) (match-beginning 0) 1))
18076 (re (format "^\\*\\{1,%d\\} " level))
18078 (while (> arg 0)
18079 (while (and (re-search-backward re nil 'move)
18080 (setq l (- (match-end 0) (match-beginning 0) 1))
18081 (= l level)
18082 (not invisible-ok)
18083 (org-invisible-p))
18084 (if (< l level) (setq arg 1)))
18085 (setq arg (1- arg)))))
18087 (defun org-show-subtree ()
18088 "Show everything after this heading at deeper levels."
18089 (outline-flag-region
18090 (point)
18091 (save-excursion
18092 (org-end-of-subtree t t))
18093 nil))
18095 (defun org-show-entry ()
18096 "Show the body directly following this heading.
18097 Show the heading too, if it is currently invisible."
18098 (interactive)
18099 (save-excursion
18100 (condition-case nil
18101 (progn
18102 (org-back-to-heading t)
18103 (outline-flag-region
18104 (max (point-min) (1- (point)))
18105 (save-excursion
18106 (if (re-search-forward
18107 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
18108 (match-beginning 1)
18109 (point-max)))
18110 nil)
18111 (org-cycle-hide-drawers 'children))
18112 (error nil))))
18114 (defun org-make-options-regexp (kwds &optional extra)
18115 "Make a regular expression for keyword lines."
18116 (concat
18118 "#?[ \t]*\\+\\("
18119 (mapconcat 'regexp-quote kwds "\\|")
18120 (if extra (concat "\\|" extra))
18121 "\\):[ \t]*"
18122 "\\(.*\\)"))
18124 ;; Make isearch reveal the necessary context
18125 (defun org-isearch-end ()
18126 "Reveal context after isearch exits."
18127 (when isearch-success ; only if search was successful
18128 (if (featurep 'xemacs)
18129 ;; Under XEmacs, the hook is run in the correct place,
18130 ;; we directly show the context.
18131 (org-show-context 'isearch)
18132 ;; In Emacs the hook runs *before* restoring the overlays.
18133 ;; So we have to use a one-time post-command-hook to do this.
18134 ;; (Emacs 22 has a special variable, see function `org-mode')
18135 (unless (and (boundp 'isearch-mode-end-hook-quit)
18136 isearch-mode-end-hook-quit)
18137 ;; Only when the isearch was not quitted.
18138 (org-add-hook 'post-command-hook 'org-isearch-post-command
18139 'append 'local)))))
18141 (defun org-isearch-post-command ()
18142 "Remove self from hook, and show context."
18143 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
18144 (org-show-context 'isearch))
18147 ;;;; Integration with and fixes for other packages
18149 ;;; Imenu support
18151 (defvar org-imenu-markers nil
18152 "All markers currently used by Imenu.")
18153 (make-variable-buffer-local 'org-imenu-markers)
18155 (defun org-imenu-new-marker (&optional pos)
18156 "Return a new marker for use by Imenu, and remember the marker."
18157 (let ((m (make-marker)))
18158 (move-marker m (or pos (point)))
18159 (push m org-imenu-markers)
18162 (defun org-imenu-get-tree ()
18163 "Produce the index for Imenu."
18164 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
18165 (setq org-imenu-markers nil)
18166 (let* ((n org-imenu-depth)
18167 (re (concat "^" outline-regexp))
18168 (subs (make-vector (1+ n) nil))
18169 (last-level 0)
18170 m level head)
18171 (save-excursion
18172 (save-restriction
18173 (widen)
18174 (goto-char (point-max))
18175 (while (re-search-backward re nil t)
18176 (setq level (org-reduced-level (funcall outline-level)))
18177 (when (<= level n)
18178 (looking-at org-complex-heading-regexp)
18179 (setq head (org-link-display-format
18180 (org-match-string-no-properties 4))
18181 m (org-imenu-new-marker))
18182 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
18183 (if (>= level last-level)
18184 (push (cons head m) (aref subs level))
18185 (push (cons head (aref subs (1+ level))) (aref subs level))
18186 (loop for i from (1+ level) to n do (aset subs i nil)))
18187 (setq last-level level)))))
18188 (aref subs 1)))
18190 (eval-after-load "imenu"
18191 '(progn
18192 (add-hook 'imenu-after-jump-hook
18193 (lambda ()
18194 (if (eq major-mode 'org-mode)
18195 (org-show-context 'org-goto))))))
18197 (defun org-link-display-format (link)
18198 "Replace a link with either the description, or the link target
18199 if no description is present"
18200 (save-match-data
18201 (if (string-match org-bracket-link-analytic-regexp link)
18202 (replace-match (if (match-end 5)
18203 (match-string 5 link)
18204 (concat (match-string 1 link)
18205 (match-string 3 link)))
18206 nil t link)
18207 link)))
18209 ;; Speedbar support
18211 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
18212 "Overlay marking the agenda restriction line in speedbar.")
18213 (org-overlay-put org-speedbar-restriction-lock-overlay
18214 'face 'org-agenda-restriction-lock)
18215 (org-overlay-put org-speedbar-restriction-lock-overlay
18216 'help-echo "Agendas are currently limited to this item.")
18217 (org-detach-overlay org-speedbar-restriction-lock-overlay)
18219 (defun org-speedbar-set-agenda-restriction ()
18220 "Restrict future agenda commands to the location at point in speedbar.
18221 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
18222 (interactive)
18223 (require 'org-agenda)
18224 (let (p m tp np dir txt)
18225 (cond
18226 ((setq p (text-property-any (point-at-bol) (point-at-eol)
18227 'org-imenu t))
18228 (setq m (get-text-property p 'org-imenu-marker))
18229 (with-current-buffer (marker-buffer m)
18230 (goto-char m)
18231 (org-agenda-set-restriction-lock 'subtree)))
18232 ((setq p (text-property-any (point-at-bol) (point-at-eol)
18233 'speedbar-function 'speedbar-find-file))
18234 (setq tp (previous-single-property-change
18235 (1+ p) 'speedbar-function)
18236 np (next-single-property-change
18237 tp 'speedbar-function)
18238 dir (speedbar-line-directory)
18239 txt (buffer-substring-no-properties (or tp (point-min))
18240 (or np (point-max))))
18241 (with-current-buffer (find-file-noselect
18242 (let ((default-directory dir))
18243 (expand-file-name txt)))
18244 (unless (org-mode-p)
18245 (error "Cannot restrict to non-Org-mode file"))
18246 (org-agenda-set-restriction-lock 'file)))
18247 (t (error "Don't know how to restrict Org-mode's agenda")))
18248 (org-move-overlay org-speedbar-restriction-lock-overlay
18249 (point-at-bol) (point-at-eol))
18250 (setq current-prefix-arg nil)
18251 (org-agenda-maybe-redo)))
18253 (eval-after-load "speedbar"
18254 '(progn
18255 (speedbar-add-supported-extension ".org")
18256 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
18257 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
18258 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
18259 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18260 (add-hook 'speedbar-visiting-tag-hook
18261 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
18264 ;;; Fixes and Hacks for problems with other packages
18266 ;; Make flyspell not check words in links, to not mess up our keymap
18267 (defun org-mode-flyspell-verify ()
18268 "Don't let flyspell put overlays at active buttons."
18269 (and (not (get-text-property (point) 'keymap))
18270 (not (get-text-property (point) 'org-no-flyspell))))
18272 (defun org-remove-flyspell-overlays-in (beg end)
18273 "Remove flyspell overlays in region."
18274 (and (org-bound-and-true-p flyspell-mode)
18275 (fboundp 'flyspell-delete-region-overlays)
18276 (flyspell-delete-region-overlays beg end))
18277 (add-text-properties beg end '(org-no-flyspell t)))
18279 ;; Make `bookmark-jump' shows the jump location if it was hidden.
18280 (eval-after-load "bookmark"
18281 '(if (boundp 'bookmark-after-jump-hook)
18282 ;; We can use the hook
18283 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
18284 ;; Hook not available, use advice
18285 (defadvice bookmark-jump (after org-make-visible activate)
18286 "Make the position visible."
18287 (org-bookmark-jump-unhide))))
18289 ;; Make sure saveplace shows the location if it was hidden
18290 (eval-after-load "saveplace"
18291 '(defadvice save-place-find-file-hook (after org-make-visible activate)
18292 "Make the position visible."
18293 (org-bookmark-jump-unhide)))
18295 ;; Make sure ecb shows the location if it was hidden
18296 (eval-after-load "ecb"
18297 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
18298 "Make hierarchy visible when jumping into location from ECB tree buffer."
18299 (if (eq major-mode 'org-mode)
18300 (org-show-context))))
18302 (defun org-bookmark-jump-unhide ()
18303 "Unhide the current position, to show the bookmark location."
18304 (and (org-mode-p)
18305 (or (org-invisible-p)
18306 (save-excursion (goto-char (max (point-min) (1- (point))))
18307 (org-invisible-p)))
18308 (org-show-context 'bookmark-jump)))
18310 ;; Make session.el ignore our circular variable
18311 (eval-after-load "session"
18312 '(add-to-list 'session-globals-exclude 'org-mark-ring))
18314 ;;;; Experimental code
18316 (defun org-closed-in-range ()
18317 "Sparse tree of items closed in a certain time range.
18318 Still experimental, may disappear in the future."
18319 (interactive)
18320 ;; Get the time interval from the user.
18321 (let* ((time1 (org-float-time
18322 (org-read-date nil 'to-time nil "Starting date: ")))
18323 (time2 (org-float-time
18324 (org-read-date nil 'to-time nil "End date:")))
18325 ;; callback function
18326 (callback (lambda ()
18327 (let ((time
18328 (org-float-time
18329 (apply 'encode-time
18330 (org-parse-time-string
18331 (match-string 1))))))
18332 ;; check if time in interval
18333 (and (>= time time1) (<= time time2))))))
18334 ;; make tree, check each match with the callback
18335 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
18337 ;;;; Finish up
18339 (provide 'org)
18341 (run-hooks 'org-load-hook)
18343 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
18345 ;;; org.el ends here