LaTeX export: Fix problems with use of \verb in headlines
[org-mode.git] / lisp / org.el
blob31e14424f1797c9cea5fdf79468d371394aa5f2a
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.27trans
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.27trans"
99 "The version number of the file org.el.")
101 (defun org-version (&optional here)
102 "Show the org-mode version in the echo area.
103 With prefix arg HERE, insert it at point."
104 (interactive "P")
105 (let ((version (format "Org-mode version %s" org-version)))
106 (message version)
107 (if here
108 (insert version))))
110 ;;; Compatibility constants
112 ;;; The custom variables
114 (defgroup org nil
115 "Outline-based notes management and organizer."
116 :tag "Org"
117 :group 'outlines
118 :group 'hypermedia
119 :group 'calendar)
121 (defcustom org-load-hook nil
122 "Hook that is run after org.el has been loaded."
123 :group 'org
124 :type 'hook)
126 (defvar org-modules) ; defined below
127 (defvar org-modules-loaded nil
128 "Have the modules been loaded already?")
130 (defun org-load-modules-maybe (&optional force)
131 "Load all extensions listed in `org-modules'."
132 (when (or force (not org-modules-loaded))
133 (mapc (lambda (ext)
134 (condition-case nil (require ext)
135 (error (message "Problems while trying to load feature `%s'" ext))))
136 org-modules)
137 (setq org-modules-loaded t)))
139 (defun org-set-modules (var value)
140 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
141 (set var value)
142 (when (featurep 'org)
143 (org-load-modules-maybe 'force)))
145 (when (org-bound-and-true-p org-modules)
146 (let ((a (member 'org-infojs org-modules)))
147 (and a (setcar a 'org-jsinfo))))
149 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
150 "Modules that should always be loaded together with org.el.
151 If a description starts with <C>, the file is not part of Emacs
152 and loading it will require that you have downloaded and properly installed
153 the org-mode distribution.
155 You can also use this system to load external packages (i.e. neither Org
156 core modules, not modules from the CONTRIB directory). Just add symbols
157 to the end of the list. If the package is called org-xyz.el, then you need
158 to add the symbol `xyz', and the package must have a call to
160 (provide 'org-xyz)"
161 :group 'org
162 :set 'org-set-modules
163 :type
164 '(set :greedy t
165 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
166 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
167 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
168 (const :tag " id: Global IDs for identifying entries" org-id)
169 (const :tag " info: Links to Info nodes" org-info)
170 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
171 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
172 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
173 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
174 (const :tag " mew Links to Mew folders/messages" org-mew)
175 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
176 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
177 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
178 (const :tag " vm: Links to VM folders/messages" org-vm)
179 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
180 (const :tag " w3m: Special cut/paste from w3m to Org." org-w3m)
181 (const :tag " mouse: Additional mouse support" org-mouse)
183 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
184 (const :tag "C annotation-helper: Call Remember directly from Browser (OBSOLETE, use org-protocol)" org-annotation-helper)
185 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
186 (const :tag "C browser-url: Store link, directly from Browser (OBSOLETE, use org-protocol)" org-browser-url)
187 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
188 (const :tag "C collector: Collect properties into tables" org-collector)
189 (const :tag "C depend: TODO dependencies for Org-mode (PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
190 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
191 (const :tag "C eval: Include command output as text" org-eval)
192 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
193 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
194 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
195 (const :tag "C exp-blocks: Pre-process blocks for export" org-exp-blocks)
196 (const :tag "C interactive-query: Interactive modification of tags query (PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
197 (const :tag "C jira Add a jira:ticket protocol to Org" org-jira)
198 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
199 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
200 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
201 (const :tag "C mtags: Support for muse-like tags" org-mtags)
202 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
203 (const :tag "C R: Computation using the R language" org-R)
204 (const :tag "C registry: A registry for Org links" org-registry)
205 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
206 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
207 (const :tag "C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
208 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
209 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
210 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
212 (defcustom org-support-shift-select nil
213 "Non-nil means, make shift-cursor commands select text when possible.
215 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
216 selecting a region, or enlarge thusly regions started in this way.
217 In Org-mode, in special contexts, these same keys are used for other
218 purposes, important enough to compete with shift selection. Org tries
219 to balance these needs by supporting `shift-select-mode' outside these
220 special contexts, under control of this variable.
222 The default of this variable is nil, to avoid confusing behavior. Shifted
223 cursor keys will then execute Org commands in the following contexts:
224 - on a headline, changing TODO state (left/right) and priority (up/down)
225 - on a time stamp, changing the time
226 - in a plain list item, changing the bullet type
227 - in a property definition line, switching between allowed values
228 - in the BEGIN line of a clock table (changing the time block).
229 Outside these contexts, the commands will throw an error.
231 When this variable is t and the cursor is not in a special context,
232 Org-mode will support shift-selection for making and enlarging regions.
233 To make this more effective, the bullet cycling will no longer happen
234 anywhere in an item line, but only if the cursor is exactly on the bullet.
236 If you set this variable to the symbol `always', then the keys
237 will not be special in headlines, property lines, and item lines, to make
238 shift selection work there as well. If this is what you want, you can
239 use the following alternative commands: `C-c C-t' and `C-c ,' to
240 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
241 TODO sets, `C-c -' to cycle item bullet types, and properties can be
242 edited by hand or in column view.
244 However, when the cursor is on a timestamp, shift-cursor commands
245 will still edit the time stamp - this is just too good to give up.
247 XEmacs user should have this variable set to nil, because shift-select-mode
248 is Emacs 23 only."
249 :group 'org
250 :type '(choice
251 (const :tag "Never" nil)
252 (const :tag "When outside special context" t)
253 (const :tag "Everywhere except timestamps" always)))
255 (defgroup org-startup nil
256 "Options concerning startup of Org-mode."
257 :tag "Org Startup"
258 :group 'org)
260 (defcustom org-startup-folded t
261 "Non-nil means, entering Org-mode will switch to OVERVIEW.
262 This can also be configured on a per-file basis by adding one of
263 the following lines anywhere in the buffer:
265 #+STARTUP: fold
266 #+STARTUP: nofold
267 #+STARTUP: content"
268 :group 'org-startup
269 :type '(choice
270 (const :tag "nofold: show all" nil)
271 (const :tag "fold: overview" t)
272 (const :tag "content: all headlines" content)))
274 (defcustom org-startup-truncated t
275 "Non-nil means, entering Org-mode will set `truncate-lines'.
276 This is useful since some lines containing links can be very long and
277 uninteresting. Also tables look terrible when wrapped."
278 :group 'org-startup
279 :type 'boolean)
281 (defcustom org-startup-align-all-tables nil
282 "Non-nil means, align all tables when visiting a file.
283 This is useful when the column width in tables is forced with <N> cookies
284 in table fields. Such tables will look correct only after the first re-align.
285 This can also be configured on a per-file basis by adding one of
286 the following lines anywhere in the buffer:
287 #+STARTUP: align
288 #+STARTUP: noalign"
289 :group 'org-startup
290 :type 'boolean)
292 (defcustom org-insert-mode-line-in-empty-file nil
293 "Non-nil means insert the first line setting Org-mode in empty files.
294 When the function `org-mode' is called interactively in an empty file, this
295 normally means that the file name does not automatically trigger Org-mode.
296 To ensure that the file will always be in Org-mode in the future, a
297 line enforcing Org-mode will be inserted into the buffer, if this option
298 has been set."
299 :group 'org-startup
300 :type 'boolean)
302 (defcustom org-replace-disputed-keys nil
303 "Non-nil means use alternative key bindings for some keys.
304 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
305 These keys are also used by other packages like shift-selection-mode'
306 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
307 If you want to use Org-mode together with one of these other modes,
308 or more generally if you would like to move some Org-mode commands to
309 other keys, set this variable and configure the keys with the variable
310 `org-disputed-keys'.
312 This option is only relevant at load-time of Org-mode, and must be set
313 *before* org.el is loaded. Changing it requires a restart of Emacs to
314 become effective."
315 :group 'org-startup
316 :type 'boolean)
318 (defcustom org-use-extra-keys nil
319 "Non-nil means use extra key sequence definitions for certain
320 commands. This happens automatically if you run XEmacs or if
321 window-system is nil. This variable lets you do the same
322 manually. You must set it before loading org.
324 Example: on Carbon Emacs 22 running graphically, with an external
325 keyboard on a Powerbook, the default way of setting M-left might
326 not work for either Alt or ESC. Setting this variable will make
327 it work for ESC."
328 :group 'org-startup
329 :type 'boolean)
331 (if (fboundp 'defvaralias)
332 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
334 (defcustom org-disputed-keys
335 '(([(shift up)] . [(meta p)])
336 ([(shift down)] . [(meta n)])
337 ([(shift left)] . [(meta -)])
338 ([(shift right)] . [(meta +)])
339 ([(control shift right)] . [(meta shift +)])
340 ([(control shift left)] . [(meta shift -)]))
341 "Keys for which Org-mode and other modes compete.
342 This is an alist, cars are the default keys, second element specifies
343 the alternative to use when `org-replace-disputed-keys' is t.
345 Keys can be specified in any syntax supported by `define-key'.
346 The value of this option takes effect only at Org-mode's startup,
347 therefore you'll have to restart Emacs to apply it after changing."
348 :group 'org-startup
349 :type 'alist)
351 (defun org-key (key)
352 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
353 Or return the original if not disputed."
354 (if org-replace-disputed-keys
355 (let* ((nkey (key-description key))
356 (x (org-find-if (lambda (x)
357 (equal (key-description (car x)) nkey))
358 org-disputed-keys)))
359 (if x (cdr x) key))
360 key))
362 (defun org-find-if (predicate seq)
363 (catch 'exit
364 (while seq
365 (if (funcall predicate (car seq))
366 (throw 'exit (car seq))
367 (pop seq)))))
369 (defun org-defkey (keymap key def)
370 "Define a key, possibly translated, as returned by `org-key'."
371 (define-key keymap (org-key key) def))
373 (defcustom org-ellipsis nil
374 "The ellipsis to use in the Org-mode outline.
375 When nil, just use the standard three dots. When a string, use that instead,
376 When a face, use the standard 3 dots, but with the specified face.
377 The change affects only Org-mode (which will then use its own display table).
378 Changing this requires executing `M-x org-mode' in a buffer to become
379 effective."
380 :group 'org-startup
381 :type '(choice (const :tag "Default" nil)
382 (face :tag "Face" :value org-warning)
383 (string :tag "String" :value "...#")))
385 (defvar org-display-table nil
386 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
388 (defgroup org-keywords nil
389 "Keywords in Org-mode."
390 :tag "Org Keywords"
391 :group 'org)
393 (defcustom org-deadline-string "DEADLINE:"
394 "String to mark deadline entries.
395 A deadline is this string, followed by a time stamp. Should be a word,
396 terminated by a colon. You can insert a schedule keyword and
397 a timestamp with \\[org-deadline].
398 Changes become only effective after restarting Emacs."
399 :group 'org-keywords
400 :type 'string)
402 (defcustom org-scheduled-string "SCHEDULED:"
403 "String to mark scheduled TODO entries.
404 A schedule is this string, followed by a time stamp. Should be a word,
405 terminated by a colon. You can insert a schedule keyword and
406 a timestamp with \\[org-schedule].
407 Changes become only effective after restarting Emacs."
408 :group 'org-keywords
409 :type 'string)
411 (defcustom org-closed-string "CLOSED:"
412 "String used as the prefix for timestamps logging closing a TODO entry."
413 :group 'org-keywords
414 :type 'string)
416 (defcustom org-clock-string "CLOCK:"
417 "String used as prefix for timestamps clocking work hours on an item."
418 :group 'org-keywords
419 :type 'string)
421 (defcustom org-comment-string "COMMENT"
422 "Entries starting with this keyword will never be exported.
423 An entry can be toggled between COMMENT and normal with
424 \\[org-toggle-comment].
425 Changes become only effective after restarting Emacs."
426 :group 'org-keywords
427 :type 'string)
429 (defcustom org-quote-string "QUOTE"
430 "Entries starting with this keyword will be exported in fixed-width font.
431 Quoting applies only to the text in the entry following the headline, and does
432 not extend beyond the next headline, even if that is lower level.
433 An entry can be toggled between QUOTE and normal with
434 \\[org-toggle-fixed-width-section]."
435 :group 'org-keywords
436 :type 'string)
438 (defconst org-repeat-re
439 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
440 "Regular expression for specifying repeated events.
441 After a match, group 1 contains the repeat expression.")
443 (defgroup org-structure nil
444 "Options concerning the general structure of Org-mode files."
445 :tag "Org Structure"
446 :group 'org)
448 (defgroup org-reveal-location nil
449 "Options about how to make context of a location visible."
450 :tag "Org Reveal Location"
451 :group 'org-structure)
453 (defconst org-context-choice
454 '(choice
455 (const :tag "Always" t)
456 (const :tag "Never" nil)
457 (repeat :greedy t :tag "Individual contexts"
458 (cons
459 (choice :tag "Context"
460 (const agenda)
461 (const org-goto)
462 (const occur-tree)
463 (const tags-tree)
464 (const link-search)
465 (const mark-goto)
466 (const bookmark-jump)
467 (const isearch)
468 (const default))
469 (boolean))))
470 "Contexts for the reveal options.")
472 (defcustom org-show-hierarchy-above '((default . t))
473 "Non-nil means, show full hierarchy when revealing a location.
474 Org-mode often shows locations in an org-mode file which might have
475 been invisible before. When this is set, the hierarchy of headings
476 above the exposed location is shown.
477 Turning this off for example for sparse trees makes them very compact.
478 Instead of t, this can also be an alist specifying this option for different
479 contexts. Valid contexts are
480 agenda when exposing an entry from the agenda
481 org-goto when using the command `org-goto' on key C-c C-j
482 occur-tree when using the command `org-occur' on key C-c /
483 tags-tree when constructing a sparse tree based on tags matches
484 link-search when exposing search matches associated with a link
485 mark-goto when exposing the jump goal of a mark
486 bookmark-jump when exposing a bookmark location
487 isearch when exiting from an incremental search
488 default default for all contexts not set explicitly"
489 :group 'org-reveal-location
490 :type org-context-choice)
492 (defcustom org-show-following-heading '((default . nil))
493 "Non-nil means, show following heading when revealing a location.
494 Org-mode often shows locations in an org-mode file which might have
495 been invisible before. When this is set, the heading following the
496 match is shown.
497 Turning this off for example for sparse trees makes them very compact,
498 but makes it harder to edit the location of the match. In such a case,
499 use the command \\[org-reveal] to show more context.
500 Instead of t, this can also be an alist specifying this option for different
501 contexts. See `org-show-hierarchy-above' for valid contexts."
502 :group 'org-reveal-location
503 :type org-context-choice)
505 (defcustom org-show-siblings '((default . nil) (isearch t))
506 "Non-nil means, show all sibling heading when revealing a location.
507 Org-mode often shows locations in an org-mode file which might have
508 been invisible before. When this is set, the sibling of the current entry
509 heading are all made visible. If `org-show-hierarchy-above' is t,
510 the same happens on each level of the hierarchy above the current entry.
512 By default this is on for the isearch context, off for all other contexts.
513 Turning this off for example for sparse trees makes them very compact,
514 but makes it harder to edit the location of the match. In such a case,
515 use the command \\[org-reveal] to show more context.
516 Instead of t, this can also be an alist specifying this option for different
517 contexts. See `org-show-hierarchy-above' for valid contexts."
518 :group 'org-reveal-location
519 :type org-context-choice)
521 (defcustom org-show-entry-below '((default . nil))
522 "Non-nil means, show the entry below a headline when revealing a location.
523 Org-mode often shows locations in an org-mode file which might have
524 been invisible before. When this is set, the text below the headline that is
525 exposed is also shown.
527 By default this is off for all contexts.
528 Instead of t, this can also be an alist specifying this option for different
529 contexts. See `org-show-hierarchy-above' for valid contexts."
530 :group 'org-reveal-location
531 :type org-context-choice)
533 (defcustom org-indirect-buffer-display 'other-window
534 "How should indirect tree buffers be displayed?
535 This applies to indirect buffers created with the commands
536 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
537 Valid values are:
538 current-window Display in the current window
539 other-window Just display in another window.
540 dedicated-frame Create one new frame, and re-use it each time.
541 new-frame Make a new frame each time. Note that in this case
542 previously-made indirect buffers are kept, and you need to
543 kill these buffers yourself."
544 :group 'org-structure
545 :group 'org-agenda-windows
546 :type '(choice
547 (const :tag "In current window" current-window)
548 (const :tag "In current frame, other window" other-window)
549 (const :tag "Each time a new frame" new-frame)
550 (const :tag "One dedicated frame" dedicated-frame)))
552 (defgroup org-cycle nil
553 "Options concerning visibility cycling in Org-mode."
554 :tag "Org Cycle"
555 :group 'org-structure)
557 (defcustom org-cycle-max-level nil
558 "Maximum level which should still be subject to visibility cycling.
559 Levels higher than this will, for cycling, be treated as text, not a headline.
560 When `org-odd-levels-only' is set, a value of N in this variable actually
561 means 2N-1 stars as the limiting headline.
562 When nil, cycle all levels.
563 Note that the limiting level of cycling is also influenced by
564 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
565 `org-inlinetask-min-level' is, cycling will be limited to levels one less
566 than its value."
567 :group 'org-cycle
568 :type '(choice
569 (const :tag "No limit" nil)
570 (integer :tag "Maximum level")))
572 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
573 "Names of drawers. Drawers are not opened by cycling on the headline above.
574 Drawers only open with a TAB on the drawer line itself. A drawer looks like
575 this:
576 :DRAWERNAME:
577 .....
578 :END:
579 The drawer \"PROPERTIES\" is special for capturing properties through
580 the property API.
582 Drawers can be defined on the per-file basis with a line like:
584 #+DRAWERS: HIDDEN STATE PROPERTIES"
585 :group 'org-structure
586 :group 'org-cycle
587 :type '(repeat (string :tag "Drawer Name")))
589 (defcustom org-hide-block-startup nil
590 "Non-nil means, , entering Org-mode will fold all blocks.
591 This can also be set in on a per-file basis with
593 #+STARTUP: hideblocks
594 #+STARTUP: showblocks"
595 :group 'org-startup
596 :group 'org-cycle
597 :type 'boolean)
599 (defcustom org-cycle-global-at-bob nil
600 "Cycle globally if cursor is at beginning of buffer and not at a headline.
601 This makes it possible to do global cycling without having to use S-TAB or
602 C-u TAB. For this special case to work, the first line of the buffer
603 must not be a headline - it may be empty or some other text. When used in
604 this way, `org-cycle-hook' is disables temporarily, to make sure the
605 cursor stays at the beginning of the buffer.
606 When this option is nil, don't do anything special at the beginning
607 of the buffer."
608 :group 'org-cycle
609 :type 'boolean)
611 (defcustom org-cycle-emulate-tab t
612 "Where should `org-cycle' emulate TAB.
613 nil Never
614 white Only in completely white lines
615 whitestart Only at the beginning of lines, before the first non-white char
616 t Everywhere except in headlines
617 exc-hl-bol Everywhere except at the start of a headline
618 If TAB is used in a place where it does not emulate TAB, the current subtree
619 visibility is cycled."
620 :group 'org-cycle
621 :type '(choice (const :tag "Never" nil)
622 (const :tag "Only in completely white lines" white)
623 (const :tag "Before first char in a line" whitestart)
624 (const :tag "Everywhere except in headlines" t)
625 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
628 (defcustom org-cycle-separator-lines 2
629 "Number of empty lines needed to keep an empty line between collapsed trees.
630 If you leave an empty line between the end of a subtree and the following
631 headline, this empty line is hidden when the subtree is folded.
632 Org-mode will leave (exactly) one empty line visible if the number of
633 empty lines is equal or larger to the number given in this variable.
634 So the default 2 means, at least 2 empty lines after the end of a subtree
635 are needed to produce free space between a collapsed subtree and the
636 following headline.
638 Special case: when 0, never leave empty lines in collapsed view."
639 :group 'org-cycle
640 :type 'integer)
641 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
643 (defcustom org-pre-cycle-hook nil
644 "Hook that is run before visibility cycling is happening.
645 The function(s) in this hook must accept a single argument which indicates
646 the new state that will be set right after running this hook. The
647 argument is a symbol. Before a global state change, it can have the values
648 `overview', `content', or `all'. Before a local state change, it can have
649 the values `folded', `children', or `subtree'."
650 :group 'org-cycle
651 :type 'hook)
653 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
654 org-cycle-hide-drawers
655 org-cycle-show-empty-lines
656 org-optimize-window-after-visibility-change)
657 "Hook that is run after `org-cycle' has changed the buffer visibility.
658 The function(s) in this hook must accept a single argument which indicates
659 the new state that was set by the most recent `org-cycle' command. The
660 argument is a symbol. After a global state change, it can have the values
661 `overview', `content', or `all'. After a local state change, it can have
662 the values `folded', `children', or `subtree'."
663 :group 'org-cycle
664 :type 'hook)
666 (defgroup org-edit-structure nil
667 "Options concerning structure editing in Org-mode."
668 :tag "Org Edit Structure"
669 :group 'org-structure)
671 (defcustom org-odd-levels-only nil
672 "Non-nil means, skip even levels and only use odd levels for the outline.
673 This has the effect that two stars are being added/taken away in
674 promotion/demotion commands. It also influences how levels are
675 handled by the exporters.
676 Changing it requires restart of `font-lock-mode' to become effective
677 for fontification also in regions already fontified.
678 You may also set this on a per-file basis by adding one of the following
679 lines to the buffer:
681 #+STARTUP: odd
682 #+STARTUP: oddeven"
683 :group 'org-edit-structure
684 :group 'org-font-lock
685 :type 'boolean)
687 (defcustom org-adapt-indentation t
688 "Non-nil means, adapt indentation when promoting and demoting.
689 When this is set and the *entire* text in an entry is indented, the
690 indentation is increased by one space in a demotion command, and
691 decreased by one in a promotion command. If any line in the entry
692 body starts at column 0, indentation is not changed at all.
694 This variable also influences how property drawers and planning
695 information is inserted. When t, these lines drawers will be inserted
696 indented. When nil, they will not be indented."
697 :group 'org-edit-structure
698 :type 'boolean)
700 (defcustom org-special-ctrl-a/e nil
701 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
703 When t, `C-a' will bring back the cursor to the beginning of the
704 headline text, i.e. after the stars and after a possible TODO keyword.
705 In an item, this will be the position after the bullet.
706 When the cursor is already at that position, another `C-a' will bring
707 it to the beginning of the line.
709 `C-e' will jump to the end of the headline, ignoring the presence of tags
710 in the headline. A second `C-e' will then jump to the true end of the
711 line, after any tags.
713 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
714 and only a directly following, identical keypress will bring the cursor
715 to the special positions.
717 This may also be a cons cell where the behavior for `C-a' and `C-e' is
718 set separately."
719 :group 'org-edit-structure
720 :type '(choice
721 (const :tag "off" nil)
722 (const :tag "after stars/bullet and before tags first" t)
723 (const :tag "true line boundary first" reversed)
724 (cons :tag "Set C-a and C-e separately"
725 (choice :tag "Special C-a"
726 (const :tag "off" nil)
727 (const :tag "after stars/bullet first" t)
728 (const :tag "before stars/bullet first" reversed))
729 (choice :tag "Special C-e"
730 (const :tag "off" nil)
731 (const :tag "before tags first" t)
732 (const :tag "after tags first" reversed)))))
733 (if (fboundp 'defvaralias)
734 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
736 (defcustom org-special-ctrl-k nil
737 "Non-nil means `C-k' will behave specially in headlines.
738 When nil, `C-k' will call the default `kill-line' command.
739 When t, the following will happen while the cursor is in the headline:
741 - When the cursor is at the beginning of a headline, kill the entire
742 line and possible the folded subtree below the line.
743 - When in the middle of the headline text, kill the headline up to the tags.
744 - When after the headline text, kill the tags."
745 :group 'org-edit-structure
746 :type 'boolean)
748 (defcustom org-yank-folded-subtrees t
749 "Non-nil means, when yanking subtrees, fold them.
750 If the kill is a single subtree, or a sequence of subtrees, i.e. if
751 it starts with a heading and all other headings in it are either children
752 or siblings, then fold all the subtrees. However, do this only if no
753 text after the yank would be swallowed into a folded tree by this action."
754 :group 'org-edit-structure
755 :type 'boolean)
757 (defcustom org-yank-adjusted-subtrees nil
758 "Non-nil means, when yanking subtrees, adjust the level.
759 With this setting, `org-paste-subtree' is used to insert the subtree, see
760 this function for details."
761 :group 'org-edit-structure
762 :type 'boolean)
764 (defcustom org-M-RET-may-split-line '((default . t))
765 "Non-nil means, M-RET will split the line at the cursor position.
766 When nil, it will go to the end of the line before making a
767 new line.
768 You may also set this option in a different way for different
769 contexts. Valid contexts are:
771 headline when creating a new headline
772 item when creating a new item
773 table in a table field
774 default the value to be used for all contexts not explicitly
775 customized"
776 :group 'org-structure
777 :group 'org-table
778 :type '(choice
779 (const :tag "Always" t)
780 (const :tag "Never" nil)
781 (repeat :greedy t :tag "Individual contexts"
782 (cons
783 (choice :tag "Context"
784 (const headline)
785 (const item)
786 (const table)
787 (const default))
788 (boolean)))))
791 (defcustom org-insert-heading-respect-content nil
792 "Non-nil means, insert new headings after the current subtree.
793 When nil, the new heading is created directly after the current line.
794 The commands \\[org-insert-heading-respect-content] and
795 \\[org-insert-todo-heading-respect-content] turn this variable on
796 for the duration of the command."
797 :group 'org-structure
798 :type 'boolean)
800 (defcustom org-blank-before-new-entry '((heading . auto)
801 (plain-list-item . auto))
802 "Should `org-insert-heading' leave a blank line before new heading/item?
803 The value is an alist, with `heading' and `plain-list-item' as car,
804 and a boolean flag as cdr. For plain lists, if the variable
805 `org-empty-line-terminates-plain-lists' is set, the setting here
806 is ignored and no empty line is inserted, to keep the list in tact."
807 :group 'org-edit-structure
808 :type '(list
809 (cons (const heading)
810 (choice (const :tag "Never" nil)
811 (const :tag "Always" t)
812 (const :tag "Auto" auto)))
813 (cons (const plain-list-item)
814 (choice (const :tag "Never" nil)
815 (const :tag "Always" t)
816 (const :tag "Auto" auto)))))
818 (defcustom org-insert-heading-hook nil
819 "Hook being run after inserting a new heading."
820 :group 'org-edit-structure
821 :type 'hook)
823 (defcustom org-enable-fixed-width-editor t
824 "Non-nil means, lines starting with \":\" are treated as fixed-width.
825 This currently only means, they are never auto-wrapped.
826 When nil, such lines will be treated like ordinary lines.
827 See also the QUOTE keyword."
828 :group 'org-edit-structure
829 :type 'boolean)
832 (defcustom org-goto-auto-isearch t
833 "Non-nil means, typing characters in org-goto starts incremental search."
834 :group 'org-edit-structure
835 :type 'boolean)
837 (defgroup org-sparse-trees nil
838 "Options concerning sparse trees in Org-mode."
839 :tag "Org Sparse Trees"
840 :group 'org-structure)
842 (defcustom org-highlight-sparse-tree-matches t
843 "Non-nil means, highlight all matches that define a sparse tree.
844 The highlights will automatically disappear the next time the buffer is
845 changed by an edit command."
846 :group 'org-sparse-trees
847 :type 'boolean)
849 (defcustom org-remove-highlights-with-change t
850 "Non-nil means, any change to the buffer will remove temporary highlights.
851 Such highlights are created by `org-occur' and `org-clock-display'.
852 When nil, `C-c C-c needs to be used to get rid of the highlights.
853 The highlights created by `org-preview-latex-fragment' always need
854 `C-c C-c' to be removed."
855 :group 'org-sparse-trees
856 :group 'org-time
857 :type 'boolean)
860 (defcustom org-occur-hook '(org-first-headline-recenter)
861 "Hook that is run after `org-occur' has constructed a sparse tree.
862 This can be used to recenter the window to show as much of the structure
863 as possible."
864 :group 'org-sparse-trees
865 :type 'hook)
867 (defgroup org-imenu-and-speedbar nil
868 "Options concerning imenu and speedbar in Org-mode."
869 :tag "Org Imenu and Speedbar"
870 :group 'org-structure)
872 (defcustom org-imenu-depth 2
873 "The maximum level for Imenu access to Org-mode headlines.
874 This also applied for speedbar access."
875 :group 'org-imenu-and-speedbar
876 :type 'integer)
878 (defgroup org-table nil
879 "Options concerning tables in Org-mode."
880 :tag "Org Table"
881 :group 'org)
883 (defcustom org-enable-table-editor 'optimized
884 "Non-nil means, lines starting with \"|\" are handled by the table editor.
885 When nil, such lines will be treated like ordinary lines.
887 When equal to the symbol `optimized', the table editor will be optimized to
888 do the following:
889 - Automatic overwrite mode in front of whitespace in table fields.
890 This makes the structure of the table stay in tact as long as the edited
891 field does not exceed the column width.
892 - Minimize the number of realigns. Normally, the table is aligned each time
893 TAB or RET are pressed to move to another field. With optimization this
894 happens only if changes to a field might have changed the column width.
895 Optimization requires replacing the functions `self-insert-command',
896 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
897 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
898 very good at guessing when a re-align will be necessary, but you can always
899 force one with \\[org-ctrl-c-ctrl-c].
901 If you would like to use the optimized version in Org-mode, but the
902 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
904 This variable can be used to turn on and off the table editor during a session,
905 but in order to toggle optimization, a restart is required.
907 See also the variable `org-table-auto-blank-field'."
908 :group 'org-table
909 :type '(choice
910 (const :tag "off" nil)
911 (const :tag "on" t)
912 (const :tag "on, optimized" optimized)))
914 (defcustom org-self-insert-cluster-for-undo t
915 "Non-nil means cluster self-insert commands for undo when possible.
916 If this is set, then, like in the Emacs command loop, 20 consequtive
917 characters will be undone together.
918 This is configurable, because there is some impact on typing performance."
919 :group 'org-table
920 :type 'boolean)
922 (defcustom org-table-tab-recognizes-table.el t
923 "Non-nil means, TAB will automatically notice a table.el table.
924 When it sees such a table, it moves point into it and - if necessary -
925 calls `table-recognize-table'."
926 :group 'org-table-editing
927 :type 'boolean)
929 (defgroup org-link nil
930 "Options concerning links in Org-mode."
931 :tag "Org Link"
932 :group 'org)
934 (defvar org-link-abbrev-alist-local nil
935 "Buffer-local version of `org-link-abbrev-alist', which see.
936 The value of this is taken from the #+LINK lines.")
937 (make-variable-buffer-local 'org-link-abbrev-alist-local)
939 (defcustom org-link-abbrev-alist nil
940 "Alist of link abbreviations.
941 The car of each element is a string, to be replaced at the start of a link.
942 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
943 links in Org-mode buffers can have an optional tag after a double colon, e.g.
945 [[linkkey:tag][description]]
947 The 'linkkey' must be a word word, starting with a letter, followed
948 by letters, numbers, '-' or '_'.
950 If REPLACE is a string, the tag will simply be appended to create the link.
951 If the string contains \"%s\", the tag will be inserted there. Alternatively,
952 the placeholder \"%h\" will cause a url-encoded version of the tag to
953 be inserted at that point (see the function `url-hexify-string').
955 REPLACE may also be a function that will be called with the tag as the
956 only argument to create the link, which should be returned as a string.
958 See the manual for examples."
959 :group 'org-link
960 :type '(repeat
961 (cons
962 (string :tag "Protocol")
963 (choice
964 (string :tag "Format")
965 (function)))))
967 (defcustom org-descriptive-links t
968 "Non-nil means, hide link part and only show description of bracket links.
969 Bracket links are like [[link][description]]. This variable sets the initial
970 state in new org-mode buffers. The setting can then be toggled on a
971 per-buffer basis from the Org->Hyperlinks menu."
972 :group 'org-link
973 :type 'boolean)
975 (defcustom org-link-file-path-type 'adaptive
976 "How the path name in file links should be stored.
977 Valid values are:
979 relative Relative to the current directory, i.e. the directory of the file
980 into which the link is being inserted.
981 absolute Absolute path, if possible with ~ for home directory.
982 noabbrev Absolute path, no abbreviation of home directory.
983 adaptive Use relative path for files in the current directory and sub-
984 directories of it. For other files, use an absolute path."
985 :group 'org-link
986 :type '(choice
987 (const relative)
988 (const absolute)
989 (const noabbrev)
990 (const adaptive)))
992 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
993 "Types of links that should be activated in Org-mode files.
994 This is a list of symbols, each leading to the activation of a certain link
995 type. In principle, it does not hurt to turn on most link types - there may
996 be a small gain when turning off unused link types. The types are:
998 bracket The recommended [[link][description]] or [[link]] links with hiding.
999 angular Links in angular brackets that may contain whitespace like
1000 <bbdb:Carsten Dominik>.
1001 plain Plain links in normal text, no whitespace, like http://google.com.
1002 radio Text that is matched by a radio target, see manual for details.
1003 tag Tag settings in a headline (link to tag search).
1004 date Time stamps (link to calendar).
1005 footnote Footnote labels.
1007 Changing this variable requires a restart of Emacs to become effective."
1008 :group 'org-link
1009 :type '(set :greedy t
1010 (const :tag "Double bracket links (new style)" bracket)
1011 (const :tag "Angular bracket links (old style)" angular)
1012 (const :tag "Plain text links" plain)
1013 (const :tag "Radio target matches" radio)
1014 (const :tag "Tags" tag)
1015 (const :tag "Timestamps" date)
1016 (const :tag "Footnotes" footnote)))
1018 (defcustom org-make-link-description-function nil
1019 "Function to use to generate link descriptions from links. If
1020 nil the link location will be used. This function must take two
1021 parameters; the first is the link and the second the description
1022 org-insert-link has generated, and should return the description
1023 to use."
1024 :group 'org-link
1025 :type 'function)
1027 (defgroup org-link-store nil
1028 "Options concerning storing links in Org-mode."
1029 :tag "Org Store Link"
1030 :group 'org-link)
1032 (defcustom org-email-link-description-format "Email %c: %.30s"
1033 "Format of the description part of a link to an email or usenet message.
1034 The following %-escapes will be replaced by corresponding information:
1036 %F full \"From\" field
1037 %f name, taken from \"From\" field, address if no name
1038 %T full \"To\" field
1039 %t first name in \"To\" field, address if no name
1040 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1041 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1042 %s subject
1043 %m message-id.
1045 You may use normal field width specification between the % and the letter.
1046 This is for example useful to limit the length of the subject.
1048 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1049 :group 'org-link-store
1050 :type 'string)
1052 (defcustom org-from-is-user-regexp
1053 (let (r1 r2)
1054 (when (and user-mail-address (not (string= user-mail-address "")))
1055 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1056 (when (and user-full-name (not (string= user-full-name "")))
1057 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1058 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1059 "Regexp matched against the \"From:\" header of an email or usenet message.
1060 It should match if the message is from the user him/herself."
1061 :group 'org-link-store
1062 :type 'regexp)
1064 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1065 "Non-nil means, storing a link to an Org file will use entry IDs.
1067 Note that before this variable is even considered, org-id must be loaded,
1068 to please customize `org-modules' and turn it on.
1070 The variable can have the following values:
1072 t Create an ID if needed to make a link to the current entry.
1074 create-if-interactive
1075 If `org-store-link' is called directly (interactively, as a user
1076 command), do create an ID to support the link. But when doing the
1077 job for remember, only use the ID if it already exists. The
1078 purpose of this setting is to avoid proliferation of unwanted
1079 IDs, just because you happen to be in an Org file when you
1080 call `org-remember' that automatically and preemptively
1081 creates a link. If you do want to get an ID link in a remember
1082 template to an entry not having an ID, create it first by
1083 explicitly creating a link to it, using `C-c C-l' first.
1085 use-existing
1086 Use existing ID, do not create one.
1088 nil Never use an ID to make a link, instead link using a text search for
1089 the headline text."
1090 :group 'org-link-store
1091 :type '(choice
1092 (const :tag "Create ID to make link" t)
1093 (const :tag "Create if storing link interactively"
1094 create-if-interactive)
1095 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1096 create-if-interactive-and-no-custom-id)
1097 (const :tag "Only use existing" use-existing)
1098 (const :tag "Do not use ID to create link" nil)))
1100 (defcustom org-context-in-file-links t
1101 "Non-nil means, file links from `org-store-link' contain context.
1102 A search string will be added to the file name with :: as separator and
1103 used to find the context when the link is activated by the command
1104 `org-open-at-point'.
1105 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1106 negates this setting for the duration of the command."
1107 :group 'org-link-store
1108 :type 'boolean)
1110 (defcustom org-keep-stored-link-after-insertion nil
1111 "Non-nil means, keep link in list for entire session.
1113 The command `org-store-link' adds a link pointing to the current
1114 location to an internal list. These links accumulate during a session.
1115 The command `org-insert-link' can be used to insert links into any
1116 Org-mode file (offering completion for all stored links). When this
1117 option is nil, every link which has been inserted once using \\[org-insert-link]
1118 will be removed from the list, to make completing the unused links
1119 more efficient."
1120 :group 'org-link-store
1121 :type 'boolean)
1123 (defgroup org-link-follow nil
1124 "Options concerning following links in Org-mode."
1125 :tag "Org Follow Link"
1126 :group 'org-link)
1128 (defcustom org-link-translation-function nil
1129 "Function to translate links with different syntax to Org syntax.
1130 This can be used to translate links created for example by the Planner
1131 or emacs-wiki packages to Org syntax.
1132 The function must accept two parameters, a TYPE containing the link
1133 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1134 which is everything after the link protocol. It should return a cons
1135 with possibly modified values of type and path.
1136 Org contains a function for this, so if you set this variable to
1137 `org-translate-link-from-planner', you should be able follow many
1138 links created by planner."
1139 :group 'org-link-follow
1140 :type 'function)
1142 (defcustom org-follow-link-hook nil
1143 "Hook that is run after a link has been followed."
1144 :group 'org-link-follow
1145 :type 'hook)
1147 (defcustom org-tab-follows-link nil
1148 "Non-nil means, on links TAB will follow the link.
1149 Needs to be set before org.el is loaded.
1150 This really should not be used, it does not make sense, and the
1151 implementation is bad."
1152 :group 'org-link-follow
1153 :type 'boolean)
1155 (defcustom org-return-follows-link nil
1156 "Non-nil means, on links RET will follow the link.
1157 Needs to be set before org.el is loaded."
1158 :group 'org-link-follow
1159 :type 'boolean)
1161 (defcustom org-mouse-1-follows-link
1162 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1163 "Non-nil means, mouse-1 on a link will follow the link.
1164 A longer mouse click will still set point. Does not work on XEmacs.
1165 Needs to be set before org.el is loaded."
1166 :group 'org-link-follow
1167 :type 'boolean)
1169 (defcustom org-mark-ring-length 4
1170 "Number of different positions to be recorded in the ring
1171 Changing this requires a restart of Emacs to work correctly."
1172 :group 'org-link-follow
1173 :type 'integer)
1175 (defcustom org-link-frame-setup
1176 '((vm . vm-visit-folder-other-frame)
1177 (gnus . gnus-other-frame)
1178 (file . find-file-other-window))
1179 "Setup the frame configuration for following links.
1180 When following a link with Emacs, it may often be useful to display
1181 this link in another window or frame. This variable can be used to
1182 set this up for the different types of links.
1183 For VM, use any of
1184 `vm-visit-folder'
1185 `vm-visit-folder-other-frame'
1186 For Gnus, use any of
1187 `gnus'
1188 `gnus-other-frame'
1189 `org-gnus-no-new-news'
1190 For FILE, use any of
1191 `find-file'
1192 `find-file-other-window'
1193 `find-file-other-frame'
1194 For the calendar, use the variable `calendar-setup'.
1195 For BBDB, it is currently only possible to display the matches in
1196 another window."
1197 :group 'org-link-follow
1198 :type '(list
1199 (cons (const vm)
1200 (choice
1201 (const vm-visit-folder)
1202 (const vm-visit-folder-other-window)
1203 (const vm-visit-folder-other-frame)))
1204 (cons (const gnus)
1205 (choice
1206 (const gnus)
1207 (const gnus-other-frame)
1208 (const org-gnus-no-new-news)))
1209 (cons (const file)
1210 (choice
1211 (const find-file)
1212 (const find-file-other-window)
1213 (const find-file-other-frame)))))
1215 (defcustom org-display-internal-link-with-indirect-buffer nil
1216 "Non-nil means, use indirect buffer to display infile links.
1217 Activating internal links (from one location in a file to another location
1218 in the same file) normally just jumps to the location. When the link is
1219 activated with a C-u prefix (or with mouse-3), the link is displayed in
1220 another window. When this option is set, the other window actually displays
1221 an indirect buffer clone of the current buffer, to avoid any visibility
1222 changes to the current buffer."
1223 :group 'org-link-follow
1224 :type 'boolean)
1226 (defcustom org-open-non-existing-files nil
1227 "Non-nil means, `org-open-file' will open non-existing files.
1228 When nil, an error will be generated."
1229 :group 'org-link-follow
1230 :type 'boolean)
1232 (defcustom org-open-directory-means-index-dot-org nil
1233 "Non-nil means, a link to a directory really means to index.org.
1234 When nil, following a directory link will run dired or open a finder/explorer
1235 window on that directory."
1236 :group 'org-link-follow
1237 :type 'boolean)
1239 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1240 "Function and arguments to call for following mailto links.
1241 This is a list with the first element being a lisp function, and the
1242 remaining elements being arguments to the function. In string arguments,
1243 %a will be replaced by the address, and %s will be replaced by the subject
1244 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1245 :group 'org-link-follow
1246 :type '(choice
1247 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1248 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1249 (const :tag "message-mail" (message-mail "%a" "%s"))
1250 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1252 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1253 "Non-nil means, ask for confirmation before executing shell links.
1254 Shell links can be dangerous: just think about a link
1256 [[shell:rm -rf ~/*][Google Search]]
1258 This link would show up in your Org-mode document as \"Google Search\",
1259 but really it would remove your entire home directory.
1260 Therefore we advise against setting this variable to nil.
1261 Just change it to `y-or-n-p' if you want to confirm with a
1262 single keystroke rather than having to type \"yes\"."
1263 :group 'org-link-follow
1264 :type '(choice
1265 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1266 (const :tag "with y-or-n (faster)" y-or-n-p)
1267 (const :tag "no confirmation (dangerous)" nil)))
1269 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1270 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1271 Elisp links can be dangerous: just think about a link
1273 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1275 This link would show up in your Org-mode document as \"Google Search\",
1276 but really it would remove your entire home directory.
1277 Therefore we advise against setting this variable to nil.
1278 Just change it to `y-or-n-p' if you want to confirm with a
1279 single keystroke rather than having to type \"yes\"."
1280 :group 'org-link-follow
1281 :type '(choice
1282 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1283 (const :tag "with y-or-n (faster)" y-or-n-p)
1284 (const :tag "no confirmation (dangerous)" nil)))
1286 (defconst org-file-apps-defaults-gnu
1287 '((remote . emacs)
1288 (system . mailcap)
1289 (t . mailcap))
1290 "Default file applications on a UNIX or GNU/Linux system.
1291 See `org-file-apps'.")
1293 (defconst org-file-apps-defaults-macosx
1294 '((remote . emacs)
1295 (t . "open %s")
1296 (system . "open %s")
1297 ("ps.gz" . "gv %s")
1298 ("eps.gz" . "gv %s")
1299 ("dvi" . "xdvi %s")
1300 ("fig" . "xfig %s"))
1301 "Default file applications on a MacOS X system.
1302 The system \"open\" is known as a default, but we use X11 applications
1303 for some files for which the OS does not have a good default.
1304 See `org-file-apps'.")
1306 (defconst org-file-apps-defaults-windowsnt
1307 (list
1308 '(remote . emacs)
1309 (cons t
1310 (list (if (featurep 'xemacs)
1311 'mswindows-shell-execute
1312 'w32-shell-execute)
1313 "open" 'file))
1314 (cons 'system
1315 (list (if (featurep 'xemacs)
1316 'mswindows-shell-execute
1317 'w32-shell-execute)
1318 "open" 'file)))
1319 "Default file applications on a Windows NT system.
1320 The system \"open\" is used for most files.
1321 See `org-file-apps'.")
1323 (defcustom org-file-apps
1325 (auto-mode . emacs)
1326 ("\\.x?html?\\'" . default)
1327 ("\\.pdf\\'" . default)
1329 "External applications for opening `file:path' items in a document.
1330 Org-mode uses system defaults for different file types, but
1331 you can use this variable to set the application for a given file
1332 extension. The entries in this list are cons cells where the car identifies
1333 files and the cdr the corresponding command. Possible values for the
1334 file identifier are
1335 \"regex\" Regular expression matched against the file name. For backward
1336 compatibility, this can also be a string with only alphanumeric
1337 characters, which is then interpreted as an extension.
1338 `directory' Matches a directory
1339 `remote' Matches a remote file, accessible through tramp or efs.
1340 Remote files most likely should be visited through Emacs
1341 because external applications cannot handle such paths.
1342 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1343 so all files Emacs knows how to handle. Using this with
1344 command `emacs' will open most files in Emacs. Beware that this
1345 will also open html files inside Emacs, unless you add
1346 (\"html\" . default) to the list as well.
1347 t Default for files not matched by any of the other options.
1348 `system' The system command to open files, like `open' on Windows
1349 and Mac OS X, and mailcap under GNU/Linux. This is the command
1350 that will be selected if you call `C-c C-o' with a double
1351 `C-u C-u' prefix.
1353 Possible values for the command are:
1354 `emacs' The file will be visited by the current Emacs process.
1355 `default' Use the default application for this file type, which is the
1356 association for t in the list, most likely in the system-specific
1357 part.
1358 This can be used to overrule an unwanted setting in the
1359 system-specific variable.
1360 `system' Use the system command for opening files, like \"open\".
1361 This command is specified by the entry whose car is `system'.
1362 Most likely, the system-specific version of this variable
1363 does define this command, but you can overrule/replace it
1364 here.
1365 string A command to be executed by a shell; %s will be replaced
1366 by the path to the file.
1367 sexp A Lisp form which will be evaluated. The file path will
1368 be available in the Lisp variable `file'.
1369 For more examples, see the system specific constants
1370 `org-file-apps-defaults-macosx'
1371 `org-file-apps-defaults-windowsnt'
1372 `org-file-apps-defaults-gnu'."
1373 :group 'org-link-follow
1374 :type '(repeat
1375 (cons (choice :value ""
1376 (string :tag "Extension")
1377 (const :tag "System command to open files" system)
1378 (const :tag "Default for unrecognized files" t)
1379 (const :tag "Remote file" remote)
1380 (const :tag "Links to a directory" directory)
1381 (const :tag "Any files that have Emacs modes"
1382 auto-mode))
1383 (choice :value ""
1384 (const :tag "Visit with Emacs" emacs)
1385 (const :tag "Use default" default)
1386 (const :tag "Use the system command" system)
1387 (string :tag "Command")
1388 (sexp :tag "Lisp form")))))
1390 (defgroup org-refile nil
1391 "Options concerning refiling entries in Org-mode."
1392 :tag "Org Refile"
1393 :group 'org)
1395 (defcustom org-directory "~/org"
1396 "Directory with org files.
1397 This is just a default location to look for Org files. There is no need
1398 at all to put your files into this directory. It is only used in the
1399 following situations:
1401 1. When a remember template specifies a target file that is not an
1402 absolute path. The path will then be interpreted relative to
1403 `org-directory'
1404 2. When a remember note is filed away in an interactive way (when exiting the
1405 note buffer with `C-1 C-c C-c'. The the user is prompted for an org file,
1406 with `org-directory' as the default path."
1407 :group 'org-refile
1408 :group 'org-remember
1409 :type 'directory)
1411 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1412 "Default target for storing notes.
1413 Used by the hooks for remember.el. This can be a string, or nil to mean
1414 the value of `remember-data-file'.
1415 You can set this on a per-template basis with the variable
1416 `org-remember-templates'."
1417 :group 'org-refile
1418 :group 'org-remember
1419 :type '(choice
1420 (const :tag "Default from remember-data-file" nil)
1421 file))
1423 (defcustom org-goto-interface 'outline
1424 "The default interface to be used for `org-goto'.
1425 Allowed values are:
1426 outline The interface shows an outline of the relevant file
1427 and the correct heading is found by moving through
1428 the outline or by searching with incremental search.
1429 outline-path-completion Headlines in the current buffer are offered via
1430 completion. This is the interface also used by
1431 the refile command."
1432 :group 'org-refile
1433 :type '(choice
1434 (const :tag "Outline" outline)
1435 (const :tag "Outline-path-completion" outline-path-completion)))
1437 (defcustom org-goto-max-level 5
1438 "Maximum level to be considered when running org-goto with refile interface."
1439 :group 'org-refile
1440 :type 'integer)
1442 (defcustom org-reverse-note-order nil
1443 "Non-nil means, store new notes at the beginning of a file or entry.
1444 When nil, new notes will be filed to the end of a file or entry.
1445 This can also be a list with cons cells of regular expressions that
1446 are matched against file names, and values."
1447 :group 'org-remember
1448 :group 'org-refile
1449 :type '(choice
1450 (const :tag "Reverse always" t)
1451 (const :tag "Reverse never" nil)
1452 (repeat :tag "By file name regexp"
1453 (cons regexp boolean))))
1455 (defcustom org-refile-targets nil
1456 "Targets for refiling entries with \\[org-refile].
1457 This is list of cons cells. Each cell contains:
1458 - a specification of the files to be considered, either a list of files,
1459 or a symbol whose function or variable value will be used to retrieve
1460 a file name or a list of file names. If you use `org-agenda-files' for
1461 that, all agenda files will be scanned for targets. Nil means, consider
1462 headings in the current buffer.
1463 - A specification of how to find candidate refile targets. This may be
1464 any of:
1465 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1466 This tag has to be present in all target headlines, inheritance will
1467 not be considered.
1468 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1469 todo keyword.
1470 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1471 headlines that are refiling targets.
1472 - a cons cell (:level . N). Any headline of level N is considered a target.
1473 Note that, when `org-odd-levels-only' is set, level corresponds to
1474 order in hierarchy, not to the number of stars.
1475 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1476 Note that, when `org-odd-levels-only' is set, level corresponds to
1477 order in hierarchy, not to the number of stars.
1479 You can set the variable `org-refile-target-verify-function' to a function
1480 to verify each headline found by the simple critery above.
1482 When this variable is nil, all top-level headlines in the current buffer
1483 are used, equivalent to the value `((nil . (:level . 1))'."
1484 :group 'org-refile
1485 :type '(repeat
1486 (cons
1487 (choice :value org-agenda-files
1488 (const :tag "All agenda files" org-agenda-files)
1489 (const :tag "Current buffer" nil)
1490 (function) (variable) (file))
1491 (choice :tag "Identify target headline by"
1492 (cons :tag "Specific tag" (const :value :tag) (string))
1493 (cons :tag "TODO keyword" (const :value :todo) (string))
1494 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1495 (cons :tag "Level number" (const :value :level) (integer))
1496 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1498 (defcustom org-refile-target-verify-function nil
1499 "Function to verify if the headline at point should be a refile target.
1500 The function will be called without arguments, with point at the
1501 beginning of the headline. It should return t and leave point
1502 where it is if the headline is a valid target for refiling.
1504 If the target should not be selected, the function must return nil.
1505 In addition to this, it may move point to a place from where the search
1506 should be continued. For example, the function may decide that the entire
1507 subtree of the current entry should be excluded and move point to the end
1508 of the subtree."
1509 :group 'org-refile
1510 :type 'function)
1512 (defcustom org-refile-use-outline-path nil
1513 "Non-nil means, provide refile targets as paths.
1514 So a level 3 headline will be available as level1/level2/level3.
1516 When the value is `file', also include the file name (without directory)
1517 into the path. In this case, you can also stop the completion after
1518 the file name, to get entries inserted as top level in the file.
1520 When `full-file-path', include the full file path."
1521 :group 'org-refile
1522 :type '(choice
1523 (const :tag "Not" nil)
1524 (const :tag "Yes" t)
1525 (const :tag "Start with file name" file)
1526 (const :tag "Start with full file path" full-file-path)))
1528 (defcustom org-outline-path-complete-in-steps t
1529 "Non-nil means, complete the outline path in hierarchical steps.
1530 When Org-mode uses the refile interface to select an outline path
1531 \(see variable `org-refile-use-outline-path'), the completion of
1532 the path can be done is a single go, or if can be done in steps down
1533 the headline hierarchy. Going in steps is probably the best if you
1534 do not use a special completion package like `ido' or `icicles'.
1535 However, when using these packages, going in one step can be very
1536 fast, while still showing the whole path to the entry."
1537 :group 'org-refile
1538 :type 'boolean)
1540 (defcustom org-refile-allow-creating-parent-nodes nil
1541 "Non-nil means, allow to create new nodes as refile targets.
1542 New nodes are then created by adding \"/new node name\" to the completion
1543 of an existing node. When the value of this variable is `confirm',
1544 new node creation must be confirmed by the user (recommended)
1545 When nil, the completion must match an existing entry.
1547 Note that, if the new heading is not seen by the criteria
1548 listed in `org-refile-targets', multiple instances of the same
1549 heading would be created by trying again to file under the new
1550 heading."
1551 :group 'org-refile
1552 :type '(choice
1553 (const :tag "Never" nil)
1554 (const :tag "Always" t)
1555 (const :tag "Prompt for confirmation" confirm)))
1557 (defgroup org-todo nil
1558 "Options concerning TODO items in Org-mode."
1559 :tag "Org TODO"
1560 :group 'org)
1562 (defgroup org-progress nil
1563 "Options concerning Progress logging in Org-mode."
1564 :tag "Org Progress"
1565 :group 'org-time)
1567 (defvar org-todo-interpretation-widgets
1569 (:tag "Sequence (cycling hits every state)" sequence)
1570 (:tag "Type (cycling directly to DONE)" type))
1571 "The available interpretation symbols for customizing
1572 `org-todo-keywords'.
1573 Interested libraries should add to this list.")
1575 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1576 "List of TODO entry keyword sequences and their interpretation.
1577 \\<org-mode-map>This is a list of sequences.
1579 Each sequence starts with a symbol, either `sequence' or `type',
1580 indicating if the keywords should be interpreted as a sequence of
1581 action steps, or as different types of TODO items. The first
1582 keywords are states requiring action - these states will select a headline
1583 for inclusion into the global TODO list Org-mode produces. If one of
1584 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1585 signify that no further action is necessary. If \"|\" is not found,
1586 the last keyword is treated as the only DONE state of the sequence.
1588 The command \\[org-todo] cycles an entry through these states, and one
1589 additional state where no keyword is present. For details about this
1590 cycling, see the manual.
1592 TODO keywords and interpretation can also be set on a per-file basis with
1593 the special #+SEQ_TODO and #+TYP_TODO lines.
1595 Each keyword can optionally specify a character for fast state selection
1596 \(in combination with the variable `org-use-fast-todo-selection')
1597 and specifiers for state change logging, using the same syntax
1598 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1599 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1600 indicates to record a time stamp each time this state is selected.
1602 Each keyword may also specify if a timestamp or a note should be
1603 recorded when entering or leaving the state, by adding additional
1604 characters in the parenthesis after the keyword. This looks like this:
1605 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1606 record only the time of the state change. With X and Y being either
1607 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1608 Y when leaving the state if and only if the *target* state does not
1609 define X. You may omit any of the fast-selection key or X or /Y,
1610 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1612 For backward compatibility, this variable may also be just a list
1613 of keywords - in this case the interpretation (sequence or type) will be
1614 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1615 :group 'org-todo
1616 :group 'org-keywords
1617 :type '(choice
1618 (repeat :tag "Old syntax, just keywords"
1619 (string :tag "Keyword"))
1620 (repeat :tag "New syntax"
1621 (cons
1622 (choice
1623 :tag "Interpretation"
1624 ;;Quick and dirty way to see
1625 ;;`org-todo-interpretations'. This takes the
1626 ;;place of item arguments
1627 :convert-widget
1628 (lambda (widget)
1629 (widget-put widget
1630 :args (mapcar
1631 #'(lambda (x)
1632 (widget-convert
1633 (cons 'const x)))
1634 org-todo-interpretation-widgets))
1635 widget))
1636 (repeat
1637 (string :tag "Keyword"))))))
1639 (defvar org-todo-keywords-1 nil
1640 "All TODO and DONE keywords active in a buffer.")
1641 (make-variable-buffer-local 'org-todo-keywords-1)
1642 (defvar org-todo-keywords-for-agenda nil)
1643 (defvar org-done-keywords-for-agenda nil)
1644 (defvar org-todo-keyword-alist-for-agenda nil)
1645 (defvar org-tag-alist-for-agenda nil)
1646 (defvar org-agenda-contributing-files nil)
1647 (defvar org-not-done-keywords nil)
1648 (make-variable-buffer-local 'org-not-done-keywords)
1649 (defvar org-done-keywords nil)
1650 (make-variable-buffer-local 'org-done-keywords)
1651 (defvar org-todo-heads nil)
1652 (make-variable-buffer-local 'org-todo-heads)
1653 (defvar org-todo-sets nil)
1654 (make-variable-buffer-local 'org-todo-sets)
1655 (defvar org-todo-log-states nil)
1656 (make-variable-buffer-local 'org-todo-log-states)
1657 (defvar org-todo-kwd-alist nil)
1658 (make-variable-buffer-local 'org-todo-kwd-alist)
1659 (defvar org-todo-key-alist nil)
1660 (make-variable-buffer-local 'org-todo-key-alist)
1661 (defvar org-todo-key-trigger nil)
1662 (make-variable-buffer-local 'org-todo-key-trigger)
1664 (defcustom org-todo-interpretation 'sequence
1665 "Controls how TODO keywords are interpreted.
1666 This variable is in principle obsolete and is only used for
1667 backward compatibility, if the interpretation of todo keywords is
1668 not given already in `org-todo-keywords'. See that variable for
1669 more information."
1670 :group 'org-todo
1671 :group 'org-keywords
1672 :type '(choice (const sequence)
1673 (const type)))
1675 (defcustom org-use-fast-todo-selection t
1676 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1677 This variable describes if and under what circumstances the cycling
1678 mechanism for TODO keywords will be replaced by a single-key, direct
1679 selection scheme.
1681 When nil, fast selection is never used.
1683 When the symbol `prefix', it will be used when `org-todo' is called with
1684 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1685 in an agenda buffer.
1687 When t, fast selection is used by default. In this case, the prefix
1688 argument forces cycling instead.
1690 In all cases, the special interface is only used if access keys have actually
1691 been assigned by the user, i.e. if keywords in the configuration are followed
1692 by a letter in parenthesis, like TODO(t)."
1693 :group 'org-todo
1694 :type '(choice
1695 (const :tag "Never" nil)
1696 (const :tag "By default" t)
1697 (const :tag "Only with C-u C-c C-t" prefix)))
1699 (defcustom org-provide-todo-statistics t
1700 "Non-nil means, update todo statistics after insert and toggle.
1701 When this is set, todo statistics is updated in the parent of the current
1702 entry each time a todo state is changed."
1703 :group 'org-todo
1704 :type 'boolean)
1706 (defcustom org-hierarchical-todo-statistics t
1707 "Non-nil means, TODO statistics covers just direct children.
1708 When nil, all entries in the subtree are considered.
1709 This has only an effect if `org-provide-todo-statistics' is set."
1710 :group 'org-todo
1711 :type 'boolean)
1713 (defcustom org-after-todo-state-change-hook nil
1714 "Hook which is run after the state of a TODO item was changed.
1715 The new state (a string with a TODO keyword, or nil) is available in the
1716 Lisp variable `state'."
1717 :group 'org-todo
1718 :type 'hook)
1720 (defvar org-blocker-hook nil
1721 "Hook for functions that are allowed to block a state change.
1723 Each function gets as its single argument a property list, see
1724 `org-trigger-hook' for more information about this list.
1726 If any of the functions in this hook returns nil, the state change
1727 is blocked.")
1729 (defvar org-trigger-hook nil
1730 "Hook for functions that are triggered by a state change.
1732 Each function gets as its single argument a property list with at least
1733 the following elements:
1735 (:type type-of-change :position pos-at-entry-start
1736 :from old-state :to new-state)
1738 Depending on the type, more properties may be present.
1740 This mechanism is currently implemented for:
1742 TODO state changes
1743 ------------------
1744 :type todo-state-change
1745 :from previous state (keyword as a string), or nil, or a symbol
1746 'todo' or 'done', to indicate the general type of state.
1747 :to new state, like in :from")
1749 (defcustom org-enforce-todo-dependencies nil
1750 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1751 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1752 be blocked if any prior sibling is not yet done.
1753 Finally, if the parent is blocked because of ordered siblings of its own,
1754 the child will also be blocked.
1755 This variable needs to be set before org.el is loaded, and you need to
1756 restart Emacs after a change to make the change effective. The only way
1757 to change is while Emacs is running is through the customize interface."
1758 :set (lambda (var val)
1759 (set var val)
1760 (if val
1761 (add-hook 'org-blocker-hook
1762 'org-block-todo-from-children-or-siblings-or-parent)
1763 (remove-hook 'org-blocker-hook
1764 'org-block-todo-from-children-or-siblings-or-parent)))
1765 :group 'org-todo
1766 :type 'boolean)
1768 (defcustom org-enforce-todo-checkbox-dependencies nil
1769 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1770 When this is nil, checkboxes have no influence on switching TODO states.
1771 When non-nil, you first need to check off all check boxes before the TODO
1772 entry can be switched to DONE.
1773 This variable needs to be set before org.el is loaded, and you need to
1774 restart Emacs after a change to make the change effective. The only way
1775 to change is while Emacs is running is through the customize interface."
1776 :set (lambda (var val)
1777 (set var val)
1778 (if val
1779 (add-hook 'org-blocker-hook
1780 'org-block-todo-from-checkboxes)
1781 (remove-hook 'org-blocker-hook
1782 'org-block-todo-from-checkboxes)))
1783 :group 'org-todo
1784 :type 'boolean)
1786 (defcustom org-treat-insert-todo-heading-as-state-change nil
1787 "Non-nil means, inserting a TODO heading is treated as state change.
1788 So when the command \\[org-insert-todo-heading] is used, state change
1789 logging will apply if appropriate. When nil, the new TODO item will
1790 be inserted directly, and no logging will take place."
1791 :group 'org-todo
1792 :type 'boolean)
1794 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1795 "Non-nil means, switching TODO states with S-cursor counts as state change.
1796 This is the default behavior. However, setting this to nil allows a
1797 convenient way to select a TODO state and bypass any logging associated
1798 with that."
1799 :group 'org-todo
1800 :type 'boolean)
1802 (defcustom org-todo-state-tags-triggers nil
1803 "Tag changes that should be triggered by TODO state changes.
1804 This is a list. Each entry is
1806 (state-change (tag . flag) .......)
1808 State-change can be a string with a state, and empty string to indicate the
1809 state that has no TODO keyword, or it can be one of the symbols `todo'
1810 or `done', meaning any not-done or done state, respectively."
1811 :group 'org-todo
1812 :group 'org-tags
1813 :type '(repeat
1814 (cons (choice :tag "When changing to"
1815 (const :tag "Not-done state" todo)
1816 (const :tag "Done state" done)
1817 (string :tag "State"))
1818 (repeat
1819 (cons :tag "Tag action"
1820 (string :tag "Tag")
1821 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1823 (defcustom org-log-done nil
1824 "Information to record when a task moves to the DONE state.
1826 Possible values are:
1828 nil Don't add anything, just change the keyword
1829 time Add a time stamp to the task
1830 note Prompt a closing note and add it with template `org-log-note-headings'
1832 This option can also be set with on a per-file-basis with
1834 #+STARTUP: nologdone
1835 #+STARTUP: logdone
1836 #+STARTUP: lognotedone
1838 You can have local logging settings for a subtree by setting the LOGGING
1839 property to one or more of these keywords."
1840 :group 'org-todo
1841 :group 'org-progress
1842 :type '(choice
1843 (const :tag "No logging" nil)
1844 (const :tag "Record CLOSED timestamp" time)
1845 (const :tag "Record CLOSED timestamp with closing note." note)))
1847 ;; Normalize old uses of org-log-done.
1848 (cond
1849 ((eq org-log-done t) (setq org-log-done 'time))
1850 ((and (listp org-log-done) (memq 'done org-log-done))
1851 (setq org-log-done 'note)))
1853 (defcustom org-log-note-clock-out nil
1854 "Non-nil means, record a note when clocking out of an item.
1855 This can also be configured on a per-file basis by adding one of
1856 the following lines anywhere in the buffer:
1858 #+STARTUP: lognoteclock-out
1859 #+STARTUP: nolognoteclock-out"
1860 :group 'org-todo
1861 :group 'org-progress
1862 :type 'boolean)
1864 (defcustom org-log-done-with-time t
1865 "Non-nil means, the CLOSED time stamp will contain date and time.
1866 When nil, only the date will be recorded."
1867 :group 'org-progress
1868 :type 'boolean)
1870 (defcustom org-log-note-headings
1871 '((done . "CLOSING NOTE %t")
1872 (state . "State %-12s from %-12S %t")
1873 (note . "Note taken on %t")
1874 (clock-out . ""))
1875 "Headings for notes added to entries.
1876 The value is an alist, with the car being a symbol indicating the note
1877 context, and the cdr is the heading to be used. The heading may also be the
1878 empty string.
1879 %t in the heading will be replaced by a time stamp.
1880 %s will be replaced by the new TODO state, in double quotes.
1881 %S will be replaced by the old TODO state, in double quotes.
1882 %u will be replaced by the user name.
1883 %U will be replaced by the full user name."
1884 :group 'org-todo
1885 :group 'org-progress
1886 :type '(list :greedy t
1887 (cons (const :tag "Heading when closing an item" done) string)
1888 (cons (const :tag
1889 "Heading when changing todo state (todo sequence only)"
1890 state) string)
1891 (cons (const :tag "Heading when just taking a note" note) string)
1892 (cons (const :tag "Heading when clocking out" clock-out) string)))
1894 (unless (assq 'note org-log-note-headings)
1895 (push '(note . "%t") org-log-note-headings))
1897 (defcustom org-log-into-drawer nil
1898 "Non-nil means, insert state change notes and time stamps into a drawer.
1899 When nil, state changes notes will be inserted after the headline and
1900 any scheduling and clock lines, but not inside a drawer.
1902 The value of this variable should be the name of the drawer to use.
1903 LOGBOOK is proposed at the default drawer for this purpose, you can
1904 also set this to a string to define the drawer of your choice.
1906 A value of t is also allowed, representing \"LOGBOOK\".
1908 If this variable is set, `org-log-state-notes-insert-after-drawers'
1909 will be ignored.
1911 You can set the property LOG_INTO_DRAWER to overrule this setting for
1912 a subtree."
1913 :group 'org-todo
1914 :group 'org-progress
1915 :type '(choice
1916 (const :tag "Not into a drawer" nil)
1917 (const :tag "LOGBOOK" t)
1918 (string :tag "Other")))
1920 (if (fboundp 'defvaralias)
1921 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
1923 (defun org-log-into-drawer ()
1924 "Return the value of `org-log-into-drawer', but let properties overrule.
1925 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
1926 used instead of the default value."
1927 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
1928 (cond
1929 ((or (not p) (equal p "nil")) org-log-into-drawer)
1930 ((equal p "t") "LOGBOOK")
1931 (t p))))
1933 (defcustom org-log-state-notes-insert-after-drawers nil
1934 "Non-nil means, insert state change notes after any drawers in entry.
1935 Only the drawers that *immediately* follow the headline and the
1936 deadline/scheduled line are skipped.
1937 When nil, insert notes right after the heading and perhaps the line
1938 with deadline/scheduling if present.
1940 This variable will have no effect if `org-log-into-drawer' is
1941 set."
1942 :group 'org-todo
1943 :group 'org-progress
1944 :type 'boolean)
1946 (defcustom org-log-states-order-reversed t
1947 "Non-nil means, the latest state change note will be directly after heading.
1948 When nil, the notes will be orderer according to time."
1949 :group 'org-todo
1950 :group 'org-progress
1951 :type 'boolean)
1953 (defcustom org-log-repeat 'time
1954 "Non-nil means, record moving through the DONE state when triggering repeat.
1955 An auto-repeating tasks is immediately switched back to TODO when marked
1956 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1957 the TODO keyword definition, or recording a closing note by setting
1958 `org-log-done', there will be no record of the task moving through DONE.
1959 This variable forces taking a note anyway. Possible values are:
1961 nil Don't force a record
1962 time Record a time stamp
1963 note Record a note
1965 This option can also be set with on a per-file-basis with
1967 #+STARTUP: logrepeat
1968 #+STARTUP: lognoterepeat
1969 #+STARTUP: nologrepeat
1971 You can have local logging settings for a subtree by setting the LOGGING
1972 property to one or more of these keywords."
1973 :group 'org-todo
1974 :group 'org-progress
1975 :type '(choice
1976 (const :tag "Don't force a record" nil)
1977 (const :tag "Force recording the DONE state" time)
1978 (const :tag "Force recording a note with the DONE state" note)))
1981 (defgroup org-priorities nil
1982 "Priorities in Org-mode."
1983 :tag "Org Priorities"
1984 :group 'org-todo)
1986 (defcustom org-enable-priority-commands t
1987 "Non-nil means, priority commands are active.
1988 When nil, these commands will be disabled, so that you never accidentally
1989 set a priority."
1990 :group 'org-priorities
1991 :type 'boolean)
1993 (defcustom org-highest-priority ?A
1994 "The highest priority of TODO items. A character like ?A, ?B etc.
1995 Must have a smaller ASCII number than `org-lowest-priority'."
1996 :group 'org-priorities
1997 :type 'character)
1999 (defcustom org-lowest-priority ?C
2000 "The lowest priority of TODO items. A character like ?A, ?B etc.
2001 Must have a larger ASCII number than `org-highest-priority'."
2002 :group 'org-priorities
2003 :type 'character)
2005 (defcustom org-default-priority ?B
2006 "The default priority of TODO items.
2007 This is the priority an item get if no explicit priority is given."
2008 :group 'org-priorities
2009 :type 'character)
2011 (defcustom org-priority-start-cycle-with-default t
2012 "Non-nil means, start with default priority when starting to cycle.
2013 When this is nil, the first step in the cycle will be (depending on the
2014 command used) one higher or lower that the default priority."
2015 :group 'org-priorities
2016 :type 'boolean)
2018 (defgroup org-time nil
2019 "Options concerning time stamps and deadlines in Org-mode."
2020 :tag "Org Time"
2021 :group 'org)
2023 (defcustom org-insert-labeled-timestamps-at-point nil
2024 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
2025 When nil, these labeled time stamps are forces into the second line of an
2026 entry, just after the headline. When scheduling from the global TODO list,
2027 the time stamp will always be forced into the second line."
2028 :group 'org-time
2029 :type 'boolean)
2031 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2032 "Formats for `format-time-string' which are used for time stamps.
2033 It is not recommended to change this constant.")
2035 (defcustom org-time-stamp-rounding-minutes '(0 5)
2036 "Number of minutes to round time stamps to.
2037 These are two values, the first applies when first creating a time stamp.
2038 The second applies when changing it with the commands `S-up' and `S-down'.
2039 When changing the time stamp, this means that it will change in steps
2040 of N minutes, as given by the second value.
2042 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2043 numbers should be factors of 60, so for example 5, 10, 15.
2045 When this is larger than 1, you can still force an exact time-stamp by using
2046 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2047 and by using a prefix arg to `S-up/down' to specify the exact number
2048 of minutes to shift."
2049 :group 'org-time
2050 :get '(lambda (var) ; Make sure all entries have 5 elements
2051 (if (integerp (default-value var))
2052 (list (default-value var) 5)
2053 (default-value var)))
2054 :type '(list
2055 (integer :tag "when inserting times")
2056 (integer :tag "when modifying times")))
2058 ;; Normalize old customizations of this variable.
2059 (when (integerp org-time-stamp-rounding-minutes)
2060 (setq org-time-stamp-rounding-minutes
2061 (list org-time-stamp-rounding-minutes
2062 org-time-stamp-rounding-minutes)))
2064 (defcustom org-display-custom-times nil
2065 "Non-nil means, overlay custom formats over all time stamps.
2066 The formats are defined through the variable `org-time-stamp-custom-formats'.
2067 To turn this on on a per-file basis, insert anywhere in the file:
2068 #+STARTUP: customtime"
2069 :group 'org-time
2070 :set 'set-default
2071 :type 'sexp)
2072 (make-variable-buffer-local 'org-display-custom-times)
2074 (defcustom org-time-stamp-custom-formats
2075 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2076 "Custom formats for time stamps. See `format-time-string' for the syntax.
2077 These are overlayed over the default ISO format if the variable
2078 `org-display-custom-times' is set. Time like %H:%M should be at the
2079 end of the second format. The custom formats are also honored by export
2080 commands, if custom time display is turned on at the time of export."
2081 :group 'org-time
2082 :type 'sexp)
2084 (defun org-time-stamp-format (&optional long inactive)
2085 "Get the right format for a time string."
2086 (let ((f (if long (cdr org-time-stamp-formats)
2087 (car org-time-stamp-formats))))
2088 (if inactive
2089 (concat "[" (substring f 1 -1) "]")
2090 f)))
2092 (defcustom org-time-clocksum-format "%d:%02d"
2093 "The format string used when creating CLOCKSUM lines, or when
2094 org-mode generates a time duration."
2095 :group 'org-time
2096 :type 'string)
2098 (defcustom org-deadline-warning-days 14
2099 "No. of days before expiration during which a deadline becomes active.
2100 This variable governs the display in sparse trees and in the agenda.
2101 When 0 or negative, it means use this number (the absolute value of it)
2102 even if a deadline has a different individual lead time specified.
2104 Custom commands can set this variable in the options section."
2105 :group 'org-time
2106 :group 'org-agenda-daily/weekly
2107 :type 'integer)
2109 (defcustom org-read-date-prefer-future t
2110 "Non-nil means, assume future for incomplete date input from user.
2111 This affects the following situations:
2112 1. The user gives a day, but no month.
2113 For example, if today is the 15th, and you enter \"3\", Org-mode will
2114 read this as the third of *next* month. However, if you enter \"17\",
2115 it will be considered as *this* month.
2116 2. The user gives a month but not a year.
2117 For example, if it is april and you enter \"feb 2\", this will be read
2118 as feb 2, *next* year. \"May 5\", however, will be this year.
2120 Currently this does not work for ISO week specifications.
2122 When this option is nil, the current month and year will always be used
2123 as defaults."
2124 :group 'org-time
2125 :type 'boolean)
2127 (defcustom org-read-date-display-live t
2128 "Non-nil means, display current interpretation of date prompt live.
2129 This display will be in an overlay, in the minibuffer."
2130 :group 'org-time
2131 :type 'boolean)
2133 (defcustom org-read-date-popup-calendar t
2134 "Non-nil means, pop up a calendar when prompting for a date.
2135 In the calendar, the date can be selected with mouse-1. However, the
2136 minibuffer will also be active, and you can simply enter the date as well.
2137 When nil, only the minibuffer will be available."
2138 :group 'org-time
2139 :type 'boolean)
2140 (if (fboundp 'defvaralias)
2141 (defvaralias 'org-popup-calendar-for-date-prompt
2142 'org-read-date-popup-calendar))
2144 (defcustom org-read-date-minibuffer-setup-hook nil
2145 "Hook to be used to set up keys for the date/time interface.
2146 Add key definitions to `minibuffer-local-map', which will be a temporary
2147 copy."
2148 :group 'org-time
2149 :type 'hook)
2151 (defcustom org-extend-today-until 0
2152 "The hour when your day really ends. Must be an integer.
2153 This has influence for the following applications:
2154 - When switching the agenda to \"today\". It it is still earlier than
2155 the time given here, the day recognized as TODAY is actually yesterday.
2156 - When a date is read from the user and it is still before the time given
2157 here, the current date and time will be assumed to be yesterday, 23:59.
2158 Also, timestamps inserted in remember templates follow this rule.
2160 IMPORTANT: This is a feature whose implementation is and likely will
2161 remain incomplete. Really, it is only here because past midnight seems to
2162 be the favorite working time of John Wiegley :-)"
2163 :group 'org-time
2164 :type 'integer)
2166 (defcustom org-edit-timestamp-down-means-later nil
2167 "Non-nil means, S-down will increase the time in a time stamp.
2168 When nil, S-up will increase."
2169 :group 'org-time
2170 :type 'boolean)
2172 (defcustom org-calendar-follow-timestamp-change t
2173 "Non-nil means, make the calendar window follow timestamp changes.
2174 When a timestamp is modified and the calendar window is visible, it will be
2175 moved to the new date."
2176 :group 'org-time
2177 :type 'boolean)
2179 (defgroup org-tags nil
2180 "Options concerning tags in Org-mode."
2181 :tag "Org Tags"
2182 :group 'org)
2184 (defcustom org-tag-alist nil
2185 "List of tags allowed in Org-mode files.
2186 When this list is nil, Org-mode will base TAG input on what is already in the
2187 buffer.
2188 The value of this variable is an alist, the car of each entry must be a
2189 keyword as a string, the cdr may be a character that is used to select
2190 that tag through the fast-tag-selection interface.
2191 See the manual for details."
2192 :group 'org-tags
2193 :type '(repeat
2194 (choice
2195 (cons (string :tag "Tag name")
2196 (character :tag "Access char"))
2197 (const :tag "Start radio group" (:startgroup))
2198 (const :tag "End radio group" (:endgroup))
2199 (const :tag "New line" (:newline)))))
2201 (defcustom org-tag-persistent-alist nil
2202 "List of tags that will always appear in all Org-mode files.
2203 This is in addition to any in buffer settings or customizations
2204 of `org-tag-alist'.
2205 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2206 The value of this variable is an alist, the car of each entry must be a
2207 keyword as a string, the cdr may be a character that is used to select
2208 that tag through the fast-tag-selection interface.
2209 See the manual for details.
2210 To disable these tags on a per-file basis, insert anywhere in the file:
2211 #+STARTUP: noptag"
2212 :group 'org-tags
2213 :type '(repeat
2214 (choice
2215 (cons (string :tag "Tag name")
2216 (character :tag "Access char"))
2217 (const :tag "Start radio group" (:startgroup))
2218 (const :tag "End radio group" (:endgroup))
2219 (const :tag "New line" (:newline)))))
2221 (defvar org-file-tags nil
2222 "List of tags that can be inherited by all entries in the file.
2223 The tags will be inherited if the variable `org-use-tag-inheritance'
2224 says they should be.
2225 This variable is populated from #+TAG lines.")
2227 (defcustom org-use-fast-tag-selection 'auto
2228 "Non-nil means, use fast tag selection scheme.
2229 This is a special interface to select and deselect tags with single keys.
2230 When nil, fast selection is never used.
2231 When the symbol `auto', fast selection is used if and only if selection
2232 characters for tags have been configured, either through the variable
2233 `org-tag-alist' or through a #+TAGS line in the buffer.
2234 When t, fast selection is always used and selection keys are assigned
2235 automatically if necessary."
2236 :group 'org-tags
2237 :type '(choice
2238 (const :tag "Always" t)
2239 (const :tag "Never" nil)
2240 (const :tag "When selection characters are configured" 'auto)))
2242 (defcustom org-fast-tag-selection-single-key nil
2243 "Non-nil means, fast tag selection exits after first change.
2244 When nil, you have to press RET to exit it.
2245 During fast tag selection, you can toggle this flag with `C-c'.
2246 This variable can also have the value `expert'. In this case, the window
2247 displaying the tags menu is not even shown, until you press C-c again."
2248 :group 'org-tags
2249 :type '(choice
2250 (const :tag "No" nil)
2251 (const :tag "Yes" t)
2252 (const :tag "Expert" expert)))
2254 (defvar org-fast-tag-selection-include-todo nil
2255 "Non-nil means, fast tags selection interface will also offer TODO states.
2256 This is an undocumented feature, you should not rely on it.")
2258 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2259 "The column to which tags should be indented in a headline.
2260 If this number is positive, it specifies the column. If it is negative,
2261 it means that the tags should be flushright to that column. For example,
2262 -80 works well for a normal 80 character screen."
2263 :group 'org-tags
2264 :type 'integer)
2266 (defcustom org-auto-align-tags t
2267 "Non-nil means, realign tags after pro/demotion of TODO state change.
2268 These operations change the length of a headline and therefore shift
2269 the tags around. With this options turned on, after each such operation
2270 the tags are again aligned to `org-tags-column'."
2271 :group 'org-tags
2272 :type 'boolean)
2274 (defcustom org-use-tag-inheritance t
2275 "Non-nil means, tags in levels apply also for sublevels.
2276 When nil, only the tags directly given in a specific line apply there.
2277 This may also be a list of tags that should be inherited, or a regexp that
2278 matches tags that should be inherited. Additional control is possible
2279 with the variable `org-tags-exclude-from-inheritance' which gives an
2280 explicit list of tags to be excluded from inheritance., even if the value of
2281 `org-use-tag-inheritance' would select it for inheritance.
2283 If this option is t, a match early-on in a tree can lead to a large
2284 number of matches in the subtree when constructing the agenda or creating
2285 a sparse tree. If you only want to see the first match in a tree during
2286 a search, check out the variable `org-tags-match-list-sublevels'."
2287 :group 'org-tags
2288 :type '(choice
2289 (const :tag "Not" nil)
2290 (const :tag "Always" t)
2291 (repeat :tag "Specific tags" (string :tag "Tag"))
2292 (regexp :tag "Tags matched by regexp")))
2294 (defcustom org-tags-exclude-from-inheritance nil
2295 "List of tags that should never be inherited.
2296 This is a way to exclude a few tags from inheritance. For way to do
2297 the opposite, to actively allow inheritance for selected tags,
2298 see the variable `org-use-tag-inheritance'."
2299 :group 'org-tags
2300 :type '(repeat (string :tag "Tag")))
2302 (defun org-tag-inherit-p (tag)
2303 "Check if TAG is one that should be inherited."
2304 (cond
2305 ((member tag org-tags-exclude-from-inheritance) nil)
2306 ((eq org-use-tag-inheritance t) t)
2307 ((not org-use-tag-inheritance) nil)
2308 ((stringp org-use-tag-inheritance)
2309 (string-match org-use-tag-inheritance tag))
2310 ((listp org-use-tag-inheritance)
2311 (member tag org-use-tag-inheritance))
2312 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2314 (defcustom org-tags-match-list-sublevels t
2315 "Non-nil means list also sublevels of headlines matching a search.
2316 This variable applies to tags/property searches, and also to stuck
2317 projects because this search is based on a tags match as well.
2319 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2320 the sublevels of a headline matching a tag search often also match
2321 the same search. Listing all of them can create very long lists.
2322 Setting this variable to nil causes subtrees of a match to be skipped.
2324 As a special case, if the tag search is restricted to TODO items, the
2325 value of this variable is ignored and sublevels are always checked, to
2326 make sure all corresponding TODO items find their way into the list.
2328 This variable is semi-obsolete and probably should always be true. It
2329 is better to limit inheritance to certain tags using the variables
2330 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2331 :group 'org-tags
2332 :type '(choice
2333 (const :tag "No, don't list them" nil)
2334 (const :tag "Yes, do list them" t)
2335 (const :tag "List them, indented with leading dots" indented)))
2337 (defvar org-tags-history nil
2338 "History of minibuffer reads for tags.")
2339 (defvar org-last-tags-completion-table nil
2340 "The last used completion table for tags.")
2341 (defvar org-after-tags-change-hook nil
2342 "Hook that is run after the tags in a line have changed.")
2344 (defgroup org-properties nil
2345 "Options concerning properties in Org-mode."
2346 :tag "Org Properties"
2347 :group 'org)
2349 (defcustom org-property-format "%-10s %s"
2350 "How property key/value pairs should be formatted by `indent-line'.
2351 When `indent-line' hits a property definition, it will format the line
2352 according to this format, mainly to make sure that the values are
2353 lined-up with respect to each other."
2354 :group 'org-properties
2355 :type 'string)
2357 (defcustom org-use-property-inheritance nil
2358 "Non-nil means, properties apply also for sublevels.
2360 This setting is chiefly used during property searches. Turning it on can
2361 cause significant overhead when doing a search, which is why it is not
2362 on by default.
2364 When nil, only the properties directly given in the current entry count.
2365 When t, every property is inherited. The value may also be a list of
2366 properties that should have inheritance, or a regular expression matching
2367 properties that should be inherited.
2369 However, note that some special properties use inheritance under special
2370 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2371 and the properties ending in \"_ALL\" when they are used as descriptor
2372 for valid values of a property.
2374 Note for programmers:
2375 When querying an entry with `org-entry-get', you can control if inheritance
2376 should be used. By default, `org-entry-get' looks only at the local
2377 properties. You can request inheritance by setting the inherit argument
2378 to t (to force inheritance) or to `selective' (to respect the setting
2379 in this variable)."
2380 :group 'org-properties
2381 :type '(choice
2382 (const :tag "Not" nil)
2383 (const :tag "Always" t)
2384 (repeat :tag "Specific properties" (string :tag "Property"))
2385 (regexp :tag "Properties matched by regexp")))
2387 (defun org-property-inherit-p (property)
2388 "Check if PROPERTY is one that should be inherited."
2389 (cond
2390 ((eq org-use-property-inheritance t) t)
2391 ((not org-use-property-inheritance) nil)
2392 ((stringp org-use-property-inheritance)
2393 (string-match org-use-property-inheritance property))
2394 ((listp org-use-property-inheritance)
2395 (member property org-use-property-inheritance))
2396 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2398 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2399 "The default column format, if no other format has been defined.
2400 This variable can be set on the per-file basis by inserting a line
2402 #+COLUMNS: %25ITEM ....."
2403 :group 'org-properties
2404 :type 'string)
2406 (defcustom org-columns-ellipses ".."
2407 "The ellipses to be used when a field in column view is truncated.
2408 When this is the empty string, as many characters as possible are shown,
2409 but then there will be no visual indication that the field has been truncated.
2410 When this is a string of length N, the last N characters of a truncated
2411 field are replaced by this string. If the column is narrower than the
2412 ellipses string, only part of the ellipses string will be shown."
2413 :group 'org-properties
2414 :type 'string)
2416 (defcustom org-columns-modify-value-for-display-function nil
2417 "Function that modifies values for display in column view.
2418 For example, it can be used to cut out a certain part from a time stamp.
2419 The function must take 2 arguments:
2421 column-title The title of the column (*not* the property name)
2422 value The value that should be modified.
2424 The function should return the value that should be displayed,
2425 or nil if the normal value should be used."
2426 :group 'org-properties
2427 :type 'function)
2429 (defcustom org-effort-property "Effort"
2430 "The property that is being used to keep track of effort estimates.
2431 Effort estimates given in this property need to have the format H:MM."
2432 :group 'org-properties
2433 :group 'org-progress
2434 :type '(string :tag "Property"))
2436 (defconst org-global-properties-fixed
2437 '(("VISIBILITY_ALL" . "folded children content all")
2438 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2439 "List of property/value pairs that can be inherited by any entry.
2441 These are fixed values, for the preset properties. The user variable
2442 that can be used to add to this list is `org-global-properties'.
2444 The entries in this list are cons cells where the car is a property
2445 name and cdr is a string with the value. If the value represents
2446 multiple items like an \"_ALL\" property, separate the items by
2447 spaces.")
2449 (defcustom org-global-properties nil
2450 "List of property/value pairs that can be inherited by any entry.
2452 This list will be combined with the constant `org-global-properties-fixed'.
2454 The entries in this list are cons cells where the car is a property
2455 name and cdr is a string with the value.
2457 You can set buffer-local values for the same purpose in the variable
2458 `org-file-properties' this by adding lines like
2460 #+PROPERTY: NAME VALUE"
2461 :group 'org-properties
2462 :type '(repeat
2463 (cons (string :tag "Property")
2464 (string :tag "Value"))))
2466 (defvar org-file-properties nil
2467 "List of property/value pairs that can be inherited by any entry.
2468 Valid for the current buffer.
2469 This variable is populated from #+PROPERTY lines.")
2470 (make-variable-buffer-local 'org-file-properties)
2472 (defgroup org-agenda nil
2473 "Options concerning agenda views in Org-mode."
2474 :tag "Org Agenda"
2475 :group 'org)
2477 (defvar org-category nil
2478 "Variable used by org files to set a category for agenda display.
2479 Such files should use a file variable to set it, for example
2481 # -*- mode: org; org-category: \"ELisp\"
2483 or contain a special line
2485 #+CATEGORY: ELisp
2487 If the file does not specify a category, then file's base name
2488 is used instead.")
2489 (make-variable-buffer-local 'org-category)
2490 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2492 (defcustom org-agenda-files nil
2493 "The files to be used for agenda display.
2494 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2495 \\[org-remove-file]. You can also use customize to edit the list.
2497 If an entry is a directory, all files in that directory that are matched by
2498 `org-agenda-file-regexp' will be part of the file list.
2500 If the value of the variable is not a list but a single file name, then
2501 the list of agenda files is actually stored and maintained in that file, one
2502 agenda file per line."
2503 :group 'org-agenda
2504 :type '(choice
2505 (repeat :tag "List of files and directories" file)
2506 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2508 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2509 "Regular expression to match files for `org-agenda-files'.
2510 If any element in the list in that variable contains a directory instead
2511 of a normal file, all files in that directory that are matched by this
2512 regular expression will be included."
2513 :group 'org-agenda
2514 :type 'regexp)
2516 (defcustom org-agenda-text-search-extra-files nil
2517 "List of extra files to be searched by text search commands.
2518 These files will be search in addition to the agenda files by the
2519 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2520 Note that these files will only be searched for text search commands,
2521 not for the other agenda views like todo lists, tag searches or the weekly
2522 agenda. This variable is intended to list notes and possibly archive files
2523 that should also be searched by these two commands.
2524 In fact, if the first element in the list is the symbol `agenda-archives',
2525 than all archive files of all agenda files will be added to the search
2526 scope."
2527 :group 'org-agenda
2528 :type '(set :greedy t
2529 (const :tag "Agenda Archives" agenda-archives)
2530 (repeat :inline t (file))))
2532 (if (fboundp 'defvaralias)
2533 (defvaralias 'org-agenda-multi-occur-extra-files
2534 'org-agenda-text-search-extra-files))
2536 (defcustom org-agenda-skip-unavailable-files nil
2537 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2538 A nil value means to remove them, after a query, from the list."
2539 :group 'org-agenda
2540 :type 'boolean)
2542 (defcustom org-calendar-to-agenda-key [?c]
2543 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2544 The command `org-calendar-goto-agenda' will be bound to this key. The
2545 default is the character `c' because then `c' can be used to switch back and
2546 forth between agenda and calendar."
2547 :group 'org-agenda
2548 :type 'sexp)
2550 (defcustom org-calendar-agenda-action-key [?k]
2551 "The key to be installed in `calendar-mode-map' for agenda-action.
2552 The command `org-agenda-action' will be bound to this key. The
2553 default is the character `k' because we use the same key in the agenda."
2554 :group 'org-agenda
2555 :type 'sexp)
2557 (eval-after-load "calendar"
2558 '(progn
2559 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2560 'org-calendar-goto-agenda)
2561 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2562 'org-agenda-action)))
2564 (defgroup org-latex nil
2565 "Options for embedding LaTeX code into Org-mode."
2566 :tag "Org LaTeX"
2567 :group 'org)
2569 (defcustom org-format-latex-options
2570 '(:foreground default :background default :scale 1.0
2571 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2572 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2573 "Options for creating images from LaTeX fragments.
2574 This is a property list with the following properties:
2575 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2576 `default' means use the foreground of the default face.
2577 :background the background color, or \"Transparent\".
2578 `default' means use the background of the default face.
2579 :scale a scaling factor for the size of the images.
2580 :html-foreground, :html-background, :html-scale
2581 the same numbers for HTML export.
2582 :matchers a list indicating which matchers should be used to
2583 find LaTeX fragments. Valid members of this list are:
2584 \"begin\" find environments
2585 \"$1\" find single characters surrounded by $.$
2586 \"$\" find math expressions surrounded by $...$
2587 \"$$\" find math expressions surrounded by $$....$$
2588 \"\\(\" find math expressions surrounded by \\(...\\)
2589 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2590 :group 'org-latex
2591 :type 'plist)
2593 (defcustom org-format-latex-header "\\documentclass{article}
2594 \\usepackage{fullpage} % do not remove
2595 \\usepackage{amssymb}
2596 \\usepackage[usenames]{color}
2597 \\usepackage{amsmath}
2598 \\usepackage{latexsym}
2599 \\usepackage[mathscr]{eucal}
2600 \\pagestyle{empty} % do not remove"
2601 "The document header used for processing LaTeX fragments."
2602 :group 'org-latex
2603 :type 'string)
2606 (defgroup org-font-lock nil
2607 "Font-lock settings for highlighting in Org-mode."
2608 :tag "Org Font Lock"
2609 :group 'org)
2611 (defcustom org-level-color-stars-only nil
2612 "Non-nil means fontify only the stars in each headline.
2613 When nil, the entire headline is fontified.
2614 Changing it requires restart of `font-lock-mode' to become effective
2615 also in regions already fontified."
2616 :group 'org-font-lock
2617 :type 'boolean)
2619 (defcustom org-hide-leading-stars nil
2620 "Non-nil means, hide the first N-1 stars in a headline.
2621 This works by using the face `org-hide' for these stars. This
2622 face is white for a light background, and black for a dark
2623 background. You may have to customize the face `org-hide' to
2624 make this work.
2625 Changing it requires restart of `font-lock-mode' to become effective
2626 also in regions already fontified.
2627 You may also set this on a per-file basis by adding one of the following
2628 lines to the buffer:
2630 #+STARTUP: hidestars
2631 #+STARTUP: showstars"
2632 :group 'org-font-lock
2633 :type 'boolean)
2635 (defcustom org-fontify-done-headline nil
2636 "Non-nil means, change the face of a headline if it is marked DONE.
2637 Normally, only the TODO/DONE keyword indicates the state of a headline.
2638 When this is non-nil, the headline after the keyword is set to the
2639 `org-headline-done' as an additional indication."
2640 :group 'org-font-lock
2641 :type 'boolean)
2643 (defcustom org-fontify-emphasized-text t
2644 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2645 Changing this variable requires a restart of Emacs to take effect."
2646 :group 'org-font-lock
2647 :type 'boolean)
2649 (defcustom org-highlight-latex-fragments-and-specials nil
2650 "Non-nil means, fontify what is treated specially by the exporters."
2651 :group 'org-font-lock
2652 :type 'boolean)
2654 (defcustom org-hide-emphasis-markers nil
2655 "Non-nil mean font-lock should hide the emphasis marker characters."
2656 :group 'org-font-lock
2657 :type 'boolean)
2659 (defvar org-emph-re nil
2660 "Regular expression for matching emphasis.")
2661 (defvar org-verbatim-re nil
2662 "Regular expression for matching verbatim text.")
2663 (defvar org-emphasis-regexp-components) ; defined just below
2664 (defvar org-emphasis-alist) ; defined just below
2665 (defun org-set-emph-re (var val)
2666 "Set variable and compute the emphasis regular expression."
2667 (set var val)
2668 (when (and (boundp 'org-emphasis-alist)
2669 (boundp 'org-emphasis-regexp-components)
2670 org-emphasis-alist org-emphasis-regexp-components)
2671 (let* ((e org-emphasis-regexp-components)
2672 (pre (car e))
2673 (post (nth 1 e))
2674 (border (nth 2 e))
2675 (body (nth 3 e))
2676 (nl (nth 4 e))
2677 (body1 (concat body "*?"))
2678 (markers (mapconcat 'car org-emphasis-alist ""))
2679 (vmarkers (mapconcat
2680 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2681 org-emphasis-alist "")))
2682 ;; make sure special characters appear at the right position in the class
2683 (if (string-match "\\^" markers)
2684 (setq markers (concat (replace-match "" t t markers) "^")))
2685 (if (string-match "-" markers)
2686 (setq markers (concat (replace-match "" t t markers) "-")))
2687 (if (string-match "\\^" vmarkers)
2688 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2689 (if (string-match "-" vmarkers)
2690 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2691 (if (> nl 0)
2692 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2693 (int-to-string nl) "\\}")))
2694 ;; Make the regexp
2695 (setq org-emph-re
2696 (concat "\\([" pre "]\\|^\\)"
2697 "\\("
2698 "\\([" markers "]\\)"
2699 "\\("
2700 "[^" border "]\\|"
2701 "[^" border "]"
2702 body1
2703 "[^" border "]"
2704 "\\)"
2705 "\\3\\)"
2706 "\\([" post "]\\|$\\)"))
2707 (setq org-verbatim-re
2708 (concat "\\([" pre "]\\|^\\)"
2709 "\\("
2710 "\\([" vmarkers "]\\)"
2711 "\\("
2712 "[^" border "]\\|"
2713 "[^" border "]"
2714 body1
2715 "[^" border "]"
2716 "\\)"
2717 "\\3\\)"
2718 "\\([" post "]\\|$\\)")))))
2720 (defcustom org-emphasis-regexp-components
2721 '(" \t('\"{" "- \t.,:!?;'\")}" " \t\r\n,\"'" "." 1)
2722 "Components used to build the regular expression for emphasis.
2723 This is a list with 6 entries. Terminology: In an emphasis string
2724 like \" *strong word* \", we call the initial space PREMATCH, the final
2725 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2726 and \"trong wor\" is the body. The different components in this variable
2727 specify what is allowed/forbidden in each part:
2729 pre Chars allowed as prematch. Beginning of line will be allowed too.
2730 post Chars allowed as postmatch. End of line will be allowed too.
2731 border The chars *forbidden* as border characters.
2732 body-regexp A regexp like \".\" to match a body character. Don't use
2733 non-shy groups here, and don't allow newline here.
2734 newline The maximum number of newlines allowed in an emphasis exp.
2736 Use customize to modify this, or restart Emacs after changing it."
2737 :group 'org-font-lock
2738 :set 'org-set-emph-re
2739 :type '(list
2740 (sexp :tag "Allowed chars in pre ")
2741 (sexp :tag "Allowed chars in post ")
2742 (sexp :tag "Forbidden chars in border ")
2743 (sexp :tag "Regexp for body ")
2744 (integer :tag "number of newlines allowed")
2745 (option (boolean :tag "Please ignore this button"))))
2747 (defcustom org-emphasis-alist
2748 `(("*" bold "<b>" "</b>")
2749 ("/" italic "<i>" "</i>")
2750 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2751 ("=" org-code "<code>" "</code>" verbatim)
2752 ("~" org-verbatim "<code>" "</code>" verbatim)
2753 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2754 "<del>" "</del>")
2756 "Special syntax for emphasized text.
2757 Text starting and ending with a special character will be emphasized, for
2758 example *bold*, _underlined_ and /italic/. This variable sets the marker
2759 characters, the face to be used by font-lock for highlighting in Org-mode
2760 Emacs buffers, and the HTML tags to be used for this.
2761 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
2762 Use customize to modify this, or restart Emacs after changing it."
2763 :group 'org-font-lock
2764 :set 'org-set-emph-re
2765 :type '(repeat
2766 (list
2767 (string :tag "Marker character")
2768 (choice
2769 (face :tag "Font-lock-face")
2770 (plist :tag "Face property list"))
2771 (string :tag "HTML start tag")
2772 (string :tag "HTML end tag")
2773 (option (const verbatim)))))
2775 ;;; Miscellaneous options
2777 (defgroup org-completion nil
2778 "Completion in Org-mode."
2779 :tag "Org Completion"
2780 :group 'org)
2782 (defcustom org-completion-use-ido nil
2783 "Non-nil means, use ido completion wherever possible.
2784 Note that `ido-mode' must be active for this variable to be relevant.
2785 If you decide to turn this variable on, you might well want to turn off
2786 `org-outline-path-complete-in-steps'."
2787 :group 'org-completion
2788 :type 'boolean)
2790 (defcustom org-completion-fallback-command 'hippie-expand
2791 "The expansion command called by \\[org-complete] in normal context.
2792 Normal means, no org-mode-specific context."
2793 :group 'org-completion
2794 :type 'function)
2796 ;;; Functions and variables from ther packages
2797 ;; Declared here to avoid compiler warnings
2799 ;; XEmacs only
2800 (defvar outline-mode-menu-heading)
2801 (defvar outline-mode-menu-show)
2802 (defvar outline-mode-menu-hide)
2803 (defvar zmacs-regions) ; XEmacs regions
2805 ;; Emacs only
2806 (defvar mark-active)
2808 ;; Various packages
2809 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2810 (declare-function calendar-forward-day "cal-move" (arg))
2811 (declare-function calendar-goto-date "cal-move" (date))
2812 (declare-function calendar-goto-today "cal-move" ())
2813 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2814 (defvar calc-embedded-close-formula)
2815 (defvar calc-embedded-open-formula)
2816 (declare-function cdlatex-tab "ext:cdlatex" ())
2817 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2818 (defvar font-lock-unfontify-region-function)
2819 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2820 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2821 (defvar iswitchb-temp-buflist)
2822 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2823 (defvar org-agenda-tags-todo-honor-ignore-options)
2824 (declare-function org-agenda-skip "org-agenda" ())
2825 (declare-function org-format-agenda-item "org-agenda"
2826 (extra txt &optional category tags dotime noprefix remove-re))
2827 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2828 (declare-function org-agenda-change-all-lines "org-agenda"
2829 (newhead hdmarker &optional fixface just-this))
2830 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2831 (declare-function org-agenda-maybe-redo "org-agenda" ())
2832 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2833 (beg end))
2834 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2835 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2836 "org-agenda" (&optional end))
2838 (declare-function parse-time-string "parse-time" (string))
2839 (declare-function remember "remember" (&optional initial))
2840 (declare-function remember-buffer-desc "remember" ())
2841 (declare-function remember-finalize "remember" ())
2842 (defvar remember-save-after-remembering)
2843 (defvar remember-data-file)
2844 (defvar remember-register)
2845 (defvar remember-buffer)
2846 (defvar remember-handler-functions)
2847 (defvar remember-annotation-functions)
2848 (defvar texmathp-why)
2849 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2850 (declare-function table--at-cell-p "table" (position &optional object at-column))
2852 (defvar w3m-current-url)
2853 (defvar w3m-current-title)
2855 (defvar org-latex-regexps)
2857 ;;; Autoload and prepare some org modules
2859 ;; Some table stuff that needs to be defined here, because it is used
2860 ;; by the functions setting up org-mode or checking for table context.
2862 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2863 "Detects an org-type or table-type table.")
2864 (defconst org-table-line-regexp "^[ \t]*|"
2865 "Detects an org-type table line.")
2866 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2867 "Detects an org-type table line.")
2868 (defconst org-table-hline-regexp "^[ \t]*|-"
2869 "Detects an org-type table hline.")
2870 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2871 "Detects a table-type table hline.")
2872 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2873 "Searching from within a table (any type) this finds the first line
2874 outside the table.")
2876 ;; Autoload the functions in org-table.el that are needed by functions here.
2878 (eval-and-compile
2879 (org-autoload "org-table"
2880 '(org-table-align org-table-begin org-table-blank-field
2881 org-table-convert org-table-convert-region org-table-copy-down
2882 org-table-copy-region org-table-create
2883 org-table-create-or-convert-from-region
2884 org-table-create-with-table.el org-table-current-dline
2885 org-table-cut-region org-table-delete-column org-table-edit-field
2886 org-table-edit-formulas org-table-end org-table-eval-formula
2887 org-table-export org-table-field-info
2888 org-table-get-stored-formulas org-table-goto-column
2889 org-table-hline-and-move org-table-import org-table-insert-column
2890 org-table-insert-hline org-table-insert-row org-table-iterate
2891 org-table-justify-field-maybe org-table-kill-row
2892 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2893 org-table-move-column org-table-move-column-left
2894 org-table-move-column-right org-table-move-row
2895 org-table-move-row-down org-table-move-row-up
2896 org-table-next-field org-table-next-row org-table-paste-rectangle
2897 org-table-previous-field org-table-recalculate
2898 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2899 org-table-toggle-coordinate-overlays
2900 org-table-toggle-formula-debugger org-table-wrap-region
2901 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2903 (defun org-at-table-p (&optional table-type)
2904 "Return t if the cursor is inside an org-type table.
2905 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2906 (if org-enable-table-editor
2907 (save-excursion
2908 (beginning-of-line 1)
2909 (looking-at (if table-type org-table-any-line-regexp
2910 org-table-line-regexp)))
2911 nil))
2912 (defsubst org-table-p () (org-at-table-p))
2914 (defun org-at-table.el-p ()
2915 "Return t if and only if we are at a table.el table."
2916 (and (org-at-table-p 'any)
2917 (save-excursion
2918 (goto-char (org-table-begin 'any))
2919 (looking-at org-table1-hline-regexp))))
2920 (defun org-table-recognize-table.el ()
2921 "If there is a table.el table nearby, recognize it and move into it."
2922 (if org-table-tab-recognizes-table.el
2923 (if (org-at-table.el-p)
2924 (progn
2925 (beginning-of-line 1)
2926 (if (looking-at org-table-dataline-regexp)
2928 (if (looking-at org-table1-hline-regexp)
2929 (progn
2930 (beginning-of-line 2)
2931 (if (looking-at org-table-any-border-regexp)
2932 (beginning-of-line -1)))))
2933 (if (re-search-forward "|" (org-table-end t) t)
2934 (progn
2935 (require 'table)
2936 (if (table--at-cell-p (point))
2938 (message "recognizing table.el table...")
2939 (table-recognize-table)
2940 (message "recognizing table.el table...done")))
2941 (error "This should not happen..."))
2943 nil)
2944 nil))
2946 (defun org-at-table-hline-p ()
2947 "Return t if the cursor is inside a hline in a table."
2948 (if org-enable-table-editor
2949 (save-excursion
2950 (beginning-of-line 1)
2951 (looking-at org-table-hline-regexp))
2952 nil))
2954 (defvar org-table-clean-did-remove-column nil)
2956 (defun org-table-map-tables (function)
2957 "Apply FUNCTION to the start of all tables in the buffer."
2958 (save-excursion
2959 (save-restriction
2960 (widen)
2961 (goto-char (point-min))
2962 (while (re-search-forward org-table-any-line-regexp nil t)
2963 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2964 (beginning-of-line 1)
2965 (if (looking-at org-table-line-regexp)
2966 (save-excursion (funcall function)))
2967 (re-search-forward org-table-any-border-regexp nil 1))))
2968 (message "Mapping tables: done"))
2970 ;; Declare and autoload functions from org-exp.el & Co
2972 (declare-function org-default-export-plist "org-exp")
2973 (declare-function org-infile-export-plist "org-exp")
2974 (declare-function org-get-current-options "org-exp")
2975 (eval-and-compile
2976 (org-autoload "org-exp"
2977 '(org-export org-export-visible
2978 org-insert-export-options-template
2979 org-table-clean-before-export))
2980 (org-autoload "org-ascii"
2981 '(org-export-as-ascii org-export-ascii-preprocess
2982 org-export-as-ascii-to-buffer org-replace-region-by-ascii
2983 org-export-region-as-ascii))
2984 (org-autoload "org-html"
2985 '(org-export-as-html-and-open
2986 org-export-as-html-batch org-export-as-html-to-buffer
2987 org-replace-region-by-html org-export-region-as-html
2988 org-export-as-html))
2989 (org-autoload "org-icalendar"
2990 '(org-export-icalendar-this-file
2991 org-export-icalendar-all-agenda-files
2992 org-export-icalendar-combine-agenda-files))
2993 (org-autoload "org-xoxo" '(org-export-as-xoxo)))
2995 ;; Declare and autoload functions from org-agenda.el
2997 (eval-and-compile
2998 (org-autoload "org-agenda"
2999 '(org-agenda org-agenda-list org-search-view
3000 org-todo-list org-tags-view org-agenda-list-stuck-projects
3001 org-diary org-agenda-to-appt
3002 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3004 ;; Autoload org-remember
3006 (eval-and-compile
3007 (org-autoload "org-remember"
3008 '(org-remember-insinuate org-remember-annotation
3009 org-remember-apply-template org-remember org-remember-handler)))
3011 ;; Autoload org-clock.el
3014 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3015 (beg end))
3016 (declare-function org-clock-update-mode-line "org-clock" ())
3017 (defvar org-clock-start-time)
3018 (defvar org-clock-marker (make-marker)
3019 "Marker recording the last clock-in.")
3021 (eval-and-compile
3022 (org-autoload
3023 "org-clock"
3024 '(org-clock-in org-clock-out org-clock-cancel
3025 org-clock-goto org-clock-sum org-clock-display
3026 org-clock-remove-overlays org-clock-report
3027 org-clocktable-shift org-dblock-write:clocktable
3028 org-get-clocktable)))
3030 (defun org-clock-update-time-maybe ()
3031 "If this is a CLOCK line, update it and return t.
3032 Otherwise, return nil."
3033 (interactive)
3034 (save-excursion
3035 (beginning-of-line 1)
3036 (skip-chars-forward " \t")
3037 (when (looking-at org-clock-string)
3038 (let ((re (concat "[ \t]*" org-clock-string
3039 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3040 "\\([ \t]*=>.*\\)?\\)?"))
3041 ts te h m s neg)
3042 (cond
3043 ((not (looking-at re))
3044 nil)
3045 ((not (match-end 2))
3046 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3047 (> org-clock-marker (point))
3048 (<= org-clock-marker (point-at-eol)))
3049 ;; The clock is running here
3050 (setq org-clock-start-time
3051 (apply 'encode-time
3052 (org-parse-time-string (match-string 1))))
3053 (org-clock-update-mode-line)))
3055 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3056 (end-of-line 1)
3057 (setq ts (match-string 1)
3058 te (match-string 3))
3059 (setq s (- (time-to-seconds
3060 (apply 'encode-time (org-parse-time-string te)))
3061 (time-to-seconds
3062 (apply 'encode-time (org-parse-time-string ts))))
3063 neg (< s 0)
3064 s (abs s)
3065 h (floor (/ s 3600))
3066 s (- s (* 3600 h))
3067 m (floor (/ s 60))
3068 s (- s (* 60 s)))
3069 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3070 t))))))
3072 (defun org-check-running-clock ()
3073 "Check if the current buffer contains the running clock.
3074 If yes, offer to stop it and to save the buffer with the changes."
3075 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3076 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3077 (buffer-name))))
3078 (org-clock-out)
3079 (when (y-or-n-p "Save changed buffer?")
3080 (save-buffer))))
3082 (defun org-clocktable-try-shift (dir n)
3083 "Check if this line starts a clock table, if yes, shift the time block."
3084 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3085 (org-clocktable-shift dir n)))
3087 ;; Autoload org-timer.el
3089 (eval-and-compile
3090 (org-autoload
3091 "org-timer"
3092 '(org-timer-start org-timer org-timer-item
3093 org-timer-change-times-in-region)))
3095 ;; Autoload org-feed.el
3097 (eval-and-compile
3098 (org-autoload
3099 "org-feed"
3100 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3103 ;; Autoload archiving code
3104 ;; The stuff that is needed for cycling and tags has to be defined here.
3106 (defgroup org-archive nil
3107 "Options concerning archiving in Org-mode."
3108 :tag "Org Archive"
3109 :group 'org-structure)
3111 (defcustom org-archive-location "%s_archive::"
3112 "The location where subtrees should be archived.
3114 The value of this variable is a string, consisting of two parts,
3115 separated by a double-colon. The first part is a filename and
3116 the second part is a headline.
3118 When the filename is omitted, archiving happens in the same file.
3119 %s in the filename will be replaced by the current file
3120 name (without the directory part). Archiving to a different file
3121 is useful to keep archived entries from contributing to the
3122 Org-mode Agenda.
3124 The archived entries will be filed as subtrees of the specified
3125 headline. When the headline is omitted, the subtrees are simply
3126 filed away at the end of the file, as top-level entries. Also in
3127 the heading you can use %s to represent the file name, this can be
3128 useful when using the same archive for a number of different files.
3130 Here are a few examples:
3131 \"%s_archive::\"
3132 If the current file is Projects.org, archive in file
3133 Projects.org_archive, as top-level trees. This is the default.
3135 \"::* Archived Tasks\"
3136 Archive in the current file, under the top-level headline
3137 \"* Archived Tasks\".
3139 \"~/org/archive.org::\"
3140 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3142 \"~/org/archive.org::From %s\"
3143 Archive in file ~/org/archive.org (absolute path), und headlines
3144 \"From FILENAME\" where file name is the current file name.
3146 \"basement::** Finished Tasks\"
3147 Archive in file ./basement (relative path), as level 3 trees
3148 below the level 2 heading \"** Finished Tasks\".
3150 You may set this option on a per-file basis by adding to the buffer a
3151 line like
3153 #+ARCHIVE: basement::** Finished Tasks
3155 You may also define it locally for a subtree by setting an ARCHIVE property
3156 in the entry. If such a property is found in an entry, or anywhere up
3157 the hierarchy, it will be used."
3158 :group 'org-archive
3159 :type 'string)
3161 (defcustom org-archive-tag "ARCHIVE"
3162 "The tag that marks a subtree as archived.
3163 An archived subtree does not open during visibility cycling, and does
3164 not contribute to the agenda listings.
3165 After changing this, font-lock must be restarted in the relevant buffers to
3166 get the proper fontification."
3167 :group 'org-archive
3168 :group 'org-keywords
3169 :type 'string)
3171 (defcustom org-agenda-skip-archived-trees t
3172 "Non-nil means, the agenda will skip any items located in archived trees.
3173 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3174 variable is no longer recommended, you should leave it at the value t.
3175 Instead, use the key `v' to cycle the archives-mode in the agenda."
3176 :group 'org-archive
3177 :group 'org-agenda-skip
3178 :type 'boolean)
3180 (defcustom org-columns-skip-arrchived-trees t
3181 "Non-nil means, irgnore archived trees when creating column view."
3182 :group 'org-archive
3183 :group 'org-properties
3184 :type 'boolean)
3186 (defcustom org-cycle-open-archived-trees nil
3187 "Non-nil means, `org-cycle' will open archived trees.
3188 An archived tree is a tree marked with the tag ARCHIVE.
3189 When nil, archived trees will stay folded. You can still open them with
3190 normal outline commands like `show-all', but not with the cycling commands."
3191 :group 'org-archive
3192 :group 'org-cycle
3193 :type 'boolean)
3195 (defcustom org-sparse-tree-open-archived-trees nil
3196 "Non-nil means sparse tree construction shows matches in archived trees.
3197 When nil, matches in these trees are highlighted, but the trees are kept in
3198 collapsed state."
3199 :group 'org-archive
3200 :group 'org-sparse-trees
3201 :type 'boolean)
3203 (defun org-cycle-hide-archived-subtrees (state)
3204 "Re-hide all archived subtrees after a visibility state change."
3205 (when (and (not org-cycle-open-archived-trees)
3206 (not (memq state '(overview folded))))
3207 (save-excursion
3208 (let* ((globalp (memq state '(contents all)))
3209 (beg (if globalp (point-min) (point)))
3210 (end (if globalp (point-max) (org-end-of-subtree t))))
3211 (org-hide-archived-subtrees beg end)
3212 (goto-char beg)
3213 (if (looking-at (concat ".*:" org-archive-tag ":"))
3214 (message "%s" (substitute-command-keys
3215 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3217 (defun org-force-cycle-archived ()
3218 "Cycle subtree even if it is archived."
3219 (interactive)
3220 (setq this-command 'org-cycle)
3221 (let ((org-cycle-open-archived-trees t))
3222 (call-interactively 'org-cycle)))
3224 (defun org-hide-archived-subtrees (beg end)
3225 "Re-hide all archived subtrees after a visibility state change."
3226 (save-excursion
3227 (let* ((re (concat ":" org-archive-tag ":")))
3228 (goto-char beg)
3229 (while (re-search-forward re end t)
3230 (and (org-on-heading-p) (hide-subtree))
3231 (org-end-of-subtree t)))))
3233 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3235 (eval-and-compile
3236 (org-autoload "org-archive"
3237 '(org-add-archive-files org-archive-subtree
3238 org-archive-to-archive-sibling org-toggle-archive-tag)))
3240 ;; Autoload Column View Code
3242 (declare-function org-columns-number-to-string "org-colview")
3243 (declare-function org-columns-get-format-and-top-level "org-colview")
3244 (declare-function org-columns-compute "org-colview")
3246 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3247 '(org-columns-number-to-string org-columns-get-format-and-top-level
3248 org-columns-compute org-agenda-columns org-columns-remove-overlays
3249 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3251 ;; Autoload ID code
3253 (declare-function org-id-store-link "org-id")
3254 (declare-function org-id-locations-load "org-id")
3255 (declare-function org-id-locations-save "org-id")
3256 (defvar org-id-track-globally)
3257 (org-autoload "org-id"
3258 '(org-id-get-create org-id-new org-id-copy org-id-get
3259 org-id-get-with-outline-path-completion
3260 org-id-get-with-outline-drilling
3261 org-id-goto org-id-find org-id-store-link))
3263 ;; Autoload Plotting Code
3265 (org-autoload "org-plot"
3266 '(org-plot/gnuplot))
3268 ;;; Variables for pre-computed regular expressions, all buffer local
3270 (defvar org-drawer-regexp nil
3271 "Matches first line of a hidden block.")
3272 (make-variable-buffer-local 'org-drawer-regexp)
3273 (defvar org-todo-regexp nil
3274 "Matches any of the TODO state keywords.")
3275 (make-variable-buffer-local 'org-todo-regexp)
3276 (defvar org-not-done-regexp nil
3277 "Matches any of the TODO state keywords except the last one.")
3278 (make-variable-buffer-local 'org-not-done-regexp)
3279 (defvar org-not-done-heading-regexp nil
3280 "Matches a TODO headline that is not done.")
3281 (make-variable-buffer-local 'org-not-done-regexp)
3282 (defvar org-todo-line-regexp nil
3283 "Matches a headline and puts TODO state into group 2 if present.")
3284 (make-variable-buffer-local 'org-todo-line-regexp)
3285 (defvar org-complex-heading-regexp nil
3286 "Matches a headline and puts everything into groups:
3287 group 1: the stars
3288 group 2: The todo keyword, maybe
3289 group 3: Priority cookie
3290 group 4: True headline
3291 group 5: Tags")
3292 (make-variable-buffer-local 'org-complex-heading-regexp)
3293 (defvar org-todo-line-tags-regexp nil
3294 "Matches a headline and puts TODO state into group 2 if present.
3295 Also put tags into group 4 if tags are present.")
3296 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3297 (defvar org-nl-done-regexp nil
3298 "Matches newline followed by a headline with the DONE keyword.")
3299 (make-variable-buffer-local 'org-nl-done-regexp)
3300 (defvar org-looking-at-done-regexp nil
3301 "Matches the DONE keyword a point.")
3302 (make-variable-buffer-local 'org-looking-at-done-regexp)
3303 (defvar org-ds-keyword-length 12
3304 "Maximum length of the Deadline and SCHEDULED keywords.")
3305 (make-variable-buffer-local 'org-ds-keyword-length)
3306 (defvar org-deadline-regexp nil
3307 "Matches the DEADLINE keyword.")
3308 (make-variable-buffer-local 'org-deadline-regexp)
3309 (defvar org-deadline-time-regexp nil
3310 "Matches the DEADLINE keyword together with a time stamp.")
3311 (make-variable-buffer-local 'org-deadline-time-regexp)
3312 (defvar org-deadline-line-regexp nil
3313 "Matches the DEADLINE keyword and the rest of the line.")
3314 (make-variable-buffer-local 'org-deadline-line-regexp)
3315 (defvar org-scheduled-regexp nil
3316 "Matches the SCHEDULED keyword.")
3317 (make-variable-buffer-local 'org-scheduled-regexp)
3318 (defvar org-scheduled-time-regexp nil
3319 "Matches the SCHEDULED keyword together with a time stamp.")
3320 (make-variable-buffer-local 'org-scheduled-time-regexp)
3321 (defvar org-closed-time-regexp nil
3322 "Matches the CLOSED keyword together with a time stamp.")
3323 (make-variable-buffer-local 'org-closed-time-regexp)
3325 (defvar org-keyword-time-regexp nil
3326 "Matches any of the 4 keywords, together with the time stamp.")
3327 (make-variable-buffer-local 'org-keyword-time-regexp)
3328 (defvar org-keyword-time-not-clock-regexp nil
3329 "Matches any of the 3 keywords, together with the time stamp.")
3330 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3331 (defvar org-maybe-keyword-time-regexp nil
3332 "Matches a timestamp, possibly preceeded by a keyword.")
3333 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3334 (defvar org-planning-or-clock-line-re nil
3335 "Matches a line with planning or clock info.")
3336 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3338 (defconst org-plain-time-of-day-regexp
3339 (concat
3340 "\\(\\<[012]?[0-9]"
3341 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3342 "\\(--?"
3343 "\\(\\<[012]?[0-9]"
3344 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3345 "\\)?")
3346 "Regular expression to match a plain time or time range.
3347 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3348 groups carry important information:
3349 0 the full match
3350 1 the first time, range or not
3351 8 the second time, if it is a range.")
3353 (defconst org-plain-time-extension-regexp
3354 (concat
3355 "\\(\\<[012]?[0-9]"
3356 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3357 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3358 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3359 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3360 groups carry important information:
3361 0 the full match
3362 7 hours of duration
3363 9 minutes of duration")
3365 (defconst org-stamp-time-of-day-regexp
3366 (concat
3367 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3368 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3369 "\\(--?"
3370 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3371 "Regular expression to match a timestamp time or time range.
3372 After a match, the following groups carry important information:
3373 0 the full match
3374 1 date plus weekday, for backreferencing to make sure both times on same day
3375 2 the first time, range or not
3376 4 the second time, if it is a range.")
3378 (defconst org-startup-options
3379 '(("fold" org-startup-folded t)
3380 ("overview" org-startup-folded t)
3381 ("nofold" org-startup-folded nil)
3382 ("showall" org-startup-folded nil)
3383 ("content" org-startup-folded content)
3384 ("hidestars" org-hide-leading-stars t)
3385 ("showstars" org-hide-leading-stars nil)
3386 ("odd" org-odd-levels-only t)
3387 ("oddeven" org-odd-levels-only nil)
3388 ("align" org-startup-align-all-tables t)
3389 ("noalign" org-startup-align-all-tables nil)
3390 ("customtime" org-display-custom-times t)
3391 ("logdone" org-log-done time)
3392 ("lognotedone" org-log-done note)
3393 ("nologdone" org-log-done nil)
3394 ("lognoteclock-out" org-log-note-clock-out t)
3395 ("nolognoteclock-out" org-log-note-clock-out nil)
3396 ("logrepeat" org-log-repeat state)
3397 ("lognoterepeat" org-log-repeat note)
3398 ("nologrepeat" org-log-repeat nil)
3399 ("fninline" org-footnote-define-inline t)
3400 ("nofninline" org-footnote-define-inline nil)
3401 ("fnlocal" org-footnote-section nil)
3402 ("fnauto" org-footnote-auto-label t)
3403 ("fnprompt" org-footnote-auto-label nil)
3404 ("fnconfirm" org-footnote-auto-label confirm)
3405 ("fnplain" org-footnote-auto-label plain)
3406 ("constcgs" constants-unit-system cgs)
3407 ("constSI" constants-unit-system SI)
3408 ("noptag" org-tag-persistent-alist nil)
3409 ("hideblocks" org-hide-block-startup t)
3410 ("nohideblocks" org-hide-block-startup nil))
3411 "Variable associated with STARTUP options for org-mode.
3412 Each element is a list of three items: The startup options as written
3413 in the #+STARTUP line, the corresponding variable, and the value to
3414 set this variable to if the option is found. An optional forth element PUSH
3415 means to push this value onto the list in the variable.")
3417 (defun org-set-regexps-and-options ()
3418 "Precompute regular expressions for current buffer."
3419 (when (org-mode-p)
3420 (org-set-local 'org-todo-kwd-alist nil)
3421 (org-set-local 'org-todo-key-alist nil)
3422 (org-set-local 'org-todo-key-trigger nil)
3423 (org-set-local 'org-todo-keywords-1 nil)
3424 (org-set-local 'org-done-keywords nil)
3425 (org-set-local 'org-todo-heads nil)
3426 (org-set-local 'org-todo-sets nil)
3427 (org-set-local 'org-todo-log-states nil)
3428 (org-set-local 'org-file-properties nil)
3429 (org-set-local 'org-file-tags nil)
3430 (let ((re (org-make-options-regexp
3431 '("CATEGORY" "TODO" "COLUMNS"
3432 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3433 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3434 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3435 (splitre "[ \t]+")
3436 kwds kws0 kwsa key log value cat arch tags const links hw dws
3437 tail sep kws1 prio props ftags drawers
3438 ext-setup-or-nil setup-contents (start 0))
3439 (save-excursion
3440 (save-restriction
3441 (widen)
3442 (goto-char (point-min))
3443 (while (or (and ext-setup-or-nil
3444 (string-match re ext-setup-or-nil start)
3445 (setq start (match-end 0)))
3446 (and (setq ext-setup-or-nil nil start 0)
3447 (re-search-forward re nil t)))
3448 (setq key (upcase (match-string 1 ext-setup-or-nil))
3449 value (org-match-string-no-properties 2 ext-setup-or-nil))
3450 (cond
3451 ((equal key "CATEGORY")
3452 (if (string-match "[ \t]+$" value)
3453 (setq value (replace-match "" t t value)))
3454 (setq cat value))
3455 ((member key '("SEQ_TODO" "TODO"))
3456 (push (cons 'sequence (org-split-string value splitre)) kwds))
3457 ((equal key "TYP_TODO")
3458 (push (cons 'type (org-split-string value splitre)) kwds))
3459 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3460 ;; general TODO-like setup
3461 (push (cons (intern (downcase (match-string 1 key)))
3462 (org-split-string value splitre)) kwds))
3463 ((equal key "TAGS")
3464 (setq tags (append tags (if tags '("\\n") nil)
3465 (org-split-string value splitre))))
3466 ((equal key "COLUMNS")
3467 (org-set-local 'org-columns-default-format value))
3468 ((equal key "LINK")
3469 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3470 (push (cons (match-string 1 value)
3471 (org-trim (match-string 2 value)))
3472 links)))
3473 ((equal key "PRIORITIES")
3474 (setq prio (org-split-string value " +")))
3475 ((equal key "PROPERTY")
3476 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3477 (push (cons (match-string 1 value) (match-string 2 value))
3478 props)))
3479 ((equal key "FILETAGS")
3480 (when (string-match "\\S-" value)
3481 (setq ftags
3482 (append
3483 ftags
3484 (apply 'append
3485 (mapcar (lambda (x) (org-split-string x ":"))
3486 (org-split-string value)))))))
3487 ((equal key "DRAWERS")
3488 (setq drawers (org-split-string value splitre)))
3489 ((equal key "CONSTANTS")
3490 (setq const (append const (org-split-string value splitre))))
3491 ((equal key "STARTUP")
3492 (let ((opts (org-split-string value splitre))
3493 l var val)
3494 (while (setq l (pop opts))
3495 (when (setq l (assoc l org-startup-options))
3496 (setq var (nth 1 l) val (nth 2 l))
3497 (if (not (nth 3 l))
3498 (set (make-local-variable var) val)
3499 (if (not (listp (symbol-value var)))
3500 (set (make-local-variable var) nil))
3501 (set (make-local-variable var) (symbol-value var))
3502 (add-to-list var val))))))
3503 ((equal key "ARCHIVE")
3504 (string-match " *$" value)
3505 (setq arch (replace-match "" t t value))
3506 (remove-text-properties 0 (length arch)
3507 '(face t fontified t) arch))
3508 ((equal key "SETUPFILE")
3509 (setq setup-contents (org-file-contents
3510 (expand-file-name
3511 (org-remove-double-quotes value))
3512 'noerror))
3513 (if (not ext-setup-or-nil)
3514 (setq ext-setup-or-nil setup-contents start 0)
3515 (setq ext-setup-or-nil
3516 (concat (substring ext-setup-or-nil 0 start)
3517 "\n" setup-contents "\n"
3518 (substring ext-setup-or-nil start)))))
3519 ))))
3520 (when cat
3521 (org-set-local 'org-category (intern cat))
3522 (push (cons "CATEGORY" cat) props))
3523 (when prio
3524 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3525 (setq prio (mapcar 'string-to-char prio))
3526 (org-set-local 'org-highest-priority (nth 0 prio))
3527 (org-set-local 'org-lowest-priority (nth 1 prio))
3528 (org-set-local 'org-default-priority (nth 2 prio)))
3529 (and props (org-set-local 'org-file-properties (nreverse props)))
3530 (and ftags (org-set-local 'org-file-tags
3531 (mapcar 'org-add-prop-inherited ftags)))
3532 (and drawers (org-set-local 'org-drawers drawers))
3533 (and arch (org-set-local 'org-archive-location arch))
3534 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3535 ;; Process the TODO keywords
3536 (unless kwds
3537 ;; Use the global values as if they had been given locally.
3538 (setq kwds (default-value 'org-todo-keywords))
3539 (if (stringp (car kwds))
3540 (setq kwds (list (cons org-todo-interpretation
3541 (default-value 'org-todo-keywords)))))
3542 (setq kwds (reverse kwds)))
3543 (setq kwds (nreverse kwds))
3544 (let (inter kws kw)
3545 (while (setq kws (pop kwds))
3546 (let ((kws (or
3547 (run-hook-with-args-until-success
3548 'org-todo-setup-filter-hook kws)
3549 kws)))
3550 (setq inter (pop kws) sep (member "|" kws)
3551 kws0 (delete "|" (copy-sequence kws))
3552 kwsa nil
3553 kws1 (mapcar
3554 (lambda (x)
3555 ;; 1 2
3556 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3557 (progn
3558 (setq kw (match-string 1 x)
3559 key (and (match-end 2) (match-string 2 x))
3560 log (org-extract-log-state-settings x))
3561 (push (cons kw (and key (string-to-char key))) kwsa)
3562 (and log (push log org-todo-log-states))
3564 (error "Invalid TODO keyword %s" x)))
3565 kws0)
3566 kwsa (if kwsa (append '((:startgroup))
3567 (nreverse kwsa)
3568 '((:endgroup))))
3569 hw (car kws1)
3570 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3571 tail (list inter hw (car dws) (org-last dws))))
3572 (add-to-list 'org-todo-heads hw 'append)
3573 (push kws1 org-todo-sets)
3574 (setq org-done-keywords (append org-done-keywords dws nil))
3575 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3576 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3577 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3578 (setq org-todo-sets (nreverse org-todo-sets)
3579 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3580 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3581 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3582 ;; Process the constants
3583 (when const
3584 (let (e cst)
3585 (while (setq e (pop const))
3586 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3587 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3588 (setq org-table-formula-constants-local cst)))
3590 ;; Process the tags.
3591 (when tags
3592 (let (e tgs)
3593 (while (setq e (pop tags))
3594 (cond
3595 ((equal e "{") (push '(:startgroup) tgs))
3596 ((equal e "}") (push '(:endgroup) tgs))
3597 ((equal e "\\n") (push '(:newline) tgs))
3598 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3599 (push (cons (match-string 1 e)
3600 (string-to-char (match-string 2 e)))
3601 tgs))
3602 (t (push (list e) tgs))))
3603 (org-set-local 'org-tag-alist nil)
3604 (while (setq e (pop tgs))
3605 (or (and (stringp (car e))
3606 (assoc (car e) org-tag-alist))
3607 (push e org-tag-alist)))))
3609 ;; Compute the regular expressions and other local variables
3610 (if (not org-done-keywords)
3611 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3612 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3613 (length org-scheduled-string)
3614 (length org-clock-string)
3615 (length org-closed-string)))
3616 org-drawer-regexp
3617 (concat "^[ \t]*:\\("
3618 (mapconcat 'regexp-quote org-drawers "\\|")
3619 "\\):[ \t]*$")
3620 org-not-done-keywords
3621 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3622 org-todo-regexp
3623 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3624 "\\|") "\\)\\>")
3625 org-not-done-regexp
3626 (concat "\\<\\("
3627 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3628 "\\)\\>")
3629 org-not-done-heading-regexp
3630 (concat "^\\(\\*+\\)[ \t]+\\("
3631 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3632 "\\)\\>")
3633 org-todo-line-regexp
3634 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3635 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3636 "\\)\\>\\)?[ \t]*\\(.*\\)")
3637 org-complex-heading-regexp
3638 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3639 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3640 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3641 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3642 org-nl-done-regexp
3643 (concat "\n\\*+[ \t]+"
3644 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3645 "\\)" "\\>")
3646 org-todo-line-tags-regexp
3647 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3648 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3649 (org-re
3650 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3651 org-looking-at-done-regexp
3652 (concat "^" "\\(?:"
3653 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3654 "\\>")
3655 org-deadline-regexp (concat "\\<" org-deadline-string)
3656 org-deadline-time-regexp
3657 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3658 org-deadline-line-regexp
3659 (concat "\\<\\(" org-deadline-string "\\).*")
3660 org-scheduled-regexp
3661 (concat "\\<" org-scheduled-string)
3662 org-scheduled-time-regexp
3663 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3664 org-closed-time-regexp
3665 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3666 org-keyword-time-regexp
3667 (concat "\\<\\(" org-scheduled-string
3668 "\\|" org-deadline-string
3669 "\\|" org-closed-string
3670 "\\|" org-clock-string "\\)"
3671 " *[[<]\\([^]>]+\\)[]>]")
3672 org-keyword-time-not-clock-regexp
3673 (concat "\\<\\(" org-scheduled-string
3674 "\\|" org-deadline-string
3675 "\\|" org-closed-string
3676 "\\)"
3677 " *[[<]\\([^]>]+\\)[]>]")
3678 org-maybe-keyword-time-regexp
3679 (concat "\\(\\<\\(" org-scheduled-string
3680 "\\|" org-deadline-string
3681 "\\|" org-closed-string
3682 "\\|" org-clock-string "\\)\\)?"
3683 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3684 org-planning-or-clock-line-re
3685 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3686 "\\|" org-deadline-string
3687 "\\|" org-closed-string "\\|" org-clock-string
3688 "\\)\\>\\)")
3690 (org-compute-latex-and-specials-regexp)
3691 (org-set-font-lock-defaults))))
3693 (defun org-file-contents (file &optional noerror)
3694 "Return the contents of FILE, as a string."
3695 (if (or (not file)
3696 (not (file-readable-p file)))
3697 (if noerror
3698 (progn
3699 (message "Cannot read file %s" file)
3700 (ding) (sit-for 2)
3702 (error "Cannot read file %s" file))
3703 (with-temp-buffer
3704 (insert-file-contents file)
3705 (buffer-string))))
3707 (defun org-extract-log-state-settings (x)
3708 "Extract the log state setting from a TODO keyword string.
3709 This will extract info from a string like \"WAIT(w@/!)\"."
3710 (let (kw key log1 log2)
3711 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3712 (setq kw (match-string 1 x)
3713 key (and (match-end 2) (match-string 2 x))
3714 log1 (and (match-end 3) (match-string 3 x))
3715 log2 (and (match-end 4) (match-string 4 x)))
3716 (and (or log1 log2)
3717 (list kw
3718 (and log1 (if (equal log1 "!") 'time 'note))
3719 (and log2 (if (equal log2 "!") 'time 'note)))))))
3721 (defun org-remove-keyword-keys (list)
3722 "Remove a pair of parenthesis at the end of each string in LIST."
3723 (mapcar (lambda (x)
3724 (if (string-match "(.*)$" x)
3725 (substring x 0 (match-beginning 0))
3727 list))
3729 ;; FIXME: this could be done much better, using second characters etc.
3730 (defun org-assign-fast-keys (alist)
3731 "Assign fast keys to a keyword-key alist.
3732 Respect keys that are already there."
3733 (let (new e k c c1 c2 (char ?a))
3734 (while (setq e (pop alist))
3735 (cond
3736 ((equal e '(:startgroup)) (push e new))
3737 ((equal e '(:endgroup)) (push e new))
3738 ((equal e '(:newline)) (push e new))
3740 (setq k (car e) c2 nil)
3741 (if (cdr e)
3742 (setq c (cdr e))
3743 ;; automatically assign a character.
3744 (setq c1 (string-to-char
3745 (downcase (substring
3746 k (if (= (string-to-char k) ?@) 1 0)))))
3747 (if (or (rassoc c1 new) (rassoc c1 alist))
3748 (while (or (rassoc char new) (rassoc char alist))
3749 (setq char (1+ char)))
3750 (setq c2 c1))
3751 (setq c (or c2 char)))
3752 (push (cons k c) new))))
3753 (nreverse new)))
3755 ;;; Some variables used in various places
3757 (defvar org-window-configuration nil
3758 "Used in various places to store a window configuration.")
3759 (defvar org-finish-function nil
3760 "Function to be called when `C-c C-c' is used.
3761 This is for getting out of special buffers like remember.")
3764 ;; FIXME: Occasionally check by commenting these, to make sure
3765 ;; no other functions uses these, forgetting to let-bind them.
3766 (defvar entry)
3767 (defvar last-state)
3768 (defvar date)
3770 ;; Defined somewhere in this file, but used before definition.
3771 (defvar org-html-entities)
3772 (defvar org-struct-menu)
3773 (defvar org-org-menu)
3774 (defvar org-tbl-menu)
3775 (defvar org-agenda-keymap)
3777 ;;;; Define the Org-mode
3779 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3780 (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."))
3783 ;; We use a before-change function to check if a table might need
3784 ;; an update.
3785 (defvar org-table-may-need-update t
3786 "Indicates that a table might need an update.
3787 This variable is set by `org-before-change-function'.
3788 `org-table-align' sets it back to nil.")
3789 (defun org-before-change-function (beg end)
3790 "Every change indicates that a table might need an update."
3791 (setq org-table-may-need-update t))
3792 (defvar org-mode-map)
3793 (defvar org-mode-hook nil
3794 "Mode hook for Org-mode, run after the mode was turned on.")
3795 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3796 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3797 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
3798 (defvar org-table-buffer-is-an nil)
3799 (defconst org-outline-regexp "\\*+ ")
3801 ;;;###autoload
3802 (define-derived-mode org-mode outline-mode "Org"
3803 "Outline-based notes management and organizer, alias
3804 \"Carsten's outline-mode for keeping track of everything.\"
3806 Org-mode develops organizational tasks around a NOTES file which
3807 contains information about projects as plain text. Org-mode is
3808 implemented on top of outline-mode, which is ideal to keep the content
3809 of large files well structured. It supports ToDo items, deadlines and
3810 time stamps, which magically appear in the diary listing of the Emacs
3811 calendar. Tables are easily created with a built-in table editor.
3812 Plain text URL-like links connect to websites, emails (VM), Usenet
3813 messages (Gnus), BBDB entries, and any files related to the project.
3814 For printing and sharing of notes, an Org-mode file (or a part of it)
3815 can be exported as a structured ASCII or HTML file.
3817 The following commands are available:
3819 \\{org-mode-map}"
3821 ;; Get rid of Outline menus, they are not needed
3822 ;; Need to do this here because define-derived-mode sets up
3823 ;; the keymap so late. Still, it is a waste to call this each time
3824 ;; we switch another buffer into org-mode.
3825 (if (featurep 'xemacs)
3826 (when (boundp 'outline-mode-menu-heading)
3827 ;; Assume this is Greg's port, it used easymenu
3828 (easy-menu-remove outline-mode-menu-heading)
3829 (easy-menu-remove outline-mode-menu-show)
3830 (easy-menu-remove outline-mode-menu-hide))
3831 (define-key org-mode-map [menu-bar headings] 'undefined)
3832 (define-key org-mode-map [menu-bar hide] 'undefined)
3833 (define-key org-mode-map [menu-bar show] 'undefined))
3835 (org-load-modules-maybe)
3836 (easy-menu-add org-org-menu)
3837 (easy-menu-add org-tbl-menu)
3838 (org-install-agenda-files-menu)
3839 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3840 (org-add-to-invisibility-spec '(org-cwidth))
3841 (org-add-to-invisibility-spec '(org-hide-block . t))
3842 (when (featurep 'xemacs)
3843 (org-set-local 'line-move-ignore-invisible t))
3844 (org-set-local 'outline-regexp org-outline-regexp)
3845 (org-set-local 'outline-level 'org-outline-level)
3846 (when (and org-ellipsis
3847 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3848 (fboundp 'make-glyph-code))
3849 (unless org-display-table
3850 (setq org-display-table (make-display-table)))
3851 (set-display-table-slot
3852 org-display-table 4
3853 (vconcat (mapcar
3854 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3855 org-ellipsis)))
3856 (if (stringp org-ellipsis) org-ellipsis "..."))))
3857 (setq buffer-display-table org-display-table))
3858 (org-set-regexps-and-options)
3859 (when (and org-tag-faces (not org-tags-special-faces-re))
3860 ;; tag faces set outside customize.... force initialization.
3861 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3862 ;; Calc embedded
3863 (org-set-local 'calc-embedded-open-mode "# ")
3864 (modify-syntax-entry ?# "<")
3865 (modify-syntax-entry ?@ "w")
3866 (if org-startup-truncated (setq truncate-lines t))
3867 (org-set-local 'font-lock-unfontify-region-function
3868 'org-unfontify-region)
3869 ;; Activate before-change-function
3870 (org-set-local 'org-table-may-need-update t)
3871 (org-add-hook 'before-change-functions 'org-before-change-function nil
3872 'local)
3873 ;; Check for running clock before killing a buffer
3874 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3875 ;; Paragraphs and auto-filling
3876 (org-set-autofill-regexps)
3877 (setq indent-line-function 'org-indent-line-function)
3878 (org-update-radio-target-regexp)
3879 ;; Make sure dependence stuff works reliably, even for users who set it
3880 ;; too late :-(
3881 (if org-enforce-todo-dependencies
3882 (add-hook 'org-blocker-hook
3883 'org-block-todo-from-children-or-siblings-or-parent)
3884 (remove-hook 'org-blocker-hook
3885 'org-block-todo-from-children-or-siblings-or-parent))
3886 (if org-enforce-todo-checkbox-dependencies
3887 (add-hook 'org-blocker-hook
3888 'org-block-todo-from-checkboxes)
3889 (remove-hook 'org-blocker-hook
3890 'org-block-todo-from-checkboxes))
3892 ;; Comment characters
3893 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3894 (org-set-local 'comment-padding " ")
3896 ;; Align options lines
3897 (org-set-local
3898 'align-mode-rules-list
3899 '((org-in-buffer-settings
3900 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3901 (modes . '(org-mode)))))
3903 ;; Imenu
3904 (org-set-local 'imenu-create-index-function
3905 'org-imenu-get-tree)
3907 ;; Make isearch reveal context
3908 (if (or (featurep 'xemacs)
3909 (not (boundp 'outline-isearch-open-invisible-function)))
3910 ;; Emacs 21 and XEmacs make use of the hook
3911 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3912 ;; Emacs 22 deals with this through a special variable
3913 (org-set-local 'outline-isearch-open-invisible-function
3914 (lambda (&rest ignore) (org-show-context 'isearch))))
3916 ;; If empty file that did not turn on org-mode automatically, make it to.
3917 (if (and org-insert-mode-line-in-empty-file
3918 (interactive-p)
3919 (= (point-min) (point-max)))
3920 (insert "# -*- mode: org -*-\n\n"))
3922 (unless org-inhibit-startup
3923 (when org-startup-align-all-tables
3924 (let ((bmp (buffer-modified-p)))
3925 (org-table-map-tables 'org-table-align)
3926 (set-buffer-modified-p bmp)))
3927 (org-set-startup-visibility)))
3929 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3931 (defun org-current-time ()
3932 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3933 (if (> (car org-time-stamp-rounding-minutes) 1)
3934 (let ((r (car org-time-stamp-rounding-minutes))
3935 (time (decode-time)))
3936 (apply 'encode-time
3937 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3938 (nthcdr 2 time))))
3939 (current-time)))
3941 ;;;; Font-Lock stuff, including the activators
3943 (defvar org-mouse-map (make-sparse-keymap))
3944 (org-defkey org-mouse-map
3945 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3946 (org-defkey org-mouse-map
3947 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3948 (when org-mouse-1-follows-link
3949 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3950 (when org-tab-follows-link
3951 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3952 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3954 (require 'font-lock)
3956 (defconst org-non-link-chars "]\t\n\r<>")
3957 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3958 "shell" "elisp"))
3959 (defvar org-link-types-re nil
3960 "Matches a link that has a url-like prefix like \"http:\"")
3961 (defvar org-link-re-with-space nil
3962 "Matches a link with spaces, optional angular brackets around it.")
3963 (defvar org-link-re-with-space2 nil
3964 "Matches a link with spaces, optional angular brackets around it.")
3965 (defvar org-link-re-with-space3 nil
3966 "Matches a link with spaces, only for internal part in bracket links.")
3967 (defvar org-angle-link-re nil
3968 "Matches link with angular brackets, spaces are allowed.")
3969 (defvar org-plain-link-re nil
3970 "Matches plain link, without spaces.")
3971 (defvar org-bracket-link-regexp nil
3972 "Matches a link in double brackets.")
3973 (defvar org-bracket-link-analytic-regexp nil
3974 "Regular expression used to analyze links.
3975 Here is what the match groups contain after a match:
3976 1: http:
3977 2: http
3978 3: path
3979 4: [desc]
3980 5: desc")
3981 (defvar org-bracket-link-analytic-regexp++ nil
3982 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3983 (defvar org-any-link-re nil
3984 "Regular expression matching any link.")
3986 (defun org-make-link-regexps ()
3987 "Update the link regular expressions.
3988 This should be called after the variable `org-link-types' has changed."
3989 (setq org-link-types-re
3990 (concat
3991 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3992 org-link-re-with-space
3993 (concat
3994 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3995 "\\([^" org-non-link-chars " ]"
3996 "[^" org-non-link-chars "]*"
3997 "[^" org-non-link-chars " ]\\)>?")
3998 org-link-re-with-space2
3999 (concat
4000 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4001 "\\([^" org-non-link-chars " ]"
4002 "[^\t\n\r]*"
4003 "[^" org-non-link-chars " ]\\)>?")
4004 org-link-re-with-space3
4005 (concat
4006 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4007 "\\([^" org-non-link-chars " ]"
4008 "[^\t\n\r]*\\)")
4009 org-angle-link-re
4010 (concat
4011 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4012 "\\([^" org-non-link-chars " ]"
4013 "[^" org-non-link-chars "]*"
4014 "\\)>")
4015 org-plain-link-re
4016 (concat
4017 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4018 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4019 org-bracket-link-regexp
4020 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4021 org-bracket-link-analytic-regexp
4022 (concat
4023 "\\[\\["
4024 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4025 "\\([^]]+\\)"
4026 "\\]"
4027 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4028 "\\]")
4029 org-bracket-link-analytic-regexp++
4030 (concat
4031 "\\[\\["
4032 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4033 "\\([^]]+\\)"
4034 "\\]"
4035 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4036 "\\]")
4037 org-any-link-re
4038 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4039 org-angle-link-re "\\)\\|\\("
4040 org-plain-link-re "\\)")))
4042 (org-make-link-regexps)
4044 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4045 "Regular expression for fast time stamp matching.")
4046 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4047 "Regular expression for fast time stamp matching.")
4048 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4049 "Regular expression matching time strings for analysis.
4050 This one does not require the space after the date, so it can be used
4051 on a string that terminates immediately after the date.")
4052 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4053 "Regular expression matching time strings for analysis.")
4054 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4055 "Regular expression matching time stamps, with groups.")
4056 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4057 "Regular expression matching time stamps (also [..]), with groups.")
4058 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4059 "Regular expression matching a time stamp range.")
4060 (defconst org-tr-regexp-both
4061 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4062 "Regular expression matching a time stamp range.")
4063 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4064 org-ts-regexp "\\)?")
4065 "Regular expression matching a time stamp or time stamp range.")
4066 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4067 org-ts-regexp-both "\\)?")
4068 "Regular expression matching a time stamp or time stamp range.
4069 The time stamps may be either active or inactive.")
4071 (defvar org-emph-face nil)
4073 (defun org-do-emphasis-faces (limit)
4074 "Run through the buffer and add overlays to links."
4075 (let (rtn a)
4076 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4077 (if (not (= (char-after (match-beginning 3))
4078 (char-after (match-beginning 4))))
4079 (progn
4080 (setq rtn t)
4081 (setq a (assoc (match-string 3) org-emphasis-alist))
4082 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4083 'face
4084 (nth 1 a))
4085 (and (nth 4 a)
4086 (org-remove-flyspell-overlays-in
4087 (match-beginning 0) (match-end 0)))
4088 (add-text-properties (match-beginning 2) (match-end 2)
4089 '(font-lock-multiline t))
4090 (when org-hide-emphasis-markers
4091 (add-text-properties (match-end 4) (match-beginning 5)
4092 '(invisible org-link))
4093 (add-text-properties (match-beginning 3) (match-end 3)
4094 '(invisible org-link)))))
4095 (backward-char 1))
4096 rtn))
4098 (defun org-emphasize (&optional char)
4099 "Insert or change an emphasis, i.e. a font like bold or italic.
4100 If there is an active region, change that region to a new emphasis.
4101 If there is no region, just insert the marker characters and position
4102 the cursor between them.
4103 CHAR should be either the marker character, or the first character of the
4104 HTML tag associated with that emphasis. If CHAR is a space, the means
4105 to remove the emphasis of the selected region.
4106 If char is not given (for example in an interactive call) it
4107 will be prompted for."
4108 (interactive)
4109 (let ((eal org-emphasis-alist) e det
4110 (erc org-emphasis-regexp-components)
4111 (prompt "")
4112 (string "") beg end move tag c s)
4113 (if (org-region-active-p)
4114 (setq beg (region-beginning) end (region-end)
4115 string (buffer-substring beg end))
4116 (setq move t))
4118 (while (setq e (pop eal))
4119 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4120 c (aref tag 0))
4121 (push (cons c (string-to-char (car e))) det)
4122 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4123 (substring tag 1)))))
4124 (setq det (nreverse det))
4125 (unless char
4126 (message "%s" (concat "Emphasis marker or tag:" prompt))
4127 (setq char (read-char-exclusive)))
4128 (setq char (or (cdr (assoc char det)) char))
4129 (if (equal char ?\ )
4130 (setq s "" move nil)
4131 (unless (assoc (char-to-string char) org-emphasis-alist)
4132 (error "No such emphasis marker: \"%c\"" char))
4133 (setq s (char-to-string char)))
4134 (while (and (> (length string) 1)
4135 (equal (substring string 0 1) (substring string -1))
4136 (assoc (substring string 0 1) org-emphasis-alist))
4137 (setq string (substring string 1 -1)))
4138 (setq string (concat s string s))
4139 (if beg (delete-region beg end))
4140 (unless (or (bolp)
4141 (string-match (concat "[" (nth 0 erc) "\n]")
4142 (char-to-string (char-before (point)))))
4143 (insert " "))
4144 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4145 (char-to-string (char-after (point))))
4146 (insert " ") (backward-char 1))
4147 (insert string)
4148 (and move (backward-char 1))))
4150 (defconst org-nonsticky-props
4151 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4153 (defsubst org-rear-nonsticky-at (pos)
4154 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4156 (defun org-activate-plain-links (limit)
4157 "Run through the buffer and add overlays to links."
4158 (catch 'exit
4159 (let (f)
4160 (while (re-search-forward org-plain-link-re limit t)
4161 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4162 (setq f (get-text-property (match-beginning 0) 'face))
4163 (if (or (eq f 'org-tag)
4164 (and (listp f) (memq 'org-tag f)))
4166 (add-text-properties (match-beginning 0) (match-end 0)
4167 (list 'mouse-face 'highlight
4168 'keymap org-mouse-map))
4169 (org-rear-nonsticky-at (match-end 0))
4170 (throw 'exit t))))))
4172 (defun org-activate-code (limit)
4173 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4174 (progn
4175 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4176 (remove-text-properties (match-beginning 0) (match-end 0)
4177 '(display t invisible t intangible t))
4178 t)))
4180 (defun org-fontify-meta-lines-and-blocks (limit)
4181 "Fontify #+ lines and blocks, in the correct ways."
4182 (let ((case-fold-search t))
4183 (if (re-search-forward
4184 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4185 limit t)
4186 (let ((beg (match-beginning 0))
4187 (beg1 (line-beginning-position 2))
4188 (dc1 (downcase (match-string 2)))
4189 (dc3 (downcase (match-string 3)))
4190 end end1 quoting)
4191 (cond
4192 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4193 ;; a single line of backend-specific content
4194 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4195 (remove-text-properties (match-beginning 0) (match-end 0)
4196 '(display t invisible t intangible t))
4197 (add-text-properties (match-beginning 1) (match-end 3)
4198 '(font-lock-fontified t face org-meta-line))
4199 (add-text-properties (match-beginning 6) (match-end 6)
4200 '(font-lock-fontified t face org-block))
4202 ((and (match-end 4) (equal dc3 "begin"))
4203 ;; Truely a block
4204 (setq quoting (member (downcase (match-string 5))
4205 org-protecting-blocks))
4206 (when (re-search-forward
4207 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4208 nil t) ;; on purpose, we look further than LIMIT
4209 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4210 (when quoting
4211 (remove-text-properties beg end
4212 '(display t invisible t intangible t)))
4213 (add-text-properties
4214 beg end
4215 '(font-lock-fontified t font-lock-multiline t))
4216 (add-text-properties beg beg1 '(face org-meta-line))
4217 (add-text-properties end1 end '(face org-meta-line))
4218 (when quoting
4219 (add-text-properties beg1 end1 '(face org-block)))
4221 ((not (member (char-after beg) '(?\ ?\t)))
4222 ;; just any other in-buffer setting, but not indented
4223 (add-text-properties
4224 beg (match-end 0)
4225 '(font-lock-fontified t face org-meta-line))
4227 ((or (member dc1 '("caption:" "label:" "orgtbl:" "tblfm:"))
4228 (and (match-end 4) (equal dc3 "attr")))
4229 (add-text-properties
4230 beg (match-end 0)
4231 '(font-lock-fontified t face org-meta-line))
4233 (t nil))))))
4235 (defun org-activate-angle-links (limit)
4236 "Run through the buffer and add overlays to links."
4237 (if (re-search-forward org-angle-link-re limit t)
4238 (progn
4239 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4240 (add-text-properties (match-beginning 0) (match-end 0)
4241 (list 'mouse-face 'highlight
4242 'keymap org-mouse-map))
4243 (org-rear-nonsticky-at (match-end 0))
4244 t)))
4246 (defun org-activate-footnote-links (limit)
4247 "Run through the buffer and add overlays to links."
4248 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4249 limit t)
4250 (progn
4251 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4252 (add-text-properties (match-beginning 2) (match-end 2)
4253 (list 'mouse-face 'highlight
4254 'keymap org-mouse-map
4255 'help-echo
4256 (if (= (point-at-bol) (match-beginning 2))
4257 "Footnote definition"
4258 "Footnote reference")
4260 (org-rear-nonsticky-at (match-end 2))
4261 t)))
4263 (defun org-activate-bracket-links (limit)
4264 "Run through the buffer and add overlays to bracketed links."
4265 (if (re-search-forward org-bracket-link-regexp limit t)
4266 (let* ((help (concat "LINK: "
4267 (org-match-string-no-properties 1)))
4268 ;; FIXME: above we should remove the escapes.
4269 ;; but that requires another match, protecting match data,
4270 ;; a lot of overhead for font-lock.
4271 (ip (org-maybe-intangible
4272 (list 'invisible 'org-link
4273 'keymap org-mouse-map 'mouse-face 'highlight
4274 'font-lock-multiline t 'help-echo help)))
4275 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4276 'font-lock-multiline t 'help-echo help)))
4277 ;; We need to remove the invisible property here. Table narrowing
4278 ;; may have made some of this invisible.
4279 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4280 (remove-text-properties (match-beginning 0) (match-end 0)
4281 '(invisible nil))
4282 (if (match-end 3)
4283 (progn
4284 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4285 (org-rear-nonsticky-at (match-beginning 3))
4286 (add-text-properties (match-beginning 3) (match-end 3) vp)
4287 (org-rear-nonsticky-at (match-end 3))
4288 (add-text-properties (match-end 3) (match-end 0) ip)
4289 (org-rear-nonsticky-at (match-end 0)))
4290 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4291 (org-rear-nonsticky-at (match-beginning 1))
4292 (add-text-properties (match-beginning 1) (match-end 1) vp)
4293 (org-rear-nonsticky-at (match-end 1))
4294 (add-text-properties (match-end 1) (match-end 0) ip)
4295 (org-rear-nonsticky-at (match-end 0)))
4296 t)))
4298 (defun org-activate-dates (limit)
4299 "Run through the buffer and add overlays to dates."
4300 (if (re-search-forward org-tsr-regexp-both limit t)
4301 (progn
4302 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4303 (add-text-properties (match-beginning 0) (match-end 0)
4304 (list 'mouse-face 'highlight
4305 'keymap org-mouse-map))
4306 (org-rear-nonsticky-at (match-end 0))
4307 (when org-display-custom-times
4308 (if (match-end 3)
4309 (org-display-custom-time (match-beginning 3) (match-end 3)))
4310 (org-display-custom-time (match-beginning 1) (match-end 1)))
4311 t)))
4313 (defvar org-target-link-regexp nil
4314 "Regular expression matching radio targets in plain text.")
4315 (make-variable-buffer-local 'org-target-link-regexp)
4316 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4317 "Regular expression matching a link target.")
4318 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4319 "Regular expression matching a radio target.")
4320 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4321 "Regular expression matching any target.")
4323 (defun org-activate-target-links (limit)
4324 "Run through the buffer and add overlays to target matches."
4325 (when org-target-link-regexp
4326 (let ((case-fold-search t))
4327 (if (re-search-forward org-target-link-regexp limit t)
4328 (progn
4329 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4330 (add-text-properties (match-beginning 0) (match-end 0)
4331 (list 'mouse-face 'highlight
4332 'keymap org-mouse-map
4333 'help-echo "Radio target link"
4334 'org-linked-text t))
4335 (org-rear-nonsticky-at (match-end 0))
4336 t)))))
4338 (defun org-update-radio-target-regexp ()
4339 "Find all radio targets in this file and update the regular expression."
4340 (interactive)
4341 (when (memq 'radio org-activate-links)
4342 (setq org-target-link-regexp
4343 (org-make-target-link-regexp (org-all-targets 'radio)))
4344 (org-restart-font-lock)))
4346 (defun org-hide-wide-columns (limit)
4347 (let (s e)
4348 (setq s (text-property-any (point) (or limit (point-max))
4349 'org-cwidth t))
4350 (when s
4351 (setq e (next-single-property-change s 'org-cwidth))
4352 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4353 (goto-char e)
4354 t)))
4356 (defvar org-latex-and-specials-regexp nil
4357 "Regular expression for highlighting export special stuff.")
4358 (defvar org-match-substring-regexp)
4359 (defvar org-match-substring-with-braces-regexp)
4360 (defvar org-export-html-special-string-regexps)
4362 (defun org-compute-latex-and-specials-regexp ()
4363 "Compute regular expression for stuff treated specially by exporters."
4364 (if (not org-highlight-latex-fragments-and-specials)
4365 (org-set-local 'org-latex-and-specials-regexp nil)
4366 (require 'org-exp)
4367 (let*
4368 ((matchers (plist-get org-format-latex-options :matchers))
4369 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4370 org-latex-regexps)))
4371 (options (org-combine-plists (org-default-export-plist)
4372 (org-infile-export-plist)))
4373 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4374 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4375 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4376 (org-export-html-expand (plist-get options :expand-quoted-html))
4377 (org-export-with-special-strings (plist-get options :special-strings))
4378 (re-sub
4379 (cond
4380 ((equal org-export-with-sub-superscripts '{})
4381 (list org-match-substring-with-braces-regexp))
4382 (org-export-with-sub-superscripts
4383 (list org-match-substring-regexp))
4384 (t nil)))
4385 (re-latex
4386 (if org-export-with-LaTeX-fragments
4387 (mapcar (lambda (x) (nth 1 x)) latexs)))
4388 (re-macros
4389 (if org-export-with-TeX-macros
4390 (list (concat "\\\\"
4391 (regexp-opt
4392 (append (mapcar 'car org-html-entities)
4393 (if (boundp 'org-latex-entities)
4394 (mapcar (lambda (x)
4395 (or (car-safe x) x))
4396 org-latex-entities)
4397 nil))
4398 'words))) ; FIXME
4400 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4401 (re-special (if org-export-with-special-strings
4402 (mapcar (lambda (x) (car x))
4403 org-export-html-special-string-regexps)))
4404 (re-rest
4405 (delq nil
4406 (list
4407 (if org-export-html-expand "@<[^>\n]+>")
4408 ))))
4409 (org-set-local
4410 'org-latex-and-specials-regexp
4411 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4412 re-rest) "\\|")))))
4414 (defun org-do-latex-and-special-faces (limit)
4415 "Run through the buffer and add overlays to links."
4416 (when org-latex-and-specials-regexp
4417 (let (rtn d)
4418 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4419 limit t))
4420 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4421 'face))
4422 '(org-code org-verbatim underline)))
4423 (progn
4424 (setq rtn t
4425 d (cond ((member (char-after (1+ (match-beginning 0)))
4426 '(?_ ?^)) 1)
4427 (t 0)))
4428 (font-lock-prepend-text-property
4429 (+ d (match-beginning 0)) (match-end 0)
4430 'face 'org-latex-and-export-specials)
4431 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4432 '(font-lock-multiline t)))))
4433 rtn)))
4435 (defun org-restart-font-lock ()
4436 "Restart font-lock-mode, to force refontification."
4437 (when (and (boundp 'font-lock-mode) font-lock-mode)
4438 (font-lock-mode -1)
4439 (font-lock-mode 1)))
4441 (defun org-all-targets (&optional radio)
4442 "Return a list of all targets in this file.
4443 With optional argument RADIO, only find radio targets."
4444 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4445 rtn)
4446 (save-excursion
4447 (goto-char (point-min))
4448 (while (re-search-forward re nil t)
4449 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4450 rtn)))
4452 (defun org-make-target-link-regexp (targets)
4453 "Make regular expression matching all strings in TARGETS.
4454 The regular expression finds the targets also if there is a line break
4455 between words."
4456 (and targets
4457 (concat
4458 "\\<\\("
4459 (mapconcat
4460 (lambda (x)
4461 (while (string-match " +" x)
4462 (setq x (replace-match "\\s-+" t t x)))
4464 targets
4465 "\\|")
4466 "\\)\\>")))
4468 (defun org-activate-tags (limit)
4469 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4470 (progn
4471 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4472 (add-text-properties (match-beginning 1) (match-end 1)
4473 (list 'mouse-face 'highlight
4474 'keymap org-mouse-map))
4475 (org-rear-nonsticky-at (match-end 1))
4476 t)))
4478 (defun org-outline-level ()
4479 (save-excursion
4480 (looking-at outline-regexp)
4481 (if (match-beginning 1)
4482 (+ (org-get-string-indentation (match-string 1)) 1000)
4483 (1- (- (match-end 0) (match-beginning 0))))))
4485 (defvar org-font-lock-keywords nil)
4487 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4488 "Regular expression matching a property line.")
4490 (defvar org-font-lock-hook nil
4491 "Functions to be called for special font lock stuff.")
4493 (defun org-font-lock-hook (limit)
4494 (run-hook-with-args 'org-font-lock-hook limit))
4496 (defun org-set-font-lock-defaults ()
4497 (let* ((em org-fontify-emphasized-text)
4498 (lk org-activate-links)
4499 (org-font-lock-extra-keywords
4500 (list
4501 ;; Call the hook
4502 '(org-font-lock-hook)
4503 ;; Headlines
4504 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4505 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4506 ;; Table lines
4507 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4508 (1 'org-table t))
4509 ;; Table internals
4510 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4511 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4512 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4513 ;; Drawers
4514 (list org-drawer-regexp '(0 'org-special-keyword t))
4515 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4516 ;; Properties
4517 (list org-property-re
4518 '(1 'org-special-keyword t)
4519 '(3 'org-property-value t))
4520 (if org-format-transports-properties-p
4521 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4522 ;; Links
4523 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4524 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4525 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4526 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4527 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4528 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4529 (if (memq 'footnote lk) '(org-activate-footnote-links
4530 (2 'org-footnote t)))
4531 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4532 '(org-hide-wide-columns (0 nil append))
4533 ;; TODO lines
4534 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4535 '(1 (org-get-todo-face 1) t))
4536 ;; DONE
4537 (if org-fontify-done-headline
4538 (list (concat "^[*]+ +\\<\\("
4539 (mapconcat 'regexp-quote org-done-keywords "\\|")
4540 "\\)\\(.*\\)")
4541 '(2 'org-headline-done t))
4542 nil)
4543 ;; Priorities
4544 '(org-font-lock-add-priority-faces)
4545 ;; Tags
4546 '(org-font-lock-add-tag-faces)
4547 ;; Special keywords
4548 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4549 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4550 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4551 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4552 ;; Emphasis
4553 (if em
4554 (if (featurep 'xemacs)
4555 '(org-do-emphasis-faces (0 nil append))
4556 '(org-do-emphasis-faces)))
4557 ;; Checkboxes
4558 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4559 2 'org-checkbox prepend)
4560 (if org-provide-checkbox-statistics
4561 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4562 (0 (org-get-checkbox-statistics-face) t)))
4563 ;; Description list items
4564 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4565 2 'bold prepend)
4566 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4567 '(1 'org-archived prepend))
4568 ;; Specials
4569 '(org-do-latex-and-special-faces)
4570 ;; Code
4571 '(org-activate-code (1 'org-code t))
4572 ;; COMMENT
4573 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4574 "\\|" org-quote-string "\\)\\>")
4575 '(1 'org-special-keyword t))
4576 '("^#.*" (0 'font-lock-comment-face t))
4577 ;; Blocks and meta lines
4578 '(org-fontify-meta-lines-and-blocks)
4580 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4581 ;; Now set the full font-lock-keywords
4582 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4583 (org-set-local 'font-lock-defaults
4584 '(org-font-lock-keywords t nil nil backward-paragraph))
4585 (kill-local-variable 'font-lock-keywords) nil))
4587 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
4588 "Fontify string S like in Org-mode"
4589 (with-temp-buffer
4590 (insert s)
4591 (let ((org-odd-levels-only odd-levels))
4592 (org-mode)
4593 (font-lock-fontify-buffer)
4594 (buffer-string))))
4596 (defvar org-m nil)
4597 (defvar org-l nil)
4598 (defvar org-f nil)
4599 (defun org-get-level-face (n)
4600 "Get the right face for match N in font-lock matching of headlines."
4601 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4602 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4603 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4604 (cond
4605 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4606 ((eq n 2) org-f)
4607 (t (if org-level-color-stars-only nil org-f))))
4609 (defun org-get-todo-face (kwd)
4610 "Get the right face for a TODO keyword KWD.
4611 If KWD is a number, get the corresponding match group."
4612 (if (numberp kwd) (setq kwd (match-string kwd)))
4613 (or (cdr (assoc kwd org-todo-keyword-faces))
4614 (and (member kwd org-done-keywords) 'org-done)
4615 'org-todo))
4617 (defun org-font-lock-add-tag-faces (limit)
4618 "Add the special tag faces."
4619 (when (and org-tag-faces org-tags-special-faces-re)
4620 (while (re-search-forward org-tags-special-faces-re limit t)
4621 (add-text-properties (match-beginning 1) (match-end 1)
4622 (list 'face (org-get-tag-face 1)
4623 'font-lock-fontified t))
4624 (backward-char 1))))
4626 (defun org-font-lock-add-priority-faces (limit)
4627 "Add the special priority faces."
4628 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4629 (add-text-properties
4630 (match-beginning 0) (match-end 0)
4631 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4632 org-priority-faces))
4633 'org-special-keyword)
4634 'font-lock-fontified t))))
4636 (defun org-get-tag-face (kwd)
4637 "Get the right face for a TODO keyword KWD.
4638 If KWD is a number, get the corresponding match group."
4639 (if (numberp kwd) (setq kwd (match-string kwd)))
4640 (or (cdr (assoc kwd org-tag-faces))
4641 'org-tag))
4643 (defun org-unfontify-region (beg end &optional maybe_loudly)
4644 "Remove fontification and activation overlays from links."
4645 (font-lock-default-unfontify-region beg end)
4646 (let* ((buffer-undo-list t)
4647 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4648 (inhibit-modification-hooks t)
4649 deactivate-mark buffer-file-name buffer-file-truename)
4650 (remove-text-properties beg end
4651 '(mouse-face t keymap t org-linked-text t
4652 invisible t intangible t
4653 org-no-flyspell t))))
4655 ;;;; Visibility cycling, including org-goto and indirect buffer
4657 ;;; Cycling
4659 (defvar org-cycle-global-status nil)
4660 (make-variable-buffer-local 'org-cycle-global-status)
4661 (defvar org-cycle-subtree-status nil)
4662 (make-variable-buffer-local 'org-cycle-subtree-status)
4664 ;;;###autoload
4666 (defvar org-inlinetask-min-level)
4668 (defun org-cycle (&optional arg)
4669 "TAB-action and visibility cycling for Org-mode.
4671 This is the command invoked in Org-moe by the TAB key. It's main purpose
4672 is outine visibility cycling, but it also invokes other actions
4673 in special contexts.
4675 - When this function is called with a prefix argument, rotate the entire
4676 buffer through 3 states (global cycling)
4677 1. OVERVIEW: Show only top-level headlines.
4678 2. CONTENTS: Show all headlines of all levels, but no body text.
4679 3. SHOW ALL: Show everything.
4680 When called with two `C-u C-u' prefixes, switch to the startup visibility,
4681 determined by the variable `org-startup-folded', and by any VISIBILITY
4682 properties in the buffer.
4683 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
4684 including any drawers.
4686 - When inside a table, re-align the table and move to the next field.
4688 - When point is at the beginning of a headline, rotate the subtree started
4689 by this line through 3 different states (local cycling)
4690 1. FOLDED: Only the main headline is shown.
4691 2. CHILDREN: The main headline and the direct children are shown.
4692 From this state, you can move to one of the children
4693 and zoom in further.
4694 3. SUBTREE: Show the entire subtree, including body text.
4696 - When there is a numeric prefix, go up to a heading with level ARG, do
4697 a `show-subtree' and return to the previous cursor position. If ARG
4698 is negative, go up that many levels.
4700 - When point is not at the beginning of a headline, execute the global
4701 binding for TAB, which is re-indenting the line. See the option
4702 `org-cycle-emulate-tab' for details.
4704 - Special case: if point is at the beginning of the buffer and there is
4705 no headline in line 1, this function will act as if called with prefix arg.
4706 But only if also the variable `org-cycle-global-at-bob' is t."
4707 (interactive "P")
4708 (org-load-modules-maybe)
4709 (unless (run-hook-with-args-until-success 'org-tab-first-hook)
4710 (let* ((limit-level
4711 (or org-cycle-max-level
4712 (and (boundp 'org-inlinetask-min-level)
4713 org-inlinetask-min-level
4714 (1- org-inlinetask-min-level))))
4715 (nstars (and limit-level
4716 (if org-odd-levels-only
4717 (and limit-level (1- (* limit-level 2)))
4718 limit-level)))
4719 (outline-regexp
4720 (cond
4721 ((not (org-mode-p)) outline-regexp)
4722 (org-cycle-include-plain-lists
4723 (concat "\\(?:\\*"
4724 (if nstars (format "\\{1,%d\\}" nstars) "+")
4725 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
4726 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
4727 (bob-special (and org-cycle-global-at-bob (bobp)
4728 (not (looking-at outline-regexp))))
4729 (org-cycle-hook
4730 (if bob-special
4731 (delq 'org-optimize-window-after-visibility-change
4732 (copy-sequence org-cycle-hook))
4733 org-cycle-hook))
4734 (pos (point)))
4736 (if (or bob-special (equal arg '(4)))
4737 ;; special case: use global cycling
4738 (setq arg t))
4740 (cond
4742 ((equal arg '(16))
4743 (org-set-startup-visibility)
4744 (message "Startup visibility, plus VISIBILITY properties"))
4746 ((equal arg '(64))
4747 (show-all)
4748 (message "Entire buffer visible, including drawers"))
4750 ((org-at-table-p 'any)
4751 ;; Enter the table or move to the next field in the table
4752 (or (org-table-recognize-table.el)
4753 (progn
4754 (if arg (org-table-edit-field t)
4755 (org-table-justify-field-maybe)
4756 (call-interactively 'org-table-next-field)))))
4758 ((run-hook-with-args-until-success
4759 'org-tab-after-check-for-table-hook))
4761 ((eq arg t) ;; Global cycling
4762 (org-cycle-internal-global))
4764 ((and org-drawers org-drawer-regexp
4765 (save-excursion
4766 (beginning-of-line 1)
4767 (looking-at org-drawer-regexp)))
4768 ;; Toggle block visibility
4769 (org-flag-drawer
4770 (not (get-char-property (match-end 0) 'invisible))))
4772 ((integerp arg)
4773 ;; Show-subtree, ARG levels up from here.
4774 (save-excursion
4775 (org-back-to-heading)
4776 (outline-up-heading (if (< arg 0) (- arg)
4777 (- (funcall outline-level) arg)))
4778 (org-show-subtree)))
4780 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4781 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4783 (org-cycle-internal-local))
4785 ;; TAB emulation and template completion
4786 (buffer-read-only (org-back-to-heading))
4788 ((run-hook-with-args-until-success
4789 'org-tab-after-check-for-cycling-hook))
4791 ((org-try-structure-completion))
4793 ((org-try-cdlatex-tab))
4795 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4796 (or (not (bolp))
4797 (not (looking-at outline-regexp))))
4798 (call-interactively (global-key-binding "\t")))
4800 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4801 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4802 (or (and (eq org-cycle-emulate-tab 'white)
4803 (= (match-end 0) (point-at-eol)))
4804 (and (eq org-cycle-emulate-tab 'whitestart)
4805 (>= (match-end 0) pos))))
4807 (eq org-cycle-emulate-tab t))
4808 (call-interactively (global-key-binding "\t")))
4810 (t (save-excursion
4811 (org-back-to-heading)
4812 (org-cycle)))))))
4814 (defun org-cycle-internal-global ()
4815 "Do the global cycling action."
4816 (cond
4817 ((and (eq last-command this-command)
4818 (eq org-cycle-global-status 'overview))
4819 ;; We just created the overview - now do table of contents
4820 ;; This can be slow in very large buffers, so indicate action
4821 (run-hook-with-args 'org-pre-cycle-hook 'contents)
4822 (message "CONTENTS...")
4823 (org-content)
4824 (message "CONTENTS...done")
4825 (setq org-cycle-global-status 'contents)
4826 (run-hook-with-args 'org-cycle-hook 'contents))
4828 ((and (eq last-command this-command)
4829 (eq org-cycle-global-status 'contents))
4830 ;; We just showed the table of contents - now show everything
4831 (run-hook-with-args 'org-pre-cycle-hook 'all)
4832 (show-all)
4833 (message "SHOW ALL")
4834 (setq org-cycle-global-status 'all)
4835 (run-hook-with-args 'org-cycle-hook 'all))
4838 ;; Default action: go to overview
4839 (run-hook-with-args 'org-pre-cycle-hook 'overview)
4840 (org-overview)
4841 (message "OVERVIEW")
4842 (setq org-cycle-global-status 'overview)
4843 (run-hook-with-args 'org-cycle-hook 'overview))))
4845 (defun org-cycle-internal-local ()
4846 "Do the local cycling action."
4847 (org-back-to-heading)
4848 (let ((goal-column 0) eoh eol eos)
4849 ;; First, some boundaries
4850 (save-excursion
4851 (org-back-to-heading)
4852 (save-excursion
4853 (beginning-of-line 2)
4854 (while (and (not (eobp)) ;; this is like `next-line'
4855 (get-char-property (1- (point)) 'invisible))
4856 (beginning-of-line 2)) (setq eol (point)))
4857 (outline-end-of-heading) (setq eoh (point))
4858 (org-end-of-subtree t)
4859 (unless (eobp)
4860 (skip-chars-forward " \t\n")
4861 (beginning-of-line 1) ; in case this is an item
4863 (setq eos (1- (point))))
4864 ;; Find out what to do next and set `this-command'
4865 (cond
4866 ((= eos eoh)
4867 ;; Nothing is hidden behind this heading
4868 (run-hook-with-args 'org-pre-cycle-hook 'empty)
4869 (message "EMPTY ENTRY")
4870 (setq org-cycle-subtree-status nil)
4871 (save-excursion
4872 (goto-char eos)
4873 (outline-next-heading)
4874 (if (org-invisible-p) (org-flag-heading nil))))
4875 ((or (>= eol eos)
4876 (not (string-match "\\S-" (buffer-substring eol eos))))
4877 ;; Entire subtree is hidden in one line: open it
4878 (run-hook-with-args 'org-pre-cycle-hook 'children)
4879 (org-show-entry)
4880 (show-children)
4881 (message "CHILDREN")
4882 (save-excursion
4883 (goto-char eos)
4884 (outline-next-heading)
4885 (if (org-invisible-p) (org-flag-heading nil)))
4886 (setq org-cycle-subtree-status 'children)
4887 (run-hook-with-args 'org-cycle-hook 'children))
4888 ((and (eq last-command this-command)
4889 (eq org-cycle-subtree-status 'children))
4890 ;; We just showed the children, now show everything.
4891 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
4892 (org-show-subtree)
4893 (message "SUBTREE")
4894 (setq org-cycle-subtree-status 'subtree)
4895 (run-hook-with-args 'org-cycle-hook 'subtree))
4897 ;; Default action: hide the subtree.
4898 (run-hook-with-args 'org-pre-cycle-hook 'folded)
4899 (hide-subtree)
4900 (message "FOLDED")
4901 (setq org-cycle-subtree-status 'folded)
4902 (run-hook-with-args 'org-cycle-hook 'folded)))))
4904 ;;;###autoload
4905 (defun org-global-cycle (&optional arg)
4906 "Cycle the global visibility. For details see `org-cycle'.
4907 With C-u prefix arg, switch to startup visibility.
4908 With a numeric prefix, show all headlines up to that level."
4909 (interactive "P")
4910 (let ((org-cycle-include-plain-lists
4911 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4912 (cond
4913 ((integerp arg)
4914 (show-all)
4915 (hide-sublevels arg)
4916 (setq org-cycle-global-status 'contents))
4917 ((equal arg '(4))
4918 (org-set-startup-visibility)
4919 (message "Startup visibility, plus VISIBILITY properties."))
4921 (org-cycle '(4))))))
4923 (defun org-set-startup-visibility ()
4924 "Set the visibility required by startup options and properties."
4925 (cond
4926 ((eq org-startup-folded t)
4927 (org-cycle '(4)))
4928 ((eq org-startup-folded 'content)
4929 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4930 (org-cycle '(4)) (org-cycle '(4)))))
4931 (if org-hide-block-startup (org-hide-block-all))
4932 (org-set-visibility-according-to-property 'no-cleanup)
4933 (org-cycle-hide-archived-subtrees 'all)
4934 (org-cycle-hide-drawers 'all)
4935 (org-cycle-show-empty-lines 'all))
4937 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4938 "Switch subtree visibilities according to :VISIBILITY: property."
4939 (interactive)
4940 (let (org-show-entry-below state)
4941 (save-excursion
4942 (goto-char (point-min))
4943 (while (re-search-forward
4944 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4945 nil t)
4946 (setq state (match-string 1))
4947 (save-excursion
4948 (org-back-to-heading t)
4949 (hide-subtree)
4950 (org-reveal)
4951 (cond
4952 ((equal state '("fold" "folded"))
4953 (hide-subtree))
4954 ((equal state "children")
4955 (org-show-hidden-entry)
4956 (show-children))
4957 ((equal state "content")
4958 (save-excursion
4959 (save-restriction
4960 (org-narrow-to-subtree)
4961 (org-content))))
4962 ((member state '("all" "showall"))
4963 (show-subtree)))))
4964 (unless no-cleanup
4965 (org-cycle-hide-archived-subtrees 'all)
4966 (org-cycle-hide-drawers 'all)
4967 (org-cycle-show-empty-lines 'all)))))
4969 (defun org-overview ()
4970 "Switch to overview mode, showing only top-level headlines.
4971 Really, this shows all headlines with level equal or greater than the level
4972 of the first headline in the buffer. This is important, because if the
4973 first headline is not level one, then (hide-sublevels 1) gives confusing
4974 results."
4975 (interactive)
4976 (let ((level (save-excursion
4977 (goto-char (point-min))
4978 (if (re-search-forward (concat "^" outline-regexp) nil t)
4979 (progn
4980 (goto-char (match-beginning 0))
4981 (funcall outline-level))))))
4982 (and level (hide-sublevels level))))
4984 (defun org-content (&optional arg)
4985 "Show all headlines in the buffer, like a table of contents.
4986 With numerical argument N, show content up to level N."
4987 (interactive "P")
4988 (save-excursion
4989 ;; Visit all headings and show their offspring
4990 (and (integerp arg) (org-overview))
4991 (goto-char (point-max))
4992 (catch 'exit
4993 (while (and (progn (condition-case nil
4994 (outline-previous-visible-heading 1)
4995 (error (goto-char (point-min))))
4997 (looking-at outline-regexp))
4998 (if (integerp arg)
4999 (show-children (1- arg))
5000 (show-branches))
5001 (if (bobp) (throw 'exit nil))))))
5004 (defun org-optimize-window-after-visibility-change (state)
5005 "Adjust the window after a change in outline visibility.
5006 This function is the default value of the hook `org-cycle-hook'."
5007 (when (get-buffer-window (current-buffer))
5008 (cond
5009 ((eq state 'content) nil)
5010 ((eq state 'all) nil)
5011 ((eq state 'folded) nil)
5012 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5013 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5015 (defun org-compact-display-after-subtree-move ()
5016 "Show a compacter version of the tree of the entry's parent."
5017 (save-excursion
5018 (if (org-up-heading-safe)
5019 (progn
5020 (hide-subtree)
5021 (show-entry)
5022 (show-children)
5023 (org-cycle-show-empty-lines 'children)
5024 (org-cycle-hide-drawers 'children))
5025 (org-overview))))
5027 (defun org-cycle-show-empty-lines (state)
5028 "Show empty lines above all visible headlines.
5029 The region to be covered depends on STATE when called through
5030 `org-cycle-hook'. Lisp program can use t for STATE to get the
5031 entire buffer covered. Note that an empty line is only shown if there
5032 are at least `org-cycle-separator-lines' empty lines before the headline."
5033 (when (> org-cycle-separator-lines 0)
5034 (save-excursion
5035 (let* ((n org-cycle-separator-lines)
5036 (re (cond
5037 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5038 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5039 (t (let ((ns (number-to-string (- n 2))))
5040 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5041 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5042 beg end)
5043 (cond
5044 ((memq state '(overview contents t))
5045 (setq beg (point-min) end (point-max)))
5046 ((memq state '(children folded))
5047 (setq beg (point) end (progn (org-end-of-subtree t t)
5048 (beginning-of-line 2)
5049 (point)))))
5050 (when beg
5051 (goto-char beg)
5052 (while (re-search-forward re end t)
5053 (if (not (get-char-property (match-end 1) 'invisible))
5054 (outline-flag-region
5055 (match-beginning 1) (match-end 1) nil)))))))
5056 ;; Never hide empty lines at the end of the file.
5057 (save-excursion
5058 (goto-char (point-max))
5059 (outline-previous-heading)
5060 (outline-end-of-heading)
5061 (if (and (looking-at "[ \t\n]+")
5062 (= (match-end 0) (point-max)))
5063 (outline-flag-region (point) (match-end 0) nil))))
5065 (defun org-show-empty-lines-in-parent ()
5066 "Move to the parent and re-show empty lines before visible headlines."
5067 (save-excursion
5068 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5069 (org-cycle-show-empty-lines context))))
5071 (defun org-cycle-hide-drawers (state)
5072 "Re-hide all drawers after a visibility state change."
5073 (when (and (org-mode-p)
5074 (not (memq state '(overview folded))))
5075 (save-excursion
5076 (let* ((globalp (memq state '(contents all)))
5077 (beg (if globalp (point-min) (point)))
5078 (end (if globalp (point-max) (org-end-of-subtree t))))
5079 (goto-char beg)
5080 (while (re-search-forward org-drawer-regexp end t)
5081 (org-flag-drawer t))))))
5083 (defun org-flag-drawer (flag)
5084 (save-excursion
5085 (beginning-of-line 1)
5086 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5087 (let ((b (match-end 0))
5088 (outline-regexp org-outline-regexp))
5089 (if (re-search-forward
5090 "^[ \t]*:END:"
5091 (save-excursion (outline-next-heading) (point)) t)
5092 (outline-flag-region b (point-at-eol) flag)
5093 (error ":END: line missing"))))))
5095 (defun org-subtree-end-visible-p ()
5096 "Is the end of the current subtree visible?"
5097 (pos-visible-in-window-p
5098 (save-excursion (org-end-of-subtree t) (point))))
5100 (defun org-first-headline-recenter (&optional N)
5101 "Move cursor to the first headline and recenter the headline.
5102 Optional argument N means, put the headline into the Nth line of the window."
5103 (goto-char (point-min))
5104 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5105 (beginning-of-line)
5106 (recenter (prefix-numeric-value N))))
5108 ;;; Folding of blocks
5110 (defconst org-block-regexp
5112 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5113 "Regular expression for hiding blocks.")
5115 (defvar org-hide-block-overlays nil
5116 "Overays hiding blocks.")
5117 (make-variable-buffer-local 'org-hide-block-overlays)
5119 (defun org-block-map (function &optional start end)
5120 "Call func at the head of all source blocks in the current
5121 buffer. Optional arguments START and END can be used to limit
5122 the range."
5123 (let ((start (or start (point-min)))
5124 (end (or end (point-max))))
5125 (save-excursion
5126 (goto-char start)
5127 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5128 (save-excursion
5129 (save-match-data
5130 (goto-char (match-beginning 0))
5131 (funcall function)))))))
5133 (defun org-hide-block-toggle-all ()
5134 "Toggle the visibility of all blocks in the current buffer."
5135 (org-block-map #'org-hide-block-toggle))
5137 (defun org-hide-block-all ()
5138 "Fold all blocks in the current buffer."
5139 (interactive)
5140 (org-show-block-all)
5141 (org-block-map #'org-hide-block-toggle-maybe))
5143 (defun org-show-block-all ()
5144 "Unfold all blocks in the current buffer."
5145 (mapc 'org-delete-overlay org-hide-block-overlays)
5146 (setq org-hide-block-overlays nil))
5148 (defun org-hide-block-toggle-maybe ()
5149 "Toggle visibility of block at point."
5150 (interactive)
5151 (let ((case-fold-search t))
5152 (if (save-excursion
5153 (beginning-of-line 1)
5154 (looking-at org-block-regexp))
5155 (progn (org-hide-block-toggle)
5156 t) ;; to signal that we took action
5157 nil))) ;; to signal that we did not
5159 (defun org-hide-block-toggle (&optional force)
5160 "Toggle the visibility of the current block."
5161 (interactive)
5162 (save-excursion
5163 (beginning-of-line)
5164 (if (re-search-forward org-block-regexp nil t)
5165 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5166 (end (match-end 0))
5167 ov) ;; end of entire body
5168 (if (memq t (mapcar (lambda (overlay)
5169 (eq (org-overlay-get overlay 'invisible)
5170 'org-hide-block))
5171 (org-overlays-at start)))
5172 (if (or (not force) (eq force 'off))
5173 (mapc (lambda (ov)
5174 (when (member ov org-hide-block-overlays)
5175 (setq org-hide-block-overlays
5176 (delq ov org-hide-block-overlays)))
5177 (when (eq (org-overlay-get ov 'invisible)
5178 'org-hide-block)
5179 (org-delete-overlay ov)))
5180 (org-overlays-at start)))
5181 (setq ov (make-overlay start end))
5182 (org-overlay-put ov 'invisible 'org-hide-block)
5183 (push ov org-hide-block-overlays)))
5184 (error "Not looking at a source block"))))
5186 ;; org-tab-after-check-for-cycling-hook
5187 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5188 ;; Remove overlays when changing major mode
5189 (add-hook 'org-mode-hook
5190 (lambda () (org-add-hook 'change-major-mode-hook
5191 'org-show-block-all 'append 'local)))
5193 ;;; Org-goto
5195 (defvar org-goto-window-configuration nil)
5196 (defvar org-goto-marker nil)
5197 (defvar org-goto-map
5198 (let ((map (make-sparse-keymap)))
5199 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5200 (while (setq cmd (pop cmds))
5201 (substitute-key-definition cmd cmd map global-map)))
5202 (suppress-keymap map)
5203 (org-defkey map "\C-m" 'org-goto-ret)
5204 (org-defkey map [(return)] 'org-goto-ret)
5205 (org-defkey map [(left)] 'org-goto-left)
5206 (org-defkey map [(right)] 'org-goto-right)
5207 (org-defkey map [(control ?g)] 'org-goto-quit)
5208 (org-defkey map "\C-i" 'org-cycle)
5209 (org-defkey map [(tab)] 'org-cycle)
5210 (org-defkey map [(down)] 'outline-next-visible-heading)
5211 (org-defkey map [(up)] 'outline-previous-visible-heading)
5212 (if org-goto-auto-isearch
5213 (if (fboundp 'define-key-after)
5214 (define-key-after map [t] 'org-goto-local-auto-isearch)
5215 nil)
5216 (org-defkey map "q" 'org-goto-quit)
5217 (org-defkey map "n" 'outline-next-visible-heading)
5218 (org-defkey map "p" 'outline-previous-visible-heading)
5219 (org-defkey map "f" 'outline-forward-same-level)
5220 (org-defkey map "b" 'outline-backward-same-level)
5221 (org-defkey map "u" 'outline-up-heading))
5222 (org-defkey map "/" 'org-occur)
5223 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5224 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5225 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5226 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5227 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5228 map))
5230 (defconst org-goto-help
5231 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5232 RET=jump to location [Q]uit and return to previous location
5233 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5235 (defvar org-goto-start-pos) ; dynamically scoped parameter
5237 ;; FIXME: Docstring doe not mention both interfaces
5238 (defun org-goto (&optional alternative-interface)
5239 "Look up a different location in the current file, keeping current visibility.
5241 When you want look-up or go to a different location in a document, the
5242 fastest way is often to fold the entire buffer and then dive into the tree.
5243 This method has the disadvantage, that the previous location will be folded,
5244 which may not be what you want.
5246 This command works around this by showing a copy of the current buffer
5247 in an indirect buffer, in overview mode. You can dive into the tree in
5248 that copy, use org-occur and incremental search to find a location.
5249 When pressing RET or `Q', the command returns to the original buffer in
5250 which the visibility is still unchanged. After RET is will also jump to
5251 the location selected in the indirect buffer and expose the
5252 the headline hierarchy above."
5253 (interactive "P")
5254 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5255 (org-refile-use-outline-path t)
5256 (org-refile-target-verify-function nil)
5257 (interface
5258 (if (not alternative-interface)
5259 org-goto-interface
5260 (if (eq org-goto-interface 'outline)
5261 'outline-path-completion
5262 'outline)))
5263 (org-goto-start-pos (point))
5264 (selected-point
5265 (if (eq interface 'outline)
5266 (car (org-get-location (current-buffer) org-goto-help))
5267 (nth 3 (org-refile-get-location "Goto: ")))))
5268 (if selected-point
5269 (progn
5270 (org-mark-ring-push org-goto-start-pos)
5271 (goto-char selected-point)
5272 (if (or (org-invisible-p) (org-invisible-p2))
5273 (org-show-context 'org-goto)))
5274 (message "Quit"))))
5276 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5277 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5278 (defvar org-goto-local-auto-isearch-map) ; defined below
5280 (defun org-get-location (buf help)
5281 "Let the user select a location in the Org-mode buffer BUF.
5282 This function uses a recursive edit. It returns the selected position
5283 or nil."
5284 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5285 (isearch-hide-immediately nil)
5286 (isearch-search-fun-function
5287 (lambda () 'org-goto-local-search-headings))
5288 (org-goto-selected-point org-goto-exit-command))
5289 (save-excursion
5290 (save-window-excursion
5291 (delete-other-windows)
5292 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5293 (switch-to-buffer
5294 (condition-case nil
5295 (make-indirect-buffer (current-buffer) "*org-goto*")
5296 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5297 (with-output-to-temp-buffer "*Help*"
5298 (princ help))
5299 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5300 (setq buffer-read-only nil)
5301 (let ((org-startup-truncated t)
5302 (org-startup-folded nil)
5303 (org-startup-align-all-tables nil))
5304 (org-mode)
5305 (org-overview))
5306 (setq buffer-read-only t)
5307 (if (and (boundp 'org-goto-start-pos)
5308 (integer-or-marker-p org-goto-start-pos))
5309 (let ((org-show-hierarchy-above t)
5310 (org-show-siblings t)
5311 (org-show-following-heading t))
5312 (goto-char org-goto-start-pos)
5313 (and (org-invisible-p) (org-show-context)))
5314 (goto-char (point-min)))
5315 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5316 (message "Select location and press RET")
5317 (use-local-map org-goto-map)
5318 (recursive-edit)
5320 (kill-buffer "*org-goto*")
5321 (cons org-goto-selected-point org-goto-exit-command)))
5323 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5324 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5325 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5326 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5328 (defun org-goto-local-search-headings (string bound noerror)
5329 "Search and make sure that any matches are in headlines."
5330 (catch 'return
5331 (while (if isearch-forward
5332 (search-forward string bound noerror)
5333 (search-backward string bound noerror))
5334 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5335 (and (member :headline context)
5336 (not (member :tags context))))
5337 (throw 'return (point))))))
5339 (defun org-goto-local-auto-isearch ()
5340 "Start isearch."
5341 (interactive)
5342 (goto-char (point-min))
5343 (let ((keys (this-command-keys)))
5344 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5345 (isearch-mode t)
5346 (isearch-process-search-char (string-to-char keys)))))
5348 (defun org-goto-ret (&optional arg)
5349 "Finish `org-goto' by going to the new location."
5350 (interactive "P")
5351 (setq org-goto-selected-point (point)
5352 org-goto-exit-command 'return)
5353 (throw 'exit nil))
5355 (defun org-goto-left ()
5356 "Finish `org-goto' by going to the new location."
5357 (interactive)
5358 (if (org-on-heading-p)
5359 (progn
5360 (beginning-of-line 1)
5361 (setq org-goto-selected-point (point)
5362 org-goto-exit-command 'left)
5363 (throw 'exit nil))
5364 (error "Not on a heading")))
5366 (defun org-goto-right ()
5367 "Finish `org-goto' by going to the new location."
5368 (interactive)
5369 (if (org-on-heading-p)
5370 (progn
5371 (setq org-goto-selected-point (point)
5372 org-goto-exit-command 'right)
5373 (throw 'exit nil))
5374 (error "Not on a heading")))
5376 (defun org-goto-quit ()
5377 "Finish `org-goto' without cursor motion."
5378 (interactive)
5379 (setq org-goto-selected-point nil)
5380 (setq org-goto-exit-command 'quit)
5381 (throw 'exit nil))
5383 ;;; Indirect buffer display of subtrees
5385 (defvar org-indirect-dedicated-frame nil
5386 "This is the frame being used for indirect tree display.")
5387 (defvar org-last-indirect-buffer nil)
5389 (defun org-tree-to-indirect-buffer (&optional arg)
5390 "Create indirect buffer and narrow it to current subtree.
5391 With numerical prefix ARG, go up to this level and then take that tree.
5392 If ARG is negative, go up that many levels.
5393 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5394 indirect buffer previously made with this command, to avoid proliferation of
5395 indirect buffers. However, when you call the command with a `C-u' prefix, or
5396 when `org-indirect-buffer-display' is `new-frame', the last buffer
5397 is kept so that you can work with several indirect buffers at the same time.
5398 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5399 requests that a new frame be made for the new buffer, so that the dedicated
5400 frame is not changed."
5401 (interactive "P")
5402 (let ((cbuf (current-buffer))
5403 (cwin (selected-window))
5404 (pos (point))
5405 beg end level heading ibuf)
5406 (save-excursion
5407 (org-back-to-heading t)
5408 (when (numberp arg)
5409 (setq level (org-outline-level))
5410 (if (< arg 0) (setq arg (+ level arg)))
5411 (while (> (setq level (org-outline-level)) arg)
5412 (outline-up-heading 1 t)))
5413 (setq beg (point)
5414 heading (org-get-heading))
5415 (org-end-of-subtree t) (setq end (point)))
5416 (if (and (buffer-live-p org-last-indirect-buffer)
5417 (not (eq org-indirect-buffer-display 'new-frame))
5418 (not arg))
5419 (kill-buffer org-last-indirect-buffer))
5420 (setq ibuf (org-get-indirect-buffer cbuf)
5421 org-last-indirect-buffer ibuf)
5422 (cond
5423 ((or (eq org-indirect-buffer-display 'new-frame)
5424 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5425 (select-frame (make-frame))
5426 (delete-other-windows)
5427 (switch-to-buffer ibuf)
5428 (org-set-frame-title heading))
5429 ((eq org-indirect-buffer-display 'dedicated-frame)
5430 (raise-frame
5431 (select-frame (or (and org-indirect-dedicated-frame
5432 (frame-live-p org-indirect-dedicated-frame)
5433 org-indirect-dedicated-frame)
5434 (setq org-indirect-dedicated-frame (make-frame)))))
5435 (delete-other-windows)
5436 (switch-to-buffer ibuf)
5437 (org-set-frame-title (concat "Indirect: " heading)))
5438 ((eq org-indirect-buffer-display 'current-window)
5439 (switch-to-buffer ibuf))
5440 ((eq org-indirect-buffer-display 'other-window)
5441 (pop-to-buffer ibuf))
5442 (t (error "Invalid value.")))
5443 (if (featurep 'xemacs)
5444 (save-excursion (org-mode) (turn-on-font-lock)))
5445 (narrow-to-region beg end)
5446 (show-all)
5447 (goto-char pos)
5448 (and (window-live-p cwin) (select-window cwin))))
5450 (defun org-get-indirect-buffer (&optional buffer)
5451 (setq buffer (or buffer (current-buffer)))
5452 (let ((n 1) (base (buffer-name buffer)) bname)
5453 (while (buffer-live-p
5454 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5455 (setq n (1+ n)))
5456 (condition-case nil
5457 (make-indirect-buffer buffer bname 'clone)
5458 (error (make-indirect-buffer buffer bname)))))
5460 (defun org-set-frame-title (title)
5461 "Set the title of the current frame to the string TITLE."
5462 ;; FIXME: how to name a single frame in XEmacs???
5463 (unless (featurep 'xemacs)
5464 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5466 ;;;; Structure editing
5468 ;;; Inserting headlines
5470 (defun org-previous-line-empty-p ()
5471 (save-excursion
5472 (and (not (bobp))
5473 (or (beginning-of-line 0) t)
5474 (save-match-data
5475 (looking-at "[ \t]*$")))))
5477 (defun org-insert-heading (&optional force-heading)
5478 "Insert a new heading or item with same depth at point.
5479 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5480 If point is at the beginning of a headline, insert a sibling before the
5481 current headline. If point is not at the beginning, do not split the line,
5482 but create the new headline after the current line."
5483 (interactive "P")
5484 (if (= (buffer-size) 0)
5485 (insert "\n* ")
5486 (when (or force-heading (not (org-insert-item)))
5487 (let* ((empty-line-p nil)
5488 (head (save-excursion
5489 (condition-case nil
5490 (progn
5491 (org-back-to-heading)
5492 (setq empty-line-p (org-previous-line-empty-p))
5493 (match-string 0))
5494 (error "*"))))
5495 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5496 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5497 pos hide-previous previous-pos)
5498 (cond
5499 ((and (org-on-heading-p) (bolp)
5500 (or (bobp)
5501 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5502 ;; insert before the current line
5503 (open-line (if blank 2 1)))
5504 ((and (bolp)
5505 (or (bobp)
5506 (save-excursion
5507 (backward-char 1) (not (org-invisible-p)))))
5508 ;; insert right here
5509 nil)
5511 ;; somewhere in the line
5512 (save-excursion
5513 (setq previous-pos (point-at-bol))
5514 (end-of-line)
5515 (setq hide-previous (org-invisible-p)))
5516 (and org-insert-heading-respect-content (org-show-subtree))
5517 (let ((split
5518 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5519 (save-excursion
5520 (let ((p (point)))
5521 (goto-char (point-at-bol))
5522 (and (looking-at org-complex-heading-regexp)
5523 (> p (match-beginning 4)))))))
5524 tags pos)
5525 (cond
5526 (org-insert-heading-respect-content
5527 (org-end-of-subtree nil t)
5528 (or (bolp) (newline))
5529 (or (org-previous-line-empty-p)
5530 (and blank (newline)))
5531 (open-line 1))
5532 ((org-on-heading-p)
5533 (when hide-previous
5534 (show-children)
5535 (org-show-entry))
5536 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5537 (setq tags (and (match-end 2) (match-string 2)))
5538 (and (match-end 1)
5539 (delete-region (match-beginning 1) (match-end 1)))
5540 (setq pos (point-at-bol))
5541 (or split (end-of-line 1))
5542 (delete-horizontal-space)
5543 (newline (if blank 2 1))
5544 (when tags
5545 (save-excursion
5546 (goto-char pos)
5547 (end-of-line 1)
5548 (insert " " tags)
5549 (org-set-tags nil 'align))))
5551 (or split (end-of-line 1))
5552 (newline (if blank 2 1)))))))
5553 (insert head) (just-one-space)
5554 (setq pos (point))
5555 (end-of-line 1)
5556 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5557 (when (and org-insert-heading-respect-content hide-previous)
5558 (save-excursion
5559 (goto-char previous-pos)
5560 (hide-subtree)))
5561 (run-hooks 'org-insert-heading-hook)))))
5563 (defun org-get-heading (&optional no-tags)
5564 "Return the heading of the current entry, without the stars."
5565 (save-excursion
5566 (org-back-to-heading t)
5567 (if (looking-at
5568 (if no-tags
5569 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5570 "\\*+[ \t]+\\([^\r\n]*\\)"))
5571 (match-string 1) "")))
5573 (defun org-heading-components ()
5574 "Return the components of the current heading.
5575 This is a list with the following elements:
5576 - the level as an integer
5577 - the reduced level, different if `org-odd-levels-only' is set.
5578 - the TODO keyword, or nil
5579 - the priority character, like ?A, or nil if no priority is given
5580 - the headline text itself, or the tags string if no headline text
5581 - the tags string, or nil."
5582 (save-excursion
5583 (org-back-to-heading t)
5584 (if (looking-at org-complex-heading-regexp)
5585 (list (length (match-string 1))
5586 (org-reduced-level (length (match-string 1)))
5587 (org-match-string-no-properties 2)
5588 (and (match-end 3) (aref (match-string 3) 2))
5589 (org-match-string-no-properties 4)
5590 (org-match-string-no-properties 5)))))
5592 (defun org-get-entry ()
5593 "Get the entry text, after heading, entire subtree."
5594 (save-excursion
5595 (org-back-to-heading t)
5596 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
5598 (defun org-insert-heading-after-current ()
5599 "Insert a new heading with same level as current, after current subtree."
5600 (interactive)
5601 (org-back-to-heading)
5602 (org-insert-heading)
5603 (org-move-subtree-down)
5604 (end-of-line 1))
5606 (defun org-insert-heading-respect-content ()
5607 (interactive)
5608 (let ((org-insert-heading-respect-content t))
5609 (org-insert-heading t)))
5611 (defun org-insert-todo-heading-respect-content (&optional force-state)
5612 (interactive "P")
5613 (let ((org-insert-heading-respect-content t))
5614 (org-insert-todo-heading force-state t)))
5616 (defun org-insert-todo-heading (arg &optional force-heading)
5617 "Insert a new heading with the same level and TODO state as current heading.
5618 If the heading has no TODO state, or if the state is DONE, use the first
5619 state (TODO by default). Also with prefix arg, force first state."
5620 (interactive "P")
5621 (when (or force-heading (not (org-insert-item 'checkbox)))
5622 (org-insert-heading force-heading)
5623 (save-excursion
5624 (org-back-to-heading)
5625 (outline-previous-heading)
5626 (looking-at org-todo-line-regexp))
5627 (let*
5628 ((new-mark-x
5629 (if (or arg
5630 (not (match-beginning 2))
5631 (member (match-string 2) org-done-keywords))
5632 (car org-todo-keywords-1)
5633 (match-string 2)))
5634 (new-mark
5636 (run-hook-with-args-until-success
5637 'org-todo-get-default-hook new-mark-x nil)
5638 new-mark-x)))
5639 (beginning-of-line 1)
5640 (and (looking-at "\\*+ ") (goto-char (match-end 0))
5641 (if org-treat-insert-todo-heading-as-state-change
5642 (org-todo new-mark)
5643 (insert new-mark " "))))
5644 (when org-provide-todo-statistics
5645 (org-update-parent-todo-statistics))))
5647 (defun org-insert-subheading (arg)
5648 "Insert a new subheading and demote it.
5649 Works for outline headings and for plain lists alike."
5650 (interactive "P")
5651 (org-insert-heading arg)
5652 (cond
5653 ((org-on-heading-p) (org-do-demote))
5654 ((org-at-item-p) (org-indent-item 1))))
5656 (defun org-insert-todo-subheading (arg)
5657 "Insert a new subheading with TODO keyword or checkbox and demote it.
5658 Works for outline headings and for plain lists alike."
5659 (interactive "P")
5660 (org-insert-todo-heading arg)
5661 (cond
5662 ((org-on-heading-p) (org-do-demote))
5663 ((org-at-item-p) (org-indent-item 1))))
5665 ;;; Promotion and Demotion
5667 (defun org-promote-subtree ()
5668 "Promote the entire subtree.
5669 See also `org-promote'."
5670 (interactive)
5671 (save-excursion
5672 (org-map-tree 'org-promote))
5673 (org-fix-position-after-promote))
5675 (defun org-demote-subtree ()
5676 "Demote the entire subtree. See `org-demote'.
5677 See also `org-promote'."
5678 (interactive)
5679 (save-excursion
5680 (org-map-tree 'org-demote))
5681 (org-fix-position-after-promote))
5684 (defun org-do-promote ()
5685 "Promote the current heading higher up the tree.
5686 If the region is active in `transient-mark-mode', promote all headings
5687 in the region."
5688 (interactive)
5689 (save-excursion
5690 (if (org-region-active-p)
5691 (org-map-region 'org-promote (region-beginning) (region-end))
5692 (org-promote)))
5693 (org-fix-position-after-promote))
5695 (defun org-do-demote ()
5696 "Demote the current heading lower down the tree.
5697 If the region is active in `transient-mark-mode', demote all headings
5698 in the region."
5699 (interactive)
5700 (save-excursion
5701 (if (org-region-active-p)
5702 (org-map-region 'org-demote (region-beginning) (region-end))
5703 (org-demote)))
5704 (org-fix-position-after-promote))
5706 (defun org-fix-position-after-promote ()
5707 "Make sure that after pro/demotion cursor position is right."
5708 (let ((pos (point)))
5709 (when (save-excursion
5710 (beginning-of-line 1)
5711 (looking-at org-todo-line-regexp)
5712 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5713 (cond ((eobp) (insert " "))
5714 ((eolp) (insert " "))
5715 ((equal (char-after) ?\ ) (forward-char 1))))))
5717 (defun org-reduced-level (l)
5718 "Compute the effective level of a heading.
5719 This takes into account the setting of `org-odd-levels-only'."
5720 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5722 (defun org-get-valid-level (level &optional change)
5723 "Rectify a level change under the influence of `org-odd-levels-only'
5724 LEVEL is a current level, CHANGE is by how much the level should be
5725 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5726 even level numbers will become the next higher odd number."
5727 (if org-odd-levels-only
5728 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5729 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5730 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5731 (max 1 (+ level (or change 0)))))
5733 (if (boundp 'define-obsolete-function-alias)
5734 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5735 (define-obsolete-function-alias 'org-get-legal-level
5736 'org-get-valid-level)
5737 (define-obsolete-function-alias 'org-get-legal-level
5738 'org-get-valid-level "23.1")))
5740 (defun org-promote ()
5741 "Promote the current heading higher up the tree.
5742 If the region is active in `transient-mark-mode', promote all headings
5743 in the region."
5744 (org-back-to-heading t)
5745 (let* ((level (save-match-data (funcall outline-level)))
5746 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5747 (diff (abs (- level (length up-head) -1))))
5748 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5749 (replace-match up-head nil t)
5750 ;; Fixup tag positioning
5751 (and org-auto-align-tags (org-set-tags nil t))
5752 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5754 (defun org-demote ()
5755 "Demote the current heading lower down the tree.
5756 If the region is active in `transient-mark-mode', demote all headings
5757 in the region."
5758 (org-back-to-heading t)
5759 (let* ((level (save-match-data (funcall outline-level)))
5760 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5761 (diff (abs (- level (length down-head) -1))))
5762 (replace-match down-head nil t)
5763 ;; Fixup tag positioning
5764 (and org-auto-align-tags (org-set-tags nil t))
5765 (if org-adapt-indentation (org-fixup-indentation diff))))
5767 (defun org-map-tree (fun)
5768 "Call FUN for every heading underneath the current one."
5769 (org-back-to-heading)
5770 (let ((level (funcall outline-level)))
5771 (save-excursion
5772 (funcall fun)
5773 (while (and (progn
5774 (outline-next-heading)
5775 (> (funcall outline-level) level))
5776 (not (eobp)))
5777 (funcall fun)))))
5779 (defun org-map-region (fun beg end)
5780 "Call FUN for every heading between BEG and END."
5781 (let ((org-ignore-region t))
5782 (save-excursion
5783 (setq end (copy-marker end))
5784 (goto-char beg)
5785 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5786 (< (point) end))
5787 (funcall fun))
5788 (while (and (progn
5789 (outline-next-heading)
5790 (< (point) end))
5791 (not (eobp)))
5792 (funcall fun)))))
5794 (defun org-fixup-indentation (diff)
5795 "Change the indentation in the current entry by DIFF
5796 However, if any line in the current entry has no indentation, or if it
5797 would end up with no indentation after the change, nothing at all is done."
5798 (save-excursion
5799 (let ((end (save-excursion (outline-next-heading)
5800 (point-marker)))
5801 (prohibit (if (> diff 0)
5802 "^\\S-"
5803 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5804 col)
5805 (unless (save-excursion (end-of-line 1)
5806 (re-search-forward prohibit end t))
5807 (while (and (< (point) end)
5808 (re-search-forward "^[ \t]+" end t))
5809 (goto-char (match-end 0))
5810 (setq col (current-column))
5811 (if (< diff 0) (replace-match ""))
5812 (org-indent-to-column (+ diff col))))
5813 (move-marker end nil))))
5815 (defun org-convert-to-odd-levels ()
5816 "Convert an org-mode file with all levels allowed to one with odd levels.
5817 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5818 level 5 etc."
5819 (interactive)
5820 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5821 (let ((org-odd-levels-only nil) n)
5822 (save-excursion
5823 (goto-char (point-min))
5824 (while (re-search-forward "^\\*\\*+ " nil t)
5825 (setq n (- (length (match-string 0)) 2))
5826 (while (>= (setq n (1- n)) 0)
5827 (org-demote))
5828 (end-of-line 1))))))
5831 (defun org-convert-to-oddeven-levels ()
5832 "Convert an org-mode file with only odd levels to one with odd and even levels.
5833 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5834 section with an even level, conversion would destroy the structure of the file. An error
5835 is signaled in this case."
5836 (interactive)
5837 (goto-char (point-min))
5838 ;; First check if there are no even levels
5839 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5840 (org-show-context t)
5841 (error "Not all levels are odd in this file. Conversion not possible."))
5842 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5843 (let ((org-odd-levels-only nil) n)
5844 (save-excursion
5845 (goto-char (point-min))
5846 (while (re-search-forward "^\\*\\*+ " nil t)
5847 (setq n (/ (1- (length (match-string 0))) 2))
5848 (while (>= (setq n (1- n)) 0)
5849 (org-promote))
5850 (end-of-line 1))))))
5852 (defun org-tr-level (n)
5853 "Make N odd if required."
5854 (if org-odd-levels-only (1+ (/ n 2)) n))
5856 ;;; Vertical tree motion, cutting and pasting of subtrees
5858 (defun org-move-subtree-up (&optional arg)
5859 "Move the current subtree up past ARG headlines of the same level."
5860 (interactive "p")
5861 (org-move-subtree-down (- (prefix-numeric-value arg))))
5863 (defun org-move-subtree-down (&optional arg)
5864 "Move the current subtree down past ARG headlines of the same level."
5865 (interactive "p")
5866 (setq arg (prefix-numeric-value arg))
5867 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5868 'outline-get-last-sibling))
5869 (ins-point (make-marker))
5870 (cnt (abs arg))
5871 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5872 ;; Select the tree
5873 (org-back-to-heading)
5874 (setq beg0 (point))
5875 (save-excursion
5876 (setq ne-beg (org-back-over-empty-lines))
5877 (setq beg (point)))
5878 (save-match-data
5879 (save-excursion (outline-end-of-heading)
5880 (setq folded (org-invisible-p)))
5881 (outline-end-of-subtree))
5882 (outline-next-heading)
5883 (setq ne-end (org-back-over-empty-lines))
5884 (setq end (point))
5885 (goto-char beg0)
5886 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5887 ;; include less whitespace
5888 (save-excursion
5889 (goto-char beg)
5890 (forward-line (- ne-beg ne-end))
5891 (setq beg (point))))
5892 ;; Find insertion point, with error handling
5893 (while (> cnt 0)
5894 (or (and (funcall movfunc) (looking-at outline-regexp))
5895 (progn (goto-char beg0)
5896 (error "Cannot move past superior level or buffer limit")))
5897 (setq cnt (1- cnt)))
5898 (if (> arg 0)
5899 ;; Moving forward - still need to move over subtree
5900 (progn (org-end-of-subtree t t)
5901 (save-excursion
5902 (org-back-over-empty-lines)
5903 (or (bolp) (newline)))))
5904 (setq ne-ins (org-back-over-empty-lines))
5905 (move-marker ins-point (point))
5906 (setq txt (buffer-substring beg end))
5907 (org-save-markers-in-region beg end)
5908 (delete-region beg end)
5909 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5910 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5911 (and (not (bolp)) (looking-at "\n") (forward-char 1))
5912 (let ((bbb (point)))
5913 (insert-before-markers txt)
5914 (org-reinstall-markers-in-region bbb)
5915 (move-marker ins-point bbb))
5916 (or (bolp) (insert "\n"))
5917 (setq ins-end (point))
5918 (goto-char ins-point)
5919 (org-skip-whitespace)
5920 (when (and (< arg 0)
5921 (org-first-sibling-p)
5922 (> ne-ins ne-beg))
5923 ;; Move whitespace back to beginning
5924 (save-excursion
5925 (goto-char ins-end)
5926 (let ((kill-whole-line t))
5927 (kill-line (- ne-ins ne-beg)) (point)))
5928 (insert (make-string (- ne-ins ne-beg) ?\n)))
5929 (move-marker ins-point nil)
5930 (org-compact-display-after-subtree-move)
5931 (org-show-empty-lines-in-parent)
5932 (unless folded
5933 (org-show-entry)
5934 (show-children)
5935 (org-cycle-hide-drawers 'children))))
5937 (defvar org-subtree-clip ""
5938 "Clipboard for cut and paste of subtrees.
5939 This is actually only a copy of the kill, because we use the normal kill
5940 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5942 (defvar org-subtree-clip-folded nil
5943 "Was the last copied subtree folded?
5944 This is used to fold the tree back after pasting.")
5946 (defun org-cut-subtree (&optional n)
5947 "Cut the current subtree into the clipboard.
5948 With prefix arg N, cut this many sequential subtrees.
5949 This is a short-hand for marking the subtree and then cutting it."
5950 (interactive "p")
5951 (org-copy-subtree n 'cut))
5953 (defun org-copy-subtree (&optional n cut force-store-markers)
5954 "Cut the current subtree into the clipboard.
5955 With prefix arg N, cut this many sequential subtrees.
5956 This is a short-hand for marking the subtree and then copying it.
5957 If CUT is non-nil, actually cut the subtree.
5958 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5959 of some markers in the region, even if CUT is non-nil. This is
5960 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5961 (interactive "p")
5962 (let (beg end folded (beg0 (point)))
5963 (if (interactive-p)
5964 (org-back-to-heading nil) ; take what looks like a subtree
5965 (org-back-to-heading t)) ; take what is really there
5966 (org-back-over-empty-lines)
5967 (setq beg (point))
5968 (skip-chars-forward " \t\r\n")
5969 (save-match-data
5970 (save-excursion (outline-end-of-heading)
5971 (setq folded (org-invisible-p)))
5972 (condition-case nil
5973 (outline-forward-same-level (1- n))
5974 (error nil))
5975 (org-end-of-subtree t t))
5976 (org-back-over-empty-lines)
5977 (setq end (point))
5978 (goto-char beg0)
5979 (when (> end beg)
5980 (setq org-subtree-clip-folded folded)
5981 (when (or cut force-store-markers)
5982 (org-save-markers-in-region beg end))
5983 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5984 (setq org-subtree-clip (current-kill 0))
5985 (message "%s: Subtree(s) with %d characters"
5986 (if cut "Cut" "Copied")
5987 (length org-subtree-clip)))))
5989 (defun org-paste-subtree (&optional level tree for-yank)
5990 "Paste the clipboard as a subtree, with modification of headline level.
5991 The entire subtree is promoted or demoted in order to match a new headline
5992 level.
5994 If the cursor is at the beginning of a headline, the same level as
5995 that headline is used to paste the tree
5997 If not, the new level is derived from the *visible* headings
5998 before and after the insertion point, and taken to be the inferior headline
5999 level of the two. So if the previous visible heading is level 3 and the
6000 next is level 4 (or vice versa), level 4 will be used for insertion.
6001 This makes sure that the subtree remains an independent subtree and does
6002 not swallow low level entries.
6004 You can also force a different level, either by using a numeric prefix
6005 argument, or by inserting the heading marker by hand. For example, if the
6006 cursor is after \"*****\", then the tree will be shifted to level 5.
6008 If optional TREE is given, use this text instead of the kill ring.
6010 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6011 move back over whitespace before inserting, and move point to the end of
6012 the inserted text when done."
6013 (interactive "P")
6014 (unless (org-kill-is-subtree-p tree)
6015 (error "%s"
6016 (substitute-command-keys
6017 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6018 (let* ((visp (not (org-invisible-p)))
6019 (txt (or tree (and kill-ring (current-kill 0))))
6020 (^re (concat "^\\(" outline-regexp "\\)"))
6021 (re (concat "\\(" outline-regexp "\\)"))
6022 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6024 (old-level (if (string-match ^re txt)
6025 (- (match-end 0) (match-beginning 0) 1)
6026 -1))
6027 (force-level (cond (level (prefix-numeric-value level))
6028 ((and (looking-at "[ \t]*$")
6029 (string-match
6030 ^re_ (buffer-substring
6031 (point-at-bol) (point))))
6032 (- (match-end 1) (match-beginning 1)))
6033 ((and (bolp)
6034 (looking-at org-outline-regexp))
6035 (- (match-end 0) (point) 1))
6036 (t nil)))
6037 (previous-level (save-excursion
6038 (condition-case nil
6039 (progn
6040 (outline-previous-visible-heading 1)
6041 (if (looking-at re)
6042 (- (match-end 0) (match-beginning 0) 1)
6044 (error 1))))
6045 (next-level (save-excursion
6046 (condition-case nil
6047 (progn
6048 (or (looking-at outline-regexp)
6049 (outline-next-visible-heading 1))
6050 (if (looking-at re)
6051 (- (match-end 0) (match-beginning 0) 1)
6053 (error 1))))
6054 (new-level (or force-level (max previous-level next-level)))
6055 (shift (if (or (= old-level -1)
6056 (= new-level -1)
6057 (= old-level new-level))
6059 (- new-level old-level)))
6060 (delta (if (> shift 0) -1 1))
6061 (func (if (> shift 0) 'org-demote 'org-promote))
6062 (org-odd-levels-only nil)
6063 beg end newend)
6064 ;; Remove the forced level indicator
6065 (if force-level
6066 (delete-region (point-at-bol) (point)))
6067 ;; Paste
6068 (beginning-of-line 1)
6069 (unless for-yank (org-back-over-empty-lines))
6070 (setq beg (point))
6071 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6072 (insert-before-markers txt)
6073 (unless (string-match "\n\\'" txt) (insert "\n"))
6074 (setq newend (point))
6075 (org-reinstall-markers-in-region beg)
6076 (setq end (point))
6077 (goto-char beg)
6078 (skip-chars-forward " \t\n\r")
6079 (setq beg (point))
6080 (if (and (org-invisible-p) visp)
6081 (save-excursion (outline-show-heading)))
6082 ;; Shift if necessary
6083 (unless (= shift 0)
6084 (save-restriction
6085 (narrow-to-region beg end)
6086 (while (not (= shift 0))
6087 (org-map-region func (point-min) (point-max))
6088 (setq shift (+ delta shift)))
6089 (goto-char (point-min))
6090 (setq newend (point-max))))
6091 (when (or (interactive-p) for-yank)
6092 (message "Clipboard pasted as level %d subtree" new-level))
6093 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6094 kill-ring
6095 (eq org-subtree-clip (current-kill 0))
6096 org-subtree-clip-folded)
6097 ;; The tree was folded before it was killed/copied
6098 (hide-subtree))
6099 (and for-yank (goto-char newend))))
6101 (defun org-kill-is-subtree-p (&optional txt)
6102 "Check if the current kill is an outline subtree, or a set of trees.
6103 Returns nil if kill does not start with a headline, or if the first
6104 headline level is not the largest headline level in the tree.
6105 So this will actually accept several entries of equal levels as well,
6106 which is OK for `org-paste-subtree'.
6107 If optional TXT is given, check this string instead of the current kill."
6108 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6109 (start-level (and kill
6110 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6111 org-outline-regexp "\\)")
6112 kill)
6113 (- (match-end 2) (match-beginning 2) 1)))
6114 (re (concat "^" org-outline-regexp))
6115 (start (1+ (or (match-beginning 2) -1))))
6116 (if (not start-level)
6117 (progn
6118 nil) ;; does not even start with a heading
6119 (catch 'exit
6120 (while (setq start (string-match re kill (1+ start)))
6121 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6122 (throw 'exit nil)))
6123 t))))
6125 (defvar org-markers-to-move nil
6126 "Markers that should be moved with a cut-and-paste operation.
6127 Those markers are stored together with their positions relative to
6128 the start of the region.")
6130 (defun org-save-markers-in-region (beg end)
6131 "Check markers in region.
6132 If these markers are between BEG and END, record their position relative
6133 to BEG, so that after moving the block of text, we can put the markers back
6134 into place.
6135 This function gets called just before an entry or tree gets cut from the
6136 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6137 called immediately, to move the markers with the entries."
6138 (setq org-markers-to-move nil)
6139 (when (featurep 'org-clock)
6140 (org-clock-save-markers-for-cut-and-paste beg end))
6141 (when (featurep 'org-agenda)
6142 (org-agenda-save-markers-for-cut-and-paste beg end)))
6144 (defun org-check-and-save-marker (marker beg end)
6145 "Check if MARKER is between BEG and END.
6146 If yes, remember the marker and the distance to BEG."
6147 (when (and (marker-buffer marker)
6148 (equal (marker-buffer marker) (current-buffer)))
6149 (if (and (>= marker beg) (< marker end))
6150 (push (cons marker (- marker beg)) org-markers-to-move))))
6152 (defun org-reinstall-markers-in-region (beg)
6153 "Move all remembered markers to their position relative to BEG."
6154 (mapc (lambda (x)
6155 (move-marker (car x) (+ beg (cdr x))))
6156 org-markers-to-move)
6157 (setq org-markers-to-move nil))
6159 (defun org-narrow-to-subtree ()
6160 "Narrow buffer to the current subtree."
6161 (interactive)
6162 (save-excursion
6163 (save-match-data
6164 (narrow-to-region
6165 (progn (org-back-to-heading) (point))
6166 (progn (org-end-of-subtree t) (point))))))
6168 (defun org-clone-subtree-with-time-shift (n &optional shift)
6169 "Clone the task (subtree) at point N times.
6170 The clones will be inserted as siblings.
6172 In interactive use, the user will be prompted for the number of clones
6173 to be produced, and for a time SHIFT, which may be a repeater as used
6174 in time stamps, for example `+3d'.
6176 When a valid repeater is given and the entry contains any time stamps,
6177 the clones will become a sequence in time, with time stamps in the
6178 subtree shifted for each clone produced. If SHIFT is nil or the
6179 empty string, time stamps will be left alone.
6181 If the original subtree did contain time stamps with a repeater,
6182 the following will happen:
6183 - the repeater will be removed in each clone
6184 - an additional clone will be produced, with the current, unshifted
6185 date(s) in the entry.
6186 - the original entry will be placed *after* all the clones, with
6187 repeater intact.
6188 - the start days in the repeater in the original entry will be shifted
6189 to past the last clone.
6190 I this way you can spell out a number of instances of a repeating task,
6191 and still retain the repeater to cover future instances of the task."
6192 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6193 (let (beg end template task
6194 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6195 (if (not (and (integerp n) (> n 0)))
6196 (error "Invalid number of replications %s" n))
6197 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6198 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6199 shift)))
6200 (error "Invalid shift specification %s" shift))
6201 (when doshift
6202 (setq shift-n (string-to-number (match-string 1 shift))
6203 shift-what (cdr (assoc (match-string 2 shift)
6204 '(("d" . day) ("w" . week)
6205 ("m" . month) ("y" . year))))))
6206 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6207 (setq nmin 1 nmax n)
6208 (org-back-to-heading t)
6209 (setq beg (point))
6210 (org-end-of-subtree t t)
6211 (setq end (point))
6212 (setq template (buffer-substring beg end))
6213 (when (and doshift
6214 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6215 (delete-region beg end)
6216 (setq end beg)
6217 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6218 (goto-char end)
6219 (loop for n from nmin to nmax do
6220 (if (not doshift)
6221 (setq task template)
6222 (with-temp-buffer
6223 (insert template)
6224 (org-mode)
6225 (goto-char (point-min))
6226 (while (re-search-forward org-ts-regexp nil t)
6227 (org-timestamp-change (* n shift-n) shift-what))
6228 (unless (= n n-no-remove)
6229 (goto-char (point-min))
6230 (while (re-search-forward org-ts-regexp nil t)
6231 (save-excursion
6232 (goto-char (match-beginning 0))
6233 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6234 (delete-region (match-beginning 1) (match-end 1))))))
6235 (setq task (buffer-string))))
6236 (insert task))
6237 (goto-char beg)))
6239 ;;; Outline Sorting
6241 (defun org-sort (with-case)
6242 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6243 Optional argument WITH-CASE means sort case-sensitively.
6244 With a double prefix argument, also remove duplicate entries."
6245 (interactive "P")
6246 (if (org-at-table-p)
6247 (org-call-with-arg 'org-table-sort-lines with-case)
6248 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6250 (defun org-sort-remove-invisible (s)
6251 (remove-text-properties 0 (length s) org-rm-props s)
6252 (while (string-match org-bracket-link-regexp s)
6253 (setq s (replace-match (if (match-end 2)
6254 (match-string 3 s)
6255 (match-string 1 s)) t t s)))
6258 (defvar org-priority-regexp) ; defined later in the file
6260 (defvar org-after-sorting-entries-or-items-hook nil
6261 "Hook that is run after a bunch of entries or items have been sorted.
6262 When children are sorted, the cursor is in the parent line when this
6263 hook gets called. When a region or a plain list is sorted, the cursor
6264 will be in the first entry of the sorted region/list.")
6266 (defun org-sort-entries-or-items
6267 (&optional with-case sorting-type getkey-func compare-func property)
6268 "Sort entries on a certain level of an outline tree, or plain list items.
6269 If there is an active region, the entries in the region are sorted.
6270 Else, if the cursor is before the first entry, sort the top-level items.
6271 Else, the children of the entry at point are sorted.
6272 If the cursor is at the first item in a plain list, the list items will be
6273 sorted.
6275 Sorting can be alphabetically, numerically, by date/time as given by
6276 a time stamp, by a property or by priority.
6278 The command prompts for the sorting type unless it has been given to the
6279 function through the SORTING-TYPE argument, which needs to a character,
6280 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6281 precise meaning of each character:
6283 n Numerically, by converting the beginning of the entry/item to a number.
6284 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6285 t By date/time, either the first active time stamp in the entry, or, if
6286 none exist, by the first inactive one.
6287 In items, only the first line will be chekced.
6288 s By the scheduled date/time.
6289 d By deadline date/time.
6290 c By creation time, which is assumed to be the first inactive time stamp
6291 at the beginning of a line.
6292 p By priority according to the cookie.
6293 r By the value of a property.
6295 Capital letters will reverse the sort order.
6297 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6298 called with point at the beginning of the record. It must return either
6299 a string or a number that should serve as the sorting key for that record.
6301 Comparing entries ignores case by default. However, with an optional argument
6302 WITH-CASE, the sorting considers case as well."
6303 (interactive "P")
6304 (let ((case-func (if with-case 'identity 'downcase))
6305 start beg end stars re re2
6306 txt what tmp plain-list-p)
6307 ;; Find beginning and end of region to sort
6308 (cond
6309 ((org-region-active-p)
6310 ;; we will sort the region
6311 (setq end (region-end)
6312 what "region")
6313 (goto-char (region-beginning))
6314 (if (not (org-on-heading-p)) (outline-next-heading))
6315 (setq start (point)))
6316 ((org-at-item-p)
6317 ;; we will sort this plain list
6318 (org-beginning-of-item-list) (setq start (point))
6319 (org-end-of-item-list) (setq end (point))
6320 (goto-char start)
6321 (setq plain-list-p t
6322 what "plain list"))
6323 ((or (org-on-heading-p)
6324 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6325 ;; we will sort the children of the current headline
6326 (org-back-to-heading)
6327 (setq start (point)
6328 end (progn (org-end-of-subtree t t)
6329 (org-back-over-empty-lines)
6330 (point))
6331 what "children")
6332 (goto-char start)
6333 (show-subtree)
6334 (outline-next-heading))
6336 ;; we will sort the top-level entries in this file
6337 (goto-char (point-min))
6338 (or (org-on-heading-p) (outline-next-heading))
6339 (setq start (point) end (point-max) what "top-level")
6340 (goto-char start)
6341 (show-all)))
6343 (setq beg (point))
6344 (if (>= beg end) (error "Nothing to sort"))
6346 (unless plain-list-p
6347 (looking-at "\\(\\*+\\)")
6348 (setq stars (match-string 1)
6349 re (concat "^" (regexp-quote stars) " +")
6350 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6351 txt (buffer-substring beg end))
6352 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6353 (if (and (not (equal stars "*")) (string-match re2 txt))
6354 (error "Region to sort contains a level above the first entry")))
6356 (unless sorting-type
6357 (message
6358 (if plain-list-p
6359 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6360 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
6361 [t]ime [s]cheduled [d]eadline [c]reated
6362 A/N/T/S/D/C/P/O/F means reversed:")
6363 what)
6364 (setq sorting-type (read-char-exclusive))
6366 (and (= (downcase sorting-type) ?f)
6367 (setq getkey-func
6368 (org-ido-completing-read "Sort using function: "
6369 obarray 'fboundp t nil nil))
6370 (setq getkey-func (intern getkey-func)))
6372 (and (= (downcase sorting-type) ?r)
6373 (setq property
6374 (org-ido-completing-read "Property: "
6375 (mapcar 'list (org-buffer-property-keys t))
6376 nil t))))
6378 (message "Sorting entries...")
6380 (save-restriction
6381 (narrow-to-region start end)
6383 (let ((dcst (downcase sorting-type))
6384 (case-fold-search nil)
6385 (now (current-time)))
6386 (sort-subr
6387 (/= dcst sorting-type)
6388 ;; This function moves to the beginning character of the "record" to
6389 ;; be sorted.
6390 (if plain-list-p
6391 (lambda nil
6392 (if (org-at-item-p) t (goto-char (point-max))))
6393 (lambda nil
6394 (if (re-search-forward re nil t)
6395 (goto-char (match-beginning 0))
6396 (goto-char (point-max)))))
6397 ;; This function moves to the last character of the "record" being
6398 ;; sorted.
6399 (if plain-list-p
6400 'org-end-of-item
6401 (lambda nil
6402 (save-match-data
6403 (condition-case nil
6404 (outline-forward-same-level 1)
6405 (error
6406 (goto-char (point-max)))))))
6408 ;; This function returns the value that gets sorted against.
6409 (if plain-list-p
6410 (lambda nil
6411 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6412 (cond
6413 ((= dcst ?n)
6414 (string-to-number (buffer-substring (match-end 0)
6415 (point-at-eol))))
6416 ((= dcst ?a)
6417 (buffer-substring (match-end 0) (point-at-eol)))
6418 ((= dcst ?t)
6419 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
6420 (re-search-forward org-ts-regexp-both
6421 (point-at-eol) t))
6422 (org-time-string-to-seconds (match-string 0))
6423 (time-to-seconds now)))
6424 ((= dcst ?f)
6425 (if getkey-func
6426 (progn
6427 (setq tmp (funcall getkey-func))
6428 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6429 tmp)
6430 (error "Invalid key function `%s'" getkey-func)))
6431 (t (error "Invalid sorting type `%c'" sorting-type)))))
6432 (lambda nil
6433 (cond
6434 ((= dcst ?n)
6435 (if (looking-at org-complex-heading-regexp)
6436 (string-to-number (match-string 4))
6437 nil))
6438 ((= dcst ?a)
6439 (if (looking-at org-complex-heading-regexp)
6440 (funcall case-func (match-string 4))
6441 nil))
6442 ((= dcst ?t)
6443 (let ((end (save-excursion (outline-next-heading) (point))))
6444 (if (or (re-search-forward org-ts-regexp end t)
6445 (re-search-forward org-ts-regexp-both end t))
6446 (org-time-string-to-seconds (match-string 0))
6447 (time-to-seconds now))))
6448 ((= dcst ?c)
6449 (let ((end (save-excursion (outline-next-heading) (point))))
6450 (if (re-search-forward
6451 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
6452 end t)
6453 (org-time-string-to-seconds (match-string 0))
6454 (time-to-seconds now))))
6455 ((= dcst ?s)
6456 (let ((end (save-excursion (outline-next-heading) (point))))
6457 (if (re-search-forward org-scheduled-time-regexp end t)
6458 (org-time-string-to-seconds (match-string 1))
6459 (time-to-seconds now))))
6460 ((= dcst ?d)
6461 (let ((end (save-excursion (outline-next-heading) (point))))
6462 (if (re-search-forward org-deadline-time-regexp end t)
6463 (org-time-string-to-seconds (match-string 1))
6464 (time-to-seconds now))))
6465 ((= dcst ?p)
6466 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6467 (string-to-char (match-string 2))
6468 org-default-priority))
6469 ((= dcst ?r)
6470 (or (org-entry-get nil property) ""))
6471 ((= dcst ?o)
6472 (if (looking-at org-complex-heading-regexp)
6473 (- 9999 (length (member (match-string 2)
6474 org-todo-keywords-1)))))
6475 ((= dcst ?f)
6476 (if getkey-func
6477 (progn
6478 (setq tmp (funcall getkey-func))
6479 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6480 tmp)
6481 (error "Invalid key function `%s'" getkey-func)))
6482 (t (error "Invalid sorting type `%c'" sorting-type)))))
6484 (cond
6485 ((= dcst ?a) 'string<)
6486 ((= dcst ?f) compare-func)
6487 ((member dcst '(?p ?t ?s ?d ?c)) '<)
6488 (t nil)))))
6489 (run-hooks 'org-after-sorting-entries-or-items-hook)
6490 (message "Sorting entries...done")))
6492 (defun org-do-sort (table what &optional with-case sorting-type)
6493 "Sort TABLE of WHAT according to SORTING-TYPE.
6494 The user will be prompted for the SORTING-TYPE if the call to this
6495 function does not specify it. WHAT is only for the prompt, to indicate
6496 what is being sorted. The sorting key will be extracted from
6497 the car of the elements of the table.
6498 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6499 (unless sorting-type
6500 (message
6501 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6502 what)
6503 (setq sorting-type (read-char-exclusive)))
6504 (let ((dcst (downcase sorting-type))
6505 extractfun comparefun)
6506 ;; Define the appropriate functions
6507 (cond
6508 ((= dcst ?n)
6509 (setq extractfun 'string-to-number
6510 comparefun (if (= dcst sorting-type) '< '>)))
6511 ((= dcst ?a)
6512 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6513 (lambda(x) (downcase (org-sort-remove-invisible x))))
6514 comparefun (if (= dcst sorting-type)
6515 'string<
6516 (lambda (a b) (and (not (string< a b))
6517 (not (string= a b)))))))
6518 ((= dcst ?t)
6519 (setq extractfun
6520 (lambda (x)
6521 (if (or (string-match org-ts-regexp x)
6522 (string-match org-ts-regexp-both x))
6523 (time-to-seconds
6524 (org-time-string-to-time (match-string 0 x)))
6526 comparefun (if (= dcst sorting-type) '< '>)))
6527 (t (error "Invalid sorting type `%c'" sorting-type)))
6529 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6530 table)
6531 (lambda (a b) (funcall comparefun (car a) (car b))))))
6534 ;;; The orgstruct minor mode
6536 ;; Define a minor mode which can be used in other modes in order to
6537 ;; integrate the org-mode structure editing commands.
6539 ;; This is really a hack, because the org-mode structure commands use
6540 ;; keys which normally belong to the major mode. Here is how it
6541 ;; works: The minor mode defines all the keys necessary to operate the
6542 ;; structure commands, but wraps the commands into a function which
6543 ;; tests if the cursor is currently at a headline or a plain list
6544 ;; item. If that is the case, the structure command is used,
6545 ;; temporarily setting many Org-mode variables like regular
6546 ;; expressions for filling etc. However, when any of those keys is
6547 ;; used at a different location, function uses `key-binding' to look
6548 ;; up if the key has an associated command in another currently active
6549 ;; keymap (minor modes, major mode, global), and executes that
6550 ;; command. There might be problems if any of the keys is otherwise
6551 ;; used as a prefix key.
6553 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6554 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6555 ;; addresses this by checking explicitly for both bindings.
6557 (defvar orgstruct-mode-map (make-sparse-keymap)
6558 "Keymap for the minor `orgstruct-mode'.")
6560 (defvar org-local-vars nil
6561 "List of local variables, for use by `orgstruct-mode'")
6563 ;;;###autoload
6564 (define-minor-mode orgstruct-mode
6565 "Toggle the minor more `orgstruct-mode'.
6566 This mode is for using Org-mode structure commands in other modes.
6567 The following key behave as if Org-mode was active, if the cursor
6568 is on a headline, or on a plain list item (both in the definition
6569 of Org-mode).
6571 M-up Move entry/item up
6572 M-down Move entry/item down
6573 M-left Promote
6574 M-right Demote
6575 M-S-up Move entry/item up
6576 M-S-down Move entry/item down
6577 M-S-left Promote subtree
6578 M-S-right Demote subtree
6579 M-q Fill paragraph and items like in Org-mode
6580 C-c ^ Sort entries
6581 C-c - Cycle list bullet
6582 TAB Cycle item visibility
6583 M-RET Insert new heading/item
6584 S-M-RET Insert new TODO heading / Checkbox item
6585 C-c C-c Set tags / toggle checkbox"
6586 nil " OrgStruct" nil
6587 (org-load-modules-maybe)
6588 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6590 ;;;###autoload
6591 (defun turn-on-orgstruct ()
6592 "Unconditionally turn on `orgstruct-mode'."
6593 (orgstruct-mode 1))
6595 (defun orgstruct++-mode (&optional arg)
6596 "Toggle `orgstruct-mode', the enhanced version of it.
6597 In addition to setting orgstruct-mode, this also exports all indentation and
6598 autofilling variables from org-mode into the buffer. It will also
6599 recognize item context in multiline items.
6600 Note that turning off orgstruct-mode will *not* remove the
6601 indentation/paragraph settings. This can only be done by refreshing the
6602 major mode, for example with \[normal-mode]."
6603 (interactive "P")
6604 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6605 (if (< arg 1)
6606 (orgstruct-mode -1)
6607 (orgstruct-mode 1)
6608 (let (var val)
6609 (mapc
6610 (lambda (x)
6611 (when (string-match
6612 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6613 (symbol-name (car x)))
6614 (setq var (car x) val (nth 1 x))
6615 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6616 org-local-vars)
6617 (org-set-local 'orgstruct-is-++ t))))
6619 (defvar orgstruct-is-++ nil
6620 "Is orgstruct-mode in ++ version in the current-buffer?")
6621 (make-variable-buffer-local 'orgstruct-is-++)
6623 ;;;###autoload
6624 (defun turn-on-orgstruct++ ()
6625 "Unconditionally turn on `orgstruct++-mode'."
6626 (orgstruct++-mode 1))
6628 (defun orgstruct-error ()
6629 "Error when there is no default binding for a structure key."
6630 (interactive)
6631 (error "This key has no function outside structure elements"))
6633 (defun orgstruct-setup ()
6634 "Setup orgstruct keymaps."
6635 (let ((nfunc 0)
6636 (bindings
6637 (list
6638 '([(meta up)] org-metaup)
6639 '([(meta down)] org-metadown)
6640 '([(meta left)] org-metaleft)
6641 '([(meta right)] org-metaright)
6642 '([(meta shift up)] org-shiftmetaup)
6643 '([(meta shift down)] org-shiftmetadown)
6644 '([(meta shift left)] org-shiftmetaleft)
6645 '([(meta shift right)] org-shiftmetaright)
6646 '([?\e (up)] org-metaup)
6647 '([?\e (down)] org-metadown)
6648 '([?\e (left)] org-metaleft)
6649 '([?\e (right)] org-metaright)
6650 '([?\e (shift up)] org-shiftmetaup)
6651 '([?\e (shift down)] org-shiftmetadown)
6652 '([?\e (shift left)] org-shiftmetaleft)
6653 '([?\e (shift right)] org-shiftmetaright)
6654 '([(shift up)] org-shiftup)
6655 '([(shift down)] org-shiftdown)
6656 '([(shift left)] org-shiftleft)
6657 '([(shift right)] org-shiftright)
6658 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6659 '("\M-q" fill-paragraph)
6660 '("\C-c^" org-sort)
6661 '("\C-c-" org-cycle-list-bullet)))
6662 elt key fun cmd)
6663 (while (setq elt (pop bindings))
6664 (setq nfunc (1+ nfunc))
6665 (setq key (org-key (car elt))
6666 fun (nth 1 elt)
6667 cmd (orgstruct-make-binding fun nfunc key))
6668 (org-defkey orgstruct-mode-map key cmd))
6670 ;; Special treatment needed for TAB and RET
6671 (org-defkey orgstruct-mode-map [(tab)]
6672 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6673 (org-defkey orgstruct-mode-map "\C-i"
6674 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6676 (org-defkey orgstruct-mode-map "\M-\C-m"
6677 (orgstruct-make-binding 'org-insert-heading 105
6678 "\M-\C-m" [(meta return)]))
6679 (org-defkey orgstruct-mode-map [(meta return)]
6680 (orgstruct-make-binding 'org-insert-heading 106
6681 [(meta return)] "\M-\C-m"))
6683 (org-defkey orgstruct-mode-map [(shift meta return)]
6684 (orgstruct-make-binding 'org-insert-todo-heading 107
6685 [(meta return)] "\M-\C-m"))
6687 (org-defkey orgstruct-mode-map "\e\C-m"
6688 (orgstruct-make-binding 'org-insert-heading 108
6689 "\e\C-m" [?\e (return)]))
6690 (org-defkey orgstruct-mode-map [?\e (return)]
6691 (orgstruct-make-binding 'org-insert-heading 109
6692 [?\e (return)] "\e\C-m"))
6693 (org-defkey orgstruct-mode-map [?\e (shift return)]
6694 (orgstruct-make-binding 'org-insert-todo-heading 110
6695 [?\e (return)] "\e\C-m"))
6697 (unless org-local-vars
6698 (setq org-local-vars (org-get-local-variables)))
6702 (defun orgstruct-make-binding (fun n &rest keys)
6703 "Create a function for binding in the structure minor mode.
6704 FUN is the command to call inside a table. N is used to create a unique
6705 command name. KEYS are keys that should be checked in for a command
6706 to execute outside of tables."
6707 (eval
6708 (list 'defun
6709 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6710 '(arg)
6711 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6712 "Outside of structure, run the binding of `"
6713 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6714 "'.")
6715 '(interactive "p")
6716 (list 'if
6717 `(org-context-p 'headline 'item
6718 (and orgstruct-is-++
6719 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
6720 'item-body))
6721 (list 'org-run-like-in-org-mode (list 'quote fun))
6722 (list 'let '(orgstruct-mode)
6723 (list 'call-interactively
6724 (append '(or)
6725 (mapcar (lambda (k)
6726 (list 'key-binding k))
6727 keys)
6728 '('orgstruct-error))))))))
6730 (defun org-context-p (&rest contexts)
6731 "Check if local context is any of CONTEXTS.
6732 Possible values in the list of contexts are `table', `headline', and `item'."
6733 (let ((pos (point)))
6734 (goto-char (point-at-bol))
6735 (prog1 (or (and (memq 'table contexts)
6736 (looking-at "[ \t]*|"))
6737 (and (memq 'headline contexts)
6738 ;;????????? (looking-at "\\*+"))
6739 (looking-at outline-regexp))
6740 (and (memq 'item contexts)
6741 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
6742 (and (memq 'item-body contexts)
6743 (org-in-item-p)))
6744 (goto-char pos))))
6746 (defun org-get-local-variables ()
6747 "Return a list of all local variables in an org-mode buffer."
6748 (let (varlist)
6749 (with-current-buffer (get-buffer-create "*Org tmp*")
6750 (erase-buffer)
6751 (org-mode)
6752 (setq varlist (buffer-local-variables)))
6753 (kill-buffer "*Org tmp*")
6754 (delq nil
6755 (mapcar
6756 (lambda (x)
6757 (setq x
6758 (if (symbolp x)
6759 (list x)
6760 (list (car x) (list 'quote (cdr x)))))
6761 (if (string-match
6762 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6763 (symbol-name (car x)))
6764 x nil))
6765 varlist))))
6767 ;;;###autoload
6768 (defun org-run-like-in-org-mode (cmd)
6769 "Run a command, pretending that the current buffer is in Org-mode.
6770 This will temporarily bind local variables that are typically bound in
6771 Org-mode to the values they have in Org-mode, and then interactively
6772 call CMD."
6773 (org-load-modules-maybe)
6774 (unless org-local-vars
6775 (setq org-local-vars (org-get-local-variables)))
6776 (eval (list 'let org-local-vars
6777 (list 'call-interactively (list 'quote cmd)))))
6779 ;;;; Archiving
6781 (defun org-get-category (&optional pos)
6782 "Get the category applying to position POS."
6783 (get-text-property (or pos (point)) 'org-category))
6785 (defun org-refresh-category-properties ()
6786 "Refresh category text properties in the buffer."
6787 (let ((def-cat (cond
6788 ((null org-category)
6789 (if buffer-file-name
6790 (file-name-sans-extension
6791 (file-name-nondirectory buffer-file-name))
6792 "???"))
6793 ((symbolp org-category) (symbol-name org-category))
6794 (t org-category)))
6795 beg end cat pos optionp)
6796 (org-unmodified
6797 (save-excursion
6798 (save-restriction
6799 (widen)
6800 (goto-char (point-min))
6801 (put-text-property (point) (point-max) 'org-category def-cat)
6802 (while (re-search-forward
6803 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6804 (setq pos (match-end 0)
6805 optionp (equal (char-after (match-beginning 0)) ?#)
6806 cat (org-trim (match-string 2)))
6807 (if optionp
6808 (setq beg (point-at-bol) end (point-max))
6809 (org-back-to-heading t)
6810 (setq beg (point) end (org-end-of-subtree t t)))
6811 (put-text-property beg end 'org-category cat)
6812 (goto-char pos)))))))
6815 ;;;; Link Stuff
6817 ;;; Link abbreviations
6819 (defun org-link-expand-abbrev (link)
6820 "Apply replacements as defined in `org-link-abbrev-alist."
6821 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6822 (let* ((key (match-string 1 link))
6823 (as (or (assoc key org-link-abbrev-alist-local)
6824 (assoc key org-link-abbrev-alist)))
6825 (tag (and (match-end 2) (match-string 3 link)))
6826 rpl)
6827 (if (not as)
6828 link
6829 (setq rpl (cdr as))
6830 (cond
6831 ((symbolp rpl) (funcall rpl tag))
6832 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6833 ((string-match "%h" rpl)
6834 (replace-match (url-hexify-string (or tag "")) t t rpl))
6835 (t (concat rpl tag)))))
6836 link))
6838 ;;; Storing and inserting links
6840 (defvar org-insert-link-history nil
6841 "Minibuffer history for links inserted with `org-insert-link'.")
6843 (defvar org-stored-links nil
6844 "Contains the links stored with `org-store-link'.")
6846 (defvar org-store-link-plist nil
6847 "Plist with info about the most recently link created with `org-store-link'.")
6849 (defvar org-link-protocols nil
6850 "Link protocols added to Org-mode using `org-add-link-type'.")
6852 (defvar org-store-link-functions nil
6853 "List of functions that are called to create and store a link.
6854 Each function will be called in turn until one returns a non-nil
6855 value. Each function should check if it is responsible for creating
6856 this link (for example by looking at the major mode).
6857 If not, it must exit and return nil.
6858 If yes, it should return a non-nil value after a calling
6859 `org-store-link-props' with a list of properties and values.
6860 Special properties are:
6862 :type The link prefix. like \"http\". This must be given.
6863 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6864 This is obligatory as well.
6865 :description Optional default description for the second pair
6866 of brackets in an Org-mode link. The user can still change
6867 this when inserting this link into an Org-mode buffer.
6869 In addition to these, any additional properties can be specified
6870 and then used in remember templates.")
6872 (defun org-add-link-type (type &optional follow export)
6873 "Add TYPE to the list of `org-link-types'.
6874 Re-compute all regular expressions depending on `org-link-types'
6876 FOLLOW and EXPORT are two functions.
6878 FOLLOW should take the link path as the single argument and do whatever
6879 is necessary to follow the link, for example find a file or display
6880 a mail message.
6882 EXPORT should format the link path for export to one of the export formats.
6883 It should be a function accepting three arguments:
6885 path the path of the link, the text after the prefix (like \"http:\")
6886 desc the description of the link, if any, nil if there was no description
6887 format the export format, a symbol like `html' or `latex'.
6889 The function may use the FORMAT information to return different values
6890 depending on the format. The return value will be put literally into
6891 the exported file.
6892 Org-mode has a built-in default for exporting links. If you are happy with
6893 this default, there is no need to define an export function for the link
6894 type. For a simple example of an export function, see `org-bbdb.el'."
6895 (add-to-list 'org-link-types type t)
6896 (org-make-link-regexps)
6897 (if (assoc type org-link-protocols)
6898 (setcdr (assoc type org-link-protocols) (list follow export))
6899 (push (list type follow export) org-link-protocols)))
6901 ;;;###autoload
6902 (defun org-store-link (arg)
6903 "\\<org-mode-map>Store an org-link to the current location.
6904 This link is added to `org-stored-links' and can later be inserted
6905 into an org-buffer with \\[org-insert-link].
6907 For some link types, a prefix arg is interpreted:
6908 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6909 For file links, arg negates `org-context-in-file-links'."
6910 (interactive "P")
6911 (org-load-modules-maybe)
6912 (setq org-store-link-plist nil) ; reset
6913 (let (link cpltxt desc description search txt custom-id)
6914 (cond
6916 ((run-hook-with-args-until-success 'org-store-link-functions)
6917 (setq link (plist-get org-store-link-plist :link)
6918 desc (or (plist-get org-store-link-plist :description) link)))
6920 ((equal (buffer-name) "*Org Edit Src Example*")
6921 (let (label gc)
6922 (while (or (not label)
6923 (save-excursion
6924 (save-restriction
6925 (widen)
6926 (goto-char (point-min))
6927 (re-search-forward
6928 (regexp-quote (format org-coderef-label-format label))
6929 nil t))))
6930 (when label (message "Label exists already") (sit-for 2))
6931 (setq label (read-string "Code line label: " label)))
6932 (end-of-line 1)
6933 (setq link (format org-coderef-label-format label))
6934 (setq gc (- 79 (length link)))
6935 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6936 (insert link)
6937 (setq link (concat "(" label ")") desc nil)))
6939 ((eq major-mode 'calendar-mode)
6940 (let ((cd (calendar-cursor-to-date)))
6941 (setq link
6942 (format-time-string
6943 (car org-time-stamp-formats)
6944 (apply 'encode-time
6945 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6946 nil nil nil))))
6947 (org-store-link-props :type "calendar" :date cd)))
6949 ((eq major-mode 'w3-mode)
6950 (setq cpltxt (if (and (buffer-name)
6951 (not (string-match "Untitled" (buffer-name))))
6952 (buffer-name)
6953 (url-view-url t))
6954 link (org-make-link (url-view-url t)))
6955 (org-store-link-props :type "w3" :url (url-view-url t)))
6957 ((eq major-mode 'w3m-mode)
6958 (setq cpltxt (or w3m-current-title w3m-current-url)
6959 link (org-make-link w3m-current-url))
6960 (org-store-link-props :type "w3m" :url (url-view-url t)))
6962 ((setq search (run-hook-with-args-until-success
6963 'org-create-file-search-functions))
6964 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6965 "::" search))
6966 (setq cpltxt (or description link)))
6968 ((eq major-mode 'image-mode)
6969 (setq cpltxt (concat "file:"
6970 (abbreviate-file-name buffer-file-name))
6971 link (org-make-link cpltxt))
6972 (org-store-link-props :type "image" :file buffer-file-name))
6974 ((eq major-mode 'dired-mode)
6975 ;; link to the file in the current line
6976 (setq cpltxt (concat "file:"
6977 (abbreviate-file-name
6978 (expand-file-name
6979 (dired-get-filename nil t))))
6980 link (org-make-link cpltxt)))
6982 ((and buffer-file-name (org-mode-p))
6983 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
6984 (cond
6985 ((org-in-regexp "<<\\(.*?\\)>>")
6986 (setq cpltxt
6987 (concat "file:"
6988 (abbreviate-file-name buffer-file-name)
6989 "::" (match-string 1))
6990 link (org-make-link cpltxt)))
6991 ((and (featurep 'org-id)
6992 (or (eq org-link-to-org-use-id t)
6993 (and (eq org-link-to-org-use-id 'create-if-interactive)
6994 (interactive-p))
6995 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
6996 (interactive-p)
6997 (not custom-id))
6998 (and org-link-to-org-use-id
6999 (condition-case nil
7000 (org-entry-get nil "ID")
7001 (error nil)))))
7002 ;; We can make a link using the ID.
7003 (setq link (condition-case nil
7004 (prog1 (org-id-store-link)
7005 (setq desc (plist-get org-store-link-plist
7006 :description)))
7007 (error
7008 ;; probably before first headline, link to file only
7009 (concat "file:"
7010 (abbreviate-file-name buffer-file-name))))))
7012 ;; Just link to current headline
7013 (setq cpltxt (concat "file:"
7014 (abbreviate-file-name buffer-file-name)))
7015 ;; Add a context search string
7016 (when (org-xor org-context-in-file-links arg)
7017 (setq txt (cond
7018 ((org-on-heading-p) nil)
7019 ((org-region-active-p)
7020 (buffer-substring (region-beginning) (region-end)))
7021 (t nil)))
7022 (when (or (null txt) (string-match "\\S-" txt))
7023 (setq cpltxt
7024 (concat cpltxt "::"
7025 (condition-case nil
7026 (org-make-org-heading-search-string txt)
7027 (error "")))
7028 desc "NONE")))
7029 (if (string-match "::\\'" cpltxt)
7030 (setq cpltxt (substring cpltxt 0 -2)))
7031 (setq link (org-make-link cpltxt)))))
7033 ((buffer-file-name (buffer-base-buffer))
7034 ;; Just link to this file here.
7035 (setq cpltxt (concat "file:"
7036 (abbreviate-file-name
7037 (buffer-file-name (buffer-base-buffer)))))
7038 ;; Add a context string
7039 (when (org-xor org-context-in-file-links arg)
7040 (setq txt (if (org-region-active-p)
7041 (buffer-substring (region-beginning) (region-end))
7042 (buffer-substring (point-at-bol) (point-at-eol))))
7043 ;; Only use search option if there is some text.
7044 (when (string-match "\\S-" txt)
7045 (setq cpltxt
7046 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7047 desc "NONE")))
7048 (setq link (org-make-link cpltxt)))
7050 ((interactive-p)
7051 (error "Cannot link to a buffer which is not visiting a file"))
7053 (t (setq link nil)))
7055 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7056 (setq link (or link cpltxt)
7057 desc (or desc cpltxt))
7058 (if (equal desc "NONE") (setq desc nil))
7060 (if (and (interactive-p) link)
7061 (progn
7062 (setq org-stored-links
7063 (cons (list link desc) org-stored-links))
7064 (message "Stored: %s" (or desc link))
7065 (when custom-id
7066 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7067 "::#" custom-id))
7068 (setq org-stored-links
7069 (cons (list link desc) org-stored-links))))
7070 (and link (org-make-link-string link desc)))))
7072 (defun org-store-link-props (&rest plist)
7073 "Store link properties, extract names and addresses."
7074 (let (x adr)
7075 (when (setq x (plist-get plist :from))
7076 (setq adr (mail-extract-address-components x))
7077 (setq plist (plist-put plist :fromname (car adr)))
7078 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7079 (when (setq x (plist-get plist :to))
7080 (setq adr (mail-extract-address-components x))
7081 (setq plist (plist-put plist :toname (car adr)))
7082 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7083 (let ((from (plist-get plist :from))
7084 (to (plist-get plist :to)))
7085 (when (and from to org-from-is-user-regexp)
7086 (setq plist
7087 (plist-put plist :fromto
7088 (if (string-match org-from-is-user-regexp from)
7089 (concat "to %t")
7090 (concat "from %f"))))))
7091 (setq org-store-link-plist plist))
7093 (defun org-add-link-props (&rest plist)
7094 "Add these properties to the link property list."
7095 (let (key value)
7096 (while plist
7097 (setq key (pop plist) value (pop plist))
7098 (setq org-store-link-plist
7099 (plist-put org-store-link-plist key value)))))
7101 (defun org-email-link-description (&optional fmt)
7102 "Return the description part of an email link.
7103 This takes information from `org-store-link-plist' and formats it
7104 according to FMT (default from `org-email-link-description-format')."
7105 (setq fmt (or fmt org-email-link-description-format))
7106 (let* ((p org-store-link-plist)
7107 (to (plist-get p :toaddress))
7108 (from (plist-get p :fromaddress))
7109 (table
7110 (list
7111 (cons "%c" (plist-get p :fromto))
7112 (cons "%F" (plist-get p :from))
7113 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7114 (cons "%T" (plist-get p :to))
7115 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7116 (cons "%s" (plist-get p :subject))
7117 (cons "%m" (plist-get p :message-id)))))
7118 (when (string-match "%c" fmt)
7119 ;; Check if the user wrote this message
7120 (if (and org-from-is-user-regexp from to
7121 (save-match-data (string-match org-from-is-user-regexp from)))
7122 (setq fmt (replace-match "to %t" t t fmt))
7123 (setq fmt (replace-match "from %f" t t fmt))))
7124 (org-replace-escapes fmt table)))
7126 (defun org-make-org-heading-search-string (&optional string heading)
7127 "Make search string for STRING or current headline."
7128 (interactive)
7129 (let ((s (or string (org-get-heading))))
7130 (unless (and string (not heading))
7131 ;; We are using a headline, clean up garbage in there.
7132 (if (string-match org-todo-regexp s)
7133 (setq s (replace-match "" t t s)))
7134 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7135 (setq s (replace-match "" t t s)))
7136 (setq s (org-trim s))
7137 (if (string-match (concat "^\\(" org-quote-string "\\|"
7138 org-comment-string "\\)") s)
7139 (setq s (replace-match "" t t s)))
7140 (while (string-match org-ts-regexp s)
7141 (setq s (replace-match "" t t s))))
7142 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7143 (setq s (replace-match " " t t s)))
7144 (or string (setq s (concat "*" s))) ; Add * for headlines
7145 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7147 (defun org-make-link (&rest strings)
7148 "Concatenate STRINGS."
7149 (apply 'concat strings))
7151 (defun org-make-link-string (link &optional description)
7152 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7153 (unless (string-match "\\S-" link)
7154 (error "Empty link"))
7155 (when (stringp description)
7156 ;; Remove brackets from the description, they are fatal.
7157 (while (string-match "\\[" description)
7158 (setq description (replace-match "{" t t description)))
7159 (while (string-match "\\]" description)
7160 (setq description (replace-match "}" t t description))))
7161 (when (equal (org-link-escape link) description)
7162 ;; No description needed, it is identical
7163 (setq description nil))
7164 (when (and (not description)
7165 (not (equal link (org-link-escape link))))
7166 (setq description (org-extract-attributes link)))
7167 (concat "[[" (org-link-escape link) "]"
7168 (if description (concat "[" description "]") "")
7169 "]"))
7171 (defconst org-link-escape-chars
7172 '((?\ . "%20")
7173 (?\[ . "%5B")
7174 (?\] . "%5D")
7175 (?\340 . "%E0") ; `a
7176 (?\342 . "%E2") ; ^a
7177 (?\347 . "%E7") ; ,c
7178 (?\350 . "%E8") ; `e
7179 (?\351 . "%E9") ; 'e
7180 (?\352 . "%EA") ; ^e
7181 (?\356 . "%EE") ; ^i
7182 (?\364 . "%F4") ; ^o
7183 (?\371 . "%F9") ; `u
7184 (?\373 . "%FB") ; ^u
7185 (?\; . "%3B")
7186 (?? . "%3F")
7187 (?= . "%3D")
7188 (?+ . "%2B")
7190 "Association list of escapes for some characters problematic in links.
7191 This is the list that is used for internal purposes.")
7193 (defvar org-url-encoding-use-url-hexify nil)
7195 (defconst org-link-escape-chars-browser
7196 '((?\ . "%20")) ; 32 for the SPC char
7197 "Association list of escapes for some characters problematic in links.
7198 This is the list that is used before handing over to the browser.")
7200 (defun org-link-escape (text &optional table)
7201 "Escape characters in TEXT that are problematic for links."
7202 (if org-url-encoding-use-url-hexify
7203 (url-hexify-string text)
7204 (setq table (or table org-link-escape-chars))
7205 (when text
7206 (let ((re (mapconcat (lambda (x) (regexp-quote
7207 (char-to-string (car x))))
7208 table "\\|")))
7209 (while (string-match re text)
7210 (setq text
7211 (replace-match
7212 (cdr (assoc (string-to-char (match-string 0 text))
7213 table))
7214 t t text)))
7215 text))))
7217 (defun org-link-unescape (text &optional table)
7218 "Reverse the action of `org-link-escape'."
7219 (if org-url-encoding-use-url-hexify
7220 (url-unhex-string text)
7221 (setq table (or table org-link-escape-chars))
7222 (when text
7223 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7224 table "\\|")))
7225 (while (string-match re text)
7226 (setq text
7227 (replace-match
7228 (char-to-string (car (rassoc (match-string 0 text) table)))
7229 t t text)))
7230 text))))
7232 (defun org-xor (a b)
7233 "Exclusive or."
7234 (if a (not b) b))
7236 (defun org-fixup-message-id-for-http (s)
7237 "Replace special characters in a message id, so it can be used in an http query."
7238 (while (string-match "<" s)
7239 (setq s (replace-match "%3C" t t s)))
7240 (while (string-match ">" s)
7241 (setq s (replace-match "%3E" t t s)))
7242 (while (string-match "@" s)
7243 (setq s (replace-match "%40" t t s)))
7246 ;;;###autoload
7247 (defun org-insert-link-global ()
7248 "Insert a link like Org-mode does.
7249 This command can be called in any mode to insert a link in Org-mode syntax."
7250 (interactive)
7251 (org-load-modules-maybe)
7252 (org-run-like-in-org-mode 'org-insert-link))
7254 (defun org-insert-link (&optional complete-file link-location)
7255 "Insert a link. At the prompt, enter the link.
7257 Completion can be used to insert any of the link protocol prefixes like
7258 http or ftp in use.
7260 The history can be used to select a link previously stored with
7261 `org-store-link'. When the empty string is entered (i.e. if you just
7262 press RET at the prompt), the link defaults to the most recently
7263 stored link. As SPC triggers completion in the minibuffer, you need to
7264 use M-SPC or C-q SPC to force the insertion of a space character.
7266 You will also be prompted for a description, and if one is given, it will
7267 be displayed in the buffer instead of the link.
7269 If there is already a link at point, this command will allow you to edit link
7270 and description parts.
7272 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7273 be selected using completion. The path to the file will be relative to the
7274 current directory if the file is in the current directory or a subdirectory.
7275 Otherwise, the link will be the absolute path as completed in the minibuffer
7276 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7277 option `org-link-file-path-type'.
7279 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7280 the current directory or below.
7282 With three \\[universal-argument] prefixes, negate the meaning of
7283 `org-keep-stored-link-after-insertion'.
7285 If `org-make-link-description-function' is non-nil, this function will be
7286 called with the link target, and the result will be the default
7287 link description.
7289 If the LINK-LOCATION parameter is non-nil, this value will be
7290 used as the link location instead of reading one interactively."
7291 (interactive "P")
7292 (let* ((wcf (current-window-configuration))
7293 (region (if (org-region-active-p)
7294 (buffer-substring (region-beginning) (region-end))))
7295 (remove (and region (list (region-beginning) (region-end))))
7296 (desc region)
7297 tmphist ; byte-compile incorrectly complains about this
7298 (link link-location)
7299 entry file all-prefixes)
7300 (cond
7301 (link-location) ; specified by arg, just use it.
7302 ((org-in-regexp org-bracket-link-regexp 1)
7303 ;; We do have a link at point, and we are going to edit it.
7304 (setq remove (list (match-beginning 0) (match-end 0)))
7305 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7306 (setq link (read-string "Link: "
7307 (org-link-unescape
7308 (org-match-string-no-properties 1)))))
7309 ((or (org-in-regexp org-angle-link-re)
7310 (org-in-regexp org-plain-link-re))
7311 ;; Convert to bracket link
7312 (setq remove (list (match-beginning 0) (match-end 0))
7313 link (read-string "Link: "
7314 (org-remove-angle-brackets (match-string 0)))))
7315 ((member complete-file '((4) (16)))
7316 ;; Completing read for file names.
7317 (setq link (org-file-complete-link complete-file)))
7319 ;; Read link, with completion for stored links.
7320 (with-output-to-temp-buffer "*Org Links*"
7321 (princ "Insert a link.
7322 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
7323 (when org-stored-links
7324 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7325 (princ (mapconcat
7326 (lambda (x)
7327 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7328 (reverse org-stored-links) "\n"))))
7329 (let ((cw (selected-window)))
7330 (select-window (get-buffer-window "*Org Links*"))
7331 (setq truncate-lines t)
7332 (unless (pos-visible-in-window-p (point-max))
7333 (org-fit-window-to-buffer))
7334 (and (window-live-p cw) (select-window cw)))
7335 ;; Fake a link history, containing the stored links.
7336 (setq tmphist (append (mapcar 'car org-stored-links)
7337 org-insert-link-history))
7338 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
7339 (mapcar 'car org-link-abbrev-alist)
7340 org-link-types))
7341 (unwind-protect
7342 (progn
7343 (setq link
7344 (let ((org-completion-use-ido nil))
7345 (org-completing-read
7346 "Link: "
7347 (mapcar (lambda (x) (list (concat x ":")))
7348 all-prefixes)
7349 nil nil nil
7350 'tmphist
7351 (or (car (car org-stored-links))))))
7352 (if (or (member link all-prefixes)
7353 (and (equal ":" (substring link -1))
7354 (member (substring link 0 -1) all-prefixes)
7355 (setq link (substring link 0 -1))))
7356 (setq link (org-link-try-special-completion link))))
7357 (set-window-configuration wcf)
7358 (kill-buffer "*Org Links*"))
7359 (setq entry (assoc link org-stored-links))
7360 (or entry (push link org-insert-link-history))
7361 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7362 (not org-keep-stored-link-after-insertion))
7363 (setq org-stored-links (delq (assoc link org-stored-links)
7364 org-stored-links)))
7365 (setq desc (or desc (nth 1 entry)))))
7367 (if (string-match org-plain-link-re link)
7368 ;; URL-like link, normalize the use of angular brackets.
7369 (setq link (org-make-link (org-remove-angle-brackets link))))
7371 ;; Check if we are linking to the current file with a search option
7372 ;; If yes, simplify the link by using only the search option.
7373 (when (and buffer-file-name
7374 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7375 (let* ((path (match-string 1 link))
7376 (case-fold-search nil)
7377 (search (match-string 2 link)))
7378 (save-match-data
7379 (if (equal (file-truename buffer-file-name) (file-truename path))
7380 ;; We are linking to this same file, with a search option
7381 (setq link search)))))
7383 ;; Check if we can/should use a relative path. If yes, simplify the link
7384 (when (string-match "^file:\\(.*\\)" link)
7385 (let* ((path (match-string 1 link))
7386 (origpath path)
7387 (case-fold-search nil))
7388 (cond
7389 ((or (eq org-link-file-path-type 'absolute)
7390 (equal complete-file '(16)))
7391 (setq path (abbreviate-file-name (expand-file-name path))))
7392 ((eq org-link-file-path-type 'noabbrev)
7393 (setq path (expand-file-name path)))
7394 ((eq org-link-file-path-type 'relative)
7395 (setq path (file-relative-name path)))
7397 (save-match-data
7398 (if (string-match (concat "^" (regexp-quote
7399 (file-name-as-directory
7400 (expand-file-name "."))))
7401 (expand-file-name path))
7402 ;; We are linking a file with relative path name.
7403 (setq path (substring (expand-file-name path)
7404 (match-end 0)))
7405 (setq path (abbreviate-file-name (expand-file-name path)))))))
7406 (setq link (concat "file:" path))
7407 (if (equal desc origpath)
7408 (setq desc path))))
7410 (if org-make-link-description-function
7411 (setq desc (funcall org-make-link-description-function link desc)))
7413 (setq desc (read-string "Description: " desc))
7414 (unless (string-match "\\S-" desc) (setq desc nil))
7415 (if remove (apply 'delete-region remove))
7416 (insert (org-make-link-string link desc))))
7418 (defun org-link-try-special-completion (type)
7419 "If there is completion support for link type TAPE, offer it."
7420 (let ((fun (intern (concat "org-" type "-complete-link"))))
7421 (if (functionp fun)
7422 (funcall fun)
7423 (read-string "Link (no completion support): " (concat type ":")))))
7425 (defun org-file-complete-link (&optional arg)
7426 "Create a file link using completion."
7427 (let (file link)
7428 (setq file (read-file-name "File: "))
7429 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7430 (pwd1 (file-name-as-directory (abbreviate-file-name
7431 (expand-file-name ".")))))
7432 (cond
7433 ((equal arg '(16))
7434 (setq link (org-make-link
7435 "file:"
7436 (abbreviate-file-name (expand-file-name file)))))
7437 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7438 (setq link (org-make-link "file:" (match-string 1 file))))
7439 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7440 (expand-file-name file))
7441 (setq link (org-make-link
7442 "file:" (match-string 1 (expand-file-name file)))))
7443 (t (setq link (org-make-link "file:" file)))))
7444 link))
7446 (defun org-completing-read (&rest args)
7447 "Completing-read with SPACE being a normal character."
7448 (let ((minibuffer-local-completion-map
7449 (copy-keymap minibuffer-local-completion-map)))
7450 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7451 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7452 (apply 'org-ido-completing-read args)))
7454 (defun org-completing-read-no-ido (&rest args)
7455 (let (org-completion-use-ido)
7456 (apply 'org-completing-read args)))
7458 (defun org-ido-completing-read (&rest args)
7459 "Completing-read using `ido-mode' speedups if available"
7460 (if (and org-completion-use-ido
7461 (fboundp 'ido-completing-read)
7462 (boundp 'ido-mode) ido-mode
7463 (listp (second args)))
7464 (let ((ido-enter-matching-directory nil))
7465 (apply 'ido-completing-read (concat (car args))
7466 (mapcar (lambda (x) (car x)) (nth 1 args))
7467 (cddr args)))
7468 (apply 'completing-read args)))
7470 (defun org-extract-attributes (s)
7471 "Extract the attributes cookie from a string and set as text property."
7472 (let (a attr (start 0) key value)
7473 (save-match-data
7474 (when (string-match "{{\\([^}]+\\)}}$" s)
7475 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7476 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7477 (setq key (match-string 1 a) value (match-string 2 a)
7478 start (match-end 0)
7479 attr (plist-put attr (intern key) value))))
7480 (org-add-props s nil 'org-attr attr))
7483 (defun org-extract-attributes-from-string (tag)
7484 (let (key value attr)
7485 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
7486 (setq key (match-string 1 tag) value (match-string 2 tag)
7487 tag (replace-match "" t t tag)
7488 attr (plist-put attr (intern key) value)))
7489 (cons tag attr)))
7491 (defun org-attributes-to-string (plist)
7492 "Format a property list into an HTML attribute list."
7493 (let ((s "") key value)
7494 (while plist
7495 (setq key (pop plist) value (pop plist))
7496 (and value
7497 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7500 ;;; Opening/following a link
7502 (defvar org-link-search-failed nil)
7504 (defun org-next-link ()
7505 "Move forward to the next link.
7506 If the link is in hidden text, expose it."
7507 (interactive)
7508 (when (and org-link-search-failed (eq this-command last-command))
7509 (goto-char (point-min))
7510 (message "Link search wrapped back to beginning of buffer"))
7511 (setq org-link-search-failed nil)
7512 (let* ((pos (point))
7513 (ct (org-context))
7514 (a (assoc :link ct)))
7515 (if a (goto-char (nth 2 a)))
7516 (if (re-search-forward org-any-link-re nil t)
7517 (progn
7518 (goto-char (match-beginning 0))
7519 (if (org-invisible-p) (org-show-context)))
7520 (goto-char pos)
7521 (setq org-link-search-failed t)
7522 (error "No further link found"))))
7524 (defun org-previous-link ()
7525 "Move backward to the previous link.
7526 If the link is in hidden text, expose it."
7527 (interactive)
7528 (when (and org-link-search-failed (eq this-command last-command))
7529 (goto-char (point-max))
7530 (message "Link search wrapped back to end of buffer"))
7531 (setq org-link-search-failed nil)
7532 (let* ((pos (point))
7533 (ct (org-context))
7534 (a (assoc :link ct)))
7535 (if a (goto-char (nth 1 a)))
7536 (if (re-search-backward org-any-link-re nil t)
7537 (progn
7538 (goto-char (match-beginning 0))
7539 (if (org-invisible-p) (org-show-context)))
7540 (goto-char pos)
7541 (setq org-link-search-failed t)
7542 (error "No further link found"))))
7544 (defun org-translate-link (s)
7545 "Translate a link string if a translation function has been defined."
7546 (if (and org-link-translation-function
7547 (fboundp org-link-translation-function)
7548 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7549 (progn
7550 (setq s (funcall org-link-translation-function
7551 (match-string 1) (match-string 2)))
7552 (concat (car s) ":" (cdr s)))
7555 (defun org-translate-link-from-planner (type path)
7556 "Translate a link from Emacs Planner syntax so that Org can follow it.
7557 This is still an experimental function, your mileage may vary."
7558 (cond
7559 ((member type '("http" "https" "news" "ftp"))
7560 ;; standard Internet links are the same.
7561 nil)
7562 ((and (equal type "irc") (string-match "^//" path))
7563 ;; Planner has two / at the beginning of an irc link, we have 1.
7564 ;; We should have zero, actually....
7565 (setq path (substring path 1)))
7566 ((and (equal type "lisp") (string-match "^/" path))
7567 ;; Planner has a slash, we do not.
7568 (setq type "elisp" path (substring path 1)))
7569 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7570 ;; A typical message link. Planner has the id after the fina slash,
7571 ;; we separate it with a hash mark
7572 (setq path (concat (match-string 1 path) "#"
7573 (org-remove-angle-brackets (match-string 2 path)))))
7575 (cons type path))
7577 (defun org-find-file-at-mouse (ev)
7578 "Open file link or URL at mouse."
7579 (interactive "e")
7580 (mouse-set-point ev)
7581 (org-open-at-point 'in-emacs))
7583 (defun org-open-at-mouse (ev)
7584 "Open file link or URL at mouse."
7585 (interactive "e")
7586 (mouse-set-point ev)
7587 (if (eq major-mode 'org-agenda-mode)
7588 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7589 (org-open-at-point))
7591 (defvar org-window-config-before-follow-link nil
7592 "The window configuration before following a link.
7593 This is saved in case the need arises to restore it.")
7595 (defvar org-open-link-marker (make-marker)
7596 "Marker pointing to the location where `org-open-at-point; was called.")
7598 ;;;###autoload
7599 (defun org-open-at-point-global ()
7600 "Follow a link like Org-mode does.
7601 This command can be called in any mode to follow a link that has
7602 Org-mode syntax."
7603 (interactive)
7604 (org-run-like-in-org-mode 'org-open-at-point))
7606 ;;;###autoload
7607 (defun org-open-link-from-string (s &optional arg)
7608 "Open a link in the string S, as if it was in Org-mode."
7609 (interactive "sLink: \nP")
7610 (let ((reference-buffer (current-buffer)))
7611 (with-temp-buffer
7612 (let ((org-inhibit-startup t))
7613 (org-mode)
7614 (insert s)
7615 (goto-char (point-min))
7616 (org-open-at-point arg reference-buffer)))))
7618 (defun org-open-at-point (&optional in-emacs reference-buffer)
7619 "Open link at or after point.
7620 If there is no link at point, this function will search forward up to
7621 the end of the current line.
7622 Normally, files will be opened by an appropriate application. If the
7623 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7624 With a double prefix argument, try to open outside of Emacs, in the
7625 application the system uses for this file type."
7626 (interactive "P")
7627 (org-load-modules-maybe)
7628 (move-marker org-open-link-marker (point))
7629 (setq org-window-config-before-follow-link (current-window-configuration))
7630 (org-remove-occur-highlights nil nil t)
7631 (cond
7632 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7633 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7634 (org-footnote-action))
7636 (let (type path link line search (pos (point)))
7637 (catch 'match
7638 (save-excursion
7639 (skip-chars-forward "^]\n\r")
7640 (when (org-in-regexp org-bracket-link-regexp)
7641 (setq link (org-extract-attributes
7642 (org-link-unescape (org-match-string-no-properties 1))))
7643 (while (string-match " *\n *" link)
7644 (setq link (replace-match " " t t link)))
7645 (setq link (org-link-expand-abbrev link))
7646 (cond
7647 ((or (file-name-absolute-p link)
7648 (string-match "^\\.\\.?/" link))
7649 (setq type "file" path link))
7650 ((string-match org-link-re-with-space3 link)
7651 (setq type (match-string 1 link) path (match-string 2 link)))
7652 (t (setq type "thisfile" path link)))
7653 (throw 'match t)))
7655 (when (get-text-property (point) 'org-linked-text)
7656 (setq type "thisfile"
7657 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7658 (1+ (point)) (point))
7659 path (buffer-substring
7660 (previous-single-property-change pos 'org-linked-text)
7661 (next-single-property-change pos 'org-linked-text)))
7662 (throw 'match t))
7664 (save-excursion
7665 (when (or (org-in-regexp org-angle-link-re)
7666 (org-in-regexp org-plain-link-re))
7667 (setq type (match-string 1) path (match-string 2))
7668 (throw 'match t)))
7669 (save-excursion
7670 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7671 (setq type "tags"
7672 path (match-string 1))
7673 (while (string-match ":" path)
7674 (setq path (replace-match "+" t t path)))
7675 (throw 'match t)))
7676 (when (org-in-regexp "<\\([^><\n]+\\)>")
7677 (setq type "tree-match"
7678 path (match-string 1))
7679 (throw 'match t)))
7680 (unless path
7681 (error "No link found"))
7683 ;; switch back to reference buffer
7684 ;; needed when if called in a temporary buffer through
7685 ;; org-open-link-from-string
7686 (and reference-buffer (switch-to-buffer reference-buffer))
7688 ;; Remove any trailing spaces in path
7689 (if (string-match " +\\'" path)
7690 (setq path (replace-match "" t t path)))
7691 (if (and org-link-translation-function
7692 (fboundp org-link-translation-function))
7693 ;; Check if we need to translate the link
7694 (let ((tmp (funcall org-link-translation-function type path)))
7695 (setq type (car tmp) path (cdr tmp))))
7697 (cond
7699 ((assoc type org-link-protocols)
7700 (funcall (nth 1 (assoc type org-link-protocols)) path))
7702 ((equal type "mailto")
7703 (let ((cmd (car org-link-mailto-program))
7704 (args (cdr org-link-mailto-program)) args1
7705 (address path) (subject "") a)
7706 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7707 (setq address (match-string 1 path)
7708 subject (org-link-escape (match-string 2 path))))
7709 (while args
7710 (cond
7711 ((not (stringp (car args))) (push (pop args) args1))
7712 (t (setq a (pop args))
7713 (if (string-match "%a" a)
7714 (setq a (replace-match address t t a)))
7715 (if (string-match "%s" a)
7716 (setq a (replace-match subject t t a)))
7717 (push a args1))))
7718 (apply cmd (nreverse args1))))
7720 ((member type '("http" "https" "ftp" "news"))
7721 (browse-url (concat type ":" (org-link-escape
7722 path org-link-escape-chars-browser))))
7724 ((member type '("message"))
7725 (browse-url (concat type ":" path)))
7727 ((string= type "tags")
7728 (org-tags-view in-emacs path))
7729 ((string= type "thisfile")
7730 (if in-emacs
7731 (switch-to-buffer-other-window
7732 (org-get-buffer-for-internal-link (current-buffer)))
7733 (org-mark-ring-push))
7734 (let ((cmd `(org-link-search
7735 ,path
7736 ,(cond ((equal in-emacs '(4)) 'occur)
7737 ((equal in-emacs '(16)) 'org-occur)
7738 (t nil))
7739 ,pos)))
7740 (condition-case nil (eval cmd)
7741 (error (progn (widen) (eval cmd))))))
7743 ((string= type "tree-match")
7744 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7746 ((string= type "file")
7747 (if (string-match "::\\([0-9]+\\)\\'" path)
7748 (setq line (string-to-number (match-string 1 path))
7749 path (substring path 0 (match-beginning 0)))
7750 (if (string-match "::\\(.+\\)\\'" path)
7751 (setq search (match-string 1 path)
7752 path (substring path 0 (match-beginning 0)))))
7753 (if (string-match "[*?{]" (file-name-nondirectory path))
7754 (dired path)
7755 (org-open-file path in-emacs line search)))
7757 ((string= type "news")
7758 (require 'org-gnus)
7759 (org-gnus-follow-link path))
7761 ((string= type "shell")
7762 (let ((cmd path))
7763 (if (or (not org-confirm-shell-link-function)
7764 (funcall org-confirm-shell-link-function
7765 (format "Execute \"%s\" in shell? "
7766 (org-add-props cmd nil
7767 'face 'org-warning))))
7768 (progn
7769 (message "Executing %s" cmd)
7770 (shell-command cmd))
7771 (error "Abort"))))
7773 ((string= type "elisp")
7774 (let ((cmd path))
7775 (if (or (not org-confirm-elisp-link-function)
7776 (funcall org-confirm-elisp-link-function
7777 (format "Execute \"%s\" as elisp? "
7778 (org-add-props cmd nil
7779 'face 'org-warning))))
7780 (message "%s => %s" cmd
7781 (if (equal (string-to-char cmd) ?\()
7782 (eval (read cmd))
7783 (call-interactively (read cmd))))
7784 (error "Abort"))))
7787 (browse-url-at-point))))))
7788 (move-marker org-open-link-marker nil)
7789 (run-hook-with-args 'org-follow-link-hook))
7791 ;;;; Time estimates
7793 (defun org-get-effort (&optional pom)
7794 "Get the effort estimate for the current entry."
7795 (org-entry-get pom org-effort-property))
7797 ;;; File search
7799 (defvar org-create-file-search-functions nil
7800 "List of functions to construct the right search string for a file link.
7801 These functions are called in turn with point at the location to
7802 which the link should point.
7804 A function in the hook should first test if it would like to
7805 handle this file type, for example by checking the major-mode or
7806 the file extension. If it decides not to handle this file, it
7807 should just return nil to give other functions a chance. If it
7808 does handle the file, it must return the search string to be used
7809 when following the link. The search string will be part of the
7810 file link, given after a double colon, and `org-open-at-point'
7811 will automatically search for it. If special measures must be
7812 taken to make the search successful, another function should be
7813 added to the companion hook `org-execute-file-search-functions',
7814 which see.
7816 A function in this hook may also use `setq' to set the variable
7817 `description' to provide a suggestion for the descriptive text to
7818 be used for this link when it gets inserted into an Org-mode
7819 buffer with \\[org-insert-link].")
7821 (defvar org-execute-file-search-functions nil
7822 "List of functions to execute a file search triggered by a link.
7824 Functions added to this hook must accept a single argument, the
7825 search string that was part of the file link, the part after the
7826 double colon. The function must first check if it would like to
7827 handle this search, for example by checking the major-mode or the
7828 file extension. If it decides not to handle this search, it
7829 should just return nil to give other functions a chance. If it
7830 does handle the search, it must return a non-nil value to keep
7831 other functions from trying.
7833 Each function can access the current prefix argument through the
7834 variable `current-prefix-argument'. Note that a single prefix is
7835 used to force opening a link in Emacs, so it may be good to only
7836 use a numeric or double prefix to guide the search function.
7838 In case this is needed, a function in this hook can also restore
7839 the window configuration before `org-open-at-point' was called using:
7841 (set-window-configuration org-window-config-before-follow-link)")
7843 (defun org-link-search (s &optional type avoid-pos)
7844 "Search for a link search option.
7845 If S is surrounded by forward slashes, it is interpreted as a
7846 regular expression. In org-mode files, this will create an `org-occur'
7847 sparse tree. In ordinary files, `occur' will be used to list matches.
7848 If the current buffer is in `dired-mode', grep will be used to search
7849 in all files. If AVOID-POS is given, ignore matches near that position."
7850 (let ((case-fold-search t)
7851 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7852 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7853 (append '(("") (" ") ("\t") ("\n"))
7854 org-emphasis-alist)
7855 "\\|") "\\)"))
7856 (pos (point))
7857 (pre nil) (post nil)
7858 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7859 (cond
7860 ;; First check if there are any special
7861 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7862 ;; Now try the builtin stuff
7863 ((and (equal (string-to-char s0) ?#)
7864 (> (length s0) 1)
7865 (save-excursion
7866 (goto-char (point-min))
7867 (and
7868 (re-search-forward
7869 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
7870 (setq type 'dedicated
7871 pos (match-beginning 0))))
7872 ;; There is an exact target for this
7873 (goto-char pos)
7874 (org-back-to-heading t)))
7875 ((save-excursion
7876 (goto-char (point-min))
7877 (and
7878 (re-search-forward
7879 (concat "<<" (regexp-quote s0) ">>") nil t)
7880 (setq type 'dedicated
7881 pos (match-beginning 0))))
7882 ;; There is an exact target for this
7883 (goto-char pos))
7884 ((and (string-match "^(\\(.*\\))$" s0)
7885 (save-excursion
7886 (goto-char (point-min))
7887 (and
7888 (re-search-forward
7889 (concat "[^[]" (regexp-quote
7890 (format org-coderef-label-format
7891 (match-string 1 s0))))
7892 nil t)
7893 (setq type 'dedicated
7894 pos (1+ (match-beginning 0))))))
7895 ;; There is a coderef target for this
7896 (goto-char pos))
7897 ((string-match "^/\\(.*\\)/$" s)
7898 ;; A regular expression
7899 (cond
7900 ((org-mode-p)
7901 (org-occur (match-string 1 s)))
7902 ;;((eq major-mode 'dired-mode)
7903 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7904 (t (org-do-occur (match-string 1 s)))))
7906 ;; A normal search strings
7907 (when (equal (string-to-char s) ?*)
7908 ;; Anchor on headlines, post may include tags.
7909 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7910 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7911 s (substring s 1)))
7912 (remove-text-properties
7913 0 (length s)
7914 '(face nil mouse-face nil keymap nil fontified nil) s)
7915 ;; Make a series of regular expressions to find a match
7916 (setq words (org-split-string s "[ \n\r\t]+")
7918 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7919 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7920 "\\)" markers)
7921 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7922 re2a (concat "[ \t\r\n]" re2a_)
7923 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7924 re4 (concat "[^a-zA-Z_]" re4_)
7926 re1 (concat pre re2 post)
7927 re3 (concat pre (if pre re4_ re4) post)
7928 re5 (concat pre ".*" re4)
7929 re2 (concat pre re2)
7930 re2a (concat pre (if pre re2a_ re2a))
7931 re4 (concat pre (if pre re4_ re4))
7932 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7933 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7934 re5 "\\)"
7936 (cond
7937 ((eq type 'org-occur) (org-occur reall))
7938 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7939 (t (goto-char (point-min))
7940 (setq type 'fuzzy)
7941 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7942 (org-search-not-self 1 re1 nil t)
7943 (org-search-not-self 1 re2 nil t)
7944 (org-search-not-self 1 re2a nil t)
7945 (org-search-not-self 1 re3 nil t)
7946 (org-search-not-self 1 re4 nil t)
7947 (org-search-not-self 1 re5 nil t)
7949 (goto-char (match-beginning 1))
7950 (goto-char pos)
7951 (error "No match")))))
7953 ;; Normal string-search
7954 (goto-char (point-min))
7955 (if (search-forward s nil t)
7956 (goto-char (match-beginning 0))
7957 (error "No match"))))
7958 (and (org-mode-p) (org-show-context 'link-search))
7959 type))
7961 (defun org-search-not-self (group &rest args)
7962 "Execute `re-search-forward', but only accept matches that do not
7963 enclose the position of `org-open-link-marker'."
7964 (let ((m org-open-link-marker))
7965 (catch 'exit
7966 (while (apply 're-search-forward args)
7967 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7968 (goto-char (match-end group))
7969 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7970 (> (match-beginning 0) (marker-position m))
7971 (< (match-end 0) (marker-position m)))
7972 (save-match-data
7973 (or (not (org-in-regexp
7974 org-bracket-link-analytic-regexp 1))
7975 (not (match-end 4)) ; no description
7976 (and (<= (match-beginning 4) (point))
7977 (>= (match-end 4) (point))))))
7978 (throw 'exit (point))))))))
7980 (defun org-get-buffer-for-internal-link (buffer)
7981 "Return a buffer to be used for displaying the link target of internal links."
7982 (cond
7983 ((not org-display-internal-link-with-indirect-buffer)
7984 buffer)
7985 ((string-match "(Clone)$" (buffer-name buffer))
7986 (message "Buffer is already a clone, not making another one")
7987 ;; we also do not modify visibility in this case
7988 buffer)
7989 (t ; make a new indirect buffer for displaying the link
7990 (let* ((bn (buffer-name buffer))
7991 (ibn (concat bn "(Clone)"))
7992 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7993 (with-current-buffer ib (org-overview))
7994 ib))))
7996 (defun org-do-occur (regexp &optional cleanup)
7997 "Call the Emacs command `occur'.
7998 If CLEANUP is non-nil, remove the printout of the regular expression
7999 in the *Occur* buffer. This is useful if the regex is long and not useful
8000 to read."
8001 (occur regexp)
8002 (when cleanup
8003 (let ((cwin (selected-window)) win beg end)
8004 (when (setq win (get-buffer-window "*Occur*"))
8005 (select-window win))
8006 (goto-char (point-min))
8007 (when (re-search-forward "match[a-z]+" nil t)
8008 (setq beg (match-end 0))
8009 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8010 (setq end (1- (match-beginning 0)))))
8011 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8012 (goto-char (point-min))
8013 (select-window cwin))))
8015 ;;; The mark ring for links jumps
8017 (defvar org-mark-ring nil
8018 "Mark ring for positions before jumps in Org-mode.")
8019 (defvar org-mark-ring-last-goto nil
8020 "Last position in the mark ring used to go back.")
8021 ;; Fill and close the ring
8022 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8023 (loop for i from 1 to org-mark-ring-length do
8024 (push (make-marker) org-mark-ring))
8025 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8026 org-mark-ring)
8028 (defun org-mark-ring-push (&optional pos buffer)
8029 "Put the current position or POS into the mark ring and rotate it."
8030 (interactive)
8031 (setq pos (or pos (point)))
8032 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8033 (move-marker (car org-mark-ring)
8034 (or pos (point))
8035 (or buffer (current-buffer)))
8036 (message "%s"
8037 (substitute-command-keys
8038 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8040 (defun org-mark-ring-goto (&optional n)
8041 "Jump to the previous position in the mark ring.
8042 With prefix arg N, jump back that many stored positions. When
8043 called several times in succession, walk through the entire ring.
8044 Org-mode commands jumping to a different position in the current file,
8045 or to another Org-mode file, automatically push the old position
8046 onto the ring."
8047 (interactive "p")
8048 (let (p m)
8049 (if (eq last-command this-command)
8050 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8051 (setq p org-mark-ring))
8052 (setq org-mark-ring-last-goto p)
8053 (setq m (car p))
8054 (switch-to-buffer (marker-buffer m))
8055 (goto-char m)
8056 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8058 (defun org-remove-angle-brackets (s)
8059 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8060 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8062 (defun org-add-angle-brackets (s)
8063 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8064 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8066 (defun org-remove-double-quotes (s)
8067 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8068 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8071 ;;; Following specific links
8073 (defun org-follow-timestamp-link ()
8074 (cond
8075 ((org-at-date-range-p t)
8076 (let ((org-agenda-start-on-weekday)
8077 (t1 (match-string 1))
8078 (t2 (match-string 2)))
8079 (setq t1 (time-to-days (org-time-string-to-time t1))
8080 t2 (time-to-days (org-time-string-to-time t2)))
8081 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8082 ((org-at-timestamp-p t)
8083 (org-agenda-list nil (time-to-days (org-time-string-to-time
8084 (substring (match-string 1) 0 10)))
8086 (t (error "This should not happen"))))
8089 ;;; Following file links
8090 (defvar org-wait nil)
8091 (defun org-open-file (path &optional in-emacs line search)
8092 "Open the file at PATH.
8093 First, this expands any special file name abbreviations. Then the
8094 configuration variable `org-file-apps' is checked if it contains an
8095 entry for this file type, and if yes, the corresponding command is launched.
8097 If no application is found, Emacs simply visits the file.
8099 With optional prefix argument IN-EMACS, Emacs will visit the file.
8100 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8101 and o use an external application to visit the file.
8103 Optional LINE specifies a line to go to, optional SEARCH a string to
8104 search for. If LINE or SEARCH is given, the file will always be
8105 opened in Emacs.
8106 If the file does not exist, an error is thrown."
8107 (setq in-emacs (or in-emacs line search))
8108 (let* ((file (if (equal path "")
8109 buffer-file-name
8110 (substitute-in-file-name (expand-file-name path))))
8111 (apps (append org-file-apps (org-default-apps)))
8112 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8113 (dirp (if remp nil (file-directory-p file)))
8114 (file (if (and dirp org-open-directory-means-index-dot-org)
8115 (concat (file-name-as-directory file) "index.org")
8116 file))
8117 (a-m-a-p (assq 'auto-mode apps))
8118 (dfile (downcase file))
8119 (old-buffer (current-buffer))
8120 (old-pos (point))
8121 (old-mode major-mode)
8122 ext cmd)
8123 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8124 (setq ext (match-string 1 dfile))
8125 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8126 (setq ext (match-string 1 dfile))))
8127 (cond
8128 ((equal in-emacs '(16))
8129 (setq cmd (cdr (assoc 'system apps))))
8130 (in-emacs (setq cmd 'emacs))
8132 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8133 (and dirp (cdr (assoc 'directory apps)))
8134 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8135 'string-match)
8136 (cdr (assoc ext apps))
8137 (cdr (assoc t apps))))))
8138 (when (eq cmd 'system)
8139 (setq cmd (cdr (assoc 'system apps))))
8140 (when (eq cmd 'default)
8141 (setq cmd (cdr (assoc t apps))))
8142 (when (eq cmd 'mailcap)
8143 (require 'mailcap)
8144 (mailcap-parse-mailcaps)
8145 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8146 (command (mailcap-mime-info mime-type)))
8147 (if (stringp command)
8148 (setq cmd command)
8149 (setq cmd 'emacs))))
8150 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8151 (not (file-exists-p file))
8152 (not org-open-non-existing-files))
8153 (error "No such file: %s" file))
8154 (cond
8155 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8156 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8157 (while (string-match "['\"]%s['\"]" cmd)
8158 (setq cmd (replace-match "%s" t t cmd)))
8159 (while (string-match "%s" cmd)
8160 (setq cmd (replace-match
8161 (save-match-data
8162 (shell-quote-argument
8163 (convert-standard-filename file)))
8164 t t cmd)))
8165 (save-window-excursion
8166 (start-process-shell-command cmd nil cmd)
8167 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8169 ((or (stringp cmd)
8170 (eq cmd 'emacs))
8171 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8172 (widen)
8173 (if line (goto-line line)
8174 (if search (org-link-search search))))
8175 ((consp cmd)
8176 (let ((file (convert-standard-filename file)))
8177 (eval cmd)))
8178 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8179 (and (org-mode-p) (eq old-mode 'org-mode)
8180 (or (not (equal old-buffer (current-buffer)))
8181 (not (equal old-pos (point))))
8182 (org-mark-ring-push old-pos old-buffer))))
8184 (defun org-default-apps ()
8185 "Return the default applications for this operating system."
8186 (cond
8187 ((eq system-type 'darwin)
8188 org-file-apps-defaults-macosx)
8189 ((eq system-type 'windows-nt)
8190 org-file-apps-defaults-windowsnt)
8191 (t org-file-apps-defaults-gnu)))
8193 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8194 "Convert extensions to regular expressions in the cars of LIST.
8195 Also, weed out any non-string entries, because the return value is used
8196 only for regexp matching.
8197 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8198 point to the symbol `emacs', indicating that the file should
8199 be opened in Emacs."
8200 (append
8201 (delq nil
8202 (mapcar (lambda (x)
8203 (if (not (stringp (car x)))
8205 (if (string-match "\\W" (car x))
8207 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8208 list))
8209 (if add-auto-mode
8210 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8212 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8213 (defun org-file-remote-p (file)
8214 "Test whether FILE specifies a location on a remote system.
8215 Return non-nil if the location is indeed remote.
8217 For example, the filename \"/user@host:/foo\" specifies a location
8218 on the system \"/user@host:\"."
8219 (cond ((fboundp 'file-remote-p)
8220 (file-remote-p file))
8221 ((fboundp 'tramp-handle-file-remote-p)
8222 (tramp-handle-file-remote-p file))
8223 ((and (boundp 'ange-ftp-name-format)
8224 (string-match (car ange-ftp-name-format) file))
8226 (t nil)))
8229 ;;;; Refiling
8231 (defun org-get-org-file ()
8232 "Read a filename, with default directory `org-directory'."
8233 (let ((default (or org-default-notes-file remember-data-file)))
8234 (read-file-name (format "File name [%s]: " default)
8235 (file-name-as-directory org-directory)
8236 default)))
8238 (defun org-notes-order-reversed-p ()
8239 "Check if the current file should receive notes in reversed order."
8240 (cond
8241 ((not org-reverse-note-order) nil)
8242 ((eq t org-reverse-note-order) t)
8243 ((not (listp org-reverse-note-order)) nil)
8244 (t (catch 'exit
8245 (let ((all org-reverse-note-order)
8246 entry)
8247 (while (setq entry (pop all))
8248 (if (string-match (car entry) buffer-file-name)
8249 (throw 'exit (cdr entry))))
8250 nil)))))
8252 (defvar org-refile-target-table nil
8253 "The list of refile targets, created by `org-refile'.")
8255 (defvar org-agenda-new-buffers nil
8256 "Buffers created to visit agenda files.")
8258 (defun org-get-refile-targets (&optional default-buffer)
8259 "Produce a table with refile targets."
8260 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
8261 targets txt re files f desc descre fast-path-p level pos0)
8262 (message "Getting targets...")
8263 (with-current-buffer (or default-buffer (current-buffer))
8264 (while (setq entry (pop entries))
8265 (setq files (car entry) desc (cdr entry))
8266 (setq fast-path-p nil)
8267 (cond
8268 ((null files) (setq files (list (current-buffer))))
8269 ((eq files 'org-agenda-files)
8270 (setq files (org-agenda-files 'unrestricted)))
8271 ((and (symbolp files) (fboundp files))
8272 (setq files (funcall files)))
8273 ((and (symbolp files) (boundp files))
8274 (setq files (symbol-value files))))
8275 (if (stringp files) (setq files (list files)))
8276 (cond
8277 ((eq (car desc) :tag)
8278 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8279 ((eq (car desc) :todo)
8280 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8281 ((eq (car desc) :regexp)
8282 (setq descre (cdr desc)))
8283 ((eq (car desc) :level)
8284 (setq descre (concat "^\\*\\{" (number-to-string
8285 (if org-odd-levels-only
8286 (1- (* 2 (cdr desc)))
8287 (cdr desc)))
8288 "\\}[ \t]")))
8289 ((eq (car desc) :maxlevel)
8290 (setq fast-path-p t)
8291 (setq descre (concat "^\\*\\{1," (number-to-string
8292 (if org-odd-levels-only
8293 (1- (* 2 (cdr desc)))
8294 (cdr desc)))
8295 "\\}[ \t]")))
8296 (t (error "Bad refiling target description %s" desc)))
8297 (while (setq f (pop files))
8298 (save-excursion
8299 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
8300 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8301 (setq f (expand-file-name f))
8302 (if (eq org-refile-use-outline-path 'file)
8303 (push (list (file-name-nondirectory f) f nil nil) targets))
8304 (save-excursion
8305 (save-restriction
8306 (widen)
8307 (goto-char (point-min))
8308 (while (re-search-forward descre nil t)
8309 (goto-char (setq pos0 (point-at-bol)))
8310 (catch 'next
8311 (when org-refile-target-verify-function
8312 (save-match-data
8313 (or (funcall org-refile-target-verify-function)
8314 (throw 'next t))))
8315 (when (looking-at org-complex-heading-regexp)
8316 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8317 txt (org-link-display-format (match-string 4))
8318 re (concat "^" (regexp-quote
8319 (buffer-substring (match-beginning 1)
8320 (match-end 4)))))
8321 (if (match-end 5) (setq re (concat re "[ \t]+"
8322 (regexp-quote
8323 (match-string 5)))))
8324 (setq re (concat re "[ \t]*$"))
8325 (when org-refile-use-outline-path
8326 (setq txt (mapconcat 'org-protect-slash
8327 (append
8328 (if (eq org-refile-use-outline-path 'file)
8329 (list (file-name-nondirectory
8330 (buffer-file-name (buffer-base-buffer))))
8331 (if (eq org-refile-use-outline-path 'full-file-path)
8332 (list (buffer-file-name (buffer-base-buffer)))))
8333 (org-get-outline-path fast-path-p level txt)
8334 (list txt))
8335 "/")))
8336 (push (list txt f re (point)) targets)))
8337 (when (= (point) pos0)
8338 ;; verification function has not moved point
8339 (goto-char (point-at-eol))))))))))
8340 (message "Getting targets...done")
8341 (nreverse targets)))
8343 (defun org-protect-slash (s)
8344 (while (string-match "/" s)
8345 (setq s (replace-match "\\" t t s)))
8348 (defvar org-olpa (make-vector 20 nil))
8350 (defun org-get-outline-path (&optional fastp level heading)
8351 "Return the outline path to the current entry, as a list."
8352 (if fastp
8353 (progn
8354 (if (> level 19)
8355 (error "Outline path failure, more than 19 levels."))
8356 (loop for i from level upto 19 do
8357 (aset org-olpa i nil))
8358 (prog1
8359 (delq nil (append org-olpa nil))
8360 (aset org-olpa level heading)))
8361 (let (rtn)
8362 (save-excursion
8363 (while (org-up-heading-safe)
8364 (when (looking-at org-complex-heading-regexp)
8365 (push (org-match-string-no-properties 4) rtn)))
8366 rtn))))
8368 (defvar org-refile-history nil
8369 "History for refiling operations.")
8371 (defvar org-after-refile-insert-hook nil
8372 "Hook run after `org-refile' has inserted its stuff at the new location.
8373 Note that this is still *before* the stuff will be removed from
8374 the *old* location.")
8376 (defun org-refile (&optional goto default-buffer)
8377 "Move the entry at point to another heading.
8378 The list of target headings is compiled using the information in
8379 `org-refile-targets', which see. This list is created before each use
8380 and will therefore always be up-to-date.
8382 At the target location, the entry is filed as a subitem of the target heading.
8383 Depending on `org-reverse-note-order', the new subitem will either be the
8384 first or the last subitem.
8386 If there is an active region, all entries in that region will be moved.
8387 However, the region must fulfil the requirement that the first heading
8388 is the first one sets the top-level of the moved text - at most siblings
8389 below it are allowed.
8391 With prefix arg GOTO, the command will only visit the target location,
8392 not actually move anything.
8393 With a double prefix `C-u C-u', go to the location where the last refiling
8394 operation has put the subtree.
8396 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
8397 (interactive "P")
8398 (let* ((cbuf (current-buffer))
8399 (regionp (org-region-active-p))
8400 (region-start (and regionp (region-beginning)))
8401 (region-end (and regionp (region-end)))
8402 (region-length (and regionp (- region-end region-start)))
8403 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8404 pos it nbuf file re level reversed)
8405 (when regionp (goto-char region-start)
8406 (unless (org-kill-is-subtree-p
8407 (buffer-substring region-start region-end))
8408 (error "The region is not a (sequence of) subtree(s)")))
8409 (if (equal goto '(16))
8410 (org-refile-goto-last-stored)
8411 (when (setq it (org-refile-get-location
8412 (if goto "Goto: " "Refile to: ") default-buffer
8413 org-refile-allow-creating-parent-nodes))
8414 (setq file (nth 1 it)
8415 re (nth 2 it)
8416 pos (nth 3 it))
8417 (if (and (not goto)
8419 (equal (buffer-file-name) file)
8420 (if regionp
8421 (and (>= pos region-start)
8422 (<= pos region-end))
8423 (and (>= pos (point))
8424 (< pos (save-excursion
8425 (org-end-of-subtree t t))))))
8426 (error "Cannot refile to position inside the tree or region"))
8428 (setq nbuf (or (find-buffer-visiting file)
8429 (find-file-noselect file)))
8430 (if goto
8431 (progn
8432 (switch-to-buffer nbuf)
8433 (goto-char pos)
8434 (org-show-context 'org-goto))
8435 (if regionp
8436 (progn
8437 (kill-new (buffer-substring region-start region-end))
8438 (org-save-markers-in-region region-start region-end))
8439 (org-copy-subtree 1 nil t))
8440 (save-excursion
8441 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8442 (find-file-noselect file))))
8443 (setq reversed (org-notes-order-reversed-p))
8444 (save-excursion
8445 (save-restriction
8446 (widen)
8447 (if pos
8448 (progn
8449 (goto-char pos)
8450 (looking-at outline-regexp)
8451 (setq level (org-get-valid-level (funcall outline-level) 1))
8452 (goto-char
8453 (if reversed
8454 (or (outline-next-heading) (point-max))
8455 (or (save-excursion (outline-get-next-sibling))
8456 (org-end-of-subtree t t)
8457 (point-max)))))
8458 (setq level 1)
8459 (if (not reversed)
8460 (goto-char (point-max))
8461 (goto-char (point-min))
8462 (or (outline-next-heading) (goto-char (point-max)))))
8463 (if (not (bolp)) (newline))
8464 (bookmark-set "org-refile-last-stored")
8465 (org-paste-subtree level)
8466 (run-hooks 'org-after-refile-insert-hook))))
8467 (if regionp
8468 (delete-region (point) (+ (point) region-length))
8469 (org-cut-subtree))
8470 (setq org-markers-to-move nil)
8471 (message "Refiled to \"%s\"" (car it))))))
8472 (org-reveal))
8474 (defun org-refile-goto-last-stored ()
8475 "Go to the location where the last refile was stored."
8476 (interactive)
8477 (bookmark-jump "org-refile-last-stored")
8478 (message "This is the location of the last refile"))
8480 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
8481 "Prompt the user for a refile location, using PROMPT."
8482 (let ((org-refile-targets org-refile-targets)
8483 (org-refile-use-outline-path org-refile-use-outline-path))
8484 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8485 (unless org-refile-target-table
8486 (error "No refile targets"))
8487 (let* ((cbuf (current-buffer))
8488 (partial-completion-mode nil)
8489 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8490 (cfunc (if (and org-refile-use-outline-path
8491 org-outline-path-complete-in-steps)
8492 'org-olpath-completing-read
8493 'org-ido-completing-read))
8494 (extra (if org-refile-use-outline-path "/" ""))
8495 (filename (and cfn (expand-file-name cfn)))
8496 (tbl (mapcar
8497 (lambda (x)
8498 (if (and (not (member org-refile-use-outline-path
8499 '(file full-file-path)))
8500 (not (equal filename (nth 1 x))))
8501 (cons (concat (car x) extra " ("
8502 (file-name-nondirectory (nth 1 x)) ")")
8503 (cdr x))
8504 (cons (concat (car x) extra) (cdr x))))
8505 org-refile-target-table))
8506 (completion-ignore-case t)
8507 pa answ parent-target child parent)
8508 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
8509 nil 'org-refile-history))
8510 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
8511 (if pa
8513 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
8514 (setq parent (match-string 1 answ)
8515 child (match-string 2 answ))
8516 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
8517 (when (and parent-target
8518 (or (eq new-nodes t)
8519 (and (eq new-nodes 'confirm)
8520 (y-or-n-p (format "Create new node \"%s\"? " child)))))
8521 (org-refile-new-child parent-target child))))))
8523 (defun org-refile-new-child (parent-target child)
8524 "Use refile target PARENT-TARGET to add new CHILD below it."
8525 (unless parent-target
8526 (error "Cannot find parent for new node"))
8527 (let ((file (nth 1 parent-target))
8528 (pos (nth 3 parent-target))
8529 level)
8530 (with-current-buffer (or (find-buffer-visiting file)
8531 (find-file-noselect file))
8532 (save-excursion
8533 (save-restriction
8534 (widen)
8535 (if pos
8536 (goto-char pos)
8537 (goto-char (point-max))
8538 (if (not (bolp)) (newline)))
8539 (when (looking-at outline-regexp)
8540 (setq level (funcall outline-level))
8541 (org-end-of-subtree t t))
8542 (org-back-over-empty-lines)
8543 (insert "\n" (make-string
8544 (if pos (org-get-valid-level level 1) 1) ?*)
8545 " " child "\n")
8546 (beginning-of-line 0)
8547 (list (concat (car parent-target) "/" child) file "" (point)))))))
8549 (defun org-olpath-completing-read (prompt collection &rest args)
8550 "Read an outline path like a file name."
8551 (let ((thetable collection)
8552 (org-completion-use-ido nil)) ; does not work with ido.
8553 (apply
8554 'org-ido-completing-read prompt
8555 (lambda (string predicate &optional flag)
8556 (let (rtn r f (l (length string)))
8557 (cond
8558 ((eq flag nil)
8559 ;; try completion
8560 (try-completion string thetable))
8561 ((eq flag t)
8562 ;; all-completions
8563 (setq rtn (all-completions string thetable predicate))
8564 (mapcar
8565 (lambda (x)
8566 (setq r (substring x l))
8567 (if (string-match " ([^)]*)$" x)
8568 (setq f (match-string 0 x))
8569 (setq f ""))
8570 (if (string-match "/" r)
8571 (concat string (substring r 0 (match-end 0)) f)
8573 rtn))
8574 ((eq flag 'lambda)
8575 ;; exact match?
8576 (assoc string thetable)))
8578 args)))
8580 ;;;; Dynamic blocks
8582 (defun org-find-dblock (name)
8583 "Find the first dynamic block with name NAME in the buffer.
8584 If not found, stay at current position and return nil."
8585 (let (pos)
8586 (save-excursion
8587 (goto-char (point-min))
8588 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8589 nil t)
8590 (match-beginning 0))))
8591 (if pos (goto-char pos))
8592 pos))
8594 (defconst org-dblock-start-re
8595 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8596 "Matches the startline of a dynamic block, with parameters.")
8598 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8599 "Matches the end of a dynamic block.")
8601 (defun org-create-dblock (plist)
8602 "Create a dynamic block section, with parameters taken from PLIST.
8603 PLIST must contain a :name entry which is used as name of the block."
8604 (unless (bolp) (newline))
8605 (let ((name (plist-get plist :name)))
8606 (insert "#+BEGIN: " name)
8607 (while plist
8608 (if (eq (car plist) :name)
8609 (setq plist (cddr plist))
8610 (insert " " (prin1-to-string (pop plist)))))
8611 (insert "\n\n#+END:\n")
8612 (beginning-of-line -2)))
8614 (defun org-prepare-dblock ()
8615 "Prepare dynamic block for refresh.
8616 This empties the block, puts the cursor at the insert position and returns
8617 the property list including an extra property :name with the block name."
8618 (unless (looking-at org-dblock-start-re)
8619 (error "Not at a dynamic block"))
8620 (let* ((begdel (1+ (match-end 0)))
8621 (name (org-no-properties (match-string 1)))
8622 (params (append (list :name name)
8623 (read (concat "(" (match-string 3) ")")))))
8624 (unless (re-search-forward org-dblock-end-re nil t)
8625 (error "Dynamic block not terminated"))
8626 (setq params
8627 (append params
8628 (list :content (buffer-substring
8629 begdel (match-beginning 0)))))
8630 (delete-region begdel (match-beginning 0))
8631 (goto-char begdel)
8632 (open-line 1)
8633 params))
8635 (defun org-map-dblocks (&optional command)
8636 "Apply COMMAND to all dynamic blocks in the current buffer.
8637 If COMMAND is not given, use `org-update-dblock'."
8638 (let ((cmd (or command 'org-update-dblock))
8639 pos)
8640 (save-excursion
8641 (goto-char (point-min))
8642 (while (re-search-forward org-dblock-start-re nil t)
8643 (goto-char (setq pos (match-beginning 0)))
8644 (condition-case nil
8645 (funcall cmd)
8646 (error (message "Error during update of dynamic block")))
8647 (goto-char pos)
8648 (unless (re-search-forward org-dblock-end-re nil t)
8649 (error "Dynamic block not terminated"))))))
8651 (defun org-dblock-update (&optional arg)
8652 "User command for updating dynamic blocks.
8653 Update the dynamic block at point. With prefix ARG, update all dynamic
8654 blocks in the buffer."
8655 (interactive "P")
8656 (if arg
8657 (org-update-all-dblocks)
8658 (or (looking-at org-dblock-start-re)
8659 (org-beginning-of-dblock))
8660 (org-update-dblock)))
8662 (defun org-update-dblock ()
8663 "Update the dynamic block at point
8664 This means to empty the block, parse for parameters and then call
8665 the correct writing function."
8666 (save-window-excursion
8667 (let* ((pos (point))
8668 (line (org-current-line))
8669 (params (org-prepare-dblock))
8670 (name (plist-get params :name))
8671 (cmd (intern (concat "org-dblock-write:" name))))
8672 (message "Updating dynamic block `%s' at line %d..." name line)
8673 (funcall cmd params)
8674 (message "Updating dynamic block `%s' at line %d...done" name line)
8675 (goto-char pos))))
8677 (defun org-beginning-of-dblock ()
8678 "Find the beginning of the dynamic block at point.
8679 Error if there is no such block at point."
8680 (let ((pos (point))
8681 beg)
8682 (end-of-line 1)
8683 (if (and (re-search-backward org-dblock-start-re nil t)
8684 (setq beg (match-beginning 0))
8685 (re-search-forward org-dblock-end-re nil t)
8686 (> (match-end 0) pos))
8687 (goto-char beg)
8688 (goto-char pos)
8689 (error "Not in a dynamic block"))))
8691 (defun org-update-all-dblocks ()
8692 "Update all dynamic blocks in the buffer.
8693 This function can be used in a hook."
8694 (when (org-mode-p)
8695 (org-map-dblocks 'org-update-dblock)))
8698 ;;;; Completion
8700 (defconst org-additional-option-like-keywords
8701 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8702 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8703 "LATEX_HEADER:"
8704 "BEGIN_EXAMPLE" "END_EXAMPLE"
8705 "BEGIN_QUOTE" "END_QUOTE"
8706 "BEGIN_VERSE" "END_VERSE"
8707 "BEGIN_CENTER" "END_CENTER"
8708 "BEGIN_SRC" "END_SRC"
8709 "CATEGORY" "COLUMNS"
8710 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
8712 (defcustom org-structure-template-alist
8714 ("s" "#+begin_src ?\n\n#+end_src"
8715 "<src lang=\"?\">\n\n</src>")
8716 ("e" "#+begin_example\n?\n#+end_example"
8717 "<example>\n?\n</example>")
8718 ("q" "#+begin_quote\n?\n#+end_quote"
8719 "<quote>\n?\n</quote>")
8720 ("v" "#+begin_verse\n?\n#+end_verse"
8721 "<verse>\n?\n/verse>")
8722 ("c" "#+begin_center\n?\n#+end_center"
8723 "<center>\n?\n/center>")
8724 ("l" "#+begin_latex\n?\n#+end_latex"
8725 "<literal style=\"latex\">\n?\n</literal>")
8726 ("L" "#+latex: "
8727 "<literal style=\"latex\">?</literal>")
8728 ("h" "#+begin_html\n?\n#+end_html"
8729 "<literal style=\"html\">\n?\n</literal>")
8730 ("H" "#+html: "
8731 "<literal style=\"html\">?</literal>")
8732 ("a" "#+begin_ascii\n?\n#+end_ascii")
8733 ("A" "#+ascii: ")
8734 ("i" "#+include %file ?"
8735 "<include file=%file markup=\"?\">")
8737 "Structure completion elements.
8738 This is a list of abbreviation keys and values. The value gets inserted
8739 it you type @samp{.} followed by the key and then the completion key,
8740 usually `M-TAB'. %file will be replaced by a file name after prompting
8741 for the file using completion.
8742 There are two templates for each key, the first uses the original Org syntax,
8743 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8744 the default when the /org-mtags.el/ module has been loaded. See also the
8745 variable `org-mtags-prefer-muse-templates'.
8746 This is an experimental feature, it is undecided if it is going to stay in."
8747 :group 'org-completion
8748 :type '(repeat
8749 (string :tag "Key")
8750 (string :tag "Template")
8751 (string :tag "Muse Template")))
8753 (defun org-try-structure-completion ()
8754 "Try to complete a structure template before point.
8755 This looks for strings like \"<e\" on an otherwise empty line and
8756 expands them."
8757 (let ((l (buffer-substring (point-at-bol) (point)))
8759 (when (and (looking-at "[ \t]*$")
8760 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8761 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8762 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8763 (match-beginning 1)) a)
8764 t)))
8766 (defun org-complete-expand-structure-template (start cell)
8767 "Expand a structure template."
8768 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8769 (rpl (nth (if musep 2 1) cell))
8770 (ind ""))
8771 (delete-region start (point))
8772 (when (string-match "\\`#\\+" rpl)
8773 (cond
8774 ((bolp))
8775 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8776 (setq ind (buffer-substring (point-at-bol) (point))))
8777 (t (newline))))
8778 (setq start (point))
8779 (if (string-match "%file" rpl)
8780 (setq rpl (replace-match
8781 (concat
8782 "\""
8783 (save-match-data
8784 (abbreviate-file-name (read-file-name "Include file: ")))
8785 "\"")
8786 t t rpl)))
8787 (setq rpl (mapconcat 'identity (split-string rpl "\n")
8788 (concat "\n" ind)))
8789 (insert rpl)
8790 (if (re-search-backward "\\?" start t) (delete-char 1))))
8793 (defun org-complete (&optional arg)
8794 "Perform completion on word at point.
8795 At the beginning of a headline, this completes TODO keywords as given in
8796 `org-todo-keywords'.
8797 If the current word is preceded by a backslash, completes the TeX symbols
8798 that are supported for HTML support.
8799 If the current word is preceded by \"#+\", completes special words for
8800 setting file options.
8801 In the line after \"#+STARTUP:, complete valid keywords.\"
8802 At all other locations, this simply calls the value of
8803 `org-completion-fallback-command'."
8804 (interactive "P")
8805 (org-without-partial-completion
8806 (catch 'exit
8807 (let* ((a nil)
8808 (end (point))
8809 (beg1 (save-excursion
8810 (skip-chars-backward (org-re "[:alnum:]_@"))
8811 (point)))
8812 (beg (save-excursion
8813 (skip-chars-backward "a-zA-Z0-9_:$")
8814 (point)))
8815 (confirm (lambda (x) (stringp (car x))))
8816 (searchhead (equal (char-before beg) ?*))
8817 (struct
8818 (when (and (member (char-before beg1) '(?. ?<))
8819 (setq a (assoc (buffer-substring beg1 (point))
8820 org-structure-template-alist)))
8821 (org-complete-expand-structure-template (1- beg1) a)
8822 (throw 'exit t)))
8823 (tag (and (equal (char-before beg1) ?:)
8824 (equal (char-after (point-at-bol)) ?*)))
8825 (prop (and (equal (char-before beg1) ?:)
8826 (not (equal (char-after (point-at-bol)) ?*))))
8827 (texp (equal (char-before beg) ?\\))
8828 (link (equal (char-before beg) ?\[))
8829 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8830 beg)
8831 "#+"))
8832 (startup (string-match "^#\\+STARTUP:.*"
8833 (buffer-substring (point-at-bol) (point))))
8834 (completion-ignore-case opt)
8835 (type nil)
8836 (tbl nil)
8837 (table (cond
8838 (opt
8839 (setq type :opt)
8840 (require 'org-exp)
8841 (append
8842 (mapcar
8843 (lambda (x)
8844 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8845 (cons (match-string 2 x) (match-string 1 x)))
8846 (org-split-string (org-get-current-options) "\n"))
8847 (mapcar 'list org-additional-option-like-keywords)))
8848 (startup
8849 (setq type :startup)
8850 org-startup-options)
8851 (link (append org-link-abbrev-alist-local
8852 org-link-abbrev-alist))
8853 (texp
8854 (setq type :tex)
8855 org-html-entities)
8856 ((string-match "\\`\\*+[ \t]+\\'"
8857 (buffer-substring (point-at-bol) beg))
8858 (setq type :todo)
8859 (mapcar 'list org-todo-keywords-1))
8860 (searchhead
8861 (setq type :searchhead)
8862 (save-excursion
8863 (goto-char (point-min))
8864 (while (re-search-forward org-todo-line-regexp nil t)
8865 (push (list
8866 (org-make-org-heading-search-string
8867 (match-string 3) t))
8868 tbl)))
8869 tbl)
8870 (tag (setq type :tag beg beg1)
8871 (or org-tag-alist (org-get-buffer-tags)))
8872 (prop (setq type :prop beg beg1)
8873 (mapcar 'list (org-buffer-property-keys nil t t)))
8874 (t (progn
8875 (call-interactively org-completion-fallback-command)
8876 (throw 'exit nil)))))
8877 (pattern (buffer-substring-no-properties beg end))
8878 (completion (try-completion pattern table confirm)))
8879 (cond ((eq completion t)
8880 (if (not (assoc (upcase pattern) table))
8881 (message "Already complete")
8882 (if (and (equal type :opt)
8883 (not (member (car (assoc (upcase pattern) table))
8884 org-additional-option-like-keywords)))
8885 (insert (substring (cdr (assoc (upcase pattern) table))
8886 (length pattern)))
8887 (if (memq type '(:tag :prop)) (insert ":")))))
8888 ((null completion)
8889 (message "Can't find completion for \"%s\"" pattern)
8890 (ding))
8891 ((not (string= pattern completion))
8892 (delete-region beg end)
8893 (if (string-match " +$" completion)
8894 (setq completion (replace-match "" t t completion)))
8895 (insert completion)
8896 (if (get-buffer-window "*Completions*")
8897 (delete-window (get-buffer-window "*Completions*")))
8898 (if (assoc completion table)
8899 (if (eq type :todo) (insert " ")
8900 (if (memq type '(:tag :prop)) (insert ":"))))
8901 (if (and (equal type :opt) (assoc completion table))
8902 (message "%s" (substitute-command-keys
8903 "Press \\[org-complete] again to insert example settings"))))
8905 (message "Making completion list...")
8906 (let ((list (sort (all-completions pattern table confirm)
8907 'string<)))
8908 (with-output-to-temp-buffer "*Completions*"
8909 (condition-case nil
8910 ;; Protection needed for XEmacs and emacs 21
8911 (display-completion-list list pattern)
8912 (error (display-completion-list list)))))
8913 (message "Making completion list...%s" "done")))))))
8915 ;;;; TODO, DEADLINE, Comments
8917 (defun org-toggle-comment ()
8918 "Change the COMMENT state of an entry."
8919 (interactive)
8920 (save-excursion
8921 (org-back-to-heading)
8922 (let (case-fold-search)
8923 (if (looking-at (concat outline-regexp
8924 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8925 (replace-match "" t t nil 1)
8926 (if (looking-at outline-regexp)
8927 (progn
8928 (goto-char (match-end 0))
8929 (insert org-comment-string " ")))))))
8931 (defvar org-last-todo-state-is-todo nil
8932 "This is non-nil when the last TODO state change led to a TODO state.
8933 If the last change removed the TODO tag or switched to DONE, then
8934 this is nil.")
8936 (defvar org-setting-tags nil) ; dynamically skipped
8938 (defun org-parse-local-options (string var)
8939 "Parse STRING for startup setting relevant for variable VAR."
8940 (let ((rtn (symbol-value var))
8941 e opts)
8942 (save-match-data
8943 (if (or (not string) (not (string-match "\\S-" string)))
8945 (setq opts (delq nil (mapcar (lambda (x)
8946 (setq e (assoc x org-startup-options))
8947 (if (eq (nth 1 e) var) e nil))
8948 (org-split-string string "[ \t]+"))))
8949 (if (not opts)
8951 (setq rtn nil)
8952 (while (setq e (pop opts))
8953 (if (not (nth 3 e))
8954 (setq rtn (nth 2 e))
8955 (if (not (listp rtn)) (setq rtn nil))
8956 (push (nth 2 e) rtn)))
8957 rtn)))))
8959 (defvar org-todo-setup-filter-hook nil
8960 "Hook for functions that pre-filter todo specs.
8962 Each function takes a todo spec and returns either `nil' or the spec
8963 transformed into canonical form." )
8965 (defvar org-todo-get-default-hook nil
8966 "Hook for functions that get a default item for todo.
8968 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
8969 `nil' or a string to be used for the todo mark." )
8971 (defvar org-agenda-headline-snapshot-before-repeat)
8973 (defun org-todo (&optional arg)
8974 "Change the TODO state of an item.
8975 The state of an item is given by a keyword at the start of the heading,
8976 like
8977 *** TODO Write paper
8978 *** DONE Call mom
8980 The different keywords are specified in the variable `org-todo-keywords'.
8981 By default the available states are \"TODO\" and \"DONE\".
8982 So for this example: when the item starts with TODO, it is changed to DONE.
8983 When it starts with DONE, the DONE is removed. And when neither TODO nor
8984 DONE are present, add TODO at the beginning of the heading.
8986 With C-u prefix arg, use completion to determine the new state.
8987 With numeric prefix arg, switch to that state.
8988 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
8989 With a tripple C-u prefix, circumvent any state blocking.
8991 For calling through lisp, arg is also interpreted in the following way:
8992 'none -> empty state
8993 \"\"(empty string) -> switch to empty state
8994 'done -> switch to DONE
8995 'nextset -> switch to the next set of keywords
8996 'previousset -> switch to the previous set of keywords
8997 \"WAITING\" -> switch to the specified keyword, but only if it
8998 really is a member of `org-todo-keywords'."
8999 (interactive "P")
9000 (if (equal arg '(16)) (setq arg 'nextset))
9001 (let ((org-blocker-hook org-blocker-hook)
9002 (case-fold-search nil))
9003 (when (equal arg '(64))
9004 (setq arg nil org-blocker-hook nil))
9005 (when (and org-blocker-hook
9006 (org-entry-get nil "NOBLOCKING"))
9007 (setq org-blocker-hook nil))
9008 (save-excursion
9009 (catch 'exit
9010 (org-back-to-heading)
9011 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9012 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9013 (looking-at " *"))
9014 (let* ((match-data (match-data))
9015 (startpos (point-at-bol))
9016 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9017 (org-log-done org-log-done)
9018 (org-log-repeat org-log-repeat)
9019 (org-todo-log-states org-todo-log-states)
9020 (this (match-string 1))
9021 (hl-pos (match-beginning 0))
9022 (head (org-get-todo-sequence-head this))
9023 (ass (assoc head org-todo-kwd-alist))
9024 (interpret (nth 1 ass))
9025 (done-word (nth 3 ass))
9026 (final-done-word (nth 4 ass))
9027 (last-state (or this ""))
9028 (completion-ignore-case t)
9029 (member (member this org-todo-keywords-1))
9030 (tail (cdr member))
9031 (state (cond
9032 ((and org-todo-key-trigger
9033 (or (and (equal arg '(4))
9034 (eq org-use-fast-todo-selection 'prefix))
9035 (and (not arg) org-use-fast-todo-selection
9036 (not (eq org-use-fast-todo-selection
9037 'prefix)))))
9038 ;; Use fast selection
9039 (org-fast-todo-selection))
9040 ((and (equal arg '(4))
9041 (or (not org-use-fast-todo-selection)
9042 (not org-todo-key-trigger)))
9043 ;; Read a state with completion
9044 (org-ido-completing-read
9045 "State: " (mapcar (lambda(x) (list x))
9046 org-todo-keywords-1)
9047 nil t))
9048 ((eq arg 'right)
9049 (if this
9050 (if tail (car tail) nil)
9051 (car org-todo-keywords-1)))
9052 ((eq arg 'left)
9053 (if (equal member org-todo-keywords-1)
9055 (if this
9056 (nth (- (length org-todo-keywords-1)
9057 (length tail) 2)
9058 org-todo-keywords-1)
9059 (org-last org-todo-keywords-1))))
9060 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9061 (setq arg nil))) ; hack to fall back to cycling
9062 (arg
9063 ;; user or caller requests a specific state
9064 (cond
9065 ((equal arg "") nil)
9066 ((eq arg 'none) nil)
9067 ((eq arg 'done) (or done-word (car org-done-keywords)))
9068 ((eq arg 'nextset)
9069 (or (car (cdr (member head org-todo-heads)))
9070 (car org-todo-heads)))
9071 ((eq arg 'previousset)
9072 (let ((org-todo-heads (reverse org-todo-heads)))
9073 (or (car (cdr (member head org-todo-heads)))
9074 (car org-todo-heads))))
9075 ((car (member arg org-todo-keywords-1)))
9076 ((nth (1- (prefix-numeric-value arg))
9077 org-todo-keywords-1))))
9078 ((null member) (or head (car org-todo-keywords-1)))
9079 ((equal this final-done-word) nil) ;; -> make empty
9080 ((null tail) nil) ;; -> first entry
9081 ((memq interpret '(type priority))
9082 (if (eq this-command last-command)
9083 (car tail)
9084 (if (> (length tail) 0)
9085 (or done-word (car org-done-keywords))
9086 nil)))
9088 (car tail))))
9089 (state (or
9090 (run-hook-with-args-until-success
9091 'org-todo-get-default-hook state last-state)
9092 state))
9093 (next (if state (concat " " state " ") " "))
9094 (change-plist (list :type 'todo-state-change :from this :to state
9095 :position startpos))
9096 dolog now-done-p)
9097 (when org-blocker-hook
9098 (setq org-last-todo-state-is-todo
9099 (not (member this org-done-keywords)))
9100 (unless (save-excursion
9101 (save-match-data
9102 (run-hook-with-args-until-failure
9103 'org-blocker-hook change-plist)))
9104 (if (interactive-p)
9105 (error "TODO state change from %s to %s blocked" this state)
9106 ;; fail silently
9107 (message "TODO state change from %s to %s blocked" this state)
9108 (throw 'exit nil))))
9109 (store-match-data match-data)
9110 (replace-match next t t)
9111 (unless (pos-visible-in-window-p hl-pos)
9112 (message "TODO state changed to %s" (org-trim next)))
9113 (unless head
9114 (setq head (org-get-todo-sequence-head state)
9115 ass (assoc head org-todo-kwd-alist)
9116 interpret (nth 1 ass)
9117 done-word (nth 3 ass)
9118 final-done-word (nth 4 ass)))
9119 (when (memq arg '(nextset previousset))
9120 (message "Keyword-Set %d/%d: %s"
9121 (- (length org-todo-sets) -1
9122 (length (memq (assoc state org-todo-sets) org-todo-sets)))
9123 (length org-todo-sets)
9124 (mapconcat 'identity (assoc state org-todo-sets) " ")))
9125 (setq org-last-todo-state-is-todo
9126 (not (member state org-done-keywords)))
9127 (setq now-done-p (and (member state org-done-keywords)
9128 (not (member this org-done-keywords))))
9129 (and logging (org-local-logging logging))
9130 (when (and (or org-todo-log-states org-log-done)
9131 (not org-inhibit-logging)
9132 (not (memq arg '(nextset previousset))))
9133 ;; we need to look at recording a time and note
9134 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
9135 (nth 2 (assoc this org-todo-log-states))))
9136 (when (and state
9137 (member state org-not-done-keywords)
9138 (not (member this org-not-done-keywords)))
9139 ;; This is now a todo state and was not one before
9140 ;; If there was a CLOSED time stamp, get rid of it.
9141 (org-add-planning-info nil nil 'closed))
9142 (when (and now-done-p org-log-done)
9143 ;; It is now done, and it was not done before
9144 (org-add-planning-info 'closed (org-current-time))
9145 (if (and (not dolog) (eq 'note org-log-done))
9146 (org-add-log-setup 'done state this 'findpos 'note)))
9147 (when (and state dolog)
9148 ;; This is a non-nil state, and we need to log it
9149 (org-add-log-setup 'state state this 'findpos dolog)))
9150 ;; Fixup tag positioning
9151 (org-todo-trigger-tag-changes state)
9152 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
9153 (when org-provide-todo-statistics
9154 (org-update-parent-todo-statistics))
9155 (run-hooks 'org-after-todo-state-change-hook)
9156 (if (and arg (not (member state org-done-keywords)))
9157 (setq head (org-get-todo-sequence-head state)))
9158 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9159 ;; Do we need to trigger a repeat?
9160 (when now-done-p
9161 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
9162 ;; This is for the agenda, take a snapshot of the headline.
9163 (save-match-data
9164 (setq org-agenda-headline-snapshot-before-repeat
9165 (org-get-heading))))
9166 (org-auto-repeat-maybe state))
9167 ;; Fixup cursor location if close to the keyword
9168 (if (and (outline-on-heading-p)
9169 (not (bolp))
9170 (save-excursion (beginning-of-line 1)
9171 (looking-at org-todo-line-regexp))
9172 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9173 (progn
9174 (goto-char (or (match-end 2) (match-end 1)))
9175 (and (looking-at " ") (just-one-space))))
9176 (when org-trigger-hook
9177 (save-excursion
9178 (run-hook-with-args 'org-trigger-hook change-plist))))))))
9180 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
9181 "Block turning an entry into a TODO, using the hierarchy.
9182 This checks whether the current task should be blocked from state
9183 changes. Such blocking occurs when:
9185 1. The task has children which are not all in a completed state.
9187 2. A task has a parent with the property :ORDERED:, and there
9188 are siblings prior to the current task with incomplete
9189 status.
9191 3. The parent of the task is blocked because it has siblings that should
9192 be done first, or is child of a block grandparent TODO entry."
9194 (catch 'dont-block
9195 ;; If this is not a todo state change, or if this entry is already DONE,
9196 ;; do not block
9197 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9198 (member (plist-get change-plist :from)
9199 (cons 'done org-done-keywords))
9200 (member (plist-get change-plist :to)
9201 (cons 'todo org-not-done-keywords)))
9202 (throw 'dont-block t))
9203 ;; If this task has children, and any are undone, it's blocked
9204 (save-excursion
9205 (org-back-to-heading t)
9206 (let ((this-level (funcall outline-level)))
9207 (outline-next-heading)
9208 (let ((child-level (funcall outline-level)))
9209 (while (and (not (eobp))
9210 (> child-level this-level))
9211 ;; this todo has children, check whether they are all
9212 ;; completed
9213 (if (and (not (org-entry-is-done-p))
9214 (org-entry-is-todo-p))
9215 (throw 'dont-block nil))
9216 (outline-next-heading)
9217 (setq child-level (funcall outline-level))))))
9218 ;; Otherwise, if the task's parent has the :ORDERED: property, and
9219 ;; any previous siblings are undone, it's blocked
9220 (save-excursion
9221 (org-back-to-heading t)
9222 (let* ((pos (point))
9223 (parent-pos (and (org-up-heading-safe) (point))))
9224 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9225 (when (and (org-entry-get (point) "ORDERED")
9226 (forward-line 1)
9227 (re-search-forward org-not-done-heading-regexp pos t))
9228 (throw 'dont-block nil)) ; block, there is an older sibling not done.
9229 ;; Search further up the hierarchy, to see if an anchestor is blocked
9230 (while t
9231 (goto-char parent-pos)
9232 (if (not (looking-at org-not-done-heading-regexp))
9233 (throw 'dont-block t)) ; do not block, parent is not a TODO
9234 (setq pos (point))
9235 (setq parent-pos (and (org-up-heading-safe) (point)))
9236 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9237 (when (and (org-entry-get (point) "ORDERED")
9238 (forward-line 1)
9239 (re-search-forward org-not-done-heading-regexp pos t))
9240 (throw 'dont-block nil))))))) ; block, older sibling not done.
9242 (defcustom org-track-ordered-property-with-tag nil
9243 "Should the ORDERED property also be shown as a tag?
9244 The ORDERED property decides if an entry should require subtasks to be
9245 completed in sequence. Since a property is not very visible, setting
9246 this option means that toggling the ORDERED property with the command
9247 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
9248 not relevant for the behavior, but it makes things more visible.
9250 Note that toggling the tag with tags commands will not change the property
9251 and therefore not influence behavior!
9253 This can be t, meaning the tag ORDERED should be used, It can also be a
9254 string to select a different tag for this task."
9255 :group 'org-todo
9256 :type '(choice
9257 (const :tag "No tracking" nil)
9258 (const :tag "Track with ORDERED tag" t)
9259 (string :tag "Use other tag")))
9261 (defun org-toggle-ordered-property ()
9262 "Toggle the ORDERED property of the current entry.
9263 For better visibility, you can track the value of this property with a tag.
9264 See variable `org-track-ordered-property-with-tag'."
9265 (interactive)
9266 (let* ((t1 org-track-ordered-property-with-tag)
9267 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
9268 (save-excursion
9269 (org-back-to-heading)
9270 (if (org-entry-get nil "ORDERED")
9271 (progn
9272 (org-delete-property "ORDERED")
9273 (and tag (org-toggle-tag tag 'off))
9274 (message "Subtasks can be completed in arbitrary order"))
9275 (org-entry-put nil "ORDERED" "t")
9276 (and tag (org-toggle-tag tag 'on))
9277 (message "Subtasks must be completed in sequence")))))
9279 (defvar org-blocked-by-checkboxes) ; dynamically scoped
9280 (defun org-block-todo-from-checkboxes (change-plist)
9281 "Block turning an entry into a TODO, using checkboxes.
9282 This checks whether the current task should be blocked from state
9283 changes because there are uncheckd boxes in this entry."
9284 (catch 'dont-block
9285 ;; If this is not a todo state change, or if this entry is already DONE,
9286 ;; do not block
9287 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9288 (member (plist-get change-plist :from)
9289 (cons 'done org-done-keywords))
9290 (member (plist-get change-plist :to)
9291 (cons 'todo org-not-done-keywords)))
9292 (throw 'dont-block t))
9293 ;; If this task has checkboxes that are not checked, it's blocked
9294 (save-excursion
9295 (org-back-to-heading t)
9296 (let ((beg (point)) end)
9297 (outline-next-heading)
9298 (setq end (point))
9299 (goto-char beg)
9300 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
9301 end t)
9302 (progn
9303 (if (boundp 'org-blocked-by-checkboxes)
9304 (setq org-blocked-by-checkboxes t))
9305 (throw 'dont-block nil)))))
9306 t)) ; do not block
9308 (defvar org-entry-property-inherited-from) ;; defined below
9309 (defun org-update-parent-todo-statistics ()
9310 "Update any statistics cookie in the parent of the current headline.
9311 When `org-hierarchical-todo-statistics' is nil, statistics will cover
9312 the entire subtree and this will travel up the hierarchy and update
9313 statistics everywhere."
9314 (interactive)
9315 (let* ((lim 0) prop
9316 (recursive (or (not org-hierarchical-todo-statistics)
9317 (string-match
9318 "\\<recursive\\>"
9319 (or (setq prop (org-entry-get
9320 nil "COOKIE_DATA" 'inherit)) ""))))
9321 (lim (or (and prop (marker-position
9322 org-entry-property-inherited-from))
9323 lim))
9324 (first t)
9325 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
9326 level ltoggle l1
9327 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
9328 (catch 'exit
9329 (save-excursion
9330 (beginning-of-line 1)
9331 (if (org-at-heading-p)
9332 (setq ltoggle (funcall outline-level))
9333 (error "This should not happen"))
9334 (while (and (setq level (org-up-heading-safe))
9335 (or recursive first)
9336 (>= (point) lim))
9337 (setq first nil)
9338 (unless (and level
9339 (not (string-match
9340 "\\<checkbox\\>"
9341 (downcase
9342 (or (org-entry-get
9343 nil "COOKIE_DATA")
9344 "")))))
9345 (throw 'exit nil))
9346 (while (re-search-forward box-re (point-at-eol) t)
9347 (setq cnt-all 0 cnt-done 0 cookie-present t)
9348 (setq is-percent (match-end 2))
9349 (save-match-data
9350 (unless (outline-next-heading) (throw 'exit nil))
9351 (while (and (looking-at org-complex-heading-regexp)
9352 (> (setq l1 (length (match-string 1))) level))
9353 (setq kwd (and (or recursive (= l1 ltoggle))
9354 (match-string 2)))
9355 (and kwd (setq cnt-all (1+ cnt-all)))
9356 (and (member kwd org-done-keywords)
9357 (setq cnt-done (1+ cnt-done)))
9358 (outline-next-heading)))
9359 (replace-match
9360 (if is-percent
9361 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
9362 (format "[%d/%d]" cnt-done cnt-all)))))
9363 (when cookie-present
9364 (run-hook-with-args 'org-after-todo-statistics-hook
9365 cnt-done (- cnt-all cnt-done)))))
9366 (run-hooks 'org-todo-statistics-hook)))
9368 (defvar org-after-todo-statistics-hook nil
9369 "Hook that is called after a TODO statistics cookie has been updated.
9370 Each function is called with two arguments: the number of not-done entries
9371 and the number of done entries.
9373 For example, the following function, when added to this hook, will switch
9374 an entry to DONE when all children are done, and back to TODO when new
9375 entries are set to a TODO status. Note that this hook is only called
9376 when there is a statistics cookie in the headline!
9378 (defun org-summary-todo (n-done n-not-done)
9379 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
9380 (let (org-log-done org-log-states) ; turn off logging
9381 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
9384 (defvar org-todo-statistics-hook nil
9385 "Hook that is run whenever Org thinks TODO statistics should be updated.
9386 This hook runs even if there is no statisics cookie present, in which case
9387 `org-after-todo-statistics-hook' would not run.")
9389 (defun org-todo-trigger-tag-changes (state)
9390 "Apply the changes defined in `org-todo-state-tags-triggers'."
9391 (let ((l org-todo-state-tags-triggers)
9392 changes)
9393 (when (or (not state) (equal state ""))
9394 (setq changes (append changes (cdr (assoc "" l)))))
9395 (when (and (stringp state) (> (length state) 0))
9396 (setq changes (append changes (cdr (assoc state l)))))
9397 (when (member state org-not-done-keywords)
9398 (setq changes (append changes (cdr (assoc 'todo l)))))
9399 (when (member state org-done-keywords)
9400 (setq changes (append changes (cdr (assoc 'done l)))))
9401 (dolist (c changes)
9402 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
9404 (defun org-local-logging (value)
9405 "Get logging settings from a property VALUE."
9406 (let* (words w a)
9407 ;; directly set the variables, they are already local.
9408 (setq org-log-done nil
9409 org-log-repeat nil
9410 org-todo-log-states nil)
9411 (setq words (org-split-string value))
9412 (while (setq w (pop words))
9413 (cond
9414 ((setq a (assoc w org-startup-options))
9415 (and (member (nth 1 a) '(org-log-done org-log-repeat))
9416 (set (nth 1 a) (nth 2 a))))
9417 ((setq a (org-extract-log-state-settings w))
9418 (and (member (car a) org-todo-keywords-1)
9419 (push a org-todo-log-states)))))))
9421 (defun org-get-todo-sequence-head (kwd)
9422 "Return the head of the TODO sequence to which KWD belongs.
9423 If KWD is not set, check if there is a text property remembering the
9424 right sequence."
9425 (let (p)
9426 (cond
9427 ((not kwd)
9428 (or (get-text-property (point-at-bol) 'org-todo-head)
9429 (progn
9430 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
9431 nil (point-at-eol)))
9432 (get-text-property p 'org-todo-head))))
9433 ((not (member kwd org-todo-keywords-1))
9434 (car org-todo-keywords-1))
9435 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
9437 (defun org-fast-todo-selection ()
9438 "Fast TODO keyword selection with single keys.
9439 Returns the new TODO keyword, or nil if no state change should occur."
9440 (let* ((fulltable org-todo-key-alist)
9441 (done-keywords org-done-keywords) ;; needed for the faces.
9442 (maxlen (apply 'max (mapcar
9443 (lambda (x)
9444 (if (stringp (car x)) (string-width (car x)) 0))
9445 fulltable)))
9446 (expert nil)
9447 (fwidth (+ maxlen 3 1 3))
9448 (ncol (/ (- (window-width) 4) fwidth))
9449 tg cnt e c tbl
9450 groups ingroup)
9451 (save-excursion
9452 (save-window-excursion
9453 (if expert
9454 (set-buffer (get-buffer-create " *Org todo*"))
9455 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
9456 (erase-buffer)
9457 (org-set-local 'org-done-keywords done-keywords)
9458 (setq tbl fulltable cnt 0)
9459 (while (setq e (pop tbl))
9460 (cond
9461 ((equal e '(:startgroup))
9462 (push '() groups) (setq ingroup t)
9463 (when (not (= cnt 0))
9464 (setq cnt 0)
9465 (insert "\n"))
9466 (insert "{ "))
9467 ((equal e '(:endgroup))
9468 (setq ingroup nil cnt 0)
9469 (insert "}\n"))
9470 ((equal e '(:newline))
9471 (when (not (= cnt 0))
9472 (setq cnt 0)
9473 (insert "\n")
9474 (setq e (car tbl))
9475 (while (equal (car tbl) '(:newline))
9476 (insert "\n")
9477 (setq tbl (cdr tbl)))))
9479 (setq tg (car e) c (cdr e))
9480 (if ingroup (push tg (car groups)))
9481 (setq tg (org-add-props tg nil 'face
9482 (org-get-todo-face tg)))
9483 (if (and (= cnt 0) (not ingroup)) (insert " "))
9484 (insert "[" c "] " tg (make-string
9485 (- fwidth 4 (length tg)) ?\ ))
9486 (when (= (setq cnt (1+ cnt)) ncol)
9487 (insert "\n")
9488 (if ingroup (insert " "))
9489 (setq cnt 0)))))
9490 (insert "\n")
9491 (goto-char (point-min))
9492 (if (not expert) (org-fit-window-to-buffer))
9493 (message "[a-z..]:Set [SPC]:clear")
9494 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9495 (cond
9496 ((or (= c ?\C-g)
9497 (and (= c ?q) (not (rassoc c fulltable))))
9498 (setq quit-flag t))
9499 ((= c ?\ ) nil)
9500 ((setq e (rassoc c fulltable) tg (car e))
9502 (t (setq quit-flag t)))))))
9504 (defun org-entry-is-todo-p ()
9505 (member (org-get-todo-state) org-not-done-keywords))
9507 (defun org-entry-is-done-p ()
9508 (member (org-get-todo-state) org-done-keywords))
9510 (defun org-get-todo-state ()
9511 (save-excursion
9512 (org-back-to-heading t)
9513 (and (looking-at org-todo-line-regexp)
9514 (match-end 2)
9515 (match-string 2))))
9517 (defun org-at-date-range-p (&optional inactive-ok)
9518 "Is the cursor inside a date range?"
9519 (interactive)
9520 (save-excursion
9521 (catch 'exit
9522 (let ((pos (point)))
9523 (skip-chars-backward "^[<\r\n")
9524 (skip-chars-backward "<[")
9525 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9526 (>= (match-end 0) pos)
9527 (throw 'exit t))
9528 (skip-chars-backward "^<[\r\n")
9529 (skip-chars-backward "<[")
9530 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9531 (>= (match-end 0) pos)
9532 (throw 'exit t)))
9533 nil)))
9535 (defun org-get-repeat ()
9536 "Check if there is a deadline/schedule with repeater in this entry."
9537 (save-match-data
9538 (save-excursion
9539 (org-back-to-heading t)
9540 (if (re-search-forward
9541 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9542 (match-string 1)))))
9544 (defvar org-last-changed-timestamp)
9545 (defvar org-last-inserted-timestamp)
9546 (defvar org-log-post-message)
9547 (defvar org-log-note-purpose)
9548 (defvar org-log-note-how)
9549 (defvar org-log-note-extra)
9550 (defun org-auto-repeat-maybe (done-word)
9551 "Check if the current headline contains a repeated deadline/schedule.
9552 If yes, set TODO state back to what it was and change the base date
9553 of repeating deadline/scheduled time stamps to new date.
9554 This function is run automatically after each state change to a DONE state."
9555 ;; last-state is dynamically scoped into this function
9556 (let* ((repeat (org-get-repeat))
9557 (aa (assoc last-state org-todo-kwd-alist))
9558 (interpret (nth 1 aa))
9559 (head (nth 2 aa))
9560 (whata '(("d" . day) ("m" . month) ("y" . year)))
9561 (msg "Entry repeats: ")
9562 (org-log-done nil)
9563 (org-todo-log-states nil)
9564 (nshiftmax 10) (nshift 0)
9565 re type n what ts time)
9566 (when repeat
9567 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9568 (org-todo (if (eq interpret 'type) last-state head))
9569 (org-entry-put nil "LAST_REPEAT" (format-time-string
9570 (org-time-stamp-format t t)))
9571 (when org-log-repeat
9572 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9573 (memq 'org-add-log-note post-command-hook))
9574 ;; OK, we are already setup for some record
9575 (if (eq org-log-repeat 'note)
9576 ;; make sure we take a note, not only a time stamp
9577 (setq org-log-note-how 'note))
9578 ;; Set up for taking a record
9579 (org-add-log-setup 'state (or done-word (car org-done-keywords))
9580 last-state
9581 'findpos org-log-repeat)))
9582 (org-back-to-heading t)
9583 (org-add-planning-info nil nil 'closed)
9584 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9585 org-deadline-time-regexp "\\)\\|\\("
9586 org-ts-regexp "\\)"))
9587 (while (re-search-forward
9588 re (save-excursion (outline-next-heading) (point)) t)
9589 (setq type (if (match-end 1) org-scheduled-string
9590 (if (match-end 3) org-deadline-string "Plain:"))
9591 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
9592 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
9593 (setq n (string-to-number (match-string 2 ts))
9594 what (match-string 3 ts))
9595 (if (equal what "w") (setq n (* n 7) what "d"))
9596 ;; Preparation, see if we need to modify the start date for the change
9597 (when (match-end 1)
9598 (setq time (save-match-data (org-time-string-to-time ts)))
9599 (cond
9600 ((equal (match-string 1 ts) ".")
9601 ;; Shift starting date to today
9602 (org-timestamp-change
9603 (- (time-to-days (current-time)) (time-to-days time))
9604 'day))
9605 ((equal (match-string 1 ts) "+")
9606 (while (or (= nshift 0)
9607 (<= (time-to-days time) (time-to-days (current-time))))
9608 (when (= (incf nshift) nshiftmax)
9609 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
9610 (error "Abort")))
9611 (org-timestamp-change n (cdr (assoc what whata)))
9612 (org-at-timestamp-p t)
9613 (setq ts (match-string 1))
9614 (setq time (save-match-data (org-time-string-to-time ts))))
9615 (org-timestamp-change (- n) (cdr (assoc what whata)))
9616 ;; rematch, so that we have everything in place for the real shift
9617 (org-at-timestamp-p t)
9618 (setq ts (match-string 1))
9619 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
9620 (org-timestamp-change n (cdr (assoc what whata)))
9621 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
9622 (setq org-log-post-message msg)
9623 (message "%s" msg))))
9625 (defun org-show-todo-tree (arg)
9626 "Make a compact tree which shows all headlines marked with TODO.
9627 The tree will show the lines where the regexp matches, and all higher
9628 headlines above the match.
9629 With a \\[universal-argument] prefix, prompt for a regexp to match.
9630 With a numeric prefix N, construct a sparse tree for the Nth element
9631 of `org-todo-keywords-1'."
9632 (interactive "P")
9633 (let ((case-fold-search nil)
9634 (kwd-re
9635 (cond ((null arg) org-not-done-regexp)
9636 ((equal arg '(4))
9637 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
9638 (mapcar 'list org-todo-keywords-1))))
9639 (concat "\\("
9640 (mapconcat 'identity (org-split-string kwd "|") "\\|")
9641 "\\)\\>")))
9642 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
9643 (regexp-quote (nth (1- (prefix-numeric-value arg))
9644 org-todo-keywords-1)))
9645 (t (error "Invalid prefix argument: %s" arg)))))
9646 (message "%d TODO entries found"
9647 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
9649 (defun org-deadline (&optional remove time)
9650 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
9651 With argument REMOVE, remove any deadline from the item.
9652 When TIME is set, it should be an internal time specification, and the
9653 scheduling will use the corresponding date."
9654 (interactive "P")
9655 (if remove
9656 (progn
9657 (org-remove-timestamp-with-keyword org-deadline-string)
9658 (message "Item no longer has a deadline."))
9659 (if (org-get-repeat)
9660 (error "Cannot change deadline on task with repeater, please do that by hand")
9661 (org-add-planning-info 'deadline time 'closed)
9662 (message "Deadline on %s" org-last-inserted-timestamp))))
9664 (defun org-schedule (&optional remove time)
9665 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
9666 With argument REMOVE, remove any scheduling date from the item.
9667 When TIME is set, it should be an internal time specification, and the
9668 scheduling will use the corresponding date."
9669 (interactive "P")
9670 (if remove
9671 (progn
9672 (org-remove-timestamp-with-keyword org-scheduled-string)
9673 (message "Item is no longer scheduled."))
9674 (if (org-get-repeat)
9675 (error "Cannot reschedule task with repeater, please do that by hand")
9676 (org-add-planning-info 'scheduled time 'closed)
9677 (message "Scheduled to %s" org-last-inserted-timestamp))))
9679 (defun org-get-scheduled-time (pom &optional inherit)
9680 "Get the scheduled time as a time tuple, of a format suitable
9681 for calling org-schedule with, or if there is no scheduling,
9682 returns nil."
9683 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
9684 (when time
9685 (apply 'encode-time (org-parse-time-string time)))))
9687 (defun org-get-deadline-time (pom &optional inherit)
9688 "Get the deadine as a time tuple, of a format suitable for
9689 calling org-deadlin with, or if there is no scheduling, returns
9690 nil."
9691 (let ((time (org-entry-get pom "DEADLINE" inherit)))
9692 (when time
9693 (apply 'encode-time (org-parse-time-string time)))))
9695 (defun org-remove-timestamp-with-keyword (keyword)
9696 "Remove all time stamps with KEYWORD in the current entry."
9697 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
9698 beg)
9699 (save-excursion
9700 (org-back-to-heading t)
9701 (setq beg (point))
9702 (org-end-of-subtree t t)
9703 (while (re-search-backward re beg t)
9704 (replace-match "")
9705 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9706 (equal (char-before) ?\ ))
9707 (backward-delete-char 1)
9708 (if (string-match "^[ \t]*$" (buffer-substring
9709 (point-at-bol) (point-at-eol)))
9710 (delete-region (point-at-bol)
9711 (min (point-max) (1+ (point-at-eol))))))))))
9713 (defun org-add-planning-info (what &optional time &rest remove)
9714 "Insert new timestamp with keyword in the line directly after the headline.
9715 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9716 If non is given, the user is prompted for a date.
9717 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9718 be removed."
9719 (interactive)
9720 (let (org-time-was-given org-end-time-was-given ts
9721 end default-time default-input)
9723 (catch 'exit
9724 (when (and (not time) (memq what '(scheduled deadline)))
9725 ;; Try to get a default date/time from existing timestamp
9726 (save-excursion
9727 (org-back-to-heading t)
9728 (setq end (save-excursion (outline-next-heading) (point)))
9729 (when (re-search-forward (if (eq what 'scheduled)
9730 org-scheduled-time-regexp
9731 org-deadline-time-regexp)
9732 end t)
9733 (setq ts (match-string 1)
9734 default-time
9735 (apply 'encode-time (org-parse-time-string ts))
9736 default-input (and ts (org-get-compact-tod ts))))))
9737 (when what
9738 ;; If necessary, get the time from the user
9739 (setq time (or time (org-read-date nil 'to-time nil nil
9740 default-time default-input))))
9742 (when (and org-insert-labeled-timestamps-at-point
9743 (member what '(scheduled deadline)))
9744 (insert
9745 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9746 (org-insert-time-stamp time org-time-was-given
9747 nil nil nil (list org-end-time-was-given))
9748 (setq what nil))
9749 (save-excursion
9750 (save-restriction
9751 (let (col list elt ts buffer-invisibility-spec)
9752 (org-back-to-heading t)
9753 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9754 (goto-char (match-end 1))
9755 (setq col (current-column))
9756 (goto-char (match-end 0))
9757 (if (eobp) (insert "\n") (forward-char 1))
9758 (when (and (not what)
9759 (not (looking-at
9760 (concat "[ \t]*"
9761 org-keyword-time-not-clock-regexp))))
9762 ;; Nothing to add, nothing to remove...... :-)
9763 (throw 'exit nil))
9764 (if (and (not (looking-at outline-regexp))
9765 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9766 "[^\r\n]*"))
9767 (not (equal (match-string 1) org-clock-string)))
9768 (narrow-to-region (match-beginning 0) (match-end 0))
9769 (insert-before-markers "\n")
9770 (backward-char 1)
9771 (narrow-to-region (point) (point))
9772 (and org-adapt-indentation (org-indent-to-column col)))
9773 ;; Check if we have to remove something.
9774 (setq list (cons what remove))
9775 (while list
9776 (setq elt (pop list))
9777 (goto-char (point-min))
9778 (when (or (and (eq elt 'scheduled)
9779 (re-search-forward org-scheduled-time-regexp nil t))
9780 (and (eq elt 'deadline)
9781 (re-search-forward org-deadline-time-regexp nil t))
9782 (and (eq elt 'closed)
9783 (re-search-forward org-closed-time-regexp nil t)))
9784 (replace-match "")
9785 (if (looking-at "--+<[^>]+>") (replace-match ""))
9786 (if (looking-at " +") (replace-match ""))))
9787 (goto-char (point-max))
9788 (when what
9789 (insert
9790 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9791 (cond ((eq what 'scheduled) org-scheduled-string)
9792 ((eq what 'deadline) org-deadline-string)
9793 ((eq what 'closed) org-closed-string))
9794 " ")
9795 (setq ts (org-insert-time-stamp
9796 time
9797 (or org-time-was-given
9798 (and (eq what 'closed) org-log-done-with-time))
9799 (eq what 'closed)
9800 nil nil (list org-end-time-was-given)))
9801 (end-of-line 1))
9802 (goto-char (point-min))
9803 (widen)
9804 (if (and (looking-at "[ \t]+\n")
9805 (equal (char-before) ?\n))
9806 (delete-region (1- (point)) (point-at-eol)))
9807 ts))))))
9809 (defvar org-log-note-marker (make-marker))
9810 (defvar org-log-note-purpose nil)
9811 (defvar org-log-note-state nil)
9812 (defvar org-log-note-previous-state nil)
9813 (defvar org-log-note-how nil)
9814 (defvar org-log-note-extra nil)
9815 (defvar org-log-note-window-configuration nil)
9816 (defvar org-log-note-return-to (make-marker))
9817 (defvar org-log-post-message nil
9818 "Message to be displayed after a log note has been stored.
9819 The auto-repeater uses this.")
9821 (defun org-add-note ()
9822 "Add a note to the current entry.
9823 This is done in the same way as adding a state change note."
9824 (interactive)
9825 (org-add-log-setup 'note nil nil 'findpos nil))
9827 (defvar org-property-end-re)
9828 (defun org-add-log-setup (&optional purpose state prev-state
9829 findpos how &optional extra)
9830 "Set up the post command hook to take a note.
9831 If this is about to TODO state change, the new state is expected in STATE.
9832 When FINDPOS is non-nil, find the correct position for the note in
9833 the current entry. If not, assume that it can be inserted at point.
9834 HOW is an indicator what kind of note should be created.
9835 EXTRA is additional text that will be inserted into the notes buffer."
9836 (let* ((org-log-into-drawer (org-log-into-drawer))
9837 (drawer (cond ((stringp org-log-into-drawer)
9838 org-log-into-drawer)
9839 (org-log-into-drawer "LOGBOOK")
9840 (t nil))))
9841 (save-restriction
9842 (save-excursion
9843 (when findpos
9844 (org-back-to-heading t)
9845 (narrow-to-region (point) (save-excursion
9846 (outline-next-heading) (point)))
9847 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9848 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9849 "[^\r\n]*\\)?"))
9850 (goto-char (match-end 0))
9851 (cond
9852 (drawer
9853 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
9854 nil t)
9855 (progn
9856 (goto-char (match-end 0))
9857 (or org-log-states-order-reversed
9858 (and (re-search-forward org-property-end-re nil t)
9859 (goto-char (1- (match-beginning 0))))))
9860 (insert "\n:" drawer ":\n:END:")
9861 (beginning-of-line 0)
9862 (org-indent-line-function)
9863 (beginning-of-line 2)
9864 (org-indent-line-function)
9865 (end-of-line 0)))
9866 ((and org-log-state-notes-insert-after-drawers
9867 (save-excursion
9868 (forward-line) (looking-at org-drawer-regexp)))
9869 (forward-line)
9870 (while (looking-at org-drawer-regexp)
9871 (goto-char (match-end 0))
9872 (re-search-forward org-property-end-re (point-max) t)
9873 (forward-line))
9874 (forward-line -1)))
9875 (unless org-log-states-order-reversed
9876 (and (= (char-after) ?\n) (forward-char 1))
9877 (org-skip-over-state-notes)
9878 (skip-chars-backward " \t\n\r")))
9879 (move-marker org-log-note-marker (point))
9880 (setq org-log-note-purpose purpose
9881 org-log-note-state state
9882 org-log-note-previous-state prev-state
9883 org-log-note-how how
9884 org-log-note-extra extra)
9885 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
9887 (defun org-skip-over-state-notes ()
9888 "Skip past the list of State notes in an entry."
9889 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9890 (while (looking-at "[ \t]*- State")
9891 (condition-case nil
9892 (org-next-item)
9893 (error (org-end-of-item)))))
9895 (defun org-add-log-note (&optional purpose)
9896 "Pop up a window for taking a note, and add this note later at point."
9897 (remove-hook 'post-command-hook 'org-add-log-note)
9898 (setq org-log-note-window-configuration (current-window-configuration))
9899 (delete-other-windows)
9900 (move-marker org-log-note-return-to (point))
9901 (switch-to-buffer (marker-buffer org-log-note-marker))
9902 (goto-char org-log-note-marker)
9903 (org-switch-to-buffer-other-window "*Org Note*")
9904 (erase-buffer)
9905 (if (memq org-log-note-how '(time state))
9906 (let (current-prefix-arg) (org-store-log-note))
9907 (let ((org-inhibit-startup t)) (org-mode))
9908 (insert (format "# Insert note for %s.
9909 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9910 (cond
9911 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9912 ((eq org-log-note-purpose 'done) "closed todo item")
9913 ((eq org-log-note-purpose 'state)
9914 (format "state change from \"%s\" to \"%s\""
9915 (or org-log-note-previous-state "")
9916 (or org-log-note-state "")))
9917 ((eq org-log-note-purpose 'note)
9918 "this entry")
9919 (t (error "This should not happen")))))
9920 (if org-log-note-extra (insert org-log-note-extra))
9921 (org-set-local 'org-finish-function 'org-store-log-note)))
9923 (defvar org-note-abort nil) ; dynamically scoped
9924 (defun org-store-log-note ()
9925 "Finish taking a log note, and insert it to where it belongs."
9926 (let ((txt (buffer-string))
9927 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9928 lines ind)
9929 (kill-buffer (current-buffer))
9930 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9931 (setq txt (replace-match "" t t txt)))
9932 (if (string-match "\\s-+\\'" txt)
9933 (setq txt (replace-match "" t t txt)))
9934 (setq lines (org-split-string txt "\n"))
9935 (when (and note (string-match "\\S-" note))
9936 (setq note
9937 (org-replace-escapes
9938 note
9939 (list (cons "%u" (user-login-name))
9940 (cons "%U" user-full-name)
9941 (cons "%t" (format-time-string
9942 (org-time-stamp-format 'long 'inactive)
9943 (current-time)))
9944 (cons "%s" (if org-log-note-state
9945 (concat "\"" org-log-note-state "\"")
9946 ""))
9947 (cons "%S" (if org-log-note-previous-state
9948 (concat "\"" org-log-note-previous-state "\"")
9949 "\"\"")))))
9950 (if lines (setq note (concat note " \\\\")))
9951 (push note lines))
9952 (when (or current-prefix-arg org-note-abort)
9953 (when org-log-into-drawer
9954 (org-remove-empty-drawer-at
9955 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
9956 org-log-note-marker))
9957 (setq lines nil))
9958 (when lines
9959 (save-excursion
9960 (set-buffer (marker-buffer org-log-note-marker))
9961 (save-excursion
9962 (goto-char org-log-note-marker)
9963 (move-marker org-log-note-marker nil)
9964 (end-of-line 1)
9965 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9966 (insert "- " (pop lines))
9967 (org-indent-line-function)
9968 (beginning-of-line 1)
9969 (looking-at "[ \t]*")
9970 (setq ind (concat (match-string 0) " "))
9971 (end-of-line 1)
9972 (while lines (insert "\n" ind (pop lines)))
9973 (message "Note stored")
9974 (org-back-to-heading t)
9975 (org-cycle-hide-drawers 'children)))))
9976 (set-window-configuration org-log-note-window-configuration)
9977 (with-current-buffer (marker-buffer org-log-note-return-to)
9978 (goto-char org-log-note-return-to))
9979 (move-marker org-log-note-return-to nil)
9980 (and org-log-post-message (message "%s" org-log-post-message)))
9982 (defun org-remove-empty-drawer-at (drawer pos)
9983 "Remove an emptyr DARWER drawer at position POS.
9984 POS may also be a marker."
9985 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
9986 (save-excursion
9987 (save-restriction
9988 (widen)
9989 (goto-char pos)
9990 (if (org-in-regexp
9991 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
9992 (replace-match ""))))))
9994 (defun org-sparse-tree (&optional arg)
9995 "Create a sparse tree, prompt for the details.
9996 This command can create sparse trees. You first need to select the type
9997 of match used to create the tree:
9999 t Show entries with a specific TODO keyword.
10000 m Show entries selected by a tags/property match.
10001 p Enter a property name and its value (both with completion on existing
10002 names/values) and show entries with that property.
10003 r Show entries matching a regular expression.
10004 d Show deadlines due within `org-deadline-warning-days'.
10005 b Show deadlines and scheduled items before a date.
10006 a Show deadlines and scheduled items after a date."
10007 (interactive "P")
10008 (let (ans kwd value)
10009 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
10010 (setq ans (read-char-exclusive))
10011 (cond
10012 ((equal ans ?d)
10013 (call-interactively 'org-check-deadlines))
10014 ((equal ans ?b)
10015 (call-interactively 'org-check-before-date))
10016 ((equal ans ?a)
10017 (call-interactively 'org-check-after-date))
10018 ((equal ans ?t)
10019 (org-show-todo-tree '(4)))
10020 ((member ans '(?T ?m))
10021 (call-interactively 'org-match-sparse-tree))
10022 ((member ans '(?p ?P))
10023 (setq kwd (org-ido-completing-read "Property: "
10024 (mapcar 'list (org-buffer-property-keys))))
10025 (setq value (org-ido-completing-read "Value: "
10026 (mapcar 'list (org-property-values kwd))))
10027 (unless (string-match "\\`{.*}\\'" value)
10028 (setq value (concat "\"" value "\"")))
10029 (org-match-sparse-tree arg (concat kwd "=" value)))
10030 ((member ans '(?r ?R ?/))
10031 (call-interactively 'org-occur))
10032 (t (error "No such sparse tree command \"%c\"" ans)))))
10034 (defvar org-occur-highlights nil
10035 "List of overlays used for occur matches.")
10036 (make-variable-buffer-local 'org-occur-highlights)
10037 (defvar org-occur-parameters nil
10038 "Parameters of the active org-occur calls.
10039 This is a list, each call to org-occur pushes as cons cell,
10040 containing the regular expression and the callback, onto the list.
10041 The list can contain several entries if `org-occur' has been called
10042 several time with the KEEP-PREVIOUS argument. Otherwise, this list
10043 will only contain one set of parameters. When the highlights are
10044 removed (for example with `C-c C-c', or with the next edit (depending
10045 on `org-remove-highlights-with-change'), this variable is emptied
10046 as well.")
10047 (make-variable-buffer-local 'org-occur-parameters)
10049 (defun org-occur (regexp &optional keep-previous callback)
10050 "Make a compact tree which shows all matches of REGEXP.
10051 The tree will show the lines where the regexp matches, and all higher
10052 headlines above the match. It will also show the heading after the match,
10053 to make sure editing the matching entry is easy.
10054 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
10055 call to `org-occur' will be kept, to allow stacking of calls to this
10056 command.
10057 If CALLBACK is non-nil, it is a function which is called to confirm
10058 that the match should indeed be shown."
10059 (interactive "sRegexp: \nP")
10060 (unless keep-previous
10061 (org-remove-occur-highlights nil nil t))
10062 (push (cons regexp callback) org-occur-parameters)
10063 (let ((cnt 0))
10064 (save-excursion
10065 (goto-char (point-min))
10066 (if (or (not keep-previous) ; do not want to keep
10067 (not org-occur-highlights)) ; no previous matches
10068 ;; hide everything
10069 (org-overview))
10070 (while (re-search-forward regexp nil t)
10071 (when (or (not callback)
10072 (save-match-data (funcall callback)))
10073 (setq cnt (1+ cnt))
10074 (when org-highlight-sparse-tree-matches
10075 (org-highlight-new-match (match-beginning 0) (match-end 0)))
10076 (org-show-context 'occur-tree))))
10077 (when org-remove-highlights-with-change
10078 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10079 nil 'local))
10080 (unless org-sparse-tree-open-archived-trees
10081 (org-hide-archived-subtrees (point-min) (point-max)))
10082 (run-hooks 'org-occur-hook)
10083 (if (interactive-p)
10084 (message "%d match(es) for regexp %s" cnt regexp))
10085 cnt))
10087 (defun org-show-context (&optional key)
10088 "Make sure point and context and visible.
10089 How much context is shown depends upon the variables
10090 `org-show-hierarchy-above', `org-show-following-heading'. and
10091 `org-show-siblings'."
10092 (let ((heading-p (org-on-heading-p t))
10093 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
10094 (following-p (org-get-alist-option org-show-following-heading key))
10095 (entry-p (org-get-alist-option org-show-entry-below key))
10096 (siblings-p (org-get-alist-option org-show-siblings key)))
10097 (catch 'exit
10098 ;; Show heading or entry text
10099 (if (and heading-p (not entry-p))
10100 (org-flag-heading nil) ; only show the heading
10101 (and (or entry-p (org-invisible-p) (org-invisible-p2))
10102 (org-show-hidden-entry))) ; show entire entry
10103 (when following-p
10104 ;; Show next sibling, or heading below text
10105 (save-excursion
10106 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10107 (org-flag-heading nil))))
10108 (when siblings-p (org-show-siblings))
10109 (when hierarchy-p
10110 ;; show all higher headings, possibly with siblings
10111 (save-excursion
10112 (while (and (condition-case nil
10113 (progn (org-up-heading-all 1) t)
10114 (error nil))
10115 (not (bobp)))
10116 (org-flag-heading nil)
10117 (when siblings-p (org-show-siblings))))))))
10119 (defun org-reveal (&optional siblings)
10120 "Show current entry, hierarchy above it, and the following headline.
10121 This can be used to show a consistent set of context around locations
10122 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10123 not t for the search context.
10125 With optional argument SIBLINGS, on each level of the hierarchy all
10126 siblings are shown. This repairs the tree structure to what it would
10127 look like when opened with hierarchical calls to `org-cycle'."
10128 (interactive "P")
10129 (let ((org-show-hierarchy-above t)
10130 (org-show-following-heading t)
10131 (org-show-siblings (if siblings t org-show-siblings)))
10132 (org-show-context nil)))
10134 (defun org-highlight-new-match (beg end)
10135 "Highlight from BEG to END and mark the highlight is an occur headline."
10136 (let ((ov (org-make-overlay beg end)))
10137 (org-overlay-put ov 'face 'secondary-selection)
10138 (push ov org-occur-highlights)))
10140 (defun org-remove-occur-highlights (&optional beg end noremove)
10141 "Remove the occur highlights from the buffer.
10142 BEG and END are ignored. If NOREMOVE is nil, remove this function
10143 from the `before-change-functions' in the current buffer."
10144 (interactive)
10145 (unless org-inhibit-highlight-removal
10146 (mapc 'org-delete-overlay org-occur-highlights)
10147 (setq org-occur-highlights nil)
10148 (setq org-occur-parameters nil)
10149 (unless noremove
10150 (remove-hook 'before-change-functions
10151 'org-remove-occur-highlights 'local))))
10153 ;;;; Priorities
10155 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
10156 "Regular expression matching the priority indicator.")
10158 (defvar org-remove-priority-next-time nil)
10160 (defun org-priority-up ()
10161 "Increase the priority of the current item."
10162 (interactive)
10163 (org-priority 'up))
10165 (defun org-priority-down ()
10166 "Decrease the priority of the current item."
10167 (interactive)
10168 (org-priority 'down))
10170 (defun org-priority (&optional action)
10171 "Change the priority of an item by ARG.
10172 ACTION can be `set', `up', `down', or a character."
10173 (interactive)
10174 (unless org-enable-priority-commands
10175 (error "Priority commands are disabled"))
10176 (setq action (or action 'set))
10177 (let (current new news have remove)
10178 (save-excursion
10179 (org-back-to-heading t)
10180 (if (looking-at org-priority-regexp)
10181 (setq current (string-to-char (match-string 2))
10182 have t)
10183 (setq current org-default-priority))
10184 (cond
10185 ((or (eq action 'set)
10186 (if (featurep 'xemacs) (characterp action) (integerp action)))
10187 (if (not (eq action 'set))
10188 (setq new action)
10189 (message "Priority %c-%c, SPC to remove: "
10190 org-highest-priority org-lowest-priority)
10191 (setq new (read-char-exclusive)))
10192 (if (and (= (upcase org-highest-priority) org-highest-priority)
10193 (= (upcase org-lowest-priority) org-lowest-priority))
10194 (setq new (upcase new)))
10195 (cond ((equal new ?\ ) (setq remove t))
10196 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
10197 (error "Priority must be between `%c' and `%c'"
10198 org-highest-priority org-lowest-priority))))
10199 ((eq action 'up)
10200 (if (and (not have) (eq last-command this-command))
10201 (setq new org-lowest-priority)
10202 (setq new (if (and org-priority-start-cycle-with-default (not have))
10203 org-default-priority (1- current)))))
10204 ((eq action 'down)
10205 (if (and (not have) (eq last-command this-command))
10206 (setq new org-highest-priority)
10207 (setq new (if (and org-priority-start-cycle-with-default (not have))
10208 org-default-priority (1+ current)))))
10209 (t (error "Invalid action")))
10210 (if (or (< (upcase new) org-highest-priority)
10211 (> (upcase new) org-lowest-priority))
10212 (setq remove t))
10213 (setq news (format "%c" new))
10214 (if have
10215 (if remove
10216 (replace-match "" t t nil 1)
10217 (replace-match news t t nil 2))
10218 (if remove
10219 (error "No priority cookie found in line")
10220 (let ((case-fold-search nil))
10221 (looking-at org-todo-line-regexp))
10222 (if (match-end 2)
10223 (progn
10224 (goto-char (match-end 2))
10225 (insert " [#" news "]"))
10226 (goto-char (match-beginning 3))
10227 (insert "[#" news "] ")))))
10228 (org-preserve-lc (org-set-tags nil 'align))
10229 (if remove
10230 (message "Priority removed")
10231 (message "Priority of current item set to %s" news))))
10234 (defun org-get-priority (s)
10235 "Find priority cookie and return priority."
10236 (save-match-data
10237 (if (not (string-match org-priority-regexp s))
10238 (* 1000 (- org-lowest-priority org-default-priority))
10239 (* 1000 (- org-lowest-priority
10240 (string-to-char (match-string 2 s)))))))
10242 ;;;; Tags
10244 (defvar org-agenda-archives-mode)
10245 (defvar org-map-continue-from nil
10246 "Position from where mapping should continue.
10247 Can be set byt the action argument to `org-scan-tag's and `org-map-entries'.")
10249 (defvar org-scanner-tags nil
10250 "The current tag list while the tags scanner is running.")
10251 (defvar org-trust-scanner-tags nil
10252 "Should `org-get-tags-at' use the tags fro the scanner.
10253 This is for internal dynamical scoping only.
10254 When this is non-nil, the function `org-get-tags-at' will return the value
10255 of `org-scanner-tags' instead of building the list by itself. This
10256 can lead to large speed-ups when the tags scanner is used in a file with
10257 many entries, and when the list of tags is retrieved, for example to
10258 obtain a list of properties. Building the tags list for each entry in such
10259 a file becomes an N^2 operation - but with this variable set, it scales
10260 as N.")
10262 (defun org-scan-tags (action matcher &optional todo-only)
10263 "Scan headline tags with inheritance and produce output ACTION.
10265 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
10266 or `agenda' to produce an entry list for an agenda view. It can also be
10267 a Lisp form or a function that should be called at each matched headline, in
10268 this case the return value is a list of all return values from these calls.
10270 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
10271 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
10272 only lines with a TODO keyword are included in the output."
10273 (require 'org-agenda)
10274 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
10275 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
10276 (org-re
10277 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
10278 (props (list 'face 'default
10279 'done-face 'org-agenda-done
10280 'undone-face 'default
10281 'mouse-face 'highlight
10282 'org-not-done-regexp org-not-done-regexp
10283 'org-todo-regexp org-todo-regexp
10284 'keymap org-agenda-keymap
10285 'help-echo
10286 (format "mouse-2 or RET jump to org file %s"
10287 (abbreviate-file-name
10288 (or (buffer-file-name (buffer-base-buffer))
10289 (buffer-name (buffer-base-buffer)))))))
10290 (case-fold-search nil)
10291 (org-map-continue-from nil)
10292 lspos tags tags-list
10293 (tags-alist (list (cons 0 org-file-tags)))
10294 (llast 0) rtn rtn1 level category i txt
10295 todo marker entry priority)
10296 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
10297 (setq action (list 'lambda nil action)))
10298 (save-excursion
10299 (goto-char (point-min))
10300 (when (eq action 'sparse-tree)
10301 (org-overview)
10302 (org-remove-occur-highlights))
10303 (while (re-search-forward re nil t)
10304 (catch :skip
10305 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
10306 tags (if (match-end 4) (org-match-string-no-properties 4)))
10307 (goto-char (setq lspos (match-beginning 0)))
10308 (setq level (org-reduced-level (funcall outline-level))
10309 category (org-get-category))
10310 (setq i llast llast level)
10311 ;; remove tag lists from same and sublevels
10312 (while (>= i level)
10313 (when (setq entry (assoc i tags-alist))
10314 (setq tags-alist (delete entry tags-alist)))
10315 (setq i (1- i)))
10316 ;; add the next tags
10317 (when tags
10318 (setq tags (org-split-string tags ":")
10319 tags-alist
10320 (cons (cons level tags) tags-alist)))
10321 ;; compile tags for current headline
10322 (setq tags-list
10323 (if org-use-tag-inheritance
10324 (apply 'append (mapcar 'cdr (reverse tags-alist)))
10325 tags)
10326 org-scanner-tags tags-list)
10327 (when org-use-tag-inheritance
10328 (setcdr (car tags-alist)
10329 (mapcar (lambda (x)
10330 (setq x (copy-sequence x))
10331 (org-add-prop-inherited x))
10332 (cdar tags-alist))))
10333 (when (and tags org-use-tag-inheritance
10334 (or (not (eq t org-use-tag-inheritance))
10335 org-tags-exclude-from-inheritance))
10336 ;; selective inheritance, remove uninherited ones
10337 (setcdr (car tags-alist)
10338 (org-remove-uniherited-tags (cdar tags-alist))))
10339 (when (and (or (not todo-only)
10340 (and (member todo org-not-done-keywords)
10341 (or (not org-agenda-tags-todo-honor-ignore-options)
10342 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
10343 (let ((case-fold-search t)) (eval matcher))
10345 (not (member org-archive-tag tags-list))
10346 ;; we have an archive tag, should we use this anyway?
10347 (or (not org-agenda-skip-archived-trees)
10348 (and (eq action 'agenda) org-agenda-archives-mode))))
10349 (unless (eq action 'sparse-tree) (org-agenda-skip))
10351 ;; select this headline
10353 (cond
10354 ((eq action 'sparse-tree)
10355 (and org-highlight-sparse-tree-matches
10356 (org-get-heading) (match-end 0)
10357 (org-highlight-new-match
10358 (match-beginning 0) (match-beginning 1)))
10359 (org-show-context 'tags-tree))
10360 ((eq action 'agenda)
10361 (setq txt (org-format-agenda-item
10363 (concat
10364 (if (eq org-tags-match-list-sublevels 'indented)
10365 (make-string (1- level) ?.) "")
10366 (org-get-heading))
10367 category
10368 tags-list
10370 priority (org-get-priority txt))
10371 (goto-char lspos)
10372 (setq marker (org-agenda-new-marker))
10373 (org-add-props txt props
10374 'org-marker marker 'org-hd-marker marker 'org-category category
10375 'todo-state todo
10376 'priority priority 'type "tagsmatch")
10377 (push txt rtn))
10378 ((functionp action)
10379 (setq org-map-continue-from nil)
10380 (save-excursion
10381 (setq rtn1 (funcall action))
10382 (push rtn1 rtn)))
10383 (t (error "Invalid action")))
10385 ;; if we are to skip sublevels, jump to end of subtree
10386 (unless org-tags-match-list-sublevels
10387 (org-end-of-subtree t)
10388 (backward-char 1))))
10389 ;; Get the correct position from where to continue
10390 (if org-map-continue-from
10391 (goto-char org-map-continue-from)
10392 (and (= (point) lspos) (end-of-line 1)))))
10393 (when (and (eq action 'sparse-tree)
10394 (not org-sparse-tree-open-archived-trees))
10395 (org-hide-archived-subtrees (point-min) (point-max)))
10396 (nreverse rtn)))
10398 (defun org-remove-uniherited-tags (tags)
10399 "Remove all tags that are not inherited from the list TAGS."
10400 (cond
10401 ((eq org-use-tag-inheritance t)
10402 (if org-tags-exclude-from-inheritance
10403 (org-delete-all org-tags-exclude-from-inheritance tags)
10404 tags))
10405 ((not org-use-tag-inheritance) nil)
10406 ((stringp org-use-tag-inheritance)
10407 (delq nil (mapcar
10408 (lambda (x)
10409 (if (and (string-match org-use-tag-inheritance x)
10410 (not (member x org-tags-exclude-from-inheritance)))
10411 x nil))
10412 tags)))
10413 ((listp org-use-tag-inheritance)
10414 (delq nil (mapcar
10415 (lambda (x)
10416 (if (member x org-use-tag-inheritance) x nil))
10417 tags)))))
10419 (defvar todo-only) ;; dynamically scoped
10421 (defun org-match-sparse-tree (&optional todo-only match)
10422 "Create a sparse tree according to tags string MATCH.
10423 MATCH can contain positive and negative selection of tags, like
10424 \"+WORK+URGENT-WITHBOSS\".
10425 If optional argument TODO-ONLY is non-nil, only select lines that are
10426 also TODO lines."
10427 (interactive "P")
10428 (org-prepare-agenda-buffers (list (current-buffer)))
10429 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
10431 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
10433 (defvar org-cached-props nil)
10434 (defun org-cached-entry-get (pom property)
10435 (if (or (eq t org-use-property-inheritance)
10436 (and (stringp org-use-property-inheritance)
10437 (string-match org-use-property-inheritance property))
10438 (and (listp org-use-property-inheritance)
10439 (member property org-use-property-inheritance)))
10440 ;; Caching is not possible, check it directly
10441 (org-entry-get pom property 'inherit)
10442 ;; Get all properties, so that we can do complicated checks easily
10443 (cdr (assoc property (or org-cached-props
10444 (setq org-cached-props
10445 (org-entry-properties pom)))))))
10447 (defun org-global-tags-completion-table (&optional files)
10448 "Return the list of all tags in all agenda buffer/files."
10449 (save-excursion
10450 (org-uniquify
10451 (delq nil
10452 (apply 'append
10453 (mapcar
10454 (lambda (file)
10455 (set-buffer (find-file-noselect file))
10456 (append (org-get-buffer-tags)
10457 (mapcar (lambda (x) (if (stringp (car-safe x))
10458 (list (car-safe x)) nil))
10459 org-tag-alist)))
10460 (if (and files (car files))
10461 files
10462 (org-agenda-files))))))))
10464 (defun org-make-tags-matcher (match)
10465 "Create the TAGS//TODO matcher form for the selection string MATCH."
10466 ;; todo-only is scoped dynamically into this function, and the function
10467 ;; may change it if the matcher asks for it.
10468 (unless match
10469 ;; Get a new match request, with completion
10470 (let ((org-last-tags-completion-table
10471 (org-global-tags-completion-table)))
10472 (setq match (org-completing-read-no-ido
10473 "Match: " 'org-tags-completion-function nil nil nil
10474 'org-tags-history))))
10476 ;; Parse the string and create a lisp form
10477 (let ((match0 match)
10478 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
10479 minus tag mm
10480 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
10481 orterms term orlist re-p str-p level-p level-op time-p
10482 prop-p pn pv po cat-p gv rest)
10483 (if (string-match "/+" match)
10484 ;; match contains also a todo-matching request
10485 (progn
10486 (setq tagsmatch (substring match 0 (match-beginning 0))
10487 todomatch (substring match (match-end 0)))
10488 (if (string-match "^!" todomatch)
10489 (setq todo-only t todomatch (substring todomatch 1)))
10490 (if (string-match "^\\s-*$" todomatch)
10491 (setq todomatch nil)))
10492 ;; only matching tags
10493 (setq tagsmatch match todomatch nil))
10495 ;; Make the tags matcher
10496 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10497 (setq tagsmatcher t)
10498 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10499 (while (setq term (pop orterms))
10500 (while (and (equal (substring term -1) "\\") orterms)
10501 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10502 (while (string-match re term)
10503 (setq rest (substring term (match-end 0))
10504 minus (and (match-end 1)
10505 (equal (match-string 1 term) "-"))
10506 tag (match-string 2 term)
10507 re-p (equal (string-to-char tag) ?{)
10508 level-p (match-end 4)
10509 prop-p (match-end 5)
10510 mm (cond
10511 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10512 (level-p
10513 (setq level-op (org-op-to-function (match-string 3 term)))
10514 `(,level-op level ,(string-to-number
10515 (match-string 4 term))))
10516 (prop-p
10517 (setq pn (match-string 5 term)
10518 po (match-string 6 term)
10519 pv (match-string 7 term)
10520 cat-p (equal pn "CATEGORY")
10521 re-p (equal (string-to-char pv) ?{)
10522 str-p (equal (string-to-char pv) ?\")
10523 time-p (save-match-data
10524 (string-match "^\"[[<].*[]>]\"$" pv))
10525 pv (if (or re-p str-p) (substring pv 1 -1) pv))
10526 (if time-p (setq pv (org-matcher-time pv)))
10527 (setq po (org-op-to-function po (if time-p 'time str-p)))
10528 (cond
10529 ((equal pn "CATEGORY")
10530 (setq gv '(get-text-property (point) 'org-category)))
10531 ((equal pn "TODO")
10532 (setq gv 'todo))
10534 (setq gv `(org-cached-entry-get nil ,pn))))
10535 (if re-p
10536 (if (eq po 'org<>)
10537 `(not (string-match ,pv (or ,gv "")))
10538 `(string-match ,pv (or ,gv "")))
10539 (if str-p
10540 `(,po (or ,gv "") ,pv)
10541 `(,po (string-to-number (or ,gv ""))
10542 ,(string-to-number pv) ))))
10543 (t `(member ,tag tags-list)))
10544 mm (if minus (list 'not mm) mm)
10545 term rest)
10546 (push mm tagsmatcher))
10547 (push (if (> (length tagsmatcher) 1)
10548 (cons 'and tagsmatcher)
10549 (car tagsmatcher))
10550 orlist)
10551 (setq tagsmatcher nil))
10552 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
10553 (setq tagsmatcher
10554 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
10555 ;; Make the todo matcher
10556 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10557 (setq todomatcher t)
10558 (setq orterms (org-split-string todomatch "|") orlist nil)
10559 (while (setq term (pop orterms))
10560 (while (string-match re term)
10561 (setq minus (and (match-end 1)
10562 (equal (match-string 1 term) "-"))
10563 kwd (match-string 2 term)
10564 re-p (equal (string-to-char kwd) ?{)
10565 term (substring term (match-end 0))
10566 mm (if re-p
10567 `(string-match ,(substring kwd 1 -1) todo)
10568 (list 'equal 'todo kwd))
10569 mm (if minus (list 'not mm) mm))
10570 (push mm todomatcher))
10571 (push (if (> (length todomatcher) 1)
10572 (cons 'and todomatcher)
10573 (car todomatcher))
10574 orlist)
10575 (setq todomatcher nil))
10576 (setq todomatcher (if (> (length orlist) 1)
10577 (cons 'or orlist) (car orlist))))
10579 ;; Return the string and lisp forms of the matcher
10580 (setq matcher (if todomatcher
10581 (list 'and tagsmatcher todomatcher)
10582 tagsmatcher))
10583 (cons match0 matcher)))
10585 (defun org-op-to-function (op &optional stringp)
10586 "Turn an operator into the appropriate function."
10587 (setq op
10588 (cond
10589 ((equal op "<" ) '(< string< org-time<))
10590 ((equal op ">" ) '(> org-string> org-time>))
10591 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
10592 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
10593 ((member op '("=" "==")) '(= string= org-time=))
10594 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
10595 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
10597 (defun org<> (a b) (not (= a b)))
10598 (defun org-string<= (a b) (or (string= a b) (string< a b)))
10599 (defun org-string>= (a b) (not (string< a b)))
10600 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
10601 (defun org-string<> (a b) (not (string= a b)))
10602 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
10603 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
10604 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
10605 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
10606 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
10607 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
10608 (defun org-2ft (s)
10609 "Convert S to a floating point time.
10610 If S is already a number, just return it. If it is a string, parse
10611 it as a time string and apply `float-time' to it. If S is nil, just return 0."
10612 (cond
10613 ((numberp s) s)
10614 ((stringp s)
10615 (condition-case nil
10616 (float-time (apply 'encode-time (org-parse-time-string s)))
10617 (error 0.)))
10618 (t 0.)))
10620 (defun org-time-today ()
10621 "Time in seconds today at 0:00.
10622 Returns the float number of seconds since the beginning of the
10623 epoch to the beginning of today (00:00)."
10624 (float-time (apply 'encode-time
10625 (append '(0 0 0) (nthcdr 3 (decode-time))))))
10627 (defun org-matcher-time (s)
10628 "Interpret a time comparison value."
10629 (save-match-data
10630 (cond
10631 ((string= s "<now>") (float-time))
10632 ((string= s "<today>") (org-time-today))
10633 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
10634 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
10635 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
10636 (+ (org-time-today)
10637 (* (string-to-number (match-string 1 s))
10638 (cdr (assoc (match-string 2 s)
10639 '(("d" . 86400.0) ("w" . 604800.0)
10640 ("m" . 2678400.0) ("y" . 31557600.0)))))))
10641 (t (org-2ft s)))))
10643 (defun org-match-any-p (re list)
10644 "Does re match any element of list?"
10645 (setq list (mapcar (lambda (x) (string-match re x)) list))
10646 (delq nil list))
10648 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
10649 (defvar org-tags-overlay (org-make-overlay 1 1))
10650 (org-detach-overlay org-tags-overlay)
10652 (defun org-get-local-tags-at (&optional pos)
10653 "Get a list of tags defined in the current headline."
10654 (org-get-tags-at pos 'local))
10656 (defun org-get-local-tags ()
10657 "Get a list of tags defined in the current headline."
10658 (org-get-tags-at nil 'local))
10660 (defun org-get-tags-at (&optional pos local)
10661 "Get a list of all headline tags applicable at POS.
10662 POS defaults to point. If tags are inherited, the list contains
10663 the targets in the same sequence as the headlines appear, i.e.
10664 the tags of the current headline come last.
10665 When LOCAL is non-nil, only return tags from the current headline,
10666 ignore inherited ones."
10667 (interactive)
10668 (if (and org-trust-scanner-tags
10669 (or (not pos) (equal pos (point)))
10670 (not local))
10671 org-scanner-tags
10672 (let (tags ltags lastpos parent)
10673 (save-excursion
10674 (save-restriction
10675 (widen)
10676 (goto-char (or pos (point)))
10677 (save-match-data
10678 (catch 'done
10679 (condition-case nil
10680 (progn
10681 (org-back-to-heading t)
10682 (while (not (equal lastpos (point)))
10683 (setq lastpos (point))
10684 (when (looking-at
10685 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
10686 (setq ltags (org-split-string
10687 (org-match-string-no-properties 1) ":"))
10688 (when parent
10689 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
10690 (setq tags (append
10691 (if parent
10692 (org-remove-uniherited-tags ltags)
10693 ltags)
10694 tags)))
10695 (or org-use-tag-inheritance (throw 'done t))
10696 (if local (throw 'done t))
10697 (or (org-up-heading-safe) (error nil))
10698 (setq parent t)))
10699 (error nil)))))
10700 (append (org-remove-uniherited-tags org-file-tags) tags)))))
10702 (defun org-add-prop-inherited (s)
10703 (add-text-properties 0 (length s) '(inherited t) s)
10706 (defun org-toggle-tag (tag &optional onoff)
10707 "Toggle the tag TAG for the current line.
10708 If ONOFF is `on' or `off', don't toggle but set to this state."
10709 (let (res current)
10710 (save-excursion
10711 (org-back-to-heading t)
10712 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
10713 (point-at-eol) t)
10714 (progn
10715 (setq current (match-string 1))
10716 (replace-match ""))
10717 (setq current ""))
10718 (setq current (nreverse (org-split-string current ":")))
10719 (cond
10720 ((eq onoff 'on)
10721 (setq res t)
10722 (or (member tag current) (push tag current)))
10723 ((eq onoff 'off)
10724 (or (not (member tag current)) (setq current (delete tag current))))
10725 (t (if (member tag current)
10726 (setq current (delete tag current))
10727 (setq res t)
10728 (push tag current))))
10729 (end-of-line 1)
10730 (if current
10731 (progn
10732 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
10733 (org-set-tags nil t))
10734 (delete-horizontal-space))
10735 (run-hooks 'org-after-tags-change-hook))
10736 res))
10738 (defun org-align-tags-here (to-col)
10739 ;; Assumes that this is a headline
10740 (let ((pos (point)) (col (current-column)) ncol tags-l p)
10741 (beginning-of-line 1)
10742 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10743 (< pos (match-beginning 2)))
10744 (progn
10745 (setq tags-l (- (match-end 2) (match-beginning 2)))
10746 (goto-char (match-beginning 1))
10747 (insert " ")
10748 (delete-region (point) (1+ (match-beginning 2)))
10749 (setq ncol (max (1+ (current-column))
10750 (1+ col)
10751 (if (> to-col 0)
10752 to-col
10753 (- (abs to-col) tags-l))))
10754 (setq p (point))
10755 (insert (make-string (- ncol (current-column)) ?\ ))
10756 (setq ncol (current-column))
10757 (when indent-tabs-mode (tabify p (point-at-eol)))
10758 (org-move-to-column (min ncol col) t))
10759 (goto-char pos))))
10761 (defun org-set-tags-command (&optional arg just-align)
10762 "Call the set-tags command for the current entry."
10763 (interactive "P")
10764 (if (org-on-heading-p)
10765 (org-set-tags arg just-align)
10766 (save-excursion
10767 (org-back-to-heading t)
10768 (org-set-tags arg just-align))))
10770 (defun org-set-tags (&optional arg just-align)
10771 "Set the tags for the current headline.
10772 With prefix ARG, realign all tags in headings in the current buffer."
10773 (interactive "P")
10774 (let* ((re (concat "^" outline-regexp))
10775 (current (org-get-tags-string))
10776 (col (current-column))
10777 (org-setting-tags t)
10778 table current-tags inherited-tags ; computed below when needed
10779 tags p0 c0 c1 rpl)
10780 (if arg
10781 (save-excursion
10782 (goto-char (point-min))
10783 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
10784 (while (re-search-forward re nil t)
10785 (org-set-tags nil t)
10786 (end-of-line 1)))
10787 (message "All tags realigned to column %d" org-tags-column))
10788 (if just-align
10789 (setq tags current)
10790 ;; Get a new set of tags from the user
10791 (save-excursion
10792 (setq table (append org-tag-persistent-alist
10793 (or org-tag-alist (org-get-buffer-tags)))
10794 org-last-tags-completion-table table
10795 current-tags (org-split-string current ":")
10796 inherited-tags (nreverse
10797 (nthcdr (length current-tags)
10798 (nreverse (org-get-tags-at))))
10799 tags
10800 (if (or (eq t org-use-fast-tag-selection)
10801 (and org-use-fast-tag-selection
10802 (delq nil (mapcar 'cdr table))))
10803 (org-fast-tag-selection
10804 current-tags inherited-tags table
10805 (if org-fast-tag-selection-include-todo org-todo-key-alist))
10806 (let ((org-add-colon-after-tag-completion t))
10807 (org-trim
10808 (org-without-partial-completion
10809 (org-ido-completing-read "Tags: " 'org-tags-completion-function
10810 nil nil current 'org-tags-history)))))))
10811 (while (string-match "[-+&]+" tags)
10812 ;; No boolean logic, just a list
10813 (setq tags (replace-match ":" t t tags))))
10815 (if (string-match "\\`[\t ]*\\'" tags)
10816 (setq tags "")
10817 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
10818 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
10820 ;; Insert new tags at the correct column
10821 (beginning-of-line 1)
10822 (cond
10823 ((and (equal current "") (equal tags "")))
10824 ((re-search-forward
10825 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10826 (point-at-eol) t)
10827 (if (equal tags "")
10828 (setq rpl "")
10829 (goto-char (match-beginning 0))
10830 (setq c0 (current-column) p0 (point)
10831 c1 (max (1+ c0) (if (> org-tags-column 0)
10832 org-tags-column
10833 (- (- org-tags-column) (length tags))))
10834 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10835 (replace-match rpl t t)
10836 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
10837 tags)
10838 (t (error "Tags alignment failed")))
10839 (org-move-to-column col)
10840 (unless just-align
10841 (run-hooks 'org-after-tags-change-hook)))))
10843 (defun org-change-tag-in-region (beg end tag off)
10844 "Add or remove TAG for each entry in the region.
10845 This works in the agenda, and also in an org-mode buffer."
10846 (interactive
10847 (list (region-beginning) (region-end)
10848 (let ((org-last-tags-completion-table
10849 (if (org-mode-p)
10850 (org-get-buffer-tags)
10851 (org-global-tags-completion-table))))
10852 (org-ido-completing-read
10853 "Tag: " 'org-tags-completion-function nil nil nil
10854 'org-tags-history))
10855 (progn
10856 (message "[s]et or [r]emove? ")
10857 (equal (read-char-exclusive) ?r))))
10858 (if (fboundp 'deactivate-mark) (deactivate-mark))
10859 (let ((agendap (equal major-mode 'org-agenda-mode))
10860 l1 l2 m buf pos newhead (cnt 0))
10861 (goto-char end)
10862 (setq l2 (1- (org-current-line)))
10863 (goto-char beg)
10864 (setq l1 (org-current-line))
10865 (loop for l from l1 to l2 do
10866 (goto-line l)
10867 (setq m (get-text-property (point) 'org-hd-marker))
10868 (when (or (and (org-mode-p) (org-on-heading-p))
10869 (and agendap m))
10870 (setq buf (if agendap (marker-buffer m) (current-buffer))
10871 pos (if agendap m (point)))
10872 (with-current-buffer buf
10873 (save-excursion
10874 (save-restriction
10875 (goto-char pos)
10876 (setq cnt (1+ cnt))
10877 (org-toggle-tag tag (if off 'off 'on))
10878 (setq newhead (org-get-heading)))))
10879 (and agendap (org-agenda-change-all-lines newhead m))))
10880 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
10882 (defun org-tags-completion-function (string predicate &optional flag)
10883 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10884 (confirm (lambda (x) (stringp (car x)))))
10885 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10886 (setq s1 (match-string 1 string)
10887 s2 (match-string 2 string))
10888 (setq s1 "" s2 string))
10889 (cond
10890 ((eq flag nil)
10891 ;; try completion
10892 (setq rtn (try-completion s2 ctable confirm))
10893 (if (stringp rtn)
10894 (setq rtn
10895 (concat s1 s2 (substring rtn (length s2))
10896 (if (and org-add-colon-after-tag-completion
10897 (assoc rtn ctable))
10898 ":" ""))))
10899 rtn)
10900 ((eq flag t)
10901 ;; all-completions
10902 (all-completions s2 ctable confirm)
10904 ((eq flag 'lambda)
10905 ;; exact match?
10906 (assoc s2 ctable)))
10909 (defun org-fast-tag-insert (kwd tags face &optional end)
10910 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
10911 (insert (format "%-12s" (concat kwd ":"))
10912 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
10913 (or end "")))
10915 (defun org-fast-tag-show-exit (flag)
10916 (save-excursion
10917 (goto-line 3)
10918 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
10919 (replace-match ""))
10920 (when flag
10921 (end-of-line 1)
10922 (org-move-to-column (- (window-width) 19) t)
10923 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
10925 (defun org-set-current-tags-overlay (current prefix)
10926 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
10927 (if (featurep 'xemacs)
10928 (org-overlay-display org-tags-overlay (concat prefix s)
10929 'secondary-selection)
10930 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
10931 (org-overlay-display org-tags-overlay (concat prefix s)))))
10933 (defun org-fast-tag-selection (current inherited table &optional todo-table)
10934 "Fast tag selection with single keys.
10935 CURRENT is the current list of tags in the headline, INHERITED is the
10936 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
10937 possibly with grouping information. TODO-TABLE is a similar table with
10938 TODO keywords, should these have keys assigned to them.
10939 If the keys are nil, a-z are automatically assigned.
10940 Returns the new tags string, or nil to not change the current settings."
10941 (let* ((fulltable (append table todo-table))
10942 (maxlen (apply 'max (mapcar
10943 (lambda (x)
10944 (if (stringp (car x)) (string-width (car x)) 0))
10945 fulltable)))
10946 (buf (current-buffer))
10947 (expert (eq org-fast-tag-selection-single-key 'expert))
10948 (buffer-tags nil)
10949 (fwidth (+ maxlen 3 1 3))
10950 (ncol (/ (- (window-width) 4) fwidth))
10951 (i-face 'org-done)
10952 (c-face 'org-todo)
10953 tg cnt e c char c1 c2 ntable tbl rtn
10954 ov-start ov-end ov-prefix
10955 (exit-after-next org-fast-tag-selection-single-key)
10956 (done-keywords org-done-keywords)
10957 groups ingroup)
10958 (save-excursion
10959 (beginning-of-line 1)
10960 (if (looking-at
10961 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10962 (setq ov-start (match-beginning 1)
10963 ov-end (match-end 1)
10964 ov-prefix "")
10965 (setq ov-start (1- (point-at-eol))
10966 ov-end (1+ ov-start))
10967 (skip-chars-forward "^\n\r")
10968 (setq ov-prefix
10969 (concat
10970 (buffer-substring (1- (point)) (point))
10971 (if (> (current-column) org-tags-column)
10973 (make-string (- org-tags-column (current-column)) ?\ ))))))
10974 (org-move-overlay org-tags-overlay ov-start ov-end)
10975 (save-window-excursion
10976 (if expert
10977 (set-buffer (get-buffer-create " *Org tags*"))
10978 (delete-other-windows)
10979 (split-window-vertically)
10980 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
10981 (erase-buffer)
10982 (org-set-local 'org-done-keywords done-keywords)
10983 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10984 (org-fast-tag-insert "Current" current c-face "\n\n")
10985 (org-fast-tag-show-exit exit-after-next)
10986 (org-set-current-tags-overlay current ov-prefix)
10987 (setq tbl fulltable char ?a cnt 0)
10988 (while (setq e (pop tbl))
10989 (cond
10990 ((equal e '(:startgroup))
10991 (push '() groups) (setq ingroup t)
10992 (when (not (= cnt 0))
10993 (setq cnt 0)
10994 (insert "\n"))
10995 (insert "{ "))
10996 ((equal e '(:endgroup))
10997 (setq ingroup nil cnt 0)
10998 (insert "}\n"))
10999 ((equal e '(:newline))
11000 (when (not (= cnt 0))
11001 (setq cnt 0)
11002 (insert "\n")
11003 (setq e (car tbl))
11004 (while (equal (car tbl) '(:newline))
11005 (insert "\n")
11006 (setq tbl (cdr tbl)))))
11008 (setq tg (car e) c2 nil)
11009 (if (cdr e)
11010 (setq c (cdr e))
11011 ;; automatically assign a character.
11012 (setq c1 (string-to-char
11013 (downcase (substring
11014 tg (if (= (string-to-char tg) ?@) 1 0)))))
11015 (if (or (rassoc c1 ntable) (rassoc c1 table))
11016 (while (or (rassoc char ntable) (rassoc char table))
11017 (setq char (1+ char)))
11018 (setq c2 c1))
11019 (setq c (or c2 char)))
11020 (if ingroup (push tg (car groups)))
11021 (setq tg (org-add-props tg nil 'face
11022 (cond
11023 ((not (assoc tg table))
11024 (org-get-todo-face tg))
11025 ((member tg current) c-face)
11026 ((member tg inherited) i-face)
11027 (t nil))))
11028 (if (and (= cnt 0) (not ingroup)) (insert " "))
11029 (insert "[" c "] " tg (make-string
11030 (- fwidth 4 (length tg)) ?\ ))
11031 (push (cons tg c) ntable)
11032 (when (= (setq cnt (1+ cnt)) ncol)
11033 (insert "\n")
11034 (if ingroup (insert " "))
11035 (setq cnt 0)))))
11036 (setq ntable (nreverse ntable))
11037 (insert "\n")
11038 (goto-char (point-min))
11039 (if (not expert) (org-fit-window-to-buffer))
11040 (setq rtn
11041 (catch 'exit
11042 (while t
11043 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
11044 (if groups " [!] no groups" " [!]groups")
11045 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
11046 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11047 (cond
11048 ((= c ?\r) (throw 'exit t))
11049 ((= c ?!)
11050 (setq groups (not groups))
11051 (goto-char (point-min))
11052 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
11053 ((= c ?\C-c)
11054 (if (not expert)
11055 (org-fast-tag-show-exit
11056 (setq exit-after-next (not exit-after-next)))
11057 (setq expert nil)
11058 (delete-other-windows)
11059 (split-window-vertically)
11060 (org-switch-to-buffer-other-window " *Org tags*")
11061 (org-fit-window-to-buffer)))
11062 ((or (= c ?\C-g)
11063 (and (= c ?q) (not (rassoc c ntable))))
11064 (org-detach-overlay org-tags-overlay)
11065 (setq quit-flag t))
11066 ((= c ?\ )
11067 (setq current nil)
11068 (if exit-after-next (setq exit-after-next 'now)))
11069 ((= c ?\t)
11070 (condition-case nil
11071 (setq tg (org-ido-completing-read
11072 "Tag: "
11073 (or buffer-tags
11074 (with-current-buffer buf
11075 (org-get-buffer-tags)))))
11076 (quit (setq tg "")))
11077 (when (string-match "\\S-" tg)
11078 (add-to-list 'buffer-tags (list tg))
11079 (if (member tg current)
11080 (setq current (delete tg current))
11081 (push tg current)))
11082 (if exit-after-next (setq exit-after-next 'now)))
11083 ((setq e (rassoc c todo-table) tg (car e))
11084 (with-current-buffer buf
11085 (save-excursion (org-todo tg)))
11086 (if exit-after-next (setq exit-after-next 'now)))
11087 ((setq e (rassoc c ntable) tg (car e))
11088 (if (member tg current)
11089 (setq current (delete tg current))
11090 (loop for g in groups do
11091 (if (member tg g)
11092 (mapc (lambda (x)
11093 (setq current (delete x current)))
11094 g)))
11095 (push tg current))
11096 (if exit-after-next (setq exit-after-next 'now))))
11098 ;; Create a sorted list
11099 (setq current
11100 (sort current
11101 (lambda (a b)
11102 (assoc b (cdr (memq (assoc a ntable) ntable))))))
11103 (if (eq exit-after-next 'now) (throw 'exit t))
11104 (goto-char (point-min))
11105 (beginning-of-line 2)
11106 (delete-region (point) (point-at-eol))
11107 (org-fast-tag-insert "Current" current c-face)
11108 (org-set-current-tags-overlay current ov-prefix)
11109 (while (re-search-forward
11110 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
11111 (setq tg (match-string 1))
11112 (add-text-properties
11113 (match-beginning 1) (match-end 1)
11114 (list 'face
11115 (cond
11116 ((member tg current) c-face)
11117 ((member tg inherited) i-face)
11118 (t (get-text-property (match-beginning 1) 'face))))))
11119 (goto-char (point-min)))))
11120 (org-detach-overlay org-tags-overlay)
11121 (if rtn
11122 (mapconcat 'identity current ":")
11123 nil))))
11125 (defun org-get-tags-string ()
11126 "Get the TAGS string in the current headline."
11127 (unless (org-on-heading-p t)
11128 (error "Not on a heading"))
11129 (save-excursion
11130 (beginning-of-line 1)
11131 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11132 (org-match-string-no-properties 1)
11133 "")))
11135 (defun org-get-tags ()
11136 "Get the list of tags specified in the current headline."
11137 (org-split-string (org-get-tags-string) ":"))
11139 (defun org-get-buffer-tags ()
11140 "Get a table of all tags used in the buffer, for completion."
11141 (let (tags)
11142 (save-excursion
11143 (goto-char (point-min))
11144 (while (re-search-forward
11145 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
11146 (when (equal (char-after (point-at-bol 0)) ?*)
11147 (mapc (lambda (x) (add-to-list 'tags x))
11148 (org-split-string (org-match-string-no-properties 1) ":")))))
11149 (mapcar 'list tags)))
11151 ;;;; The mapping API
11153 ;;;###autoload
11154 (defun org-map-entries (func &optional match scope &rest skip)
11155 "Call FUNC at each headline selected by MATCH in SCOPE.
11157 FUNC is a function or a lisp form. The function will be called without
11158 arguments, with the cursor positioned at the beginning of the headline.
11159 The return values of all calls to the function will be collected and
11160 returned as a list.
11162 The call to FUNC will be wrapped into a save-excursion form, so FUNC
11163 does not need to preserve point. After evaluaton, the cursor will be
11164 moved to the end of the line (presumably of the headline of the
11165 processed entry) and search continues from there. Under some
11166 circumstances, this may not produce the wanted results. For example,
11167 if you have removed (e.g. archived) the current (sub)tree it could
11168 mean that the next entry will be skipped entirely. In such cases, you
11169 can specify the position from where search should continue by making
11170 FUNC set the variable `org-map-continue-from' to the desired buffer
11171 position.
11173 MATCH is a tags/property/todo match as it is used in the agenda tags view.
11174 Only headlines that are matched by this query will be considered during
11175 the iteration. When MATCH is nil or t, all headlines will be
11176 visited by the iteration.
11178 SCOPE determines the scope of this command. It can be any of:
11180 nil The current buffer, respecting the restriction if any
11181 tree The subtree started with the entry at point
11182 file The current buffer, without restriction
11183 file-with-archives
11184 The current buffer, and any archives associated with it
11185 agenda All agenda files
11186 agenda-with-archives
11187 All agenda files with any archive files associated with them
11188 \(file1 file2 ...)
11189 If this is a list, all files in the list will be scanned
11191 The remaining args are treated as settings for the skipping facilities of
11192 the scanner. The following items can be given here:
11194 archive skip trees with the archive tag.
11195 comment skip trees with the COMMENT keyword
11196 function or Emacs Lisp form:
11197 will be used as value for `org-agenda-skip-function', so whenever
11198 the the function returns t, FUNC will not be called for that
11199 entry and search will continue from the point where the
11200 function leaves it.
11202 If your function needs to retrieve the tags including inherited tags
11203 at the *current* entry, you can use the value of the variable
11204 `org-scanner-tags' which will be much faster than getting the value
11205 with `org-get-tags-at'. If your function gets properties with
11206 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
11207 to t around the call to `org-entry-properties' to get the same speedup.
11208 Note that if your function moves around to retrieve tags and properties at
11209 a *different* entry, you cannot use these techniques."
11210 (let* ((org-agenda-archives-mode nil) ; just to make sure
11211 (org-agenda-skip-archived-trees (memq 'archive skip))
11212 (org-agenda-skip-comment-trees (memq 'comment skip))
11213 (org-agenda-skip-function
11214 (car (org-delete-all '(comment archive) skip)))
11215 (org-tags-match-list-sublevels t)
11216 matcher file res
11217 org-todo-keywords-for-agenda
11218 org-done-keywords-for-agenda
11219 org-todo-keyword-alist-for-agenda
11220 org-tag-alist-for-agenda)
11222 (cond
11223 ((eq match t) (setq matcher t))
11224 ((eq match nil) (setq matcher t))
11225 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
11227 (save-excursion
11228 (save-restriction
11229 (when (eq scope 'tree)
11230 (org-back-to-heading t)
11231 (org-narrow-to-subtree)
11232 (setq scope nil))
11234 (if (not scope)
11235 (progn
11236 (org-prepare-agenda-buffers
11237 (list (buffer-file-name (current-buffer))))
11238 (setq res (org-scan-tags func matcher)))
11239 ;; Get the right scope
11240 (cond
11241 ((and scope (listp scope) (symbolp (car scope)))
11242 (setq scope (eval scope)))
11243 ((eq scope 'agenda)
11244 (setq scope (org-agenda-files t)))
11245 ((eq scope 'agenda-with-archives)
11246 (setq scope (org-agenda-files t))
11247 (setq scope (org-add-archive-files scope)))
11248 ((eq scope 'file)
11249 (setq scope (list (buffer-file-name))))
11250 ((eq scope 'file-with-archives)
11251 (setq scope (org-add-archive-files (list (buffer-file-name))))))
11252 (org-prepare-agenda-buffers scope)
11253 (while (setq file (pop scope))
11254 (with-current-buffer (org-find-base-buffer-visiting file)
11255 (save-excursion
11256 (save-restriction
11257 (widen)
11258 (goto-char (point-min))
11259 (setq res (append res (org-scan-tags func matcher))))))))))
11260 res))
11262 ;;;; Properties
11264 ;;; Setting and retrieving properties
11266 (defconst org-special-properties
11267 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
11268 "TIMESTAMP" "TIMESTAMP_IA")
11269 "The special properties valid in Org-mode.
11271 These are properties that are not defined in the property drawer,
11272 but in some other way.")
11274 (defconst org-default-properties
11275 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
11276 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
11277 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
11278 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
11279 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
11280 "CLOCK_MODELINE_TOTAL")
11281 "Some properties that are used by Org-mode for various purposes.
11282 Being in this list makes sure that they are offered for completion.")
11284 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
11285 "Regular expression matching the first line of a property drawer.")
11287 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
11288 "Regular expression matching the first line of a property drawer.")
11290 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
11291 "Regular expression matching the first line of a property drawer.")
11293 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
11294 "Regular expression matching the first line of a property drawer.")
11296 (defconst org-property-drawer-re
11297 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
11298 org-property-end-re "\\)\n?")
11299 "Matches an entire property drawer.")
11301 (defconst org-clock-drawer-re
11302 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
11303 org-property-end-re "\\)\n?")
11304 "Matches an entire clock drawer.")
11306 (defun org-property-action ()
11307 "Do an action on properties."
11308 (interactive)
11309 (let (c)
11310 (org-at-property-p)
11311 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
11312 (setq c (read-char-exclusive))
11313 (cond
11314 ((equal c ?s)
11315 (call-interactively 'org-set-property))
11316 ((equal c ?d)
11317 (call-interactively 'org-delete-property))
11318 ((equal c ?D)
11319 (call-interactively 'org-delete-property-globally))
11320 ((equal c ?c)
11321 (call-interactively 'org-compute-property-at-point))
11322 (t (error "No such property action %c" c)))))
11324 (defun org-at-property-p ()
11325 "Is the cursor in a property line?"
11326 ;; FIXME: Does not check if we are actually in the drawer.
11327 ;; FIXME: also returns true on any drawers.....
11328 ;; This is used by C-c C-c for property action.
11329 (save-excursion
11330 (beginning-of-line 1)
11331 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
11333 (defun org-get-property-block (&optional beg end force)
11334 "Return the (beg . end) range of the body of the property drawer.
11335 BEG and END can be beginning and end of subtree, if not given
11336 they will be found.
11337 If the drawer does not exist and FORCE is non-nil, create the drawer."
11338 (catch 'exit
11339 (save-excursion
11340 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
11341 (end (or end (progn (outline-next-heading) (point)))))
11342 (goto-char beg)
11343 (if (re-search-forward org-property-start-re end t)
11344 (setq beg (1+ (match-end 0)))
11345 (if force
11346 (save-excursion
11347 (org-insert-property-drawer)
11348 (setq end (progn (outline-next-heading) (point))))
11349 (throw 'exit nil))
11350 (goto-char beg)
11351 (if (re-search-forward org-property-start-re end t)
11352 (setq beg (1+ (match-end 0)))))
11353 (if (re-search-forward org-property-end-re end t)
11354 (setq end (match-beginning 0))
11355 (or force (throw 'exit nil))
11356 (goto-char beg)
11357 (setq end beg)
11358 (org-indent-line-function)
11359 (insert ":END:\n"))
11360 (cons beg end)))))
11362 (defun org-entry-properties (&optional pom which)
11363 "Get all properties of the entry at point-or-marker POM.
11364 This includes the TODO keyword, the tags, time strings for deadline,
11365 scheduled, and clocking, and any additional properties defined in the
11366 entry. The return value is an alist, keys may occur multiple times
11367 if the property key was used several times.
11368 POM may also be nil, in which case the current entry is used.
11369 If WHICH is nil or `all', get all properties. If WHICH is
11370 `special' or `standard', only get that subclass."
11371 (setq which (or which 'all))
11372 (org-with-point-at pom
11373 (let ((clockstr (substring org-clock-string 0 -1))
11374 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
11375 beg end range props sum-props key value string clocksum)
11376 (save-excursion
11377 (when (condition-case nil
11378 (and (org-mode-p) (org-back-to-heading t))
11379 (error nil))
11380 (setq beg (point))
11381 (setq sum-props (get-text-property (point) 'org-summaries))
11382 (setq clocksum (get-text-property (point) :org-clock-minutes))
11383 (outline-next-heading)
11384 (setq end (point))
11385 (when (memq which '(all special))
11386 ;; Get the special properties, like TODO and tags
11387 (goto-char beg)
11388 (when (and (looking-at org-todo-line-regexp) (match-end 2))
11389 (push (cons "TODO" (org-match-string-no-properties 2)) props))
11390 (when (looking-at org-priority-regexp)
11391 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
11392 (when (and (setq value (org-get-tags-string))
11393 (string-match "\\S-" value))
11394 (push (cons "TAGS" value) props))
11395 (when (setq value (org-get-tags-at))
11396 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
11397 props))
11398 (while (re-search-forward org-maybe-keyword-time-regexp end t)
11399 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
11400 string (if (equal key clockstr)
11401 (org-no-properties
11402 (org-trim
11403 (buffer-substring
11404 (match-beginning 3) (goto-char (point-at-eol)))))
11405 (substring (org-match-string-no-properties 3) 1 -1)))
11406 (unless key
11407 (if (= (char-after (match-beginning 3)) ?\[)
11408 (setq key "TIMESTAMP_IA")
11409 (setq key "TIMESTAMP")))
11410 (when (or (equal key clockstr) (not (assoc key props)))
11411 (push (cons key string) props)))
11415 (when (memq which '(all standard))
11416 ;; Get the standard properties, like :PROP: ...
11417 (setq range (org-get-property-block beg end))
11418 (when range
11419 (goto-char (car range))
11420 (while (re-search-forward
11421 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
11422 (cdr range) t)
11423 (setq key (org-match-string-no-properties 1)
11424 value (org-trim (or (org-match-string-no-properties 2) "")))
11425 (unless (member key excluded)
11426 (push (cons key (or value "")) props)))))
11427 (if clocksum
11428 (push (cons "CLOCKSUM"
11429 (org-columns-number-to-string (/ (float clocksum) 60.)
11430 'add_times))
11431 props))
11432 (unless (assoc "CATEGORY" props)
11433 (setq value (or (org-get-category)
11434 (progn (org-refresh-category-properties)
11435 (org-get-category))))
11436 (push (cons "CATEGORY" value) props))
11437 (append sum-props (nreverse props)))))))
11439 (defun org-entry-get (pom property &optional inherit)
11440 "Get value of PROPERTY for entry at point-or-marker POM.
11441 If INHERIT is non-nil and the entry does not have the property,
11442 then also check higher levels of the hierarchy.
11443 If INHERIT is the symbol `selective', use inheritance only if the setting
11444 in `org-use-property-inheritance' selects PROPERTY for inheritance.
11445 If the property is present but empty, the return value is the empty string.
11446 If the property is not present at all, nil is returned."
11447 (org-with-point-at pom
11448 (if (and inherit (if (eq inherit 'selective)
11449 (org-property-inherit-p property)
11451 (org-entry-get-with-inheritance property)
11452 (if (member property org-special-properties)
11453 ;; We need a special property. Use brute force, get all properties.
11454 (cdr (assoc property (org-entry-properties nil 'special)))
11455 (let ((range (org-get-property-block)))
11456 (if (and range
11457 (goto-char (car range))
11458 (re-search-forward
11459 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
11460 (cdr range) t))
11461 ;; Found the property, return it.
11462 (if (match-end 1)
11463 (org-match-string-no-properties 1)
11464 "")))))))
11466 (defun org-property-or-variable-value (var &optional inherit)
11467 "Check if there is a property fixing the value of VAR.
11468 If yes, return this value. If not, return the current value of the variable."
11469 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
11470 (if (and prop (stringp prop) (string-match "\\S-" prop))
11471 (read prop)
11472 (symbol-value var))))
11474 (defun org-entry-delete (pom property)
11475 "Delete the property PROPERTY from entry at point-or-marker POM."
11476 (org-with-point-at pom
11477 (if (member property org-special-properties)
11478 nil ; cannot delete these properties.
11479 (let ((range (org-get-property-block)))
11480 (if (and range
11481 (goto-char (car range))
11482 (re-search-forward
11483 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
11484 (cdr range) t))
11485 (progn
11486 (delete-region (match-beginning 0) (1+ (point-at-eol)))
11488 nil)))))
11490 ;; Multi-values properties are properties that contain multiple values
11491 ;; These values are assumed to be single words, separated by whitespace.
11492 (defun org-entry-add-to-multivalued-property (pom property value)
11493 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
11494 (let* ((old (org-entry-get pom property))
11495 (values (and old (org-split-string old "[ \t]"))))
11496 (setq value (org-entry-protect-space value))
11497 (unless (member value values)
11498 (setq values (cons value values))
11499 (org-entry-put pom property
11500 (mapconcat 'identity values " ")))))
11502 (defun org-entry-remove-from-multivalued-property (pom property value)
11503 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
11504 (let* ((old (org-entry-get pom property))
11505 (values (and old (org-split-string old "[ \t]"))))
11506 (setq value (org-entry-protect-space value))
11507 (when (member value values)
11508 (setq values (delete value values))
11509 (org-entry-put pom property
11510 (mapconcat 'identity values " ")))))
11512 (defun org-entry-member-in-multivalued-property (pom property value)
11513 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
11514 (let* ((old (org-entry-get pom property))
11515 (values (and old (org-split-string old "[ \t]"))))
11516 (setq value (org-entry-protect-space value))
11517 (member value values)))
11519 (defun org-entry-get-multivalued-property (pom property)
11520 "Return a list of values in a multivalued property."
11521 (let* ((value (org-entry-get pom property))
11522 (values (and value (org-split-string value "[ \t]"))))
11523 (mapcar 'org-entry-restore-space values)))
11525 (defun org-entry-put-multivalued-property (pom property &rest values)
11526 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
11527 VALUES should be a list of strings. Spaces will be protected."
11528 (org-entry-put pom property
11529 (mapconcat 'org-entry-protect-space values " "))
11530 (let* ((value (org-entry-get pom property))
11531 (values (and value (org-split-string value "[ \t]"))))
11532 (mapcar 'org-entry-restore-space values)))
11534 (defun org-entry-protect-space (s)
11535 "Protect spaces and newline in string S."
11536 (while (string-match " " s)
11537 (setq s (replace-match "%20" t t s)))
11538 (while (string-match "\n" s)
11539 (setq s (replace-match "%0A" t t s)))
11542 (defun org-entry-restore-space (s)
11543 "Restore spaces and newline in string S."
11544 (while (string-match "%20" s)
11545 (setq s (replace-match " " t t s)))
11546 (while (string-match "%0A" s)
11547 (setq s (replace-match "\n" t t s)))
11550 (defvar org-entry-property-inherited-from (make-marker)
11551 "Marker pointing to the entry from where a property was inherited.
11552 Each call to `org-entry-get-with-inheritance' will set this marker to the
11553 location of the entry where the inheritance search matched. If there was
11554 no match, the marker will point nowhere.
11555 Note that also `org-entry-get' calls this function, if the INHERIT flag
11556 is set.")
11558 (defun org-entry-get-with-inheritance (property)
11559 "Get entry property, and search higher levels if not present."
11560 (move-marker org-entry-property-inherited-from nil)
11561 (let (tmp)
11562 (save-excursion
11563 (save-restriction
11564 (widen)
11565 (catch 'ex
11566 (while t
11567 (when (setq tmp (org-entry-get nil property))
11568 (org-back-to-heading t)
11569 (move-marker org-entry-property-inherited-from (point))
11570 (throw 'ex tmp))
11571 (or (org-up-heading-safe) (throw 'ex nil)))))
11572 (or tmp
11573 (cdr (assoc property org-file-properties))
11574 (cdr (assoc property org-global-properties))
11575 (cdr (assoc property org-global-properties-fixed))))))
11577 (defun org-entry-put (pom property value)
11578 "Set PROPERTY to VALUE for entry at point-or-marker POM."
11579 (org-with-point-at pom
11580 (org-back-to-heading t)
11581 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
11582 range)
11583 (cond
11584 ((equal property "TODO")
11585 (when (and (stringp value) (string-match "\\S-" value)
11586 (not (member value org-todo-keywords-1)))
11587 (error "\"%s\" is not a valid TODO state" value))
11588 (if (or (not value)
11589 (not (string-match "\\S-" value)))
11590 (setq value 'none))
11591 (org-todo value)
11592 (org-set-tags nil 'align))
11593 ((equal property "PRIORITY")
11594 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
11595 (string-to-char value) ?\ ))
11596 (org-set-tags nil 'align))
11597 ((equal property "SCHEDULED")
11598 (if (re-search-forward org-scheduled-time-regexp end t)
11599 (cond
11600 ((eq value 'earlier) (org-timestamp-change -1 'day))
11601 ((eq value 'later) (org-timestamp-change 1 'day))
11602 (t (call-interactively 'org-schedule)))
11603 (call-interactively 'org-schedule)))
11604 ((equal property "DEADLINE")
11605 (if (re-search-forward org-deadline-time-regexp end t)
11606 (cond
11607 ((eq value 'earlier) (org-timestamp-change -1 'day))
11608 ((eq value 'later) (org-timestamp-change 1 'day))
11609 (t (call-interactively 'org-deadline)))
11610 (call-interactively 'org-deadline)))
11611 ((member property org-special-properties)
11612 (error "The %s property can not yet be set with `org-entry-put'"
11613 property))
11614 (t ; a non-special property
11615 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
11616 (setq range (org-get-property-block beg end 'force))
11617 (goto-char (car range))
11618 (if (re-search-forward
11619 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
11620 (progn
11621 (delete-region (match-beginning 1) (match-end 1))
11622 (goto-char (match-beginning 1)))
11623 (goto-char (cdr range))
11624 (insert "\n")
11625 (backward-char 1)
11626 (org-indent-line-function)
11627 (insert ":" property ":"))
11628 (and value (insert " " value))
11629 (org-indent-line-function)))))))
11631 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
11632 "Get all property keys in the current buffer.
11633 With INCLUDE-SPECIALS, also list the special properties that reflect things
11634 like tags and TODO state.
11635 With INCLUDE-DEFAULTS, also include properties that has special meaning
11636 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
11637 With INCLUDE-COLUMNS, also include property names given in COLUMN
11638 formats in the current buffer."
11639 (let (rtn range cfmt s p)
11640 (save-excursion
11641 (save-restriction
11642 (widen)
11643 (goto-char (point-min))
11644 (while (re-search-forward org-property-start-re nil t)
11645 (setq range (org-get-property-block))
11646 (goto-char (car range))
11647 (while (re-search-forward
11648 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
11649 (cdr range) t)
11650 (add-to-list 'rtn (org-match-string-no-properties 1)))
11651 (outline-next-heading))))
11653 (when include-specials
11654 (setq rtn (append org-special-properties rtn)))
11656 (when include-defaults
11657 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
11658 (add-to-list 'rtn org-effort-property))
11660 (when include-columns
11661 (save-excursion
11662 (save-restriction
11663 (widen)
11664 (goto-char (point-min))
11665 (while (re-search-forward
11666 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
11667 nil t)
11668 (setq cfmt (match-string 2) s 0)
11669 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
11670 cfmt s)
11671 (setq s (match-end 0)
11672 p (match-string 1 cfmt))
11673 (unless (or (equal p "ITEM")
11674 (member p org-special-properties))
11675 (add-to-list 'rtn (match-string 1 cfmt))))))))
11677 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
11679 (defun org-property-values (key)
11680 "Return a list of all values of property KEY."
11681 (save-excursion
11682 (save-restriction
11683 (widen)
11684 (goto-char (point-min))
11685 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
11686 values)
11687 (while (re-search-forward re nil t)
11688 (add-to-list 'values (org-trim (match-string 1))))
11689 (delete "" values)))))
11691 (defun org-insert-property-drawer ()
11692 "Insert a property drawer into the current entry."
11693 (interactive)
11694 (org-back-to-heading t)
11695 (looking-at outline-regexp)
11696 (let ((indent (if org-adapt-indentation
11697 (- (match-end 0)(match-beginning 0))
11699 (beg (point))
11700 (re (concat "^[ \t]*" org-keyword-time-regexp))
11701 end hiddenp)
11702 (outline-next-heading)
11703 (setq end (point))
11704 (goto-char beg)
11705 (while (re-search-forward re end t))
11706 (setq hiddenp (org-invisible-p))
11707 (end-of-line 1)
11708 (and (equal (char-after) ?\n) (forward-char 1))
11709 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
11710 (if (member (match-string 1) '("CLOCK:" ":END:"))
11711 ;; just skip this line
11712 (beginning-of-line 2)
11713 ;; Drawer start, find the end
11714 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
11715 (beginning-of-line 1)))
11716 (org-skip-over-state-notes)
11717 (skip-chars-backward " \t\n\r")
11718 (if (eq (char-before) ?*) (forward-char 1))
11719 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
11720 (beginning-of-line 0)
11721 (org-indent-to-column indent)
11722 (beginning-of-line 2)
11723 (org-indent-to-column indent)
11724 (beginning-of-line 0)
11725 (if hiddenp
11726 (save-excursion
11727 (org-back-to-heading t)
11728 (hide-entry))
11729 (org-flag-drawer t))))
11731 (defun org-set-property (property value)
11732 "In the current entry, set PROPERTY to VALUE.
11733 When called interactively, this will prompt for a property name, offering
11734 completion on existing and default properties. And then it will prompt
11735 for a value, offering completion either on allowed values (via an inherited
11736 xxx_ALL property) or on existing values in other instances of this property
11737 in the current file."
11738 (interactive
11739 (let* ((completion-ignore-case t)
11740 (keys (org-buffer-property-keys nil t t))
11741 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
11742 (prop (if (member prop0 keys)
11743 prop0
11744 (or (cdr (assoc (downcase prop0)
11745 (mapcar (lambda (x) (cons (downcase x) x))
11746 keys)))
11747 prop0)))
11748 (cur (org-entry-get nil prop))
11749 (allowed (org-property-get-allowed-values nil prop 'table))
11750 (existing (mapcar 'list (org-property-values prop)))
11751 (val (if allowed
11752 (org-completing-read "Value: " allowed nil 'req-match)
11753 (let (org-completion-use-ido)
11754 (org-completing-read
11755 (concat "Value" (if (and cur (string-match "\\S-" cur))
11756 (concat "[" cur "]") "")
11757 ": ")
11758 existing nil nil "" nil cur)))))
11759 (list prop (if (equal val "") cur val))))
11760 (unless (equal (org-entry-get nil property) value)
11761 (org-entry-put nil property value)))
11763 (defun org-delete-property (property)
11764 "In the current entry, delete PROPERTY."
11765 (interactive
11766 (let* ((completion-ignore-case t)
11767 (prop (org-ido-completing-read
11768 "Property: " (org-entry-properties nil 'standard))))
11769 (list prop)))
11770 (message "Property %s %s" property
11771 (if (org-entry-delete nil property)
11772 "deleted"
11773 "was not present in the entry")))
11775 (defun org-delete-property-globally (property)
11776 "Remove PROPERTY globally, from all entries."
11777 (interactive
11778 (let* ((completion-ignore-case t)
11779 (prop (org-ido-completing-read
11780 "Globally remove property: "
11781 (mapcar 'list (org-buffer-property-keys)))))
11782 (list prop)))
11783 (save-excursion
11784 (save-restriction
11785 (widen)
11786 (goto-char (point-min))
11787 (let ((cnt 0))
11788 (while (re-search-forward
11789 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
11790 nil t)
11791 (setq cnt (1+ cnt))
11792 (replace-match ""))
11793 (message "Property \"%s\" removed from %d entries" property cnt)))))
11795 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
11797 (defun org-compute-property-at-point ()
11798 "Compute the property at point.
11799 This looks for an enclosing column format, extracts the operator and
11800 then applies it to the property in the column format's scope."
11801 (interactive)
11802 (unless (org-at-property-p)
11803 (error "Not at a property"))
11804 (let ((prop (org-match-string-no-properties 2)))
11805 (org-columns-get-format-and-top-level)
11806 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
11807 (error "No operator defined for property %s" prop))
11808 (org-columns-compute prop)))
11810 (defun org-property-get-allowed-values (pom property &optional table)
11811 "Get allowed values for the property PROPERTY.
11812 When TABLE is non-nil, return an alist that can directly be used for
11813 completion."
11814 (let (vals)
11815 (cond
11816 ((equal property "TODO")
11817 (setq vals (org-with-point-at pom
11818 (append org-todo-keywords-1 '("")))))
11819 ((equal property "PRIORITY")
11820 (let ((n org-lowest-priority))
11821 (while (>= n org-highest-priority)
11822 (push (char-to-string n) vals)
11823 (setq n (1- n)))))
11824 ((member property org-special-properties))
11826 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
11828 (when (and vals (string-match "\\S-" vals))
11829 (setq vals (car (read-from-string (concat "(" vals ")"))))
11830 (setq vals (mapcar (lambda (x)
11831 (cond ((stringp x) x)
11832 ((numberp x) (number-to-string x))
11833 ((symbolp x) (symbol-name x))
11834 (t "???")))
11835 vals)))))
11836 (if table (mapcar 'list vals) vals)))
11838 (defun org-property-previous-allowed-value (&optional previous)
11839 "Switch to the next allowed value for this property."
11840 (interactive)
11841 (org-property-next-allowed-value t))
11843 (defun org-property-next-allowed-value (&optional previous)
11844 "Switch to the next allowed value for this property."
11845 (interactive)
11846 (unless (org-at-property-p)
11847 (error "Not at a property"))
11848 (let* ((key (match-string 2))
11849 (value (match-string 3))
11850 (allowed (or (org-property-get-allowed-values (point) key)
11851 (and (member value '("[ ]" "[-]" "[X]"))
11852 '("[ ]" "[X]"))))
11853 nval)
11854 (unless allowed
11855 (error "Allowed values for this property have not been defined"))
11856 (if previous (setq allowed (reverse allowed)))
11857 (if (member value allowed)
11858 (setq nval (car (cdr (member value allowed)))))
11859 (setq nval (or nval (car allowed)))
11860 (if (equal nval value)
11861 (error "Only one allowed value for this property"))
11862 (org-at-property-p)
11863 (replace-match (concat " :" key ": " nval) t t)
11864 (org-indent-line-function)
11865 (beginning-of-line 1)
11866 (skip-chars-forward " \t")))
11868 (defun org-find-entry-with-id (ident)
11869 "Locate the entry that contains the ID property with exact value IDENT.
11870 IDENT can be a string, a symbol or a number, this function will search for
11871 the string representation of it.
11872 Return the position where this entry starts, or nil if there is no such entry."
11873 (interactive "sID: ")
11874 (let ((id (cond
11875 ((stringp ident) ident)
11876 ((symbol-name ident) (symbol-name ident))
11877 ((numberp ident) (number-to-string ident))
11878 (t (error "IDENT %s must be a string, symbol or number" ident))))
11879 (case-fold-search nil))
11880 (save-excursion
11881 (save-restriction
11882 (widen)
11883 (goto-char (point-min))
11884 (when (re-search-forward
11885 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
11886 nil t)
11887 (org-back-to-heading)
11888 (point))))))
11890 ;;;; Timestamps
11892 (defvar org-last-changed-timestamp nil)
11893 (defvar org-last-inserted-timestamp nil
11894 "The last time stamp inserted with `org-insert-time-stamp'.")
11895 (defvar org-time-was-given) ; dynamically scoped parameter
11896 (defvar org-end-time-was-given) ; dynamically scoped parameter
11897 (defvar org-ts-what) ; dynamically scoped parameter
11899 (defun org-time-stamp (arg &optional inactive)
11900 "Prompt for a date/time and insert a time stamp.
11901 If the user specifies a time like HH:MM, or if this command is called
11902 with a prefix argument, the time stamp will contain date and time.
11903 Otherwise, only the date will be included. All parts of a date not
11904 specified by the user will be filled in from the current date/time.
11905 So if you press just return without typing anything, the time stamp
11906 will represent the current date/time. If there is already a timestamp
11907 at the cursor, it will be modified."
11908 (interactive "P")
11909 (let* ((ts nil)
11910 (default-time
11911 ;; Default time is either today, or, when entering a range,
11912 ;; the range start.
11913 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
11914 (save-excursion
11915 (re-search-backward
11916 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
11917 (- (point) 20) t)))
11918 (apply 'encode-time (org-parse-time-string (match-string 1)))
11919 (current-time)))
11920 (default-input (and ts (org-get-compact-tod ts)))
11921 org-time-was-given org-end-time-was-given time)
11922 (cond
11923 ((and (org-at-timestamp-p t)
11924 (memq last-command '(org-time-stamp org-time-stamp-inactive))
11925 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
11926 (insert "--")
11927 (setq time (let ((this-command this-command))
11928 (org-read-date arg 'totime nil nil
11929 default-time default-input)))
11930 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
11931 ((org-at-timestamp-p t)
11932 (setq time (let ((this-command this-command))
11933 (org-read-date arg 'totime nil nil default-time default-input)))
11934 (when (org-at-timestamp-p t) ; just to get the match data
11935 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
11936 (replace-match "")
11937 (setq org-last-changed-timestamp
11938 (org-insert-time-stamp
11939 time (or org-time-was-given arg)
11940 inactive nil nil (list org-end-time-was-given))))
11941 (message "Timestamp updated"))
11943 (setq time (let ((this-command this-command))
11944 (org-read-date arg 'totime nil nil default-time default-input)))
11945 (org-insert-time-stamp time (or org-time-was-given arg) inactive
11946 nil nil (list org-end-time-was-given))))))
11948 ;; FIXME: can we use this for something else, like computing time differences?
11949 (defun org-get-compact-tod (s)
11950 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
11951 (let* ((t1 (match-string 1 s))
11952 (h1 (string-to-number (match-string 2 s)))
11953 (m1 (string-to-number (match-string 3 s)))
11954 (t2 (and (match-end 4) (match-string 5 s)))
11955 (h2 (and t2 (string-to-number (match-string 6 s))))
11956 (m2 (and t2 (string-to-number (match-string 7 s))))
11957 dh dm)
11958 (if (not t2)
11960 (setq dh (- h2 h1) dm (- m2 m1))
11961 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
11962 (concat t1 "+" (number-to-string dh)
11963 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
11965 (defun org-time-stamp-inactive (&optional arg)
11966 "Insert an inactive time stamp.
11967 An inactive time stamp is enclosed in square brackets instead of angle
11968 brackets. It is inactive in the sense that it does not trigger agenda entries,
11969 does not link to the calendar and cannot be changed with the S-cursor keys.
11970 So these are more for recording a certain time/date."
11971 (interactive "P")
11972 (org-time-stamp arg 'inactive))
11974 (defvar org-date-ovl (org-make-overlay 1 1))
11975 (org-overlay-put org-date-ovl 'face 'org-warning)
11976 (org-detach-overlay org-date-ovl)
11978 (defvar org-ans1) ; dynamically scoped parameter
11979 (defvar org-ans2) ; dynamically scoped parameter
11981 (defvar org-plain-time-of-day-regexp) ; defined below
11983 (defvar org-overriding-default-time nil) ; dynamically scoped
11984 (defvar org-read-date-overlay nil)
11985 (defvar org-dcst nil) ; dynamically scoped
11986 (defvar org-read-date-history nil)
11988 (defun org-read-date (&optional with-time to-time from-string prompt
11989 default-time default-input)
11990 "Read a date, possibly a time, and make things smooth for the user.
11991 The prompt will suggest to enter an ISO date, but you can also enter anything
11992 which will at least partially be understood by `parse-time-string'.
11993 Unrecognized parts of the date will default to the current day, month, year,
11994 hour and minute. If this command is called to replace a timestamp at point,
11995 of to enter the second timestamp of a range, the default time is taken from the
11996 existing stamp. For example,
11997 3-2-5 --> 2003-02-05
11998 feb 15 --> currentyear-02-15
11999 sep 12 9 --> 2009-09-12
12000 12:45 --> today 12:45
12001 22 sept 0:34 --> currentyear-09-22 0:34
12002 12 --> currentyear-currentmonth-12
12003 Fri --> nearest Friday (today or later)
12004 etc.
12006 Furthermore you can specify a relative date by giving, as the *first* thing
12007 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
12008 change in days weeks, months, years.
12009 With a single plus or minus, the date is relative to today. With a double
12010 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
12011 +4d --> four days from today
12012 +4 --> same as above
12013 +2w --> two weeks from today
12014 ++5 --> five days from default date
12016 The function understands only English month and weekday abbreviations,
12017 but this can be configured with the variables `parse-time-months' and
12018 `parse-time-weekdays'.
12020 While prompting, a calendar is popped up - you can also select the
12021 date with the mouse (button 1). The calendar shows a period of three
12022 months. To scroll it to other months, use the keys `>' and `<'.
12023 If you don't like the calendar, turn it off with
12024 \(setq org-read-date-popup-calendar nil)
12026 With optional argument TO-TIME, the date will immediately be converted
12027 to an internal time.
12028 With an optional argument WITH-TIME, the prompt will suggest to also
12029 insert a time. Note that when WITH-TIME is not set, you can still
12030 enter a time, and this function will inform the calling routine about
12031 this change. The calling routine may then choose to change the format
12032 used to insert the time stamp into the buffer to include the time.
12033 With optional argument FROM-STRING, read from this string instead from
12034 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
12035 the time/date that is used for everything that is not specified by the
12036 user."
12037 (require 'parse-time)
12038 (let* ((org-time-stamp-rounding-minutes
12039 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
12040 (org-dcst org-display-custom-times)
12041 (ct (org-current-time))
12042 (def (or org-overriding-default-time default-time ct))
12043 (defdecode (decode-time def))
12044 (dummy (progn
12045 (when (< (nth 2 defdecode) org-extend-today-until)
12046 (setcar (nthcdr 2 defdecode) -1)
12047 (setcar (nthcdr 1 defdecode) 59)
12048 (setq def (apply 'encode-time defdecode)
12049 defdecode (decode-time def)))))
12050 (calendar-move-hook nil)
12051 (calendar-view-diary-initially-flag nil)
12052 (view-diary-entries-initially nil)
12053 (calendar-view-holidays-initially-flag nil)
12054 (view-calendar-holidays-initially nil)
12055 (timestr (format-time-string
12056 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
12057 (prompt (concat (if prompt (concat prompt " ") "")
12058 (format "Date+time [%s]: " timestr)))
12059 ans (org-ans0 "") org-ans1 org-ans2 final)
12061 (cond
12062 (from-string (setq ans from-string))
12063 (org-read-date-popup-calendar
12064 (save-excursion
12065 (save-window-excursion
12066 (calendar)
12067 (calendar-forward-day (- (time-to-days def)
12068 (calendar-absolute-from-gregorian
12069 (calendar-current-date))))
12070 (org-eval-in-calendar nil t)
12071 (let* ((old-map (current-local-map))
12072 (map (copy-keymap calendar-mode-map))
12073 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12074 (org-defkey map (kbd "RET") 'org-calendar-select)
12075 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
12076 'org-calendar-select-mouse)
12077 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
12078 'org-calendar-select-mouse)
12079 (org-defkey minibuffer-local-map [(meta shift left)]
12080 (lambda () (interactive)
12081 (org-eval-in-calendar '(calendar-backward-month 1))))
12082 (org-defkey minibuffer-local-map [(meta shift right)]
12083 (lambda () (interactive)
12084 (org-eval-in-calendar '(calendar-forward-month 1))))
12085 (org-defkey minibuffer-local-map [(meta shift up)]
12086 (lambda () (interactive)
12087 (org-eval-in-calendar '(calendar-backward-year 1))))
12088 (org-defkey minibuffer-local-map [(meta shift down)]
12089 (lambda () (interactive)
12090 (org-eval-in-calendar '(calendar-forward-year 1))))
12091 (org-defkey minibuffer-local-map [?\e (shift left)]
12092 (lambda () (interactive)
12093 (org-eval-in-calendar '(calendar-backward-month 1))))
12094 (org-defkey minibuffer-local-map [?\e (shift right)]
12095 (lambda () (interactive)
12096 (org-eval-in-calendar '(calendar-forward-month 1))))
12097 (org-defkey minibuffer-local-map [?\e (shift up)]
12098 (lambda () (interactive)
12099 (org-eval-in-calendar '(calendar-backward-year 1))))
12100 (org-defkey minibuffer-local-map [?\e (shift down)]
12101 (lambda () (interactive)
12102 (org-eval-in-calendar '(calendar-forward-year 1))))
12103 (org-defkey minibuffer-local-map [(shift up)]
12104 (lambda () (interactive)
12105 (org-eval-in-calendar '(calendar-backward-week 1))))
12106 (org-defkey minibuffer-local-map [(shift down)]
12107 (lambda () (interactive)
12108 (org-eval-in-calendar '(calendar-forward-week 1))))
12109 (org-defkey minibuffer-local-map [(shift left)]
12110 (lambda () (interactive)
12111 (org-eval-in-calendar '(calendar-backward-day 1))))
12112 (org-defkey minibuffer-local-map [(shift right)]
12113 (lambda () (interactive)
12114 (org-eval-in-calendar '(calendar-forward-day 1))))
12115 (org-defkey minibuffer-local-map ">"
12116 (lambda () (interactive)
12117 (org-eval-in-calendar '(scroll-calendar-left 1))))
12118 (org-defkey minibuffer-local-map "<"
12119 (lambda () (interactive)
12120 (org-eval-in-calendar '(scroll-calendar-right 1))))
12121 (run-hooks 'org-read-date-minibuffer-setup-hook)
12122 (unwind-protect
12123 (progn
12124 (use-local-map map)
12125 (add-hook 'post-command-hook 'org-read-date-display)
12126 (setq org-ans0 (read-string prompt default-input
12127 'org-read-date-history nil))
12128 ;; org-ans0: from prompt
12129 ;; org-ans1: from mouse click
12130 ;; org-ans2: from calendar motion
12131 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
12132 (remove-hook 'post-command-hook 'org-read-date-display)
12133 (use-local-map old-map)
12134 (when org-read-date-overlay
12135 (org-delete-overlay org-read-date-overlay)
12136 (setq org-read-date-overlay nil)))))))
12138 (t ; Naked prompt only
12139 (unwind-protect
12140 (setq ans (read-string prompt default-input
12141 'org-read-date-history timestr))
12142 (when org-read-date-overlay
12143 (org-delete-overlay org-read-date-overlay)
12144 (setq org-read-date-overlay nil)))))
12146 (setq final (org-read-date-analyze ans def defdecode))
12148 (if to-time
12149 (apply 'encode-time final)
12150 (if (and (boundp 'org-time-was-given) org-time-was-given)
12151 (format "%04d-%02d-%02d %02d:%02d"
12152 (nth 5 final) (nth 4 final) (nth 3 final)
12153 (nth 2 final) (nth 1 final))
12154 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
12155 (defvar def)
12156 (defvar defdecode)
12157 (defvar with-time)
12158 (defun org-read-date-display ()
12159 "Display the current date prompt interpretation in the minibuffer."
12160 (when org-read-date-display-live
12161 (when org-read-date-overlay
12162 (org-delete-overlay org-read-date-overlay))
12163 (let ((p (point)))
12164 (end-of-line 1)
12165 (while (not (equal (buffer-substring
12166 (max (point-min) (- (point) 4)) (point))
12167 " "))
12168 (insert " "))
12169 (goto-char p))
12170 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
12171 " " (or org-ans1 org-ans2)))
12172 (org-end-time-was-given nil)
12173 (f (org-read-date-analyze ans def defdecode))
12174 (fmts (if org-dcst
12175 org-time-stamp-custom-formats
12176 org-time-stamp-formats))
12177 (fmt (if (or with-time
12178 (and (boundp 'org-time-was-given) org-time-was-given))
12179 (cdr fmts)
12180 (car fmts)))
12181 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
12182 (when (and org-end-time-was-given
12183 (string-match org-plain-time-of-day-regexp txt))
12184 (setq txt (concat (substring txt 0 (match-end 0)) "-"
12185 org-end-time-was-given
12186 (substring txt (match-end 0)))))
12187 (setq org-read-date-overlay
12188 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
12189 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
12191 (defun org-read-date-analyze (ans def defdecode)
12192 "Analyse the combined answer of the date prompt."
12193 ;; FIXME: cleanup and comment
12194 (let (delta deltan deltaw deltadef year month day
12195 hour minute second wday pm h2 m2 tl wday1
12196 iso-year iso-weekday iso-week iso-year iso-date)
12198 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
12199 (setq ans "+0"))
12201 (when (setq delta (org-read-date-get-relative ans (current-time) def))
12202 (setq ans (replace-match "" t t ans)
12203 deltan (car delta)
12204 deltaw (nth 1 delta)
12205 deltadef (nth 2 delta)))
12207 ;; Check if there is an iso week date in there
12208 ;; If yes, sore the info and postpone interpreting it until the rest
12209 ;; of the parsing is done
12210 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
12211 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
12212 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
12213 iso-week (string-to-number (match-string 2 ans)))
12214 (setq ans (replace-match "" t t ans)))
12216 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
12217 (when (string-match
12218 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
12219 (setq year (if (match-end 2)
12220 (string-to-number (match-string 2 ans))
12221 (string-to-number (format-time-string "%Y")))
12222 month (string-to-number (match-string 3 ans))
12223 day (string-to-number (match-string 4 ans)))
12224 (if (< year 100) (setq year (+ 2000 year)))
12225 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
12226 t nil ans)))
12227 ;; Help matching am/pm times, because `parse-time-string' does not do that.
12228 ;; If there is a time with am/pm, and *no* time without it, we convert
12229 ;; so that matching will be successful.
12230 (loop for i from 1 to 2 do ; twice, for end time as well
12231 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
12232 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
12233 (setq hour (string-to-number (match-string 1 ans))
12234 minute (if (match-end 3)
12235 (string-to-number (match-string 3 ans))
12237 pm (equal ?p
12238 (string-to-char (downcase (match-string 4 ans)))))
12239 (if (and (= hour 12) (not pm))
12240 (setq hour 0)
12241 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
12242 (setq ans (replace-match (format "%02d:%02d" hour minute)
12243 t t ans))))
12245 ;; Check if a time range is given as a duration
12246 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
12247 (setq hour (string-to-number (match-string 1 ans))
12248 h2 (+ hour (string-to-number (match-string 3 ans)))
12249 minute (string-to-number (match-string 2 ans))
12250 m2 (+ minute (if (match-end 5) (string-to-number
12251 (match-string 5 ans))0)))
12252 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
12253 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
12254 t t ans)))
12256 ;; Check if there is a time range
12257 (when (boundp 'org-end-time-was-given)
12258 (setq org-time-was-given nil)
12259 (when (and (string-match org-plain-time-of-day-regexp ans)
12260 (match-end 8))
12261 (setq org-end-time-was-given (match-string 8 ans))
12262 (setq ans (concat (substring ans 0 (match-beginning 7))
12263 (substring ans (match-end 7))))))
12265 (setq tl (parse-time-string ans)
12266 day (or (nth 3 tl) (nth 3 defdecode))
12267 month (or (nth 4 tl)
12268 (if (and org-read-date-prefer-future
12269 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
12270 (1+ (nth 4 defdecode))
12271 (nth 4 defdecode)))
12272 year (or (nth 5 tl)
12273 (if (and org-read-date-prefer-future
12274 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
12275 (1+ (nth 5 defdecode))
12276 (nth 5 defdecode)))
12277 hour (or (nth 2 tl) (nth 2 defdecode))
12278 minute (or (nth 1 tl) (nth 1 defdecode))
12279 second (or (nth 0 tl) 0)
12280 wday (nth 6 tl))
12282 ;; Special date definitions below
12283 (cond
12284 (iso-week
12285 ;; There was an iso week
12286 (setq year (or iso-year year)
12287 day (or iso-weekday wday 1)
12288 wday nil ; to make sure that the trigger below does not match
12289 iso-date (calendar-gregorian-from-absolute
12290 (calendar-absolute-from-iso
12291 (list iso-week day year))))
12292 ; FIXME: Should we also push ISO weeks into the future?
12293 ; (when (and org-read-date-prefer-future
12294 ; (not iso-year)
12295 ; (< (calendar-absolute-from-gregorian iso-date)
12296 ; (time-to-days (current-time))))
12297 ; (setq year (1+ year)
12298 ; iso-date (calendar-gregorian-from-absolute
12299 ; (calendar-absolute-from-iso
12300 ; (list iso-week day year)))))
12301 (setq month (car iso-date)
12302 year (nth 2 iso-date)
12303 day (nth 1 iso-date)))
12304 (deltan
12305 (unless deltadef
12306 (let ((now (decode-time (current-time))))
12307 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
12308 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
12309 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
12310 ((equal deltaw "m") (setq month (+ month deltan)))
12311 ((equal deltaw "y") (setq year (+ year deltan)))))
12312 ((and wday (not (nth 3 tl)))
12313 ;; Weekday was given, but no day, so pick that day in the week
12314 ;; on or after the derived date.
12315 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
12316 (unless (equal wday wday1)
12317 (setq day (+ day (% (- wday wday1 -7) 7))))))
12318 (if (and (boundp 'org-time-was-given)
12319 (nth 2 tl))
12320 (setq org-time-was-given t))
12321 (if (< year 100) (setq year (+ 2000 year)))
12322 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
12323 (list second minute hour day month year)))
12325 (defvar parse-time-weekdays)
12327 (defun org-read-date-get-relative (s today default)
12328 "Check string S for special relative date string.
12329 TODAY and DEFAULT are internal times, for today and for a default.
12330 Return shift list (N what def-flag)
12331 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
12332 N is the number of WHATs to shift.
12333 DEF-FLAG is t when a double ++ or -- indicates shift relative to
12334 the DEFAULT date rather than TODAY."
12335 (when (and
12336 (string-match
12337 (concat
12338 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
12339 "\\([0-9]+\\)?"
12340 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
12341 "\\([ \t]\\|$\\)") s)
12342 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
12343 (let* ((dir (if (> (match-end 1) (match-beginning 1))
12344 (string-to-char (substring (match-string 1 s) -1))
12345 ?+))
12346 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
12347 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
12348 (what (if (match-end 3) (match-string 3 s) "d"))
12349 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
12350 (date (if rel default today))
12351 (wday (nth 6 (decode-time date)))
12352 delta)
12353 (if wday1
12354 (progn
12355 (setq delta (mod (+ 7 (- wday1 wday)) 7))
12356 (if (= dir ?-) (setq delta (- delta 7)))
12357 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
12358 (list delta "d" rel))
12359 (list (* n (if (= dir ?-) -1 1)) what rel)))))
12361 (defun org-eval-in-calendar (form &optional keepdate)
12362 "Eval FORM in the calendar window and return to current window.
12363 Also, store the cursor date in variable org-ans2."
12364 (let ((sw (selected-window)))
12365 (select-window (get-buffer-window "*Calendar*"))
12366 (eval form)
12367 (when (and (not keepdate) (calendar-cursor-to-date))
12368 (let* ((date (calendar-cursor-to-date))
12369 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12370 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
12371 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
12372 (select-window sw)))
12374 (defun org-calendar-select ()
12375 "Return to `org-read-date' with the date currently selected.
12376 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12377 (interactive)
12378 (when (calendar-cursor-to-date)
12379 (let* ((date (calendar-cursor-to-date))
12380 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12381 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12382 (if (active-minibuffer-window) (exit-minibuffer))))
12384 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
12385 "Insert a date stamp for the date given by the internal TIME.
12386 WITH-HM means, use the stamp format that includes the time of the day.
12387 INACTIVE means use square brackets instead of angular ones, so that the
12388 stamp will not contribute to the agenda.
12389 PRE and POST are optional strings to be inserted before and after the
12390 stamp.
12391 The command returns the inserted time stamp."
12392 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
12393 stamp)
12394 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
12395 (insert-before-markers (or pre ""))
12396 (insert-before-markers (setq stamp (format-time-string fmt time)))
12397 (when (listp extra)
12398 (setq extra (car extra))
12399 (if (and (stringp extra)
12400 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
12401 (setq extra (format "-%02d:%02d"
12402 (string-to-number (match-string 1 extra))
12403 (string-to-number (match-string 2 extra))))
12404 (setq extra nil)))
12405 (when extra
12406 (backward-char 1)
12407 (insert-before-markers extra)
12408 (forward-char 1))
12409 (insert-before-markers (or post ""))
12410 (setq org-last-inserted-timestamp stamp)))
12412 (defun org-toggle-time-stamp-overlays ()
12413 "Toggle the use of custom time stamp formats."
12414 (interactive)
12415 (setq org-display-custom-times (not org-display-custom-times))
12416 (unless org-display-custom-times
12417 (let ((p (point-min)) (bmp (buffer-modified-p)))
12418 (while (setq p (next-single-property-change p 'display))
12419 (if (and (get-text-property p 'display)
12420 (eq (get-text-property p 'face) 'org-date))
12421 (remove-text-properties
12422 p (setq p (next-single-property-change p 'display))
12423 '(display t))))
12424 (set-buffer-modified-p bmp)))
12425 (if (featurep 'xemacs)
12426 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12427 (org-restart-font-lock)
12428 (setq org-table-may-need-update t)
12429 (if org-display-custom-times
12430 (message "Time stamps are overlayed with custom format")
12431 (message "Time stamp overlays removed")))
12433 (defun org-display-custom-time (beg end)
12434 "Overlay modified time stamp format over timestamp between BEG and END."
12435 (let* ((ts (buffer-substring beg end))
12436 t1 w1 with-hm tf time str w2 (off 0))
12437 (save-match-data
12438 (setq t1 (org-parse-time-string ts t))
12439 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
12440 (setq off (- (match-end 0) (match-beginning 0)))))
12441 (setq end (- end off))
12442 (setq w1 (- end beg)
12443 with-hm (and (nth 1 t1) (nth 2 t1))
12444 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
12445 time (org-fix-decoded-time t1)
12446 str (org-add-props
12447 (format-time-string
12448 (substring tf 1 -1) (apply 'encode-time time))
12449 nil 'mouse-face 'highlight)
12450 w2 (length str))
12451 (if (not (= w2 w1))
12452 (add-text-properties (1+ beg) (+ 2 beg)
12453 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12454 (if (featurep 'xemacs)
12455 (progn
12456 (put-text-property beg end 'invisible t)
12457 (put-text-property beg end 'end-glyph (make-glyph str)))
12458 (put-text-property beg end 'display str))))
12460 (defun org-translate-time (string)
12461 "Translate all timestamps in STRING to custom format.
12462 But do this only if the variable `org-display-custom-times' is set."
12463 (when org-display-custom-times
12464 (save-match-data
12465 (let* ((start 0)
12466 (re org-ts-regexp-both)
12467 t1 with-hm inactive tf time str beg end)
12468 (while (setq start (string-match re string start))
12469 (setq beg (match-beginning 0)
12470 end (match-end 0)
12471 t1 (save-match-data
12472 (org-parse-time-string (substring string beg end) t))
12473 with-hm (and (nth 1 t1) (nth 2 t1))
12474 inactive (equal (substring string beg (1+ beg)) "[")
12475 tf (funcall (if with-hm 'cdr 'car)
12476 org-time-stamp-custom-formats)
12477 time (org-fix-decoded-time t1)
12478 str (format-time-string
12479 (concat
12480 (if inactive "[" "<") (substring tf 1 -1)
12481 (if inactive "]" ">"))
12482 (apply 'encode-time time))
12483 string (replace-match str t t string)
12484 start (+ start (length str)))))))
12485 string)
12487 (defun org-fix-decoded-time (time)
12488 "Set 0 instead of nil for the first 6 elements of time.
12489 Don't touch the rest."
12490 (let ((n 0))
12491 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12493 (defun org-days-to-time (timestamp-string)
12494 "Difference between TIMESTAMP-STRING and now in days."
12495 (- (time-to-days (org-time-string-to-time timestamp-string))
12496 (time-to-days (current-time))))
12498 (defun org-deadline-close (timestamp-string &optional ndays)
12499 "Is the time in TIMESTAMP-STRING close to the current date?"
12500 (setq ndays (or ndays (org-get-wdays timestamp-string)))
12501 (and (< (org-days-to-time timestamp-string) ndays)
12502 (not (org-entry-is-done-p))))
12504 (defun org-get-wdays (ts)
12505 "Get the deadline lead time appropriate for timestring TS."
12506 (cond
12507 ((<= org-deadline-warning-days 0)
12508 ;; 0 or negative, enforce this value no matter what
12509 (- org-deadline-warning-days))
12510 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
12511 ;; lead time is specified.
12512 (floor (* (string-to-number (match-string 1 ts))
12513 (cdr (assoc (match-string 2 ts)
12514 '(("d" . 1) ("w" . 7)
12515 ("m" . 30.4) ("y" . 365.25)))))))
12516 ;; go for the default.
12517 (t org-deadline-warning-days)))
12519 (defun org-calendar-select-mouse (ev)
12520 "Return to `org-read-date' with the date currently selected.
12521 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12522 (interactive "e")
12523 (mouse-set-point ev)
12524 (when (calendar-cursor-to-date)
12525 (let* ((date (calendar-cursor-to-date))
12526 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12527 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12528 (if (active-minibuffer-window) (exit-minibuffer))))
12530 (defun org-check-deadlines (ndays)
12531 "Check if there are any deadlines due or past due.
12532 A deadline is considered due if it happens within `org-deadline-warning-days'
12533 days from today's date. If the deadline appears in an entry marked DONE,
12534 it is not shown. The prefix arg NDAYS can be used to test that many
12535 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12536 (interactive "P")
12537 (let* ((org-warn-days
12538 (cond
12539 ((equal ndays '(4)) 100000)
12540 (ndays (prefix-numeric-value ndays))
12541 (t (abs org-deadline-warning-days))))
12542 (case-fold-search nil)
12543 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12544 (callback
12545 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12547 (message "%d deadlines past-due or due within %d days"
12548 (org-occur regexp nil callback)
12549 org-warn-days)))
12551 (defun org-check-before-date (date)
12552 "Check if there are deadlines or scheduled entries before DATE."
12553 (interactive (list (org-read-date)))
12554 (let ((case-fold-search nil)
12555 (regexp (concat "\\<\\(" org-deadline-string
12556 "\\|" org-scheduled-string
12557 "\\) *<\\([^>]+\\)>"))
12558 (callback
12559 (lambda () (time-less-p
12560 (org-time-string-to-time (match-string 2))
12561 (org-time-string-to-time date)))))
12562 (message "%d entries before %s"
12563 (org-occur regexp nil callback) date)))
12565 (defun org-check-after-date (date)
12566 "Check if there are deadlines or scheduled entries after DATE."
12567 (interactive (list (org-read-date)))
12568 (let ((case-fold-search nil)
12569 (regexp (concat "\\<\\(" org-deadline-string
12570 "\\|" org-scheduled-string
12571 "\\) *<\\([^>]+\\)>"))
12572 (callback
12573 (lambda () (not
12574 (time-less-p
12575 (org-time-string-to-time (match-string 2))
12576 (org-time-string-to-time date))))))
12577 (message "%d entries after %s"
12578 (org-occur regexp nil callback) date)))
12580 (defun org-evaluate-time-range (&optional to-buffer)
12581 "Evaluate a time range by computing the difference between start and end.
12582 Normally the result is just printed in the echo area, but with prefix arg
12583 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12584 If the time range is actually in a table, the result is inserted into the
12585 next column.
12586 For time difference computation, a year is assumed to be exactly 365
12587 days in order to avoid rounding problems."
12588 (interactive "P")
12590 (org-clock-update-time-maybe)
12591 (save-excursion
12592 (unless (org-at-date-range-p t)
12593 (goto-char (point-at-bol))
12594 (re-search-forward org-tr-regexp-both (point-at-eol) t))
12595 (if (not (org-at-date-range-p t))
12596 (error "Not at a time-stamp range, and none found in current line")))
12597 (let* ((ts1 (match-string 1))
12598 (ts2 (match-string 2))
12599 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12600 (match-end (match-end 0))
12601 (time1 (org-time-string-to-time ts1))
12602 (time2 (org-time-string-to-time ts2))
12603 (t1 (time-to-seconds time1))
12604 (t2 (time-to-seconds time2))
12605 (diff (abs (- t2 t1)))
12606 (negative (< (- t2 t1) 0))
12607 ;; (ys (floor (* 365 24 60 60)))
12608 (ds (* 24 60 60))
12609 (hs (* 60 60))
12610 (fy "%dy %dd %02d:%02d")
12611 (fy1 "%dy %dd")
12612 (fd "%dd %02d:%02d")
12613 (fd1 "%dd")
12614 (fh "%02d:%02d")
12615 y d h m align)
12616 (if havetime
12617 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12619 d (floor (/ diff ds)) diff (mod diff ds)
12620 h (floor (/ diff hs)) diff (mod diff hs)
12621 m (floor (/ diff 60)))
12622 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12624 d (floor (+ (/ diff ds) 0.5))
12625 h 0 m 0))
12626 (if (not to-buffer)
12627 (message "%s" (org-make-tdiff-string y d h m))
12628 (if (org-at-table-p)
12629 (progn
12630 (goto-char match-end)
12631 (setq align t)
12632 (and (looking-at " *|") (goto-char (match-end 0))))
12633 (goto-char match-end))
12634 (if (looking-at
12635 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12636 (replace-match ""))
12637 (if negative (insert " -"))
12638 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12639 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12640 (insert " " (format fh h m))))
12641 (if align (org-table-align))
12642 (message "Time difference inserted")))))
12644 (defun org-make-tdiff-string (y d h m)
12645 (let ((fmt "")
12646 (l nil))
12647 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12648 l (push y l)))
12649 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12650 l (push d l)))
12651 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12652 l (push h l)))
12653 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12654 l (push m l)))
12655 (apply 'format fmt (nreverse l))))
12657 (defun org-time-string-to-time (s)
12658 (apply 'encode-time (org-parse-time-string s)))
12659 (defun org-time-string-to-seconds (s)
12660 (time-to-seconds (org-time-string-to-time s)))
12662 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
12663 "Convert a time stamp to an absolute day number.
12664 If there is a specifyer for a cyclic time stamp, get the closest date to
12665 DAYNR.
12666 PREFER and SHOW-ALL are passed through to `org-closest-date'.
12667 the variable date is bound by the calendar when this is called."
12668 (cond
12669 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
12670 (if (org-diary-sexp-entry (match-string 1 s) "" date)
12671 daynr
12672 (+ daynr 1000)))
12673 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
12674 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
12675 (time-to-days (current-time))) (match-string 0 s)
12676 prefer show-all))
12677 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
12679 (defun org-days-to-iso-week (days)
12680 "Return the iso week number."
12681 (require 'cal-iso)
12682 (car (calendar-iso-from-absolute days)))
12684 (defun org-small-year-to-year (year)
12685 "Convert 2-digit years into 4-digit years.
12686 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
12687 The year 2000 cannot be abbreviated. Any year larger than 99
12688 is returned unchanged."
12689 (if (< year 38)
12690 (setq year (+ 2000 year))
12691 (if (< year 100)
12692 (setq year (+ 1900 year))))
12693 year)
12695 (defun org-time-from-absolute (d)
12696 "Return the time corresponding to date D.
12697 D may be an absolute day number, or a calendar-type list (month day year)."
12698 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
12699 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
12701 (defun org-calendar-holiday ()
12702 "List of holidays, for Diary display in Org-mode."
12703 (require 'holidays)
12704 (let ((hl (funcall
12705 (if (fboundp 'calendar-check-holidays)
12706 'calendar-check-holidays 'check-calendar-holidays) date)))
12707 (if hl (mapconcat 'identity hl "; "))))
12709 (defun org-diary-sexp-entry (sexp entry date)
12710 "Process a SEXP diary ENTRY for DATE."
12711 (require 'diary-lib)
12712 (let ((result (if calendar-debug-sexp
12713 (let ((stack-trace-on-error t))
12714 (eval (car (read-from-string sexp))))
12715 (condition-case nil
12716 (eval (car (read-from-string sexp)))
12717 (error
12718 (beep)
12719 (message "Bad sexp at line %d in %s: %s"
12720 (org-current-line)
12721 (buffer-file-name) sexp)
12722 (sleep-for 2))))))
12723 (cond ((stringp result) result)
12724 ((and (consp result)
12725 (stringp (cdr result))) (cdr result))
12726 (result entry)
12727 (t nil))))
12729 (defun org-diary-to-ical-string (frombuf)
12730 "Get iCalendar entries from diary entries in buffer FROMBUF.
12731 This uses the icalendar.el library."
12732 (let* ((tmpdir (if (featurep 'xemacs)
12733 (temp-directory)
12734 temporary-file-directory))
12735 (tmpfile (make-temp-name
12736 (expand-file-name "orgics" tmpdir)))
12737 buf rtn b e)
12738 (save-excursion
12739 (set-buffer frombuf)
12740 (icalendar-export-region (point-min) (point-max) tmpfile)
12741 (setq buf (find-buffer-visiting tmpfile))
12742 (set-buffer buf)
12743 (goto-char (point-min))
12744 (if (re-search-forward "^BEGIN:VEVENT" nil t)
12745 (setq b (match-beginning 0)))
12746 (goto-char (point-max))
12747 (if (re-search-backward "^END:VEVENT" nil t)
12748 (setq e (match-end 0)))
12749 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
12750 (kill-buffer buf)
12751 (delete-file tmpfile)
12752 rtn))
12754 (defun org-closest-date (start current change prefer show-all)
12755 "Find the date closest to CURRENT that is consistent with START and CHANGE.
12756 When PREFER is `past' return a date that is either CURRENT or past.
12757 When PREFER is `future', return a date that is either CURRENT or future.
12758 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
12759 ;; Make the proper lists from the dates
12760 (catch 'exit
12761 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
12762 dn dw sday cday n1 n2 n0
12763 d m y y1 y2 date1 date2 nmonths nm ny m2)
12765 (setq start (org-date-to-gregorian start)
12766 current (org-date-to-gregorian
12767 (if show-all
12768 current
12769 (time-to-days (current-time))))
12770 sday (calendar-absolute-from-gregorian start)
12771 cday (calendar-absolute-from-gregorian current))
12773 (if (<= cday sday) (throw 'exit sday))
12775 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
12776 (setq dn (string-to-number (match-string 1 change))
12777 dw (cdr (assoc (match-string 2 change) a1)))
12778 (error "Invalid change specifyer: %s" change))
12779 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
12780 (cond
12781 ((eq dw 'day)
12782 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
12783 n2 (+ n1 dn)))
12784 ((eq dw 'year)
12785 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
12786 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
12787 (setq date1 (list m d y1)
12788 n1 (calendar-absolute-from-gregorian date1)
12789 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
12790 n2 (calendar-absolute-from-gregorian date2)))
12791 ((eq dw 'month)
12792 ;; approx number of month between the two dates
12793 (setq nmonths (floor (/ (- cday sday) 30.436875)))
12794 ;; How often does dn fit in there?
12795 (setq d (nth 1 start) m (car start) y (nth 2 start)
12796 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
12797 m (+ m nm)
12798 ny (floor (/ m 12))
12799 y (+ y ny)
12800 m (- m (* ny 12)))
12801 (while (> m 12) (setq m (- m 12) y (1+ y)))
12802 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
12803 (setq m2 (+ m dn) y2 y)
12804 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12805 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
12806 (while (<= n2 cday)
12807 (setq n1 n2 m m2 y y2)
12808 (setq m2 (+ m dn) y2 y)
12809 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12810 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
12811 ;; Make sure n1 is the earlier date
12812 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
12813 (if show-all
12814 (cond
12815 ((eq prefer 'past) n1)
12816 ((eq prefer 'future) (if (= cday n1) n1 n2))
12817 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
12818 (cond
12819 ((eq prefer 'past) n1)
12820 ((eq prefer 'future) (if (= cday n1) n1 n2))
12821 (t (if (= cday n1) n1 n2)))))))
12823 (defun org-date-to-gregorian (date)
12824 "Turn any specification of DATE into a gregorian date for the calendar."
12825 (cond ((integerp date) (calendar-gregorian-from-absolute date))
12826 ((and (listp date) (= (length date) 3)) date)
12827 ((stringp date)
12828 (setq date (org-parse-time-string date))
12829 (list (nth 4 date) (nth 3 date) (nth 5 date)))
12830 ((listp date)
12831 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
12833 (defun org-parse-time-string (s &optional nodefault)
12834 "Parse the standard Org-mode time string.
12835 This should be a lot faster than the normal `parse-time-string'.
12836 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12837 hour and minute fields will be nil if not given."
12838 (if (string-match org-ts-regexp0 s)
12839 (list 0
12840 (if (or (match-beginning 8) (not nodefault))
12841 (string-to-number (or (match-string 8 s) "0")))
12842 (if (or (match-beginning 7) (not nodefault))
12843 (string-to-number (or (match-string 7 s) "0")))
12844 (string-to-number (match-string 4 s))
12845 (string-to-number (match-string 3 s))
12846 (string-to-number (match-string 2 s))
12847 nil nil nil)
12848 (make-list 9 0)))
12850 (defun org-timestamp-up (&optional arg)
12851 "Increase the date item at the cursor by one.
12852 If the cursor is on the year, change the year. If it is on the month or
12853 the day, change that.
12854 With prefix ARG, change by that many units."
12855 (interactive "p")
12856 (org-timestamp-change (prefix-numeric-value arg)))
12858 (defun org-timestamp-down (&optional arg)
12859 "Decrease the date item at the cursor by one.
12860 If the cursor is on the year, change the year. If it is on the month or
12861 the day, change that.
12862 With prefix ARG, change by that many units."
12863 (interactive "p")
12864 (org-timestamp-change (- (prefix-numeric-value arg))))
12866 (defun org-timestamp-up-day (&optional arg)
12867 "Increase the date in the time stamp by one day.
12868 With prefix ARG, change that many days."
12869 (interactive "p")
12870 (if (and (not (org-at-timestamp-p t))
12871 (org-on-heading-p))
12872 (org-todo 'up)
12873 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12875 (defun org-timestamp-down-day (&optional arg)
12876 "Decrease the date in the time stamp by one day.
12877 With prefix ARG, change that many days."
12878 (interactive "p")
12879 (if (and (not (org-at-timestamp-p t))
12880 (org-on-heading-p))
12881 (org-todo 'down)
12882 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12884 (defun org-at-timestamp-p (&optional inactive-ok)
12885 "Determine if the cursor is in or at a timestamp."
12886 (interactive)
12887 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12888 (pos (point))
12889 (ans (or (looking-at tsr)
12890 (save-excursion
12891 (skip-chars-backward "^[<\n\r\t")
12892 (if (> (point) (point-min)) (backward-char 1))
12893 (and (looking-at tsr)
12894 (> (- (match-end 0) pos) -1))))))
12895 (and ans
12896 (boundp 'org-ts-what)
12897 (setq org-ts-what
12898 (cond
12899 ((= pos (match-beginning 0)) 'bracket)
12900 ((= pos (1- (match-end 0))) 'bracket)
12901 ((org-pos-in-match-range pos 2) 'year)
12902 ((org-pos-in-match-range pos 3) 'month)
12903 ((org-pos-in-match-range pos 7) 'hour)
12904 ((org-pos-in-match-range pos 8) 'minute)
12905 ((or (org-pos-in-match-range pos 4)
12906 (org-pos-in-match-range pos 5)) 'day)
12907 ((and (> pos (or (match-end 8) (match-end 5)))
12908 (< pos (match-end 0)))
12909 (- pos (or (match-end 8) (match-end 5))))
12910 (t 'day))))
12911 ans))
12913 (defun org-toggle-timestamp-type ()
12914 "Toggle the type (<active> or [inactive]) of a time stamp."
12915 (interactive)
12916 (when (org-at-timestamp-p t)
12917 (let ((beg (match-beginning 0)) (end (match-end 0))
12918 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
12919 (save-excursion
12920 (goto-char beg)
12921 (while (re-search-forward "[][<>]" end t)
12922 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
12923 t t)))
12924 (message "Timestamp is now %sactive"
12925 (if (equal (char-after beg) ?<) "" "in")))))
12927 (defun org-timestamp-change (n &optional what)
12928 "Change the date in the time stamp at point.
12929 The date will be changed by N times WHAT. WHAT can be `day', `month',
12930 `year', `minute', `second'. If WHAT is not given, the cursor position
12931 in the timestamp determines what will be changed."
12932 (let ((pos (point))
12933 with-hm inactive
12934 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
12935 org-ts-what
12936 extra rem
12937 ts time time0)
12938 (if (not (org-at-timestamp-p t))
12939 (error "Not at a timestamp"))
12940 (if (and (not what) (eq org-ts-what 'bracket))
12941 (org-toggle-timestamp-type)
12942 (if (and (not what) (not (eq org-ts-what 'day))
12943 org-display-custom-times
12944 (get-text-property (point) 'display)
12945 (not (get-text-property (1- (point)) 'display)))
12946 (setq org-ts-what 'day))
12947 (setq org-ts-what (or what org-ts-what)
12948 inactive (= (char-after (match-beginning 0)) ?\[)
12949 ts (match-string 0))
12950 (replace-match "")
12951 (if (string-match
12952 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
12954 (setq extra (match-string 1 ts)))
12955 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
12956 (setq with-hm t))
12957 (setq time0 (org-parse-time-string ts))
12958 (when (and (eq org-ts-what 'minute)
12959 (eq current-prefix-arg nil))
12960 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
12961 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
12962 (setcar (cdr time0) (+ (nth 1 time0)
12963 (if (> n 0) (- rem) (- dm rem))))))
12964 (setq time
12965 (encode-time (or (car time0) 0)
12966 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
12967 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
12968 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
12969 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
12970 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
12971 (nthcdr 6 time0)))
12972 (when (and (member org-ts-what '(hour minute))
12973 extra
12974 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
12975 (setq extra (org-modify-ts-extra
12976 extra
12977 (if (eq org-ts-what 'hour) 2 5)
12978 n dm)))
12979 (when (integerp org-ts-what)
12980 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
12981 (if (eq what 'calendar)
12982 (let ((cal-date (org-get-date-from-calendar)))
12983 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12984 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12985 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12986 (setcar time0 (or (car time0) 0))
12987 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12988 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
12989 (setq time (apply 'encode-time time0))))
12990 (setq org-last-changed-timestamp
12991 (org-insert-time-stamp time with-hm inactive nil nil extra))
12992 (org-clock-update-time-maybe)
12993 (goto-char pos)
12994 ;; Try to recenter the calendar window, if any
12995 (if (and org-calendar-follow-timestamp-change
12996 (get-buffer-window "*Calendar*" t)
12997 (memq org-ts-what '(day month year)))
12998 (org-recenter-calendar (time-to-days time))))))
13000 (defun org-modify-ts-extra (s pos n dm)
13001 "Change the different parts of the lead-time and repeat fields in timestamp."
13002 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
13003 ng h m new rem)
13004 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
13005 (cond
13006 ((or (org-pos-in-match-range pos 2)
13007 (org-pos-in-match-range pos 3))
13008 (setq m (string-to-number (match-string 3 s))
13009 h (string-to-number (match-string 2 s)))
13010 (if (org-pos-in-match-range pos 2)
13011 (setq h (+ h n))
13012 (setq n (* dm (org-no-warnings (signum n))))
13013 (when (not (= 0 (setq rem (% m dm))))
13014 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
13015 (setq m (+ m n)))
13016 (if (< m 0) (setq m (+ m 60) h (1- h)))
13017 (if (> m 59) (setq m (- m 60) h (1+ h)))
13018 (setq h (min 24 (max 0 h)))
13019 (setq ng 1 new (format "-%02d:%02d" h m)))
13020 ((org-pos-in-match-range pos 6)
13021 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
13022 ((org-pos-in-match-range pos 5)
13023 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
13025 ((org-pos-in-match-range pos 9)
13026 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
13027 ((org-pos-in-match-range pos 8)
13028 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
13030 (when ng
13031 (setq s (concat
13032 (substring s 0 (match-beginning ng))
13034 (substring s (match-end ng))))))
13037 (defun org-recenter-calendar (date)
13038 "If the calendar is visible, recenter it to DATE."
13039 (let* ((win (selected-window))
13040 (cwin (get-buffer-window "*Calendar*" t))
13041 (calendar-move-hook nil))
13042 (when cwin
13043 (select-window cwin)
13044 (calendar-goto-date (if (listp date) date
13045 (calendar-gregorian-from-absolute date)))
13046 (select-window win))))
13048 (defun org-goto-calendar (&optional arg)
13049 "Go to the Emacs calendar at the current date.
13050 If there is a time stamp in the current line, go to that date.
13051 A prefix ARG can be used to force the current date."
13052 (interactive "P")
13053 (let ((tsr org-ts-regexp) diff
13054 (calendar-move-hook nil)
13055 (calendar-view-holidays-initially-flag nil)
13056 (view-calendar-holidays-initially nil)
13057 (calendar-view-diary-initially-flag nil)
13058 (view-diary-entries-initially nil))
13059 (if (or (org-at-timestamp-p)
13060 (save-excursion
13061 (beginning-of-line 1)
13062 (looking-at (concat ".*" tsr))))
13063 (let ((d1 (time-to-days (current-time)))
13064 (d2 (time-to-days
13065 (org-time-string-to-time (match-string 1)))))
13066 (setq diff (- d2 d1))))
13067 (calendar)
13068 (calendar-goto-today)
13069 (if (and diff (not arg)) (calendar-forward-day diff))))
13071 (defun org-get-date-from-calendar ()
13072 "Return a list (month day year) of date at point in calendar."
13073 (with-current-buffer "*Calendar*"
13074 (save-match-data
13075 (calendar-cursor-to-date))))
13077 (defun org-date-from-calendar ()
13078 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
13079 If there is already a time stamp at the cursor position, update it."
13080 (interactive)
13081 (if (org-at-timestamp-p t)
13082 (org-timestamp-change 0 'calendar)
13083 (let ((cal-date (org-get-date-from-calendar)))
13084 (org-insert-time-stamp
13085 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
13087 (defun org-minutes-to-hh:mm-string (m)
13088 "Compute H:MM from a number of minutes."
13089 (let ((h (/ m 60)))
13090 (setq m (- m (* 60 h)))
13091 (format org-time-clocksum-format h m)))
13093 (defun org-hh:mm-string-to-minutes (s)
13094 "Convert a string H:MM to a number of minutes."
13095 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
13096 (+ (* (string-to-number (match-string 1 s)) 60)
13097 (string-to-number (match-string 2 s)))
13100 ;;;; Files
13102 (defun org-save-all-org-buffers ()
13103 "Save all Org-mode buffers without user confirmation."
13104 (interactive)
13105 (message "Saving all Org-mode buffers...")
13106 (save-some-buffers t 'org-mode-p)
13107 (when (featurep 'org-id) (org-id-locations-save))
13108 (message "Saving all Org-mode buffers... done"))
13110 (defun org-revert-all-org-buffers ()
13111 "Revert all Org-mode buffers.
13112 Prompt for confirmation when there are unsaved changes.
13113 Be sure you know what you are doing before letting this function
13114 overwrite your changes.
13116 This function is useful in a setup where one tracks org files
13117 with a version control system, to revert on one machine after pulling
13118 changes from another. I believe the procedure must be like this:
13120 1. M-x org-save-all-org-buffers
13121 2. Pull changes from the other machine, resolve conflicts
13122 3. M-x org-revert-all-org-buffers"
13123 (interactive)
13124 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
13125 (error "Abort"))
13126 (save-excursion
13127 (save-window-excursion
13128 (mapc
13129 (lambda (b)
13130 (when (and (with-current-buffer b (org-mode-p))
13131 (with-current-buffer b buffer-file-name))
13132 (switch-to-buffer b)
13133 (revert-buffer t 'no-confirm)))
13134 (buffer-list))
13135 (when (and (featurep 'org-id) org-id-track-globally)
13136 (org-id-locations-load)))))
13138 ;;;; Agenda files
13140 ;;;###autoload
13141 (defun org-iswitchb (&optional arg)
13142 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
13143 With a prefix argument, restrict available to files.
13144 With two prefix arguments, restrict available buffers to agenda files.
13146 Due to some yet unresolved reason, the global function
13147 `iswitchb-mode' needs to be active for this function to work."
13148 (interactive "P")
13149 (require 'iswitchb)
13150 (let ((enabled iswitchb-mode) blist)
13151 (or enabled (iswitchb-mode 1))
13152 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13153 ((equal arg '(16)) (org-buffer-list 'agenda))
13154 (t (org-buffer-list))))
13155 (unwind-protect
13156 (let ((iswitchb-make-buflist-hook
13157 (lambda ()
13158 (setq iswitchb-temp-buflist
13159 (mapcar 'buffer-name blist)))))
13160 (switch-to-buffer
13161 (iswitchb-read-buffer
13162 "Switch-to: " nil t))
13163 (or enabled (iswitchb-mode -1))))))
13165 ;;;###autoload
13166 (defun org-ido-switchb (&optional arg)
13167 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
13168 With a prefix argument, restrict available to files.
13169 With two prefix arguments, restrict available buffers to agenda files."
13170 (interactive "P")
13171 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13172 ((equal arg '(16)) (org-buffer-list 'agenda))
13173 (t (org-buffer-list)))))
13174 (switch-to-buffer
13175 (org-ido-completing-read "Org buffer: "
13176 (mapcar 'list (mapcar 'buffer-name blist))
13177 nil t))))
13179 (defun org-buffer-list (&optional predicate exclude-tmp)
13180 "Return a list of Org buffers.
13181 PREDICATE can be `export', `files' or `agenda'.
13183 export restrict the list to Export buffers.
13184 files restrict the list to buffers visiting Org files.
13185 agenda restrict the list to buffers visiting agenda files.
13187 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
13188 (let* ((bfn nil)
13189 (agenda-files (and (eq predicate 'agenda)
13190 (mapcar 'file-truename (org-agenda-files t))))
13191 (filter
13192 (cond
13193 ((eq predicate 'files)
13194 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
13195 ((eq predicate 'export)
13196 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
13197 ((eq predicate 'agenda)
13198 (lambda (b)
13199 (with-current-buffer b
13200 (and (eq major-mode 'org-mode)
13201 (setq bfn (buffer-file-name b))
13202 (member (file-truename bfn) agenda-files)))))
13203 (t (lambda (b) (with-current-buffer b
13204 (or (eq major-mode 'org-mode)
13205 (string-match "\*Org .*Export"
13206 (buffer-name b)))))))))
13207 (delq nil
13208 (mapcar
13209 (lambda(b)
13210 (if (and (funcall filter b)
13211 (or (not exclude-tmp)
13212 (not (string-match "tmp" (buffer-name b)))))
13214 nil))
13215 (buffer-list)))))
13217 (defun org-agenda-files (&optional unrestricted archives)
13218 "Get the list of agenda files.
13219 Optional UNRESTRICTED means return the full list even if a restriction
13220 is currently in place.
13221 When ARCHIVES is t, include all archive files hat are really being
13222 used by the agenda files. If ARCHIVE is `ifmode', do this only if
13223 `org-agenda-archives-mode' is t."
13224 (let ((files
13225 (cond
13226 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
13227 ((stringp org-agenda-files) (org-read-agenda-file-list))
13228 ((listp org-agenda-files) org-agenda-files)
13229 (t (error "Invalid value of `org-agenda-files'")))))
13230 (setq files (apply 'append
13231 (mapcar (lambda (f)
13232 (if (file-directory-p f)
13233 (directory-files
13234 f t org-agenda-file-regexp)
13235 (list f)))
13236 files)))
13237 (when org-agenda-skip-unavailable-files
13238 (setq files (delq nil
13239 (mapcar (function
13240 (lambda (file)
13241 (and (file-readable-p file) file)))
13242 files))))
13243 (when (or (eq archives t)
13244 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
13245 (setq files (org-add-archive-files files)))
13246 files))
13248 (defun org-edit-agenda-file-list ()
13249 "Edit the list of agenda files.
13250 Depending on setup, this either uses customize to edit the variable
13251 `org-agenda-files', or it visits the file that is holding the list. In the
13252 latter case, the buffer is set up in a way that saving it automatically kills
13253 the buffer and restores the previous window configuration."
13254 (interactive)
13255 (if (stringp org-agenda-files)
13256 (let ((cw (current-window-configuration)))
13257 (find-file org-agenda-files)
13258 (org-set-local 'org-window-configuration cw)
13259 (org-add-hook 'after-save-hook
13260 (lambda ()
13261 (set-window-configuration
13262 (prog1 org-window-configuration
13263 (kill-buffer (current-buffer))))
13264 (org-install-agenda-files-menu)
13265 (message "New agenda file list installed"))
13266 nil 'local)
13267 (message "%s" (substitute-command-keys
13268 "Edit list and finish with \\[save-buffer]")))
13269 (customize-variable 'org-agenda-files)))
13271 (defun org-store-new-agenda-file-list (list)
13272 "Set new value for the agenda file list and save it correctly."
13273 (if (stringp org-agenda-files)
13274 (let ((f org-agenda-files) b)
13275 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
13276 (with-temp-file f
13277 (insert (mapconcat 'identity list "\n") "\n")))
13278 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
13279 (setq org-agenda-files list)
13280 (customize-save-variable 'org-agenda-files org-agenda-files))))
13282 (defun org-read-agenda-file-list ()
13283 "Read the list of agenda files from a file."
13284 (when (file-directory-p org-agenda-files)
13285 (error "`org-agenda-files' cannot be a single directory"))
13286 (when (stringp org-agenda-files)
13287 (with-temp-buffer
13288 (insert-file-contents org-agenda-files)
13289 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
13292 ;;;###autoload
13293 (defun org-cycle-agenda-files ()
13294 "Cycle through the files in `org-agenda-files'.
13295 If the current buffer visits an agenda file, find the next one in the list.
13296 If the current buffer does not, find the first agenda file."
13297 (interactive)
13298 (let* ((fs (org-agenda-files t))
13299 (files (append fs (list (car fs))))
13300 (tcf (if buffer-file-name (file-truename buffer-file-name)))
13301 file)
13302 (unless files (error "No agenda files"))
13303 (catch 'exit
13304 (while (setq file (pop files))
13305 (if (equal (file-truename file) tcf)
13306 (when (car files)
13307 (find-file (car files))
13308 (throw 'exit t))))
13309 (find-file (car fs)))
13310 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
13312 (defun org-agenda-file-to-front (&optional to-end)
13313 "Move/add the current file to the top of the agenda file list.
13314 If the file is not present in the list, it is added to the front. If it is
13315 present, it is moved there. With optional argument TO-END, add/move to the
13316 end of the list."
13317 (interactive "P")
13318 (let ((org-agenda-skip-unavailable-files nil)
13319 (file-alist (mapcar (lambda (x)
13320 (cons (file-truename x) x))
13321 (org-agenda-files t)))
13322 (ctf (file-truename buffer-file-name))
13323 x had)
13324 (setq x (assoc ctf file-alist) had x)
13326 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
13327 (if to-end
13328 (setq file-alist (append (delq x file-alist) (list x)))
13329 (setq file-alist (cons x (delq x file-alist))))
13330 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
13331 (org-install-agenda-files-menu)
13332 (message "File %s to %s of agenda file list"
13333 (if had "moved" "added") (if to-end "end" "front"))))
13335 (defun org-remove-file (&optional file)
13336 "Remove current file from the list of files in variable `org-agenda-files'.
13337 These are the files which are being checked for agenda entries.
13338 Optional argument FILE means, use this file instead of the current."
13339 (interactive)
13340 (let* ((org-agenda-skip-unavailable-files nil)
13341 (file (or file buffer-file-name))
13342 (true-file (file-truename file))
13343 (afile (abbreviate-file-name file))
13344 (files (delq nil (mapcar
13345 (lambda (x)
13346 (if (equal true-file
13347 (file-truename x))
13348 nil x))
13349 (org-agenda-files t)))))
13350 (if (not (= (length files) (length (org-agenda-files t))))
13351 (progn
13352 (org-store-new-agenda-file-list files)
13353 (org-install-agenda-files-menu)
13354 (message "Removed file: %s" afile))
13355 (message "File was not in list: %s (not removed)" afile))))
13357 (defun org-file-menu-entry (file)
13358 (vector file (list 'find-file file) t))
13360 (defun org-check-agenda-file (file)
13361 "Make sure FILE exists. If not, ask user what to do."
13362 (when (not (file-exists-p file))
13363 (message "non-existent file %s. [R]emove from list or [A]bort?"
13364 (abbreviate-file-name file))
13365 (let ((r (downcase (read-char-exclusive))))
13366 (cond
13367 ((equal r ?r)
13368 (org-remove-file file)
13369 (throw 'nextfile t))
13370 (t (error "Abort"))))))
13372 (defun org-get-agenda-file-buffer (file)
13373 "Get a buffer visiting FILE. If the buffer needs to be created, add
13374 it to the list of buffers which might be released later."
13375 (let ((buf (org-find-base-buffer-visiting file)))
13376 (if buf
13377 buf ; just return it
13378 ;; Make a new buffer and remember it
13379 (setq buf (find-file-noselect file))
13380 (if buf (push buf org-agenda-new-buffers))
13381 buf)))
13383 (defun org-release-buffers (blist)
13384 "Release all buffers in list, asking the user for confirmation when needed.
13385 When a buffer is unmodified, it is just killed. When modified, it is saved
13386 \(if the user agrees) and then killed."
13387 (let (buf file)
13388 (while (setq buf (pop blist))
13389 (setq file (buffer-file-name buf))
13390 (when (and (buffer-modified-p buf)
13391 file
13392 (y-or-n-p (format "Save file %s? " file)))
13393 (with-current-buffer buf (save-buffer)))
13394 (kill-buffer buf))))
13396 (defun org-prepare-agenda-buffers (files)
13397 "Create buffers for all agenda files, protect archived trees and comments."
13398 (interactive)
13399 (let ((pa '(:org-archived t))
13400 (pc '(:org-comment t))
13401 (pall '(:org-archived t :org-comment t))
13402 (inhibit-read-only t)
13403 (rea (concat ":" org-archive-tag ":"))
13404 bmp file re)
13405 (save-excursion
13406 (save-restriction
13407 (while (setq file (pop files))
13408 (catch 'nextfile
13409 (if (bufferp file)
13410 (set-buffer file)
13411 (org-check-agenda-file file)
13412 (set-buffer (org-get-agenda-file-buffer file)))
13413 (widen)
13414 (setq bmp (buffer-modified-p))
13415 (org-refresh-category-properties)
13416 (setq org-todo-keywords-for-agenda
13417 (append org-todo-keywords-for-agenda org-todo-keywords-1))
13418 (setq org-done-keywords-for-agenda
13419 (append org-done-keywords-for-agenda org-done-keywords))
13420 (setq org-todo-keyword-alist-for-agenda
13421 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
13422 (setq org-tag-alist-for-agenda
13423 (append org-tag-alist-for-agenda org-tag-alist))
13425 (save-excursion
13426 (remove-text-properties (point-min) (point-max) pall)
13427 (when org-agenda-skip-archived-trees
13428 (goto-char (point-min))
13429 (while (re-search-forward rea nil t)
13430 (if (org-on-heading-p t)
13431 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
13432 (goto-char (point-min))
13433 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
13434 (while (re-search-forward re nil t)
13435 (add-text-properties
13436 (match-beginning 0) (org-end-of-subtree t) pc)))
13437 (set-buffer-modified-p bmp)))))
13438 (setq org-todo-keyword-alist-for-agenda
13439 (org-uniquify org-todo-keyword-alist-for-agenda)
13440 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
13442 ;;;; Embedded LaTeX
13444 (defvar org-cdlatex-mode-map (make-sparse-keymap)
13445 "Keymap for the minor `org-cdlatex-mode'.")
13447 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
13448 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
13449 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
13450 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
13451 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
13453 (defvar org-cdlatex-texmathp-advice-is-done nil
13454 "Flag remembering if we have applied the advice to texmathp already.")
13456 (define-minor-mode org-cdlatex-mode
13457 "Toggle the minor `org-cdlatex-mode'.
13458 This mode supports entering LaTeX environment and math in LaTeX fragments
13459 in Org-mode.
13460 \\{org-cdlatex-mode-map}"
13461 nil " OCDL" nil
13462 (when org-cdlatex-mode (require 'cdlatex))
13463 (unless org-cdlatex-texmathp-advice-is-done
13464 (setq org-cdlatex-texmathp-advice-is-done t)
13465 (defadvice texmathp (around org-math-always-on activate)
13466 "Always return t in org-mode buffers.
13467 This is because we want to insert math symbols without dollars even outside
13468 the LaTeX math segments. If Orgmode thinks that point is actually inside
13469 an embedded LaTeX fragment, let texmathp do its job.
13470 \\[org-cdlatex-mode-map]"
13471 (interactive)
13472 (let (p)
13473 (cond
13474 ((not (org-mode-p)) ad-do-it)
13475 ((eq this-command 'cdlatex-math-symbol)
13476 (setq ad-return-value t
13477 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
13479 (let ((p (org-inside-LaTeX-fragment-p)))
13480 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
13481 (setq ad-return-value t
13482 texmathp-why '("Org-mode embedded math" . 0))
13483 (if p ad-do-it)))))))))
13485 (defun turn-on-org-cdlatex ()
13486 "Unconditionally turn on `org-cdlatex-mode'."
13487 (org-cdlatex-mode 1))
13489 (defun org-inside-LaTeX-fragment-p ()
13490 "Test if point is inside a LaTeX fragment.
13491 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
13492 sequence appearing also before point.
13493 Even though the matchers for math are configurable, this function assumes
13494 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
13495 delimiters are skipped when they have been removed by customization.
13496 The return value is nil, or a cons cell with the delimiter and
13497 and the position of this delimiter.
13499 This function does a reasonably good job, but can locally be fooled by
13500 for example currency specifications. For example it will assume being in
13501 inline math after \"$22.34\". The LaTeX fragment formatter will only format
13502 fragments that are properly closed, but during editing, we have to live
13503 with the uncertainty caused by missing closing delimiters. This function
13504 looks only before point, not after."
13505 (catch 'exit
13506 (let ((pos (point))
13507 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
13508 (lim (progn
13509 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
13510 (point)))
13511 dd-on str (start 0) m re)
13512 (goto-char pos)
13513 (when dodollar
13514 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
13515 re (nth 1 (assoc "$" org-latex-regexps)))
13516 (while (string-match re str start)
13517 (cond
13518 ((= (match-end 0) (length str))
13519 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
13520 ((= (match-end 0) (- (length str) 5))
13521 (throw 'exit nil))
13522 (t (setq start (match-end 0))))))
13523 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
13524 (goto-char pos)
13525 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
13526 (and (match-beginning 2) (throw 'exit nil))
13527 ;; count $$
13528 (while (re-search-backward "\\$\\$" lim t)
13529 (setq dd-on (not dd-on)))
13530 (goto-char pos)
13531 (if dd-on (cons "$$" m))))))
13534 (defun org-try-cdlatex-tab ()
13535 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
13536 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
13537 - inside a LaTeX fragment, or
13538 - after the first word in a line, where an abbreviation expansion could
13539 insert a LaTeX environment."
13540 (when org-cdlatex-mode
13541 (cond
13542 ((save-excursion
13543 (skip-chars-backward "a-zA-Z0-9*")
13544 (skip-chars-backward " \t")
13545 (bolp))
13546 (cdlatex-tab) t)
13547 ((org-inside-LaTeX-fragment-p)
13548 (cdlatex-tab) t)
13549 (t nil))))
13551 (defun org-cdlatex-underscore-caret (&optional arg)
13552 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
13553 Revert to the normal definition outside of these fragments."
13554 (interactive "P")
13555 (if (org-inside-LaTeX-fragment-p)
13556 (call-interactively 'cdlatex-sub-superscript)
13557 (let (org-cdlatex-mode)
13558 (call-interactively (key-binding (vector last-input-event))))))
13560 (defun org-cdlatex-math-modify (&optional arg)
13561 "Execute `cdlatex-math-modify' in LaTeX fragments.
13562 Revert to the normal definition outside of these fragments."
13563 (interactive "P")
13564 (if (org-inside-LaTeX-fragment-p)
13565 (call-interactively 'cdlatex-math-modify)
13566 (let (org-cdlatex-mode)
13567 (call-interactively (key-binding (vector last-input-event))))))
13569 (defvar org-latex-fragment-image-overlays nil
13570 "List of overlays carrying the images of latex fragments.")
13571 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
13573 (defun org-remove-latex-fragment-image-overlays ()
13574 "Remove all overlays with LaTeX fragment images in current buffer."
13575 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
13576 (setq org-latex-fragment-image-overlays nil))
13578 (defun org-preview-latex-fragment (&optional subtree)
13579 "Preview the LaTeX fragment at point, or all locally or globally.
13580 If the cursor is in a LaTeX fragment, create the image and overlay
13581 it over the source code. If there is no fragment at point, display
13582 all fragments in the current text, from one headline to the next. With
13583 prefix SUBTREE, display all fragments in the current subtree. With a
13584 double prefix `C-u C-u', or when the cursor is before the first headline,
13585 display all fragments in the buffer.
13586 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
13587 (interactive "P")
13588 (org-remove-latex-fragment-image-overlays)
13589 (save-excursion
13590 (save-restriction
13591 (let (beg end at msg)
13592 (cond
13593 ((or (equal subtree '(16))
13594 (not (save-excursion
13595 (re-search-backward (concat "^" outline-regexp) nil t))))
13596 (setq beg (point-min) end (point-max)
13597 msg "Creating images for buffer...%s"))
13598 ((equal subtree '(4))
13599 (org-back-to-heading)
13600 (setq beg (point) end (org-end-of-subtree t)
13601 msg "Creating images for subtree...%s"))
13603 (if (setq at (org-inside-LaTeX-fragment-p))
13604 (goto-char (max (point-min) (- (cdr at) 2)))
13605 (org-back-to-heading))
13606 (setq beg (point) end (progn (outline-next-heading) (point))
13607 msg (if at "Creating image...%s"
13608 "Creating images for entry...%s"))))
13609 (message msg "")
13610 (narrow-to-region beg end)
13611 (goto-char beg)
13612 (org-format-latex
13613 (concat "ltxpng/" (file-name-sans-extension
13614 (file-name-nondirectory
13615 buffer-file-name)))
13616 default-directory 'overlays msg at 'forbuffer)
13617 (message msg "done. Use `C-c C-c' to remove images.")))))
13619 (defvar org-latex-regexps
13620 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
13621 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
13622 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
13623 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13624 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13625 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
13626 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
13627 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
13628 "Regular expressions for matching embedded LaTeX.")
13630 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
13631 "Replace LaTeX fragments with links to an image, and produce images."
13632 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
13633 (let* ((prefixnodir (file-name-nondirectory prefix))
13634 (absprefix (expand-file-name prefix dir))
13635 (todir (file-name-directory absprefix))
13636 (opt org-format-latex-options)
13637 (matchers (plist-get opt :matchers))
13638 (re-list org-latex-regexps)
13639 (cnt 0) txt link beg end re e checkdir
13640 executables-checked
13641 m n block linkfile movefile ov)
13642 ;; Check if there are old images files with this prefix, and remove them
13643 (when (file-directory-p todir)
13644 (mapc 'delete-file
13645 (directory-files
13646 todir 'full
13647 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
13648 ;; Check the different regular expressions
13649 (while (setq e (pop re-list))
13650 (setq m (car e) re (nth 1 e) n (nth 2 e)
13651 block (if (nth 3 e) "\n\n" ""))
13652 (when (member m matchers)
13653 (goto-char (point-min))
13654 (while (re-search-forward re nil t)
13655 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
13656 (not (get-text-property (match-beginning n)
13657 'org-protected)))
13658 (setq txt (match-string n)
13659 beg (match-beginning n) end (match-end n)
13660 cnt (1+ cnt)
13661 linkfile (format "%s_%04d.png" prefix cnt)
13662 movefile (format "%s_%04d.png" absprefix cnt)
13663 link (concat block "[[file:" linkfile "]]" block))
13664 (if msg (message msg cnt))
13665 (goto-char beg)
13666 (unless checkdir ; make sure the directory exists
13667 (setq checkdir t)
13668 (or (file-directory-p todir) (make-directory todir)))
13670 (unless executables-checked
13671 (org-check-external-command
13672 "latex" "needed to convert LaTeX fragments to images")
13673 (org-check-external-command
13674 "dvipng" "needed to convert LaTeX fragments to images")
13675 (setq executables-checked t))
13677 (org-create-formula-image
13678 txt movefile opt forbuffer)
13679 (if overlays
13680 (progn
13681 (setq ov (org-make-overlay beg end))
13682 (if (featurep 'xemacs)
13683 (progn
13684 (org-overlay-put ov 'invisible t)
13685 (org-overlay-put
13686 ov 'end-glyph
13687 (make-glyph (vector 'png :file movefile))))
13688 (org-overlay-put
13689 ov 'display
13690 (list 'image :type 'png :file movefile :ascent 'center)))
13691 (push ov org-latex-fragment-image-overlays)
13692 (goto-char end))
13693 (delete-region beg end)
13694 (insert link))))))))
13696 ;; This function borrows from Ganesh Swami's latex2png.el
13697 (defun org-create-formula-image (string tofile options buffer)
13698 (let* ((tmpdir (if (featurep 'xemacs)
13699 (temp-directory)
13700 temporary-file-directory))
13701 (texfilebase (make-temp-name
13702 (expand-file-name "orgtex" tmpdir)))
13703 (texfile (concat texfilebase ".tex"))
13704 (dvifile (concat texfilebase ".dvi"))
13705 (pngfile (concat texfilebase ".png"))
13706 (fnh (if (featurep 'xemacs)
13707 (font-height (get-face-font 'default))
13708 (face-attribute 'default :height nil)))
13709 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
13710 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
13711 (fg (or (plist-get options (if buffer :foreground :html-foreground))
13712 "Black"))
13713 (bg (or (plist-get options (if buffer :background :html-background))
13714 "Transparent")))
13715 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
13716 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
13717 (with-temp-file texfile
13718 (insert org-format-latex-header
13719 "\n\\begin{document}\n" string "\n\\end{document}\n"))
13720 (let ((dir default-directory))
13721 (condition-case nil
13722 (progn
13723 (cd tmpdir)
13724 (call-process "latex" nil nil nil texfile))
13725 (error nil))
13726 (cd dir))
13727 (if (not (file-exists-p dvifile))
13728 (progn (message "Failed to create dvi file from %s" texfile) nil)
13729 (condition-case nil
13730 (call-process "dvipng" nil nil nil
13731 "-E" "-fg" fg "-bg" bg
13732 "-D" dpi
13733 ;;"-x" scale "-y" scale
13734 "-T" "tight"
13735 "-o" pngfile
13736 dvifile)
13737 (error nil))
13738 (if (not (file-exists-p pngfile))
13739 (progn (message "Failed to create png file from %s" texfile) nil)
13740 ;; Use the requested file name and clean up
13741 (copy-file pngfile tofile 'replace)
13742 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
13743 (delete-file (concat texfilebase e)))
13744 pngfile))))
13746 (defun org-dvipng-color (attr)
13747 "Return an rgb color specification for dvipng."
13748 (apply 'format "rgb %s %s %s"
13749 (mapcar 'org-normalize-color
13750 (color-values (face-attribute 'default attr nil)))))
13752 (defun org-normalize-color (value)
13753 "Return string to be used as color value for an RGB component."
13754 (format "%g" (/ value 65535.0)))
13756 ;;;; Key bindings
13758 ;; Make `C-c C-x' a prefix key
13759 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
13761 ;; TAB key with modifiers
13762 (org-defkey org-mode-map "\C-i" 'org-cycle)
13763 (org-defkey org-mode-map [(tab)] 'org-cycle)
13764 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
13765 (org-defkey org-mode-map [(meta tab)] 'org-complete)
13766 (org-defkey org-mode-map "\M-\t" 'org-complete)
13767 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
13768 ;; The following line is necessary under Suse GNU/Linux
13769 (unless (featurep 'xemacs)
13770 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
13771 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
13772 (define-key org-mode-map [backtab] 'org-shifttab)
13774 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
13775 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
13776 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
13778 ;; Cursor keys with modifiers
13779 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
13780 (org-defkey org-mode-map [(meta right)] 'org-metaright)
13781 (org-defkey org-mode-map [(meta up)] 'org-metaup)
13782 (org-defkey org-mode-map [(meta down)] 'org-metadown)
13784 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
13785 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
13786 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
13787 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
13789 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
13790 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
13791 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
13792 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
13794 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
13795 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
13797 ;;; Extra keys for tty access.
13798 ;; We only set them when really needed because otherwise the
13799 ;; menus don't show the simple keys
13801 (when (or org-use-extra-keys
13802 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
13803 (not window-system))
13804 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
13805 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
13806 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
13807 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
13808 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
13809 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
13810 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
13811 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
13812 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
13813 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
13814 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
13815 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
13816 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
13817 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
13818 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
13819 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
13820 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
13821 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
13822 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
13823 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
13824 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
13825 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
13826 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
13827 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
13828 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
13829 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
13830 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
13831 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
13833 ;; All the other keys
13835 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
13836 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
13837 (if (boundp 'narrow-map)
13838 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
13839 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
13840 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
13841 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
13842 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
13843 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
13844 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
13845 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
13846 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
13847 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
13848 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
13849 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
13850 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
13851 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
13852 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
13853 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
13854 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
13855 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
13856 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
13857 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
13858 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
13859 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
13860 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
13861 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
13862 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
13863 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
13864 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
13865 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
13866 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
13867 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
13868 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
13869 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
13870 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
13871 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
13872 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
13873 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
13874 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
13875 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
13876 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
13877 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
13878 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
13879 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13880 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
13881 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
13882 (org-defkey org-mode-map "\C-c^" 'org-sort)
13883 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
13884 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
13885 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
13886 (org-defkey org-mode-map "\C-m" 'org-return)
13887 (org-defkey org-mode-map "\C-j" 'org-return-indent)
13888 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
13889 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
13890 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
13891 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
13892 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
13893 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
13894 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
13895 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
13896 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
13897 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
13898 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
13899 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
13900 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
13901 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
13902 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
13903 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
13905 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
13906 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
13907 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
13908 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
13910 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
13911 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
13912 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
13913 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
13914 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
13915 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
13916 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
13917 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
13918 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
13919 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
13920 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
13921 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
13922 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
13924 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
13925 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
13926 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
13927 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
13929 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
13931 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
13933 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
13934 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
13936 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
13939 (when (featurep 'xemacs)
13940 (org-defkey org-mode-map 'button3 'popup-mode-menu))
13943 (defvar org-self-insert-command-undo-counter 0)
13945 (defvar org-table-auto-blank-field) ; defined in org-table.el
13946 (defun org-self-insert-command (N)
13947 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13948 If the cursor is in a table looking at whitespace, the whitespace is
13949 overwritten, and the table is not marked as requiring realignment."
13950 (interactive "p")
13951 (if (and
13952 (org-table-p)
13953 (progn
13954 ;; check if we blank the field, and if that triggers align
13955 (and (featurep 'org-table) org-table-auto-blank-field
13956 (member last-command
13957 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
13958 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
13959 ;; got extra space, this field does not determine column width
13960 (let (org-table-may-need-update) (org-table-blank-field))
13961 ;; no extra space, this field may determine column width
13962 (org-table-blank-field)))
13964 (eq N 1)
13965 (looking-at "[^|\n]* |"))
13966 (let (org-table-may-need-update)
13967 (goto-char (1- (match-end 0)))
13968 (delete-backward-char 1)
13969 (goto-char (match-beginning 0))
13970 (self-insert-command N))
13971 (setq org-table-may-need-update t)
13972 (self-insert-command N)
13973 (org-fix-tags-on-the-fly)
13974 (if org-self-insert-cluster-for-undo
13975 (if (not (eq last-command 'org-self-insert-command))
13976 (setq org-self-insert-command-undo-counter 1)
13977 (if (>= org-self-insert-command-undo-counter 20)
13978 (setq org-self-insert-command-undo-counter 1)
13979 (and (> org-self-insert-command-undo-counter 0)
13980 buffer-undo-list
13981 (not (cadr buffer-undo-list)) ; remove nil entry
13982 (setcdr buffer-undo-list (cddr buffer-undo-list)))
13983 (setq org-self-insert-command-undo-counter
13984 (1+ org-self-insert-command-undo-counter)))))))
13986 (defun org-fix-tags-on-the-fly ()
13987 (when (and (equal (char-after (point-at-bol)) ?*)
13988 (org-on-heading-p))
13989 (org-align-tags-here org-tags-column)))
13991 (defun org-delete-backward-char (N)
13992 "Like `delete-backward-char', insert whitespace at field end in tables.
13993 When deleting backwards, in tables this function will insert whitespace in
13994 front of the next \"|\" separator, to keep the table aligned. The table will
13995 still be marked for re-alignment if the field did fill the entire column,
13996 because, in this case the deletion might narrow the column."
13997 (interactive "p")
13998 (if (and (org-table-p)
13999 (eq N 1)
14000 (string-match "|" (buffer-substring (point-at-bol) (point)))
14001 (looking-at ".*?|"))
14002 (let ((pos (point))
14003 (noalign (looking-at "[^|\n\r]* |"))
14004 (c org-table-may-need-update))
14005 (backward-delete-char N)
14006 (skip-chars-forward "^|")
14007 (insert " ")
14008 (goto-char (1- pos))
14009 ;; noalign: if there were two spaces at the end, this field
14010 ;; does not determine the width of the column.
14011 (if noalign (setq org-table-may-need-update c)))
14012 (backward-delete-char N)
14013 (org-fix-tags-on-the-fly)))
14015 (defun org-delete-char (N)
14016 "Like `delete-char', but insert whitespace at field end in tables.
14017 When deleting characters, in tables this function will insert whitespace in
14018 front of the next \"|\" separator, to keep the table aligned. The table will
14019 still be marked for re-alignment if the field did fill the entire column,
14020 because, in this case the deletion might narrow the column."
14021 (interactive "p")
14022 (if (and (org-table-p)
14023 (not (bolp))
14024 (not (= (char-after) ?|))
14025 (eq N 1))
14026 (if (looking-at ".*?|")
14027 (let ((pos (point))
14028 (noalign (looking-at "[^|\n\r]* |"))
14029 (c org-table-may-need-update))
14030 (replace-match (concat
14031 (substring (match-string 0) 1 -1)
14032 " |"))
14033 (goto-char pos)
14034 ;; noalign: if there were two spaces at the end, this field
14035 ;; does not determine the width of the column.
14036 (if noalign (setq org-table-may-need-update c)))
14037 (delete-char N))
14038 (delete-char N)
14039 (org-fix-tags-on-the-fly)))
14041 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
14042 (put 'org-self-insert-command 'delete-selection t)
14043 (put 'orgtbl-self-insert-command 'delete-selection t)
14044 (put 'org-delete-char 'delete-selection 'supersede)
14045 (put 'org-delete-backward-char 'delete-selection 'supersede)
14046 (put 'org-yank 'delete-selection 'yank)
14048 ;; Make `flyspell-mode' delay after some commands
14049 (put 'org-self-insert-command 'flyspell-delayed t)
14050 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
14051 (put 'org-delete-char 'flyspell-delayed t)
14052 (put 'org-delete-backward-char 'flyspell-delayed t)
14054 ;; Make pabbrev-mode expand after org-mode commands
14055 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
14056 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
14058 ;; How to do this: Measure non-white length of current string
14059 ;; If equal to column width, we should realign.
14061 (defun org-remap (map &rest commands)
14062 "In MAP, remap the functions given in COMMANDS.
14063 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
14064 (let (new old)
14065 (while commands
14066 (setq old (pop commands) new (pop commands))
14067 (if (fboundp 'command-remapping)
14068 (org-defkey map (vector 'remap old) new)
14069 (substitute-key-definition old new map global-map)))))
14071 (when (eq org-enable-table-editor 'optimized)
14072 ;; If the user wants maximum table support, we need to hijack
14073 ;; some standard editing functions
14074 (org-remap org-mode-map
14075 'self-insert-command 'org-self-insert-command
14076 'delete-char 'org-delete-char
14077 'delete-backward-char 'org-delete-backward-char)
14078 (org-defkey org-mode-map "|" 'org-force-self-insert))
14080 (defvar org-ctrl-c-ctrl-c-hook nil
14081 "Hook for functions attaching themselves to `C-c C-c'.
14082 This can be used to add additional functionality to the C-c C-c key which
14083 executes context-dependent commands.
14084 Each function will be called with no arguments. The function must check
14085 if the context is appropriate for it to act. If yes, it should do its
14086 thing and then return a non-nil value. If the context is wrong,
14087 just do nothing and return nil.")
14089 (defvar org-tab-first-hook nil
14090 "Hook for functions to attach themselves to TAB.
14091 See `org-ctrl-c-ctrl-c-hook' for more information.
14092 This hook runs as the first action when TAB is pressed, even before
14093 `org-cycle' messes around with the `outline-regexp' to cater for
14094 inline tasks and plain list item folding.
14095 If any function in this hook returns t, not other actions like table
14096 field motion visibility cycling will be done.")
14098 (defvar org-tab-after-check-for-table-hook nil
14099 "Hook for functions to attach themselves to TAB.
14100 See `org-ctrl-c-ctrl-c-hook' for more information.
14101 This hook runs after it has been established that the cursor is not in a
14102 table, but before checking if the cursor is in a headline or if global cycling
14103 should be done.
14104 If any function in this hook returns t, not other actions like visibility
14105 cycling will be done.")
14107 (defvar org-tab-after-check-for-cycling-hook nil
14108 "Hook for functions to attach themselves to TAB.
14109 See `org-ctrl-c-ctrl-c-hook' for more information.
14110 This hook runs after it has been established that not table field motion and
14111 not visibility should be done because of current context. This is probably
14112 the place where a package like yasnippets can hook in.")
14114 (defvar org-metaleft-hook nil
14115 "Hook for functions attaching themselves to `M-left'.
14116 See `org-ctrl-c-ctrl-c-hook' for more information.")
14117 (defvar org-metaright-hook nil
14118 "Hook for functions attaching themselves to `M-right'.
14119 See `org-ctrl-c-ctrl-c-hook' for more information.")
14120 (defvar org-metaup-hook nil
14121 "Hook for functions attaching themselves to `M-up'.
14122 See `org-ctrl-c-ctrl-c-hook' for more information.")
14123 (defvar org-metadown-hook nil
14124 "Hook for functions attaching themselves to `M-down'.
14125 See `org-ctrl-c-ctrl-c-hook' for more information.")
14126 (defvar org-shiftmetaleft-hook nil
14127 "Hook for functions attaching themselves to `M-S-left'.
14128 See `org-ctrl-c-ctrl-c-hook' for more information.")
14129 (defvar org-shiftmetaright-hook nil
14130 "Hook for functions attaching themselves to `M-S-right'.
14131 See `org-ctrl-c-ctrl-c-hook' for more information.")
14132 (defvar org-shiftmetaup-hook nil
14133 "Hook for functions attaching themselves to `M-S-up'.
14134 See `org-ctrl-c-ctrl-c-hook' for more information.")
14135 (defvar org-shiftmetadown-hook nil
14136 "Hook for functions attaching themselves to `M-S-down'.
14137 See `org-ctrl-c-ctrl-c-hook' for more information.")
14138 (defvar org-metareturn-hook nil
14139 "Hook for functions attaching themselves to `M-RET'.
14140 See `org-ctrl-c-ctrl-c-hook' for more information.")
14142 (defun org-modifier-cursor-error ()
14143 "Throw an error, a modified cursor command was applied in wrong context."
14144 (error "This command is active in special context like tables, headlines or items"))
14146 (defun org-shiftselect-error ()
14147 "Throw an error because Shift-Cursor command was applied in wrong context."
14148 (if (and (boundp 'shift-select-mode) shift-select-mode)
14149 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
14150 (error "This command works only in special context like headlines or timestamps.")))
14152 (defun org-call-for-shift-select (cmd)
14153 (let ((this-command-keys-shift-translated t))
14154 (call-interactively cmd)))
14156 (defun org-shifttab (&optional arg)
14157 "Global visibility cycling or move to previous table field.
14158 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
14159 on context.
14160 See the individual commands for more information."
14161 (interactive "P")
14162 (cond
14163 ((org-at-table-p) (call-interactively 'org-table-previous-field))
14164 ((integerp arg)
14165 (message "Content view to level: %d" arg)
14166 (org-content (prefix-numeric-value arg))
14167 (setq org-cycle-global-status 'overview))
14168 (t (call-interactively 'org-global-cycle))))
14170 (defun org-shiftmetaleft ()
14171 "Promote subtree or delete table column.
14172 Calls `org-promote-subtree', `org-outdent-item',
14173 or `org-table-delete-column', depending on context.
14174 See the individual commands for more information."
14175 (interactive)
14176 (cond
14177 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
14178 ((org-at-table-p) (call-interactively 'org-table-delete-column))
14179 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
14180 ((org-at-item-p) (call-interactively 'org-outdent-item))
14181 (t (org-modifier-cursor-error))))
14183 (defun org-shiftmetaright ()
14184 "Demote subtree or insert table column.
14185 Calls `org-demote-subtree', `org-indent-item',
14186 or `org-table-insert-column', depending on context.
14187 See the individual commands for more information."
14188 (interactive)
14189 (cond
14190 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
14191 ((org-at-table-p) (call-interactively 'org-table-insert-column))
14192 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
14193 ((org-at-item-p) (call-interactively 'org-indent-item))
14194 (t (org-modifier-cursor-error))))
14196 (defun org-shiftmetaup (&optional arg)
14197 "Move subtree up or kill table row.
14198 Calls `org-move-subtree-up' or `org-table-kill-row' or
14199 `org-move-item-up' depending on context. See the individual commands
14200 for more information."
14201 (interactive "P")
14202 (cond
14203 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
14204 ((org-at-table-p) (call-interactively 'org-table-kill-row))
14205 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14206 ((org-at-item-p) (call-interactively 'org-move-item-up))
14207 (t (org-modifier-cursor-error))))
14209 (defun org-shiftmetadown (&optional arg)
14210 "Move subtree down or insert table row.
14211 Calls `org-move-subtree-down' or `org-table-insert-row' or
14212 `org-move-item-down', depending on context. See the individual
14213 commands for more information."
14214 (interactive "P")
14215 (cond
14216 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
14217 ((org-at-table-p) (call-interactively 'org-table-insert-row))
14218 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14219 ((org-at-item-p) (call-interactively 'org-move-item-down))
14220 (t (org-modifier-cursor-error))))
14222 (defun org-metaleft (&optional arg)
14223 "Promote heading or move table column to left.
14224 Calls `org-do-promote' or `org-table-move-column', depending on context.
14225 With no specific context, calls the Emacs default `backward-word'.
14226 See the individual commands for more information."
14227 (interactive "P")
14228 (cond
14229 ((run-hook-with-args-until-success 'org-metaleft-hook))
14230 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
14231 ((or (org-on-heading-p)
14232 (and (org-region-active-p)
14233 (save-excursion
14234 (goto-char (region-beginning))
14235 (org-on-heading-p))))
14236 (call-interactively 'org-do-promote))
14237 ((or (org-at-item-p)
14238 (and (org-region-active-p)
14239 (save-excursion
14240 (goto-char (region-beginning))
14241 (org-at-item-p))))
14242 (call-interactively 'org-outdent-item))
14243 (t (call-interactively 'backward-word))))
14245 (defun org-metaright (&optional arg)
14246 "Demote subtree or move table column to right.
14247 Calls `org-do-demote' or `org-table-move-column', depending on context.
14248 With no specific context, calls the Emacs default `forward-word'.
14249 See the individual commands for more information."
14250 (interactive "P")
14251 (cond
14252 ((run-hook-with-args-until-success 'org-metaright-hook))
14253 ((org-at-table-p) (call-interactively 'org-table-move-column))
14254 ((or (org-on-heading-p)
14255 (and (org-region-active-p)
14256 (save-excursion
14257 (goto-char (region-beginning))
14258 (org-on-heading-p))))
14259 (call-interactively 'org-do-demote))
14260 ((or (org-at-item-p)
14261 (and (org-region-active-p)
14262 (save-excursion
14263 (goto-char (region-beginning))
14264 (org-at-item-p))))
14265 (call-interactively 'org-indent-item))
14266 (t (call-interactively 'forward-word))))
14268 (defun org-metaup (&optional arg)
14269 "Move subtree up or move table row up.
14270 Calls `org-move-subtree-up' or `org-table-move-row' or
14271 `org-move-item-up', depending on context. See the individual commands
14272 for more information."
14273 (interactive "P")
14274 (cond
14275 ((run-hook-with-args-until-success 'org-metaup-hook))
14276 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
14277 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14278 ((org-at-item-p) (call-interactively 'org-move-item-up))
14279 (t (transpose-lines 1) (beginning-of-line -1))))
14281 (defun org-metadown (&optional arg)
14282 "Move subtree down or move table row down.
14283 Calls `org-move-subtree-down' or `org-table-move-row' or
14284 `org-move-item-down', depending on context. See the individual
14285 commands for more information."
14286 (interactive "P")
14287 (cond
14288 ((run-hook-with-args-until-success 'org-metadown-hook))
14289 ((org-at-table-p) (call-interactively 'org-table-move-row))
14290 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14291 ((org-at-item-p) (call-interactively 'org-move-item-down))
14292 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
14294 (defun org-shiftup (&optional arg)
14295 "Increase item in timestamp or increase priority of current headline.
14296 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
14297 depending on context. See the individual commands for more information."
14298 (interactive "P")
14299 (cond
14300 ((and org-support-shift-select (org-region-active-p))
14301 (org-call-for-shift-select 'previous-line))
14302 ((org-at-timestamp-p t)
14303 (call-interactively (if org-edit-timestamp-down-means-later
14304 'org-timestamp-down 'org-timestamp-up)))
14305 ((and (not (eq org-support-shift-select 'always))
14306 org-enable-priority-commands
14307 (org-on-heading-p))
14308 (call-interactively 'org-priority-up))
14309 ((and (not org-support-shift-select) (org-at-item-p))
14310 (call-interactively 'org-previous-item))
14311 ((org-clocktable-try-shift 'up arg))
14312 (org-support-shift-select
14313 (org-call-for-shift-select 'previous-line))
14314 (t (org-shiftselect-error))))
14316 (defun org-shiftdown (&optional arg)
14317 "Decrease item in timestamp or decrease priority of current headline.
14318 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
14319 depending on context. See the individual commands for more information."
14320 (interactive "P")
14321 (cond
14322 ((and org-support-shift-select (org-region-active-p))
14323 (org-call-for-shift-select 'next-line))
14324 ((org-at-timestamp-p t)
14325 (call-interactively (if org-edit-timestamp-down-means-later
14326 'org-timestamp-up 'org-timestamp-down)))
14327 ((and (not (eq org-support-shift-select 'always))
14328 org-enable-priority-commands
14329 (org-on-heading-p))
14330 (call-interactively 'org-priority-down))
14331 ((and (not org-support-shift-select) (org-at-item-p))
14332 (call-interactively 'org-next-item))
14333 ((org-clocktable-try-shift 'down arg))
14334 (org-support-shift-select
14335 (org-call-for-shift-select 'next-line))
14336 (t (org-shiftselect-error))))
14338 (defun org-shiftright (&optional arg)
14339 "Cycle the thing at point or in the current line, depending on context.
14340 Depending on context, this does one of the following:
14342 - switch a timestamp at point one day into the future
14343 - on a headline, switch to the next TODO keyword.
14344 - on an item, switch entire list to the next bullet type
14345 - on a property line, switch to the next allowed value
14346 - on a clocktable definition line, move time block into the future"
14347 (interactive "P")
14348 (cond
14349 ((and org-support-shift-select (org-region-active-p))
14350 (org-call-for-shift-select 'forward-char))
14351 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
14352 ((and (not (eq org-support-shift-select 'always))
14353 (org-on-heading-p))
14354 (let ((org-inhibit-logging
14355 (not org-treat-S-cursor-todo-selection-as-state-change)))
14356 (org-call-with-arg 'org-todo 'right)))
14357 ((or (and org-support-shift-select
14358 (not (eq org-support-shift-select 'always))
14359 (org-at-item-bullet-p))
14360 (and (not org-support-shift-select) (org-at-item-p)))
14361 (org-call-with-arg 'org-cycle-list-bullet nil))
14362 ((and (not (eq org-support-shift-select 'always))
14363 (org-at-property-p))
14364 (call-interactively 'org-property-next-allowed-value))
14365 ((org-clocktable-try-shift 'right arg))
14366 (org-support-shift-select
14367 (org-call-for-shift-select 'forward-char))
14368 (t (org-shiftselect-error))))
14370 (defun org-shiftleft (&optional arg)
14371 "Cycle the thing at point or in the current line, depending on context.
14372 Depending on context, this does one of the following:
14374 - switch a timestamp at point one day into the past
14375 - on a headline, switch to the previous TODO keyword.
14376 - on an item, switch entire list to the previous bullet type
14377 - on a property line, switch to the previous allowed value
14378 - on a clocktable definition line, move time block into the past"
14379 (interactive "P")
14380 (cond
14381 ((and org-support-shift-select (org-region-active-p))
14382 (org-call-for-shift-select 'backward-char))
14383 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
14384 ((and (not (eq org-support-shift-select 'always))
14385 (org-on-heading-p))
14386 (let ((org-inhibit-logging
14387 (not org-treat-S-cursor-todo-selection-as-state-change)))
14388 (org-call-with-arg 'org-todo 'left)))
14389 ((or (and org-support-shift-select
14390 (not (eq org-support-shift-select 'always))
14391 (org-at-item-bullet-p))
14392 (and (not org-support-shift-select) (org-at-item-p)))
14393 (org-call-with-arg 'org-cycle-list-bullet 'previous))
14394 ((and (not (eq org-support-shift-select 'always))
14395 (org-at-property-p))
14396 (call-interactively 'org-property-previous-allowed-value))
14397 ((org-clocktable-try-shift 'left arg))
14398 (org-support-shift-select
14399 (org-call-for-shift-select 'backward-char))
14400 (t (org-shiftselect-error))))
14402 (defun org-shiftcontrolright ()
14403 "Switch to next TODO set."
14404 (interactive)
14405 (cond
14406 ((and org-support-shift-select (org-region-active-p))
14407 (org-call-for-shift-select 'forward-word))
14408 ((and (not (eq org-support-shift-select 'always))
14409 (org-on-heading-p))
14410 (org-call-with-arg 'org-todo 'nextset))
14411 (org-support-shift-select
14412 (org-call-for-shift-select 'forward-word))
14413 (t (org-shiftselect-error))))
14415 (defun org-shiftcontrolleft ()
14416 "Switch to previous TODO set."
14417 (interactive)
14418 (cond
14419 ((and org-support-shift-select (org-region-active-p))
14420 (org-call-for-shift-select 'backward-word))
14421 ((and (not (eq org-support-shift-select 'always))
14422 (org-on-heading-p))
14423 (org-call-with-arg 'org-todo 'previousset))
14424 (org-support-shift-select
14425 (org-call-for-shift-select 'backward-word))
14426 (t (org-shiftselect-error))))
14428 (defun org-ctrl-c-ret ()
14429 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
14430 (interactive)
14431 (cond
14432 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
14433 (t (call-interactively 'org-insert-heading))))
14435 (defun org-copy-special ()
14436 "Copy region in table or copy current subtree.
14437 Calls `org-table-copy' or `org-copy-subtree', depending on context.
14438 See the individual commands for more information."
14439 (interactive)
14440 (call-interactively
14441 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
14443 (defun org-cut-special ()
14444 "Cut region in table or cut current subtree.
14445 Calls `org-table-copy' or `org-cut-subtree', depending on context.
14446 See the individual commands for more information."
14447 (interactive)
14448 (call-interactively
14449 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
14451 (defun org-paste-special (arg)
14452 "Paste rectangular region into table, or past subtree relative to level.
14453 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
14454 See the individual commands for more information."
14455 (interactive "P")
14456 (if (org-at-table-p)
14457 (org-table-paste-rectangle)
14458 (org-paste-subtree arg)))
14460 (defun org-edit-special ()
14461 "Call a special editor for the stuff at point.
14462 When at a table, call the formula editor with `org-table-edit-formulas'.
14463 When at the first line of an src example, call `org-edit-src-code'.
14464 When in an #+include line, visit the include file. Otherwise call
14465 `ffap' to visit the file at point."
14466 (interactive)
14467 (cond
14468 ((org-at-table-p)
14469 (call-interactively 'org-table-edit-formulas))
14470 ((save-excursion
14471 (beginning-of-line 1)
14472 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
14473 (find-file (org-trim (match-string 1))))
14474 ((org-edit-src-code))
14475 ((org-edit-fixed-width-region))
14476 (t (call-interactively 'ffap))))
14479 (defun org-ctrl-c-ctrl-c (&optional arg)
14480 "Set tags in headline, or update according to changed information at point.
14482 This command does many different things, depending on context:
14484 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
14485 this is what we do.
14487 - If the cursor is in a headline, prompt for tags and insert them
14488 into the current line, aligned to `org-tags-column'. When called
14489 with prefix arg, realign all tags in the current buffer.
14491 - If the cursor is in one of the special #+KEYWORD lines, this
14492 triggers scanning the buffer for these lines and updating the
14493 information.
14495 - If the cursor is inside a table, realign the table. This command
14496 works even if the automatic table editor has been turned off.
14498 - If the cursor is on a #+TBLFM line, re-apply the formulas to
14499 the entire table.
14501 - If the cursor is at a footnote reference or definition, jump to
14502 the corresponding definition or references, respectively.
14504 - If the cursor is a the beginning of a dynamic block, update it.
14506 - If the cursor is inside a table created by the table.el package,
14507 activate that table.
14509 - If the current buffer is a remember buffer, close note and file
14510 it. A prefix argument of 1 files to the default location
14511 without further interaction. A prefix argument of 2 files to
14512 the currently clocking task.
14514 - If the cursor is on a <<<target>>>, update radio targets and corresponding
14515 links in this buffer.
14517 - If the cursor is on a numbered item in a plain list, renumber the
14518 ordered list.
14520 - If the cursor is on a checkbox, toggle it."
14521 (interactive "P")
14522 (let ((org-enable-table-editor t))
14523 (cond
14524 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
14525 org-occur-highlights
14526 org-latex-fragment-image-overlays)
14527 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
14528 (org-remove-occur-highlights)
14529 (org-remove-latex-fragment-image-overlays)
14530 (message "Temporary highlights/overlays removed from current buffer"))
14531 ((and (local-variable-p 'org-finish-function (current-buffer))
14532 (fboundp org-finish-function))
14533 (funcall org-finish-function))
14534 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
14535 ((org-at-property-p)
14536 (call-interactively 'org-property-action))
14537 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
14538 ((org-on-heading-p) (call-interactively 'org-set-tags))
14539 ((org-at-table.el-p)
14540 (require 'table)
14541 (beginning-of-line 1)
14542 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
14543 (call-interactively 'table-recognize-table))
14544 ((org-at-table-p)
14545 (org-table-maybe-eval-formula)
14546 (if arg
14547 (call-interactively 'org-table-recalculate)
14548 (org-table-maybe-recalculate-line))
14549 (call-interactively 'org-table-align))
14550 ((or (org-footnote-at-reference-p)
14551 (org-footnote-at-definition-p))
14552 (call-interactively 'org-footnote-action))
14553 ((org-at-item-checkbox-p)
14554 (call-interactively 'org-toggle-checkbox))
14555 ((org-at-item-p)
14556 (if arg
14557 (call-interactively 'org-toggle-checkbox)
14558 (call-interactively 'org-maybe-renumber-ordered-list)))
14559 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
14560 ;; Dynamic block
14561 (beginning-of-line 1)
14562 (save-excursion (org-update-dblock)))
14563 ((save-excursion
14564 (beginning-of-line 1)
14565 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
14566 (cond
14567 ((equal (match-string 1) "TBLFM")
14568 ;; Recalculate the table before this line
14569 (save-excursion
14570 (beginning-of-line 1)
14571 (skip-chars-backward " \r\n\t")
14572 (if (org-at-table-p)
14573 (org-call-with-arg 'org-table-recalculate t))))
14575 ; (org-set-regexps-and-options)
14576 ; (org-restart-font-lock)
14577 (let ((org-inhibit-startup t)) (org-mode-restart))
14578 (message "Local setup has been refreshed"))))
14579 ((org-clock-update-time-maybe))
14580 (t (error "C-c C-c can do nothing useful at this location.")))))
14582 (defun org-mode-restart ()
14583 "Restart Org-mode, to scan again for special lines.
14584 Also updates the keyword regular expressions."
14585 (interactive)
14586 (org-mode)
14587 (message "Org-mode restarted"))
14589 (defun org-kill-note-or-show-branches ()
14590 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
14591 (interactive)
14592 (if (not org-finish-function)
14593 (call-interactively 'show-branches)
14594 (let ((org-note-abort t))
14595 (funcall org-finish-function))))
14597 (defun org-return (&optional indent)
14598 "Goto next table row or insert a newline.
14599 Calls `org-table-next-row' or `newline', depending on context.
14600 See the individual commands for more information."
14601 (interactive)
14602 (cond
14603 ((bobp) (if indent (newline-and-indent) (newline)))
14604 ((org-at-table-p)
14605 (org-table-justify-field-maybe)
14606 (call-interactively 'org-table-next-row))
14607 ((and org-return-follows-link
14608 (eq (get-text-property (point) 'face) 'org-link))
14609 (call-interactively 'org-open-at-point))
14610 ((and (org-at-heading-p)
14611 (looking-at
14612 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
14613 (org-show-entry)
14614 (end-of-line 1)
14615 (newline))
14616 (t (if indent (newline-and-indent) (newline)))))
14618 (defun org-return-indent ()
14619 "Goto next table row or insert a newline and indent.
14620 Calls `org-table-next-row' or `newline-and-indent', depending on
14621 context. See the individual commands for more information."
14622 (interactive)
14623 (org-return t))
14625 (defun org-ctrl-c-star ()
14626 "Compute table, or change heading status of lines.
14627 Calls `org-table-recalculate' or `org-toggle-heading',
14628 depending on context."
14629 (interactive)
14630 (cond
14631 ((org-at-table-p)
14632 (call-interactively 'org-table-recalculate))
14634 ;; Convert all lines in region to list items
14635 (call-interactively 'org-toggle-heading))))
14637 (defun org-ctrl-c-minus ()
14638 "Insert separator line in table or modify bullet status of line.
14639 Also turns a plain line or a region of lines into list items.
14640 Calls `org-table-insert-hline', `org-toggle-item', or
14641 `org-cycle-list-bullet', depending on context."
14642 (interactive)
14643 (cond
14644 ((org-at-table-p)
14645 (call-interactively 'org-table-insert-hline))
14646 ((org-region-active-p)
14647 (call-interactively 'org-toggle-item))
14648 ((org-in-item-p)
14649 (call-interactively 'org-cycle-list-bullet))
14651 (call-interactively 'org-toggle-item))))
14653 (defun org-toggle-item ()
14654 "Convert headings or normal lines to items, items to normal lines.
14655 If there is no active region, only the current line is considered.
14657 If the first line in the region is a headline, convert all headlines to items.
14659 If the first line in the region is an item, convert all items to normal lines.
14661 If the first line is normal text, add an item bullet to each line."
14662 (interactive)
14663 (let (l2 l beg end)
14664 (if (org-region-active-p)
14665 (setq beg (region-beginning) end (region-end))
14666 (setq beg (point-at-bol)
14667 end (min (1+ (point-at-eol)) (point-max))))
14668 (save-excursion
14669 (goto-char end)
14670 (setq l2 (org-current-line))
14671 (goto-char beg)
14672 (beginning-of-line 1)
14673 (setq l (1- (org-current-line)))
14674 (if (org-at-item-p)
14675 ;; We already have items, de-itemize
14676 (while (< (setq l (1+ l)) l2)
14677 (when (org-at-item-p)
14678 (goto-char (match-beginning 2))
14679 (delete-region (match-beginning 2) (match-end 2))
14680 (and (looking-at "[ \t]+") (replace-match "")))
14681 (beginning-of-line 2))
14682 (if (org-on-heading-p)
14683 ;; Headings, convert to items
14684 (while (< (setq l (1+ l)) l2)
14685 (if (looking-at org-outline-regexp)
14686 (replace-match "- " t t))
14687 (beginning-of-line 2))
14688 ;; normal lines, turn them into items
14689 (while (< (setq l (1+ l)) l2)
14690 (unless (org-at-item-p)
14691 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14692 (replace-match "\\1- \\2")))
14693 (beginning-of-line 2)))))))
14695 (defun org-toggle-heading (&optional nstars)
14696 "Convert headings to normal text, or items or text to headings.
14697 If there is no active region, only the current line is considered.
14699 If the first line is a heading, remove the stars from all headlines
14700 in the region.
14702 If the first line is a plain list item, turn all plain list items into
14703 headings.
14705 If the first line is a normal line, turn each and every line in the region
14706 into a heading.
14708 When converting a line into a heading, the number of stars is chosen
14709 such that the lines become children of the current entry. However, when
14710 a prefix argument is given, its value determines the number of stars to add."
14711 (interactive "P")
14712 (let (l2 l itemp beg end)
14713 (if (org-region-active-p)
14714 (setq beg (region-beginning) end (region-end))
14715 (setq beg (point-at-bol)
14716 end (min (1+ (point-at-eol)) (point-max))))
14717 (save-excursion
14718 (goto-char end)
14719 (setq l2 (org-current-line))
14720 (goto-char beg)
14721 (beginning-of-line 1)
14722 (setq l (1- (org-current-line)))
14723 (if (org-on-heading-p)
14724 ;; We already have headlines, de-star them
14725 (while (< (setq l (1+ l)) l2)
14726 (when (org-on-heading-p t)
14727 (and (looking-at outline-regexp) (replace-match "")))
14728 (beginning-of-line 2))
14729 (setq itemp (org-at-item-p))
14730 (let* ((stars
14731 (if nstars
14732 (make-string (prefix-numeric-value current-prefix-arg)
14734 (save-excursion
14735 (re-search-backward org-complex-heading-regexp nil t)
14736 (or (match-string 1) ""))))
14737 (add-stars (cond (nstars "")
14738 ((equal stars "") "*")
14739 (org-odd-levels-only "**")
14740 (t "*")))
14741 (rpl (concat stars add-stars " ")))
14742 (while (< (setq l (1+ l)) l2)
14743 (if itemp
14744 (and (org-at-item-p) (replace-match rpl t t))
14745 (unless (org-on-heading-p)
14746 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14747 (replace-match (concat rpl (match-string 2))))))
14748 (beginning-of-line 2)))))))
14750 (defun org-meta-return (&optional arg)
14751 "Insert a new heading or wrap a region in a table.
14752 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
14753 See the individual commands for more information."
14754 (interactive "P")
14755 (cond
14756 ((run-hook-with-args-until-success 'org-metareturn-hook))
14757 ((org-at-table-p)
14758 (call-interactively 'org-table-wrap-region))
14759 (t (call-interactively 'org-insert-heading))))
14761 ;;; Menu entries
14763 ;; Define the Org-mode menus
14764 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
14765 '("Tbl"
14766 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
14767 ["Next Field" org-cycle (org-at-table-p)]
14768 ["Previous Field" org-shifttab (org-at-table-p)]
14769 ["Next Row" org-return (org-at-table-p)]
14770 "--"
14771 ["Blank Field" org-table-blank-field (org-at-table-p)]
14772 ["Edit Field" org-table-edit-field (org-at-table-p)]
14773 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
14774 "--"
14775 ("Column"
14776 ["Move Column Left" org-metaleft (org-at-table-p)]
14777 ["Move Column Right" org-metaright (org-at-table-p)]
14778 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
14779 ["Insert Column" org-shiftmetaright (org-at-table-p)])
14780 ("Row"
14781 ["Move Row Up" org-metaup (org-at-table-p)]
14782 ["Move Row Down" org-metadown (org-at-table-p)]
14783 ["Delete Row" org-shiftmetaup (org-at-table-p)]
14784 ["Insert Row" org-shiftmetadown (org-at-table-p)]
14785 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
14786 "--"
14787 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
14788 ("Rectangle"
14789 ["Copy Rectangle" org-copy-special (org-at-table-p)]
14790 ["Cut Rectangle" org-cut-special (org-at-table-p)]
14791 ["Paste Rectangle" org-paste-special (org-at-table-p)]
14792 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
14793 "--"
14794 ("Calculate"
14795 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
14796 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
14797 ["Edit Formulas" org-edit-special (org-at-table-p)]
14798 "--"
14799 ["Recalculate line" org-table-recalculate (org-at-table-p)]
14800 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
14801 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
14802 "--"
14803 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
14804 "--"
14805 ["Sum Column/Rectangle" org-table-sum
14806 (or (org-at-table-p) (org-region-active-p))]
14807 ["Which Column?" org-table-current-column (org-at-table-p)])
14808 ["Debug Formulas"
14809 org-table-toggle-formula-debugger
14810 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
14811 ["Show Col/Row Numbers"
14812 org-table-toggle-coordinate-overlays
14813 :style toggle
14814 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
14815 "--"
14816 ["Create" org-table-create (and (not (org-at-table-p))
14817 org-enable-table-editor)]
14818 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
14819 ["Import from File" org-table-import (not (org-at-table-p))]
14820 ["Export to File" org-table-export (org-at-table-p)]
14821 "--"
14822 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
14824 (easy-menu-define org-org-menu org-mode-map "Org menu"
14825 '("Org"
14826 ("Show/Hide"
14827 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
14828 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
14829 ["Sparse Tree..." org-sparse-tree t]
14830 ["Reveal Context" org-reveal t]
14831 ["Show All" show-all t]
14832 "--"
14833 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
14834 "--"
14835 ["New Heading" org-insert-heading t]
14836 ("Navigate Headings"
14837 ["Up" outline-up-heading t]
14838 ["Next" outline-next-visible-heading t]
14839 ["Previous" outline-previous-visible-heading t]
14840 ["Next Same Level" outline-forward-same-level t]
14841 ["Previous Same Level" outline-backward-same-level t]
14842 "--"
14843 ["Jump" org-goto t])
14844 ("Edit Structure"
14845 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
14846 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
14847 "--"
14848 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
14849 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
14850 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
14851 "--"
14852 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
14853 "--"
14854 ["Promote Heading" org-metaleft (not (org-at-table-p))]
14855 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
14856 ["Demote Heading" org-metaright (not (org-at-table-p))]
14857 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
14858 "--"
14859 ["Sort Region/Children" org-sort (not (org-at-table-p))]
14860 "--"
14861 ["Convert to odd levels" org-convert-to-odd-levels t]
14862 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
14863 ("Editing"
14864 ["Emphasis..." org-emphasize t]
14865 ["Edit Source Example" org-edit-special t]
14866 "--"
14867 ["Footnote new/jump" org-footnote-action t]
14868 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
14869 ("Archive"
14870 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
14871 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
14872 ; :active t :keys "C-u C-c C-x C-a"]
14873 ["Sparse trees open ARCHIVE trees"
14874 (setq org-sparse-tree-open-archived-trees
14875 (not org-sparse-tree-open-archived-trees))
14876 :style toggle :selected org-sparse-tree-open-archived-trees]
14877 ["Cycling opens ARCHIVE trees"
14878 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
14879 :style toggle :selected org-cycle-open-archived-trees]
14880 "--"
14881 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
14882 ["Move Subtree to Archive" org-advertized-archive-subtree t]
14883 ; ["Check and Move Children" (org-archive-subtree '(4))
14884 ; :active t :keys "C-u C-c C-x C-s"]
14886 "--"
14887 ("Hyperlinks"
14888 ["Store Link (Global)" org-store-link t]
14889 ["Insert Link" org-insert-link t]
14890 ["Follow Link" org-open-at-point t]
14891 "--"
14892 ["Next link" org-next-link t]
14893 ["Previous link" org-previous-link t]
14894 "--"
14895 ["Descriptive Links"
14896 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
14897 :style radio
14898 :selected (member '(org-link) buffer-invisibility-spec)]
14899 ["Literal Links"
14900 (progn
14901 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
14902 :style radio
14903 :selected (not (member '(org-link) buffer-invisibility-spec))])
14904 "--"
14905 ("TODO Lists"
14906 ["TODO/DONE/-" org-todo t]
14907 ("Select keyword"
14908 ["Next keyword" org-shiftright (org-on-heading-p)]
14909 ["Previous keyword" org-shiftleft (org-on-heading-p)]
14910 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
14911 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
14912 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
14913 ["Show TODO Tree" org-show-todo-tree t]
14914 ["Global TODO list" org-todo-list t]
14915 "--"
14916 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
14917 :selected org-enforce-todo-dependencies :style toggle :active t]
14918 "Settings for tree at point"
14919 ["Do Children sequentially" org-toggle-ordered-property :style radio
14920 :selected (ignore-errors (org-entry-get nil "ORDERED"))
14921 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14922 ["Do Children parallel" org-toggle-ordered-property :style radio
14923 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
14924 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14925 "--"
14926 ["Set Priority" org-priority t]
14927 ["Priority Up" org-shiftup t]
14928 ["Priority Down" org-shiftdown t]
14929 "--"
14930 ["Get news from all feeds" org-feed-update-all t]
14931 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
14932 ["Customize feeds" (customize-variable 'org-feed-alist) t])
14933 ("TAGS and Properties"
14934 ["Set Tags" org-set-tags-command t]
14935 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
14936 "--"
14937 ["Set property" org-set-property t]
14938 ["Column view of properties" org-columns t]
14939 ["Insert Column View DBlock" org-insert-columns-dblock t])
14940 ("Dates and Scheduling"
14941 ["Timestamp" org-time-stamp t]
14942 ["Timestamp (inactive)" org-time-stamp-inactive t]
14943 ("Change Date"
14944 ["1 Day Later" org-shiftright t]
14945 ["1 Day Earlier" org-shiftleft t]
14946 ["1 ... Later" org-shiftup t]
14947 ["1 ... Earlier" org-shiftdown t])
14948 ["Compute Time Range" org-evaluate-time-range t]
14949 ["Schedule Item" org-schedule t]
14950 ["Deadline" org-deadline t]
14951 "--"
14952 ["Custom time format" org-toggle-time-stamp-overlays
14953 :style radio :selected org-display-custom-times]
14954 "--"
14955 ["Goto Calendar" org-goto-calendar t]
14956 ["Date from Calendar" org-date-from-calendar t]
14957 "--"
14958 ["Start/Restart Timer" org-timer-start t]
14959 ["Pause/Continue Timer" org-timer-pause-or-continue t]
14960 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
14961 ["Insert Timer String" org-timer t]
14962 ["Insert Timer Item" org-timer-item t])
14963 ("Logging work"
14964 ["Clock in" org-clock-in t]
14965 ["Clock out" org-clock-out t]
14966 ["Clock cancel" org-clock-cancel t]
14967 ["Goto running clock" org-clock-goto t]
14968 ["Display times" org-clock-display t]
14969 ["Create clock table" org-clock-report t]
14970 "--"
14971 ["Record DONE time"
14972 (progn (setq org-log-done (not org-log-done))
14973 (message "Switching to %s will %s record a timestamp"
14974 (car org-done-keywords)
14975 (if org-log-done "automatically" "not")))
14976 :style toggle :selected org-log-done])
14977 "--"
14978 ["Agenda Command..." org-agenda t]
14979 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
14980 ("File List for Agenda")
14981 ("Special views current file"
14982 ["TODO Tree" org-show-todo-tree t]
14983 ["Check Deadlines" org-check-deadlines t]
14984 ["Timeline" org-timeline t]
14985 ["Tags/Property tree" org-match-sparse-tree t])
14986 "--"
14987 ["Export/Publish..." org-export t]
14988 ("LaTeX"
14989 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
14990 :selected org-cdlatex-mode]
14991 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
14992 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
14993 ["Modify math symbol" org-cdlatex-math-modify
14994 (org-inside-LaTeX-fragment-p)]
14995 ["Insert citation" org-reftex-citation t]
14996 "--"
14997 ["Export LaTeX fragments as images"
14998 (if (featurep 'org-exp)
14999 (setq org-export-with-LaTeX-fragments
15000 (not org-export-with-LaTeX-fragments))
15001 (require 'org-exp))
15002 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
15003 org-export-with-LaTeX-fragments)])
15004 "--"
15005 ("Documentation"
15006 ["Show Version" org-version t]
15007 ["Info Documentation" org-info t])
15008 ("Customize"
15009 ["Browse Org Group" org-customize t]
15010 "--"
15011 ["Expand This Menu" org-create-customize-menu
15012 (fboundp 'customize-menu-create)])
15013 "--"
15014 ("Refresh/Reload"
15015 ["Refresh setup current buffer" org-mode-restart t]
15016 ["Reload Org (after update)" org-reload t]
15017 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
15020 (defun org-info (&optional node)
15021 "Read documentation for Org-mode in the info system.
15022 With optional NODE, go directly to that node."
15023 (interactive)
15024 (info (format "(org)%s" (or node ""))))
15026 (defun org-install-agenda-files-menu ()
15027 (let ((bl (buffer-list)))
15028 (save-excursion
15029 (while bl
15030 (set-buffer (pop bl))
15031 (if (org-mode-p) (setq bl nil)))
15032 (when (org-mode-p)
15033 (easy-menu-change
15034 '("Org") "File List for Agenda"
15035 (append
15036 (list
15037 ["Edit File List" (org-edit-agenda-file-list) t]
15038 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
15039 ["Remove Current File from List" org-remove-file t]
15040 ["Cycle through agenda files" org-cycle-agenda-files t]
15041 ["Occur in all agenda files" org-occur-in-agenda-files t]
15042 "--")
15043 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
15045 ;;;; Documentation
15047 ;;;###autoload
15048 (defun org-require-autoloaded-modules ()
15049 (interactive)
15050 (mapc 'require
15051 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
15052 org-docbook org-exp org-html org-icalendar
15053 org-id org-latex
15054 org-publish org-remember org-table
15055 org-timer org-xoxo)))
15057 ;;;###autoload
15058 (defun org-reload (&optional uncompiled)
15059 "Reload all org lisp files.
15060 With prefix arg UNCOMPILED, load the uncompiled versions."
15061 (interactive "P")
15062 (require 'find-func)
15063 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
15064 (dir-org (file-name-directory (org-find-library-name "org")))
15065 (dir-org-contrib (ignore-errors
15066 (file-name-directory
15067 (org-find-library-name "org-contribdir"))))
15068 (files
15069 (append (directory-files dir-org t file-re)
15070 (and dir-org-contrib
15071 (directory-files dir-org-contrib t file-re))))
15072 (remove-re (concat (if (featurep 'xemacs)
15073 "org-colview" "org-colview-xemacs")
15074 "\\'")))
15075 (setq files (mapcar 'file-name-sans-extension files))
15076 (setq files (mapcar
15077 (lambda (x) (if (string-match remove-re x) nil x))
15078 files))
15079 (setq files (delq nil files))
15080 (mapc
15081 (lambda (f)
15082 (when (featurep (intern (file-name-nondirectory f)))
15083 (if (and (not uncompiled)
15084 (file-exists-p (concat f ".elc")))
15085 (load (concat f ".elc") nil nil t)
15086 (load (concat f ".el") nil nil t))))
15087 files))
15088 (org-version))
15090 ;;;###autoload
15091 (defun org-customize ()
15092 "Call the customize function with org as argument."
15093 (interactive)
15094 (org-load-modules-maybe)
15095 (org-require-autoloaded-modules)
15096 (customize-browse 'org))
15098 (defun org-create-customize-menu ()
15099 "Create a full customization menu for Org-mode, insert it into the menu."
15100 (interactive)
15101 (org-load-modules-maybe)
15102 (org-require-autoloaded-modules)
15103 (if (fboundp 'customize-menu-create)
15104 (progn
15105 (easy-menu-change
15106 '("Org") "Customize"
15107 `(["Browse Org group" org-customize t]
15108 "--"
15109 ,(customize-menu-create 'org)
15110 ["Set" Custom-set t]
15111 ["Save" Custom-save t]
15112 ["Reset to Current" Custom-reset-current t]
15113 ["Reset to Saved" Custom-reset-saved t]
15114 ["Reset to Standard Settings" Custom-reset-standard t]))
15115 (message "\"Org\"-menu now contains full customization menu"))
15116 (error "Cannot expand menu (outdated version of cus-edit.el)")))
15118 ;;;; Miscellaneous stuff
15120 ;;; Generally useful functions
15122 (defun org-find-text-property-in-string (prop s)
15123 "Return the first non-nil value of property PROP in string S."
15124 (or (get-text-property 0 prop s)
15125 (get-text-property (or (next-single-property-change 0 prop s) 0)
15126 prop s)))
15128 (defun org-display-warning (message) ;; Copied from Emacs-Muse
15129 "Display the given MESSAGE as a warning."
15130 (if (fboundp 'display-warning)
15131 (display-warning 'org message
15132 (if (featurep 'xemacs)
15133 'warning
15134 :warning))
15135 (let ((buf (get-buffer-create "*Org warnings*")))
15136 (with-current-buffer buf
15137 (goto-char (point-max))
15138 (insert "Warning (Org): " message)
15139 (unless (bolp)
15140 (newline)))
15141 (display-buffer buf)
15142 (sit-for 0))))
15144 (defun org-goto-marker-or-bmk (marker &optional bookmark)
15145 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
15146 (if (and marker (marker-buffer marker)
15147 (buffer-live-p (marker-buffer marker)))
15148 (progn
15149 (switch-to-buffer (marker-buffer marker))
15150 (if (or (> marker (point-max)) (< marker (point-min)))
15151 (widen))
15152 (goto-char marker)
15153 (org-show-context 'org-goto))
15154 (if bookmark
15155 (bookmark-jump bookmark)
15156 (error "Cannot find location"))))
15158 (defun org-quote-csv-field (s)
15159 "Quote field for inclusion in CSV material."
15160 (if (string-match "[\",]" s)
15161 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
15164 (defun org-plist-delete (plist property)
15165 "Delete PROPERTY from PLIST.
15166 This is in contrast to merely setting it to 0."
15167 (let (p)
15168 (while plist
15169 (if (not (eq property (car plist)))
15170 (setq p (plist-put p (car plist) (nth 1 plist))))
15171 (setq plist (cddr plist)))
15174 (defun org-force-self-insert (N)
15175 "Needed to enforce self-insert under remapping."
15176 (interactive "p")
15177 (self-insert-command N))
15179 (defun org-string-width (s)
15180 "Compute width of string, ignoring invisible characters.
15181 This ignores character with invisibility property `org-link', and also
15182 characters with property `org-cwidth', because these will become invisible
15183 upon the next fontification round."
15184 (let (b l)
15185 (when (or (eq t buffer-invisibility-spec)
15186 (assq 'org-link buffer-invisibility-spec))
15187 (while (setq b (text-property-any 0 (length s)
15188 'invisible 'org-link s))
15189 (setq s (concat (substring s 0 b)
15190 (substring s (or (next-single-property-change
15191 b 'invisible s) (length s)))))))
15192 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
15193 (setq s (concat (substring s 0 b)
15194 (substring s (or (next-single-property-change
15195 b 'org-cwidth s) (length s))))))
15196 (setq l (string-width s) b -1)
15197 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
15198 (setq l (- l (get-text-property b 'org-dwidth-n s))))
15201 (defun org-get-indentation (&optional line)
15202 "Get the indentation of the current line, interpreting tabs.
15203 When LINE is given, assume it represents a line and compute its indentation."
15204 (if line
15205 (if (string-match "^ *" (org-remove-tabs line))
15206 (match-end 0))
15207 (save-excursion
15208 (beginning-of-line 1)
15209 (skip-chars-forward " \t")
15210 (current-column))))
15212 (defun org-remove-tabs (s &optional width)
15213 "Replace tabulators in S with spaces.
15214 Assumes that s is a single line, starting in column 0."
15215 (setq width (or width tab-width))
15216 (while (string-match "\t" s)
15217 (setq s (replace-match
15218 (make-string
15219 (- (* width (/ (+ (match-beginning 0) width) width))
15220 (match-beginning 0)) ?\ )
15221 t t s)))
15224 (defun org-fix-indentation (line ind)
15225 "Fix indentation in LINE.
15226 IND is a cons cell with target and minimum indentation.
15227 If the current indentation in LINE is smaller than the minimum,
15228 leave it alone. If it is larger than ind, set it to the target."
15229 (let* ((l (org-remove-tabs line))
15230 (i (org-get-indentation l))
15231 (i1 (car ind)) (i2 (cdr ind)))
15232 (if (>= i i2) (setq l (substring line i2)))
15233 (if (> i1 0)
15234 (concat (make-string i1 ?\ ) l)
15235 l)))
15237 (defun org-remove-indentation (code &optional n)
15238 "Remove the maximum common indentation from the lines in CODE.
15239 N may optionally be the number of spaces to remove."
15240 (with-temp-buffer
15241 (insert code)
15242 (org-do-remove-indentation n)
15243 (buffer-string)))
15245 (defun org-do-remove-indentation (&optional n)
15246 "Remove the maximum common indentation from the buffer."
15247 (untabify (point-min) (point-max))
15248 (let ((min 10000) re)
15249 (if n
15250 (setq min n)
15251 (goto-char (point-min))
15252 (while (re-search-forward "^ *[^ \n]" nil t)
15253 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
15254 (unless (or (= min 0) (= min 10000))
15255 (setq re (format "^ \\{%d\\}" min))
15256 (goto-char (point-min))
15257 (while (re-search-forward re nil t)
15258 (replace-match "")
15259 (end-of-line 1))
15260 min)))
15262 (defun org-base-buffer (buffer)
15263 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
15264 (if (not buffer)
15265 buffer
15266 (or (buffer-base-buffer buffer)
15267 buffer)))
15269 (defun org-trim (s)
15270 "Remove whitespace at beginning and end of string."
15271 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
15272 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
15275 (defun org-wrap (string &optional width lines)
15276 "Wrap string to either a number of lines, or a width in characters.
15277 If WIDTH is non-nil, the string is wrapped to that width, however many lines
15278 that costs. If there is a word longer than WIDTH, the text is actually
15279 wrapped to the length of that word.
15280 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
15281 many lines, whatever width that takes.
15282 The return value is a list of lines, without newlines at the end."
15283 (let* ((words (org-split-string string "[ \t\n]+"))
15284 (maxword (apply 'max (mapcar 'org-string-width words)))
15285 w ll)
15286 (cond (width
15287 (org-do-wrap words (max maxword width)))
15288 (lines
15289 (setq w maxword)
15290 (setq ll (org-do-wrap words maxword))
15291 (if (<= (length ll) lines)
15293 (setq ll words)
15294 (while (> (length ll) lines)
15295 (setq w (1+ w))
15296 (setq ll (org-do-wrap words w)))
15297 ll))
15298 (t (error "Cannot wrap this")))))
15300 (defun org-do-wrap (words width)
15301 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
15302 (let (lines line)
15303 (while words
15304 (setq line (pop words))
15305 (while (and words (< (+ (length line) (length (car words))) width))
15306 (setq line (concat line " " (pop words))))
15307 (setq lines (push line lines)))
15308 (nreverse lines)))
15310 (defun org-split-string (string &optional separators)
15311 "Splits STRING into substrings at SEPARATORS.
15312 No empty strings are returned if there are matches at the beginning
15313 and end of string."
15314 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
15315 (start 0)
15316 notfirst
15317 (list nil))
15318 (while (and (string-match rexp string
15319 (if (and notfirst
15320 (= start (match-beginning 0))
15321 (< start (length string)))
15322 (1+ start) start))
15323 (< (match-beginning 0) (length string)))
15324 (setq notfirst t)
15325 (or (eq (match-beginning 0) 0)
15326 (and (eq (match-beginning 0) (match-end 0))
15327 (eq (match-beginning 0) start))
15328 (setq list
15329 (cons (substring string start (match-beginning 0))
15330 list)))
15331 (setq start (match-end 0)))
15332 (or (eq start (length string))
15333 (setq list
15334 (cons (substring string start)
15335 list)))
15336 (nreverse list)))
15338 (defun org-uuidgen-p (s)
15339 "Is S an ID created by UUIDGEN?"
15340 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
15342 (defun org-context ()
15343 "Return a list of contexts of the current cursor position.
15344 If several contexts apply, all are returned.
15345 Each context entry is a list with a symbol naming the context, and
15346 two positions indicating start and end of the context. Possible
15347 contexts are:
15349 :headline anywhere in a headline
15350 :headline-stars on the leading stars in a headline
15351 :todo-keyword on a TODO keyword (including DONE) in a headline
15352 :tags on the TAGS in a headline
15353 :priority on the priority cookie in a headline
15354 :item on the first line of a plain list item
15355 :item-bullet on the bullet/number of a plain list item
15356 :checkbox on the checkbox in a plain list item
15357 :table in an org-mode table
15358 :table-special on a special filed in a table
15359 :table-table in a table.el table
15360 :link on a hyperlink
15361 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
15362 :target on a <<target>>
15363 :radio-target on a <<<radio-target>>>
15364 :latex-fragment on a LaTeX fragment
15365 :latex-preview on a LaTeX fragment with overlayed preview image
15367 This function expects the position to be visible because it uses font-lock
15368 faces as a help to recognize the following contexts: :table-special, :link,
15369 and :keyword."
15370 (let* ((f (get-text-property (point) 'face))
15371 (faces (if (listp f) f (list f)))
15372 (p (point)) clist o)
15373 ;; First the large context
15374 (cond
15375 ((org-on-heading-p t)
15376 (push (list :headline (point-at-bol) (point-at-eol)) clist)
15377 (when (progn
15378 (beginning-of-line 1)
15379 (looking-at org-todo-line-tags-regexp))
15380 (push (org-point-in-group p 1 :headline-stars) clist)
15381 (push (org-point-in-group p 2 :todo-keyword) clist)
15382 (push (org-point-in-group p 4 :tags) clist))
15383 (goto-char p)
15384 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
15385 (if (looking-at "\\[#[A-Z0-9]\\]")
15386 (push (org-point-in-group p 0 :priority) clist)))
15388 ((org-at-item-p)
15389 (push (org-point-in-group p 2 :item-bullet) clist)
15390 (push (list :item (point-at-bol)
15391 (save-excursion (org-end-of-item) (point)))
15392 clist)
15393 (and (org-at-item-checkbox-p)
15394 (push (org-point-in-group p 0 :checkbox) clist)))
15396 ((org-at-table-p)
15397 (push (list :table (org-table-begin) (org-table-end)) clist)
15398 (if (memq 'org-formula faces)
15399 (push (list :table-special
15400 (previous-single-property-change p 'face)
15401 (next-single-property-change p 'face)) clist)))
15402 ((org-at-table-p 'any)
15403 (push (list :table-table) clist)))
15404 (goto-char p)
15406 ;; Now the small context
15407 (cond
15408 ((org-at-timestamp-p)
15409 (push (org-point-in-group p 0 :timestamp) clist))
15410 ((memq 'org-link faces)
15411 (push (list :link
15412 (previous-single-property-change p 'face)
15413 (next-single-property-change p 'face)) clist))
15414 ((memq 'org-special-keyword faces)
15415 (push (list :keyword
15416 (previous-single-property-change p 'face)
15417 (next-single-property-change p 'face)) clist))
15418 ((org-on-target-p)
15419 (push (org-point-in-group p 0 :target) clist)
15420 (goto-char (1- (match-beginning 0)))
15421 (if (looking-at org-radio-target-regexp)
15422 (push (org-point-in-group p 0 :radio-target) clist))
15423 (goto-char p))
15424 ((setq o (car (delq nil
15425 (mapcar
15426 (lambda (x)
15427 (if (memq x org-latex-fragment-image-overlays) x))
15428 (org-overlays-at (point))))))
15429 (push (list :latex-fragment
15430 (org-overlay-start o) (org-overlay-end o)) clist)
15431 (push (list :latex-preview
15432 (org-overlay-start o) (org-overlay-end o)) clist))
15433 ((org-inside-LaTeX-fragment-p)
15434 ;; FIXME: positions wrong.
15435 (push (list :latex-fragment (point) (point)) clist)))
15437 (setq clist (nreverse (delq nil clist)))
15438 clist))
15440 ;; FIXME: Compare with at-regexp-p Do we need both?
15441 (defun org-in-regexp (re &optional nlines visually)
15442 "Check if point is inside a match of regexp.
15443 Normally only the current line is checked, but you can include NLINES extra
15444 lines both before and after point into the search.
15445 If VISUALLY is set, require that the cursor is not after the match but
15446 really on, so that the block visually is on the match."
15447 (catch 'exit
15448 (let ((pos (point))
15449 (eol (point-at-eol (+ 1 (or nlines 0))))
15450 (inc (if visually 1 0)))
15451 (save-excursion
15452 (beginning-of-line (- 1 (or nlines 0)))
15453 (while (re-search-forward re eol t)
15454 (if (and (<= (match-beginning 0) pos)
15455 (>= (+ inc (match-end 0)) pos))
15456 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
15458 (defun org-at-regexp-p (regexp)
15459 "Is point inside a match of REGEXP in the current line?"
15460 (catch 'exit
15461 (save-excursion
15462 (let ((pos (point)) (end (point-at-eol)))
15463 (beginning-of-line 1)
15464 (while (re-search-forward regexp end t)
15465 (if (and (<= (match-beginning 0) pos)
15466 (>= (match-end 0) pos))
15467 (throw 'exit t)))
15468 nil))))
15470 (defun org-occur-in-agenda-files (regexp &optional nlines)
15471 "Call `multi-occur' with buffers for all agenda files."
15472 (interactive "sOrg-files matching: \np")
15473 (let* ((files (org-agenda-files))
15474 (tnames (mapcar 'file-truename files))
15475 (extra org-agenda-text-search-extra-files)
15477 (when (eq (car extra) 'agenda-archives)
15478 (setq extra (cdr extra))
15479 (setq files (org-add-archive-files files)))
15480 (while (setq f (pop extra))
15481 (unless (member (file-truename f) tnames)
15482 (add-to-list 'files f 'append)
15483 (add-to-list 'tnames (file-truename f) 'append)))
15484 (multi-occur
15485 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
15486 regexp)))
15488 (if (boundp 'occur-mode-find-occurrence-hook)
15489 ;; Emacs 23
15490 (add-hook 'occur-mode-find-occurrence-hook
15491 (lambda ()
15492 (when (org-mode-p)
15493 (org-reveal))))
15494 ;; Emacs 22
15495 (defadvice occur-mode-goto-occurrence
15496 (after org-occur-reveal activate)
15497 (and (org-mode-p) (org-reveal)))
15498 (defadvice occur-mode-goto-occurrence-other-window
15499 (after org-occur-reveal activate)
15500 (and (org-mode-p) (org-reveal)))
15501 (defadvice occur-mode-display-occurrence
15502 (after org-occur-reveal activate)
15503 (when (org-mode-p)
15504 (let ((pos (occur-mode-find-occurrence)))
15505 (with-current-buffer (marker-buffer pos)
15506 (save-excursion
15507 (goto-char pos)
15508 (org-reveal)))))))
15510 (defun org-uniquify (list)
15511 "Remove duplicate elements from LIST."
15512 (let (res)
15513 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
15514 res))
15516 (defun org-delete-all (elts list)
15517 "Remove all elements in ELTS from LIST."
15518 (while elts
15519 (setq list (delete (pop elts) list)))
15520 list)
15522 (defun org-back-over-empty-lines ()
15523 "Move backwards over whitespace, to the beginning of the first empty line.
15524 Returns the number of empty lines passed."
15525 (let ((pos (point)))
15526 (skip-chars-backward " \t\n\r")
15527 (beginning-of-line 2)
15528 (goto-char (min (point) pos))
15529 (count-lines (point) pos)))
15531 (defun org-skip-whitespace ()
15532 (skip-chars-forward " \t\n\r"))
15534 (defun org-point-in-group (point group &optional context)
15535 "Check if POINT is in match-group GROUP.
15536 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
15537 match. If the match group does ot exist or point is not inside it,
15538 return nil."
15539 (and (match-beginning group)
15540 (>= point (match-beginning group))
15541 (<= point (match-end group))
15542 (if context
15543 (list context (match-beginning group) (match-end group))
15544 t)))
15546 (defun org-switch-to-buffer-other-window (&rest args)
15547 "Switch to buffer in a second window on the current frame.
15548 In particular, do not allow pop-up frames."
15549 (let (pop-up-frames special-display-buffer-names special-display-regexps
15550 special-display-function)
15551 (apply 'switch-to-buffer-other-window args)))
15553 (defun org-combine-plists (&rest plists)
15554 "Create a single property list from all plists in PLISTS.
15555 The process starts by copying the first list, and then setting properties
15556 from the other lists. Settings in the last list are the most significant
15557 ones and overrule settings in the other lists."
15558 (let ((rtn (copy-sequence (pop plists)))
15559 p v ls)
15560 (while plists
15561 (setq ls (pop plists))
15562 (while ls
15563 (setq p (pop ls) v (pop ls))
15564 (setq rtn (plist-put rtn p v))))
15565 rtn))
15567 (defun org-move-line-down (arg)
15568 "Move the current line down. With prefix argument, move it past ARG lines."
15569 (interactive "p")
15570 (let ((col (current-column))
15571 beg end pos)
15572 (beginning-of-line 1) (setq beg (point))
15573 (beginning-of-line 2) (setq end (point))
15574 (beginning-of-line (+ 1 arg))
15575 (setq pos (move-marker (make-marker) (point)))
15576 (insert (delete-and-extract-region beg end))
15577 (goto-char pos)
15578 (org-move-to-column col)))
15580 (defun org-move-line-up (arg)
15581 "Move the current line up. With prefix argument, move it past ARG lines."
15582 (interactive "p")
15583 (let ((col (current-column))
15584 beg end pos)
15585 (beginning-of-line 1) (setq beg (point))
15586 (beginning-of-line 2) (setq end (point))
15587 (beginning-of-line (- arg))
15588 (setq pos (move-marker (make-marker) (point)))
15589 (insert (delete-and-extract-region beg end))
15590 (goto-char pos)
15591 (org-move-to-column col)))
15593 (defun org-replace-escapes (string table)
15594 "Replace %-escapes in STRING with values in TABLE.
15595 TABLE is an association list with keys like \"%a\" and string values.
15596 The sequences in STRING may contain normal field width and padding information,
15597 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
15598 so values can contain further %-escapes if they are define later in TABLE."
15599 (let ((case-fold-search nil)
15600 e re rpl)
15601 (while (setq e (pop table))
15602 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
15603 (while (string-match re string)
15604 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
15605 (cdr e)))
15606 (setq string (replace-match rpl t t string))))
15607 string))
15610 (defun org-sublist (list start end)
15611 "Return a section of LIST, from START to END.
15612 Counting starts at 1."
15613 (let (rtn (c start))
15614 (setq list (nthcdr (1- start) list))
15615 (while (and list (<= c end))
15616 (push (pop list) rtn)
15617 (setq c (1+ c)))
15618 (nreverse rtn)))
15620 (defun org-find-base-buffer-visiting (file)
15621 "Like `find-buffer-visiting' but always return the base buffer and
15622 not an indirect buffer."
15623 (let ((buf (or (get-file-buffer file)
15624 (find-buffer-visiting file))))
15625 (if buf
15626 (or (buffer-base-buffer buf) buf)
15627 nil)))
15629 (defun org-image-file-name-regexp (&optional extensions)
15630 "Return regexp matching the file names of images.
15631 If EXTENSIONS is given, only match these."
15632 (if (and (not extensions) (fboundp 'image-file-name-regexp))
15633 (image-file-name-regexp)
15634 (let ((image-file-name-extensions
15635 (or extensions
15636 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
15637 "xbm" "xpm" "pbm" "pgm" "ppm"))))
15638 (concat "\\."
15639 (regexp-opt (nconc (mapcar 'upcase
15640 image-file-name-extensions)
15641 image-file-name-extensions)
15643 "\\'"))))
15645 (defun org-file-image-p (file &optional extensions)
15646 "Return non-nil if FILE is an image."
15647 (save-match-data
15648 (string-match (org-image-file-name-regexp extensions) file)))
15650 (defun org-get-cursor-date ()
15651 "Return the date at cursor in as a time.
15652 This works in the calendar and in the agenda, anywhere else it just
15653 returns the current time."
15654 (let (date day defd)
15655 (cond
15656 ((eq major-mode 'calendar-mode)
15657 (setq date (calendar-cursor-to-date)
15658 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15659 ((eq major-mode 'org-agenda-mode)
15660 (setq day (get-text-property (point) 'day))
15661 (if day
15662 (setq date (calendar-gregorian-from-absolute day)
15663 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
15664 (nth 2 date))))))
15665 (or defd (current-time))))
15667 (defvar org-agenda-action-marker (make-marker)
15668 "Marker pointing to the entry for the next agenda action.")
15670 (defun org-mark-entry-for-agenda-action ()
15671 "Mark the current entry as target of an agenda action.
15672 Agenda actions are actions executed from the agenda with the key `k',
15673 which make use of the date at the cursor."
15674 (interactive)
15675 (move-marker org-agenda-action-marker
15676 (save-excursion (org-back-to-heading t) (point))
15677 (current-buffer))
15678 (message
15679 "Entry marked for action; press `k' at desired date in agenda or calendar"))
15681 ;;; Paragraph filling stuff.
15682 ;; We want this to be just right, so use the full arsenal.
15684 (defun org-indent-line-function ()
15685 "Indent line like previous, but further if previous was headline or item."
15686 (interactive)
15687 (let* ((pos (point))
15688 (itemp (org-at-item-p))
15689 (case-fold-search t)
15690 (org-drawer-regexp (or org-drawer-regexp "\000"))
15691 column bpos bcol tpos tcol bullet btype bullet-type)
15692 ;; Find the previous relevant line
15693 (beginning-of-line 1)
15694 (cond
15695 ((looking-at "#") (setq column 0))
15696 ((looking-at "\\*+ ") (setq column 0))
15697 ((and (looking-at "[ \t]*:END:")
15698 (save-excursion (re-search-backward org-drawer-regexp nil t)))
15699 (save-excursion
15700 (goto-char (1- (match-beginning 1)))
15701 (setq column (current-column))))
15702 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
15703 (save-excursion
15704 (re-search-backward
15705 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
15706 (setq column (org-get-indentation (match-string 0))))
15708 (beginning-of-line 0)
15709 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
15710 (not (looking-at "[ \t]*:END:"))
15711 (not (looking-at org-drawer-regexp)))
15712 (beginning-of-line 0))
15713 (cond
15714 ((looking-at "\\*+[ \t]+")
15715 (if (not org-adapt-indentation)
15716 (setq column 0)
15717 (goto-char (match-end 0))
15718 (setq column (current-column))))
15719 ((looking-at org-drawer-regexp)
15720 (goto-char (1- (match-beginning 1)))
15721 (setq column (current-column)))
15722 ((looking-at "\\([ \t]*\\):END:")
15723 (goto-char (match-end 1))
15724 (setq column (current-column)))
15725 ((org-in-item-p)
15726 (org-beginning-of-item)
15727 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
15728 (setq bpos (match-beginning 1) tpos (match-end 0)
15729 bcol (progn (goto-char bpos) (current-column))
15730 tcol (progn (goto-char tpos) (current-column))
15731 bullet (match-string 1)
15732 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
15733 (if (> tcol (+ bcol org-description-max-indent))
15734 (setq tcol (+ bcol 5)))
15735 (if (not itemp)
15736 (setq column tcol)
15737 (goto-char pos)
15738 (beginning-of-line 1)
15739 (if (looking-at "\\S-")
15740 (progn
15741 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
15742 (setq bullet (match-string 1)
15743 btype (if (string-match "[0-9]" bullet) "n" bullet))
15744 (setq column (if (equal btype bullet-type) bcol tcol)))
15745 (setq column (org-get-indentation)))))
15746 (t (setq column (org-get-indentation))))))
15747 (goto-char pos)
15748 (if (<= (current-column) (current-indentation))
15749 (org-indent-line-to column)
15750 (save-excursion (org-indent-line-to column)))
15751 (setq column (current-column))
15752 (beginning-of-line 1)
15753 (if (looking-at
15754 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
15755 (replace-match (concat "\\1" (format org-property-format
15756 (match-string 2) (match-string 3)))
15757 t nil))
15758 (org-move-to-column column)))
15760 (defun org-set-autofill-regexps ()
15761 (interactive)
15762 ;; In the paragraph separator we include headlines, because filling
15763 ;; text in a line directly attached to a headline would otherwise
15764 ;; fill the headline as well.
15765 (org-set-local 'comment-start-skip "^#+[ \t]*")
15766 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
15767 ;; The paragraph starter includes hand-formatted lists.
15768 (org-set-local 'paragraph-start
15769 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
15770 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
15771 ;; But only if the user has not turned off tables or fixed-width regions
15772 (org-set-local
15773 'auto-fill-inhibit-regexp
15774 (concat "\\*+ \\|#\\+"
15775 "\\|[ \t]*" org-keyword-time-regexp
15776 (if (or org-enable-table-editor org-enable-fixed-width-editor)
15777 (concat
15778 "\\|[ \t]*["
15779 (if org-enable-table-editor "|" "")
15780 (if org-enable-fixed-width-editor ":" "")
15781 "]"))))
15782 ;; We use our own fill-paragraph function, to make sure that tables
15783 ;; and fixed-width regions are not wrapped. That function will pass
15784 ;; through to `fill-paragraph' when appropriate.
15785 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
15786 ; Adaptive filling: To get full control, first make sure that
15787 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
15788 (org-set-local 'adaptive-fill-regexp "\000")
15789 (org-set-local 'adaptive-fill-function
15790 'org-adaptive-fill-function)
15791 (org-set-local
15792 'align-mode-rules-list
15793 '((org-in-buffer-settings
15794 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
15795 (modes . '(org-mode))))))
15797 (defun org-fill-paragraph (&optional justify)
15798 "Re-align a table, pass through to fill-paragraph if no table."
15799 (let ((table-p (org-at-table-p))
15800 (table.el-p (org-at-table.el-p)))
15801 (cond ((and (equal (char-after (point-at-bol)) ?*)
15802 (save-excursion (goto-char (point-at-bol))
15803 (looking-at outline-regexp)))
15804 t) ; skip headlines
15805 (table.el-p t) ; skip table.el tables
15806 (table-p (org-table-align) t) ; align org-mode tables
15807 (t nil)))) ; call paragraph-fill
15809 ;; For reference, this is the default value of adaptive-fill-regexp
15810 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
15812 (defun org-adaptive-fill-function ()
15813 "Return a fill prefix for org-mode files.
15814 In particular, this makes sure hanging paragraphs for hand-formatted lists
15815 work correctly."
15816 (cond ((looking-at "#[ \t]+")
15817 (match-string 0))
15818 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
15819 (save-excursion
15820 (if (> (match-end 1) (+ (match-beginning 1)
15821 org-description-max-indent))
15822 (goto-char (+ (match-beginning 1) 5))
15823 (goto-char (match-end 0)))
15824 (make-string (current-column) ?\ )))
15825 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
15826 (save-excursion
15827 (goto-char (match-end 0))
15828 (make-string (current-column) ?\ )))
15829 (t nil)))
15831 ;;; Other stuff.
15833 (defun org-toggle-fixed-width-section (arg)
15834 "Toggle the fixed-width export.
15835 If there is no active region, the QUOTE keyword at the current headline is
15836 inserted or removed. When present, it causes the text between this headline
15837 and the next to be exported as fixed-width text, and unmodified.
15838 If there is an active region, this command adds or removes a colon as the
15839 first character of this line. If the first character of a line is a colon,
15840 this line is also exported in fixed-width font."
15841 (interactive "P")
15842 (let* ((cc 0)
15843 (regionp (org-region-active-p))
15844 (beg (if regionp (region-beginning) (point)))
15845 (end (if regionp (region-end)))
15846 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
15847 (case-fold-search nil)
15848 (re "[ \t]*\\(: \\)")
15849 off)
15850 (if regionp
15851 (save-excursion
15852 (goto-char beg)
15853 (setq cc (current-column))
15854 (beginning-of-line 1)
15855 (setq off (looking-at re))
15856 (while (> nlines 0)
15857 (setq nlines (1- nlines))
15858 (beginning-of-line 1)
15859 (cond
15860 (arg
15861 (org-move-to-column cc t)
15862 (insert ": \n")
15863 (forward-line -1))
15864 ((and off (looking-at re))
15865 (replace-match "" t t nil 1))
15866 ((not off) (org-move-to-column cc t) (insert ": ")))
15867 (forward-line 1)))
15868 (save-excursion
15869 (org-back-to-heading)
15870 (if (looking-at (concat outline-regexp
15871 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
15872 (replace-match "" t t nil 1)
15873 (if (looking-at outline-regexp)
15874 (progn
15875 (goto-char (match-end 0))
15876 (insert org-quote-string " "))))))))
15878 (defun org-reftex-citation ()
15879 "Use reftex-citation to insert a citation into the buffer.
15880 This looks for a line like
15882 #+BIBLIOGRAPHY: foo plain option:-d
15884 and derives from it that foo.bib is the bbliography file relevant
15885 for this document. It then installs the necessary environment for RefTeX
15886 to work in this buffer and calls `reftex-citation' to insert a citation
15887 into the buffer.
15889 Export of such citations to both LaTeX and HTML is handled by the contributed
15890 package org-exp-bibtex by Taru Karttunen."
15891 (interactive)
15892 (let ((reftex-docstruct-symbol 'rds)
15893 (reftex-cite-format "\\cite{%l}")
15894 rds bib)
15895 (save-excursion
15896 (save-restriction
15897 (widen)
15898 (let ((case-fold-search t)
15899 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
15900 (if (not (save-excursion
15901 (or (re-search-forward re nil t)
15902 (re-search-backward re nil t))))
15903 (error "No bibliography defined in file")
15904 (setq bib (concat (match-string 1) ".bib")
15905 rds (list (list 'bib bib)))))))
15906 (call-interactively 'reftex-citation)))
15908 ;;;; Functions extending outline functionality
15910 (defun org-beginning-of-line (&optional arg)
15911 "Go to the beginning of the current line. If that is invisible, continue
15912 to a visible line beginning. This makes the function of C-a more intuitive.
15913 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15914 first attempt, and only move to after the tags when the cursor is already
15915 beyond the end of the headline."
15916 (interactive "P")
15917 (let ((pos (point))
15918 (special (if (consp org-special-ctrl-a/e)
15919 (car org-special-ctrl-a/e)
15920 org-special-ctrl-a/e))
15921 refpos)
15922 (beginning-of-line 1)
15923 (if (and arg (fboundp 'move-beginning-of-line))
15924 (call-interactively 'move-beginning-of-line)
15925 (if (bobp)
15927 (backward-char 1)
15928 (if (org-invisible-p)
15929 (while (and (not (bobp)) (org-invisible-p))
15930 (backward-char 1)
15931 (beginning-of-line 1))
15932 (forward-char 1))))
15933 (when special
15934 (cond
15935 ((and (looking-at org-complex-heading-regexp)
15936 (= (char-after (match-end 1)) ?\ ))
15937 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
15938 (point-at-eol)))
15939 (goto-char
15940 (if (eq special t)
15941 (cond ((> pos refpos) refpos)
15942 ((= pos (point)) refpos)
15943 (t (point)))
15944 (cond ((> pos (point)) (point))
15945 ((not (eq last-command this-command)) (point))
15946 (t refpos)))))
15947 ((org-at-item-p)
15948 (goto-char
15949 (if (eq special t)
15950 (cond ((> pos (match-end 4)) (match-end 4))
15951 ((= pos (point)) (match-end 4))
15952 (t (point)))
15953 (cond ((> pos (point)) (point))
15954 ((not (eq last-command this-command)) (point))
15955 (t (match-end 4))))))))
15956 (org-no-warnings
15957 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15959 (defun org-end-of-line (&optional arg)
15960 "Go to the end of the line.
15961 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15962 first attempt, and only move to after the tags when the cursor is already
15963 beyond the end of the headline."
15964 (interactive "P")
15965 (let ((special (if (consp org-special-ctrl-a/e)
15966 (cdr org-special-ctrl-a/e)
15967 org-special-ctrl-a/e)))
15968 (if (or (not special)
15969 (not (org-on-heading-p))
15970 arg)
15971 (call-interactively (if (fboundp 'move-end-of-line)
15972 'move-end-of-line
15973 'end-of-line))
15974 (let ((pos (point)))
15975 (beginning-of-line 1)
15976 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15977 (if (eq special t)
15978 (if (or (< pos (match-beginning 1))
15979 (= pos (match-end 0)))
15980 (goto-char (match-beginning 1))
15981 (goto-char (match-end 0)))
15982 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
15983 (goto-char (match-end 0))
15984 (goto-char (match-beginning 1))))
15985 (call-interactively (if (fboundp 'move-end-of-line)
15986 'move-end-of-line
15987 'end-of-line)))))
15988 (org-no-warnings
15989 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15991 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
15992 (define-key org-mode-map "\C-e" 'org-end-of-line)
15994 (defun org-backward-sentence (&optional arg)
15995 "Go to beginning of sentence, or beginning of table field.
15996 This will call `backward-sentence' or `org-table-beginning-of-field',
15997 depending on context."
15998 (interactive "P")
15999 (cond
16000 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
16001 (t (call-interactively 'backward-sentence))))
16003 (defun org-forward-sentence (&optional arg)
16004 "Go to end of sentence, or end of table field.
16005 This will call `forward-sentence' or `org-table-end-of-field',
16006 depending on context."
16007 (interactive "P")
16008 (cond
16009 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
16010 (t (call-interactively 'forward-sentence))))
16012 (define-key org-mode-map "\M-a" 'org-backward-sentence)
16013 (define-key org-mode-map "\M-e" 'org-forward-sentence)
16015 (defun org-kill-line (&optional arg)
16016 "Kill line, to tags or end of line."
16017 (interactive "P")
16018 (cond
16019 ((or (not org-special-ctrl-k)
16020 (bolp)
16021 (not (org-on-heading-p)))
16022 (call-interactively 'kill-line))
16023 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
16024 (kill-region (point) (match-beginning 1))
16025 (org-set-tags nil t))
16026 (t (kill-region (point) (point-at-eol)))))
16028 (define-key org-mode-map "\C-k" 'org-kill-line)
16030 (defun org-yank (&optional arg)
16031 "Yank. If the kill is a subtree, treat it specially.
16032 This command will look at the current kill and check if is a single
16033 subtree, or a series of subtrees[1]. If it passes the test, and if the
16034 cursor is at the beginning of a line or after the stars of a currently
16035 empty headline, then the yank is handled specially. How exactly depends
16036 on the value of the following variables, both set by default.
16038 org-yank-folded-subtrees
16039 When set, the subtree(s) will be folded after insertion, but only
16040 if doing so would now swallow text after the yanked text.
16042 org-yank-adjusted-subtrees
16043 When set, the subtree will be promoted or demoted in order to
16044 fit into the local outline tree structure, which means that the level
16045 will be adjusted so that it becomes the smaller one of the two
16046 *visible* surrounding headings.
16048 Any prefix to this command will cause `yank' to be called directly with
16049 no special treatment. In particular, a simple `C-u' prefix will just
16050 plainly yank the text as it is.
16052 \[1] The test checks if the first non-white line is a heading
16053 and if there are no other headings with fewer stars."
16054 (interactive "P")
16055 (org-yank-generic 'yank arg))
16057 (defun org-yank-generic (command arg)
16058 "Perform some yank-like command.
16060 This function implements the behavior described in the `org-yank'
16061 documentation. However, it has been generalized to work for any
16062 interactive command with similar behavior."
16064 ;; pretend to be command COMMAND
16065 (setq this-command command)
16067 (if arg
16068 (call-interactively command)
16070 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
16071 (and (org-kill-is-subtree-p)
16072 (or (bolp)
16073 (and (looking-at "[ \t]*$")
16074 (string-match
16075 "\\`\\*+\\'"
16076 (buffer-substring (point-at-bol) (point)))))))
16077 swallowp)
16078 (cond
16079 ((and subtreep org-yank-folded-subtrees)
16080 (let ((beg (point))
16081 end)
16082 (if (and subtreep org-yank-adjusted-subtrees)
16083 (org-paste-subtree nil nil 'for-yank)
16084 (call-interactively command))
16086 (setq end (point))
16087 (goto-char beg)
16088 (when (and (bolp) subtreep
16089 (not (setq swallowp
16090 (org-yank-folding-would-swallow-text beg end))))
16091 (or (looking-at outline-regexp)
16092 (re-search-forward (concat "^" outline-regexp) end t))
16093 (while (and (< (point) end) (looking-at outline-regexp))
16094 (hide-subtree)
16095 (org-cycle-show-empty-lines 'folded)
16096 (condition-case nil
16097 (outline-forward-same-level 1)
16098 (error (goto-char end)))))
16099 (when swallowp
16100 (message
16101 "Inserted text not folded because that would swallow text"))
16103 (goto-char end)
16104 (skip-chars-forward " \t\n\r")
16105 (beginning-of-line 1)
16106 (push-mark beg 'nomsg)))
16107 ((and subtreep org-yank-adjusted-subtrees)
16108 (let ((beg (point-at-bol)))
16109 (org-paste-subtree nil nil 'for-yank)
16110 (push-mark beg 'nomsg)))
16112 (call-interactively command))))))
16114 (defun org-yank-folding-would-swallow-text (beg end)
16115 "Would hide-subtree at BEG swallow any text after END?"
16116 (let (level)
16117 (save-excursion
16118 (goto-char beg)
16119 (when (or (looking-at outline-regexp)
16120 (re-search-forward (concat "^" outline-regexp) end t))
16121 (setq level (org-outline-level)))
16122 (goto-char end)
16123 (skip-chars-forward " \t\r\n\v\f")
16124 (if (or (eobp)
16125 (and (bolp) (looking-at org-outline-regexp)
16126 (<= (org-outline-level) level)))
16127 nil ; Nothing would be swallowed
16128 t)))) ; something would swallow
16130 (define-key org-mode-map "\C-y" 'org-yank)
16132 (defun org-invisible-p ()
16133 "Check if point is at a character currently not visible."
16134 ;; Early versions of noutline don't have `outline-invisible-p'.
16135 (if (fboundp 'outline-invisible-p)
16136 (outline-invisible-p)
16137 (get-char-property (point) 'invisible)))
16139 (defun org-invisible-p2 ()
16140 "Check if point is at a character currently not visible."
16141 (save-excursion
16142 (if (and (eolp) (not (bobp))) (backward-char 1))
16143 ;; Early versions of noutline don't have `outline-invisible-p'.
16144 (if (fboundp 'outline-invisible-p)
16145 (outline-invisible-p)
16146 (get-char-property (point) 'invisible))))
16148 (defun org-back-to-heading (&optional invisible-ok)
16149 "Call `outline-back-to-heading', but provide a better error message."
16150 (condition-case nil
16151 (outline-back-to-heading invisible-ok)
16152 (error (error "Before first headline at position %d in buffer %s"
16153 (point) (current-buffer)))))
16155 (defun org-before-first-heading-p ()
16156 "Before first heading?"
16157 (save-excursion
16158 (null (re-search-backward "^\\*+ " nil t))))
16160 (defalias 'org-on-heading-p 'outline-on-heading-p)
16161 (defalias 'org-at-heading-p 'outline-on-heading-p)
16162 (defun org-at-heading-or-item-p ()
16163 (or (org-on-heading-p) (org-at-item-p)))
16165 (defun org-on-target-p ()
16166 (or (org-in-regexp org-radio-target-regexp)
16167 (org-in-regexp org-target-regexp)))
16169 (defun org-up-heading-all (arg)
16170 "Move to the heading line of which the present line is a subheading.
16171 This function considers both visible and invisible heading lines.
16172 With argument, move up ARG levels."
16173 (if (fboundp 'outline-up-heading-all)
16174 (outline-up-heading-all arg) ; emacs 21 version of outline.el
16175 (outline-up-heading arg t))) ; emacs 22 version of outline.el
16177 (defun org-up-heading-safe ()
16178 "Move to the heading line of which the present line is a subheading.
16179 This version will not throw an error. It will return the level of the
16180 headline found, or nil if no higher level is found.
16182 Also, this function will be a lot faster than `outline-up-heading',
16183 because it relies on stars being the outline starters. This can really
16184 make a significant difference in outlines with very many siblings."
16185 (let (start-level re)
16186 (org-back-to-heading t)
16187 (setq start-level (funcall outline-level))
16188 (if (equal start-level 1)
16190 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
16191 (if (re-search-backward re nil t)
16192 (funcall outline-level)))))
16194 (defun org-first-sibling-p ()
16195 "Is this heading the first child of its parents?"
16196 (interactive)
16197 (let ((re (concat "^" outline-regexp))
16198 level l)
16199 (unless (org-at-heading-p t)
16200 (error "Not at a heading"))
16201 (setq level (funcall outline-level))
16202 (save-excursion
16203 (if (not (re-search-backward re nil t))
16205 (setq l (funcall outline-level))
16206 (< l level)))))
16208 (defun org-goto-sibling (&optional previous)
16209 "Goto the next sibling, even if it is invisible.
16210 When PREVIOUS is set, go to the previous sibling instead. Returns t
16211 when a sibling was found. When none is found, return nil and don't
16212 move point."
16213 (let ((fun (if previous 're-search-backward 're-search-forward))
16214 (pos (point))
16215 (re (concat "^" outline-regexp))
16216 level l)
16217 (when (condition-case nil (org-back-to-heading t) (error nil))
16218 (setq level (funcall outline-level))
16219 (catch 'exit
16220 (or previous (forward-char 1))
16221 (while (funcall fun re nil t)
16222 (setq l (funcall outline-level))
16223 (when (< l level) (goto-char pos) (throw 'exit nil))
16224 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
16225 (goto-char pos)
16226 nil))))
16228 (defun org-show-siblings ()
16229 "Show all siblings of the current headline."
16230 (save-excursion
16231 (while (org-goto-sibling) (org-flag-heading nil)))
16232 (save-excursion
16233 (while (org-goto-sibling 'previous)
16234 (org-flag-heading nil))))
16236 (defun org-show-hidden-entry ()
16237 "Show an entry where even the heading is hidden."
16238 (save-excursion
16239 (org-show-entry)))
16241 (defun org-flag-heading (flag &optional entry)
16242 "Flag the current heading. FLAG non-nil means make invisible.
16243 When ENTRY is non-nil, show the entire entry."
16244 (save-excursion
16245 (org-back-to-heading t)
16246 ;; Check if we should show the entire entry
16247 (if entry
16248 (progn
16249 (org-show-entry)
16250 (save-excursion
16251 (and (outline-next-heading)
16252 (org-flag-heading nil))))
16253 (outline-flag-region (max (point-min) (1- (point)))
16254 (save-excursion (outline-end-of-heading) (point))
16255 flag))))
16257 (defun org-forward-same-level (arg)
16258 "Move forward to the ARG'th subheading at same level as this one.
16259 Stop at the first and last subheadings of a superior heading.
16260 This is like outline-forward-same-level, but invisible headings are ok."
16261 (interactive "p")
16262 (org-back-to-heading t)
16263 (while (> arg 0)
16264 (let ((point-to-move-to (save-excursion
16265 (org-get-next-sibling))))
16266 (if point-to-move-to
16267 (progn
16268 (goto-char point-to-move-to)
16269 (setq arg (1- arg)))
16270 (progn
16271 (setq arg 0)
16272 (error "No following same-level heading"))))))
16274 (defun org-get-next-sibling ()
16275 "Move to next heading of the same level, and return point.
16276 If there is no such heading, return nil.
16277 This is like outline-next-sibling, but invisible headings are ok."
16278 (let ((level (funcall outline-level)))
16279 (outline-next-heading)
16280 (while (and (not (eobp)) (> (funcall outline-level) level))
16281 (outline-next-heading))
16282 (if (or (eobp) (< (funcall outline-level) level))
16284 (point))))
16286 (defun org-end-of-subtree (&optional invisible-OK to-heading)
16287 ;; This contains an exact copy of the original function, but it uses
16288 ;; `org-back-to-heading', to make it work also in invisible
16289 ;; trees. And is uses an invisible-OK argument.
16290 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
16291 ;; Furthermore, when used inside Org, finding the end of a large subtree
16292 ;; with many children and grandchildren etc, this can be much faster
16293 ;; than the outline version.
16294 (org-back-to-heading invisible-OK)
16295 (let ((first t)
16296 (level (funcall outline-level)))
16297 (if (and (org-mode-p) (< level 1000))
16298 ;; A true heading (not a plain list item), in Org-mode
16299 ;; This means we can easily find the end by looking
16300 ;; only for the right number of stars. Using a regexp to do
16301 ;; this is so much faster than using a Lisp loop.
16302 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
16303 (forward-char 1)
16304 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
16305 ;; something else, do it the slow way
16306 (while (and (not (eobp))
16307 (or first (> (funcall outline-level) level)))
16308 (setq first nil)
16309 (outline-next-heading)))
16310 (unless to-heading
16311 (if (memq (preceding-char) '(?\n ?\^M))
16312 (progn
16313 ;; Go to end of line before heading
16314 (forward-char -1)
16315 (if (memq (preceding-char) '(?\n ?\^M))
16316 ;; leave blank line before heading
16317 (forward-char -1))))))
16318 (point))
16320 (defun org-show-subtree ()
16321 "Show everything after this heading at deeper levels."
16322 (outline-flag-region
16323 (point)
16324 (save-excursion
16325 (outline-end-of-subtree) (outline-next-heading) (point))
16326 nil))
16328 (defun org-show-entry ()
16329 "Show the body directly following this heading.
16330 Show the heading too, if it is currently invisible."
16331 (interactive)
16332 (save-excursion
16333 (condition-case nil
16334 (progn
16335 (org-back-to-heading t)
16336 (outline-flag-region
16337 (max (point-min) (1- (point)))
16338 (save-excursion
16339 (if (re-search-forward
16340 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
16341 (match-beginning 1)
16342 (point-max)))
16343 nil))
16344 (error nil))))
16346 (defun org-make-options-regexp (kwds &optional extra)
16347 "Make a regular expression for keyword lines."
16348 (concat
16350 "#?[ \t]*\\+\\("
16351 (mapconcat 'regexp-quote kwds "\\|")
16352 (if extra (concat "\\|" extra))
16353 "\\):[ \t]*"
16354 "\\(.+\\)"))
16356 ;; Make isearch reveal the necessary context
16357 (defun org-isearch-end ()
16358 "Reveal context after isearch exits."
16359 (when isearch-success ; only if search was successful
16360 (if (featurep 'xemacs)
16361 ;; Under XEmacs, the hook is run in the correct place,
16362 ;; we directly show the context.
16363 (org-show-context 'isearch)
16364 ;; In Emacs the hook runs *before* restoring the overlays.
16365 ;; So we have to use a one-time post-command-hook to do this.
16366 ;; (Emacs 22 has a special variable, see function `org-mode')
16367 (unless (and (boundp 'isearch-mode-end-hook-quit)
16368 isearch-mode-end-hook-quit)
16369 ;; Only when the isearch was not quitted.
16370 (org-add-hook 'post-command-hook 'org-isearch-post-command
16371 'append 'local)))))
16373 (defun org-isearch-post-command ()
16374 "Remove self from hook, and show context."
16375 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
16376 (org-show-context 'isearch))
16379 ;;;; Integration with and fixes for other packages
16381 ;;; Imenu support
16383 (defvar org-imenu-markers nil
16384 "All markers currently used by Imenu.")
16385 (make-variable-buffer-local 'org-imenu-markers)
16387 (defun org-imenu-new-marker (&optional pos)
16388 "Return a new marker for use by Imenu, and remember the marker."
16389 (let ((m (make-marker)))
16390 (move-marker m (or pos (point)))
16391 (push m org-imenu-markers)
16394 (defun org-imenu-get-tree ()
16395 "Produce the index for Imenu."
16396 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
16397 (setq org-imenu-markers nil)
16398 (let* ((n org-imenu-depth)
16399 (re (concat "^" outline-regexp))
16400 (subs (make-vector (1+ n) nil))
16401 (last-level 0)
16402 m level head)
16403 (save-excursion
16404 (save-restriction
16405 (widen)
16406 (goto-char (point-max))
16407 (while (re-search-backward re nil t)
16408 (setq level (org-reduced-level (funcall outline-level)))
16409 (when (<= level n)
16410 (looking-at org-complex-heading-regexp)
16411 (setq head (org-link-display-format
16412 (org-match-string-no-properties 4))
16413 m (org-imenu-new-marker))
16414 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
16415 (if (>= level last-level)
16416 (push (cons head m) (aref subs level))
16417 (push (cons head (aref subs (1+ level))) (aref subs level))
16418 (loop for i from (1+ level) to n do (aset subs i nil)))
16419 (setq last-level level)))))
16420 (aref subs 1)))
16422 (eval-after-load "imenu"
16423 '(progn
16424 (add-hook 'imenu-after-jump-hook
16425 (lambda ()
16426 (if (eq major-mode 'org-mode)
16427 (org-show-context 'org-goto))))))
16429 (defun org-link-display-format (link)
16430 "Replace a link with either the description, or the link target
16431 if no description is present"
16432 (save-match-data
16433 (if (string-match org-bracket-link-analytic-regexp link)
16434 (replace-match (or (match-string 5 link)
16435 (concat (match-string 1 link)
16436 (match-string 3 link)))
16437 nil nil link)
16438 link)))
16440 ;; Speedbar support
16442 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
16443 "Overlay marking the agenda restriction line in speedbar.")
16444 (org-overlay-put org-speedbar-restriction-lock-overlay
16445 'face 'org-agenda-restriction-lock)
16446 (org-overlay-put org-speedbar-restriction-lock-overlay
16447 'help-echo "Agendas are currently limited to this item.")
16448 (org-detach-overlay org-speedbar-restriction-lock-overlay)
16450 (defun org-speedbar-set-agenda-restriction ()
16451 "Restrict future agenda commands to the location at point in speedbar.
16452 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
16453 (interactive)
16454 (require 'org-agenda)
16455 (let (p m tp np dir txt)
16456 (cond
16457 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16458 'org-imenu t))
16459 (setq m (get-text-property p 'org-imenu-marker))
16460 (save-excursion
16461 (save-restriction
16462 (set-buffer (marker-buffer m))
16463 (goto-char m)
16464 (org-agenda-set-restriction-lock 'subtree))))
16465 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16466 'speedbar-function 'speedbar-find-file))
16467 (setq tp (previous-single-property-change
16468 (1+ p) 'speedbar-function)
16469 np (next-single-property-change
16470 tp 'speedbar-function)
16471 dir (speedbar-line-directory)
16472 txt (buffer-substring-no-properties (or tp (point-min))
16473 (or np (point-max))))
16474 (save-excursion
16475 (save-restriction
16476 (set-buffer (find-file-noselect
16477 (let ((default-directory dir))
16478 (expand-file-name txt))))
16479 (unless (org-mode-p)
16480 (error "Cannot restrict to non-Org-mode file"))
16481 (org-agenda-set-restriction-lock 'file))))
16482 (t (error "Don't know how to restrict Org-mode's agenda")))
16483 (org-move-overlay org-speedbar-restriction-lock-overlay
16484 (point-at-bol) (point-at-eol))
16485 (setq current-prefix-arg nil)
16486 (org-agenda-maybe-redo)))
16488 (eval-after-load "speedbar"
16489 '(progn
16490 (speedbar-add-supported-extension ".org")
16491 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
16492 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
16493 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
16494 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16495 (add-hook 'speedbar-visiting-tag-hook
16496 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
16499 ;;; Fixes and Hacks for problems with other packages
16501 ;; Make flyspell not check words in links, to not mess up our keymap
16502 (defun org-mode-flyspell-verify ()
16503 "Don't let flyspell put overlays at active buttons."
16504 (and (not (get-text-property (point) 'keymap))
16505 (not (get-text-property (point) 'org-no-flyspell))))
16507 (defun org-remove-flyspell-overlays-in (beg end)
16508 "Remove flyspell overlays in region."
16509 (and (org-bound-and-true-p flyspell-mode)
16510 (fboundp 'flyspell-delete-region-overlays)
16511 (flyspell-delete-region-overlays beg end))
16512 (add-text-properties beg end '(org-no-flyspell t)))
16514 ;; Make `bookmark-jump' show the jump location if it was hidden.
16515 (eval-after-load "bookmark"
16516 '(if (boundp 'bookmark-after-jump-hook)
16517 ;; We can use the hook
16518 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
16519 ;; Hook not available, use advice
16520 (defadvice bookmark-jump (after org-make-visible activate)
16521 "Make the position visible."
16522 (org-bookmark-jump-unhide))))
16524 ;; Make sure saveplace show the location if it was hidden
16525 (eval-after-load "saveplace"
16526 '(defadvice save-place-find-file-hook (after org-make-visible activate)
16527 "Make the position visible."
16528 (org-bookmark-jump-unhide)))
16530 (defun org-bookmark-jump-unhide ()
16531 "Unhide the current position, to show the bookmark location."
16532 (and (org-mode-p)
16533 (or (org-invisible-p)
16534 (save-excursion (goto-char (max (point-min) (1- (point))))
16535 (org-invisible-p)))
16536 (org-show-context 'bookmark-jump)))
16538 ;; Make session.el ignore our circular variable
16539 (eval-after-load "session"
16540 '(add-to-list 'session-globals-exclude 'org-mark-ring))
16542 ;;;; Experimental code
16544 (defun org-closed-in-range ()
16545 "Sparse tree of items closed in a certain time range.
16546 Still experimental, may disappear in the future."
16547 (interactive)
16548 ;; Get the time interval from the user.
16549 (let* ((time1 (time-to-seconds
16550 (org-read-date nil 'to-time nil "Starting date: ")))
16551 (time2 (time-to-seconds
16552 (org-read-date nil 'to-time nil "End date:")))
16553 ;; callback function
16554 (callback (lambda ()
16555 (let ((time
16556 (time-to-seconds
16557 (apply 'encode-time
16558 (org-parse-time-string
16559 (match-string 1))))))
16560 ;; check if time in interval
16561 (and (>= time time1) (<= time time2))))))
16562 ;; make tree, check each match with the callback
16563 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
16565 ;;;; Finish up
16567 (provide 'org)
16569 (run-hooks 'org-load-hook)
16571 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
16573 ;;; org.el ends here